@tinkerlandai/longplay-sdk 0.10.94 → 0.10.96

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.
Files changed (36) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +4 -0
  3. package/README.zh-CN.md +2 -0
  4. package/dist/{chunk-IL5OTR6J.js → chunk-3XH64DN3.js} +1 -1
  5. package/dist/{chunk-NKYNGR3L.js → chunk-5HWHBCVN.js} +1 -1
  6. package/dist/{chunk-5SB3RRGA.js → chunk-6CNAIAG2.js} +1 -1
  7. package/dist/{chunk-6QBSJRAD.js → chunk-7JJGSLXD.js} +1 -1
  8. package/dist/{chunk-FEU6XRHV.js → chunk-7NCZ6XU7.js} +1 -1
  9. package/dist/{chunk-ANEFV7YJ.js → chunk-B6TDAH7X.js} +2 -2
  10. package/dist/{chunk-C4HLVYSU.js → chunk-DLORK3P2.js} +1 -1
  11. package/dist/chunk-JDXX5XN5.js +1 -0
  12. package/dist/{chunk-FDXBCQBO.js → chunk-MYG5MAKQ.js} +1 -1
  13. package/dist/{chunk-Q5IYCTRL.js → chunk-PWE3ZWLR.js} +1 -1
  14. package/dist/{chunk-H3LJWAAE.js → chunk-TE2F4PML.js} +1 -1
  15. package/dist/{chunk-MMHL2KFB.js → chunk-XNICYGGP.js} +1 -1
  16. package/dist/{chunk-VVBXVJI6.js → chunk-XSJGNM2C.js} +1 -1
  17. package/dist/{content-K2T4V3ZD.js → content-EV62FGPW.js} +1 -1
  18. package/dist/{funnel-host-purchase-M2JNOOCE.js → funnel-host-purchase-6BBAZXCX.js} +1 -1
  19. package/dist/funnel-host-purchase-entry-5UDZJJBN.js +1 -0
  20. package/dist/{funnel-host-recovery-paywall-XFL6JS74.js → funnel-host-recovery-paywall-AK4CJGGB.js} +1 -1
  21. package/dist/{funnel-paywall-prerender-YUBH7ZC7.js → funnel-paywall-prerender-YPVUTJTO.js} +1 -1
  22. package/dist/{funnel-runtime-host-3P62SXBA.js → funnel-runtime-host-D54WIMXD.js} +1 -1
  23. package/dist/index.d.ts +11 -1
  24. package/dist/index.js +1 -1
  25. package/dist/openrouter.js +1 -1
  26. package/dist/page.js +1 -1
  27. package/dist/{paywall-JTKB4MMC.js → paywall-DWBIV43F.js} +1 -1
  28. package/dist/{paywall-content-GJX3FQ6D.js → paywall-content-S6A2WLIX.js} +1 -1
  29. package/dist/{paywall-session-PCWN2M24.js → paywall-session-R3WV3BSU.js} +1 -1
  30. package/dist/react-native.js +1 -1
  31. package/dist/server.js +1 -1
  32. package/dist/visual.js +1 -1
  33. package/package.json +1 -1
  34. package/dist/chunk-XKYVXIUI.js +0 -1
  35. package/dist/funnel-host-purchase-entry-OKHAEHOG.js +0 -1
  36. /package/dist/{chunk-ANEFV7YJ.js.LEGAL.txt → chunk-B6TDAH7X.js.LEGAL.txt} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.96
4
+
5
+ - A registered purchase entry paints its next copy as soon as the Run of an opening is on screen, not after that opening is dismissed. A click right after the close now finds a copy it can reveal; before, it found the copy still painting and opened cold. The next copy is not started while the opening's own Start is unanswered, and a replacement already painting when the click comes is kept for the next click instead of being prepared again.
6
+ - `onEvent` of `createFunnelPurchaseEntry` reports `result` once per opening: `revealed` (the Customer saw the copy) and `adopted` (the Run took it over). Count hits by `result.adopted`; `open.used` only says the opening tried the copy and overstates hits when the Run presents its own Paywall instead.
7
+
8
+ ## 0.10.95
9
+
10
+ - The merchant bridge loads the validators of its commercial replies in the background when a bridge with a commercial capability (`customer_commerce`, `purchases`, `operation_status`, `subscription_changes`) is created, and `preloadFunnelPurchase` loads them as well. Before, `readCustomerCommerce` and the other commercial reads requested that module at the read, so a read made at a click waited for the module request in addition to the merchant's reply. A failed background load is retried by the read that needs it; replies are validated as before. A bridge with only `session` loads nothing extra.
11
+
3
12
  ## 0.10.94
4
13
 
5
14
  - `prerenderFunnelPurchase` with a named `paywallId` and the Funnel's `configuration` now renders the Paywall Version the Funnel's current Version fixes for every Funnel in the public selection, not only for a Remote Funnel whose author opted in to its first-screen route. Each published Funnel Version publishes these pins (Version identities only, without its conditions, Splits or graph) at `/api/v1/configuration/{environmentId}/funnels/{funnelId}/versions/{versionId}/paywalls`; a Local Funnel's are computed from its public graph without a request. The copy is then the Version the Run presents, so the Run adopts it instead of replacing it at the click. When the pins cannot be read, or fix that Paywall at none or several Versions, the current published Version is used as before. The pre-render no longer reads the route for this; the route still serves first-screen prediction. New `configuration.funnelPaywallPins(funnelId)`.
package/README.md CHANGED
@@ -404,6 +404,10 @@ The entry replaces its copy before the copy's price age runs out, so a click fin
404
404
  can reveal however long the page has been open. Pass `onEvent` to observe the entry: `copy`
405
405
  (state, reason, whether it came from the device copy), `renewed`, `open` (what the click found
406
406
  and whether it was used) and `end`, each stamped with `performance.now()`.
407
+ The next copy is painted as soon as the Run of an opening is on screen, so a click right after
408
+ the close reveals it. `result` reports once per opening whether the Customer saw the copy
409
+ (`revealed`) and whether the Run took it over (`adopted`): count hits by `result.adopted`, since
410
+ `open.used` only says the opening tried the copy.
407
411
 
408
412
  #### Predict the first screen
409
413
 
package/README.zh-CN.md CHANGED
@@ -240,6 +240,8 @@ SDK 在入口可用时准备套餐墙,复用设备上的套餐副本,并在
240
240
  移除入口或切换场景时调用 `entry.destroy()`。当前身份结束时,SDK 也会释放该入口。
241
241
  副本的价格有效期到期之前,入口会先画好新副本再替换旧副本,所以页面开了多久点击都能直接显示。
242
242
  传入 `onEvent` 可以观察入口:`copy`(状态、原因、是否来自设备副本)、`renewed`、`open`(点击时找到了什么、是否用上)和 `end`,每条都带 `performance.now()` 时间。
243
+ 打开的 Run 一显示,入口就在它后面画好下一份副本,所以关闭后立刻再点也能直接显示。
244
+ `result` 每次打开报告一次:用户是否看到了副本(`revealed`)、Run 是否接管了它(`adopted`)。命中率按 `result.adopted` 统计,`open.used` 只表示这次打开尝试了副本。
243
245
 
244
246
  #### 预渲染首个 Paywall
245
247
 
