@jolibox/sdk 1.1.4-beta.9 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,26 +4,29 @@
4
4
  "packages/sdk/.eslintrc.js": "c11c589d14fe58bf4d37d259d8323b193bab6092",
5
5
  "packages/sdk/README.md": "5660cd88848b7a5428394cc34d881a35dd402188",
6
6
  "packages/sdk/esbuild.config.js": "7eacca35e51bf3e2face4112b3cfa76777e7c0d5",
7
- "packages/sdk/package.json": "82d6c7d31d6c04aef28578d8fea93fe809ce87f4",
7
+ "packages/sdk/package.json": "36b65c2b39db5d25e2fa737773334cb2929d03c6",
8
8
  "packages/sdk/src/api/__tests__/canIUse.test.ts": "300e4de3768f9510e956050d326d4977bc621f34",
9
9
  "packages/sdk/src/api/can-i-use.ts": "4fd7efe21419d39e535584d7ab8e6a3c4e186877",
10
10
  "packages/sdk/src/api/get-system-info.ts": "c73be9f62c7055093effadaf6c48c54d6f383542",
11
11
  "packages/sdk/src/api/index.ts": "3b4493aba6d4d842031040be7ce72607009e0665",
12
12
  "packages/sdk/src/api/login.ts": "747c923c87175b467c17e303a14210bf0ab7a1cb",
13
- "packages/sdk/src/events.ts": "e7c5994804cc627eb5ad225c161c48a37a7b3bdb",
13
+ "packages/sdk/src/events.ts": "fc2df274eeedce36bedfc7d01ec580dba16e4502",
14
14
  "packages/sdk/src/index.ts": "a772c24e370f183dba0c5346004f41dac6cb6807",
15
- "packages/sdk/src/loader/h5.ts": "9ca7acc4996893f683b9adc8cffb2456928e5875",
16
- "packages/sdk/src/loader/index.ts": "2fd698718dd7bad9fda8fa5a5f54d4d7bd209cb3",
17
- "packages/sdk/src/loader/native.ts": "b250d460509f67b4544e5ca4d5f35f8dd20373c4",
18
- "packages/sdk/src/loader/version.ts": "8b584cf9c97198b6b6d1f728cc49f56260d7c02e",
15
+ "packages/sdk/src/loader/__tests__/version.test.ts": "338ca817bfcb672d1065d6f32872b57bc43951b5",
16
+ "packages/sdk/src/loader/h5.ts": "dadad15256c17d6aa1a6bbee71217140ae77d7fe",
17
+ "packages/sdk/src/loader/index.ts": "a6757330d198d9e9ff71811e49626f5892554f1c",
18
+ "packages/sdk/src/loader/native.ts": "5f9f068c328222a28b457d19841b93c4a13ecccb",
19
+ "packages/sdk/src/loader/version.ts": "deacf56606b2c47f93e0dfa35e5b5dfbe774c69f",
19
20
  "packages/sdk/src/sdks/ads.ts": "d12ffe12be857f216a59a742f54395e31888adb5",
20
- "packages/sdk/src/sdks/keyboard.ts": "2f0cece555d7000357c45b458d9050d9f80773b2",
21
+ "packages/sdk/src/sdks/keyboard.ts": "65301960c4d8f59d5944ae4c55cb45133ad40277",
21
22
  "packages/sdk/src/sdks/lifecycle.ts": "8dad9d986cb43da7aeadf6f8af3cce37d6c37e6d",
22
- "packages/sdk/src/sdks/runtime.ts": "de05c8f898b3f5848c83e5c088fb720bd8217d99",
23
+ "packages/sdk/src/sdks/runtime.ts": "5abaabc3ead85bc07b06b6c38faeb3bb3fef0335",
23
24
  "packages/sdk/src/sdks/sdk.ts": "7ced43ddee5f0208ceaec5f8311f586d3ca5a13d",
24
25
  "packages/sdk/src/sdks/storage.ts": "e04fca273b640f2e1dfcc70f23eaa537145c3f36",
25
26
  "packages/sdk/src/sdks/task.ts": "07f5296dd999470d8d378487fd6f2a39a3f3d8ed",
26
27
  "packages/sdk/src/utils/can-i-use.ts": "10993f013cf26c07b60fe60fb7b458bbd6847244",
28
+ "packages/sdk/src/utils/env.ts": "d2e3db934d24a3b687de1f2df04fed7a5467e161",
29
+ "packages/sdk/src/utils/event-tracker.ts": "25efb905424ad0c0fb5f32372de587d80569fb56",
27
30
  "packages/sdk/src/utils/report.ts": "d928d7456a5ba829216c41ea5b66afff6627c6be",
28
31
  "packages/sdk/tsconfig.json": "0ecd9cf2b93d09e0376a098b5b662820bafcf7eb"
29
32
  },
