PageSourceSearch

https://spx.com.my/new_static/detail-bundle.ba5f3677.js

js spx.com.my collected 2026-10-03 21:21:52 UTC 697,520 bytes, 15,466 lines download raw bytes

vendor: 4,331 bytes, lines 1-27
1/**!
2
3 @license
4 handlebars v4.7.8
5
6Copyright (C) 2011-2019 by Yehuda Katz
7
8Permission is hereby granted, free of charge, to any person obtaining a copy
9of this software and associated documentation files (the "Software"), to deal
10in the Software without restriction, including without limitation the rights
11to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12copies of the Software, and to permit persons to whom the Software is
13furnished to do so, subject to the following conditions:
14
15The above copyright notice and this permission notice shall be included in
16all copies or substantial portions of the Software.
17
18THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24THE SOFTWARE.
25
26*/
27!function(a,b){"object"==typeof exports&&"object"==typeof module?module.exports=b():"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=new h.HandlebarsEnvironment;return n.extend(a,h),a.SafeString=j["default"],a.Exception=l["default"],a.Utils=n,a.escapeExpression=n.escapeExpression,a.VM=p,a.template=function(b){return p.template(b,a)},a}var e=c(1)["default"],f=c(2)["default"];b.__esModule=!0;var g=c(3),h=e(g),i=c(76),j=f(i),k=c(5),l=f(k),m=c(4),n=e(m),o=c(77),p=e(o),q=c(82),r=f(q),s=d();s.create=d,r["default"](s),s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b["default"]=a,b},b.__esModule=!0},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b,c){this.helpers=a||{},this.partials=b||{},this.decorators=c||{},i.registerDefaultHelpers(this),j.registerDefaultDecorators(this)}var e=c(2)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d;var f=c(4),g=c(5),h=e(g),i=c(9),j=c(69),k=c(71),l=e(k),m=c(72),n="4.7.8";b.VERSION=n;var o=8;b.COMPILER_REVISION=o;var p=7;b.LAST_COMPATIBLE_COMPILER_REVISION=p;var q={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0 <4.3.0",8:">= 4.3.0"};b.REVISION_CHANGES=q;var r="[object Object]";d.prototype={constructor:d,logger:l["default"],log:l["default"].log,registerHelper:function(a,b){if(f.toString.call(a)===r){if(b)throw new h["default"]("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(f.toString.call(a)===r)f.extend(this.partials,a);else{if("undefined"==typeof b)throw new h["default"]('Attempting to register a partial called "'+a+'" as undefined');this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]},registerDecorator:function(a,b){if(f.toString.call(a)===r){if(b)throw new h["default"]("Arg not supported with multiple decorators");f.extend(this.decorators,a)}else this.decorators[a]=b},unregisterDecorator:function(a){delete this.decorators[a]},resetLoggedPropertyAccesses:function(){m.resetLoggedProperties()}};var s=l["default"].log;b.log=s,b.createFrame=f.createFrame,b.logger=l["default"]},function(a,b){"use strict";function c(a){return k[a]}function d(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return m.test(a)?a.replace(l,c):a}
vendor: 2,141 bytes, line 27
27function g(a){return!a&&0!==a||!(!p(a)||0!==a.length)}function h(a){var b=d({},a);return b._parent=a,b}function i(a,b){return a.path=b,a}function j(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.createFrame=h,b.blockParams=i,b.appendContextPath=j;var k={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;","=":"&#x3D;"},l=/[&<>"'`=]/g,m=/[&<>"'`=]/,n=Object.prototype.toString;b.toString=n;var o=function(a){return"function"==typeof a};o(/x/)&&(b.isFunction=o=function(a){return"function"==typeof a&&"[object Function]"===n.call(a)}),b.isFunction=o;var p=Array.isArray||function(a){return!(!a||"object"!=typeof a)&&"[object Array]"===n.call(a)};b.isArray=p},function(a,b,c){"use strict";function d(a,b){var c=b&&b.loc,g=void 0,h=void 0,i=void 0,j=void 0;c&&(g=c.start.line,h=c.end.line,i=c.start.column,j=c.end.column,a+=" - "+g+":"+i);for(var k=Error.prototype.constructor.call(this,a),l=0;l<f.length;l++)this[f[l]]=k[f[l]];Error.captureStackTrace&&Error.captureStackTrace(this,d);try{c&&(this.lineNumber=g,this.endLineNumber=h,e?(Object.defineProperty(this,"column",{value:i,enumerable:!0}),Object.defineProperty(this,"endColumn",{value:j,enumerable:!0})):(this.column=i,this.endColumn=j))}catch(m){}}var e=c(6)["default"];b.__esModule=!0;var f=["description","fileName","lineNumber","endLineNumber","message","name","number","stack"];d.prototype=new Error,b["default"]=d,a.exports=b["default"]},function(a,b,c){a.exports={"default":c(7),__esModule:!0}},function(a,b,c){var d=c(8);a.exports=function(a,b,c){return d.setDesc(a,b,c)}},function(a,b){var c=Object;a.exports={create:c.create,getProto:c.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:c.getOwnPropertyDescriptor,setDesc:c.defineProperty,setDescs:c.defineProperties,getKeys:c.keys,getNames:c.getOwnPropertyNames,getSymbols:c.getOwnPropertySymbols,each:[].forEach}},function(a,b,c){"use strict";function d(a){h["default"](a),j["default"](a),l["default"](a),n["default"](a),p["default"](a),r["default"](a),t["default"](a)}function e(a,b,c){a.helpers[b]&&(a.hooks[b]=a.helpers[b],c||delete a.helpers[b]
vendor: 14,607 bytes, line 27
27)}var f=c(2)["default"];b.__esModule=!0,b.registerDefaultHelpers=d,b.moveHelperToHooks=e;var g=c(10),h=f(g),i=c(11),j=f(i),k=c(64),l=f(k),m=c(65),n=f(m),o=c(66),p=f(o),q=c(67),r=f(q),s=c(68),t=f(s)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(4);b["default"]=function(a){a.registerHelper("blockHelperMissing",function(b,c){var e=c.inverse,f=c.fn;if(b===!0)return f(this);if(b===!1||null==b)return e(this);if(d.isArray(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):e(this);if(c.data&&c.ids){var g=d.createFrame(c.data);g.contextPath=d.appendContextPath(c.data.contextPath,c.name),c={data:g}}return f(b,c)})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(12)["default"],e=c(42)["default"],f=c(54)["default"],g=c(59)["default"],h=c(2)["default"];b.__esModule=!0;var i=c(4),j=c(5),k=h(j);b["default"]=function(a){a.registerHelper("each",function(a,b){function c(b,c,d){n&&(n.key=b,n.index=c,n.first=0===c,n.last=!!d,o&&(n.contextPath=o+b)),m+=h(a[b],{data:n,blockParams:i.blockParams([a[b],b],[o+b,null])})}if(!b)throw new k["default"]("Must pass iterator to #each");var h=b.fn,j=b.inverse,l=0,m="",n=void 0,o=void 0;if(b.data&&b.ids&&(o=i.appendContextPath(b.data.contextPath,b.ids[0])+"."),i.isFunction(a)&&(a=a.call(this)),b.data&&(n=i.createFrame(b.data)),a&&"object"==typeof a)if(i.isArray(a))for(var p=a.length;l<p;l++)l in a&&c(l,l,l===a.length-1);else if("function"==typeof d&&a[e]){for(var q=[],r=f(a),s=r.next();!s.done;s=r.next())q.push(s.value);a=q;for(var p=a.length;l<p;l++)c(l,l,l===a.length-1)}else!function(){var b=void 0;g(a).forEach(function(a){void 0!==b&&c(b,l-1),b=a,l++}),void 0!==b&&c(b,l-1,!0)}();return 0===l&&(m=j(this)),m})},a.exports=b["default"]},function(a,b,c){a.exports={"default":c(13),__esModule:!0}},function(a,b,c){c(14),c(41),a.exports=c(20).Symbol},function(a,b,c){"use strict";var d=c(8),e=c(15),f=c(16),g=c(17),h=c(19),i=c(23),j=c(18),k=c(26),l=c(27),m=c(29),n=c(28),o=c(30),p=c(35),q=c(36),r=c(37),s=c(38),t=c(31),u=c(25),v=d.getDesc,w=d.setDesc,x=d.create,y=p.get,z=e.Symbol,A=e.JSON,B=A&&A.stringify,C=!1,D=n("_hidden"),E=d.isEnum,F=k("symbol-registry"),G=k("symbols"),H="function"==typeof z,I=Object.prototype,J=g&&j(function(){return 7!=x(w({},"a",{get:function(){return w(this,"a",{value:7}).a}})).a})?function(a,b,c){var d=v(I,b);d&&delete I[b],w(a,b,c),d&&a!==I&&w(I,b,d)}:w,K=function(a){var b=G[a]=x(z.prototype);return b._k=a,g&&C&&J(I,a,{configurable:!0,set:function(b){f(this,D)&&f(this[D],a)&&(this[D][a]=!1),J(this,a,u(1,b))}}),b},L=function(a){return"symbol"==typeof a},M=function(a,b,c){return c&&f(G,b)?(c.enumerable?(f(a,D)&&a[D][b]&&(a[D][b]=!1),c=x(c,{enumerable:u(0,!1)})):(f(a,D)||w(a,D,u(1,{})),a[D][b]=!0),J(a,b,c)):w(a,b,c)},N=function(a,b){s(a);for(var c,d=q(b=t(b)),e=0,f=d.length;f>e;)M(a,c=d[e++],b[c]);return a},O=function(a,b){return void 0===b?x(a):N(x(a),b)},P=function(a){var b=E.call(this,a);return!(b||!f(this,a)||!f(G,a)||f(this,D)&&this[D][a])||b},Q=function(a,b){var c=v(a=t(a),b);return!c||!f(G,b)||f(a,D)&&a[D][b]||(c.enumerable=!0),c},R=function(a){for(var b,c=y(t(a)),d=[],e=0;c.length>e;)f(G,b=c[e++])||b==D||d.push(b);return d},S=function(a){for(var b,c=y(t(a)),d=[],e=0;c.length>e;)f(G,b=c[e++])&&d.push(G[b]);return d},T=function(a){if(void 0!==a&&!L(a)){for(var b,c,d=[a],e=1,f=arguments;f.length>e;)d.push(f[e++]);return b=d[1],"function"==typeof b&&(c=b),!c&&r(b)||(b=function(a,b){if(c&&(b=c.call(this,a,b)),!L(b))return b}),d[1]=b,B.apply(A,d)}},U=j(function(){var a=z();return"[null]"!=B([a])||"{}"!=B({a:a})||"{}"!=B(Object(a))});H||(z=function(){if(L(this))throw TypeError("Symbol is not a constructor");return K(m(arguments.length>0?arguments[0]:void 0))},i(z.prototype,"toString",function(){return this._k}),L=function(a){return a instanceof z},d.create=O,d.isEnum=P,d.getDesc=Q,d.setDesc=M,d.setDescs=N,d.getNames=p.get=R,d.getSymbols=S,g&&!c(40)&&i(I,"propertyIsEnumerable",P,!0));var V={"for":function(a){return f(F,a+="")?F[a]:F[a]=z(a)},keyFor:function(a){return o(F,a)},useSetter:function(){C=!0},useSimple:function(){C=!1}};d.each.call("hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),function(a){var b=n(a);V[a]=H?b:K(b)}),C=!0,h(h.G+h.W,{Symbol:z}),h(h.S,"Symbol",V),h(h.S+h.F*!H,"Object",{create:O,defineProperty:M,defineProperties:N,getOwnPropertyDescriptor:Q,getOwnPropertyNames:R,getOwnPropertySymbols:S}),A&&h(h.S+h.F*(!H||U),"JSON",{stringify:T}),l(z,"Symbol"),l(Math,"Math",!0),l(e.JSON,"JSON",!0)},function(a,b){var c=a.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=c)},function(a,b){var c={}.hasOwnProperty;a.exports=function(a,b){return c.call(a,b)}},function(a,b,c){a.exports=!c(18)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(a,b){a.exports=function(a){try{return!!a()}catch(b){return!0}}},function(a,b,c){var d=c(15),e=c(20),f=c(21),g="prototype",h=function(a,b,c){var i,j,k,l=a&h.F,m=a&h.G,n=a&h.S,o=a&h.P,p=a&h.B,q=a&h.W,r=m?e:e[b]||(e[b]={}),s=m?d:n?d[b]:(d[b]||{})[g];m&&(c=b);for(i in c)j=!l&&s&&i in s,j&&i in r||(k=j?s[i]:c[i],r[i]=m&&"function"!=typeof s[i]?c[i]:p&&j?f(k,d):q&&s[i]==k?function(a){var b=function(b){return this instanceof a?new a(b):a(b)};return b[g]=a[g],b}(k):o&&"function"==typeof k?f(Function.call,k):k,o&&((r[g]||(r[g]={}))[i]=k))};h.F=1,h.G=2,h.S=4,h.P=8,h.B=16,h.W=32,a.exports=h},function(a,b){var c=a.exports={version:"1.2.6"};"number"==typeof __e&&(__e=c)},function(a,b,c){var d=c(22);a.exports=function(a,b,c){if(d(a),void 0===b)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)}}return function(){return a.apply(b,arguments)}}},function(a,b){a.exports=function(a){if("function"!=typeof a)throw TypeError(a+" is not a function!");return a}},function(a,b,c){a.exports=c(24)},function(a,b,c){var d=c(8),e=c(25);a.exports=c(17)?function(a,b,c){return d.setDesc(a,b,e(1,c))}:function(a,b,c){return a[b]=c,a}},function(a,b){a.exports=function(a,b){return{enumerable:!(1&a),configurable:!(2&a),writable:!(4&a),value:b}}},function(a,b,c){var d=c(15),e="__core-js_shared__",f=d[e]||(d[e]={});a.exports=function(a){return f[a]||(f[a]={})}},function(a,b,c){var d=c(8).setDesc,e=c(16),f=c(28)("toStringTag");a.exports=function(a,b,c){a&&!e(a=c?a:a.prototype,f)&&d(a,f,{configurable:!0,value:b})}},function(a,b,c){var d=c(26)("wks"),e=c(29),f=c(15).Symbol;a.exports=function(a){return d[a]||(d[a]=f&&f[a]||(f||e)("Symbol."+a))}},function(a,b){var c=0,d=Math.random();a.exports=function(a){return"Symbol(".concat(void 0===a?"":a,")_",(++c+d).toString(36))}},function(a,b,c){var d=c(8),e=c(31);a.exports=function(a,b){for(var c,f=e(a),g=d.getKeys(f),h=g.length,i=0;h>i;)if(f[c=g[i++]]===b)return c}},function(a,b,c){var d=c(32),e=c(34);a.exports=function(a){return d(e(a))}},function(a,b,c){var d=c(33);a.exports=Object("z").propertyIsEnumerable(0)?Object:function(a){return"String"==d(a)?a.split(""):Object(a)}},function(a,b){var c={}.toString;a.exports=function(a){return c.call(a).slice(8,-1)}},function(a,b){a.exports=function(a){if(void 0==a)throw TypeError("Can't call method on  "+a);return a}},function(a,b,c){var d=c(31),e=c(8).getNames,f={}.toString,g="object"==typeof window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],h=function(a){try{return e(a)}catch(b){return g.slice()}};a.exports.get=function(a){return g&&"[object Window]"==f.call(a)?h(a):e(d(a))}},function(a,b,c){var d=c(8);a.exports=function(a){var b=d.getKeys(a),c=d.getSymbols;if(c)for(var e,f=c(a),g=d.isEnum,h=0;f.length>h;)g.call(a,e=f[h++])&&b.push(e);return b}},function(a,b,c){var d=c(33);a.exports=Array.isArray||function(a){return"Array"==d(a)}},function(a,b,c){var d=c(39);a.exports=function(a){if(!d(a))throw TypeError(a+" is not an object!");return a}},function(a,b){a.exports=function(a){return"object"==typeof a?null!==a:"function"==typeof a}},function(a,b){a.exports=!0},function(a,b){},function(a,b,c){a.exports={"default":c(43),__esModule:!0}},function(a,b,c){c(44),c(50),a.exports=c(28)("iterator")},function(a,b,c){"use strict";var d=c(45)(!0);c(47)(String,"String",function(a){this._t=String(a),this._i=0},function(){var a,b=this._t,c=this._i;return c>=b.length?{value:void 0,done:!0}:(a=d(b,c),this._i+=a.length,{value:a,done:!1})})},function(a,b,c){var d=c(46),e=c(34);a.exports=function(a){return function(b,c){var f,g,h=String(e(b)),i=d(c),j=h.length;return i<0||i>=j?a?"":void 0:(f=h.charCodeAt(i),f<55296||f>56319||i+1===j||(g=h.charCodeAt(i+1))<56320||g>57343?a?h.charAt(i):f:a?h.slice(i,i+2):(f-55296<<10)+(g-56320)+65536)}}},function(a,b){var c=Math.ceil,d=Math.floor;a.exports=function(a){return isNaN(a=+a)?0:(a>0?d:c)(a)}},function(a,b,c){"use strict";var d=c(40),e=c(19),f=c(23),g=c(24),h=c(16),i=c(48),j=c(49),k=c(27),l=c(8).getProto,m=c(28)("iterator"),n=!([].keys&&"next"in[].keys()),o="@@iterator",p="keys",q="values",r=function(){return this};a.exports=function(a,b,c,s,t,u,v){j(c,b,s);var w,x,y=function(a){if(!n&&a in C)return C[a];switch(a){case p:return function(){return new c(this,a)};case q:return function(){return new c(this,a)}}return function(){return new c(this,a)}},z=b+" Iterator",A=t==q,B=!1,C=a.prototype,D=C[m]||C[o]||t&&C[t],E=D||y(t);if(D){var F=l(E.call(new a));k(F,z,!0),!d&&h(C,o)&&g(F,m,r),A&&D.name!==q&&(B=!0,E=function(){return D.call(this)})}if(d&&!v||!n&&!B&&C[m]||g(C,m,E),i[b]=E,i[z]=r,t)if(w={values:A?E:y(q),keys:u?E:y(p),entries:A?y("entries"):E},v)for(x in w)x in C||f(C,x,w[x]);else e(e.P+e.F*(n||B),b,w);return w}},function(a,b){a.exports={}},function(a,b,c){"use strict";var d=c(8),e=c(25),f=c(27),g={};c(24)(g,c(28)("iterator"),function(){return this}),a.exports=function(a,b,c){a.prototype=d.create(g,{next:e(1,c)}),f(a,b+" Iterator")}},function(a,b,c){c(51);var d=c(48);d.NodeList=d.HTMLCollection=d.Array},function(a,b,c){"use strict";var d=c(52),e=c(53),f=c(48),g=c(31);a.exports=c(47)(Array,"Array",function(a,b){this._t=g(a),this._i=0,this._k=b},function(){var a=this._t,b=this._k,c=this._i++;return!a||c>=a.length?(this._t=void 0,e(1)):"keys"==b?e(0,c):"values"==b?e(0,a[c]):e(0,[c,a[c]])},"values"),f.Arguments=f.Array,d("keys"),d("values"),d("entries")},function(a,b){a.exports=function(){}},function(a,b){a.exports=function(a,b){return{value:b,done:!!a}}},function(a,b,c){a.exports={"default":c(55),__esModule:!0}},function(a,b,c){c(50),c(44),a.exports=c(56)},function(a,b,c){var d=c(38),e=c(57);a.exports=c(20).getIterator=function(a){var b=e(a);if("function"!=typeof b)throw TypeError(a+" is not iterable!");return d(b.call(a))}},function(a,b,c){var d=c(58),e=c(28)("iterator"),f=c(48);a.exports=c(20).getIteratorMethod=function(a){if(void 0!=a)return a[e]||a["@@iterator"]||f[d(a)]}},function(a,b,c){var d=c(33),e=c(28)("toStringTag"),f="Arguments"==d(function(){return arguments}());a.exports=function(a){var b,c,g;return void 0===a?"Undefined":null===a?"Null":"string"==typeof(c=(b=Object(a))[e])?c:f?d(b):"Object"==(g=d(b))&&"function"==typeof b.callee?"Arguments":g}},function(a,b,c){a.exports={"default":c(60),__esModule:!0}},function(a,b,c){c(61),a.exports=c(20).Object.keys},function(a,b,c){var d=c(62);c(63)("keys",function(a){return function(b){return a(d(b))}})},function(a,b,c){var d=c(34);a.exports=function(a){return Object(d(a))}},function(a,b,c){var d=c(19),e=c(20),f=c(18);a.exports=function(a,b){var c=(e.Object||{})[a]||Object[a],g={};g[a]=b(c),d(d.S+d.F*f(function(){c(1)}),"Object",g)}},function(a,b,c){"use strict";var d=c(2)["default"];b.__esModule=!0;var e=c(5),f=d(e);b["default"]=function(a){a.registerHelper("helperMissing",function(){if(1!==arguments.length)throw new f["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(2)["default"];b.__esModule=!0;var e=c(4),f=c(5),g=d(f);b["default"]=function(a){a.registerHelper("if",function(a,b){if(2!=arguments.length)throw new g["default"]("#if requires exactly one argument");return e.isFunction(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||e.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){if(2!=arguments.length)throw new g["default"]("#unless requires exactly one argument");return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("log",function(){for(var b=[void 0],c=arguments[arguments.length-1],d=0;d<arguments.length-1;d++)b.push(arguments[d]);var e=1;null!=c.hash.level?e=c.hash.level:c.data&&null!=c.data.level&&(e=c.data.level),b[0]=e,a.log.apply(a,b)})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("lookup",function(a,b,c){return a?c.lookupProperty(a,b):a})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(2)["default"];b.__esModule=!0;var e=c(4),f=c(5),g=d(f);b["default"]=function(a){a.registerHelper("with",function(a,b){if(2!=arguments.length)throw new g["default"]("#with requires exactly one argument");e.isFunction(a)&&(a=a.call(this));var c=b.fn;if(e.isEmpty(a))return b.inverse(this);var d=b.data;return b.data&&b.ids&&(d=e.createFrame(b.data),d.contextPath=e.appendContextPath(b.data.contextPath,b.ids[0])),c(a,{data:d,blockParams:e.blockParams([a],[d&&d.contextPath])})})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){g["default"](a)}var e=c(2)["default"];b.__esModule=!0,b.registerDefaultDecorators=d;var f=c(70),g=e(f)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(4);b["default"]=function(a){a.registerDecorator("inline",function(a,b,c,e){var f=a;return b.partials||(b.partials={},f=function(e,f){var g=c.partials;c.partials=d.extend({},g,b.partials);var h=a(e,f);return c.partials=g,h}),b.partials[e.args[0]]=e.fn,f})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(4),e={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(a){if("string"==typeof a){var b=d.indexOf(e.methodMap,a.toLowerCase());a=b>=0?b:parseInt(a,10)}return a},log:function(a){if(a=e.lookupLevel(a),"undefined"!=typeof console&&e.lookupLevel(e.level)<=a){var b=e.methodMap[a];console[b]||(b="log");for(var c=arguments.length,d=Array(c>1?c-1:0),f=1;f<c;f++)d[f-1]=arguments[f];console[b].apply(console,d)}}};b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=i(null);b.
27constructor=!1,b.__defineGetter__=!1,b.__defineSetter__=!1,b.__lookupGetter__=!1;var c=i(null);return c.__proto__=!1,{properties:{whitelist:l.createNewLookupObject(c,a.allowedProtoProperties),defaultValue:a.allowProtoPropertiesByDefault},methods:{whitelist:l.createNewLookupObject(b,a.allowedProtoMethods),defaultValue:a.allowProtoMethodsByDefault}}}function e(a,b,c){return"function"==typeof a?f(b.methods,c):f(b.properties,c)}function f(a,b){return void 0!==a.whitelist[b]?a.whitelist[b]===!0:void 0!==a.defaultValue?a.defaultValue:(g(b),!1)}function g(a){o[a]!==!0&&(o[a]=!0,n["default"].log("error",'Handlebars: Access has been denied to resolve the property "'+a+'" because it is not an "own property" of its parent.\nYou can add a runtime option to disable the check or this warning:\nSee https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details'))}function h(){j(o).forEach(function(a){delete o[a]})}var i=c(73)["default"],j=c(59)["default"],k=c(2)["default"];b.__esModule=!0,b.createProtoAccessControl=d,b.resultIsAllowed=e,b.resetLoggedProperties=h;var l=c(75),m=c(71),n=k(m),o=i(null)},function(a,b,c){a.exports={"default":c(74),__esModule:!0}},function(a,b,c){var d=c(8);a.exports=function(a,b){return d.create(a,b)}},function(a,b,c){"use strict";function d(){for(var a=arguments.length,b=Array(a),c=0;c<a;c++)b[c]=arguments[c];return f.extend.apply(void 0,[e(null)].concat(b))}var e=c(73)["default"];b.__esModule=!0,b.createNewLookupObject=d;var f=c(4)},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=v.COMPILER_REVISION;if(!(b>=v.LAST_COMPATIBLE_COMPILER_REVISION&&b<=v.COMPILER_REVISION)){if(b<v.LAST_COMPATIBLE_COMPILER_REVISION){var d=v.REVISION_CHANGES[c],e=v.REVISION_CHANGES[b];throw new u["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new u["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=s.extend({},d,e.hash),e.ids&&(e.ids[0]=!0)),c=b.VM.resolvePartial.call(this,c,d,e);var f=s.extend({},e,{hooks:this.hooks,protoAccessControl:this.protoAccessControl}),g=b.VM.invokePartial.call(this,c,d,f);if(null==g&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),g=e.partials[e.name](d,f)),null!=g){if(e.indent){for(var h=g.split("\n"),i=0,j=h.length;i<j&&(h[i]||i+1!==j);i++)h[i]=e.indent+h[i];g=h.join("\n")}return g}throw new u["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){function c(b){return""+a.main(g,b,g.helpers,g.partials,f,i,h)}var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],f=e.data;d._setup(e),!e.partial&&a.useData&&(f=j(b,f));var h=void 0,i=a.useBlockParams?[]:void 0;return a.useDepths&&(h=e.depths?b!=e.depths[0]?[b].concat(e.depths):e.depths:[b]),(c=k(a.main,c,g,e.depths||[],f,i))(b,e)}if(!b)throw new u["default"]("No environment passed to template");if(!a||!a.main)throw new u["default"]("Unknown template object: "+typeof a);a.main.decorator=a.main_d,b.VM.checkRevision(a.compiler);var e=a.compiler&&7===a.compiler[0],g={strict:function(a,b,c){if(!(a&&b in a))throw new u["default"]('"'+b+'" not defined in '+a,{loc:c});return g.lookupProperty(a,b)},lookupProperty:function(a,b){var c=a[b];return null==c?c:Object.prototype.hasOwnProperty.call(a,b)?c:y.resultIsAllowed(c,g.protoAccessControl,b)?c:void 0},lookup:function(a,b){for(var c=a.length,d=0;d<c;d++){var e=a[d]&&g.lookupProperty(a[d],b);if(null!=e)return a[d][b]}},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:s.escapeExpression,invokePartial:c,fn:function(b){var c=a[b];return c.decorator=a[b+"_d"],c},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},mergeIfNeeded:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=s.extend({},b,a)),c},nullContext:n({}),noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){if(c.partial)g.protoAccessControl
27=c.protoAccessControl,g.helpers=c.helpers,g.partials=c.partials,g.decorators=c.decorators,g.hooks=c.hooks;else{var d=s.extend({},b.helpers,c.helpers);l(d,g),g.helpers=d,a.usePartial&&(g.partials=g.mergeIfNeeded(c.partials,b.partials)),(a.usePartial||a.useDecorators)&&(g.decorators=s.extend({},b.decorators,c.decorators)),g.hooks={},g.protoAccessControl=y.createProtoAccessControl(c);var f=c.allowCallsToHelperMissing||e;w.moveHelperToHooks(g,"helperMissing",f),w.moveHelperToHooks(g,"blockHelperMissing",f)}},d._child=function(b,c,d,e){if(a.useBlockParams&&!d)throw new u["default"]("must pass block params");if(a.useDepths&&!e)throw new u["default"]("must pass parent depths");return f(g,b,a[b],c,0,d,e)},d}function f(a,b,c,d,e,f,g){function h(b){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],h=g;return!g||b==g[0]||b===a.nullContext&&null===g[0]||(h=[b].concat(g)),c(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),h)}return h=k(c,h,a,g,d,f),h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a="@partial-block"===c.name?c.data["partial-block"]:c.partials[c.name],a}function h(a,b,c){var d=c.data&&c.data["partial-block"];c.partial=!0,c.ids&&(c.data.contextPath=c.ids[0]||c.data.contextPath);var e=void 0;if(c.fn&&c.fn!==i&&!function(){c.data=v.createFrame(c.data);var a=c.fn;e=c.data["partial-block"]=function(b){var c=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return c.data=v.createFrame(c.data),c.data["partial-block"]=d,a(b,c)},a.partials&&(c.partials=s.extend({},c.partials,a.partials))}(),void 0===a&&e&&(a=e),void 0===a)throw new u["default"]("The partial "+c.name+" could not be found");if(a instanceof Function)return a(b,c)}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?v.createFrame(b):{},b.root=a),b}function k(a,b,c,d,e,f){if(a.decorator){var g={};b=a.decorator(b,g,c,d&&d[0],e,f,d),s.extend(b,g)}return b}function l(a,b){o(a).forEach(function(c){var d=a[c];a[c]=m(d,b)})}function m(a,b){var c=b.lookupProperty;return x.wrapHelper(a,function(a){return s.extend({lookupProperty:c},a)})}var n=c(78)["default"],o=c(59)["default"],p=c(1)["default"],q=c(2)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var r=c(4),s=p(r),t=c(5),u=q(t),v=c(3),w=c(9),x=c(81),y=c(72)},function(a,b,c){a.exports={"default":c(79),__esModule:!0}},function(a,b,c){c(80),a.exports=c(20).Object.seal},function(a,b,c){var d=c(39);c(63)("seal",function(a){return function(b){return a&&d(b)?a(b):b}})},function(a,b){"use strict";function c(a,b){if("function"!=typeof a)return a;var c=function(){var c=arguments[arguments.length-1];return arguments[arguments.length-1]=b(c),a.apply(this,arguments)};return c}
27b.__esModule=!0,b.wrapHelper=c},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){!function(){"object"!=typeof globalThis&&(Object.prototype.__defineGetter__("__magic__",function(){return this}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__)}();var b=globalThis.Handlebars;a.noConflict=function(){return globalThis.Handlebars===a&&(globalThis.Handlebars=b),a}},a.exports=b["default"]}])});
28(function () {
29    'use strict';
30
31    /******************************************************************************
32    Copyright (c) Microsoft Corporation.
33
34    Permission to use, copy, modify, and/or distribute this software for any
35    purpose with or without fee is hereby granted.
36
37    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
38    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
39    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
40    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
41    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
42    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
43    PERFORMANCE OF THIS SOFTWARE.
44    ***************************************************************************** */
45    /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
46
47
48    var __assign$3 = function() {
49        __assign$3 = Object.assign || function __assign(t) {
50            for (var s, i = 1, n = arguments.length; i < n; i++) {
51                s = arguments[i];
52                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
53            }
54            return t;
55        };
56        return __assign$3.apply(this, arguments);
57    };
58
59    function __rest(s, e) {
60        var t = {};
61        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
62            t[p] = s[p];
63        if (s != null && typeof Object.getOwnPropertySymbols === "function")
64            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
65                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
66                    t[p[i]] = s[p[i]];
67            }
68        return t;
69    }
70
71    function __awaiter$7(thisArg, _arguments, P, generator) {
72        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
73        return new (P || (P = Promise))(function (resolve, reject) {
74            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
75            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
76            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
77            step((generator = generator.apply(thisArg, _arguments || [])).next());
78        });
79    }
80
81    function __generator$7(thisArg, body) {
82        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
83        return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
84        function verb(n) { return function (v) { return step([n, v]); }; }
85        function step(op) {
86            if (f) throw new TypeError("Generator is already executing.");
87            while (g && (g = 0, op[0] && (_ = 0)), _) try {
88                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
89                if (y = 0, t) op = [op[0] & 2, t.value];
90                switch (op[0]) {
91                    case 0: case 1: t = op; break;
92                    case 4: _.label++; return { value: op[1], done: false };
93                    case 5: _.label++; y = op[1]; op = [0]; continue;
94                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
95                    default:
96                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
97                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
98                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
99                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
100                        if (t[2]) _.ops.pop();
101                        _.trys.pop(); continue;
102                }
103                op = body.call(thisArg, _);
104            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
105            if (op[0] & 5) throw op[1];
105 return { value: op[0] ? op[1] : void 0, done: true };
106        }
107    }
108
109    function __spreadArray$2(to, from, pack) {
110        if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
111            if (ar || !(i in from)) {
112                if (!ar) ar = Array.prototype.slice.call(from, 0, i);
113                ar[i] = from[i];
114            }
115        }
116        return to.concat(ar || Array.prototype.slice.call(from));
117    }
118
119    typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
120        var e = new Error(message);
121        return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
122    };
123
124    var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
125
126    function getDefaultExportFromCjs (x) {
127    	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
128    }
129
130    var index_umd$1 = {exports: {}};
131
132    var index_umd = index_umd$1.exports;
133
134    var hasRequiredIndex_umd;
135
136    function requireIndex_umd () {
137    	if (hasRequiredIndex_umd) return index_umd$1.exports;
138    	hasRequiredIndex_umd = 1;
139    	(function (module, exports) {
140    		!function(t,r){r(exports);}(index_umd,(function(t){var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof commonjsGlobal?commonjsGlobal:"undefined"!=typeof self?self:{};function e(t,r,e){return t(e={path:r,exports:{},require:function(t,r){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==r&&e.path)}},e.exports),e.exports}var n=function(t){return t&&t.Math==Math&&t},o=n("object"==typeof globalThis&&globalThis)||n("object"==typeof window&&window)||n("object"==typeof self&&self)||n("object"==typeof r&&r)||function(){return this}()||Function("return this")(),i=function(t){try{return !!t()}catch(t){return !0}},c=!i((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),u={}.propertyIsEnumerable,a=Object.getOwnPropertyDescriptor,f={f:a&&!u.call({1:2},1)?function(t){var r=a(this,t);return !!r&&r.enumerable}:u},l=function(t,r){return {enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:r}},s={}.toString,p=function(t){return s.call(t).slice(8,-1)},g="".split,d=i((function(){return !Object("z").propertyIsEnumerable(0)}))?function(t){return "String"==p(t)?g.call(t,""):Object(t)}:Object,h=function(t){if(null==t)throw TypeError("Can't call method on "+t);return t},v=function(t){return d(h(t))},y=function(t){return "object"==typeof t?null!==t:"function"==typeof t},b=function(t,r){if(!y(t))return t;var e,n;if(r&&"function"==typeof(e=t.toString)&&!y(n=e.call(t)))return n;if("function"==typeof(e=t.valueOf)&&!y(n=e.call(t)))return n;if(!r&&"function"==typeof(e=t.toString)&&!y(n=e.call(t)))return n;throw TypeError("Can't convert object to primitive value")},m=function(t){return Object(h(t))},S={}.hasOwnProperty,x=function(t,r){return S.call(m(t),r)},E=o.document,j=y(E)&&y(E.createElement),w=!c&&!i((function(){return 7!=Object.defineProperty((t="div",j?E.createElement(t):{}),"a",{get:function(){return 7}}).a;var t;})),O=Object.getOwnPropertyDescriptor,A={f:c?O:function(t,r){if(t=v(t),r=b(r,!0),w)try{return O(t,r)}catch(t){}if(x(t,r))return l(!f.f.call(t,r),t[r])}},T=function(t){if(!y(t))throw TypeError(String(t)+" is not an object");return t},I=Object.defineProperty,P={f:c?I:function(t,r,e){if(T(t),r=b(r,!0),T(e),w)try{return I(t,r,e)}catch(t){}if("get"in e||"set"in e)throw TypeError("Accessors not supported");return "value"in e&&(t[r]=e.value),t}},R=c?function(t,r,e){return P.f(t,r,l(1,e))}:function(t,r,e){return t[r]=e,t},C=function(t,r){try{R(o,t,r);}catch(e){o[t]=r;}return r},_="__core-js_shared__",k=o[_]||C(_,{}),M=Function.toString;"function"!=typeof k.inspectSource&&(k.inspectSource=function(t){return M.call(t)});var N,$,U,D,K=k.inspectSource,L=o.WeakMap,z="function"==typeof L&&/native code/.test(K(L)),F=e((function(t){(t.exports=function(t,r){return k[t]||(k[t]=void 0!==r?r:{})})("versions",[]).push({version:"3.13.0",mode:"global",copyright:"© 2021 Denis Pushkarev (zloirock.ru)"});})),q=0,B=Math.random(),G=function(t){return "Symbol("+String(void 0===t?"":t)+")_"+(++q+B).toString(36)},W=F("keys"),Y={},V="Object already initialized",X=o.WeakMap;if(z||k.state){var H=k.state||(k.state=new X),J=H.get,Q=H.has,Z=H.set;N=function(t,r){if(Q.call(H,t))throw new TypeError(V);return r.facade=t,Z.call(H,t,r),r},$=function(t){return J.call(H,t)||{}},U=function(t){return Q.call(H,t)};}else {var tt=W[D="state"]||(W[D]=G(D));Y[tt]=!0,N=function(t,r){if(x(t,tt))throw new TypeError(V);return r.facade=t,R(t,tt,r),r},$=function(t){return x(t,tt)?t[tt]:{}},U=function(t){return x(t,tt)};}var rt,et,nt={set:N,get:$,has:U,enforce:function(t){return U(t)?$(t):N(t,{})},getterFor:function(t){return function(r){var e;if(!y(r)||(e=$(r)).type!==t)throw TypeError("Incompatible receiver, "+t+" required");return e}}},ot=e((function(t){var r=nt.get,e=nt.enforce,n=String(String).split("String");(t.exports=function(t,r,i,c){var u,a=!!c&&!!c.unsafe,f=!!c&&!!c.enumerable,l=!!c&&!!c.noTargetGet;"function"==typeof i&&("string"!=typeof r||x(i,"name")||R(i,"name",r),(u=e(i)).source||(u.source=n.join("string"==typeof r?r:""))),t!==o?(a?!l&&t[r]&&(f=!0):delete t[r],f?t[r]=i:R(t,r,i)):f?t[r]=i:C(r,i);})(Function.prototype,"toString",(function(){return "function"==typeof this&&r(this).source||K(this)}));})),it=o,ct=function(t){return "function"==typeof t?t:void 0},ut=function(t,r){return arguments.length<2?ct(it[t])||ct(o[t]):it[t]&&it[t][r]||o[t]&&o[t][r]},at=Math.ceil,ft=Math.floor,lt=function(t){return isNaN(t=+t)?0:(t>0?ft:at)(t)},st=Math.min,pt=function(t){return t>0?st(lt(t),9007199254740991):0},gt=Math.max,dt=Math.min,ht=function(t,r){var e=lt(t);return e<0?gt(e+r,0):dt(e,r)},vt=function(t){return function(r,e,n){var o,i=v(r),c=pt(i.length),u=ht(n,c);if(t&&e!=e){for(;c>u;)if((o=i[u++])!=o)return !0}else for(;c>u;u++)if((t||u in i)&&i[u]===e)return t||u||0;return !t&&-1}},yt={includes:vt(!0),indexOf:vt(!1)}.indexOf,bt=function(t,r){var e,n=v(t),o=0,i=[];for(e in n)!x(Y,e)&&x(n,e)&&i.push(e);for(;r.length>
140o;)x(n,e=r[o++])&&(~yt(i,e)||i.push(e));return i},mt=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],St=mt.concat("length","prototype"),xt={f:Object.getOwnPropertyNames||function(t){return bt(t,St)}},Et={f:Object.getOwnPropertySymbols},jt=ut("Reflect","ownKeys")||function(t){var r=xt.f(T(t)),e=Et.f;return e?r.concat(e(t)):r},wt=function(t,r){for(var e=jt(r),n=P.f,o=A.f,i=0;i<e.length;i++){var c=e[i];x(t,c)||n(t,c,o(r,c));}},Ot=/#|\.prototype\./,At=function(t,r){var e=It[Tt(t)];return e==Rt||e!=Pt&&("function"==typeof r?i(r):!!r)},Tt=At.normalize=function(t){return String(t).replace(Ot,".").toLowerCase()},It=At.data={},Pt=At.NATIVE="N",Rt=At.POLYFILL="P",Ct=At,_t=A.f,kt=function(t,r){var e,n,i,c,u,a=t.target,f=t.global,l=t.stat;if(e=f?o:l?o[a]||C(a,{}):(o[a]||{}).prototype)for(n in r){if(c=r[n],i=t.noTargetGet?(u=_t(e,n))&&u.value:e[n],!Ct(f?n:a+(l?".":"#")+n,t.forced)&&void 0!==i){if(typeof c==typeof i)continue;wt(c,i);}(t.sham||i&&i.sham)&&R(c,"sham",!0),ot(e,n,c,t);}},Mt=function(t,r,e){if(function(t){if("function"!=typeof t)throw TypeError(String(t)+" is not a function")}(t),void 0===r)return t;switch(e){case 0:return function(){return t.call(r)};case 1:return function(e){return t.call(r,e)};case 2:return function(e,n){return t.call(r,e,n)};case 3:return function(e,n,o){return t.call(r,e,n,o)}}return function(){return t.apply(r,arguments)}},Nt=Array.isArray||function(t){return "Array"==p(t)},$t=ut("navigator","userAgent")||"",Ut=o.process,Dt=Ut&&Ut.versions,Kt=Dt&&Dt.v8;Kt?et=(rt=Kt.split("."))[0]<4?1:rt[0]+rt[1]:$t&&(!(rt=$t.match(/Edge\/(\d+)/))||rt[1]>=74)&&(rt=$t.match(/Chrome\/(\d+)/))&&(et=rt[1]);var Lt=et&&+et,zt=!!Object.getOwnPropertySymbols&&!i((function(){return !String(Symbol())||!Symbol.sham&&Lt&&Lt<41})),Ft=zt&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,qt=F("wks"),Bt=o.Symbol,Gt=Ft?Bt:Bt&&Bt.withoutSetter||G,Wt=function(t){return x(qt,t)&&(zt||"string"==typeof qt[t])||(zt&&x(Bt,t)?qt[t]=Bt[t]:qt[t]=Gt("Symbol."+t)),qt[t]},Yt=Wt("species"),Vt=function(t,r){var e;return Nt(t)&&("function"!=typeof(e=t.constructor)||e!==Array&&!Nt(e.prototype)?y(e)&&null===(e=e[Yt])&&(e=void 0):e=void 0),new(void 0===e?Array:e)(0===r?0:r)},Xt=[].push,Ht=function(t){var r=1==t,e=2==t,n=3==t,o=4==t,i=6==t,c=7==t,u=5==t||i;return function(a,f,l,s){for(var p,g,h=m(a),v=d(h),y=Mt(f,l,3),b=pt(v.length),S=0,x=s||Vt,E=r?x(a,b):e||c?x(a,0):void 0;b>S;S++)if((u||S in v)&&(g=y(p=v[S],S,h),t))if(r)E[S]=g;else if(g)switch(t){case 3:return !0;case 5:return p;case 6:return S;case 2:Xt.call(E,p);}else switch(t){case 4:return !1;case 7:Xt.call(E,p);}return i?-1:n||o?o:E}},Jt={forEach:Ht(0),map:Ht(1),filter:Ht(2),some:Ht(3),every:Ht(4),find:Ht(5),findIndex:Ht(6),filterOut:Ht(7)},Qt=Wt("species"),Zt=function(t){return Lt>=51||!i((function(){var r=[];return (r.constructor={})[Qt]=function(){return {foo:1}},1!==r[t](Boolean).foo}))},tr=Jt.filter;kt({target:"Array",proto:!0,forced:!Zt("filter")},{filter:function(t){return tr(this,t,arguments.length>1?arguments[1]:void 0)}});var rr,er,nr=[].join,or=d!=Object,ir=(rr=",",!!(er=[]["join"])&&i((function(){er.call(null,rr||function(){throw 1},1);})));kt({target:"Array",proto:!0,forced:or||!ir},{join:function(t){return nr.call(v(this),void 0===t?",":t)}});var cr=function(t,r,e){var n=b(r);n in t?P.f(t,n,l(0,e)):t[n]=e;},ur=Zt("slice"),ar=Wt("species"),fr=[].slice,lr=Math.max;kt({target:"Array",proto:!0,forced:!ur},{slice:function(t,r){var e,n,o,i=v(this),c=pt(i.length),u=ht(t,c),a=ht(void 0===r?c:r,c);if(Nt(i)&&("function"!=typeof(e=i.constructor)||e!==Array&&!Nt(e.prototype)?y(e)&&null===(e=e[ar])&&(e=void 0):e=void 0,e===Array||void 0===e))return fr.call(i,u,a);for(n=new(void 0===e?Array:e)(lr(a-u,0)),o=0;u<a;u++,o++)u in i&&cr(n,o,i[u]);return n.length=o,n}});var sr={};sr[Wt("toStringTag")]="z";var pr="[object z]"===String(sr),gr=Wt("toStringTag"),dr="Arguments"==p(function(){return arguments}()),hr=pr?p:function(t){var r,e,n;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(e=function(t,r){try{return t[r]}catch(t){}}(r=Object(t),gr))?e:dr?p(r):"Object"==(n=p(r))&&"function"==typeof r.callee?"Arguments":n},vr=pr?{}.toString:function(){return "[object "+hr(this)+"]"};pr||ot(Object.prototype,"toString",vr,{unsafe:!0});var yr=function(){var t=T(this),r="";return t.global&&(r+="g"),t.ignoreCase&&(r+="i"),t.multiline&&(r+="m"),t.dotAll&&(r+="s"),t.unicode&&(r+="u"),t.sticky&&(r+="y"),r};function br(t,r){return RegExp(t,r)}var mr,Sr,xr={UNSUPPORTED_Y:i((function(){var t=br("a","y");return t.lastIndex=2,null!=t.exec("abcd")})),BROKEN_CARET:i((function(){var t=br("^r","gy");return t.lastIndex=2,null!=t.exec("str")}))},Er=RegExp.prototype.exec,jr=F("native-string-replace",String.prototype.replace),wr=Er,Or=(mr=/a/,Sr=/b*/g,Er.call(mr,"a"),Er.call(Sr,"a"),0!==mr.lastIndex||0!==Sr.lastIndex),Ar=xr.UNSUPPORTED_Y||xr.BROKEN_CARET,Tr=void 0!==/()??/.exec("")[1];(Or||Tr||Ar)&&(wr=function(t){var r,e,n,o,i=this,c=Ar&&i.sticky,u=yr.call(i),a=i.source,f=0,l=t;return c&&(-1===(u=u.replace("y","")).indexOf("g")&&(u+="g"),l=String(t).slice(i.lastIndex),i.lastIndex>0&&(!i.multiline||i.multiline&&"\n"!==t[i.lastIndex-1])&&(a="(?: "+a+")",l=" "+l,f++),e=new RegExp("^(?:"+a+")",u)),Tr&&(e=new RegExp("^"+a+"$(?!\\s)",u)),Or&&(r=i.lastIndex),n=Er.call(c?e:i,l),c?n?(n.input=n.input.slice(f),n[0]=n[0].slice(f),n.index=i.lastIndex,i.lastIndex+=n[0].length):i.lastIndex=0:Or&&n&&(i.lastIndex=i.global?n.index+n[0].length:r),Tr&&n&&n.length>1&&jr.call(n[0],e,(function(){for(o=1;o<arguments.length-2;o++)void 0===arguments[o]&&(n[o]=void 0);})),n});var Ir=wr;kt({target:"RegExp",proto:!0,forced:/./.exec!==Ir},{exec:Ir});var Pr=Wt("species"),Rr=RegExp.prototype,Cr=!i((function(){var t=/./;return t.exec=function(){var t=[];return t.groups={a:"7"},t},"7"!=="".replace(t,"$<a>")})),_r="$0"==="a".replace(/./,"$0"),kr=Wt("replace"),Mr=!!/./[kr]&&""===/./[kr]("a","$0");!i((function(){var t=/(?:)/,r=t.exec;t.exec=function(){return r.apply(this,arguments)};var e="ab".split(t);return 2!==e.length||"a"!==e[0]||"b"!==e[1]}));var $r=function(t){return function(r,e){var n,o,i=String(h(r)),c=lt(e),u=i.length;return c<0||c>=u?t?"":void 0:(n=i.charCodeAt(c))<55296||n>56319||c+1===u||(o=i.charCodeAt(c+1))<56320||o>57343?t?i.charAt(c):n:t?i.slice(c,c+2):o-56320+(n-55296<<10)+65536}},Ur={codeAt:$r(!1),charAt:$r(!0)}.charAt,Dr=function(t,r,e){return r+(e?Ur(t,r).length:1)},Kr=Math.floor,Lr="".replace,zr=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Fr=/\$([$&'`]|\d{1,2})/g,qr=function(t,r,e,n,o,i){var c=e+t.length,u=n.length,a=Fr;return void 0!==o&&(o=m(o),a=zr),Lr.call(i,a,(function(i,a){var f;switch(a.charAt(0)){case"$":return "$";case"&":return t;case"`":return r.slice(0,e);case"'":return r.slice(c);case"<":f=o[a.slice(1,-1)];break;default:var l=+a;if(0===l)return i;if(l>u){var s=Kr(l/10);return 0===s?i:s<=u?void 0===n[s-1]?a.charAt(1):n[s-1]+a.charAt(1):i}f=n[l-1];}return void 0===f?"":f}))},Br=function(t,r){var e=t.exec;if("function"==typeof e){var n=e.call(t,r);
140if("object"!=typeof n)throw TypeError("RegExp exec method returned something other than an Object or null");return n}if("RegExp"!==p(t))throw TypeError("RegExp#exec called on incompatible receiver");return Ir.call(t,r)},Gr=Math.max,Wr=Math.min;!function(t,r,e,n){var o=Wt(t),c=!i((function(){var r={};return r[o]=function(){return 7},7!=""[t](r)})),u=c&&!i((function(){var r=!1,e=/a/;return "split"===t&&((e={}).constructor={},e.constructor[Pr]=function(){return e},e.flags="",e[o]=/./[o]),e.exec=function(){return r=!0,null},e[o](""),!r}));if(!c||!u||(!Cr||!_r||Mr)||"split"===t){var a=/./[o],f=e(o,""[t],(function(t,r,e,n,o){var i=r.exec;return i===Ir||i===Rr.exec?c&&!o?{done:!0,value:a.call(r,e,n)}:{done:!0,value:t.call(e,r,n)}:{done:!1}}),{REPLACE_KEEPS_$0:_r,REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE:Mr}),l=f[0],s=f[1];ot(String.prototype,t,l),ot(Rr,o,function(t,r){return s.call(t,this,r)});}}("replace",2,(function(t,r,e,n){var o=n.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE,i=n.REPLACE_KEEPS_$0,c=o?"$":"$0";return [function(e,n){var o=h(this),i=null==e?void 0:e[t];return void 0!==i?i.call(e,o,n):r.call(String(o),e,n)},function(t,n){if(!o&&i||"string"==typeof n&&-1===n.indexOf(c)){var u=e(r,t,this,n);if(u.done)return u.value}var a=T(t),f=String(this),l="function"==typeof n;l||(n=String(n));var s=a.global;if(s){var p=a.unicode;a.lastIndex=0;}for(var g=[];;){var d=Br(a,f);if(null===d)break;if(g.push(d),!s)break;""===String(d[0])&&(a.lastIndex=Dr(f,pt(a.lastIndex),p));}for(var h,v="",y=0,b=0;b<g.length;b++){d=g[b];for(var m=String(d[0]),S=Gr(Wr(lt(d.index),f.length),0),x=[],E=1;E<d.length;E++)x.push(void 0===(h=d[E])?h:String(h));var j=d.groups;if(l){var w=[m].concat(x,S,f);void 0!==j&&w.push(j);var O=String(n.apply(void 0,w));}else O=qr(m,f,S,x,j,n);S>=y&&(v+=f.slice(y,S)+O,y=S+m.length);}return v+f.slice(y)}]}));var Yr=e((function(t){!function(r){function e(t,r){var e=(65535&t)+(65535&r);return (t>>16)+(r>>16)+(e>>16)<<16|65535&e}function n(t,r,n,o,i,c){return e((u=e(e(r,t),e(o,c)))<<(a=i)|u>>>32-a,n);var u,a;}function o(t,r,e,o,i,c,u){return n(r&e|~r&o,t,r,i,c,u)}function i(t,r,e,o,i,c,u){return n(r&o|e&~o,t,r,i,c,u)}function c(t,r,e,o,i,c,u){return n(r^e^o,t,r,i,c,u)}function u(t,r,e,o,i,c,u){return n(e^(r|~o),t,r,i,c,u)}function a(t,r){var n,a,f,l,s;t[r>>5]|=128<<r%32,t[14+(r+64>>>9<<4)]=r;var p=1732584193,g=-271733879,d=-1732584194,h=271733878;for(n=0;n<t.length;n+=16)a=p,f=g,l=d,s=h,p=o(p,g,d,h,t[n],7,-680876936),h=o(h,p,g,d,t[n+1],12,-389564586),d=o(d,h,p,g,t[n+2],17,606105819),g=o(g,d,h,p,t[n+3],22,-1044525330),p=o(p,g,d,h,t[n+4],7,-176418897),h=o(h,p,g,d,t[n+5],12,1200080426),d=o(d,h,p,g,t[n+6],17,-1473231341),g=o(g,d,h,p,t[n+7],22,-45705983),p=o(p,g,d,h,t[n+8],7,1770035416),h=o(h,p,g,d,t[n+9],12,-1958414417),d=o(d,h,p,g,t[n+10],17,-42063),g=o(g,d,h,p,t[n+11],22,-1990404162),p=o(p,g,d,h,t[n+12],7,1804603682),h=o(h,p,g,d,t[n+13],12,-40341101),d=o(d,h,p,g,t[n+14],17,-1502002290),p=i(p,g=o(g,d,h,p,t[n+15],22,1236535329),d,h,t[n+1],5,-165796510),h=i(h,p,g,d,t[n+6],9,-1069501632),d=i(d,h,p,g,t[n+11],14,643717713),g=i(g,d,h,p,t[n],20,-373897302),p=i(p,g,d,h,t[n+5],5,-701558691),h=i(h,p,g,d,t[n+10],9,38016083),d=i(d,h,p,g,t[n+15],14,-660478335),g=i(g,d,h,p,t[n+4],20,-405537848),p=i(p,g,d,h,t[n+9],5,568446438),h=i(h,p,g,d,t[n+14],9,-1019803690),d=i(d,h,p,g,t[n+3],14,-187363961),g=i(g,d,h,p,t[n+8],20,1163531501),p=i(p,g,d,h,t[n+13],5,-1444681467),h=i(h,p,g,d,t[n+2],9,-51403784),d=i(d,h,p,g,t[n+7],14,1735328473),p=c(p,g=i(g,d,h,p,t[n+12],20,-1926607734),d,h,t[n+5],4,-378558),h=c(h,p,g,d,t[n+8],11,-2022574463),d=c(d,h,p,g,t[n+11],16,1839030562),g=c(g,d,h,p,t[n+14],23,-35309556),p=c(p,g,d,h,t[n+1],4,-1530992060),h=c(h,p,g,d,t[n+4],11,1272893353),d=c(d,h,p,g,t[n+7],16,-155497632),g=c(g,d,h,p,t[n+10],23,-1094730640),p=c(p,g,d,h,t[n+13],4,681279174),h=c(h,p,g,d,t[n],11,-358537222),d=c(d,h,p,g,t[n+3],16,-722521979),g=c(g,d,h,p,t[n+6],23,76029189),p=c(p,g,d,h,t[n+9],4,-640364487),h=c(h,p,g,d,t[n+12],11,-421815835),d=c(d,h,p,g,t[n+15],16,530742520),p=u(p,g=c(g,d,h,p,t[n+2],23,-995338651),d,h,t[n],6,-198630844),h=u(h,p,g,d,t[n+7],10,1126891415),d=u(d,h,p,g,t[n+14],15,-1416354905),g=u(g,d,h,p,t[n+5],21,-57434055),p=u(p,g,d,h,t[n+12],6,1700485571),h=u(h,p,g,d,t[n+3],10,-1894986606),d=u(d,h,p,g,t[n+10],15,-1051523),g=u(g,d,h,p,t[n+1],21,-2054922799),p=u(p,g,d,h,t[n+8],6,1873313359),h=u(h,p,g,d,t[n+15],10,-30611744),d=u(d,h,p,g,t[n+6],15,-1560198380),g=u(g,d,h,p,t[n+13],21,1309151649),p=u(p,g,d,h,t[n+4],6,-145523070),h=u(h,p,g,d,t[n+11],10,-1120210379),d=u(d,h,p,g,t[n+2],15,718787259),g=u(g,d,h,p,t[n+9],21,-343485551),p=e(p,a),g=e(g,f),d=e(d,l),h=e(h,s);return [p,g,d,h]}function f(t){var r,e="",n=32*t.length;for(r=0;r<n;r+=8)e+=String.fromCharCode(t[r>>5]>>>r%32&255);return e}function l(t){var r,e=[];for(e[(t.length>>2)-1]=void 0,r=0;r<e.length;r+=1)e[r]=0;var n=8*t.length;for(r=0;r<n;r+=8)e[r>>5]|=(255&t.charCodeAt(r/8))<<r%32;return e}function s(t){var r,e,n="0123456789abcdef",o="";for(e=0;e<t.length;e+=1)r=t.charCodeAt(e),o+=n.charAt(r>>>4&15)+n.charAt(15&r);return o}function p(t){return unescape(encodeURIComponent(t))}function g(t){return function(t){return f(a(l(t),8*t.length))}(p(t))}function d(t,r){return function(t,r){var e,n,o=l(t),i=[],c=[];for(i[15]=c[15]=void 0,o.length>16&&(o=a(o,8*t.length)),e=0;e<16;e+=1)i[e]=909522486^o[e],c[e]=1549556828^o[e];return n=a(i.concat(l(r)),512+8*r.length),f(a(c.concat(n),640))}(p(t),p(r))}function h(t,r,e){return r?e?d(r,t):s(d(r,t)):e?g(t):s(g(t))}t.exports?t.exports=h:r.md5=h;}(r);}));function Vr(t){var r=t.label,e=t.project,n=t.namespace;if(!e||!r)return "";var o=[e,n,r].filter((function(t){return !!t})).join("_").replace(/\s/g,"_");return Yr(o).slice(8,24)}kt({target:"Array",stat:!0},{isArray:Nt});var Xr=Jt.map;kt({target:"Array",proto:!0,forced:!Zt("map")},{map:function(t){return Xr(this,t,arguments.length>1?arguments[1]:void 0)}});var Hr=Object.keys||function(t){return bt(t,mt)}
140,Jr=Object.assign,Qr=Object.defineProperty,Zr=!Jr||i((function(){if(c&&1!==Jr({b:1},Jr(Qr({},"a",{enumerable:!0,get:function(){Qr(this,"b",{value:3,enumerable:!1});}}),{b:2})).b)return !0;var t={},r={},e=Symbol(),n="abcdefghijklmnopqrst";return t[e]=7,n.split("").forEach((function(t){r[t]=t;})),7!=Jr({},t)[e]||Hr(Jr({},r)).join("")!=n}))?function(t,r){for(var e=m(t),n=arguments.length,o=1,i=Et.f,u=f.f;n>o;)for(var a,l=d(arguments[o++]),s=i?Hr(l).concat(i(l)):Hr(l),p=s.length,g=0;p>g;)a=s[g++],c&&!u.call(l,a)||(e[a]=l[a]);return e}:Jr;kt({target:"Object",stat:!0,forced:Object.assign!==Zr},{assign:Zr}),kt({target:"Object",stat:!0,forced:i((function(){Hr(1);}))},{keys:function(t){return Hr(m(t))}});var te="ssc-transify-switch";function re(){try{return !!localStorage.getItem(te)}catch(t){return !1}}function ee(t,r){t.innerText=r?"Show "+r:"Show Key",t.style.backgroundColor=r?"#55CC77":"#EE4D2D";}t.generateKey=Vr,t.generateTransifyCommon=function(t){if(!t||!t.project||!t.project.length)throw new Error("project is required!");var r=Array.isArray(t.project)?t.project:[t.project],e=r.length>1,n=t.projectsResourceIdsMap||{},o=t.t,i=t.needWarning;return function(c,u,a){for(var f=re()||t.isShowKey,l=null,s="",p="",g=0;g<r.length;g++){var d=r[g],h=Vr({label:c,namespace:u,project:d}),v=o(h,void 0);if(h!==v&&(l=n[d],p=h,s=v,c!==v||f))break}return p?f?e&&l?l+" - "+p:p:a?o(p,a):s:(i&&console.warn("the key '"+p+"' for label '"+c+"' is undefined."),f?"No Key: "+c:c)}},t.generateTransifyVueI18n=function(t,r){if(!r||!r.project)throw new Error("project is required!");return function(e,n,o){var i=Vr({label:e,namespace:n,project:r.project});if(!i)return "";var c=t.t(i,o);return r.isShowKey||c===i&&(c=e),c}},t.getShowKey=re,t.useSSCTransify=function(t,r,e){var n="";try{n=localStorage.getItem(te)||"";}catch(t){return}var o=function(t,r){var e=document.createElement("button"),n=r||{},o=n.btnStyle,i=Object.assign({position:"fixed",zIndex:"10000",right:"4px",top:"100px",padding:"2px 8px",border:0,borderRadius:"4px",color:"#fff"},o||{});return e.setAttribute("style",Object.keys(i).map((function(t){return t+":"+i[t]})).join(";")),ee(e,t),document.body.appendChild(e),e}(n,e);o.addEventListener("click",(function(){var e=localStorage.getItem(te);if(e)t(e),localStorage.removeItem(te),ee(o);else {var n=r();t("ssc-transify"),localStorage.setItem(te,n),ee(o,n);}}));},Object.defineProperty(t,"__esModule",{value:!0});}));
141    		
142    	} (index_umd$1, index_umd$1.exports));
143    	return index_umd$1.exports;
144    }
145
146    var index_umdExports = requireIndex_umd();
147
148    const isString = obj => typeof obj === 'string';
149    const defer = () => {
150      let res;
151      let rej;
152      const promise = new Promise((resolve, reject) => {
153        res = resolve;
154        rej = reject;
155      });
156      promise.resolve = res;
157      promise.reject = rej;
158      return promise;
159    };
160    const makeString = object => {
161      if (object == null) return '';
162      return '' + object;
163    };
164    const copy = (a, s, t) => {
165      a.forEach(m => {
166        if (s[m]) t[m] = s[m];
167      });
168    };
169    const lastOfPathSeparatorRegExp = /###/g;
170    const cleanKey = key => key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key;
171    const canNotTraverseDeeper = object => !object || isString(object);
172    const getLastOfPath = (object, path, Empty) => {
173      const stack = !isString(path) ? path : path.split('.');
174      let stackIndex = 0;
175      while (stackIndex < stack.length - 1) {
176        if (canNotTraverseDeeper(object)) return {};
177        const key = cleanKey(stack[stackIndex]);
178        if (!object[key] && Empty) object[key] = new Empty();
179        if (Object.prototype.hasOwnProperty.call(object, key)) {
180          object = object[key];
181        } else {
182          object = {};
183        }
184        ++stackIndex;
185      }
186      if (canNotTraverseDeeper(object)) return {};
187      return {
188        obj: object,
189        k: cleanKey(stack[stackIndex])
190      };
191    };
192    const setPath = (object, path, newValue) => {
193      const {
194        obj,
195        k
196      } = getLastOfPath(object, path, Object);
197      if (obj !== undefined || path.length === 1) {
198        obj[k] = newValue;
199        return;
200      }
201      let e = path[path.length - 1];
202      let p = path.slice(0, path.length - 1);
203      let last = getLastOfPath(object, p, Object);
204      while (last.obj === undefined && p.length) {
205        e = `${p[p.length - 1]}.${e}`;
206        p = p.slice(0, p.length - 1);
207        last = getLastOfPath(object, p, Object);
208        if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {
209          last.obj = undefined;
210        }
211      }
212      last.obj[`${last.k}.${e}`] = newValue;
213    };
214    const pushPath = (object, path, newValue, concat) => {
215      const {
216        obj,
217        k
218      } = getLastOfPath(object, path, Object);
219      obj[k] = obj[k] || [];
220      obj[k].push(newValue);
221    };
222    const getPath = (object, path) => {
223      const {
224        obj,
225        k
226      } = getLastOfPath(object, path);
227      if (!obj) return undefined;
228      if (!Object.prototype.hasOwnProperty.call(obj, k)) return undefined;
229      return obj[k];
230    };
231    const getPathWithDefaults = (data, defaultData, key) => {
232      const value = getPath(data, key);
233      if (value !== undefined) {
234        return value;
235      }
236      return getPath(defaultData, key);
237    };
238    const deepExtend = (target, source, overwrite) => {
239      for (const prop in source) {
240        if (prop !== '__proto__' && prop !== 'constructor') {
241          if (prop in target) {
242            if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
243              if (overwrite) target[prop] = source[prop];
244            } else {
245              deepExtend(target[prop], source[prop], overwrite);
246            }
247          } else {
248            target[prop] = source[prop];
249          }
250        }
251      }
252      return target;
253    };
254    const regexEscape = str => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
255    var _entityMap = {
256      '&': '&amp;',
257      '<': '&lt;',
258      '>': '&gt;',
259      '"': '&quot;',
260      "'": '&#39;',
261      '/': '&#x2F;'
262    };
263    const escape$1 = data => {
264      if (isString(data)) {
265        return data.replace(/[&<>
vendor: 5,461 bytes, lines 265-437
265"'\/]/g, s => _entityMap[s]);
266      }
267      return data;
268    };
269    class RegExpCache {
270      constructor(capacity) {
271        this.capacity = capacity;
272        this.regExpMap = new Map();
273        this.regExpQueue = [];
274      }
275      getRegExp(pattern) {
276        const regExpFromCache = this.regExpMap.get(pattern);
277        if (regExpFromCache !== undefined) {
278          return regExpFromCache;
279        }
280        const regExpNew = new RegExp(pattern);
281        if (this.regExpQueue.length === this.capacity) {
282          this.regExpMap.delete(this.regExpQueue.shift());
283        }
284        this.regExpMap.set(pattern, regExpNew);
285        this.regExpQueue.push(pattern);
286        return regExpNew;
287      }
288    }
289    const chars = [' ', ',', '?', '!', ';'];
290    const looksLikeObjectPathRegExpCache = new RegExpCache(20);
291    const looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
292      nsSeparator = nsSeparator || '';
293      keySeparator = keySeparator || '';
294      const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
295      if (possibleChars.length === 0) return true;
296      const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`);
297      let matched = !r.test(key);
298      if (!matched) {
299        const ki = key.indexOf(keySeparator);
300        if (ki > 0 && !r.test(key.substring(0, ki))) {
301          matched = true;
302        }
303      }
304      return matched;
305    };
306    const deepFind = (obj, path, keySeparator = '.') => {
307      if (!obj) return undefined;
308      if (obj[path]) {
309        if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined;
310        return obj[path];
311      }
312      const tokens = path.split(keySeparator);
313      let current = obj;
314      for (let i = 0; i < tokens.length;) {
315        if (!current || typeof current !== 'object') {
316          return undefined;
317        }
318        let next;
319        let nextPath = '';
320        for (let j = i; j < tokens.length; ++j) {
321          if (j !== i) {
322            nextPath += keySeparator;
323          }
324          nextPath += tokens[j];
325          next = current[nextPath];
326          if (next !== undefined) {
327            if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) {
328              continue;
329            }
330            i += j - i + 1;
331            break;
332          }
333        }
334        current = next;
335      }
336      return current;
337    };
338    const getCleanedCode = code => code?.replace(/_/g, '-');
339
340    const consoleLogger = {
341      type: 'logger',
342      log(args) {
343        this.output('log', args);
344      },
345      warn(args) {
346        this.output('warn', args);
347      },
348      error(args) {
349        this.output('error', args);
350      },
351      output(type, args) {
352        console?.[type]?.apply?.(console, args);
353      }
354    };
355    class Logger {
356      constructor(concreteLogger, options = {}) {
357        this.init(concreteLogger, options);
358      }
359      init(concreteLogger, options = {}) {
360        this.prefix = options.prefix || 'i18next:';
361        this.logger = concreteLogger || consoleLogger;
362        this.options = options;
363        this.debug = options.debug;
364      }
365      log(...args) {
366        return this.forward(args, 'log', '', true);
367      }
368      warn(...args) {
369        return this.forward(args, 'warn', '', true);
370      }
371      error(...args) {
372        return this.forward(args, 'error', '');
373      }
374      deprecate(...args) {
375        return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
376      }
377      forward(args, lvl, prefix, debugOnly) {
378        if (debugOnly && !this.debug) return null;
379        if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
380        return this.logger[lvl](args);
381      }
382      create(moduleName) {
383        return new Logger(this.logger, {
384          ...{
385            prefix: `${this.prefix}:${moduleName}:`
386          },
387          ...this.options
388        });
389      }
390      clone(options) {
391        options = options || this.options;
392        options.prefix = options.prefix || this.prefix;
393        return new Logger(this.logger, options);
394      }
395    }
396    var baseLogger = new Logger();
397
398    class EventEmitter {
399      constructor() {
400        this.observers = {};
401      }
402      on(events, listener) {
403        events.split(' ').forEach(event => {
404          if (!this.observers[event]) this.observers[event] = new Map();
405          const numListeners = this.observers[event].get(listener) || 0;
406          this.observers[event].set(listener, numListeners + 1);
407        });
408        return this;
409      }
410      off(event, listener) {
411        if (!this.observers[event]) return;
412        if (!listener) {
413          delete this.observers[event];
414          return;
415        }
416        this.observers[event].delete(listener);
417      }
418      emit(event, ...args) {
419        if (this.observers[event]) {
420          const cloned = Array.from(this.observers[event].entries());
421          cloned.forEach(([observer, numTimesAdded]) => {
422            for (let i = 0; i < numTimesAdded; i++) {
423              observer(...args);
424            }
425          });
426        }
427        if (this.observers['*']) {
428          const cloned = Array.from(this.observers['*'].entries());
429          cloned.forEach(([observer, numTimesAdded]) => {
430            for (let i = 0; i < numTimesAdded; i++) {
431              observer.apply(observer, [event, ...args]);
432            }
433          });
434        }
435      }
436    }
437
vendor: 4,585 bytes, lines 438-573
438    class ResourceStore extends EventEmitter {
439      constructor(data, options = {
440        ns: ['translation'],
441        defaultNS: 'translation'
442      }) {
443        super();
444        this.data = data || {};
445        this.options = options;
446        if (this.options.keySeparator === undefined) {
447          this.options.keySeparator = '.';
448        }
449        if (this.options.ignoreJSONStructure === undefined) {
450          this.options.ignoreJSONStructure = true;
451        }
452      }
453      addNamespaces(ns) {
454        if (this.options.ns.indexOf(ns) < 0) {
455          this.options.ns.push(ns);
456        }
457      }
458      removeNamespaces(ns) {
459        const index = this.options.ns.indexOf(ns);
460        if (index > -1) {
461          this.options.ns.splice(index, 1);
462        }
463      }
464      getResource(lng, ns, key, options = {}) {
465        const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
466        const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
467        let path;
468        if (lng.indexOf('.') > -1) {
469          path = lng.split('.');
470        } else {
471          path = [lng, ns];
472          if (key) {
473            if (Array.isArray(key)) {
474              path.push(...key);
475            } else if (isString(key) && keySeparator) {
476              path.push(...key.split(keySeparator));
477            } else {
478              path.push(key);
479            }
480          }
481        }
482        const result = getPath(this.data, path);
483        if (!result && !ns && !key && lng.indexOf('.') > -1) {
484          lng = path[0];
485          ns = path[1];
486          key = path.slice(2).join('.');
487        }
488        if (result || !ignoreJSONStructure || !isString(key)) return result;
489        return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
490      }
491      addResource(lng, ns, key, value, options = {
492        silent: false
493      }) {
494        const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
495        let path = [lng, ns];
496        if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
497        if (lng.indexOf('.') > -1) {
498          path = lng.split('.');
499          value = ns;
500          ns = path[1];
501        }
502        this.addNamespaces(ns);
503        setPath(this.data, path, value);
504        if (!options.silent) this.emit('added', lng, ns, key, value);
505      }
506      addResources(lng, ns, resources, options = {
507        silent: false
508      }) {
509        for (const m in resources) {
510          if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
511            silent: true
512          });
513        }
514        if (!options.silent) this.emit('added', lng, ns, resources);
515      }
516      addResourceBundle(lng, ns, resources, deep, overwrite, options = {
517        silent: false,
518        skipCopy: false
519      }) {
520        let path = [lng, ns];
521        if (lng.indexOf('.') > -1) {
522          path = lng.split('.');
523          deep = resources;
524          resources = ns;
525          ns = path[1];
526        }
527        this.addNamespaces(ns);
528        let pack = getPath(this.data, path) || {};
529        if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
530        if (deep) {
531          deepExtend(pack, resources, overwrite);
532        } else {
533          pack = {
534            ...pack,
535            ...resources
536          };
537        }
538        setPath(this.data, path, pack);
539        if (!options.silent) this.emit('added', lng, ns, resources);
540      }
541      removeResourceBundle(lng, ns) {
542        if (this.hasResourceBundle(lng, ns)) {
543          delete this.data[lng][ns];
544        }
545        this.removeNamespaces(ns);
546        this.emit('removed', lng, ns);
547      }
548      hasResourceBundle(lng, ns) {
549        return this.getResource(lng, ns) !== undefined;
550      }
551      getResourceBundle(lng, ns) {
552        if (!ns) ns = this.options.defaultNS;
553        return this.getResource(lng, ns);
554      }
555      getDataByLanguage(lng) {
556        return this.data[lng];
557      }
558      hasLanguageSomeTranslations(lng) {
559        const data = this.getDataByLanguage(lng);
560        const n = data && Object.keys(data) || [];
561        return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);
562      }
563      toJSON() {
564        return this.data;
565      }
566    }
567
568    var postProcessor = {
569      processors: {},
570      addPostProcessor(module) {
571        this.processors[module.name] = module;
572      },
573      handle(processors, value, key, options, translator) {
vendor: 4,522 bytes, lines 574-686
574        processors.forEach(processor => {
575          value = this.processors[processor]?.process(value, key, options, translator) ?? value;
576        });
577        return value;
578      }
579    };
580
581    const PATH_KEY = Symbol('i18next/PATH_KEY');
582    function createProxy() {
583      const state = [];
584      const handler = Object.create(null);
585      let proxy;
586      handler.get = (target, key) => {
587        proxy?.revoke?.();
588        if (key === PATH_KEY) return state;
589        state.push(key);
590        proxy = Proxy.revocable(target, handler);
591        return proxy.proxy;
592      };
593      return Proxy.revocable(Object.create(null), handler).proxy;
594    }
595    function keysFromSelector(selector, opts) {
596      const {
597        [PATH_KEY]: path
598      } = selector(createProxy());
599      const keySeparator = opts?.keySeparator ?? '.';
600      const nsSeparator = opts?.nsSeparator ?? ':';
601      if (path.length > 1 && nsSeparator) {
602        const ns = opts?.ns;
603        const nsArray = Array.isArray(ns) ? ns : null;
604        if (nsArray && nsArray.length > 1 && nsArray.slice(1).includes(path[0])) {
605          return `${path[0]}${nsSeparator}${path.slice(1).join(keySeparator)}`;
606        }
607      }
608      return path.join(keySeparator);
609    }
610
611    const checkedLoadedFor = {};
612    const shouldHandleAsObject = res => !isString(res) && typeof res !== 'boolean' && typeof res !== 'number';
613    class Translator extends EventEmitter {
614      constructor(services, options = {}) {
615        super();
616        copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);
617        this.options = options;
618        if (this.options.keySeparator === undefined) {
619          this.options.keySeparator = '.';
620        }
621        this.logger = baseLogger.create('translator');
622      }
623      changeLanguage(lng) {
624        if (lng) this.language = lng;
625      }
626      exists(key, o = {
627        interpolation: {}
628      }) {
629        const opt = {
630          ...o
631        };
632        if (key == null) return false;
633        const resolved = this.resolve(key, opt);
634        if (resolved?.res === undefined) return false;
635        const isObject = shouldHandleAsObject(resolved.res);
636        if (opt.returnObjects === false && isObject) {
637          return false;
638        }
639        return true;
640      }
641      extractFromKey(key, opt) {
642        let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
643        if (nsSeparator === undefined) nsSeparator = ':';
644        const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
645        let namespaces = opt.ns || this.options.defaultNS || [];
646        const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
647        const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
648        if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
649          const m = key.match(this.interpolator.nestingRegexp);
650          if (m && m.length > 0) {
651            return {
652              key,
653              namespaces: isString(namespaces) ? [namespaces] : namespaces
654            };
655          }
656          const parts = key.split(nsSeparator);
657          if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
658          key = parts.join(keySeparator);
659        }
660        return {
661          key,
662          namespaces: isString(namespaces) ? [namespaces] : namespaces
663        };
664      }
665      translate(keys, o, lastKey) {
666        let opt = typeof o === 'object' ? {
667          ...o
668        } : o;
669        if (typeof opt !== 'object' && this.options.overloadTranslationOptionHandler) {
670          opt = this.options.overloadTranslationOptionHandler(arguments);
671        }
672        if (typeof opt === 'object') opt = {
673          ...opt
674        };
675        if (!opt) opt = {};
676        if (keys == null) return '';
677        if (typeof keys === 'function') keys = keysFromSelector(keys, {
678          ...this.options,
679          ...opt
680        });
681        if (!Array.isArray(keys)) keys = [String(keys)];
682        keys = keys.map(k => typeof k === 'function' ? keysFromSelector(k, {
683          ...this.options,
684          ...opt
685        }) : String(k));
686        const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails;
vendor: 9,895 bytes, lines 687-885
687        const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
688        const {
689          key,
690          namespaces
691        } = this.extractFromKey(keys[keys.length - 1], opt);
692        const namespace = namespaces[namespaces.length - 1];
693        let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
694        if (nsSeparator === undefined) nsSeparator = ':';
695        const lng = opt.lng || this.language;
696        const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
697        if (lng?.toLowerCase() === 'cimode') {
698          if (appendNamespaceToCIMode) {
699            if (returnDetails) {
700              return {
701                res: `${namespace}${nsSeparator}${key}`,
702                usedKey: key,
703                exactUsedKey: key,
704                usedLng: lng,
705                usedNS: namespace,
706                usedParams: this.getUsedParamsDetails(opt)
707              };
708            }
709            return `${namespace}${nsSeparator}${key}`;
710          }
711          if (returnDetails) {
712            return {
713              res: key,
714              usedKey: key,
715              exactUsedKey: key,
716              usedLng: lng,
717              usedNS: namespace,
718              usedParams: this.getUsedParamsDetails(opt)
719            };
720          }
721          return key;
722        }
723        const resolved = this.resolve(keys, opt);
724        let res = resolved?.res;
725        const resUsedKey = resolved?.usedKey || key;
726        const resExactUsedKey = resolved?.exactUsedKey || key;
727        const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
728        const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays;
729        const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
730        const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
731        const hasDefaultValue = Translator.hasDefaultValue(opt);
732        const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : '';
733        const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
734          ordinal: false
735        }) : '';
736        const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
737        const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
738        let resForObjHndl = res;
739        if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
740          resForObjHndl = defaultValue;
741        }
742        const handleAsObject = shouldHandleAsObject(resForObjHndl);
743        const resType = Object.prototype.toString.apply(resForObjHndl);
744        if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
745          if (!opt.returnObjects && !this.options.returnObjects) {
746            if (!this.options.returnedObjectHandler) {
747              this.logger.warn('accessing an object - but returnObjects options is not enabled!');
748            }
749            const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
750              ...opt,
751              ns: namespaces
752            }) : `key '${key} (${this.language})' returned an object instead of string.`;
753            if (returnDetails) {
754              resolved.res = r;
755              resolved.usedParams = this.getUsedParamsDetails(opt);
756              return resolved;
757            }
758            return r;
759          }
760          if (keySeparator) {
761            const resTypeIsArray = Array.isArray(resForObjHndl);
762            const copy = resTypeIsArray ? [] : {};
763            const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
764            for (const m in resForObjHndl) {
765              if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
766                const deepKey = `${newKeyToUse}${keySeparator}${m}`;
767                if (hasDefaultValue && !res) {
768                  copy[m] = this.translate(deepKey, {
769                    ...opt,
770                    defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined,
771                    ...{
772                      joinArrays: false,
773                      ns: namespaces
774                    }
775                  });
776                } else {
777                  copy[m] = this.translate(deepKey, {
778                    ...opt,
779                    ...{
780                      joinArrays: false,
781                      ns: namespaces
782                    }
783                  });
784                }
785                if (copy[m] === deepKey) copy[m] = resForObjHndl[m];
786              }
787            }
788            res = copy;
789          }
790        } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
791          res = res.join(joinArrays);
792          if (res) res = this.extendTranslation(res, keys, opt, lastKey);
793        } else {
794          let usedDefault = false;
795          let usedKey = false;
796          if (!this.isValidLookup(res) && hasDefaultValue) {
797            usedDefault = true;
798            res = defaultValue;
799          }
800          if (!this.isValidLookup(res)) {
801            usedKey = true;
802            res = key;
803          }
804          const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
805          const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
806          const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
807          if (usedKey || usedDefault || updateMissing) {
808            this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
809            if (keySeparator) {
810              const fk = this.resolve(key, {
811                ...opt,
812                keySeparator: false
813              });
814              if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');
815            }
816            let lngs = [];
817            const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
818            if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
819              for (let i = 0; i < fallbackLngs.length; i++) {
820                lngs.push(fallbackLngs[i]);
821              }
822            } else if (this.options.saveMissingTo === 'all') {
823              lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
824            } else {
825              lngs.push(opt.lng || this.language);
826            }
827            const send = (l, k, specificDefaultValue) => {
828              const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
829              if (this.options.missingKeyHandler) {
830                this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
831              } else if (this.backendConnector?.saveMissing) {
832                this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
833              }
834              this.emit('missingKey', l, namespace, k, res);
835            };
836            if (this.options.saveMissing) {
837              if (this.options.saveMissingPlurals && needsPluralHandling) {
838                lngs.forEach(language => {
839                  const suffixes = this.pluralResolver.getSuffixes(language, opt);
840                  if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
841                    suffixes.push(`${this.options.pluralSeparator}zero`);
842                  }
843                  suffixes.forEach(suffix => {
844                    send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
845                  });
846                });
847              } else {
848                send(lngs, key, defaultValue);
849              }
850            }
851          }
852          res = this.extendTranslation(res, keys, opt, resolved, lastKey);
853          if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
854            res = `${namespace}${nsSeparator}${key}`;
855          }
856          if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
857            res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt);
858          }
859        }
860        if (returnDetails) {
861          resolved.res = res;
862          resolved.usedParams = this.getUsedParamsDetails(opt);
863          return resolved;
864        }
865        return res;
866      }
867      extendTranslation(res, key, opt, resolved, lastKey) {
868        if (this.i18nFormat?.parse) {
869          res = this.i18nFormat.parse(res, {
870            ...this.options.interpolation.defaultVariables,
871            ...opt
872          }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
873            resolved
874          });
875        } else if (!opt.skipInterpolation) {
876          if (opt.interpolation) this.interpolator.init({
877            ...opt,
878            ...{
879              interpolation: {
880                ...this.options.interpolation,
881                ...opt.interpolation
882              }
883            }
884          });
885          const skipOnVariables = isString(res) && (opt?.interpolation?.ski
vendor: 7,754 bytes, lines 885-1043
885pOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
886          let nestBef;
887          if (skipOnVariables) {
888            const nb = res.match(this.interpolator.nestingRegexp);
889            nestBef = nb && nb.length;
890          }
891          let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
892          if (this.options.interpolation.defaultVariables) data = {
893            ...this.options.interpolation.defaultVariables,
894            ...data
895          };
896          res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
897          if (skipOnVariables) {
898            const na = res.match(this.interpolator.nestingRegexp);
899            const nestAft = na && na.length;
900            if (nestBef < nestAft) opt.nest = false;
901          }
902          if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
903          if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
904            if (lastKey?.[0] === args[0] && !opt.context) {
905              this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
906              return null;
907            }
908            return this.translate(...args, key);
909          }, opt);
910          if (opt.interpolation) this.interpolator.reset();
911        }
912        const postProcess = opt.postProcess || this.options.postProcess;
913        const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
914        if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
915          res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
916            i18nResolved: {
917              ...resolved,
918              usedParams: this.getUsedParamsDetails(opt)
919            },
920            ...opt
921          } : opt, this);
922        }
923        return res;
924      }
925      resolve(keys, opt = {}) {
926        let found;
927        let usedKey;
928        let exactUsedKey;
929        let usedLng;
930        let usedNS;
931        if (isString(keys)) keys = [keys];
932        if (Array.isArray(keys)) keys = keys.map(k => typeof k === 'function' ? keysFromSelector(k, {
933          ...this.options,
934          ...opt
935        }) : k);
936        keys.forEach(k => {
937          if (this.isValidLookup(found)) return;
938          const extracted = this.extractFromKey(k, opt);
939          const key = extracted.key;
940          usedKey = key;
941          let namespaces = extracted.namespaces;
942          if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
943          const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
944          const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
945          const needsContextHandling = opt.context !== undefined && (isString(opt.context) || typeof opt.context === 'number') && opt.context !== '';
946          const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
947          namespaces.forEach(ns => {
948            if (this.isValidLookup(found)) return;
949            usedNS = ns;
950            if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
951              checkedLoadedFor[`${codes[0]}-${ns}`] = true;
952              this.logger.warn(`key "${usedKey}" for languages "${codes.join(', ')}" won't get resolved as namespace "${usedNS}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
953            }
954            codes.forEach(code => {
955              if (this.isValidLookup(found)) return;
956              usedLng = code;
957              const finalKeys = [key];
958              if (this.i18nFormat?.addLookupKeys) {
959                this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
960              } else {
961                let pluralSuffix;
962                if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
963                const zeroSuffix = `${this.options.pluralSeparator}zero`;
964                const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
965                if (needsPluralHandling) {
966                  if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
967                    finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
968                  }
969                  finalKeys.push(key + pluralSuffix);
970                  if (needsZeroSuffixLookup) {
971                    finalKeys.push(key + zeroSuffix);
972                  }
973                }
974                if (needsContextHandling) {
975                  const contextKey = `${key}${this.options.contextSeparator || '_'}${opt.context}`;
976                  finalKeys.push(contextKey);
977                  if (needsPluralHandling) {
978                    if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
979                      finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
980                    }
981                    finalKeys.push(contextKey + pluralSuffix);
982                    if (needsZeroSuffixLookup) {
983                      finalKeys.push(contextKey + zeroSuffix);
984                    }
985                  }
986                }
987              }
988              let possibleKey;
989              while (possibleKey = finalKeys.pop()) {
990                if (!this.isValidLookup(found)) {
991                  exactUsedKey = possibleKey;
992                  found = this.getResource(code, ns, possibleKey, opt);
993                }
994              }
995            });
996          });
997        });
998        return {
999          res: found,
1000          usedKey,
1001          exactUsedKey,
1002          usedLng,
1003          usedNS
1004        };
1005      }
1006      isValidLookup(res) {
1007        return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
1008      }
1009      getResource(code, ns, key, options = {}) {
1010        if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
1011        return this.resourceStore.getResource(code, ns, key, options);
1012      }
1013      getUsedParamsDetails(options = {}) {
1014        const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];
1015        const useOptionsReplaceForData = options.replace && !isString(options.replace);
1016        let data = useOptionsReplaceForData ? options.replace : options;
1017        if (useOptionsReplaceForData && typeof options.count !== 'undefined') {
1018          data.count = options.count;
1019        }
1020        if (this.options.interpolation.defaultVariables) {
1021          data = {
1022            ...this.options.interpolation.defaultVariables,
1023            ...data
1024          };
1025        }
1026        if (!useOptionsReplaceForData) {
1027          data = {
1028            ...data
1029          };
1030          for (const key of optionsKeys) {
1031            delete data[key];
1032          }
1033        }
1034        return data;
1035      }
1036      static hasDefaultValue(options) {
1037        const prefix = 'defaultValue';
1038        for (const option in options) {
1039          if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
1040            return true;
1041          }
1042        }
1043        return false;
vendor: 4,708 bytes, lines 1044-1147
1044      }
1045    }
1046
1047    class LanguageUtil {
1048      constructor(options) {
1049        this.options = options;
1050        this.supportedLngs = this.options.supportedLngs || false;
1051        this.logger = baseLogger.create('languageUtils');
1052      }
1053      getScriptPartFromCode(code) {
1054        code = getCleanedCode(code);
1055        if (!code || code.indexOf('-') < 0) return null;
1056        const p = code.split('-');
1057        if (p.length === 2) return null;
1058        p.pop();
1059        if (p[p.length - 1].toLowerCase() === 'x') return null;
1060        return this.formatLanguageCode(p.join('-'));
1061      }
1062      getLanguagePartFromCode(code) {
1063        code = getCleanedCode(code);
1064        if (!code || code.indexOf('-') < 0) return code;
1065        const p = code.split('-');
1066        return this.formatLanguageCode(p[0]);
1067      }
1068      formatLanguageCode(code) {
1069        if (isString(code) && code.indexOf('-') > -1) {
1070          let formattedCode;
1071          try {
1072            formattedCode = Intl.getCanonicalLocales(code)[0];
1073          } catch (e) {}
1074          if (formattedCode && this.options.lowerCaseLng) {
1075            formattedCode = formattedCode.toLowerCase();
1076          }
1077          if (formattedCode) return formattedCode;
1078          if (this.options.lowerCaseLng) {
1079            return code.toLowerCase();
1080          }
1081          return code;
1082        }
1083        return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
1084      }
1085      isSupportedCode(code) {
1086        if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
1087          code = this.getLanguagePartFromCode(code);
1088        }
1089        return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
1090      }
1091      getBestMatchFromCodes(codes) {
1092        if (!codes) return null;
1093        let found;
1094        codes.forEach(code => {
1095          if (found) return;
1096          const cleanedLng = this.formatLanguageCode(code);
1097          if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
1098        });
1099        if (!found && this.options.supportedLngs) {
1100          codes.forEach(code => {
1101            if (found) return;
1102            const lngScOnly = this.getScriptPartFromCode(code);
1103            if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
1104            const lngOnly = this.getLanguagePartFromCode(code);
1105            if (this.isSupportedCode(lngOnly)) return found = lngOnly;
1106            found = this.options.supportedLngs.find(supportedLng => {
1107              if (supportedLng === lngOnly) return supportedLng;
1108              if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
1109              if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng;
1110              if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
1111            });
1112          });
1113        }
1114        if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
1115        return found;
1116      }
1117      getFallbackCodes(fallbacks, code) {
1118        if (!fallbacks) return [];
1119        if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
1120        if (isString(fallbacks)) fallbacks = [fallbacks];
1121        if (Array.isArray(fallbacks)) return fallbacks;
1122        if (!code) return fallbacks.default || [];
1123        let found = fallbacks[code];
1124        if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
1125        if (!found) found = fallbacks[this.formatLanguageCode(code)];
1126        if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
1127        if (!found) found = fallbacks.default;
1128        return found || [];
1129      }
1130      toResolveHierarchy(code, fallbackCode) {
1131        const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
1132        const codes = [];
1133        const addCode = c => {
1134          if (!c) return;
1135          if (this.isSupportedCode(c)) {
1136            codes.push(c);
1137          } else {
1138            this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
1139          }
1140        };
1141        if (isString(code) && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {
1142          if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
1143          if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
1144          if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
1145        } else if (isString(code)) {
1146          addCode(this.formatLanguageCode(code));
1147        }
vendor: 3,162 bytes, lines 1148-1232
1148        fallbackCodes.forEach(fc => {
1149          if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
1150        });
1151        return codes;
1152      }
1153    }
1154
1155    const suffixesOrder = {
1156      zero: 0,
1157      one: 1,
1158      two: 2,
1159      few: 3,
1160      many: 4,
1161      other: 5
1162    };
1163    const dummyRule = {
1164      select: count => count === 1 ? 'one' : 'other',
1165      resolvedOptions: () => ({
1166        pluralCategories: ['one', 'other']
1167      })
1168    };
1169    class PluralResolver {
1170      constructor(languageUtils, options = {}) {
1171        this.languageUtils = languageUtils;
1172        this.options = options;
1173        this.logger = baseLogger.create('pluralResolver');
1174        this.pluralRulesCache = {};
1175      }
1176      clearCache() {
1177        this.pluralRulesCache = {};
1178      }
1179      getRule(code, options = {}) {
1180        const cleanedCode = getCleanedCode(code === 'dev' ? 'en' : code);
1181        const type = options.ordinal ? 'ordinal' : 'cardinal';
1182        const cacheKey = JSON.stringify({
1183          cleanedCode,
1184          type
1185        });
1186        if (cacheKey in this.pluralRulesCache) {
1187          return this.pluralRulesCache[cacheKey];
1188        }
1189        let rule;
1190        try {
1191          rule = new Intl.PluralRules(cleanedCode, {
1192            type
1193          });
1194        } catch (err) {
1195          if (typeof Intl === 'undefined') {
1196            this.logger.error('No Intl support, please use an Intl polyfill!');
1197            return dummyRule;
1198          }
1199          if (!code.match(/-|_/)) return dummyRule;
1200          const lngPart = this.languageUtils.getLanguagePartFromCode(code);
1201          rule = this.getRule(lngPart, options);
1202        }
1203        this.pluralRulesCache[cacheKey] = rule;
1204        return rule;
1205      }
1206      needsPlural(code, options = {}) {
1207        let rule = this.getRule(code, options);
1208        if (!rule) rule = this.getRule('dev', options);
1209        return rule?.resolvedOptions().pluralCategories.length > 1;
1210      }
1211      getPluralFormsOfKey(code, key, options = {}) {
1212        return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);
1213      }
1214      getSuffixes(code, options = {}) {
1215        let rule = this.getRule(code, options);
1216        if (!rule) rule = this.getRule('dev', options);
1217        if (!rule) return [];
1218        return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);
1219      }
1220      getSuffix(code, count, options = {}) {
1221        const rule = this.getRule(code, options);
1222        if (rule) {
1223          return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;
1224        }
1225        this.logger.warn(`no plural rule found for: ${code}`);
1226        return this.getSuffix('dev', count, options);
1227      }
1228    }
1229
1230    const deepFindWithDefaults = (data, defaultData, key, keySeparator = '.', ignoreJSONStructure = true) => {
1231      let path = getPathWithDefaults(data, defaultData, key);
1232      if (!path && ignoreJSONStructure && isString(key)) {
vendor: 1,350 bytes, lines 1233-1271
1233        path = deepFind(data, key, keySeparator);
1234        if (path === undefined) path = deepFind(defaultData, key, keySeparator);
1235      }
1236      return path;
1237    };
1238    const regexSafe = val => val.replace(/\$/g, '$$$$');
1239    class Interpolator {
1240      constructor(options = {}) {
1241        this.logger = baseLogger.create('interpolator');
1242        this.options = options;
1243        this.format = options?.interpolation?.format || (value => value);
1244        this.init(options);
1245      }
1246      init(options = {}) {
1247        if (!options.interpolation) options.interpolation = {
1248          escapeValue: true
1249        };
1250        const {
1251          escape: escape$1$1,
1252          escapeValue,
1253          useRawValueToEscape,
1254          prefix,
1255          prefixEscaped,
1256          suffix,
1257          suffixEscaped,
1258          formatSeparator,
1259          unescapeSuffix,
1260          unescapePrefix,
1261          nestingPrefix,
1262          nestingPrefixEscaped,
1263          nestingSuffix,
1264          nestingSuffixEscaped,
1265          nestingOptionsSeparator,
1266          maxReplaces,
1267          alwaysFormat
1268        } = options.interpolation;
1269        this.escape = escape$1$1 !== undefined ? escape$1$1 : escape$1;
1270        this.escapeValue = escapeValue !== undefined ? escapeValue : true;
1271        this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;
vendor: 6,367 bytes, lines 1272-1404
1272        this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || '{{';
1273        this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || '}}';
1274        this.formatSeparator = formatSeparator || ',';
1275        this.unescapePrefix = unescapeSuffix ? '' : unescapePrefix || '-';
1276        this.unescapeSuffix = this.unescapePrefix ? '' : unescapeSuffix || '';
1277        this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape('$t(');
1278        this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(')');
1279        this.nestingOptionsSeparator = nestingOptionsSeparator || ',';
1280        this.maxReplaces = maxReplaces || 1000;
1281        this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;
1282        this.resetRegExp();
1283      }
1284      reset() {
1285        if (this.options) this.init(this.options);
1286      }
1287      resetRegExp() {
1288        const getOrResetRegExp = (existingRegExp, pattern) => {
1289          if (existingRegExp?.source === pattern) {
1290            existingRegExp.lastIndex = 0;
1291            return existingRegExp;
1292          }
1293          return new RegExp(pattern, 'g');
1294        };
1295        this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
1296        this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
1297        this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
1298      }
1299      interpolate(str, data, lng, options) {
1300        let match;
1301        let value;
1302        let replaces;
1303        const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1304        const handleFormat = key => {
1305          if (key.indexOf(this.formatSeparator) < 0) {
1306            const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1307            return this.alwaysFormat ? this.format(path, undefined, lng, {
1308              ...options,
1309              ...data,
1310              interpolationkey: key
1311            }) : path;
1312          }
1313          const p = key.split(this.formatSeparator);
1314          const k = p.shift().trim();
1315          const f = p.join(this.formatSeparator).trim();
1316          return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1317            ...options,
1318            ...data,
1319            interpolationkey: k
1320          });
1321        };
1322        this.resetRegExp();
1323        const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
1324        const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1325        const todos = [{
1326          regex: this.regexpUnescape,
1327          safeValue: val => regexSafe(val)
1328        }, {
1329          regex: this.regexp,
1330          safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1331        }];
1332        todos.forEach(todo => {
1333          replaces = 0;
1334          while (match = todo.regex.exec(str)) {
1335            const matchedVar = match[1].trim();
1336            value = handleFormat(matchedVar);
1337            if (value === undefined) {
1338              if (typeof missingInterpolationHandler === 'function') {
1339                const temp = missingInterpolationHandler(str, match, options);
1340                value = isString(temp) ? temp : '';
1341              } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1342                value = '';
1343              } else if (skipOnVariables) {
1344                value = match[0];
1345                continue;
1346              } else {
1347                this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1348                value = '';
1349              }
1350            } else if (!isString(value) && !this.useRawValueToEscape) {
1351              value = makeString(value);
1352            }
1353            const safeValue = todo.safeValue(value);
1354            str = str.replace(match[0], safeValue);
1355            if (skipOnVariables) {
1356              todo.regex.lastIndex += value.length;
1357              todo.regex.lastIndex -= match[0].length;
1358            } else {
1359              todo.regex.lastIndex = 0;
1360            }
1361            replaces++;
1362            if (replaces >= this.maxReplaces) {
1363              break;
1364            }
1365          }
1366        });
1367        return str;
1368      }
1369      nest(str, fc, options = {}) {
1370        let match;
1371        let value;
1372        let clonedOptions;
1373        const handleHasOptions = (key, inheritedOptions) => {
1374          const sep = this.nestingOptionsSeparator;
1375          if (key.indexOf(sep) < 0) return key;
1376          const c = key.split(new RegExp(`${regexEscape(sep)}[ ]*{`));
1377          let optionsString = `{${c[1]}`;
1378          key = c[0];
1379          optionsString = this.interpolate(optionsString, clonedOptions);
1380          const matchedSingleQuotes = optionsString.match(/'/g);
1381          const matchedDoubleQuotes = optionsString.match(/"/g);
1382          if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || (matchedDoubleQuotes?.length ?? 0) % 2 !== 0) {
1383            optionsString = optionsString.replace(/'/g, '"');
1384          }
1385          try {
1386            clonedOptions = JSON.parse(optionsString);
1387            if (inheritedOptions) clonedOptions = {
1388              ...inheritedOptions,
1389              ...clonedOptions
1390            };
1391          } catch (e) {
1392            this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1393            return `${key}${sep}${optionsString}`;
1394          }
1395          if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
1396          return key;
1397        };
1398        while (match = this.nestingRegexp.exec(str)) {
1399          let formatters = [];
1400          clonedOptions = {
1401            ...options
1402          };
1403          clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
1404          clonedOptions.applyPostProcessor = false;
vendor: 15,699 bytes, lines 1405-1822
1405          delete clonedOptions.defaultValue;
1406          const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf('}') + 1 : match[1].indexOf(this.formatSeparator);
1407          if (keyEndIndex !== -1) {
1408            formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map(elem => elem.trim()).filter(Boolean);
1409            match[1] = match[1].slice(0, keyEndIndex);
1410          }
1411          value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1412          if (value && match[0] === str && !isString(value)) return value;
1413          if (!isString(value)) value = makeString(value);
1414          if (!value) {
1415            this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1416            value = '';
1417          }
1418          if (formatters.length) {
1419            value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1420              ...options,
1421              interpolationkey: match[1].trim()
1422            }), value.trim());
1423          }
1424          str = str.replace(match[0], value);
1425          this.regexp.lastIndex = 0;
1426        }
1427        return str;
1428      }
1429    }
1430
1431    const parseFormatStr = formatStr => {
1432      let formatName = formatStr.toLowerCase().trim();
1433      const formatOptions = {};
1434      if (formatStr.indexOf('(') > -1) {
1435        const p = formatStr.split('(');
1436        formatName = p[0].toLowerCase().trim();
1437        const optStr = p[1].substring(0, p[1].length - 1);
1438        if (formatName === 'currency' && optStr.indexOf(':') < 0) {
1439          if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1440        } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
1441          if (!formatOptions.range) formatOptions.range = optStr.trim();
1442        } else {
1443          const opts = optStr.split(';');
1444          opts.forEach(opt => {
1445            if (opt) {
1446              const [key, ...rest] = opt.split(':');
1447              const val = rest.join(':').trim().replace(/^'+|'+$/g, '');
1448              const trimmedKey = key.trim();
1449              if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
1450              if (val === 'false') formatOptions[trimmedKey] = false;
1451              if (val === 'true') formatOptions[trimmedKey] = true;
1452              if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
1453            }
1454          });
1455        }
1456      }
1457      return {
1458        formatName,
1459        formatOptions
1460      };
1461    };
1462    const createCachedFormatter = fn => {
1463      const cache = {};
1464      return (v, l, o) => {
1465        let optForCache = o;
1466        if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
1467          optForCache = {
1468            ...optForCache,
1469            [o.interpolationkey]: undefined
1470          };
1471        }
1472        const key = l + JSON.stringify(optForCache);
1473        let frm = cache[key];
1474        if (!frm) {
1475          frm = fn(getCleanedCode(l), o);
1476          cache[key] = frm;
1477        }
1478        return frm(v);
1479      };
1480    };
1481    const createNonCachedFormatter = fn => (v, l, o) => fn(getCleanedCode(l), o)(v);
1482    class Formatter {
1483      constructor(options = {}) {
1484        this.logger = baseLogger.create('formatter');
1485        this.options = options;
1486        this.init(options);
1487      }
1488      init(services, options = {
1489        interpolation: {}
1490      }) {
1491        this.formatSeparator = options.interpolation.formatSeparator || ',';
1492        const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
1493        this.formats = {
1494          number: cf((lng, opt) => {
1495            const formatter = new Intl.NumberFormat(lng, {
1496              ...opt
1497            });
1498            return val => formatter.format(val);
1499          }),
1500          currency: cf((lng, opt) => {
1501            const formatter = new Intl.NumberFormat(lng, {
1502              ...opt,
1503              style: 'currency'
1504            });
1505            return val => formatter.format(val);
1506          }),
1507          datetime: cf((lng, opt) => {
1508            const formatter = new Intl.DateTimeFormat(lng, {
1509              ...opt
1510            });
1511            return val => formatter.format(val);
1512          }),
1513          relativetime: cf((lng, opt) => {
1514            const formatter = new Intl.RelativeTimeFormat(lng, {
1515              ...opt
1516            });
1517            return val => formatter.format(val, opt.range || 'day');
1518          }),
1519          list: cf((lng, opt) => {
1520            const formatter = new Intl.ListFormat(lng, {
1521              ...opt
1522            });
1523            return val => formatter.format(val);
1524          })
1525        };
1526      }
1527      add(name, fc) {
1528        this.formats[name.toLowerCase().trim()] = fc;
1529      }
1530      addCached(name, fc) {
1531        this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1532      }
1533      format(value, format, lng, options = {}) {
1534        const formats = format.split(this.formatSeparator);
1535        if (formats.length > 1 && formats[0].indexOf('(') > 1 && formats[0].indexOf(')') < 0 && formats.find(f => f.indexOf(')') > -1)) {
1536          const lastIndex = formats.findIndex(f => f.indexOf(')') > -1);
1537          formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
1538        }
1539        const result = formats.reduce((mem, f) => {
1540          const {
1541            formatName,
1542            formatOptions
1543          } = parseFormatStr(f);
1544          if (this.formats[formatName]) {
1545            let formatted = mem;
1546            try {
1547              const valOptions = options?.formatParams?.[options.interpolationkey] || {};
1548              const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1549              formatted = this.formats[formatName](mem, l, {
1550                ...formatOptions,
1551                ...options,
1552                ...valOptions
1553              });
1554            } catch (error) {
1555              this.logger.warn(error);
1556            }
1557            return formatted;
1558          } else {
1559            this.logger.warn(`there was no format function for ${formatName}`);
1560          }
1561          return mem;
1562        }, value);
1563        return result;
1564      }
1565    }
1566
1567    const removePending = (q, name) => {
1568      if (q.pending[name] !== undefined) {
1569        delete q.pending[name];
1570        q.pendingCount--;
1571      }
1572    };
1573    class Connector extends EventEmitter {
1574      constructor(backend, store, services, options = {}) {
1575        super();
1576        this.backend = backend;
1577        this.store = store;
1578        this.services = services;
1579        this.languageUtils = services.languageUtils;
1580        this.options = options;
1581        this.logger = baseLogger.create('backendConnector');
1582        this.waitingReads = [];
1583        this.maxParallelReads = options.maxParallelReads || 10;
1584        this.readingCalls = 0;
1585        this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1586        this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1587        this.state = {};
1588        this.queue = [];
1589        this.backend?.init?.(services, options.backend, options);
1590      }
1591      queueLoad(languages, namespaces, options, callback) {
1592        const toLoad = {};
1593        const pending = {};
1594        const toLoadLanguages = {};
1595        const toLoadNamespaces = {};
1596        languages.forEach(lng => {
1597          let hasAllNamespaces = true;
1598          namespaces.forEach(ns => {
1599            const name = `${lng}|${ns}`;
1600            if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
1601              this.state[name] = 2;
1602            } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {
1603              if (pending[name] === undefined) pending[name] = true;
1604            } else {
1605              this.state[name] = 1;
1606              hasAllNamespaces = false;
1607              if (pending[name] === undefined) pending[name] = true;
1608              if (toLoad[name] === undefined) toLoad[name] = true;
1609              if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
1610            }
1611          });
1612          if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1613        });
1614        if (Object.keys(toLoad).length || Object.keys(pending).length) {
1615          this.queue.push({
1616            pending,
1617            pendingCount: Object.keys(pending).length,
1618            loaded: {},
1619            errors: [],
1620            callback
1621          });
1622        }
1623        return {
1624          toLoad: Object.keys(toLoad),
1625          pending: Object.keys(pending),
1626          toLoadLanguages: Object.keys(toLoadLanguages),
1627          toLoadNamespaces: Object.keys(toLoadNamespaces)
1628        };
1629      }
1630      loaded(name, err, data) {
1631        const s = name.split('|');
1632        const lng = s[0];
1633        const ns = s[1];
1634        if (err) this.emit('failedLoading', lng, ns, err);
1635        if (!err && data) {
1636          this.store.addResourceBundle(lng, ns, data, undefined, undefined, {
1637            skipCopy: true
1638          });
1639        }
1640        this.state[name] = err ? -1 : 2;
1641        if (err && data) this.state[name] = 0;
1642        const loaded = {};
1643        this.queue.forEach(q => {
1644          pushPath(q.loaded, [lng], ns);
1645          removePending(q, name);
1646          if (err) q.errors.push(err);
1647          if (q.pendingCount === 0 && !q.done) {
1648            Object.keys(q.loaded).forEach(l => {
1649              if (!loaded[l]) loaded[l] = {};
1650              const loadedKeys = q.loaded[l];
1651              if (loadedKeys.length) {
1652                loadedKeys.forEach(n => {
1653                  if (loaded[l][n] === undefined) loaded[l][n] = true;
1654                });
1655              }
1656            });
1657            q.done = true;
1658            if (q.errors.length) {
1659              q.callback(q.errors);
1660            } else {
1661              q.callback();
1662            }
1663          }
1664        });
1665        this.emit('loaded', loaded);
1666        this.queue = this.queue.filter(q => !q.done);
1667      }
1668      read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
1669        if (!lng.length) return callback(null, {});
1670        if (this.readingCalls >= this.maxParallelReads) {
1671          this.waitingReads.push({
1672            lng,
1673            ns,
1674            fcName,
1675            tried,
1676            wait,
1677            callback
1678          });
1679          return;
1680        }
1681        this.readingCalls++;
1682        const resolver = (err, data) => {
1683          this.readingCalls--;
1684          if (this.waitingReads.length > 0) {
1685            const next = this.waitingReads.shift();
1686            this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1687          }
1688          if (err && data && tried < this.maxRetries) {
1689            setTimeout(() => {
1690              this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1691            }, wait);
1692            return;
1693          }
1694          callback(err, data);
1695        };
1696        const fc = this.backend[fcName].bind(this.backend);
1697        if (fc.length === 2) {
1698          try {
1699            const r = fc(lng, ns);
1700            if (r && typeof r.then === 'function') {
1701              r.then(data => resolver(null, data)).catch(resolver);
1702            } else {
1703              resolver(null, r);
1704            }
1705          } catch (err) {
1706            resolver(err);
1707          }
1708          return;
1709        }
1710        return fc(lng, ns, resolver);
1711      }
1712      prepareLoading(languages, namespaces, options = {}, callback) {
1713        if (!this.backend) {
1714          this.logger.warn('No backend was added via i18next.use. Will not load resources.');
1715          return callback && callback();
1716        }
1717        if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
1718        if (isString(namespaces)) namespaces = [namespaces];
1719        const toLoad = this.queueLoad(languages, namespaces, options, callback);
1720        if (!toLoad.toLoad.length) {
1721          if (!toLoad.pending.length) callback();
1722          return null;
1723        }
1724        toLoad.toLoad.forEach(name => {
1725          this.loadOne(name);
1726        });
1727      }
1728      load(languages, namespaces, callback) {
1729        this.prepareLoading(languages, namespaces, {}, callback);
1730      }
1731      reload(languages, namespaces, callback) {
1732        this.prepareLoading(languages, namespaces, {
1733          reload: true
1734        }, callback);
1735      }
1736      loadOne(name, prefix = '') {
1737        const s = name.split('|');
1738        const lng = s[0];
1739        const ns = s[1];
1740        this.read(lng, ns, 'read', undefined, undefined, (err, data) => {
1741          if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1742          if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1743          this.loaded(name, err, data);
1744        });
1745      }
1746      saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {
1747        if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
1748          this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
1749          return;
1750        }
1751        if (key === undefined || key === null || key === '') return;
1752        if (this.backend?.create) {
1753          const opts = {
1754            ...options,
1755            isUpdate
1756          };
1757          const fc = this.backend.create.bind(this.backend);
1758          if (fc.length < 6) {
1759            try {
1760              let r;
1761              if (fc.length === 5) {
1762                r = fc(languages, namespace, key, fallbackValue, opts);
1763              } else {
1764                r = fc(languages, namespace, key, fallbackValue);
1765              }
1766              if (r && typeof r.then === 'function') {
1767                r.then(data => clb(null, data)).catch(clb);
1768              } else {
1769                clb(null, r);
1770              }
1771            } catch (err) {
1772              clb(err);
1773            }
1774          } else {
1775            fc(languages, namespace, key, fallbackValue, clb, opts);
1776          }
1777        }
1778        if (!languages || !languages[0]) return;
1779        this.store.addResource(languages[0], namespace, key, fallbackValue);
1780      }
1781    }
1782
1783    const get$1 = () => ({
1784      debug: false,
1785      initAsync: true,
1786      ns: ['translation'],
1787      defaultNS: ['translation'],
1788      fallbackLng: ['dev'],
1789      fallbackNS: false,
1790      supportedLngs: false,
1791      nonExplicitSupportedLngs: false,
1792      load: 'all',
1793      preload: false,
1794      simplifyPluralSuffix: true,
1795      keySeparator: '.',
1796      nsSeparator: ':',
1797      pluralSeparator: '_',
1798      contextSeparator: '_',
1799      partialBundledLanguages: false,
1800      saveMissing: false,
1801      updateMissing: false,
1802      saveMissingTo: 'fallback',
1803      saveMissingPlurals: true,
1804      missingKeyHandler: false,
1805      missingInterpolationHandler: false,
1806      postProcess: false,
1807      postProcessPassResolved: false,
1808      returnNull: false,
1809      returnEmptyString: true,
1810      returnObjects: false,
1811      joinArrays: false,
1812      returnedObjectHandler: false,
1813      parseMissingKeyHandler: false,
1814      appendNamespaceToMissingKey: false,
1815      appendNamespaceToCIMode: false,
1816      overloadTranslationOptionHandler: args => {
1817        let ret = {};
1818        if (typeof args[1] === 'object') ret = args[1];
1819        if (isString(args[1])) ret.defaultValue = args[1];
1820        if (isString(args[2])) ret.tDescription = args[2];
1821        if (typeof args[2] === 'object' || typeof args[3] === 'object') {
1822          const options = args[3] || args[2];
vendor: 5,572 bytes, lines 1823-1961
1823          Object.keys(options).forEach(key => {
1824            ret[key] = options[key];
1825          });
1826        }
1827        return ret;
1828      },
1829      interpolation: {
1830        escapeValue: true,
1831        format: value => value,
1832        prefix: '{{',
1833        suffix: '}}',
1834        formatSeparator: ',',
1835        unescapePrefix: '-',
1836        nestingPrefix: '$t(',
1837        nestingSuffix: ')',
1838        nestingOptionsSeparator: ',',
1839        maxReplaces: 1000,
1840        skipOnVariables: true
1841      },
1842      cacheInBuiltFormats: true
1843    });
1844    const transformOptions = options => {
1845      if (isString(options.ns)) options.ns = [options.ns];
1846      if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
1847      if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
1848      if (options.supportedLngs?.indexOf?.('cimode') < 0) {
1849        options.supportedLngs = options.supportedLngs.concat(['cimode']);
1850      }
1851      if (typeof options.initImmediate === 'boolean') options.initAsync = options.initImmediate;
1852      return options;
1853    };
1854
1855    const noop = () => {};
1856    const bindMemberFunctions = inst => {
1857      const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
1858      mems.forEach(mem => {
1859        if (typeof inst[mem] === 'function') {
1860          inst[mem] = inst[mem].bind(inst);
1861        }
1862      });
1863    };
1864    const SUPPORT_NOTICE_KEY = '__i18next_supportNoticeShown';
1865    const getSupportNoticeShown = () => {
1866      if (typeof globalThis !== 'undefined' && !!globalThis[SUPPORT_NOTICE_KEY]) return true;
1867      if (typeof process !== 'undefined' && process.env && process.env.I18NEXT_NO_SUPPORT_NOTICE) return true;
1868      if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'production') return true;
1869      return false;
1870    };
1871    const setSupportNoticeShown = () => {
1872      if (typeof globalThis !== 'undefined') globalThis[SUPPORT_NOTICE_KEY] = true;
1873    };
1874    const usesLocize = inst => {
1875      if (inst?.modules?.backend?.name?.indexOf('Locize') > 0) return true;
1876      if (inst?.modules?.backend?.constructor?.name?.indexOf('Locize') > 0) return true;
1877      if (inst?.options?.backend?.backends) {
1878        if (inst.options.backend.backends.some(b => b?.name?.indexOf('Locize') > 0 || b?.constructor?.name?.indexOf('Locize') > 0)) return true;
1879      }
1880      if (inst?.options?.backend?.projectId) return true;
1881      if (inst?.options?.backend?.backendOptions) {
1882        if (inst.options.backend.backendOptions.some(b => b?.projectId)) return true;
1883      }
1884      return false;
1885    };
1886    class I18n extends EventEmitter {
1887      constructor(options = {}, callback) {
1888        super();
1889        this.options = transformOptions(options);
1890        this.services = {};
1891        this.logger = baseLogger;
1892        this.modules = {
1893          external: []
1894        };
1895        bindMemberFunctions(this);
1896        if (callback && !this.isInitialized && !options.isClone) {
1897          if (!this.options.initAsync) {
1898            this.init(options, callback);
1899            return this;
1900          }
1901          setTimeout(() => {
1902            this.init(options, callback);
1903          }, 0);
1904        }
1905      }
1906      init(options = {}, callback) {
1907        this.isInitializing = true;
1908        if (typeof options === 'function') {
1909          callback = options;
1910          options = {};
1911        }
1912        if (options.defaultNS == null && options.ns) {
1913          if (isString(options.ns)) {
1914            options.defaultNS = options.ns;
1915          } else if (options.ns.indexOf('translation') < 0) {
1916            options.defaultNS = options.ns[0];
1917          }
1918        }
1919        const defOpts = get$1();
1920        this.options = {
1921          ...defOpts,
1922          ...this.options,
1923          ...transformOptions(options)
1924        };
1925        this.options.interpolation = {
1926          ...defOpts.interpolation,
1927          ...this.options.interpolation
1928        };
1929        if (options.keySeparator !== undefined) {
1930          this.options.userDefinedKeySeparator = options.keySeparator;
1931        }
1932        if (options.nsSeparator !== undefined) {
1933          this.options.userDefinedNsSeparator = options.nsSeparator;
1934        }
1935        if (typeof this.options.overloadTranslationOptionHandler !== 'function') {
1936          this.options.overloadTranslationOptionHandler = defOpts.overloadTranslationOptionHandler;
1937        }
1938        if (this.options.showSupportNotice !== false && !usesLocize(this) && !getSupportNoticeShown()) {
1939          if (typeof console !== 'undefined' && typeof console.info !== 'undefined') console.info('🌐 i18next is made possible by our own product, Locize — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙');
1940          setSupportNoticeShown();
1941        }
1942        const createClassOnDemand = ClassOrObject => {
1943          if (!ClassOrObject) return null;
1944          if (typeof ClassOrObject === 'function') return new ClassOrObject();
1945          return ClassOrObject;
1946        };
1947        if (!this.options.isClone) {
1948          if (this.modules.logger) {
1949            baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1950          } else {
1951            baseLogger.init(null, this.options);
1952          }
1953          let formatter;
1954          if (this.modules.formatter) {
1955            formatter = this.modules.formatter;
1956          } else {
1957            formatter = Formatter;
1958          }
1959          const lu = new LanguageUtil(this.options);
1960          this.store = new ResourceStore(this.options.resources, this.options);
1961          const s = this.services;
vendor: 4,755 bytes, lines 1962-2053
1962          s.logger = baseLogger;
1963          s.resourceStore = this.store;
1964          s.languageUtils = lu;
1965          s.pluralResolver = new PluralResolver(lu, {
1966            prepend: this.options.pluralSeparator,
1967            simplifyPluralSuffix: this.options.simplifyPluralSuffix
1968          });
1969          const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;
1970          if (usingLegacyFormatFunction) {
1971            this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);
1972          }
1973          if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
1974            s.formatter = createClassOnDemand(formatter);
1975            if (s.formatter.init) s.formatter.init(s, this.options);
1976            this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1977          }
1978          s.interpolator = new Interpolator(this.options);
1979          s.utils = {
1980            hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
1981          };
1982          s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1983          s.backendConnector.on('*', (event, ...args) => {
1984            this.emit(event, ...args);
1985          });
1986          if (this.modules.languageDetector) {
1987            s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1988            if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1989          }
1990          if (this.modules.i18nFormat) {
1991            s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1992            if (s.i18nFormat.init) s.i18nFormat.init(this);
1993          }
1994          this.translator = new Translator(this.services, this.options);
1995          this.translator.on('*', (event, ...args) => {
1996            this.emit(event, ...args);
1997          });
1998          this.modules.external.forEach(m => {
1999            if (m.init) m.init(this);
2000          });
2001        }
2002        this.format = this.options.interpolation.format;
2003        if (!callback) callback = noop;
2004        if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
2005          const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2006          if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
2007        }
2008        if (!this.services.languageDetector && !this.options.lng) {
2009          this.logger.warn('init: no languageDetector is used and no lng is defined');
2010        }
2011        const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
2012        storeApi.forEach(fcName => {
2013          this[fcName] = (...args) => this.store[fcName](...args);
2014        });
2015        const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
2016        storeApiChained.forEach(fcName => {
2017          this[fcName] = (...args) => {
2018            this.store[fcName](...args);
2019            return this;
2020          };
2021        });
2022        const deferred = defer();
2023        const load = () => {
2024          const finish = (err, t) => {
2025            this.isInitializing = false;
2026            if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');
2027            this.isInitialized = true;
2028            if (!this.options.isClone) this.logger.log('initialized', this.options);
2029            this.emit('initialized', this.options);
2030            deferred.resolve(t);
2031            callback(err, t);
2032          };
2033          if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
2034          this.changeLanguage(this.options.lng, finish);
2035        };
2036        if (this.options.resources || !this.options.initAsync) {
2037          load();
2038        } else {
2039          setTimeout(load, 0);
2040        }
2041        return deferred;
2042      }
2043      loadResources(language, callback = noop) {
2044        let usedCallback = callback;
2045        const usedLng = isString(language) ? language : this.language;
2046        if (typeof language === 'function') usedCallback = language;
2047        if (!this.options.resources || this.options.partialBundledLanguages) {
2048          if (usedLng?.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
2049          const toLoad = [];
2050          const append = lng => {
2051            if (!lng) return;
2052            if (lng === 'cimode') return;
2053            const lngs = this.services.languageUtils.toResolveHierarchy(lng);
vendor: 10,209 bytes, lines 2054-2306
2054            lngs.forEach(l => {
2055              if (l === 'cimode') return;
2056              if (toLoad.indexOf(l) < 0) toLoad.push(l);
2057            });
2058          };
2059          if (!usedLng) {
2060            const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2061            fallbacks.forEach(l => append(l));
2062          } else {
2063            append(usedLng);
2064          }
2065          this.options.preload?.forEach?.(l => append(l));
2066          this.services.backendConnector.load(toLoad, this.options.ns, e => {
2067            if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
2068            usedCallback(e);
2069          });
2070        } else {
2071          usedCallback(null);
2072        }
2073      }
2074      reloadResources(lngs, ns, callback) {
2075        const deferred = defer();
2076        if (typeof lngs === 'function') {
2077          callback = lngs;
2078          lngs = undefined;
2079        }
2080        if (typeof ns === 'function') {
2081          callback = ns;
2082          ns = undefined;
2083        }
2084        if (!lngs) lngs = this.languages;
2085        if (!ns) ns = this.options.ns;
2086        if (!callback) callback = noop;
2087        this.services.backendConnector.reload(lngs, ns, err => {
2088          deferred.resolve();
2089          callback(err);
2090        });
2091        return deferred;
2092      }
2093      use(module) {
2094        if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
2095        if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
2096        if (module.type === 'backend') {
2097          this.modules.backend = module;
2098        }
2099        if (module.type === 'logger' || module.log && module.warn && module.error) {
2100          this.modules.logger = module;
2101        }
2102        if (module.type === 'languageDetector') {
2103          this.modules.languageDetector = module;
2104        }
2105        if (module.type === 'i18nFormat') {
2106          this.modules.i18nFormat = module;
2107        }
2108        if (module.type === 'postProcessor') {
2109          postProcessor.addPostProcessor(module);
2110        }
2111        if (module.type === 'formatter') {
2112          this.modules.formatter = module;
2113        }
2114        if (module.type === '3rdParty') {
2115          this.modules.external.push(module);
2116        }
2117        return this;
2118      }
2119      setResolvedLanguage(l) {
2120        if (!l || !this.languages) return;
2121        if (['cimode', 'dev'].indexOf(l) > -1) return;
2122        for (let li = 0; li < this.languages.length; li++) {
2123          const lngInLngs = this.languages[li];
2124          if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
2125          if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
2126            this.resolvedLanguage = lngInLngs;
2127            break;
2128          }
2129        }
2130        if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {
2131          this.resolvedLanguage = l;
2132          this.languages.unshift(l);
2133        }
2134      }
2135      changeLanguage(lng, callback) {
2136        this.isLanguageChangingTo = lng;
2137        const deferred = defer();
2138        this.emit('languageChanging', lng);
2139        const setLngProps = l => {
2140          this.language = l;
2141          this.languages = this.services.languageUtils.toResolveHierarchy(l);
2142          this.resolvedLanguage = undefined;
2143          this.setResolvedLanguage(l);
2144        };
2145        const done = (err, l) => {
2146          if (l) {
2147            if (this.isLanguageChangingTo === lng) {
2148              setLngProps(l);
2149              this.translator.changeLanguage(l);
2150              this.isLanguageChangingTo = undefined;
2151              this.emit('languageChanged', l);
2152              this.logger.log('languageChanged', l);
2153            }
2154          } else {
2155            this.isLanguageChangingTo = undefined;
2156          }
2157          deferred.resolve((...args) => this.t(...args));
2158          if (callback) callback(err, (...args) => this.t(...args));
2159        };
2160        const setLng = lngs => {
2161          if (!lng && !lngs && this.services.languageDetector) lngs = [];
2162          const fl = isString(lngs) ? lngs : lngs && lngs[0];
2163          const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
2164          if (l) {
2165            if (!this.language) {
2166              setLngProps(l);
2167            }
2168            if (!this.translator.language) this.translator.changeLanguage(l);
2169            this.services.languageDetector?.cacheUserLanguage?.(l);
2170          }
2171          this.loadResources(l, err => {
2172            done(err, l);
2173          });
2174        };
2175        if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
2176          setLng(this.services.languageDetector.detect());
2177        } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
2178          if (this.services.languageDetector.detect.length === 0) {
2179            this.services.languageDetector.detect().then(setLng);
2180          } else {
2181            this.services.languageDetector.detect(setLng);
2182          }
2183        } else {
2184          setLng(lng);
2185        }
2186        return deferred;
2187      }
2188      getFixedT(lng, ns, keyPrefix) {
2189        const fixedT = (key, opts, ...rest) => {
2190          let o;
2191          if (typeof opts !== 'object') {
2192            o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2193          } else {
2194            o = {
2195              ...opts
2196            };
2197          }
2198          o.lng = o.lng || fixedT.lng;
2199          o.lngs = o.lngs || fixedT.lngs;
2200          o.ns = o.ns || fixedT.ns;
2201          if (o.keyPrefix !== '') o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
2202          const selectorOpts = {
2203            ...this.options,
2204            ...o
2205          };
2206          if (typeof o.keyPrefix === 'function') o.keyPrefix = keysFromSelector(o.keyPrefix, selectorOpts);
2207          const keySeparator = this.options.keySeparator || '.';
2208          let resultKey;
2209          if (o.keyPrefix && Array.isArray(key)) {
2210            resultKey = key.map(k => {
2211              if (typeof k === 'function') k = keysFromSelector(k, selectorOpts);
2212              return `${o.keyPrefix}${keySeparator}${k}`;
2213            });
2214          } else {
2215            if (typeof key === 'function') key = keysFromSelector(key, selectorOpts);
2216            resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
2217          }
2218          return this.t(resultKey, o);
2219        };
2220        if (isString(lng)) {
2221          fixedT.lng = lng;
2222        } else {
2223          fixedT.lngs = lng;
2224        }
2225        fixedT.ns = ns;
2226        fixedT.keyPrefix = keyPrefix;
2227        return fixedT;
2228      }
2229      t(...args) {
2230        return this.translator?.translate(...args);
2231      }
2232      exists(...args) {
2233        return this.translator?.exists(...args);
2234      }
2235      setDefaultNamespace(ns) {
2236        this.options.defaultNS = ns;
2237      }
2238      hasLoadedNamespace(ns, options = {}) {
2239        if (!this.isInitialized) {
2240          this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
2241          return false;
2242        }
2243        if (!this.languages || !this.languages.length) {
2244          this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
2245          return false;
2246        }
2247        const lng = options.lng || this.resolvedLanguage || this.languages[0];
2248        const fallbackLng = this.options ? this.options.fallbackLng : false;
2249        const lastLng = this.languages[this.languages.length - 1];
2250        if (lng.toLowerCase() === 'cimode') return true;
2251        const loadNotPending = (l, n) => {
2252          const loadState = this.services.backendConnector.state[`${l}|${n}`];
2253          return loadState === -1 || loadState === 0 || loadState === 2;
2254        };
2255        if (options.precheck) {
2256          const preResult = options.precheck(this, loadNotPending);
2257          if (preResult !== undefined) return preResult;
2258        }
2259        if (this.hasResourceBundle(lng, ns)) return true;
2260        if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2261        if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2262        return false;
2263      }
2264      loadNamespaces(ns, callback) {
2265        const deferred = defer();
2266        if (!this.options.ns) {
2267          if (callback) callback();
2268          return Promise.resolve();
2269        }
2270        if (isString(ns)) ns = [ns];
2271        ns.forEach(n => {
2272          if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2273        });
2274        this.loadResources(err => {
2275          deferred.resolve();
2276          if (callback) callback(err);
2277        });
2278        return deferred;
2279      }
2280      loadLanguages(lngs, callback) {
2281        const deferred = defer();
2282        if (isString(lngs)) lngs = [lngs];
2283        const preloaded = this.options.preload || [];
2284        const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
2285        if (!newLngs.length) {
2286          if (callback) callback();
2287          return Promise.resolve();
2288        }
2289        this.options.preload = preloaded.concat(newLngs);
2290        this.loadResources(err => {
2291          deferred.resolve();
2292          if (callback) callback(err);
2293        });
2294        return deferred;
2295      }
2296      dir(lng) {
2297        if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
2298        if (!lng) return 'rtl';
2299        try {
2300          const l = new Intl.Locale(lng);
2301          if (l && l.getTextInfo) {
2302            const ti = l.getTextInfo();
2303            if (ti && ti.direction) return ti.direction;
2304          }
2305        } catch (e) {}
2306        const rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', '
2306yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];
2307        const languageUtils = this.services?.languageUtils || new LanguageUtil(get$1());
2308        if (lng.toLowerCase().indexOf('-latn') > 1) return 'ltr';
2309        return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
2310      }
2311      static createInstance(options = {}, callback) {
2312        const instance = new I18n(options, callback);
2313        instance.createInstance = I18n.createInstance;
2314        return instance;
2315      }
2316      cloneInstance(options = {}, callback = noop) {
2317        const forkResourceStore = options.forkResourceStore;
2318        if (forkResourceStore) delete options.forkResourceStore;
2319        const mergedOptions = {
2320          ...this.options,
2321          ...options,
2322          ...{
2323            isClone: true
2324          }
2325        };
2326        const clone = new I18n(mergedOptions);
2327        if (options.debug !== undefined || options.prefix !== undefined) {
2328          clone.logger = clone.logger.clone(options);
2329        }
2330        const membersToCopy = ['store', 'services', 'language'];
2331        membersToCopy.forEach(m => {
2332          clone[m] = this[m];
2333        });
2334        clone.services = {
2335          ...this.services
2336        };
2337        clone.services.utils = {
2338          hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2339        };
2340        if (forkResourceStore) {
2341          const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
2342            prev[l] = {
2343              ...this.store.data[l]
2344            };
2345            prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
2346              acc[n] = {
2347                ...prev[l][n]
2348              };
2349              return acc;
2350            }, prev[l]);
2351            return prev;
2352          }, {});
2353          clone.store = new ResourceStore(clonedData, mergedOptions);
2354          clone.services.resourceStore = clone.store;
2355        }
2356        if (options.interpolation) {
2357          const defOpts = get$1();
2358          const mergedInterpolation = {
2359            ...defOpts.interpolation,
2360            ...this.options.interpolation,
2361            ...options.interpolation
2362          };
2363          const mergedForInterpolator = {
2364            ...mergedOptions,
2365            interpolation: mergedInterpolation
2366          };
2367          clone.services.interpolator = new Interpolator(mergedForInterpolator);
2368        }
2369        clone.translator = new Translator(clone.services, mergedOptions);
2370        clone.translator.on('*', (event, ...args) => {
2371          clone.emit(event, ...args);
2372        });
2373        clone.init(mergedOptions, callback);
2374        clone.translator.options = mergedOptions;
2375        clone.translator.backendConnector.services.utils = {
2376          hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2377        };
2378        return clone;
2379      }
2380      toJSON() {
2381        return {
2382          options: this.options,
2383          store: this.store,
2384          language: this.language,
2385          languages: this.languages,
2386          resolvedLanguage: this.resolvedLanguage
2387        };
2388      }
2389    }
2390    const instance = I18n.createInstance();
2391
2392    instance.createInstance;
2393    instance.dir;
2394    instance.init;
2395    instance.loadResources;
2396    instance.reloadResources;
2397    instance.use;
2398    instance.changeLanguage;
2399    instance.getFixedT;
2400    instance.t;
2401    instance.exists;
2402    instance.setDefaultNamespace;
2403    instance.hasLoadedNamespace;
2404    instance.loadNamespaces;
2405    instance.loadLanguages;
2406
2407    var isRunIngInNodeEnv = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
2408    // 构建时 {"NODE_ENV":"development","APP_VERSION":"v20260929-1220-MY-LIVE","env":"live","PARTNER_ID":"shopee"}.* 会被自动替换
2409    // test, uat, live
2410    var ENV = 'live';
2411    var CID = 'my';
2412    var PARTNER_ID = 'shopee';
2413    var isCtl = PARTNER_ID === 'ctl';
2414    var getRegion = function () {
2415        return CID.toUpperCase();
2416    };
2417    function getCurEnv() {
2418        if (window.location.origin.includes('test'))
2419            return 'test';
2420        if (window.location.origin.includes('uat'))
2421            return 'uat';
2422        if (window.location.origin.includes('staging'))
2423            return 'staging';
2424        if (window.location.origin.includes('localhost'))
2425            return 'test';
2426        return 'live';
2427    }
2428    var isDetailPage = function (pathname) {
2429        if (!pathname) {
2430            return false;
2431        }
2432        return pathname.split('/').filter(Boolean).length > 1;
2433    };
2434
2435    // 各个市场的语言列表
2436    var languageListMapByRegion = {
2437        'VN': ['en', 'vi', 'zh-Hans'],
2438        'TH': ['en', 'th', 'zh-Hans'],
2439        'MY': ['en', 'ms', 'zh-Hans'],
2440        'MY_CTL': ['en', 'ms', 'zh-Hans'],
2441        'SG': ['en', 'zh-Hans'],
2442        'PH': ['en', 'fil', 'zh-Hans'],
2443        'ID': ['en', 'id', 'zh-Hans'],
2444        'BR': ['en', 'br', 'zh-Hans'],
2445        'TW': ['tw', 'zh-Hans'],
2446        'CN': ['zh-Hans'],
2447        'UNKNOWN': ['en', 'zh-Hans'],
2448    };
2449    // 各个市场的本地语言
2450    var localLangMapByRegion = {
2451        'VN': 'vi',
2452        'TH': 'th',
2453        'MY': 'ms',
2454        'MY_CTL': 'ms',
2455        'ID': 'id',
2456        'SG': 'en',
2457        'PH': 'fil',
2458        'BR': 'br',
2459        'TW': 'tw',
2460        'CN': 'zh-Hans',
2461        'UNKNOWN': 'en',
2462    };
2463    var LanguageText = {
2464        en: 'EN',
2465        th: 'TH',
2466        vi: 'VI',
2467        ms: 'MS',
2468        id: 'ID',
2469        br: 'PT',
2470        tw: '繁體中文',
2471        'zh-Hans': 'CN',
2472        fil: 'FIL'
2473    };
2474    // 只有 TW 不同
2475    var urlLangMap = {
2476        en: 'en',
2477        th: 'th',
2478        vi: 'vi',
2479        ms: 'ms',
2480        id: 'id',
2481        br: 'br',
2482        fil: 'fil',
2483        'zh-Hans': 'zh-Hans',
2484        tw: 'zh-Hant',
2485    };
2486    // tsp 平台语言映射
2487    var tspLanguageMap = {
2488        en: 'en',
2489        br: 'pt-br',
2490        th: 'th',
2491        vi: 'vi',
2492        ms: 'ms-my',
2493        id: 'id',
2494        tw: 'zh-Hant',
2495        'zh-Hans': 'zh-Hans',
2496        fil: 'ph', // 翻译资源统一用 ph
2497    };
2498    // TSP 区域语言映射配置
2499    // 用于将应用内部语言代码映射到 Transify 平台上的目录名称
2500    var tspRegionalLanguageMap = {
2501        'VN': {
2502            'en': 'en-VN',
2503            'zh-Hans': 'zh-VN',
2504        },
2505        'TH': {
2506            'en': 'en-TH',
2507            'zh-Hans': 'zh-TH',
2508        },
2509        'MY': {
2510            'en': 'en-MY',
2511            'zh-Hans': 'zh-MY',
2512        },
2513        'MY_CTL': {
2514            'en': 'en-MY',
2515            'zh-Hans': 'zh-MY',
2516        },
2517        'SG': {
2518            'en': 'SG', // SG 市场特殊处理
2519            'zh-Hans': 'zh-SG',
2520        },
2521        'PH': {
2522            'en': 'en-PH',
2523            'zh-Hans': 'zh-PH',
2524        },
2525        'ID': {
2526            'en': 'en-ID',
2527            'zh-Hans': 'zh-ID',
2528        },
2529        'BR': {
2530            'en': 'en-BR',
2531            'zh-Hans': 'zh-BR',
2532        },
2533        'TW': {
2534            'en': 'en-TW',
2535        },
2536        'CN': {
2537            'zh-Hans': 'zh-Hans',
2538        },
2539        'UNKNOWN': {
2540            'en': 'en',
2541            'zh-Hans': 'zh-Hans',
2542        },
2543    };
2544    var getChatUserLanguage = function (region) {
2545        switch (region) {
2546            case 'tw':
2547                return 'zh-Hant';
2548            case 'th':
2549                return 'th-TH';
2550            case 'vi':
2551                return 'vi-VN';
2552            case 'id':
2553                return 'id-ID';
2554            case 'my':
2555                return 'ms-MY';
2556            case 'br':
2557                return 'pt-BR';
2558            case 'mx':
2559                return 'es-MX';
2560            case 'co':
2561                return 'es-CO';
2562            case 'cl':
2563                return 'es-CL';
2564            case 'ar':
2565                return 'es-AR';
2566            case 'pl':
2567                return 'pl';
2568            case 'es':
2569                return 'es-ES';
2570            case 'fr':
2571                return 'fr';
2572            case 'in':
2573                return 'en';
2574            // Rich-todo: fil 待确认
2575            default:
2576                return 'en';
2577        }
2578    };
2579    var getLanguageList = function (cid) {
2580        var country = getRegion();
2581        return languageListMapByRegion[country.toUpperCase()] || [];
2582    };
2583    // 和老官网保持一致
2584    var LANGUAGE_CACHE_KEY = 'language';
2585    var LANGUAGE_MOBILE_CACHE_KEY = 'SYSTEM_LANGUAGE';
2586    var LANGUAGE_COOKIE_KEY = 'app_lang';
2587    // url 需要显示 zh-Hant,符合国际化和 seo
2588    // 这里改了也需要改 getLangFromUrl 的逻辑
2589    var convertLangForUrl = function (lang) {
2590        if (lang === 'tw') {
2591            return 'zh-Hant';
2592        }
2593        return lang;
2594    };
2595    var convertUrlLangForI18n = function (lang) {
2596        if (lang === 'zh-Hant') {
2597            return 'tw';
2598        }
2599        return lang;
2600    };
2601    var getLangFromUrl = function (defaultLang, type) {
2602        if (type === void 0) { type = 'i18n'; }
2603        var pathname = window.location.pathname;
2604        // pathname中的 region 是小写的地区枚举值
2605        var lang = pathname.split('/')[1];
2606        if (!lang) {
2607            return defaultLang;
2608        }
2609        if (lang === 'zh-Hant') {
2610            return type === 'i18n' ? 'tw' : lang;
2611        }
2612        var matchedLangText = LanguageText[lang];
2613        if (matchedLangText) {
2614            return lang;
2615        }
2616        return defaultLang;
2617    };
2618
2619    function transformObjectToArray(obj, fields = []) {
2620      if (!obj || typeof obj !== "object") {
2621        return [];
2622      }
2623      return fields.map((key) => {
2624        if (!obj[key]) return null;
2625        return {
2626          key,
2627          value: obj[key]
2628        };
2629      }).filter((i) => !!i);
2630    }
2631    const createMenuList = (menu) => {
2632      return transformObjectToArray(menu, [
2633        "shipping",
2634        "service",
2635        "contact_sales",
2636        "join_us",
2637        "become_partner",
2638        "driver",
2639        "shopee_agency",
2640        "help_center"
2641      ]).filter((item) => item.value.main_menu && item.value.main_menu.length > 0);
2642    };
2643    const formatAccountInfo = (account, type) => {
2644      if (!account) {
2645        return "";
2646      }
2647      if (type === "phone") {
2648        const last4Digits = account.slice(-4);
2649        return `**${last4Digits}`;
2650      } else if (type === "email") {
2651        const first2Chars = account.slice(0, 2);
2652        return `${first2Chars}****`;
2653      }
2654      return "";
2655    };
2656    const timezoneMap = {
2657      UNKNOWN: "Asia/Taipei",
2658      SG: "Asia/Taipei",
2659      MY: "Asia/Taipei",
2660      "MY_CTL": "Asia/Taipei",
2661      TH: "Asia/Jakarta",
2662      TW: "Asia/Taipei",
2663      ID: "Asia/Jakarta",
2664      VN: "Asia/Jakarta",
2665      PH: "Asia/Taipei",
2666      BR: "America/Sao_Paulo",
2667      CN: "Asia/Shanghai"
2668    };
2669
2670    var __defProp$1 = Object.defineProperty;
2671    var __defProps$1 = Object.defineProperties;
2672    var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
2673    var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
2674    var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
2675    var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
2676    var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2677    var __spreadValues$1 = (a, b) => {
2678      for (var prop in b || (b = {}))
2679        if (__hasOwnProp$1.call(b, prop))
2680          __defNormalProp$1(a, prop, b[prop]);
2681      if (__getOwnPropSymbols$1)
2682        for (var prop of __getOwnPropSymbols$1(b)) {
2683          if (__propIsEnum$1.call(b, prop))
2684            __defNormalProp$1(a, prop, b[prop]);
2685        }
2686      return a;
2687    };
2688    var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
2689    var __objRest = (source, exclude) => {
2690      var target = {};
2691      for (var prop in source)
2692        if (__hasOwnProp$1.call(source, prop) && exclude.indexOf(prop) < 0)
2693          target[prop] = source[prop];
2694      if (source != null && __getOwnPropSymbols$1)
2695        for (var prop of __getOwnPropSymbols$1(source)) {
2696          if (exclude.indexOf(prop) < 0 && __propIsEnum$1.call(source, prop))
2697            target[prop] = source[prop];
2698        }
2699      return target;
2700    };
2701    const NSS_BANNER_REPORT_KEY = "nss_banner";
2702    class Banner {
2703      constructor(element, config = {}) {
2704        this.currentIndex = 0;
2705        this.autoPlayTimer = null;
2706        this.isHovered = false;
2707        this.touchStartX = 0;
2708        this.touchEndX = 0;
2709        this.container = element;
2710        const _a = config, { reportHandler } = _a, restConfig = __objRest(_a, ["reportHandler"]);
2711        this.reportHandler = reportHandler || (() => {
2712        });
2713        this.config = __spreadValues$1({
2714          autoPlay: true,
2715          autoPlayInterval: 5e3,
2716          showArrows: true,
2717          showDots: true
2718        }, restConfig);
2719        this.init();
2720      }
2721      init() {
2722        this.slidesContainer = this.container.querySelector(
2723          ".nss-banner__slides"
2724        );
2725        this.slides = this.container.querySelectorAll(".nss-banner__slide");
2726        this.dots = this.container.querySelectorAll(".nss-banner__dot");
2727        this.prevButton = this.container.querySelector(".nss-banner__arrow--prev");
2728        this.nextButton = this.container.querySelector(".nss-banner__arrow--next");
2729        if (this.slides.length <= 1) {
2730          return;
2731        }
2732        this.bindEvents();
2733        this.updateActiveDot();
2734        this.startAutoPlay();
2735        this.reportHandler({
2736          action_type: "banner_init",
2737          slide_index: this.currentIndex,
2738          slide_data: this.getSlideData(this.currentIndex)
2739        });
2740      }
2741      bindEvents() {
2742        if (this.prevButton) {
2743          this.prevButton.addEventListener("click", (e) => {
2744            e.preventDefault();
2745            this.reportHandler({
2746              action_type: "navigation_click",
2747              navigation_type: "prev_arrow",
2748              slide_index: this.currentIndex
2749            });
2750            this.goToPrevSlide();
2751          });
2752        }
2753        if (this.nextButton) {
2754          this.nextButton.addEventListener("click", (e) => {
2755            e.preventDefault();
2756            this.reportHandler({
2757              action_type: "navigation_click",
2758              navigation_type: "next_arrow",
2759              slide_index: this.currentIndex
2760            });
2761            this.goToNextSlide();
2762          });
2763        }
2764        this.dots.forEach((dot, index) => {
2765          dot.addEventListener("click", (e) => {
2766            e.preventDefault();
2767            this.reportHandler({
2768              action_type: "navigation_click",
2769              navigation_type: "dot",
2770              slide_index: index
2771            });
2772            this.goToSlide(index);
2773          });
2774        });
2775        this.container.addEventListener("keydown", (e) => {
2776          if (e.key === "ArrowLeft") {
2777            e.preventDefault();
2778            this.reportHandler({
2779              action_type: "keyboard_navigation",
2780              interaction_type: "arrow_left",
2781              slide_index: this.currentIndex
2782            });
2783            this.goToPrevSlide();
2784          } else if (e.key === "ArrowRight") {
2785            e.preventDefault();
2786            this.reportHandler({
2787              action_type: "keyboard_navigation",
2788              interaction_type: "arrow_right",
2789              slide_index: this.currentIndex
2790            });
2791            this.goToNextSlide();
2792          }
2793        });
2794        if (this.slides.length > 1) {
2795          this.container.addEventListener("mouseenter", () => {
2796            this.isHovered = true;
2797            this.reportHandler({
2798              action_type: "auto_play_pause",
2799              auto_play_action: "hover_pause"
2800            });
2801            this.stopAutoPlay();
2802          });
2803          this.container.addEventListener("mouseleave", () => {
2804            this.isHovered = false;
2805            this.reportHandler({
2806              action_type: "auto_play_resume",
2807              auto_play_action: "hover_resume"
2808            });
2809            this.startAutoPlay();
2810          });
2811        }
2812        this.slidesContainer.addEventListener(
2813          "touchstart",
2814          (e) => {
2815            this.touchStartX = e.changedTouches[0].screenX;
2816            this.reportHandler({
2817              action_type: "touch_start",
2818              interaction_type: "swipe",
2819              slide_index: this.currentIndex
2820            });
2821            this.stopAutoPlay();
2822          },
2823          { passive: true }
2824        );
2825        this.slidesContainer.addEventListener(
2826          "touchend",
2827          (e) => {
2828            this.touchEndX = e.changedTouches[0].screenX;
2829            this.handleSwipe();
2830            if (!this.isHovered) {
2831              this.startAutoPlay();
2832            }
2833          },
2834          { passive: true }
2835        );
2836        this.slides.forEach((slide, index) => {
2837          const link = slide.querySelector(".nss-banner__link");
2838          if (link) {
2839            link.addEventListener("click", (e) => {
2840              e.preventDefault();
2841              const slideData = this.getSlideData(index);
2842              this.reportHandler({
2843                action_type: "slide_click",
2844                slide_index: index,
2845                slide_data: slideData
2846              });
2847              if (this.config.onItemClick) {
2848                this.config.onItemClick(slideData, index);
2849              }
2850            });
2851          }
2852        });
2853        this.container.setAttribute("tabindex", "0");
2854      }
2855      updateActiveDot() {
2856        this.dots.forEach((dot, index) => {
2857          if (index === this.currentIndex) {
2858            dot.style.background = "#ffffff";
2859          } else {
2860            dot.style.background = "";
2861          }
2862        });
2863      }
2864      handleSwipe() {
2865        const swipeThreshold = 50;
2866        const diff = this.touchStartX - this.touchEndX;
2867        if (Math.abs(diff) > swipeThreshold) {
2868          if (diff > 0) {
2869            this.reportHandler({
2870              action_type: "swipe_navigation",
2871              interaction_type: "swipe_left",
2872              slide_index: this.currentIndex
2873            });
2874            this.goToNextSlide();
2875          } else {
2876            this.reportHandler({
2877              action_type: "swipe_navigation",
2878              interaction_type: "swipe_right",
2879              slide_index: this.currentIndex
2880            });
2881            this.goToPrevSlide();
2882          }
2883        }
2884      }
2885      goToSlide(index) {
2886        if (index === this.currentIndex || index < 0 || index >= this.slides.length) {
2887          return;
2888        }
2889        this.slides[this.currentIndex].classList.remove("nss-banner__slide--active");
2890        if (this.dots[this.currentIndex]) {
2891          this.dots[this.currentIndex].classList.remove("nss-banner__dot--active");
2892        }
2893        this.currentIndex = index;
2894        this.slides[this.currentIndex].classList.add("nss-banner__slide--active");
2895        if (this.dots[this.currentIndex]) {
2896          this.dots[this.currentIndex].classList.add("nss-banner__dot--active");
2897        }
2898        const translateX = -this.currentIndex * 100;
2899        this.slidesContainer.style.transform = `translateX(${translateX}%)`;
2900        this.updateActiveDot();
2901        if (this.config.onSlideChange) {
2902          this.config.onSlideChange(this.currentIndex);
2903        }
2904      }
2905      goToNextSlide() {
2906        const nextIndex = (this.currentIndex + 1) % this.slides.length;
2907        this.goToSlide(nextIndex);
2908      }
2909      goToPrevSlide() {
2910        const prevIndex = (this.currentIndex - 1 + this.slides.length) % this.slides.length;
2911        this.goToSlide(prevIndex);
2912      }
2913      startAutoPlay() {
2914        if (!this.config.autoPlay || this.slides.length <= 1 || this.isHovered) {
2915          return;
2916        }
2917        this.stopAutoPlay();
2918        this.autoPlayTimer = window.setTimeout(() => {
2919          this.goToNextSlide();
2920          this.startAutoPlay();
2921        }, this.config.autoPlayInterval);
2922      }
2923      stopAutoPlay() {
2924        if (this.autoPlayTimer) {
2925          clearTimeout(this.autoPlayTimer);
2926          this.autoPlayTimer = null;
2927        }
2928      }
2929      getSlideData(index) {
2930        const slide = this.slides[index];
2931        const image = slide.querySelector(".nss-banner__image");
2932        const link = slide.querySelector(".nss-banner__link");
2933        const bannerId = slide.dataset.bannerId ? parseInt(slide.dataset.bannerId) : void 0;
2934        return {
2935          banner_id: bannerId,
2936          image: (image == null ? void 0 : image.src) || "",
2937          link: (link == null ? void 0 : link.href) || ""
2938        };
2939      }
2940      // Public methods
2941      getCurrentIndex() {
2942        return this.currentIndex;
2943      }
2944      getTotalSlides() {
2945        return this.slides.length;
2946      }
2947      pause() {
2948        this.reportHandler({
2949          action_type: "auto_play_pause",
2950          auto_play_action: "manual_pause"
2951        });
2952        this.stopAutoPlay();
2953        this.isHovered = true;
2954      }
2955      resume() {
2956        this.reportHandler({
2957          action_type: "auto_play_resume",
2958          auto_play_action: "manual_resume"
2959        });
2960        this.isHovered = false;
2961        this.startAutoPlay();
2962      }
2963      destroy() {
2964        this.stopAutoPlay();
2965      }
2966    }
2967    const initBanner = (selector = ".nss-banner", config = {}) => {
2968      const banners = document.querySelectorAll(selector);
2969      banners.forEach((banner) => {
2970        const element = banner;
2971        new Banner(element, config);
2972      });
2973    };
2974    var BannerType = /* @__PURE__ */ ((BannerType2) => {
2975      BannerType2[BannerType2["Main"] = 1] = "Main";
2976      BannerType2[BannerType2["Footer"] = 2] = "Footer";
2977      BannerType2[BannerType2["App"] = 3] = "App";
2978      return BannerType2;
2979    })(BannerType || {});
2980    const convertTimestampToComparableTime = (timezone, timestamp) => {
2981      var _a, _b, _c, _d, _e, _f;
2982      const date = timestamp ? new Date(timestamp * 1e3) : /* @__PURE__ */ new Date();
2983      const formatter = new Intl.DateTimeFormat("en-US", {
2984        timeZone: timezone,
2985        year: "numeric",
2986        month: "2-digit",
2987        day: "2-digit",
2988        hour: "2-digit",
2989        minute: "2-digit",
2990        second: "2-digit",
2991        hour12: false
2992      });
2993      const parts = formatter.formatToParts(date);
2994      const year = ((_a = parts.find((p) => p.type === "year")) == null ? void 0 : _a.value) || "0";
2995      const month = ((_b = parts.find((p) => p.type === "month")) == null ? void 0 : _b.value) || "0";
2996      const day = ((_c = parts.find((p) => p.type === "day")) == null ? void 0 : _c.value) || "0";
2997      const hour = ((_d = parts.find((p) => p.type === "hour")) == null ? void 0 : _d.value) || "0";
2998      const minute = ((_e = parts.find((p) => p.type === "minute")) == null ? void 0 : _e.value) || "0";
2999      const second = ((_f = parts.find((p) => p.type === "second")) == null ? void 0 : _f.value) || "0";
3000      return parseInt(`${year}${month}${day}${hour}${minute}${second}`);
3001    };
3002    const getCurrentBannerData = (configData, bannerType, region, isPreviewPage = false) => {
3003      var _a, _b, _c;
3004      if (!configData) {
3005        return null;
3006      }
3007      const defaultBanner = bannerType === 1 /* Main */ && (configData == null ? void 0 : configData.default_banner) ? { item_list: [configData.default_banner] } : null;
3008      let bannerData = defaultBanner;
3009      if (!isPreviewPage && ((_b = (_a = configData == null ? void 0 : configData.banner) == null ? void 0 : _a.banner_plan) == null ? void 0 : _b.length)) {
3010        const currentTimezone = timezoneMap[region];
3011        const currentTime = convertTimestampToComparableTime(currentTimezone);
3012        const currentBanner = configData.banner.banner_plan.find(
3013          (item) => item.banner_type === bannerType && item.effective_start_time && item.effective_end_time && currentTime >= convertTimestampToComparableTime(currentTimezone, item.effective_start_time) && currentTime <= convertTimestampToComparableTime(currentTimezone, item.effective_end_time)
3014        );
3015        if (currentBanner) {
3016          bannerData = __spreadProps$1(__spreadValues$1({}, currentBanner), {
3017            item_list: (_c = currentBanner.item_list) != null ? _c : []
3018          });
3019        }
3020      }
3021      return "basic" in configData && bannerData ? __spreadValues$1(__spreadValues$1({}, bannerData), configData.basic) : bannerData;
3022    };
3023
3024    var __defProp = Object.defineProperty;
3025    var __defProps = Object.defineProperties;
3026    var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
3027    var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3028    var __hasOwnProp = Object.prototype.hasOwnProperty;
3029    var __propIsEnum = Object.prototype.propertyIsEnumerable;
3030    var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3031    var __spreadValues = (a, b) => {
3032      for (var prop in b || (b = {}))
3033        if (__hasOwnProp.call(b, prop))
3034          __defNormalProp(a, prop, b[prop]);
3035      if (__getOwnPropSymbols)
3036        for (var prop of __getOwnPropSymbols(b)) {
3037          if (__propIsEnum.call(b, prop))
3038            __defNormalProp(a, prop, b[prop]);
3039        }
3040      return a;
3041    };
3042    var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
3043    const mergeMenuInFooter = (menu) => {
3044      const menuList = createMenuList(menu);
3045      const [itemsWithSubMenu, itemsWithoutSubMenu] = menuList.reduce(
3046        ([withSub, withoutSub], item) => {
3047          if (item.value.sub_menu && item.value.sub_menu.length > 0) {
3048            withSub.push(item);
3049          } else {
3050            withoutSub.push(item);
3051          }
3052          return [withSub, withoutSub];
3053        },
3054        [[], []]
3055      );
3056      const shouldMerge = itemsWithoutSubMenu.length >= 2;
3057      if (shouldMerge) {
3058        itemsWithSubMenu.push({
3059          key: "others",
3060          value: {
3061            main_menu: [{ name: "others", link_url: "" }],
3062            sub_menu: itemsWithoutSubMenu.map((item) => {
3063              var _a;
3064              return (_a = item.value.main_menu) == null ? void 0 : _a[0];
3065            }).filter(Boolean)
3066          }
3067        });
3068      }
3069      return shouldMerge ? itemsWithSubMenu : menuList;
3070    };
3071    const convertFooterData = (config, options) => {
3072      var _a;
3073      const menuConfig = (_a = config == null ? void 0 : config.menu) == null ? void 0 : _a.download_app;
3074      return __spreadProps(__spreadValues(__spreadValues({}, (config == null ? void 0 : config.footer) || {}), options), {
3075        download_app: menuConfig,
3076        show_download_app_tip: !!((menuConfig == null ? void 0 : menuConfig.deep_link) || (menuConfig == null ? void 0 : menuConfig.apple_store_link) || (menuConfig == null ? void 0 : menuConfig.google_store_link)),
3077        menu_list: mergeMenuInFooter(config.menu)
3078      });
3079    };
3080
3081    const isBrowser$1 = typeof window !== "undefined" && typeof navigator !== "undefined";
3082    const getUserAgent = (userAgent) => {
3083      if (isBrowser$1 && navigator.userAgent) {
3084        return navigator.userAgent.toLowerCase();
3085      }
3086      if (typeof globalThis !== "undefined") {
3087        const globalUA = globalThis.__USER_AGENT__ || globalThis.userAgent;
3088        if (globalUA) {
3089          return globalUA.toLowerCase();
3090        }
3091      }
3092      return "";
3093    };
3094    const isMobile = (userAgent) => {
3095      const ua = getUserAgent();
3096      if (!ua) {
3097        return false;
3098      }
3099      const mobilePatterns = [
3100        // Standard mobile devices
3101        /android/i,
3102        /iphone/i,
3103        /ipad/i,
3104        /ipod/i,
3105        /blackberry/i,
3106        /iemobile/i,
3107        /opera mini/i,
3108        // Additional mobile patterns
3109        /mobile/i,
3110        /phone/i,
3111        /mobi/i,
3112        /nokia/i,
3113        /samsung/i,
3114        /htc/i,
3115        /lg/i,
3116        /motorola/i,
3117        /sony/i,
3118        /xiaomi/i,
3119        /huawei/i,
3120        /oppo/i,
3121        /vivo/i,
3122        /oneplus/i,
3123        // Tablets (some consider tablets as mobile)
3124        /tablet/i,
3125        /kindle/i,
3126        /silk/i,
3127        /playbook/i,
3128        /bb10/i,
3129        // Mobile browsers
3130        /crios/i,
3131        // Chrome iOS
3132        /fxios/i,
3133        // Firefox iOS
3134        /ucbrowser/i,
3135        // UC Browser
3136        /samsungbrowser/i
3137        // Samsung Browser
3138      ];
3139      return mobilePatterns.some((pattern) => pattern.test(ua));
3140    };
3141
3142    const ALL_LANG_URL_PREFIX = [
3143      "en",
3144      "th",
3145      "vi",
3146      "ms",
3147      "id",
3148      "br",
3149      "fil",
3150      "zh-Hans",
3151      "zh-Hant"
3152    ];
3153    const getUrlPathWithoutLang = (url) => {
3154      let tempUrl = url;
3155      let hostname = void 0;
3156      if (tempUrl.startsWith("https") || tempUrl.startsWith("http")) {
3157        const urlObj = new URL(tempUrl);
3158        tempUrl = urlObj.pathname;
3159        hostname = urlObj.hostname;
3160      }
3161      const pathParts = tempUrl.split("/");
3162      if (ALL_LANG_URL_PREFIX.includes(pathParts[1])) {
3163        let pathWithoutLang = pathParts.slice(2).join("/");
3164        return [`/${pathWithoutLang}`, hostname];
3165      }
3166      return [tempUrl, hostname];
3167    };
3168    const judgeUrlPathEqual = (urlFromConfig, urlFromPage, curHostname) => {
3169      const [pathFromConfig, hostnameFromConfig] = getUrlPathWithoutLang(urlFromConfig);
3170      const currentHostname = curHostname || window.location.hostname;
3171      if (hostnameFromConfig && currentHostname && hostnameFromConfig !== currentHostname) {
3172        return false;
3173      }
3174      const [pathFromPage] = getUrlPathWithoutLang(urlFromPage);
3175      return pathFromConfig === pathFromPage;
3176    };
3177    const envs = ["test.", "uat.", "staging.", ""];
3178    const suffixes = ["vn", "co.th", "co.id", "sg", "com.br", "com.my", "ph"];
3179    const NSS_WEBSITE_URLS = (() => {
3180      const whitelist = [];
3181      const domain = "spx";
3182      for (const env of envs) {
3183        for (const suffix of suffixes) {
3184          whitelist.push(`https://${env}${domain}.${suffix}`);
3185          whitelist.push(`http://${env}${domain}.${suffix}`);
3186        }
3187      }
3188      return whitelist;
3189    })();
3190    const ctlDomain = "citylinkexpress-ecomm.com";
3191    const CTL_WEBSITE_URLS = envs.flatMap((env) => [
3192      `https://www.${env}${ctlDomain}`,
3193      `http://www.${env}${ctlDomain}`,
3194      `https://${env}${ctlDomain}`,
3195      `http://${env}${ctlDomain}`
3196    ]);
3197    const PARTNER_CONFIGS = {
3198      shopee: {
3199        adminUrlPrefix: "spx-admin",
3200        websiteUrls: NSS_WEBSITE_URLS
3201      },
3202      ctl: {
3203        adminUrlPrefix: "ctl-admin",
3204        websiteUrls: CTL_WEBSITE_URLS
3205      }
3206    };
3207    class PartnerUrlManager {
3208      constructor(partner = "shopee") {
3209        this.goToMyPortal = () => {
3210          window.location.href = isMobile() ? this.urlMap[`/${this.adminUrlPrefix}`] : `/${this.adminUrlPrefix}`;
3211        };
3212        /**
3213         * Handle URL navigation with partner-specific website URLs
3214         */
3215        this.handleUrlNavigation = (url) => {
3216          if (!url || typeof url !== "string") return;
3217          if (url.endsWith(".pdf")) {
3218            window.open(url, "_blank");
3219            return;
3220          }
3221          if (!(url.startsWith("https://") || url.startsWith("http://"))) {
3222            window.location.href = url;
3223            return;
3224          }
3225          const isCurrentWebsiteUrl = this.currentWebsiteUrls.some(
3226            (prefix) => url.startsWith(prefix)
3227          );
3228          if (isCurrentWebsiteUrl) {
3229            window.location.href = url;
3230          } else {
3231            window.open(url, "_blank");
3232          }
3233        };
3234        this.defaultUrlHandler = (url) => {
3235          if (url.targetAttr === "_blank") {
3236            window.open(
3237              url.href,
3238              "_blank",
3239              url.relAttr ? `rel=${url.relAttr}` : void 0
3240            );
3241          } else {
3242            setTimeout(() => {
3243              this.handleUrlNavigation(url.href);
3244            }, 150);
3245          }
3246        };
3247        this.isNeedLoginUrl = (url) => {
3248          if (!this.needLoginPaths.includes(url.pathname)) {
3249            return false;
3250          }
3251          const isCurrentWebsiteUrl = this.currentWebsiteUrls.some((prefix) => url.href.startsWith(prefix));
3252          return isCurrentWebsiteUrl;
3253        };
3254        this.proxyLinkClick = (e, urlHandler) => {
3255          return proxyLinkClick$1(e, urlHandler, this.urlMap, this.defaultUrlHandler);
3256        };
3257        this.partner = partner;
3258        this.partnerConfig = PARTNER_CONFIGS[partner];
3259        this.adminUrlPrefix = this.partnerConfig.adminUrlPrefix;
3260        this.currentWebsiteUrls = this.partnerConfig.websiteUrls;
3261        this.commonAdminUrls = PartnerUrlManager.generateAdminUrls(this.adminUrlPrefix);
3262        this.needLoginPaths = PartnerUrlManager.generateLoginPaths(this.commonAdminUrls);
3263        this.urlMap = PartnerUrlManager.generateUrlMapping(this.adminUrlPrefix, this.commonAdminUrls);
3264      }
3265      /**
3266       * Create a new instance with a different partner
3267       * Since fields are readonly, we return a new instance instead of mutating
3268       */
3269      withPartner(partner) {
3270        return new PartnerUrlManager(partner);
3271      }
3272      static isPartnerSupported(partner) {
3273        return partner in PARTNER_CONFIGS;
3274      }
3275      static getSupportedPartners() {
3276        return Object.keys(PARTNER_CONFIGS);
3277      }
3278      /**
3279       * Static helper methods to generate data without instance dependencies
3280       * These can be used independently and make dependencies explicit
3281       */
3282      static generateAdminUrls(adminUrlPrefix) {
3283        return {
3284          singleCreateOrder: `/${adminUrlPrefix}/single-order/create`,
3285          massCreateOrder: `/${adminUrlPrefix}/mass-order/create`
3286        };
3287      }
3288      static generateLoginPaths(commonAdminUrls) {
3289        return [
3290          commonAdminUrls.singleCreateOrder,
3291          commonAdminUrls.massCreateOrder,
3292          "/m/order/creation"
3293        ];
3294      }
3295      static generateUrlMapping(adminUrlPrefix, commonAdminUrls) {
3296        return {
3297          [commonAdminUrls.singleCreateOrder]: "/m/order/creation",
3298          [`/${adminUrlPrefix}`]: "/m/portal",
3299          [`/${adminUrlPrefix}
3299/easypack/create`]: "/m/easy-pack-help/h5",
3300          [`/${adminUrlPrefix}/account/profile`]: "/m/my-profile",
3301          [`/${adminUrlPrefix}/my-shop`]: "/m/my-shop-list",
3302          [`/${adminUrlPrefix}/notification`]: "/m/notification/list",
3303          [`/${adminUrlPrefix}/finance/payment-settings`]: "/m/bank/list",
3304          [`/${adminUrlPrefix}/finance/my-seller-balance`]: "/m/finance/my-seller-balance",
3305          [`/${adminUrlPrefix}/kyc-authentication`]: "/m/kyc",
3306          [`/${adminUrlPrefix}/order/trackings`]: "/m/order/tracking",
3307          [`/${adminUrlPrefix}/account/default-order-options`]: "/m/order/default",
3308          [`/${adminUrlPrefix}/account/pickup-address`]: "/m/address-book",
3309          [`/${adminUrlPrefix}/account/my-referral`]: "/m/referral",
3310          [`/${adminUrlPrefix}/account/profile/e-contract`]: "/m/e-contract/detail",
3311          "/esf-tool": "/m/shipping-rate",
3312          "/claiming-introduction": "/m/lead/claiming",
3313          "/easypack/create": "/m/easy-pack-help/h5",
3314          "/one-time-order/creation": "/m/one-time-order/creation",
3315          "/track": "/m/track",
3316          "/cookies-preference": "/m/cookie",
3317          "/interest-form": "/m/interest",
3318          "/cod-interest-form": "/m/cod-interest",
3319          "/how-to-ship-introduction": "/m/lead/how-to-ship",
3320          "/pickup-introduction": "/m/lead/pickup",
3321          "/drop-off-introduction": "/m/lead/drop-off",
3322          "/cod-introduction": "/m/lead/cod",
3323          "/insurance-service-introduction": "/m/lead/insurance",
3324          "/customer-service-introduction": "/m/lead/contact",
3325          "/introduction/news-center": "/m/lead/news-center",
3326          "/introduction/promotion-news": "/m/lead/promotion-news",
3327          "/tuyendung": "/m/tuyendung",
3328          "/dangky-dichvu-vanchuyen": "/m/dangky-dichvu-vanchuyen",
3329          "/dichvu-thuhang": "/m/dichvu-thuhang",
3330          "/support": "/m/support",
3331          "/ROS-COD-Policy": "/m/ROS-COD-Policy",
3332          "/link": "/m/link",
3333          "/login-exception": "/m/login-exception",
3334          "/account-interceptor": "/m/account-interceptor",
3335          "/webform/feedback": "/m/webform/feedback"
3336        };
3337      }
3338    }
3339    function matchSupportCenterFaqUrl(pathname) {
3340      const supportCenterFaqRegex = /^\/support-center\/faq(?:\/category\/([^\/]+)(?:\/article\/([^\/]+))?)?$/;
3341      const match = pathname.match(supportCenterFaqRegex);
3342      if (match) {
3343        const [, categoryId, articleId] = match;
3344        if (categoryId && articleId) {
3345          return `/m/help-center/detail?aid=${articleId}&cid=${categoryId}`;
3346        } else {
3347          return "/m/help-center";
3348        }
3349      }
3350      return null;
3351    }
3352    function proxyLinkClick$1(e, urlHandler, urlMap = {}, defaultUrlHandler = () => {
3353    }) {
3354      const target = e.target;
3355      const linkElement = target.closest("a");
3356      if (!linkElement || !linkElement.hasAttribute("href")) {
3357        return;
3358      }
3359      let linkUrl = linkElement.getAttribute("href");
3360      if (!linkUrl) {
3361        return;
3362      }
3363      let tempLinkUrl = linkUrl.startsWith("/") ? new URL(`${location.origin}${linkUrl}`) : new URL(linkUrl);
3364      if (isMobile()) {
3365        const supportCenterMobileUrl = matchSupportCenterFaqUrl(tempLinkUrl.pathname);
3366        if (supportCenterMobileUrl) {
3367          linkUrl = `${tempLinkUrl.origin}${supportCenterMobileUrl}${tempLinkUrl.search}${tempLinkUrl.hash}`;
3368          tempLinkUrl = new URL(linkUrl);
3369        } else {
3370          const mobileUrl = urlMap[tempLinkUrl.pathname];
3371          if (mobileUrl) {
3372            linkUrl = `${tempLinkUrl.origin}${mobileUrl}${tempLinkUrl.search}${tempLinkUrl.hash}`;
3373            tempLinkUrl = new URL(linkUrl);
3374          }
3375        }
3376      }
3377      e.preventDefault();
3378      const targetAttr = linkElement.getAttribute("target");
3379      const relAttr = linkElement.getAttribute("rel");
3380      const urlParams = {
3381        href: tempLinkUrl.href,
3382        origin: tempLinkUrl.origin,
3383        pathname: tempLinkUrl.pathname,
3384        search: tempLinkUrl.search,
3385        hash: tempLinkUrl.hash,
3386        host: tempLinkUrl.host,
3387        hostname: tempLinkUrl.hostname,
3388        port: tempLinkUrl.port,
3389        protocol: tempLinkUrl.protocol,
3390        targetAttr,
3391        relAttr
3392      };
3393      if (urlHandler) {
3394        urlHandler(urlParams, defaultUrlHandler);
3395        return;
3396      }
3397      defaultUrlHandler(urlParams);
3398    }
3399
3400    const hideLinkInMenu = (link, hideSignal) => {
3401      if (hideSignal !== void 0 && !hideSignal) return;
3402      if (isMobile()) {
3403        const linkCreateBtn2 = document.querySelectorAll(
3404          `.main-menu__mobile-list a[href*="${link}"]`
3405        );
3406        linkCreateBtn2 == null ? void 0 : linkCreateBtn2.forEach((item) => {
3407          var _a;
3408          (_a = item.closest(".main-menu__mobile-item")) == null ? void 0 : _a.remove();
3409        });
3410        return;
3411      }
3412      const linkCreateBtn = document.querySelectorAll(
3413        `.main-menu__list a[href*="${link}"]`
3414      );
3415      linkCreateBtn == null ? void 0 : linkCreateBtn.forEach((item) => {
3416        var _a;
3417        (_a = item.closest(".dropdown__item")) == null ? void 0 : _a.remove();
3418      });
3419    };
3420    const hideLinkInFooter = (link, hideSignal) => {
3421      if (hideSignal !== void 0 && !hideSignal) return;
3422      const linkFooterLinks = document.querySelectorAll(
3423        `.footer__menu-container .footer__menu-link[href*="${link}"]`
3424      );
3425      linkFooterLinks == null ? void 0 : linkFooterLinks.forEach((item) => {
3426        item.remove();
3427      });
3428    };
3429    const hideLinkInMenuAndFooter = ({
3430      checkCount = 20,
3431      checkInterval = 200,
3432      link,
3433      isAsync = false,
3434      getHideSignal
3435    }) => {
3436      const inMobile = isMobile();
3437      if (!isAsync) {
3438        hideLinkInMenu(link);
3439        !inMobile && hideLinkInFooter(link);
3440        return;
3441      }
3442      let timer = null;
3443      let count = 0;
3444      const loop = () => {
3445        var _a;
3446        let hideSignal = false;
3447        try {
3448          hideSignal = (_a = getHideSignal == null ? void 0 : getHideSignal()) != null ? _a : false;
3449        } catch (error) {
3450          console.error("hideLinkInMenuAndFooter getHideSignal error: ", error);
3451        }
3452        if (count >= checkCount || hideSignal) {
3453          timer && clearTimeout(timer);
3454          hideLinkInMenu(link, hideSignal);
3455          !inMobile && hideLinkInFooter(link, hideSignal);
3456          return;
3457        }
3458        count++;
3459        timer = setTimeout(loop, checkInterval);
3460      };
3461      loop();
3462    };
3463    const hideEasyPack = (easyPackSuffix = "/easypack/create") => {
3464      hideLinkInMenuAndFooter({
3465        link: easyPackSuffix,
3466        isAsync: false
3467      });
3468    };
3469    const hideMassCreateInMobile = (massCreateSuffix = "/mass-order/create") => {
3470      if (isMobile()) {
3471        hideLinkInMenuAndFooter({
3472          link: massCreateSuffix,
3473          isAsync: false
3474        });
3475      }
3476    };
3477
3478    const getAccountLanguage = (language) => {
3479      switch (language) {
3480        case "br":
3481        // tsp
3482        case "pt-br":
3483          return "pt-BR";
3484        case "tw":
3485        case "zh-Hant":
3486          return "zh-Hant";
3487        case "zh-Hans":
3488          return "zh-Hans";
3489        case "fil":
3490        // tsp
3491        case "ph":
3492          return "fil";
3493        case "ms":
3494        // tsp
3495        case "ms-my":
3496          return "ms";
3497        case "id":
3498          return "id";
3499        case "th":
3500          return "th";
3501        case "vi":
3502          return "vi";
3503        default:
3504          return "en";
3505      }
3506    };
3507
3508    function formatExpireTime(times) {
3509        if (!times)
3510            return;
3511        if (String(times).length === 13)
3512            return times;
3513        if (String(times).length === 10) {
3514            return times * 1000;
3515        }
3516        return new Date(Date.now() + times).getTime();
3517    }
3518    var getKey = function (key) {
3519        return "spx-open-mobile-".concat(getRegion(), "-").concat(key);
3520    };
3521    var parseData = function (serializedData, expireCb) {
3522        var result = null;
3523        if (serializedData !== null) {
3524            try {
3525                var data = JSON.parse(serializedData);
3526                // 过期
3527                if (data.expireTime && data.expireTime < Date.now()) {
3528                    expireCb === null || expireCb === void 0 ? void 0 : expireCb();
3529                    result = null;
3530                }
3531                else {
3532                    result = data.value;
3533                }
3534            }
3535            catch (error) {
3536                console.error(error);
3537            }
3538        }
3539        return result;
3540    };
3541    var storage = {
3542        // 项目名 + 当前市场 + 用户ID + 缓存key
3543        getKey: getKey,
3544        parseData: function (dataKey, serializedData) {
3545            return parseData(serializedData, function () {
3546                storage.removeItem(dataKey);
3547            });
3548        },
3549        /**
3550         *
3551         * @param key 存储key
3552         * @param value 存储值
3553         * @param times 保存时长,不传则默认永久
3554         */
3555        setItem: function (key, value, times) {
3556            var dataKey = storage.getKey(key);
3557            var data = {
3558                value: value !== null && value !== void 0 ? value : null, // 存储值
3559                expireTime: formatExpireTime(times), // 过期时间
3560            };
3561            var serializedData = JSON.stringify(data);
3562            localStorage.setItem(dataKey, serializedData);
3563        },
3564        asyncGetItem: function (key) { return __awaiter$7(void 0, void 0, void 0, function () {
3565            var dataKey, value;
3566            return __generator$7(this, function (_a) {
3567                dataKey = storage.getKey(key);
3568                value = null;
3569                if (!value) {
3570                    return [2 /*return*/, storage.getItem(key)];
3571                }
3572                return [2 /*return*/, storage.parseData(dataKey, value)];
3573            });
3574        }); },
3575        getItem: function (key) {
3576            var dataKey = storage.getKey(key);
3577            var value = localStorage.getItem(dataKey);
3578            return storage.parseData(dataKey, value);
3579        },
3580        removeItem: function (key) {
3581            var dataKey = storage.getKey(key);
3582            localStorage.removeItem(dataKey);
3583        },
3584        clear: function () {
3585            localStorage.clear();
3586        },
3587    };
3588    // 单独创建这个函数是因为 reload-page 需要用到,它要单独打包成一个文件
3589    // 减少对 storage 这种对象的依赖可以显著减少代ç 
3589çš„体积
3590    var getStorageItem = function (key) {
3591        var dataKey = getKey(key);
3592        var value = localStorage.getItem(dataKey);
3593        return parseData(value);
3594    };
3595    var getCacheLanguage = function () {
3596        // follow old mobile web logic
3597        var isMobileWeb = isMobile();
3598        if (isMobileWeb) {
3599            return getStorageItem(LANGUAGE_MOBILE_CACHE_KEY);
3600        }
3601        return localStorage.getItem(LANGUAGE_CACHE_KEY);
3602    };
3603    var setCacheLanguage = function (language) {
3604        // follow old mobile web logic
3605        storage.setItem(LANGUAGE_MOBILE_CACHE_KEY, language);
3606        localStorage.setItem(LANGUAGE_CACHE_KEY, language);
3607    };
3608
3609    /*
3610     * 系统是否显示 tsp 的 key
3611     */
3612    var SYSTEM_SHOW_TSP_KEY = 'SYSTEM_SHOW_TSP_KEY';
3613    var IS_DYNAMIC_RENDER_KEY = 'is_dynamic_render';
3614
3615    /** @description: copy form spx-open-pc */
3616    // 转换规则定义
3617    var transRule = {
3618        newline: '\n',
3619        backslash: '\''
3620    };
3621    // 自定义一些转换规则,变量名用$开头的
3622    var customTrans = function (str) {
3623        var reg = /{\$([\w]+)?}/g;
3624        return str.replace(reg, function (_, r) {
3625            var rule = transRule[r];
3626            if (typeof rule === 'function') {
3627                return rule(r, _);
3628            }
3629            if (typeof rule === 'string') {
3630                return rule;
3631            }
3632            return r;
3633        });
3634    };
3635    // 原生的$gt
3636    var _$gt = index_umdExports.generateTransifyCommon({
3637        t: function (key, options) {
3638            var val = instance.t(key, options) || '';
3639            return val;
3640        },
3641        project: ['spxopen'],
3642        isShowKey: isRunIngInNodeEnv ? false : storage.getItem(SYSTEM_SHOW_TSP_KEY),
3643        needWarning: false,
3644    });
3645    /**
3646     * 因为目前翻译工具是在运行时执行
3647     * js运行时的字符串中可能会有转义字符,例如:\n会被解析为换行,而git中读取到的是未被转义的字符串,从而导致md5加密的结果不一致
3648     * 为了解决这个问题,这里用自定义的规则newline在最后结果返回的时候做了一层转换
3649     */
3650    var $gt = function (s) {
3651        var args = [];
3652        for (var _i = 1; _i < arguments.length; _i++) {
3653            args[_i - 1] = arguments[_i];
3654        }
3655        var transVal = customTrans(_$gt.apply(void 0, __spreadArray$2([s], args, false)));
3656        return transVal;
3657    };
3658
3659    var utmParamsSearch = '';
3660    /**
3661     * 拼上utm参数
3662     * @param url
3663     * @returns
3664     */
3665    var getUrlWithUtmParams = function (url) {
3666        try {
3667            if (!utmParamsSearch)
3668                return url;
3669            return appendSearchParameter(url, utmParamsSearch).toString();
3670        }
3671        catch (_a) {
3672            return url;
3673        }
3674    };
3675    var PlatformType;
3676    (function (PlatformType) {
3677        PlatformType[PlatformType["Browser"] = 0] = "Browser";
3678        PlatformType[PlatformType["Native"] = 1] = "Native";
3679    })(PlatformType || (PlatformType = {}));
3680    /** webview 环境下的 navigator.userAgent 中有此标识,可以以此判断是否是 webview 环境 */
3681    var WEBVIEW_TAG = 'spx-express';
3682    /**
3683     * 获取当前页面运行在哪个环境(IOSWebview, AndroidWebview, Browser)
3684     * @returns PlatformType
3685     */
3686    var getPlatformType = function () {
3687        var userAgent = navigator.userAgent.toLowerCase() || '';
3688        // 判断是否是 webview 环境 (本地可以通过 sessionStorage 设置来模拟 webview 环境)
3689        if (userAgent.includes(WEBVIEW_TAG) || sessionStorage.getItem(WEBVIEW_TAG)) {
3690            return PlatformType.Native;
3691        }
3692        return PlatformType.Browser;
3693    };
3694    var shouldOpenMobileLink = function (url) {
3695        return getPlatformType() !== PlatformType.Browser && typeof url === 'string' && url.endsWith('pdf');
3696    };
3697    function getOrigin() {
3698        return window.location.origin;
3699    }
3700    /**
3701     * 重写window.open方法
3702     */
3703    var originalOpenFn = window.open;
3704    function openWindow(url, target, features) {
3705        if (shouldOpenMobileLink(url)) {
3706            return originalOpenFn("".concat(getOrigin(), "/m/pdf-viewer?file_url=").concat(getUrlWithUtmParams(url)), target, features);
3707        }
3708        return originalOpenFn(getUrlWithUtmParams(url), target, features);
3709    }
3710    /**
3711     * 拼search
3712     * @param url
3713     * @param parameter
3714     * @returns
3715     */
3716    function appendSearchParameter(url, parameter) {
3717        var urlObject = new URL(url, location.href);
3718        if (urlObject.search) {
3719            urlObject.search += "&".concat(parameter);
3720        }
3721        else {
3722            urlObject.search = "?".concat(parameter);
3723        }
3724        return urlObject;
3725    }
3726    /**
3727     * resolve route to string
3728     * @param route
3729     * @returns
3730     */
3731    function resolveRoutePath(route) {
3732        var path = route.pathname;
3733        if (route.search) {
3734            path += "".concat(route.search);
3735        }
3736        if (route.hash) {
3737            path += "".concat(route.hash);
3738        }
3739        return path;
3740    }
3741    /**
3742     * 保存UTM参数,并带着跳转
3743     */
3744    var utmPatch = function () {
3745        try {
3746            // patch history
3747            var searchParams_1 = new URLSearchParams(location.search);
3748            utmParamsSearch = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'fbclid'].map(function (item) { return "".concat(item, "=").concat(searchParams_1.get(item) || ''); }).join('&');
3749            [['pushState', history.pushState], ['replaceState', history.replaceState]].forEach(function (item) {
3750                var name = item[0], func = item[1];
3751                history[name] = function (state, title, url) {
3752                    var newURL = url;
3753                    try {
3754                        if (typeof url === 'string') {
3755                            newURL = resolveRoutePath(appendSearchParameter(url, utmParamsSearch));
3756                        }
3757                        else if (url && typeof url === 'object') {
3758                            newURL = (appendSearchParameter(url === null || url === void 0 ? void 0 : url.toString(), utmParamsSearch)).toString();
3759                        }
3760                    }
3761                    catch (error) {
3762                        console.error(error);
3763                    }
3764                    func.call(history, state, title, newURL);
3765                };
3766            });
3767            // patch window.open
3768            window.open = openWindow;
3769            // patch a 标签
3770            document.addEventListener('click', function (event) {
3771                var target = event.target;
3772                if ((target === null || target === void 0 ? void 0 : target.tagName) === 'A') {
3773                    var aNode = target;
3774                    if (shouldOpenMobileLink(aNode.href)) {
3775                        aNode.href = "".concat(getOrigin(), "/m/pdf-viewer?file_url=").concat(aNode.href);
3776                    }
3777                    if (aNode.target === '_blank') {
3778                        event.preventDefault(); // 阻止默认的跳转行为
3779                        window.open(aNode.href, aNode.target); // èµ°window.open
3780                    }
3781                    else if (['', '_self'].includes(aNode.target)) {
3782                        if (location.href !== getUrlWithUtmParams(aNode.href)) {
3783                            // 原生的a标签会进这里,LINK 类型的在click事件之前已经跳转,location.href 和 aNode.href 会一致
3784                            event.preventDefault(); // 阻止默认的跳转行为
3785                            location.href = getUrlWithUtmParams(aNode.href);
3786                        }
3787                    }
3788                }
3789            });
3790        }
3791        catch (error) {
3792            console.error(error);
3793        }
3794    };
3795
3796    var browser = {};
3797
3798    var canPromise;
3799    var hasRequiredCanPromise;
3800
3801    function requireCanPromise () {
3802    	if (hasRequiredCanPromise) return canPromise;
3803    	hasRequiredCanPromise = 1;
3804    	// can-promise has a crash in some versions of react native that dont have
3805    	// standard global objects
3806    	// https://github.com/soldair/node-qrcode/issues/157
3807
3808    	canPromise = function () {
3809    	  return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then
3810    	};
3811    	return canPromise;
3812    }
3813
3814    var qrcode = {};
3815
3816    var utils$1 = {};
3817
3818    var hasRequiredUtils$1;
3819
3820    function requireUtils$1 () {
3821    	if (hasRequiredUtils$1) return utils$1;
3822    	hasRequiredUtils$1 = 1;
3823    	let toSJISFunction;
3824    	const CODEWORDS_COUNT = [
3825    	  0, // Not used
3826    	  26, 44, 70, 100, 134, 172, 196, 242, 292, 346,
3827    	  404, 466, 532, 581, 655, 733, 815, 901, 991, 1085,
3828    	  1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185,
3829    	  2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706
3830    	];
3831
3832    	/**
3833    	 * Returns the QR Code size for the specified version
3834    	 *
3835    	 * @param  {Number} version QR Code version
3836    	 * @return {Number}         size of QR code
3837    	 */
3838    	utils$1.getSymbolSize = function getSymbolSize (version) {
3839    	  if (!version) throw new Error('"version" cannot be null or undefined')
3840    	  if (version < 1 || version > 40) throw new Error('"version" should be in range from 1 to 40')
3841    	  return version * 4 + 17
3842    	};
3843
3844    	/**
3845    	 * Returns the total number of codewords used to store data and EC information.
3846    	 *
3847    	 * @param  {Number} version QR Code version
3848    	 * @return {Number}         Data length in bits
3849    	 */
3850    	utils$1.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) {
vendor: 6,268 bytes, lines 3851-4095
3851    	  return CODEWORDS_COUNT[version]
3852    	};
3853
3854    	/**
3855    	 * Encode data with Bose-Chaudhuri-Hocquenghem
3856    	 *
3857    	 * @param  {Number} data Value to encode
3858    	 * @return {Number}      Encoded value
3859    	 */
3860    	utils$1.getBCHDigit = function (data) {
3861    	  let digit = 0;
3862
3863    	  while (data !== 0) {
3864    	    digit++;
3865    	    data >>>= 1;
3866    	  }
3867
3868    	  return digit
3869    	};
3870
3871    	utils$1.setToSJISFunction = function setToSJISFunction (f) {
3872    	  if (typeof f !== 'function') {
3873    	    throw new Error('"toSJISFunc" is not a valid function.')
3874    	  }
3875
3876    	  toSJISFunction = f;
3877    	};
3878
3879    	utils$1.isKanjiModeEnabled = function () {
3880    	  return typeof toSJISFunction !== 'undefined'
3881    	};
3882
3883    	utils$1.toSJIS = function toSJIS (kanji) {
3884    	  return toSJISFunction(kanji)
3885    	};
3886    	return utils$1;
3887    }
3888
3889    var errorCorrectionLevel = {};
3890
3891    var hasRequiredErrorCorrectionLevel;
3892
3893    function requireErrorCorrectionLevel () {
3894    	if (hasRequiredErrorCorrectionLevel) return errorCorrectionLevel;
3895    	hasRequiredErrorCorrectionLevel = 1;
3896    	(function (exports) {
3897    		exports.L = { bit: 1 };
3898    		exports.M = { bit: 0 };
3899    		exports.Q = { bit: 3 };
3900    		exports.H = { bit: 2 };
3901
3902    		function fromString (string) {
3903    		  if (typeof string !== 'string') {
3904    		    throw new Error('Param is not a string')
3905    		  }
3906
3907    		  const lcStr = string.toLowerCase();
3908
3909    		  switch (lcStr) {
3910    		    case 'l':
3911    		    case 'low':
3912    		      return exports.L
3913
3914    		    case 'm':
3915    		    case 'medium':
3916    		      return exports.M
3917
3918    		    case 'q':
3919    		    case 'quartile':
3920    		      return exports.Q
3921
3922    		    case 'h':
3923    		    case 'high':
3924    		      return exports.H
3925
3926    		    default:
3927    		      throw new Error('Unknown EC Level: ' + string)
3928    		  }
3929    		}
3930
3931    		exports.isValid = function isValid (level) {
3932    		  return level && typeof level.bit !== 'undefined' &&
3933    		    level.bit >= 0 && level.bit < 4
3934    		};
3935
3936    		exports.from = function from (value, defaultValue) {
3937    		  if (exports.isValid(value)) {
3938    		    return value
3939    		  }
3940
3941    		  try {
3942    		    return fromString(value)
3943    		  } catch (e) {
3944    		    return defaultValue
3945    		  }
3946    		}; 
3947    	} (errorCorrectionLevel));
3948    	return errorCorrectionLevel;
3949    }
3950
3951    var bitBuffer;
3952    var hasRequiredBitBuffer;
3953
3954    function requireBitBuffer () {
3955    	if (hasRequiredBitBuffer) return bitBuffer;
3956    	hasRequiredBitBuffer = 1;
3957    	function BitBuffer () {
3958    	  this.buffer = [];
3959    	  this.length = 0;
3960    	}
3961
3962    	BitBuffer.prototype = {
3963
3964    	  get: function (index) {
3965    	    const bufIndex = Math.floor(index / 8);
3966    	    return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1
3967    	  },
3968
3969    	  put: function (num, length) {
3970    	    for (let i = 0; i < length; i++) {
3971    	      this.putBit(((num >>> (length - i - 1)) & 1) === 1);
3972    	    }
3973    	  },
3974
3975    	  getLengthInBits: function () {
3976    	    return this.length
3977    	  },
3978
3979    	  putBit: function (bit) {
3980    	    const bufIndex = Math.floor(this.length / 8);
3981    	    if (this.buffer.length <= bufIndex) {
3982    	      this.buffer.push(0);
3983    	    }
3984
3985    	    if (bit) {
3986    	      this.buffer[bufIndex] |= (0x80 >>> (this.length % 8));
3987    	    }
3988
3989    	    this.length++;
3990    	  }
3991    	};
3992
3993    	bitBuffer = BitBuffer;
3994    	return bitBuffer;
3995    }
3996
3997    /**
3998     * Helper class to handle QR Code symbol modules
3999     *
4000     * @param {Number} size Symbol size
4001     */
4002
4003    var bitMatrix;
4004    var hasRequiredBitMatrix;
4005
4006    function requireBitMatrix () {
4007    	if (hasRequiredBitMatrix) return bitMatrix;
4008    	hasRequiredBitMatrix = 1;
4009    	function BitMatrix (size) {
4010    	  if (!size || size < 1) {
4011    	    throw new Error('BitMatrix size must be defined and greater than 0')
4012    	  }
4013
4014    	  this.size = size;
4015    	  this.data = new Uint8Array(size * size);
4016    	  this.reservedBit = new Uint8Array(size * size);
4017    	}
4018
4019    	/**
4020    	 * Set bit value at specified location
4021    	 * If reserved flag is set, this bit will be ignored during masking process
4022    	 *
4023    	 * @param {Number}  row
4024    	 * @param {Number}  col
4025    	 * @param {Boolean} value
4026    	 * @param {Boolean} reserved
4027    	 */
4028    	BitMatrix.prototype.set = function (row, col, value, reserved) {
4029    	  const index = row * this.size + col;
4030    	  this.data[index] = value;
4031    	  if (reserved) this.reservedBit[index] = true;
4032    	};
4033
4034    	/**
4035    	 * Returns bit value at specified location
4036    	 *
4037    	 * @param  {Number}  row
4038    	 * @param  {Number}  col
4039    	 * @return {Boolean}
4040    	 */
4041    	BitMatrix.prototype.get = function (row, col) {
4042    	  return this.data[row * this.size + col]
4043    	};
4044
4045    	/**
4046    	 * Applies xor operator at specified location
4047    	 * (used during masking process)
4048    	 *
4049    	 * @param {Number}  row
4050    	 * @param {Number}  col
4051    	 * @param {Boolean} value
4052    	 */
4053    	BitMatrix.prototype.xor = function (row, col, value) {
4054    	  this.data[row * this.size + col] ^= value;
4055    	};
4056
4057    	/**
4058    	 * Check if bit at specified location is reserved
4059    	 *
4060    	 * @param {Number}   row
4061    	 * @param {Number}   col
4062    	 * @return {Boolean}
4063    	 */
4064    	BitMatrix.prototype.isReserved = function (row, col) {
4065    	  return this.reservedBit[row * this.size + col]
4066    	};
4067
4068    	bitMatrix = BitMatrix;
4069    	return bitMatrix;
4070    }
4071
4072    var alignmentPattern = {};
4073
4074    /**
4075     * Alignment pattern are fixed reference pattern in defined positions
4076     * in a matrix symbology, which enables the decode software to re-synchronise
4077     * the coordinate mapping of the image modules in the event of moderate amounts
4078     * of distortion of the image.
4079     *
4080     * Alignment patterns are present only in QR Code symbols of version 2 or larger
4081     * and their number depends on the symbol version.
4082     */
4083
4084    var hasRequiredAlignmentPattern;
4085
4086    function requireAlignmentPattern () {
4087    	if (hasRequiredAlignmentPattern) return alignmentPattern;
4088    	hasRequiredAlignmentPattern = 1;
4089    	(function (exports) {
4090    		const getSymbolSize = requireUtils$1().getSymbolSize;
4091
4092    		/**
4093    		 * Calculate the row/column coordinates of the center module of each alignment pattern
4094    		 * for the specified QR Code version.
4095    		 *
4096    		 * The alignment patterns are positioned symmetrically on either side of the diagonal
4097    		 * running from the top left corner of the symbol to the bottom right corner.
4098    		 *
4099    		 * Since positions are simmetrical only half of the coordinates are returned.
4100    		 * Each item of the array will represent in turn the x and y coordinate.
4101    		 * @see {@link getPositions}
4102    		 *
4103    		 * @param  {Number} version QR Code version
4104    		 * @return {Array}          Array of coordinate
4105    		 */
4106    		exports.getRowColCoords = function getRowColCoords (version) {
4107    		  if (version === 1) return []
4108
4109    		  const posCount = Math.floor(version / 7) + 2;
4110    		  const size = getSymbolSize(version);
4111    		  const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2;
4112    		  const positions = [size - 7]; // Last coord is always (size - 7)
4113
4114    		  for (let i = 1; i < posCount - 1; i++) {
4115    		    positions[i] = positions[i - 1] - intervals;
4116    		  }
4117
4118    		  positions.push(6); // First coord is always 6
4119
4120    		  return positions.reverse()
4121    		};
4122
4123    		/**
4124    		 * Returns an array containing the positions of each alignment pattern.
4125    		 * Each array's element represent the center point of the pattern as (x, y) coordinates
4126    		 *
4127    		 * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}
4128    		 * and filtering out the items that overlaps with finder pattern
4129    		 *
4130    		 * @example
4131    		 * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.
4132    		 * The alignment patterns, therefore, are to be centered on (row, column)
4133    		 * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).
4134    		 * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns
4135    		 * and are not therefore used for alignment patterns.
4136    		 *
4137    		 * let pos = getPositions(7)
4138    		 * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]
4139    		 *
4140    		 * @param  {Number} version QR Code version
4141    		 * @return {Array}          Array of coordinates
4142    		 */
4143    		exports.getPositions = function getPositions (version) {
4144    		  const coords = [];
4145    		  const pos = exports.getRowColCoords(version);
4146    		  const posLength = pos.length;
4147
4148    		  for (let i = 0; i < posLength; i++) {
4149    		    for (let j = 0; j < posLength; j++) {
4150    		      // Skip if position is occupied by finder patterns
4151    		      if ((i === 0 && j === 0) || // top-left
4152    		          (i === 0 && j === posLength - 1) || // bottom-left
4153    		          (i === posLength - 1 && j === 0)) { // top-right
4154    		        continue
4155    		      }
4156
4157    		      coords.push([pos[i], pos[j]]);
4158    		    }
4159    		  }
4160
4161    		  return coords
4162    		}; 
4163    	} (alignmentPattern));
4164    	return alignmentPattern;
4165    }
4166
4167    var finderPattern = {};
4168
4169    var hasRequiredFinderPattern;
4170
4171    function requireFinderPattern () {
4172    	if (hasRequiredFinderPattern) return finderPattern;
4173    	hasRequiredFinderPattern = 1;
4174    	const getSymbolSize = requireUtils$1().getSymbolSize;
4175    	const FINDER_PATTERN_SIZE = 7;
4176
4177    	/**
4178    	 * Returns an array containing the positions of each finder pattern.
4179    	 * Each array's element represent the top-left point of the pattern as (x, y) coordinates
4180    	 *
4181    	 * @param  {Number} version QR Code version
4182    	 * @return {Array}          Array of coordinates
4183    	 */
4184    	finderPattern.getPositions = function getPositions (version) {
4185    	  const size = getSymbolSize(version);
4186
4187    	  return [
4188    	    // top-left
4189    	    [0, 0],
4190    	    // top-right
4191    	    [size - FINDER_PATTERN_SIZE, 0],
4192    	    // bottom-left
4193    	    [0, size - FINDER_PATTERN_SIZE]
4194    	  ]
4195    	};
4196    	return finderPattern;
4197    }
4198
4199    var maskPattern = {};
4200
4201    /**
4202     * Data mask pattern reference
4203     * @type {Object}
4204     */
4205
4206    var hasRequiredMaskPattern;
4207
4208    function requireMaskPattern () {
4209    	if (hasRequiredMaskPattern) return maskPattern;
4210    	hasRequiredMaskPattern = 1;
4211    	(function (exports) {
4212    		exports.Patterns = {
4213    		  PATTERN000: 0,
4214    		  PATTERN001: 1,
4215    		  PATTERN010: 2,
4216    		  PATTERN011: 3,
4217    		  PATTERN100: 4,
4218    		  PATTERN101: 5,
4219    		  PATTERN110: 6,
4220    		  PATTERN111: 7
4221    		};
4222
4223    		/**
4224    		 * Weighted penalty scores for the undesirable features
4225    		 * @type {Object}
4226    		 */
4227    		const PenaltyScores = {
4228    		  N1: 3,
4229    		  N2: 3,
4230    		  N3: 40,
4231    		  N4: 10
4232    		};
4233
4234    		/**
4235    		 * Check if mask pattern value is valid
4236    		 *
4237    		 * @param  {Number}  mask    Mask pattern
4238    		 * @return {Boolean}         true if valid, false otherwise
4239    		 */
4240    		exports.isValid = function isValid (mask) {
4241    		  return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7
4242    		};
4243
4244    		/**
4245    		 * Returns mask pattern from a value.
vendor: 4,909 bytes, lines 4246-4387
4246    		 * If value is not valid, returns undefined
4247    		 *
4248    		 * @param  {Number|String} value        Mask pattern value
4249    		 * @return {Number}                     Valid mask pattern or undefined
4250    		 */
4251    		exports.from = function from (value) {
4252    		  return exports.isValid(value) ? parseInt(value, 10) : undefined
4253    		};
4254
4255    		/**
4256    		* Find adjacent modules in row/column with the same color
4257    		* and assign a penalty value.
4258    		*
4259    		* Points: N1 + i
4260    		* i is the amount by which the number of adjacent modules of the same color exceeds 5
4261    		*/
4262    		exports.getPenaltyN1 = function getPenaltyN1 (data) {
4263    		  const size = data.size;
4264    		  let points = 0;
4265    		  let sameCountCol = 0;
4266    		  let sameCountRow = 0;
4267    		  let lastCol = null;
4268    		  let lastRow = null;
4269
4270    		  for (let row = 0; row < size; row++) {
4271    		    sameCountCol = sameCountRow = 0;
4272    		    lastCol = lastRow = null;
4273
4274    		    for (let col = 0; col < size; col++) {
4275    		      let module = data.get(row, col);
4276    		      if (module === lastCol) {
4277    		        sameCountCol++;
4278    		      } else {
4279    		        if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
4280    		        lastCol = module;
4281    		        sameCountCol = 1;
4282    		      }
4283
4284    		      module = data.get(col, row);
4285    		      if (module === lastRow) {
4286    		        sameCountRow++;
4287    		      } else {
4288    		        if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
4289    		        lastRow = module;
4290    		        sameCountRow = 1;
4291    		      }
4292    		    }
4293
4294    		    if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
4295    		    if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
4296    		  }
4297
4298    		  return points
4299    		};
4300
4301    		/**
4302    		 * Find 2x2 blocks with the same color and assign a penalty value
4303    		 *
4304    		 * Points: N2 * (m - 1) * (n - 1)
4305    		 */
4306    		exports.getPenaltyN2 = function getPenaltyN2 (data) {
4307    		  const size = data.size;
4308    		  let points = 0;
4309
4310    		  for (let row = 0; row < size - 1; row++) {
4311    		    for (let col = 0; col < size - 1; col++) {
4312    		      const last = data.get(row, col) +
4313    		        data.get(row, col + 1) +
4314    		        data.get(row + 1, col) +
4315    		        data.get(row + 1, col + 1);
4316
4317    		      if (last === 4 || last === 0) points++;
4318    		    }
4319    		  }
4320
4321    		  return points * PenaltyScores.N2
4322    		};
4323
4324    		/**
4325    		 * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column,
4326    		 * preceded or followed by light area 4 modules wide
4327    		 *
4328    		 * Points: N3 * number of pattern found
4329    		 */
4330    		exports.getPenaltyN3 = function getPenaltyN3 (data) {
4331    		  const size = data.size;
4332    		  let points = 0;
4333    		  let bitsCol = 0;
4334    		  let bitsRow = 0;
4335
4336    		  for (let row = 0; row < size; row++) {
4337    		    bitsCol = bitsRow = 0;
4338    		    for (let col = 0; col < size; col++) {
4339    		      bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col);
4340    		      if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++;
4341
4342    		      bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row);
4343    		      if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++;
4344    		    }
4345    		  }
4346
4347    		  return points * PenaltyScores.N3
4348    		};
4349
4350    		/**
4351    		 * Calculate proportion of dark modules in entire symbol
4352    		 *
4353    		 * Points: N4 * k
4354    		 *
4355    		 * k is the rating of the deviation of the proportion of dark modules
4356    		 * in the symbol from 50% in steps of 5%
4357    		 */
4358    		exports.getPenaltyN4 = function getPenaltyN4 (data) {
4359    		  let darkCount = 0;
4360    		  const modulesCount = data.data.length;
4361
4362    		  for (let i = 0; i < modulesCount; i++) darkCount += data.data[i];
4363
4364    		  const k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10);
4365
4366    		  return k * PenaltyScores.N4
4367    		};
4368
4369    		/**
4370    		 * Return mask value at given position
4371    		 *
4372    		 * @param  {Number} maskPattern Pattern reference value
4373    		 * @param  {Number} i           Row
4374    		 * @param  {Number} j           Column
4375    		 * @return {Boolean}            Mask value
4376    		 */
4377    		function getMaskAt (maskPattern, i, j) {
4378    		  switch (maskPattern) {
4379    		    case exports.Patterns.PATTERN000: return (i + j) % 2 === 0
4380    		    case exports.Patterns.PATTERN001: return i % 2 === 0
4381    		    case exports.Patterns.PATTERN010: return j % 3 === 0
4382    		    case exports.Patterns.PATTERN011: return (i + j) % 3 === 0
4383    		    case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0
4384    		    case exports.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0
4385    		    case exports.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0
4386    		    case exports.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0
4387
vendor: 21,005 bytes, lines 4388-5084
4388    		    default: throw new Error('bad maskPattern:' + maskPattern)
4389    		  }
4390    		}
4391
4392    		/**
4393    		 * Apply a mask pattern to a BitMatrix
4394    		 *
4395    		 * @param  {Number}    pattern Pattern reference number
4396    		 * @param  {BitMatrix} data    BitMatrix data
4397    		 */
4398    		exports.applyMask = function applyMask (pattern, data) {
4399    		  const size = data.size;
4400
4401    		  for (let col = 0; col < size; col++) {
4402    		    for (let row = 0; row < size; row++) {
4403    		      if (data.isReserved(row, col)) continue
4404    		      data.xor(row, col, getMaskAt(pattern, row, col));
4405    		    }
4406    		  }
4407    		};
4408
4409    		/**
4410    		 * Returns the best mask pattern for data
4411    		 *
4412    		 * @param  {BitMatrix} data
4413    		 * @return {Number} Mask pattern reference number
4414    		 */
4415    		exports.getBestMask = function getBestMask (data, setupFormatFunc) {
4416    		  const numPatterns = Object.keys(exports.Patterns).length;
4417    		  let bestPattern = 0;
4418    		  let lowerPenalty = Infinity;
4419
4420    		  for (let p = 0; p < numPatterns; p++) {
4421    		    setupFormatFunc(p);
4422    		    exports.applyMask(p, data);
4423
4424    		    // Calculate penalty
4425    		    const penalty =
4426    		      exports.getPenaltyN1(data) +
4427    		      exports.getPenaltyN2(data) +
4428    		      exports.getPenaltyN3(data) +
4429    		      exports.getPenaltyN4(data);
4430
4431    		    // Undo previously applied mask
4432    		    exports.applyMask(p, data);
4433
4434    		    if (penalty < lowerPenalty) {
4435    		      lowerPenalty = penalty;
4436    		      bestPattern = p;
4437    		    }
4438    		  }
4439
4440    		  return bestPattern
4441    		}; 
4442    	} (maskPattern));
4443    	return maskPattern;
4444    }
4445
4446    var errorCorrectionCode = {};
4447
4448    var hasRequiredErrorCorrectionCode;
4449
4450    function requireErrorCorrectionCode () {
4451    	if (hasRequiredErrorCorrectionCode) return errorCorrectionCode;
4452    	hasRequiredErrorCorrectionCode = 1;
4453    	const ECLevel = requireErrorCorrectionLevel();
4454
4455    	const EC_BLOCKS_TABLE = [
4456    	// L  M  Q  H
4457    	  1, 1, 1, 1,
4458    	  1, 1, 1, 1,
4459    	  1, 1, 2, 2,
4460    	  1, 2, 2, 4,
4461    	  1, 2, 4, 4,
4462    	  2, 4, 4, 4,
4463    	  2, 4, 6, 5,
4464    	  2, 4, 6, 6,
4465    	  2, 5, 8, 8,
4466    	  4, 5, 8, 8,
4467    	  4, 5, 8, 11,
4468    	  4, 8, 10, 11,
4469    	  4, 9, 12, 16,
4470    	  4, 9, 16, 16,
4471    	  6, 10, 12, 18,
4472    	  6, 10, 17, 16,
4473    	  6, 11, 16, 19,
4474    	  6, 13, 18, 21,
4475    	  7, 14, 21, 25,
4476    	  8, 16, 20, 25,
4477    	  8, 17, 23, 25,
4478    	  9, 17, 23, 34,
4479    	  9, 18, 25, 30,
4480    	  10, 20, 27, 32,
4481    	  12, 21, 29, 35,
4482    	  12, 23, 34, 37,
4483    	  12, 25, 34, 40,
4484    	  13, 26, 35, 42,
4485    	  14, 28, 38, 45,
4486    	  15, 29, 40, 48,
4487    	  16, 31, 43, 51,
4488    	  17, 33, 45, 54,
4489    	  18, 35, 48, 57,
4490    	  19, 37, 51, 60,
4491    	  19, 38, 53, 63,
4492    	  20, 40, 56, 66,
4493    	  21, 43, 59, 70,
4494    	  22, 45, 62, 74,
4495    	  24, 47, 65, 77,
4496    	  25, 49, 68, 81
4497    	];
4498
4499    	const EC_CODEWORDS_TABLE = [
4500    	// L  M  Q  H
4501    	  7, 10, 13, 17,
4502    	  10, 16, 22, 28,
4503    	  15, 26, 36, 44,
4504    	  20, 36, 52, 64,
4505    	  26, 48, 72, 88,
4506    	  36, 64, 96, 112,
4507    	  40, 72, 108, 130,
4508    	  48, 88, 132, 156,
4509    	  60, 110, 160, 192,
4510    	  72, 130, 192, 224,
4511    	  80, 150, 224, 264,
4512    	  96, 176, 260, 308,
4513    	  104, 198, 288, 352,
4514    	  120, 216, 320, 384,
4515    	  132, 240, 360, 432,
4516    	  144, 280, 408, 480,
4517    	  168, 308, 448, 532,
4518    	  180, 338, 504, 588,
4519    	  196, 364, 546, 650,
4520    	  224, 416, 600, 700,
4521    	  224, 442, 644, 750,
4522    	  252, 476, 690, 816,
4523    	  270, 504, 750, 900,
4524    	  300, 560, 810, 960,
4525    	  312, 588, 870, 1050,
4526    	  336, 644, 952, 1110,
4527    	  360, 700, 1020, 1200,
4528    	  390, 728, 1050, 1260,
4529    	  420, 784, 1140, 1350,
4530    	  450, 812, 1200, 1440,
4531    	  480, 868, 1290, 1530,
4532    	  510, 924, 1350, 1620,
4533    	  540, 980, 1440, 1710,
4534    	  570, 1036, 1530, 1800,
4535    	  570, 1064, 1590, 1890,
4536    	  600, 1120, 1680, 1980,
4537    	  630, 1204, 1770, 2100,
4538    	  660, 1260, 1860, 2220,
4539    	  720, 1316, 1950, 2310,
4540    	  750, 1372, 2040, 2430
4541    	];
4542
4543    	/**
4544    	 * Returns the number of error correction block that the QR Code should contain
4545    	 * for the specified version and error correction level.
4546    	 *
4547    	 * @param  {Number} version              QR Code version
4548    	 * @param  {Number} errorCorrectionLevel Error correction level
4549    	 * @return {Number}                      Number of error correction blocks
4550    	 */
4551    	errorCorrectionCode.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) {
4552    	  switch (errorCorrectionLevel) {
4553    	    case ECLevel.L:
4554    	      return EC_BLOCKS_TABLE[(version - 1) * 4 + 0]
4555    	    case ECLevel.M:
4556    	      return EC_BLOCKS_TABLE[(version - 1) * 4 + 1]
4557    	    case ECLevel.Q:
4558    	      return EC_BLOCKS_TABLE[(version - 1) * 4 + 2]
4559    	    case ECLevel.H:
4560    	      return EC_BLOCKS_TABLE[(version - 1) * 4 + 3]
4561    	    default:
4562    	      return undefined
4563    	  }
4564    	};
4565
4566    	/**
4567    	 * Returns the number of error correction codewords to use for the specified
4568    	 * version and error correction level.
4569    	 *
4570    	 * @param  {Number} version              QR Code version
4571    	 * @param  {Number} errorCorrectionLevel Error correction level
4572    	 * @return {Number}                      Number of error correction codewords
4573    	 */
4574    	errorCorrectionCode.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) {
4575    	  switch (errorCorrectionLevel) {
4576    	    case ECLevel.L:
4577    	      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0]
4578    	    case ECLevel.M:
4579    	      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1]
4580    	    case ECLevel.Q:
4581    	      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2]
4582    	    case ECLevel.H:
4583    	      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3]
4584    	    default:
4585    	      return undefined
4586    	  }
4587    	};
4588    	return errorCorrectionCode;
4589    }
4590
4591    var polynomial = {};
4592
4593    var galoisField = {};
4594
4595    var hasRequiredGaloisField;
4596
4597    function requireGaloisField () {
4598    	if (hasRequiredGaloisField) return galoisField;
4599    	hasRequiredGaloisField = 1;
4600    	const EXP_TABLE = new Uint8Array(512);
4601    	const LOG_TABLE = new Uint8Array(256)
4602    	/**
4603    	 * Precompute the log and anti-log tables for faster computation later
4604    	 *
4605    	 * For each possible value in the galois field 2^8, we will pre-compute
4606    	 * the logarithm and anti-logarithm (exponential) of this value
4607    	 *
4608    	 * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields}
4609    	 */
4610    	;(function initTables () {
4611    	  let x = 1;
4612    	  for (let i = 0; i < 255; i++) {
4613    	    EXP_TABLE[i] = x;
4614    	    LOG_TABLE[x] = i;
4615
4616    	    x <<= 1; // multiply by 2
4617
4618    	    // The QR code specification says to use byte-wise modulo 100011101 arithmetic.
4619    	    // This means that when a number is 256 or larger, it should be XORed with 0x11D.
4620    	    if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256)
4621    	      x ^= 0x11D;
4622    	    }
4623    	  }
4624
4625    	  // Optimization: double the size of the anti-log table so that we don't need to mod 255 to
4626    	  // stay inside the bounds (because we will mainly use this table for the multiplication of
4627    	  // two GF numbers, no more).
4628    	  // @see {@link mul}
4629    	  for (let i = 255; i < 512; i++) {
4630    	    EXP_TABLE[i] = EXP_TABLE[i - 255];
4631    	  }
4632    	}());
4633
4634    	/**
4635    	 * Returns log value of n inside Galois Field
4636    	 *
4637    	 * @param  {Number} n
4638    	 * @return {Number}
4639    	 */
4640    	galoisField.log = function log (n) {
4641    	  if (n < 1) throw new Error('log(' + n + ')')
4642    	  return LOG_TABLE[n]
4643    	};
4644
4645    	/**
4646    	 * Returns anti-log value of n inside Galois Field
4647    	 *
4648    	 * @param  {Number} n
4649    	 * @return {Number}
4650    	 */
4651    	galoisField.exp = function exp (n) {
4652    	  return EXP_TABLE[n]
4653    	};
4654
4655    	/**
4656    	 * Multiplies two number inside Galois Field
4657    	 *
4658    	 * @param  {Number} x
4659    	 * @param  {Number} y
4660    	 * @return {Number}
4661    	 */
4662    	galoisField.mul = function mul (x, y) {
4663    	  if (x === 0 || y === 0) return 0
4664
4665    	  // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized
4666    	  // @see {@link initTables}
4667    	  return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]]
4668    	};
4669    	return galoisField;
4670    }
4671
4672    var hasRequiredPolynomial;
4673
4674    function requirePolynomial () {
4675    	if (hasRequiredPolynomial) return polynomial;
4676    	hasRequiredPolynomial = 1;
4677    	(function (exports) {
4678    		const GF = requireGaloisField();
4679
4680    		/**
4681    		 * Multiplies two polynomials inside Galois Field
4682    		 *
4683    		 * @param  {Uint8Array} p1 Polynomial
4684    		 * @param  {Uint8Array} p2 Polynomial
4685    		 * @return {Uint8Array}    Product of p1 and p2
4686    		 */
4687    		exports.mul = function mul (p1, p2) {
4688    		  const coeff = new Uint8Array(p1.length + p2.length - 1);
4689
4690    		  for (let i = 0; i < p1.length; i++) {
4691    		    for (let j = 0; j < p2.length; j++) {
4692    		      coeff[i + j] ^= GF.mul(p1[i], p2[j]);
4693    		    }
4694    		  }
4695
4696    		  return coeff
4697    		};
4698
4699    		/**
4700    		 * Calculate the remainder of polynomials division
4701    		 *
4702    		 * @param  {Uint8Array} divident Polynomial
4703    		 * @param  {Uint8Array} divisor  Polynomial
4704    		 * @return {Uint8Array}          Remainder
4705    		 */
4706    		exports.mod = function mod (divident, divisor) {
4707    		  let result = new Uint8Array(divident);
4708
4709    		  while ((result.length - divisor.length) >= 0) {
4710    		    const coeff = result[0];
4711
4712    		    for (let i = 0; i < divisor.length; i++) {
4713    		      result[i] ^= GF.mul(divisor[i], coeff);
4714    		    }
4715
4716    		    // remove all zeros from buffer head
4717    		    let offset = 0;
4718    		    while (offset < result.length && result[offset] === 0) offset++;
4719    		    result = result.slice(offset);
4720    		  }
4721
4722    		  return result
4723    		};
4724
4725    		/**
4726    		 * Generate an irreducible generator polynomial of specified degree
4727    		 * (used by Reed-Solomon encoder)
4728    		 *
4729    		 * @param  {Number} degree Degree of the generator polynomial
4730    		 * @return {Uint8Array}    Buffer containing polynomial coefficients
4731    		 */
4732    		exports.generateECPolynomial = function generateECPolynomial (degree) {
4733    		  let poly = new Uint8Array([1]);
4734    		  for (let i = 0; i < degree; i++) {
4735    		    poly = exports.mul(poly, new Uint8Array([1, GF.exp(i)]));
4736    		  }
4737
4738    		  return poly
4739    		}; 
4740    	} (polynomial));
4741    	return polynomial;
4742    }
4743
4744    var reedSolomonEncoder;
4745    var hasRequiredReedSolomonEncoder;
4746
4747    function requireReedSolomonEncoder () {
4748    	if (hasRequiredReedSolomonEncoder) return reedSolomonEncoder;
4749    	hasRequiredReedSolomonEncoder = 1;
4750    	const Polynomial = requirePolynomial();
4751
4752    	function ReedSolomonEncoder (degree) {
4753    	  this.genPoly = undefined;
4754    	  this.degree = degree;
4755
4756    	  if (this.degree) this.initialize(this.degree);
4757    	}
4758
4759    	/**
4760    	 * Initialize the encoder.
4761    	 * The input param should correspond to the number of error correction codewords.
4762    	 *
4763    	 * @param  {Number} degree
4764    	 */
4765    	ReedSolomonEncoder.prototype.initialize = function initialize (degree) {
4766    	  // create an irreducible generator polynomial
4767    	  this.degree = degree;
4768    	  this.genPoly = Polynomial.generateECPolynomial(this.degree);
4769    	};
4770
4771    	/**
4772    	 * Encodes a chunk of data
4773    	 *
4774    	 * @param  {Uint8Array} data Buffer containing input data
4775    	 * @return {Uint8Array}      Buffer containing encoded data
4776    	 */
4777    	ReedSolomonEncoder.prototype.encode = function encode (data) {
4778    	  if (!this.genPoly) {
4779    	    throw new Error('Encoder not initialized')
4780    	  }
4781
4782    	  // Calculate EC for this data block
4783    	  // extends data size to data+genPoly size
4784    	  const paddedData = new Uint8Array(data.length + this.degree);
4785    	  paddedData.set(data);
4786
4787    	  // The error correction codewords are the remainder after dividing the data codewords
4788    	  // by a generator polynomial
4789    	  const remainder = Polynomial.mod(paddedData, this.genPoly);
4790
4791    	  // return EC data blocks (last n byte, where n is the degree of genPoly)
4792    	  // If coefficients number in remainder are less than genPoly degree,
4793    	  // pad with 0s to the left to reach the needed number of coefficients
4794    	  const start = this.degree - remainder.length;
4795    	  if (start > 0) {
4796    	    const buff = new Uint8Array(this.degree);
4797    	    buff.set(remainder, start);
4798
4799    	    return buff
4800    	  }
4801
4802    	  return remainder
4803    	};
4804
4805    	reedSolomonEncoder = ReedSolomonEncoder;
4806    	return reedSolomonEncoder;
4807    }
4808
4809    var version = {};
4810
4811    var mode = {};
4812
4813    var versionCheck = {};
4814
4815    /**
4816     * Check if QR Code version is valid
4817     *
4818     * @param  {Number}  version QR Code version
4819     * @return {Boolean}         true if valid version, false otherwise
4820     */
4821
4822    var hasRequiredVersionCheck;
4823
4824    function requireVersionCheck () {
4825    	if (hasRequiredVersionCheck) return versionCheck;
4826    	hasRequiredVersionCheck = 1;
4827    	versionCheck.isValid = function isValid (version) {
4828    	  return !isNaN(version) && version >= 1 && version <= 40
4829    	};
4830    	return versionCheck;
4831    }
4832
4833    var regex = {};
4834
4835    var hasRequiredRegex;
4836
4837    function requireRegex () {
4838    	if (hasRequiredRegex) return regex;
4839    	hasRequiredRegex = 1;
4840    	const numeric = '[0-9]+';
4841    	const alphanumeric = '[A-Z $%*+\\-./:]+';
4842    	let kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' +
4843    	  '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' +
4844    	  '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' +
4845    	  '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+';
4846    	kanji = kanji.replace(/u/g, '\\u');
4847
4848    	const byte = '(?:(?![A-Z0-9 $%*+\\-./:]|' + kanji + ')(?:.|[\r\n]))+';
4849
4850    	regex.KANJI = new RegExp(kanji, 'g');
4851    	regex.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\-./:]+', 'g');
4852    	regex.BYTE = new RegExp(byte, 'g');
4853    	regex.NUMERIC = new RegExp(numeric, 'g');
4854    	regex.ALPHANUMERIC = new RegExp(alphanumeric, 'g');
4855
4856    	const TEST_KANJI = new RegExp('^' + kanji + '$');
4857    	const TEST_NUMERIC = new RegExp('^' + numeric + '$');
4858    	const TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\-./:]+$');
4859
4860    	regex.testKanji = function testKanji (str) {
4861    	  return TEST_KANJI.test(str)
4862    	};
4863
4864    	regex.testNumeric = function testNumeric (str) {
4865    	  return TEST_NUMERIC.test(str)
4866    	};
4867
4868    	regex.testAlphanumeric = function testAlphanumeric (str) {
4869    	  return TEST_ALPHANUMERIC.test(str)
4870    	};
4871    	return regex;
4872    }
4873
4874    var hasRequiredMode;
4875
4876    function requireMode () {
4877    	if (hasRequiredMode) return mode;
4878    	hasRequiredMode = 1;
4879    	(function (exports) {
4880    		const VersionCheck = requireVersionCheck();
4881    		const Regex = requireRegex();
4882
4883    		/**
4884    		 * Numeric mode encodes data from the decimal digit set (0 - 9)
4885    		 * (byte values 30HEX to 39HEX).
4886    		 * Normally, 3 data characters are represented by 10 bits.
4887    		 *
4888    		 * @type {Object}
4889    		 */
4890    		exports.NUMERIC = {
4891    		  id: 'Numeric',
4892    		  bit: 1 << 0,
4893    		  ccBits: [10, 12, 14]
4894    		};
4895
4896    		/**
4897    		 * Alphanumeric mode encodes data from a set of 45 characters,
4898    		 * i.e. 10 numeric digits (0 - 9),
4899    		 *      26 alphabetic characters (A - Z),
4900    		 *   and 9 symbols (SP, $, %, *, +, -, ., /, :).
4901    		 * Normally, two input characters are represented by 11 bits.
4902    		 *
4903    		 * @type {Object}
4904    		 */
4905    		exports.ALPHANUMERIC = {
4906    		  id: 'Alphanumeric',
4907    		  bit: 1 << 1,
4908    		  ccBits: [9, 11, 13]
4909    		};
4910
4911    		/**
4912    		 * In byte mode, data is encoded at 8 bits per character.
4913    		 *
4914    		 * @type {Object}
4915    		 */
4916    		exports.BYTE = {
4917    		  id: 'Byte',
4918    		  bit: 1 << 2,
4919    		  ccBits: [8, 16, 16]
4920    		};
4921
4922    		/**
4923    		 * The Kanji mode efficiently encodes Kanji characters in accordance with
4924    		 * the Shift JIS system based on JIS X 0208.
4925    		 * The Shift JIS values are shifted from the JIS X 0208 values.
4926    		 * JIS X 0208 gives details of the shift coded representation.
4927    		 * Each two-byte character value is compacted to a 13-bit binary codeword.
4928    		 *
4929    		 * @type {Object}
4930    		 */
4931    		exports.KANJI = {
4932    		  id: 'Kanji',
4933    		  bit: 1 << 3,
4934    		  ccBits: [8, 10, 12]
4935    		};
4936
4937    		/**
4938    		 * Mixed mode will contain a sequences of data in a combination of any of
4939    		 * the modes described above
4940    		 *
4941    		 * @type {Object}
4942    		 */
4943    		exports.MIXED = {
4944    		  bit: -1
4945    		};
4946
4947    		/**
4948    		 * Returns the number of bits needed to store the data length
4949    		 * according to QR Code specifications.
4950    		 *
4951    		 * @param  {Mode}   mode    Data mode
4952    		 * @param  {Number} version QR Code version
4953    		 * @return {Number}         Number of bits
4954    		 */
4955    		exports.getCharCountIndicator = function getCharCountIndicator (mode, version) {
4956    		  if (!mode.ccBits) throw new Error('Invalid mode: ' + mode)
4957
4958    		  if (!VersionCheck.isValid(version)) {
4959    		    throw new Error('Invalid version: ' + version)
4960    		  }
4961
4962    		  if (version >= 1 && version < 10) return mode.ccBits[0]
4963    		  else if (version < 27) return mode.ccBits[1]
4964    		  return mode.ccBits[2]
4965    		};
4966
4967    		/**
4968    		 * Returns the most efficient mode to store the specified data
4969    		 *
4970    		 * @param  {String} dataStr Input data string
4971    		 * @return {Mode}           Best mode
4972    		 */
4973    		exports.getBestModeForData = function getBestModeForData (dataStr) {
4974    		  if (Regex.testNumeric(dataStr)) return exports.NUMERIC
4975    		  else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC
4976    		  else if (Regex.testKanji(dataStr)) return exports.KANJI
4977    		  else return exports.BYTE
4978    		};
4979
4980    		/**
4981    		 * Return mode name as string
4982    		 *
4983    		 * @param {Mode} mode Mode object
4984    		 * @returns {String}  Mode name
4985    		 */
4986    		exports.toString = function toString (mode) {
4987    		  if (mode && mode.id) return mode.id
4988    		  throw new Error('Invalid mode')
4989    		};
4990
4991    		/**
4992    		 * Check if input param is a valid mode object
4993    		 *
4994    		 * @param   {Mode}    mode Mode object
4995    		 * @returns {Boolean} True if valid mode, false otherwise
4996    		 */
4997    		exports.isValid = function isValid (mode) {
4998    		  return mode && mode.bit && mode.ccBits
4999    		};
5000
5001    		/**
5002    		 * Get mode object from its name
5003    		 *
5004    		 * @param   {String} string Mode name
5005    		 * @returns {Mode}          Mode object
5006    		 */
5007    		function fromString (string) {
5008    		  if (typeof string !== 'string') {
5009    		    throw new Error('Param is not a string')
5010    		  }
5011
5012    		  const lcStr = string.toLowerCase();
5013
5014    		  switch (lcStr) {
5015    		    case 'numeric':
5016    		      return exports.NUMERIC
5017    		    case 'alphanumeric':
5018    		      return exports.ALPHANUMERIC
5019    		    case 'kanji':
5020    		      return exports.KANJI
5021    		    case 'byte':
5022    		      return exports.BYTE
5023    		    default:
5024    		      throw new Error('Unknown mode: ' + string)
5025    		  }
5026    		}
5027
5028    		/**
5029    		 * Returns mode from a value.
5030    		 * If value is not a valid mode, returns defaultValue
5031    		 *
5032    		 * @param  {Mode|String} value        Encoding mode
5033    		 * @param  {Mode}        defaultValue Fallback value
5034    		 * @return {Mode}                     Encoding mode
5035    		 */
5036    		exports.from = function from (value, defaultValue) {
5037    		  if (exports.isValid(value)) {
5038    		    return value
5039    		  }
5040
5041    		  try {
5042    		    return fromString(value)
5043    		  } catch (e) {
5044    		    return defaultValue
5045    		  }
5046    		}; 
5047    	} (mode));
5048    	return mode;
5049    }
5050
5051    var hasRequiredVersion;
5052
5053    function requireVersion () {
5054    	if (hasRequiredVersion) return version;
5055    	hasRequiredVersion = 1;
5056    	(function (exports) {
5057    		const Utils = requireUtils$1();
5058    		const ECCode = requireErrorCorrectionCode();
5059    		const ECLevel = requireErrorCorrectionLevel();
5060    		const Mode = requireMode();
5061    		const VersionCheck = requireVersionCheck();
5062
5063    		// Generator polynomial used to encode version information
5064    		const G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0);
5065    		const G18_BCH = Utils.getBCHDigit(G18);
5066
5067    		function getBestVersionForDataLength (mode, length, errorCorrectionLevel) {
5068    		  for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
5069    		    if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) {
5070    		      return currentVersion
5071    		    }
5072    		  }
5073
5074    		  return undefined
5075    		}
5076
5077    		function getReservedBitsCount (mode, version) {
5078    		  // Character count indicator + mode indicator bits
5079    		  return Mode.getCharCountIndicator(mode, version) + 4
5080    		}
5081
5082    		function getTotalBitsFromDataArray (segments, version) {
5083    		  let totalBits = 0;
5084
vendor: 4,487 bytes, lines 5085-5213
5085    		  segments.forEach(function (data) {
5086    		    const reservedBits = getReservedBitsCount(data.mode, version);
5087    		    totalBits += reservedBits + data.getBitsLength();
5088    		  });
5089
5090    		  return totalBits
5091    		}
5092
5093    		function getBestVersionForMixedData (segments, errorCorrectionLevel) {
5094    		  for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
5095    		    const length = getTotalBitsFromDataArray(segments, currentVersion);
5096    		    if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) {
5097    		      return currentVersion
5098    		    }
5099    		  }
5100
5101    		  return undefined
5102    		}
5103
5104    		/**
5105    		 * Returns version number from a value.
5106    		 * If value is not a valid version, returns defaultValue
5107    		 *
5108    		 * @param  {Number|String} value        QR Code version
5109    		 * @param  {Number}        defaultValue Fallback value
5110    		 * @return {Number}                     QR Code version number
5111    		 */
5112    		exports.from = function from (value, defaultValue) {
5113    		  if (VersionCheck.isValid(value)) {
5114    		    return parseInt(value, 10)
5115    		  }
5116
5117    		  return defaultValue
5118    		};
5119
5120    		/**
5121    		 * Returns how much data can be stored with the specified QR code version
5122    		 * and error correction level
5123    		 *
5124    		 * @param  {Number} version              QR Code version (1-40)
5125    		 * @param  {Number} errorCorrectionLevel Error correction level
5126    		 * @param  {Mode}   mode                 Data mode
5127    		 * @return {Number}                      Quantity of storable data
5128    		 */
5129    		exports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) {
5130    		  if (!VersionCheck.isValid(version)) {
5131    		    throw new Error('Invalid QR Code version')
5132    		  }
5133
5134    		  // Use Byte mode as default
5135    		  if (typeof mode === 'undefined') mode = Mode.BYTE;
5136
5137    		  // Total codewords for this QR code version (Data + Error correction)
5138    		  const totalCodewords = Utils.getSymbolTotalCodewords(version);
5139
5140    		  // Total number of error correction codewords
5141    		  const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
5142
5143    		  // Total number of data codewords
5144    		  const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8;
5145
5146    		  if (mode === Mode.MIXED) return dataTotalCodewordsBits
5147
5148    		  const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version);
5149
5150    		  // Return max number of storable codewords
5151    		  switch (mode) {
5152    		    case Mode.NUMERIC:
5153    		      return Math.floor((usableBits / 10) * 3)
5154
5155    		    case Mode.ALPHANUMERIC:
5156    		      return Math.floor((usableBits / 11) * 2)
5157
5158    		    case Mode.KANJI:
5159    		      return Math.floor(usableBits / 13)
5160
5161    		    case Mode.BYTE:
5162    		    default:
5163    		      return Math.floor(usableBits / 8)
5164    		  }
5165    		};
5166
5167    		/**
5168    		 * Returns the minimum version needed to contain the amount of data
5169    		 *
5170    		 * @param  {Segment} data                    Segment of data
5171    		 * @param  {Number} [errorCorrectionLevel=H] Error correction level
5172    		 * @param  {Mode} mode                       Data mode
5173    		 * @return {Number}                          QR Code version
5174    		 */
5175    		exports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) {
5176    		  let seg;
5177
5178    		  const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M);
5179
5180    		  if (Array.isArray(data)) {
5181    		    if (data.length > 1) {
5182    		      return getBestVersionForMixedData(data, ecl)
5183    		    }
5184
5185    		    if (data.length === 0) {
5186    		      return 1
5187    		    }
5188
5189    		    seg = data[0];
5190    		  } else {
5191    		    seg = data;
5192    		  }
5193
5194    		  return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl)
5195    		};
5196
5197    		/**
5198    		 * Returns version information with relative error correction bits
5199    		 *
5200    		 * The version information is included in QR Code symbols of version 7 or larger.
5201    		 * It consists of an 18-bit sequence containing 6 data bits,
5202    		 * with 12 error correction bits calculated using the (18, 6) Golay code.
5203    		 *
5204    		 * @param  {Number} version QR Code version
5205    		 * @return {Number}         Encoded version info bits
5206    		 */
5207    		exports.getEncodedBits = function getEncodedBits (version) {
5208    		  if (!VersionCheck.isValid(version) || version < 7) {
5209    		    throw new Error('Invalid QR Code version')
5210    		  }
5211
5212    		  let d = version << 12;
5213
vendor: 28,071 bytes, lines 5214-6057
5214    		  while (Utils.getBCHDigit(d) - G18_BCH >= 0) {
5215    		    d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH));
5216    		  }
5217
5218    		  return (version << 12) | d
5219    		}; 
5220    	} (version));
5221    	return version;
5222    }
5223
5224    var formatInfo = {};
5225
5226    var hasRequiredFormatInfo;
5227
5228    function requireFormatInfo () {
5229    	if (hasRequiredFormatInfo) return formatInfo;
5230    	hasRequiredFormatInfo = 1;
5231    	const Utils = requireUtils$1();
5232
5233    	const G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0);
5234    	const G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1);
5235    	const G15_BCH = Utils.getBCHDigit(G15);
5236
5237    	/**
5238    	 * Returns format information with relative error correction bits
5239    	 *
5240    	 * The format information is a 15-bit sequence containing 5 data bits,
5241    	 * with 10 error correction bits calculated using the (15, 5) BCH code.
5242    	 *
5243    	 * @param  {Number} errorCorrectionLevel Error correction level
5244    	 * @param  {Number} mask                 Mask pattern
5245    	 * @return {Number}                      Encoded format information bits
5246    	 */
5247    	formatInfo.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {
5248    	  const data = ((errorCorrectionLevel.bit << 3) | mask);
5249    	  let d = data << 10;
5250
5251    	  while (Utils.getBCHDigit(d) - G15_BCH >= 0) {
5252    	    d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH));
5253    	  }
5254
5255    	  // xor final data with mask pattern in order to ensure that
5256    	  // no combination of Error Correction Level and data mask pattern
5257    	  // will result in an all-zero data string
5258    	  return ((data << 10) | d) ^ G15_MASK
5259    	};
5260    	return formatInfo;
5261    }
5262
5263    var segments = {};
5264
5265    var numericData;
5266    var hasRequiredNumericData;
5267
5268    function requireNumericData () {
5269    	if (hasRequiredNumericData) return numericData;
5270    	hasRequiredNumericData = 1;
5271    	const Mode = requireMode();
5272
5273    	function NumericData (data) {
5274    	  this.mode = Mode.NUMERIC;
5275    	  this.data = data.toString();
5276    	}
5277
5278    	NumericData.getBitsLength = function getBitsLength (length) {
5279    	  return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0)
5280    	};
5281
5282    	NumericData.prototype.getLength = function getLength () {
5283    	  return this.data.length
5284    	};
5285
5286    	NumericData.prototype.getBitsLength = function getBitsLength () {
5287    	  return NumericData.getBitsLength(this.data.length)
5288    	};
5289
5290    	NumericData.prototype.write = function write (bitBuffer) {
5291    	  let i, group, value;
5292
5293    	  // The input data string is divided into groups of three digits,
5294    	  // and each group is converted to its 10-bit binary equivalent.
5295    	  for (i = 0; i + 3 <= this.data.length; i += 3) {
5296    	    group = this.data.substr(i, 3);
5297    	    value = parseInt(group, 10);
5298
5299    	    bitBuffer.put(value, 10);
5300    	  }
5301
5302    	  // If the number of input digits is not an exact multiple of three,
5303    	  // the final one or two digits are converted to 4 or 7 bits respectively.
5304    	  const remainingNum = this.data.length - i;
5305    	  if (remainingNum > 0) {
5306    	    group = this.data.substr(i);
5307    	    value = parseInt(group, 10);
5308
5309    	    bitBuffer.put(value, remainingNum * 3 + 1);
5310    	  }
5311    	};
5312
5313    	numericData = NumericData;
5314    	return numericData;
5315    }
5316
5317    var alphanumericData;
5318    var hasRequiredAlphanumericData;
5319
5320    function requireAlphanumericData () {
5321    	if (hasRequiredAlphanumericData) return alphanumericData;
5322    	hasRequiredAlphanumericData = 1;
5323    	const Mode = requireMode();
5324
5325    	/**
5326    	 * Array of characters available in alphanumeric mode
5327    	 *
5328    	 * As per QR Code specification, to each character
5329    	 * is assigned a value from 0 to 44 which in this case coincides
5330    	 * with the array index
5331    	 *
5332    	 * @type {Array}
5333    	 */
5334    	const ALPHA_NUM_CHARS = [
5335    	  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
5336    	  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
5337    	  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
5338    	  ' ', '$', '%', '*', '+', '-', '.', '/', ':'
5339    	];
5340
5341    	function AlphanumericData (data) {
5342    	  this.mode = Mode.ALPHANUMERIC;
5343    	  this.data = data;
5344    	}
5345
5346    	AlphanumericData.getBitsLength = function getBitsLength (length) {
5347    	  return 11 * Math.floor(length / 2) + 6 * (length % 2)
5348    	};
5349
5350    	AlphanumericData.prototype.getLength = function getLength () {
5351    	  return this.data.length
5352    	};
5353
5354    	AlphanumericData.prototype.getBitsLength = function getBitsLength () {
5355    	  return AlphanumericData.getBitsLength(this.data.length)
5356    	};
5357
5358    	AlphanumericData.prototype.write = function write (bitBuffer) {
5359    	  let i;
5360
5361    	  // Input data characters are divided into groups of two characters
5362    	  // and encoded as 11-bit binary codes.
5363    	  for (i = 0; i + 2 <= this.data.length; i += 2) {
5364    	    // The character value of the first character is multiplied by 45
5365    	    let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45;
5366
5367    	    // The character value of the second digit is added to the product
5368    	    value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1]);
5369
5370    	    // The sum is then stored as 11-bit binary number
5371    	    bitBuffer.put(value, 11);
5372    	  }
5373
5374    	  // If the number of input data characters is not a multiple of two,
5375    	  // the character value of the final character is encoded as a 6-bit binary number.
5376    	  if (this.data.length % 2) {
5377    	    bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6);
5378    	  }
5379    	};
5380
5381    	alphanumericData = AlphanumericData;
5382    	return alphanumericData;
5383    }
5384
5385    var byteData;
5386    var hasRequiredByteData;
5387
5388    function requireByteData () {
5389    	if (hasRequiredByteData) return byteData;
5390    	hasRequiredByteData = 1;
5391    	const Mode = requireMode();
5392
5393    	function ByteData (data) {
5394    	  this.mode = Mode.BYTE;
5395    	  if (typeof (data) === 'string') {
5396    	    this.data = new TextEncoder().encode(data);
5397    	  } else {
5398    	    this.data = new Uint8Array(data);
5399    	  }
5400    	}
5401
5402    	ByteData.getBitsLength = function getBitsLength (length) {
5403    	  return length * 8
5404    	};
5405
5406    	ByteData.prototype.getLength = function getLength () {
5407    	  return this.data.length
5408    	};
5409
5410    	ByteData.prototype.getBitsLength = function getBitsLength () {
5411    	  return ByteData.getBitsLength(this.data.length)
5412    	};
5413
5414    	ByteData.prototype.write = function (bitBuffer) {
5415    	  for (let i = 0, l = this.data.length; i < l; i++) {
5416    	    bitBuffer.put(this.data[i], 8);
5417    	  }
5418    	};
5419
5420    	byteData = ByteData;
5421    	return byteData;
5422    }
5423
5424    var kanjiData;
5425    var hasRequiredKanjiData;
5426
5427    function requireKanjiData () {
5428    	if (hasRequiredKanjiData) return kanjiData;
5429    	hasRequiredKanjiData = 1;
5430    	const Mode = requireMode();
5431    	const Utils = requireUtils$1();
5432
5433    	function KanjiData (data) {
5434    	  this.mode = Mode.KANJI;
5435    	  this.data = data;
5436    	}
5437
5438    	KanjiData.getBitsLength = function getBitsLength (length) {
5439    	  return length * 13
5440    	};
5441
5442    	KanjiData.prototype.getLength = function getLength () {
5443    	  return this.data.length
5444    	};
5445
5446    	KanjiData.prototype.getBitsLength = function getBitsLength () {
5447    	  return KanjiData.getBitsLength(this.data.length)
5448    	};
5449
5450    	KanjiData.prototype.write = function (bitBuffer) {
5451    	  let i;
5452
5453    	  // In the Shift JIS system, Kanji characters are represented by a two byte combination.
5454    	  // These byte values are shifted from the JIS X 0208 values.
5455    	  // JIS X 0208 gives details of the shift coded representation.
5456    	  for (i = 0; i < this.data.length; i++) {
5457    	    let value = Utils.toSJIS(this.data[i]);
5458
5459    	    // For characters with Shift JIS values from 0x8140 to 0x9FFC:
5460    	    if (value >= 0x8140 && value <= 0x9FFC) {
5461    	      // Subtract 0x8140 from Shift JIS value
5462    	      value -= 0x8140;
5463
5464    	    // For characters with Shift JIS values from 0xE040 to 0xEBBF
5465    	    } else if (value >= 0xE040 && value <= 0xEBBF) {
5466    	      // Subtract 0xC140 from Shift JIS value
5467    	      value -= 0xC140;
5468    	    } else {
5469    	      throw new Error(
5470    	        'Invalid SJIS character: ' + this.data[i] + '\n' +
5471    	        'Make sure your charset is UTF-8')
5472    	    }
5473
5474    	    // Multiply most significant byte of result by 0xC0
5475    	    // and add least significant byte to product
5476    	    value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff);
5477
5478    	    // Convert result to a 13-bit binary string
5479    	    bitBuffer.put(value, 13);
5480    	  }
5481    	};
5482
5483    	kanjiData = KanjiData;
5484    	return kanjiData;
5485    }
5486
5487    var dijkstra = {exports: {}};
5488
5489    var hasRequiredDijkstra;
5490
5491    function requireDijkstra () {
5492    	if (hasRequiredDijkstra) return dijkstra.exports;
5493    	hasRequiredDijkstra = 1;
5494    	(function (module) {
5495
5496    		/******************************************************************************
5497    		 * Created 2008-08-19.
5498    		 *
5499    		 * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
5500    		 *
5501    		 * Copyright (C) 2008
5502    		 *   Wyatt Baldwin <[email protected]>
5503    		 *   All rights reserved
5504    		 *
5505    		 * Licensed under the MIT license.
5506    		 *
5507    		 *   http://www.opensource.org/licenses/mit-license.php
5508    		 *
5509    		 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5510    		 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
5511    		 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
5512    		 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
5513    		 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
5514    		 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
5515    		 * THE SOFTWARE.
5516    		 *****************************************************************************/
5517    		var dijkstra = {
5518    		  single_source_shortest_paths: function(graph, s, d) {
5519    		    // Predecessor map for each node that has been encountered.
5520    		    // node ID => predecessor node ID
5521    		    var predecessors = {};
5522
5523    		    // Costs of shortest paths from s to all nodes encountered.
5524    		    // node ID => cost
5525    		    var costs = {};
5526    		    costs[s] = 0;
5527
5528    		    // Costs of shortest paths from s to all nodes encountered; differs from
5529    		    // `costs` in that it provides easy access to the node that currently has
5530    		    // the known shortest path from s.
5531    		    // XXX: Do we actually need both `costs` and `open`?
5532    		    var open = dijkstra.PriorityQueue.make();
5533    		    open.push(s, 0);
5534
5535    		    var closest,
5536    		        u, v,
5537    		        cost_of_s_to_u,
5538    		        adjacent_nodes,
5539    		        cost_of_e,
5540    		        cost_of_s_to_u_plus_cost_of_e,
5541    		        cost_of_s_to_v,
5542    		        first_visit;
5543    		    while (!open.empty()) {
5544    		      // In the nodes remaining in graph that have a known cost from s,
5545    		      // find the node, u, that currently has the shortest path from s.
5546    		      closest = open.pop();
5547    		      u = closest.value;
5548    		      cost_of_s_to_u = closest.cost;
5549
5550    		      // Get nodes adjacent to u...
5551    		      adjacent_nodes = graph[u] || {};
5552
5553    		      // ...and explore the edges that connect u to those nodes, updating
5554    		      // the cost of the shortest paths to any or all of those nodes as
5555    		      // necessary. v is the node across the current edge from u.
5556    		      for (v in adjacent_nodes) {
5557    		        if (adjacent_nodes.hasOwnProperty(v)) {
5558    		          // Get the cost of the edge running from u to v.
5559    		          cost_of_e = adjacent_nodes[v];
5560
5561    		          // Cost of s to u plus the cost of u to v across e--this is *a*
5562    		          // cost from s to v that may or may not be less than the current
5563    		          // known cost to v.
5564    		          cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;
5565
5566    		          // If we haven't visited v yet OR if the current known cost from s to
5567    		          // v is greater than the new cost we just found (cost of s to u plus
5568    		          // cost of u to v across e), update v's cost in the cost list and
5569    		          // update v's predecessor in the predecessor list (it's now u).
5570    		          cost_of_s_to_v = costs[v];
5571    		          first_visit = (typeof costs[v] === 'undefined');
5572    		          if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
5573    		            costs[v] = cost_of_s_to_u_plus_cost_of_e;
5574    		            open.push(v, cost_of_s_to_u_plus_cost_of_e);
5575    		            predecessors[v] = u;
5576    		          }
5577    		        }
5578    		      }
5579    		    }
5580
5581    		    if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {
5582    		      var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');
5583    		      throw new Error(msg);
5584    		    }
5585
5586    		    return predecessors;
5587    		  },
5588
5589    		  extract_shortest_path_from_predecessor_list: function(predecessors, d) {
5590    		    var nodes = [];
5591    		    var u = d;
5592    		    while (u) {
5593    		      nodes.push(u);
5594    		      predecessors[u];
5595    		      u = predecessors[u];
5596    		    }
5597    		    nodes.reverse();
5598    		    return nodes;
5599    		  },
5600
5601    		  find_path: function(graph, s, d) {
5602    		    var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);
5603    		    return dijkstra.extract_shortest_path_from_predecessor_list(
5604    		      predecessors, d);
5605    		  },
5606
5607    		  /**
5608    		   * A very naive priority queue implementation.
5609    		   */
5610    		  PriorityQueue: {
5611    		    make: function (opts) {
5612    		      var T = dijkstra.PriorityQueue,
5613    		          t = {},
5614    		          key;
5615    		      opts = opts || {};
5616    		      for (key in T) {
5617    		        if (T.hasOwnProperty(key)) {
5618    		          t[key] = T[key];
5619    		        }
5620    		      }
5621    		      t.queue = [];
5622    		      t.sorter = opts.sorter || T.default_sorter;
5623    		      return t;
5624    		    },
5625
5626    		    default_sorter: function (a, b) {
5627    		      return a.cost - b.cost;
5628    		    },
5629
5630    		    /**
5631    		     * Add a new item to the queue and ensure the highest priority element
5632    		     * is at the front of the queue.
5633    		     */
5634    		    push: function (value, cost) {
5635    		      var item = {value: value, cost: cost};
5636    		      this.queue.push(item);
5637    		      this.queue.sort(this.sorter);
5638    		    },
5639
5640    		    /**
5641    		     * Return the highest priority element in the queue.
5642    		     */
5643    		    pop: function () {
5644    		      return this.queue.shift();
5645    		    },
5646
5647    		    empty: function () {
5648    		      return this.queue.length === 0;
5649    		    }
5650    		  }
5651    		};
5652
5653
5654    		// node.js module exports
5655    		{
5656    		  module.exports = dijkstra;
5657    		} 
5658    	} (dijkstra));
5659    	return dijkstra.exports;
5660    }
5661
5662    var hasRequiredSegments;
5663
5664    function requireSegments () {
5665    	if (hasRequiredSegments) return segments;
5666    	hasRequiredSegments = 1;
5667    	(function (exports) {
5668    		const Mode = requireMode();
5669    		const NumericData = requireNumericData();
5670    		const AlphanumericData = requireAlphanumericData();
5671    		const ByteData = requireByteData();
5672    		const KanjiData = requireKanjiData();
5673    		const Regex = requireRegex();
5674    		const Utils = requireUtils$1();
5675    		const dijkstra = requireDijkstra();
5676
5677    		/**
5678    		 * Returns UTF8 byte length
5679    		 *
5680    		 * @param  {String} str Input string
5681    		 * @return {Number}     Number of byte
5682    		 */
5683    		function getStringByteLength (str) {
5684    		  return unescape(encodeURIComponent(str)).length
5685    		}
5686
5687    		/**
5688    		 * Get a list of segments of the specified mode
5689    		 * from a string
5690    		 *
5691    		 * @param  {Mode}   mode Segment mode
5692    		 * @param  {String} str  String to process
5693    		 * @return {Array}       Array of object with segments data
5694    		 */
5695    		function getSegments (regex, mode, str) {
5696    		  const segments = [];
5697    		  let result;
5698
5699    		  while ((result = regex.exec(str)) !== null) {
5700    		    segments.push({
5701    		      data: result[0],
5702    		      index: result.index,
5703    		      mode: mode,
5704    		      length: result[0].length
5705    		    });
5706    		  }
5707
5708    		  return segments
5709    		}
5710
5711    		/**
5712    		 * Extracts a series of segments with the appropriate
5713    		 * modes from a string
5714    		 *
5715    		 * @param  {String} dataStr Input string
5716    		 * @return {Array}          Array of object with segments data
5717    		 */
5718    		function getSegmentsFromString (dataStr) {
5719    		  const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr);
5720    		  const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr);
5721    		  let byteSegs;
5722    		  let kanjiSegs;
5723
5724    		  if (Utils.isKanjiModeEnabled()) {
5725    		    byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr);
5726    		    kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr);
5727    		  } else {
5728    		    byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr);
5729    		    kanjiSegs = [];
5730    		  }
5731
5732    		  const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs);
5733
5734    		  return segs
5735    		    .sort(function (s1, s2) {
5736    		      return s1.index - s2.index
5737    		    })
5738    		    .map(function (obj) {
5739    		      return {
5740    		        data: obj.data,
5741    		        mode: obj.mode,
5742    		        length: obj.length
5743    		      }
5744    		    })
5745    		}
5746
5747    		/**
5748    		 * Returns how many bits are needed to encode a string of
5749    		 * specified length with the specified mode
5750    		 *
5751    		 * @param  {Number} length String length
5752    		 * @param  {Mode} mode     Segment mode
5753    		 * @return {Number}        Bit length
5754    		 */
5755    		function getSegmentBitsLength (length, mode) {
5756    		  switch (mode) {
5757    		    case Mode.NUMERIC:
5758    		      return NumericData.getBitsLength(length)
5759    		    case Mode.ALPHANUMERIC:
5760    		      return AlphanumericData.getBitsLength(length)
5761    		    case Mode.KANJI:
5762    		      return KanjiData.getBitsLength(length)
5763    		    case Mode.BYTE:
5764    		      return ByteData.getBitsLength(length)
5765    		  }
5766    		}
5767
5768    		/**
5769    		 * Merges adjacent segments which have the same mode
5770    		 *
5771    		 * @param  {Array} segs Array of object with segments data
5772    		 * @return {Array}      Array of object with segments data
5773    		 */
5774    		function mergeSegments (segs) {
5775    		  return segs.reduce(function (acc, curr) {
5776    		    const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null;
5777    		    if (prevSeg && prevSeg.mode === curr.mode) {
5778    		      acc[acc.length - 1].data += curr.data;
5779    		      return acc
5780    		    }
5781
5782    		    acc.push(curr);
5783    		    return acc
5784    		  }, [])
5785    		}
5786
5787    		/**
5788    		 * Generates a list of all possible nodes combination which
5789    		 * will be used to build a segments graph.
5790    		 *
5791    		 * Nodes are divided by groups. Each group will contain a list of all the modes
5792    		 * in which is possible to encode the given text.
5793    		 *
5794    		 * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte.
5795    		 * The group for '12345' will contain then 3 objects, one for each
5796    		 * possible encoding mode.
5797    		 *
5798    		 * Each node represents a possible segment.
5799    		 *
5800    		 * @param  {Array} segs Array of object with segments data
5801    		 * @return {Array}      Array of object with segments data
5802    		 */
5803    		function buildNodes (segs) {
5804    		  const nodes = [];
5805    		  for (let i = 0; i < segs.length; i++) {
5806    		    const seg = segs[i];
5807
5808    		    switch (seg.mode) {
5809    		      case Mode.NUMERIC:
5810    		        nodes.push([seg,
5811    		          { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length },
5812    		          { data: seg.data, mode: Mode.BYTE, length: seg.length }
5813    		        ]);
5814    		        break
5815    		      case Mode.ALPHANUMERIC:
5816    		        nodes.push([seg,
5817    		          { data: seg.data, mode: Mode.BYTE, length: seg.length }
5818    		        ]);
5819    		        break
5820    		      case Mode.KANJI:
5821    		        nodes.push([seg,
5822    		          { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
5823    		        ]);
5824    		        break
5825    		      case Mode.BYTE:
5826    		        nodes.push([
5827    		          { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
5828    		        ]);
5829    		    }
5830    		  }
5831
5832    		  return nodes
5833    		}
5834
5835    		/**
5836    		 * Builds a graph from a list of nodes.
5837    		 * All segments in each node group will be connected with all the segments of
5838    		 * the next group and so on.
5839    		 *
5840    		 * At each connection will be assigned a weight depending on the
5841    		 * segment's byte length.
5842    		 *
5843    		 * @param  {Array} nodes    Array of object with segments data
5844    		 * @param  {Number} version QR Code version
5845    		 * @return {Object}         Graph of all possible segments
5846    		 */
5847    		function buildGraph (nodes, version) {
5848    		  const table = {};
5849    		  const graph = { start: {} };
5850    		  let prevNodeIds = ['start'];
5851
5852    		  for (let i = 0; i < nodes.length; i++) {
5853    		    const nodeGroup = nodes[i];
5854    		    const currentNodeIds = [];
5855
5856    		    for (let j = 0; j < nodeGroup.length; j++) {
5857    		      const node = nodeGroup[j];
5858    		      const key = '' + i + j;
5859
5860    		      currentNodeIds.push(key);
5861    		      table[key] = { node: node, lastCount: 0 };
5862    		      graph[key] = {};
5863
5864    		      for (let n = 0; n < prevNodeIds.length; n++) {
5865    		        const prevNodeId = prevNodeIds[n];
5866
5867    		        if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {
5868    		          graph[prevNodeId][key] =
5869    		            getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) -
5870    		            getSegmentBitsLength(table[prevNodeId].lastCount, node.mode);
5871
5872    		          table[prevNodeId].lastCount += node.length;
5873    		        } else {
5874    		          if (table[prevNodeId]) table[prevNodeId].lastCount = node.length;
5875
5876    		          graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) +
5877    		            4 + Mode.getCharCountIndicator(node.mode, version); // switch cost
5878    		        }
5879    		      }
5880    		    }
5881
5882    		    prevNodeIds = currentNodeIds;
5883    		  }
5884
5885    		  for (let n = 0; n < prevNodeIds.length; n++) {
5886    		    graph[prevNodeIds[n]].end = 0;
5887    		  }
5888
5889    		  return { map: graph, table: table }
5890    		}
5891
5892    		/**
5893    		 * Builds a segment from a specified data and mode.
5894    		 * If a mode is not specified, the more suitable will be used.
5895    		 *
5896    		 * @param  {String} data             Input data
5897    		 * @param  {Mode | String} modesHint Data mode
5898    		 * @return {Segment}                 Segment
5899    		 */
5900    		function buildSingleSegment (data, modesHint) {
5901    		  let mode;
5902    		  const bestMode = Mode.getBestModeForData(data);
5903
5904    		  mode = Mode.from(modesHint, bestMode);
5905
5906    		  // Make sure data can be encoded
5907    		  if (mode !== Mode.BYTE && mode.bit < bestMode.bit) {
5908    		    throw new Error('"' + data + '"' +
5909    		      ' cannot be encoded with mode ' + Mode.toString(mode) +
5910    		      '.\n Suggested mode is: ' + Mode.toString(bestMode))
5911    		  }
5912
5913    		  // Use Mode.BYTE if Kanji support is disabled
5914    		  if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) {
5915    		    mode = Mode.BYTE;
5916    		  }
5917
5918    		  switch (mode) {
5919    		    case Mode.NUMERIC:
5920    		      return new NumericData(data)
5921
5922    		    case Mode.ALPHANUMERIC:
5923    		      return new AlphanumericData(data)
5924
5925    		    case Mode.KANJI:
5926    		      return new KanjiData(data)
5927
5928    		    case Mode.BYTE:
5929    		      return new ByteData(data)
5930    		  }
5931    		}
5932
5933    		/**
5934    		 * Builds a list of segments from an array.
5935    		 * Array can contain Strings or Objects with segment's info.
5936    		 *
5937    		 * For each item which is a string, will be generated a segment with the given
5938    		 * string and the more appropriate encoding mode.
5939    		 *
5940    		 * For each item which is an object, will be generated a segment with the given
5941    		 * data and mode.
5942    		 * Objects must contain at least the property "data".
5943    		 * If property "mode" is not present, the more suitable mode will be used.
5944    		 *
5945    		 * @param  {Array} array Array of objects with segments data
5946    		 * @return {Array}       Array of Segments
5947    		 */
5948    		exports.fromArray = function fromArray (array) {
5949    		  return array.reduce(function (acc, seg) {
5950    		    if (typeof seg === 'string') {
5951    		      acc.push(buildSingleSegment(seg, null));
5952    		    } else if (seg.data) {
5953    		      acc.push(buildSingleSegment(seg.data, seg.mode));
5954    		    }
5955
5956    		    return acc
5957    		  }, [])
5958    		};
5959
5960    		/**
5961    		 * Builds an optimized sequence of segments from a string,
5962    		 * which will produce the shortest possible bitstream.
5963    		 *
5964    		 * @param  {String} data    Input string
5965    		 * @param  {Number} version QR Code version
5966    		 * @return {Array}          Array of segments
5967    		 */
5968    		exports.fromString = function fromString (data, version) {
5969    		  const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled());
5970
5971    		  const nodes = buildNodes(segs);
5972    		  const graph = buildGraph(nodes, version);
5973    		  const path = dijkstra.find_path(graph.map, 'start', 'end');
5974
5975    		  const optimizedSegs = [];
5976    		  for (let i = 1; i < path.length - 1; i++) {
5977    		    optimizedSegs.push(graph.table[path[i]].node);
5978    		  }
5979
5980    		  return exports.fromArray(mergeSegments(optimizedSegs))
5981    		};
5982
5983    		/**
5984    		 * Splits a string in various segments with the modes which
5985    		 * best represent their content.
5986    		 * The produced segments are far from being optimized.
5987    		 * The output of this function is only used to estimate a QR Code version
5988    		 * which may contain the data.
5989    		 *
5990    		 * @param  {string} data Input string
5991    		 * @return {Array}       Array of segments
5992    		 */
5993    		exports.rawSplit = function rawSplit (data) {
5994    		  return exports.fromArray(
5995    		    getSegmentsFromString(data, Utils.isKanjiModeEnabled())
5996    		  )
5997    		}; 
5998    	} (segments));
5999    	return segments;
6000    }
6001
6002    var hasRequiredQrcode;
6003
6004    function requireQrcode () {
6005    	if (hasRequiredQrcode) return qrcode;
6006    	hasRequiredQrcode = 1;
6007    	const Utils = requireUtils$1();
6008    	const ECLevel = requireErrorCorrectionLevel();
6009    	const BitBuffer = requireBitBuffer();
6010    	const BitMatrix = requireBitMatrix();
6011    	const AlignmentPattern = requireAlignmentPattern();
6012    	const FinderPattern = requireFinderPattern();
6013    	const MaskPattern = requireMaskPattern();
6014    	const ECCode = requireErrorCorrectionCode();
6015    	const ReedSolomonEncoder = requireReedSolomonEncoder();
6016    	const Version = requireVersion();
6017    	const FormatInfo = requireFormatInfo();
6018    	const Mode = requireMode();
6019    	const Segments = requireSegments();
6020
6021    	/**
6022    	 * QRCode for JavaScript
6023    	 *
6024    	 * modified by Ryan Day for nodejs support
6025    	 * Copyright (c) 2011 Ryan Day
6026    	 *
6027    	 * Licensed under the MIT license:
6028    	 *   http://www.opensource.org/licenses/mit-license.php
6029    	 *
6030    	//---------------------------------------------------------------------
6031    	// QRCode for JavaScript
6032    	//
6033    	// Copyright (c) 2009 Kazuhiko Arase
6034    	//
6035    	// URL: http://www.d-project.com/
6036    	//
6037    	// Licensed under the MIT license:
6038    	//   http://www.opensource.org/licenses/mit-license.php
6039    	//
6040    	// The word "QR Code" is registered trademark of
6041    	// DENSO WAVE INCORPORATED
6042    	//   http://www.denso-wave.com/qrcode/faqpatent-e.html
6043    	//
6044    	//---------------------------------------------------------------------
6045    	*/
6046
6047    	/**
6048    	 * Add finder patterns bits to matrix
6049    	 *
6050    	 * @param  {BitMatrix} matrix  Modules matrix
6051    	 * @param  {Number}    version QR Code version
6052    	 */
6053    	function setupFinderPattern (matrix, version) {
6054    	  const size = matrix.size;
6055    	  const pos = FinderPattern.getPositions(version);
6056
6057    	  for (let i = 0; i < pos.length; i++) {
vendor: 9,598 bytes, lines 6058-6331
6058    	    const row = pos[i][0];
6059    	    const col = pos[i][1];
6060
6061    	    for (let r = -1; r <= 7; r++) {
6062    	      if (row + r <= -1 || size <= row + r) continue
6063
6064    	      for (let c = -1; c <= 7; c++) {
6065    	        if (col + c <= -1 || size <= col + c) continue
6066
6067    	        if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) ||
6068    	          (c >= 0 && c <= 6 && (r === 0 || r === 6)) ||
6069    	          (r >= 2 && r <= 4 && c >= 2 && c <= 4)) {
6070    	          matrix.set(row + r, col + c, true, true);
6071    	        } else {
6072    	          matrix.set(row + r, col + c, false, true);
6073    	        }
6074    	      }
6075    	    }
6076    	  }
6077    	}
6078
6079    	/**
6080    	 * Add timing pattern bits to matrix
6081    	 *
6082    	 * Note: this function must be called before {@link setupAlignmentPattern}
6083    	 *
6084    	 * @param  {BitMatrix} matrix Modules matrix
6085    	 */
6086    	function setupTimingPattern (matrix) {
6087    	  const size = matrix.size;
6088
6089    	  for (let r = 8; r < size - 8; r++) {
6090    	    const value = r % 2 === 0;
6091    	    matrix.set(r, 6, value, true);
6092    	    matrix.set(6, r, value, true);
6093    	  }
6094    	}
6095
6096    	/**
6097    	 * Add alignment patterns bits to matrix
6098    	 *
6099    	 * Note: this function must be called after {@link setupTimingPattern}
6100    	 *
6101    	 * @param  {BitMatrix} matrix  Modules matrix
6102    	 * @param  {Number}    version QR Code version
6103    	 */
6104    	function setupAlignmentPattern (matrix, version) {
6105    	  const pos = AlignmentPattern.getPositions(version);
6106
6107    	  for (let i = 0; i < pos.length; i++) {
6108    	    const row = pos[i][0];
6109    	    const col = pos[i][1];
6110
6111    	    for (let r = -2; r <= 2; r++) {
6112    	      for (let c = -2; c <= 2; c++) {
6113    	        if (r === -2 || r === 2 || c === -2 || c === 2 ||
6114    	          (r === 0 && c === 0)) {
6115    	          matrix.set(row + r, col + c, true, true);
6116    	        } else {
6117    	          matrix.set(row + r, col + c, false, true);
6118    	        }
6119    	      }
6120    	    }
6121    	  }
6122    	}
6123
6124    	/**
6125    	 * Add version info bits to matrix
6126    	 *
6127    	 * @param  {BitMatrix} matrix  Modules matrix
6128    	 * @param  {Number}    version QR Code version
6129    	 */
6130    	function setupVersionInfo (matrix, version) {
6131    	  const size = matrix.size;
6132    	  const bits = Version.getEncodedBits(version);
6133    	  let row, col, mod;
6134
6135    	  for (let i = 0; i < 18; i++) {
6136    	    row = Math.floor(i / 3);
6137    	    col = i % 3 + size - 8 - 3;
6138    	    mod = ((bits >> i) & 1) === 1;
6139
6140    	    matrix.set(row, col, mod, true);
6141    	    matrix.set(col, row, mod, true);
6142    	  }
6143    	}
6144
6145    	/**
6146    	 * Add format info bits to matrix
6147    	 *
6148    	 * @param  {BitMatrix} matrix               Modules matrix
6149    	 * @param  {ErrorCorrectionLevel}    errorCorrectionLevel Error correction level
6150    	 * @param  {Number}    maskPattern          Mask pattern reference value
6151    	 */
6152    	function setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) {
6153    	  const size = matrix.size;
6154    	  const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern);
6155    	  let i, mod;
6156
6157    	  for (i = 0; i < 15; i++) {
6158    	    mod = ((bits >> i) & 1) === 1;
6159
6160    	    // vertical
6161    	    if (i < 6) {
6162    	      matrix.set(i, 8, mod, true);
6163    	    } else if (i < 8) {
6164    	      matrix.set(i + 1, 8, mod, true);
6165    	    } else {
6166    	      matrix.set(size - 15 + i, 8, mod, true);
6167    	    }
6168
6169    	    // horizontal
6170    	    if (i < 8) {
6171    	      matrix.set(8, size - i - 1, mod, true);
6172    	    } else if (i < 9) {
6173    	      matrix.set(8, 15 - i - 1 + 1, mod, true);
6174    	    } else {
6175    	      matrix.set(8, 15 - i - 1, mod, true);
6176    	    }
6177    	  }
6178
6179    	  // fixed module
6180    	  matrix.set(size - 8, 8, 1, true);
6181    	}
6182
6183    	/**
6184    	 * Add encoded data bits to matrix
6185    	 *
6186    	 * @param  {BitMatrix}  matrix Modules matrix
6187    	 * @param  {Uint8Array} data   Data codewords
6188    	 */
6189    	function setupData (matrix, data) {
6190    	  const size = matrix.size;
6191    	  let inc = -1;
6192    	  let row = size - 1;
6193    	  let bitIndex = 7;
6194    	  let byteIndex = 0;
6195
6196    	  for (let col = size - 1; col > 0; col -= 2) {
6197    	    if (col === 6) col--;
6198
6199    	    while (true) {
6200    	      for (let c = 0; c < 2; c++) {
6201    	        if (!matrix.isReserved(row, col - c)) {
6202    	          let dark = false;
6203
6204    	          if (byteIndex < data.length) {
6205    	            dark = (((data[byteIndex] >>> bitIndex) & 1) === 1);
6206    	          }
6207
6208    	          matrix.set(row, col - c, dark);
6209    	          bitIndex--;
6210
6211    	          if (bitIndex === -1) {
6212    	            byteIndex++;
6213    	            bitIndex = 7;
6214    	          }
6215    	        }
6216    	      }
6217
6218    	      row += inc;
6219
6220    	      if (row < 0 || size <= row) {
6221    	        row -= inc;
6222    	        inc = -inc;
6223    	        break
6224    	      }
6225    	    }
6226    	  }
6227    	}
6228
6229    	/**
6230    	 * Create encoded codewords from data input
6231    	 *
6232    	 * @param  {Number}   version              QR Code version
6233    	 * @param  {ErrorCorrectionLevel}   errorCorrectionLevel Error correction level
6234    	 * @param  {ByteData} data                 Data input
6235    	 * @return {Uint8Array}                    Buffer containing encoded codewords
6236    	 */
6237    	function createData (version, errorCorrectionLevel, segments) {
6238    	  // Prepare data buffer
6239    	  const buffer = new BitBuffer();
6240
6241    	  segments.forEach(function (data) {
6242    	    // prefix data with mode indicator (4 bits)
6243    	    buffer.put(data.mode.bit, 4);
6244
6245    	    // Prefix data with character count indicator.
6246    	    // The character count indicator is a string of bits that represents the
6247    	    // number of characters that are being encoded.
6248    	    // The character count indicator must be placed after the mode indicator
6249    	    // and must be a certain number of bits long, depending on the QR version
6250    	    // and data mode
6251    	    // @see {@link Mode.getCharCountIndicator}.
6252    	    buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version));
6253
6254    	    // add binary data sequence to buffer
6255    	    data.write(buffer);
6256    	  });
6257
6258    	  // Calculate required number of bits
6259    	  const totalCodewords = Utils.getSymbolTotalCodewords(version);
6260    	  const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
6261    	  const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8;
6262
6263    	  // Add a terminator.
6264    	  // If the bit string is shorter than the total number of required bits,
6265    	  // a terminator of up to four 0s must be added to the right side of the string.
6266    	  // If the bit string is more than four bits shorter than the required number of bits,
6267    	  // add four 0s to the end.
6268    	  if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) {
6269    	    buffer.put(0, 4);
6270    	  }
6271
6272    	  // If the bit string is fewer than four bits shorter, add only the number of 0s that
6273    	  // are needed to reach the required number of bits.
6274
6275    	  // After adding the terminator, if the number of bits in the string is not a multiple of 8,
6276    	  // pad the string on the right with 0s to make the string's length a multiple of 8.
6277    	  while (buffer.getLengthInBits() % 8 !== 0) {
6278    	    buffer.putBit(0);
6279    	  }
6280
6281    	  // Add pad bytes if the string is still shorter than the total number of required bits.
6282    	  // Extend the buffer to fill the data capacity of the symbol corresponding to
6283    	  // the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC)
6284    	  // and 00010001 (0x11) alternately.
6285    	  const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8;
6286    	  for (let i = 0; i < remainingByte; i++) {
6287    	    buffer.put(i % 2 ? 0x11 : 0xEC, 8);
6288    	  }
6289
6290    	  return createCodewords(buffer, version, errorCorrectionLevel)
6291    	}
6292
6293    	/**
6294    	 * Encode input data with Reed-Solomon and return codewords with
6295    	 * relative error correction bits
6296    	 *
6297    	 * @param  {BitBuffer} bitBuffer            Data to encode
6298    	 * @param  {Number}    version              QR Code version
6299    	 * @param  {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
6300    	 * @return {Uint8Array}                     Buffer containing encoded codewords
6301    	 */
6302    	function createCodewords (bitBuffer, version, errorCorrectionLevel) {
6303    	  // Total codewords for this QR code version (Data + Error correction)
6304    	  const totalCodewords = Utils.getSymbolTotalCodewords(version);
6305
6306    	  // Total number of error correction codewords
6307    	  const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
6308
6309    	  // Total number of data codewords
6310    	  const dataTotalCodewords = totalCodewords - ecTotalCodewords;
6311
6312    	  // Total number of blocks
6313    	  const ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel);
6314
6315    	  // Calculate how many blocks each group should contain
6316    	  const blocksInGroup2 = totalCodewords % ecTotalBlocks;
6317    	  const blocksInGroup1 = ecTotalBlocks - blocksInGroup2;
6318
6319    	  const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks);
6320
6321    	  const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks);
6322    	  const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1;
6323
6324    	  // Number of EC codewords is the same for both groups
6325    	  const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1;
6326
6327    	  // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount
6328    	  const rs = new ReedSolomonEncoder(ecCount);
6329
6330    	  let offset = 0;
6331    	  const dcData = new Array(ecTotalBlocks);
vendor: 16,365 bytes, lines 6332-6859
6332    	  const ecData = new Array(ecTotalBlocks);
6333    	  let maxDataSize = 0;
6334    	  const buffer = new Uint8Array(bitBuffer.buffer);
6335
6336    	  // Divide the buffer into the required number of blocks
6337    	  for (let b = 0; b < ecTotalBlocks; b++) {
6338    	    const dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2;
6339
6340    	    // extract a block of data from buffer
6341    	    dcData[b] = buffer.slice(offset, offset + dataSize);
6342
6343    	    // Calculate EC codewords for this data block
6344    	    ecData[b] = rs.encode(dcData[b]);
6345
6346    	    offset += dataSize;
6347    	    maxDataSize = Math.max(maxDataSize, dataSize);
6348    	  }
6349
6350    	  // Create final data
6351    	  // Interleave the data and error correction codewords from each block
6352    	  const data = new Uint8Array(totalCodewords);
6353    	  let index = 0;
6354    	  let i, r;
6355
6356    	  // Add data codewords
6357    	  for (i = 0; i < maxDataSize; i++) {
6358    	    for (r = 0; r < ecTotalBlocks; r++) {
6359    	      if (i < dcData[r].length) {
6360    	        data[index++] = dcData[r][i];
6361    	      }
6362    	    }
6363    	  }
6364
6365    	  // Apped EC codewords
6366    	  for (i = 0; i < ecCount; i++) {
6367    	    for (r = 0; r < ecTotalBlocks; r++) {
6368    	      data[index++] = ecData[r][i];
6369    	    }
6370    	  }
6371
6372    	  return data
6373    	}
6374
6375    	/**
6376    	 * Build QR Code symbol
6377    	 *
6378    	 * @param  {String} data                 Input string
6379    	 * @param  {Number} version              QR Code version
6380    	 * @param  {ErrorCorretionLevel} errorCorrectionLevel Error level
6381    	 * @param  {MaskPattern} maskPattern     Mask pattern
6382    	 * @return {Object}                      Object containing symbol data
6383    	 */
6384    	function createSymbol (data, version, errorCorrectionLevel, maskPattern) {
6385    	  let segments;
6386
6387    	  if (Array.isArray(data)) {
6388    	    segments = Segments.fromArray(data);
6389    	  } else if (typeof data === 'string') {
6390    	    let estimatedVersion = version;
6391
6392    	    if (!estimatedVersion) {
6393    	      const rawSegments = Segments.rawSplit(data);
6394
6395    	      // Estimate best version that can contain raw splitted segments
6396    	      estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel);
6397    	    }
6398
6399    	    // Build optimized segments
6400    	    // If estimated version is undefined, try with the highest version
6401    	    segments = Segments.fromString(data, estimatedVersion || 40);
6402    	  } else {
6403    	    throw new Error('Invalid data')
6404    	  }
6405
6406    	  // Get the min version that can contain data
6407    	  const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel);
6408
6409    	  // If no version is found, data cannot be stored
6410    	  if (!bestVersion) {
6411    	    throw new Error('The amount of data is too big to be stored in a QR Code')
6412    	  }
6413
6414    	  // If not specified, use min version as default
6415    	  if (!version) {
6416    	    version = bestVersion;
6417
6418    	  // Check if the specified version can contain the data
6419    	  } else if (version < bestVersion) {
6420    	    throw new Error('\n' +
6421    	      'The chosen QR Code version cannot contain this amount of data.\n' +
6422    	      'Minimum version required to store current data is: ' + bestVersion + '.\n'
6423    	    )
6424    	  }
6425
6426    	  const dataBits = createData(version, errorCorrectionLevel, segments);
6427
6428    	  // Allocate matrix buffer
6429    	  const moduleCount = Utils.getSymbolSize(version);
6430    	  const modules = new BitMatrix(moduleCount);
6431
6432    	  // Add function modules
6433    	  setupFinderPattern(modules, version);
6434    	  setupTimingPattern(modules);
6435    	  setupAlignmentPattern(modules, version);
6436
6437    	  // Add temporary dummy bits for format info just to set them as reserved.
6438    	  // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask}
6439    	  // since the masking operation must be performed only on the encoding region.
6440    	  // These blocks will be replaced with correct values later in code.
6441    	  setupFormatInfo(modules, errorCorrectionLevel, 0);
6442
6443    	  if (version >= 7) {
6444    	    setupVersionInfo(modules, version);
6445    	  }
6446
6447    	  // Add data codewords
6448    	  setupData(modules, dataBits);
6449
6450    	  if (isNaN(maskPattern)) {
6451    	    // Find best mask pattern
6452    	    maskPattern = MaskPattern.getBestMask(modules,
6453    	      setupFormatInfo.bind(null, modules, errorCorrectionLevel));
6454    	  }
6455
6456    	  // Apply mask pattern
6457    	  MaskPattern.applyMask(maskPattern, modules);
6458
6459    	  // Replace format info bits with correct values
6460    	  setupFormatInfo(modules, errorCorrectionLevel, maskPattern);
6461
6462    	  return {
6463    	    modules: modules,
6464    	    version: version,
6465    	    errorCorrectionLevel: errorCorrectionLevel,
6466    	    maskPattern: maskPattern,
6467    	    segments: segments
6468    	  }
6469    	}
6470
6471    	/**
6472    	 * QR Code
6473    	 *
6474    	 * @param {String | Array} data                 Input data
6475    	 * @param {Object} options                      Optional configurations
6476    	 * @param {Number} options.version              QR Code version
6477    	 * @param {String} options.errorCorrectionLevel Error correction level
6478    	 * @param {Function} options.toSJISFunc         Helper func to convert utf8 to sjis
6479    	 */
6480    	qrcode.create = function create (data, options) {
6481    	  if (typeof data === 'undefined' || data === '') {
6482    	    throw new Error('No input text')
6483    	  }
6484
6485    	  let errorCorrectionLevel = ECLevel.M;
6486    	  let version;
6487    	  let mask;
6488
6489    	  if (typeof options !== 'undefined') {
6490    	    // Use higher error correction level as default
6491    	    errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M);
6492    	    version = Version.from(options.version);
6493    	    mask = MaskPattern.from(options.maskPattern);
6494
6495    	    if (options.toSJISFunc) {
6496    	      Utils.setToSJISFunction(options.toSJISFunc);
6497    	    }
6498    	  }
6499
6500    	  return createSymbol(data, version, errorCorrectionLevel, mask)
6501    	};
6502    	return qrcode;
6503    }
6504
6505    var canvas = {};
6506
6507    var utils = {};
6508
6509    var hasRequiredUtils;
6510
6511    function requireUtils () {
6512    	if (hasRequiredUtils) return utils;
6513    	hasRequiredUtils = 1;
6514    	(function (exports) {
6515    		function hex2rgba (hex) {
6516    		  if (typeof hex === 'number') {
6517    		    hex = hex.toString();
6518    		  }
6519
6520    		  if (typeof hex !== 'string') {
6521    		    throw new Error('Color should be defined as hex string')
6522    		  }
6523
6524    		  let hexCode = hex.slice().replace('#', '').split('');
6525    		  if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {
6526    		    throw new Error('Invalid hex color: ' + hex)
6527    		  }
6528
6529    		  // Convert from short to long form (fff -> ffffff)
6530    		  if (hexCode.length === 3 || hexCode.length === 4) {
6531    		    hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) {
6532    		      return [c, c]
6533    		    }));
6534    		  }
6535
6536    		  // Add default alpha value
6537    		  if (hexCode.length === 6) hexCode.push('F', 'F');
6538
6539    		  const hexValue = parseInt(hexCode.join(''), 16);
6540
6541    		  return {
6542    		    r: (hexValue >> 24) & 255,
6543    		    g: (hexValue >> 16) & 255,
6544    		    b: (hexValue >> 8) & 255,
6545    		    a: hexValue & 255,
6546    		    hex: '#' + hexCode.slice(0, 6).join('')
6547    		  }
6548    		}
6549
6550    		exports.getOptions = function getOptions (options) {
6551    		  if (!options) options = {};
6552    		  if (!options.color) options.color = {};
6553
6554    		  const margin = typeof options.margin === 'undefined' ||
6555    		    options.margin === null ||
6556    		    options.margin < 0
6557    		    ? 4
6558    		    : options.margin;
6559
6560    		  const width = options.width && options.width >= 21 ? options.width : undefined;
6561    		  const scale = options.scale || 4;
6562
6563    		  return {
6564    		    width: width,
6565    		    scale: width ? 4 : scale,
6566    		    margin: margin,
6567    		    color: {
6568    		      dark: hex2rgba(options.color.dark || '#000000ff'),
6569    		      light: hex2rgba(options.color.light || '#ffffffff')
6570    		    },
6571    		    type: options.type,
6572    		    rendererOpts: options.rendererOpts || {}
6573    		  }
6574    		};
6575
6576    		exports.getScale = function getScale (qrSize, opts) {
6577    		  return opts.width && opts.width >= qrSize + opts.margin * 2
6578    		    ? opts.width / (qrSize + opts.margin * 2)
6579    		    : opts.scale
6580    		};
6581
6582    		exports.getImageWidth = function getImageWidth (qrSize, opts) {
6583    		  const scale = exports.getScale(qrSize, opts);
6584    		  return Math.floor((qrSize + opts.margin * 2) * scale)
6585    		};
6586
6587    		exports.qrToImageData = function qrToImageData (imgData, qr, opts) {
6588    		  const size = qr.modules.size;
6589    		  const data = qr.modules.data;
6590    		  const scale = exports.getScale(size, opts);
6591    		  const symbolSize = Math.floor((size + opts.margin * 2) * scale);
6592    		  const scaledMargin = opts.margin * scale;
6593    		  const palette = [opts.color.light, opts.color.dark];
6594
6595    		  for (let i = 0; i < symbolSize; i++) {
6596    		    for (let j = 0; j < symbolSize; j++) {
6597    		      let posDst = (i * symbolSize + j) * 4;
6598    		      let pxColor = opts.color.light;
6599
6600    		      if (i >= scaledMargin && j >= scaledMargin &&
6601    		        i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {
6602    		        const iSrc = Math.floor((i - scaledMargin) / scale);
6603    		        const jSrc = Math.floor((j - scaledMargin) / scale);
6604    		        pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0];
6605    		      }
6606
6607    		      imgData[posDst++] = pxColor.r;
6608    		      imgData[posDst++] = pxColor.g;
6609    		      imgData[posDst++] = pxColor.b;
6610    		      imgData[posDst] = pxColor.a;
6611    		    }
6612    		  }
6613    		}; 
6614    	} (utils));
6615    	return utils;
6616    }
6617
6618    var hasRequiredCanvas;
6619
6620    function requireCanvas () {
6621    	if (hasRequiredCanvas) return canvas;
6622    	hasRequiredCanvas = 1;
6623    	(function (exports) {
6624    		const Utils = requireUtils();
6625
6626    		function clearCanvas (ctx, canvas, size) {
6627    		  ctx.clearRect(0, 0, canvas.width, canvas.height);
6628
6629    		  if (!canvas.style) canvas.style = {};
6630    		  canvas.height = size;
6631    		  canvas.width = size;
6632    		  canvas.style.height = size + 'px';
6633    		  canvas.style.width = size + 'px';
6634    		}
6635
6636    		function getCanvasElement () {
6637    		  try {
6638    		    return document.createElement('canvas')
6639    		  } catch (e) {
6640    		    throw new Error('You need to specify a canvas element')
6641    		  }
6642    		}
6643
6644    		exports.render = function render (qrData, canvas, options) {
6645    		  let opts = options;
6646    		  let canvasEl = canvas;
6647
6648    		  if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
6649    		    opts = canvas;
6650    		    canvas = undefined;
6651    		  }
6652
6653    		  if (!canvas) {
6654    		    canvasEl = getCanvasElement();
6655    		  }
6656
6657    		  opts = Utils.getOptions(opts);
6658    		  const size = Utils.getImageWidth(qrData.modules.size, opts);
6659
6660    		  const ctx = canvasEl.getContext('2d');
6661    		  const image = ctx.createImageData(size, size);
6662    		  Utils.qrToImageData(image.data, qrData, opts);
6663
6664    		  clearCanvas(ctx, canvasEl, size);
6665    		  ctx.putImageData(image, 0, 0);
6666
6667    		  return canvasEl
6668    		};
6669
6670    		exports.renderToDataURL = function renderToDataURL (qrData, canvas, options) {
6671    		  let opts = options;
6672
6673    		  if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
6674    		    opts = canvas;
6675    		    canvas = undefined;
6676    		  }
6677
6678    		  if (!opts) opts = {};
6679
6680    		  const canvasEl = exports.render(qrData, canvas, opts);
6681
6682    		  const type = opts.type || 'image/png';
6683    		  const rendererOpts = opts.rendererOpts || {};
6684
6685    		  return canvasEl.toDataURL(type, rendererOpts.quality)
6686    		}; 
6687    	} (canvas));
6688    	return canvas;
6689    }
6690
6691    var svgTag = {};
6692
6693    var hasRequiredSvgTag;
6694
6695    function requireSvgTag () {
6696    	if (hasRequiredSvgTag) return svgTag;
6697    	hasRequiredSvgTag = 1;
6698    	const Utils = requireUtils();
6699
6700    	function getColorAttrib (color, attrib) {
6701    	  const alpha = color.a / 255;
6702    	  const str = attrib + '="' + color.hex + '"';
6703
6704    	  return alpha < 1
6705    	    ? str + ' ' + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"'
6706    	    : str
6707    	}
6708
6709    	function svgCmd (cmd, x, y) {
6710    	  let str = cmd + x;
6711    	  if (typeof y !== 'undefined') str += ' ' + y;
6712
6713    	  return str
6714    	}
6715
6716    	function qrToPath (data, size, margin) {
6717    	  let path = '';
6718    	  let moveBy = 0;
6719    	  let newRow = false;
6720    	  let lineLength = 0;
6721
6722    	  for (let i = 0; i < data.length; i++) {
6723    	    const col = Math.floor(i % size);
6724    	    const row = Math.floor(i / size);
6725
6726    	    if (!col && !newRow) newRow = true;
6727
6728    	    if (data[i]) {
6729    	      lineLength++;
6730
6731    	      if (!(i > 0 && col > 0 && data[i - 1])) {
6732    	        path += newRow
6733    	          ? svgCmd('M', col + margin, 0.5 + row + margin)
6734    	          : svgCmd('m', moveBy, 0);
6735
6736    	        moveBy = 0;
6737    	        newRow = false;
6738    	      }
6739
6740    	      if (!(col + 1 < size && data[i + 1])) {
6741    	        path += svgCmd('h', lineLength);
6742    	        lineLength = 0;
6743    	      }
6744    	    } else {
6745    	      moveBy++;
6746    	    }
6747    	  }
6748
6749    	  return path
6750    	}
6751
6752    	svgTag.render = function render (qrData, options, cb) {
6753    	  const opts = Utils.getOptions(options);
6754    	  const size = qrData.modules.size;
6755    	  const data = qrData.modules.data;
6756    	  const qrcodesize = size + opts.margin * 2;
6757
6758    	  const bg = !opts.color.light.a
6759    	    ? ''
6760    	    : '<path ' + getColorAttrib(opts.color.light, 'fill') +
6761    	      ' d="M0 0h' + qrcodesize + 'v' + qrcodesize + 'H0z"/>';
6762
6763    	  const path =
6764    	    '<path ' + getColorAttrib(opts.color.dark, 'stroke') +
6765    	    ' d="' + qrToPath(data, size, opts.margin) + '"/>';
6766
6767    	  const viewBox = 'viewBox="' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '"';
6768
6769    	  const width = !opts.width ? '' : 'width="' + opts.width + '" height="' + opts.width + '" ';
6770
6771    	  const svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path + '</svg>\n';
6772
6773    	  if (typeof cb === 'function') {
6774    	    cb(null, svgTag);
6775    	  }
6776
6777    	  return svgTag
6778    	};
6779    	return svgTag;
6780    }
6781
6782    var hasRequiredBrowser;
6783
6784    function requireBrowser () {
6785    	if (hasRequiredBrowser) return browser;
6786    	hasRequiredBrowser = 1;
6787    	const canPromise = requireCanPromise();
6788
6789    	const QRCode = requireQrcode();
6790    	const CanvasRenderer = requireCanvas();
6791    	const SvgRenderer = requireSvgTag();
6792
6793    	function renderCanvas (renderFunc, canvas, text, opts, cb) {
6794    	  const args = [].slice.call(arguments, 1);
6795    	  const argsNum = args.length;
6796    	  const isLastArgCb = typeof args[argsNum - 1] === 'function';
6797
6798    	  if (!isLastArgCb && !canPromise()) {
6799    	    throw new Error('Callback required as last argument')
6800    	  }
6801
6802    	  if (isLastArgCb) {
6803    	    if (argsNum < 2) {
6804    	      throw new Error('Too few arguments provided')
6805    	    }
6806
6807    	    if (argsNum === 2) {
6808    	      cb = text;
6809    	      text = canvas;
6810    	      canvas = opts = undefined;
6811    	    } else if (argsNum === 3) {
6812    	      if (canvas.getContext && typeof cb === 'undefined') {
6813    	        cb = opts;
6814    	        opts = undefined;
6815    	      } else {
6816    	        cb = opts;
6817    	        opts = text;
6818    	        text = canvas;
6819    	        canvas = undefined;
6820    	      }
6821    	    }
6822    	  } else {
6823    	    if (argsNum < 1) {
6824    	      throw new Error('Too few arguments provided')
6825    	    }
6826
6827    	    if (argsNum === 1) {
6828    	      text = canvas;
6829    	      canvas = opts = undefined;
6830    	    } else if (argsNum === 2 && !canvas.getContext) {
6831    	      opts = text;
6832    	      text = canvas;
6833    	      canvas = undefined;
6834    	    }
6835
6836    	    return new Promise(function (resolve, reject) {
6837    	      try {
6838    	        const data = QRCode.create(text, opts);
6839    	        resolve(renderFunc(data, canvas, opts));
6840    	      } catch (e) {
6841    	        reject(e);
6842    	      }
6843    	    })
6844    	  }
6845
6846    	  try {
6847    	    const data = QRCode.create(text, opts);
6848    	    cb(null, renderFunc(data, canvas, opts));
6849    	  } catch (e) {
6850    	    cb(e);
6851    	  }
6852    	}
6853
6854    	browser.create = QRCode.create;
6855    	browser.toCanvas = renderCanvas.bind(null, CanvasRenderer.render);
6856    	browser.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL);
6857
6858    	// only svg for now.
6859    	browser.toString = renderCanvas.bind(null, function (data, _, opts) {
6860    	  return SvgRenderer.render(data, opts)
6861    	});
6862    	return browser;
6863    }
6864
6865    var browserExports = requireBrowser();
6866    var QRCode = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
6867
6868    var partnerUrlManager = new PartnerUrlManager(PARTNER_ID);
6869    var ClientId;
6870    (function (ClientId) {
6871        ClientId[ClientId["SPX"] = 2] = "SPX";
6872        ClientId[ClientId["CTL"] = 28] = "CTL";
6873    })(ClientId || (ClientId = {}));
6874    var clientId = ClientId.SPX;
6875    var getLoginRedirectPage = function () {
6876        // const currentOrigin = getCurrentOrigin();
6877        // const currentRegion = getRegion();
6878        // if (currentRegion === 'BR' && !window.location.pathname.includes(PaymentSettingRoute.path)) {
6879        //   // bank accounts
6880        //   return `${currentOrigin}/spx-admin/account/profile`;
6881        // }
6882        return window.location.href;
6883    };
6884    function getDomainSuffix() {
6885        var region = getRegion();
6886        switch (region) {
6887            case 'VN':
6888                return 'vn';
6889            case 'TH':
6890                return 'co.th';
6891            case 'ID':
6892                return 'co.id';
6893            case 'SG':
6894                return 'sg';
6895            case 'BR':
6896                return 'com.br';
6897            case 'MY':
6898                return 'com.my';
6899            case 'PH':
6900                return 'ph';
6901            default:
6902                return '';
6903        }
6904    }
6905    /**
6906     * Get environment prefix for URL construction
6907     * @param options Configuration options
6908     * @returns Environment prefix (e.g., 'test.', 'uat.', '')
6909     */
6910    function getEnvironmentPrefix(options) {
6911        if (options === void 0) { options = {}; }
6912        options.useDotSuffix;
6913        // Production environment - no prefix needed
6914        {
6915            return '';
6916        }
6917    }
6918    function getSpxServerOrigin() {
6919        var env = getEnvironmentPrefix();
6920        var suffix = getDomainSuffix();
6921        var domain = 'spx';
6922        return "https://".concat(env).concat(domain, ".").concat(suffix);
6923    }
6924    var getCurrentHostName = function () {
6925        var currentOrigin = getSpxServerOrigin();
6926        var urlObj = new URL(currentOrigin);
6927        return urlObj.hostname;
6928    };
6929    function getCurrentOrigin() {
6930        var currentOrigin = window.location.origin;
6931        if (instance.language === 'en') {
6932            currentOrigin += '/en';
6933        }
6934        return currentOrigin;
6935    }
6936    var getPortalLoginRedirectPage = function () {
6937        var currentOrigin = getCurrentOrigin();
6938        var currentRegion = getRegion();
6939        if (currentRegion === 'BR')
6940            return "".concat(currentOrigin, "/").concat(partnerUrlManager.partnerConfig.adminUrlPrefix, "/account/profile");
6941        // 标记从主页到shipment页面的链路,方便上报
6942        var fromHome = /^\/$|^\/en\/$/.test(location.pathname);
6943        var search = fromHome ? '?from=1' : '';
6944        return "".concat(currentOrigin, "/").concat(partnerUrlManager.partnerConfig.adminUrlPrefix).concat(search);
6945    };
6946    function redirectUrlFactory(path, redirectUrl, params) {
6947        var accountTeamOrigin = getAccountTeamOrigin();
6948        var url = "".concat(accountTeamOrigin).concat(path, "?next=").concat(encodeURIComponent(redirectUrl), "&client_id=").concat(clientId);
6949        if (params) {
6950            Object.keys(params).forEach(function (key) {
6951                url += "&".concat(key, "=").concat(params[key]);
6952            });
6953        }
6954        return url;
6955    }
6956    function getAccountTeamOrigin() {
6957        var env = getEnvironmentPrefix({ useDotSuffix: true });
6958        var suffix = getDomainSuffix();
6959        var currentRegion = getRegion();
6960        if (currentRegion === 'BR' || currentRegion === 'TW') {
6961            return "https://spx.business.accounts".concat(env, ".shopee.").concat(suffix);
6962        }
6963        return "https://account".concat(env, ".spx.").concat(suffix);
6964    }
6965    function getLoginUrl(defaultCurrentPage) {
6966        var currentPage = defaultCurrentPage || getLoginRedirectPage();
6967        var spxServerOrigin = getSpxServerOrigin();
6968        var spxRedirectUrl = "".concat(spxServerOrigin, "/shipment/account/api/login?redirect=").concat(encodeURIComponent(getUrlWithUtmParams(currentPage)));
6969        var redirectUrl = redirectUrlFactory('/authenticate/login', spxRedirectUrl, {
6970            should_hide_back: true,
6971            lang: getAccountLanguage(instance.language),
6972        });
6973        return redirectUrl;
6974    }
6975    function getPortalLoginUrl() {
6976        var redirectPage = getPortalLoginRedirectPage();
6977        return getLoginUrl(redirectPage);
6978    }
6979    var beforeRoutePortal = function (callback) {
6980        var _a, _b;
6981        var accountId = (_b = (_a = window.__NSS_CONTEXT__) === null || _a === void 0 ? void 0 : _a.userInfo) === null || _b === void 0 ? void 0 : _b.account_id;
6982        if (!accountId) {
6983            window.location.href = getPortalLoginUrl();
6984            return;
6985        }
6986        callback === null || callback === void 0 ? void 0 : callback();
6987    };
6988    var generateQR = function (url, options) { return __awaiter$7(void 0, void 0, void 0, function () {
6989        var err_1;
6990        return __generator$7(this, function (_a) {
6991            switch (_a.label) {
6992                case 0:
6993                    _a.trys.push([0, 2, , 3]);
6994                    return [4 /*yield*/, QRCode.toDataURL(url, options)];
6995                case 1: return [2 /*return*/, _a.sent()];
6996                case 2:
6997                    err_1 = _a.sent();
6998                    console.error(err_1);
6999                    return [3 /*break*/, 3];
7000                case 3: return [2 /*return*/];
7001            }
7002        });
7003    }); };
7004    var applyQRToImage = function (className, sourceUrl) { return __awaiter$7(void 0, void 0, void 0, function () {
7005        var images, url;
7006        return __generator$7(this, function (_a) {
7007            images = document.querySelectorAll(".".concat(className));
7008            if (images.length === 0)
7009                return [2 /*return*/];
7010            url = sourceUrl;
7011            if (!url) {
7012                images.forEach(function (image) {
7013                    if (image instanceof HTMLImageElement && !url) {
7014                        url = image.getAttribute('data-url') || '';
7015                        return;
7016                    }
7017                });
7018            }
7019            if (!url)
7020                return [2 /*return*/];
7021            images.forEach(function (image) { return __awaiter$7(void 0, void 0, void 0, function () {
7022                var dataUrl;
7023                return __generator$7(this, function (_a) {
7024                    switch (_a.label) {
7025                        case 0:
7026                            if (!(image instanceof HTMLImageElement)) return [3 /*break*/, 2];
7027                            return [4 /*yield*/, generateQR(url, {
7028                                    margin: 0,
7029                                    width: Number(image.getAttribute('data-width') || 100),
7030                                })];
7031                        case 1:
7032                            dataUrl = _a.sent();
7033                            if (!dataUrl)
7034                                return [2 /*return*/];
7035                            image.src = dataUrl;
7036                            _a.label = 2;
7037                        case 2: return [2 /*return*/];
7038                    }
7039                });
7040            }); });
7041            return [2 /*return*/];
7042        });
7043    }); };
7044    var getPreviewId = function () {
7045        return new URLSearchParams(location.search).get('previewV2');
7046    };
7047    /**
7048     * 检查 URL 中是否带有 bi=1 参数,用于隐藏头部
7049     * @param search - URL search string,Node.js 环境由调用方传入,浏览器可缺省使用 location.search
7050     */
7051    var shouldHideHeaderByBi = function (search) {
7052        var searchStr = search !== null && search !== void 0 ? search : (isRunIngInNodeEnv ? '' : location.search);
7053        return new URLSearchParams(searchStr).get('bi') === '1';
7054    };
7055    var getIsPreviewPage = function () {
7056        return new URLSearchParams(location.search).get('isPreviewPage') === 'true';
7057    };
7058    var proxyLinkHandler = function (e) {
7059        partnerUrlManager.proxyLinkClick(e, function (urlOject, defaultHandler) {
7060            if (partnerUrlManager.isNeedLoginUrl(urlOject)) {
7061                beforeRoutePortal(function () {
7062                    defaultHandler(urlOject);
7063                });
7064            }
7065            else {
7066                defaultHandler(urlOject);
7067            }
7068        });
7069    };
7070    var getServicePointHref = function () {
7071        return '/service-point';
7072    };
7073    var getCurrentUrlWithoutOrigin = function () {
7074        return window.location.pathname + window.location.search + window.location.hash;
7075    };
7076
7077    // import dropdownTemplate from '@/templates/common/dropdown/index.hbs'
7078    /**
7079     * 作用范围:同构模块
7080     * 在浏览器端,页面有加载 public/js/handlebars.runtime.js 文件,是一个全局变量
7081     * 在node环境下,是依赖 Handlebars 模块,默认没有global下的 Handlebars
7082     * 所以需要在global下注册了 Handlebars 模块 才调用 Handlebars.registerHelper.registerHelper,
7083     * 因此需要把这些 helper 放到函数里面,在 Handlebars ready 后再调用
7084     */
7085    var registerHelpers = function () {
7086        Handlebars.registerHelper('dataCount', function (data) {
7087            if (Array.isArray(data)) {
7088                return data.length;
7089            }
7090            if (typeof data === 'object') {
7091                return Object.keys(data).length;
7092            }
7093            return 0;
7094        });
7095        Handlebars.registerHelper('serviceCount', function (data) {
7096            if (!data || typeof data !== 'object' || Array.isArray(data)) {
7097                return 0;
7098            }
7099            // Trucking 仅作为隐藏的 hydration 占位卡片,不计入普通卡片的基础布局数量。
7100            data.tracking; data.checkFeePath; data.servicePointHref; data.trucking; var rest = __rest(data, ["tracking", "checkFeePath", "servicePointHref", "trucking"]);
7101            return Object.values(rest).filter(Boolean).length;
7102        });
7103        Handlebars.registerHelper('t', function (key) {
7104            return $gt(key) || key;
7105        });
7106        Handlebars.registerHelper('eq', function (a, b) {
7107            return a === b;
7108        });
7109        // Greater than comparison helper for banner template
7110        Handlebars.registerHelper('gt', function (a, b) {
7111            return a > b;
7112        });
7113        // Add numbers helper for banner template aria-labels
7114        Handlebars.registerHelper('add', function (a, b) {
7115            return (Number(a) || 0) + (Number(b) || 0);
7116        });
7117        // Subtract numbers helper for banner navigation
7118        Handlebars.registerHelper('subtract', function (a, b) {
7119            return (Number(a) || 0) - (Number(b) || 0);
7120        });
7121        // Modulo helper for banner circular navigation
7122        Handlebars.registerHelper('modulo', function (a, b) {
7123            return (Number(a) || 0) % (Number(b) || 1);
7124        });
7125        Handlebars.registerHelper('upper', function (str) {
7126            return typeof str === 'string' ? str.toUpperCase() : '';
7127        });
7128        Handlebars.registerHelper('lower', function (str) {
7129            return typeof str === 'string' ? str.toLowerCase() : '';
7130        });
7131        Handlebars.registerHelper('isTrue', function (value) {
7132            return !!value;
7133        });
7134        Handlebars.registerHelper('isFalse', function (value) {
7135            return !value;
7136        });
7137        Handlebars.registerHelper('menuActive', function (menuItem, pagePath, type) {
7138            if (type === void 0) { type = 'sub'; }
7139            if (!menuItem || !pagePath)
7140                return false;
7141            var currentHostName = isRunIngInNodeEnv ? getCurrentHostName() : undefined;
7142            if (type === 'sub') {
7143                // For sub menu items, check direct link_url match
7144                return judgeUrlPathEqual(menuItem.link_url, pagePath, currentHostName);
7145            }
7146            else if (type === 'main') {
7147                // For main menu items, check if any sub_menu item matches
7148                if (menuItem.sub_menu && Array.isArray(menuItem.sub_menu)) {
7149                    return menuItem.sub_menu.some(function (subItem) {
7150                        return judgeUrlPathEqual(subItem.link_url, pagePath, currentHostName);
7151                    });
7152                }
7153                if (menuItem.main_menu && menuItem.main_menu[0]) {
7154                    return judgeUrlPathEqual(menuItem.main_menu[0].link_url, pagePath, currentHostName);
7155                }
7156            }
7157            return false;
7158        });
7159        Handlebars.registerHelper('blankImg', function () {
7160            return 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
7161        });
7162        // spx站内域名当前页跳转,外链新窗跳转
7163        Handlebars.registerHelper('linkTarget', function (url) {
7164            if (!url || typeof url !== 'string')
7165                return '_self';
7166            if (!url.startsWith('https://')) {
7167                return '_self';
7168            }
7169            var isNssWebsiteUrl = partnerUrlManager.currentWebsiteUrls.some(function (prefix) {
7170                return url.startsWith(prefix);
7171            });
7172            return isNssWebsiteUrl ? '_self' : '_blank';
7173        });
7174        // Show banner overlay if there are multiple slides OR if there's a page title
7175        Handlebars.registerHelper('shouldShowBannerOverlay', function (itemListLength, pageTitle) {
7176            return itemListLength > 1 || !!pageTitle;
7177        });
7178    };
7179    // export const registerPartials = () => {
7180    //   Handlebars.registerPartial('dropdown', dropdownTemplate)
7181    // }
7182
7183    var RE_TOKEN_LIST_VALUE = /^(?:\d)+/;
7184    var RE_TOKEN_NAMED_VALUE = /^(?:\w)+/;
7185    // 去除翻译里面的多余花括号,已经花括号内的空格
7186    function trimStr(str) {
7187        if (!str) {
7188            return str;
7189        }
7190        var reg3 = /{{{\s*(.*?)\s*}}}/g;
7191        var reg2 = /{{\s*(.*?)\s*}}/g;
7192        str = str.replace(reg3, function (m, n) { return '{' + n + '}'; });
7193        str = str.replace(reg2, function (m, n) { return '{' + n + '}'; });
7194        return str;
7195    }
7196    function parse(format) {
7197        format = trimStr(format);
7198        var tokens = [];
7199        var position = 0;
7200        var text = '';
7201        while (position < format.length) {
7202            var char = format[position++];
7203            if (char === '{') {
7204                if (text) {
7205                    tokens.push({ type: 'text', value: text });
7206                }
7207                text = '';
7208                var sub = '';
7209                char = format[position++];
7210                while (char !== undefined && char !== '}') {
7211                    sub += char;
7212                    char = format[position++];
7213                }
7214                var isClosed = char === '}';
7215                var type = RE_TOKEN_LIST_VALUE.test(sub)
7216                    ? 'list'
7217                    : isClosed && RE_TOKEN_NAMED_VALUE.test(sub)
7218                        ? 'named'
7219                        : 'unknown';
7220                tokens.push({ value: sub, type: type });
7221            }
7222            else if (char === '%') {
7223                // when found rails i18n syntax, skip text capture
7224                if (format[position] !== '{') {
7225                    text += char;
7226                }
7227            }
7228            else {
7229                text += char;
7230            }
7231        }
7232        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
7233        text && tokens.push({ type: 'text', value: text });
7234        return tokens;
7235    }
7236    function isObject(obj) {
7237        return obj !== null && typeof obj === 'object';
7238    }
7239    function compile(tokens, values) {
7240        var compiled = [];
7241        var index = 0;
7242        var mode = Array.isArray(values) ? 'list' : isObject(values) ? 'named' : 'unknown';
7243        if (mode === 'unknown') {
7244            return compiled;
7245        }
7246        while (index < tokens.length) {
7247            var token = tokens[index];
7248            switch (token.type) {
7249                case 'text':
7250                    compiled.push(token.value);
7251                    break;
7252                case 'list':
7253                    // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
7254                    compiled.push(values[parseInt(token.value, 10)]);
7255                    break;
7256                case 'named':
7257                    if (mode === 'named') {
7258                        // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
7259                        compiled.push(values[token.value]);
7260                    }
7261                    break;
7262                case 'unknown':
7263                    console.warn("Detect 'unknown' type of token!");
7264                    break;
7265            }
7266            index++;
7267        }
7268        return compiled;
7269    }
7270    function interpolate(message, values, mode) {
7271        if (mode === void 0) { mode = 'string'; }
7272        if (!values || typeof message !== 'string') {
7273            return message;
7274        }
7275        var tokens = parse(message);
7276        var ret = compile(tokens, values);
7277        return mode === 'string' && typeof ret !== 'string' ? ret.join('') : ret;
7278    }
7279
7280    // https://deo.shopeesz.com/shopee/shopee-seller-live-sg/tsp/api/
7281    // https://deo.shopeemobile.com/shopee/shopee-seller-live-sg/tsp/api/
7282    var getSuffix = function (env, sep) { return (['live', 'stable'].includes(env) ? '' : sep + 'nonlive'); };
7283    var apiBase = function (env, cn, region) {
7284        var s = getSuffix(env, '/');
7285        if (cn) {
7286            return "https://seller.sg.shopee.cn/api/tsp".concat(s);
7287        }
7288        else if (region === 'br') {
7289            return "https://seller.shopee.com.br/api/tsp".concat(s);
7290        }
7291        return "https://seller.shopee.sg/api/tsp".concat(s);
7292    };
7293    var cdnBase$1 = function (env, cn) {
7294        var s = getSuffix(env, '-');
7295        return "https://deo.shopee".concat(cn ? 'sz' : 'mobile', ".com/shopee/shopee-seller-live-sg/tsp/api").concat(s);
7296    };
7297
7298    var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
7299        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
7300        return new (P || (P = Promise))(function (resolve, reject) {
7301            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7302            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7303            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7304            step((generator = generator.apply(thisArg, _arguments || [])).next());
7305        });
7306    };
7307    var __generator$6 = (undefined && undefined.__generator) || function (thisArg, body) {
7308        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
7309        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
7310        function verb(n) { return function (v) { return step([n, v]); }; }
7311        function step(op) {
7312            if (f) throw new TypeError("Generator is already executing.");
7313            while (g && (g = 0, op[0] && (_ = 0)), _) try {
7314                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
7315                if (y = 0, t) op = [op[0] & 2, t.value];
7316                switch (op[0]) {
7317                    case 0: case 1: t = op; break;
7318                    case 4: _.label++; return { value: op[1], done: false };
7319                    case 5: _.label++; y = op[1]; op = [0]; continue;
7320                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
7321                    default:
7322                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
7323                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
7324                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
7325                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
7326                        if (t[2]) _.ops.pop();
7327                        _.trys.pop(); continue;
7328                }
7329                op = body.call(thisArg, _);
7330            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
7331            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
7332        }
7333    };
7334    /**
7335     * CN CDN uses https://deo.shopeesz.com/shopee/stm-sg-live/tsp-migration-20251105/en.col1431.1764586458047.json
7336     * Non-CN CDN uses https://deo.shopeemobile.com/shopee/stm-sg-live/shopee-mobilemall-live-sg/nonlive/en.col8.1760512595.json
7337     * nonlive suffix is only used for non-live environment and prefixed before the filename.
7338     */
7339    var cdnBase = function (cdnPath, env, cn) {
7340        var envSuffix = ['live', 'stable'].includes(env) ? '' : 'nonlive/';
7341        return "https://deo.shopee".concat(cn ? 'sz' : 'mobile', ".com/shopee/stm-sg-live/").concat(cdnPath, "/").concat(envSuffix);
7342    };
7343    /**
7344     * This class will fetch translations from UTM CDN only.
7345     */
7346    var APIV2 = /** @class */ (function () {
7347        function APIV2(options) {
7348            var _this = this;
7349            this.getTranslationFromCDN = function (args) { return __awaiter$6(_this, void 0, void 0, function () {
7350                var fileName;
7351                return __generator$6(this, function (_a) {
7352                    fileName = this.getFileName(args);
7353                    return [2 /*return*/, this.fetch({ url: "".concat(this.cdnBase).concat(fileName) })];
7354                });
7355            }); };
7356            this.cdnBase = cdnBase(options.cdnPath, options.env, options.isMainland);
7357            this.fetch = options.fetch;
7358        }
7359        APIV2.prototype.getFileName = function (_a) {
7360            var langCode = _a.langCode, id = _a.id, hash = _a.hash;
7361            return "".concat(langCode.toLowerCase(), ".col").concat(id).concat(hash ? ".".concat(hash) : '', ".json");
7362        };
7363        return APIV2;
7364    }());
7365
7366    var __assign$2 = (undefined && undefined.__assign) || function () {
7367        __assign$2 = Object.assign || function(t) {
7368            for (var s, i = 1, n = arguments.length; i < n; i++) {
7369                s = arguments[i];
7370                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7371                    t[p] = s[p];
7372            }
7373            return t;
7374        };
7375        return __assign$2.apply(this, arguments);
7376    };
7377    var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
7378        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
7379        return new (P || (P = Promise))(function (resolve, reject) {
7380            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7381            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7382            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7383            step((generator = generator.apply(thisArg, _arguments || [])).next());
7384        });
7385    };
7386    var __generator$5 = (undefined && undefined.__generator) || function (thisArg, body) {
7387        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
7388        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
7389        function verb(n) { return function (v) { return step([n, v]); }; }
7390        function step(op) {
7391            if (f) throw new TypeError("Generator is already executing.");
7392            while (g && (g = 0, op[0] && (_ = 0)), _) try {
7393                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
7394                if (y = 0, t) op = [op[0] & 2, t.value];
7395                switch (op[0]) {
7396                    case 0: case 1: t = op; break;
7397                    case 4: _.label++; return { value: op[1], done: false };
7398                    case 5: _.label++; y = op[1]; op = [0]; continue;
7399                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
7400                    default:
7401                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
7402                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
7403                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
7404                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
7405                        if (t[2]) _.ops.pop();
7406                        _.trys.pop(); continue;
7407                }
7408                op = body.call(thisArg, _);
7409            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
7410            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
7411        }
7412    };
7413    var CdnManager = /** @class */ (function () {
7414        function CdnManager(options) {
7415            this.cdnPathApiMap = {};
7416            this.collectionHashes = {};
7417            this.cdnPathCollectionIdMap = {};
7418            this.defaultCdnPath = options.defaultCdnPath;
7419            this.fetch = options.fetch;
7420            this.env = options.env;
7421            this.isMainland = options.isMainland;
7422            this.cdnPathApiMap[this.defaultCdnPath] = new APIV2({
7423                cdnPath: this.defaultCdnPath,
7424                env: options.env,
7425                isMainland: options.isMainland,
7426                fetch: options.fetch,
7427            });
7428        }
7429        CdnManager.prototype.getTranslationFromCDN = function (_a) {
7430            var _b, _c;
7431            var id = _a.id, langCode = _a.langCode;
7432            return __awaiter$5(this, void 0, void 0, function () {
7433                var normalizedLangCode, cdnPath, cdnApi, hash;
7434                return __generator$5(this, function (_d) {
7435                    normalizedLangCode = langCode.toLowerCase();
7436                    cdnPath = this.getCdnPath(id);
7437                    cdnApi = this.cdnPathApiMap[cdnPath];
7438                    if (!cdnApi) {
7439                        // This should never happen if initializeCdnPathApiMap was called correctly,
7440                        // but adding a safety check to prevent runtime errors
7441                        throw new Error("CDN API not initialized for path: ".concat(cdnPath));
7442                    }
7443                    hash = (_c = (_b = this.collectionHashes[id]) === null || _b === void 0 ? void 0 : _b[normalizedLangCode]) !== null && _c !== void 0 ? _c : '';
7444                    return [2 /*return*/, cdnApi.getTranslationFromCDN({ langCode: normalizedLangCode, id: id, hash: hash })];
7445                });
7446            });
7447        };
7448        /**
7449         * Update the CDN path to collection ID mapping.
7450         * This should be called when new modules are loaded.
7451         */
7452        CdnManager.prototype.updateCdnPathCollectionIdMap = function (cdnPathCollectionIdMap) {
7453            this.setCdnPathCollectionIdMap(cdnPathCollectionIdMap);
7454            this.setCdnPathApiMap();
7455        };
7456        /**
7457         * Update the collection hashes.
7458         * This should be called when new modules are loaded.
7459         */
7460        CdnManager.prototype.updateCollectionHashes = function (collectionHashes) {
7461            this.setCollectionHashes(collectionHashes);
7462        };
7463        CdnManager.prototype.getCdnPath = function (id) {
7464            for (var _i = 0, _a = Object.keys(this.cdnPathCollectionIdMap); _i < _a.length; _i++) {
7465                var cdnPath = _a[_i];
7466                if (this.cdnPathCollectionIdMap[cdnPath].has(id)) {
7467                    return cdnPath;
7468                }
7469            }
7470            return this.defaultCdnPath;
7471        };
7472        CdnManager.prototype.setCdnPathCollectionIdMap = function (cdnPathCollectionIdMap) {
7473            for (var _i = 0, _a = Object.keys(cdnPathCollectionIdMap); _i < _a.length; _i++) {
7474                var cdnPath = _a[_i];
7475                if (!this.cdnPathCollectionIdMap[cdnPath]) {
7476                    this.cdnPathCollectionIdMap[cdnPath] = new Set();
7477                }
7478                for (var _b = 0, _c = cdnPathCollectionIdMap[cdnPath]; _b < _c.length; _b++) {
7479                    var id = _c[_b];
7480                    this.cdnPathCollectionIdMap[cdnPath].add(id);
7481                }
7482            }
7483        };
7484        CdnManager.prototype.setCollectionHashes = function (collectionHashes) {
7485            var storeCollectionHashes = this.parseCollectionHashes(collectionHashes);
7486            this.collectionHashes = __assign$2(__assign$2({}, this.collectionHashes), storeCollectionHashes);
7487        };
7488        /**
7489         * Parse a mapping from '<langCode>-<env>-<id>' → hash into a
7490         * nested mapping of id → langCode → hash.
7491         * @param collectionHashes
7492         * @returns {StoreCollectionHashes}
7493         */
7494        CdnManager.prototype.parseCollectionHashes = function (collectionHashes) {
7495            var _a;
7496            var storeCollectionHashes = {};
7497            for (var _i = 0, _b = Object.keys(collectionHashes); _i < _b.length; _i++) {
7498                var langCodeRaw = _b[_i];
7499                var langCode = langCodeRaw.toLowerCase();
7500                var entries = (_a = collectionHashes[langCodeRaw]) === null || _a === void 0 ? void 0 : _a.timestamps;
7501                if (!entries) {
7502                    continue;
7503                }
7504                for (var _c = 0, entries_1 = entries; _c < entries_1.length; _c++) {
7505                    var entry = entries_1[_c];
7506                    if (!entry) {
7507                        continue;
7508                    }
7509                    var id = entry.id, timestamp = entry.timestamp;
7510                    if (!storeCollectionHashes[id]) {
7511                        storeCollectionHashes[id] = {};
7512                    }
7513                    storeCollectionHashes[id][langCode] = String(timestamp);
7514                }
7515            }
7516            return storeCollectionHashes;
7517        };
7518        CdnManager.prototype.setCdnPathApiMap = function () {
7519            for (var _i = 0, _a = Object.keys(this.cdnPathCollectionIdMap); _i < _a.length; _i++) {
7520                var cdnPath = _a[_i];
7521                if (!this.cdnPathApiMap[cdnPath]) {
7522                    this.cdnPathApiMap[cdnPath] = new APIV2({
7523                        cdnPath: cdnPath,
7524                        env: this.env,
7525                        isMainland: this.isMainland,
7526                        fetch: this.fetch,
7527                    });
7528                }
7529            }
7530        };
7531        return CdnManager;
7532    }());
7533
7534    // import { MdapSdk, CustomPlugin } from '@mdap/javascript-sdk';
7535    // let customName: string = '';
7536    // let customReporter: CustomPlugin;
7537    // const secretKeys = {
7538    //   live: '73c575ca86b204fac81be2de8bf505b14acd63a6e4755e84e9deba44e1253188',
7539    //   test: '32b004a142233cc3d292ab2698035ed27a05460cebbd45a6e5b631de40f6b21d',
7540    // };
7541    // export const initReporter = (options: any) => {
7542    //   try {
7543    //     const env = options.env || 'live';
7544    //     const region = options.region || 'sg';
7545    //     customName = options.name || '';
7546    //     const sdk = new MdapSdk({
7547    //       app_name: 'tsp-web',
7548    //       secret_key: (secretKeys as any)[env] || secretKeys.test,
7549    //       // environment值为 ‘live’ 时,数据会上报到正服环境 https://mdap.shopee.io, 为其他值时数据会上报到测服  https://mdap.exp.shopee.io
7550    //       environment: env,
7551    //       // 上报地区/Reporting Region | sg | tw | ph | th | id | my | br | mx | ...
7552    //       region: region,
7553    //       // 是否开启调试日志/Toggle of debug logger | default - false
7554    //       logger: false,
7555    //       // 业务应用版本 business application version
7556    //       app_version: 'undefined',
7557    //       // sampling rate 采样率 - default 0.1 | 采样率控制sdk是否采样开启,如果采样命中则全引用的插件生效,否则全部不生效,采样结果会在下一次启动时(刷新或新开tab)生效 Sampling result will be effective at next startup (refresh page OR open a new tab)
7558    //       sample: 0.1
7559    //     });
7560    //     customReporter = new CustomPlugin({});
7561    //     sdk.use(customReporter);
7562    //   } catch (e) {}
7563    // }
7564    var report = function (id, value, categories) {
7565    };
7566
7567    var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
7568        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
7569        return new (P || (P = Promise))(function (resolve, reject) {
7570            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7571            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7572            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7573            step((generator = generator.apply(thisArg, _arguments || [])).next());
7574        });
7575    };
7576    var __generator$4 = (undefined && undefined.__generator) || function (thisArg, body) {
7577        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
7578        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
7579        function verb(n) { return function (v) { return step([n, v]); }; }
7580        function step(op) {
7581            if (f) throw new TypeError("Generator is already executing.");
7582            while (g && (g = 0, op[0] && (_ = 0)), _) try {
7583                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
7584                if (y = 0, t) op = [op[0] & 2, t.value];
7585                switch (op[0]) {
7586                    case 0: case 1: t = op; break;
7587                    case 4: _.label++; return { value: op[1], done: false };
7588                    case 5: _.label++; y = op[1]; op = [0]; continue;
7589                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
7590                    default:
7591                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
7592                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
7593                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
7594                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
7595                        if (t[2]) _.ops.pop();
7596                        _.trys.pop(); continue;
7597                }
7598                op = body.call(thisArg, _);
7599            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
7600            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
7601        }
7602    };
7603    function measureTime(id) {
7604        return function (target, key, descriptor) {
7605            var origin = descriptor.value;
7606            descriptor.value = function () {
7607                var args = [];
7608                for (var _i = 0; _i < arguments.length; _i++) {
7609                    args[_i] = arguments[_i];
7610                }
7611                return __awaiter$4(this, void 0, void 0, function () {
7612                    var t, res;
7613                    return __generator$4(this, function (_a) {
7614                        switch (_a.label) {
7615                            case 0:
7616                                t = 0;
7617                                if (typeof window !== 'undefined' && typeof performance !== 'undefined') {
7618                                    t = performance.now();
7619                                }
7620                                return [4 /*yield*/, origin.apply(this, args)];
7621                            case 1:
7622                                res = _a.sent();
7623                                if (typeof window !== 'undefined' && typeof performance !== 'undefined') {
7624                                    report(id, performance.now() - t);
7625                                }
7626                                return [2 /*return*/, res];
7627                        }
7628                    });
7629                });
7630            };
7631        };
7632    }
7633
7634    var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
7635        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
7636        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
7637        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
7638        return c > 3 && r && Object.defineProperty(target, key, r), r;
7639    };
7640    var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
7641        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
7642        return new (P || (P = Promise))(function (resolve, reject) {
7643            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7644            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7645            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7646            step((generator = generator.apply(thisArg, _arguments || [])).next());
7647        });
7648    };
7649    var __generator$3 = (undefined && undefined.__generator) || function (thisArg, body) {
7650        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
7651        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
7652        function verb(n) { return function (v) { return step([n, v]); }; }
7653        function step(op) {
7654            if (f) throw new TypeError("Generator is already executing.");
7655            while (g && (g = 0, op[0] && (_ = 0)), _) try {
7656                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
7657                if (y = 0, t) op = [op[0] & 2, t.value];
7658                switch (op[0]) {
7659                    case 0: case 1: t = op; break;
7660                    case 4: _.label++; return { value: op[1], done: false };
7661                    case 5: _.label++; y = op[1]; op = [0]; continue;
7662                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
7663                    default:
7664                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
7665                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
7666                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
7667                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
7668                        if (t[2]) _.ops.pop();
7669                        _.trys.pop(); continue;
7670                }
7671                op = body.call(thisArg, _);
7672            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
7673            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
7674        }
7675    };
7676    var promises = {};
7677    var getURL = function (_a) {
7678        var url = _a.url, params = _a.params;
7679        var urlObj = new URL(url);
7680        if (params) {
7681            for (var _i = 0, _b = Object.keys(params); _i < _b.length; _i++) {
7682                var key = _b[_i];
7683                urlObj.searchParams.append(key, params[key]);
7684            }
7685        }
7686        urlObj.searchParams.sort();
7687        return urlObj.toString();
7688    };
7689    var API = /** @class */ (function () {
7690        function API(options) {
7691            var _this = this;
7692            this.getTranslationFromAPI = function (_a) {
7693                var language = _a.language, type = _a.type, id = _a.id, keys = _a.keys, hash = _a.hash;
7694                return __awaiter$3(_this, void 0, void 0, function () {
7695                    var params, options, key, res;
7696                    var _b;
7697                    return __generator$3(this, function (_c) {
7698                        switch (_c.label) {
7699                            case 0:
7700                                params = (_b = {}, _b["".concat(type, "_id")] = id, _b.language = language, _b.keys = keys, _b.hash = hash, _b);
7701                                options = { url: "".concat(this.apiBase, "/transify"), params: params };
7702                                key = getURL(options);
7703                                if (!promises[key]) {
7704                                    promises[key] = this.fetch(options);
7705                                }
7706                                _c.label = 1;
7707                            case 1:
7708                                _c.trys.push([1, , 3, 4]);
7709                                return [4 /*yield*/, promises[key]];
7710                            case 2:
7711                                res = _c.sent();
7712                                return [2 /*return*/, res];
7713                            case 3:
7714                                delete promises[key];
7715                                return [7 /*endfinally*/];
7716                            case 4: return [2 /*return*/];
7717                        }
7718                    });
7719                });
7720            };
7721            this.getTranslationFromCDN = function (args) { return __awaiter$3(_this, void 0, void 0, function () {
7722                var fileName;
7723                return __generator$3(this, function (_a) {
7724                    fileName = this.getFileName(args);
7725                    return [2 /*return*/, this.fetch({ url: "".concat(this.cdnBase, "/").concat(fileName) })];
7726                });
7727            }); };
7728            var cn = options.isMainland || options.region === 'cn';
7729            this.apiBase = apiBase(options.env, cn, options.region);
7730            this.cdnBase = cdnBase$1(options.env, cn);
7731            this.fetch = options.fetch;
7732        }
7733        API.prototype.init = function (language, mod) {
7734            var _a, _b;
7735            return __awaiter$3(this, void 0, void 0, function () {
7736                var params, data;
7737                return __generator$3(this, function (_c) {
7738                    switch (_c.label) {
7739                        case 0:
7740                            _c.trys.push([0, 2, , 3]);
7741                            params = {
7742                                language: language,
7743                                projectId: mod.projectId,
7744                                resources: (_a = mod.resources) === null || _a === void 0 ? void 0 : _a.join(';'),
7745                                collections: (_b = mod.collections) === null || _b === void 0 ? void 0 : _b.join(';'),
7746                            };
7747                            return [4 /*yield*/, this.fetch({
7748                                    url: "".concat(this.apiBase, "/init"),
7749                                    params: params,
7750                                })];
7751                        case 1:
7752                            data = _c.sent();
7753                            return [2 /*return*/, data.body || {}];
7754                        case 2:
7755                            _c.sent();
7756                            return [2 /*return*/, {}];
7757                        case 3: return [2 /*return*/];
7758                    }
7759                });
7760            });
7761        };
7762        API.prototype.getFileName = function (_a) {
7763            var type = _a.type, language = _a.language, id = _a.id, hash = _a.hash;
7764            // 取type的第一个字符
7765            var t = "".concat(type[0], "_").concat(id, "_").concat(language.toLowerCase());
7766            return hash ? "".concat(t, "_").concat(hash, ".js") : "".concat(t, ".json");
7767        };
7768        __decorate$1([
7769            measureTime('5d42f2badb8e75f819c0b005535c8dc3')
7770        ], API.prototype, "init", null);
7771        return API;
7772    }());
7773
7774    var TIMEOUT_MS = 3000;
7775    function rejectAfterDelay(milliseconds) {
7776        var timeoutId = null;
7777        var promise = new Promise(function (_, reject) {
7778            timeoutId = setTimeout(function () {
7779                reject(new Error('Timeout'));
7780            }, milliseconds);
7781        });
7782        return {
7783            promise: promise,
7784            clearTimeout: function () {
7785                if (timeoutId !== null) {
7786                    clearTimeout(timeoutId);
7787                    timeoutId = null;
7788                }
7789            },
7790        };
7791    }
7792    function allSettled(promises) {
7793        if (promises.length === 0) {
7794            return Promise.resolve([]);
7795        }
7796        return new Promise(function (resolve) {
7797            var results = new Array(promises.length);
7798            var timeoutCleanups = [];
7799            var settledCount = 0;
7800            var isResolved = false;
7801            var checkSettled = function () {
7802                // Atomically increment and check to prevent race conditions
7803                if (++settledCount === promises.length && !isResolved) {
7804                    isResolved = true;
7805                    // Clear all remaining timeouts
7806                    timeoutCleanups.forEach(function (cleanup) {
7807                        cleanup();
7808                    });
7809                    resolve(results);
7810                }
7811            };
7812            promises.forEach(function (promise, index) {
7813                var _a = rejectAfterDelay(TIMEOUT_MS), timeoutPromise = _a.promise, clearTimeout = _a.clearTimeout;
7814                timeoutCleanups.push(clearTimeout);
7815                Promise.race([promise, timeoutPromise])
7816                    .then(function (value) {
7817                    clearTimeout(); // Clear timeout when promise resolves
7818                    results[index] = { status: 'fulfilled', value: value };
7819                    checkSettled();
7820                })
7821                    .catch(function (error) {
7822                    clearTimeout(); // Clear timeout when promise rejects or times out
7823                    results[index] = { status: 'rejected', error: error };
7824                    checkSettled();
7825                });
7826            });
7827        });
7828    }
7829
7830    var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
7831        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
7832        return new (P || (P = Promise))(function (resolve, reject) {
7833            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7834            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7835            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7836            step((generator = generator.apply(thisArg, _arguments || [])).next());
7837        });
7838    };
7839    var __generator$2 = (undefined && undefined.__generator) || function (thisArg, body) {
7840        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
7841        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
7842        function verb(n) { return function (v) { return step([n, v]); }; }
7843        function step(op) {
7844            if (f) throw new TypeError("Generator is already executing.");
7845            while (g && (g = 0, op[0] && (_ = 0)), _) try {
7846                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
7847                if (y = 0, t) op = [op[0] & 2, t.value];
7848                switch (op[0]) {
7849                    case 0: case 1: t = op; break;
7850                    case 4: _.label++; return { value: op[1], done: false };
7851                    case 5: _.label++; y = op[1]; op = [0]; continue;
7852                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
7853                    default:
7854                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
7855                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
7856                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
7857                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
7858                        if (t[2]) _.ops.pop();
7859                        _.trys.pop(); continue;
7860                }
7861                op = body.call(thisArg, _);
7862            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
7863            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
7864        }
7865    };
7866    var tokens = {};
7867    var i = 0;
7868    var getToken = function () { return "delay_token_".concat(i++); };
7869    var CmdToken = {
7870        source: function () {
7871            var token = getToken();
7872            var cancel = function () {
7873                var _a;
7874                clearTimeout((_a = tokens[token]) === null || _a === void 0 ? void 0 : _a.timer);
7875                delete tokens[token];
7876            };
7877            var execute = function () {
7878                var t = tokens[token];
7879                if (t) {
7880                    clearTimeout(t.timer);
7881                    return t.fn();
7882                }
7883            };
7884            return { token: token, cancel: cancel, execute: execute };
7885        },
7886    };
7887    var delayExec = function (fn, timeout, cmdToken) { return __awaiter$2(void 0, void 0, void 0, function () {
7888        return __generator$2(this, function (_a) {
7889            return [2 /*return*/, new Promise(function (resolve, reject) {
7890                    var timer = setTimeout(function () {
7891                        fn().then(resolve).catch(reject);
7892                    }, timeout);
7893                    if (cmdToken) {
7894                        tokens[cmdToken] = { timer: timer, fn: fn };
7895                    }
7896                })];
7897        });
7898    }); };
7899
7900    var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
7901        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
7902        return new (P || (P = Promise))(function (resolve, reject) {
7903            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7904            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7905            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7906            step((generator = generator.apply(thisArg, _arguments || [])).next());
7907        });
7908    };
7909    var __generator$1 = (undefined && undefined.__generator) || function (thisArg, body) {
7910        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
7911        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
7912        function verb(n) { return function (v) { return step([n, v]); }; }
7913        function step(op) {
7914            if (f) throw new TypeError("Generator is already executing.");
7915            while (g && (g = 0, op[0] && (_ = 0)), _) try {
7916                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
7917                if (y = 0, t) op = [op[0] & 2, t.value];
7918                switch (op[0]) {
7919                    case 0: case 1: t = op; break;
7920                    case 4: _.label++; return { value: op[1], done: false };
7921                    case 5: _.label++; y = op[1]; op = [0]; continue;
7922                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
7923                    default:
7924                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
7925                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
7926                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
7927                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
7928                        if (t[2]) _.ops.pop();
7929                        _.trys.pop(); continue;
7930                }
7931                op = body.call(thisArg, _);
7932            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
7933            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
7934        }
7935    };
7936    var SUCCESS_STATUS = 200;
7937    var tryParse = function (data) {
7938        try {
7939            return JSON.parse(data);
7940        }
7941        catch (e) {
7942            return data;
7943        }
7944    };
7945    var get = function (_a) {
7946        var url = _a.url, params = _a.params, timeout = _a.timeout;
7947        return __awaiter$1(void 0, void 0, void 0, function () {
7948            var key, request, timeoutPromise, res, data, headers;
7949            return __generator$1(this, function (_b) {
7950                switch (_b.label) {
7951                    case 0:
7952                        if (typeof window === 'undefined')
7953                            throw new Error('window is not available in node environment. Please pass in a fetch method as createOptions.fetch');
7954                        if (typeof params === 'number') {
7955                            timeout = params;
7956                            params = {};
7957                        }
7958                        for (key in params) {
7959                            if (!params[key]) {
7960                                // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
7961                                delete params[key];
7962                            }
7963                        }
7964                        if (params && Object.keys(params).length) {
7965                            url = "".concat(url, "?").concat(new 
7965URLSearchParams(params).toString());
7966                        }
7967                        if (timeout) {
7968                            timeoutPromise = new Promise(function (resolve, reject) {
7969                                setTimeout(function () {
7970                                    reject('TSP Request Timeout');
7971                                }, timeout);
7972                            });
7973                            request = Promise.race([timeoutPromise, fetch(url)]);
7974                        }
7975                        else {
7976                            request = fetch(url);
7977                        }
7978                        return [4 /*yield*/, request];
7979                    case 1:
7980                        res = _b.sent();
7981                        return [4 /*yield*/, res.json()];
7982                    case 2:
7983                        data = _b.sent();
7984                        headers = {};
7985                        res.headers.forEach(function (value, key) { return (headers[key] = value); });
7986                        if (res.status !== SUCCESS_STATUS) {
7987                            throw new Error(data);
7988                        }
7989                        return [2 /*return*/, {
7990                                headers: headers,
7991                                body: tryParse(data),
7992                            }];
7993                }
7994            });
7995        });
7996    };
7997
7998    // 各种语言的单复数规则
7999    // @see https://unicode-org.github.io/cldr-staging/charts/latest/supplemental/language_plural_rules.html
8000    /**
8001     * french
8002     */
8003    var fr = function (n) {
8004        if (n === 0 || n === 1) {
8005            return 'one';
8006        }
8007        if (n >= 1e6) {
8008            return 'many';
8009        }
8010        return 'other';
8011    };
8012    /**
8013     * polish
8014     */
8015    var pl = function (n) {
8016        if (n === 1) {
8017            return 'one';
8018        }
8019        if (!Number.isInteger(n)) {
8020            return 'other';
8021        }
8022        if ([2, 3, 4].includes(n % 10) && ![12, 13, 14].includes(n % 100)) {
8023            return 'few';
8024        }
8025        if (![2, 3, 4].includes(n % 10) || [12, 13, 14].includes(n % 100)) {
8026            return 'many';
8027        }
8028        return 'other';
8029    };
8030    /**
8031     * english, default
8032     */
8033    var en = function (n) {
8034        if (n === 0) {
8035            return 'zero';
8036        }
8037        if (n === 1) {
8038            return 'one';
8039        }
8040        return 'other';
8041    };
8042    var handler = { fr: fr, pl: pl, en: en };
8043
8044    var __assign$1 = (undefined && undefined.__assign) || function () {
8045        __assign$1 = Object.assign || function(t) {
8046            for (var s, i = 1, n = arguments.length; i < n; i++) {
8047                s = arguments[i];
8048                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
8049                    t[p] = s[p];
8050            }
8051            return t;
8052        };
8053        return __assign$1.apply(this, arguments);
8054    };
8055    var __spreadArray$1 = (undefined && undefined.__spreadArray) || function (to, from, pack) {
8056        if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
8057            if (ar || !(i in from)) {
8058                if (!ar) ar = Array.prototype.slice.call(from, 0, i);
8059                ar[i] = from[i];
8060            }
8061        }
8062        return to.concat(ar || Array.prototype.slice.call(from));
8063    };
8064    var Store = /** @class */ (function () {
8065        function Store() {
8066            this.utmCollectionHashMap = {};
8067            this.utmCollectionCdnMap = {};
8068        }
8069        Store.prototype.setDefaultCdnPath = function (defaultCdnPath) {
8070            this.defaultCdnPath = defaultCdnPath;
8071        };
8072        Store.prototype.setCollectionHashMap = function (collectionHashMap) {
8073            if (!collectionHashMap) {
8074                return;
8075            }
8076            // Deep clone the existing hash map
8077            var clonedExisting = {};
8078            for (var _i = 0, _a = Object.keys(this.utmCollectionHashMap); _i < _a.length; _i++) {
8079                var langCode = _a[_i];
8080                var existingEntry = this.utmCollectionHashMap[langCode];
8081                if (existingEntry === null || existingEntry === void 0 ? void 0 : existingEntry.timestamps) {
8082                    clonedExisting[langCode] = {
8083                        timestamps: existingEntry.timestamps.map(function (entry) { return (__assign$1({}, entry)); }),
8084                    };
8085                }
8086            }
8087            // Deep clone and merge the new hash map
8088            var merged = __assign$1({}, clonedExisting);
8089            for (var _b = 0, _c = Object.keys(collectionHashMap); _b < _c.length; _b++) {
8090                var langCode = _c[_b];
8091                var newEntry = collectionHashMap[langCode];
8092                if (newEntry === null || newEntry === void 0 ? void 0 : newEntry.timestamps) {
8093                    var clonedTimestamps = newEntry.timestamps.map(function (entry) { return (__assign$1({}, entry)); });
8094                    if (merged[langCode]) {
8095                        // Merge timestamps arrays if langCode already exists
8096                        merged[langCode] = {
8097                            timestamps: __spreadArray$1(__spreadArray$1([], merged[langCode].timestamps, true), clonedTimestamps, true),
8098                        };
8099                    }
8100                    else {
8101                        // Create new entry if langCode doesn't exist
8102                        merged[langCode] = {
8103                            timestamps: clonedTimestamps,
8104                        };
8105                    }
8106                }
8107            }
8108            this.utmCollectionHashMap = merged;
8109        };
8110        Store.prototype.setCollectionCdnMap = function (utmCollectionCdnMap) {
8111            this.utmCollectionCdnMap = __assign$1(__assign$1({}, this.utmCollectionCdnMap), (utmCollectionCdnMap !== null && utmCollectionCdnMap !== void 0 ? utmCollectionCdnMap : {}));
8112        };
8113        Store.prototype.setFetch = function (fetch) {
8114            this.fetch = fetch;
8115        };
8116        Store.prototype.isV2Module = function (module) {
8117            var _a, _b, _c, _d;
8118            var hasUtmCollections = ((_b = (_a = module.utmCollections) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0;
8119            var hasUtmLazyCollections = ((_d = (_c = module.utmLazyCollections) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0) > 0;
8120            return (hasUtmCollections || hasUtmLazyCollections) && this.defaultCdnPath !== undefined;
8121        };
8122        Store.prototype.getFetch = function () {
8123            return this.fetch;
8124        };
8125        Store.prototype.getCollectionHashMap = function () {
8126            return this.utmCollectionHashMap;
8127        };
8128        Store.prototype.getCollectionCdnMap = function () {
8129            return this.utmCollectionCdnMap;
8130        };
8131        Store.prototype.getDefaultCdnPath = function () {
8132            if (this.defaultCdnPath != null) {
8133                return this.defaultCdnPath;
8134            }
8135            throw new Error('defaultCdnPath is not set in TSPSDK constructor');
8136        };
8137        return Store;
8138    }());
8139
8140    var __assign = (undefined && undefined.__assign) || function () {
8141        __assign = Object.assign || function(t) {
8142            for (var s, i = 1, n = arguments.length; i < n; i++) {
8143                s = arguments[i];
8144                for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
8145                    t[p] = s[p];
8146            }
8147            return t;
8148        };
8149        return __assign.apply(this, arguments);
8150    };
8151    var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
8152        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
8153        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
8154        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c >
8154 3 ? d(target, key, r) : d(target, key)) || r;
8155        return c > 3 && r && Object.defineProperty(target, key, r), r;
8156    };
8157    var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
8158        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8159        return new (P || (P = Promise))(function (resolve, reject) {
8160            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8161            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8162            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8163            step((generator = generator.apply(thisArg, _arguments || [])).next());
8164        });
8165    };
8166    var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
8167        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
8168        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
8169        function verb(n) { return function (v) { return step([n, v]); }; }
8170        function step(op) {
8171            if (f) throw new TypeError("Generator is already executing.");
8172            while (g && (g = 0, op[0] && (_ = 0)), _) try {
8173                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
8174                if (y = 0, t) op = [op[0] & 2, t.value];
8175                switch (op[0]) {
8176                    case 0: case 1: t = op; break;
8177                    case 4: _.label++; return { value: op[1], done: false };
8178                    case 5: _.label++; y = op[1]; op = [0]; continue;
8179                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
8180                    default:
8181                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
8182                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
8183                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
8184                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
8185                        if (t[2]) _.ops.pop();
8186                        _.trys.pop(); continue;
8187                }
8188                op = body.call(thisArg, _);
8189            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
8190            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
8191        }
8192    };
8193    var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from, pack) {
8194        if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
8195            if (ar || !(i in from)) {
8196                if (!ar) ar = Array.prototype.slice.call(from, 0, i);
8197                ar[i] = from[i];
8198            }
8199        }
8200        return to.concat(ar || Array.prototype.slice.call(from));
8201    };
8202    function warnV2Module(module) {
8203        var _a, _b, _c, _d;
8204        if (((_a = module.collections) === null || _a === void 0 ? void 0 : _a.length) ||
8205            ((_b = module.resources) === null || _b === void 0 ? void 0 : _b.length) ||
8206            ((_c = module.lazyCollections) === null || _c === void 0 ? void 0 : _c.length) ||
8207            ((_d = module.lazyResources) === null || _d === void 0 ? void 0 : _d.length)) {
8208            console.warn('You are using TSP V2 behaviour now. Passing in V1 properties will be ignored.');
8209            return;
8210        }
8211    }
8212    var TSPSDK = /** @class */ (function () {
8213        /**
8214         * 构造函数
8215         * @param options.name - SDK实例名称
8216         * @param options.isSSR - 是否用于服务端渲染
8217         *
8218         */
8219        function TSPSDK(options) {
8220            if (options === void 0) { options = { name: '' }; }
8221            var _this = this;
8222            /**
8223             * This property is not used internally by the SDK. It serves as an identification/metadata property.
8224             */
8225            this.name = '';
8226            /**
8227             * 是否用于服务端渲染
8228             */
8229            this.isSSR = false;
8230            /**
8231             * 从TSP API 获取翻译的超时毫秒数
8232             * @type {number}
8233             */
8234            this.timeout = 3000;
8235            /**
8236             * 用于区分live/non-live的TSP API, 默认live
8237             * @type {string}
8238             */
8239            this.env = 'live';
8240            /**
8241             *
8242             * 是否是mainland,用于CDN地址选择
8243             * @type {boolean}
8244             */
8245            this.isMainland = undefined;
8246            /**
8247             * 切换语言时用来重新渲染页面
8248             * @type {function}
8249             */
8250            this.forceUpdate = function () { };
8251            /**
8252             * 自定义的替换特殊字符
8253             * @type {function}
8254             */
8255            this.replacer = function (content) { return content; };
8256            /**
8257             * 存储通过调用 mergeTranslation 方法的翻译数据 形如 {en: {ps_home: 'Home'}}
8258             * @type {SimpleObject}
8259             */
8260            this.commonCache = {};
8261            /**
8262             *
8263             * 当前模块名称 例如 finance
8264             * @private
8265             * @type {string}
8266             */
8267            this.currentModuleName = '';
8268            /**
8269             *
8270             * 基础模块 例如 framework
8271             * @private
8272             * @type {TspModules}
8273             */
8274            this.baseModules = {};
8275            /**
8276             *
8277             * 所有业务模块 例如 finance、account
8278             * @private
8279             * @type {TspModules}
8280             */
8281            this.modules = {};
8282            /**
8283             * 所有resource、collection翻译内容的hash值
8284             */
8285            this.translationHashes = {};
8286            this.useCdn = false;
8287            this.timeLimitedGet = function (fn, args) { return __awaiter(_this, void 0, void 0, function () {
8288                var promises, cdnReq, cdnPromise, apiPromise;
8289                var _this = this;
8290                return __generator(this, function (_a) {
8291                    promises = [];
8292                    cdnReq = CmdToken.source();
8293                    if (this.timeout) {
8294                        cdnPromise = delayExec(function () {
8295                            // 不带hash,请求的是默认cdn
8296                            var _args = __assign(__assign({}, args), { hash: '' });
8297                            return _this.api.getTranslationFromCDN(_args).catch(function () { return ({ headers: {}, body: {} }); });
8298                        }, this.timeout, cdnReq.token);
8299                        promises.push(cdnPromise);
8300                    }
8301                    apiPromise = function () { return __awaiter(_this, void 0, void 0, function () {
8302                        var ret;
8303                        return __generator(this, function (_a) {
8304                            switch (_a.label) {
8305                                case 0:
8306                                    _a.trys.push([0, 2, , 3]);
8307                                    return [4 /*yield*/, fn(args)];
8308                                case 1:
8309                                    ret = _a.sent();
8310                                    if (!Object.keys(ret.body).length) {
8311                                        return [2 /*return*/, cdnReq.execute()];
8312                                    }
8313                                    cdnReq.cancel();
8314                                    return [2 /*return*/, ret];
8315                                case 2:
8316                                    _a.sent();
8317                                    return [2 /*return*/, cdnReq.execute()];
8318                                case 3: return [2 /*return*/];
8319                            }
8320                        });
8321                    }); };
8322                    promises.push(apiPromise());
8323                    return [2 /*return*/, Promise.race(promises)];
8324                });
8325            }); };
8326            this.v2Properties = new Store();
8327            if (options) {
8328                this.name = options.name || '';
8329                this.isSSR = options.isSSR || false;
8330                // Store TspOptionsV2 properties if they exist
8331                this.v2Properties.setDefaultCdnPath(options.defaultCdnPath);
8332                this.v2Properties.setCollectionHashMap(options.utmCollectionHashMap);
8333                this.v2Properties.setCollectionCdnMap(options.utmCollectionCdnMap);
8334            }
8335            this.api = new API({
8336                env: this.env,
8337                isMainland: false,
8338                region: 'default',
8339                fetch: get,
8340            });
8341            this.invokeGlobalHook();
8342        }
8343        /**
8344         * 初始化TSPSDK
8345         * @param options.locale - 当前语言类型
8346         * @param [options.isMainland] - 用于选择CDN地址
8347         * @param [options.forceUplate] - 切换语言时用来重新渲染页面
8348         */
8349        TSPSDK.prototype.create = function (options) {
8350            if (options === void 0) { options = {}; }
8351            return __awaiter(this, void 0, void 0, function () {
8352                var translation, accumulatedTranslations, res, _a;
8353                return __generator(this, function (_b) {
8354                    switch (_b.label) {
8355                        case 0:
8356                            this.setOptions(options);
8357                            translation = options.translation;
8358                            if (!(translation && this.v2Properties.isV2Module(translation))) return [3 /*break*/, 2];
8359                            this.currentModuleName = translation.name || 'base';
8360                            translation.name = this.currentModuleName;
8361                            return [4 /*yield*/, this.getTranslationByModuleV2(TSPSDK.locale, translation)];
8362                        case 1:
8363                            accumulatedTranslations = _b.sent();
8364                            this.exposeTranslator(this);
8365                            return [2 /*return*/, { translation: accumulatedTranslations }];
8366                        case 2: return [4 /*yield*/, this.initRemoteConfig(TSPSDK.locale, translation)];
8367                        case 3:
8368                            res = _b.sent();
8369                            translation = res.formattedMod;
8370                            if (!(translation && (!res.translation || !Object.keys(res.translation).length))) return [3 /*break*/, 5];
8371                            _a = res;
8372                            return [4 /*yield*/, this.initBaseTranslation(translation)];
8373                        case 4:
8374                            _a.translation = _b.sent();
8375                            return [3 /*break*/, 6];
8376                        case 5:
8377                            if (translation && this.hasLazyModules(translation)) {
8378                                this.initBaseLazyTranslation(translation);
8379                            }
8380                            _b.label = 6;
8381                        case 6:
8382                            this.exposeTranslator(this);
8383                            return [2 /*return*/, { translation: res.translation }];
8384                    }
8385                });
8386            });
8387        };
8388        TSPSDK.prototype.hasLazyModules = function (mod) {
8389            return (mod.lazyResources && !!mod.lazyResources.length) || (mod.lazyCollections && !!mod.lazyCollections.length);
8390        };
8391        TSPSDK.prototype.formatMod = function (project, mod) {
8392            if (!project) {
8393                return mod;
8394            }
8395            var result = {};
8396            if (project.resource_ids && project.resource_ids.length) {
8397                result.resources = project.resource_ids;
8398            }
8399            if (project.collection_ids && project.collection_ids.length) {
8400                result.collections = project.collection_ids;
8401            }
8402            if (project.lazy_resource_ids && project.lazy_resource_ids.length) {
8403                result.lazyResources = project.lazy_resource_ids;
8404            }
8405            if (project.lazy_collection_ids && project.lazy_collection_ids.length) {
8406                result.lazyCollections = project.lazy_collection_ids;
8407            }
8408            if (typeof project.lazy_time === 'number') {
8409                result.lazyTime = project.lazy_time;
8410            }
8411            if (Object.keys(result).length) {
8412                var _mod = mod || {};
8413                return __assign(__assign({}, _mod), result);
8414            }
8415            return mod;
8416        };
8417        TSPSDK.prototype.invokeGlobalHook = function () {
8418            if (typeof window === 'undefined') {
8419                return;
8420            }
8421            var hooks = window.__tspsdk_global_hooks__;
8422            if (hooks && typeof hooks === 'object' && typeof hooks.created === 'function') {
8423                hooks.created(this);
8424            }
8425        };
8426        TSPSDK.prototype.exposeTranslator = function (it) {
8427            if (typeof window === 'undefined') {
8428                return;
8429            }
8430            if (!window.__tspsdk_translator__) {
8431                window.__tspsdk_translator__ = [];
8432            }
8433            if (window.__tspsdk_translator__.every(function (t) { return t !== it; })) {
8434                window.__tspsdk_translator__.push(it);
8435            }
8436        };
8437        TSPSDK.prototype.setOptions = function (options) {
8438            var _a, _b, _c, _d;
8439            if (options.locale !== undefined) {
8440                TSPSDK.locale = options.locale;
8441            }
8442            if (options.env !== undefined) {
8443                this.env = options.env;
8444            }
8445            if (options.timeout !== undefined) {
8446                this.timeout = options.timeout;
8447            }
8448            this.isMainland = options.isMainland;
8449            var region = (options.region ? options.region.toLowerCase() : 'default');
8450            if (typeof window === 'undefined' && !options.fetch)
8451                throw new Error('For node env,fetch method is required!');
8452            this.v2Properties.setFetch((_a = options.fetch) !== null && _a !== void 0 ? _a : get);
8453            this.v2Properties.setCollectionHashMap((_b = options === null || options === void 0 ? void 0 : options.translation) === null || _b === void 0 ? void 0 : _b.utmCollectionHashMap);
8454            this.v2Properties.setCollectionCdnMap((_c = options === null || options === void 0 ? void 0 : options.translation) === null || _c === void 0 ? void 0 : _c.utmCollectionCdnMap);
8455            if (options.translation && this.v2Properties.isV2Module(options.translation)) {
8456                this.setCdnManager();
8457            }
8458            this.api = new API({
8459                env: this.env,
8460                isMainland: Boolean(this.isMainland),
8461                region: region,
8462                fetch: (_d = options.fetch) !== null && _d !== void 0 ? _d : get,
8463            });
8464            this.forceUpdate = options.forceUpdate || this.forceUpdate;
8465            this.replacer = options.replacer || this.replacer;
8466        };
8467        TSPSDK.prototype.setCdnManager = function () {
8468            var _a;
8469            if (this.cdnManager == null) {
8470                this.cdnManager = new CdnManager({
8471                    env: this.env,
8472                    isMainland: Boolean(this.isMainland),
8473                    defaultCdnPath: this.v2Properties.getDefaultCdnPath(),
8474                    fetch: (_a = this.v2Properties.getFetch()) !== null && _a !== void 0 ? _a : get,
8475                });
8476            }
8477            this.syncCdnManager();
8478        };
8479        TSPSDK.prototype.syncCdnManager = function () {
8480            if (this.cdnManager) {
8481                this.cdnManager.updateCdnPathCollectionIdMap(this.v2Properties.getCollectionCdnMap());
8482                this.cdnManager.updateCollectionHashes(this.v2Properties.getCollectionHashMap());
8483            }
8484        };
8485        TSPSDK.prototype.initRemoteConfig = function (language, mod) {
8486            var _a;
8487            if (mod === void 0) { mod = {}; }
8488            return __awaiter(this, void 0, void 0, function () {
8489                var cacheKey, cacheData, data, translation;
8490                return __generator(this, function (_b) {
8491                    switch (_b.label) {
8492                        case 0:
8493                            cacheKey = this.getInitApiCacheKey(language, mod);
8494                            cacheData = this.getInitApiCache(cacheKey);
8495                            if (!(cacheData && this.isSSR)) return [3 /*break*/, 1];
8496                            data = cacheData;
8497                            return [3 /*break*/, 3];
8498                        case 1: return [4 /*yield*/, this.fetchInitApi(language, mod)];
8499                        case 2:
8500                            data = _b.sent();
8501                            _b.label = 3;
8502                        case 3:
8503                            this.translationHashes[language] = data.hashes || {};
8504                            return [4 /*yield*/, this.setTranslation(language, data.translations)];
8505                        case 4:
8506                            translation = _b.sent();
8507                            if (mod) {
8508                                mod.name = mod.name || 'base';
8509                                this.currentModuleName = mod.name;
8510                                if (data.project) {
8511                                    mod = this.formatMod(data.project, mod);
8512                                }
8513                                this.mergeModule(this.baseModules, mod);
8514                            }
8515                            this.useCdn = !!+(((_a = data.config) === null || _a === void 0 ? void 0 : _a.use_cdn) || '');
8516                            return [2 /*return*/, { translation: translation, formattedMod: mod }];
8517                    }
8518                });
8519            });
8520        };
8521        TSPSDK.prototype.fetchInitApi = function (language, mod) {
8522            if (mod === void 0) { mod = {}; }
8523            return __awaiter(this, void 0, void 0, function () {
8524                var data, cacheKey;
8525                return __generator(this, function (_a) {
8526                    switch (_a.label) {
8527                        case 0: return [4 /*yield*/, this.api.init(language, mod)];
8528                        case 1:
8529                            data = _a.sent();
8530                            cacheKey = this.getInitApiCacheKey(language, mod);
8531                            this.setInitApiCache(cacheKey, data);
8532                            return [2 /*return*/, data];
8533                    }
8534                });
8535            });
8536        };
8537        TSPSDK.prototype.getInitApiCacheKey = function (language, mod) {
8538            var sortFn = function (a, b) {
8539                return a - b;
8540            };
8541            var projectId = mod.projectId || '';
8542            var resources = mod.resources || [];
8543            var collections = mod.collections || [];
8544            var resourceIds = resources.sort(sortFn).join(',');
8545            var collectionIds = collections.sort(sortFn).join(',');
8546            return "".concat(language, "_p").concat(projectId, "_r").concat(resourceIds, "_c").concat(collectionIds);
8547        };
8548        TSPSDK.prototype.getInitApiParamsByCacheKey = function (cacheKey) {
8549            var language = cacheKey.split('_r')[0];
8550            var ids = cacheKey.split('_r')[1].split('_c');
8551            var resources = ids[0] ? ids[0].split(',').map(function (id) { return +id; }) : [];
8552            var collections = ids[1] ? ids[1].split(',').map(function (id) { return +id; }) : [];
8553            return { language: language, resources: resources, collections: collections };
8554        };
8555        TSPSDK.prototype.setTranslation = function (language, translations) {
8556            if (translations === void 0) { translations = {}; }
8557            return __awaiter(this, void 0, void 0, function () {
8558                var fetchNow, _translation;
8559                var _this = this;
8560                return __generator(this, function (_a) {
8561                    switch (_a.label) {
8562                        case 0:
8563                            fetchNow = [];
8564                            _translation = {};
8565                            ['resource', 'collection'].forEach(function (key) {
8566                                var translationSet = translations[key];
8567                                if (translationSet) {
8568                                    var _loop_1 = function (id) {
8569                                        var content = translationSet[id];
8570                                        if (content === 1) {
8571                                            fetchNow.push(function () { return __awaiter(_this, void 0, void 0, function () {
8572                                                var res;
8573                                                return __generator(this, function (_a) {
8574                                                    switch (_a.label) {
8575                                                        case 0: return [4 /*yield*/, this.getTranslationByType(key, +id, language)];
8576                                                        case 1:
8577                                                            res = _a.sent();
8578                                                            Object.assign(_translation, res);
8579                                                            return [2 /*return*/, res];
8580                                                    }
8581                                                });
8582                                            }); });
8583                                            return "continue";
8584                                        }
8585                                        _this.setCache(key, +id, language, content);
8586                                        Object.assign(_translation, content);
8587                                    };
8588                                    for (var _i = 0, _a = Object.keys(translationSet); _i < _a.length; _i++) {
8589                                        var id = _a[_i];
8590                                        _loop_1(id);
8591                                    }
8592                                }
8593                            });
8594                            if (!fetchNow.length) return [3 /*break*/, 2];
8595                            return [4 /*yield*/, Promise.all(fetchNow.map(function (fn) { return fn(); }))];
8596                        case 1:
8597                            _a.sent();
8598                            _a.label = 2;
8599                        case 2: return [2 /*return*/, _translation];
8600                    }
8601                });
8602            });
8603        };
8604        TSPSDK.prototype.initBaseTranslation = function (mod) {
8605            return this.loadTranslation(mod);
8606        };
8607        TSPSDK.prototype.initBaseLazyTranslation = function (mod) {
8608            return this.getLazyTranslationByModule(TSPSDK.locale, mod);
8609        };
8610        /**
8611         * 获取当前的模块信息
8612         */
8613        TSPSDK.prototype.getCurrentModule = function () {
8614            return this.modules[this.currentModuleName];
8615        };
8616        /**
8617         * 返回TSPSDK中存储的所有模块信息
8618         */
8619        TSPSDK.prototype.getAllModules = function () {
8620            return __assign(__assign({}, this.baseModules), this.modules);
8621        };
8622        TSPSDK.prototype.getModuleByName = function (name) {
8623            return this.getAllModules()[name] || null;
8624        };
8625        /**
8626         * 切换语言,并拉取相关的翻译数据
8627         * moduleNames: 例如['listing', 'drc']
8628         * @param {string} locale
8629         * @param {string[]} [moduleNames]
8630         */
8631        TSPSDK.prototype.switchLanguage = function (locale, moduleNames) {
8632            return __awaiter(this, void 0, void 0, function () {
8633                var hasModuleNamesInputParam, allModules, requiedModules, baseModules, translations;
8634                var _a;
8635                var _this = this;
8636                return __generator(this, function (_b) {
8637                    switch (_b.label) {
8638                        case 0:
8639                            hasModuleNamesInputParam = moduleNames != null && Array.isArray(moduleNames) && moduleNames.length > 0;
8640                            allModules = this.getAllModules();
8641                            requiedModules = {};
8642                            if (hasModuleNamesInputParam) {
8643                                moduleNames.map(function (name) {
8644                                    requiedModules[name] = allModules[name];
8645                                });
8646                                requiedModules = __assign(__assign({}, this.baseModules), requiedModules);
8647                            }
8648                            baseModules = this.baseModules[Object.keys(this.baseModules)[0]];
8649                            if (!(baseModules && !this.v2Properties.isV2Module(baseModules))) return [3 /*break*/, 2];
8650                            return [4 /*yield*/, this.initRemoteConfig(locale, baseModules)];
8651                        case 1:
8652                            _b.sent();
8653                            _b.label = 2;
8654                        case 2: return [4 /*yield*/, this.getTranslationByModules(locale, hasModuleNamesInputParam ? requiedModules : allModules)];
8655                        case 3:
8656                            translations = _b.sent();
8657                            TSPSDK.locale = locale;
8658                            if (this.forceUpdate && typeof this.forceUpdate === 'function') {
8659                                setTimeout(function () {
8660                                    _this.forceUpdate();
8661                                }, 0);
8662                            }
8663                            return [2 /*return*/, (_a = Object.assign).call.apply(_a, __spreadArray([null, {}], translations, false))];
8664                    }
8665                });
8666            });
8667        };
8668        /**
8669         * 切换模块,并拉取相关的翻译数据
8670         */
8671        TSPSDK.prototype.switchModule = function (module) {
8672            if (typeof module === 'string') {
8673                if (!this.getAllModules()[module]) {
8674                    throw new Error('module not found');
8675                }
8676                this.currentModuleName = module;
8677                module = this.getAllModules()[module];
8678            }
8679            else {
8680                if (!module.name) {
8681                    throw new Error('module must have a name');
8682                }
8683                this.currentModuleName = module.name;
8684            }
8685            return this.getTranslationByModule(TSPSDK.locale, module);
8686        };
8687        /**
8688         * use mergeTranslation instead
8689         * @deprecated
8690         */
8691        TSPSDK.prototype.mergeLocale = function (locale, message) {
8692            return this.mergeTranslation(message, locale);
8693        };
8694        /**
8695         * 合并额外的翻译数据
8696         */
8697        TSPSDK.prototype.mergeTranslation = function (translation, locale) {
8698            if (locale === void 0) { locale = TSPSDK.locale; }
8699            this.commonCache[locale] = this.commonCache[locale] || {};
8700            for (var k in translation) {
8701                if (Object.prototype.hasOwnProperty.call(translation, k)) {
8702                    this.commonCache[locale][k] = translation[k];
8703                }
8704            }
8705            // this.commonCache[locale] = {...this.commonCache[locale], ...message};
8706        };
8707        /**
8708         * 建议使用 $t
8709         * 返回单复数形式的key的翻译字符串
8710         * @deprecated
8711         */
8712        TSPSDK.prototype.$tc2 = function (key, count, values, useModule) {
8713            return this.$t(key, count, values, useModule);
8714        };
8715        /**
8716         * 返回翻译字符串
8717         */
8718        TSPSDK.prototype.$t = function (key, count, values, useModule) {
8719            var result = this._$t(key, count, values, undefined, useModule);
8720            return result && typeof result === 'string' ? result : key;
8721        };
8722        /**
8723         * 用于i18n组件
8724         */
8725        TSPSDK.prototype.$i = function (key, values, useModule) {
8726            // count = '_' 仅为了区分非数字与非空的情况
8727            return this._$t(key, '_', values, 'raw', useModule) || key;
8728        };
8729        /**
8730         * 返回翻译字符串
8731         */
8732        TSPSDK.prototype._$t = function (key, count, values, mode, useModule) {
8733            count = Number(count) || count; // 兼容count传了字符串类型的数字. 如: $t('ps_', '1')
8734            if (values) {
8735                count = count || 0; // 解决没有传count, 但是传了values的情况. 如: $t('ps_', undefined, {count: 1})
8736            }
8737            if (count !== null && typeof count === 'object') {
8738                values = count; // 当只传了两个参数,那么第二个参数应该是values
8739            }
8740            var content = this.findTranslationByKey(key, useModule);
8741            if (typeof count === 'number') {
8742                var cat = (handler[TSPSDK.locale] || handler.en)(count);
8743                // 复数第一种模式
8744                // plural_key: { one: '', other: '', zero: '' }
8745                if (typeof content === 'object') {
8746                    return this.__$t(content[cat] || content.one || content.other, values, mode);
8747                }
8748                // 复数第二种模式
8749                // plural_key__one: '',
8750                // plural_key__other: '',
8751                // plural_key__zero: ''
8752                var findOrder = this.pluralFindOrder(cat);
8753                for (var _i = 0, findOrder_1 = findOrder;
8753 _i < findOrder_1.length; _i++) {
8754                    var _cat = findOrder_1[_i];
8755                    var findKey = "".concat(key, "__").concat(_cat);
8756                    var foundContent = this.findTranslationByKey(findKey);
8757                    var result = this.__$t(foundContent, values, mode);
8758                    if (result && findKey !== result) {
8759                        return result;
8760                    }
8761                }
8762            }
8763            return this.__$t(content, values, mode);
8764        };
8765        TSPSDK.prototype.pluralFindOrder = function (cat) {
8766            if (cat === 'one') {
8767                return ['one', 'other'];
8768            }
8769            if (cat === 'other') {
8770                return ['other', 'one'];
8771            }
8772            return [cat, 'one', 'other'];
8773        };
8774        /**
8775         * 处理翻译内容
8776         */
8777        TSPSDK.prototype.__$t = function (content, values, mode) {
8778            if (typeof content === 'object' || !content) {
8779                return content;
8780            }
8781            var result = content;
8782            if (this.replacer) {
8783                try {
8784                    result = this.replacer(result);
8785                }
8786                catch (e) {
8787                    // console.error('TSPSDK replacer error: ', e);
8788                }
8789            }
8790            return values ? interpolate(result, values, mode) : result;
8791        };
8792        /**
8793         * 获取某个resource或collection的特定key的翻译数据
8794         * @param {string} keys [如果多个key,以逗号分隔]
8795         * @deprecated in V2 TspModule. Move to use $t instead.
8796         */
8797        TSPSDK.prototype.getTranslationByKeys = function (locale, type, id, keys) {
8798            if (this.v2Properties.isV2Module(this.getCurrentModule())) {
8799                return this.getTranslationByTypeV2(id, locale, keys);
8800            }
8801            return this.getTranslationByType(type, id, locale, keys);
8802        };
8803        /**
8804         * @private 拉取多个模块的翻译
8805         * @param {string} locale
8806         * @param {TspModules} modules
8807         * @returns Promise
8808         */
8809        TSPSDK.prototype.getTranslationByModules = function (locale, modules) {
8810            var _this = this;
8811            var promises = Object.keys(modules).map(function (name) {
8812                return _this.getTranslationByModule(locale, _this.getAllModules()[name]);
8813            });
8814            return Promise.all(promises);
8815        };
8816        /**
8817         * 拉取一个模块的翻译
8818         * 推荐使用loadTranslation
8819         * @deprecated
8820         */
8821        TSPSDK.prototype.getTranslationByModule = function (locale, module) {
8822            return __awaiter(this, void 0, void 0, function () {
8823                var resources, collections, lazyResources, lazyCollections, lazyTime, promises, res;
8824                var _a;
8825                var _this = this;
8826                return __generator(this, function (_b) {
8827                    switch (_b.label) {
8828                        case 0:
8829                            if (!module) {
8830                                // console.error('TSPSDK.getTranslationByModule has no module');
8831                                return [2 /*return*/, {}];
8832                            }
8833                            this.v2Properties.setCollectionHashMap(module === null || module === void 0 ? void 0 : module.utmCollectionHashMap);
8834                            this.v2Properties.setCollectionCdnMap(module === null || module === void 0 ? void 0 : module.utmCollectionCdnMap);
8835                            if (this.v2Properties.isV2Module(module)) {
8836                                return [2 /*return*/, this.getTranslationByModuleV2(locale, module)];
8837                            }
8838                            module.name = module.name || 'mod_' + Date.now();
8839                            this.mergeModule(this.modules, module);
8840                            resources = module.resources, collections = module.collections, lazyResources = module.lazyResources, lazyCollections = module.lazyCollections, lazyTime = module.lazyTime;
8841                            promises = [];
8842                            if (collections === null || collections === void 0 ? void 0 : collections.length) {
8843                                promises.push.apply(promises, collections.map(function (id) { return _this.getTranslationByType('collection', id, locale); }));
8844                            }
8845                            if (resources === null || resources === void 0 ? void 0 : resources.length) {
8846                                promises.push.apply(promises, resources.map(function (id) { return _this.getTranslationByType('resource', id, locale); }));
8847                            }
8848                            if (lazyResources && lazyResources.length) {
8849                                setTimeout(function () {
8850                                    lazyResources === null || lazyResources === void 0 ? void 0 : lazyResources.forEach(function (id) { return _this.getTranslationByType('resource', id, locale); });
8851                                }, lazyTime || 3000);
8852                            }
8853                            if (lazyCollections && lazyCollections.length) {
8854                                setTimeout(function () {
8855                                    lazyCollections === null || lazyCollections === void 0 ? void 0 : lazyCollections.map(function (id) { return _this.getTranslationByType('collection', id, locale); });
8856                                }, lazyTime || 3000);
8857                            }
8858                            return [4 /*yield*/, Promise.all(promises)];
8859                        case 1:
8860                            res = _b.sent();
8861                            return [2 /*return*/, (_a = Object.assign).call.apply(_a, __spreadArray([null, {}], res, false))];
8862                    }
8863                });
8864            });
8865        };
8866        TSPSDK.prototype.getTranslationByModuleV2 = function (langCode, module) {
8867            var _a;
8868            return __awaiter(this, void 0, void 0, function () {
8869                var utmCollections, utmLazyCollections, _b, lazyTime, promises, res, translation;
8870                var _this = this;
8871                return __generator(this, function (_c) {
8872                    switch (_c.label) {
8873                        case 0:
8874                            if (!module) {
8875                                return [2 /*return*/, {}];
8876                            }
8877                            warnV2Module(module);
8878                            module.name = (_a = module.name) !== null && _a !== void 0 ? _a : "mod_".concat(Date.now());
8879                            this.mergeModule(this.modules, module);
8880                            utmCollections = module.utmCollections, utmLazyCollections = module.utmLazyCollections, _b = module.lazyTime, lazyTime = _b === void 0 ? this.timeout : _b;
8881                            promises = [];
8882                            if (utmCollections === null || utmCollections === void 0 ? void 0 : utmCollections.length) {
8883                                promises.push.apply(promises, utmCollections.map(function (id) { return _this.getTranslationByTypeV2(id, langCode); }));
8884                            }
8885                            return [4 /*yield*/, allSettled(promises)];
8886                        case 1:
8887                            res = _c.sent();
8888                            // Do not await lazy collections to match V1 behaviour
8889                            if (utmLazyCollections === null || utmLazyCollections === void 0 ? void 0 : utmLazyCollections.length) {
8890                                setTimeout(function () {
8891                                    utmLazyCollections.forEach(function (id) {
8892                                        void _this.getTranslationByTypeV2(id, langCode);
8893                                    });
8894                                }, lazyTime);
8895                            }
8896                            translation = {};
8897                            res.forEach(function (result) {
8898                                if (result.status === 'fulfilled') {
8899                                    Object.assign(translation, result.value);
8900                                }
8901                                else {
8902                                    console.error(result.error);
8903                                }
8904                            });
8905                            return [2 /*return*/, translation];
8906                    }
8907                });
8908            });
8909        };
8910        /**
8911         * 拉取模块的lazy翻译
8912         */
8913        TSPSDK.prototype.getLazyTranslationByModule = function (locale, module) {
8914            return __awaiter(this, void 0, void 0, function () {
8915                var lazyResources, lazyCollections, lazyTime;
8916                var _this = this;
8917                return __generator(this, function (_a) {
8918                    if (!module) {
8919                        return [2 /*return*/, {}];
8920                    }
8921                    module.name = module.name || 'mod_' + Date.now();
8922                    lazyResources = module.lazyResources, lazyCollections = module.lazyCollections, lazyTime = module.lazyTime;
8923                    if (lazyResources && lazyResources.length) {
8924                        setTimeout(function () {
8925                            lazyResources === null || lazyResources === void 0 ? void 0 : lazyResources.forEac
8925h(function (id) { return _this.getTranslationByType('resource', id, locale); });
8926                        }, lazyTime || 3000);
8927                    }
8928                    if (lazyCollections && lazyCollections.length) {
8929                        setTimeout(function () {
8930                            lazyCollections === null || lazyCollections === void 0 ? void 0 : lazyCollections.map(function (id) { return _this.getTranslationByType('collection', id, locale); });
8931                        }, lazyTime || 3000);
8932                    }
8933                    return [2 /*return*/, {}];
8934                });
8935            });
8936        };
8937        /**
8938         * 根据当前的语言拉取更多的翻译数据
8939         * @param mod
8940         * @param locale 如果想拉取其他语言的翻译,可以指定对于的语言
8941         */
8942        TSPSDK.prototype.loadTranslation = function (mod, locale) {
8943            return this.getTranslationByModule(locale || TSPSDK.locale, mod);
8944        };
8945        /**
8946         * 根据传入的resource和collection id列表拉取翻译
8947         * @deprecated
8948         */
8949        TSPSDK.prototype.getTranslations = function (locale, mod) {
8950            return this.getTranslationByModule(locale, mod);
8951        };
8952        TSPSDK.prototype.getTranslationByType = function (type, id, language, keys) {
8953            return __awaiter(this, void 0, void 0, function () {
8954                var cache, body;
8955                return __generator(this, function (_a) {
8956                    switch (_a.label) {
8957                        case 0:
8958                            cache = this.getCache(type, id, language);
8959                            if (cache) {
8960                                return [2 /*return*/, cache];
8961                            }
8962                            return [4 /*yield*/, this.fetchTranslation(type, id, language, keys)];
8963                        case 1:
8964                            body = (_a.sent()).body;
8965                            if (keys) {
8966                                this.mergeTranslation(body, language);
8967                            }
8968                            else {
8969                                this.setCache(type, id, language, body);
8970                            }
8971                            return [2 /*return*/, body];
8972                    }
8973                });
8974            });
8975        };
8976        TSPSDK.prototype.getTranslationByTypeV2 = function (id, langCode, keys) {
8977            return __awaiter(this, void 0, void 0, function () {
8978                var cache, body;
8979                return __generator(this, function (_a) {
8980                    switch (_a.label) {
8981                        case 0:
8982                            this.setCdnManager();
8983                            if (this.cdnManager === undefined) {
8984                                throw new Error('SDK using TSP V2 behaviour but SDK is not initialized as V2');
8985                            }
8986                            cache = this.getCache('collection', id, langCode);
8987                            if (cache) {
8988                                return [2 /*return*/, cache];
8989                            }
8990                            return [4 /*yield*/, this.cdnManager.getTranslationFromCDN({
8991                                    id: id,
8992                                    langCode: langCode,
8993                                })];
8994                        case 1:
8995                            body = (_a.sent()).body;
8996                            if (keys) {
8997                                this.mergeTranslation(body, langCode);
8998                            }
8999                            else {
9000                                this.setCache('collection', id, langCode, body);
9001                            }
9002                            return [2 /*return*/, body];
9003                    }
9004                });
9005            });
9006        };
9007        TSPSDK.prototype.fetchTranslation = function (type, id, language, keys) {
9008            var _a, _b;
9009            return __awaiter(this, void 0, void 0, function () {
9010                var hash, fn;
9011                return __generator(this, function (_c) {
9012                    hash = (_b = (_a = this.translationHashes[language]) === null || _a === void 0 ? void 0 : _a[type]) === null || _b === void 0 ? void 0 : _b[id];
9013                    fn = this.useCdn ? this.api.getTranslationFromCDN : this.api.getTranslationFromAPI;
9014                    return [2 /*return*/, this.timeLimitedGet(fn, { type: type, id: id, language: language, hash: hash, keys: keys })];
9015                });
9016            });
9017        };
9018        TSPSDK.prototype.getCacheKey = function (id, locale) {
9019            return id + '_' + locale.toLowerCase();
9020        };
9021        TSPSDK.prototype.setCache = function (type, id, locale, message) {
9022            var cache = type === 'resource' ? TSPSDK.resourceCache : TSPSDK.collectionCache;
9023            var key = this.getCacheKey(id, locale); // for example: 52en
9024            cache[key] = cache[key] || {};
9025            cache[key] = __assign(__assign({}, cache[key]), message);
9026        };
9027        TSPSDK.prototype.getCache = function (type, id, locale) {
9028            var cache = type === 'resource' ? TSPSDK.resourceCache : TSPSDK.collectionCache;
9029            var key = this.getCacheKey(id, locale); // for example: 52en
9030            return cache[key];
9031        };
9032        TSPSDK.prototype.setInitApiCache = function (key, data) {
9033            return (TSPSDK.initApiCache[key] = data);
9034        };
9035        TSPSDK.prototype.getInitApiCache = function (key) {
9036            return TSPSDK.initApiCache[key];
9037        };
9038        TSPSDK.prototype.findTranslationByKey = function (key, useModule) {
9039            var result = '';
9040            //如果外界调用t方法传入了module 要优先使用外界的传入的module的翻译
9041            var applyModule = (useModule && this.getModuleByName(useModule)) || this.getCurrentModule(
9041);
9042            if (applyModule) {
9043                result = this.findTranslationFromModule(key, applyModule);
9044                if (result) {
9045                    return result;
9046                }
9047            }
9048            var baseModuleNames = Object.keys(this.baseModules);
9049            for (var i = 0; i < baseModuleNames.length; i++) {
9050                var name_1 = baseModuleNames[i];
9051                result = this.findTranslationFromModule(key, this.baseModules[name_1]);
9052                if (result) {
9053                    return result;
9054                }
9055            }
9056            result = this.findTranslationFromCommon(key);
9057            if (result) {
9058                return result;
9059            }
9060            var allModules = this.getAllModules();
9061            var allModuleNames = Object.keys(allModules);
9062            for (var i = 0; i < allModuleNames.length; i++) {
9063                var name_2 = allModuleNames[i];
9064                result = this.findTranslationFromModule(key, allModules[name_2]);
9065                if (result) {
9066                    return result;
9067                }
9068            }
9069            return result || '';
9070        };
9071        TSPSDK.prototype.findTranslationFromModule = function (key, module) {
9072            if (this.v2Properties.isV2Module(module)) {
9073                return this.findTranslationFromModuleV2(key, module);
9074            }
9075            var collections = (module.collections || []).concat(module.lazyCollections || []);
9076            var resources = (module.resources || []).concat(module.lazyResources || []);
9077            for (var i = 0; i < collections.length; i++) {
9078                var cache = this.getCache('collection', collections[i], TSPSDK.locale);
9079                if (cache && cache[key]) {
9080                    return cache[key];
9081                }
9082            }
9083            for (var i = 0; i < resources.length; i++) {
9084                var cache = this.getCache('resource', resources[i], TSPSDK.locale);
9085                if (cache && cache[key]) {
9086                    return cache[key];
9087                }
9088            }
9089            return '';
9090        };
9091        TSPSDK.prototype.findTranslationFromModuleV2 = function (key, module) {
9092            var _a, _b;
9093            warnV2Module(module);
9094            var collections = ((_a = module.utmCollections) !== null && _a !== void 0 ? _a : []).concat((_b = module.utmLazyCollections) !== null && _b !== void 0 ? _b : []);
9095            for (var _i = 0, collections_1 = collections; _i < collections_1.length; _i++) {
9096                var collection = collections_1[_i];
9097                var cache = this.getCache('collection', collection, TSPSDK.locale);
9098                if (cache === null || cache === void 0 ? void 0 : cache[key]) {
9099                    return cache[key];
9100                }
9101            }
9102            return '';
9103        };
9104        TSPSDK.prototype.findTranslationFromCommon = function (key) {
9105            var cache = this.commonCache[TSPSDK.locale];
9106            if (cache && cache[key]) {
9107                return cache[key];
9108            }
9109            return '';
9110        };
9111        TSPSDK.prototype.mergeModule = function (modules, module) {
9112            var _a, _b;
9113            var current = modules[module.name + ''];
9114            if (!current) {
9115                modules[module.name + ''] = module;
9116                return;
9117            }
9118            if (this.v2Properties.isV2Module(module)) {
9119                warnV2Module(module);
9120                var utmCollectionsSet = new Set(__spreadArray(__spreadArray([], ((_a = current.utmCollections) !== null && _a !== void 0 ? _a : []), true), ((_b = module.utmCollections) !== null && _b !== void 0 ? _b : []), true));
9121                current.utmCollections = Array.from(utmCollectionsSet);
9122                return;
9123            }
9124            current.collections = current.collections || [];
9125            current.resources = current.resources || [];
9126            module.collections = module.collections || [];
9127            module.resources = module.resources || [];
9128            module.collections.map(function (id) {
9129                var _a;
9130                if (((_a = current.collections) === null || _a === void 0 ? void 0 : _a.indexOf(id)) === -1) {
9131                    current.collections.push(id);
9132                }
9133            });
9134            module.resources.map(function (id) {
9135                var _a;
9136                if (((_a = current.resources) === null || _a === void 0 ? void 0 : _a.indexOf(id)) === -1) {
9137                    current.resources.push(id);
9138                }
9139            });
9140        };
9141        TSPSDK.version = 'undefined';
9142        /**
9143         * 当前的语言类型
9144         */
9145        TSPSDK.locale = 'en';
9146        /**
9147         * 按resource id + locale存储翻译数据 形如 {52en: {ps_home: 'Home'}}
9148         * @type {ResourceCache}
9149         */
9150        TSPSDK.resourceCache = {};
9151        /**
9152         *
9153         * 按collection id + locale存储翻译数据 形如 {33en: {ps_home: 'Home'}}
9154         * @type {ResourceCache}
9155         */
9156        TSPSDK.collectionCache = {};
9157        /**
9158         *
9159         * 按collection id + locale存储翻译数据 形如 {33en: {ps_home: 'Home'}}
9160         * @type {ResourceCache}
9161         */
9162        TSPSDK.initApiCache = {};
9163        __decorate([
9164            measureTime('66434261232b824496e0a6569d107c83')
9165        ], TSPSDK.prototype, "create", null);
9166        __decorate([
9167            measureTime('2abb8903b113cbe3b812775bbb3d7654')
9168        ], TSPSDK.prototype, "initRemoteConfig", null);
9169        __decorate([
9170            measureTime('f7d982865e455c53251a928695cf8ba4')
9171        ], TSPSDK.prototype, "setTranslation", null);
9172        __decorate([
9173            measureTime('59d11e7cc0a156483eb9bff150e31046')
9174        ], TSPSDK.prototype, "initBaseTranslation", null);
9175        __decorate([
9176            measureTime('eb066b904c4b0717fd91463a102b41cf')
9177        ], TSPSDK.prototype, "initBaseLazyTranslation", null);
9178        return TSPSDK;
9179    }());
9180
9181    /*! js-cookie v3.0.8 | MIT */
9182    function assign (target) {
9183      for (var i = 1; i < arguments.length; i++) {
9184        var source = arguments[i];
9185        for (var key in source) {
9186          if (key === '__proto__') continue
9187          target[key] = source[key];
9188        }
9189      }
9190      return target
9191    }
9192
9193    var defaultConverter = {
9194      read: function (value) {
9195        if (value[0] === '"') {
9196          value = value.slice(1, -1);
9197        }
9198        return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent)
9199      },
9200      write: function (value) {
9201        return encodeURIComponent(value).replace(
9202          /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,
9203          decodeURIComponent
9204        )
9205      }
9206    };
9207
9208    function init$1(converter, defaultAttributes) {
9209      function set(name, value, attributes) {
9210        if (typeof document === 'undefined') {
9211          return
9212        }
9213
9214        attributes = assign({}, defaultAttributes, attributes);
9215
9216        if (typeof attributes.expires === 'number') {
9217          attributes.expires = new Date(Date.now() + attributes.expires * 864e5);
9218        }
9219        if (attributes.expires) {
9220          attributes.expires = attributes.expires.toUTCString();
9221        }
9222
9223        name = encodeURIComponent(name)
9224          .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)
9225          .replace(/[()]/g, escape);
9226
9227        var stringifiedAttributes = '';
9228        for (var attributeName in attributes) {
9229          if (!attributes[attributeName]) {
9230            continue
9231          }
9232
9233          stringifiedAttributes += '; ' + attributeName;
9234
9235          if (attributes[attributeName] === true) {
9236            continue
9237          }
9238
9239          // Considers RFC 6265 section 5.2:
9240          // ...
9241          // 3.  If the remaining unparsed-attributes contains a %x3B (";")
9242          //     character:
9243          // Consume the characters of the unparsed-attributes up to,
9244          // not including, the first %x3B (";") character.
9245          // ...
9246          stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
9247        }
9248
9249        return (document.cookie =
9250          name + '=' + converter.write(value, name) + stringifiedAttributes)
9251      }
9252
9253      function get(name) {
9254        if (typeof document === 'undefined' || (arguments.length && !name)) {
9255          return
9256        }
9257
9258        // To prevent the for loop in the first place assign an empty array
9259        // in case there are no cookies at all.
9260        var cookies = document.cookie ? document.cookie.split('; ') : [];
9261        var jar = {};
9262        for (var i = 0; i < cookies.length; i++) {
9263          var parts = cookies[i].split('=');
9264          var value = parts.slice(1).join('=');
9265
9266          try {
9267            var found = decodeURIComponent(parts[0]);
9268            if (!(found in jar)) jar[found] = converter.read(value, found);
9269            if (name === found) {
9270              break
9271            }
9272          } catch (_e) {
9273            // Do nothing...
9274          }
9275        }
9276
9277        return name ? jar[name] : jar
9278      }
9279
9280      return Object.create(
9281        {
9282          set: set,
9283          get: get,
9284          remove: function (name, attributes) {
9285            set(
9286              name,
9287              '',
9288              assign({}, attributes, {
9289                expires: -1
9290              })
9291            );
9292          },
9293          withAttributes: function (attributes) {
9294            return init$1(this.converter, assign({}, this.attributes, attributes))
9295          },
9296          withConverter: function (converter) {
9297            return init$1(assign({}, this.converter, converter), this.attributes)
9298          }
9299        },
9300        {
9301          attributes: { value: Object.freeze(defaultAttributes) },
9302          converter: { value: Object.freeze(converter) }
9303        }
9304      )
9305    }
9306
9307    var api = init$1(defaultConverter, { path: '/' });
9308
9309    var DEFAULT_LANGUAGE$1 = 'en';
9310    var checkCurrentLanguage = function () {
9311        // 在静态化服务中执行时,直接返回默认
9312        if (isRunIngInNodeEnv) {
9313            return DEFAULT_LANGUAGE$1;
9314        }
9315        var lang = getLangFromUrl();
9316        if (lang) {
9317            return lang;
9318        }
9319        var cachedLanguage = getCacheLanguage();
9320        if (cachedLanguage && LanguageText[cachedLanguage]) {
9321            return cachedLanguage;
9322        }
9323        return localLangMapByRegion[getRegion()] || DEFAULT_LANGUAGE$1;
9324    };
9325
9326    var DEFAULT_LANGUAGE = 'en';
9327    var translator = new TSPSDK({ name: 'spxopen', defaultCdnPath: 'tsp-default' });
9328    var isNonLive = ['test', 'uat', 'staging', 'fte'].includes('live');
9329    /**
9330     * 根据语言代码和市场生成区域特定的 TSP 语言代码
9331     * @param language 应用内部语言代码
9332     * @returns 区域特定的 TSP 语言代码
9333     */
9334    var generateRegionalTspLanguage = function (language) {
9335        var region = getRegion();
9336        // 使用 map 配置获取区域特定的 TSP 语言代码
9337        var regionalMap = tspRegionalLanguageMap[region];
9338        if (regionalMap && regionalMap[language]) {
9339            return regionalMap[language];
9340        }
9341        // 如果没有找到映射,返回原始语言代码
9342        return tspLanguageMap[language] || language;
9343    };
9344    var loadResource = function (targetLang) { return __awaiter$7(void 0, void 0, void 0, function () {
9345        var lang, tspLang, currentModule, res, e_1;
9346        var _a;
9347        return __generator$7(this, function (_b) {
9348            switch (_b.label) {
9349                case 0:
9350                    lang = targetLang;
9351                    if (!lang) {
9352                        lang = checkCurrentLanguage();
9353                    }
9354                    if (!isRunIngInNodeEnv) {
9355                        api.set(LANGUAGE_COOKIE_KEY, lang);
9356                        setCacheLanguage(lang);
9357                    }
9358                    tspLang = generateRegionalTspLanguage(lang);
9359                    _b.label = 1;
9360                case 1:
9361                    _b.trys.push([1, 6, , 7]);
9362                    return [4 /*yield*/, translator.create({
9363                            env: isNonLive ? 'non-live' : 'live',
9364                            locale: tspLang, // language code, en, vi, th, zh-Hans etc, case insensitive
9365                            translation: {
9366                                utmLazyCollections: [1528],
9367                            },
9368                        })];
9369                case 2:
9370                    _b.sent();
9371                    return [4 /*yield*/, translator.getCurrentModule(
9371)];
9372                case 3:
9373                    currentModule = _b.sent();
9374                    return [4 /*yield*/, translator.loadTranslation(currentModule, tspLang)];
9375                case 4:
9376                    res = _b.sent();
9377                    return [4 /*yield*/, instance.init({
9378                            lng: lang,
9379                            fallbackLng: DEFAULT_LANGUAGE,
9380                            // defaultNS: 'common',
9381                            keySeparator: false,
9382                            // debug: {"NODE_ENV":"development","APP_VERSION":"v20260929-1220-MY-LIVE","env":"live","PARTNER_ID":"shopee"}.NODE_ENV === 'development',
9383                            resources: (_a = {},
9384                                _a[lang] = {
9385                                    translation: res,
9386                                },
9387                                _a),
9388                            interpolation: {
9389                                escapeValue: false,
9390                            },
9391                            react: {
9392                                wait: false,
9393                                bindI18n: 'languageChanged loaded',
9394                                bindStore: 'added removed',
9395                                nsMode: 'default',
9396                            },
9397                        })
9398                        // console.log('i18next resource', res)
9399                    ];
9400                case 5:
9401                    _b.sent();
9402                    return [3 /*break*/, 7];
9403                case 6:
9404                    e_1 = _b.sent();
9405                    console.error(e_1);
9406                    return [3 /*break*/, 7];
9407                case 7: return [2 /*return*/];
9408            }
9409        });
9410    }); };
9411
9412    /**
9413     * Get CSRF token from cookies
9414     */
9415    var getCsrfToken = function () {
9416        if (isRunIngInNodeEnv)
9417            return '';
9418        var match = document.cookie.match(new RegExp('(^| )csrftoken=([^;]+)'));
9419        return match ? match[2] : '';
9420    };
9421    var sourceInfo = undefined;
9422    /**
9423     * 读取响应体并解析为 JSON。
9424     * 先 text() 再 JSON.parse,避免后端返回非 JSON(如网关 HTML 错误页)时被
9425     * response.json() 内部抛出的 SyntaxError 吞掉 status / url 等排障上下文。
9426     * 浏览器与 Node 原生 fetch 均支持,同构安全。
9427     */
9428    function parseResponse(response, context) {
9429        return __awaiter$7(this, void 0, void 0, function () {
9430            var bodyText, data;
9431            return __generator$7(this, function (_a) {
9432                switch (_a.label) {
9433                    case 0: return [4 /*yield*/, response.text()];
9434                    case 1:
9435                        bodyText = _a.sent();
9436                        try {
9437                            data = bodyText ? JSON.parse(bodyText) : null;
9438                        }
9439                        catch (_b) {
9440                            // 截断防日志洪泛(网关错误页可能很大)
9441                            throw new Error("Invalid JSON response! Status: ".concat(response.status, ", ").concat(context, ", body: ").concat(bodyText.slice(0, 500)));
9442                        }
9443                        if (!response.ok) {
9444                            // Rich-todo: 上报错误
9445                            throw new Error("HTTP error! Status: ".concat(response.status, ", ").concat(context, ", response: ").concat(JSON.stringify(data)));
9446                        }
9447                        return [2 /*return*/, data];
9448                }
9449            });
9450        });
9451    }
9452    /**
9453     * Makes a GET request using the native fetch API
9454     * @param url The URL to fetch from
9455     * @param params Optional query parameters
9456     * @param options Additional fetch options
9457     * @returns Promise with the response data
9458     */
9459    function fetchGet(url_1, params_1) {
9460        return __awaiter$7(this, arguments, void 0, function (url, params, options) {
9461            var fullUrl, queryString, fetchOptions, response;
9462            if (options === void 0) { options = {}; }
9463            return __generator$7(this, function (_a) {
9464                switch (_a.label) {
9465                    case 0:
9466                        fullUrl = url;
9467                        if (params && Object.keys(params).length > 0) {
9468                            queryString = Object.keys(params)
9469                                .flatMap(function (key) {
9470                                var value = params[key];
9471                                var values = Array.isArray(value) ? value : [value];
9472                                return values.map(function (item) { return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(item)); });
9473                            })
9474                                .join('&');
9475                            fullUrl = "".concat(url).concat(url.includes('?') ? '&' : '?').concat(queryString);
9476                        }
9477                        fetchOptions = __assign$3({ method: 'GET', credentials: 'include', headers: __assign$3(__assign$3({ 'X-CSRFToken': getCsrfToken(), 'Content-Type': 'application/json' }, sourceInfo), (options.headers || {})) }, options);
9478                        console.info(fetchOptions, fullUrl);
9479                        return [4 /*yield*/, fetch(fullUrl, fetchOptions)];
9480                    case 1:
9481                        response = _a.sent();
9482                        return [2 /*return*/, parseResponse(response, "url: ".concat(fullUrl, ", params: ").concat(JSON.stringify(params)))];
9483                }
9484            });
9485        });
9486    }
9487    // refer fetchGet, write a fetchPost
9488    function fetchPost(url_1, requestData_1) {
9489        return __awaiter$7(this, arguments, void 0, function (url, requestData, options) {
9490            var isFormData, isUrlEncoded, baseHeaders, fetchOptions, response;
9491            if (options === void 0) { options = {}; }
9492            return __generator$7(this, function (_a) {
9493                switch (_a.label) {
9494                    case 0:
9495                        isFormData = typeof FormData !== 'undefined' && requestData instanceof FormData;
9496                        isUrlEncoded = requestData instanceof URLSearchParams;
9497                        baseHeaders = __assign$3(__assign$3({ 'X-CSRFToken': getCsrfToken() }, sourceInfo), options.headers);
9498                        // FormData / URLSearchParams 由浏览器自动设置正确的 Content-Type 与 boundary
9499                        if (!isFormData && !isUrlEncoded) {
9500                            baseHeaders['Content-Type'] = 'application/json';
9501                        }
9502                        fetchOptions = __assign$3({ method: 'POST', credentials: 'include', headers: baseHeaders, body: isFormData || isUrlEncoded
9503                                ? requestData
9504                                : JSON.stringify(requestData) }, options);
9505                        return [4 /*yield*/, fetch(url, fetchOptions)];
9506                    case 1:
9507                        response = _a.sent();
9508                        return [2 /*return*/, parseResponse(response, "url: ".concat(url, ", requestData: ").concat(JSON.stringify(requestData)))];
9509                }
9510            });
9511        });
9512    }
9513
9514    var CAREER_PATH = {
9515        home: '/spx-career-home-page.html',
9516        jobs: '/career/jobs.html',
9517        detail: '/career/job-detail.html',
9518        apply: '/career/apply',
9519    };
9520    var CAREER_LEGACY_PATH = {
9521        home: '/career',
9522        jobs: '/career/jobs',
9523        detail: '/career/job-detail',
9524        apply: '/career/apply',
9525    };
9526    var buildQueryString = function (query) {
9527        var entries = Object.entries(query).filter(function (_a) {
9528            var value = _a[1];
9529            return value !== undefined && value !== '';
9530        });
9531        if (entries.length === 0)
9532            return '';
9533        return ('?' +
9534            entries
9535                .map(function (_a) {
9536                var key = _a[0], value = _a[1];
9537                return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(String(value)));
9538            })
9539                .join('&'));
9540    };
9541    var LANG_PREFIXES = ['en', 'vi', 'cn', 'th', 'ms', 'id', 'br', 'fil', 'zh-Hans', 'zh-Hant'];
9542    var getCurrentPathname = function () {
9543        var _a;
9544        if (typeof window === 'undefined' || !((_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 ? void 0 : _a.pathname)) {
9545            return '';
9546        }
9547        return window.location.pathname;
9548    };
9549    var getCurrentSearch = function () {
9550        var _a;
9551        if (typeof window === 'undefined' || !((_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 ? void 0 : _a.search)) {
9552            return '';
9553        }
9554        return window.location.search;
9555    };
9556    var getLangPrefix = function (path) {
9557        var firstSegment = (path || getCurrentPathname()).split('/')[1] || '';
9558        if (LANG_PREFIXES.includes(firstSegment)) {
9559            return '/' + firstSegment;
9560        }
9561        return '';
9562    };
9563    function buildCareerJobsUrl(query, path) {
9564        if (query === void 0) { query = {}; }
9565        var page_size = query.page_size, rest = __rest(query, ["page_size"]);
9566        var params = __assign$3(__assign$3({}, rest), { page_size: page_size });
9567        return "".concat(getLangPrefix(path)).concat(CAREER_PATH.jobs).concat(buildQueryString(params));
9568    }
9569    function parseCareerJobsQuery(search) {
9570        var raw = getCurrentSearch() || '';
9571        var params = new URLSearchParams(raw.startsWith('?') ? raw.slice(1) : raw);
9572        var pageRaw = params.get('page');
9573        var pageSizeRaw = params.get('page_size');
9574        var page = pageRaw ? Number(pageRaw) : undefined;
9575        var pageSize = pageSizeRaw ? Number(pageSizeRaw) : undefined;
9576        return {
9577            keyword: params.get('keyword') || undefined,
9578            department: params.get('department') || undefined,
9579            location: params.get('location') || undefined,
9580            level: params.get('level') || undefined,
9581            page: Number.isFinite(page) ? page : undefined,
9582            page_size: Number.isFinite(pageSize) ? pageSize : undefined,
9583        };
9584    }
9585    function buildCareerDetailUrl(jobId, path) {
9586        return "".concat(getLangPrefix(path)).concat(CAREER_PATH.detail).concat(buildQueryString({ job_id: jobId }));
9587    }
9588    function getCareerJobId(search) {
9589        var raw = getCurrentSearch() || '';
9590        var params = new URLSearchParams(raw.startsWith('?') ? raw.slice(1) : raw);
9591        return params.get('job_id') || undefined;
9592    }
9593    function getCareerChannel(search) {
9594        var raw = getCurrentSearch() || '';
9595        var params = new URLSearchParams(raw.startsWith('?') ? raw.slice(1) : raw);
9596        return params.get('channel') || undefined;
9597    }
9598    function buildCareerApplyUrl(jobId, channel) {
9599        return "".concat(CAREER_PATH.apply).concat(buildQueryString({ job_id: jobId, channel: channel }));
9600    }
9601    var stripLangPrefix = function (path) {
9602        var langPattern = /^\/(en|vi|cn|th|ms|id|br|fil|zh-Hans|zh-Hant)(\/|$)/;
9603        return path.replace(langPattern, '/');
9604    };
9605    var normalizeCareerPath = function (path) {
9606        return stripLangPrefix((path || getCurrentPathname() || '').split('?')[0].replace(/\/+$/, ''));
9607    };
9608    var isCareerHomePath$1 = function (path) {
9609        var target = normalizeCareerPath(path);
9610        return (target === CAREER_LEGACY_PATH.home ||
9611            target === CAREER_PATH.home ||
9612            target.endsWith(CAREER_PATH.home));
9613    };
9614    var getCareerBasePath = function (path) {
9615        var target = normalizeCareerPath(path);
9616        if (!target) {
9617            return CAREER_PATH.home.replace(/\.html$/, '');
9618        }
9619        var withoutDetail = target
9620            .replace(/\/job-detail(?:\.html)?$/, '')
9621            .replace(/\/jobs(?:\.html)?$/, '')
9622            .replace(/\.html$/, '');
9623        if (withoutDetail === CAREER_LEGACY_PATH.home) {
9624            return CAREER_PATH.home.replace(/\.html$/, '');
9625        }
9626        return withoutDetail || CAREER_PATH.home.replace(/\.html$/, '');
9627    };
9628    function buildCareerHomeConfigPath(path) {
9629        return "".concat(getLangPrefix(path)).concat(getCareerBasePath(path), ".html");
9630    }
9631    var isCareerPath = {
9632        home: function (path) {
9633            return isCareerHomePath$1(path);
9634        },
9635        jobs: function (path) {
9636            var target = normalizeCareerPath(path);
9637            return (target === CAREER_PATH.jobs ||
9638                target === CAREER_LEGACY_PATH.jobs ||
9639                /\/jobs(?:\.html)?$/.test(target));
9640        },
9641        detail: function (path) {
9642            var target = normalizeCareerPath(path);
9643            return (target === CAREER_PATH.detail ||
9644                target === CAREER_LEGACY_PATH.detail ||
9645                /\/job-detail(?:\.html)?$/.test(target));
9646        },
9647        apply: function (path) {
9648            var target = normalizeCareerPath(path);
9649            return target.includes(CAREER_PATH.apply);
9650        },
9651    };
9652
9653    var shopee = {
9654    	id: "shopee",
9655    	theme: {
9656    		primaryColor: "#ee4d2d",
9657    		primaryColorHighlight: "color-mix(in srgb, #ee4d2d 96%, black)",
9658    		backgroundColor: "#fff5f0",
9659    		blurColor: "rgba(255, 91, 30, 0.15)"
9660    	},
9661    	branding: {
9662    		logo: "/new_static/assets/images/sea-logo.svg",
9663    		favicon: "/new_static/assets/images/favicon.ico",
9664    		appleTouchIcon: "/new_static/assets/images/favicon.png",
9665    		logoWrapperClass: "main-menu__logo",
9666    		logoClass: "main-menu__logo-shopee",
9667    		footerLogoClass: "footer__logo"
9668    	}
9669    };
9670    var ctl = {
9671    	id: "ctl",
9672    	theme: {
9673    		primaryColor: "#00a551",
9674    		primaryColorHighlight: "color-mix(in srgb, #00a551 96%, black)",
9675    		backgroundColor: "#eefcf5",
9676    		blurColor: "rgba(0, 165, 81, 0.15)"
9677    	},
9678    	branding: {
9679    		logo: "/new_static/assets/images/logo-my-ctl.png",
9680    		favicon: "/new_static/assets/images/citylink-favicon.ico",
9681    		appleTouchIcon: "/new_static/assets/images/citylink-favicon.png",
9682    		logoWrapperClass: "main-menu__logo-ctl-container",
9683    		logoClass: "main-menu__logo-ctl",
9684    		footerLogoClass: "footer__logo-ctl"
9685    	}
9686    };
9687    var partnerships = {
9688    	shopee: shopee,
9689    	ctl: ctl
9690    };
9691
9692    // Import from shared JSON configuration
9693    var PARTNERSHIPS = partnerships;
9694    function getPartnershipConfig(partnerId) {
9695        // Use build-time injected constant 'shopee'
9696        var id = 'shopee';
9697        return PARTNERSHIPS[id] || PARTNERSHIPS.shopee;
9698    }
9699
9700    var DETAIL_PAGE_TYPE = {
9701        home: 1,
9702        secondary: 2,
9703        aboutUs: 3,
9704        notShow: 4,
9705        career: 5,
9706    };
9707
9708    /**
9709     * Convert language in URL to current language
9710     *
9711     * @param params - Object containing all parameters for the conversion
9712     * @returns The converted URL or original URL if conversion is not applicable
9713     */
9714    var convertLangInUrl = function (_a) {
9715        var originalUrl = _a.originalUrl, currentLang = _a.currentLang, activeConfigUrl = _a.activeConfigUrl;
9716        if (!originalUrl || !currentLang) {
9717            return originalUrl;
9718        }
9719        var currentRegion = (getRegion());
9720        var supportedLanguages = languageListMapByRegion[currentRegion] || [];
9721        if (!supportedLanguages.includes(currentLang)) {
9722            return originalUrl;
9723        }
9724        var currentOrigin = getSpxServerOrigin();
9725        var currentUrlLang = convertLangForUrl(currentLang);
9726        if (originalUrl === '/') {
9727            return "/".concat(currentUrlLang);
9728        }
9729        if (originalUrl.startsWith('http') || originalUrl.startsWith('/')) {
9730            try {
9731                var cleanOriginalUrl = originalUrl.startsWith('/') ? "".concat(currentOrigin).concat(originalUrl) : originalUrl;
9732                var urlObj = new URL(cleanOriginalUrl);
9733                // 原链接可能是http, 需要兼容
9734                if ("https://".concat(urlObj.hostname) !== currentOrigin) {
9735                    return originalUrl;
9736                }
9737                var pathname = urlObj.pathname;
9738                // 如果路径在 activeConfigUrl 中,则直接返回当前语言的 URL
9739                if (activeConfigUrl.includes(pathname)) {
9740                    return "".concat(urlObj.origin, "/").concat(currentUrlLang, "/").concat(pathname).concat(urlObj.search).concat(urlObj.hash);
9741                }
9742                var pathParts = pathname.split('/').filter(Boolean);
9743                if (pathParts.length === 0) {
9744                    return "".concat(urlObj.origin, "/").concat(currentUrlLang).concat(urlObj.search).concat(urlObj.hash);
9745                }
9746                var firstPart = pathParts[0];
9747                var convertedUrlLang = convertUrlLangForI18n(firstPart);
9748                if (!supportedLanguages.includes(convertedUrlLang)) {
9749                    return originalUrl;
9750                }
9751                var convertedLang = convertLangForUrl(currentLang);
9752                if (pathParts.length === 1) {
9753                    return "".concat(urlObj.origin, "/").concat(convertedLang).concat(urlObj.search).concat(urlObj.hash);
9754                }
9755                pathParts[0] = convertedLang;
9756                return "".concat(urlObj.origin, "/").concat(pathParts.join('/')).concat(urlObj.search).concat(urlObj.hash);
9757            }
9758            catch (_b) {
9759                return originalUrl;
9760            }
9761        }
9762        return originalUrl;
9763    };
9764    /**
9765     * Normalize configuration data by converting URLs based on the provided configuration
9766     *
9767     * This function recursively processes configuration objects and converts URL fields
9768     * from one language to another based on the provided keysConfig.
9769     * Note: This function mutates the original configData object for better performance.
9770     *
9771     * @param params - Object containing all parameters for the normalization
9772     * @returns The normalized configuration data with converted URLs (same reference as input)
9773     *
9774     * @example
9775     * // Basic usage with TemplateData
9776     * const templateData = {
9777     *   about_us: {
9778     *     title: 'About Us',
9779     *     link: '/en/about-us'
9780     *   },
9781     *   service: {
9782     *     item_list: [
9783     *       { title: 'Service 1', link: '/en/service1' },
9784     *       { title: 'Service 2', link: '/en/service2' }
9785     *     ]
9786     *   }
9787     * }
9788     *
9789     * const keysConfig = {
9790     *   about_us: {
9791     *     link: true  // Convert about_us.link
9792     *   },
9793     *   service: {
9794     *     item_list: [{  // For arrays, specify config for array items
9795     *       link: true   // Convert service.item_list[].link
9796     *     }]
9797     *   }
9798     * }
9799     *
9800     * const normalized = normalizeConfigData({
9801     *   configData: templateData,
9802     *   keysConfig,
9803     *   lang: 'zh-Hans',
9804     *   activeConfigUrl: ['about-us', 'service1', 'service2'],
9805     *   region: 'ID'
9806     * })
9807     * // Result: about_us.link becomes '/zh-Hans/about-us'
9808     * //         service.item_list[0].link becomes '/zh-Hans/service1'
9809     * //         service.item_list[1].link becomes '/zh-Hans/service2'
9810     *
9811     * @example
9812     * // Usage with nested menu structure
9813     * const menuConfig = {
9814     *   menu: {
9815     *     shipping: {
9816     *       main_menu: [{
9817     *         link_url: true  // Convert all main_menu items' link_url
9818     *       }],
9819     *       sub_menu: [{
9820     *         link_url: true  // Convert all sub_menu items' link_url
9821     *       }]
9822     *     }
9823     *   }
9824     * }
9825     */
9826    var normalizeConfigData = function (_a) {
9827        var configData = _a.configData, keysConfig = _a.keysConfig, lang = _a.lang, activeConfigUrl = _a.activeConfigUrl, region = _a.region;
9828        if (!configData || typeof configData !== 'object' || !activeConfigUrl || activeConfigUrl.length === 0) {
9829            return configData;
9830        }
9831        /**
9832         * Recursively process nested objects and arrays based on configuration
9833         */
9834        var processValue = function (value, config, path) {
9835            if (path === void 0) { path = []; }
9836            // If config is true, convert this value if it's a string URL
9837            if (config === true) {
9838                if (typeof value === 'string' && value.trim()) {
9839                    var convertedUrl = convertLangInUrl({
9840                        originalUrl: value,
9841                        currentLang: lang,
9842                        region: region,
9843                        activeConfigUrl: activeConfigUrl
9844                    });
9845                    return convertedUrl;
9846                }
9847                return value;
9848            }
9849            // If config is false or not provided, return original value
9850            if (config === false || config === undefined) {
9851                return value;
9852            }
9853            // If value is null or undefined, return as is
9854            if (value == null) {
9855                return value;
9856            }
9857            // Handle arrays
9858            if (Array.isArray(value) && Array.isArray(config)) {
9859                return value.map(function (item, index) {
9860                    // Use the first config item for all array elements, or specific index if available
9861                    var itemConfig = config[index] || config[0] || false;
9862                    return processValue(item, itemConfig, __spreadArray$2(__spreadArray$2([], path, true), [index.toString()], false));
9863                });
9864            }
9865            // Handle objects
9866            if (typeof value === 'object' && typeof config === 'object' && !Array.isArray(config)) {
9867                var result = {};
9868                for (var _i = 0, _a = Object.entries(value); _i < _a.length; _i++) {
9869                    var _b = _a[_i], key = _b[0], val = _b[1];
9870                    var keyConfig = config[key];
9871                    result[key] = processValue(val, keyConfig, __spreadArray$2(__spreadArray$2([], path, true), [key], false));
9872                }
9873                return result;
9874            }
9875            // Default: return original value
9876            return value;
9877        };
9878        // Process each top-level key in the data (mutating the original object)
9879        for (var _i = 0, _b = Object.entries(configData); _i < _b.length; _i++) {
9880            var _c = _b[_i], key = _c[0], value = _c[1];
9881            var keyConfig = keysConfig[key];
9882            if (keyConfig !== undefined) {
9883                configData[key] = processValue(value, keyConfig, [ke
9883y]);
9884            }
9885        }
9886        return configData;
9887    };
9888
9889    var _a$3;
9890    var DisplayLimitType;
9891    (function (DisplayLimitType) {
9892        DisplayLimitType[DisplayLimitType["Unlimited"] = 1] = "Unlimited";
9893        DisplayLimitType[DisplayLimitType["Max"] = 2] = "Max";
9894    })(DisplayLimitType || (DisplayLimitType = {}));
9895    var DisplayLimitUnit;
9896    (function (DisplayLimitUnit) {
9897        DisplayLimitUnit[DisplayLimitUnit["NotApplicable"] = 0] = "NotApplicable";
9898        DisplayLimitUnit[DisplayLimitUnit["Hour"] = 1] = "Hour";
9899        DisplayLimitUnit[DisplayLimitUnit["Day"] = 2] = "Day";
9900        DisplayLimitUnit[DisplayLimitUnit["Week"] = 3] = "Week";
9901    })(DisplayLimitUnit || (DisplayLimitUnit = {}));
9902    var WEBSITE_POPUP_TYPE = 4;
9903    var DISPLAY_WINDOW_SECONDS = (_a$3 = {},
9904        _a$3[DisplayLimitUnit.NotApplicable] = 0,
9905        _a$3[DisplayLimitUnit.Hour] = 3600,
9906        _a$3[DisplayLimitUnit.Day] = 86400,
9907        _a$3[DisplayLimitUnit.Week] = 604800,
9908        _a$3);
9909    function selectWebsitePopupPlanFromBannerPlan(plan, mobile, mode) {
9910        if (mode === void 0) { mode = 'live'; }
9911        return plan ? mapWebsitePopupPlan(plan, mobile, mode) : null;
9912    }
9913    function getWebsitePopupTemplateData(data, pageType) {
9914        var _a, _b, _c;
9915        var plan = (_b = (_a = data === null || data === void 0 ? void 0 : data.banner) === null || _a === void 0 ? void 0 : _a.banner_plan) === null || _b === void 0 ? void 0 : _b.find(function (item) { return item.banner_type === WEBSITE_POPUP_TYPE &&
9916            matchesTargetPage(item, data === null || data === void 0 ? void 0 : data.page_path, pageType); });
9917        if (!plan) {
9918            return null;
9919        }
9920        var item = (_c = plan === null || plan === void 0 ? void 0 : plan.item_list) === null || _c === void 0 ? void 0 : _c[0];
9921        if (!item) {
9922            return null;
9923        }
9924        return {
9925            popupConfig: JSON.stringify(plan),
9926            imageUrlPc: item === null || item === void 0 ? void 0 : item.banner_url_pc,
9927            imageUrlMobile: item.banner_url_mobile,
9928            linkUrl: item.link,
9929            popupSize: mapPopupSize(item.popup_size),
9930        };
9931    }
9932    function matchesTargetPage(plan, pagePath, pageType) {
9933        var targetPage = plan.target_page;
9934        if (targetPage === undefined || targetPage === 'all')
9935            return true;
9936        if (targetPage === 'home' || targetPage === 'index' || targetPage === 1) {
9937            return pageType === 'index';
9938        }
9939        if (targetPage === 'detail' || targetPage === 'secondary' || targetPage === 2) {
9940            return pageType === 'detail';
9941        }
9942        return targetPage === pagePath;
9943    }
9944    function mapWebsitePopupPlan(plan, mobile, mode) {
9945        var _a;
9946        var item = (_a = plan.item_list) === null || _a === void 0 ? void 0 : _a[0];
9947        var imageUrl = mobile ? item === null || item === void 0 ? void 0 : item.banner_url_mobile : item === null || item === void 0 ? void 0 : item.banner_url_pc;
9948        if (!isValidPopupPlan(plan, mode) || !imageUrl) {
9949            return null;
9950        }
9951        return {
9952            planId: plan.plan_id,
9953            effectiveStartTime: plan.effective_start_time,
9954            effectiveEndTime: plan.effective_end_time,
9955            displayLimitType: plan.display_limit_type || DisplayLimitType.Unlimited,
9956            displayLimitValue: plan.display_limit_value || 0,
9957            displayLimitUnit: plan.display_limit_unit || DisplayLimitUnit.NotApplicable,
9958            imageUrl: imageUrl,
9959            linkUrl: item === null || item === void 0 ? void 0 : item.link,
9960            popupSize: mapPopupSize(item === null || item === void 0 ? void 0 : item.popup_size),
9961        };
9962    }
9963    function isValidPopupPlan(plan, mode) {
9964        if (mode === 'live' && !plan.plan_id) {
9965            return false;
9966        }
9967        if (!plan.effective_start_time || !plan.effective_end_time) {
9968            return false;
9969        }
9970        // banner pool 预览没有 display limit 配置,预览时按不限次展示
9971        if (mode === 'preview' || plan.display_limit_type === DisplayLimitType.Unlimited) {
9972            return true;
9973        }
9974        return plan.display_limit_type === DisplayLimitType.Max &&
9975            !!plan.display_limit_value &&
9976            isDisplayLimitUnit(plan.display_limit_unit);
9977    }
9978    function isDisplayLimitUnit(unit) {
9979        return unit === DisplayLimitUnit.Hour ||
9980            unit === DisplayLimitUnit.Day ||
9981            unit === DisplayLimitUnit.Week;
9982    }
9983    function mapPopupSize(size) {
9984        if (size === 1)
9985            return 'large';
9986        if (size === 3)
9987            return 'small';
9988        return 'medium';
9989    }
9990    function mapPopupImpressionState(response) {
9991        return {
9992            planId: response.plan_id,
9993            impressionCount: response.impression_count,
9994            lastImpressionTime: response.last_impression_time,
9995        };
9996    }
9997    function shouldShowPopup(plan, state, nowSeconds) {
9998        if (nowSeconds < plan.effectiveStartTime || nowSeconds > plan.effectiveEndTime) {
9999            return false;
10000        }
10001        if (plan.displayLimitType === DisplayLimitType.Unlimited) {
10002            return true;
10003        }
10004        return getEffectiveImpressionCount(plan, state, nowSeconds) < plan.displayLimitValue;
10005    }
10006    function getEffectiveImpressionCount(plan, state, nowSeconds) {
10007        return isPopupCacheExpired(plan, state, nowSeconds) ? 0 : state.impressionCount;
10008    }
10009    function isPopupCacheExpired(plan, state, nowSeconds) {
10010        if (nowSeconds > plan.effectiveEndTime)
10011            return true;
10012        if (plan.displayLimitType === DisplayLimitType.Unlimited)
10013            return false;
10014        var windowSeconds = DISPLAY_WINDOW_SECONDS[plan.displayLimitUnit];
10015        return !state.lastImpressionTime ||
10016            state.lastImpressionTime + windowSeconds <= nowSeconds;
10017    }
10018    function recordLocalExposure(plan, state, nowSeconds) {
10019        return {
10020            planId: plan.planId || state.planId,
10021            impressionCount: getEffectiveImpressionCount(plan, state, nowSeconds) + 1,
10022            lastImpressionTime: nowSeconds,
10023        };
10024    }
10025
10026    var CAREER_PAGE_TYPE = {
10027        home: 'index',
10028        detail: 'detail',
10029    };
10030    var CAREER_SORT_MODULES = [
10031        'career_search',
10032        'department',
10033        'career_home',
10034        'career_jobs',
10035        'career_job_detail',
10036    ];
10037    var CAREER_COMPONENT_KEYS = [
10038        'career_search',
10039        'department',
10040        'career_home',
10041        'career_jobs',
10042        'career_job_detail',
10043    ];
10044    var isCareerHomePath = function (path) { return isCareerPath.home(path); };
10045    var isCareerJobsPath = function (path) { return isCareerPath.jobs(path); };
10046    var isCareerJobDetailPath = function (path) { return isCareerPath.detail(path); };
10047    var isCareerPagePath = function (path) {
10048        return isCareerHomePath(path) || isCareerJobsPath(path) || isCareerJobDetailPath(path);
10049    };
10050    var getCurrentBrowserPath = function () {
10051        if (typeof window === 'undefined' || !window.location) {
10052            return undefined;
10053        }
10054        var pathname = window.location.pathname || '';
10055        var search = window.location.search || '';
10056        return pathname ? "".concat(pathname).concat(search) : undefined;
10057    };
10058    // 根据 pageType + path 拼出 website info 接口的 query params。
10059    // - home: 只传 language
10060    // - secondary: 统一传 ?language=&path=,path 保留语言前缀(/en/、/vi/ 等)
10061    var normalizeCareerWebsiteInfoPath = function (path) {
10062        var currentPath = path || getCurrentBrowserPath();
10063        if (!currentPath) {
10064            return currentPath;
10065        }
10066        var _a = currentPath.split('?'), pathname = _a[0], _b = _a[1], search = _b === void 0 ? '' : _b;
10067        var normalizedPathname = pathname;
10068        var isCareerPagePath = isCareerHomePath(pathname) ||
10069            isCareerJobsPath(pathname) ||
10070            isCareerJobDetailPath(pathname);
10071        if (isCareerPagePath) {
10072            normalizedPathname = buildCareerHomeConfigPath(pathname);
10073        }
10074        return isCareerPagePath
10075            ? normalizedPathname
10076            : search
10077                ? "".concat(normalizedPathname, "?").concat(search)
10078                : normalizedPathname;
10079    };
10080    var buildWebsiteInfoParams = function (pageType, language, path) {
10081        if (pageType === CAREER_PAGE_TYPE.home) {
10082            return { language: language };
10083        }
10084        var currentPath = path || getCurrentBrowserPath();
10085        if (pageType === CAREER_PAGE_TYPE.detail && isCareerPagePath(currentPath)) {
10086            return {
10087                language: language,
10088                page_type: DETAIL_PAGE_TYPE.career,
10089                path: normalizeCareerWebsiteInfoPath(currentPath),
10090            };
10091        }
10092        return { language: language, path: normalizeCareerWebsiteInfoPath(currentPath) };
10093    };
10094
10095    // 模块级缓存:dept/job_count 和 city/job_count 的 id→name 映射,作为 meta/slice 数据不足时的兜底
10096    var _deptJobCountCache = null;
10097    var _cityJobCountCache = null;
10098    var setDeptJobCountCache = function (data) { _deptJobCountCache = data; };
10099    var setCityJobCountCache = function (data) { _cityJobCountCache = data; };
10100    var tCareer = function (key) { return $gt(key) || key; };
10101    var escapeCareerHtml = function (value) {
10102        return String(value)
10103            .replace(/&/g, '&amp;')
10104            .replace(/</g, '&lt;')
10105            .replace(/>/g, '&gt;')
10106            .replace(/"/g, '&quot;')
10107            .replace(/'/g, '&#39;');
10108    };
10109    var sanitizeHtml = function (html) {
10110        if (!html)
10111            return '';
10112        // 白名单过滤:仅允许基础排版标签,去除 script/style/on* 事件与 javascript: 协议
10113        return String(html)
10114            .replace(/<\s*script[\s\S]*?<\s*\/\s*script\s*>/gi, '')
10115            .replace(/<\s*style[\s\S]*?<\s*\/\s*style\s*>/gi, '')
10116            .replace(/<\s*link[^>]*>/gi, '')
10117            .replace(/ on[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, '')
10118            .replace(/(href|src)\s*=\s*("\s*javascript:[^"]*"|'\s*javascript:[^']*'|javascript:[^\s>]+)/gi, '$1="#"');
10119    };
10120    var formatCareerEmploymentName = function (meta, employmentId) {
10121        if (employmentId === undefined || employmentId === null || employmentId === 0)
10122            return '';
10123        if (!meta || !Array.isArray(meta.employment_level_list))
10124            return "".concat(tCareer('Level'), " ").concat(employmentId);
10125        var id = String(employmentId);
10126        var item = meta.employment_level_list.find(function (l) { return String(l.employment_level_id) === id; });
10127        return item ? (item.default_text || item.employment_type_name || '') : "".concat(tCareer('Level'), " ").concat(employmentId);
10128    };
10129    var formatCareerCityName = function (meta, cityId) {
10130        if (cityId === undefined || cityId === null || cityId === 0)
10131            return '';
10132        var id = String(cityId);
10133        if (meta && Array.isArray(meta.flat_locations)) {
10134            var item = meta.flat_locations.find(function (l) { return String(l.city_id) === id; });
10135            if (item)
10136                return item.city_name || '';
10137        }
10138        if (Array.isArray(_cityJobCountCache)) {
10139            for (var _i = 0, _cityJobCountCache_1 = _cityJobCountCache; _i < _cityJobCountCache_1.length; _i++) {
10140                var region = _cityJobCountCache_1[_i];
10141                if (Array.isArray(region.cities)) {
10142                    var city = region.cities.find(function (c) { return String(c.city_id) === id; });
10143                    if (city === null || city === void 0 ? void 0 : city.city_name)
10144                        return city.city_name;
10145                }
10146            }
10147        }
10148        return "".concat(tCareer('City'), " ").concat(cityId);
10149    };
10150    var formatCareerDeptName = function (meta, deptId) {
10151        if (deptId === undefined || deptId === null || deptId === 0)
10152            return '';
10153        var id = String(deptId);
10154        if (meta) {
10155            if (Array.isArray(meta.dept_list)) {
10156                var item = meta.dept_list.find(function (d) { return String(d.dept_id) === id; });
10157                if (item === null || item === void 0 ? void 0 : item.dept_name)
10158                    return item.dept_name;
10159            }
10160            if (meta.department_name_map) {
10161                for (var _i = 0, _a = Object.keys(meta.department_name_map); _i < _a.length; _i++) {
10162                    var key = _a[_i];
10163                    var list = meta.department_name_map[key];
10164                    if (Array.isArray(list)) {
10165                        var match = list.find(function (d) { return String(d.department_id) === id; });
10166                        if (match === null || match === void 0 ? void 0 : match.department_name)
10167                            return match.department_name;
10168                    }
10169                }
10170            }
10171        }
10172        if (Array.isArray(_deptJobCountCache)) {
10173            var item = _deptJobCountCache.find(function (d) { return String(d.dept_id) === id; });
10174            if (item === null || item === void 0 ? void 0 : item.dept_name)
10175                return item.dept_name;
10176        }
10177        return "".concat(tCareer('Dept'), " ").concat(deptId);
10178    };
10179
10180    var getCareerShellPagePath = function (defaultPath, path) {
10181        if (path) {
10182            var currentPath = getCurrentBrowserPath();
10183            if (currentPath && !path.includes('?')) {
10184                var _a = currentPath.split('?'), currentPathname = _a[0], _b = _a[1], currentSearch = _b === void 0 ? '' : _b;
10185                if (currentPathname === path && currentSearch) {
10186                    return "".concat(path, "?").concat(currentSearch);
10187                }
10188            }
10189            return path;
10190        }
10191        return getCurrentBrowserPath() || defaultPath;
10192    };
10193    var getCareerChannelFromPath = function (path) {
10194        var search = path.split('?')[1] || '';
10195        if (!search)
10196            return undefined;
10197        return new URLSearchParams(search).get('channel') || undefined;
10198    };
10199    var getCareerJobsShellConfig = function (query, path) {
10200        if (query === void 0) { query = {}; }
10201        var keyword = query.keyword || '';
10202        return {
10203            page_path: getCareerShellPagePath('/career/jobs.html', path),
10204            sort_module: ['career_jobs'],
10205            career_jobs: {
10206                banner: {
10207                    image_url: '',
10208                    title: '',
10209                    subtitle: '',
10210                },
10211                search: {
10212                    action: buildCareerJobsUrl({}, path),
10213                    placeholder: tCareer('Type in keyword'),
10214                    button_text: tCareer('Search Job'),
10215                    keyword: keyword,
10216                },
10217                filters: [
10218                    { key: 'department', title: tCareer('Department'), options: [] },
10219                    { key: 'level', title: tCareer('Level'), options: [] },
10220                    { key: 'location', title: tCareer('Location'), options: [] },
10221                ],
10222                list: {
10223                    title: tCareer('Available Positions'),
10224                    total_label: "0 ".concat(tCareer('Positions')),
10225                    empty: true,
10226                    empty_text: tCareer('No jobs match your filters. Try clearing some filters.'),
10227                    items: [],
10228                },
10229                pagination: {
10230                    prev_text: tCareer('Previous'),
10231                    next_text: tCareer('Next'),
10232                    prev_disabled: true,
10233                    next_disabled: true,
10234                    pages: [],
10235                },
10236            },
10237        };
10238    };
10239    var getCareerJobDetailShellConfig = function (jobId, path) {
10240        var pagePath = getCareerShellPagePath('/career/job-detail.html', path);
10241        var channel = getCareerChannelFromPath(pagePath);
10242        return {
10243            page_path: pagePath,
10244            sort_module: ['career_job_detail'],
10245            career_job_detail: {
10246                job: {
10247                    job_id: jobId || '',
10248                    job_name: tCareer('Loading…'),
10249                    department_name: '',
10250                    employment_name: '',
10251                    city_name: '',
10252                },
10253                apply_url: buildCareerApplyUrl(jobId || '', channel),
10254                apply_text: tCareer('Apply Now'),
10255                loading_text: tCareer('Loading job details…'),
10256            },
10257        };
10258    };
10259    var getCareerHomeShellConfig = function (path) { return ({
10260        page_path: '/career',
10261        sort_module: ['career_home'],
10262        career_home: {
10263            jobs_path: buildCareerJobsUrl({}, path),
10264            hero: {
10265                title: tCareer('Speed. Precision. Impact.'),
10266                subtitle: tCareer('Build the future of logistics with teams who move quickly, think clearly, and care deeply about every delivery.'),
10267                image_url: 'https://images.unsplash.com/photo-1556761175-b413da4baf72?auto=format&fit=crop&w=1800&q=80',
10268            },
10269            search: {
10270                placeholder: tCareer('Type in keyword'),
10271                button_text: tCareer('Search Job'),
10272            },
10273            intro: {
10274                title: tCareer('Make it Simple. Make it Last'),
10275                description: tCareer('At SPX, you will shape the future of simple, reliable digital finance that better fits the lives of individuals and businesses. You will create impact that lasts and grow in a vibrant, digital-first culture built around trust, collaboration, and excellence.'),
10276            },
10277            departments: {
10278                title: tCareer('Find Your Passion'),
10279                // 部门列表不再 fallback 写死,由 /dept/job_count 在前端运行时动态渲染
10280                item_list: [],
10281            },
10282            apply_button: {
10283                text: tCareer('Apply Now'),
10284                link_url: buildCareerJobsUrl({}, path),
10285            },
10286            life: {
10287                title: tCareer('Life at SPX'),
10288                images: [
10289                    {
10290                        url: 'https://images.unsplash.com/photo-1515169067868-5387ec356754?auto=format&fit=crop&w=520&q=80',
10291                        alt: tCareer('SPX event'),
10292                    },
10293                    {
10294                        url: 'https://images.unsplash.com/photo-1552664730-d307ca884978?auto=format&fit=crop&w=960&q=80',
10295                        alt: tCareer('SPX teammates collaborating'),
10296                        main: true,
10297                    },
10298                    {
10299                        url: 'https://images.unsplash.com/photo-1531482615713-2afd69097998?auto=format&fit=crop&w=520&q=80',
10300                        alt: tCareer('SPX workplace'),
10301                    },
10302                ],
10303            },
10304        },
10305    }); };
10306    // 把 spx-open-account secondary/info 返回的 data 映射到 career_home 模板需要的结构。
10307    // 模板字段来源(API 已经在服务端按 language 过滤,所以直接取非后缀字段):
10308    //   hero          <- basic.page_title / basic.page_sub_title + banner.banner_url_pc
10309    //   intro         <- main_introduction.introduction_with_photos.title / text
10310    //   departments   <- department.title(item_list 始终为空,由 runtime /dept/job_count 动态填充)
10311    //   life          <- text_and_image.only_images.title / item_list[].image_url / desc
10312    // 任意字段 API 没给就回退到 fallback'
10313    var normalizeCareerHomeSortModules = function (apiSortModules) {
10314        if (!Array.isArray(apiSortModules) || apiSortModules.length === 0) {
10315            return ['banner', 'career_search', 'main_introduction', 'department', 'text_and_image'];
10316        }
10317        var modules = [];
10318        apiSortModules.forEach(function (module) {
10319            if (typeof module !== 'string' || !module)
10320                return;
10321            modules.push(module);
10322            if (module === 'banner' && !apiSortModules.includes('career_search')) {
10323                modules.push('career_search');
10324            }
10325        });
10326        if (!modules.includes('career_search')) {
10327            modules.unshift('career_search');
10328        }
10329        return modules;
10330    };
10331    var mapApiDataToCareerHome = function (apiData, fallback, language) {
10332        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
10333        if (!apiData || typeof apiData !== 'object')
10334            return fallback;
10335        var fbHome = fallback.career_home || {};
10336        // 尝试多个位置拿 banner 图片:API 实测可能放在 banner.* 或 default_banner.*
10337        var bannerImage = ((_a = apiData.banner) === null || _a === void 0 ? void 0 : _a.banner_url_pc) ||
10338            ((_b = apiData.banner) === null || _b === void 0 ? void 0 : _b.image_url) ||
10339            ((_c = apiData.banner) === null || _c === void 0 ? void 0 : _c.banner_url) ||
10340            ((_d = apiData.default_banner) === null || _d === void 0 ? void 0 : _d.banner_url_pc) ||
10341            ((_e = apiData.default_banner) === null || _e === void 0 ? void 0 : _e.image_url) ||
10342            ((_f = apiData.default_banner) === null || _f === void 0 ? void 0 : _f.banner_url) ||
10343            '';
10344        var hero = {
10345            title: ((_g = apiData.basic) === null || _g === void 0 ? void 0 : _g.page_title) || ((_h = fbHome.hero) === null || _h === void 0 ? void 0 : _h.title) || '',
10346            subtitle: ((_j = apiData.basic) === null || _j === void 0 ? void 0 : _j.page_sub_title) || ((_k = fbHome.hero) === null || _k === void 0 ? void 0 : _k.subtitle) || '',
10347            image_url: bannerImage || ((_l = fbHome.hero) === null || _l === void 0 ? void 0 : _l.image_url) || '',
10348        };
10349        // main_introduction.is_display=false 时,intro 块整体隐藏(标题/描述都清空)
10350        var introIsDisplay = ((_m = apiData.main_introduction) === null || _m === void 0 ? void 0 : _m.is_display) !== false;
10351        var introPhotos = ((_o = apiData.main_introduction) === null || _o === void 0 ? void 0 : _o.introduction_with_photos) || {};
10352        var intro = introIsDisplay
10353            ? {
10354                title: introPhotos.title || ((_p = fbHome.intro) === null || _p === void 0 ? void 0 : _p.title) || '',
10355                description: introPhotos.text ||
10356                    introPhotos.html_text ||
10357                    introPhotos.edit_text ||
10358                    ((_q = fbHome.intro) === null || _q === void 0 ? void 0 : _q.description) ||
10359                    '',
10360            }
10361            : { title: '', description: '' };
10362        var departments = {
10363            title: ((_r = apiData.department) === null || _r === void 0 ? void 0 : _r.title) || ((_s = fbHome.departments) === null || _s === void 0 ? void 0 : _s.title) || '',
10364            item_list: [],
10365        };
10366        // text_and_image.is_display=false 时,life 块整体隐藏(标题/图片都清空)
10367        var lifeIsDisplay = ((_t = apiData.text_and_image) === null || _t === void 0 ? void 0 : _t.is_display) !== false;
10368        var onlyImages = ((_u = apiData.text_and_image) === null || _u === void 0 ? void 0 : _u.only_images) || {};
10369        var apiImages = (onlyImages.item_list || []).map(function (item) { return ({
10370            url: item.image_url || '',
10371            alt: item.desc || '',
10372        }); });
10373        var life = lifeIsDisplay
10374            ? {
10375                title: onlyImages.title || ((_v = fbHome.life) === null || _v === void 0 ? void 0 : _v.title) || '',
10376                images: apiImages.length > 0 ? apiImages : ((_w = fbHome.life) === null || _w === void 0 ? void 0 : _w.images) || [],
10377            }
10378            : { title: '', images: [] };
10379        return __assign$3(__assign$3({}, apiData), { page_path: apiData.page_path || fallback.page_path, sort_module: normalizeCareerHomeSortModules(apiData.sort_module), career_home: {
10380                jobs_path: fbHome.jobs_path || '/career/jobs',
10381                search: fbHome.search || {
10382                    placeholder: tCareer('Type in keyword'),
10383                    button_text: tCareer('Search Job'),
10384                },
10385                hero: hero,
10386                intro: intro,
10387                departments: departments,
10388                apply_button: fbHome.apply_button || {
10389                    text: tCareer('Apply Now'),
10390                    link_url: buildCareerJobsUrl(),
10391                },
10392                life: life,
10393            } });
10394    };
10395    var getCareerSearchTemplateData = function (configData) {
10396        var fallback = getCareerHomeShellConfig(configData === null || configData === void 0 ? void 0 : configData.page_path);
10397        var fallbackHome = fallback.career_home;
10398        var careerHome = configData.career_home || {};
10399        return {
10400            jobs_path: careerHome.jobs_path ||
10401                fallbackHome.jobs_path ||
10402                buildCareerJobsUrl({}, configData === null || configData === void 0 ? void 0 : configData.page_path),
10403            search: careerHome.search ||
10404                fallbackHome.search || {
10405                placeholder: tCareer('Type in keyword'),
10406                button_text: tCareer('Search Job'),
10407            },
10408        };
10409    };
10410    var getCareerDepartmentTemplateData = function (configData) {
10411        var fallback = getCareerHomeShellConfig(configData === null || configData === void 0 ? void 0 : configData.page_path);
10412        var fallbackHome = fallback.career_home;
10413        var careerHome = configData.career_home || {};
10414        return {
10415            departments: careerHome.departments ||
10416                fallbackHome.departments || {
10417                title: '',
10418                item_list: [],
10419            },
10420            apply_button: careerHome.apply_button ||
10421                fallbackHome.apply_button || {
10422                text: tCareer('Apply Now'),
10423                link_url: buildCareerJobsUrl({}, configData === null || configData === void 0 ? void 0 : configData.page_path),
10424            },
10425        };
10426    };
10427    var getCareerIntroductionTemplateData = function (configData) {
10428        var fallback = getCareerHomeShellConfig(configData === null || configData === void 0 ? void 0 : configData.page_path);
10429        var fallbackHome = fallback.career_home;
10430        var careerHome = configData.career_home || {};
10431        var intro = careerHome.intro || fallbackHome.intro || {};
10432        return {
10433            title: intro.title || '',
10434            description: intro.description || '',
10435        };
10436    };
10437    var getCareerTextAndImageTemplateData = function (configData) {
10438        var fallback = getCareerHomeShellConfig(configData === null || configData === void 0 ? void 0 : configData.page_path);
10439        var fallbackHome = fallback.career_home;
10440        var careerHome = configData.career_home || {};
10441        return careerHome.life || fallbackHome.life || { title: '', images: [] };
10442    };
10443    var isCareerHomeConfigData = function (configData) {
10444        if (!configData || typeof configData !== 'object') {
10445            return false;
10446        }
10447        var sortModules = Array.isArray(configData.sort_module)
10448            ? configData.sort_module
10449            : [];
10450        return Boolean(configData.page_type === DETAIL_PAGE_TYPE.career ||
10451            configData.career_home ||
10452            configData.department ||
10453            sortModules.includes('career_search') ||
10454            sortModules.includes('department') ||
10455            sortModules.includes('career_home'));
10456    };
10457    var getCareerShellBannerImage = function (apiData) {
10458        var _a, _b, _c, _d, _e, _f;
10459        return (((_a = apiData === null || apiData === void 0 ? void 0 : apiData.banner) === null || _a === void 0 ? void 0 : _a.banner_url_pc) ||
10460            ((_b = apiData === null || apiData === void 0 ? void 0 : apiData.banner) === null || _b === void 0 ? void 0 : _b.image_url) ||
10461            ((_c = apiData === null || apiData === void 0 ? void 0 : apiData.banner) === null || _c === void 0 ? void 0 : _c.banner_url) ||
10462            ((_d = apiData === null || apiData === void 0 ? void 0 : apiData.default_banner) === null || _d === void 0 ? void 0 : _d.banner_url_pc) ||
10463            ((_e = apiData === null || apiData === void 0 ? void 0 : apiData.default_banner) === null || _e === void 0 ? void 0 : _e.image_url) ||
10464            ((_f = apiData === null || apiData === void 0 ? void 0 : apiData.default_banner) === null || _f === void 0 ? void 0 : _f.banner_url) ||
10465            '');
10466    };
10467    var mapApiDataToCareerJobs = function (apiData, fallback) {
10468        var _a;
10469        if (!apiData || typeof apiData !== 'object')
10470            return fallback;
10471        var fallbackJobs = fallback.career_jobs || {};
10472        return __assign$3(__assign$3(__assign$3({}, apiData), fallback), { career_jobs: __assign$3(__assign$3({}, fallbackJobs), { banner: {
10473                    image_url: getCareerShellBannerImage(apiData) ||
10474                        ((_a = fallbackJobs.banner) === null || _a === void 0 ? void 0 : _a.image_url) ||
10475                        '',
10476                    title: '',
10477                    subtitle: '',
10478                } }) });
10479    };
10480    var mapApiDataToCareerJobDetail = function (apiData, fallback) {
10481        if (!apiData || typeof apiData !== 'object')
10482            return fallback;
10483        return __assign$3(__assign$3({}, apiData), fallback);
10484    };
10485
10486    var CAREER_API_PREFIX = '/shipment/account/career/user';
10487    // 默认每页 50 条
10488    var DEFAULT_PAGE_SIZE = 50;
10489    var toArray = function (values) {
10490        if (values === undefined || values === null)
10491            return [];
10492        if (Array.isArray(values)) {
10493            return values
10494                .filter(function (v) { return v !== undefined && v !== null && v !== '' && v !== 'undefined' && v !== 'null'; })
10495                .map(function (v) { return String(v); });
10496        }
10497        var value = String(values);
10498        if (value === 'undefined' || value === 'null' || value === '')
10499            return [];
10500        return value.split(',').filter(Boolean);
10501    };
10502    var cleanCareerParams = function (params) {
10503        return Object.entries(params).reduce(function (acc, _a) {
10504            var key = _a[0], value = _a[1];
10505            if (value === undefined ||
10506                value === null ||
10507                (Array.isArray(value) && value.length === 0) ||
10508                value === '' ||
10509                value === 'undefined' ||
10510                value === 'null') {
10511                return acc;
10512            }
10513            acc[key] = value;
10514            return acc;
10515        }, {});
10516    };
10517    var normalizeListReq = function (params) {
10518        var _a, _b, _c, _d, _e, _f, _g;
10519        if (params === void 0) { params = {}; }
10520        var offset = (_a = params.offset) !== null && _a !== void 0 ? _a : (params.page ? Math.max(0, (params.page - 1) * (params.page_size || DEFAULT_PAGE_SIZE)) : 0);
10521        var limit = (_c = (_b = params.limit) !== null && _b !== void 0 ? _b : params.page_size) !== null && _c !== void 0 ? _c : DEFAULT_PAGE_SIZE;
10522        return cleanCareerParams({
10523            search_content: (_d = params.search_content) !== null && _d !== void 0 ? _d : params.keyword,
10524            city_ids: (_e = params.city_ids) !== null && _e !== void 0 ? _e : toArray(params.location),
10525            region_ids: params.region_ids,
10526            employment_ids: (_f = params.employment_ids) !== null && _f !== void 0 ? _f : toArray(params.level),
10527            department_ids: (_g = params.department_ids) !== null && _g !== void 0 ? _g : toArray(params.department),
10528            offset: offset,
10529            limit: limit,
10530            post_type: params.post_type,
10531            search_channel: params.search_channel,
10532            language: params.language,
10533        });
10534    };
10535    var careerApi = {
10536        getDeptJobCount: function (params) {
10537            return fetchGet("".concat(CAREER_API_PREFIX, "/dept/job_count"), cleanCareerParams(params || {}));
10538        },
10539        getCityJobCount: function (params) {
10540            return fetchGet("".concat(CAREER_API_PREFIX, "/city/job_count"), cleanCareerParams(params || {}));
10541        },
10542        getMetaSlice: function (params) {
10543            // 不传 flags 时, 走 DEFAULT_CAREER_META_FLAGS, 确保列表/详情页拿到 city/employment/department name 映射
10544            var merged = params ? __assign$3({}, params) : {};
10545            // merged.flags = params?.flags ?? String(DEFAULT_CAREER_META_FLAGS)
10546            return fetchGet("".concat(CAREER_API_PREFIX, "/meta/slice"), cleanCareerParams(merged));
10547        },
10548        getJobList: function (params) {
10549            if (params === void 0) { params = {}; }
10550            return fetchGet("".concat(CAREER_API_PREFIX, "/job/list"), normalizeListReq(params));
10551        },
10552        getJobDetail: function (params) {
10553            return fetchGet("".concat(CAREER_API_PREFIX, "/job"), cleanCareerParams(params));
10554        },
10555        // 相关职位接口:当前 Home/List/Detail runtime 暂不调用,预留以备后续详情页 Related Jobs 模块启用
10556        getRelatedJobList: function (params) {
10557            return fetchGet("".concat(CAREER_API_PREFIX, "/job/relate_list"), cleanCareerParams(params));
10558        },
10559        uploadFile: function (formData) {
10560            return fetchPost("".concat(CAREER_API_PREFIX, "/file/upload"), formData);
10561        },
10562        parseResume: function (payload) {
10563            return fetchPost("".concat(CAREER_API_PREFIX, "/resume/parsing"), payload);
10564        },
10565        submitDefaultApplication: function (payload) {
10566            return fetchPost("".concat(CAREER_API_PREFIX, "/job/apply"), payload);
10567        },
10568        submitBlueCollarApplication: function (payload) {
10569            return fetchPost("".concat(CAREER_API_PREFIX, "/job/apply/blue_collar"), payload);
10570        },
10571    };
10572
10573    // career home / list / detail 三个页面共用同一份 page config,info 接口统一传 /career
10574    var formatCareerDeptCountText = function (count) {
10575        var safe = typeof count === 'number' && !Number.isNaN(count) ? Math.max(0, Math.floor(count)) : 0;
10576        return "".concat(safe, " ").concat(safe === 1 ? tCareer('Opening') : tCareer('Openings'));
10577    };
10578    var renderCareerHomeDepartments = function (container, deptCounts) {
10579        if (!container)
10580            return;
10581        // 部门列表完全由 /dept/job_count 驱动,渲染前清空容器(包含模板里的 mock 项)
10582        container.replaceChildren();
10583        if (!Array.isArray(deptCounts) || deptCounts.length === 0) {
10584            var empty = document.createElement('div');
10585            empty.className = 'career-home__departments-empty';
10586            empty.textContent = tCareer('No openings at the moment. Please check back later.');
10587            container.appendChild(empty);
10588            return;
10589        }
10590        var fragment = document.createDocumentFragment();
10591        deptCounts.forEach(function (item) {
10592            if (!item || item.dept_id === undefined || item.dept_id === null)
10593                return;
10594            var link = document.createElement('a');
10595            link.className = 'career-home__department';
10596            link.href = buildCareerJobsUrl({ department: String(item.dept_id) });
10597            link.dataset.deptId = String(item.dept_id);
10598            link.dataset.careerDepartment = '';
10599            if (item.name_transify_key) {
10600                link.dataset.careerDeptTransifyKey = item.name_transify_key;
10601            }
10602            var name = (item.dept_name || '').trim();
10603            link.dataset.careerDeptName = name;
10604            link.setAttribute('aria-label', name || "".concat(tCareer('Department'), " ").concat(item.dept_id));
10605            var indicatorSpan = document.createElement('span');
10606            indicatorSpan.className = 'career-home__department-indicator';
10607            indicatorSpan.setAttribute('aria-hidden', 'true');
10608            var nameSpan = document.createElement('span');
10609            nameSpan.className = 'career-home__department-name';
10610            nameSpan.textContent = name;
10611            var countSpan = document.createElement('span');
10612            countSpan.className = 'career-home__department-count';
10613            countSpan.textContent = formatCareerDeptCountText(item.dept_job_count || 0);
10614            link.appendChild(indicatorSpan);
10615            link.appendChild(nameSpan);
10616            link.appendChild(countSpan);
10617            fragment.appendChild(link);
10618        });
10619        container.appendChild(fragment);
10620    };
10621    var initCareerGalleryRuntime = function () {
10622        if (isRunIngInNodeEnv)
10623            return;
10624        if (typeof document === 'undefined')
10625            return;
10626        var galleries = document.querySelectorAll('[data-career-gallery]');
10627        galleries.forEach(function (gallery) {
10628            if (gallery.dataset.careerGalleryInited === '1')
10629                return;
10630            gallery.dataset.careerGalleryInited = '1';
10631            var wrapper = gallery.closest('.career-home__gallery-wrapper');
10632            var prevBtn = wrapper === null || wrapper === void 0 ? void 0 : wrapper.querySelector('[data-career-gallery-prev]');
10633            var nextBtn = wrapper === null || wrapper === void 0 ? void 0 : wrapper.querySelector('[data-career-gallery-next]');
10634            var getStep = function () {
10635                var photos = gallery.querySelectorAll('.career-home__photo');
10636                if (photos.length < 2)
10637                    return 200;
10638                return photos[1].offsetLeft - photos[0].offsetLeft;
10639            };
10640            // 初始居中第 2 张图(index 1)
10641            var scrollToPhoto = function (index) {
10642                var photos = gallery.querySelectorAll('.career-home__photo');
10643                var target = photos[index];
10644                if (!target)
10645                    return;
10646                var scrollTarget = target.offsetLeft + target.offsetWidth / 2 - gallery.clientWidth / 2;
10647                gallery.scrollTo({ left: scrollTarget, behavior: 'auto' });
10648            };
10649            requestAnimationFrame(function () { return scrollToPhoto(1); });
10650            prevBtn === null || prevBtn === void 0 ? void 0 : prevBtn.addEventListener('click', function () {
10651                gallery.scrollBy({ left: -getStep(), behavior: 'smooth' });
10652            });
10653            nextBtn === null || nextBtn === void 0 ? void 0 : nextBtn.addEventListener('click', function () {
10654                gallery.scrollBy({ left: getStep(), behavior: 'smooth' });
10655            });
10656        });
10657    };
10658    var initCareerHomeRuntime = function (path) {
10659        if (isRunIngInNodeEnv)
10660            return;
10661        if (!isCareerHomePath(path))
10662            return;
10663        if (typeof document === 'undefined')
10664            return;
10665        var container = document.querySelector('.career-home__departments');
10666        if (!container)
10667            return;
10668        if (container.dataset.careerRuntimeInited === '1')
10669            return;
10670        container.dataset.careerRuntimeInited = '1';
10671        initCareerGalleryRuntime();
10672        careerApi
10673            .getDeptJobCount()
10674            .then(function (resp) {
10675            if (resp && resp.retcode === 0 && Array.isArray(resp.data)) {
10676                setDeptJobCountCache(resp.data);
10677                renderCareerHomeDepartments(container, resp.data);
10678            }
10679            else {
10680                console.warn('career home dept job_count returned non-success:', resp);
10681                renderCareerHomeDepartments(container, []);
10682            }
10683        })
10684            .catch(function (error) {
10685            console.warn('career home dept job_count request failed:', error);
10686            renderCareerHomeDepartments(container, []);
10687        });
10688    };
10689
10690    // ====================== Career Jobs Runtime ======================
10691    var CAREER_JOBS_PAGE_SIZE = 50;
10692    var careerJobsMobileState = null;
10693    var careerJobsMobileLoading = false;
10694    var _careerMetaSliceCache = null;
10695    var _careerMetaSlicePromise = null;
10696    var _careerJobDetailPromiseCache = new Map();
10697    var fetchCareerMetaSliceOnce = function () {
10698        if (_careerMetaSliceCache) {
10699            return Promise.resolve({
10700                retcode: 0,
10701                message: 'career meta/slice cache',
10702                data: _careerMetaSliceCache,
10703            });
10704        }
10705        if (!_careerMetaSlicePromise) {
10706            _careerMetaSlicePromise = careerApi
10707                .getMetaSlice()
10708                .then(function (resp) {
10709                if (resp && resp.retcode === 0 && resp.data) {
10710                    _careerMetaSliceCache = resp.data;
10711                }
10712                else {
10713                    _careerMetaSlicePromise = null;
10714                }
10715                return resp;
10716            })
10717                .catch(function (error) {
10718                _careerMetaSlicePromise = null;
10719                console.warn('career meta/slice request failed:', error);
10720                return null;
10721            });
10722        }
10723        return _careerMetaSlicePromise;
10724    };
10725    var fetchCareerJobDetailOnce = function (jobId) {
10726        var cached = _careerJobDetailPromiseCache.get(jobId);
10727        if (cached)
10728            return cached;
10729        var promise = careerApi
10730            .getJobDetail({ job_id: jobId })
10731            .then(function (resp) {
10732            if (!resp || resp.retcode !== 0 || !resp.data) {
10733                _careerJobDetailPromiseCache.delete(jobId);
10734            }
10735            return resp;
10736        })
10737            .catch(function (error) {
10738            _careerJobDetailPromiseCache.delete(jobId);
10739            throw error;
10740        });
10741        _careerJobDetailPromiseCache.set(jobId, promise);
10742        return promise;
10743    };
10744    var computeCareerJobsPages = function (state) {
10745        var pages = [];
10746        state.total; var page = state.page, totalPages = state.totalPages;
10747        if (totalPages <= 1) {
10748            if (totalPages === 1) {
10749                pages.push({ page: 1, label: '1', active: true });
10750            }
10751            return pages;
10752        }
10753        var window = 2;
10754        var set = new Set([1, totalPages]);
10755        for (var i = page - window; i <= page + window; i++) {
10756            if (i > 1 && i < totalPages)
10757                set.add(i);
10758        }
10759        var sorted = Array.from(set).sort(function (a, b) { return a - b; });
10760        var prev = 0;
10761        for (var _i = 0, sorted_1 = sorted; _i < sorted_1.length; _i++) {
10762            var p = sorted_1[_i];
10763            if (p - prev > 1) {
10764                pages.push({ page: prev, label: '…', active: false, ellipsis: true });
10765            }
10766            pages.push({ page: p, label: String(p), active: p === page });
10767            prev = p;
10768        }
10769        return pages;
10770    };
10771    var updateCareerJobsList = function (state, items, meta, options) {
10772        if (options === void 0) { options = {}; }
10773        var container = document.querySelector('[data-career-page="jobs"]');
10774        if (!container) {
10775            return;
10776        }
10777        var itemsEl = container.querySelector('[data-career-items]');
10778        var totalEl = container.querySelector('[data-career-total]');
10779        var pageListEl = container.querySelector('[data-career-page-list]');
10780        var prevBtn = container.querySelector('[data-page-action="prev"]');
10781        var nextBtn = container.querySelector('[data-page-action="next"]');
10782        if (totalEl) {
10783            totalEl.textContent = "".concat(state.total, " ").concat(tCareer('Positions'));
10784        }
10785        if (itemsEl) {
10786            if (!items || items.length === 0) {
10787                if (!options.append) {
10788                    itemsEl.innerHTML =
10789                        '<div class="career-jobs__empty"><p>' +
10790                            escapeCareerHtml(tCareer('No jobs match your filters. Try clearing some filters.')) +
10791                            '</p></div>';
10792                }
10793            }
10794            else {
10795                var html = items
10796                    .map(function (it) {
10797                    var department = it.department_name || formatCareerDeptName(meta, it.department_id);
10798                    var employment = it.employment_name || formatCareerEmploymentName(meta, it.employment_id);
10799                    var city = it.city_name || formatCareerCityName(meta, it.city_id);
10800                    var isFallbackDept = department.startsWith("".concat(tCareer('Dept'), " "));
10801                    var isFallbackLevel = employment.startsWith("".concat(tCareer('Level'), " "));
10802                    var isFallbackCity = city.startsWith("".concat(tCareer('City'), " "));
10803                    var metaState = meta === null
10804                        ? 'unavailable'
10805                        : (department && !isFallbackDept) ||
10806                            (employment && !isFallbackLevel) ||
10807                            (city && !isFallbackCity)
10808                            ? 'partial'
10809                            : 'matched';
10810                    return ('<a class="career-jobs__item" href="' +
10811                        buildCareerDetailUrl(it.job_id) +
10812                        '" data-job-id="' +
10813                        it.job_id +
10814                        '" data-dept-name="' + (department || '') + '"' +
10815                        ' data-employment-name="' + (employment || '') + '"' +
10816                        ' data-city-name="' + (city || '') + '"' +
10817                        ' data-meta-state="' + metaState + '"' +
10818                        '>' +
10819                        '<h3 class="career-jobs__item-title">' +
10820                        (it.job_name || '') +
10821                        '</h3>' +
10822                        '<div class="career-jobs__item-meta">' +
10823                        (department ? '<span class="career-jobs__item-tag"><i class="career-jobs__icon career-jobs__icon--dept" aria-hidden="true"></i>' + department + '</span>' : '') +
10824                        (employment ? '<span class="career-jobs__item-tag"><i class="career-jobs__icon career-jobs__icon--level" aria-hidden="true"></i>' + employment + '</span>' : '') +
10825                        (city ? '<span class="career-jobs__item-tag"><i class="career-jobs__icon career-jobs__icon--loc" aria-hidden="true"></i>' + city + '</span>' : '') +
10826                        '</div></a>');
10827                })
10828                    .join('');
10829                if (options.append) {
10830                    itemsEl.insertAdjacentHTML('beforeend', html);
10831                }
10832                else {
10833                    itemsEl.innerHTML = html;
10834                }
10835            }
10836        }
10837        if (pageListEl) {
10838            var pages = computeCareerJobsPages(state);
10839            pageListEl.innerHTML = pages
10840                .map(function (p) {
10841                return p.ellipsis
10842                    ? '<li class="career-jobs__page-ellipsis">…</li>'
10843                    : '<li><button type="button" class="career-jobs__page-btn' +
10844                        (p.active ? ' career-jobs__page-btn--active' : '') +
10845                        '" data-page-action="goto" data-page="' +
10846                        p.page +
10847                        '">' +
10848                        p.label +
10849                        '</button></li>';
10850            })
10851                .join('');
10852        }
10853        if (prevBtn)
10854            prevBtn.disabled = state.page <= 1;
10855        if (nextBtn)
10856            nextBtn.disabled = state.page >= state.totalPages;
10857    };
10858    var readSelectedFilters = function () {
10859        if (typeof document === 'undefined')
10860            return {};
10861        var container = document.querySelector('[data-career-filter]');
10862        if (!container)
10863            return {};
10864        var collect = function (key) {
10865            var inputs = container.querySelectorAll("input[name=\"".concat(key, "\"]:checked"));
10866            return Array.from(inputs).map(function (el) { return el.value; }
10866).filter(Boolean);
10867        };
10868        var department = collect('department').join(',');
10869        var level = collect('level').join(',');
10870        var location = collect('location').join(',');
10871        return { department: department, level: level, location: location };
10872    };
10873    var fetchAndRenderCareerJobs = function (state, options) {
10874        var _a, _b, _c;
10875        if (options === void 0) { options = {}; }
10876        if (typeof document === 'undefined')
10877            return Promise.resolve();
10878        var filters = readSelectedFilters();
10879        var params = {
10880            page: state.page,
10881            page_size: CAREER_JOBS_PAGE_SIZE,
10882            keyword: state.keyword,
10883            department: (_a = state.department) !== null && _a !== void 0 ? _a : filters.department,
10884            level: (_b = state.level) !== null && _b !== void 0 ? _b : filters.level,
10885            location: (_c = state.location) !== null && _c !== void 0 ? _c : filters.location,
10886        };
10887        var container = document.querySelector('[data-career-page="jobs"]');
10888        var itemsEl = container === null || container === void 0 ? void 0 : container.querySelector('[data-career-items]');
10889        if (itemsEl && !options.append) {
10890            itemsEl.innerHTML =
10891                '<div class="career-jobs__empty"><p>' +
10892                    escapeCareerHtml(tCareer('Loading…')) +
10893                    '</p></div>';
10894        }
10895        // list 先 await 渲染, meta/slice 单独再请求, 避免 meta hang 阻塞 list 展示导致页面卡 Loading
10896        return careerApi
10897            .getJobList(params)
10898            .then(function (jobsResp) {
10899            var _a, _b;
10900            if (jobsResp && jobsResp.retcode === 0 && jobsResp.data) {
10901                var data_1 = jobsResp.data;
10902                var total_1 = (_b = (_a = data_1.total_count) !== null && _a !== void 0 ? _a : data_1.total) !== null && _b !== void 0 ? _b : 0;
10903                var pageSize_1 = data_1.page_size || data_1.limit || params.page_size || CAREER_JOBS_PAGE_SIZE;
10904                var page_1 = data_1.page || state.page;
10905                var totalPages_1 = pageSize_1 > 0 ? Math.max(1, Math.ceil(total_1 / pageSize_1)) : 1;
10906                careerJobsMobileState = { total: total_1, page: page_1, pageSize: pageSize_1, totalPages: totalPages_1 };
10907                // 先用 null meta 渲染, 名字字段 fallback 到 "Dept X / Level X / City X", meta 回来再二次更新
10908                updateCareerJobsList({ total: total_1, page: page_1, pageSize: pageSize_1, totalPages: totalPages_1 }, data_1.job_list || [], options.append ? _careerMetaSliceCache : null, { append: options.append });
10909                fetchCareerMetaSliceOnce()
10910                    .then(function (metaResp) {
10911                    if (options.append) {
10912                        return;
10913                    }
10914                    if (metaResp && metaResp.retcode === 0 && metaResp.data) {
10915                        updateCareerJobsList({ total: total_1, page: page_1, pageSize: pageSize_1, totalPages: totalPages_1 }, data_1.job_list || [], metaResp.data);
10916                    }
10917                    else {
10918                        console.warn('[career-jobs] meta/slice returned non-success:', metaResp);
10919                    }
10920                });
10921            }
10922            else {
10923                console.warn('[career-jobs] list returned non-success:', jobsResp);
10924                careerJobsMobileState = { total: 0, page: 1, pageSize: CAREER_JOBS_PAGE_SIZE, totalPages: 1 };
10925                updateCareerJobsList({ total: 0, page: 1, pageSize: CAREER_JOBS_PAGE_SIZE, totalPages: 1 }, [], null, { append: options.append });
10926            }
10927        })
10928            .catch(function (error) {
10929            console.warn('[career-jobs] list request failed:', error);
10930            careerJobsMobileState = { total: 0, page: 1, pageSize: CAREER_JOBS_PAGE_SIZE, totalPages: 1 };
10931            updateCareerJobsList({ total: 0, page: 1, pageSize: CAREER_JOBS_PAGE_SIZE, totalPages: 1 }, [], null, { append: options.append });
10932        })
10933            .finally(function () {
10934            if (options.append) {
10935                careerJobsMobileLoading = false;
10936            }
10937        });
10938    };
10939    var isCareerMobileFilter = function () {
10940        return typeof window !== 'undefined' && window.matchMedia('(max-width: 767px)').matches;
10941    };
10942    var shouldLoadMoreCareerJobs = function () {
10943        if (typeof window === 'undefined' || typeof document === 'undefined')
10944            return false;
10945        if (!isCareerMobileFilter())
10946            return false;
10947        if (careerJobsMobileLoading || !careerJobsMobileState)
10948            return false;
10949        if (careerJobsMobileState.page >= careerJobsMobileState.totalPages)
10950            return false;
10951        var scrollBottom = window.scrollY + window.innerHeight;
10952        var documentHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
10953        return documentHeight - scrollBottom < 360;
10954    };
10955    var loadMoreCareerJobsIfNeeded = function (container) {
10956        var _a;
10957        if (!shouldLoadMoreCareerJobs() || !careerJobsMobileState)
10958            return;
10959        careerJobsMobileLoading = true;
10960        var keyword = ((_a = container.querySelector('input[name="keyword"]')) === null || _a === void 0 ? void 0 : _a.value) || '';
10961        fetchAndRenderCareerJobs({ page: careerJobsMobileState.page + 1, keyword: keyword }, { append: true });
10962    };
10963    var closeCareerFilterSheet = function () {
10964        var _a;
10965        if (typeof document === 'undefined')
10966            return;
10967        (_a = document.querySelector('.career-jobs__filter-sheet-mask')) === null || _a === void 0 ? void 0 : _a.remove();
10968    };
10969    var openCareerFilterSheet = function (container, group, groupKey) {
10970        var _a, _b;
10971        if (typeof document === 'undefined')
10972            return;
10973        closeCareerFilterSheet();
10974        var title = ((_a = group.querySelector('.career-jobs__filter-trigger span')) === null || _a === void 0 ? void 0 : _a.textContent) ||
10975            ((_b = group.querySelector('.career-jobs__filter-title')) === null || _b === void 0 ? void 0 : _b.textContent) ||
10976            '';
10977        var inputs = Array.from(group.querySelectorAll('input[type="checkbox"]'));
10978        if (inputs.length === 0)
10979            return;
10980        var selected = new Set(inputs.filter(function (input) { return input.checked; }).map(function (input) { return input.value; }));
10981        var mask = document.createElement('div');
10982        mask.className = 'career-jobs__filter-sheet-mask';
10983        mask.innerHTML =
10984            '<div class="career-jobs__filter-sheet" role="dialog" aria-modal="true">' +
10985                '<div class="career-jobs__filter-sheet-header">' +
10986                '<div class="career-jobs__filter-sheet-title">' + escapeCareerHtml(title) + '</div>' +
10987                '<button type="button" class="career-jobs__filter-sheet-close" aria-label="' +
10988                escapeCareerHtml(tCareer('Close')) +
10989                '">&times;</button>' +
10990                '</div>' +
10991                '<div class="career-jobs__filter-sheet-options">' +
10992                inputs.map(function (input) {
10993                    var _a, _b;
10994                    var label = ((_b = (_a = input.closest('label')) === null || _a === void 0 ? void 0 : _a.querySelector('span')) === null || _b === void 0 ? void 0 : _b.textContent) || input.value;
10995                    var active = selected.has(input.value) ? ' career-jobs__filter-sheet-option--active' : '';
10996                    return ('<button type="button" class="career-jobs__filter-sheet-option' +
10997                        active +
10998                        '" data-filter-value="' +
10999                        escapeCareerHtml(input.value) +
11000                        '">' +
11001                        escapeCareerHtml(label) +
11002                        '</button>');
11003                }).join('') +
11004                '</div>' +
11005                '<div class="career-jobs__filter-sheet-actions">' +
11006                '<button type="button" class="career-jobs__filter-sheet-reset">' +
11007                escapeCareerHtml(tCareer('Reset')) +
11008                '</button>' +
11009                '<button type="button" class="career-jobs__filter-sheet-confirm">' +
11010                escapeCareerHtml(tCareer('Confirm')) +
11011                '</button>' +
11012                '</div>' +
11013                '</div>';
11014        mask.addEventListener('click', function (e) {
11015            var _a;
11016            var _b;
11017            if (e.target === mask) {
11018                closeCareerFilterSheet();
11019                return;
11020            }
11021            var target = e.target;
11022            var option = target.closest('[data-filter-value]');
11023            if (option) {
11024                var value = option.dataset.filterValue || '';
11025                if (selected.has(value)) {
11026                    selected.delete(value);
11027                    option.classList.remove('career-jobs__filter-sheet-option--active');
11028                }
11029                else {
11030                    selected.add(value);
11031                    option.classList.add('career-jobs__filter-sheet-option--active');
11032                }
11033                return;
11034            }
11035            if (target.closest('.career-jobs__filter-sheet-close')) {
11036                closeCareerFilterSheet();
11037                return;
11038            }
11039            if (target.closest('.career-jobs__filter-sheet-reset')) {
11040                selected.clear();
11041                inputs.forEach(function (input) {
11042                    input.checked = false;
11043                });
11044                mask
11045                    .querySelectorAll('.career-jobs__filter-sheet-option--active')
11046                    .forEach(function (el) { return el.classList.remove('career-jobs__filter-sheet-option--active'); });
11047                return;
11048            }
11049            if (target.closest('.career-jobs__filter-sheet-confirm')) {
11050                inputs.forEach(function (input) {
11051                    input.checked = selected.has(input.value);
11052                });
11053                updateCareerFilterTriggerState(group);
11054                closeCareerFilterSheet();
11055                fetchAndRenderCareerJobs({
11056                    page: 1,
11057                    keyword: ((_b = container.querySelector('input[name="keyword"]')) === null || _b === void 0 ? void 0 : _b.value) || '',
11058                });
11059                try {
11060                    var newQuery = parseCareerJobsQuery();
11061                    var values = Array.from(selected).join(',');
11062                    var newUrl = buildCareerJobsUrl(__assign$3(__assign$3({}, newQuery), (_a = {}, _a[groupKey] = values || undefined, _a.page = 1, _a.page_size = CAREER_JOBS_PAGE_SIZE, _a)));
11063                    window.history.replaceState(null, '', newUrl);
11064                }
11065                catch (err) {
11066                    // ignore
11067                }
11068            }
11069        });
11070        document.body.appendChild(mask);
11071    };
11072    var getCareerFilterLabelText = function (input) {
11073        var _a, _b;
11074        var label = ((_b = (_a = input.closest('label')) === null || _a === void 0 ? void 0 : _a.querySelector('span')) === null || _b === void 0 ? void 0 : _b.textContent) || input.value;
11075        return label.replace(/\s*\(\d+\)\s*$/, '').trim();
11076    };
11077    var updateCareerFilterTriggerState = function (group) {
11078        var _a;
11079        var trigger = group.querySelector('[data-career-filter-trigger]');
11080        if (!trigger)
11081            return;
11082        var title = trigger.dataset.careerFilterTitle || ((_a = trigger.textContent) === null || _a === void 0 ? void 0 : _a.trim()) || '';
11083        trigger.dataset.careerFilterTitle = title;
11084        var textEl = trigger.querySelector('.career-jobs__filter-trigger-text');
11085        var checkedInputs = Array.from(group.querySelectorAll('input[type="checkbox"]:checked'));
11086        var selectedLabels = checkedInputs.map(getCareerFilterLabelText).filter(Boolean);
11087        var displayText = selectedLabels.length > 0 ? selectedLabels.join(', ') : title;
11088        if (textEl) {
11089            textEl.textContent = displayText;
11090        }
11091        else {
11092            trigger.textContent = displayText;
11093        }
11094        trigger.classList.toggle('career-jobs__filter-trigger--active', selectedLabels.length > 0);
11095        trigger.setAttribute('title', displayText);
11096    };
11097    var updateCareerFilterTriggerStates = function () {
11098        if (typeof document === 'undefined')
11099            return;
11100        document
11101            .querySelectorAll('[data-career-filter-group]')
11102            .forEach(updateCareerFilterTriggerState);
11103    };
11104    var bindCareerJobsEvents = function () {
11105        if (typeof document === 'undefined')
11106            return;
11107        var container = document.querySelector('[data-career-page="jobs"]');
11108        if (!container)
11109            return;
11110        if (container.dataset.careerBound === '1')
11111            return;
11112        container.dataset.careerBound = '1';
11113        var filterEl = container.querySelector('[data-career-filter]');
11114        if (filterEl) {
11115            filterEl.addEventListener('click', function (e) {
11116                var trigger = e.target.closest('[data-career-filter-trigger]');
11117                if (!trigger || !isCareerMobileFilter())
11118                    return;
11119                var group = trigger.closest('[data-career-filter-group]');
11120                var groupKey = trigger.dataset.careerFilterTrigger || '';
11121                if (!group || !groupKey)
11122                    return;
11123                openCareerFilterSheet(container, group, groupKey);
11124            });
11125            filterEl.addEventListener('change', function (e) {
11126                var _a;
11127                if (isCareerMobileFilter())
11128                    return;
11129                var target = e.target;
11130                if (!target || target.tagName !== 'INPUT')
11131                    return;
11132                var group = target.closest('[data-career-filter-group]');
11133                if (group)
11134                    updateCareerFilterTriggerState(group);
11135                // 任意筛选变动:重置到第 1 页
11136                fetchAndRenderCareerJobs({ page: 1, keyword: ((_a = container.querySelector('input[name="keyword"]')) === null || _a === void 0 ? void 0 : _a.value) || '' });
11137            });
11138        }
11139        var paginationEl = container.querySelector('[data-career-pagination]');
11140        if (paginationEl) {
11141            paginationEl.addEventListener('click', function (e) {
11142                var _a, _b;
11143                var target = e.target.closest('[data-page-action]');
11144                if (!target)
11145                    return;
11146                var action = target.dataset.pageAction;
11147                var currentPage = Number(((_a = paginationEl.querySelector('[data-career-page-list] .career-jobs__page-btn--active')) === null || _a === void 0 ? void 0 : _a.getAttribute('data-page')) || '1') || 1;
11148                var nextPage = currentPage;
11149                if (action === 'prev')
11150                    nextPage = Math.max(1, currentPage - 1);
11151                else if (action === 'next')
11152                    nextPage = currentPage + 1;
11153                else if (action === 'goto')
11154                    nextPage = Number(target.dataset.page) || 1;
11155                if (nextPage === currentPage)
11156                    return;
11157                var keyword = ((_b = container.querySelector('input[name="keyword"]')) === null || _b === void 0 ? void 0 : _b.value) || '';
11158                fetchAndRenderCareerJobs({ page: nextPage, keyword: keyword });
11159                // 同步 URL
11160                try {
11161                    var newQuery = parseCareerJobsQuery();
11162                    var newUrl = buildCareerJobsUrl(__assign$3(__assign$3({}, newQuery), { page: nextPage, page_size: CAREER_JOBS_PAGE_SIZE }));
11163                    window.history.replaceState(null, '', newUrl);
11164                }
11165                catch (err) {
11166                    // ignore
11167                }
11168            });
11169        }
11170        var searchForm = container.querySelector('.career-jobs__search');
11171        if (searchForm) {
11172            searchForm.addEventListener('submit', function (e) {
11173                e.preventDefault();
11174                var keyword = new FormData(searchForm).get('keyword') || '';
11175                try {
11176                    var newQuery = parseCareerJobsQuery();
11177                    var newUrl = buildCareerJobsUrl(__assign$3(__assign$3({}, newQuery), { page: 1, keyword: keyword }));
11178                    window.history.replaceState(null, '', newUrl);
11179                }
11180                catch (err) {
11181                    // ignore
11182                }
11183                fetchAndRenderCareerJobs({ page: 1, keyword: keyword });
11184            });
11185        }
11186        window.addEventListener('scroll', function () {
11187            loadMoreCareerJobsIfNeeded(container);
11188        }, { passive: true });
11189        window.addEventListener('resize', function () {
11190            loadMoreCareerJobsIfNeeded(container);
11191        }, { passive: true });
11192    };
11193    var buildCareerLocationOptions = function (data) {
11194        if (!Array.isArray(data))
11195            return [];
11196        var selectedLocations = new Set((parseCareerJobsQuery().location || '').split(',').filter(Boolean));
11197        var options = [];
11198        data.forEach(function (region) {
11199            if (!region || !Array.isArray(region.cities))
11200                return;
11201            region.cities.forEach(function (city) {
11202                if (!city)
11203                    return;
11204                var regionName = (region.region_name || '').trim();
11205                var cityName = (city.city_name || '').trim();
11206                var count = typeof city.job_count === 'number' ? city.job_count : 0;
11207                var baseLabel = regionName && cityName && regionName !== cityName
11208                    ? "".concat(regionName, " - ").concat(cityName)
11209                    : cityName;
11210                if (!baseLabel)
11211                    return;
11212                options.push({
11213                    id: String(city.city_id),
11214                    label: count > 0 ? "".concat(baseLabel, " (").concat(count, ")") : baseLabel,
11215                    checked: selectedLocations.has(String(city.city_id)),
11216                });
11217            });
11218        });
11219        return options;
11220    };
11221    var buildCareerDepartmentOptions = function (data) {
11222        if (!Array.isArray(data))
11223            return [];
11224        var selectedDepartments = new Set((parseCareerJobsQuery().department || '').split(',').filter(Boolean));
11225        return data
11226            .map(function (dept) {
11227            var name = ((dept === null || dept === void 0 ? void 0 : dept.dept_name) || '').trim();
11228            if (!dept || dept.dept_id === undefined || dept.dept_id === null || !name) {
11229                return undefined;
11230            }
11231            var count = typeof dept.dept_job_count === 'number' ? dept.dept_job_count : 0;
11232            return {
11233                id: String(dept.dept_id),
11234                label: count > 0 ? "".concat(name, " (").concat(count, ")") : name,
11235                checked: selectedDepartments.has(String(dept.dept_id)),
11236            };
11237        })
11238            .filter(Boolean);
11239    };
11240    var buildCareerLevelOptions = function (data) {
11241        if (!data || !Array.isArray(data.employment_level_list))
11242            return [];
11243        var selectedLevels = new Set((parseCareerJobsQuery().level || '').split(',').filter(Boolean));
11244        return data.employment_level_list
11245            .map(function (level) {
11246            if (!level || level.employment_level_id === undefined || level.employment_level_id === null) {
11247                return undefined;
11248            }
11249            var label = (level.default_text || level.employment_type_name || '').trim();
11250            if (!label)
11251                return undefined;
11252            return {
11253                id: String(level.employment_level_id),
11254                label: label,
11255                checked: selectedLevels.has(String(level.employment_level_id)),
11256            };
11257        })
11258            .filter(Boolean);
11259    };
11260    var updateCareerFilterGroup = function (groupKey, options) {
11261        var _a;
11262        if (typeof document === 'undefined' || options.length === 0)
11263            return;
11264        var container = document.querySelector('[data-career-filter]');
11265        if (!container)
11266            return;
11267        var group = container.querySelector("[data-career-filter-group=\"".concat(groupKey, "\"]"));
11268        if (!group)
11269            return;
11270        var trigger = group.querySelector('[data-career-filter-trigger]');
11271        var triggerText = trigger === null || trigger === void 0 ? void 0 : trigger.querySelector('.career-jobs__filter-trigger-text');
11272        if (trigger && triggerText && !trigger.dataset.careerFilterTitle) {
11273            trigger.dataset.careerFilterTitle = ((_a = triggerText.textContent) === null || _a === void 0 ? void 0 : _a.trim()) || '';
11274        }
11275        var list = group.querySelector('.career-jobs__filter-list');
11276        if (!list)
11277            return;
11278        // 保留用户当前已选中的 id,避免 API 返回后清空状态
11279        var checkedIds = new Set(Array.from(list.querySelectorAll("input[name=\"".concat(groupKey, "\"]:checked"))).map(function (el) { return el.value; }));
11280        list.innerHTML = options
11281            .map(function (o) {
11282            var checked = checkedIds.has(o.id) || o.checked ? ' checked' : '';
11283            return ('<li class="career-jobs__filter-item">' +
11284                '<label>' +
11285                '<input type="checkbox" name="' +
11286                groupKey +
11287                '" value="' +
11288                escapeCareerHtml(o.id) +
11289                '"' +
11290                checked +
11291                ' />' +
11292                '<span>' +
11293                escapeCareerHtml(o.label) +
11294                '</span>' +
11295                '</label>' +
11296                '</li>');
11297        })
11298            .join('');
11299        updateCareerFilterTriggerState(group);
11300    };
11301    var updateCareerLocationFilter = function (options) {
11302        updateCareerFilterGroup('location', options);
11303    };
11304    var updateCareerDepartmentFilter = function (options) {
11305        updateCareerFilterGroup('department', options);
11306    };
11307    var updateCareerLevelFilter = function (options) {
11308        updateCareerFilterGroup('level', options);
11309    };
11310    var initCareerJobsRuntime = function (path) {
11311        if (isRunIngInNodeEnv)
11312            return;
11313        if (!isCareerJobsPath(path))
11314            return;
11315        if (typeof document === 'undefined')
11316            return;
11317        var query = parseCareerJobsQuery();
11318        var initialPage = query.page && query.page > 0 ? query.page : 1;
11319        var keyword = query.keyword;
11320        bindCareerJobsEvents();
11321        updateCareerFilterTriggerStates();
11322        fetchAndRenderCareerJobs({
11323            page: initialPage,
11324            keyword: keyword,
11325            department: query.department,
11326            level: query.level,
11327            location: query.location,
11328        });
11329        // 用 city/job_count 运行时刷新 location 筛选,并缓存数据用于 job list name 匹配
11330        careerApi
11331            .getCityJobCount()
11332            .then(function (resp) {
11333            if (resp && resp.retcode === 0 && Array.isArray(resp.data)) {
11334                setCityJobCountCache(resp.data);
11335                var options = buildCareerLocationOptions(resp.data);
11336                if (options.length > 0) {
11337                    updateCareerLocationFilter(options);
11338                }
11339            }
11340            else {
11341                console.warn('career jobs city job_count returned non-success:', resp);
11342            }
11343        })
11344            .catch(function (error) {
11345            console.warn('career jobs city job_count request failed:', error);
11346        });
11347        // 用 dept/job_count 缓存部门数据,用于 job list name 匹配
11348        careerApi
11349            .getDeptJobCount()
11350            .then(function (resp) {
11351            if (resp && resp.retcode === 0 && Array.isArray(resp.data)) {
11352                setDeptJobCountCache(resp.data);
11353                var options = buildCareerDepartmentOptions(resp.data);
11354                if (options.length > 0) {
11355                    updateCareerDepartmentFilter(options);
11356                }
11357            }
11358            else {
11359                console.warn('career jobs dept job_count returned non-success:', resp);
11360            }
11361        })
11362            .catch(function (error) {
11363            console.warn('career jobs dept job_count request failed:', error);
11364        });
11365        fetchCareerMetaSliceOnce()
11366            .then(function (resp) {
11367            if (resp && resp.retcode === 0 && resp.data) {
11368                var options = buildCareerLevelOptions(resp.data);
11369                if (options.length > 0) {
11370                    updateCareerLevelFilter(options);
11371                }
11372            }
11373            else {
11374                console.warn('career jobs meta/slice returned non-success:', resp);
11375            }
11376        });
11377    };
11378    // ====================== Career Job Detail Runtime ======================
11379    var renderCareerJobDetailBody = function (data, errorText) {
11380        var container = document.querySelector('[data-career-page="job-detail"]');
11381        if (!container)
11382            return;
11383        var bodyEl = container.querySelector('[data-career-job-body]');
11384        var titleEl = container.querySelector('[data-career-job-title]');
11385        var tagsEl = container.querySelector('[data-career-job-tags]');
11386        if (!data) {
11387            if (bodyEl) {
11388                bodyEl.innerHTML =
11389                    '<div class="career-job-detail__error"><p>' +
11390                        escapeCareerHtml(errorText || tCareer('This job is no longer available.')) +
11391                        '</p></div>';
11392            }
11393            return;
11394        }
11395        if (titleEl) {
11396            titleEl.textContent = data.job_name || '';
11397        }
11398        if (tagsEl) {
11399            var tags = [];
11400            if (data.department_name)
11401                tags.push(data.department_name);
11402            if (data.employment_name)
11403                tags.push(data.employment_name);
11404            if (data.city_name)
11405                tags.push(data.city_name);
11406            tagsEl.innerHTML = tags.map(function (t) { return '<li><span class="career-job-detail__tag">' + t + '</span></li>'; }).join('');
11407        }
11408        if (bodyEl) {
11409            var about = sanitizeHtml(data.sub_team_description || '');
11410            var description = sanitizeHtml(data.job_description || '');
11411            var requirements = sanitizeHtml(data.requirements || '');
11412            var parts = [];
11413            if (about) {
11414                parts.push('<h2>' + escapeCareerHtml(tCareer('About the Team')) + '</h2>' + about);
11415            }
11416            if (description) {
11417                parts.push('<h2>' + escapeCareerHtml(tCareer('Job Description')) + '</h2>' + description);
11418            }
11419            if (requirements) {
11420                parts.push('<h2>' + escapeCareerHtml(tCareer('Requirements')) + '</h2>' + requirements);
11421            }
11422            if (parts.length === 0) {
11423                bodyEl.innerHTML =
11424                    '<div class="career-job-detail__empty"><p>' +
11425                        escapeCareerHtml(tCareer('No description available for this job.')) +
11426                        '</p></div>';
11427            }
11428            else {
11429                bodyEl.innerHTML = parts.join('');
11430            }
11431        }
11432    };
11433    var initCareerJobDetailRuntime = function (path) {
11434        if (isRunIngInNodeEnv)
11435            return;
11436        if (!isCareerJobDetailPath(path))
11437            return;
11438        if (typeof document === 'undefined')
11439            return;
11440        var jobId = getCareerJobId();
11441        var channel = getCareerChannel();
11442        if (!jobId) {
11443            renderCareerJobDetailBody(null, tCareer('Missing job_id. Please go back to the job list.'));
11444            return;
11445        }
11446        var applyLink = document.querySelector('[data-career-apply-link]');
11447        if (applyLink) {
11448            applyLink.href = buildCareerApplyUrl(jobId, channel);
11449        }
11450        Promise.all([fetchCareerJobDetailOnce(jobId), fetchCareerMetaSliceOnce()])
11451            .then(function (_a) {
11452            var detailResp = _a[0], metaResp = _a[1];
11453            if (detailResp && detailResp.retcode === 0 && detailResp.data) {
11454                var data = detailResp.data;
11455                if (metaResp && metaResp.retcode === 0 && metaResp.data) {
11456                    var meta = metaResp.data;
11457                    if (!data.department_name) {
11458                        var name_1 = formatCareerDeptName(meta, data.department_id);
11459                        if (name_1)
11460                            data.department_name = name_1;
11461                    }
11462                    if (!data.employment_name) {
11463                        var name_2 = formatCareerEmploymentName(meta, data.employment_id);
11464                        if (name_2)
11465                            data.employment_name = name_2;
11466                    }
11467                    if (!data.city_name) {
11468                        var name_3 = formatCareerCityName(meta, data.city_id);
11469                        if (name_3)
11470                            data.city_name = name_3;
11471                    }
11472                }
11473                renderCareerJobDetailBody(data);
11474            }
11475            else {
11476                renderCareerJobDetailBody(null, (detailResp === null || detailResp === void 0 ? void 0 : detailResp.message) || tCareer('This job is no longer available.'));
11477            }
11478        })
11479            .catch(function (error) {
11480            console.warn('career job detail request failed:', error);
11481            renderCareerJobDetailBody(null, tCareer('Failed to load job details. Please try again later.'));
11482        });
11483    };
11484
11485    var initCareerRuntime = function (path) {
11486        if (!isRunIngInNodeEnv && typeof document !== 'undefined') {
11487            initCareerGalleryRuntime();
11488        }
11489        if (isCareerJobsPath(path)) {
11490            initCareerJobsRuntime(path);
11491        }
11492        else if (isCareerJobDetailPath(path)) {
11493            initCareerJobDetailRuntime(path);
11494        }
11495        else if (isCareerHomePath(path) ||
11496            (!isRunIngInNodeEnv &&
11497                typeof document !== 'undefined' &&
11498                Boolean(document.querySelector('.career-home__search, [data-career-departments]')))) {
11499            initCareerHomeRuntime(path);
11500        }
11501    };
11502
11503    var partnershipConfig = getPartnershipConfig();
11504    var primaryColor = partnershipConfig.theme.primaryColor;
11505    var convertMenuData = function (config, cid, pageType, lang, isPreview) {
11506        var _a, _b;
11507        var menu = config.menu, page_path = config.page_path;
11508        var finalPagePath = isPreview ? getCurrentUrlWithoutOrigin() : page_path;
11509        var userInfo = window.__NSS_CONTEXT__.userInfo;
11510        var currentLanguage = lang || instance.language;
11511        // 只有详情页才需要,用来拼接语言切换中的链接
11512        var tempPagePathWithoutLang = pageType === PAGE_TYPE.home || !finalPagePath ? undefined : getUrlPathWithoutLang(finalPagePath)[0];
11513        // 相等说明没有符合规则的语言前缀
11514        var pagePathWithoutLang = tempPagePathWithoutLang === finalPagePath ? undefined : tempPagePathWithoutLang;
11515        return {
11516            menu_list: createMenuList(menu),
11517            download_app: menu === null || menu === void 0 ? void 0 : menu.download_app,
11518            current_language: currentLanguage,
11519            language_list: getLanguageList(),
11520            language_list_text: LanguageText,
11521            url_lang_map: urlLangMap,
11522            user_info: {
11523                phone: formatAccountInfo(userInfo === null || userInfo === void 0 ? void 0 : userInfo.phone_number, 'phone'),
11524                email: formatAccountInfo(userInfo === null || userInfo === void 0 ? void 0 : userInfo.email, 'email'),
11525                account_id: userInfo === null || userInfo === void 0 ? void 0 : userInfo.account_id,
11526            },
11527            show_login_button: isMobile() ? ((_a = menu === null || menu === void 0 ? void 0 : menu.basic_info) === null || _a === void 0 ? void 0 : _a.login_button_h5_toggle) === 1 : ((_b = menu === null || menu === void 0 ? void 0 : menu.basic_info) === null || _b === void 0 ? void 0 : _b.login_button_pc_toggle) === 1,
11528            page_path: pageType === PAGE_TYPE.home ? '/' : finalPagePath,
11529            page_path_without_lang: pagePathWithoutLang,
11530            primary_color: primaryColor,
11531            logo: partnershipConfig.branding.logo,
11532            logo_wrapper_class: partnershipConfig.branding.logoWrapperClass,
11533            logo_class: partnershipConfig.branding.logoClass,
11534        };
11535    };
11536    var getBannerData = function (configData, bannerType) {
11537        var currentRegion = getRegion();
11538        var tempIsPreviewPage = isRunIngInNodeEnv ? undefined : getIsPreviewPage();
11539        var isPreviewPage = tempIsPreviewPage && !!getPreviewId();
11540        return getCurrentBannerData(configData, bannerType, currentRegion, isPreviewPage);
11541    };
11542    /**
11543     * 页面类型列表
11544     */
11545    var PAGE_TYPE = {
11546        home: 'index',
11547        detail: 'detail',
11548    };
11549    var isCareerPageConfig = function (configData) {
11550        return ((configData === null || configData === void 0 ? void 0 : configData.page_type) === DETAIL_PAGE_TYPE.career ||
11551            isCareerHomeConfigData(configData));
11552    };
11553    var renderBanner = function (configData, bannerType) {
11554        var bannerData = getBannerData(configData, bannerType);
11555        if (bannerData) {
11556            if (bannerType === BannerType.Main) {
11557                return Templates.banner(bannerData);
11558            }
11559            else if (bannerType === BannerType.Footer) {
11560                return Templates.footerBanner(bannerData);
11561            }
11562        }
11563        return '';
11564    };
11565    var renderHomePageContent = function (configData, contentHolder, isPreview) {
11566        var _a, _b;
11567        contentHolder += renderBanner(configData, BannerType.Main);
11568        if ((_a = configData.seo_config) === null || _a === void 0 ? void 0 : _a.html_title) {
11569            contentHolder += Templates.seoH1Title(configData.seo_config);
11570        }
11571        var currentRegion = getRegion();
11572        if (configData.main_func) {
11573            var checkFeePath = ['ID'].includes(currentRegion) ? '/spx-esf-tool' : '/esf-tool';
11574            var servicePointHref = getServicePointHref();
11575            // 这里增减字段需要检查 src/utils/register-helper.ts 和 build/tasks/build-template.js 中的 serviceCount 方法
11576            // 是否受到影响。Trucking 会以隐藏卡片保留在静态 HTML 中,但不计入普通卡片基础布局。
11577            contentHolder += Templates.serviceCards(__assign$3(__assign$3({}, (configData.main_func || {})), { checkFeePath: checkFeePath, servicePointHref: servicePointHref }));
11578        }
11579        if (configData.service) {
11580            contentHolder += Templates.spxExpressService(configData.service);
11581        }
11582        if (configData.about_us) {
11583            contentHolder += Templates.aboutUs(configData.about_us);
11584        }
11585        if (configData.partner) {
11586            contentHolder += Templates.brandPartner(configData.partner);
11587        }
11588        if ((_b = configData.seo_footer) === null || _b === void 0 ? void 0 : _b.text) {
11589            contentHolder += Templates.seoFooter(configData.seo_footer);
11590        }
11591        if (isPreview) {
11592            contentHolder += renderBanner(configData, BannerType.Footer);
11593        }
11594        // 这是一个弹窗,先把它渲染出来但不显示,以增加 SEO 的权重。之后会动态渲æ
11594Ÿ“覆盖掉
11595        contentHolder += Templates.shipModal({
11596            easyPackCreate: true,
11597            easyPackLink: '/easypack/create',
11598            oneTimeCreate: true,
11599            isPC: true,
11600        });
11601        return contentHolder;
11602    };
11603    var ADVANTAGES_STYLE_TYPE_KEY = {
11604        1: ['advantages_with_icons', 'advantagesWithIcons'],
11605        2: ['advantages_with_photos', 'advantagesWithPhotos'],
11606    };
11607    var MAIN_INTRODUCTION_STYLE_TYPE_KEY = {
11608        1: ['introduction_with_video', 'mainIntroductionWithVideo'],
11609        2: ['introduction_with_photos', 'introductionWithPhotos'],
11610    };
11611    var STEPS_STYLE_TYPE_KEY = {
11612        1: ['un_clickable_steps', 'unClickableSteps'],
11613        2: ['clickable_steps', 'clickableSteps'],
11614    };
11615    var TEXT_AND_IMAGE_STYLE_TYPE_KEY = {
11616        1: ['article', 'pureText'],
11617        2: ['only_images', 'onlyImages'],
11618    };
11619    var DETAILED_INTRODUCTION_STYLE_TYPE_KEY = {
11620        1: ['introduction_with_tabs', 'introductionWithTabs'],
11621        2: ['introduction_without_tabs', 'introductionWithoutTabs'],
11622    };
11623    var MORE_INFO_STYLE_TYPE_KEY = {
11624        1: ['other_service_and_faq', 'otherServiceAndFaq'],
11625        2: ['other_services', 'otherServices'],
11626    };
11627    var renderTitleWithoutBanner = function (configData) {
11628        if (configData.basic && !configData.banner && !configData.default_banner) {
11629            return Templates.titleWithoutBanner(configData.basic);
11630        }
11631        return '';
11632    };
11633    var ALL_SORT_MODULES = __spreadArray$2(__spreadArray$2([], CAREER_SORT_MODULES, true), [
11634        'banner',
11635        'footer_banner',
11636        'advantages',
11637        'main_introduction',
11638        'steps',
11639        'text_and_image',
11640        'detailed_introduction',
11641        'more_info',
11642    ], false);
11643    var renderDetailPageContent = function (configData, contentHolder, isPreview) {
11644        var _a;
11645        contentHolder += renderTitleWithoutBanner(configData);
11646        if ((configData === null || configData === void 0 ? void 0 : configData.page_type) === DETAIL_PAGE_TYPE.aboutUs) {
11647            contentHolder += renderBanner(configData, BannerType.Main);
11648            if ((_a = configData.content) === null || _a === void 0 ? void 0 : _a.item_list) {
11649                var data = configData.content;
11650                contentHolder += Templates['introductionWithoutTabs'](__assign$3(__assign$3({}, data), { standalone: true }));
11651            }
11652            return contentHolder;
11653        }
11654        var sortModules = configData.sort_module || (isPreview ? ALL_SORT_MODULES : []);
11655        sortModules.forEach(function (module) {
11656            var _a, _b, _c, _d, _e, _f;
11657            switch (module) {
11658                case 'career_search':
11659                    contentHolder += Templates.careerSearch(getCareerSearchTemplateData(configData));
11660                    break;
11661                case 'department':
11662                    contentHolder += Templates.careerDepartment(getCareerDepartmentTemplateData(configData));
11663                    break;
11664                case 'career_home':
11665                    if (configData.career_home) {
11666                        contentHolder += Templates.careerHome(configData.career_home);
11667                    }
11668                    break;
11669                case 'career_jobs':
11670                    if (configData.career_jobs) {
11671                        contentHolder += Templates.careerJobs(configData.career_jobs);
11672                    }
11673                    break;
11674                case 'career_job_detail':
11675                    if (configData.career_job_detail) {
11676                        contentHolder += Templates.careerJobDetail(configData.career_job_detail);
11677                    }
11678                    break;
11679                case 'banner':
11680                    contentHolder += renderBanner(configData, BannerType.Main);
11681                    break;
11682                case 'footer_banner':
11683                    contentHolder += renderBanner(configData, BannerType.Footer);
11684                    break;
11685                case 'advantages':
11686                    if (configData.advantages) {
11687                        var _g = ADVANTAGES_STYLE_TYPE_KEY[(_a = configData.advantages) === null || _a === void 0 ? void 0 : _a.style_type], dataKey = _g[0], templateKey = _g[1];
11688                        if (dataKey) {
11689                            contentHolder += Templates[templateKey](configData.advantages[dataKey] || {});
11690                        }
11691                    }
11692                    break;
11693                case 'main_introduction':
11694                    if (configData.main_introduction) {
11695                        if (isCareerPageConfig(configData)) {
11696                            contentHolder += Templates.careerIntroduction(getCareerIntroductionTemplateData(configData));
11697                            break;
11698                        }
11699                        var _h = MAIN_INTRODUCTION_STYLE_TYPE_KEY[(_b = configData.main_introduction) === null || _b === void 0 ? void 0 : _b.style_type], dataKey = _h[0], templateKey = _h[1];
11700                        if (dataKey) {
11701                            contentHolder += Templates[templateKey](configData.main_introduction[dataKey] || {});
11702                        }
11703                    }
11704                    break;
11705                case 'steps':
11706                    if (configData.steps) {
11707                        var _j = STEPS_STYLE_TYPE_KEY[(_c = configData.steps) === null || _c === void 0 ? void 0 : _c.style_type], dataKey = _j[0], templateKey = _j[1];
11708                        if (dataKey) {
11709                            contentHolder += Templates[templateKey](__assign$3(__assign$3({}, (configData.steps[dataKey] || {})), { primaryColor: primaryColor }));
11710                        }
11711                    }
11712                    break;
11713                case 'text_and_image':
11714                    if (configData.text_and_image) {
11715                        if (isCareerPageConfig(configData)) {
11716                            contentHolder += Templates.careerTextAndImage(getCareerTextAndImageTemplateData(configData));
11717                            break;
11718                        }
11719                        var _k = TEXT_AND_IMAGE_STYLE_TYPE_KEY[(_d = configData.text_and_image) === null || _d === void 0 ? void 0 : _d.style_type], dataKey = _k[0], templateKey = _k[1];
11720                        if (dataKey) {
11721                            var data = configData.text_and_image[dataKey] || {};
11722                            var standalone = isStandalone(configData, 'text_and_image');
11723                            var templateContent = Templates[templateKey](__assign$3(__assign$3({}, data), { standalone: standalone }));
11724                            contentHolder += templateContent;
11725                        }
11726                    }
11727                    break;
11728                case 'detailed_introduction':
11729                    if (configData.detailed_introduction) {
11730                        var _l = DETAILED_INTRODUCTION_STYLE_TYPE_KEY[(_e = configData.detailed_introduction) === null || _e === void 0 ? void 0 : _e.style_type], dataKey = _l[0], templateKey = _l[1];
11731                        if (dataKey) {
11732                            var data = configData.detailed_introduction[dataKey] || {};
11733                            var standalone = isStandalone(configData, 'detailed_introduction');
11734                            contentHolder += Templates[templateKey](__assign$3(__assign$3({}, data), { standalone: standalone }));
11735                        }
11736                    }
11737                    break;
11738                case 'more_info':
11739                    if (configData.more_info) {
11740                        var _m = MORE_INFO_STYLE_TYPE_KEY[(_f = configData.more_info) === null || _f === void 0 ? void 0 : _f.style_type], dataKey = _m[0], templateKey = _m[1];
11741                        if (dataKey) {
11742                            contentHolder += Templates[templateKey](configData.more_info[dataKey] || {});
11743                        }
11744                    }
11745            }
11746        });
11747        return contentHolder;
11748    };
11749    var COMPONENT_KEYS = __spreadArray$2(__spreadArray$2([
11750        'basic'
11751    ], CAREER_COMPONENT_KEYS, true), [
11752        'banner',
11753        'default_banner',
11754        'main_introduction',
11755        'advantages',
11756        'detailed_introduction',
11757        'steps',
11758        'text_and_image',
11759        'more_info',
11760        'menu',
11761        'footer',
11762    ], false);
11763    var isStandalone = function (configData, singleModule) {
11764        var publicModules = ['menu', 'footer', 'basic', 'banner', 'default_banner'];
11765        var exceptModules = __spreadArray$2([singleModule], publicModules, true);
11766        if (!configData) {
11767            return false;
11768        }
11769        var configDataKeys = Object.keys(configData).filter(function (key) {
11770            return COMPONENT_KEYS.includes(key);
11771        });
11772        return (configDataKeys.filter(function (module) { return !exceptModules.includes(module); })
11773            .length === 0);
11774    };
11775    var renderPageContent = function (configData, contentHolder, pageType, isPreview) {
11776        if (pageType === PAGE_TYPE.home) {
11777            return renderHomePageContent(configData, contentHolder, isPreview);
11778        }
11779        if (pageType === PAGE_TYPE.detail) {
11780            return renderDetailPageContent(configData, contentHolder, isPreview);
11781        }
11782        return contentHolder;
11783    };
11784    var isEmptyConfig = function (configData) {
11785        return !configData || Object.keys(configData).length === 0;
11786    };
11787    var homeUrlConversionKeysConfig = {
11788        service: {
11789            item_list: [{ link: true }]
11790        },
11791        about_us: {
11792            link: true
11793        },
11794        footer: {
11795            policy: [{ link_url: true }]
11796        }
11797    };
11798    var detailUrlConversionKeysConfig = {
11799        main_introduction: {
11800            introduction_with_video: {
11801                button_link: true,
11802                video_link: true
11803            },
11804            introduction_with_photos: {
11805                button_link: true
11806            }
11807        },
11808        steps: {
11809            clickable_steps: {
11810                button_link: true
11811            },
11812            un_clickable_steps: {
11813                button_link: true
11814            }
11815        },
11816        more_info: {
11817            other_service_and_faq: {
11818                service_item_list: [{ link: true }]
11819            },
11820            other_services: {
11821                service_item_list: [{ link: true }]
11822            }
11823        },
11824        footer: {
11825            policy: [{ link_url: true }]
11826        }
11827    };
11828    var getUrlConversionKeysConfig = function (pageType) {
11829        if (pageType === PAGE_TYPE.home) {
11830            return homeUrlConversionKeysConfig;
11831        }
11832        return detailUrlConversionKeysConfig;
11833    };
11834    function renderTemplates(originalConfigData, cid, pageType, lang, originalActiveConfigUrl, search) {
11835        var _a, _b, _c;
11836        if (pageType === void 0) { pageType = PAGE_TYPE.home; }
11837        if (isEmptyConfig(originalConfigData)) {
11838            return;
11839        }
11840        var activeConfigUrl = [];
11841        if (!isRunIngInNodeEnv) {
11842            activeConfigUrl = window.ACTIVE_PAGE_PATHS || [];
11843        }
11844        var configData = normalizeConfigData({
11845            configData: originalConfigData,
11846            keysConfig: getUrlConversionKeysConfig(pageType),
11847            // lang 的初始化逻辑和 get-translation.ts 中的 loadResource 一致
11848            lang: checkCurrentLanguage(),
11849            activeConfigUrl: activeConfigUrl,
11850            region: cid
11851        });
11852        var contentHTML = '';
11853        var headerHTML = '';
11854        // Generate SEO header if seo_config exists
11855        if (configData.seo_config) {
11856            var processedSeoConfig = __assign$3(__assign$3({}, configData.seo_config), { rich_snippets: configData.seo_config.rich_snippets
11857                    .split('\n')
11858                    .filter(Boolean) });
11859            headerHTML += Templates.seoHeader(processedSeoConfig);
11860        }
11861        // 如果 URL 中带有 bi=1 参数,隐藏头部(menu)
11862        var hideHeaderByBi = shouldHideHeaderByBi(search);
11863        // 添加移动端下载条(只在首页且有download_app配置时才渲染)
11864        if (pageType === PAGE_TYPE.home && ((_a = configData.menu) === null || _a === void 0 ? void 0 : _a.download_app)) {
11865            contentHTML += Templates.mobileDownloadBar({});
11866        }
11867        var previewId = isRunIngInNodeEnv ? undefined : getPreviewId();
11868        var isPreview = !!previewId;
11869        if (!hideHeaderByBi && configData.menu) {
11870            contentHTML += Templates.menu(convertMenuData(configData, cid, pageType, lang, isPreview));
11871        }
11872        contentHTML = renderPageContent(configData, contentHTML, pageType, isPreview);
11873        var websitePopup = getWebsitePopupTemplateData(configData, pageType);
11874        if (websitePopup) {
11875            contentHTML += Templates.websitePopup(websitePopup);
11876        }
11877        if (configData.footer) {
11878            contentHTML += Templates.footer(convertFooterData(configData, {
11879                logoImage: partnershipConfig.branding.logo,
11880                logoImageClassName: partnershipConfig.branding.footerLogoClass,
11881            }));
11882            if (((_c = (_b = configData.footer.cookie) === null || _b === void 0 ? void 0 : _b.cookie_popup) === null || _c === void 0 ? void 0 : _c.active_type) === 1) {
11883                contentHTML += Templates.cookieModal({});
11884            }
11885        }
11886        // 如果是在 nodejs 环境中运行,则直接返回 contentHTML
11887        // body 的 html 和 header 的html 分开返回
11888        if (isRunIngInNodeEnv) {
11889            return {
11890                body: contentHTML,
11891                header: headerHTML,
11892            };
11893        }
11894        var contentContainer = document.getElementById('content-container');
11895        if (!contentContainer) {
11896            console.error('Template container not found');
11897            return;
11898        }
11899        contentContainer.innerHTML = contentHTML;
11900        reportRenderFinish();
11901    }
11902    // 上报渲染完成
11903    var reportRenderFinish = function () {
11904        var _a, _b;
11905        (_b = (_a = window.__NSS_CONTEXT__).reportToES) === null || _b === void 0 ? void 0 : _b.call(_a, 'entry', {
11906            render: 1,
11907            renderTime: Date.now() - window.__NSS_CONTEXT__.__PAGE_RENDER_START__,
11908        });
11909    };
11910    // https://apidoc.i.ssc.shopeemobile.com/project/2060/interface/api/353393
11911    var getLanguageParam = function () {
11912        var language = checkCurrentLanguage();
11913        if (language === 'en') {
11914            return 'en';
11915        }
11916        else if (language === 'zh-Hans') {
11917            return 'cn';
11918        }
11919        else {
11920            return 'local';
11921        }
11922    };
11923    /**
11924     * 获取模板数据
11925     * @param pageId
11926     * @returns
11927     */
11928    var getTemplateData = function () {
11929        var args_1 = [];
11930        for (var _i = 0; _i < arguments.length; _i++) {
11931            args_1[_i] = arguments[_i];
11932        }
11933        return __awaiter$7(void 0, __spreadArray$2([], args_1, true), void 0, function (pageType) {
11934            var language, previewId, path, response;
11935            if (pageType === void 0) { pageType = PAGE_TYPE.home; }
11936            return __generator$7(this, function (_a) {
11937                switch (_a.label) {
11938                    case 0:
11939                        language = getLanguageParam();
11940                        previewId = getPreviewId();
11941                        path = window.location.pathname;
11942                        return [4 /*yield*/, fetchData(language, previewId, '', undefined, pageType, path)];
11943                    case 1:
11944                        response = (_a.sent()).response;
11945                        if (response.retcode !== 0) {
11946                            // reportToES('load-config-error', {
11947                            //   page_type: pageType,
11948                            //   language,
11949                            //   preview_id: previewId,
11950                            //   path,
11951                            //   err_msg: response.message,
11952                            // })
11953                            return [2 /*return*/, {}];
11954                        }
11955                        return [2 /*return*/, response.data];
11956                }
11957            });
11958        });
11959    };
11960    var fetchData = function (language_1, previewId_1) {
11961        var args_1 = [];
11962        for (var _i = 2; _i < arguments.length; _i++) {
11963            args_1[_i - 2] = arguments[_i];
11964        }
11965        return __awaiter$7(void 0, __spreadArray$2([language_1, previewId_1], args_1, true), void 0, function (language, previewId, apiPrefix, fetchOptions, pageType, path, 
11966        // 配合静态化服务使用
11967        log) {
11968            var url, params, pageTypePath, response, error_1, careerConfig, jobId, careerConfig, careerConfig;
11969            var _a;
11970            if (apiPrefix === void 0) { apiPrefix = ''; }
11971            if (pageType === void 0) { pageType = PAGE_TYPE.home; }
11972            return __generator$7(this, function (_b) {
11973                switch (_b.label) {
11974                    case 0:
11975                        url = '';
11976                        params = {};
11977                        if (previewId) {
11978                            url = "/shipment/account/open/website/page/get_preview";
11979                            params = {
11980                                preview_id: previewId,
11981                                language: language,
11982                            };
11983                        }
11984                        else {
11985                            pageTypePath = pageType === PAGE_TYPE.home ? 'home' : 'secondary';
11986                            url = apiPrefix + "/shipment/account/open/website/".concat(pageTypePath, "/info");
11987                            params = buildWebsiteInfoParams(pageType, language, path);
11988                        }
11989                        _b.label = 1;
11990                    case 1:
11991                        _b.trys.push([1, 3, , 4]);
11992                        return [4 /*yield*/, fetchGet(url, params, fetchOptions)];
11993                    case 2:
11994                        response = _b.sent();
11995                        return [3 /*break*/, 4];
11996                    case 3:
11997                        error_1 = _b.sent();
11998                        throw error_1;
11999                    case 4:
12000                        // career 即使接口成功也走专用 mapper/shell,
12001                        // 避免 secondary/info 的 sort_module(basic/banner/main_introduction/department/text_and_image)
12002                        // 被渲染器当成多个独立模块拆开渲染,也避免 jobs/detail 因 page_path=/career.html 被按 home 渲染。
12003                        if (response.retcode === 0 && pageType === PAGE_TYPE.detail) {
12004                            if (isCareerJobsPath(path)) {
12005                                careerConfig = getCareerJobsShellConfig(parseCareerJobsQuery(), path);
12006                                response.data = mapApiDataToCareerJobs(response.data, careerConfig);
12007                            }
12008                            else if (isCareerJobDetailPath(path)) {
12009                                jobId = getCareerJobId() || '';
12010                                careerConfig = getCareerJobDetailShellConfig(jobId, path);
12011                                response.data = mapApiDataToCareerJobDetail(response.data, careerConfig);
12012                            }
12013                            else if (isCareerHomePath(path) ||
12014                                ((_a = response.data) === null || _a === void 0 ? void 0 : _a.page_type) === DETAIL_PAGE_TYPE.career ||
12015                                isCareerHomeConfigData(response.data)) {
12016                                careerConfig = getCareerHomeShellConfig(path);
12017                                response.data = mapApiDataToCareerHome(response.data, careerConfig);
12018                            }
12019                        }
12020                        return [2 /*return*/, {
12021                                response: response,
12022                                url: url,
12023                                params: params,
12024                            }];
12025                }
12026            });
12027        });
12028    };
12029
12030    var formatAPIBasicInfo = function (apiResData) {
12031        // 这些字段默认用主账号(登录账号)的值
12032        var _a = apiResData || {}, region = _a.region, email = _a.email, phone_number = _a.phone_number, account_status = _a.account_status, account_id = _a.account_id, user_id = _a.user_id, user_secret = _a.user_secret, tc_acceptance_time = _a.tc_acceptance_time, pp_acceptance_time = _a.pp_acceptance_time, main_shop = _a.main_shop;
12033        // 这些字段默认用子账号的值
12034        var _b = (apiResData === null || apiResData === void 0 ? void 0 : apiResData.sub_account_base_info) || apiResData || {}, kyc_status = _b.kyc_status, kyc_type = _b.kyc_type, is_linked = _b.is_linked, is_agree_sync = _b.is_agree_sync, address_sync_latest_time = _b.address_sync_latest_time, address_sync_status = _b.address_sync_status, bank_sync_latest_time = _b.bank_sync_latest_time, bank_sync_status = _b.bank_sync_status, shop_sync_latest_time = _b.shop_sync_latest_time, shop_sync_status = _b.shop_sync_status, is_close_sync = _b.is_close_sync, is_support_cod = _b.is_support_cod, cod_interest_form_status = _b.cod_interest_form_status; // 如果切到了子账号就会返回子账号的值
12035        var loginAccountInfo = __assign$3({}, (apiResData || {}));
12036        if (loginAccountInfo.sub_account_base_info) {
12037            delete loginAccountInfo.sub_account_base_info;
12038        }
12039        var basicInfo = {
12040            // 默认为主账号的值
12041            region: region,
12042            email: email,
12043            phone_number: phone_number,
12044            account_status: account_status,
12045            account_id: account_id,
12046            user_id: user_id,
12047            user_secret: user_secret,
12048            tc_acceptance_time: tc_acceptance_time,
12049            pp_acceptance_time: pp_acceptance_time,
12050            main_shop: main_shop,
12051            // 默认子账号的值,没有切到子账号就是主账号的值
12052            kyc_status: kyc_status,
12053            kyc_type: kyc_type,
12054            is_linked: is_linked,
12055            is_agree_sync: is_agree_sync,
12056            address_sync_latest_time: address_sync_latest_time,
12057            address_sync_status: address_sync_status,
12058            bank_sync_latest_time: bank_sync_latest_time,
12059            bank_sync_status: bank_sync_status,
12060            shop_sync_latest_time: shop_sync_latest_time,
12061            shop_sync_status: shop_sync_status,
12062            is_close_sync: is_close_sync,
12063            is_support_cod: is_support_cod,
12064            cod_interest_form_status: cod_interest_form_status,
12065            // 根据场景判断是取主账号还是子账号的值
12066            curtLoginAccountInfo: loginAccountInfo,
12067            // 优先取子账号sub_account_base_info的数据,否则取主账号的数据
12068            curtSubAccountInfo: (apiResData === null || apiResData === void 0 ? void 0 : apiResData.sub_account_base_info) || loginAccountInfo,
12069        };
12070        return basicInfo;
12071    };
12072    function getBasicInfo() {
12073        // dev login need to avoid call this api to make login success.
12074        var isDevLoginPage = location.pathname.includes('dev-login-redirect');
12075        if (isDevLoginPage)
12076            return Promise.resolve({});
12077        return fetchGet('/shipment/account/api/base_info/detail');
12078    }
12079
12080    var setGlobalData = function (key, val, namespace) {
12081        if (!window.__NSS_CONTEXT__) {
12082            window.__NSS_CONTEXT__ = {};
12083        }
12084        window.__NSS_CONTEXT__[key] = val;
12085    };
12086    var getGlobalData = function (key, namespace) {
12087        if (!window.__NSS_CONTEXT__) {
12088            window.__NSS_CONTEXT__ = {};
12089        }
12090        return window.__NSS_CONTEXT__[key];
12091    };
12092    var setGlobalEvent = function (key, val) {
12093        if (!window.__NSS_EVENT__) {
12094            window.__NSS_EVENT__ = {};
12095        }
12096        window.__NSS_EVENT__[key] = val;
12097    };
12098    var getUserInfo = function () { return __awaiter$7(void 0, void 0, void 0, function () {
12099        var userInfoInSession, res_1, res;
12100        return __generator$7(this, function (_a) {
12101            switch (_a.label) {
12102                case 0:
12103                    userInfoInSession = sessionStorage.getItem('nss_user_info');
12104                    if (userInfoInSession) {
12105                        try {
12106                            res_1 = JSON.parse(userInfoInSession);
12107                            setGlobalData('userInfo', res_1);
12108                            return [2 /*return*/, res_1];
12109                        }
12110                        catch (e) {
12111                            return [2 /*return*/, window.__NSS_CONTEXT__.userInfo];
12112                        }
12113                    }
12114                    if (window.__NSS_CONTEXT__.userInfo) {
12115                        return [2 /*return*/, window.__NSS_CONTEXT__.userInfo];
12116                    }
12117                    return [4 /*yield*/, getBasicInfo()];
12118                case 1:
12119                    res = (_a.sent()).data;
12120                    setGlobalData('userInfo', res);
12121                    return [2 /*return*/, res];
12122            }
12123        });
12124    }); };
12125
12126    const byteToHex = [];
12127    for (let i = 0; i < 256; ++i) {
12128        byteToHex.push((i + 0x100).toString(16).slice(1));
12129    }
12130    function unsafeStringify(arr, offset = 0) {
12131        return (byteToHex[arr[offset + 0]] +
12132            byteToHex[arr[offset + 1]] +
12133            byteToHex[arr[offset + 2]] +
12134            byteToHex[arr[offset + 3]] +
12135            '-' +
12136            byteToHex[arr[offset + 4]] +
12137            byteToHex[arr[offset + 5]] +
12138            '-' +
12139            byteToHex[arr[offset + 6]] +
12140            byteToHex[arr[offset + 7]] +
12141            '-' +
12142            byteToHex[arr[offset + 8]] +
12143            byteToHex[arr[offset + 9]] +
12144            '-' +
12145            byteToHex[arr[offset + 10]] +
12146            byteToHex[arr[offset + 11]] +
12147            byteToHex[arr[offset + 12]] +
12148            byteToHex[arr[offset + 13]] +
12149            byteToHex[arr[offset + 14]] +
12150            byteToHex[arr[offset + 15]]).toLowerCase();
12151    }
12152
12153    let getRandomValues;
12154    const rnds8 = new Uint8Array(16);
12155    function rng() {
12156        if (!getRandomValues) {
12157            if (typeof crypto === 'undefined' || !crypto.getRandomValues) {
12158                throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
12159            }
12160            getRandomValues = crypto.getRandomValues.bind(crypto);
12161        }
12162        return getRandomValues(rnds8);
12163    }
12164
12165    const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
12166    var native = { randomUUID };
12167
12168    function v4(options, buf, offset) {
12169        if (native.randomUUID && !buf && !options) {
12170            return native.randomUUID();
12171        }
12172        options = options || {};
12173        const rnds = options.random ?? options.rng?.() ?? rng();
12174        if (rnds.length < 16) {
12175            throw new Error('Random bytes length must be >= 16');
12176        }
12177        rnds[6] = (rnds[6] & 0x0f) | 0x40;
12178        rnds[8] = (rnds[8] & 0x3f) | 0x80;
12179        return unsafeStringify(rnds);
12180    }
12181
12182    function wrapTranslationFunToText(data, translationText) {
12183        if (typeof data === 'string' && translationText.some(function (t) { return t === data; })) {
12184            return function () { return $gt(data); };
12185        }
12186        if (data && typeof data === 'object') {
12187            for (var key in data) {
12188                data[key] = wrapTranslationFunToText(data[key], translationText);
12189            }
12190        }
12191        return data;
12192    }
12193    function wrapTranslationText(data, translationText) {
12194        if (typeof data === 'string' && translationText.some(function (t) { return t === data; })) {
12195            return $gt(data);
12196        }
12197        if (data && typeof data === 'object') {
12198            for (var key in data) {
12199                data[key] = wrapTranslationText(data[key], translationText);
12200            }
12201        }
12202        return data;
12203    }
12204    function formatData(data) {
12205        try {
12206            var pageConfigInfo_1 = {};
12207            Object.entries(data).forEach(function (_a) {
12208                var key = _a[0], value = _a[1];
12209                var configData = value.config;
12210                var translationText = value.translationText;
12211                if (!configData)
12212                    return;
12213                // 全局配置文案需要用 $gt 函数包裹成函数调用形式,页面配置返回翻译后的文案即可
12214                if (key === 'global') {
12215                    pageConfigInfo_1.globalPageConfig = wrapTranslationFunToText(configData, translationText || []);
12216                    return;
12217                }
12218                pageConfigInfo_1[key] = wrapTranslationText(configData, translationText || []);
12219            });
12220            return pageConfigInfo_1;
12221        }
12222        catch (e) {
12223            // mdapReporter.capture({
12224            //   error: e,
12225            //   data: {
12226            //     name: 'PageConfigFormat',
12227            //     data_field: { error_type: 'page_config_format', },
12228            //     level: 'error',
12229            //     extra: data,
12230            //   },
12231            // });
12232            return {};
12233        }
12234    }
12235    var cachedConfig;
12236    function getV1PageConfig() {
12237        if (cachedConfig) {
12238            return cachedConfig;
12239        }
12240        var isPreview = location.search.includes('preview=');
12241        // publish后变成active的数据,还没有变成draft时去preview,草稿数据被删除
12242        var data = isPreview && window.__nss_page_config_draft__ ? window.__nss_page_config_draft__ : window.__nss_page_config__;
12243        if (data && typeof data === 'object') {
12244            cachedConfig = formatData(data);
12245            return cachedConfig;
12246        }
12247        return {};
12248    }
12249    // get specified config
12250    function getSpecifiedConfig(key) {
12251        var config = getV1PageConfig();
12252        return config[key];
12253    }
12254
12255    var PageType;
12256    (function (PageType) {
12257        PageType["MainPage"] = "mainPage";
12258        PageType["LandingPage"] = "landingPage";
12259        PageType["HelpCenterPage"] = "helpCenterPage";
12260        PageType["OtherPage"] = "otherPages";
12261    })(PageType || (PageType = {}));
12262    var LiveChatProject;
12263    (function (LiveChatProject) {
12264        LiveChatProject[LiveChatProject["SPX"] = 8] = "SPX";
12265        // help center 不在重构的页面中
12266        // SPXHelp = 9,
12267        LiveChatProject[LiveChatProject["SPXEnquiries"] = 12] = "SPXEnquiries";
12268    })(LiveChatProject || (LiveChatProject = {}));
12269    function hashCode(str) {
12270        var hash = 0;
12271        for (var i = 0; i < str.length; i++) {
12272            hash = (hash << 5) - hash + str.charCodeAt(i);
12273            hash |= 0;
12274        }
12275        return hash;
12276    }
12277    var matchPath = function (pathname, path) {
12278        {
12279            return pathname === '/';
12280        }
12281    };
12282    var getPageType = function (pathname) {
12283        if (matchPath(pathname) || getLangFromUrl()) {
12284            return PageType.MainPage;
12285        }
12286        else {
12287            return PageType.OtherPage;
12288        }
12289    };
12290    var getUuidCode = function () {
12291        if (!localStorage.getItem('nss_uuid')) {
12292            localStorage.setItem('nss_uuid', v4());
12293        }
12294        var uuid = localStorage.getItem('nss_uuid');
12295        return hashCode(uuid || '');
12296    };
12297    var snakeCase = function (str) {
12298        return str
12299            .replace(/([a-z])([A-Z])/g, '$1_$2')
12300            .replace(/[\s-]+/g, '_')
12301            .toLowerCase();
12302    };
12303    var showLiveChatByConfig = function (pathname, liveChatConfig) {
12304        var _a, _b;
12305        var pageType = getPageType(pathname);
12306        var storageKey = "live_chat_".concat(snakeCase(pageType));
12307        if (storage.getItem(storageKey)) {
12308            return true;
12309        }
12310        var uuidCode = getUuidCode();
12311        var greyScale = ((_a = liveChatConfig === null || liveChatConfig === void 0 ? void 0 : liveChatConfig[pageType]) === null || _a === void 0 ? void 0 : _a.greyScale) || 100;
12312        var show = !!((_b = liveChatConfig === null || liveChatConfig === void 0 ? void 0 : liveChatConfig[pageType]) === null || _b === void 0 ? void 0 : _b.show) && uuidCode % 100 < greyScale;
12313        if (show) {
12314            var now = new Date();
12315            var endOfDay = new Date(now);
12316            endOfDay.setHours(23, 59, 59, 999);
12317            var times = Math.floor(endOfDay.getTime() / 1000) - Math.floor(now.getTime() / 1000);
12318            storage.setItem(storageKey, 1, times);
12319        }
12320        return show;
12321    };
12322    var getLiveChatProject = function () {
12323        var region = getRegion();
12324        if (['MY', 'ID', 'TH', 'PH', 'SG'].includes(region)) {
12325            return LiveChatProject.SPXEnquiries;
12326        }
12327        return LiveChatProject.SPX;
12328    };
12329    var injectChatSDK = function (loadedCb) {
12330        var region = getRegion().toLowerCase();
12331        var script = document.createElement('script');
12332        script.type = 'text/javascript';
12333        script.async = true;
12334        script.src =
12335            'https://deo.shopeemobile.com/shopee/shopee-cschat-' +
12336                getCurEnv() +
12337                '-' +
12338                region +
12339                '/cschat.js?timestamp=' +
12340                new Date().getTime();
12341        document.body.appendChild(script);
12342        window.OnCSChatSourceLoad = function () {
12343            // Load initialization
12344            loadedCb === null || loadedCb === void 0 ? void 0 : loadedCb();
12345        };
12346        window.csChatLogin = function () {
12347            window.location.href = getLoginUrl();
12348        };
12349    };
12350    function getChatToken(params) {
12351        var region = getRegion();
12352        // Rich-todo: 依赖了翻译 KEY,需要改
12353        var useNewTokenApi = region === 'ID';
12354        // Determine which endpoint to use
12355        var endpoint = useNewTokenApi
12356            ? '/shipment/account/api/marketChatBot/getAccessToken'
12357            : '/shipment/account/api/chatbox/getAccessToken';
12358        return fetchGet(endpoint, params);
12359    }
12360    var initChat = function (project, isLogin) { return __awaiter$7(void 0, void 0, void 0, function () {
12361        var region;
12362        var _a, _b;
12363        return __generator$7(this, function (_c) {
12364            if (!isLogin) {
12365                (_a = window.CSChatToggleChatWindow) === null || _a === void 0 ? void 0 : _a.call(window);
12366            }
12367            try {
12368                region = getRegion().toLowerCase();
12369                (_b = window.CSChatAgentInit) === null || _b === void 0 ? void 0 : _b.call(window, {
12370                    project: project,
12371                    userLanguage: getChatUserLanguage(instance.language),
12372                    region: region,
12373                    isLogined: isLogin,
12374                    getToken: function () { return __awaiter$7(void 0, void 0, void 0, function () {
12375                        var token, error_1;
12376                        return __generator$7(this, function (_a) {
12377                            switch (_a.label) {
12378                                case 0:
12379                                    _a.trys.push([0, 2, , 3]);
12380                                    return [4 /*yield*/, getChatToken({ max_ttl: 3600 })];
12381                                case 1:
12382                                    token = (_a.sent()).data.AccessToken;
12383                                    return [2 /*return*/, { code: 0, token: token }];
12384                                case 2:
12385                                    error_1 = _a.sent();
12386                                    console.error(error_1);
12387                                    return [2 /*return*/, { code: -1, token: '' }];
12388                                case 3: return [2 /*return*/];
12389                            }
12390                        });
12391                    }); },
12392                });
12393            }
12394            catch (err) {
12395                console.error(err);
12396            }
12397            return [2 /*return*/];
12398        });
12399    }); };
12400    var showLiveChat = function (pathname, liveChatConfig) {
12401        var region = getRegion();
12402        switch (region) {
12403            case 'ID':
12404            case 'VN':
12405            case 'TH':
12406            case 'MY':
12407            case 'PH':
12408            case 'SG':
12409                return showLiveChatByConfig(pathname, liveChatConfig);
12410            default:
12411                return false;
12412        }
12413    };
12414    var loadAndInitChat = function () { return __awaiter$7(void 0, void 0, void 0, function () {
12415        var liveChatConfig, accountId_1, res, formatData;
12416        var _a, _b, _c, _d;
12417        return __generator$7(this, function (_e) {
12418            switch (_e.label) {
12419                case 0:
12420                    liveChatConfig = getSpecifiedConfig('liveChat');
12421                    if (!showLiveChat(location.pathname, liveChatConfig)) {
12422                        return [2 /*return*/];
12423                    }
12424                    _e.label = 1;
12425                case 1:
12426                    _e.trys.push([1, 5, , 6]);
12427                    accountId_1 = null;
12428                    if (!((_b = (_a = window.__NSS_CONTEXT__) === null || _a === void 0 ? void 0 : _a.userInfo) === null || _b === void 0 ? void 0 : _b.account_id)) return [3 /*break*/, 2];
12429                    accountId_1 = (_d = (_c = window.__NSS_CONTEXT__) === null || _c === void 0 ? void 0 : _c.userInfo) === null || _d === void 0 ? void 0 : _d.account_id;
12430                    return [3 /*break*/, 4];
12431                case 2: return [4 /*yield*/, getBasicInfo()];
12432                case 3:
12433                    res = (_e.sent()).data;
12434                    formatData = formatAPIBasicInfo(res);
12435                    accountId_1 = formatData.account_id;
12436                    _e.label = 4;
12437                case 4:
12438                    injectChatSDK(function () { return initChat(getLiveChatProject(), !!accountId_1); });
12439                    return [3 /*break*/, 6];
12440                case 5:
12441                    _e.sent();
12442                    return [3 /*break*/, 6];
12443                case 6: return [2 /*return*/];
12444            }
12445        });
12446    }); };
12447    // when page completely loaded, init live chat
12448    var initLiveChat = function () {
12449        if (isMobile() || isCtl) {
12450            return;
12451        }
12452        window.addEventListener('load', function () { return __awaiter$7(void 0, void 0, void 0, function () {
12453            return __generator$7(this, function (_a) {
12454                switch (_a.label) {
12455                    case 0: return [4 /*yield*/, loadAndInitChat()];
12456                    case 1:
12457                        _a.sent();
12458                        return [2 /*return*/];
12459                }
12460            });
12461        }); });
12462    };
12463
12464    /**
12465     * 图片懒加载实现
12466     * 使用 Intersection Observer API 实现
12467     * 支持两种加载策略:
12468     * 1. 图片进入视口时加载
12469     * 2. 页面加载完成后,提前加载可视区域附近的图片
12470     * 用法:
12471     * 在 img 标签上,加上类名 "lazy-load" 和 data-src 属性即可
12472     * 例如:
12473     * <img class="lazy-load" data-src="https://example.com/image.jpg" alt="图片描述" />
12474     */
12475    var LazyLoader = /** @class */ (function () {
12476        function LazyLoader(options) {
12477            if (options === void 0) { options = {}; }
12478            this.options = __assign$3({ root: null, rootMargin: '50px 0px', threshold: 0.1 }, options);
12479            this.observer = null;
12480            this.images = [];
12481            this.init();
12482        }
12483        LazyLoader.prototype.init = function () {
12484            var _this = this;
12485            // 立即加载首屏图片
12486            this.preloadVisibleImages();
12487            // 监听窗口大小变化,重新加载可视区域图片
12488            window.addEventListener('resize', function () {
12489                _this.preloadVisibleImages();
12490            });
12491            // 监听 visualViewport 变化(移动设备键盘弹出等)
12492            if (window.visualViewport) {
12493                window.visualViewport.addEventListener('resize', function () {
12494                    _this.preloadVisibleImages();
12495                });
12496            }
12497            // 检查浏览器是否支持 Intersection Observer
12498            if ('IntersectionObserver' in window) {
12499                this.observer = new IntersectionObserver(this.handleIntersection.bind(this), this.options);
12500                this.observeImages();
12501            }
12502            else {
12503                // 降级处理:直接加载所有图片
12504                this.loadAllImages();
12505            }
12506            // 页面加载完成后,提前加载可视区域附近的图片
12507            if (document.readyState === 'loading') {
12508                document.addEventListener('DOMContentLoaded', function () { return _this.preloadVisibleImages(); });
12509            }
12510        };
12511        LazyLoader.prototype.observeImages = function () {
12512            var _this = this;
12513            this.images = document.querySelectorAll('img.lazy-load');
12514            this.images.forEach(function (img) { var _a; return (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.observe(img); });
12515        };
12516        LazyLoader.prototype.handleIntersection = function (entries) {
12517            var _this = this;
12518            entries.forEach(function (entry) {
12519                var _a;
12520                if (entry.isIntersecting) {
12521                    _this.loadImage(entry.target);
12522                    (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.unobserve(entry.target);
12523                }
12524            });
12525        };
12526        LazyLoader.prototype.loadImage = function (img) {
12527            var src = img.dataset.src;
12528            if (!src)
12529                return;
12530            img.onload = function () {
12531                img.removeAttribute('data-src');
12532            };
12533            img.src = src;
12534        };
12535        LazyLoader.prototype.preloadVisibleImages = function () {
12536            var _this = this;
12537            var _a;
12538            // 获取可视区域附近的图片
12539            var viewportHeight = document.documentElement.clientHeight || window.innerHeight;
12540            var preloadDistance = parseInt(((_a = this.options.rootMargin) === null || _a === void 0 ? void 0 : _a.split(' ')[0]) || '50');
12541            this.images.forEach(function (img) {
12542                var _a;
12543                var rect = img.getBoundingClientRect();
12544                // 如果图片在可视区域附近(上下各50px范围内),提前加载
12545                if (rect.top < viewportHeight + preloadDistance && rect.bottom > -preloadDistance) {
12546                    _this.loadImage(img);
12547                    (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.unobserve(img);
12548                }
12549            });
12550        };
12551        LazyLoader.prototype.loadAllImages = function () {
12552            var _this = this;
12553            this.images.forEach(function (img) { return _this.loadImage(img); });
12554        };
12555        return LazyLoader;
12556    }());
12557
12558    var EventFactory = /** @class */ (function () {
12559        function EventFactory(options) {
12560            if (options === void 0) { options = {}; }
12561            var _a, _b, _c;
12562            this.eventQueue = [];
12563            this.options = {
12564                maxConcurrency: (_a = options.maxConcurrency) !== null && _a !== void 0 ? _a : 4,
12565                timeout: (_b = options.timeout) !== null && _b !== void 0 ? _b : 30000, // 30 seconds default timeout
12566                enableLogging: (_c = options.enableLogging) !== null && _c !== void 0 ? _c : false,
12567            };
12568        }
12569        /**
12570         * Add an event handler to the queue
12571         * @param handler - Function to be executed, can be sync or async
12572         * @param name - Optional name for debugging and logging
12573         */
12574        EventFactory.prototype.subscribe = function (handler, name) {
12575            if (typeof handler !== 'function') {
12576                throw new Error('Event handler must be a function');
12577            }
12578            var handlerName = name || handler.name || "anonymous_".concat(this.eventQueue.length);
12579            this.eventQueue.push({
12580                handler: handler,
12581                name: handlerName,
12582            });
12583            if (this.options.enableLogging) {
12584                console.log("[EventFactory] Handler \"".concat(handlerName, "\" added to queue"));
12585            }
12586        };
12587        /**
12588         * Execute all events in parallel with proper error isolation
12589         * @param configData - Data to be passed to each event handler
12590         * @returns Promise with execution results
12591         */
12592        EventFactory.prototype.execute = function (configData, name) {
12593            return __awaiter$7(this, void 0, void 0, function () {
12594                var events, count, semaphore, executionPromises, results, eventResults, successCount, failureCount;
12595                var _this = this;
12596                return __generator$7(this, function (_a) {
12597                    switch (_a.label) {
12598                        case 0:
12599                            if (this.eventQueue.length === 0) {
12600                                if (this.options.enableLogging) {
12601                                    console.log('[EventFactory] No events to execute');
12602                                }
12603                                return [2 /*return*/, []];
12604                            }
12605                            events = name ? this.eventQueue.filter(function (event) { return event.name === name; }) : this.eventQueue;
12606                            count = events.length;
12607                            if (this.options.enableLogging) {
12608                                console.log("[EventFactory] Executing ".concat(count, " events in parallel"));
12609                            }
12610                            semaphore = new Semaphore(this.options.maxConcurrency);
12611                            executionPromises = events.map(function (_a) {
12612                                var handler = _a.handler, name = _a.name;
12613                                return semaphore.acquire().then(function () {
12614                                    return _this.executeWithIsolation(handler, configData, name)
12615                                        .finally(function () { return semaphore.release(); });
12616                                });
12617                            });
12618                            return [4 /*yield*/, Promise.allSettled(executionPromises)];
12619                        case 1:
12620                            results = _a.sent();
12621                            eventResults = results.map(function (result, index) {
12622                                var _a;
12623                                if (result.status === 'fulfilled') {
12624                                    return result.value;
12625                                }
12626                                else {
12627                                    // This should rarely happen due to our error isolation
12628                                    return {
12629                                        success: false,
12630                                        error: new Error("Unexpected promise rejection: ".concat(result.reason)),
12631                                        handlerName: (_a = events[index]) === null || _a === void 0 ? void 0 : _a.name,
12632                                        executionTime: 0,
12633                                    };
12634                                }
12635                            });
12636                            if (this.options.enableLogging) {
12637                                successCount = eventResults.filter(function (r) { return r.success; }).length;
12638                                failureCount = eventResults.length - successCount;
12639                                console.log("[EventFactory] Execution completed: ".concat(successCount, " successful, ").concat(failureCount, " failed"));
12640                            }
12641                            return [2 /*return*/, eventResults];
12642                    }
12643                });
12644            });
12645        };
12646        /**
12647         * Execute a single handler with proper error isolation and timeout
12648         */
12649        EventFactory.prototype.executeWithIsolation = function (handler, configData, handlerName) {
12650            return __awaiter$7(this, void 0, void 0, function () {
12651                var startTime, timeoutPromise, handlerPromise, executionTime, error_1, executionTime, finalError;
12652                var _this = this;
12653                return __generator$7(this, function (_a) {
12654                    switch (_a.label) {
12655                        case 0:
12656                            startTime = Date.now();
12657                            _a.label = 1;
12658                        case 1:
12659                            _a.trys.push([1, 3, , 4]);
12660                            timeoutPromise = new Promise(function (_, reject) {
12661                                setTimeout(function () {
12662                                    reject(new Error("Handler \"".concat(handlerName, "\" timed out after ").concat(_this.options.timeout, "ms, configData: ").concat(JSON.stringify(configData))));
12663                                }, _this.options.timeout);
12664                            });
12665                            handlerPromise = Promise.resolve(handler(configData));
12666                            return [4 /*yield*/, Promise.race([handlerPromise, timeoutPromise])];
12667                        case 2:
12668                            _a.sent();
12669                            executionTime = Date.now() - startTime;
12670                            if (this.options.enableLogging) {
12671                                console.log("[EventFactory] Handler \"".concat(handlerName, "\" completed successfully in ").concat(executionTime, "ms"));
12672                            }
12673                            return [2 /*return*/, {
12674                                    success: true,
12675                                    handlerName: handlerName,
12676                                    executionTime: executionTime,
12677                                }];
12678                        case 3:
12679                            error_1 = _a.sent();
12680                            executionTime = Date.now() - startTime;
12681                            finalError = error_1 instanceof Error ? error_1 : new Error(String(error_1));
12682                            if (this.options.enableLogging) {
12683                                console.error("[EventFactory] Handler \"".concat(handlerName, "\" failed after ").concat(executionTime, "ms:"), finalError.message);
12684                            }
12685                            return [2 /*return*/, {
12686                                    success: false,
12687                                    error: finalError,
12688                                    handlerName: handlerName,
12689                                    executionTime: executionTime,
12690                                }];
12691                        case 4: return [2 /*return*/];
12692                    }
12693                });
12694            });
12695        };
12696        /**
12697         * Clear all event handlers from the queue
12698         */
12699        EventFactory.prototype.clear = function () {
12700            var count = this.eventQueue.length;
12701            this.eventQueue = [];
12702            if (this.options.enableLogging) {
12703                console.log("[EventFactory] Cleared ".concat(count, " handlers from queue"));
12704            }
12705        };
12706        return EventFactory;
12707    }());
12708    /**
12709     * Simple semaphore implementation for concurrency control
12710     */
12711    var Semaphore = /** @class */ (function () {
12712        function Semaphore(permits) {
12713            this.waitQueue = [];
12714            this.permits = permits;
12715        }
12716        Semaphore.prototype.acquire = function () {
12717            return __awaiter$7(this, void 0, void 0, function () {
12718                var _this = this;
12719                return __generator$7(this, function (_a) {
12720                    if (this.permits > 0) {
12721                        this.permits--;
12722                        return [2 /*return*/, Promise.resolve()];
12723                    }
12724                    return [2 /*return*/, new Promise(function (resolve) {
12725                            _this.waitQueue.push(resolve);
12726                        })];
12727                });
12728            });
12729        };
12730        Semaphore.prototype.release = function () {
12731            this.permits++;
12732            var next = this.waitQueue.shift();
12733            if (next) {
12734                this.permits--;
12735                next();
12736            }
12737        };
12738        return Semaphore;
12739    }());
12740    /**
12741     * Create a new event factory instance
12742     * @param options - Configuration options
12743     * @returns New EventFactory instance
12744     */
12745    function createEventFactory(options) {
12746        return new EventFactory(options);
12747    }
12748    /**
12749     * 作用范围:同构模块
12750     * 全局事件管理器,用于管理所有事件
12751     * EventList 是事件的类型,用于区分不同的事件
12752     * 事件的执行顺序:
12753     * 1. before-init 初始化前调用
12754     * 2. init 初始化时调用
12755     * 3. load-resource-success 加载资源成功时调用, 静态渲染模式不会执行
12756     * 2. template-rendered 模板渲染完成时调用
12757     * 4. load-resource-error 加载资源失败时调用, 静态渲染模式不会执行
12758     * 5. render-error 渲染失败时调用, 静态渲染模式不会执行
12759     * 6. page-finish 页面完成时调用
12760     */
12761    var pageGlobalEvent = createEventFactory();
12762
12763    var getRenderWayConfig = function () { return __awaiter$7(void 0, void 0, void 0, function () {
12764        var response;
12765        return __generator$7(this, function (_a) {
12766            switch (_a.label) {
12767                case 0: return [4 /*yield*/, fetchPost('/shipment/account/website/config-center/get', [
12768                        {
12769                            group: 'PageInit',
12770                            key: ['DynamicRender'],
12771                        },
12772                    ])];
12773                case 1:
12774                    response = _a.sent();
12775                    return [2 /*return*/, response.data];
12776            }
12777        });
12778    }); };
12779    var FORCE_DYNAMIC_RENDER_VALUE = '1';
12780    var backupDynamicRender = function () { return __awaiter$7(void 0, void 0, void 0, function () {
12781        var config, dynamicRenderConfig, isDynamicRender, currentCacheConfig;
12782        return __generator$7(this, function (_a) {
12783            switch (_a.label) {
12784                case 0: return [4 /*yield*/, getRenderWayConfig()];
12785                case 1:
12786                    config = _a.sent();
12787                    dynamicRenderConfig = config === null || config === void 0 ? void 0 : config['sls-nss-common-config.PageInit.DynamicRender'];
12788                    isDynamicRender = dynamicRenderConfig == FORCE_DYNAMIC_RENDER_VALUE;
12789                    if (isDynamicRender) {
12790                        currentCacheConfig = storage.getItem(IS_DYNAMIC_RENDER_KEY);
12791                        if (!currentCacheConfig) {
12792                            storage.setItem(IS_DYNAMIC_RENDER_KEY, FORCE_DYNAMIC_RENDER_VALUE);
12793                            location.reload();
12794                        }
12795                        return [2 /*return*/];
12796                    }
12797                    // 如果动态渲染关闭,则删除缓存
12798                    storage.removeItem(IS_DYNAMIC_RENDER_KEY);
12799                    return [2 /*return*/];
12800            }
12801        });
12802    }); };
12803    var initRenderSwitcher = function () {
12804        // register event listener when page is loaded
12805        window.addEventListener('load', backupDynamicRender);
12806    };
12807
12808    // VN标准快递物流产品
12809    var VN_STANDARD_PRODUCT_ID = 53001;
12810    // SG标准快递物流产品
12811    var SG_PRODUCT_ID = 13001;
12812    // TH标准快递物流产品
12813    var TH_PRODUCT_ID = 73001;
12814    // PH标准快递物流产品
12815    var PH_PRODUCT_ID = 43001;
12816    // ID标准快递物流产品
12817    var ID_PRODUCT_ID = 80050;
12818    // MY标准快递物流产品
12819    var MY_PRODUCT_ID = 20777;
12820    var PRODUCT_ID_CONFIG = {
12821        VN: VN_STANDARD_PRODUCT_ID,
12822        TH: TH_PRODUCT_ID,
12823        SG: SG_PRODUCT_ID,
12824        PH: PH_PRODUCT_ID,
12825        MY: MY_PRODUCT_ID,
12826        ID: ID_PRODUCT_ID,
12827    };
12828    var getDefaultProductId = function () {
12829        return PRODUCT_ID_CONFIG[getRegion()];
12830    };
12831    // 同一页面内的 EasyPack、Trucking 等功能共享完整白名单响应。
12832    // 登录/登出当前会通过页面跳转或刷新完成,因此缓存不会跨账号复用。
12833    var accountWhiteListPromise;
12834    var accountWhiteListProductId;
12835    var getAccountWhiteList = function () {
12836        var defaultProductId = getDefaultProductId();
12837        if (!defaultProductId) {
12838            var error = new Error('Account whitelist product id is unavailable');
12839            console.warn('getAccountWhiteList skipped: product id is unavailable', {
12840                region: getRegion(),
12841            });
12842            return Promise.reject(error);
12843        }
12844        if (accountWhiteListPromise &&
12845            accountWhiteListProductId === defaultProductId) {
12846            console.info('getAccountWhiteList reused cached request', {
12847                productId: defaultProductId,
12848            });
12849            return accountWhiteListPromise;
12850        }
12851        accountWhiteListProductId = defaultProductId;
12852        console.info('getAccountWhiteList request started', {
12853            productId: defaultProductId,
12854        });
12855        accountWhiteListPromise = fetchGet('/shipment/account/api/common_whitelist/check', {
12856            product_id: defaultProductId,
12857        })
12858            .then(function (response) { return response.data; })
12859            .catch(function (error) {
12860            // 失败不缓存,避免一次网络异常阻塞后续重试。
12861            if (accountWhiteListProductId === defaultProductId) {
12862                accountWhiteListPromise = undefined;
12863                accountWhiteListProductId = undefined;
12864            }
12865            console.warn('getAccountWhiteList request failed', {
12866                productId: defaultProductId,
12867                error: error,
12868            });
12869            throw error;
12870        });
12871        return accountWhiteListPromise;
12872    };
12873
12874    var initEasyPack = function () { return __awaiter$7(void 0, void 0, void 0, function () {
12875        var isOpenEasyPack, accountWhiteList, showEasyPack;
12876        var _a, _b;
12877        return __generator$7(this, function (_c) {
12878            switch (_c.label) {
12879                case 0:
12880                    isOpenEasyPack = (_b = (_a = getSpecifiedConfig('easypack')) === null || _a === void 0 ? void 0 : _a.homePage) === null || _b === void 0 ? void 0 : _b.show;
12881                    if (isOpenEasyPack) {
12882                        return [2 /*return*/, setGlobalData('openEasyPack', true)];
12883                    }
12884                    return [4 /*yield*/, getAccountWhiteList()];
12885                case 1:
12886                    accountWhiteList = _c.sent();
12887                    showEasyPack = (accountWhiteList === null || accountWhiteList === void 0 ? void 0 : accountWhiteList.is_open_easy_pack) === true;
12888                    !showEasyPack && hideEasyPack();
12889                    setGlobalData('openEasyPack', showEasyPack);
12890                    return [2 /*return*/];
12891            }
12892        });
12893    }); };
12894
12895    // 1.1.33 also reports action_first_view_utm_report for initial UTM/affiliate URLs.
12896    var TRACKING_LOADER_VERSION = '1.1.33';
12897    var TRACKING_LOADER_URL = 'https://deo.shopeemobile.com/shopee/shopee-trackingsdk-live-sg/index.js';
12898    // Tracking points: https://trafficsuite.shopee.io/tms/tracker/trackerLibrary?appId=333
12899    var TRACKING_APP_ID = 333;
12900    var initialized = false;
12901    var loaderPromise;
12902    var pendingEvents = [];
12903    var normalizeAutoViewRoute = function (pathname) {
12904        var pathWithoutQuery = pathname.split(/[?#]/, 1)[0];
12905        var pathWithoutLocale = pathWithoutQuery.replace(/^\/en(?=\/|$)/, '');
12906        var route = pathWithoutLocale.length > 1
12907            ? pathWithoutLocale.replace(/\/+$/, '')
12908            : pathWithoutLocale;
12909        return route || '/';
12910    };
12911    var loadTrackingSDK = function () {
12912        if (window.trackingSDK)
12913            return Promise.resolve();
12914        if (loaderPromise)
12915            return loaderPromise;
12916        loaderPromise = new Promise(function (resolve, reject) {
12917            var script = document.createElement('script');
12918            script.async = true;
12919            script.src = TRACKING_LOADER_URL;
12920            script.onload = function () { return resolve(); };
12921            script.onerror = function () { return reject(new Error('Failed to load TrackingSDK')); };
12922            document.head.appendChild(script);
12923        });
12924        return loaderPromise;
12925    };
12926    var setTrackingUserId = function (userId) {
12927        var _a;
12928        if (!userId)
12929            return;
12930        window.__NSS_TRACKING_USER_ID__ = userId;
12931        (_a = window.trackingSDK) === null || _a === void 0 ? void 0 : _a.ubt('setUserId', userId);
12932    };
12933    var sendTrackingEvent = function (eventData) {
12934        var _a;
12935        (_a = window.trackingSDK) === null || _a === void 0 ? void 0 : _a.ubt('track', eventData);
12936    };
12937    var flushPendingEvents = function () {
12938        if (!window.trackingSDK)
12939            return;
12940        while (pendingEvents.length) {
12941            var eventData = pendingEvents.shift();
12942            if (eventData)
12943                sendTrackingEvent(eventData);
12944        }
12945    };
12946    var reportTrackingEvent = function (eventData) {
12947        try {
12948            if (!window.trackingSDK || !initialized) {
12949                pendingEvents.push(eventData);
12950                void initTrackingSDK();
12951                return;
12952            }
12953            sendTrackingEvent(eventData);
12954        }
12955        catch (error) {
12956            console.warn('[TrackingSDK]', error);
12957        }
12958    };
12959    var reportAnchorClick = function (event) {
12960        // 1. 使用事件委托定位实际点击的链接,兼容链接内的文字、图片等子元素。
12961        var link = event.target.closest('a[href]');
12962        if (!link)
12963            return;
12964        // 2. 只上报网页链接,避免把邮箱、电话等内容作为埋点数据发送。
12965        var url = new URL(link.href, window.location.href);
12966        if (url.protocol !== 'http:' && url.protocol !== 'https:')
12967            return;
12968        // 3. 查询参数和锚点可能包含敏感信息,只保留稳定的来源路径和目标地址。
12969        reportTrackingEvent({
12970            operation: 'click',
12971            page_type: 'spx_website',
12972            page_section: 'global_link',
12973            target_type: 'anchor_click',
12974            data: {
12975                page_path: window.location.pathname,
12976                link_url: "".concat(url.origin).concat(url.pathname),
12977            },
12978        });
12979    };
12980    var getCurrentPageTrackingUserId = function () { var _a, _b; return (_b = (_a = window.__NSS_CONTEXT__) === null || _a === void 0 ? void 0 : _a.userInfo) === null || _b === void 0 ? void 0 : _b.account_id; };
12981    var initTrackingSDK = function () { return __awaiter$7(void 0, void 0, void 0, function () {
12982        var error_1;
12983        var _a;
12984        return __generator$7(this, function (_b) {
12985            switch (_b.label) {
12986                case 0:
12987                    if (initialized)
12988                        return [2 /*return*/];
12989                    _b.label = 1;
12990                case 1:
12991                    _b.trys.push([1, 3, , 4]);
12992                    return [4 /*yield*/, loadTrackingSDK()];
12993                case 2:
12994                    _b.sent();
12995                    if (initialized || !window.trackingSDK)
12996                        return [2 /*return*/];
12997                    window.trackingSDK.init(['ubt'], function (name) {
12998                        if (name !== 'ubt')
12999                            return {};
13000                        return {
13001                            appId: TRACKING_APP_ID,
13002                            version: {"NODE_ENV":"development","APP_VERSION":"v20260929-1220-MY-LIVE","env":"live","PARTNER_ID":"shopee"}.APP_VERSION,
13003                            app_version: {"NODE_ENV":"development","APP_VERSION":"v20260929-1220-MY-LIVE","env":"live","PARTNER_ID":"shopee"}.APP_VERSION,
13004                            autoTrackMatchRoutes: normalizeAutoViewRoute,
13005                            enableAutoTrack: true,
13006                            env: 'live' ,
13007                            locale: CID.toLowerCase(),
13008                            platform: 'pc',
13009                        };
13010                    }, TRACKING_LOADER_VERSION);
13011                    initialized = true;
13012                    setTrackingUserId((_a = window.__NSS_TRACKING_USER_ID__) !== null && _a !== void 0 ? _a : getCurrentPageTrackingUserId());
13013                    flushPendingEvents();
13014                    return [3 /*break*/, 4];
13015                case 3:
13016                    error_1 = _b.sent();
13017                    console.warn('[TrackingSDK]', error_1);
13018                    return [3 /*break*/, 4];
13019                case 4: return [2 /*return*/];
13020            }
13021        });
13022    }); };
13023
13024    var _a$2;
13025    // 1. 仅在页面主入口注册一次全局链接点击监听,避免共享模块被多个 bundle 引入时重复上报。
13026    (_a$2 = document.addEventListener) === null || _a$2 === void 0 ? void 0 : _a$2.call(document, 'click', reportAnchorClick, true);
13027    window.__NSS_CONTEXT__.appContainer =
13028        document.getElementById('content-container');
13029    // request loadResource and getTemplateData same time, then renderTemplates
13030    // if getTemplateData failed, show error message to the user
13031    function init(config) {
13032        return __awaiter$7(this, void 0, void 0, function () {
13033            var start, pageType, renderedCallback, templateFile, content, menu, isDynamicRender, isPreview;
13034            var _this = this;
13035            var _a, _b, _c, _d;
13036            return __generator$7(this, function (_e) {
13037                switch (_e.label) {
13038                    case 0:
13039                        void initTrackingSDK();
13040                        initRenderSwitcher();
13041                        initLiveChat();
13042                        pageGlobalEvent.execute(null, 'before-init');
13043                        // google analysis 相关的功能,运营投放需要,且要在
13044                        // loadAndInitChat 前运行,live chat 登陆后的 redirect 地址
13045                        // 依赖 google analysis 这些参数
13046                        if ((_a = location.search) === null || _a === void 0 ? void 0 : _a.includes('utm_source')) {
13047                            utmPatch();
13048                        }
13049                        start = Date.now();
13050                        pageType = config.pageType, renderedCallback = config.renderedCallback;
13051                        templateFile = pageType === 'index'
13052                            ? '/new_static/index-templates.497ef22f.js'
13053                            : '/new_static/detail-templates.a0a07c27.js';
13054                        content = (_b = window.__NSS_CONTEXT__.appContainer) === null || _b === void 0 ? void 0 : _b.innerHTML.trim();
13055                        // const isShowingTransifyKey = storage.getItem(SYSTEM_SHOW_TSP_KEY)
13056                        // bi=1: 轻量隐藏头部,不触发完整重渲染,保持 SSG 静态页面优势
13057                        if (shouldHideHeaderByBi(location.search)) {
13058                            menu = document.querySelector('.main-menu-layout');
13059                            if (menu)
13060                                menu.style.display = 'none';
13061                        }
13062                        isDynamicRender = storage.getItem(IS_DYNAMIC_RENDER_KEY);
13063                        isPreview = !!getPreviewId();
13064                        console.info('ENV, !isPreview, !isDynamicRender', ENV, !isPreview, !isDynamicRender);
13065                        if (!(!isPreview && content && !isDynamicRender)) return [3 /*break*/, 3];
13066                        reportRenderFinish();
13067                        renderedCallback === null || renderedCallback === void 0 ? void 0 : renderedCallback();
13068                        pageGlobalEvent.execute(null, 'template-rendered');
13069                        return [4 /*yield*/, initMustHave()];
13070                    case 1:
13071                        _e.sent();
13072                        (_d = (_c = window.__NSS_CONTEXT__).reportToES) === null || _d === void 0 ? void 0 : _d.call(_c, 'init-finish', {
13073                            duration: Date.now() - start,
13074                        });
13075                        pageGlobalEvent.execute(null, 'page-finish');
13076                        // 动态渲染:ship-modal 依赖 Templates 实现弹窗的动态更新
13077                        return [4 /*yield*/, loadTemplate(templateFile)
13078                            // 动态渲染的模版依赖 helper
13079                        ];
13080                    case 2:
13081                        // 动态渲染:ship-modal 依赖 Templates 实现弹窗的动态更新
13082                        _e.sent();
13083                        // 动态渲染的模版依赖 helper
13084                        registerHelpers();
13085                        return [2 /*return*/];
13086                    case 3:
13087                        /**
13088                         * 模板名不能动态拼装,因为build的时候会替换掉
13089                         */
13090                        Promise.all([
13091                            loadResource(),
13092                            loadTemplate(templateFile),
13093                            getTemplateData(pageType),
13094                        ])
13095                            .then(function (_a) { return __awaiter$7(_this, [_a], void 0, function (_b) {
13096                            var _c, _d;
13097                            _b[0]; _b[1]; var configData = _b[2];
13098                            return __generator$7(this, function (_e) {
13099                                switch (_e.label) {
13100                                    case 0:
13101                                        pageGlobalEvent.execute(configData, 'load-resource-success');
13102                                        try {
13103                                            registerHelpers();
13104                                            renderTemplates(configData, undefined, pageType, undefined, undefined, location.search);
13105                                            initDynamicRenderEvents(configData);
13106                                            renderedCallback === null || renderedCallback === void 0 ? void 0 : renderedCallback(configData);
13107                                            pageGlobalEvent.execute(configData, 'template-rendered');
13108                                        }
13109                                        catch (error) {
13110                                            console.error('render template error:', error);
13111                                            pageGlobalEvent.execute(configData, 'render-error');
13112                                            // Rich-todo: 替换为message类似的组件
13113                                        }
13114                                        setGlobalData('pageConfig', configData);
13115                                        (_d = (_c = window.__NSS_CONTEXT__).reportToES) === null || _d === void 0 ? void 0 : _d.call(_c, 'init-finish', {
13116                                            duration: Date.now() - start,
13117                                        });
13118                                        pageGlobalEvent.execute(configData, 'page-finish');
13119                                        return [4 /*yield*/, initMustHave()];
13120                                    case 1:
13121                                        _e.sent();
13122                                        return [2 /*return*/];
13123                                }
13124                            });
13125                        }); })
13126                            .catch(function (error) {
13127                            console.error('Error loading template data:', error);
13128                            pageGlobalEvent.execute(null, 'load-resource-error');
13129                            // Rich-todo: 替换为message类似的组件
13130                        });
13131                        return [2 /*return*/];
13132                }
13133            });
13134        });
13135    }
13136    /**
13137     * 不管动态渲染,还是静态渲染,都要执行的初始化
13138     */
13139    function initMustHave() {
13140        return __awaiter$7(this, void 0, void 0, function () {
13141            return __generator$7(this, function (_a) {
13142                switch (_a.label) {
13143                    case 0:
13144                        new LazyLoader();
13145                        initCareerRuntime();
13146                        proxyLinkClick();
13147                        return [4 /*yield*/, initEasyPack()];
13148                    case 1:
13149                        _a.sent();
13150                        return [2 /*return*/];
13151                }
13152            });
13153        });
13154    }
13155    function loadTemplate(templateFile) {
13156        return new Promise(function (resolve, reject) {
13157            // 非开发模式,使用CDN线上路径
13158            var filePath = templateFile
13159                ;
13160            var script = document.createElement('script');
13161            script.type = 'text/javascript';
13162            script.src = filePath;
13163            script.onload = function () {
13164                resolve(true);
13165            };
13166            script.onerror = function () {
13167                reject(new Error("Template ".concat(templateFile, " not found")));
13168            };
13169            document.body.appendChild(script);
13170        });
13171    }
13172    function initDynamicRenderEvents(configData) {
13173        setGlobalData('$gt', $gt);
13174    }
13175    //setCookieEvent()
13176    /**
13177     * 劫持 a 标签的行为
13178     * 处理带有 link 属性的 a 标签点击事件
13179     * 使用捕获阶段确保事件能被可靠捕获
13180     */
13181    function proxyLinkClick() {
13182        document.addEventListener('click', proxyLinkHandler, true);
13183    }
13184
13185    var LEGACY_PFB_SELECTOR_PATH = '/new_static/pfb-selector.js';
13186    function getCurrentBundleScriptSrc() {
13187        var _a;
13188        if (typeof document === 'undefined') {
13189            return '';
13190        }
13191        var currentScript = document.currentScript;
13192        var currentScriptSrc = (currentScript === null || currentScript === void 0 ? void 0 : currentScript.getAttribute('src')) || (currentScript === null || currentScript === void 0 ? void 0 : currentScript.src);
13193        if (currentScriptSrc) {
13194            return currentScriptSrc;
13195        }
13196        var scripts = Array.from(((_a = document.getElementsByTagName) === null || _a === void 0 ? void 0 : _a.call(
13196document, 'script')) || []);
13197        var bundleScript = scripts.reverse().find(function (script) {
13198            var src = script.getAttribute('src') || script.src || '';
13199            return /(?:index|detail)-bundle(?:\.[^.\/]+)?\.js(?:[?#].*)?$/.test(src);
13200        });
13201        return (bundleScript === null || bundleScript === void 0 ? void 0 : bundleScript.getAttribute('src')) || (bundleScript === null || bundleScript === void 0 ? void 0 : bundleScript.src) || '';
13202    }
13203    var getPfbSelectorScriptSrc = function (bundleScriptSrc) {
13204        if (!bundleScriptSrc) {
13205            return LEGACY_PFB_SELECTOR_PATH;
13206        }
13207        var cleanSrc = bundleScriptSrc.split('#')[0].split('?')[0];
13208        var lastSlashIndex = cleanSrc.lastIndexOf('/');
13209        if (lastSlashIndex < 0) {
13210            return LEGACY_PFB_SELECTOR_PATH;
13211        }
13212        return "".concat(cleanSrc.slice(0, lastSlashIndex + 1), "pfb-selector.js");
13213    };
13214    var currentBundleScriptSrc = getCurrentBundleScriptSrc();
13215    /**
13216     * Conditionally load PFB selector for mobile devices in test/uat environments
13217     * Uses script tag injection to load a separate bundle that calls renderPfbSelector
13218     */
13219    var loadPfbSelector = function () {
13220        // Only load in browser environments
13221        if (typeof window === 'undefined') {
13222            return;
13223        }
13224        // Check conditions
13225        var shouldLoad = isMobile() && (ENV === 'uat');
13226        if (!shouldLoad) {
13227            return;
13228        }
13229        try {
13230            console.log('Loading PFB selector for mobile device in', ENV, 'environment');
13231            // Check if already loaded
13232            if (document.querySelector('script[data-pfb-selector]')) {
13233                console.log('PFB selector already loaded');
13234                return;
13235            }
13236            // Create script element to load PFB selector
13237            var script = document.createElement('script');
13238            script.setAttribute('data-pfb-selector', 'true');
13239            script.type = 'text/javascript';
13240            // Load the separate pfb-selector bundle
13241            script.src = getPfbSelectorScriptSrc(currentBundleScriptSrc);
13242            script.onload = function () {
13243                console.log('PFB selector script loaded successfully');
13244            };
13245            script.onerror = function (error) {
13246                console.warn('Failed to load PFB selector script:', error);
13247            };
13248            document.head.appendChild(script);
13249        }
13250        catch (error) {
13251            console.warn('Failed to load PFB selector:', error);
13252        }
13253    };
13254    // Initialize when DOM is ready
13255    if (typeof window !== 'undefined') {
13256        if (document.readyState === 'loading') {
13257            document.addEventListener('DOMContentLoaded', loadPfbSelector);
13258        }
13259        else {
13260            // DOM is already ready
13261            loadPfbSelector();
13262        }
13263    }
13264
13265    /**
13266     * 作用范围:同构模块
13267     */
13268    var TemplateAction = /** @class */ (function () {
13269        function TemplateAction(options) {
13270            options.beforeInit && pageGlobalEvent.subscribe(options.beforeInit, 'before-init');
13271            options.rendered && pageGlobalEvent.subscribe(options.rendered, 'template-rendered');
13272            options.pageFinish && pageGlobalEvent.subscribe(options.pageFinish, 'page-finish');
13273        }
13274        return TemplateAction;
13275    }());
13276
13277    // 更新tab下方长条位置
13278    function updateIndicator$1(tab, indicator) {
13279        var tabLeft = tab.offsetLeft;
13280        var tabWidth = tab.offsetWidth;
13281        var indicatorWidth = window.innerWidth < 768 ? 24 : 40;
13282        var centerOffset = tabLeft + tabWidth / 2 - indicatorWidth / 2;
13283        indicator.style.transform = "translateX(".concat(centerOffset, "px)");
13284    }
13285    // 滚动tab到中间位置
13286    function scrollIntoViewIfNeeded$1(tab, tabContainer) {
13287        var container = tabContainer;
13288        var containerWidth = container.offsetWidth;
13289        var tabCenter = tab.offsetLeft + tab.offsetWidth / 2;
13290        var targetScroll = tabCenter - containerWidth / 2;
13291        container.scrollTo({
13292            left: Math.max(0, targetScroll),
13293            behavior: 'smooth'
13294        });
13295    }
13296    // 检查tab是否溢出控制是居中显示还是靠左
13297    function checkTabOverflow$1(tabList, tabContainer) {
13298        var isOverflowing = tabList.scrollWidth > tabContainer.offsetWidth;
13299        tabContainer.classList.toggle('scrollable', isOverflowing);
13300    }
13301    // 共同处理tab和step的点击()为了处理resize,所以点击某一种时同步更新另一种的状态
13302    function handleAllClick(steps, tabs, index, indicator, tabContainer, content) {
13303        var _a, _b, _c;
13304        // 处理Step
13305        (_a = document.querySelector('.clickable-steps__step.clickable-steps__step--active')) === null || _a === void 0 ? void 0 : _a.classList.remove('clickable-steps__step--active');
13306        steps[index].classList.add('clickable-steps__step--active');
13307        // 处理tab
13308        (_b = document.querySelector('.clickable-steps__nav-item.clickable-steps__nav-item--active')) === null || _b === void 0 ? void 0 : _b.classList.remove('clickable-steps__nav-item--active');
13309        tabs[index].classList.add('clickable-steps__nav-item--active');
13310        updateIndicator$1(tabs[index], indicator);
13311        scrollIntoViewIfNeeded$1(tabs[index], tabContainer);
13312        // 处理content
13313        (_c = document.querySelector('.clickable-steps__item.clickable-steps__item--active')) === null || _c === void 0 ? void 0 : _c.classList.remove('clickable-steps__item--active');
13314        content[index].classList.add('clickable-steps__item--active');
13315    }
13316    // 初始化tabs
13317    function initTabs$1(tabContainer, tabList, indicator, content) {
13318        var activeTab = document.querySelector('.clickable-steps__nav-item.clickable-steps__nav-item--active');
13319        checkTabOverflow$1(tabList, tabContainer);
13320        if (activeTab)
13321            updateIndicator$1(activeTab, indicator);
13322    }
13323    new TemplateAction({
13324        rendered: function () {
13325            var tabContainer = document.querySelector('.clickable-steps__nav');
13326            var tabList = document.querySelector('.clickable-steps__nav-list');
13327            var indicator = document.querySelector('.clickable-steps__indicator');
13328            var tabs = document.querySelectorAll('.clickable-steps__nav-item');
13329            var content = document.querySelectorAll('.clickable-steps__item');
13330            var steps = document.querySelectorAll('.clickable-steps__step');
13331            tabs.forEach(function (tab, index) {
13332                tab.addEventListener('click', function () { return handleAllClick(steps, tabs, index, indicator, tabContainer, content); });
13333            });
13334            steps.forEach(function (step, index) {
13335                step.addEventListener('click', function () { return handleAllClick(steps, tabs, index, indicator, tabContainer, content); });
13336            });
13337            initTabs$1(tabContainer, tabList, indicator);
13338            window.addEventListener('resize', function () {
13339                var activeTab = document.querySelector('.clickable-steps__nav-item.clickable-steps__nav-item--active');
13340                if (activeTab)
13341                    updateIndicator$1(activeTab, indicator);
13342                checkTabOverflow$1(tabList, tabContainer);
13343            });
13344        }
13345    });
13346
13347    /*
13348      用于初始化html块的样式(富文本编辑器)
13349      此方法仅用于初始化子元素中仅有div标签的元素
13350      请传入放置html片段的dom节点
13351    */
13352    function initHtmlFragmentStyle(rootElement) {
13353        var firstLevelChildren = Array.from(rootElement.children[0].children[0].children);
13354        var isFirstDiv = true;
13355        firstLevelChildren.forEach(function (child) {
13356            // 如果 child 的任意后代中存在 <br>,隐藏它
13357            if (child.querySelector('br')) {
13358                child.style.display = 'none';
13359                return; // 跳过这个元素,继续下一个
13360            }
13361            else if (isFirstDiv) {
13362                isFirstDiv = false;
13363                // 第一个非br的div不显示margin-top
13364                child.style.setProperty('margin-top', '0px', 'important');
13365            }
13366        });
13367    }
13368
13369    new TemplateAction({
13370        rendered: function () {
13371            var descElement = document.querySelector('.intro-photo__desc');
13372            initHtmlFragmentStyle(descElement);
13373        }
13374    });
13375
13376    // 调整所有tab content高度一致(仅当tab content内容左右排列时)
13377    function adjustTabContentHeight(content, panes) {
13378        content.style.height = '';
13379        if (window.innerWidth < 900) {
13380            return;
13381        }
13382        var maxHeight = Number(window.getComputedStyle(content).minHeight.slice(0, -2));
13383        panes.forEach(function (pane) {
13384            var originalDisplay = pane.style.display;
13385            pane.style.display = 'flex';
13386            var height = pane.clientHeight;
13387            pane.style.display = originalDisplay;
13388            if (height > maxHeight) {
13389                maxHeight = height;
13390            }
13391        });
13392        content.style.height = maxHeight + 'px';
13393    }
13394    // 更新tab下方长条位置
13395    function updateIndicator(tab, indicator) {
13396        var tabLeft = tab.offsetLeft;
13397        var tabWidth = tab.offsetWidth;
13398        var indicatorWidth = window.innerWidth < 768 ? 24 : 40;
13399        var centerOffset = tabLeft + tabWidth / 2 - indicatorWidth / 2;
13400        indicator.style.transform = "translateX(".concat(centerOffset, "px)");
13401    }
13402    // 滚动tab到中间位置
13403    function scrollIntoViewIfNeeded(tab, tabContainer) {
13404        var container = tabContainer;
13405        var containerWidth = container.offsetWidth;
13406        var tabCenter = tab.offsetLeft + tab.offsetWidth / 2;
13407        var targetScroll = tabCenter - containerWidth / 2;
13408        container.scrollTo({
13409            left: Math.max(0, targetScroll),
13410            behavior: 'smooth'
13411        });
13412    }
13413    // 检查tab是否溢出控制是居中显示还是靠左
13414    function checkTabOverflow(tabList, tabContainer) {
13415        var isOverflowing = tabList.scrollWidth > tabContainer.offsetWidth;
13416        tabContainer.classList.toggle('scrollable', isOverflowing);
13417    }
13418    // 处理tab点击事件
13419    function handleTabClick(tab, panes, index, indicator, tabContainer) {
13420        var _a, _b;
13421        (_a = document.querySelector('.intro-tabs__item.intro-tabs__item--active')) === null || _a === void 0 ? void 0 : _a.classList.remove('intro-tabs__item--active');
13422        tab.classList.add('intro-tabs__item--active');
13423        (_b = document.querySelector('.intro-tabs__panel.intro-tabs__panel--active')) === null || _b === void 0 ? void 0 : _b.classList.remove('intro-tabs__panel--active');
13424        panes[index].classList.add('intro-tabs__panel--active');
13425        updateIndicator(tab, indicator);
13426        scrollIntoViewIfNeeded(tab, tabContainer);
13427    }
13428    // 初始化tabs
13429    function initTabs(tabContainer, tabList, indicator, panes, content) {
13430        var activeTab = document.querySelector('.intro-tabs__item.intro-tabs__item--active');
13431        checkTabOverflow(tabList, tabContainer);
13432        adjustTabContentHeight(content, panes);
13433        if (activeTab)
13434            updateIndicator(activeTab, indicator);
13435    }
13436    new TemplateAction({
13437        rendered: function () {
13438            var tabContainer = document.querySelector('.intro-tabs__nav');
13439            var tabList = document.querySelector('.intro-tabs__list');
13440            var indicator = document.querySelector('.intro-tabs__indicator');
13441            var tabs = document.querySelectorAll('.intro-tabs__item');
13442            var panes = document.querySelectorAll('.intro-tabs__panel');
13443            var content = document.querySelector('.intro-tabs__content');
13444            tabs.forEach(function (tab, index) {
13445                tab.addEventListener('click', function () { return handleTabClick(tab, panes, index, indicator, tabContainer); });
13446            });
13447            initTabs(tabContainer, tabList, indicator, panes, content);
13448            window.addEventListener('resize', function () {
13449                var activeTab = document.querySelector('.intro-tabs__item.intro-tabs__item--active');
13450                if (activeTab)
13451                    updateIndicator(activeTab, indicator);
13452                checkTabOverflow(tabList, tabContainer);
13453                adjustTabContentHeight(content, panes);
13454            });
13455        }
13456    });
13457
13458    // 页面尺寸在768 - 1039时,如果文字上下间距 <24px,由左右排列改为上下排列
13459    function initContent(contentList, itemList, introNoTabs) {
13460        introNoTabs.classList.remove('column-for-tablets');
13461        contentList.forEach(function (content) {
13462            var contentMarginTop = Number(window.getComputedStyle(content).marginTop.slice(0, -2));
13463            if (window.innerWidth >= 768 && window.innerWidth < 1040 && contentMarginTop < 24) {
13464                introNoTabs.classList.add('column-for-tablets');
13465            }
13466        });
13467    }
13468    new TemplateAction({
13469        rendered: function () {
13470            var contentList = document.querySelectorAll('.intro-no-tabs__content');
13471            var itemList = document.querySelectorAll('.intro-no-tabs__item');
13472            var introNoTabs = document.querySelector('.intro-no-tabs');
13473            initContent(contentList, itemList, introNoTabs);
13474            window.addEventListener('resize', function () {
13475                initContent(contentList, itemList, introNoTabs);
13476            });
13477        }
13478    });
13479
13480    // 格式化视频时间
13481    var formatTime = function (sec) {
13482        var h = Math.floor(sec / 3600);
13483        var m = Math.floor((sec % 3600) / 60);
13484        var s = Math.floor(sec % 60);
13485        return (h > 0 ? h + ':' : '') + m + ':' + (s < 10 ? '0' + s : s);
13486    };
13487    // 初始化时间显示(显示总时长,当前时间为0)
13488    var initTimeDisplay = function (video, timeDisplay) {
13489        if (video.duration && !isNaN(video.duration)) {
13490            timeDisplay.textContent = "0:00 / ".concat(formatTime(video.duration));
13491        }
13492    };
13493    // 判断鼠标是否不在容器内
13494    var judgeNotInContainer = function (e, container) {
13495        var inContainer = container.getBoundingClientRect();
13496        return e.clientX < inContainer.left || e.clientX > inContainer.right ||
13497            e.clientY < inContainer.top || e.clientY > inContainer.bottom;
13498    };
13499    // 切换图标显示(传入图标需要显示的状态)
13500    function toggleIcon(container, status) {
13501        if (!container || container.children.length < 2)
13502            return;
13503        var first = container.children[0];
13504        var second = container.children[1];
13505        if (status === 'pause' || status === 'voiceOff' || status === 'fullScreen') {
13506            first.style.display = '';
13507            second.style.display = 'none';
13508        }
13509        else {
13510            first.style.display = 'none';
13511            second.style.display = '';
13512        }
13513    }
13514    function initControls(controls) {
13515        controls.classList.add('init-show-controls');
13516        setTimeout(function () {
13517            controls.classList.remove('init-show-controls');
13518        }, 3000);
13519    }
13520    // 移动端显示控制栏控制(无点击后3s消失)
13521    var showControlsForMobile = function (controls, hideControlsTimeout) {
13522        controls.classList.add('show-controls');
13523        if (hideControlsTimeout) {
13524            clearTimeout(hideControlsTimeout);
13525        }
13526        return setTimeout(function () {
13527            controls.classList.remove('show-controls');
13528        }, 3000);
13529    };
13530    // 视频播放更新进度条UI(优化版 - 拖动时不更新)
13531    var timeUpdate = function (video, progress, progressThumb, timeDisplay, playBtn, dragManager) {
13532        // 如果正在拖动,不更新进度条UI,避免与用户操作冲突
13533        if (dragManager.state.isDragging) {
13534            return;
13535        }
13536        if (video.duration && !isNaN(video.duration)) {
13537            var percent = (video.currentTime / video.duration) * 100;
13538            progress.style.width = percent + '%';
13539            progressThumb.style.left = percent + '%';
13540            timeDisplay.textContent = "".concat(formatTime(video.currentTime), " / ").concat(formatTime(video.duration));
13541            if (percent === 100) {
13542                toggleIcon(playBtn, 'pause');
13543            }
13544        }
13545    };
13546    // 按钮控制视频播放与停止
13547    var playVideo = function (video, playBtn) {
13548        toggleIcon(playBtn, video.paused ? 'play' : 'pause');
13549        if (video.paused) {
13550            video.play();
13551        }
13552        else {
13553            video.pause();
13554        }
13555    };
13556    // 创建拖动状态管理器
13557    var createDragManager = function () {
13558        var state = {
13559            isDragging: false,
13560            targetTime: 0,
13561            animationId: null,
13562            wasPlaying: false,
13563            previewUpdateId: null
13564        };
13565        // 防抖函数用于预览更新
13566        var debounce = function (func, wait) {
13567            var timeout;
13568            return function executedFunction() {
13569                var args = [];
13570                for (var _i = 0; _i < arguments.length; _i++) {
13571                    args[_i] = arguments[_i];
13572                }
13573                var later = function () {
13574                    clearTimeout(timeout);
13575                    func.apply(void 0, args);
13576                };
13577                clearTimeout(timeout);
13578                timeout = setTimeout(later, wait);
13579            };
13580        };
13581        // 流畅更新UI的函数
13582        var updateUI = function (percent, progress, progressThumb, timeDisplay, targetTime, videoDuration) {
13583            if (state.animationId) {
13584                cancelAnimationFrame(state.animationId);
13585            }
13586            state.animationId = requestAnimationFrame(function () {
13587                progress.style.width = percent + '%';
13588                progressThumb.style.left = percent + '%';
13589                timeDisplay.textContent = "".concat(formatTime(targetTime), " / ").concat(formatTime(videoDuration));
13590            });
13591        };
13592        // 预览更新函数(防抖处理)
13593        var previewUpdate = debounce(function (video, targetTime) {
13594            if (state.isDragging && Math.abs(video.currentTime - targetTime) > 0.1) {
13595                video.currentTime = targetTime;
13596            }
13597        }, 100); // 100ms防抖,减少跳转频率
13598        return { state: state, updateUI: updateUI, previewUpdate: previewUpdate };
13599    };
13600    // 视频进度条跳转指定位置(优化版)
13601    var seek = function (e, video, progressBar, progress, progressThumb, timeDisplay, dragManager) {
13602        var rect = progressBar.getBoundingClientRect();
13603        var ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
13604        if (video.duration && !isNaN(video.duration)) {
13605            var targetTime = ratio * video.duration;
13606            var percent = ratio * 100;
13607            // 立即更新UI,提供流畅的视觉反馈
13608            dragManager.updateUI(percent, progress, progressThumb, timeDisplay, targetTime, video.duration);
13609            // 存储目标时间
13610            dragManager.state.targetTime = targetTime;
13611            // 如果正在拖动,使用防抖预览更新
13612            if (dragManager.state.isDragging) {
13613                dragManager.previewUpdate(video, targetTime);
13614            }
13615            else {
13616                // 非拖动状态直接跳转(比如点击进度条)
13617                video.currentTime = targetTime;
13618                // 临时设置拖动状态,防止 timeupdate 立即覆盖UI
13619                dragManager.state.isDragging = true;
13620                setTimeout(function () {
13621                    dragManager.state.isDragging = false;
13622                }, 100);
13623            }
13624        }
13625    };
13626    // 处理PC和移动端视频进度条点击(优化版)
13627    var processClickDown = function (e, video, progressBar, progress, progressThumb, controls, playBtn, timeDisplay, dragManager) {
13628        // 记录是否正在播放
13629        dragManager.state.wasPlaying = !video.paused;
13630        // 暂停视频但不立即更新按钮状态
13631        if (!video.paused) {
13632            video.pause();
13633        }
13634        dragManager.state.isDragging = true;
13635        progressThumb.classList.add('dragging');
13636        controls.classList.add('show-controls');
13637        document.body.style.cursor = 'pointer';
13638        // 立即处理第一次位置更新
13639        seek(e, video, progressBar, progress, progressThumb, timeDisplay, dragManager);
13640        return true;
13641    };
13642    // 处理PC和移动端视频进度条点击结束(优化版)
13643    var processClickUp = function (video, playBtn, dragManager) {
13644        if (!dragManager.state.isDragging)
13645            return false;
13646        var targetTime = dragManager.state.targetTime;
13647        // 清理动画帧
13648        if (dragManager.state.animationId) {
13649            cancelAnimationFrame(dragManager.state.animationId);
13650            dragManager.state.animationId = null;
13651        }
13652        // 最终设置视频时间
13653        if (targetTime !== undefined) {
13654            video.currentTime = targetTime;
13655        }
13656        document.body.style.cursor = 'default';
13657        // 延迟结束拖动状态,给视频跳转留出时间
13658        // 这样可以防止 timeupdate 事件立即覆盖用户设置的进度条位置
13659        setTimeout(function () {
13660            dragManager.state.isDragging = false;
13661            // 恢复播放状态
13662            if (dragManager.state.wasPlaying) {
13663                video.play().then(function () {
13664                    toggleIcon(playBtn, 'play');
13665                }).catch(function () {
13666                    toggleIcon(playBtn, 'pause');
13667                });
13668            }
13669            else {
13670                toggleIcon(playBtn, 'pause');
13671            }
13672        }, 100); // 100ms延迟,足够视频处理跳转请求
13673        return false;
13674    };
13675    // 更新音频进度条样式
13676    var updateVolumeBar = function (ratio, volumeLevel, volumeThumb) {
13677        volumeLevel.style.width = (ratio * 100) + '%';
13678        volumeThumb.style.left = (ratio * 100) + '%';
13679    };
13680    // 更新音频(支持PC和移动端)
13681    var updateVolume = function (e, video, volumeBar, volumeLevel, volumeThumb, muteBtn) {
13682        var rect = volumeBar.getBoundingClientRect();
13683        var ratio = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width));
13684        video.volume = ratio;
13685        if (ratio === 0 && !video.muted) {
13686            toggleIcon(muteBtn, 'voiceOff');
13687        }
13688        else if (ratio !== 0 && video.muted) {
13689            toggleIcon(muteBtn, 'voiceOn');
13690        }
13691        video.muted = ratio === 0;
13692        updateVolumeBar(ratio, volumeLevel, volumeThumb);
13693        return ratio;
13694    };
13695    // 音量进度条拖动开始处理(PC和移动端通用)
13696    var processVolumeClickDown = function (e, video, volumeBar, volumeLevel, volumeThumb, muteBtn, controls) {
13697        var newVolume = updateVolume(e, video, volumeBar, volumeLevel, volumeThumb, muteBtn);
13698        volumeBar.classList.add('dragging');
13699        controls.classList.add('show-controls');
13700        document.body.style.cursor = 'pointer';
13701        // 确保拖动时音量进度条可见
13702        volumeBar.style.display = 'block';
13703        return newVolume;
13704    };
13705    // 音量进度条拖动结束处理
13706    var processVolumeClickUp = function (volumeBar) {
13707        document.body.style.cursor = 'default';
13708        // 拖动结束后,对于触摸设备,延迟隐藏音量进度条
13709        var isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
13710        if (isTouchDevice && window.innerWidth >= 768) {
13711            setTimeout(function () {
13712                volumeBar.style.display = '';
13713            }, 2000); // 2秒后隐藏
13714        }
13715        return false;
13716    };
13717    // 静音按钮点击
13718    var volumeIconClick = function (video, muteBtn, lastVolume, volumeLevel, volumeThumb) {
13719        toggleIcon(muteBtn, video.muted ? 'voiceOn' : 'voiceOff');
13720        video.muted = !video.muted;
13721        if (window.innerWidth < 768) {
13722            var ratio = video.muted ? 0 : 1;
13723            updateVolumeBar(ratio, volumeLevel, volumeThumb);
13724            video.volume = ratio;
13725        }
13726        else {
13727            var ratio = video.muted ? 0 : lastVolume;
13728            updateVolumeBar(ratio, volumeLevel, volumeThumb);
13729            video.volume = ratio;
13730        }
13731    };
13732    // 全屏按钮点击
13733    var fullScreenClick = function (videoContainer, fullScreenBtn) {
13734        var isFullscreen = !!(document.fullscreenElement ||
13735            (document === null || document === void 0 ? void 0 : document.webkitFullscreenElement) || // Safari
13736            (document === null || document === void 0 ? void 0 : document.msFullscreenElement) // IE11
13737        );
13738        if (!isFullscreen) {
13739            if (videoContainer.requestFullscreen) {
13740                videoContainer.requestFullscreen();
13741            }
13742            else if (videoContainer === null || videoContainer === void 0 ? void 0 : videoContainer.webkitRequestFullscreen) { // Safari
13743                videoContainer === null || videoContainer === void 0 ? void 0 : videoContainer.msRequestFullscreen();
13744            }
13745            else if (videoContainer === null || videoContainer === void 0 ? void 0 : videoContainer.msRequestFullScreen) { // IE/Edge 老版本
13746                videoContainer === null || videoContainer === void 0 ? void 0 : videoContainer.msRequestFullScreen();
13747            }
13748        }
13749        else {
13750            if (document.exitFullscreen) {
13751                document.exitFullscreen();
13752            }
13753            else if (document === null || document === void 0 ? void 0 : document.webkitExitFullscreen) { // Safari
13754                document === null || document === void 0 ? void 0 : document.webkitExitFullscreen();
13755            }
13756            else if (document === null || document === void 0 ? void 0 : document.mosExitFullScreen) { // IE/Edge 老版本
13757                document === null || document === void 0 ? void 0 : document.mosExitFullScreen();
13758            }
13759        }
13760    };
13761    // 更新全屏按钮图片
13762    var updateFullscreenIcon = function (fullScreenBtns) {
13763        fullScreenBtns.forEach(function (fullScreenBtn) {
13764            var isFullscreen = !!(document.fullscreenElement ||
13765                (document === null || document === void 0 ? void 0 : document.webkitFullscreenElement) || // Safari
13766                (document === null || document === void 0 ? void 0 : document.msFullscreenElement) // IE11
13767            );
13768            console.log(isFullscreen);
13769            toggleIcon(fullScreenBtn, isFullscreen ? 'exitFullScreen' : 'fullScreen');
13770        });
13771    };
13772    // 检查视频是否已经加载完成(处理缓存情况)
13773    var isVideoReady = function (video) {
13774        return video.readyState >= HTMLMediaElement.HAVE_METADATA;
13775    };
13776    // 安全地尝试播放视频
13777    var safeVideoPlay = function (video_1, playBtn_1) {
13778        var args_1 = [];
13779        for (var _i = 2; _i < arguments.length; _i++) {
13780            args_1[_i - 2] = arguments[_i];
13781        }
13782        return __awaiter$7(void 0, __spreadArray$2([video_1, playBtn_1], args_1, true), void 0, function (video, playBtn, retryCount) {
13783            var error_1;
13784            if (retryCount === void 0) { retryCount = 0; }
13785            return __generator$7(this, function (_a) {
13786                switch (_a.label) {
13787                    case 0:
13788                        _a.trys.push([0, 2, , 3]);
13789                        return [4 /*yield*/, video.play()];
13790                    case 1:
13791                        _a.sent();
13792                        toggleIcon(playBtn, 'play');
13793                        return [2 /*return*/, true];
13794                    case 2:
13795                        error_1 = _a.sent();
13796                        console.warn('Video play failed:', error_1);
13797                        if (retryCount < 2) {
13798                            // 等待一小段时间后重试
13799                            setTimeout(function () { return safeVideoPlay(video, playBtn, retryCount + 1); }, 100);
13800                        }
13801                        return [2 /*return*/, false];
13802                    case 3: return [2 /*return*/];
13803                }
13804            });
13805        });
13806    };
13807    // 初始化视频自动播放观察器
13808    var initVideoAutoPlay = function (video, playBtn, controls) {
13809        var setupObserver = function () {
13810            var observer = new IntersectionObserver(function (entries) {
13811                entries.forEach(function (entry) {
13812                    if (entry.isIntersecting && entry.intersectionRatio === 1) {
13813                        safeVideoPlay(video, playBtn);
13814                        observer.unobserve(video); // 播放一次后取消观察
13815                        initControls(controls);
13816                    }
13817                });
13818            }, {
13819                threshold: 1.0
13820            });
13821            observer.observe(video);
13822        };
13823        // 如果视频已经准备好,立即设置观察器
13824        if (isVideoReady(video)) {
13825            setupObserver();
13826        }
13827        else {
13828            // 否则等待视频准备好
13829            var handleReady_1 = function () {
13830                setupObserver();
13831                video.removeEventListener('loadedmetadata', handleReady_1);
13832                video.removeEventListener('loadeddata', handleReady_1);
13833            };
13834            video.addEventListener('loadedmetadata', handleReady_1);
13835            video.addEventListener('loadeddata', handleReady_1);
13836        }
13837    };
13838    // 视频开始加载
13839    var videoStartLoading = function (videoLoading, status) {
13840        videoLoading.style.display = 'flex';
13841        videoLoading.style.backgroundColor = status === 'playing' ? '#000000CC' : '#000000';
13842    };
13843    // 视频停止加载
13844    var videoStopLoading = function (videoLoading) {
13845        videoLoading.style.display = 'none';
13846        videoLoading.style.backgroundColor = '';
13847    };
13848    // 视频重试
13849    var videoRetry = function (video, mobileRetryContainer, pcRetryContainer, controls, videoLoading) {
13850        mobileRetryContainer.style.display = "none";
13851        pcRetryContainer.style.display = "none";
13852        controls.classList.remove('video-error');
13853        videoStartLoading(videoLoading, 'init');
13854        // 监听视频加载完成事件,加载成功后再播放
13855        var handleLoadedData = function () {
13856            videoStopLoading(videoLoading);
13857            video.play().catch(function (error) {
13858                videoStopLoading(videoLoading);
13859                if (window.innerWidth < 768) {
13860                    mobileRetryContainer.style.display = "flex";
13861                }
13862                else {
13863                    pcRetryContainer.style.display = "flex";
13864                }
13865            });
13866            // 移除事件监听器,避免重复绑定
13867            video.removeEventListener('loadeddata', handleLoadedData);
13868        };
13869        video.addEventListener('loadeddata', handleLoadedData);
13870        video.load();
13871    };
13872    new TemplateAction({
13873        rendered: function () {
13874            var video = document.querySelector('.main-introduction-with-video-video'); //视频
13875            var videoSource = document.querySelector('.main-introduction-with-video-video source'); //视频源
13876            var playBtn = document.querySelector('.video-control-info-play'); //播放按钮
13877            var muteBtn = document.querySelector('.video-control-info-voice-play'); //静音按钮
13878            var progressBar = document.querySelector('.video-process'); //进度条
13879            var progress = document.querySelector('.video-process-current'); //进度条当前位置
13880            var progressThumb = document.querySelector('.video-process-thumb'); //进度条小球当前位置
13881            var volumeBar = document.querySelector('.video-control-info-voice-process'); //音量条
13882            var volumeLevel = document.querySelector('.video-control-info-voice-process-current'); //音量条当前位置
13883            var volumeThumb = document.querySelector('.video-control-info-voice-process-thumb'); //音量条小球当前位置
13884            var timeDisplay = document.querySelector('.video-control-info-time'); //时间
13885            var controls = document.querySelector('.main-introduction-with-video__video-control'); //控制栏
13886            var vedioContainer = document.querySelector('.main-introduction-with-video__video'); //视频容器
13887            var fullScreenBtns = document.querySelectorAll('.video-control-fullScreen'); //全屏按钮
13888            var videoLoading = document.querySelector('.video-loading'); //视频加载中
13889            var pcRetryContainer = document.querySelector('.video-retry-pc'); //PC重试按钮
13890            var pcRetryText = document.querySelector('.video-retry-pc-text-click'); //PC重试按钮文本
13891            var mobileRetryContainer = document.querySelector('.video-retry-mobile'); //移动端重试按钮
13892            var textDesc = document.querySelector('.main-introduction-with-video__desc-text'); //文字描述
13893            var isVedioDragging = false; //视频是否正在拖拽
13894            var draggingVolume = false; //音量条是否正在拖拽
13895            var lastVolume = 0; //音量条最后位置
13896            var hideControlsTimeout; //控制栏隐藏定时器
13897            // 初始化拖动状态管理器
13898            var dragManager = createDragManager();
13899            // 初始化音量进度条显示(移动端和PC端通用)
13900            if (volumeBar && volumeLevel && volumeThumb) {
13901                var initialVolume = video.volume || 1;
13902                updateVolumeBar(initialVolume, volumeLevel, volumeThumb);
13903                lastVolume = initialVolume;
13904                // 为触摸设备显示音量进度条(iPad等设备)
13905                var isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
13906                if (isTouchDevice && window.innerWidth >= 768) {
13907                    // 在触摸设备上,音量区域被点击时显示音量进度条
13908                    var voiceContainer = document.querySelector('.video-control-info-voice');
13909                    if (voiceContainer) {
13910                        voiceContainer.addEventListener('touchstart', function () {
13911                            volumeBar.style.display = 'block';
13912                            // 3秒后自动隐藏
13913                            setTimeout(function () {
13914                                if (!draggingVolume) {
13915                                    volumeBar.style.display = '';
13916                                }
13917                            }, 3000);
13918                        });
13919                    }
13920                }
13921            }
13922            initHtmlFragmentStyle(textDesc);
13923            fullScreenBtns === null || fullScreenBtns === void 0 ? void 0 : fullScreenBtns.forEach(function (item) { return item.addEventListener('click', function () {
13924                fullScreenClick(vedioContainer);
13925                if (window.innerWidth < 768) {
13926                    hideControlsTimeout = showControlsForMobile(control
13926s, hideControlsTimeout);
13927                }
13928            }); });
13929            // 全屏状态更新
13930            document.addEventListener('fullscreenchange', function () {
13931                updateFullscreenIcon(fullScreenBtns);
13932            });
13933            // 全屏状态更新-Safari浏览器
13934            document.addEventListener('webkitfullscreenchange', function () {
13935                updateFullscreenIcon(fullScreenBtns);
13936            });
13937            // 全屏状态更新-IE11浏览器
13938            document.addEventListener('MSFullscreenChange', function () {
13939                updateFullscreenIcon(fullScreenBtns);
13940            });
13941            // 视频事件监听优化
13942            // 视频元数据加载完成(包括缓存情况)
13943            video.addEventListener("loadedmetadata", function () {
13944                videoStopLoading(videoLoading);
13945                initTimeDisplay(video, timeDisplay);
13946            });
13947            // 视频初始化加载完成
13948            video.addEventListener("loadeddata", function () {
13949                videoStopLoading(videoLoading);
13950                // 确保时间显示已初始化(防止loadedmetadata未触发的情况)
13951                if (timeDisplay.textContent === '0:00 / 0:00') {
13952                    initTimeDisplay(video, timeDisplay);
13953                }
13954            });
13955            // 视频可以开始播放
13956            video.addEventListener("canplay", function () {
13957                videoStopLoading(videoLoading);
13958                // 最后确保时间显示已初始化
13959                if (timeDisplay.textContent === '0:00 / 0:00') {
13960                    initTimeDisplay(video, timeDisplay);
13961                }
13962            });
13963            // 缓冲开始
13964            video.addEventListener("waiting", function () {
13965                videoStartLoading(videoLoading, 'playing');
13966            });
13967            // 缓冲完成
13968            video.addEventListener("playing", function () {
13969                videoStopLoading(videoLoading);
13970            });
13971            // // 出错处理
13972            videoSource.addEventListener("error", function () {
13973                controls.classList.add('video-error');
13974                videoStopLoading(videoLoading);
13975                if (window.innerWidth < 768) {
13976                    mobileRetryContainer.style.display = "flex";
13977                }
13978                else {
13979                    pcRetryContainer.style.display = "flex";
13980                }
13981            });
13982            // PC端重试按钮点击
13983            pcRetryText.addEventListener('click', function () {
13984                videoRetry(video, mobileRetryContainer, pcRetryContainer, controls, videoLoading);
13985            });
13986            // 移动端重试按钮点击
13987            mobileRetryContainer.addEventListener('click', function () {
13988                videoRetry(video, mobileRetryContainer, pcRetryContainer, controls, videoLoading);
13989            });
13990            // 视频自动播放逻辑
13991            if (video) {
13992                // 监听时间更新
13993                video.addEventListener('timeupdate', function () {
13994                    timeUpdate(video, progress, progressThumb, timeDisplay, playBtn, dragManager);
13995                });
13996                // 初始化自动播放
13997                initVideoAutoPlay(video, playBtn, controls);
13998            }
13999            // 播放按钮点击
14000            playBtn === null || playBtn === void 0 ? void 0 : playBtn.addEventListener('click', function () {
14001                playVideo(video, playBtn);
14002                if (window.innerWidth < 768) {
14003                    hideControlsTimeout = showControlsForMobile(controls, hideControlsTimeout);
14004                }
14005            });
14006            // 静音按钮点击
14007            muteBtn === null || muteBtn === void 0 ? void 0 : muteBtn.addEventListener('click', function () {
14008                volumeIconClick(video, muteBtn, lastVolume, volumeLevel, volumeThumb);
14009                if (window.innerWidth < 768) {
14010                    hideControlsTimeout = showControlsForMobile(controls, hideControlsTimeout);
14011                }
14012            });
14013            // PC端特殊交互绑定
14014            // 视频进度条PC点击
14015            progressBar.addEventListener('mousedown', function (e) {
14016                isVedioDragging = processClickDown(e, video, progressBar, progress, progressThumb, controls, playBtn, timeDisplay, dragManager);
14017            });
14018            // 音量进度条PC点击
14019            volumeBar.addEventListener('mousedown', function (e) {
14020                lastVolume = processVolumeClickDown(e, video, volumeBar, volumeLevel, volumeThumb, muteBtn, controls);
14021                draggingVolume = true;
14022            });
14023            // 视频进度条和音量进度条PC移动
14024            document.addEventListener('mousemove', function (e) {
14025                if (isVedioDragging) {
14026                    // 使用优化后的拖动逻辑,无需手动节流
14027                    seek(e, video, progressBar, progress, progressThumb, timeDisplay, dragManager);
14028                }
14029                if (draggingVolume) {
14030                    lastVolume = updateVolume(e, video, volumeBar, volumeLevel, volumeThumb, muteBtn);
14031                }
14032                if (!isVedioDragging && !draggingVolume) {
14033                    if (judgeNotInContainer(e, video)) {
14034                        controls.classList.remove('show-controls');
14035                    }
14036                    if (judgeNotInContainer(e, progressBar)) {
14037                        progressThumb.classList.remove('dragging');
14038                    }
14039                    if (judgeNotInContainer(e, volumeBar)) {
14040                        volumeBar.classList.remove('dragging');
14041                    }
14042                }
14043            });
14044            // 视频进度条和音量进度条PC点击结束
14045            document.addEventListener('mouseup', function () {
14046                if (isVedioDragging) {
14047                    isVedioDragging = processClickUp(video, playBtn, dragManager);
14048                }
14049                if (draggingVolume) {
14050                    draggingVolume = processVolumeClickUp(volumeBar);
14051                    volumeBar.classList.remove('dragging');
14052                }
14053            });
14054            // 移动端特殊交互绑定(包括音量进度条)
14055            // 视频进度条移动端点击
14056            progressBar.addEventListener('touchstart', function (e) {
14057                isVedioDragging = processClickDown(e.touches[0], video, progressBar, progress, progressThumb, controls, playBtn, timeDisplay, dragManager);
14058                hideControlsTimeout = showControlsForMobile(controls, hideControlsTimeout);
14059            });
14060            // 音量进度条移动端点击(iPad等设备支持)
14061            if (volumeBar) {
14062                volumeBar.addEventListener('touchstart', function (e) {
14063                    e.preventDefault(); // 防止页面滚动
14064                    lastVolume = processVolumeClickDown(e.touches[0], video, volumeBar, volumeLevel, volumeThumb, muteBtn, controls);
14065                    draggingVolume = true;
14066                    hideControlsTimeout = showControlsForMobile(controls, hideControlsTimeout);
14067                });
14068            }
14069            // 视频进度条和音量进度条移动端移动
14070            document.addEventListener('touchmove', function (e) {
14071                if (isVedioDragging) {
14072                    // 使用优化后的拖动逻辑,无需手动节流
14073                    seek(e.touches[0], video, progressBar, progress, progressThumb, timeDisplay, dragManager);
14074                    hideControlsTimeout = showControlsForMobile(controls, hideControlsTimeout);
14075                }
14076                if (draggingVolume) {
14077                    e.preventDefault(); // 防止页面滚动
14078                    lastVolume = updateVolume(e.touches[0], video, volumeBar, volumeLevel, volumeThumb, muteBtn);
14079                    hideControlsTimeout = showControlsForMobile(controls, hideControlsTimeout);
14080                }
14081            });
14082            // 视频进度条和音量进度条移动端点击结束
14083            document.addEventListener('touchend', function () {
14084                if (isVedioDragging) {
14085                    isVedioDragging = processClickUp(video, playBtn, dragManager);
14086                }
14087                if (draggingVolume) {
14088                    draggingVolume = processVolumeClickUp(volumeBar);
14089                    if (volumeBar) {
14090                        volumeBar.classList.remove('dragging');
14091                    }
14092                }
14093            });
14094            // 移动端视频点击控制栏展示与隐藏
14095            video.addEventListener('click', function (e) {
14096                if (window.innerWidth < 768) {
14097                    e.stopPropagation();
14098                    if (!controls.classList.contains('show-controls')) {
14099                        hideControlsTimeout = showControlsForMobile(controls, hideControlsTimeout);
14100                    }
14101                    else {
14102                        controls.classList.remove('show-controls');
14103                    }
14104                }
14105            });
14106            // 移动端点击控制栏以外部分隐藏控制栏
14107            document.addEventListener('click', function (e) {
14108                if (!controls.contains(e.target) && controls.classList.contains('show-controls') && window.innerWidth < 768) {
14109                    controls.classList.remove('show-controls');
14110                }
14111            });
14112            // 屏幕尺寸变化时调整error div
14113            window.addEventListener('resize', function () {
14114                if (window.innerWidth < 768 && pcRetryContainer.style.display === "flex") {
14115                    pcRetryContainer.style.display = "none";
14116                    mobileRetryContainer.style.display = "flex";
14117                }
14118                else if (window.innerWidth >= 768 && mobileRetryContainer.style.display === "flex") {
14119                    pcRetryContainer.style.display = "flex";
14120                    mobileRetryContainer.style.display = "none";
14121                }
14122            });
14123        }
14124    });
14125
14126    // Check if browser supports :has() selector
14127    function supportsHasSelector() {
14128        try {
14129            return CSS.supports('selector(:has(div))');
14130        }
14131        catch (_a) {
14132            return false;
14133        }
14134    }
14135    // Lightweight fallback for browsers without :has() support
14136    function processChildrenFallback(rootElement) {
14137        if (supportsHasSelector()) {
14138            // Modern browsers: CSS handles everything
14139            return;
14140        }
14141        // Fallback for older browsers
14142        var firstLevelChildren = Array.from(rootElement.children);
14143        var isFirstDiv = true;
14144        firstLevelChildren.forEach(function (child) {
14145            var element = child;
14146            // Set margin-top: 0 for first element
14147            if (isFirstDiv && ['DIV', 'UL', 'OL', 'FIGURE'].includes(element.tagName)) {
14148                element.classList.add('js-first-element');
14149            }
14150            isFirstDiv = false;
14151            // Handle image containers
14152            if (element.querySelector('img')) {
14153                // Add class to current element and traverse up to set container styles
14154                var current = element;
14155                while (current) {
14156                    current.classList.add('js-img-container');
14157                    if (current === rootElement)
14158                        break;
14159                    current = current.parentElement;
14160                }
14161            }
14162        });
14163    }
14164    new TemplateAction({
14165        rendered: function () {
14166            var _a;
14167            var pureText = document.querySelector('.pure-text__content');
14168            if ((_a = pureText === null || pureText === void 0 ? void 0 : pureText.children[0]) === null || _a === void 0 ? void 0 : _a.children[0]) {
14169                processChildrenFallback(pureText.children[0].children[0]);
14170            }
14171        }
14172    });
14173
14174    var _a$1;
14175    var isBrowser = typeof window !== 'undefined' && typeof window.navigator !== 'undefined';
14176    // define navigator for compatibility
14177    var customNavigator = isBrowser ? window.navigator : { userAgent: '' };
14178    var userAgentStr = isBrowser ? (((_a$1 = navigator.userAgent) === null || _a$1 === void 0 ? void 0 : _a$1.toLowerCase()) || '') : '';
14179    var isMobileWeb = isBrowser ? /mobile/i.test(userAgentStr) : false;
14180    var isNativeAPP = userAgentStr.includes('spx-express');
14181    isNativeAPP && userAgentStr.includes('iphone');
14182    isNativeAPP && userAgentStr.includes('android');
14183    var isHeadlessUA = userAgentStr.includes('headless');
14184
14185    function loadUserInfoAsync() {
14186        if (getRegion() !== 'TW' &&
14187            !window.location.pathname.includes('dev-login-redirect')) {
14188            try {
14189                return fetch('/shipment/account/api/base_info/detail', {
14190                    headers: __assign$3({}, (isCtl ? { 'X-source': PARTNER_ID } : {}))
14191                })
14192                    .then(function (res) { return res.json(); })
14193                    .then(function (data) {
14194                    var userInfo = data === null || data === void 0 ? void 0 : data.data;
14195                    if (userInfo) {
14196                        window.__NSS_CONTEXT__.userInfo = userInfo;
14197                        sessionStorage.setItem('nss_user_info', JSON.stringify(userInfo));
14198                        setTrackingUserId(userInfo.account_id);
14199                    }
14200                    else {
14201                        sessionStorage.removeItem('nss_user_info');
14202                    }
14203                })
14204                    .catch(function (e) {
14205                    sessionStorage.removeItem('nss_user_info');
14206                });
14207            }
14208            catch (e) { }
14209        }
14210    }
14211    loadUserInfoAsync();
14212    var uuid = function () {
14213        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
14214            var r = (Math.random() * 16) | 0;
14215            var v = c === 'x' ? r : (r & 0x3) | 0x8;
14216            return v.toString(16);
14217        });
14218    };
14219    var getUserId = function () {
14220        var userInfo = sessionStorage.getItem('nss_user_info');
14221        if (userInfo) {
14222            try {
14223                return "".concat(JSON.parse(userInfo).account_id);
14224            }
14225            catch (e) {
14226                return '';
14227            }
14228        }
14229        return '';
14230    };
14231    // 和旧官网保持一致
14232    var SESSION_ID_KEY = 'ssc_reporter_sessionId';
14233    var DEVICE_ID_KEY = 'ssc_reporter_deviceId';
14234    var RELATED_DEVICE_ID_KEY = '+_)(*3&^'; // 250815 ~ 250821 之间用的错误的Device ID,一个月后可以下掉
14235    var REFERRER_ID_KEY = 'ssc_reporter_referrer';
14236    var getSessionId = function () {
14237        var sessionId = sessionStorage.getItem(SESSION_ID_KEY);
14238        if (sessionId) {
14239            return sessionId;
14240        }
14241        var newSessionId = uuid();
14242        sessionStorage.setItem(SESSION_ID_KEY, newSessionId);
14243        return newSessionId;
14244    };
14245    var getDeviceId = function () {
14246        var deviceId = localStorage.getItem(DEVICE_ID_KEY);
14247        if (deviceId) {
14248            return deviceId;
14249        }
14250        var newDeviceId = uuid();
14251        localStorage.setItem(DEVICE_ID_KEY, newDeviceId);
14252        return newDeviceId;
14253    };
14254    var getRelatedDeviceId = function () {
14255        var deviceId = localStorage.getItem(RELATED_DEVICE_ID_KEY);
14256        if (deviceId) {
14257            return deviceId;
14258        }
14259        var newDeviceId = uuid();
14260        localStorage.setItem(RELATED_DEVICE_ID_KEY, newDeviceId);
14261        return newDeviceId;
14262    };
14263    var getReferrer = function () {
14264        var referrer = sessionStorage.getItem(REFERRER_ID_KEY);
14265        if (referrer) {
14266            return referrer;
14267        }
14268        var newReferrer = document.referrer || '';
14269        sessionStorage.setItem(REFERRER_ID_KEY, newReferrer);
14270        return newReferrer;
14271    };
14272    var SEARCH_PARAMS_NAMES_FOR_REPORT = ['referrer_trigger_type'];
14273    var getSearchParams = function () {
14274        try {
14275            if (!window.location.search)
14276                return {};
14277            var urlParams = new URLSearchParams(window.location.search);
14278            var allParams = Object.fromEntries(urlParams.entries());
14279            return Object.fromEntries(Object.entries(allParams).filter(function (_a) {
14280                var key = _a[0];
14281                return SEARCH_PARAMS_NAMES_FOR_REPORT.includes(key);
14282            }));
14283        }
14284        catch (error) {
14285            return {};
14286        }
14287    };
14288    var app_version = {"NODE_ENV":"development","APP_VERSION":"v20260929-1220-MY-LIVE","env":"live","PARTNER_ID":"shopee"}.APP_VERSION;
14289    /**
14290     * Get the page initialization time
14291     */
14292    var getPageInitTime = function () {
14293        var _a, _b;
14294        return (_b = (_a = window.__NSS_CONTEXT__) === null || _a === void 0 ? void 0 : _a.pageInitTime) !== null && _b !== void 0 ? _b : null;
14295    };
14296    /**
14297     * Report custom LCP time based on banner image load
14298     * @param imageLoadTime The time when the first banner image loaded (performance.now())
14299     * @param imageUrl The URL of the loaded image
14300     * @param bannerId Optional banner ID for tracking
14301     * @param additionalTimingData Optional additional timing data (duration, fetch times, etc.)
14302     */
14303    var reportCustomLCP = function (imageLoadTime, imageUrl, bannerId, additionalTimingData) {
14304        var initTime = getPageInitTime();
14305        var lcpReportData = __assign$3({ type: 'nss_banner_lcp', lcp_time: imageLoadTime, page_init_time: Math.round(initTime || 0), image_url: imageUrl, banner_id: bannerId }, additionalTimingData);
14306        // Report to analytics
14307        reportToES('nss_custom_lcp', lcpReportData);
14308    };
14309    /**
14310     * Track when an image starts loading by storing the start time
14311     * Call this right before setting the image src
14312     */
14313    window.trackImageLoadStart = function (bannerId) {
14314        var startTime = performance.now();
14315        // Store in a global map for later retrieval
14316        if (!window.__imageLoadStartTimes) {
14317            window.__imageLoadStartTimes = new Map();
14318        }
14319        window.__imageLoadStartTimes.set(bannerId, startTime);
14320        return startTime;
14321    };
14322    /**
14323     * Get the stored start time for an image
14324     */
14325    window.getImageLoadStartTime = function (bannerId) {
14326        var _a;
14327        return ((_a = window.__imageLoadStartTimes) === null || _a === void 0 ? void 0 : _a.get(bannerId)) || null;
14328    };
14329    window.reportBannerLCP = function (img, loadTime, loadResult) {
14330        var bannerId = img.dataset.bannerId ? parseInt(img.dataset.bannerId) : undefined;
14331        var slideIndex = img.dataset.slide ? parseInt(img.dataset.slide) : undefined;
14332        var isFirstImage = slideIndex === 0;
14333        var imageUrl = img.currentSrc || img.src;
14334        // Get image loading timing from Resource Timing API
14335        var getImageLoadingDuration = function () {
14336            var _a;
14337            try {
14338                // Get the resource timing entry for this image
14339                var resourceEntries = performance.getEntriesByName(imageUrl, 'resource');
14340                var latestEntry = resourceEntries[resourceEntries.length - 1]; // Get the most recent entry
14341                if (latestEntry) {
14342                    return {
14343                        startTime: Math.round(latestEntry.fetchStart),
14344                        duration: Math.round(latestEntry.responseEnd - latestEntry.fetchStart),
14345                        fetchStart: Math.round(latestEntry.fetchStart),
14346                        responseEnd: Math.round(latestEntry.responseEnd)
14347                    };
14348                }
14349            }
14350            catch (error) {
14351                console.warn('Failed to get resource timing for image:', error);
14352            }
14353            // Fallback: use manual tracking or dataset or estimate
14354            var manualStartTime = (_a = window.getImageLoadStartTime) === null || _a === void 0 ? void 0 : _a.call(window, img.dataset.bannerId || '');
14355            var datasetStartTime = img.dataset.loadStartTime ? parseFloat(img.dataset.loadStartTime) : null;
14356            var startTime = manualStartTime || datasetStartTime || (loadTime - 100); // Rough estimate if no start time
14357            return {
14358                startTime: Math.round(startTime),
14359                duration: Math.round(loadTime - startTime)
14360            };
14361        };
14362        var timingData = getImageLoadingDuration();
14363        var timeSource = timingData.fetchStart ? 'resource_timing_api' : 'fallback';
14364        // Report LCP immediately for the first image
14365        if (isFirstImage) {
14366            reportCustomLCP(loadTime, imageUrl, bannerId, {
14367                image_duration: timingData.duration,
14368                load_start_time: timingData.startTime,
14369                timing_source: timeSource,
14370                load_result: loadResult,
14371                slide_index: slideIndex,
14372            });
14373        }
14374        // Report detailed image loading metrics
14375        reportToES(NSS_BANNER_REPORT_KEY, {
14376            type: 'image_loading_time',
14377            banner_id: bannerId,
14378            duration: timingData.duration,
14379            load_start_time: timingData.startTime,
14380            fetch_start: timingData.fetchStart,
14381            response_end: timingData.responseEnd,
14382            image_url: imageUrl,
14383            loading_method: img.dataset.loadingMethod,
14384            slide_index: slideIndex,
14385            timing_source: timeSource,
14386            load_result: loadResult,
14387        });
14388    };
14389    /**
14390     * 上报的基础数据
14391     */
14392    var basicData = {
14393        bt: 'SLS',
14394        sbt: 'NSS',
14395        env: ENV,
14396        // ut: 'normal',
14397        sid: getDeviceId(),
14398        a: getRegion(),
14399        pf: isMobileWeb ? 'm' : 'pc',
14400        dt: 'count',
14401        // nt: customNavigator.connection?.effectiveType || 'unknown',
14402        r: 1,
14403        s: window.location.href,
14404        did: getRelatedDeviceId(),
14405        // V2 代表新官网
14406        v: "V2-".concat(app_version),
14407        tag: {
14408            _sessionId: getSessionId(),
14409            _ua: customNavigator.userAgent || '',
14410        },
14411    };
14412    var reportAPI = "https://autobahn.ssc.shopeemobile.com/data/";
14413    /**
14414     * 上报数据到ES
14415     * @param key 上报的key
14416     * @param data 上报的数据
14417     */
14418    var reportToES = function (key, data, useBeacon) {
14419        var _a;
14420        if (useBeacon === void 0) { useBeacon = true; }
14421        var visitType = 'valid_visit';
14422        var reportData = __assign$3(__assign$3({}, basicData), { uid: getUserId(), ct: Math.floor(Date.now() / 1000), d: {
14423                key: key,
14424                type: data.type,
14425                data: __assign$3(__assign$3(__assign$3({ visit_type: visitType, href: window.location.href, pathname: window.location.pathname, referrer: getReferrer(), prevPath: document.referrer, lang: checkCurrentLanguage() }, data), getSearchParams()), ({})),
14426            } });
14427        // 判断是否正常请求
14428        var validStrValueRule = /^([\w-.]+)+$/;
14429        var validUrlRule = /^https?:\/\/([.\w]+)(\/)?([#\w/?=&%-.]+)?/;
14430        var referrer = reportData.d.data.referrer, v = reportData.v, sid = reportData.sid, pf = reportData.pf, s = reportData.s, dt = reportData.dt;
14431        var isValidStr = [v, sid, pf, key, dt,].every(function (v) { return validStrValueRule.test(v); });
14432        var isValidUrl = [s, referrer].every(function (v) { return validUrlRule.test(v) || !v; });
14433        if (isHeadlessUA) {
14434            reportData.d.data.visit_type = 'crawl_visit';
14435        }
14436        if (!isValidStr || !isValidUrl) {
14437            reportData.d.data.visit_type = 'xss_visit';
14438        }
14439        if (useBeacon) {
14440            var blob = new Blob([JSON.stringify(reportData)], { type: 'application/json' });
14441            (_a = customNavigator.sendBeacon) === null || _a === void 0 ? void 0 : _a.call(customNavigator, reportAPI, blob);
14442            return;
14443        }
14444        fetch(reportAPI, {
14445            method: 'POST',
14446            headers: {
14447                'Content-Type': 'application/json',
14448                'Accept': 'application/json',
14449            },
14450            body: JSON.stringify(reportData),
14451        }).catch(function (error) {
14452            console.error('Report failed:', error);
14453        });
14454    };
14455
14456    new TemplateAction({
14457        rendered: function () {
14458            initBanner(undefined, {
14459                reportHandler: function (data) {
14460                    reportToES(NSS_BANNER_REPORT_KEY, data);
14461                }
14462            });
14463        }
14464    });
14465
14466    var _a;
14467    var LOCALSTORAGE_COOKIE_MODAL = 'hideCookieModalTag'; // 存储用户首次访问时的 cookie 弹窗提示状态
14468    var LOCALSTORAGE_COOKIES_SETTING = 'open-spx-cookiesTypeList'; // 存储用户cookie setting
14469    // 判断是否展示cookie弹窗
14470    var isShowCookieModal = function () { return __awaiter$7(void 0, void 0, void 0, function () {
14471        var previewId;
14472        return __generator$7(this, function (_a) {
14473            switch (_a.label) {
14474                case 0:
14475                    previewId = getPreviewId();
14476                    if (previewId) {
14477                        return [2 /*return*/, true];
14478                    }
14479                    return [4 /*yield*/, storage.asyncGetItem(LOCALSTORAGE_COOKIE_MODAL)];
14480                case 1: return [2 /*return*/, (_a.sent()) !== '1'];
14481            }
14482        });
14483    }); };
14484    // 设置关闭cookie弹窗
14485    var setHideCookieModalTag = function () {
14486        storage.setItem(LOCALSTORAGE_COOKIE_MODAL, '1');
14487    };
14488    var CookieType;
14489    (function (CookieType) {
14490        CookieType["necessary"] = "necessary";
14491        CookieType["performance"] = "performance";
14492        CookieType["targeting"] = "targeting";
14493        CookieType["functionality"] = "functionality";
14494        CookieType["socialMedia"] = "socialMedia";
14495    })(CookieType || (CookieType = {}));
14496    // cookie配置项关联的cookie中的key,关闭对应的配置项后,需要移除关联的cookie key
14497    var cookieMap = (_a = {},
14498        _a[CookieType.performance] = ['_ga', '_gid', 'scfe_sid'],
14499        _a[CookieType.functionality] = ['spx_first_login_flag', 'fms_language'],
14500        _a[CookieType.socialMedia] = ['ssc_skey', 'ssc_user_email', 'login_google_auth_redirect'],
14501        _a);
14502    function saveCookieSetting(data) {
14503        return fetchPost('/shipment/account/api/cookie_setting/add', data);
14504    }
14505    function saveCookieSettingToServe(list) {
14506        var data = {
14507            performance_cookie: Number(list.includes(CookieType.performance)),
14508            targeting_cookie: Number(list.includes(CookieType.targeting)),
14509            functionality_cookie: Number(list.includes(CookieType.functionality)),
14510            social_media_cookie: Number(list.includes(CookieType.socialMedia))
14511        };
14512        return saveCookieSetting(data);
14513    }
14514    var changeGtagConfig = function (list) {
14515        var mode = list.includes(CookieType.performance) ? 'granted' : 'denied';
14516        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
14517        // @ts-ignore  pc逻辑,应该是谷歌分析的
14518        window.gtag && window.gtag('consent', 'update', {
14519            ad_storage: mode,
14520            analytics_storage: mode
14521        });
14522    };
14523    var clearUnacceptedCookie = function (list) {
14524        Object.keys(cookieMap).forEach(function (item) {
14525            if (!list.includes(item)) {
14526                cookieMap[item].forEach(function (key) {
14527                    api.remove(key);
14528                });
14529            }
14530        });
14531    };
14532    var handleCookieRuleChange = function (list) {
14533        if (list === void 0) { list = []; }
14534        storage.setItem(LOCALSTORAGE_COOKIES_SETTING, JSON.stringify(list));
14535        saveCookieSettingToServe(list);
14536        changeGtagConfig(list);
14537        clearUnacceptedCookie(list);
14538        setHideCookieModalTag();
14539    };
14540    var acceptAllCookie = function () {
14541        handleCookieRuleChange([
14542            CookieType.performance,
14543            CookieType.targeting,
14544            CookieType.functionality,
14545            CookieType.socialMedia,
14546            CookieType.necessary
14547        ]);
14548    };
14549    var rejectAllCookie = function () {
14550        handleCookieRuleChange([CookieType.necessary]);
14551    };
14552    var COOKIE_MODAL_ID = 'nss-cookie-modal';
14553    var closeCookieModal = function () {
14554        var modal = document.getElementById(COOKIE_MODAL_ID);
14555        if (modal) {
14556            modal.style.display = 'none';
14557        }
14558    };
14559    var onCookieModalClose = function () {
14560        rejectAllCookie();
14561        closeCookieModal();
14562    };
14563    var onCookieModalAccept = function () {
14564        acceptAllCookie();
14565        closeCookieModal();
14566    };
14567    var onCookieModalSetting = function () {
14568        // Rich-todo: 跳转cookie setting页面. 本地新官网移动端还会有/m/吗
14569        window.location.href = isMobile() ? '/m/cookie?tab=setting' : '/cookies-preference/setting';
14570        closeCookieModal();
14571    };
14572    var initCookieModal = function () { return __awaiter$7(void 0, void 0, void 0, function () {
14573        var isShow, modal;
14574        return __generator$7(this, function (_a) {
14575            switch (_a.label) {
14576                case 0: return [4 /*yield*/, isShowCookieModal()];
14577                case 1:
14578                    isShow = _a.sent();
14579                    if (isShow) {
14580                        modal = document.getElementById(COOKIE_MODAL_ID);
14581                        if (modal) {
14582                            modal.style.display = 'block';
14583                            modal.addEventListener('click', function (e) {
14584                                var _a;
14585                                var target = e.target;
14586                                var targetId = target.id || ((_a = target.closest('[id]')) === null || _a === void 0 ? void 0 : _a.id) || '';
14587                                if (targetId === 'nss-cookie-close') {
14588                                    onCookieModalClose();
14589                                }
14590                                else if (targetId === 'nss-cookie-setting') {
14591                                    onCookieModalSetting();
14592                                }
14593                                else if (targetId === 'nss-cookie-accept-all') {
14594                                    onCookieModalAccept();
14595                                }
14596                            });
14597                        }
14598                    }
14599                    return [2 /*return*/];
14600            }
14601        });
14602    }); };
14603    new TemplateAction({
14604        rendered: function () {
14605            initCookieModal();
14606        }
14607    });
14608
14609    var login = function () {
14610        window.location.href = getPortalLoginUrl();
14611    };
14612    var logout = function () {
14613        fetchGet('/shipment/account/api/logout').then(function () {
14614            sessionStorage.removeItem('nss_user_info');
14615            window.location.reload();
14616        });
14617    };
14618    var switchLanguage = function (event) {
14619        event.preventDefault();
14620        var target = event.target.closest('.dropdown__item');
14621        if (!target) {
14622            return;
14623        }
14624        var lang = target.dataset.lang;
14625        if (!lang) {
14626            return;
14627        }
14628        setCacheLanguage(lang);
14629        api.set(LANGUAGE_COOKIE_KEY, lang);
14630        var pathname = window.location.pathname;
14631        var searchParams = window.location.search;
14632        // if the pathname is /<lang>/<secondary-path>
14633        // then redirect to /<new-lang>/<secondary-path>
14634        if (isDetailPage(pathname)) {
14635            var pathnameArr = pathname.split('/');
14636            pathnameArr[1] = convertLangForUrl(lang);
14637            window.location.href = pathnameArr.join('/') + searchParams;
14638            return;
14639        }
14640        window.location.href = "/".concat(convertLangForUrl(lang)).concat(searchParams);
14641    };
14642    var toggleMobileMenu = function () {
14643        var mainMenu = document.querySelector('.nss-main-menu-v2');
14644        if (mainMenu) {
14645            mainMenu.classList.toggle('main-menu--mobile-open');
14646            document.body.style.overflow = mainMenu.classList.contains('main-menu--mobile-open') ? 'hidden' : '';
14647        }
14648    };
14649    var toggleSubmenu = function (event) {
14650        var element = event.target.closest('.main-menu__mobile-trigger');
14651        if (!element) {
14652            return;
14653        }
14654        var menuItem = element.closest('.main-menu__mobile-item--expandable');
14655        if (menuItem) {
14656            var isExpanded = menuItem.classList.contains('main-menu__mobile-item--expanded');
14657            // Close all other expanded submenus
14658            var allExpanded = document.querySelectorAll('.main-menu__mobile-item--expanded');
14659            allExpanded.forEach(function (item) {
14660                if (item !== menuItem) {
14661                    item.classList.remove('main-menu__mobile-item--expanded');
14662                }
14663            });
14664            // Toggle current submenu
14665            if (isExpanded) {
14666                menuItem.classList.remove('main-menu__mobile-item--expanded');
14667            }
14668            else {
14669                menuItem.classList.add('main-menu__mobile-item--expanded');
14670            }
14671        }
14672    };
14673    // 用于静态化后的页面,更新登录信息 以及 userInfo 加载太慢的兜底处理
14674    var updateLoginInfo = function () { return __awaiter$7(void 0, void 0, void 0, function () {
14675        var loginBtn, userInfo, text, loginInfo, loginInfoWrapper;
14676        return __generator$7(this, function (_a) {
14677            switch (_a.label) {
14678                case 0:
14679                    loginBtn = document.getElementById('nss-login-btn');
14680                    return [4 /*yield*/, getUserInfo()
14681                        // 有login btn 说明要显示登录信息且没获取到userInfo
14682                    ];
14683                case 1:
14684                    userInfo = _a.sent();
14685                    // 有login btn 说明要显示登录信息且没获取到userInfo
14686                    if (loginBtn && (userInfo === null || userInfo === void 0 ? void 0 : userInfo.account_id)) {
14687                        text = formatAccountInfo(userInfo === null || userInfo === void 0 ? void 0 : userInfo.email, 'email') || formatAccountInfo(userInfo === null || userInfo === void 0 ? void 0 : userInfo.phone_number, 'phone') || '';
14688                        loginInfo = document.getElementById('nss-login-info');
14689                        if (loginInfo) {
14690                            loginInfo.textContent = text;
14691                            loginInfoWrapper = document.getElementById('nss-login-info-wrapper');
14692                            loginInfoWrapper === null || loginInfoWrapper === void 0 ? void 0 : loginInfoWrapper.classList.remove('main-menu__hide-login-info');
14693                            loginBtn.classList.add('main-menu__hide-login-info');
14694                        }
14695                    }
14696                    return [2 /*return*/];
14697            }
14698        });
14699    }); };
14700    new TemplateAction({
14701        rendered: function () {
14702            var loginBtn = document.getElementById('login');
14703            var logoutBtn = document.getElementById('logout');
14704            var myPortalBtn = document.getElementById('my-portal');
14705            var switchLanguageBtn = document.querySelectorAll('#switch-language .dropdown__item');
14706            var mainMenuMobileList = document.querySelectorAll('#main-menu-mobile-list .main-menu__mobile-trigger');
14707            var toggleMobileMenuBtn = document.querySelectorAll('.toggle-mobile-menu');
14708            loginBtn === null || loginBtn === void 0 ? void 0 : loginBtn.addEventListener('click', login);
14709            logoutBtn === null || logoutBtn === void 0 ? void 0 : logoutBtn.addEventListener('click', logout);
14710            myPortalBtn === null || myPortalBtn === void 0 ? void 0 : myPortalBtn.addEventListener('click', partnerUrlManager.goToMyPortal);
14711            switchLanguageBtn === null || switchLanguageBtn === void 0 ? void 0 : switchLanguageBtn.forEac
14711h(function (item) { return item.addEventListener('click', switchLanguage); });
14712            mainMenuMobileList === null || mainMenuMobileList === void 0 ? void 0 : mainMenuMobileList.forEach(function (item) { return item.addEventListener('click', toggleSubmenu); });
14713            toggleMobileMenuBtn === null || toggleMobileMenuBtn === void 0 ? void 0 : toggleMobileMenuBtn.forEach(function (item) { return item.addEventListener('click', toggleMobileMenu); });
14714            updateLoginInfo();
14715            applyQRToImage('nss-qr-code');
14716            hideMassCreateInMobile();
14717        }
14718    });
14719
14720    // 本地存储键名
14721    var STORAGE_KEYS = {
14722        CLOSE_COUNT: 'mobile_download_bar_close_count',
14723        LAST_CLOSE_TIME: 'mobile_download_bar_last_close_time',
14724        PERMANENTLY_HIDDEN: 'mobile_download_bar_permanently_hidden'
14725    };
14726    var CONFIG = {
14727        MAX_CLOSE_COUNT: 3, // 最大关闭次数
14728        SHOW_INTERVAL_DAYS: 7, // 重新显示间隔天数
14729        DEEPLINK_TIMEOUT: 1000, // Deeplink超时时间
14730    };
14731    var MobileDownloadBarManager = /** @class */ (function () {
14732        function MobileDownloadBarManager(downloadAppConfig) {
14733            this.downloadApp = downloadAppConfig;
14734        }
14735        // 检查是否应该显示下载条
14736        MobileDownloadBarManager.prototype.shouldShowDownloadBar = function () {
14737            var _a, _b, _c;
14738            // 检查是否在移动端
14739            if (!isMobile()) {
14740                return false;
14741            }
14742            // 检查是否已经在APP内
14743            if (isNativeAPP) {
14744                return false;
14745            }
14746            // 检查是否配置了下载链接
14747            if (!((_a = this.downloadApp) === null || _a === void 0 ? void 0 : _a.deep_link) && !((_b = this.downloadApp) === null || _b === void 0 ? void 0 : _b.apple_store_link) && !((_c = this.downloadApp) === null || _c === void 0 ? void 0 : _c.google_store_link)) {
14748                return false;
14749            }
14750            // 检查是否已永久隐藏
14751            var permanentlyHidden = storage.getItem(STORAGE_KEYS.PERMANENTLY_HIDDEN);
14752            if (permanentlyHidden === 'true') {
14753                return false;
14754            }
14755            // 检查关闭次数和时间间隔
14756            var closeCount = parseInt(storage.getItem(STORAGE_KEYS.CLOSE_COUNT) || '0');
14757            var lastCloseTime = parseInt(storage.getItem(STORAGE_KEYS.LAST_CLOSE_TIME) || '0');
14758            // 如果关闭次数达到上限,永久隐藏
14759            if (closeCount >= CONFIG.MAX_CLOSE_COUNT) {
14760                storage.setItem(STORAGE_KEYS.PERMANENTLY_HIDDEN, 'true');
14761                return false;
14762            }
14763            // 如果有关闭记录,检查是否满足时间间隔
14764            if (lastCloseTime > 0) {
14765                var daysSinceLastClose = (Date.now() - lastCloseTime) / (1000 * 60 * 60 * 24);
14766                if (daysSinceLastClose < CONFIG.SHOW_INTERVAL_DAYS) {
14767                    return false;
14768                }
14769            }
14770            return true;
14771        };
14772        // 检测是否已安装APP
14773        MobileDownloadBarManager.prototype.detectAppInstalled = function () {
14774            var _this = this;
14775            return new Promise(function (resolve) {
14776                var _a;
14777                if (!((_a = _this.downloadApp) === null || _a === void 0 ? void 0 : _a.deep_link)) {
14778                    resolve(false);
14779                    return;
14780                }
14781                var startTime = Date.now();
14782                var iframe = document.createElement('iframe');
14783                iframe.style.display = 'none';
14784                iframe.src = _this.downloadApp.deep_link;
14785                document.body.appendChild(iframe);
14786                // 设置超时检测
14787                var timer = setTimeout(function () {
14788                    document.body.removeChild(iframe);
14789                    // 如果在超时时间内没有切换到APP,认为未安装
14790                    var timeDiff = Date.now() - startTime;
14791                    resolve(timeDiff < CONFIG.DEEPLINK_TIMEOUT);
14792                }, CONFIG.DEEPLINK_TIMEOUT);
14793                // 监听页面可见性变化(用户切换到APP时页面会隐藏)
14794                var handleVisibilityChange = function () {
14795                    if (document.hidden) {
14796                        clearTimeout(timer);
14797                        document.removeEventListener('visibilitychange', handleVisibilityChange);
14798                        try {
14799                            document.body.removeChild(iframe);
14800                        }
14801                        catch (e) {
14802                            // iframe可能已被移除
14803                        }
14804                        resolve(true);
14805                    }
14806                };
14807                document.addEventListener('visibilitychange', handleVisibilityChange);
14808            });
14809        };
14810        // 处理下载按钮点击
14811        MobileDownloadBarManager.prototype.handleDownloadClick = function () {
14812            return __awaiter$7(this, void 0, void 0, function () {
14813                var appInstalled, error_1;
14814                var _this = this;
14815                var _a;
14816                return __generator$7(this, function (_b) {
14817                    switch (_b.label) {
14818                        case 0:
14819                            // 设置加载状态
14820                            this.setButtonLoading(true);
14821                            _b.label = 1;
14822                        case 1:
14823                            _b.trys.push([1, 4, 5, 6]);
14824                            reportToES('mobile_download_bar_click', {
14825                                type: 'download_button_click',
14826                            });
14827                            if (!((_a = this.downloadApp) === null || _a === void 0 ? void 0 : _a.deep_link)) return [3 /*break*/, 3];
14828                            return [4 /*yield*/, this.detectAppInstalled()];
14829                        case 2:
14830                            appInstalled = _b.sent();
14831                            if (appInstalled) {
14832                                // APP已安装,直接打开
14833                                reportToES('mobile_download_bar_app_opened', {
14834                                    type: 'app_opened',
14835                                });
14836                                return [2 /*return*/];
14837                            }
14838                            _b.label = 3;
14839                        case 3:
14840                            // APP未安装或没有deep_link,跳转到下载页面
14841                            this.redirectToDownloadPage();
14842                            return [3 /*break*/, 6];
14843                        case 4:
14844                            error_1 = _b.sent();
14845                            console.error('Download button click error:', error_1);
14846                            // 出错时也尝试跳转到下载页面
14847                            this.redirectToDownloadPage();
14848                            return [3 /*break*/, 6];
14849                        case 5:
14850                            setTimeout(function () {
14851                                _this.setButtonLoading(false);
14852                            }, 500);
14853                            return [7 /*endfinally*/];
14854                        case 6: return [2 /*return*/];
14855                    }
14856                });
14857            });
14858        };
14859        // 按钮加载状态
14860        MobileDownloadBarManager.prototype.setButtonLoading = function (loading) {
14861            var downloadBtn = document.getElementById('mobile-download-btn');
14862            if (!downloadBtn)
14863                return;
14864            if (loading) {
14865                downloadBtn.classList.add('loading');
14866                downloadBtn.disabled = true;
14867            }
14868            else {
14869                downloadBtn.classList.remove('loading');
14870                downloadBtn.disabled = false;
14871            }
14872        };
14873        // 跳转到下载页面
14874        MobileDownloadBarManager.prototype.redirectToDownloadPage = function () {
14875            var _a, _b, _c, _d;
14876            var userAgent = navigator.userAgent.toLowerCase();
14877            var downloadUrl = '';
14878            // 根据设备类型选择下载链接
14879            if (/iphone|ipad/.test(userAgent) && ((_a = this.downloadApp) === null || _a === void 0 ? void 0 : _a.apple_store_link)) {
14880                downloadUrl = this.downloadApp.apple_store_link;
14881            }
14882            else if (/android/.test(userAgent) && ((_b = this.downloadApp) === null || _b === void 0 ? void 0 : _b.google_store_link)) {
14883                downloadUrl = this.downloadApp.google_store_link;
14884            }
14885            else {
14886                // 默认使用第一个可用的链接
14887                downloadUrl = ((_c = this.downloadApp) === null || _c === void 0 ? void 0 : _c.apple_store_link) || ((_d = this.downloadApp) === null || _d === void 0 ? void 0 : _d.google_store_link) || '';
14888            }
14889            if (downloadUrl) {
14890                reportToES('mobile_download_bar_store_redirect', {
14891                    type: 'store_redirect',
14892                    store_type: downloadUrl.includes('apple') ? 'app_store' : 'google_play',
14893                });
14894                window.location.assign(downloadUrl);
14895            }
14896        };
14897        // 处理关闭按钮点击
14898        MobileDownloadBarManager.prototype.handleCloseClick = function () {
14899            var currentCloseCount = parseInt(storage.getItem(STORAGE_KEYS.CLOSE_COUNT) || '0');
14900            var newCloseCount = currentCloseCount + 1;
14901            // 更新关闭次数和时间
14902            storage.setItem(STORAGE_KEYS.CLOSE_COUNT, newCloseCount.toString());
14903            storage.setItem(STORAGE_KEYS.LAST_CLOSE_TIME, Date.now().toString());
14904            reportToES('mobile_download_bar_close', {
14905                type: 'close_button_click',
14906                close_count: newCloseCount,
14907            });
14908            // 如果达到最大关闭次数,永久隐藏
14909            if (newCloseCount >= CONFIG.MAX_CLOSE_COUNT) {
14910                storage.setItem(STORAGE_KEYS.PERMANENTLY_HIDDEN, 'true');
14911                reportToES('mobile_download_bar_permanently_hidden', {
14912                    type: 'permanently_hidden',
14913                });
14914            }
14915            this.hideDownloadBar();
14916        };
14917        // 显示下载条
14918        MobileDownloadBarManager.prototype.showDownloadBar = function () {
14919            var downloadBar = document.getElementById('mobile-download-bar');
14920            if (downloadBar) {
14921                downloadBar.style.display = 'block';
14922                setTimeout(function () {
14923                    downloadBar.classList.add('mobile-download-bar--visible');
14924                    document.body.classList.add('mobile-download-bar-visible');
14925                }, 10);
14926                reportToES('mobile_download_bar_show', {
14927                    type: 'download_bar_shown',
14928                });
14929            }
14930        };
14931        // 隐藏下载条
14932        MobileDownloadBarManager.prototype.hideDownloadBar = function () {
14933            var downloadBar = document.getElementById('mobile-download-bar');
14934            if (downloadBar) {
14935                downloadBar.classList.remove('mobile-download-bar--visible');
14936                document.body.classList.remove('mobile-download-bar-visible');
14937                // 动画完成后隐藏元素
14938                setTimeout(function () {
14939                    downloadBar.style.display = 'none';
14940                }, 300);
14941            }
14942        };
14943        // 初始化下载条
14944        MobileDownloadBarManager.prototype.init = function () {
14945            var _this = this;
14946            if (!this.shouldShowDownloadBar()) {
14947                return;
14948            }
14949            // 延迟显示,避免影响页面加载
14950            setTimeout(function () {
14951                _this.showDownloadBar();
14952            }, 1000);
14953            // 绑定事件监听器
14954            var downloadBtn = document.getElementById('mobile-download-btn');
14955            var closeBtn = document.getElementById('mobile-download-close');
14956            downloadBtn === null || downloadBtn === void 0 ? void 0 : downloadBtn.addEventListener('click', function (e) { return __awaiter$7(_this, void 0, void 0, function () {
14957                return __generator$7(this, function (_a) {
14958                    switch (_a.label) {
14959                        case 0:
14960                            e.preventDefault();
14961                            return [4 /*yield*/, this.handleDownloadClick()];
14962                        case 1:
14963                            _a.sent();
14964                            return [2 /*return*/];
14965                    }
14966                });
14967            }); });
14968            closeBtn === null || closeBtn === void 0 ? void 0 : closeBtn.addEventListener('click', function (e) {
14969                e.preventDefault();
14970                _this.handleCloseClick();
14971            });
14972        };
14973        return MobileDownloadBarManager;
14974    }());
14975    // 导出给模板使用
14976    new TemplateAction({
14977        rendered: function () {
14978            var _a;
14979            // 检查是否在浏览器环境中
14980            if (typeof window === 'undefined') {
14981                return;
14982            }
14983            // 从全局配置中获取下载链接配置
14984            var pageConfig = getGlobalData('pageConfig');
14985            var downloadAppConfig = (_a = pageConfig === null || pageConfig === void 0 ? void 0 : page
14985Config.menu) === null || _a === void 0 ? void 0 : _a.download_app;
14986            var manager = new MobileDownloadBarManager(downloadAppConfig);
14987            manager.init();
14988        }
14989    });
14990
14991    var Dragger = /** @class */ (function () {
14992        function Dragger(element, x, y, toggleCB) {
14993            this.element = element;
14994            this.isDragging = false;
14995            this.dragMoved = false;
14996            this.startX = 0;
14997            this.startY = 0;
14998            this.bindEvents();
14999            this.toggleCB = toggleCB;
15000            this.currentX = x;
15001            this.currentY = y;
15002            this.setPosition(this.currentX, this.currentY);
15003        }
15004        Dragger.prototype.bindEvents = function () {
15005            // 鼠标事件
15006            this.element.addEventListener('mousedown', this.handleMouseDown.bind(this));
15007            document.addEventListener('mousemove', this.handleMouseMove.bind(this));
15008            document.addEventListener('mouseup', this.handleMouseUp.bind(this));
15009            // 触摸事件
15010            this.element.addEventListener('touchstart', this.handleTouchStart.bind(this));
15011            document.addEventListener('touchmove', this.handleTouchMove.bind(this));
15012            document.addEventListener('touchend', this.handleTouchEnd.bind(this));
15013        };
15014        Dragger.prototype.handleMouseDown = function (e) {
15015            this.startDrag(e.clientX, e.clientY);
15016            e.preventDefault();
15017        };
15018        Dragger.prototype.handleMouseMove = function (e) {
15019            this.updateDrag(e.clientX, e.clientY);
15020        };
15021        Dragger.prototype.handleMouseUp = function () {
15022            this.endDrag();
15023        };
15024        Dragger.prototype.handleTouchStart = function (e) {
15025            var touch = e.touches[0];
15026            this.startDrag(touch.clientX, touch.clientY);
15027            e.preventDefault();
15028        };
15029        Dragger.prototype.handleTouchMove = function (e) {
15030            var touch = e.touches[0];
15031            this.updateDrag(touch.clientX, touch.clientY);
15032            e.preventDefault();
15033        };
15034        Dragger.prototype.handleTouchEnd = function () {
15035            this.endDrag();
15036        };
15037        Dragger.prototype.startDrag = function (clientX, clientY) {
15038            this.isDragging = true;
15039            this.dragMoved = false;
15040            this.startX = clientX - this.currentX;
15041            this.startY = clientY - this.currentY;
15042            this.element.classList.add('dragging');
15043        };
15044        Dragger.prototype.updateDrag = function (clientX, clientY) {
15045            if (!this.isDragging)
15046                return;
15047            var newX = clientX - this.startX;
15048            var newY = clientY - this.startY;
15049            // 检测是否有足够的移动距离
15050            var deltaX = Math.abs(newX - this.currentX);
15051            var deltaY = Math.abs(newY - this.currentY);
15052            if (deltaX > 5 || deltaY > 5) {
15053                this.dragMoved = true;
15054            }
15055            this.currentX = newX;
15056            this.currentY = newY;
15057            this.constrainPosition();
15058            this.setPosition(this.currentX, this.currentY);
15059        };
15060        Dragger.prototype.endDrag = function () {
15061            if (!this.isDragging)
15062                return;
15063            this.isDragging = false;
15064            this.element.classList.remove('dragging');
15065            // 如果没有拖拽,则执行切换
15066            if (!this.dragMoved) {
15067                this.toggle();
15068            }
15069            this.dragMoved = false;
15070        };
15071        Dragger.prototype.toggle = function () {
15072            var _a;
15073            (_a = this.toggleCB) === null || _a === void 0 ? void 0 : _a.call(this);
15074        };
15075        Dragger.prototype.constrainPosition = function () {
15076            var maxX = window.innerWidth - 50;
15077            var maxY = window.innerHeight - 50;
15078            this.currentX = Math.max(0, Math.min(this.currentX, maxX));
15079            this.currentY = Math.max(0, Math.min(this.currentY, maxY));
15080        };
15081        Dragger.prototype.setPosition = function (x, y) {
15082            this.element.style.left = "".concat(x, "px");
15083            this.element.style.top = "".concat(y, "px");
15084        };
15085        return Dragger;
15086    }());
15087
15088    var ShowKeyToggle = /** @class */ (function () {
15089        function ShowKeyToggle() {
15090            var _a;
15091            _a = this.setInitPosition(), this.currentX = _a[0], this.currentY = _a[1];
15092            this.isEnabled = false;
15093            this.init();
15094        }
15095        ShowKeyToggle.prototype.setInitPosition = function () {
15096            this.currentX = window.innerWidth - 60;
15097            this.currentY = window.innerHeight - 150;
15098            return [this.currentX, this.currentY];
15099        };
15100        ShowKeyToggle.prototype.init = function () {
15101            var _this = this;
15102            // 检查是否在开发环境
15103            if (!this.shouldShow()) {
15104                return;
15105            }
15106            var button = this.createButton();
15107            var dragger = new Dragger(button, this.currentX, this.currentY, this.toggle.bind(this));
15108            console.log('init ShowKeyToggle', this.button);
15109            var enabled = storage.getItem(SYSTEM_SHOW_TSP_KEY);
15110            if (enabled) {
15111                this.enable();
15112            }
15113            // 窗口大小改变时重新定位
15114            window.addEventListener('resize', function () {
15115                _this.setInitPosition();
15116                dragger.setPosition(_this.currentX, _this.currentY);
15117            });
15118        };
15119        ShowKeyToggle.prototype.createButton = function () {
15120            this.button = document.createElement('div');
15121            this.button.setAttribute('title', 'show the translation key');
15122            this.button.classList.add('dev-toggle-button');
15123            this.button.classList.add('disabled');
15124            this.button.innerHTML = 'key';
15125            document.body.appendChild(this.button);
15126            return this.button;
15127        };
15128        ShowKeyToggle.prototype.shouldShow = function () {
15129            // 非 live 显示
15130            return ENV !== 'live';
15131        };
15132        ShowKeyToggle.prototype.toggle = function () {
15133            this.isEnabled = !this.isEnabled;
15134            this.updateButtonState();
15135            storage.setItem(SYSTEM_SHOW_TSP_KEY, this.isEnabled, 1000 * 60 * 60 * 24);
15136            setTimeout(function () {
15137                location.reload();
15138            }, 300);
15139        };
15140        ShowKeyToggle.prototype.updateButtonState = function () {
15141            var _a, _b, _c, _d;
15142            if (this.isEnabled) {
15143                (_a = this.button) === null || _a === void 0 ? void 0 : _a.classList.add('enabled');
15144                (_b = this.button) === null || _b === void 0 ? void 0 : _b.classList.remove('disabled');
15145            }
15146            else {
15147                (_c = this.button) === null || _c === void 0 ? void 0 : _c.classList.add('disabled');
15148                (_d = this.button) === null || _d === void 0 ? void 0 : _d.classList.remove('enabled');
15149            }
15150        };
15151        // 公共方法
15152        ShowKeyToggle.prototype.enable = function () {
15153            this.isEnabled = true;
15154            this.updateButtonState();
15155        };
15156        ShowKeyToggle.prototype.getState = function () {
15157            return this.isEnabled;
15158        };
15159        return ShowKeyToggle;
15160    }());
15161    new TemplateAction({
15162        pageFinish: function () {
15163            new ShowKeyToggle();
15164        }
15165    });
15166
15167    var HOME_POPUP_PAGE_TYPE = 'spx_homepage';
15168    var HOME_POPUP_PAGE_SECTION = 'home_popup';
15169    var POPUP_WRAPPER_SELECTOR = '.website-popup__wrapper';
15170    var POPUP_DIALOG_SELECTOR = '.website-popup__dialog';
15171    function getPopupImpressionState(planId) {
15172        return __awaiter$7(this, void 0, void 0, function () {
15173            var response;
15174            return __generator$7(this, function (_a) {
15175                switch (_a.label) {
15176                    case 0: return [4 /*yield*/, fetchGet('/shipment/account/open/website/popup/impression/check', { plan_id: planId })];
15177                    case 1:
15178                        response = _a.sent();
15179                        if (response.retcode !== 0) {
15180                            throw new Error(response.message || 'popup impression check failed');
15181                        }
15182                        return [2 /*return*/, response.data];
15183                }
15184            });
15185        });
15186    }
15187    function reportPopupImpression(planId) {
15188        return __awaiter$7(this, void 0, void 0, function () {
15189            var response;
15190            return __generator$7(this, function (_a) {
15191                switch (_a.label) {
15192                    case 0: return [4 /*yield*/, fetchPost('/shipment/account/open/website/popup/impression/report', { plan_id: planId })];
15193                    case 1:
15194                        response = _a.sent();
15195                        if (response.retcode !== 0) {
15196                            throw new Error(response.message || 'popup impression report failed');
15197                        }
15198                        return [2 /*return*/, response.data];
15199                }
15200            });
15201        });
15202    }
15203    function preloadWebsitePopupImage(plan) {
15204        return new Promise(function (resolve, reject) {
15205            var image = new Image();
15206            image.onload = function () { return resolve(); };
15207            image.onerror = reject;
15208            image.src = plan.imageUrl;
15209        });
15210    }
15211    function getWebsitePopupConfig() {
15212        var dialog = document.querySelector(POPUP_DIALOG_SELECTOR);
15213        var config = dialog === null || dialog === void 0 ? void 0 : dialog.getAttribute('data-popup-config');
15214        if (!config)
15215            return null;
15216        try {
15217            return JSON.parse(config);
15218        }
15219        catch (_a) {
15220            return null;
15221        }
15222    }
15223    function showWebsitePopup(plan) {
15224        var wrapper = document.querySelector(POPUP_WRAPPER_SELECTOR);
15225        var elements = wrapper ? getPopupElements(wrapper) : null;
15226        if (!wrapper || !elements)
15227            return;
15228        if (!wrapper.websitePopupBound) {
15229            bindPopupEvents(wrapper, elements, plan);
15230            wrapper.websitePopupBound = true;
15231        }
15232        wrapper.classList.remove('website-popup--hidden');
15233        wrapper.classList.add('website-popup--visible');
15234        wrapper.setAttribute('aria-hidden', 'false');
15235        reportWebsitePopupShow(plan);
15236    }
15237    function getPopupElements(wrapper) {
15238        var link = wrapper.querySelector('.website-popup__link');
15239        var closeButton = wrapper.querySelector('.website-popup__close');
15240        if (!link || !closeButton)
15241            return null;
15242        return { link: link, closeButton: closeButton };
15243    }
15244    function bindPopupEvents(wrapper, elements, plan) {
15245        var closeWrapper = function () { return closePopup(wrapper, 'mask'); };
15246        var closeButton = function (event) {
15247            event.stopPropagation();
15248            closePopup(wrapper, 'x');
15249        };
15250        var closeEsc = function (event) {
15251            if (event.key === 'Escape')
15252                closePopup(wrapper, 'esc');
15253        };
15254        var clickImage = function (event) {
15255            event.stopPropagation();
15256            reportWebsitePopupClick(plan);
15257            closeAndRemove(wrapper);
15258        };
15259        wrapper.addEventListener('click', closeWrapper);
15260        elements.closeButton.addEventListener('click', closeButton);
15261        elements.link.addEventListener('click', clickImage);
15262        document.addEventListener('keydown', closeEsc);
15263        wrapper.websitePopupCleanup = createCleanup(closeEsc);
15264    }
15265    function createCleanup(closeEsc) {
15266        var previousOverflow = document.body.style.overflow;
15267        document.body.style.overflow = 'hidden';
15268        return function () {
15269            document.body.style.overflow = previousOverflow;
15270            document.removeEventListener('keydown', closeEsc);
15271        };
15272    }
15273    function closePopup(wrapper, way) {
15274        reportWebsitePopupClose(way);
15275        closeAndRemove(wrapper);
15276    }
15277    function reportWebsitePopupShow(plan) {
15278        reportTrackingEvent({
15279            page_type: HOME_POPUP_PAGE_TYPE,
15280            page_section: HOME_POPUP_PAGE_SECTION,
15281            target_type: 'home_popup_show',
15282            operation: 'view',
15283            data: { size: plan.popupSize, plan_id: plan.planId || '' },
15284        });
15285    }
15286    function reportWebsitePopupClick(plan) {
15287        reportTrackingEvent({
15288            page_type: HOME_POPUP_PAGE_TYPE,
15289            page_section: HOME_POPUP_PAGE_SECTION,
15290            target_type: 'home_popup_click',
15291            operation: 'click',
15292            data: { link_url: plan.linkUrl },
15293        });
15294    }
15295    function reportWebsitePopupClose(way) {
15296        reportTrackingEvent({
15297            page_type: HOME_POPUP_PAGE_TYPE,
15298            page_section: HOME_POPUP_PAGE_SECTION,
15299            target_type: 'home_popup_close',
15300            operation: 'click',
15301            data: { way: way },
15302        });
15303    }
15304    function closeAndRemove(wrapper) {
15305        var _a;
15306        (_a = wrapper.websitePopupCleanup) === null || _a === void 0 ? void 0 : _a.call(wrapper);
15307        if (wrapper.parentNode)
15308            wrapper.parentNode.removeChild(wrapper);
15309    }
15310
15311    var getPopupCacheKey = function (accountId, planId) {
15312        return "website_popup_plan_".concat(accountId, "_").concat(planId
15312);
15313    };
15314    function readPopupImpressionCache(accountId, planId) {
15315        try {
15316            return storage.getItem(getPopupCacheKey(accountId, planId)) || null;
15317        }
15318        catch (_a) {
15319            return null;
15320        }
15321    }
15322    function writePopupImpressionCache(accountId, state) {
15323        try {
15324            storage.setItem(getPopupCacheKey(accountId, state.planId), state);
15325        }
15326        catch (_a) {
15327            return;
15328        }
15329    }
15330    function removePopupImpressionCache(accountId, planId) {
15331        try {
15332            storage.removeItem(getPopupCacheKey(accountId, planId));
15333        }
15334        catch (_a) {
15335            return;
15336        }
15337    }
15338
15339    function loadWebsitePopupRuntime(bannerPlan_1, accountId_1, mobile_1) {
15340        return __awaiter$7(this, arguments, void 0, function (bannerPlan, accountId, mobile, nowSeconds, mode) {
15341            var plan, impressionState;
15342            if (nowSeconds === void 0) { nowSeconds = currentSeconds(); }
15343            if (mode === void 0) { mode = 'live'; }
15344            return __generator$7(this, function (_a) {
15345                switch (_a.label) {
15346                    case 0:
15347                        plan = selectWebsitePopupPlanFromBannerPlan(bannerPlan, mobile, mode);
15348                        if (!plan)
15349                            return [2 /*return*/, null];
15350                        if (mode === 'preview')
15351                            return [2 /*return*/, { mode: mode, plan: plan }];
15352                        if (!plan.planId)
15353                            return [2 /*return*/, null];
15354                        return [4 /*yield*/, loadImpressionState(accountId, plan, nowSeconds)];
15355                    case 1:
15356                        impressionState = _a.sent();
15357                        if (!impressionState || !shouldShowPopup(plan, impressionState, nowSeconds)) {
15358                            return [2 /*return*/, null];
15359                        }
15360                        return [2 /*return*/, {
15361                                mode: mode,
15362                                accountId: accountId,
15363                                plan: plan,
15364                                impressionState: impressionState,
15365                            }];
15366                }
15367            });
15368        });
15369    }
15370    function loadImpressionState(accountId, plan, nowSeconds) {
15371        return __awaiter$7(this, void 0, void 0, function () {
15372            var cached, response, state;
15373            return __generator$7(this, function (_b) {
15374                switch (_b.label) {
15375                    case 0:
15376                        cached = readPopupImpressionCache(accountId, plan.planId);
15377                        if (cached && !isPopupCacheExpired(plan, cached, nowSeconds)) {
15378                            return [2 /*return*/, cached];
15379                        }
15380                        removePopupImpressionCache(accountId, plan.planId);
15381                        _b.label = 1;
15382                    case 1:
15383                        _b.trys.push([1, 3, , 4]);
15384                        return [4 /*yield*/, getPopupImpressionState(plan.planId)];
15385                    case 2:
15386                        response = _b.sent();
15387                        state = mapPopupImpressionState(response);
15388                        writePopupImpressionCache(accountId, state);
15389                        return [2 /*return*/, state];
15390                    case 3:
15391                        _b.sent();
15392                        return [2 /*return*/, null];
15393                    case 4: return [2 /*return*/];
15394                }
15395            });
15396        });
15397    }
15398    function recordWebsitePopupExposure(runtime, nowSeconds) {
15399        if (nowSeconds === void 0) { nowSeconds = currentSeconds(); }
15400        if (runtime.mode === 'preview')
15401            return;
15402        void reportPopupImpression(runtime.plan.planId).then(function (response) {
15403            writePopupImpressionCache(runtime.accountId, {
15404                planId: runtime.plan.planId,
15405                impressionCount: response.impression_count,
15406                lastImpressionTime: response.last_impression_time,
15407            });
15408        }).catch(function (error) {
15409            console.error('[website-popup] report impression failed', error);
15410            writePopupImpressionCache(runtime.accountId, recordLocalExposure(runtime.plan, runtime.impressionState, nowSeconds));
15411        });
15412    }
15413    function currentSeconds() {
15414        return Math.floor(Date.now() / 1000);
15415    }
15416
15417    var initWebsitePopup = function () { return __awaiter$7(void 0, void 0, void 0, function () {
15418        var bannerPlan, userInfo, runtime_1, error_1;
15419        return __generator$7(this, function (_a) {
15420            switch (_a.label) {
15421                case 0:
15422                    _a.trys.push([0, 4, , 5]);
15423                    bannerPlan = getWebsitePopupConfig();
15424                    if (!bannerPlan)
15425                        return [2 /*return*/];
15426                    return [4 /*yield*/, getUserInfo()];
15427                case 1:
15428                    userInfo = _a.sent();
15429                    if (!(userInfo === null || userInfo === void 0 ? void 0 : userInfo.account_id))
15430                        return [2 /*return*/];
15431                    return [4 /*yield*/, loadWebsitePopupRuntime(bannerPlan, userInfo.account_id, isMobile() || window.innerWidth <= 768, undefined, getPreviewId() ? 'preview' : 'live')];
15432                case 2:
15433                    runtime_1 = _a.sent();
15434                    if (!runtime_1)
15435                        return [2 /*return*/];
15436                    return [4 /*yield*/, preloadWebsitePopupImage(runtime_1.plan)];
15437                case 3:
15438                    _a.sent();
15439                    setTimeout(function () {
15440                        showWebsitePopup(runtime_1.plan);
15441                        recordWebsitePopupExposure(runtime_1);
15442                    }, 0);
15443                    return [3 /*break*/, 5];
15444                case 4:
15445                    error_1 = _a.sent();
15446                    console.error('[website-popup] init failed', error_1);
15447                    return [3 /*break*/, 5];
15448                case 5: return [2 /*return*/];
15449            }
15450        });
15451    }); };
15452    new TemplateAction({ rendered: initWebsitePopup });
15453
15454    console.info('=========detail-entry');
15455    // 这里可以写你的代码
15456    var initDetail = function () {
15457        init({
15458            pageType: 'detail',
15459        });
15460    };
15461    setGlobalEvent('initDetail', initDetail);
15462
15463})();
15464
15465
15466//# sourceMappingURL=detail-bundle.js.map

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.