@@ -1 +1 @@
1
- import{A as ge,E as it,b as He,c as Ke,d as Ee,h as Ye,i as We,j as Qe,n as Xe,q as tt,z as ot}from"./chunk-FDXBCQBO.js";import{a as rt}from"./chunk-C4HLVYSU.js";import{c as _e,d as Le,e as De,f as Ue,g as Ve,i as Me,m as Ge,n as M,o as Be,q as be,r as _,s as ze,t as $e,u as Je,v as qe}from"./chunk-BT7IC765.js";import{K as U,e as ke,q as Se,r as je}from"./chunk-ME6QTD5Y.js";import{a as pe,b as et}from"./chunk-6QBSJRAD.js";import{a as fe}from"./chunk-KCUE2VFJ.js";import{e as me}from"./chunk-A5WUQLAO.js";import{a as D}from"./chunk-UGATOG2T.js";import{h as ie}from"./chunk-LFR2LWYC.js";import{b as nt}from"./chunk-3VUPVXAV.js";import{a as Ze}from"./chunk-5MRSFLQA.js";import{b as n}from"./chunk-W22ESUYY.js";import{c as Ne,f as Te}from"./chunk-FYMVNLQN.js";var j=n.literal(ke),vt=n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=n.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),at=n.discriminatedUnion("type",[n.strictObject({type:n.literal("guest"),guestToken:xe}),n.strictObject({type:n.literal("customer"),customer:Se,customerData:je.optional()})]),Ae=n.strictObject({id:n.uuid(),runId:n.uuid(),customerId:n.uuid(),requestId:n.uuid(),acceptedAt:n.iso.datetime({offset:!0})}),St=n.strictObject({participantId:n.uuid(),startedAs:n.enum(["guest","identified"]),binding:Ae.omit({runId:!0,requestId:!0}).nullable()}),bt=n.union([He,n.strictObject({type:n.literal("authentication_required"),reason:n.enum(["customer_required","customer_experiment_required"]),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative()})]),Et=Ke.omit({authenticated:!0}).extend({identity:St,instruction:bt.nullable()}),xt=n.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),he={contract:j,customerToken:n.string().regex(fe)},st={contract:j,requestId:n.uuid(),runToken:vt,externalUserId:Se.options[1].shape.value},ut=n.discriminatedUnion("operation",[n.strictObject({contract:j,operation:n.literal("describe")}),n.strictObject({contract:j,operation:n.literal("start"),source:at,funnelId:U.options[0].shape.funnelId,requestId:n.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),Ye.omit({operation:!0}).extend({contract:j,operation:n.literal("entry_start"),source:at}),n.strictObject({...st,operation:n.literal("bind_customer"),guestToken:xe,claimRequestId:n.uuid(),expectedBindingId:n.null()}),n.strictObject({...st,operation:n.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...he,operation:n.literal("get"),settlementBindingId:n.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...he,operation:n.literal("review")}),Qe.omit({customerToken:!0}).extend(he),n.strictObject({...he,operation:n.literal("command"),identity:n.strictObject({bindingId:n.uuid().nullable()}),command:xt})]),At=Ee.omit({run:!0}).extend({contract:j,run:Et,settlement:Ee.shape.settlement.unwrap().extend({accepted:n.boolean().nullable().optional()}).optional()}),Gt=We.extend({contract:j}),Bt=n.discriminatedUnion("operation",[ut.options[1].omit({contract:!0,source:!0,requestId:!0}),ut.options[2].omit({contract:!0,source:!0,requestId:!0})]),zt=At.extend({binding:Ae,outcome:n.enum(["bound","already_bound"]),replayed:n.boolean()}),$t=n.discriminatedUnion("state",[n.strictObject({contract:j,scope:ie,state:n.literal("not_accepted")}),n.strictObject({contract:j,scope:ie,state:n.literal("conflict")}),n.strictObject({contract:j,scope:ie,state:n.literal("bound"),binding:Ae})]),Jt=n.strictObject({contract:j,scope:ie,keyId:n.uuid(),operations:n.array(n.string()).max(20)});var ct=n.string().regex(/^[a-f0-9]{64}$/),Ct=_e.omit({variations:!0,active:!0}).extend({changeId:ct,variations:n.array(n.strictObject({urlRedirect:n.string().max(2048)})).min(2).max(20)}),lt=n.strictObject({environmentId:n.uuid(),trackExposures:n.boolean(),generation:ct,experiments:n.array(Ct).max(100),savedGroups:Le}),Pt=n.strictObject({eventUuid:n.uuid(),timestamp:n.iso.datetime({offset:!0}).optional(),deviceId:n.string().min(1).max(128),sessionId:n.string().min(1).max(128).optional(),url:n.url().max(2048),pageTitle:n.string().max(512).optional(),experimentKey:n.string().min(1).max(255),variationKey:n.string().min(1).max(64)}),Yt=n.strictObject({events:n.array(Pt).min(1).max(20)}),Wt=n.strictObject({inserted:n.number().int().nonnegative(),duplicates:n.number().int().nonnegative(),skipped:n.number().int().nonnegative(),rejected:n.array(n.strictObject({index:n.number().int().nonnegative(),reason:n.string()}))});function nn(i){let a=null,g=null,x=0,I=0,v=new Set,d=null,y=null,m=new Set,S=()=>{for(let s of m)try{s()}catch{}},p={attributes:me.parse(i.attributes??{}),onFeatureUsage:i.onFeatureUsage?(s,E)=>{!v.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&i.onFeatureUsage(s,structuredClone(E),structuredClone(p.attributes),a.generation)}:void 0,onExperimentViewed:i.onExperimentViewed?(s,E)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&i.onExperimentViewed(structuredClone(s),structuredClone(E),structuredClone(p.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(i.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:i.saveStickyBucketAssignmentDoc?s=>i.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},A=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,E=new Set){return v.has(s)?!d||!d.features[s]||["unknownFeature","cyclicPrerequisite"].includes(d.features[s].source):E.has(s)?!1:(E.add(s),(a?.features[s]?.rules??[]).some(O=>[...O.parentConditions??[],...(O.tracks??[]).flatMap(F=>F.experiment.parentConditions??[])].some(F=>h(F.id,E))))}let C=s=>{if(i.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return d?.expiresAt&&Date.parse(d.expiresAt)<=Date.now()&&(d=null,p.features=a.features),v.has(s)?!d||d.expiresAt&&Date.parse(d.expiresAt)<=Date.now()?A():structuredClone(d.features[s]??A()):i.evaluateRemote&&(p.attributes?.merchandise||p.attributes?.merchandiseId)&&!d||h(s)?A():structuredClone(Te(s,p))};async function V(){if(!a||!v.size&&!p.attributes?.merchandise&&!p.attributes?.merchandiseId)return;if(!i.evaluateRemote){if(v.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=I;if(y?.revision===s)return y.loading;let E=x,O=a,F=[...v],P=(async()=>{let b=Me.parse(await i.evaluateRemote({attributes:structuredClone(p.attributes),features:F}));if(!(E!==x||s!==I||O!==a)){if(i.assertUsable?.(O.generation),b.generation!==O.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(F.some(T=>!Object.hasOwn(b.features,T))||Object.keys(b.features).some(T=>!v.has(T)))throw new Error("Invalid remote Feature results");if(p.attributes?.merchandise||p.attributes?.merchandiseId){if(!b.merchandiseContext)throw new Error("Server did not resolve merchandise context");p.attributes=me.parse({...p.attributes,...b.merchandiseContext})}d=structuredClone(b),p.features={...O.features,...Object.fromEntries(Object.entries(d.features).map(([T,$])=>[T,{defaultValue:$.value}]))},S()}})();y={revision:s,loading:P};try{await P}finally{y?.loading===P&&(y=null)}}function L(){V().catch(s=>{try{i.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=x,E=(async()=>{let O=await i.load(),F="remoteFeatures"in O?Ue.parse(O):null,P=F??De.parse(O);if(P.scope.projectId!==i.scope.projectId||P.scope.environment!==i.scope.environment)throw new Error("Feature payload scope changed");if(s!==x)throw new Error("Feature client was reset");if(i.assertUsable&&a?.generation===P.generation){let{evaluatedAt:T,expiresAt:$,...ae}=a,{evaluatedAt:X,expiresAt:ye,...G}=P;if(_(ae)!==_(G))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=P.evaluatedAt,a.expiresAt=P.expiresAt,S(),(!d||d.expiresAt&&Date.parse(d.expiresAt)<=Date.now())&&L(),structuredClone(a)}let b=new Set(F?.remoteFeatures??[]);if([...b].some(T=>Object.hasOwn(P.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in P&&!a.analyticsConfig.experimentViewsEnabled&&F?.analyticsConfig.experimentViewsEnabled&&p.trackedExperiments?.clear(),a=structuredClone(P),v=b,d=null,y=null,I++,p.features=a.features,p.savedGroups=Ne(a.savedGroups),p.trackedFeatureUsage={},S(),L(),structuredClone(a)})();g=E;try{return await E}finally{g===E&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let E=me.parse(s);(p.attributes?.merchandise||p.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&p.trackedExperiments?.clear(),p.attributes=E,I++,d=null,y=null,p.features=a?.features??{},p.trackedFeatureUsage={},S(),L()},evalFeature:C,isOn(s){return C(s).on},isOff(s){return C(s).off},getFeatureValue(s,E){let O=C(s).value;return structuredClone(O===null?E:O)},reset(){x++,I++,g=null,y=null,a=null,d=null,v.clear(),p.features={},p.savedGroups={},p.stickyBucketAssignmentDocs={},p.attributes={},p.trackedFeatureUsage={},p.trackedExperiments?.clear(),S()}}}var Rt=n.record(n.string().regex(/^[a-f0-9]{64}$/),n.strictObject({at:n.number(),text:n.string()})),Q=2*1048576,Ot=100;function Ft(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function dt(i,a){let g=a===void 0?Ft():a,x=new Map,I=0,v=!1,d=!1,y,m;async function S(A){if(!g)return null;let h;try{let C=await Promise.race([Promise.resolve().then(()=>g.getItem(A)),new Promise(V=>{h=setTimeout(()=>V(null),Ot)})]);return typeof C=="string"&&C.length<=Q&&new TextEncoder().encode(C).byteLength<=Q?C:null}catch{return null}finally{clearTimeout(h)}}function p(){if(m)return m;let A=(async()=>{try{let h=await S(`${i}:artifacts`);if(h)return Rt.parse(JSON.parse(h))}catch{}return{}})();return m=A,A.finally(()=>{m===A&&(m=void 0)}),A}return{async readManifest(){return S(i)},writeManifest(A){!g||A.length>Q||new TextEncoder().encode(A).byteLength>Q||(y=A,!d&&(d=!0,Promise.resolve().then(async()=>{try{for(;y!==void 0;){let h=y;try{await g.setItem(i,h)}catch{}y===h&&(y=void 0)}}finally{d=!1}})))},async readArtifact(A){let h=(await p())[A],C=Date.now();return h&&C>=h.at&&C-h.at<=M.retentionMs?h.text:void 0},writeArtifact(A,h){if(!g||h.length>Q)return;let C=x.get(A);if(C?.text===h||!C&&x.size>=128)return;let V=new TextEncoder().encode(h).byteLength;I-(C?.byteLength??0)+V>Q||(x.set(A,{text:h,byteLength:V}),I+=V-(C?.byteLength??0),!v&&(v=!0,Promise.resolve().then(async()=>{try{for(;x.size;){let L=new Map(x);try{let k={...await p()},s=Date.now();for(let[P,b]of L)k[P]={at:s,text:b.text};let E={},O=2,F=0;for(let[P,b]of Object.entries(k).sort(([,T],[,$])=>$.at-T.at)){if(b.at>s||s-b.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[P]:b})).byteLength;O+T>Q||F>=128||(E[P]=b,O+=T,F++)}await g.setItem(`${i}:artifacts`,JSON.stringify(E))}catch{}finally{for(let[k,s]of L)x.get(k)===s&&(x.delete(k),I-=s.byteLength)}}}finally{v=!1}})))}}}var c=(i,a)=>new D(i,a),z=()=>performance.now(),ft=i=>{typeof i=="object"&&"unref"in i&&i.unref()},Nt=12e4;function Tt(i,a,g,x){let I=Object.entries(x.paywalls??{}),v={};for(let d of g.screens){if(d.type!=="paywall")continue;let y=I.find(([,S])=>Object.hasOwn(S.versions,d.paywallVersionId))?.[0];if(!y)continue;let m=v[y]??=[];m.includes(d.paywallVersionId)||m.push(d.paywallVersionId)}for(let d of Object.values(v))d.sort();return{kind:"funnel_paywall_pins",formatVersion:1,funnelId:i,versionId:a,paywalls:v}}function vn(i){let a=Be.parse(i.scope),g=new pe(i.origin??Ze);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw c("INVALID_URL","Configuration requires a trusted HTTPS origin");let x=new Set([g.origin,...(i.assetOrigins??[]).map(e=>{let t=new pe(e);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw c("INVALID_URL","Invalid configuration asset origin");return t.origin})]),I=i.fetch??globalThis.fetch.bind(globalThis),v=`/api/v1/configuration/${a.environmentId}`,d=`indiana:configuration:1:${g.origin}:${_(a)}`,y=dt(d,i.storage),m,S=0,p=0,A=!1,h=!1,C=0,V=0,L,k,s,E,O=0,F=new Set,P=new Set,b=new Map,T=new Map,$=0,ae=!1;function X(){for(let e of F)try{e()}catch{}}function ye(e){try{i.onError?.(e)}catch{}}let G=()=>!h&&!A&&!!m&&z()<S&&Date.now()<p;function re(){if(!G())throw c("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(e,t,o){if(!b.has(e)){for(;b.size&&(b.size>=128||$+o>M.maxCacheBytes);){let r=b.entries().next().value;$-=r[1].byteLength,b.delete(r[0])}b.set(e,{text:t,byteLength:o}),$+=o}}function we(e,t,o){return nt(e,t,{signal:o,error:r=>c("INVALID_RESPONSE",r==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function Ie(e){let t=new pe(e,g);if(!x.has(t.origin)||t.username||t.password||t.hash||t.search)throw c("INVALID_URL","Configuration artifact origin is not trusted");return t.href}async function ve(e,t,o=!1){let r=await I(Ie(e),{method:"GET",credentials:"omit",redirect:"error",cache:o?"default":"no-cache",signal:t,headers:{}});if(r.status===429){let u=r.headers.get("retry-after")??"";O=/^\d+$/.test(u)?Number(u)*1e3:Math.max(0,Date.parse(u)-Date.now())||15e3}if(!r.ok&&r.status!==304)throw c(`CONFIGURATION_HTTP_${r.status}`,"Configuration synchronization failed");return r}function pt(e,t,o){let r=Date.parse(e.headers.get("x-indiana-config-validated-at")??""),u=Date.parse(e.headers.get("x-indiana-config-valid-until")??""),f=Date.parse(e.headers.get("date")??""),l=e.headers.get("age"),w=l!==null&&/^\d+(\.\d+)?$/.test(l)?Number(l)*1e3:NaN;if(![r,u,f,w].every(Number.isFinite)||u<=r||u-r>M.maxControlAgeMs||r>f+1e3)throw c("INVALID_RESPONSE","Configuration freshness evidence is invalid");let R=Math.min(u-r,o.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(w,f-r,0)-(z()-t);if(R<=0)throw c("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return z()+R}function se(){if(clearTimeout(s),clearTimeout(E),h||!F.size||(G()&&(E=setTimeout(()=>{G()?se():X()},Math.max(1,S-z())),ft(E)),typeof document<"u"&&document.visibilityState==="hidden"))return;let e=Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3),t=V>2?Math.min(Nt,e*2**(V-2)):e;s=setTimeout(()=>{Z().catch(ye)},Math.max(O,t*(.8+Math.random()*.2))),ft(s)}async function Z(){if(h)throw c("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let e=C,t=new AbortController;k=t;let o=(async()=>{if(!ae){ae=!0;try{let de=await y.readManifest();if(de&&!m){let q=be.parse(JSON.parse(de));_(q.scope)===_(a)&&(m=q)}}catch{}}t.signal.throwIfAborted();let l=m,w=z(),N=await ve(v,t.signal);N.status===304&&(!l||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await ve(v,t.signal));let R=N.status===304?l:be.parse(JSON.parse(await we(N,M.maxManifestBytes,t.signal))),{generation:te,...ne}=R,J=N.headers.get("etag");if(_(R.scope)!==_(a)||$e(ne)!==te||J!==`"${te}"`&&J!==`W/"${te}"`)throw c("INVALID_RESPONSE","Configuration scope or content identity changed");if(l&&(R.revision<l.revision||R.revision===l.revision&&R.generation!==l.generation))throw c("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[de,q]of Object.entries(l?.funnels??{})){let W=R.funnels[de];if(W&&(W.controlRevision<q.controlRevision||W.evaluationRevision<q.evaluationRevision||W.controlRevision===q.controlRevision&&W.state!==q.state||W.evaluationRevision===q.evaluationRevision&&W.evaluationMode!==q.evaluationMode))throw c("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=pt(N,w,R.policy);if(t.signal.throwIfAborted(),e!==C)throw c("CONFIGURATION_DISPOSED","Configuration scope changed");return m=R,S=Y,p=Date.now()+Math.max(0,Y-z()),A=!1,V=0,O=0,y.writeManifest(_(R)),X(),structuredClone(R)})(),r=setTimeout(()=>t.abort(c("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),u=new Promise((l,w)=>t.signal.addEventListener("abort",()=>w(t.signal.reason),{once:!0})),f=Promise.race([o,u]).catch(l=>{throw V++,(l instanceof n.ZodError||l instanceof SyntaxError||l instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(l.code))&&(S=0,A=!0,X()),l}).finally(()=>{clearTimeout(r),L===f&&(L=void 0),se()});return L=f,f}async function ue(e){let t=e.sha256,o=ne=>rt(ne,e);Ie(e.url);let r=b.get(t);if(r){if(r.byteLength!==e.byteLength)throw c("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return b.delete(t),b.set(t,r),r.text}let u=T.get(t);if(u){if(u.byteLength!==e.byteLength)throw c("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return u.promise}let f=new AbortController;P.add(f);let l=C,w=(async()=>{try{let Y=await y.readArtifact(t);if(Y&&o(Y)){if(f.signal.throwIfAborted(),h||l!==C)throw c("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(t,Y,e.byteLength),Y}}catch{}f.signal.throwIfAborted();let ne=await ve(e.url,f.signal,!0),J=await we(ne,e.byteLength,f.signal);if(!o(J))throw c("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||l!==C)throw c("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(t,J,e.byteLength),y.writeArtifact(t,J),J})(),N=setTimeout(()=>f.abort(c("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),R=new Promise((ne,J)=>f.signal.addEventListener("abort",()=>J(f.signal.reason),{once:!0})),te=Promise.race([w,R]).finally(()=>{clearTimeout(N),P.delete(f),T.delete(t)});return T.set(t,{promise:te,byteLength:e.byteLength}),te}async function K(){return G()||await Z(),re(),m}async function H(e){let t,o=new Promise((r,u)=>{t=setTimeout(()=>u(c("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([e(),o])}finally{clearTimeout(t)}}function B(e,t){if(re(),m?.generation!==e.generation)throw c("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(t&&m.funnels[t]?.state!=="active")throw c("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Pe(e){let t=e.gb.features;if(!t)throw c("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let o=e.artifacts[t];if(o.formatVersion!==1)throw c("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let r=Ve.parse(JSON.parse(await ue(o)));if(_(r.scope)!==_({projectId:a.projectId,environment:a.environment})||r.generation!==o.generation||r.remoteFeatures.some(u=>Object.hasOwn(r.features,u)))throw c("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return B(e),{...r,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,S-z())).toISOString()}}async function Re(e,t){let o=await K(),r=o.funnels[e];t&&(!r||r.evaluationMode==="local"&&!r.versions[t])&&(L&&await L,o=await Z()),B(o,e);let u=o.funnels[e];if(u.evaluationMode!=="local")throw c("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let f=t??u.currentVersionId,l=u.versions[f];if(!l)throw c("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(o.artifacts[l.artifact].formatVersion!==3)throw c("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[w,N]=await Promise.all([ue(o.artifacts[l.artifact]).then(R=>qe(JSON.parse(R))),u.evaluationMode==="local"?Pe(o):void 0]);if(N&&_(Je(w,N))!==_(l.dependencies))throw c("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return B(o,e),{document:w,growth:N,versionId:f,control:structuredClone(u),manifest:structuredClone(o)}}async function ce(e,t){try{return await Re(e,t)}catch(o){if(!(o instanceof D)||!(o.code==="CONFIGURATION_CHANGED"||o.code==="CONFIGURATION_HTTP_404"&&G()))throw o;let r=m?.generation;if(L&&await L,await Z(),o.code!=="CONFIGURATION_CHANGED"&&m?.generation===r)throw o;return Re(e,t)}}let oe=new Map;async function Oe(e,t,o,r){let u=new AbortController;P.add(u);let f=setTimeout(()=>u.abort(c("CONFIGURATION_UNAVAILABLE",`${o} read timed out`)),M.initializationMs);try{let l=await I(Ie(`${v}/${e}`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:u.signal,headers:{}});if(l.status===404)throw c(...r);if(!l.ok)throw c(`CONFIGURATION_HTTP_${l.status}`,`${o} read failed`);let w=await we(l,t,u.signal),N=ze(w),R=l.headers.get("etag");if(R!==`"${N}"`&&R!==`W/"${N}"`)throw c("INVALID_RESPONSE",`${o} identity changed`);return JSON.parse(w)}finally{clearTimeout(f),P.delete(u)}}async function gt(e,t){let{FUNNEL_ROUTE_LIMITS:o,funnelRouteSchema:r}=await import("./funnel-route-source-HYWJWEM3.js"),u=r.safeParse(await Oe(`funnels/${e}/versions/${t}/route`,o.maxBytes,"Funnel route",["ROUTE_UNAVAILABLE","This Funnel Version publishes no route"]));if(!u.success||u.data.funnelId!==e||u.data.versionId!==t)throw c("INVALID_RESPONSE","Funnel route does not describe this Version");return u.data}async function ht(e,t){let{FUNNEL_PAYWALL_PINS_LIMITS:o,funnelPaywallPinsSchema:r}=await import("./funnel-paywall-pins-source-ZK2DZWY3.js"),u=r.safeParse(await Oe(`funnels/${e}/versions/${t}/paywalls`,o.maxBytes,"Funnel Paywall pins",["PAYWALL_PINS_UNAVAILABLE","This Funnel Version publishes no Paywall pins"]));if(!u.success||u.data.funnelId!==e||u.data.versionId!==t)throw c("INVALID_RESPONSE","Funnel Paywall pins do not describe this Version");return u.data}let le=new Map;async function yt(e){let t=await K();B(t,e);let o=t.funnels[e],r=o.currentVersionId,u;if(o.evaluationMode==="local"){let f=await ce(e,r);u=Tt(e,r,f.document,f.manifest)}else{let f=`${e}:${r}`,l=le.get(f);if(!l){let w=ht(e,r);le.set(f,w),w.catch(()=>{le.get(f)===w&&le.delete(f)}),l=w}u=await l}return B(t,e),{pins:structuredClone(u),generation:t.generation}}async function wt(e){let t=await K();B(t,e);let o=t.funnels[e],r=o.currentVersionId,u;if(o.evaluationMode==="local"){let{projectFunnelRoute:f}=await import("./funnel-route-source-HYWJWEM3.js"),l=await ce(e,r),w=Object.entries(l.manifest.paywalls??{});u=f({funnelId:e,versionId:r,document:l.document,experiments:l.growth?.experiments??{},paywallOf:N=>w.find(([,R])=>Object.hasOwn(R.versions,N))?.[0]})}else{let f=`${e}:${r}`,l=oe.get(f);if(!l||z()-l.readAt>=M.maxControlAgeMs){let w={promise:gt(e,r),readAt:z()};oe.set(f,w),w.promise.catch(()=>{oe.get(f)===w&&oe.delete(f)}),l=w}u=await l.promise}return B(t,e),{route:structuredClone(u),control:structuredClone(o),generation:t.generation}}function ee(){if(G()||X(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}Z().catch(ye)}function It(e){if(h)throw c("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return F.add(e),F.size===1&&(typeof window<"u"&&(window.addEventListener("online",ee),window.addEventListener("focus",ee),document.addEventListener("visibilitychange",ee)),se()),()=>{F.delete(e),F.size||(clearTimeout(s),clearTimeout(E),Fe())}}function Fe(){typeof window<"u"&&(window.removeEventListener("online",ee),window.removeEventListener("focus",ee),document.removeEventListener("visibilitychange",ee))}return{scope:Object.freeze({...a}),refresh:Z,subscribe:It,assertFresh:re,assertFeatures(e){re();let t=m.gb.features;if(!t)throw c("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(e!==void 0&&m.artifacts[t].generation!==e)throw c("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return G()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return G()?Math.max(0,S-z()):0},async features(){return H(async()=>Pe(await K()))},pageExperiments:()=>H(async()=>{let e=await K(),t=e.gb.pageExperiments;if(!t)throw c("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let o=e.artifacts[t];if(o.formatVersion!==1)throw c("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let r=lt.parse(JSON.parse(await ue(o)));if(r.environmentId!==a.environmentId||r.generation!==o.generation)throw c("INVALID_RESPONSE","Page experiment scope or generation changed");return B(e),r}),funnel:(e,t)=>H(()=>ce(e,t)),funnelControl:e=>H(async()=>{let t=await K();return B(t,e),structuredClone(t.funnels[e])}),funnelRoute:e=>H(()=>wt(e)),funnelPaywallPins:e=>H(()=>yt(e)),paywall:(e,t)=>H(async()=>{let o=await K(),r=o.paywalls?.[e];if(!r||!t&&r.state!=="published")throw c("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let u=t??r.currentVersionId,f=r.versions[u],l=f&&o.artifacts[f.artifact];if(!l||l.kind!=="paywall"||l.formatVersion!==1)throw c("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let w=Ge.parse(JSON.parse(await ue(l)));return B(o),{document:w,versionId:u,version:f.version,control:structuredClone(r),manifest:structuredClone(o)}}),async localFunnel(e,t){let o=await H(()=>ce(e,t));if(!o.growth)throw c("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:r,remoteFeatures:u,...f}=o.growth;return Xe({scope:{projectId:a.projectId,environment:a.environment},funnelId:e,versionId:o.versionId,evaluationMode:"local",evaluationRevision:o.control.evaluationRevision,document:o.document,payload:f})},assertFunnel(e,t,o){re();let r=m.funnels[e];if(!r||r.state!=="active")throw c("FUNNEL_STOPPED","Funnel is paused or unavailable");if(r.evaluationMode!=="local")throw c("EVALUATION_MODE","This Funnel now executes at Longplay");if(t!==void 0&&r.controlRevision!==t)throw c("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(o!==void 0&&!r.versions[o])throw c("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,C++,S=0,k?.abort(c("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(E),Fe(),X(),F.clear();for(let e of P)e.abort(c("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));b.clear(),oe.clear(),$=0}}}}function mt(i){let a=fe.test(i.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!ge.test(i.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let x=U.safeParse({...g,operation:"start"});if(!x.success||x.data.operation!=="start"||(a?x.data.customer!==void 0:x.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let I=x.data,v=et({...i,timeoutMs:i.timeoutMs??35e3});try{i.session||v.identify(i.apiKey);let d=tt(i,await v.request("funnels",I));if(!d.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(d.run.source.id!==I.funnelId||d.run.locale!==(I.locale??"en")||!ot(d.run.parameters,I.parameters??{})||(I.customer?!d.customerId||I.customer.type==="id"&&d.customerId!==I.customer.value:d.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...d,runToken:d.runToken}}finally{v.dispose()}}}}async function Ln(i){i={...i};let a=i.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(i.scope&&_(g)!==_(i.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(i.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let I=ge.test(i.credential);if(I?!i.customerId:i.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let v=mt({...i,scope:g,apiKey:i.credential}),d=(y,m)=>{let S=it({...i,scope:g,runToken:y,initialResponse:m,...I?{serverKey:i.credential}:{}});return I||S.identify(i.credential),S};return{async start(y){let m=await v.start({...y,funnelId:i.funnelId,...I?{customer:{type:"id",value:i.customerId}}:{}}),S=d(m.runToken,m),p=await S.get();return{...m,...p,controller:S}},async restore(y){let m=d(y),S=await m.get();if(S.run.source.id!==i.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...S,runToken:y,controller:m}}}}export{ut as a,At as b,Gt as c,Bt as d,zt as e,$t as f,Jt as g,nn as h,vn as i,mt as j,Ln as k};
1
+ import{A as ge,E as it,b as He,c as Ke,d as Ee,h as Ye,i as We,j as Qe,n as Xe,q as tt,z as ot}from"./chunk-MYG5MAKQ.js";import{a as rt}from"./chunk-DLORK3P2.js";import{c as _e,d as Le,e as De,f as Ue,g as Ve,i as Me,m as Ge,n as M,o as Be,q as be,r as _,s as ze,t as $e,u as Je,v as qe}from"./chunk-BT7IC765.js";import{K as U,e as ke,q as Se,r as je}from"./chunk-ME6QTD5Y.js";import{a as pe,b as et}from"./chunk-7JJGSLXD.js";import{a as fe}from"./chunk-KCUE2VFJ.js";import{e as me}from"./chunk-A5WUQLAO.js";import{a as D}from"./chunk-UGATOG2T.js";import{h as ie}from"./chunk-LFR2LWYC.js";import{b as nt}from"./chunk-3VUPVXAV.js";import{a as Ze}from"./chunk-5MRSFLQA.js";import{b as n}from"./chunk-W22ESUYY.js";import{c as Ne,f as Te}from"./chunk-FYMVNLQN.js";var j=n.literal(ke),vt=n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=n.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),at=n.discriminatedUnion("type",[n.strictObject({type:n.literal("guest"),guestToken:xe}),n.strictObject({type:n.literal("customer"),customer:Se,customerData:je.optional()})]),Ae=n.strictObject({id:n.uuid(),runId:n.uuid(),customerId:n.uuid(),requestId:n.uuid(),acceptedAt:n.iso.datetime({offset:!0})}),St=n.strictObject({participantId:n.uuid(),startedAs:n.enum(["guest","identified"]),binding:Ae.omit({runId:!0,requestId:!0}).nullable()}),bt=n.union([He,n.strictObject({type:n.literal("authentication_required"),reason:n.enum(["customer_required","customer_experiment_required"]),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative()})]),Et=Ke.omit({authenticated:!0}).extend({identity:St,instruction:bt.nullable()}),xt=n.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),he={contract:j,customerToken:n.string().regex(fe)},st={contract:j,requestId:n.uuid(),runToken:vt,externalUserId:Se.options[1].shape.value},ut=n.discriminatedUnion("operation",[n.strictObject({contract:j,operation:n.literal("describe")}),n.strictObject({contract:j,operation:n.literal("start"),source:at,funnelId:U.options[0].shape.funnelId,requestId:n.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),Ye.omit({operation:!0}).extend({contract:j,operation:n.literal("entry_start"),source:at}),n.strictObject({...st,operation:n.literal("bind_customer"),guestToken:xe,claimRequestId:n.uuid(),expectedBindingId:n.null()}),n.strictObject({...st,operation:n.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...he,operation:n.literal("get"),settlementBindingId:n.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...he,operation:n.literal("review")}),Qe.omit({customerToken:!0}).extend(he),n.strictObject({...he,operation:n.literal("command"),identity:n.strictObject({bindingId:n.uuid().nullable()}),command:xt})]),At=Ee.omit({run:!0}).extend({contract:j,run:Et,settlement:Ee.shape.settlement.unwrap().extend({accepted:n.boolean().nullable().optional()}).optional()}),Gt=We.extend({contract:j}),Bt=n.discriminatedUnion("operation",[ut.options[1].omit({contract:!0,source:!0,requestId:!0}),ut.options[2].omit({contract:!0,source:!0,requestId:!0})]),zt=At.extend({binding:Ae,outcome:n.enum(["bound","already_bound"]),replayed:n.boolean()}),$t=n.discriminatedUnion("state",[n.strictObject({contract:j,scope:ie,state:n.literal("not_accepted")}),n.strictObject({contract:j,scope:ie,state:n.literal("conflict")}),n.strictObject({contract:j,scope:ie,state:n.literal("bound"),binding:Ae})]),Jt=n.strictObject({contract:j,scope:ie,keyId:n.uuid(),operations:n.array(n.string()).max(20)});var ct=n.string().regex(/^[a-f0-9]{64}$/),Ct=_e.omit({variations:!0,active:!0}).extend({changeId:ct,variations:n.array(n.strictObject({urlRedirect:n.string().max(2048)})).min(2).max(20)}),lt=n.strictObject({environmentId:n.uuid(),trackExposures:n.boolean(),generation:ct,experiments:n.array(Ct).max(100),savedGroups:Le}),Pt=n.strictObject({eventUuid:n.uuid(),timestamp:n.iso.datetime({offset:!0}).optional(),deviceId:n.string().min(1).max(128),sessionId:n.string().min(1).max(128).optional(),url:n.url().max(2048),pageTitle:n.string().max(512).optional(),experimentKey:n.string().min(1).max(255),variationKey:n.string().min(1).max(64)}),Yt=n.strictObject({events:n.array(Pt).min(1).max(20)}),Wt=n.strictObject({inserted:n.number().int().nonnegative(),duplicates:n.number().int().nonnegative(),skipped:n.number().int().nonnegative(),rejected:n.array(n.strictObject({index:n.number().int().nonnegative(),reason:n.string()}))});function nn(i){let a=null,g=null,x=0,I=0,v=new Set,d=null,y=null,m=new Set,S=()=>{for(let s of m)try{s()}catch{}},p={attributes:me.parse(i.attributes??{}),onFeatureUsage:i.onFeatureUsage?(s,E)=>{!v.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&i.onFeatureUsage(s,structuredClone(E),structuredClone(p.attributes),a.generation)}:void 0,onExperimentViewed:i.onExperimentViewed?(s,E)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&i.onExperimentViewed(structuredClone(s),structuredClone(E),structuredClone(p.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(i.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:i.saveStickyBucketAssignmentDoc?s=>i.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},A=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,E=new Set){return v.has(s)?!d||!d.features[s]||["unknownFeature","cyclicPrerequisite"].includes(d.features[s].source):E.has(s)?!1:(E.add(s),(a?.features[s]?.rules??[]).some(O=>[...O.parentConditions??[],...(O.tracks??[]).flatMap(F=>F.experiment.parentConditions??[])].some(F=>h(F.id,E))))}let C=s=>{if(i.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return d?.expiresAt&&Date.parse(d.expiresAt)<=Date.now()&&(d=null,p.features=a.features),v.has(s)?!d||d.expiresAt&&Date.parse(d.expiresAt)<=Date.now()?A():structuredClone(d.features[s]??A()):i.evaluateRemote&&(p.attributes?.merchandise||p.attributes?.merchandiseId)&&!d||h(s)?A():structuredClone(Te(s,p))};async function V(){if(!a||!v.size&&!p.attributes?.merchandise&&!p.attributes?.merchandiseId)return;if(!i.evaluateRemote){if(v.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=I;if(y?.revision===s)return y.loading;let E=x,O=a,F=[...v],P=(async()=>{let b=Me.parse(await i.evaluateRemote({attributes:structuredClone(p.attributes),features:F}));if(!(E!==x||s!==I||O!==a)){if(i.assertUsable?.(O.generation),b.generation!==O.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(F.some(T=>!Object.hasOwn(b.features,T))||Object.keys(b.features).some(T=>!v.has(T)))throw new Error("Invalid remote Feature results");if(p.attributes?.merchandise||p.attributes?.merchandiseId){if(!b.merchandiseContext)throw new Error("Server did not resolve merchandise context");p.attributes=me.parse({...p.attributes,...b.merchandiseContext})}d=structuredClone(b),p.features={...O.features,...Object.fromEntries(Object.entries(d.features).map(([T,$])=>[T,{defaultValue:$.value}]))},S()}})();y={revision:s,loading:P};try{await P}finally{y?.loading===P&&(y=null)}}function L(){V().catch(s=>{try{i.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=x,E=(async()=>{let O=await i.load(),F="remoteFeatures"in O?Ue.parse(O):null,P=F??De.parse(O);if(P.scope.projectId!==i.scope.projectId||P.scope.environment!==i.scope.environment)throw new Error("Feature payload scope changed");if(s!==x)throw new Error("Feature client was reset");if(i.assertUsable&&a?.generation===P.generation){let{evaluatedAt:T,expiresAt:$,...ae}=a,{evaluatedAt:X,expiresAt:ye,...G}=P;if(_(ae)!==_(G))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=P.evaluatedAt,a.expiresAt=P.expiresAt,S(),(!d||d.expiresAt&&Date.parse(d.expiresAt)<=Date.now())&&L(),structuredClone(a)}let b=new Set(F?.remoteFeatures??[]);if([...b].some(T=>Object.hasOwn(P.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in P&&!a.analyticsConfig.experimentViewsEnabled&&F?.analyticsConfig.experimentViewsEnabled&&p.trackedExperiments?.clear(),a=structuredClone(P),v=b,d=null,y=null,I++,p.features=a.features,p.savedGroups=Ne(a.savedGroups),p.trackedFeatureUsage={},S(),L(),structuredClone(a)})();g=E;try{return await E}finally{g===E&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let E=me.parse(s);(p.attributes?.merchandise||p.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&p.trackedExperiments?.clear(),p.attributes=E,I++,d=null,y=null,p.features=a?.features??{},p.trackedFeatureUsage={},S(),L()},evalFeature:C,isOn(s){return C(s).on},isOff(s){return C(s).off},getFeatureValue(s,E){let O=C(s).value;return structuredClone(O===null?E:O)},reset(){x++,I++,g=null,y=null,a=null,d=null,v.clear(),p.features={},p.savedGroups={},p.stickyBucketAssignmentDocs={},p.attributes={},p.trackedFeatureUsage={},p.trackedExperiments?.clear(),S()}}}var Rt=n.record(n.string().regex(/^[a-f0-9]{64}$/),n.strictObject({at:n.number(),text:n.string()})),Q=2*1048576,Ot=100;function Ft(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function dt(i,a){let g=a===void 0?Ft():a,x=new Map,I=0,v=!1,d=!1,y,m;async function S(A){if(!g)return null;let h;try{let C=await Promise.race([Promise.resolve().then(()=>g.getItem(A)),new Promise(V=>{h=setTimeout(()=>V(null),Ot)})]);return typeof C=="string"&&C.length<=Q&&new TextEncoder().encode(C).byteLength<=Q?C:null}catch{return null}finally{clearTimeout(h)}}function p(){if(m)return m;let A=(async()=>{try{let h=await S(`${i}:artifacts`);if(h)return Rt.parse(JSON.parse(h))}catch{}return{}})();return m=A,A.finally(()=>{m===A&&(m=void 0)}),A}return{async readManifest(){return S(i)},writeManifest(A){!g||A.length>Q||new TextEncoder().encode(A).byteLength>Q||(y=A,!d&&(d=!0,Promise.resolve().then(async()=>{try{for(;y!==void 0;){let h=y;try{await g.setItem(i,h)}catch{}y===h&&(y=void 0)}}finally{d=!1}})))},async readArtifact(A){let h=(await p())[A],C=Date.now();return h&&C>=h.at&&C-h.at<=M.retentionMs?h.text:void 0},writeArtifact(A,h){if(!g||h.length>Q)return;let C=x.get(A);if(C?.text===h||!C&&x.size>=128)return;let V=new TextEncoder().encode(h).byteLength;I-(C?.byteLength??0)+V>Q||(x.set(A,{text:h,byteLength:V}),I+=V-(C?.byteLength??0),!v&&(v=!0,Promise.resolve().then(async()=>{try{for(;x.size;){let L=new Map(x);try{let k={...await p()},s=Date.now();for(let[P,b]of L)k[P]={at:s,text:b.text};let E={},O=2,F=0;for(let[P,b]of Object.entries(k).sort(([,T],[,$])=>$.at-T.at)){if(b.at>s||s-b.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[P]:b})).byteLength;O+T>Q||F>=128||(E[P]=b,O+=T,F++)}await g.setItem(`${i}:artifacts`,JSON.stringify(E))}catch{}finally{for(let[k,s]of L)x.get(k)===s&&(x.delete(k),I-=s.byteLength)}}}finally{v=!1}})))}}}var c=(i,a)=>new D(i,a),z=()=>performance.now(),ft=i=>{typeof i=="object"&&"unref"in i&&i.unref()},Nt=12e4;function Tt(i,a,g,x){let I=Object.entries(x.paywalls??{}),v={};for(let d of g.screens){if(d.type!=="paywall")continue;let y=I.find(([,S])=>Object.hasOwn(S.versions,d.paywallVersionId))?.[0];if(!y)continue;let m=v[y]??=[];m.includes(d.paywallVersionId)||m.push(d.paywallVersionId)}for(let d of Object.values(v))d.sort();return{kind:"funnel_paywall_pins",formatVersion:1,funnelId:i,versionId:a,paywalls:v}}function vn(i){let a=Be.parse(i.scope),g=new pe(i.origin??Ze);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw c("INVALID_URL","Configuration requires a trusted HTTPS origin");let x=new Set([g.origin,...(i.assetOrigins??[]).map(e=>{let t=new pe(e);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw c("INVALID_URL","Invalid configuration asset origin");return t.origin})]),I=i.fetch??globalThis.fetch.bind(globalThis),v=`/api/v1/configuration/${a.environmentId}`,d=`indiana:configuration:1:${g.origin}:${_(a)}`,y=dt(d,i.storage),m,S=0,p=0,A=!1,h=!1,C=0,V=0,L,k,s,E,O=0,F=new Set,P=new Set,b=new Map,T=new Map,$=0,ae=!1;function X(){for(let e of F)try{e()}catch{}}function ye(e){try{i.onError?.(e)}catch{}}let G=()=>!h&&!A&&!!m&&z()<S&&Date.now()<p;function re(){if(!G())throw c("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(e,t,o){if(!b.has(e)){for(;b.size&&(b.size>=128||$+o>M.maxCacheBytes);){let r=b.entries().next().value;$-=r[1].byteLength,b.delete(r[0])}b.set(e,{text:t,byteLength:o}),$+=o}}function we(e,t,o){return nt(e,t,{signal:o,error:r=>c("INVALID_RESPONSE",r==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function Ie(e){let t=new pe(e,g);if(!x.has(t.origin)||t.username||t.password||t.hash||t.search)throw c("INVALID_URL","Configuration artifact origin is not trusted");return t.href}async function ve(e,t,o=!1){let r=await I(Ie(e),{method:"GET",credentials:"omit",redirect:"error",cache:o?"default":"no-cache",signal:t,headers:{}});if(r.status===429){let u=r.headers.get("retry-after")??"";O=/^\d+$/.test(u)?Number(u)*1e3:Math.max(0,Date.parse(u)-Date.now())||15e3}if(!r.ok&&r.status!==304)throw c(`CONFIGURATION_HTTP_${r.status}`,"Configuration synchronization failed");return r}function pt(e,t,o){let r=Date.parse(e.headers.get("x-indiana-config-validated-at")??""),u=Date.parse(e.headers.get("x-indiana-config-valid-until")??""),f=Date.parse(e.headers.get("date")??""),l=e.headers.get("age"),w=l!==null&&/^\d+(\.\d+)?$/.test(l)?Number(l)*1e3:NaN;if(![r,u,f,w].every(Number.isFinite)||u<=r||u-r>M.maxControlAgeMs||r>f+1e3)throw c("INVALID_RESPONSE","Configuration freshness evidence is invalid");let R=Math.min(u-r,o.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(w,f-r,0)-(z()-t);if(R<=0)throw c("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return z()+R}function se(){if(clearTimeout(s),clearTimeout(E),h||!F.size||(G()&&(E=setTimeout(()=>{G()?se():X()},Math.max(1,S-z())),ft(E)),typeof document<"u"&&document.visibilityState==="hidden"))return;let e=Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3),t=V>2?Math.min(Nt,e*2**(V-2)):e;s=setTimeout(()=>{Z().catch(ye)},Math.max(O,t*(.8+Math.random()*.2))),ft(s)}async function Z(){if(h)throw c("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let e=C,t=new AbortController;k=t;let o=(async()=>{if(!ae){ae=!0;try{let de=await y.readManifest();if(de&&!m){let q=be.parse(JSON.parse(de));_(q.scope)===_(a)&&(m=q)}}catch{}}t.signal.throwIfAborted();let l=m,w=z(),N=await ve(v,t.signal);N.status===304&&(!l||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await ve(v,t.signal));let R=N.status===304?l:be.parse(JSON.parse(await we(N,M.maxManifestBytes,t.signal))),{generation:te,...ne}=R,J=N.headers.get("etag");if(_(R.scope)!==_(a)||$e(ne)!==te||J!==`"${te}"`&&J!==`W/"${te}"`)throw c("INVALID_RESPONSE","Configuration scope or content identity changed");if(l&&(R.revision<l.revision||R.revision===l.revision&&R.generation!==l.generation))throw c("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[de,q]of Object.entries(l?.funnels??{})){let W=R.funnels[de];if(W&&(W.controlRevision<q.controlRevision||W.evaluationRevision<q.evaluationRevision||W.controlRevision===q.controlRevision&&W.state!==q.state||W.evaluationRevision===q.evaluationRevision&&W.evaluationMode!==q.evaluationMode))throw c("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=pt(N,w,R.policy);if(t.signal.throwIfAborted(),e!==C)throw c("CONFIGURATION_DISPOSED","Configuration scope changed");return m=R,S=Y,p=Date.now()+Math.max(0,Y-z()),A=!1,V=0,O=0,y.writeManifest(_(R)),X(),structuredClone(R)})(),r=setTimeout(()=>t.abort(c("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),u=new Promise((l,w)=>t.signal.addEventListener("abort",()=>w(t.signal.reason),{once:!0})),f=Promise.race([o,u]).catch(l=>{throw V++,(l instanceof n.ZodError||l instanceof SyntaxError||l instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(l.code))&&(S=0,A=!0,X()),l}).finally(()=>{clearTimeout(r),L===f&&(L=void 0),se()});return L=f,f}async function ue(e){let t=e.sha256,o=ne=>rt(ne,e);Ie(e.url);let r=b.get(t);if(r){if(r.byteLength!==e.byteLength)throw c("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return b.delete(t),b.set(t,r),r.text}let u=T.get(t);if(u){if(u.byteLength!==e.byteLength)throw c("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return u.promise}let f=new AbortController;P.add(f);let l=C,w=(async()=>{try{let Y=await y.readArtifact(t);if(Y&&o(Y)){if(f.signal.throwIfAborted(),h||l!==C)throw c("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(t,Y,e.byteLength),Y}}catch{}f.signal.throwIfAborted();let ne=await ve(e.url,f.signal,!0),J=await we(ne,e.byteLength,f.signal);if(!o(J))throw c("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||l!==C)throw c("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(t,J,e.byteLength),y.writeArtifact(t,J),J})(),N=setTimeout(()=>f.abort(c("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),R=new Promise((ne,J)=>f.signal.addEventListener("abort",()=>J(f.signal.reason),{once:!0})),te=Promise.race([w,R]).finally(()=>{clearTimeout(N),P.delete(f),T.delete(t)});return T.set(t,{promise:te,byteLength:e.byteLength}),te}async function K(){return G()||await Z(),re(),m}async function H(e){let t,o=new Promise((r,u)=>{t=setTimeout(()=>u(c("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([e(),o])}finally{clearTimeout(t)}}function B(e,t){if(re(),m?.generation!==e.generation)throw c("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(t&&m.funnels[t]?.state!=="active")throw c("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Pe(e){let t=e.gb.features;if(!t)throw c("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let o=e.artifacts[t];if(o.formatVersion!==1)throw c("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let r=Ve.parse(JSON.parse(await ue(o)));if(_(r.scope)!==_({projectId:a.projectId,environment:a.environment})||r.generation!==o.generation||r.remoteFeatures.some(u=>Object.hasOwn(r.features,u)))throw c("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return B(e),{...r,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,S-z())).toISOString()}}async function Re(e,t){let o=await K(),r=o.funnels[e];t&&(!r||r.evaluationMode==="local"&&!r.versions[t])&&(L&&await L,o=await Z()),B(o,e);let u=o.funnels[e];if(u.evaluationMode!=="local")throw c("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let f=t??u.currentVersionId,l=u.versions[f];if(!l)throw c("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(o.artifacts[l.artifact].formatVersion!==3)throw c("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[w,N]=await Promise.all([ue(o.artifacts[l.artifact]).then(R=>qe(JSON.parse(R))),u.evaluationMode==="local"?Pe(o):void 0]);if(N&&_(Je(w,N))!==_(l.dependencies))throw c("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return B(o,e),{document:w,growth:N,versionId:f,control:structuredClone(u),manifest:structuredClone(o)}}async function ce(e,t){try{return await Re(e,t)}catch(o){if(!(o instanceof D)||!(o.code==="CONFIGURATION_CHANGED"||o.code==="CONFIGURATION_HTTP_404"&&G()))throw o;let r=m?.generation;if(L&&await L,await Z(),o.code!=="CONFIGURATION_CHANGED"&&m?.generation===r)throw o;return Re(e,t)}}let oe=new Map;async function Oe(e,t,o,r){let u=new AbortController;P.add(u);let f=setTimeout(()=>u.abort(c("CONFIGURATION_UNAVAILABLE",`${o} read timed out`)),M.initializationMs);try{let l=await I(Ie(`${v}/${e}`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:u.signal,headers:{}});if(l.status===404)throw c(...r);if(!l.ok)throw c(`CONFIGURATION_HTTP_${l.status}`,`${o} read failed`);let w=await we(l,t,u.signal),N=ze(w),R=l.headers.get("etag");if(R!==`"${N}"`&&R!==`W/"${N}"`)throw c("INVALID_RESPONSE",`${o} identity changed`);return JSON.parse(w)}finally{clearTimeout(f),P.delete(u)}}async function gt(e,t){let{FUNNEL_ROUTE_LIMITS:o,funnelRouteSchema:r}=await import("./funnel-route-source-HYWJWEM3.js"),u=r.safeParse(await Oe(`funnels/${e}/versions/${t}/route`,o.maxBytes,"Funnel route",["ROUTE_UNAVAILABLE","This Funnel Version publishes no route"]));if(!u.success||u.data.funnelId!==e||u.data.versionId!==t)throw c("INVALID_RESPONSE","Funnel route does not describe this Version");return u.data}async function ht(e,t){let{FUNNEL_PAYWALL_PINS_LIMITS:o,funnelPaywallPinsSchema:r}=await import("./funnel-paywall-pins-source-ZK2DZWY3.js"),u=r.safeParse(await Oe(`funnels/${e}/versions/${t}/paywalls`,o.maxBytes,"Funnel Paywall pins",["PAYWALL_PINS_UNAVAILABLE","This Funnel Version publishes no Paywall pins"]));if(!u.success||u.data.funnelId!==e||u.data.versionId!==t)throw c("INVALID_RESPONSE","Funnel Paywall pins do not describe this Version");return u.data}let le=new Map;async function yt(e){let t=await K();B(t,e);let o=t.funnels[e],r=o.currentVersionId,u;if(o.evaluationMode==="local"){let f=await ce(e,r);u=Tt(e,r,f.document,f.manifest)}else{let f=`${e}:${r}`,l=le.get(f);if(!l){let w=ht(e,r);le.set(f,w),w.catch(()=>{le.get(f)===w&&le.delete(f)}),l=w}u=await l}return B(t,e),{pins:structuredClone(u),generation:t.generation}}async function wt(e){let t=await K();B(t,e);let o=t.funnels[e],r=o.currentVersionId,u;if(o.evaluationMode==="local"){let{projectFunnelRoute:f}=await import("./funnel-route-source-HYWJWEM3.js"),l=await ce(e,r),w=Object.entries(l.manifest.paywalls??{});u=f({funnelId:e,versionId:r,document:l.document,experiments:l.growth?.experiments??{},paywallOf:N=>w.find(([,R])=>Object.hasOwn(R.versions,N))?.[0]})}else{let f=`${e}:${r}`,l=oe.get(f);if(!l||z()-l.readAt>=M.maxControlAgeMs){let w={promise:gt(e,r),readAt:z()};oe.set(f,w),w.promise.catch(()=>{oe.get(f)===w&&oe.delete(f)}),l=w}u=await l.promise}return B(t,e),{route:structuredClone(u),control:structuredClone(o),generation:t.generation}}function ee(){if(G()||X(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}Z().catch(ye)}function It(e){if(h)throw c("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return F.add(e),F.size===1&&(typeof window<"u"&&(window.addEventListener("online",ee),window.addEventListener("focus",ee),document.addEventListener("visibilitychange",ee)),se()),()=>{F.delete(e),F.size||(clearTimeout(s),clearTimeout(E),Fe())}}function Fe(){typeof window<"u"&&(window.removeEventListener("online",ee),window.removeEventListener("focus",ee),document.removeEventListener("visibilitychange",ee))}return{scope:Object.freeze({...a}),refresh:Z,subscribe:It,assertFresh:re,assertFeatures(e){re();let t=m.gb.features;if(!t)throw c("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(e!==void 0&&m.artifacts[t].generation!==e)throw c("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return G()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return G()?Math.max(0,S-z()):0},async features(){return H(async()=>Pe(await K()))},pageExperiments:()=>H(async()=>{let e=await K(),t=e.gb.pageExperiments;if(!t)throw c("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let o=e.artifacts[t];if(o.formatVersion!==1)throw c("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let r=lt.parse(JSON.parse(await ue(o)));if(r.environmentId!==a.environmentId||r.generation!==o.generation)throw c("INVALID_RESPONSE","Page experiment scope or generation changed");return B(e),r}),funnel:(e,t)=>H(()=>ce(e,t)),funnelControl:e=>H(async()=>{let t=await K();return B(t,e),structuredClone(t.funnels[e])}),funnelRoute:e=>H(()=>wt(e)),funnelPaywallPins:e=>H(()=>yt(e)),paywall:(e,t)=>H(async()=>{let o=await K(),r=o.paywalls?.[e];if(!r||!t&&r.state!=="published")throw c("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let u=t??r.currentVersionId,f=r.versions[u],l=f&&o.artifacts[f.artifact];if(!l||l.kind!=="paywall"||l.formatVersion!==1)throw c("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let w=Ge.parse(JSON.parse(await ue(l)));return B(o),{document:w,versionId:u,version:f.version,control:structuredClone(r),manifest:structuredClone(o)}}),async localFunnel(e,t){let o=await H(()=>ce(e,t));if(!o.growth)throw c("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:r,remoteFeatures:u,...f}=o.growth;return Xe({scope:{projectId:a.projectId,environment:a.environment},funnelId:e,versionId:o.versionId,evaluationMode:"local",evaluationRevision:o.control.evaluationRevision,document:o.document,payload:f})},assertFunnel(e,t,o){re();let r=m.funnels[e];if(!r||r.state!=="active")throw c("FUNNEL_STOPPED","Funnel is paused or unavailable");if(r.evaluationMode!=="local")throw c("EVALUATION_MODE","This Funnel now executes at Longplay");if(t!==void 0&&r.controlRevision!==t)throw c("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(o!==void 0&&!r.versions[o])throw c("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,C++,S=0,k?.abort(c("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(E),Fe(),X(),F.clear();for(let e of P)e.abort(c("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));b.clear(),oe.clear(),$=0}}}}function mt(i){let a=fe.test(i.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!ge.test(i.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let x=U.safeParse({...g,operation:"start"});if(!x.success||x.data.operation!=="start"||(a?x.data.customer!==void 0:x.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let I=x.data,v=et({...i,timeoutMs:i.timeoutMs??35e3});try{i.session||v.identify(i.apiKey);let d=tt(i,await v.request("funnels",I));if(!d.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(d.run.source.id!==I.funnelId||d.run.locale!==(I.locale??"en")||!ot(d.run.parameters,I.parameters??{})||(I.customer?!d.customerId||I.customer.type==="id"&&d.customerId!==I.customer.value:d.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...d,runToken:d.runToken}}finally{v.dispose()}}}}async function Ln(i){i={...i};let a=i.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(i.scope&&_(g)!==_(i.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(i.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let I=ge.test(i.credential);if(I?!i.customerId:i.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let v=mt({...i,scope:g,apiKey:i.credential}),d=(y,m)=>{let S=it({...i,scope:g,runToken:y,initialResponse:m,...I?{serverKey:i.credential}:{}});return I||S.identify(i.credential),S};return{async start(y){let m=await v.start({...y,funnelId:i.funnelId,...I?{customer:{type:"id",value:i.customerId}}:{}}),S=d(m.runToken,m),p=await S.get();return{...m,...p,controller:S}},async restore(y){let m=d(y),S=await m.get();if(S.run.source.id!==i.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...S,runToken:y,controller:m}}}}export{ut as a,At as b,Gt as c,Bt as d,zt as e,$t as f,Jt as g,nn as h,vn as i,mt as j,Ln as k};
@@ -1 +1 @@
1
- import{a as Se,b as Re}from"./chunk-7CZEXBQY.js";import{d as We,e as te}from"./chunk-MOIVJERE.js";import{a as Ue}from"./chunk-UGATOG2T.js";import{a as k}from"./chunk-DSPLGTQI.js";var rn=5*6e4,tn=15e3,Ge=new WeakMap;function dn(u){return Ge.get(u)}var V=u=>Array.isArray(u)?u.map(V):u&&typeof u=="object"?Object.fromEntries(Object.keys(u).sort().map(n=>[n,V(u[n])])):u,L=(u,n)=>JSON.stringify(V(u))===JSON.stringify(V(n)),ae=u=>JSON.stringify(V([u.funnelId,u.locale??null,u.parameters??{}])),an=["onObservationChange","onPurchaseIntent","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","beforeCheckoutReplacement","purchaseConfirmation","confirmOnHostedCheckout","resolveOfferId","prepareSubscriptionChange","resolveSubscriptionChange","onOpenUrl","onEvent","onAction","onComplete","onError"];function on(u,n,I){let O=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),g,_="",T=n.start instanceof Promise?void 0:O(n.start),j=T?.funnelId??n.funnelId,oe=e=>e?.parameters?.commerce,J=Promise.resolve(n.start).then(e=>e?O(e):void 0),le=n.maxAgeMs??rn,Ae=new AbortController,y=AbortSignal.any([Ae.signal,n.client.identitySignal,...n.signal?[n.signal]:[]]),ie=()=>d("released","aborted"),t="preparing",ke,U,se=()=>{},W=0,b=null,v=null,C=null,w=null,h,x,E,Ve=new Map,P=null,G=new Set,F=new Map,ce,_e=new Promise(e=>ce=e),B,ue=new Promise(e=>B=e),de,Be=new Promise(e=>de=e);function K(e,r){t!==e&&(t=e,ke=r,k(n.onState,e))}function Ke(){y.removeEventListener("abort",ie),Q(),v?.destroy(),v=null,b?.remove(),b=null,C=null}function d(e,r){["adopted","unavailable","released","closed"].includes(t)||(K(e,r),Ke(),ce(!1),B(!1),$(!1),de(null))}function N(e){t!=="shown"&&d("unavailable",e)}let f,fe=!1,D=n.client.paywallCopies,pe,Ee=new Promise(e=>pe=e),we=!1,S=!1,ye,z=!1,X=n.whenPurchasePending==="recover"&&!I,$,ze=new Promise(e=>$=e);function Xe(e){if(!X||f||!e||!w||!E||!R(w,E.commerce)||!["preparing","ready","shown"].includes(t))return!1;let r={savedAt:Date.now(),funnelId:e,context:E,resolution:structuredClone(w)};return f=r,ge(r),ne(),!0}function me(e){return!X||!f||!["preparing","ready","shown"].includes(t)?!1:(S=!0,ye=e,t==="shown"&&De(),!0)}function Fe(){S=!1,ye=void 0,z=!1}function De(){let e=f?.context.locale??n.locale??"";v?.setPurchaseRecovery(e.startsWith("zh")?"正在查询原订单…":"Checking your purchase…")}function ge(e){Ee.then(r=>{r&&D&&D.write(r,e).catch(()=>{})})}function He(e){Ee.then(async r=>{if(!r||!D)return;let o=await D.read(r);y.aborted||fe||o&&("presented"in o||j&&o.funnelId!==j)||await D.write(r,e)}).catch(()=>{})}let he=e=>`error:${e?.code??e?.name??"unknown"}`,Pe=u.ownerDocument.defaultView,M=!I,Oe=null,H=!1,$e=e=>e.storageArea===Pe?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),xe=e=>{$e(e)&&Y()},Qe=I?()=>{}:n.client.subscribe(()=>Y());function Q(){M&&(M=!1,Pe?.removeEventListener("storage",xe),Qe(),se())}let ve=()=>M&&(t==="ready"||t==="preparing");function be(e){(t==="ready"||t==="preparing")&&d("unavailable",e)}function Y(){if(t==="ready"&&Date.now()-W>=le)return Q();H=!0,Oe??=(async()=>{for(;H&&Ne();){H=!1;try{if(await n.client.retained()==="pending"){if(S)continue;me("purchase_pending")?z=!0:be("purchase_pending")}else z&&ve()&&Fe()}catch(e){y.aborted?d("released","aborted"):be(he(e))}}})().finally(()=>{Oe=null,H&&Ne()&&Y()})}function Ne(){return!!g&&(!S||z)&&ve()}I||Pe?.addEventListener("storage",xe),y.addEventListener("abort",ie,{once:!0});let Me=I?Promise.resolve("none"):n.client.findPurchase();Me.catch(()=>{});let Z;function ee(e){let r=Z?.paywallVersionId??n.paywallVersionId??f?.resolution.id??w?.id,o=JSON.stringify(V([r??null,e])),i=Ve.get(o);return i||(i=n.client.readPaywall({paywallVersionId:r,...r?{}:{paywallId:Z?.paywallId??n.paywallId},...e}),Ve.set(o,i)),i}function R(e,r){let o=Object.values(e.capabilities.plans),i=Object.values(e.document.buttons).some(a=>a.type==="checkout");return i&&o.length===0?!1:r.intent==="subscription_change"&&i?o.some(a=>a.available):o.every(a=>a.available)}function Ie(e,r){if(w&&!te(e,w))return d("unavailable","paywall_changed"),!1;w=e,E=r,$(!0);for(let o of F.keys())k(o,structuredClone(e));return!0}function qe(e,r){if(!(!w||!["preparing","ready","shown"].includes(t))){if(!te(e,w))return N("paywall_changed");if(!R(e,r.commerce))return N("plan_unavailable");Ie(e,r)}}async function q(){let e=await Be;if(!e)throw new Ue("PURCHASE_PENDING","The purchase did not start; open it again");return e}let Ye={get view(){return P?P.view:w},get signal(){return P?.signal??n.client.identitySignal},get quote(){return P?.quote??null},get operation(){return P?.operation??null},webViewUrl:"bundled",get canReselect(){return P?.canReselect},get recovery(){return P?.recovery},get pendingCancellation(){return P?.pendingCancellation},subscribe(e){return F.set(e,P?.subscribe?.(e)??(()=>{})),()=>{F.get(e)?.(),F.delete(e)}},refresh:async()=>P?P.refresh():structuredClone(w),preview:async e=>(await q()).preview(e),confirm:async()=>(await q()).confirm(),cancel:async()=>(await q()).cancel(),read:async()=>(await q()).read(),destroy(){P?.destroy()}},Le=n.onPurchaseIntent&&(e=>n.onPurchaseIntent(e)),p={options:{},handoff:{}},Te={loading:"host",focusAtReveal:!0,settleMotionAtReveal:!0,signal:n.client.identitySignal,...n.mountControls&&{mountControls:n.mountControls},start:async()=>Ye,canInteract:()=>p.options.canInteract?p.options.canInteract():!["unavailable","released","closed"].includes(t),async beforeAction(e){if(e?.purchaseIntent&&t!=="adopted"&&Le)return;let r=t!=="adopted",o=w?.capabilities,i=await q();if(r&&!L(i.view?.capabilities,o))throw new We;await p.options.beforeAction?.()}};for(let e of an)Object.defineProperty(Te,e,{enumerable:!0,get:()=>e==="onPurchaseIntent"?p.options.onPurchaseIntent??Le:p.options[e]});function ne(){t!=="preparing"||!C||!v||!f&&(!g||!L(E?.commerce,oe(g))||E?.locale!==g.locale)||(K("ready"),ce(!0))}let je={present(e){if(p.handoff.present)return p.handoff.present(e);t==="preparing"&&(C=e,W=Date.now(),ne())},async dismiss(){if(p.handoff.dismiss)return p.handoff.dismiss();d("closed");for(let e of[...G])k(e)},async closeAction(e){if(p.handoff.closeAction)return p.handoff.closeAction(e);p.options.onAction?await p.options.onAction(e):await je.dismiss()},quoteError(e){p.handoff.quoteError?p.handoff.quoteError(e):k(p.options.onError,e)}};async function Ze(e,r){let o=n.funnelId??T?.funnelId??(await Promise.resolve(n.start).catch(()=>null))?.funnelId;if(o)try{let{pins:i}=await e.funnelPaywallPins(o),a=i.paywalls[r]??[];return a.length===1?a[0]:void 0}catch{return}}async function en(){if(n.paywallVersionId)return{paywallVersionId:n.paywallVersionId,paywallId:n.paywallId};if(n.paywallId)return{paywallVersionId:n.configuration?await Ze(n.configuration,n.paywallId):void 0,paywallId:n.paywallId};let e=n.configuration;if(!e)return d("unavailable","paywall_missing"),null;let r=await Promise.resolve(n.start).catch(()=>null);if(!r||t!=="preparing")return null;let o=()=>Se(e,{funnelId:r.funnelId,customerId:n.client.customerId,parameters:r.parameters??{}});if(U=await o(),t!=="preparing")return null;let i=U;if(i.type!=="paywall")return d("unavailable",Re(i)??"route"),null;let a=!1;return se=e.subscribe(()=>{a||!ve()||(a=!0,o().then(c=>{!(c.type==="unavailable"&&!["funnel_stopped","route_unavailable"].includes(c.reason))&&(c.type!=="paywall"||c.paywallVersionId!==i.paywallVersionId)&&be("route_changed")}).finally(()=>a=!1))}),M||se(),{paywallVersionId:i.paywallVersionId}}(async()=>{try{let[{showPaywall:e},r]=await Promise.all([import("./paywall-JTKB4MMC.js"),en()]),o=n.commerce??oe(T),i=n.locale??T?.locale,a=r&&o&&i?JSON.stringify(V([r.paywallVersionId??null,r.paywallId??null,{commerce:o,locale:i}])):null;if(pe(a),y.throwIfAborted(),t!=="preparing"||!r)return;if(!o)return d("unavailable","commerce_missing");if(!i)return d("unavailable","locale_missing");Z=r;let c={commerce:o,locale:i},m=a?await D?.read(a).catch(()=>null):null,l=!j||m?.funnelId===j;if(we=!!m&&"presented"in m&&l,y.throwIfAborted(),t!=="preparing"||we)return;m&&!("presented"in m)&&l&&R(m.resolution,m.context.commerce)&&(f=m),B(!!f);let s;if(f){let Ce=f.context;c=Ce,s=structuredClone(f.resolution),ee(Ce).then(nn=>qe(nn,Ce),()=>{})}else s=await ee(c);if(y.throwIfAborted(),t!=="preparing"||(!R(s,c.commerce)&&n.start instanceof Promise&&!h&&await J,!f&&h&&!L(c,h)&&(c=h,s=await ee(c)),y.throwIfAborted(),t!=="preparing"))return;if(!R(s,c.commerce))return d("unavailable","plan_unavailable");if(!Ie(s,c))return;b=u.ownerDocument.createElement("div"),u.append(b);let A=setTimeout(()=>t==="preparing"&&d("unavailable","timeout"),tn);_e.then(()=>clearTimeout(A));let re=await e(b,Te,je);if(!re.host||y.aborted||t!=="preparing"){re.host?.destroy(),d(y.aborted?"released":"unavailable","error");return}v=re.host,ne()}catch(e){d(y.aborted?"released":"unavailable",he(e))}finally{pe(null),B(!1),$(!1)}})(),J.then(async e=>{let r=l=>{He(null),N(l)},o=async()=>{let l=await Me;return l==="pending"?"purchase_pending":l==="found"?"original_purchase":l==="blocked"?"purchase_blocked":void 0},i=async l=>!l||l==="purchase_blocked"||!X?!1:(await ue,me(l)?!0:await ze&&Xe(e?.funnelId??await n.client.pendingFunnel().catch(()=>null)??void 0)&&me(l));if(!e)return X&&await i(await o().catch(()=>{}))?void 0:r("gated");let a=e,c=oe(a),m=n.commerce??c;if(!L(c&&{...c,intent:void 0},m&&{...m,intent:void 0})||n.locale!==void 0&&a.locale!==n.locale)return r("start_mismatch");if(!c)return r("commerce_missing");h={commerce:c,locale:a.locale},x=a,f&&["preparing","ready","shown"].includes(t)&&(g=a,_=ae(a));try{let l=await o();if(await i(l)){g=void 0,_="";return}if(l)return r(l);if(!["preparing","ready","shown"].includes(t))return;if(n.configuration&&(n.paywallId||n.paywallVersionId)){let s=await Se(n.configuration,{funnelId:a.funnelId,customerId:n.client.customerId,parameters:a.parameters??{}});y.throwIfAborted();let A=s.type==="unknown"||s.type==="unavailable"&&s.reason!=="funnel_stopped";if(s.type==="paywall"?f?s.paywallId!==f.resolution.paywallId:n.paywallVersionId?s.paywallVersionId!==n.paywallVersionId:s.paywallId!==n.paywallId:!A)return r(Re(s)??"route_changed")}if(M&&(H=!1,await n.client.retained()==="pending")){if(await i("purchase_pending")){g=void 0,_="";return}return r("purchase_pending")}if(await ue,we){g=a,_=ae(a);return}if(Z||n.paywallId||n.paywallVersionId||w){let s=await ee(h);if(y.throwIfAborted(),He(R(s,h.commerce)?{savedAt:Date.now(),funnelId:a.funnelId,context:h,resolution:s}:null),f)qe(s,h);else{if(t!=="preparing")return;if(w){if(!R(s,h.commerce))return d("unavailable","plan_unavailable");if(!Ie(s,h))return}}}}catch(l){return y.aborted?d("released","aborted"):N(he(l))}["preparing","ready","shown"].includes(t)&&(g=a,_=ae(a),ne(),H&&Y())},()=>N("gated"));let Je={get state(){return t},get reason(){return ke??ye},ready:_e,local:ue,get start(){return g},get prediction(){return U?structuredClone(U):void 0},matches:e=>g?ae(e)===_:!!f&&e.funnelId===f.funnelId&&e.locale===f.context.locale,open(){if(t==="preparing")return"pending";if(t!=="ready"||!C)return!1;if(Date.now()-W>=le)return d("unavailable","expired"),!1;let e=C;return C=null,Q(),K("shown"),S&&De(),e(),"shown"},destroy(){Ae.abort()}};return Ge.set(Je,{onClose(e){return t==="closed"?(k(e),()=>{}):(G.add(e),()=>{G.delete(e)})},claim(){Q()},remember(e){fe=!0;let r=structuredClone(e);J.then(()=>{!x||!h||ge({savedAt:Date.now(),funnelId:x.funnelId,context:h,resolution:r})},()=>{})},withhold(){fe=!0,J.then(()=>{x&&ge({savedAt:Date.now(),funnelId:x.funnelId,presented:"nothing"})},()=>{})},async adopt(e,r){let o=e.paywall?.resolution,i=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(t!=="shown"||!v||!w||!o||!i||e.source.id!==g?.funnelId||e.locale!==g?.locale||!L(e.parameters??{},g?.parameters??{})||!["running","waiting"].includes(e.status)||!te(o,w))return null;let a;try{a=await r.start()}catch{return null}if(t!=="shown"||!v)return a.destroy(),null;S&&(v.clearPurchaseRecovery(),Fe()),P=a,p.options=r.options,p.handoff=r.handoff;for(let[l]of F)F.set(l,a.subscribe?.(l)??(()=>{})),a.view&&k(l,structuredClone(a.view));y.removeEventListener("abort",ie),K("adopted"),de(a),G.clear();let c=v,m=b;return v=null,b=null,C=null,new Proxy(c,{get(l,s){return s==="destroy"?()=>{l.destroy(),m?.remove()}:s==="retainPurchaseDialog"?()=>{let A=l.retainPurchaseDialog();if(A)return{dialog:A.dialog,release(){A.release(),m?.remove()}}}:Reflect.get(l,s,l)}})},retainPurchaseDialog(){if(t!=="shown")return;let e=v?.retainPurchaseDialog();if(!e)return;let r=b;return v=null,b=null,d("released"),{dialog:e.dialog,release(){e.release(),r?.remove()}}},get modal(){return w?.document.presentation.type!=="inline"},mountsControls:!!n.mountControls,get revealable(){return t==="ready"&&!!C&&Date.now()-W<le},get recovering(){return S},release(){d("released")}}),Je}function fn(u,n){let I=n.run.parameters??{},O=I?.commerce;return on(u,{client:n.client,start:{funnelId:n.run.source.id,locale:n.run.locale,parameters:I},paywallVersionId:n.paywallVersionId,...O&&{commerce:O},locale:n.run.locale,signal:n.signal},{run:!0})}export{rn as a,dn as b,on as c,fn as d};
1
+ import{a as Se,b as Re}from"./chunk-7CZEXBQY.js";import{d as We,e as te}from"./chunk-MOIVJERE.js";import{a as Ue}from"./chunk-UGATOG2T.js";import{a as k}from"./chunk-DSPLGTQI.js";var rn=5*6e4,tn=15e3,Ge=new WeakMap;function dn(u){return Ge.get(u)}var V=u=>Array.isArray(u)?u.map(V):u&&typeof u=="object"?Object.fromEntries(Object.keys(u).sort().map(n=>[n,V(u[n])])):u,L=(u,n)=>JSON.stringify(V(u))===JSON.stringify(V(n)),ae=u=>JSON.stringify(V([u.funnelId,u.locale??null,u.parameters??{}])),an=["onObservationChange","onPurchaseIntent","onPurchase","onCheckoutUrl","resumeCheckout","allowNewPurchase","checkoutNavigation","terminateCheckout","beforeCheckoutReplacement","purchaseConfirmation","confirmOnHostedCheckout","resolveOfferId","prepareSubscriptionChange","resolveSubscriptionChange","onOpenUrl","onEvent","onAction","onComplete","onError"];function on(u,n,I){let O=e=>structuredClone({funnelId:e.funnelId,locale:e.locale,parameters:e.parameters}),g,_="",T=n.start instanceof Promise?void 0:O(n.start),j=T?.funnelId??n.funnelId,oe=e=>e?.parameters?.commerce,J=Promise.resolve(n.start).then(e=>e?O(e):void 0),le=n.maxAgeMs??rn,Ae=new AbortController,y=AbortSignal.any([Ae.signal,n.client.identitySignal,...n.signal?[n.signal]:[]]),ie=()=>d("released","aborted"),t="preparing",ke,U,se=()=>{},W=0,b=null,v=null,C=null,w=null,h,x,E,Ve=new Map,P=null,G=new Set,F=new Map,ce,_e=new Promise(e=>ce=e),B,ue=new Promise(e=>B=e),de,Be=new Promise(e=>de=e);function K(e,r){t!==e&&(t=e,ke=r,k(n.onState,e))}function Ke(){y.removeEventListener("abort",ie),Q(),v?.destroy(),v=null,b?.remove(),b=null,C=null}function d(e,r){["adopted","unavailable","released","closed"].includes(t)||(K(e,r),Ke(),ce(!1),B(!1),$(!1),de(null))}function N(e){t!=="shown"&&d("unavailable",e)}let f,fe=!1,D=n.client.paywallCopies,pe,Ee=new Promise(e=>pe=e),we=!1,S=!1,ye,z=!1,X=n.whenPurchasePending==="recover"&&!I,$,ze=new Promise(e=>$=e);function Xe(e){if(!X||f||!e||!w||!E||!R(w,E.commerce)||!["preparing","ready","shown"].includes(t))return!1;let r={savedAt:Date.now(),funnelId:e,context:E,resolution:structuredClone(w)};return f=r,ge(r),ne(),!0}function me(e){return!X||!f||!["preparing","ready","shown"].includes(t)?!1:(S=!0,ye=e,t==="shown"&&De(),!0)}function Fe(){S=!1,ye=void 0,z=!1}function De(){let e=f?.context.locale??n.locale??"";v?.setPurchaseRecovery(e.startsWith("zh")?"正在查询原订单…":"Checking your purchase…")}function ge(e){Ee.then(r=>{r&&D&&D.write(r,e).catch(()=>{})})}function He(e){Ee.then(async r=>{if(!r||!D)return;let o=await D.read(r);y.aborted||fe||o&&("presented"in o||j&&o.funnelId!==j)||await D.write(r,e)}).catch(()=>{})}let he=e=>`error:${e?.code??e?.name??"unknown"}`,Pe=u.ownerDocument.defaultView,M=!I,Oe=null,H=!1,$e=e=>e.storageArea===Pe?.localStorage&&(e.key===null||e.key.startsWith("indiana.funnel.purchases.")),xe=e=>{$e(e)&&Y()},Qe=I?()=>{}:n.client.subscribe(()=>Y());function Q(){M&&(M=!1,Pe?.removeEventListener("storage",xe),Qe(),se())}let ve=()=>M&&(t==="ready"||t==="preparing");function be(e){(t==="ready"||t==="preparing")&&d("unavailable",e)}function Y(){if(t==="ready"&&Date.now()-W>=le)return Q();H=!0,Oe??=(async()=>{for(;H&&Ne();){H=!1;try{if(await n.client.retained()==="pending"){if(S)continue;me("purchase_pending")?z=!0:be("purchase_pending")}else z&&ve()&&Fe()}catch(e){y.aborted?d("released","aborted"):be(he(e))}}})().finally(()=>{Oe=null,H&&Ne()&&Y()})}function Ne(){return!!g&&(!S||z)&&ve()}I||Pe?.addEventListener("storage",xe),y.addEventListener("abort",ie,{once:!0});let Me=I?Promise.resolve("none"):n.client.findPurchase();Me.catch(()=>{});let Z;function ee(e){let r=Z?.paywallVersionId??n.paywallVersionId??f?.resolution.id??w?.id,o=JSON.stringify(V([r??null,e])),i=Ve.get(o);return i||(i=n.client.readPaywall({paywallVersionId:r,...r?{}:{paywallId:Z?.paywallId??n.paywallId},...e}),Ve.set(o,i)),i}function R(e,r){let o=Object.values(e.capabilities.plans),i=Object.values(e.document.buttons).some(a=>a.type==="checkout");return i&&o.length===0?!1:r.intent==="subscription_change"&&i?o.some(a=>a.available):o.every(a=>a.available)}function Ie(e,r){if(w&&!te(e,w))return d("unavailable","paywall_changed"),!1;w=e,E=r,$(!0);for(let o of F.keys())k(o,structuredClone(e));return!0}function qe(e,r){if(!(!w||!["preparing","ready","shown"].includes(t))){if(!te(e,w))return N("paywall_changed");if(!R(e,r.commerce))return N("plan_unavailable");Ie(e,r)}}async function q(){let e=await Be;if(!e)throw new Ue("PURCHASE_PENDING","The purchase did not start; open it again");return e}let Ye={get view(){return P?P.view:w},get signal(){return P?.signal??n.client.identitySignal},get quote(){return P?.quote??null},get operation(){return P?.operation??null},webViewUrl:"bundled",get canReselect(){return P?.canReselect},get recovery(){return P?.recovery},get pendingCancellation(){return P?.pendingCancellation},subscribe(e){return F.set(e,P?.subscribe?.(e)??(()=>{})),()=>{F.get(e)?.(),F.delete(e)}},refresh:async()=>P?P.refresh():structuredClone(w),preview:async e=>(await q()).preview(e),confirm:async()=>(await q()).confirm(),cancel:async()=>(await q()).cancel(),read:async()=>(await q()).read(),destroy(){P?.destroy()}},Le=n.onPurchaseIntent&&(e=>n.onPurchaseIntent(e)),p={options:{},handoff:{}},Te={loading:"host",focusAtReveal:!0,settleMotionAtReveal:!0,signal:n.client.identitySignal,...n.mountControls&&{mountControls:n.mountControls},start:async()=>Ye,canInteract:()=>p.options.canInteract?p.options.canInteract():!["unavailable","released","closed"].includes(t),async beforeAction(e){if(e?.purchaseIntent&&t!=="adopted"&&Le)return;let r=t!=="adopted",o=w?.capabilities,i=await q();if(r&&!L(i.view?.capabilities,o))throw new We;await p.options.beforeAction?.()}};for(let e of an)Object.defineProperty(Te,e,{enumerable:!0,get:()=>e==="onPurchaseIntent"?p.options.onPurchaseIntent??Le:p.options[e]});function ne(){t!=="preparing"||!C||!v||!f&&(!g||!L(E?.commerce,oe(g))||E?.locale!==g.locale)||(K("ready"),ce(!0))}let je={present(e){if(p.handoff.present)return p.handoff.present(e);t==="preparing"&&(C=e,W=Date.now(),ne())},async dismiss(){if(p.handoff.dismiss)return p.handoff.dismiss();d("closed");for(let e of[...G])k(e)},async closeAction(e){if(p.handoff.closeAction)return p.handoff.closeAction(e);p.options.onAction?await p.options.onAction(e):await je.dismiss()},quoteError(e){p.handoff.quoteError?p.handoff.quoteError(e):k(p.options.onError,e)}};async function Ze(e,r){let o=n.funnelId??T?.funnelId??(await Promise.resolve(n.start).catch(()=>null))?.funnelId;if(o)try{let{pins:i}=await e.funnelPaywallPins(o),a=i.paywalls[r]??[];return a.length===1?a[0]:void 0}catch{return}}async function en(){if(n.paywallVersionId)return{paywallVersionId:n.paywallVersionId,paywallId:n.paywallId};if(n.paywallId)return{paywallVersionId:n.configuration?await Ze(n.configuration,n.paywallId):void 0,paywallId:n.paywallId};let e=n.configuration;if(!e)return d("unavailable","paywall_missing"),null;let r=await Promise.resolve(n.start).catch(()=>null);if(!r||t!=="preparing")return null;let o=()=>Se(e,{funnelId:r.funnelId,customerId:n.client.customerId,parameters:r.parameters??{}});if(U=await o(),t!=="preparing")return null;let i=U;if(i.type!=="paywall")return d("unavailable",Re(i)??"route"),null;let a=!1;return se=e.subscribe(()=>{a||!ve()||(a=!0,o().then(c=>{!(c.type==="unavailable"&&!["funnel_stopped","route_unavailable"].includes(c.reason))&&(c.type!=="paywall"||c.paywallVersionId!==i.paywallVersionId)&&be("route_changed")}).finally(()=>a=!1))}),M||se(),{paywallVersionId:i.paywallVersionId}}(async()=>{try{let[{showPaywall:e},r]=await Promise.all([import("./paywall-DWBIV43F.js"),en()]),o=n.commerce??oe(T),i=n.locale??T?.locale,a=r&&o&&i?JSON.stringify(V([r.paywallVersionId??null,r.paywallId??null,{commerce:o,locale:i}])):null;if(pe(a),y.throwIfAborted(),t!=="preparing"||!r)return;if(!o)return d("unavailable","commerce_missing");if(!i)return d("unavailable","locale_missing");Z=r;let c={commerce:o,locale:i},m=a?await D?.read(a).catch(()=>null):null,l=!j||m?.funnelId===j;if(we=!!m&&"presented"in m&&l,y.throwIfAborted(),t!=="preparing"||we)return;m&&!("presented"in m)&&l&&R(m.resolution,m.context.commerce)&&(f=m),B(!!f);let s;if(f){let Ce=f.context;c=Ce,s=structuredClone(f.resolution),ee(Ce).then(nn=>qe(nn,Ce),()=>{})}else s=await ee(c);if(y.throwIfAborted(),t!=="preparing"||(!R(s,c.commerce)&&n.start instanceof Promise&&!h&&await J,!f&&h&&!L(c,h)&&(c=h,s=await ee(c)),y.throwIfAborted(),t!=="preparing"))return;if(!R(s,c.commerce))return d("unavailable","plan_unavailable");if(!Ie(s,c))return;b=u.ownerDocument.createElement("div"),u.append(b);let A=setTimeout(()=>t==="preparing"&&d("unavailable","timeout"),tn);_e.then(()=>clearTimeout(A));let re=await e(b,Te,je);if(!re.host||y.aborted||t!=="preparing"){re.host?.destroy(),d(y.aborted?"released":"unavailable","error");return}v=re.host,ne()}catch(e){d(y.aborted?"released":"unavailable",he(e))}finally{pe(null),B(!1),$(!1)}})(),J.then(async e=>{let r=l=>{He(null),N(l)},o=async()=>{let l=await Me;return l==="pending"?"purchase_pending":l==="found"?"original_purchase":l==="blocked"?"purchase_blocked":void 0},i=async l=>!l||l==="purchase_blocked"||!X?!1:(await ue,me(l)?!0:await ze&&Xe(e?.funnelId??await n.client.pendingFunnel().catch(()=>null)??void 0)&&me(l));if(!e)return X&&await i(await o().catch(()=>{}))?void 0:r("gated");let a=e,c=oe(a),m=n.commerce??c;if(!L(c&&{...c,intent:void 0},m&&{...m,intent:void 0})||n.locale!==void 0&&a.locale!==n.locale)return r("start_mismatch");if(!c)return r("commerce_missing");h={commerce:c,locale:a.locale},x=a,f&&["preparing","ready","shown"].includes(t)&&(g=a,_=ae(a));try{let l=await o();if(await i(l)){g=void 0,_="";return}if(l)return r(l);if(!["preparing","ready","shown"].includes(t))return;if(n.configuration&&(n.paywallId||n.paywallVersionId)){let s=await Se(n.configuration,{funnelId:a.funnelId,customerId:n.client.customerId,parameters:a.parameters??{}});y.throwIfAborted();let A=s.type==="unknown"||s.type==="unavailable"&&s.reason!=="funnel_stopped";if(s.type==="paywall"?f?s.paywallId!==f.resolution.paywallId:n.paywallVersionId?s.paywallVersionId!==n.paywallVersionId:s.paywallId!==n.paywallId:!A)return r(Re(s)??"route_changed")}if(M&&(H=!1,await n.client.retained()==="pending")){if(await i("purchase_pending")){g=void 0,_="";return}return r("purchase_pending")}if(await ue,we){g=a,_=ae(a);return}if(Z||n.paywallId||n.paywallVersionId||w){let s=await ee(h);if(y.throwIfAborted(),He(R(s,h.commerce)?{savedAt:Date.now(),funnelId:a.funnelId,context:h,resolution:s}:null),f)qe(s,h);else{if(t!=="preparing")return;if(w){if(!R(s,h.commerce))return d("unavailable","plan_unavailable");if(!Ie(s,h))return}}}}catch(l){return y.aborted?d("released","aborted"):N(he(l))}["preparing","ready","shown"].includes(t)&&(g=a,_=ae(a),ne(),H&&Y())},()=>N("gated"));let Je={get state(){return t},get reason(){return ke??ye},ready:_e,local:ue,get start(){return g},get prediction(){return U?structuredClone(U):void 0},matches:e=>g?ae(e)===_:!!f&&e.funnelId===f.funnelId&&e.locale===f.context.locale,open(){if(t==="preparing")return"pending";if(t!=="ready"||!C)return!1;if(Date.now()-W>=le)return d("unavailable","expired"),!1;let e=C;return C=null,Q(),K("shown"),S&&De(),e(),"shown"},destroy(){Ae.abort()}};return Ge.set(Je,{onClose(e){return t==="closed"?(k(e),()=>{}):(G.add(e),()=>{G.delete(e)})},claim(){Q()},remember(e){fe=!0;let r=structuredClone(e);J.then(()=>{!x||!h||ge({savedAt:Date.now(),funnelId:x.funnelId,context:h,resolution:r})},()=>{})},withhold(){fe=!0,J.then(()=>{x&&ge({savedAt:Date.now(),funnelId:x.funnelId,presented:"nothing"})},()=>{})},async adopt(e,r){let o=e.paywall?.resolution,i=e.paywall&&!e.paywall.quote&&!e.paywall.operation&&!e.paywall.purchaseRequestId&&!(e.paywall.selectionGeneration??0);if(t!=="shown"||!v||!w||!o||!i||e.source.id!==g?.funnelId||e.locale!==g?.locale||!L(e.parameters??{},g?.parameters??{})||!["running","waiting"].includes(e.status)||!te(o,w))return null;let a;try{a=await r.start()}catch{return null}if(t!=="shown"||!v)return a.destroy(),null;S&&(v.clearPurchaseRecovery(),Fe()),P=a,p.options=r.options,p.handoff=r.handoff;for(let[l]of F)F.set(l,a.subscribe?.(l)??(()=>{})),a.view&&k(l,structuredClone(a.view));y.removeEventListener("abort",ie),K("adopted"),de(a),G.clear();let c=v,m=b;return v=null,b=null,C=null,new Proxy(c,{get(l,s){return s==="destroy"?()=>{l.destroy(),m?.remove()}:s==="retainPurchaseDialog"?()=>{let A=l.retainPurchaseDialog();if(A)return{dialog:A.dialog,release(){A.release(),m?.remove()}}}:Reflect.get(l,s,l)}})},retainPurchaseDialog(){if(t!=="shown")return;let e=v?.retainPurchaseDialog();if(!e)return;let r=b;return v=null,b=null,d("released"),{dialog:e.dialog,release(){e.release(),r?.remove()}}},get modal(){return w?.document.presentation.type!=="inline"},mountsControls:!!n.mountControls,get revealable(){return t==="ready"&&!!C&&Date.now()-W<le},get recovering(){return S},release(){d("released")}}),Je}function fn(u,n){let I=n.run.parameters??{},O=I?.commerce;return on(u,{client:n.client,start:{funnelId:n.run.source.id,locale:n.run.locale,parameters:I},paywallVersionId:n.paywallVersionId,...O&&{commerce:O},locale:n.run.locale,signal:n.signal},{run:!0})}export{rn as a,dn as b,on as c,fn as d};
@@ -1 +1 @@
1
- import{a as T,b as se}from"./chunk-XLGNBPGF.js";import{b as re,h as ae,j as ce}from"./chunk-IL5OTR6J.js";import{E as M,a as J}from"./chunk-FDXBCQBO.js";import{a as b,b as f,c as m}from"./chunk-S2S4ROGY.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-2OBXRQMW.js";import{a as oe,b as j}from"./chunk-PUDTOCQF.js";import{b as W,j as X}from"./chunk-BT7IC765.js";import{n as $}from"./chunk-ME6QTD5Y.js";import{b as ie}from"./chunk-6QBSJRAD.js";import{a as B}from"./chunk-KCUE2VFJ.js";import{a as s}from"./chunk-UGATOG2T.js";import{h as Q}from"./chunk-LFR2LWYC.js";import{b as K}from"./chunk-W22ESUYY.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-YJM6772C.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-YJM6772C.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-YJM6772C.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-YJM6772C.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};
1
+ import{a as T,b as se}from"./chunk-XLGNBPGF.js";import{b as re,h as ae,j as ce}from"./chunk-3XH64DN3.js";import{E as M,a as J}from"./chunk-MYG5MAKQ.js";import{a as b,b as f,c as m}from"./chunk-S2S4ROGY.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-2OBXRQMW.js";import{a as oe,b as j}from"./chunk-PUDTOCQF.js";import{b as W,j as X}from"./chunk-BT7IC765.js";import{n as $}from"./chunk-ME6QTD5Y.js";import{b as ie}from"./chunk-7JJGSLXD.js";import{a as B}from"./chunk-KCUE2VFJ.js";import{a as s}from"./chunk-UGATOG2T.js";import{h as Q}from"./chunk-LFR2LWYC.js";import{b as K}from"./chunk-W22ESUYY.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-YJM6772C.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-YJM6772C.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-YJM6772C.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-YJM6772C.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};