package/dist/index.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";var P=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var ke=Object.prototype.hasOwnProperty;var Oe=(e,t)=>{for(var r in t)P(e,r,{get:t[r],enumerable:!0})},Ke=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ce(t))!ke.call(e,s)&&s!==r&&P(e,s,{get:()=>t[s],enumerable:!(n=De(t,s))||n.enumerable});return e};var Me=e=>Ke(P({},"__esModule",{value:!0}),e);var ct={};Oe(ct,{JoliboxSDK:()=>N});module.exports=Me(ct);var X=Object.defineProperty,Ne=Object.getOwnPropertyDescriptor,Pe=(e,t)=>{for(var r in t)X(e,r,{get:t[r],enumerable:!0})},q=(e,t,r,n)=>{for(var s=n>1?void 0:n?Ne(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&X(t,r,s),s};function je(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function V(e){return typeof e=="string"}function Z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function Je(e){return typeof e>"u"}function Fe(e){return Je(e)||e===null}function Be(e){return typeof e=="function"}function ee(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}var Ve=(e=>(e[e.DEVELOPER_FILE_NOT_FOUND=0]="DEVELOPER_FILE_NOT_FOUND",e[e.INTERNAL_IOS_CAN_NOT_FOUND_PKG=1]="INTERNAL_IOS_CAN_NOT_FOUND_PKG",e[e.USER_IOS_LOAD_TIMEOUT=2]="USER_IOS_LOAD_TIMEOUT",e[e.INTERNAL_IOS_PKG_LOAD_ERROR=3]="INTERNAL_IOS_PKG_LOAD_ERROR",e[e.INTERNAL_IOS_PKG_PARSE_FAIL=4]="INTERNAL_IOS_PKG_PARSE_FAIL",e[e.USER_IOS_GET_EMPTY_DATA=5]="USER_IOS_GET_EMPTY_DATA",e[e.USER_ANDROID_GET_PKG_FAIL=6]="USER_ANDROID_GET_PKG_FAIL",e[e.DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE=7]="DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE",e))(Ve||{}),$e=class extends Error{constructor(e){if(typeof e=="string"){super(e),this.priority="P1";return}super(e.message),this.priority="P1",this.stack=e.stack,this.raw=e}},te=class extends $e{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}};var re=class extends te{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_FETCH_ERROR",this.priority="P0"}},R=class extends te{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function S(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var He={log:S("log"),warn:S("warn"),info:S("info"),error:S("error"),debug:S("debug")};Object.assign(globalThis,{logger:He});var ne=Symbol.for("Jolibox.canIUseMap"),Ge={};globalThis[ne]=Ge;var se={get config(){return globalThis[ne]}};function $(e,t,r){let n=0;if(e!==t){let s=e.split("."),o=t.split("."),i=Math.max(s.length,o.length);for(let l=0;l<i;l++){let g=parseInt(s[l],10)||0,c=parseInt(o[l],10)||0;if(g>c){n=1;break}else if(g<c){n=-1;break}}}if(!r)return n;switch(r){case">":return n>0;case"<":return n<0;case"=":return n===0;case">=":return n>=0;case"<=":return n<=0;default:return!1}}var a=class U{static{this.Undefined=new U(void 0)}constructor(t){this.element=t,this.next=U.Undefined,this.prev=U.Undefined}},ze=class{constructor(){this._first=a.Undefined,this._last=a.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===a.Undefined}clear(){let e=this._first;for(;e!==a.Undefined;){let t=e.next;e.prev=a.Undefined,e.next=a.Undefined,e=t}this._first=a.Undefined,this._last=a.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let r=new a(e);if(this._first===a.Undefined)this._first=r,this._last=r;else if(t){let s=this._last;this._last=r,r.prev=s,s.next=r}else{let s=this._first;this._first=r,r.next=s,s.prev=r}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(r))}}shift(){if(this._first!==a.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==a.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==a.Undefined&&e.next!==a.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===a.Undefined&&e.next===a.Undefined?(this._first=a.Undefined,this._last=a.Undefined):e.next===a.Undefined?(this._last=this._last.prev,this._last.next=a.Undefined):e.prev===a.Undefined&&(this._first=this._first.next,this._first.prev=a.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==a.Undefined;)yield e.element,e=e.next}},We=0,w=class{constructor(e){this.value=e,this.id=We++}},v=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof w&&(this._listeners=[this._listeners]),this._listeners=this._listeners.filter(t=>t?.value===e)):(this._listeners=void 0,this._size=0)),this.options?.onDidRemoveLastListener?.())}get event(){return this._event??=(e,t)=>{if(this._disposed)return()=>{console.info("[Jolibox SDK] Emitter is _disposed")};t&&(e=e.bind(t));let r=new w(e);this._listeners?this._listeners instanceof w?this._listeners=[this._listeners,r]:this._listeners.push(r):(this.options?.onWillAddFirstListener?.(this),this._listeners=r,this.options?.onDidFirstListener?.(this)),this.options?.onDidAddListener?.(this),this._size++},this._event}_deliver(e,t){if(!e)return;let r=this.options?.onListenerError||Error.constructor;if(!r){e.value(t);return}try{e.value(t)}catch(n){r(n)}}fire(e){this._listeners&&(this._listeners instanceof w?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},H=class{constructor(){this.listeners=new Map,this.listerHandlerMap=new WeakMap,this.cachedEventQueue=new Map}on(e,t){let r=this.listeners.get(e)??new v,n=o=>t(...o.args);this.listerHandlerMap.set(t,n),r.event(n),this.listeners.set(e,r);let s=this.cachedEventQueue.get(e);if(s)for(;s.size>0;)r.fire({event:e,...s.shift()})}off(e,t){let r=this.listeners.get(e);if(r){let n=this.listerHandlerMap.get(t);r.dispose(n)}}emit(e,...t){let r=this.listeners.get(e);if(r)r.fire({event:e,args:t});else{let n=this.cachedEventQueue.get(e);n||(n=new ze,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},F={};Pe(F,{None:()=>Qe,filter:()=>Xe,once:()=>oe,toPromise:()=>Ye});var Qe=()=>{console.log("[Jolibox SDK] None Event")};function Ye(e){return new Promise(t=>oe(e)(t))}function oe(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function Xe(e,t){return(r=>{let n,s={onWillAddFirstListener(){n=r(o.fire,o)}},o=new v(s);return o.event})((r,n=null)=>e(s=>t(s)&&r.call(n,s),null))}var j=Symbol.for("Jolibox.hostEmitter"),qe=()=>{let e=new H;return globalThis[j]||(globalThis[j]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[j]},ie=qe();function Ze(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)et(e[n],t[n])}function et(e,t){if(V(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(Be(t)){try{if(e instanceof t)return}catch{}if(!Fe(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("[Jolibox SDK]argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}var L=class{constructor(){this._commands=new Map,this._onDidRegisterCommand=new v,this.onDidRegisterCommand=this._onDidRegisterCommand.event,console.log("[Jolibox SDK] command registry")}registerCommand(e){if(!e)throw new Error("invalid command");if(e.metadata&&Array.isArray(e.metadata.args)){let r=[];for(let s of e.metadata.args)r.push(s.constraint);let n=e.handler;e.handler=function(...s){return Ze(s,r),n(...s)}}let{id:t}=e;this._commands.get(t)&&console.info(`[Jolibox SDK] duplicated command is registered ${t}`),this._commands.set(t,e),this._onDidRegisterCommand.fire(t)}getCommand(e){return this._commands.get(e)}getCommands(){let e=new Map;for(let t of this._commands.keys()){let r=this.getCommand(t);r&&e.set(t,r)}return e}};L=q([ee],L);var B=class{constructor(){this._onWillExecuteCommand=new v,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new v,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new L,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=je(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),F.toPromise(F.filter(this.registry.onDidRegisterCommand,r=>r===e))])]),this._tryExecuteCommand(e,t))}executeCommandThowErr(e,...t){if(!this.registry.getCommand(e))throw new Error(`command '${e}' not found`);let r=this.registry.getCommand(e);this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),n}_tryExecuteCommand(e,t){let r=this.registry.getCommand(e);if(!r)return Promise.reject(new Error(`command '${e}' not found`));try{this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),Promise.resolve(n)}catch(n){return Promise.reject(n)}}invokeFunction(e,...t){let r=!1;try{return e(...t)}finally{r=!0}}};B=q([ee],B);var J=Symbol.for("Jolibox.commands");function p(){if(globalThis[J])return globalThis[J];let e=new L,t=new B,r={registerCommand(n,s,o){e.registerCommand({id:n,handler:s,metadata:o})},executeCommand(n,...s){return t.executeCommand(n,...s)},excuteCommandSync(n,...s){return t.executeCommandThowErr(n,...s)}};return globalThis[J]=r,r}document.addEventListener("DOMContentLoaded",()=>ie.emit("onDocumentReady",b.startTime));var tt=()=>{let e=0;return{set startTime(t){e=t},get startTime(){return e}}},b=tt(),ae=p(),G=e=>{ae.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`)})},E=G;window.addEventListener("unhandledrejection",G.bind(void 0));window.addEventListener("error",G.bind(void 0));window.onerror=(e,t,r,n,s)=>{ae.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})}}).catch(o=>{console.error(`Fallback report: ${o} ${JSON.stringify(e)}`)})};var z=e=>{let t=e.split("-")[1];t&&(e=e.replace(`-${t}`,""));let r=e.split("+")[1];r&&(e=e.replace(`+${r}`,""));let n=e.split(".").slice(0,3),[s,o,i]=[n[0]??"0",n[1]??"0",n[2]??"0"];return{major:s,minor:o,patch:i,prerelease:t,build:r}},x=e=>parseInt(z(e).major,10),I=(e,t)=>{let{major:r,minor:n,patch:s}=z(e),{major:o,minor:i,patch:l}=z(t);return r!==o?r>o?1:-1:n!==i?n>i?1:-1:s!==l?s>l?1:-1:0};var ce=p(),A=(e,t)=>{ce.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},_=(e,t,r)=>{ce.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var de="jolibox-sdk-loadermeta",T=JSON.parse(localStorage.getItem(de)??"{}"),W=Date.now(),me=(e,t)=>e>t&&Math.abs(e-t)/(1e3*60*60*24)>=7,le=e=>!/^(Failed to fetch version|Couldn't find the requested file)/.test(e);async function rt(){let e="https://stg-api.jolibox.com/api/fe-configs/js-sdk/version_metadata";try{let t=await fetch(e,{method:"GET",headers:{"Content-Type":"application/json"}}),{implement_version:r,bootstrap_version:n}=await t.json(),s={...T,timestamp:W};if(n){let{bootstrap_version:o}=T;if(!(o&&I(o,n))){let i=await(await fetch(Q(n))).text();le(i)&&(s={...s,bootstrap_version:n,bootstrap_script:i})}}if(r){let{implement_version:o}=T;if(!(o&&I(o,r))){let i=await(await fetch(Y(r))).text();le(i)&&(s={...s,implement_version:r,implement_script:i})}}localStorage.setItem(de,JSON.stringify(s))}catch(t){console.warn("Failed to fetch loader metadata: ",t)}}var ue=e=>{let{currentMajorVersion:t,currentVersion:r,bootstrapUrl:n,implementUrl:s}=e;function o(){let{bootstrap_version:c,bootstrap_script:f,timestamp:u}=T;if(c&&f&&u&&!me(W,u)&&x(c)==t&&I(c,r)>0)return{script:f,type:"localscript"};try{let m=new XMLHttpRequest;return m.open("GET",n,!1),m.send(),{script:m.responseText,type:"fetch_from_cdn"}}catch(m){E(new re(`Bootstrap module faile to fetch ${m}`))}}function i(){let c=Date.now();A("jsSdkBegin",{t:c}),b.startTime=c;let{script:f,type:u}=o()??{};if(f){let m=document.createElement("script");m.type="text/javascript",m.innerHTML=f,document.head.appendChild(m),_("bootstrapModuleLoaded",Date.now()-c,{type:u})}}function l(c){(async u=>{try{let m=new Blob([u],{type:"application/javascript"}),h=URL.createObjectURL(m),Ae=await import(h);return URL.revokeObjectURL(h),Ae}catch(m){E(new R(`implement module evaluate error in h5:${m} `))}})(c)}function g(){let c=Date.now(),{implement_script:f,implement_version:u,timestamp:m}=T;if(f&&u&&m&&!me(W,m)&&x(u)==t&&I(u,r)>0){l(f),_("implementModuleLoaded",Date.now()-c,{type:"loadscript"});return}let h=document.createElement("script");h.type="module",h.crossOrigin="anonymous",h.src=s,h.onload=()=>{_("bootstrapModuleLoaded",Date.now()-c,{type:"fetch_from_cdn"})},document.head.appendChild(h)}return()=>{try{i(),g(),rt()}catch(c){E(new R(`module evaluate error: ${c}`))}}};var pe=(e,t)=>{let r=s=>{let o=e({path:s});if(!o)throw`module ${s} load failed ${o}`;return o};function n(s){(async i=>{try{let l=new Blob([i],{type:"application/javascript"}),g=URL.createObjectURL(l),c=await import(g);return URL.revokeObjectURL(g),c}catch(l){E(new R(`implement module evaluate error in native:${l} `))}})(s)}return()=>{try{let s=Date.now();A("jsSdkBegin",{t:s}),b.startTime=s;let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),_("implementModuleLoaded",Date.now()-s,{type:"native"});let l=r(t.implementUrl);n(l),_("bootstrapModuleLoaded",Date.now()-s,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),E(new R(`module load failed ${s}`))}}};var nt="1.1.4-beta.9",D=nt,ge=x(D),Ee=window.webkit||window.JoliAndroidSDKBridge?e=>{let t=window.prompt("invoke",JSON.stringify({event:"loadScriptSync",paramsString:JSON.stringify(e)}));if(t){let{data:r}=JSON.parse(t);return r}}:void 0,st=typeof Ee<"u",Q=e=>`https://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,Y=e=>`https://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,ot=e=>/^\d+\.\d+\.\d+$/.test(e),_e=ot(D)?ge:D,fe=Q(_e),he=Y(_e);function it(){st?pe(Ee,{bootstrapUrl:fe,implementUrl:he})():ue({bootstrapUrl:fe,implementUrl:he,currentMajorVersion:ge,currentVersion:D})()}it();var ye=p();function Re(){return ye.excuteCommandSync("API.getSystemInfoSync")}function Se(){return ye.excuteCommandSync("API.env")}function ve(e,t){return se.config[e]?.[t]}function be(e,t,r){let n=Array.isArray(t)?t:t.replace(/\[(\d+)\]/g,".$1").split("."),s=e;for(let o of n)if(s&&(typeof s=="object"||Array.isArray(s)))s=s[o];else return r;return s===void 0?r:s}var Ie="1.1.4-beta.9";function y(e){let r=Se().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=ve(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||$(Ie,i,"<")?!1:s.length===0?!0:xe(o,s)||xe(o.properties,s)}function xe(e,t){if(!e)return!1;let r=be(e,t);return r?Z(r)?!0:V(r)?$(Ie,r,">="):!1:!1}var Te=p();async function we(){return y("login")?await Te.executeCommand("API.login"):{code:"FAILURE",message:"[Jolibox SDK]login is not supported in this platform"}}async function Ue(){return y("checkSession")?await Te.executeCommand("API.checkSession"):{code:"FAILURE",message:"[Jolibox SDK]checkSession is not supported in this platform"}}var Le=window.JoliboxRuntime;var d=class{constructor(){this.commands=p();this._emitter=new H}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return y(t)}canIUseIfThrow(t){if(!this.canUse(t))return{code:"FAILURE",message:`[Jolibox SDK] ${t} is not supported in this platform`}}};var at="LifecycleSDK.onReady",C=class extends d{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(at,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exit(t){let r=this.canIUseIfThrow("lifeCycle.exit");if(r)return r;this.commands.executeCommand("LifecycleSDK.exit",t.onBeforeExit)}onJoliboxHide(t){this.commands.executeCommand("LifecycleSDK.onJoliboxHide",t.bind(this))}onJoliboxShow(t){this.commands.executeCommand("LifecycleSDK.onJoliboxShow",t.bind(this))}};var k=class extends d{async getItem(t){return await this.commands.executeCommand("StorageSDK.getItem",t)}async setItem(t,r){if(t.length>128)return{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key should be less than 128"};let n=typeof r=="string"?r:String(r);return t.length+n.length>1024?{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key and value should be less than 1024"}:await this.commands.executeCommand("StorageSDK.setItem",t,r)}async removeItem(t){return this.commands.executeCommand("StorageSDK.removeItem",t)}async clear(){return this.commands.executeCommand("StorageSDK.clear")}};var O=class extends d{constructor(){super();this.init=r=>{this.commands.executeCommand("AdsSDK.init",r)};this.adConfig=r=>{this.commands.executeCommand("AdsSDK.adConfig",r)};this.adBreak=r=>{this.commands.executeCommand("AdsSDK.adBreak",r)};this.adUnit=r=>{this.commands.executeCommand("AdsSDK.adUnit",r)}}};var K=class extends d{showKeyboard(t){let r=this.canIUseIfThrow("keyboard.showKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){let r=this.canIUseIfThrow("keyboard.updateKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.updateKeyboard",t)}hideKeyboard(){let t=this.canIUseIfThrow("keyboard.hideKeyboard");if(t)return t;this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var M=class extends d{async onLevelFinished(t,r,n){let s=this.canIUseIfThrow("TaskTrackerSDK.onLevelFinished");return s?Promise.resolve(s):await this.commands.executeCommand("TaskTrackerSDK.levelFinished",t,{result:r,duration:n})}async onTaskFinished(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskFinished");return n||await this.commands.executeCommand("TaskTrackerSDK.taskFinished",t,{duration:r})}async onTaskEvent(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskEvent");return n||await this.commands.executeCommand("TaskTrackerSDK.taskEvent",t,r)}async onLevelUpgrade(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onLevelUpgrade");return n||await this.commands.executeCommand("TaskTrackerSDK.levelUpgrade",t,r)}async onHistoryUserLevel(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserLevel");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserLevel",t)}async onHistoryUserScore(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserScore");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserScore",t)}};var N=class{constructor(){this.jssdkVersion="1.1.4-beta.9";this.runtime=new Le;this.ads=new O;this.lifecycle=new C;this.storage=new k;this.keyboard=new K;this.task=new M;this.getSystemInfoSync=Re.bind(this);this.canIUse=y.bind(this);this.login=we.bind(this);this.checkSession=Ue.bind(this)}};window.JoliboxSDK=N;
1
+ "use strict";var F=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Ge=Object.getOwnPropertyNames;var He=Object.prototype.hasOwnProperty;var We=(e,t)=>{for(var r in t)F(e,r,{get:t[r],enumerable:!0})},ze=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ge(t))!He.call(e,s)&&s!==r&&F(e,s,{get:()=>t[s],enumerable:!(n=$e(t,s))||n.enumerable});return e};var Ye=e=>ze(F({},"__esModule",{value:!0}),e);var Jt={};We(Jt,{JoliboxSDK:()=>J});module.exports=Ye(Jt);var oe=Object.defineProperty,Qe=Object.getOwnPropertyDescriptor,Xe=(e,t)=>{for(var r in t)oe(e,r,{get:t[r],enumerable:!0})},ie=(e,t,r,n)=>{for(var s=n>1?void 0:n?Qe(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&oe(t,r,s),s};function qe(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function H(e){return typeof e=="string"}function ae(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function Ze(e){return typeof e>"u"}function et(e){return Ze(e)||e===null}function tt(e){return typeof e=="function"}function ce(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}var rt=(e=>(e[e.DEVELOPER_FILE_NOT_FOUND=0]="DEVELOPER_FILE_NOT_FOUND",e[e.INTERNAL_IOS_CAN_NOT_FOUND_PKG=1]="INTERNAL_IOS_CAN_NOT_FOUND_PKG",e[e.USER_IOS_LOAD_TIMEOUT=2]="USER_IOS_LOAD_TIMEOUT",e[e.INTERNAL_IOS_PKG_LOAD_ERROR=3]="INTERNAL_IOS_PKG_LOAD_ERROR",e[e.INTERNAL_IOS_PKG_PARSE_FAIL=4]="INTERNAL_IOS_PKG_PARSE_FAIL",e[e.USER_IOS_GET_EMPTY_DATA=5]="USER_IOS_GET_EMPTY_DATA",e[e.USER_ANDROID_GET_PKG_FAIL=6]="USER_ANDROID_GET_PKG_FAIL",e[e.DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE=7]="DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE",e))(rt||{}),nt=class extends Error{constructor(e){if(typeof e=="string"){super(e),this.priority="P1";return}super(e.message),this.priority="P1",this.stack=e.stack,this.raw=e}},me=class extends nt{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}};var le=class extends me{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_FETCH_ERROR",this.priority="P0"}},S=class extends me{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function v(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var st={log:v("log"),warn:v("warn"),info:v("info"),error:v("error"),debug:v("debug")};Object.assign(globalThis,{logger:st});var de=Symbol.for("Jolibox.canIUseMap"),ot={};globalThis[de]=ot;var ue={get config(){return globalThis[de]}};function W(e,t,r){let n=0;if(e!==t){let s=e.split("."),o=t.split("."),i=Math.max(s.length,o.length);for(let m=0;m<i;m++){let d=parseInt(s[m],10)||0,a=parseInt(o[m],10)||0;if(d>a){n=1;break}else if(d<a){n=-1;break}}}if(!r)return n;switch(r){case">":return n>0;case"<":return n<0;case"=":return n===0;case">=":return n>=0;case"<=":return n<=0;default:return!1}}var z=(e=>(e[e.System=1e3]="System",e[e.ErrorTrace=1001]="ErrorTrace",e[e.UserDefined=1002]="UserDefined",e))(z||{}),Y=(e=>(e.MiniGame="mini-game",e.MiniDrama="mini-drama",e.App="app",e.WebSDK="web-sdk",e.AppSDK="app-sdk",e))(Y||{}),it=(e=>(e[e.App=0]="App",e[e.H5=1]="H5",e[e.Weapp=2]="Weapp",e[e.Alipay=3]="Alipay",e[e.Gcash=4]="Gcash",e[e.Dana=5]="Dana",e[e.Umma=6]="Umma",e[e.WebSDK=1e3]="WebSDK",e[e.AppSDK=1001]="AppSDK",e[e.Other=9999]="Other",e))(it||{}),se=["name","params"],at=["name","type","location","target","extra","timestamp","userId"],ct=["platform","os","appVersion","appId","model","brand","uuid","jsSdkVersion","extra"];function D(e,t){return t.map(r=>{if(r==="params"&&e[r]){let n=e[r];return Object.keys(n).reduce((s,o)=>(s[o]=String(n[o]),s),{})}return e[r]})}function mt(e){let t=e.location?D(e.location,se):null,r=e.target?D(e.target,se):null;return D({...e,location:t,target:r},at)}function pe(e){let t=e.events.map(n=>mt(n)),r=D(e.device,ct);return[e.protocolVersion,t,r,e.project]}var lt=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)});var A={isiOS:navigator.userAgent.includes("iPhone")||navigator.userAgent.includes("iPod")||navigator.userAgent.includes("iPad")||navigator.userAgent.includes("iPhone OS"),iosVersion:()=>{let e=navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);return[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3]||"0",10)]},isAndroid:navigator.userAgent.includes("Android"),isMac:navigator.userAgent.includes("Mac"),isFacebook:navigator.userAgent.includes("FB_IAB"),isPC:!navigator.userAgent.includes("iPhone")&&!navigator.userAgent.includes("Android")},dt=()=>A.isiOS?"iOS":A.isAndroid?"Android":A.isMac?"Mac":A.isFacebook?"Facebook":"PC",ut="device_id",pt="advertising_id",fe=e=>(localStorage.getItem(e)||localStorage.setItem(e,lt()),localStorage.getItem(e)),ft=()=>fe(ut),ht=()=>fe(pt),gt=e=>e.charAt(0).toUpperCase()+e.slice(1),Et=()=>{let e=new URLSearchParams(window.location.search);return gt(e.get("utm_source")??"")||"JoliboxSDK"},he=e=>{let t="JoliboxWebSDK",r=dt(),n=navigator.language,s=ft(),o=ht();return`${t} (${Et()}${r}; UnknownModel; UnknownSystemVersion; ${n}) uuid/${s} adid/${o} version/${e||""}`},c=class U{static{this.Undefined=new U(void 0)}constructor(t){this.element=t,this.next=U.Undefined,this.prev=U.Undefined}},_t=class{constructor(){this._first=c.Undefined,this._last=c.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===c.Undefined}clear(){let e=this._first;for(;e!==c.Undefined;){let t=e.next;e.prev=c.Undefined,e.next=c.Undefined,e=t}this._first=c.Undefined,this._last=c.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let r=new c(e);if(this._first===c.Undefined)this._first=r,this._last=r;else if(t){let s=this._last;this._last=r,r.prev=s,s.next=r}else{let s=this._first;this._first=r,r.next=s,s.prev=r}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(r))}}shift(){if(this._first!==c.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==c.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==c.Undefined&&e.next!==c.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===c.Undefined&&e.next===c.Undefined?(this._first=c.Undefined,this._last=c.Undefined):e.next===c.Undefined?(this._last=this._last.prev,this._last.next=c.Undefined):e.prev===c.Undefined&&(this._first=this._first.next,this._first.prev=c.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==c.Undefined;)yield e.element,e=e.next}},yt=0,w=class{constructor(e){this.value=e,this.id=yt++}},x=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof w&&(this._listeners=[this._listeners]),this._listeners=this._listeners.filter(t=>t?.value===e)):(this._listeners=void 0,this._size=0)),this.options?.onDidRemoveLastListener?.())}get event(){return this._event??=(e,t)=>{if(this._disposed)return()=>{console.info("[Jolibox SDK] Emitter is _disposed")};t&&(e=e.bind(t));let r=new w(e);this._listeners?this._listeners instanceof w?this._listeners=[this._listeners,r]:this._listeners.push(r):(this.options?.onWillAddFirstListener?.(this),this._listeners=r,this.options?.onDidFirstListener?.(this)),this.options?.onDidAddListener?.(this),this._size++},this._event}_deliver(e,t){if(!e)return;let r=this.options?.onListenerError||Error.constructor;if(!r){e.value(t);return}try{e.value(t)}catch(n){r(n)}}fire(e){this._listeners&&(this._listeners instanceof w?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},Q=class{constructor(){this.listeners=new Map,this.listerHandlerMap=new WeakMap,this.cachedEventQueue=new Map}on(e,t){let r=this.listeners.get(e)??new x,n=o=>t(...o.args);this.listerHandlerMap.set(t,n),r.event(n),this.listeners.set(e,r);let s=this.cachedEventQueue.get(e);if(s)for(;s.size>0;)r.fire({event:e,...s.shift()})}off(e,t){let r=this.listeners.get(e);if(r){let n=this.listerHandlerMap.get(t);r.dispose(n)}}emit(e,...t){let r=this.listeners.get(e);if(r)r.fire({event:e,args:t});else{let n=this.cachedEventQueue.get(e);n||(n=new _t,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},$={};Xe($,{None:()=>St,filter:()=>xt,once:()=>ge,toPromise:()=>vt});var St=()=>{console.log("[Jolibox SDK] None Event")};function vt(e){return new Promise(t=>ge(e)(t))}function ge(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function xt(e,t){return(r=>{let n,s={onWillAddFirstListener(){n=r(o.fire,o)}},o=new x(s);return o.event})((r,n=null)=>e(s=>t(s)&&r.call(n,s),null))}var B=Symbol.for("Jolibox.hostEmitter"),Rt=()=>{let e=new Q;return globalThis[B]||(globalThis[B]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[B]},Ee=Rt();function It(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)bt(e[n],t[n])}function bt(e,t){if(H(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(tt(t)){try{if(e instanceof t)return}catch{}if(!et(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("[Jolibox SDK]argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}var L=class{constructor(){this._commands=new Map,this._onDidRegisterCommand=new x,this.onDidRegisterCommand=this._onDidRegisterCommand.event,console.log("[Jolibox SDK] command registry")}registerCommand(e){if(!e)throw new Error("invalid command");if(e.metadata&&Array.isArray(e.metadata.args)){let r=[];for(let s of e.metadata.args)r.push(s.constraint);let n=e.handler;e.handler=function(...s){return It(s,r),n(...s)}}let{id:t}=e;this._commands.get(t)&&console.info(`[Jolibox SDK] duplicated command is registered ${t}`),this._commands.set(t,e),this._onDidRegisterCommand.fire(t)}getCommand(e){return this._commands.get(e)}getCommands(){let e=new Map;for(let t of this._commands.keys()){let r=this.getCommand(t);r&&e.set(t,r)}return e}};L=ie([ce],L);var G=class{constructor(){this._onWillExecuteCommand=new x,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new x,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new L,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=qe(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),$.toPromise($.filter(this.registry.onDidRegisterCommand,r=>r===e))])]),this._tryExecuteCommand(e,t))}executeCommandThowErr(e,...t){if(!this.registry.getCommand(e))throw new Error(`command '${e}' not found`);let r=this.registry.getCommand(e);this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),n}_tryExecuteCommand(e,t){let r=this.registry.getCommand(e);if(!r)return Promise.reject(new Error(`command '${e}' not found`));try{this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),Promise.resolve(n)}catch(n){return Promise.reject(n)}}invokeFunction(e,...t){let r=!1;try{return e(...t)}finally{r=!0}}};G=ie([ce],G);var V=Symbol.for("Jolibox.commands");function g(){if(globalThis[V])return globalThis[V];let e=new L,t=new G,r={registerCommand(n,s,o){e.registerCommand({id:n,handler:s,metadata:o})},executeCommand(n,...s){return t.executeCommand(n,...s)},excuteCommandSync(n,...s){return t.executeCommandThowErr(n,...s)}};return globalThis[V]=r,r}var O=new URLSearchParams(window.location.search).get("joliboxEnv")==="staging";function Tt(){let e=new URLSearchParams(window.location.search),t={};return e.forEach((r,n)=>{t[n]=r}),{name:"GamePage",params:t}}function At(){return{platform:1e3,os:"h5",appVersion:"1.1.5",appId:"1",model:"UnknownModel",brand:"UnknownBrand",uuid:"1",jsSdkVersion:"1.1.5",extra:{}}}var _e={default:{test:"https://stg-collect.jolibox.com",prod:"https://collect.jolibox.com"},"oss.jolibox.com":{test:"https://stg-collect.jolibox.com",prod:"https://collect.jolibox.com"},"oss.pico-game.com":{test:"https://stg-collect.pico-game.com",prod:"https://collect.pico-game.com"}},wt=()=>{let e=_e[window.location.host]??_e.default;return O?e.test:e.prod},Dt=wt(),ye=e=>{let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};AbortSignal.timeout??=ye;var Ut=()=>new URLSearchParams(window.location.search).get("joliSource")??null,Lt=Ut(),Ot=async e=>{let r=`${Dt}/report`,n=he("1.1.5"),s=Lt,o={"Content-Type":"application/json"};return n&&(o["x-user-agent"]=n),s&&(o["x-joli-source"]=s),await fetch(r,{method:"POST",headers:o,body:JSON.stringify(e),signal:ye(5e3)})};async function E(e){let t={name:"globalJsError",type:z.ErrorTrace,location:Tt(),target:null,extra:e,timestamp:Date.now(),userId:null},r=At(),s={protocolVersion:"1.0.0",events:[t],device:r,project:Y.WebSDK},o=pe(s);Ot(o)}document.addEventListener("DOMContentLoaded",()=>Ee.emit("onDocumentReady",R.startTime));var kt=()=>{let e=0;return{set startTime(t){e=t},get startTime(){return e}}},R=kt(),Se=g(),X=e=>{Se.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`),E({err:JSON.stringify({message:t.message,source:t.source,lineno:t.lineno,colno:t.colno,error:t.error})})})},q=X;window.addEventListener("unhandledrejection",X.bind(void 0));window.addEventListener("error",X.bind(void 0));window.onerror=(e,t,r,n,s)=>{Se.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})}}).catch(o=>{E({err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})})})};var Z=e=>{let t=e.split("-")[1];t&&(e=e.replace(`-${t}`,""));let r=e.split("+")[1];r&&(e=e.replace(`+${r}`,""));let n=e.split(".").slice(0,3),[s,o,i]=[n[0]??"0",n[1]??"0",n[2]??"0"];return{major:s,minor:o,patch:i,prerelease:t,build:r}},I=e=>parseInt(Z(e).major,10),b=(e,t)=>{let{major:r,minor:n,patch:s,prerelease:o}=Z(e),{major:i,minor:m,patch:d,prerelease:a}=Z(t);return r!==i?r>i?1:-1:n!==m?n>m?1:-1:s!==d?s>d?1:-1:o&&!a?-1:!o&&a?1:o&&a?o>a?1:o<a?-1:0:0};var ve=g(),k=(e,t)=>{ve.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},_=(e,t,r)=>{ve.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var Ie="jolibox-sdk-loadermeta",T=JSON.parse(localStorage.getItem(Ie)??"{}"),ee=Date.now(),xe=(e,t)=>e>t&&Math.abs(e-t)/(1e3*60*60*24)>=7,Re=e=>!/^(Failed to fetch version|Couldn't find the requested file)/.test(e);async function Ct(){let t=`${O?"https://stg-api.jolibox.com":"https://api.jolibox.com"}/api/fe-configs/js-sdk/version-metadata`;try{let r=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}}),{implement_version:n,bootstrap_version:s}=await r.json(),o={...T,timestamp:ee};if(s){let{bootstrap_version:i}=T;if(!(i&&b(i,s)>=0)){let m=await(await fetch(te(s))).text();Re(m)&&(o={...o,bootstrap_version:s,bootstrap_script:m})}}if(n){let{implement_version:i}=T;if(!(i&&b(i,n)>=0)){let m=await(await fetch(re(n))).text();Re(m)&&(o={...o,implement_version:n,implement_script:m})}}localStorage.setItem(Ie,JSON.stringify(o))}catch(r){console.warn("Failed to fetch loader metadata: ",r)}}var be=e=>{let{currentMajorVersion:t,currentVersion:r,bootstrapUrl:n,implementUrl:s}=e;function o(){let{bootstrap_version:a,bootstrap_script:f,timestamp:h}=T;if(a&&f&&h&&!xe(ee,h)&&I(a)==t&&b(a,r)>=0)return{script:f,type:"localscript"};try{let l=new XMLHttpRequest;return l.open("GET",n,!1),l.send(),{script:l.responseText,type:"fetch_from_cdn"}}catch(l){let u=new le(`Bootstrap module faile to fetch ${l}`);E({err:`${u}`})}}function i(){let a=Date.now();k("jsSdkBegin",{t:a}),R.startTime=a;let{script:f,type:h}=o()??{};if(f){let l=document.createElement("script");l.type="text/javascript",l.innerHTML=f,document.head.appendChild(l),_("bootstrapModuleLoaded",Date.now()-a,{type:h})}}function m(a){(async h=>{try{let l=new Blob([h],{type:"application/javascript"}),u=URL.createObjectURL(l),Ve=await import(u);return URL.revokeObjectURL(u),Ve}catch(l){let u=new S(`implement module evaluate error in h5:${l} `);E({err:`${u}`})}})(a)}function d(){let a=Date.now(),{implement_script:f,implement_version:h,timestamp:l}=T;if(f&&h&&l&&!xe(ee,l)&&I(h)==t&&b(h,r)>=0){m(f),_("implementModuleLoaded",Date.now()-a,{type:"loadscript"});return}let u=document.createElement("script");u.type="module",u.crossOrigin="anonymous",u.src=s,u.onload=()=>{_("implementModuleLoaded",Date.now()-a,{type:"fetch_from_cdn"})},document.head.appendChild(u)}return()=>{try{i(),d(),Ct()}catch(a){let f=new S(`module evaluate error: ${a}`);E({err:`${f}`})}}};var Te=(e,t)=>{let r=s=>{let o=e({path:s});if(!o)throw`module ${s} load failed ${o}`;return o};function n(s){(async i=>{try{let m=new Blob([i],{type:"application/javascript"}),d=URL.createObjectURL(m),a=await import(d);return URL.revokeObjectURL(d),a}catch(m){q(new S(`implement module evaluate error in native:${m} `))}})(s)}return()=>{try{let s=Date.now();k("jsSdkBegin",{t:s}),R.startTime=s;let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),_("bootstrapModuleLoaded",Date.now()-s,{type:"native"});let m=Date.now(),d=r(t.implementUrl);n(d),_("implementModuleLoaded",Date.now()-m,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),q(new S(`module load failed ${s}`))}}};var Pt="1.1.5",C=Pt,De=I(C),Ue=window.JoliAndroidSDKBridge?e=>{let t=window.prompt("invoke",JSON.stringify({event:"loadScriptSync",paramsString:JSON.stringify(e)}));if(t){let{data:r}=JSON.parse(t);return r}}:void 0,Kt=typeof Ue<"u",te=e=>`https://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,re=e=>`https://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,Mt=e=>/^\d+\.\d+\.\d+$/.test(e),Le=Mt(C)?De:C,Ae=te(Le),we=re(Le);function Nt(){Kt?Te(Ue,{bootstrapUrl:Ae,implementUrl:we})():be({bootstrapUrl:Ae,implementUrl:we,currentMajorVersion:De,currentVersion:C})()}Nt();var Oe=g();function ke(){return Oe.excuteCommandSync("API.getSystemInfoSync")}function Ce(){return Oe.excuteCommandSync("API.env")}function Pe(e,t){return ue.config[e]?.[t]}function Ke(e,t,r){let n=Array.isArray(t)?t:t.replace(/\[(\d+)\]/g,".$1").split("."),s=e;for(let o of n)if(s&&(typeof s=="object"||Array.isArray(s)))s=s[o];else return r;return s===void 0?r:s}var Ne="1.1.5";function y(e){let r=Ce().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=Pe(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||W(Ne,i,"<")?!1:s.length===0?!0:Me(o,s)||Me(o.properties,s)}function Me(e,t){if(!e)return!1;let r=Ke(e,t);return r?ae(r)?!0:H(r)?W(Ne,r,">="):!1:!1}var je=g();async function Je(){return y("login")?await je.executeCommand("API.login"):{code:"FAILURE",message:"[Jolibox SDK]login is not supported in this platform"}}async function Fe(){return y("checkSession")?await je.executeCommand("API.checkSession"):{code:"FAILURE",message:"[Jolibox SDK]checkSession is not supported in this platform"}}var ne=class{constructor(){this.loadFinished=()=>{let t=new Event("JOLIBOX_RUNTIME_LOAD_FINISHED");window.dispatchEvent(t)};this.notifyLoadProgress=t=>{let r=Math.ceil(t),n=new CustomEvent("JOLIBOX_RUNTIME_LOAD_PROGRESS",{detail:r});window.dispatchEvent(n)}}},Be=window.JoliboxRuntime||ne;var p=class{constructor(){this.commands=g();this._emitter=new Q}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return y(t)}canIUseIfThrow(t){if(!this.canUse(t))return{code:"FAILURE",message:`[Jolibox SDK] ${t} is not supported in this platform`}}};var jt="LifecycleSDK.onReady",P=class extends p{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(jt,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exit(t){let r=this.canIUseIfThrow("lifeCycle.exit");if(r)return r;this.commands.executeCommand("LifecycleSDK.exit",t.onBeforeExit)}onJoliboxHide(t){this.commands.executeCommand("LifecycleSDK.onJoliboxHide",t.bind(this))}onJoliboxShow(t){this.commands.executeCommand("LifecycleSDK.onJoliboxShow",t.bind(this))}};var K=class extends p{async getItem(t){return await this.commands.executeCommand("StorageSDK.getItem",t)}async setItem(t,r){if(t.length>128)return{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key should be less than 128"};let n=typeof r=="string"?r:String(r);return t.length+n.length>1024?{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key and value should be less than 1024"}:await this.commands.executeCommand("StorageSDK.setItem",t,r)}async removeItem(t){return this.commands.executeCommand("StorageSDK.removeItem",t)}async clear(){return this.commands.executeCommand("StorageSDK.clear")}};var M=class extends p{constructor(){super();this.init=r=>{this.commands.executeCommand("AdsSDK.init",r)};this.adConfig=r=>{this.commands.executeCommand("AdsSDK.adConfig",r)};this.adBreak=r=>{this.commands.executeCommand("AdsSDK.adBreak",r)};this.adUnit=r=>{this.commands.executeCommand("AdsSDK.adUnit",r)}}};var N=class extends p{showKeyboard(t){let r=this.canIUseIfThrow("keyboard.showKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){let r=this.canIUseIfThrow("keyboard.updateKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.updateKeyboard",{value:t})}hideKeyboard(){let t=this.canIUseIfThrow("keyboard.hideKeyboard");if(t)return t;this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var j=class extends p{async onLevelFinished(t,r,n){let s=this.canIUseIfThrow("TaskTrackerSDK.onLevelFinished");return s?Promise.resolve(s):await this.commands.executeCommand("TaskTrackerSDK.levelFinished",t,{result:r,duration:n})}async onTaskFinished(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskFinished");return n||await this.commands.executeCommand("TaskTrackerSDK.taskFinished",t,{duration:r})}async onTaskEvent(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskEvent");return n||await this.commands.executeCommand("TaskTrackerSDK.taskEvent",t,r)}async onLevelUpgrade(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onLevelUpgrade");return n||await this.commands.executeCommand("TaskTrackerSDK.levelUpgrade",t,r)}async onHistoryUserLevel(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserLevel");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserLevel",t)}async onHistoryUserScore(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserScore");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserScore",t)}};var J=class{constructor(){this.jssdkVersion="1.1.5";this.runtime=new Be;this.ads=new M;this.lifecycle=new P;this.storage=new K;this.keyboard=new N;this.task=new j;this.getSystemInfoSync=ke.bind(this);this.canIUse=y.bind(this);this.login=Je.bind(this);this.checkSession=Fe.bind(this)}};window.JoliboxSDK=J;
package/dist/index.d.ts CHANGED
@@ -20,7 +20,10 @@ declare global {
20
20
  }
21
21
  export declare class JoliboxSDK {
22
22
  readonly jssdkVersion = "__JOLIBOX_LOCAL_SDK_VERSION__";
23
- readonly runtime: any;
23
+ readonly runtime: {
24
+ loadFinished: () => void;
25
+ notifyLoadProgress: (progress: number) => void;
26
+ };
24
27
  readonly ads: JoliboxAds;
25
28
  readonly lifecycle: LifecycleSDK;
26
29
  readonly storage: StorageSDK;
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- var Y=Object.defineProperty,Ae=Object.getOwnPropertyDescriptor,De=(e,t)=>{for(var r in t)Y(e,r,{get:t[r],enumerable:!0})},X=(e,t,r,n)=>{for(var s=n>1?void 0:n?Ae(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&Y(t,r,s),s};function Ce(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function F(e){return typeof e=="string"}function q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function ke(e){return typeof e>"u"}function Oe(e){return ke(e)||e===null}function Ke(e){return typeof e=="function"}function Z(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}var Me=(e=>(e[e.DEVELOPER_FILE_NOT_FOUND=0]="DEVELOPER_FILE_NOT_FOUND",e[e.INTERNAL_IOS_CAN_NOT_FOUND_PKG=1]="INTERNAL_IOS_CAN_NOT_FOUND_PKG",e[e.USER_IOS_LOAD_TIMEOUT=2]="USER_IOS_LOAD_TIMEOUT",e[e.INTERNAL_IOS_PKG_LOAD_ERROR=3]="INTERNAL_IOS_PKG_LOAD_ERROR",e[e.INTERNAL_IOS_PKG_PARSE_FAIL=4]="INTERNAL_IOS_PKG_PARSE_FAIL",e[e.USER_IOS_GET_EMPTY_DATA=5]="USER_IOS_GET_EMPTY_DATA",e[e.USER_ANDROID_GET_PKG_FAIL=6]="USER_ANDROID_GET_PKG_FAIL",e[e.DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE=7]="DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE",e))(Me||{}),Ne=class extends Error{constructor(e){if(typeof e=="string"){super(e),this.priority="P1";return}super(e.message),this.priority="P1",this.stack=e.stack,this.raw=e}},ee=class extends Ne{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}};var te=class extends ee{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_FETCH_ERROR",this.priority="P0"}},R=class extends ee{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function S(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var Pe={log:S("log"),warn:S("warn"),info:S("info"),error:S("error"),debug:S("debug")};Object.assign(globalThis,{logger:Pe});var re=Symbol.for("Jolibox.canIUseMap"),je={};globalThis[re]=je;var ne={get config(){return globalThis[re]}};function B(e,t,r){let n=0;if(e!==t){let s=e.split("."),o=t.split("."),i=Math.max(s.length,o.length);for(let l=0;l<i;l++){let g=parseInt(s[l],10)||0,c=parseInt(o[l],10)||0;if(g>c){n=1;break}else if(g<c){n=-1;break}}}if(!r)return n;switch(r){case">":return n>0;case"<":return n<0;case"=":return n===0;case">=":return n>=0;case"<=":return n<=0;default:return!1}}var a=class U{static{this.Undefined=new U(void 0)}constructor(t){this.element=t,this.next=U.Undefined,this.prev=U.Undefined}},Je=class{constructor(){this._first=a.Undefined,this._last=a.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===a.Undefined}clear(){let e=this._first;for(;e!==a.Undefined;){let t=e.next;e.prev=a.Undefined,e.next=a.Undefined,e=t}this._first=a.Undefined,this._last=a.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let r=new a(e);if(this._first===a.Undefined)this._first=r,this._last=r;else if(t){let s=this._last;this._last=r,r.prev=s,s.next=r}else{let s=this._first;this._first=r,r.next=s,s.prev=r}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(r))}}shift(){if(this._first!==a.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==a.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==a.Undefined&&e.next!==a.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===a.Undefined&&e.next===a.Undefined?(this._first=a.Undefined,this._last=a.Undefined):e.next===a.Undefined?(this._last=this._last.prev,this._last.next=a.Undefined):e.prev===a.Undefined&&(this._first=this._first.next,this._first.prev=a.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==a.Undefined;)yield e.element,e=e.next}},Fe=0,w=class{constructor(e){this.value=e,this.id=Fe++}},v=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof w&&(this._listeners=[this._listeners]),this._listeners=this._listeners.filter(t=>t?.value===e)):(this._listeners=void 0,this._size=0)),this.options?.onDidRemoveLastListener?.())}get event(){return this._event??=(e,t)=>{if(this._disposed)return()=>{console.info("[Jolibox SDK] Emitter is _disposed")};t&&(e=e.bind(t));let r=new w(e);this._listeners?this._listeners instanceof w?this._listeners=[this._listeners,r]:this._listeners.push(r):(this.options?.onWillAddFirstListener?.(this),this._listeners=r,this.options?.onDidFirstListener?.(this)),this.options?.onDidAddListener?.(this),this._size++},this._event}_deliver(e,t){if(!e)return;let r=this.options?.onListenerError||Error.constructor;if(!r){e.value(t);return}try{e.value(t)}catch(n){r(n)}}fire(e){this._listeners&&(this._listeners instanceof w?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},V=class{constructor(){this.listeners=new Map,this.listerHandlerMap=new WeakMap,this.cachedEventQueue=new Map}on(e,t){let r=this.listeners.get(e)??new v,n=o=>t(...o.args);this.listerHandlerMap.set(t,n),r.event(n),this.listeners.set(e,r);let s=this.cachedEventQueue.get(e);if(s)for(;s.size>0;)r.fire({event:e,...s.shift()})}off(e,t){let r=this.listeners.get(e);if(r){let n=this.listerHandlerMap.get(t);r.dispose(n)}}emit(e,...t){let r=this.listeners.get(e);if(r)r.fire({event:e,args:t});else{let n=this.cachedEventQueue.get(e);n||(n=new Je,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},j={};De(j,{None:()=>Be,filter:()=>$e,once:()=>se,toPromise:()=>Ve});var Be=()=>{console.log("[Jolibox SDK] None Event")};function Ve(e){return new Promise(t=>se(e)(t))}function se(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function $e(e,t){return(r=>{let n,s={onWillAddFirstListener(){n=r(o.fire,o)}},o=new v(s);return o.event})((r,n=null)=>e(s=>t(s)&&r.call(n,s),null))}var N=Symbol.for("Jolibox.hostEmitter"),He=()=>{let e=new V;return globalThis[N]||(globalThis[N]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[N]},oe=He();function Ge(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)ze(e[n],t[n])}function ze(e,t){if(F(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(Ke(t)){try{if(e instanceof t)return}catch{}if(!Oe(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("[Jolibox SDK]argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}var L=class{constructor(){this._commands=new Map,this._onDidRegisterCommand=new v,this.onDidRegisterCommand=this._onDidRegisterCommand.event,console.log("[Jolibox SDK] command registry")}registerCommand(e){if(!e)throw new Error("invalid command");if(e.metadata&&Array.isArray(e.metadata.args)){let r=[];for(let s of e.metadata.args)r.push(s.constraint);let n=e.handler;e.handler=function(...s){return Ge(s,r),n(...s)}}let{id:t}=e;this._commands.get(t)&&console.info(`[Jolibox SDK] duplicated command is registered ${t}`),this._commands.set(t,e),this._onDidRegisterCommand.fire(t)}getCommand(e){return this._commands.get(e)}getCommands(){let e=new Map;for(let t of this._commands.keys()){let r=this.getCommand(t);r&&e.set(t,r)}return e}};L=X([Z],L);var J=class{constructor(){this._onWillExecuteCommand=new v,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new v,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new L,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=Ce(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),j.toPromise(j.filter(this.registry.onDidRegisterCommand,r=>r===e))])]),this._tryExecuteCommand(e,t))}executeCommandThowErr(e,...t){if(!this.registry.getCommand(e))throw new Error(`command '${e}' not found`);let r=this.registry.getCommand(e);this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),n}_tryExecuteCommand(e,t){let r=this.registry.getCommand(e);if(!r)return Promise.reject(new Error(`command '${e}' not found`));try{this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),Promise.resolve(n)}catch(n){return Promise.reject(n)}}invokeFunction(e,...t){let r=!1;try{return e(...t)}finally{r=!0}}};J=X([Z],J);var P=Symbol.for("Jolibox.commands");function p(){if(globalThis[P])return globalThis[P];let e=new L,t=new J,r={registerCommand(n,s,o){e.registerCommand({id:n,handler:s,metadata:o})},executeCommand(n,...s){return t.executeCommand(n,...s)},excuteCommandSync(n,...s){return t.executeCommandThowErr(n,...s)}};return globalThis[P]=r,r}document.addEventListener("DOMContentLoaded",()=>oe.emit("onDocumentReady",b.startTime));var We=()=>{let e=0;return{set startTime(t){e=t},get startTime(){return e}}},b=We(),ie=p(),$=e=>{ie.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`)})},E=$;window.addEventListener("unhandledrejection",$.bind(void 0));window.addEventListener("error",$.bind(void 0));window.onerror=(e,t,r,n,s)=>{ie.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})}}).catch(o=>{console.error(`Fallback report: ${o} ${JSON.stringify(e)}`)})};var H=e=>{let t=e.split("-")[1];t&&(e=e.replace(`-${t}`,""));let r=e.split("+")[1];r&&(e=e.replace(`+${r}`,""));let n=e.split(".").slice(0,3),[s,o,i]=[n[0]??"0",n[1]??"0",n[2]??"0"];return{major:s,minor:o,patch:i,prerelease:t,build:r}},x=e=>parseInt(H(e).major,10),I=(e,t)=>{let{major:r,minor:n,patch:s}=H(e),{major:o,minor:i,patch:l}=H(t);return r!==o?r>o?1:-1:n!==i?n>i?1:-1:s!==l?s>l?1:-1:0};var ae=p(),A=(e,t)=>{ae.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},_=(e,t,r)=>{ae.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var le="jolibox-sdk-loadermeta",T=JSON.parse(localStorage.getItem(le)??"{}"),G=Date.now(),ce=(e,t)=>e>t&&Math.abs(e-t)/(1e3*60*60*24)>=7,me=e=>!/^(Failed to fetch version|Couldn't find the requested file)/.test(e);async function Qe(){let e="https://stg-api.jolibox.com/api/fe-configs/js-sdk/version_metadata";try{let t=await fetch(e,{method:"GET",headers:{"Content-Type":"application/json"}}),{implement_version:r,bootstrap_version:n}=await t.json(),s={...T,timestamp:G};if(n){let{bootstrap_version:o}=T;if(!(o&&I(o,n))){let i=await(await fetch(z(n))).text();me(i)&&(s={...s,bootstrap_version:n,bootstrap_script:i})}}if(r){let{implement_version:o}=T;if(!(o&&I(o,r))){let i=await(await fetch(W(r))).text();me(i)&&(s={...s,implement_version:r,implement_script:i})}}localStorage.setItem(le,JSON.stringify(s))}catch(t){console.warn("Failed to fetch loader metadata: ",t)}}var de=e=>{let{currentMajorVersion:t,currentVersion:r,bootstrapUrl:n,implementUrl:s}=e;function o(){let{bootstrap_version:c,bootstrap_script:f,timestamp:u}=T;if(c&&f&&u&&!ce(G,u)&&x(c)==t&&I(c,r)>0)return{script:f,type:"localscript"};try{let m=new XMLHttpRequest;return m.open("GET",n,!1),m.send(),{script:m.responseText,type:"fetch_from_cdn"}}catch(m){E(new te(`Bootstrap module faile to fetch ${m}`))}}function i(){let c=Date.now();A("jsSdkBegin",{t:c}),b.startTime=c;let{script:f,type:u}=o()??{};if(f){let m=document.createElement("script");m.type="text/javascript",m.innerHTML=f,document.head.appendChild(m),_("bootstrapModuleLoaded",Date.now()-c,{type:u})}}function l(c){(async u=>{try{let m=new Blob([u],{type:"application/javascript"}),h=URL.createObjectURL(m),Le=await import(h);return URL.revokeObjectURL(h),Le}catch(m){E(new R(`implement module evaluate error in h5:${m} `))}})(c)}function g(){let c=Date.now(),{implement_script:f,implement_version:u,timestamp:m}=T;if(f&&u&&m&&!ce(G,m)&&x(u)==t&&I(u,r)>0){l(f),_("implementModuleLoaded",Date.now()-c,{type:"loadscript"});return}let h=document.createElement("script");h.type="module",h.crossOrigin="anonymous",h.src=s,h.onload=()=>{_("bootstrapModuleLoaded",Date.now()-c,{type:"fetch_from_cdn"})},document.head.appendChild(h)}return()=>{try{i(),g(),Qe()}catch(c){E(new R(`module evaluate error: ${c}`))}}};var ue=(e,t)=>{let r=s=>{let o=e({path:s});if(!o)throw`module ${s} load failed ${o}`;return o};function n(s){(async i=>{try{let l=new Blob([i],{type:"application/javascript"}),g=URL.createObjectURL(l),c=await import(g);return URL.revokeObjectURL(g),c}catch(l){E(new R(`implement module evaluate error in native:${l} `))}})(s)}return()=>{try{let s=Date.now();A("jsSdkBegin",{t:s}),b.startTime=s;let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),_("implementModuleLoaded",Date.now()-s,{type:"native"});let l=r(t.implementUrl);n(l),_("bootstrapModuleLoaded",Date.now()-s,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),E(new R(`module load failed ${s}`))}}};var Ye="1.1.4-beta.9",D=Ye,he=x(D),ge=window.webkit||window.JoliAndroidSDKBridge?e=>{let t=window.prompt("invoke",JSON.stringify({event:"loadScriptSync",paramsString:JSON.stringify(e)}));if(t){let{data:r}=JSON.parse(t);return r}}:void 0,Xe=typeof ge<"u",z=e=>`https://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,W=e=>`https://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,qe=e=>/^\d+\.\d+\.\d+$/.test(e),Ee=qe(D)?he:D,pe=z(Ee),fe=W(Ee);function Ze(){Xe?ue(ge,{bootstrapUrl:pe,implementUrl:fe})():de({bootstrapUrl:pe,implementUrl:fe,currentMajorVersion:he,currentVersion:D})()}Ze();var _e=p();function ye(){return _e.excuteCommandSync("API.getSystemInfoSync")}function Re(){return _e.excuteCommandSync("API.env")}function Se(e,t){return ne.config[e]?.[t]}function ve(e,t,r){let n=Array.isArray(t)?t:t.replace(/\[(\d+)\]/g,".$1").split("."),s=e;for(let o of n)if(s&&(typeof s=="object"||Array.isArray(s)))s=s[o];else return r;return s===void 0?r:s}var xe="1.1.4-beta.9";function y(e){let r=Re().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=Se(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||B(xe,i,"<")?!1:s.length===0?!0:be(o,s)||be(o.properties,s)}function be(e,t){if(!e)return!1;let r=ve(e,t);return r?q(r)?!0:F(r)?B(xe,r,">="):!1:!1}var Ie=p();async function Te(){return y("login")?await Ie.executeCommand("API.login"):{code:"FAILURE",message:"[Jolibox SDK]login is not supported in this platform"}}async function we(){return y("checkSession")?await Ie.executeCommand("API.checkSession"):{code:"FAILURE",message:"[Jolibox SDK]checkSession is not supported in this platform"}}var Ue=window.JoliboxRuntime;var d=class{constructor(){this.commands=p();this._emitter=new V}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return y(t)}canIUseIfThrow(t){if(!this.canUse(t))return{code:"FAILURE",message:`[Jolibox SDK] ${t} is not supported in this platform`}}};var et="LifecycleSDK.onReady",C=class extends d{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(et,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exit(t){let r=this.canIUseIfThrow("lifeCycle.exit");if(r)return r;this.commands.executeCommand("LifecycleSDK.exit",t.onBeforeExit)}onJoliboxHide(t){this.commands.executeCommand("LifecycleSDK.onJoliboxHide",t.bind(this))}onJoliboxShow(t){this.commands.executeCommand("LifecycleSDK.onJoliboxShow",t.bind(this))}};var k=class extends d{async getItem(t){return await this.commands.executeCommand("StorageSDK.getItem",t)}async setItem(t,r){if(t.length>128)return{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key should be less than 128"};let n=typeof r=="string"?r:String(r);return t.length+n.length>1024?{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key and value should be less than 1024"}:await this.commands.executeCommand("StorageSDK.setItem",t,r)}async removeItem(t){return this.commands.executeCommand("StorageSDK.removeItem",t)}async clear(){return this.commands.executeCommand("StorageSDK.clear")}};var O=class extends d{constructor(){super();this.init=r=>{this.commands.executeCommand("AdsSDK.init",r)};this.adConfig=r=>{this.commands.executeCommand("AdsSDK.adConfig",r)};this.adBreak=r=>{this.commands.executeCommand("AdsSDK.adBreak",r)};this.adUnit=r=>{this.commands.executeCommand("AdsSDK.adUnit",r)}}};var K=class extends d{showKeyboard(t){let r=this.canIUseIfThrow("keyboard.showKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){let r=this.canIUseIfThrow("keyboard.updateKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.updateKeyboard",t)}hideKeyboard(){let t=this.canIUseIfThrow("keyboard.hideKeyboard");if(t)return t;this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var M=class extends d{async onLevelFinished(t,r,n){let s=this.canIUseIfThrow("TaskTrackerSDK.onLevelFinished");return s?Promise.resolve(s):await this.commands.executeCommand("TaskTrackerSDK.levelFinished",t,{result:r,duration:n})}async onTaskFinished(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskFinished");return n||await this.commands.executeCommand("TaskTrackerSDK.taskFinished",t,{duration:r})}async onTaskEvent(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskEvent");return n||await this.commands.executeCommand("TaskTrackerSDK.taskEvent",t,r)}async onLevelUpgrade(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onLevelUpgrade");return n||await this.commands.executeCommand("TaskTrackerSDK.levelUpgrade",t,r)}async onHistoryUserLevel(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserLevel");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserLevel",t)}async onHistoryUserScore(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserScore");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserScore",t)}};var Q=class{constructor(){this.jssdkVersion="1.1.4-beta.9";this.runtime=new Ue;this.ads=new O;this.lifecycle=new C;this.storage=new k;this.keyboard=new K;this.task=new M;this.getSystemInfoSync=ye.bind(this);this.canIUse=y.bind(this);this.login=Te.bind(this);this.checkSession=we.bind(this)}};window.JoliboxSDK=Q;export{Q as JoliboxSDK};
1
+ var se=Object.defineProperty,Ve=Object.getOwnPropertyDescriptor,$e=(e,t)=>{for(var r in t)se(e,r,{get:t[r],enumerable:!0})},oe=(e,t,r,n)=>{for(var s=n>1?void 0:n?Ve(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&se(t,r,s),s};function Ge(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function $(e){return typeof e=="string"}function ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function He(e){return typeof e>"u"}function We(e){return He(e)||e===null}function ze(e){return typeof e=="function"}function ae(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}var Ye=(e=>(e[e.DEVELOPER_FILE_NOT_FOUND=0]="DEVELOPER_FILE_NOT_FOUND",e[e.INTERNAL_IOS_CAN_NOT_FOUND_PKG=1]="INTERNAL_IOS_CAN_NOT_FOUND_PKG",e[e.USER_IOS_LOAD_TIMEOUT=2]="USER_IOS_LOAD_TIMEOUT",e[e.INTERNAL_IOS_PKG_LOAD_ERROR=3]="INTERNAL_IOS_PKG_LOAD_ERROR",e[e.INTERNAL_IOS_PKG_PARSE_FAIL=4]="INTERNAL_IOS_PKG_PARSE_FAIL",e[e.USER_IOS_GET_EMPTY_DATA=5]="USER_IOS_GET_EMPTY_DATA",e[e.USER_ANDROID_GET_PKG_FAIL=6]="USER_ANDROID_GET_PKG_FAIL",e[e.DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE=7]="DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE",e))(Ye||{}),Qe=class extends Error{constructor(e){if(typeof e=="string"){super(e),this.priority="P1";return}super(e.message),this.priority="P1",this.stack=e.stack,this.raw=e}},ce=class extends Qe{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}};var me=class extends ce{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_FETCH_ERROR",this.priority="P0"}},S=class extends ce{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function v(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var Xe={log:v("log"),warn:v("warn"),info:v("info"),error:v("error"),debug:v("debug")};Object.assign(globalThis,{logger:Xe});var le=Symbol.for("Jolibox.canIUseMap"),qe={};globalThis[le]=qe;var de={get config(){return globalThis[le]}};function G(e,t,r){let n=0;if(e!==t){let s=e.split("."),o=t.split("."),i=Math.max(s.length,o.length);for(let m=0;m<i;m++){let d=parseInt(s[m],10)||0,a=parseInt(o[m],10)||0;if(d>a){n=1;break}else if(d<a){n=-1;break}}}if(!r)return n;switch(r){case">":return n>0;case"<":return n<0;case"=":return n===0;case">=":return n>=0;case"<=":return n<=0;default:return!1}}var H=(e=>(e[e.System=1e3]="System",e[e.ErrorTrace=1001]="ErrorTrace",e[e.UserDefined=1002]="UserDefined",e))(H||{}),W=(e=>(e.MiniGame="mini-game",e.MiniDrama="mini-drama",e.App="app",e.WebSDK="web-sdk",e.AppSDK="app-sdk",e))(W||{}),Ze=(e=>(e[e.App=0]="App",e[e.H5=1]="H5",e[e.Weapp=2]="Weapp",e[e.Alipay=3]="Alipay",e[e.Gcash=4]="Gcash",e[e.Dana=5]="Dana",e[e.Umma=6]="Umma",e[e.WebSDK=1e3]="WebSDK",e[e.AppSDK=1001]="AppSDK",e[e.Other=9999]="Other",e))(Ze||{}),ne=["name","params"],et=["name","type","location","target","extra","timestamp","userId"],tt=["platform","os","appVersion","appId","model","brand","uuid","jsSdkVersion","extra"];function D(e,t){return t.map(r=>{if(r==="params"&&e[r]){let n=e[r];return Object.keys(n).reduce((s,o)=>(s[o]=String(n[o]),s),{})}return e[r]})}function rt(e){let t=e.location?D(e.location,ne):null,r=e.target?D(e.target,ne):null;return D({...e,location:t,target:r},et)}function ue(e){let t=e.events.map(n=>rt(n)),r=D(e.device,tt);return[e.protocolVersion,t,r,e.project]}var nt=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)});var A={isiOS:navigator.userAgent.includes("iPhone")||navigator.userAgent.includes("iPod")||navigator.userAgent.includes("iPad")||navigator.userAgent.includes("iPhone OS"),iosVersion:()=>{let e=navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);return[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3]||"0",10)]},isAndroid:navigator.userAgent.includes("Android"),isMac:navigator.userAgent.includes("Mac"),isFacebook:navigator.userAgent.includes("FB_IAB"),isPC:!navigator.userAgent.includes("iPhone")&&!navigator.userAgent.includes("Android")},st=()=>A.isiOS?"iOS":A.isAndroid?"Android":A.isMac?"Mac":A.isFacebook?"Facebook":"PC",ot="device_id",it="advertising_id",pe=e=>(localStorage.getItem(e)||localStorage.setItem(e,nt()),localStorage.getItem(e)),at=()=>pe(ot),ct=()=>pe(it),mt=e=>e.charAt(0).toUpperCase()+e.slice(1),lt=()=>{let e=new URLSearchParams(window.location.search);return mt(e.get("utm_source")??"")||"JoliboxSDK"},fe=e=>{let t="JoliboxWebSDK",r=st(),n=navigator.language,s=at(),o=ct();return`${t} (${lt()}${r}; UnknownModel; UnknownSystemVersion; ${n}) uuid/${s} adid/${o} version/${e||""}`},c=class U{static{this.Undefined=new U(void 0)}constructor(t){this.element=t,this.next=U.Undefined,this.prev=U.Undefined}},dt=class{constructor(){this._first=c.Undefined,this._last=c.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===c.Undefined}clear(){let e=this._first;for(;e!==c.Undefined;){let t=e.next;e.prev=c.Undefined,e.next=c.Undefined,e=t}this._first=c.Undefined,this._last=c.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let r=new c(e);if(this._first===c.Undefined)this._first=r,this._last=r;else if(t){let s=this._last;this._last=r,r.prev=s,s.next=r}else{let s=this._first;this._first=r,r.next=s,s.prev=r}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(r))}}shift(){if(this._first!==c.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==c.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==c.Undefined&&e.next!==c.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===c.Undefined&&e.next===c.Undefined?(this._first=c.Undefined,this._last=c.Undefined):e.next===c.Undefined?(this._last=this._last.prev,this._last.next=c.Undefined):e.prev===c.Undefined&&(this._first=this._first.next,this._first.prev=c.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==c.Undefined;)yield e.element,e=e.next}},ut=0,w=class{constructor(e){this.value=e,this.id=ut++}},x=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof w&&(this._listeners=[this._listeners]),this._listeners=this._listeners.filter(t=>t?.value===e)):(this._listeners=void 0,this._size=0)),this.options?.onDidRemoveLastListener?.())}get event(){return this._event??=(e,t)=>{if(this._disposed)return()=>{console.info("[Jolibox SDK] Emitter is _disposed")};t&&(e=e.bind(t));let r=new w(e);this._listeners?this._listeners instanceof w?this._listeners=[this._listeners,r]:this._listeners.push(r):(this.options?.onWillAddFirstListener?.(this),this._listeners=r,this.options?.onDidFirstListener?.(this)),this.options?.onDidAddListener?.(this),this._size++},this._event}_deliver(e,t){if(!e)return;let r=this.options?.onListenerError||Error.constructor;if(!r){e.value(t);return}try{e.value(t)}catch(n){r(n)}}fire(e){this._listeners&&(this._listeners instanceof w?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},z=class{constructor(){this.listeners=new Map,this.listerHandlerMap=new WeakMap,this.cachedEventQueue=new Map}on(e,t){let r=this.listeners.get(e)??new x,n=o=>t(...o.args);this.listerHandlerMap.set(t,n),r.event(n),this.listeners.set(e,r);let s=this.cachedEventQueue.get(e);if(s)for(;s.size>0;)r.fire({event:e,...s.shift()})}off(e,t){let r=this.listeners.get(e);if(r){let n=this.listerHandlerMap.get(t);r.dispose(n)}}emit(e,...t){let r=this.listeners.get(e);if(r)r.fire({event:e,args:t});else{let n=this.cachedEventQueue.get(e);n||(n=new dt,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},B={};$e(B,{None:()=>pt,filter:()=>ht,once:()=>he,toPromise:()=>ft});var pt=()=>{console.log("[Jolibox SDK] None Event")};function ft(e){return new Promise(t=>he(e)(t))}function he(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function ht(e,t){return(r=>{let n,s={onWillAddFirstListener(){n=r(o.fire,o)}},o=new x(s);return o.event})((r,n=null)=>e(s=>t(s)&&r.call(n,s),null))}var J=Symbol.for("Jolibox.hostEmitter"),gt=()=>{let e=new z;return globalThis[J]||(globalThis[J]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[J]},ge=gt();function Et(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)_t(e[n],t[n])}function _t(e,t){if($(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(ze(t)){try{if(e instanceof t)return}catch{}if(!We(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("[Jolibox SDK]argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}var L=class{constructor(){this._commands=new Map,this._onDidRegisterCommand=new x,this.onDidRegisterCommand=this._onDidRegisterCommand.event,console.log("[Jolibox SDK] command registry")}registerCommand(e){if(!e)throw new Error("invalid command");if(e.metadata&&Array.isArray(e.metadata.args)){let r=[];for(let s of e.metadata.args)r.push(s.constraint);let n=e.handler;e.handler=function(...s){return Et(s,r),n(...s)}}let{id:t}=e;this._commands.get(t)&&console.info(`[Jolibox SDK] duplicated command is registered ${t}`),this._commands.set(t,e),this._onDidRegisterCommand.fire(t)}getCommand(e){return this._commands.get(e)}getCommands(){let e=new Map;for(let t of this._commands.keys()){let r=this.getCommand(t);r&&e.set(t,r)}return e}};L=oe([ae],L);var V=class{constructor(){this._onWillExecuteCommand=new x,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new x,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new L,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=Ge(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),B.toPromise(B.filter(this.registry.onDidRegisterCommand,r=>r===e))])]),this._tryExecuteCommand(e,t))}executeCommandThowErr(e,...t){if(!this.registry.getCommand(e))throw new Error(`command '${e}' not found`);let r=this.registry.getCommand(e);this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),n}_tryExecuteCommand(e,t){let r=this.registry.getCommand(e);if(!r)return Promise.reject(new Error(`command '${e}' not found`));try{this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),Promise.resolve(n)}catch(n){return Promise.reject(n)}}invokeFunction(e,...t){let r=!1;try{return e(...t)}finally{r=!0}}};V=oe([ae],V);var F=Symbol.for("Jolibox.commands");function g(){if(globalThis[F])return globalThis[F];let e=new L,t=new V,r={registerCommand(n,s,o){e.registerCommand({id:n,handler:s,metadata:o})},executeCommand(n,...s){return t.executeCommand(n,...s)},excuteCommandSync(n,...s){return t.executeCommandThowErr(n,...s)}};return globalThis[F]=r,r}var O=new URLSearchParams(window.location.search).get("joliboxEnv")==="staging";function yt(){let e=new URLSearchParams(window.location.search),t={};return e.forEach((r,n)=>{t[n]=r}),{name:"GamePage",params:t}}function St(){return{platform:1e3,os:"h5",appVersion:"1.1.5",appId:"1",model:"UnknownModel",brand:"UnknownBrand",uuid:"1",jsSdkVersion:"1.1.5",extra:{}}}var Ee={default:{test:"https://stg-collect.jolibox.com",prod:"https://collect.jolibox.com"},"oss.jolibox.com":{test:"https://stg-collect.jolibox.com",prod:"https://collect.jolibox.com"},"oss.pico-game.com":{test:"https://stg-collect.pico-game.com",prod:"https://collect.pico-game.com"}},vt=()=>{let e=Ee[window.location.host]??Ee.default;return O?e.test:e.prod},xt=vt(),_e=e=>{let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};AbortSignal.timeout??=_e;var Rt=()=>new URLSearchParams(window.location.search).get("joliSource")??null,It=Rt(),bt=async e=>{let r=`${xt}/report`,n=fe("1.1.5"),s=It,o={"Content-Type":"application/json"};return n&&(o["x-user-agent"]=n),s&&(o["x-joli-source"]=s),await fetch(r,{method:"POST",headers:o,body:JSON.stringify(e),signal:_e(5e3)})};async function E(e){let t={name:"globalJsError",type:H.ErrorTrace,location:yt(),target:null,extra:e,timestamp:Date.now(),userId:null},r=St(),s={protocolVersion:"1.0.0",events:[t],device:r,project:W.WebSDK},o=ue(s);bt(o)}document.addEventListener("DOMContentLoaded",()=>ge.emit("onDocumentReady",R.startTime));var Tt=()=>{let e=0;return{set startTime(t){e=t},get startTime(){return e}}},R=Tt(),ye=g(),Y=e=>{ye.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`),E({err:JSON.stringify({message:t.message,source:t.source,lineno:t.lineno,colno:t.colno,error:t.error})})})},Q=Y;window.addEventListener("unhandledrejection",Y.bind(void 0));window.addEventListener("error",Y.bind(void 0));window.onerror=(e,t,r,n,s)=>{ye.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})}}).catch(o=>{E({err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})})})};var X=e=>{let t=e.split("-")[1];t&&(e=e.replace(`-${t}`,""));let r=e.split("+")[1];r&&(e=e.replace(`+${r}`,""));let n=e.split(".").slice(0,3),[s,o,i]=[n[0]??"0",n[1]??"0",n[2]??"0"];return{major:s,minor:o,patch:i,prerelease:t,build:r}},I=e=>parseInt(X(e).major,10),b=(e,t)=>{let{major:r,minor:n,patch:s,prerelease:o}=X(e),{major:i,minor:m,patch:d,prerelease:a}=X(t);return r!==i?r>i?1:-1:n!==m?n>m?1:-1:s!==d?s>d?1:-1:o&&!a?-1:!o&&a?1:o&&a?o>a?1:o<a?-1:0:0};var Se=g(),k=(e,t)=>{Se.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},_=(e,t,r)=>{Se.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var Re="jolibox-sdk-loadermeta",T=JSON.parse(localStorage.getItem(Re)??"{}"),q=Date.now(),ve=(e,t)=>e>t&&Math.abs(e-t)/(1e3*60*60*24)>=7,xe=e=>!/^(Failed to fetch version|Couldn't find the requested file)/.test(e);async function At(){let t=`${O?"https://stg-api.jolibox.com":"https://api.jolibox.com"}/api/fe-configs/js-sdk/version-metadata`;try{let r=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}}),{implement_version:n,bootstrap_version:s}=await r.json(),o={...T,timestamp:q};if(s){let{bootstrap_version:i}=T;if(!(i&&b(i,s)>=0)){let m=await(await fetch(Z(s))).text();xe(m)&&(o={...o,bootstrap_version:s,bootstrap_script:m})}}if(n){let{implement_version:i}=T;if(!(i&&b(i,n)>=0)){let m=await(await fetch(ee(n))).text();xe(m)&&(o={...o,implement_version:n,implement_script:m})}}localStorage.setItem(Re,JSON.stringify(o))}catch(r){console.warn("Failed to fetch loader metadata: ",r)}}var Ie=e=>{let{currentMajorVersion:t,currentVersion:r,bootstrapUrl:n,implementUrl:s}=e;function o(){let{bootstrap_version:a,bootstrap_script:f,timestamp:h}=T;if(a&&f&&h&&!ve(q,h)&&I(a)==t&&b(a,r)>=0)return{script:f,type:"localscript"};try{let l=new XMLHttpRequest;return l.open("GET",n,!1),l.send(),{script:l.responseText,type:"fetch_from_cdn"}}catch(l){let u=new me(`Bootstrap module faile to fetch ${l}`);E({err:`${u}`})}}function i(){let a=Date.now();k("jsSdkBegin",{t:a}),R.startTime=a;let{script:f,type:h}=o()??{};if(f){let l=document.createElement("script");l.type="text/javascript",l.innerHTML=f,document.head.appendChild(l),_("bootstrapModuleLoaded",Date.now()-a,{type:h})}}function m(a){(async h=>{try{let l=new Blob([h],{type:"application/javascript"}),u=URL.createObjectURL(l),Be=await import(u);return URL.revokeObjectURL(u),Be}catch(l){let u=new S(`implement module evaluate error in h5:${l} `);E({err:`${u}`})}})(a)}function d(){let a=Date.now(),{implement_script:f,implement_version:h,timestamp:l}=T;if(f&&h&&l&&!ve(q,l)&&I(h)==t&&b(h,r)>=0){m(f),_("implementModuleLoaded",Date.now()-a,{type:"loadscript"});return}let u=document.createElement("script");u.type="module",u.crossOrigin="anonymous",u.src=s,u.onload=()=>{_("implementModuleLoaded",Date.now()-a,{type:"fetch_from_cdn"})},document.head.appendChild(u)}return()=>{try{i(),d(),At()}catch(a){let f=new S(`module evaluate error: ${a}`);E({err:`${f}`})}}};var be=(e,t)=>{let r=s=>{let o=e({path:s});if(!o)throw`module ${s} load failed ${o}`;return o};function n(s){(async i=>{try{let m=new Blob([i],{type:"application/javascript"}),d=URL.createObjectURL(m),a=await import(d);return URL.revokeObjectURL(d),a}catch(m){Q(new S(`implement module evaluate error in native:${m} `))}})(s)}return()=>{try{let s=Date.now();k("jsSdkBegin",{t:s}),R.startTime=s;let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),_("bootstrapModuleLoaded",Date.now()-s,{type:"native"});let m=Date.now(),d=r(t.implementUrl);n(d),_("implementModuleLoaded",Date.now()-m,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),Q(new S(`module load failed ${s}`))}}};var wt="1.1.5",C=wt,we=I(C),De=window.JoliAndroidSDKBridge?e=>{let t=window.prompt("invoke",JSON.stringify({event:"loadScriptSync",paramsString:JSON.stringify(e)}));if(t){let{data:r}=JSON.parse(t);return r}}:void 0,Dt=typeof De<"u",Z=e=>`https://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,ee=e=>`https://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,Ut=e=>/^\d+\.\d+\.\d+$/.test(e),Ue=Ut(C)?we:C,Te=Z(Ue),Ae=ee(Ue);function Lt(){Dt?be(De,{bootstrapUrl:Te,implementUrl:Ae})():Ie({bootstrapUrl:Te,implementUrl:Ae,currentMajorVersion:we,currentVersion:C})()}Lt();var Le=g();function Oe(){return Le.excuteCommandSync("API.getSystemInfoSync")}function ke(){return Le.excuteCommandSync("API.env")}function Ce(e,t){return de.config[e]?.[t]}function Pe(e,t,r){let n=Array.isArray(t)?t:t.replace(/\[(\d+)\]/g,".$1").split("."),s=e;for(let o of n)if(s&&(typeof s=="object"||Array.isArray(s)))s=s[o];else return r;return s===void 0?r:s}var Me="1.1.5";function y(e){let r=ke().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=Ce(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||G(Me,i,"<")?!1:s.length===0?!0:Ke(o,s)||Ke(o.properties,s)}function Ke(e,t){if(!e)return!1;let r=Pe(e,t);return r?ie(r)?!0:$(r)?G(Me,r,">="):!1:!1}var Ne=g();async function je(){return y("login")?await Ne.executeCommand("API.login"):{code:"FAILURE",message:"[Jolibox SDK]login is not supported in this platform"}}async function Je(){return y("checkSession")?await Ne.executeCommand("API.checkSession"):{code:"FAILURE",message:"[Jolibox SDK]checkSession is not supported in this platform"}}var te=class{constructor(){this.loadFinished=()=>{let t=new Event("JOLIBOX_RUNTIME_LOAD_FINISHED");window.dispatchEvent(t)};this.notifyLoadProgress=t=>{let r=Math.ceil(t),n=new CustomEvent("JOLIBOX_RUNTIME_LOAD_PROGRESS",{detail:r});window.dispatchEvent(n)}}},Fe=window.JoliboxRuntime||te;var p=class{constructor(){this.commands=g();this._emitter=new z}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return y(t)}canIUseIfThrow(t){if(!this.canUse(t))return{code:"FAILURE",message:`[Jolibox SDK] ${t} is not supported in this platform`}}};var Ot="LifecycleSDK.onReady",P=class extends p{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(Ot,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exit(t){let r=this.canIUseIfThrow("lifeCycle.exit");if(r)return r;this.commands.executeCommand("LifecycleSDK.exit",t.onBeforeExit)}onJoliboxHide(t){this.commands.executeCommand("LifecycleSDK.onJoliboxHide",t.bind(this))}onJoliboxShow(t){this.commands.executeCommand("LifecycleSDK.onJoliboxShow",t.bind(this))}};var K=class extends p{async getItem(t){return await this.commands.executeCommand("StorageSDK.getItem",t)}async setItem(t,r){if(t.length>128)return{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key should be less than 128"};let n=typeof r=="string"?r:String(r);return t.length+n.length>1024?{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key and value should be less than 1024"}:await this.commands.executeCommand("StorageSDK.setItem",t,r)}async removeItem(t){return this.commands.executeCommand("StorageSDK.removeItem",t)}async clear(){return this.commands.executeCommand("StorageSDK.clear")}};var M=class extends p{constructor(){super();this.init=r=>{this.commands.executeCommand("AdsSDK.init",r)};this.adConfig=r=>{this.commands.executeCommand("AdsSDK.adConfig",r)};this.adBreak=r=>{this.commands.executeCommand("AdsSDK.adBreak",r)};this.adUnit=r=>{this.commands.executeCommand("AdsSDK.adUnit",r)}}};var N=class extends p{showKeyboard(t){let r=this.canIUseIfThrow("keyboard.showKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){let r=this.canIUseIfThrow("keyboard.updateKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.updateKeyboard",{value:t})}hideKeyboard(){let t=this.canIUseIfThrow("keyboard.hideKeyboard");if(t)return t;this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var j=class extends p{async onLevelFinished(t,r,n){let s=this.canIUseIfThrow("TaskTrackerSDK.onLevelFinished");return s?Promise.resolve(s):await this.commands.executeCommand("TaskTrackerSDK.levelFinished",t,{result:r,duration:n})}async onTaskFinished(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskFinished");return n||await this.commands.executeCommand("TaskTrackerSDK.taskFinished",t,{duration:r})}async onTaskEvent(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskEvent");return n||await this.commands.executeCommand("TaskTrackerSDK.taskEvent",t,r)}async onLevelUpgrade(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onLevelUpgrade");return n||await this.commands.executeCommand("TaskTrackerSDK.levelUpgrade",t,r)}async onHistoryUserLevel(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserLevel");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserLevel",t)}async onHistoryUserScore(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserScore");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserScore",t)}};var re=class{constructor(){this.jssdkVersion="1.1.5";this.runtime=new Fe;this.ads=new M;this.lifecycle=new P;this.storage=new K;this.keyboard=new N;this.task=new j;this.getSystemInfoSync=Oe.bind(this);this.canIUse=y.bind(this);this.login=je.bind(this);this.checkSession=Je.bind(this)}};window.JoliboxSDK=re;export{re as JoliboxSDK};
@@ -1 +1 @@
1
- "use strict";(()=>{var Y=Object.defineProperty,Ae=Object.getOwnPropertyDescriptor,De=(e,t)=>{for(var r in t)Y(e,r,{get:t[r],enumerable:!0})},X=(e,t,r,n)=>{for(var s=n>1?void 0:n?Ae(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&Y(t,r,s),s};function Ce(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function F(e){return typeof e=="string"}function q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function ke(e){return typeof e>"u"}function Oe(e){return ke(e)||e===null}function Ke(e){return typeof e=="function"}function Z(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}var Me=(e=>(e[e.DEVELOPER_FILE_NOT_FOUND=0]="DEVELOPER_FILE_NOT_FOUND",e[e.INTERNAL_IOS_CAN_NOT_FOUND_PKG=1]="INTERNAL_IOS_CAN_NOT_FOUND_PKG",e[e.USER_IOS_LOAD_TIMEOUT=2]="USER_IOS_LOAD_TIMEOUT",e[e.INTERNAL_IOS_PKG_LOAD_ERROR=3]="INTERNAL_IOS_PKG_LOAD_ERROR",e[e.INTERNAL_IOS_PKG_PARSE_FAIL=4]="INTERNAL_IOS_PKG_PARSE_FAIL",e[e.USER_IOS_GET_EMPTY_DATA=5]="USER_IOS_GET_EMPTY_DATA",e[e.USER_ANDROID_GET_PKG_FAIL=6]="USER_ANDROID_GET_PKG_FAIL",e[e.DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE=7]="DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE",e))(Me||{}),Ne=class extends Error{constructor(e){if(typeof e=="string"){super(e),this.priority="P1";return}super(e.message),this.priority="P1",this.stack=e.stack,this.raw=e}},ee=class extends Ne{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}};var te=class extends ee{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_FETCH_ERROR",this.priority="P0"}},R=class extends ee{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function S(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var Pe={log:S("log"),warn:S("warn"),info:S("info"),error:S("error"),debug:S("debug")};Object.assign(globalThis,{logger:Pe});var re=Symbol.for("Jolibox.canIUseMap"),je={};globalThis[re]=je;var ne={get config(){return globalThis[re]}};function B(e,t,r){let n=0;if(e!==t){let s=e.split("."),o=t.split("."),i=Math.max(s.length,o.length);for(let l=0;l<i;l++){let g=parseInt(s[l],10)||0,c=parseInt(o[l],10)||0;if(g>c){n=1;break}else if(g<c){n=-1;break}}}if(!r)return n;switch(r){case">":return n>0;case"<":return n<0;case"=":return n===0;case">=":return n>=0;case"<=":return n<=0;default:return!1}}var a=class U{static{this.Undefined=new U(void 0)}constructor(t){this.element=t,this.next=U.Undefined,this.prev=U.Undefined}},Je=class{constructor(){this._first=a.Undefined,this._last=a.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===a.Undefined}clear(){let e=this._first;for(;e!==a.Undefined;){let t=e.next;e.prev=a.Undefined,e.next=a.Undefined,e=t}this._first=a.Undefined,this._last=a.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let r=new a(e);if(this._first===a.Undefined)this._first=r,this._last=r;else if(t){let s=this._last;this._last=r,r.prev=s,s.next=r}else{let s=this._first;this._first=r,r.next=s,s.prev=r}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(r))}}shift(){if(this._first!==a.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==a.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==a.Undefined&&e.next!==a.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===a.Undefined&&e.next===a.Undefined?(this._first=a.Undefined,this._last=a.Undefined):e.next===a.Undefined?(this._last=this._last.prev,this._last.next=a.Undefined):e.prev===a.Undefined&&(this._first=this._first.next,this._first.prev=a.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==a.Undefined;)yield e.element,e=e.next}},Fe=0,w=class{constructor(e){this.value=e,this.id=Fe++}},v=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof w&&(this._listeners=[this._listeners]),this._listeners=this._listeners.filter(t=>t?.value===e)):(this._listeners=void 0,this._size=0)),this.options?.onDidRemoveLastListener?.())}get event(){return this._event??=(e,t)=>{if(this._disposed)return()=>{console.info("[Jolibox SDK] Emitter is _disposed")};t&&(e=e.bind(t));let r=new w(e);this._listeners?this._listeners instanceof w?this._listeners=[this._listeners,r]:this._listeners.push(r):(this.options?.onWillAddFirstListener?.(this),this._listeners=r,this.options?.onDidFirstListener?.(this)),this.options?.onDidAddListener?.(this),this._size++},this._event}_deliver(e,t){if(!e)return;let r=this.options?.onListenerError||Error.constructor;if(!r){e.value(t);return}try{e.value(t)}catch(n){r(n)}}fire(e){this._listeners&&(this._listeners instanceof w?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},V=class{constructor(){this.listeners=new Map,this.listerHandlerMap=new WeakMap,this.cachedEventQueue=new Map}on(e,t){let r=this.listeners.get(e)??new v,n=o=>t(...o.args);this.listerHandlerMap.set(t,n),r.event(n),this.listeners.set(e,r);let s=this.cachedEventQueue.get(e);if(s)for(;s.size>0;)r.fire({event:e,...s.shift()})}off(e,t){let r=this.listeners.get(e);if(r){let n=this.listerHandlerMap.get(t);r.dispose(n)}}emit(e,...t){let r=this.listeners.get(e);if(r)r.fire({event:e,args:t});else{let n=this.cachedEventQueue.get(e);n||(n=new Je,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},j={};De(j,{None:()=>Be,filter:()=>$e,once:()=>se,toPromise:()=>Ve});var Be=()=>{console.log("[Jolibox SDK] None Event")};function Ve(e){return new Promise(t=>se(e)(t))}function se(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function $e(e,t){return(r=>{let n,s={onWillAddFirstListener(){n=r(o.fire,o)}},o=new v(s);return o.event})((r,n=null)=>e(s=>t(s)&&r.call(n,s),null))}var N=Symbol.for("Jolibox.hostEmitter"),He=()=>{let e=new V;return globalThis[N]||(globalThis[N]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[N]},oe=He();function Ge(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)ze(e[n],t[n])}function ze(e,t){if(F(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(Ke(t)){try{if(e instanceof t)return}catch{}if(!Oe(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("[Jolibox SDK]argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}var L=class{constructor(){this._commands=new Map,this._onDidRegisterCommand=new v,this.onDidRegisterCommand=this._onDidRegisterCommand.event,console.log("[Jolibox SDK] command registry")}registerCommand(e){if(!e)throw new Error("invalid command");if(e.metadata&&Array.isArray(e.metadata.args)){let r=[];for(let s of e.metadata.args)r.push(s.constraint);let n=e.handler;e.handler=function(...s){return Ge(s,r),n(...s)}}let{id:t}=e;this._commands.get(t)&&console.info(`[Jolibox SDK] duplicated command is registered ${t}`),this._commands.set(t,e),this._onDidRegisterCommand.fire(t)}getCommand(e){return this._commands.get(e)}getCommands(){let e=new Map;for(let t of this._commands.keys()){let r=this.getCommand(t);r&&e.set(t,r)}return e}};L=X([Z],L);var J=class{constructor(){this._onWillExecuteCommand=new v,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new v,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new L,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=Ce(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),j.toPromise(j.filter(this.registry.onDidRegisterCommand,r=>r===e))])]),this._tryExecuteCommand(e,t))}executeCommandThowErr(e,...t){if(!this.registry.getCommand(e))throw new Error(`command '${e}' not found`);let r=this.registry.getCommand(e);this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),n}_tryExecuteCommand(e,t){let r=this.registry.getCommand(e);if(!r)return Promise.reject(new Error(`command '${e}' not found`));try{this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),Promise.resolve(n)}catch(n){return Promise.reject(n)}}invokeFunction(e,...t){let r=!1;try{return e(...t)}finally{r=!0}}};J=X([Z],J);var P=Symbol.for("Jolibox.commands");function p(){if(globalThis[P])return globalThis[P];let e=new L,t=new J,r={registerCommand(n,s,o){e.registerCommand({id:n,handler:s,metadata:o})},executeCommand(n,...s){return t.executeCommand(n,...s)},excuteCommandSync(n,...s){return t.executeCommandThowErr(n,...s)}};return globalThis[P]=r,r}document.addEventListener("DOMContentLoaded",()=>oe.emit("onDocumentReady",b.startTime));var We=()=>{let e=0;return{set startTime(t){e=t},get startTime(){return e}}},b=We(),ie=p(),$=e=>{ie.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`)})},E=$;window.addEventListener("unhandledrejection",$.bind(void 0));window.addEventListener("error",$.bind(void 0));window.onerror=(e,t,r,n,s)=>{ie.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})}}).catch(o=>{console.error(`Fallback report: ${o} ${JSON.stringify(e)}`)})};var H=e=>{let t=e.split("-")[1];t&&(e=e.replace(`-${t}`,""));let r=e.split("+")[1];r&&(e=e.replace(`+${r}`,""));let n=e.split(".").slice(0,3),[s,o,i]=[n[0]??"0",n[1]??"0",n[2]??"0"];return{major:s,minor:o,patch:i,prerelease:t,build:r}},x=e=>parseInt(H(e).major,10),I=(e,t)=>{let{major:r,minor:n,patch:s}=H(e),{major:o,minor:i,patch:l}=H(t);return r!==o?r>o?1:-1:n!==i?n>i?1:-1:s!==l?s>l?1:-1:0};var ae=p(),A=(e,t)=>{ae.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},_=(e,t,r)=>{ae.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var le="jolibox-sdk-loadermeta",T=JSON.parse(localStorage.getItem(le)??"{}"),G=Date.now(),ce=(e,t)=>e>t&&Math.abs(e-t)/(1e3*60*60*24)>=7,me=e=>!/^(Failed to fetch version|Couldn't find the requested file)/.test(e);async function Qe(){let e="https://stg-api.jolibox.com/api/fe-configs/js-sdk/version_metadata";try{let t=await fetch(e,{method:"GET",headers:{"Content-Type":"application/json"}}),{implement_version:r,bootstrap_version:n}=await t.json(),s={...T,timestamp:G};if(n){let{bootstrap_version:o}=T;if(!(o&&I(o,n))){let i=await(await fetch(z(n))).text();me(i)&&(s={...s,bootstrap_version:n,bootstrap_script:i})}}if(r){let{implement_version:o}=T;if(!(o&&I(o,r))){let i=await(await fetch(W(r))).text();me(i)&&(s={...s,implement_version:r,implement_script:i})}}localStorage.setItem(le,JSON.stringify(s))}catch(t){console.warn("Failed to fetch loader metadata: ",t)}}var de=e=>{let{currentMajorVersion:t,currentVersion:r,bootstrapUrl:n,implementUrl:s}=e;function o(){let{bootstrap_version:c,bootstrap_script:f,timestamp:u}=T;if(c&&f&&u&&!ce(G,u)&&x(c)==t&&I(c,r)>0)return{script:f,type:"localscript"};try{let m=new XMLHttpRequest;return m.open("GET",n,!1),m.send(),{script:m.responseText,type:"fetch_from_cdn"}}catch(m){E(new te(`Bootstrap module faile to fetch ${m}`))}}function i(){let c=Date.now();A("jsSdkBegin",{t:c}),b.startTime=c;let{script:f,type:u}=o()??{};if(f){let m=document.createElement("script");m.type="text/javascript",m.innerHTML=f,document.head.appendChild(m),_("bootstrapModuleLoaded",Date.now()-c,{type:u})}}function l(c){(async u=>{try{let m=new Blob([u],{type:"application/javascript"}),h=URL.createObjectURL(m),Le=await import(h);return URL.revokeObjectURL(h),Le}catch(m){E(new R(`implement module evaluate error in h5:${m} `))}})(c)}function g(){let c=Date.now(),{implement_script:f,implement_version:u,timestamp:m}=T;if(f&&u&&m&&!ce(G,m)&&x(u)==t&&I(u,r)>0){l(f),_("implementModuleLoaded",Date.now()-c,{type:"loadscript"});return}let h=document.createElement("script");h.type="module",h.crossOrigin="anonymous",h.src=s,h.onload=()=>{_("bootstrapModuleLoaded",Date.now()-c,{type:"fetch_from_cdn"})},document.head.appendChild(h)}return()=>{try{i(),g(),Qe()}catch(c){E(new R(`module evaluate error: ${c}`))}}};var ue=(e,t)=>{let r=s=>{let o=e({path:s});if(!o)throw`module ${s} load failed ${o}`;return o};function n(s){(async i=>{try{let l=new Blob([i],{type:"application/javascript"}),g=URL.createObjectURL(l),c=await import(g);return URL.revokeObjectURL(g),c}catch(l){E(new R(`implement module evaluate error in native:${l} `))}})(s)}return()=>{try{let s=Date.now();A("jsSdkBegin",{t:s}),b.startTime=s;let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),_("implementModuleLoaded",Date.now()-s,{type:"native"});let l=r(t.implementUrl);n(l),_("bootstrapModuleLoaded",Date.now()-s,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),E(new R(`module load failed ${s}`))}}};var Ye="1.1.4-beta.9",D=Ye,he=x(D),ge=window.webkit||window.JoliAndroidSDKBridge?e=>{let t=window.prompt("invoke",JSON.stringify({event:"loadScriptSync",paramsString:JSON.stringify(e)}));if(t){let{data:r}=JSON.parse(t);return r}}:void 0,Xe=typeof ge<"u",z=e=>`https://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,W=e=>`https://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,qe=e=>/^\d+\.\d+\.\d+$/.test(e),Ee=qe(D)?he:D,pe=z(Ee),fe=W(Ee);function Ze(){Xe?ue(ge,{bootstrapUrl:pe,implementUrl:fe})():de({bootstrapUrl:pe,implementUrl:fe,currentMajorVersion:he,currentVersion:D})()}Ze();var _e=p();function ye(){return _e.excuteCommandSync("API.getSystemInfoSync")}function Re(){return _e.excuteCommandSync("API.env")}function Se(e,t){return ne.config[e]?.[t]}function ve(e,t,r){let n=Array.isArray(t)?t:t.replace(/\[(\d+)\]/g,".$1").split("."),s=e;for(let o of n)if(s&&(typeof s=="object"||Array.isArray(s)))s=s[o];else return r;return s===void 0?r:s}var xe="1.1.4-beta.9";function y(e){let r=Re().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=Se(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||B(xe,i,"<")?!1:s.length===0?!0:be(o,s)||be(o.properties,s)}function be(e,t){if(!e)return!1;let r=ve(e,t);return r?q(r)?!0:F(r)?B(xe,r,">="):!1:!1}var Ie=p();async function Te(){return y("login")?await Ie.executeCommand("API.login"):{code:"FAILURE",message:"[Jolibox SDK]login is not supported in this platform"}}async function we(){return y("checkSession")?await Ie.executeCommand("API.checkSession"):{code:"FAILURE",message:"[Jolibox SDK]checkSession is not supported in this platform"}}var Ue=window.JoliboxRuntime;var d=class{constructor(){this.commands=p();this._emitter=new V}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return y(t)}canIUseIfThrow(t){if(!this.canUse(t))return{code:"FAILURE",message:`[Jolibox SDK] ${t} is not supported in this platform`}}};var et="LifecycleSDK.onReady",C=class extends d{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(et,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exit(t){let r=this.canIUseIfThrow("lifeCycle.exit");if(r)return r;this.commands.executeCommand("LifecycleSDK.exit",t.onBeforeExit)}onJoliboxHide(t){this.commands.executeCommand("LifecycleSDK.onJoliboxHide",t.bind(this))}onJoliboxShow(t){this.commands.executeCommand("LifecycleSDK.onJoliboxShow",t.bind(this))}};var k=class extends d{async getItem(t){return await this.commands.executeCommand("StorageSDK.getItem",t)}async setItem(t,r){if(t.length>128)return{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key should be less than 128"};let n=typeof r=="string"?r:String(r);return t.length+n.length>1024?{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key and value should be less than 1024"}:await this.commands.executeCommand("StorageSDK.setItem",t,r)}async removeItem(t){return this.commands.executeCommand("StorageSDK.removeItem",t)}async clear(){return this.commands.executeCommand("StorageSDK.clear")}};var O=class extends d{constructor(){super();this.init=r=>{this.commands.executeCommand("AdsSDK.init",r)};this.adConfig=r=>{this.commands.executeCommand("AdsSDK.adConfig",r)};this.adBreak=r=>{this.commands.executeCommand("AdsSDK.adBreak",r)};this.adUnit=r=>{this.commands.executeCommand("AdsSDK.adUnit",r)}}};var K=class extends d{showKeyboard(t){let r=this.canIUseIfThrow("keyboard.showKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){let r=this.canIUseIfThrow("keyboard.updateKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.updateKeyboard",t)}hideKeyboard(){let t=this.canIUseIfThrow("keyboard.hideKeyboard");if(t)return t;this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var M=class extends d{async onLevelFinished(t,r,n){let s=this.canIUseIfThrow("TaskTrackerSDK.onLevelFinished");return s?Promise.resolve(s):await this.commands.executeCommand("TaskTrackerSDK.levelFinished",t,{result:r,duration:n})}async onTaskFinished(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskFinished");return n||await this.commands.executeCommand("TaskTrackerSDK.taskFinished",t,{duration:r})}async onTaskEvent(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskEvent");return n||await this.commands.executeCommand("TaskTrackerSDK.taskEvent",t,r)}async onLevelUpgrade(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onLevelUpgrade");return n||await this.commands.executeCommand("TaskTrackerSDK.levelUpgrade",t,r)}async onHistoryUserLevel(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserLevel");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserLevel",t)}async onHistoryUserScore(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserScore");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserScore",t)}};var Q=class{constructor(){this.jssdkVersion="1.1.4-beta.9";this.runtime=new Ue;this.ads=new O;this.lifecycle=new C;this.storage=new k;this.keyboard=new K;this.task=new M;this.getSystemInfoSync=ye.bind(this);this.canIUse=y.bind(this);this.login=Te.bind(this);this.checkSession=we.bind(this)}};window.JoliboxSDK=Q;})();
1
+ "use strict";(()=>{var se=Object.defineProperty,Ve=Object.getOwnPropertyDescriptor,$e=(e,t)=>{for(var r in t)se(e,r,{get:t[r],enumerable:!0})},oe=(e,t,r,n)=>{for(var s=n>1?void 0:n?Ve(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&se(t,r,s),s};function Ge(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}function $(e){return typeof e=="string"}function ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}function He(e){return typeof e>"u"}function We(e){return He(e)||e===null}function ze(e){return typeof e=="function"}function ae(e){let t=e,r=null,n=function(...s){return r||(r=new t(...s)),r};return n.prototype=t.prototype,n}var Ye=(e=>(e[e.DEVELOPER_FILE_NOT_FOUND=0]="DEVELOPER_FILE_NOT_FOUND",e[e.INTERNAL_IOS_CAN_NOT_FOUND_PKG=1]="INTERNAL_IOS_CAN_NOT_FOUND_PKG",e[e.USER_IOS_LOAD_TIMEOUT=2]="USER_IOS_LOAD_TIMEOUT",e[e.INTERNAL_IOS_PKG_LOAD_ERROR=3]="INTERNAL_IOS_PKG_LOAD_ERROR",e[e.INTERNAL_IOS_PKG_PARSE_FAIL=4]="INTERNAL_IOS_PKG_PARSE_FAIL",e[e.USER_IOS_GET_EMPTY_DATA=5]="USER_IOS_GET_EMPTY_DATA",e[e.USER_ANDROID_GET_PKG_FAIL=6]="USER_ANDROID_GET_PKG_FAIL",e[e.DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE=7]="DEVELOPER_ANDROID_PACKAGE_FILE_UNEXPECTED_REQUIRE",e))(Ye||{}),Qe=class extends Error{constructor(e){if(typeof e=="string"){super(e),this.priority="P1";return}super(e.message),this.priority="P1",this.stack=e.stack,this.raw=e}},ce=class extends Qe{constructor(){super(...arguments),this.kind="INTERNAL_ERROR"}};var me=class extends ce{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_FETCH_ERROR",this.priority="P0"}},S=class extends ce{constructor(){super(...arguments),this.name="INTERNAL_JS_MODULE_EVAL_ERROR",this.priority="P0"}};function v(e){return(...t)=>{(globalThis.VConsole?.[e]??globalThis.console[e])(...t)}}var Xe={log:v("log"),warn:v("warn"),info:v("info"),error:v("error"),debug:v("debug")};Object.assign(globalThis,{logger:Xe});var le=Symbol.for("Jolibox.canIUseMap"),qe={};globalThis[le]=qe;var de={get config(){return globalThis[le]}};function G(e,t,r){let n=0;if(e!==t){let s=e.split("."),o=t.split("."),i=Math.max(s.length,o.length);for(let m=0;m<i;m++){let d=parseInt(s[m],10)||0,a=parseInt(o[m],10)||0;if(d>a){n=1;break}else if(d<a){n=-1;break}}}if(!r)return n;switch(r){case">":return n>0;case"<":return n<0;case"=":return n===0;case">=":return n>=0;case"<=":return n<=0;default:return!1}}var H=(e=>(e[e.System=1e3]="System",e[e.ErrorTrace=1001]="ErrorTrace",e[e.UserDefined=1002]="UserDefined",e))(H||{}),W=(e=>(e.MiniGame="mini-game",e.MiniDrama="mini-drama",e.App="app",e.WebSDK="web-sdk",e.AppSDK="app-sdk",e))(W||{}),Ze=(e=>(e[e.App=0]="App",e[e.H5=1]="H5",e[e.Weapp=2]="Weapp",e[e.Alipay=3]="Alipay",e[e.Gcash=4]="Gcash",e[e.Dana=5]="Dana",e[e.Umma=6]="Umma",e[e.WebSDK=1e3]="WebSDK",e[e.AppSDK=1001]="AppSDK",e[e.Other=9999]="Other",e))(Ze||{}),ne=["name","params"],et=["name","type","location","target","extra","timestamp","userId"],tt=["platform","os","appVersion","appId","model","brand","uuid","jsSdkVersion","extra"];function D(e,t){return t.map(r=>{if(r==="params"&&e[r]){let n=e[r];return Object.keys(n).reduce((s,o)=>(s[o]=String(n[o]),s),{})}return e[r]})}function rt(e){let t=e.location?D(e.location,ne):null,r=e.target?D(e.target,ne):null;return D({...e,location:t,target:r},et)}function ue(e){let t=e.events.map(n=>rt(n)),r=D(e.device,tt);return[e.protocolVersion,t,r,e.project]}var nt=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)});var A={isiOS:navigator.userAgent.includes("iPhone")||navigator.userAgent.includes("iPod")||navigator.userAgent.includes("iPad")||navigator.userAgent.includes("iPhone OS"),iosVersion:()=>{let e=navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);return[parseInt(e[1],10),parseInt(e[2],10),parseInt(e[3]||"0",10)]},isAndroid:navigator.userAgent.includes("Android"),isMac:navigator.userAgent.includes("Mac"),isFacebook:navigator.userAgent.includes("FB_IAB"),isPC:!navigator.userAgent.includes("iPhone")&&!navigator.userAgent.includes("Android")},st=()=>A.isiOS?"iOS":A.isAndroid?"Android":A.isMac?"Mac":A.isFacebook?"Facebook":"PC",ot="device_id",it="advertising_id",pe=e=>(localStorage.getItem(e)||localStorage.setItem(e,nt()),localStorage.getItem(e)),at=()=>pe(ot),ct=()=>pe(it),mt=e=>e.charAt(0).toUpperCase()+e.slice(1),lt=()=>{let e=new URLSearchParams(window.location.search);return mt(e.get("utm_source")??"")||"JoliboxSDK"},fe=e=>{let t="JoliboxWebSDK",r=st(),n=navigator.language,s=at(),o=ct();return`${t} (${lt()}${r}; UnknownModel; UnknownSystemVersion; ${n}) uuid/${s} adid/${o} version/${e||""}`},c=class U{static{this.Undefined=new U(void 0)}constructor(t){this.element=t,this.next=U.Undefined,this.prev=U.Undefined}},dt=class{constructor(){this._first=c.Undefined,this._last=c.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===c.Undefined}clear(){let e=this._first;for(;e!==c.Undefined;){let t=e.next;e.prev=c.Undefined,e.next=c.Undefined,e=t}this._first=c.Undefined,this._last=c.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let r=new c(e);if(this._first===c.Undefined)this._first=r,this._last=r;else if(t){let s=this._last;this._last=r,r.prev=s,s.next=r}else{let s=this._first;this._first=r,r.next=s,s.prev=r}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(r))}}shift(){if(this._first!==c.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==c.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==c.Undefined&&e.next!==c.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===c.Undefined&&e.next===c.Undefined?(this._first=c.Undefined,this._last=c.Undefined):e.next===c.Undefined?(this._last=this._last.prev,this._last.next=c.Undefined):e.prev===c.Undefined&&(this._first=this._first.next,this._first.prev=c.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==c.Undefined;)yield e.element,e=e.next}},ut=0,w=class{constructor(e){this.value=e,this.id=ut++}},x=class{constructor(e){this.options=e,this._size=0}dispose(e){this._disposed||(this._disposed=!0,this._listeners&&(e?(this._listeners instanceof w&&(this._listeners=[this._listeners]),this._listeners=this._listeners.filter(t=>t?.value===e)):(this._listeners=void 0,this._size=0)),this.options?.onDidRemoveLastListener?.())}get event(){return this._event??=(e,t)=>{if(this._disposed)return()=>{console.info("[Jolibox SDK] Emitter is _disposed")};t&&(e=e.bind(t));let r=new w(e);this._listeners?this._listeners instanceof w?this._listeners=[this._listeners,r]:this._listeners.push(r):(this.options?.onWillAddFirstListener?.(this),this._listeners=r,this.options?.onDidFirstListener?.(this)),this.options?.onDidAddListener?.(this),this._size++},this._event}_deliver(e,t){if(!e)return;let r=this.options?.onListenerError||Error.constructor;if(!r){e.value(t);return}try{e.value(t)}catch(n){r(n)}}fire(e){this._listeners&&(this._listeners instanceof w?this._deliver(this._listeners,e):this._listeners.forEach(t=>this._deliver(t,e)))}hasListeners(){return this._size>0}},z=class{constructor(){this.listeners=new Map,this.listerHandlerMap=new WeakMap,this.cachedEventQueue=new Map}on(e,t){let r=this.listeners.get(e)??new x,n=o=>t(...o.args);this.listerHandlerMap.set(t,n),r.event(n),this.listeners.set(e,r);let s=this.cachedEventQueue.get(e);if(s)for(;s.size>0;)r.fire({event:e,...s.shift()})}off(e,t){let r=this.listeners.get(e);if(r){let n=this.listerHandlerMap.get(t);r.dispose(n)}}emit(e,...t){let r=this.listeners.get(e);if(r)r.fire({event:e,args:t});else{let n=this.cachedEventQueue.get(e);n||(n=new dt,this.cachedEventQueue.set(e,n)),n.push({args:t})}}},B={};$e(B,{None:()=>pt,filter:()=>ht,once:()=>he,toPromise:()=>ft});var pt=()=>{console.log("[Jolibox SDK] None Event")};function ft(e){return new Promise(t=>he(e)(t))}function he(e){return(t,r=null)=>{let n=!1;return e(s=>{if(!n)return n=!0,t.call(r,s)},null)}}function ht(e,t){return(r=>{let n,s={onWillAddFirstListener(){n=r(o.fire,o)}},o=new x(s);return o.event})((r,n=null)=>e(s=>t(s)&&r.call(n,s),null))}var J=Symbol.for("Jolibox.hostEmitter"),gt=()=>{let e=new z;return globalThis[J]||(globalThis[J]={on:e.on.bind(e),off:e.off.bind(e),emit:e.emit.bind(e)}),globalThis[J]},ge=gt();function Et(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)_t(e[n],t[n])}function _t(e,t){if($(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(ze(t)){try{if(e instanceof t)return}catch{}if(!We(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("[Jolibox SDK]argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}var L=class{constructor(){this._commands=new Map,this._onDidRegisterCommand=new x,this.onDidRegisterCommand=this._onDidRegisterCommand.event,console.log("[Jolibox SDK] command registry")}registerCommand(e){if(!e)throw new Error("invalid command");if(e.metadata&&Array.isArray(e.metadata.args)){let r=[];for(let s of e.metadata.args)r.push(s.constraint);let n=e.handler;e.handler=function(...s){return Et(s,r),n(...s)}}let{id:t}=e;this._commands.get(t)&&console.info(`[Jolibox SDK] duplicated command is registered ${t}`),this._commands.set(t,e),this._onDidRegisterCommand.fire(t)}getCommand(e){return this._commands.get(e)}getCommands(){let e=new Map;for(let t of this._commands.keys()){let r=this.getCommand(t);r&&e.set(t,r)}return e}};L=oe([ae],L);var V=class{constructor(){this._onWillExecuteCommand=new x,this.onWillExecuteCommand=this._onWillExecuteCommand.event,this._onDidExecuteCommand=new x,this.onDidExecuteCommand=this._onDidExecuteCommand.event,this.registry=new L,this._starActivation=null}_activateStar(){return this._starActivation||(this._starActivation=Ge(3e4)),this._starActivation}async executeCommand(e,...t){return this.registry.getCommand(e)?this._tryExecuteCommand(e,t):(await Promise.all([Promise.race([this._activateStar(),B.toPromise(B.filter(this.registry.onDidRegisterCommand,r=>r===e))])]),this._tryExecuteCommand(e,t))}executeCommandThowErr(e,...t){if(!this.registry.getCommand(e))throw new Error(`command '${e}' not found`);let r=this.registry.getCommand(e);this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),n}_tryExecuteCommand(e,t){let r=this.registry.getCommand(e);if(!r)return Promise.reject(new Error(`command '${e}' not found`));try{this._onWillExecuteCommand.fire({commandId:e,args:t});let n=this.invokeFunction(r.handler,...t);return this._onDidExecuteCommand.fire({commandId:e,args:t}),Promise.resolve(n)}catch(n){return Promise.reject(n)}}invokeFunction(e,...t){let r=!1;try{return e(...t)}finally{r=!0}}};V=oe([ae],V);var F=Symbol.for("Jolibox.commands");function g(){if(globalThis[F])return globalThis[F];let e=new L,t=new V,r={registerCommand(n,s,o){e.registerCommand({id:n,handler:s,metadata:o})},executeCommand(n,...s){return t.executeCommand(n,...s)},excuteCommandSync(n,...s){return t.executeCommandThowErr(n,...s)}};return globalThis[F]=r,r}var O=new URLSearchParams(window.location.search).get("joliboxEnv")==="staging";function yt(){let e=new URLSearchParams(window.location.search),t={};return e.forEach((r,n)=>{t[n]=r}),{name:"GamePage",params:t}}function St(){return{platform:1e3,os:"h5",appVersion:"1.1.5",appId:"1",model:"UnknownModel",brand:"UnknownBrand",uuid:"1",jsSdkVersion:"1.1.5",extra:{}}}var Ee={default:{test:"https://stg-collect.jolibox.com",prod:"https://collect.jolibox.com"},"oss.jolibox.com":{test:"https://stg-collect.jolibox.com",prod:"https://collect.jolibox.com"},"oss.pico-game.com":{test:"https://stg-collect.pico-game.com",prod:"https://collect.pico-game.com"}},vt=()=>{let e=Ee[window.location.host]??Ee.default;return O?e.test:e.prod},xt=vt(),_e=e=>{let t=new AbortController;return setTimeout(()=>t.abort(),e),t.signal};AbortSignal.timeout??=_e;var Rt=()=>new URLSearchParams(window.location.search).get("joliSource")??null,It=Rt(),bt=async e=>{let r=`${xt}/report`,n=fe("1.1.5"),s=It,o={"Content-Type":"application/json"};return n&&(o["x-user-agent"]=n),s&&(o["x-joli-source"]=s),await fetch(r,{method:"POST",headers:o,body:JSON.stringify(e),signal:_e(5e3)})};async function E(e){let t={name:"globalJsError",type:H.ErrorTrace,location:yt(),target:null,extra:e,timestamp:Date.now(),userId:null},r=St(),s={protocolVersion:"1.0.0",events:[t],device:r,project:W.WebSDK},o=ue(s);bt(o)}document.addEventListener("DOMContentLoaded",()=>ge.emit("onDocumentReady",R.startTime));var Tt=()=>{let e=0;return{set startTime(t){e=t},get startTime(){return e}}},R=Tt(),ye=g(),Y=e=>{ye.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify(e)}}).catch(t=>{console.error(`Fallback report: ${t} ${JSON.stringify(e)}`),E({err:JSON.stringify({message:t.message,source:t.source,lineno:t.lineno,colno:t.colno,error:t.error})})})},Q=Y;window.addEventListener("unhandledrejection",Y.bind(void 0));window.addEventListener("error",Y.bind(void 0));window.onerror=(e,t,r,n,s)=>{ye.executeCommand("ReportSDK.traceSystem",{event:"globalJsError",info:{err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})}}).catch(o=>{E({err:JSON.stringify({message:e,source:t,lineno:r,colno:n,error:s})})})};var X=e=>{let t=e.split("-")[1];t&&(e=e.replace(`-${t}`,""));let r=e.split("+")[1];r&&(e=e.replace(`+${r}`,""));let n=e.split(".").slice(0,3),[s,o,i]=[n[0]??"0",n[1]??"0",n[2]??"0"];return{major:s,minor:o,patch:i,prerelease:t,build:r}},I=e=>parseInt(X(e).major,10),b=(e,t)=>{let{major:r,minor:n,patch:s,prerelease:o}=X(e),{major:i,minor:m,patch:d,prerelease:a}=X(t);return r!==i?r>i?1:-1:n!==m?n>m?1:-1:s!==d?s>d?1:-1:o&&!a?-1:!o&&a?1:o&&a?o>a?1:o<a?-1:0:0};var Se=g(),k=(e,t)=>{Se.executeCommand("ReportSDK.traceSystem",{event:e,info:t})},_=(e,t,r)=>{Se.executeCommand("ReportSDK.traceSystemTimeline",{event:e,duration:t,extra:r})};var Re="jolibox-sdk-loadermeta",T=JSON.parse(localStorage.getItem(Re)??"{}"),q=Date.now(),ve=(e,t)=>e>t&&Math.abs(e-t)/(1e3*60*60*24)>=7,xe=e=>!/^(Failed to fetch version|Couldn't find the requested file)/.test(e);async function At(){let t=`${O?"https://stg-api.jolibox.com":"https://api.jolibox.com"}/api/fe-configs/js-sdk/version-metadata`;try{let r=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}}),{implement_version:n,bootstrap_version:s}=await r.json(),o={...T,timestamp:q};if(s){let{bootstrap_version:i}=T;if(!(i&&b(i,s)>=0)){let m=await(await fetch(Z(s))).text();xe(m)&&(o={...o,bootstrap_version:s,bootstrap_script:m})}}if(n){let{implement_version:i}=T;if(!(i&&b(i,n)>=0)){let m=await(await fetch(ee(n))).text();xe(m)&&(o={...o,implement_version:n,implement_script:m})}}localStorage.setItem(Re,JSON.stringify(o))}catch(r){console.warn("Failed to fetch loader metadata: ",r)}}var Ie=e=>{let{currentMajorVersion:t,currentVersion:r,bootstrapUrl:n,implementUrl:s}=e;function o(){let{bootstrap_version:a,bootstrap_script:f,timestamp:h}=T;if(a&&f&&h&&!ve(q,h)&&I(a)==t&&b(a,r)>=0)return{script:f,type:"localscript"};try{let l=new XMLHttpRequest;return l.open("GET",n,!1),l.send(),{script:l.responseText,type:"fetch_from_cdn"}}catch(l){let u=new me(`Bootstrap module faile to fetch ${l}`);E({err:`${u}`})}}function i(){let a=Date.now();k("jsSdkBegin",{t:a}),R.startTime=a;let{script:f,type:h}=o()??{};if(f){let l=document.createElement("script");l.type="text/javascript",l.innerHTML=f,document.head.appendChild(l),_("bootstrapModuleLoaded",Date.now()-a,{type:h})}}function m(a){(async h=>{try{let l=new Blob([h],{type:"application/javascript"}),u=URL.createObjectURL(l),Be=await import(u);return URL.revokeObjectURL(u),Be}catch(l){let u=new S(`implement module evaluate error in h5:${l} `);E({err:`${u}`})}})(a)}function d(){let a=Date.now(),{implement_script:f,implement_version:h,timestamp:l}=T;if(f&&h&&l&&!ve(q,l)&&I(h)==t&&b(h,r)>=0){m(f),_("implementModuleLoaded",Date.now()-a,{type:"loadscript"});return}let u=document.createElement("script");u.type="module",u.crossOrigin="anonymous",u.src=s,u.onload=()=>{_("implementModuleLoaded",Date.now()-a,{type:"fetch_from_cdn"})},document.head.appendChild(u)}return()=>{try{i(),d(),At()}catch(a){let f=new S(`module evaluate error: ${a}`);E({err:`${f}`})}}};var be=(e,t)=>{let r=s=>{let o=e({path:s});if(!o)throw`module ${s} load failed ${o}`;return o};function n(s){(async i=>{try{let m=new Blob([i],{type:"application/javascript"}),d=URL.createObjectURL(m),a=await import(d);return URL.revokeObjectURL(d),a}catch(m){Q(new S(`implement module evaluate error in native:${m} `))}})(s)}return()=>{try{let s=Date.now();k("jsSdkBegin",{t:s}),R.startTime=s;let o=r(t.bootstrapUrl),i=document.createElement("script");i.type="text/javascript",i.innerHTML=o,document.head.appendChild(i),_("bootstrapModuleLoaded",Date.now()-s,{type:"native"});let m=Date.now(),d=r(t.implementUrl);n(d),_("implementModuleLoaded",Date.now()-m,{type:"native"})}catch(s){console.error(`native load script error: ${s}`),Q(new S(`module load failed ${s}`))}}};var wt="1.1.5",C=wt,we=I(C),De=window.JoliAndroidSDKBridge?e=>{let t=window.prompt("invoke",JSON.stringify({event:"loadScriptSync",paramsString:JSON.stringify(e)}));if(t){let{data:r}=JSON.parse(t);return r}}:void 0,Dt=typeof De<"u",Z=e=>`https://cdn.jsdelivr.net/npm/@jolibox/bootstrap@${e}/dist/index.js`,ee=e=>`https://cdn.jsdelivr.net/npm/@jolibox/implement@${e}/dist/index.js`,Ut=e=>/^\d+\.\d+\.\d+$/.test(e),Ue=Ut(C)?we:C,Te=Z(Ue),Ae=ee(Ue);function Lt(){Dt?be(De,{bootstrapUrl:Te,implementUrl:Ae})():Ie({bootstrapUrl:Te,implementUrl:Ae,currentMajorVersion:we,currentVersion:C})()}Lt();var Le=g();function Oe(){return Le.excuteCommandSync("API.getSystemInfoSync")}function ke(){return Le.excuteCommandSync("API.env")}function Ce(e,t){return de.config[e]?.[t]}function Pe(e,t,r){let n=Array.isArray(t)?t:t.replace(/\[(\d+)\]/g,".$1").split("."),s=e;for(let o of n)if(s&&(typeof s=="object"||Array.isArray(s)))s=s[o];else return r;return s===void 0?r:s}var Me="1.1.5";function y(e){let r=ke().data?.deviceInfo?.platform;if(!r)return!1;let[n,...s]=e.split(":"),o=Ce(r=="h5"?r:"native",n);if(!o)return!1;let i=o.version;return typeof i!="string"||G(Me,i,"<")?!1:s.length===0?!0:Ke(o,s)||Ke(o.properties,s)}function Ke(e,t){if(!e)return!1;let r=Pe(e,t);return r?ie(r)?!0:$(r)?G(Me,r,">="):!1:!1}var Ne=g();async function je(){return y("login")?await Ne.executeCommand("API.login"):{code:"FAILURE",message:"[Jolibox SDK]login is not supported in this platform"}}async function Je(){return y("checkSession")?await Ne.executeCommand("API.checkSession"):{code:"FAILURE",message:"[Jolibox SDK]checkSession is not supported in this platform"}}var te=class{constructor(){this.loadFinished=()=>{let t=new Event("JOLIBOX_RUNTIME_LOAD_FINISHED");window.dispatchEvent(t)};this.notifyLoadProgress=t=>{let r=Math.ceil(t),n=new CustomEvent("JOLIBOX_RUNTIME_LOAD_PROGRESS",{detail:r});window.dispatchEvent(n)}}},Fe=window.JoliboxRuntime||te;var p=class{constructor(){this.commands=g();this._emitter=new z}addEventListener(t,r){this._emitter.on(t,(...n)=>r(n[0]))}triggerEvent(t,r){this._emitter.emit(t,r)}canUse(t){return y(t)}canIUseIfThrow(t){if(!this.canUse(t))return{code:"FAILURE",message:`[Jolibox SDK] ${t} is not supported in this platform`}}};var Ot="LifecycleSDK.onReady",P=class extends p{constructor(){super()}onReady(t){let r=n=>{t.call(this,n),this.triggerEvent(Ot,n)};this.commands.executeCommand("LifecycleSDK.onReady",r.bind(this))}exit(t){let r=this.canIUseIfThrow("lifeCycle.exit");if(r)return r;this.commands.executeCommand("LifecycleSDK.exit",t.onBeforeExit)}onJoliboxHide(t){this.commands.executeCommand("LifecycleSDK.onJoliboxHide",t.bind(this))}onJoliboxShow(t){this.commands.executeCommand("LifecycleSDK.onJoliboxShow",t.bind(this))}};var K=class extends p{async getItem(t){return await this.commands.executeCommand("StorageSDK.getItem",t)}async setItem(t,r){if(t.length>128)return{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key should be less than 128"};let n=typeof r=="string"?r:String(r);return t.length+n.length>1024?{code:"PARAMETER_ERROR",message:"[SDK] cloud storage setItem error: length of key and value should be less than 1024"}:await this.commands.executeCommand("StorageSDK.setItem",t,r)}async removeItem(t){return this.commands.executeCommand("StorageSDK.removeItem",t)}async clear(){return this.commands.executeCommand("StorageSDK.clear")}};var M=class extends p{constructor(){super();this.init=r=>{this.commands.executeCommand("AdsSDK.init",r)};this.adConfig=r=>{this.commands.executeCommand("AdsSDK.adConfig",r)};this.adBreak=r=>{this.commands.executeCommand("AdsSDK.adBreak",r)};this.adUnit=r=>{this.commands.executeCommand("AdsSDK.adUnit",r)}}};var N=class extends p{showKeyboard(t){let r=this.canIUseIfThrow("keyboard.showKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.showKeyboard",t)}updateKeyboard(t){let r=this.canIUseIfThrow("keyboard.updateKeyboard");if(r)return r;this.commands.executeCommand("KeyboardSDK.updateKeyboard",{value:t})}hideKeyboard(){let t=this.canIUseIfThrow("keyboard.hideKeyboard");if(t)return t;this.commands.executeCommand("KeyboardSDK.hideKeyboard")}};var j=class extends p{async onLevelFinished(t,r,n){let s=this.canIUseIfThrow("TaskTrackerSDK.onLevelFinished");return s?Promise.resolve(s):await this.commands.executeCommand("TaskTrackerSDK.levelFinished",t,{result:r,duration:n})}async onTaskFinished(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskFinished");return n||await this.commands.executeCommand("TaskTrackerSDK.taskFinished",t,{duration:r})}async onTaskEvent(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onTaskEvent");return n||await this.commands.executeCommand("TaskTrackerSDK.taskEvent",t,r)}async onLevelUpgrade(t,r){let n=this.canIUseIfThrow("TaskTrackerSDK.onLevelUpgrade");return n||await this.commands.executeCommand("TaskTrackerSDK.levelUpgrade",t,r)}async onHistoryUserLevel(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserLevel");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserLevel",t)}async onHistoryUserScore(t){let r=this.canIUseIfThrow("TaskTrackerSDK.onHistoryUserScore");return r||await this.commands.executeCommand("TaskTrackerSDK.historyUserScore",t)}};var re=class{constructor(){this.jssdkVersion="1.1.5";this.runtime=new Fe;this.ads=new M;this.lifecycle=new P;this.storage=new K;this.keyboard=new N;this.task=new j;this.getSystemInfoSync=Oe.bind(this);this.canIUse=y.bind(this);this.login=je.bind(this);this.checkSession=Je.bind(this)}};window.JoliboxSDK=re;})();
@@ -0,0 +1 @@
1
+ export {};
@@ -1 +1,35 @@
1
- export declare const RuntimeSDK: any;
1
+ export declare enum JoliboxRuntimeEvents {
2
+ /**
3
+ * Event dispatched when the loading starts
4
+ */
5
+ LOAD_START = "JOLIBOX_RUNTIME_LOAD_START",
6
+ /**
7
+ * Event dispatched when the loading is finished
8
+ */
9
+ LOAD_FINISHED = "JOLIBOX_RUNTIME_LOAD_FINISHED",
10
+ /**
11
+ * Event dispatched when the loading progress is updated
12
+ */
13
+ LOAD_PROGRESS = "JOLIBOX_RUNTIME_LOAD_PROGRESS"
14
+ }
15
+ /**
16
+ * Default implementation of JoliboxRuntime, in case the JoliboxRuntime is not available
17
+ */
18
+ declare class FallbackJoliboxRuntime {
19
+ /**
20
+ * Notify the end of the loading, will close the loading splash screen
21
+ */
22
+ loadFinished: () => void;
23
+ /**
24
+ * Notify the progress of the loading, will update the loading splash screen
25
+ * @param progress - The progress of the loading, should be an integer between 0 and 100
26
+ */
27
+ notifyLoadProgress: (progress: number) => void;
28
+ }
29
+ declare global {
30
+ interface Window {
31
+ JoliboxRuntime: typeof FallbackJoliboxRuntime;
32
+ }
33
+ }
34
+ export declare const RuntimeSDK: typeof FallbackJoliboxRuntime;
35
+ export {};
@@ -0,0 +1 @@
1
+ export declare const testMode: boolean;
@@ -0,0 +1 @@
1
+ export declare function trackError(errorData: Record<string, string>): Promise<void>;
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@jolibox/sdk",
3
3
  "description": "This project is common Jolibox JS-SDk interfere",
4
- "version": "1.1.4-beta.9",
4
+ "version": "1.1.5",
5
5
  "main": "dist/index.cjs.js",
6
6
  "module": "dist/index.esm.js",
7
7
  "typings": "dist/index.d.ts",
8
8
  "license": "MIT",
9
9
  "dependencies": {
10
- "@jolibox/common": "1.1.4-beta.9",
11
- "@jolibox/types": "1.1.4-beta.9"
10
+ "@jolibox/common": "1.1.5",
11
+ "@jolibox/types": "1.1.5"
12
12
  },
13
13
  "devDependencies": {
14
14
  "typescript": "5.7.3",
package/sdk.build.log CHANGED
@@ -1,17 +1,17 @@
1
1
  Invoking: npm run clean && npm run build:cjs && npm run build:esm && npm run build:iife && tsc
2
2
 
3
- > @jolibox/sdk@1.1.4-beta.9 clean
3
+ > @jolibox/sdk@1.1.5 clean
4
4
  > rimraf ./dist
5
5
 
6
6
 
7
- > @jolibox/sdk@1.1.4-beta.9 build:cjs
7
+ > @jolibox/sdk@1.1.5 build:cjs
8
8
  > BUILD_VERSION=$(node -p "require('./package.json').version") node esbuild.config.js --format=cjs
9
9
 
10
10
 
11
- > @jolibox/sdk@1.1.4-beta.9 build:esm
11
+ > @jolibox/sdk@1.1.5 build:esm
12
12
  > BUILD_VERSION=$(node -p "require('./package.json').version") node esbuild.config.js --format=esm
13
13
 
14
14
 
15
- > @jolibox/sdk@1.1.4-beta.9 build:iife
15
+ > @jolibox/sdk@1.1.5 build:iife
16
16
  > BUILD_VERSION=$(node -p "require('./package.json').version") node esbuild.config.js --format=iife
17
17
 
package/src/events.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { hostEmitter, createCommands, BaseError } from '@jolibox/common';
1
+ import { hostEmitter, createCommands, BaseError, EProject } from '@jolibox/common';
2
+ import { trackError } from './utils/event-tracker';
2
3
  document.addEventListener('DOMContentLoaded', () => hostEmitter.emit('onDocumentReady', timeline.startTime));
3
4
 
4
5
  const timelineFactory = () => {
@@ -28,6 +29,15 @@ const rejectHandler = (event: PromiseRejectionEvent | ErrorEvent | BaseError) =>
28
29
  .catch((e) => {
29
30
  // 兜底上报
30
31
  console.error(`Fallback report: ${e} ${JSON.stringify(event)}`);
32
+ trackError({
33
+ err: JSON.stringify({
34
+ message: e.message,
35
+ source: e.source,
36
+ lineno: e.lineno,
37
+ colno: e.colno,
38
+ error: e.error
39
+ })
40
+ });
31
41
  });
32
42
  };
33
43
 
@@ -51,6 +61,14 @@ window.onerror = (message, source, lineno, colno, error) => {
51
61
  })
52
62
  .catch((e) => {
53
63
  // 兜底上报
54
- console.error(`Fallback report: ${e} ${JSON.stringify(message)}`);
64
+ trackError({
65
+ err: JSON.stringify({
66
+ message,
67
+ source,
68
+ lineno,
69
+ colno,
70
+ error
71
+ })
72
+ });
55
73
  });
56
74
  };
@@ -0,0 +1,65 @@
1
+ import { compare } from '../version';
2
+
3
+ describe('version compare', () => {
4
+ describe('major version comparison', () => {
5
+ it('should return 1 when first major version is greater', () => {
6
+ expect(compare('2.0.0', '1.0.0')).toBe(1);
7
+ });
8
+
9
+ it('should return -1 when first major version is smaller', () => {
10
+ expect(compare('1.0.0', '2.0.0')).toBe(-1);
11
+ });
12
+ });
13
+
14
+ describe('minor version comparison', () => {
15
+ it('should return 1 when first minor version is greater', () => {
16
+ expect(compare('1.2.0', '1.1.0')).toBe(1);
17
+ });
18
+
19
+ it('should return -1 when first minor version is smaller', () => {
20
+ expect(compare('1.1.0', '1.2.0')).toBe(-1);
21
+ });
22
+ });
23
+
24
+ describe('patch version comparison', () => {
25
+ it('should return 1 when first patch version is greater', () => {
26
+ expect(compare('1.0.2', '1.0.1')).toBe(1);
27
+ });
28
+
29
+ it('should return -1 when first patch version is smaller', () => {
30
+ expect(compare('1.0.1', '1.0.2')).toBe(-1);
31
+ });
32
+ });
33
+
34
+ describe('prerelease version comparison', () => {
35
+ it('should return -1 when comparing prerelease version with release version', () => {
36
+ expect(compare('1.0.0-beta.1', '1.0.0')).toBe(-1);
37
+ });
38
+
39
+ it('should return 1 when comparing release version with prerelease version', () => {
40
+ expect(compare('1.0.0', '1.0.0-beta.1')).toBe(1);
41
+ });
42
+
43
+ it('should compare prerelease versions correctly', () => {
44
+ expect(compare('1.0.0-beta.2', '1.0.0-beta.1')).toBe(1);
45
+ expect(compare('1.0.0-beta.1', '1.0.0-beta.2')).toBe(-1);
46
+ expect(compare('1.0.0-beta.1', '1.0.0-beta.1')).toBe(0);
47
+ });
48
+ });
49
+
50
+ describe('equal versions', () => {
51
+ it('should return 0 when versions are equal', () => {
52
+ expect(compare('1.0.0', '1.0.0')).toBe(0);
53
+ expect(compare('1.1.1', '1.1.1')).toBe(0);
54
+ expect(compare('1.0.0-beta.1', '1.0.0-beta.1')).toBe(0);
55
+ });
56
+ });
57
+
58
+ describe('complex version comparison', () => {
59
+ it('should handle complex version comparisons correctly', () => {
60
+ expect(compare('2.0.0-beta.1', '1.9.9')).toBe(1); // Major version takes precedence
61
+ expect(compare('1.2.3-beta.1', '1.2.3-alpha.1')).toBe(1); // beta > alpha
62
+ expect(compare('1.0.0-rc.1', '1.0.0-beta.9')).toBe(1); // rc > beta
63
+ });
64
+ });
65
+ });
package/src/loader/h5.ts CHANGED
@@ -2,7 +2,9 @@ import { compare, major } from './version';
2
2
  import { track, trackPerformance } from '../utils/report';
3
3
  import { InternalJSModuleEvalError, InternalJSModuleFetchError } from '@jolibox/common';
4
4
  import { getBoostrapModuleUrl, getImplementModuleUrl } from './index';
5
- import { reportError, timeline } from '../events';
5
+ import { timeline } from '../events';
6
+ import { testMode } from '@/utils/env';
7
+ import { trackError } from '@/utils/event-tracker';
6
8
 
7
9
  const LOCAL_STORE_KEY = 'jolibox-sdk-loadermeta';
8
10
  interface LocalStoreMeta {
@@ -23,8 +25,8 @@ const expired = (now: number, prev: number) =>
23
25
  const isLegalScript = (str: string) =>
24
26
  !/^(Failed to fetch version|Couldn't find the requested file)/.test(str);
25
27
  async function fetchCurrentRemoteScript() {
26
- // TODO: adjust host
27
- const path = `https://stg-api.jolibox.com/api/fe-configs/js-sdk/version_metadata`;
28
+ const host = testMode ? 'https://stg-api.jolibox.com' : 'https://api.jolibox.com';
29
+ const path = `${host}/api/fe-configs/js-sdk/version-metadata`;
28
30
  try {
29
31
  const response = await fetch(path, {
30
32
  method: 'GET',
@@ -36,7 +38,7 @@ async function fetchCurrentRemoteScript() {
36
38
  let currentStore: LocalStoreMeta = { ...CURRENT_VERSION_STORE, timestamp: now };
37
39
  if (bootstrap_version) {
38
40
  const { bootstrap_version: currentLocalBootstrapVersion } = CURRENT_VERSION_STORE;
39
- if (currentLocalBootstrapVersion && compare(currentLocalBootstrapVersion, bootstrap_version)) {
41
+ if (currentLocalBootstrapVersion && compare(currentLocalBootstrapVersion, bootstrap_version) >= 0) {
40
42
  // no-op
41
43
  } else {
42
44
  const currentBootstrapModuleStr = await (await fetch(getBoostrapModuleUrl(bootstrap_version))).text();
@@ -50,7 +52,7 @@ async function fetchCurrentRemoteScript() {
50
52
  }
51
53
  if (implement_version) {
52
54
  const { implement_version: currentLocalImpelementVersion } = CURRENT_VERSION_STORE;
53
- if (currentLocalImpelementVersion && compare(currentLocalImpelementVersion, implement_version)) {
55
+ if (currentLocalImpelementVersion && compare(currentLocalImpelementVersion, implement_version) >= 0) {
54
56
  // no-op
55
57
  } else {
56
58
  const currentImplementModuleStr = await (
@@ -89,7 +91,7 @@ export const createLoadImplement = (params: {
89
91
  if (
90
92
  !expired(now, timestamp) &&
91
93
  major(bootstrap_version) == currentMajorVersion &&
92
- compare(bootstrap_version, currentVersion) > 0
94
+ compare(bootstrap_version, currentVersion) >= 0
93
95
  ) {
94
96
  return { script: bootstrap_script, type: 'localscript' };
95
97
  }
@@ -100,7 +102,10 @@ export const createLoadImplement = (params: {
100
102
  xhr.send();
101
103
  return { script: xhr.responseText, type: 'fetch_from_cdn' };
102
104
  } catch (e) {
103
- reportError(new InternalJSModuleFetchError(`Bootstrap module faile to fetch ${e}`));
105
+ const internalError = new InternalJSModuleFetchError(`Bootstrap module faile to fetch ${e}`);
106
+ trackError({
107
+ err: `${internalError}`
108
+ });
104
109
  }
105
110
  }
106
111
 
@@ -130,7 +135,12 @@ export const createLoadImplement = (params: {
130
135
  URL.revokeObjectURL(blobUrl);
131
136
  return module;
132
137
  } catch (error) {
133
- reportError(new InternalJSModuleEvalError(`implement module evaluate error in h5:${error} `));
138
+ const internalError = new InternalJSModuleEvalError(
139
+ `implement module evaluate error in h5:${error} `
140
+ );
141
+ trackError({
142
+ err: `${internalError}`
143
+ });
134
144
  }
135
145
  };
136
146
  evalJS(code);
@@ -147,7 +157,7 @@ export const createLoadImplement = (params: {
147
157
  if (
148
158
  !expired(now, timestamp) &&
149
159
  major(implement_version) == currentMajorVersion &&
150
- compare(implement_version, currentVersion) > 0
160
+ compare(implement_version, currentVersion) >= 0
151
161
  ) {
152
162
  evalLocalJSModule(implement_script);
153
163
  trackPerformance('implementModuleLoaded', Date.now() - implStartLoad, { type: 'loadscript' });
@@ -159,7 +169,7 @@ export const createLoadImplement = (params: {
159
169
  asyncScript.crossOrigin = 'anonymous';
160
170
  asyncScript.src = implementUrl;
161
171
  asyncScript.onload = () => {
162
- trackPerformance('bootstrapModuleLoaded', Date.now() - implStartLoad, { type: 'fetch_from_cdn' });
172
+ trackPerformance('implementModuleLoaded', Date.now() - implStartLoad, { type: 'fetch_from_cdn' });
163
173
  };
164
174
  document.head.appendChild(asyncScript);
165
175
  }
@@ -170,7 +180,10 @@ export const createLoadImplement = (params: {
170
180
  loadRemoteImplement();
171
181
  fetchCurrentRemoteScript();
172
182
  } catch (e) {
173
- reportError(new InternalJSModuleEvalError(`module evaluate error: ${e}`));
183
+ const internalError = new InternalJSModuleEvalError(`module evaluate error: ${e}`);
184
+ trackError({
185
+ err: `${internalError}`
186
+ });
174
187
  }
175
188
  };
176
189
  };
@@ -19,24 +19,22 @@ declare global {
19
19
  webkit?: unknown;
20
20
  }
21
21
  }
22
- const loadScript =
23
- window.webkit || window.JoliAndroidSDKBridge
24
- ? (params: { path: string }) => {
25
- const res = window.prompt(
26
- 'invoke',
27
- JSON.stringify({
28
- event: 'loadScriptSync',
29
- paramsString: JSON.stringify(params)
30
- })
31
- );
32
- if (res) {
33
- const { data } = JSON.parse(res);
34
- return data;
35
- }
36
- return undefined;
22
+ const loadScript = window.JoliAndroidSDKBridge
23
+ ? (params: { path: string }) => {
24
+ const res = window.prompt(
25
+ 'invoke',
26
+ JSON.stringify({
27
+ event: 'loadScriptSync',
28
+ paramsString: JSON.stringify(params)
29
+ })
30
+ );
31
+ if (res) {
32
+ const { data } = JSON.parse(res);
33
+ return data;
37
34
  }
38
- : undefined;
39
-
35
+ return undefined;
36
+ }
37
+ : undefined;
40
38
  const isNative = typeof loadScript !== 'undefined';
41
39
 
42
40
  /**
@@ -46,14 +46,15 @@ export const createLoadImplement = (
46
46
  script.type = 'text/javascript';
47
47
  script.innerHTML = bootstrapModuleStr;
48
48
  document.head.appendChild(script);
49
- trackPerformance('implementModuleLoaded', Date.now() - startToLoad, { type: 'native' });
49
+ trackPerformance('bootstrapModuleLoaded', Date.now() - startToLoad, { type: 'native' });
50
50
 
51
51
  /**
52
52
  * implement module
53
53
  */
54
+ const implStartLoad = Date.now();
54
55
  const implModuleStr = tryLoadScript(params.implementUrl);
55
56
  evalLocalJSModule(implModuleStr);
56
- trackPerformance('bootstrapModuleLoaded', Date.now() - startToLoad, { type: 'native' });
57
+ trackPerformance('implementModuleLoaded', Date.now() - implStartLoad, { type: 'native' });
57
58
  } catch (e) {
58
59
  console.error(`native load script error: ${e}`);
59
60
  // TODO
@@ -25,9 +25,10 @@ const splitSemver = (
25
25
  export const major = (version: string): number => parseInt(splitSemver(version).major, 10);
26
26
 
27
27
  export const compare = (v1: string, v2: string): -1 | 0 | 1 => {
28
- const { major: major1, minor: minor1, patch: patch1 } = splitSemver(v1);
29
- const { major: major2, minor: minor2, patch: patch2 } = splitSemver(v2);
28
+ const { major: major1, minor: minor1, patch: patch1, prerelease: pre1 } = splitSemver(v1);
29
+ const { major: major2, minor: minor2, patch: patch2, prerelease: pre2 } = splitSemver(v2);
30
30
 
31
+ // Compare major.minor.patch first
31
32
  if (major1 !== major2) {
32
33
  return major1 > major2 ? 1 : -1;
33
34
  }
@@ -40,5 +41,11 @@ export const compare = (v1: string, v2: string): -1 | 0 | 1 => {
40
41
  return patch1 > patch2 ? 1 : -1;
41
42
  }
42
43
 
44
+ if (pre1 && !pre2) return -1; // 正式版比预发布版本大
45
+ if (!pre1 && pre2) return 1; // 正式版比预发布版本大
46
+ if (pre1 && pre2) {
47
+ return pre1 > pre2 ? 1 : pre1 < pre2 ? -1 : 0;
48
+ }
49
+
43
50
  return 0;
44
51
  };
@@ -24,7 +24,7 @@ export class KeyboardSDK extends BaseSDK implements Keyboard {
24
24
  if (errMsg) {
25
25
  return errMsg;
26
26
  }
27
- this.commands.executeCommand('KeyboardSDK.updateKeyboard', value);
27
+ this.commands.executeCommand('KeyboardSDK.updateKeyboard', { value });
28
28
  }
29
29
  /**
30
30
  * 隐藏键盘
@@ -1,3 +1,50 @@
1
+ export enum JoliboxRuntimeEvents {
2
+ /**
3
+ * Event dispatched when the loading starts
4
+ */
5
+ LOAD_START = 'JOLIBOX_RUNTIME_LOAD_START',
6
+
7
+ /**
8
+ * Event dispatched when the loading is finished
9
+ */
10
+ LOAD_FINISHED = 'JOLIBOX_RUNTIME_LOAD_FINISHED',
11
+
12
+ /**
13
+ * Event dispatched when the loading progress is updated
14
+ */
15
+ LOAD_PROGRESS = 'JOLIBOX_RUNTIME_LOAD_PROGRESS'
16
+ }
17
+ /**
18
+ * Default implementation of JoliboxRuntime, in case the JoliboxRuntime is not available
19
+ */
20
+ class FallbackJoliboxRuntime {
21
+ /**
22
+ * Notify the end of the loading, will close the loading splash screen
23
+ */
24
+ loadFinished = (): void => {
25
+ const loadFinishedEvent = new Event(JoliboxRuntimeEvents.LOAD_FINISHED);
26
+ window.dispatchEvent(loadFinishedEvent);
27
+ };
28
+
29
+ /**
30
+ * Notify the progress of the loading, will update the loading splash screen
31
+ * @param progress - The progress of the loading, should be an integer between 0 and 100
32
+ */
33
+ notifyLoadProgress = (progress: number): void => {
34
+ const detail = Math.ceil(progress);
35
+ const event = new CustomEvent(JoliboxRuntimeEvents.LOAD_PROGRESS, {
36
+ detail
37
+ });
38
+ window.dispatchEvent(event);
39
+ };
40
+ }
41
+
42
+ declare global {
43
+ interface Window {
44
+ JoliboxRuntime: typeof FallbackJoliboxRuntime;
45
+ }
46
+ }
47
+
1
48
  //eslint-disable-next-line @typescript-eslint/ban-ts-comment
2
49
  //@ts-ignore
3
- export const RuntimeSDK = window.JoliboxRuntime;
50
+ export const RuntimeSDK = window.JoliboxRuntime || FallbackJoliboxRuntime;
@@ -0,0 +1 @@
1
+ export const testMode = new URLSearchParams(window.location.search).get('joliboxEnv') === 'staging';
@@ -0,0 +1,126 @@
1
+ /**
2
+ * 兜底上报
3
+ */
4
+ import {
5
+ serializeEventPackage,
6
+ IEvent,
7
+ EProject,
8
+ IEventPackage,
9
+ IPage,
10
+ IDevice,
11
+ EPlatform,
12
+ EventType,
13
+ timeout,
14
+ xUserAgent
15
+ } from '@jolibox/common';
16
+ import { testMode } from './env';
17
+
18
+ function getLocation(): IPage {
19
+ const urlParams = new URLSearchParams(window.location.search);
20
+ const params: Record<string, any> = {};
21
+ urlParams.forEach((value, key) => {
22
+ params[key] = value;
23
+ });
24
+ return {
25
+ name: 'GamePage',
26
+ params
27
+ };
28
+ }
29
+
30
+ function getDevice(): IDevice {
31
+ return {
32
+ platform: 1000,
33
+ os: 'h5',
34
+ appVersion: '__JOLIBOX_LOCAL_SDK_VERSION__', // mock
35
+ appId: '1',
36
+ model: 'UnknownModel',
37
+ brand: 'UnknownBrand',
38
+ uuid: '1',
39
+ jsSdkVersion: '__JOLIBOX_LOCAL_SDK_VERSION__', // mock
40
+ extra: {}
41
+ };
42
+ }
43
+
44
+ const hostToApiMap: Record<string | 'default', { test: string; prod: string }> = {
45
+ default: {
46
+ test: 'https://stg-collect.jolibox.com',
47
+ prod: 'https://collect.jolibox.com'
48
+ },
49
+ 'oss.jolibox.com': {
50
+ test: 'https://stg-collect.jolibox.com',
51
+ prod: 'https://collect.jolibox.com'
52
+ },
53
+ 'oss.pico-game.com': {
54
+ test: 'https://stg-collect.pico-game.com',
55
+ prod: 'https://collect.pico-game.com'
56
+ }
57
+ };
58
+
59
+ const apiBaseURL = () => {
60
+ const api = hostToApiMap[window.location.host] ?? hostToApiMap.default;
61
+ return testMode ? api.test : api.prod;
62
+ };
63
+
64
+ const API_BASE_URL = apiBaseURL();
65
+
66
+ const timeoutFn = (ms: number) => {
67
+ const ctrl = new AbortController();
68
+ setTimeout(() => ctrl.abort(), ms);
69
+ return ctrl.signal;
70
+ };
71
+
72
+ (AbortSignal as any).timeout ??= timeoutFn;
73
+
74
+ const getJoliSource = () => {
75
+ const urlParams = new URLSearchParams(window.location.search);
76
+ return urlParams.get('joliSource') ?? null;
77
+ };
78
+
79
+ const JOLI_SOURCE = getJoliSource();
80
+
81
+ const postToReporter = async (data: unknown) => {
82
+ const reporterHost = API_BASE_URL;
83
+ const url = `${reporterHost}/report`;
84
+ const xua = xUserAgent('__JOLIBOX_LOCAL_SDK_VERSION__');
85
+ const joliSource = JOLI_SOURCE;
86
+ const headers: Record<string, string> = {
87
+ 'Content-Type': 'application/json'
88
+ };
89
+
90
+ if (xua) headers['x-user-agent'] = xua;
91
+ if (joliSource) headers['x-joli-source'] = joliSource;
92
+
93
+ const response = await fetch(url, {
94
+ method: 'POST',
95
+ headers,
96
+ body: JSON.stringify(data),
97
+ signal: timeoutFn(5000)
98
+ });
99
+
100
+ // return text
101
+ return response;
102
+ };
103
+
104
+ export async function trackError(errorData: Record<string, string>) {
105
+ const errEvent: IEvent = {
106
+ name: 'globalJsError',
107
+ type: EventType.ErrorTrace,
108
+ location: getLocation(),
109
+ target: null,
110
+ extra: errorData,
111
+ timestamp: Date.now(),
112
+ userId: null
113
+ };
114
+
115
+ const device = getDevice();
116
+ const events: IEvent[] = [errEvent];
117
+ const eventPackage: IEventPackage = {
118
+ protocolVersion: '1.0.0',
119
+ events,
120
+ device,
121
+ project: EProject.WebSDK
122
+ };
123
+ const serializedEventPackage = serializeEventPackage(eventPackage);
124
+
125
+ postToReporter(serializedEventPackage);
126
+ }