@tinkerlandai/longplay-sdk 0.10.41 → 0.10.42

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 (90) hide show
  1. package/CHANGELOG.md +9 -3
  2. package/README.md +1 -0
  3. package/dist/check-response-OIBVUP72.js +1 -0
  4. package/dist/{chunk-P6XQC7GG.js → chunk-2EVGXJ4R.js} +1 -1
  5. package/dist/{chunk-EECTJHI6.js → chunk-3SXPCVIP.js} +1 -1
  6. package/dist/{chunk-6OVMC5BT.js → chunk-3WTVQ6OV.js} +1 -1
  7. package/dist/{chunk-MYDMOAKX.js → chunk-5JRBCW6V.js} +1 -1
  8. package/dist/{chunk-VJHURKRY.js → chunk-5TJISOWN.js} +1 -1
  9. package/dist/{chunk-2RUJXZCO.js → chunk-67SIVUOS.js} +1 -1
  10. package/dist/{chunk-S4P4UUUF.js → chunk-6XRXHFM6.js} +1 -1
  11. package/dist/{chunk-KINNES62.js → chunk-7MYS52FL.js} +1 -1
  12. package/dist/{chunk-W3J2SIPY.js → chunk-ABXCDVC7.js} +1 -1
  13. package/dist/{chunk-OEONV3JY.js → chunk-AC53CUJE.js} +1 -1
  14. package/dist/{chunk-4B4RB36N.js → chunk-ANXDWUPK.js} +1 -1
  15. package/dist/{chunk-W35FZWGG.js → chunk-AQONMY2H.js} +1 -1
  16. package/dist/{chunk-5PNH2FPI.js → chunk-ASL7TJFU.js} +1 -1
  17. package/dist/{chunk-H26F3IOI.js → chunk-AV2WZSII.js} +1 -1
  18. package/dist/chunk-B4AELNLE.js +1 -0
  19. package/dist/{chunk-CQRSMCCG.js → chunk-C4NG6RVA.js} +1 -1
  20. package/dist/{chunk-NFY7DKVJ.js → chunk-CALDEF4M.js} +1 -1
  21. package/dist/{chunk-24Z3THUR.js → chunk-CSLTAXC7.js} +1 -1
  22. package/dist/{chunk-HGH2X6QM.js → chunk-CWD36SJO.js} +1 -1
  23. package/dist/{chunk-OAAS5LJY.js → chunk-DCZWNTG2.js} +1 -1
  24. package/dist/{chunk-GXADA7OV.js → chunk-DGZCD3AY.js} +1 -1
  25. package/dist/{chunk-SYHMHKFQ.js → chunk-FTGRTYBL.js} +1 -1
  26. package/dist/{chunk-EOPKOAR5.js → chunk-HLCDAU5A.js} +1 -1
  27. package/dist/{chunk-EJSDOSP5.js → chunk-HTXB2WVI.js} +1 -1
  28. package/dist/chunk-JWTA2OCB.js +1 -0
  29. package/dist/{chunk-VWRQBQZD.js → chunk-KEF6HIFK.js} +1 -1
  30. package/dist/{chunk-7IVLNV5H.js → chunk-KP4QI4RX.js} +1 -1
  31. package/dist/{chunk-26UXCYBP.js → chunk-LSVTH3TS.js} +1 -1
  32. package/dist/{chunk-2XF34Q6D.js → chunk-LUGZNBIW.js} +1 -1
  33. package/dist/{chunk-DPEMW2FO.js → chunk-LZ3OJYBY.js} +1 -1
  34. package/dist/{chunk-QJMM37CB.js → chunk-MEDW4N3F.js} +1 -1
  35. package/dist/{chunk-2LERKK7O.js → chunk-MPD3UIY4.js} +1 -1
  36. package/dist/{chunk-Y2HXKANG.js → chunk-MWICFZUF.js} +1 -1
  37. package/dist/{chunk-EON4IKWR.js → chunk-NVF54BDR.js} +1 -1
  38. package/dist/{chunk-2P2YSNYU.js → chunk-O6CUNETH.js} +1 -1
  39. package/dist/chunk-OXXPMJRJ.js +1 -0
  40. package/dist/{chunk-AQQJPP3P.js → chunk-P6TNBX2S.js} +1 -1
  41. package/dist/{chunk-6EBS6MLW.js → chunk-PBZSOTKZ.js} +1 -1
  42. package/dist/{chunk-756SIMZF.js → chunk-QHWR5UHD.js} +1 -1
  43. package/dist/{chunk-RQTYIUWP.js → chunk-RDUKCMST.js} +1 -1
  44. package/dist/{chunk-6STWY5GX.js → chunk-RJY5CUTB.js} +1 -1
  45. package/dist/chunk-S7A3IBAF.js +10 -0
  46. package/dist/{chunk-FTVNGN6Z.js → chunk-SVLEVNHP.js} +1 -1
  47. package/dist/{chunk-G6CWZBT5.js → chunk-TL67SYPH.js} +1 -1
  48. package/dist/{chunk-O3HLNU6T.js → chunk-UJMP7AMY.js} +1 -1
  49. package/dist/{chunk-TGPZJ5A7.js → chunk-V65FSNYO.js} +1 -1
  50. package/dist/{chunk-2LUVO7GM.js → chunk-ZICZN6WO.js} +1 -1
  51. package/dist/{content-XYUJFGY2.js → content-KSIF5AXD.js} +1 -1
  52. package/dist/{funnel-host-purchase-BNS3242X.js → funnel-host-purchase-YNC4LQJS.js} +1 -1
  53. package/dist/funnel-paywall-prerender-DAAQUEEZ.js +1 -0
  54. package/dist/funnel-route-prediction-XGCMCIKA.js +1 -0
  55. package/dist/funnel-route-source-O76QSUYU.js +1 -0
  56. package/dist/funnel-runtime-host-WPU42YVT.js +1 -0
  57. package/dist/index.js +1 -1
  58. package/dist/merchant-bridge-contracts-FB63H7NE.js +1 -0
  59. package/dist/native-shell.js +1 -1
  60. package/dist/openrouter.js +1 -1
  61. package/dist/operation-contracts-YSFIINLK.js +1 -0
  62. package/dist/page.js +1 -1
  63. package/dist/paywall-PZ4BBEFG.js +1 -0
  64. package/dist/paywall-content-5IWLT7YD.js +1 -0
  65. package/dist/paywall-session-K7GPR3UF.js +1 -0
  66. package/dist/popup.js +1 -1
  67. package/dist/react-native.js +1 -1
  68. package/dist/screen-renderer-RDXKWHYE.js +1 -0
  69. package/dist/server.js +1 -1
  70. package/dist/{visual-dom-7YYJQ2ZI.js → visual-dom-IN6DRNX3.js} +1 -1
  71. package/dist/visual.js +1 -1
  72. package/package.json +1 -1
  73. package/dist/check-response-SR3PDVGE.js +0 -1
  74. package/dist/chunk-ANXK3B5B.js +0 -1
  75. package/dist/chunk-BWRRZ2NW.js +0 -1
  76. package/dist/chunk-H7AHDGVU.js +0 -10
  77. package/dist/chunk-PYLX3WF6.js +0 -1
  78. package/dist/funnel-paywall-prerender-DDQI3GAZ.js +0 -1
  79. package/dist/funnel-route-prediction-BT5ZWU54.js +0 -1
  80. package/dist/funnel-route-source-7ZJMZRID.js +0 -1
  81. package/dist/funnel-runtime-host-3SSDNG24.js +0 -1
  82. package/dist/merchant-bridge-contracts-YU53UKUN.js +0 -1
  83. package/dist/operation-contracts-GEIGP23I.js +0 -1
  84. package/dist/paywall-YZAEI7TF.js +0 -1
  85. package/dist/paywall-content-QBSB5NA7.js +0 -1
  86. package/dist/paywall-session-MHBAZLS7.js +0 -1
  87. package/dist/screen-renderer-SEJG7A2C.js +0 -1
  88. /package/dist/{chunk-2ULWP26K.js → chunk-GPJF3T43.js} +0 -0
  89. /package/dist/{chunk-4PGYQ2TI.js → chunk-RA7GZ67U.js} +0 -0
  90. /package/dist/{chunk-PBBREFS5.js → chunk-WPFTSHP2.js} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,9 +1,15 @@
1
1
  # Changelog
2
2
 
3
- ## 0.10.41
3
+ ## 0.10.42
4
+
5
+ - Keep native subscription upgrades and their original purchase operation through Funnel quotes, confirmation and recovery, including prepaid quantities. Show the merchant’s exact amount due today.
6
+ - A provisional first Paywall rereads availability when the merchant resolves a subscription-change intent. Preserve first-screen route prediction.
7
+ - Restore a pending merchant Checkout from its verified redirect, and permit reselection after a sealed failed change only when the server confirms closure.
8
+ - Keep the accessible Continue checkout label synchronized with the visible button.
9
+ - Synchronize authored slider labels and local price state when eligibility becomes available again. Keep restored confirmation controls disabled until the opening read releases them.
10
+ - Wire protocol remains `0.10`.
4
11
 
5
- - Funnel and standalone Paywalls support an explicitly selected subscription change, display the charge due today separately from credits, tax and renewal, and recover the original update after an interrupted confirmation. Native Paywalls refuse unsupported Web membership changes.
6
- - Provisional pre-renders re-read eligibility when admission changes the commerce intent to a subscription change; prepaid Feature quantities remain bound to the selected plan.
12
+ ## 0.10.41
7
13
 
8
14
  - `predictFunnelStart(configuration, { funnelId, customerId, parameters })` says on the device, before the click, which first screen a Run of the Funnel would present for this Customer: a Paywall (with `paywallId`, `paywallVersionId` and `presentation`), a Funnel screen such as a popup, an external page, an end such as `ineligible`, `unknown` when a step needs the server, or `unavailable`. It records nothing: no Run, exposure, Sticky assignment or Coupon. Splits bucket by the session's Customer ID, as the server does.
9
15
  - A Remote Funnel's route is read from `/api/v1/configuration/{environmentId}/funnels/{funnelId}/versions/{versionId}/route`, outside the manifest, and only while its author has turned on **Publish the first-screen route**; until the API serves it, the prediction is `unavailable` (`route_unavailable`). A Local Funnel's route is computed from its public graph.
package/README.md CHANGED
@@ -349,6 +349,7 @@ button.onclick = () => {
349
349
  - `paywallVersionId` (one exact Version) or `paywallId` (its current published Version) names the Paywall the Funnel presents first. The copy is read with `purchase.readPaywall()` as a standalone Paywall would be, for the Start's `parameters.commerce` and `locale`.
350
350
  - Or pass `configuration` (the page's `createConfigurationSync`) and name no Paywall: the SDK predicts this Customer's first screen from the Funnel's published route (see below) once the Start is final, and renders that Paywall. `prepared.prediction` holds the prediction. A first screen that is not a Paywall leaves the copy `unavailable` with reason `first_screen_popup`, `first_screen_page`, `first_screen_external_page`, `route_end_<outcome>` (for example `route_end_ineligible`) or `route_unknown_<reason>`; a route that is not published reads `route_unavailable`. Until a click takes it, a ready copy becomes `unavailable` (`route_changed`) when a configuration refresh routes the Start to another first screen.
351
351
  - `start` can be a promise while the merchant's own checks run: rendering starts at once and the copy becomes ready only with the Start. Pass provisional `commerce` and `locale` then. If admission changes only `commerce.intent`, the SDK rereads the same Paywall's server availability for the final intent before revealing it; an unavailable provisional purchase screen cannot decide upgrade eligibility. A provider, currency or locale change, `null` or a rejection leaves it `unavailable`.
352
+
352
353
  - `state` is `preparing`, `ready`, `unavailable` (see `reason`), `shown`, `adopted`, `released` or `closed`; `ready` resolves `true` once it can be revealed and `false` when it never will be; `onState` reports each change.
353
354
  - Call `open()` synchronously from the opening click. It returns `"shown"` (revealed now), `"pending"` (still rendering: pass it anyway; it is revealed only if it is ready before the Run presents anything, so the click never waits for it) or `false` (show the purchase the normal way). Pass the same Start to `showFunnelPurchase`; `matches(start)` says whether a Start would present this copy (the request ID may differ).
354
355
  - Passing `prepared` to `showFunnelPurchase` (or `showFunnelRun`) hands it to the SDK. When the SDK cannot use it (a presentation for the client is already open, another or no Start, no Run, operation-only or blocked recovery, a failure, an instruction or another presentation first), it releases it, so a revealed copy is never left on screen. A revealed presentation that ends without a Run reports `onDismiss(null)`, or `onError` for a failure; a Funnel paused before the takeover dismisses a revealed dialog for good, as it does one the Run presented. Do not reuse a copy you passed; pre-render a new one.
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-MPD3UIY4.js";import"./chunk-CWD36SJO.js";import"./chunk-5JRBCW6V.js";import"./chunk-TL67SYPH.js";import"./chunk-6XRXHFM6.js";import"./chunk-GPJF3T43.js";import"./chunk-WPFTSHP2.js";import"./chunk-WOT6VMZA.js";export{a as validateEntitlementCheck,b as validateResourceCheck};
@@ -1 +1 @@
1
- import{A as me,E as rt,b as qe,c as $e,d as Se,h as He,i as Ke,j as Ye,n as We,q as Xe,z as nt}from"./chunk-4B4RB36N.js";import{a as tt}from"./chunk-2RUJXZCO.js";import{c as Ne,d as Te,e as _e,f as Le,g as De,i as Ue,m as ke,n as M,o as Ge,q as be,r as _,s as je,t as ze,u as Be,v as Je}from"./chunk-EOPKOAR5.js";import{K as U,e as Ve,q as ve,r as Me}from"./chunk-OAAS5LJY.js";import{a as fe,b as Ze}from"./chunk-2XF34Q6D.js";import{a as le}from"./chunk-26UXCYBP.js";import{e as de}from"./chunk-EECTJHI6.js";import{a as D}from"./chunk-G6CWZBT5.js";import{h as ie}from"./chunk-S4P4UUUF.js";import{b as et}from"./chunk-3VUPVXAV.js";import{b as Qe}from"./chunk-2LUVO7GM.js";import{b as e}from"./chunk-2ULWP26K.js";import{c as Fe,f as Pe}from"./chunk-CQRSMCCG.js";var j=e.literal(Ve),ht=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ot=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:xe}),e.strictObject({type:e.literal("customer"),customer:ve,customerData:Me.optional()})]),Ee=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),yt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:Ee.omit({runId:!0,requestId:!0}).nullable()}),wt=e.union([qe,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),It=$e.omit({authenticated:!0}).extend({identity:yt,instruction:wt.nullable()}),vt=e.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})]),pe={contract:j,customerToken:e.string().regex(le)},it={contract:j,requestId:e.uuid(),runToken:ht,externalUserId:ve.options[1].shape.value},at=e.discriminatedUnion("operation",[e.strictObject({contract:j,operation:e.literal("describe")}),e.strictObject({contract:j,operation:e.literal("start"),source:ot,funnelId:U.options[0].shape.funnelId,requestId:e.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),He.omit({operation:!0}).extend({contract:j,operation:e.literal("entry_start"),source:ot}),e.strictObject({...it,operation:e.literal("bind_customer"),guestToken:xe,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...it,operation:e.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("review")}),Ye.omit({customerToken:!0}).extend(pe),e.strictObject({...pe,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:vt})]),bt=Se.omit({run:!0}).extend({contract:j,run:It,settlement:Se.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Dt=Ke.extend({contract:j}),Ut=e.discriminatedUnion("operation",[at.options[1].omit({contract:!0,source:!0,requestId:!0}),at.options[2].omit({contract:!0,source:!0,requestId:!0})]),Vt=bt.extend({binding:Ee,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Mt=e.discriminatedUnion("state",[e.strictObject({contract:j,scope:ie,state:e.literal("not_accepted")}),e.strictObject({contract:j,scope:ie,state:e.literal("conflict")}),e.strictObject({contract:j,scope:ie,state:e.literal("bound"),binding:Ee})]),kt=e.strictObject({contract:j,scope:ie,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var st=e.string().regex(/^[a-f0-9]{64}$/),St=Ne.omit({variations:!0,active:!0}).extend({changeId:st,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),ut=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:st,experiments:e.array(St).max(100),savedGroups:Te}),xt=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),Bt=e.strictObject({events:e.array(xt).min(1).max(20)}),Jt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Wt(r){let a=null,g=null,O=0,v=0,C=new Set,l=null,w=null,m=new Set,b=()=>{for(let s of m)try{s()}catch{}},d={attributes:de.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,I)=>{!C.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(I),structuredClone(d.attributes),a.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,I)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(I),structuredClone(d.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,I=new Set){return C.has(s)?!l||!l.features[s]||["unknownFeature","cyclicPrerequisite"].includes(l.features[s].source):I.has(s)?!1:(I.add(s),(a?.features[s]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(P=>P.experiment.parentConditions??[])].some(P=>h(P.id,I))))}let x=s=>{if(r.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 l?.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(l=null,d.features=a.features),C.has(s)?!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()?S():structuredClone(l.features[s]??S()):r.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!l||h(s)?S():structuredClone(Pe(s,d))};async function V(){if(!a||!C.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=v;if(w?.revision===s)return w.loading;let I=O,F=a,P=[...C],E=(async()=>{let y=Ue.parse(await r.evaluateRemote({attributes:structuredClone(d.attributes),features:P}));if(!(I!==O||s!==v||F!==a)){if(r.assertUsable?.(F.generation),y.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(P.some(T=>!Object.hasOwn(y.features,T))||Object.keys(y.features).some(T=>!C.has(T)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!y.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=de.parse({...d.attributes,...y.merchandiseContext})}l=structuredClone(y),d.features={...F.features,...Object.fromEntries(Object.entries(l.features).map(([T,J])=>[T,{defaultValue:J.value}]))},b()}})();w={revision:s,loading:E};try{await E}finally{w?.loading===E&&(w=null)}}function L(){V().catch(s=>{try{r.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=O,I=(async()=>{let F=await r.load(),P="remoteFeatures"in F?Le.parse(F):null,E=P??_e.parse(F);if(E.scope.projectId!==r.scope.projectId||E.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==O)throw new Error("Feature client was reset");if(r.assertUsable&&a?.generation===E.generation){let{evaluatedAt:T,expiresAt:J,...ae}=a,{evaluatedAt:Z,expiresAt:ge,...z}=E;if(_(ae)!==_(z))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=E.evaluatedAt,a.expiresAt=E.expiresAt,b(),(!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())&&L(),structuredClone(a)}let y=new Set(P?.remoteFeatures??[]);if([...y].some(T=>Object.hasOwn(E.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in E&&!a.analyticsConfig.experimentViewsEnabled&&P?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),a=structuredClone(E),C=y,l=null,w=null,v++,d.features=a.features,d.savedGroups=Fe(a.savedGroups),d.trackedFeatureUsage={},b(),L(),structuredClone(a)})();g=I;try{return await I}finally{g===I&&(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 I=de.parse(s);(d.attributes?.merchandise||d.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=I,v++,l=null,w=null,d.features=a?.features??{},d.trackedFeatureUsage={},b(),L()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,I){let F=x(s).value;return structuredClone(F===null?I:F)},reset(){O++,v++,g=null,w=null,a=null,l=null,C.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),b()}}}var Et=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),Q=2*1048576,Ct=100;function Rt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ct(r,a){let g=a===void 0?Rt():a,O=new Map,v=0,C=!1,l=!1,w,m;async function b(S){if(!g)return null;let h;try{let x=await Promise.race([Promise.resolve().then(()=>g.getItem(S)),new Promise(V=>{h=setTimeout(()=>V(null),Ct)})]);return typeof x=="string"&&x.length<=Q&&new TextEncoder().encode(x).byteLength<=Q?x:null}catch{return null}finally{clearTimeout(h)}}function d(){if(m)return m;let S=(async()=>{try{let h=await b(`${r}:artifacts`);if(h)return Et.parse(JSON.parse(h))}catch{}return{}})();return m=S,S.finally(()=>{m===S&&(m=void 0)}),S}return{async readManifest(){return b(r)},writeManifest(S){!g||S.length>Q||new TextEncoder().encode(S).byteLength>Q||(w=S,!l&&(l=!0,Promise.resolve().then(async()=>{try{for(;w!==void 0;){let h=w;try{await g.setItem(r,h)}catch{}w===h&&(w=void 0)}}finally{l=!1}})))},async readArtifact(S){let h=(await d())[S],x=Date.now();return h&&x>=h.at&&x-h.at<=M.retentionMs?h.text:void 0},writeArtifact(S,h){if(!g||h.length>Q)return;let x=O.get(S);if(x?.text===h||!x&&O.size>=128)return;let V=new TextEncoder().encode(h).byteLength;v-(x?.byteLength??0)+V>Q||(O.set(S,{text:h,byteLength:V}),v+=V-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;O.size;){let L=new Map(O);try{let k={...await d()},s=Date.now();for(let[E,y]of L)k[E]={at:s,text:y.text};let I={},F=2,P=0;for(let[E,y]of Object.entries(k).sort(([,T],[,J])=>J.at-T.at)){if(y.at>s||s-y.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[E]:y})).byteLength;F+T>Q||P>=128||(I[E]=y,F+=T,P++)}await g.setItem(`${r}:artifacts`,JSON.stringify(I))}catch{}finally{for(let[k,s]of L)O.get(k)===s&&(O.delete(k),v-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,a)=>new D(r,a),B=()=>performance.now(),lt=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function pn(r){let a=Ge.parse(r.scope),g=new fe(r.origin??Qe);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 u("INVALID_URL","Configuration requires a trusted HTTPS origin");let O=new Set([g.origin,...(r.assetOrigins??[]).map(t=>{let n=new fe(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return n.origin})]),v=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${a.environmentId}`,l=`indiana:configuration:1:${g.origin}:${_(a)}`,w=ct(l,r.storage),m,b=0,d=0,S=!1,h=!1,x=0,V=0,L,k,s,I,F=0,P=new Set,E=new Set,y=new Map,T=new Map,J=0,ae=!1;function Z(){for(let t of P)try{t()}catch{}}function ge(t){try{r.onError?.(t)}catch{}}let z=()=>!h&&!S&&!!m&&B()<b&&Date.now()<d;function re(){if(!z())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(t,n,i){if(!y.has(t)){for(;y.size&&(y.size>=128||J+i>M.maxCacheBytes);){let o=y.entries().next().value;J-=o[1].byteLength,y.delete(o[0])}y.set(t,{text:n,byteLength:i}),J+=i}}function he(t,n,i){return et(t,n,{signal:i,error:o=>u("INVALID_RESPONSE",o==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function ye(t){let n=new fe(t,g);if(!O.has(n.origin)||n.username||n.password||n.hash||n.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return n.href}async function we(t,n,i=!1){let o=await v(ye(t),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:n,headers:{}});if(o.status===429){let f=o.headers.get("retry-after")??"";F=/^\d+$/.test(f)?Number(f)*1e3:Math.max(0,Date.parse(f)-Date.now())||15e3}if(!o.ok&&o.status!==304)throw u(`CONFIGURATION_HTTP_${o.status}`,"Configuration synchronization failed");return o}function ft(t,n,i){let o=Date.parse(t.headers.get("x-indiana-config-validated-at")??""),f=Date.parse(t.headers.get("x-indiana-config-valid-until")??""),p=Date.parse(t.headers.get("date")??""),c=t.headers.get("age"),R=c!==null&&/^\d+(\.\d+)?$/.test(c)?Number(c)*1e3:NaN;if(![o,f,p,R].every(Number.isFinite)||f<=o||f-o>M.maxControlAgeMs||o>p+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let A=Math.min(f-o,i.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(R,p-o,0)-(B()-n);if(A<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return B()+A}function se(){if(clearTimeout(s),clearTimeout(I),h||!P.size||(z()&&(I=setTimeout(()=>{z()?se():Z()},Math.max(1,b-B())),lt(I)),typeof document<"u"&&document.visibilityState==="hidden"))return;let t=V?Math.min(15e3,1e3*2**Math.min(V-1,4)):Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{X().catch(ge)},Math.max(F,t*(.8+Math.random()*.2))),lt(s)}async function X(){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let t=x,n=new AbortController;k=n;let i=(async()=>{if(!ae){ae=!0;try{let ce=await w.readManifest();if(ce&&!m){let $=be.parse(JSON.parse(ce));_($.scope)===_(a)&&(m=$)}}catch{}}n.signal.throwIfAborted();let c=m,R=B(),N=await we(C,n.signal);N.status===304&&(!c||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await we(C,n.signal));let A=N.status===304?c:be.parse(JSON.parse(await he(N,M.maxManifestBytes,n.signal))),{generation:G,...ne}=A,q=N.headers.get("etag");if(_(A.scope)!==_(a)||ze(ne)!==G||q!==`"${G}"`&&q!==`W/"${G}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(c&&(A.revision<c.revision||A.revision===c.revision&&A.generation!==c.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ce,$]of Object.entries(c?.funnels??{})){let W=A.funnels[ce];if(W&&(W.controlRevision<$.controlRevision||W.evaluationRevision<$.evaluationRevision||W.controlRevision===$.controlRevision&&W.state!==$.state||W.evaluationRevision===$.evaluationRevision&&W.evaluationMode!==$.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=ft(N,R,A.policy);if(n.signal.throwIfAborted(),t!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return m=A,b=Y,d=Date.now()+Math.max(0,Y-B()),S=!1,V=0,F=0,w.writeManifest(_(A)),Z(),structuredClone(A)})(),o=setTimeout(()=>n.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),f=new Promise((c,R)=>n.signal.addEventListener("abort",()=>R(n.signal.reason),{once:!0})),p=Promise.race([i,f]).catch(c=>{throw V++,(c instanceof e.ZodError||c instanceof SyntaxError||c instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(c.code))&&(b=0,S=!0,Z()),c}).finally(()=>{clearTimeout(o),L===p&&(L=void 0),se()});return L=p,p}async function ue(t){let n=t.sha256,i=ne=>tt(ne,t);ye(t.url);let o=y.get(n);if(o){if(o.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return y.delete(n),y.set(n,o),o.text}let f=T.get(n);if(f){if(f.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return f.promise}let p=new AbortController;E.add(p);let c=x,R=(async()=>{try{let Y=await w.readArtifact(n);if(Y&&i(Y)){if(p.signal.throwIfAborted(),h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,Y,t.byteLength),Y}}catch{}p.signal.throwIfAborted();let ne=await we(t.url,p.signal,!0),q=await he(ne,t.byteLength,p.signal);if(!i(q))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,q,t.byteLength),w.writeArtifact(n,q),q})(),N=setTimeout(()=>p.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),A=new Promise((ne,q)=>p.signal.addEventListener("abort",()=>q(p.signal.reason),{once:!0})),G=Promise.race([R,A]).finally(()=>{clearTimeout(N),E.delete(p),T.delete(n)});return T.set(n,{promise:G,byteLength:t.byteLength}),G}async function ee(){return z()||await X(),re(),m}async function K(t){let n,i=new Promise((o,f)=>{n=setTimeout(()=>f(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([t(),i])}finally{clearTimeout(n)}}function H(t,n){if(re(),m?.generation!==t.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(n&&m.funnels[n]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Re(t){let n=t.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let o=De.parse(JSON.parse(await ue(i)));if(_(o.scope)!==_({projectId:a.projectId,environment:a.environment})||o.generation!==i.generation||o.remoteFeatures.some(f=>Object.hasOwn(o.features,f)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return H(t),{...o,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,b-B())).toISOString()}}async function Oe(t,n){let i=await ee(),o=i.funnels[t];n&&(!o||o.evaluationMode==="local"&&!o.versions[n])&&(L&&await L,i=await X()),H(i,t);let f=i.funnels[t];if(f.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let p=n??f.currentVersionId,c=f.versions[p];if(!c)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[c.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[R,N]=await Promise.all([ue(i.artifacts[c.artifact]).then(A=>Je(JSON.parse(A))),f.evaluationMode==="local"?Re(i):void 0]);if(N&&_(Be(R,N))!==_(c.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return H(i,t),{document:R,growth:N,versionId:p,control:structuredClone(f),manifest:structuredClone(i)}}async function Ie(t,n){try{return await Oe(t,n)}catch(i){if(!(i instanceof D)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&z()))throw i;let o=m?.generation;if(L&&await L,await X(),i.code!=="CONFIGURATION_CHANGED"&&m?.generation===o)throw i;return Oe(t,n)}}let oe=new Map;async function mt(t,n){let{FUNNEL_ROUTE_LIMITS:i,funnelRouteSchema:o}=await import("./funnel-route-source-7ZJMZRID.js"),f=new AbortController;E.add(f);let p=setTimeout(()=>f.abort(u("CONFIGURATION_UNAVAILABLE","Funnel route read timed out")),M.initializationMs);try{let c=await v(ye(`${C}/funnels/${t}/versions/${n}/route`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:f.signal,headers:{}});if(c.status===404)throw u("ROUTE_UNAVAILABLE","This Funnel Version publishes no route");if(!c.ok)throw u(`CONFIGURATION_HTTP_${c.status}`,"Funnel route read failed");let R=await he(c,i.maxBytes,f.signal),N=je(R),A=c.headers.get("etag");if(A!==`"${N}"`&&A!==`W/"${N}"`)throw u("INVALID_RESPONSE","Funnel route identity changed");let G=o.safeParse(JSON.parse(R));if(!G.success||G.data.funnelId!==t||G.data.versionId!==n)throw u("INVALID_RESPONSE","Funnel route does not describe this Version");return G.data}finally{clearTimeout(p),E.delete(f)}}async function pt(t){let n=await ee();H(n,t);let i=n.funnels[t],o=i.currentVersionId,f;if(i.evaluationMode==="local"){let{projectFunnelRoute:p}=await import("./funnel-route-source-7ZJMZRID.js"),c=await Ie(t,o),R=Object.entries(c.manifest.paywalls??{});f=p({funnelId:t,versionId:o,document:c.document,experiments:c.growth?.experiments??{},paywallOf:N=>R.find(([,A])=>Object.hasOwn(A.versions,N))?.[0]})}else{let p=`${t}:${o}`,c=oe.get(p);if(!c||B()-c.readAt>=M.maxControlAgeMs){let R={promise:mt(t,o),readAt:B()};oe.set(p,R),R.promise.catch(()=>{oe.get(p)===R&&oe.delete(p)}),c=R}f=await c.promise}return H(n,t),{route:structuredClone(f),control:structuredClone(i),generation:n.generation}}function te(){if(z()||Z(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}X().catch(ge)}function gt(t){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(t),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("focus",te),document.addEventListener("visibilitychange",te)),se()),()=>{P.delete(t),P.size||(clearTimeout(s),clearTimeout(I),Ae())}}function Ae(){typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",te))}return{scope:Object.freeze({...a}),refresh:X,subscribe:gt,assertFresh:re,assertFeatures(t){re();let n=m.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(t!==void 0&&m.artifacts[n].generation!==t)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return z()?Math.max(0,b-B()):0},async features(){return K(async()=>Re(await ee()))},pageExperiments:()=>K(async()=>{let t=await ee(),n=t.gb.pageExperiments;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let o=ut.parse(JSON.parse(await ue(i)));if(o.environmentId!==a.environmentId||o.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return H(t),o}),funnel:(t,n)=>K(()=>Ie(t,n)),funnelControl:t=>K(async()=>{let n=await ee();return H(n,t),structuredClone(n.funnels[t])}),funnelRoute:t=>K(()=>pt(t)),paywall:(t,n)=>K(async()=>{let i=await ee(),o=i.paywalls?.[t];if(!o||!n&&o.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let f=n??o.currentVersionId,p=o.versions[f],c=p&&i.artifacts[p.artifact];if(!c||c.kind!=="paywall"||c.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let R=ke.parse(JSON.parse(await ue(c)));return H(i),{document:R,versionId:f,version:p.version,control:structuredClone(o),manifest:structuredClone(i)}}),async localFunnel(t,n){let i=await K(()=>Ie(t,n));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:o,remoteFeatures:f,...p}=i.growth;return We({scope:{projectId:a.projectId,environment:a.environment},funnelId:t,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:p})},assertFunnel(t,n,i){re();let o=m.funnels[t];if(!o||o.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(o.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(n!==void 0&&o.controlRevision!==n)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!o.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,x++,b=0,k?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(I),Ae(),Z(),P.clear();for(let t of E)t.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));y.clear(),oe.clear(),J=0}}}}function dt(r){let a=le.test(r.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!me.test(r.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let O=U.safeParse({...g,operation:"start"});if(!O.success||O.data.operation!=="start"||(a?O.data.customer!==void 0:O.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let v=O.data,C=Ze({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let l=Xe(r,await C.request("funnels",v));if(!l.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(l.run.source.id!==v.funnelId||l.run.locale!==(v.locale??"en")||!nt(l.run.parameters,v.parameters??{})||(v.customer?!l.customerId||v.customer.type==="id"&&l.customerId!==v.customer.value:l.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...l,runToken:l.runToken}}finally{C.dispose()}}}}async function An(r){r={...r};let a=r.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(r.scope&&_(g)!==_(r.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(r.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let v=me.test(r.credential);if(v?!r.customerId:r.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=dt({...r,scope:g,apiKey:r.credential}),l=(w,m)=>{let b=rt({...r,scope:g,runToken:w,initialResponse:m,...v?{serverKey:r.credential}:{}});return v||b.identify(r.credential),b};return{async start(w){let m=await C.start({...w,funnelId:r.funnelId,...v?{customer:{type:"id",value:r.customerId}}:{}}),b=l(m.runToken,m),d=await b.get();return{...m,...d,controller:b}},async restore(w){let m=l(w),b=await m.get();if(b.run.source.id!==r.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...b,runToken:w,controller:m}}}}export{at as a,bt as b,Dt as c,Ut as d,Vt as e,Mt as f,kt as g,Wt as h,pn as i,dt as j,An as k};
1
+ import{A as me,E as rt,b as qe,c as $e,d as Se,h as He,i as Ke,j as Ye,n as We,q as Xe,z as nt}from"./chunk-ANXDWUPK.js";import{a as tt}from"./chunk-67SIVUOS.js";import{c as Ne,d as Te,e as _e,f as Le,g as De,i as Ue,m as ke,n as M,o as Ge,q as be,r as _,s as je,t as ze,u as Be,v as Je}from"./chunk-HLCDAU5A.js";import{K as U,e as Ve,q as ve,r as Me}from"./chunk-DCZWNTG2.js";import{a as fe,b as Ze}from"./chunk-LUGZNBIW.js";import{a as le}from"./chunk-LSVTH3TS.js";import{e as de}from"./chunk-3SXPCVIP.js";import{a as D}from"./chunk-TL67SYPH.js";import{h as ie}from"./chunk-6XRXHFM6.js";import{b as et}from"./chunk-3VUPVXAV.js";import{b as Qe}from"./chunk-ZICZN6WO.js";import{b as e}from"./chunk-GPJF3T43.js";import{c as Fe,f as Pe}from"./chunk-C4NG6RVA.js";var j=e.literal(Ve),ht=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ot=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:xe}),e.strictObject({type:e.literal("customer"),customer:ve,customerData:Me.optional()})]),Ee=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),yt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:Ee.omit({runId:!0,requestId:!0}).nullable()}),wt=e.union([qe,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),It=$e.omit({authenticated:!0}).extend({identity:yt,instruction:wt.nullable()}),vt=e.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})]),pe={contract:j,customerToken:e.string().regex(le)},it={contract:j,requestId:e.uuid(),runToken:ht,externalUserId:ve.options[1].shape.value},at=e.discriminatedUnion("operation",[e.strictObject({contract:j,operation:e.literal("describe")}),e.strictObject({contract:j,operation:e.literal("start"),source:ot,funnelId:U.options[0].shape.funnelId,requestId:e.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),He.omit({operation:!0}).extend({contract:j,operation:e.literal("entry_start"),source:ot}),e.strictObject({...it,operation:e.literal("bind_customer"),guestToken:xe,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...it,operation:e.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("review")}),Ye.omit({customerToken:!0}).extend(pe),e.strictObject({...pe,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:vt})]),bt=Se.omit({run:!0}).extend({contract:j,run:It,settlement:Se.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Dt=Ke.extend({contract:j}),Ut=e.discriminatedUnion("operation",[at.options[1].omit({contract:!0,source:!0,requestId:!0}),at.options[2].omit({contract:!0,source:!0,requestId:!0})]),Vt=bt.extend({binding:Ee,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Mt=e.discriminatedUnion("state",[e.strictObject({contract:j,scope:ie,state:e.literal("not_accepted")}),e.strictObject({contract:j,scope:ie,state:e.literal("conflict")}),e.strictObject({contract:j,scope:ie,state:e.literal("bound"),binding:Ee})]),kt=e.strictObject({contract:j,scope:ie,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var st=e.string().regex(/^[a-f0-9]{64}$/),St=Ne.omit({variations:!0,active:!0}).extend({changeId:st,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),ut=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:st,experiments:e.array(St).max(100),savedGroups:Te}),xt=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),Bt=e.strictObject({events:e.array(xt).min(1).max(20)}),Jt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Wt(r){let a=null,g=null,O=0,v=0,C=new Set,l=null,w=null,m=new Set,b=()=>{for(let s of m)try{s()}catch{}},d={attributes:de.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,I)=>{!C.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(I),structuredClone(d.attributes),a.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,I)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(I),structuredClone(d.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,I=new Set){return C.has(s)?!l||!l.features[s]||["unknownFeature","cyclicPrerequisite"].includes(l.features[s].source):I.has(s)?!1:(I.add(s),(a?.features[s]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(P=>P.experiment.parentConditions??[])].some(P=>h(P.id,I))))}let x=s=>{if(r.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 l?.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(l=null,d.features=a.features),C.has(s)?!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()?S():structuredClone(l.features[s]??S()):r.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!l||h(s)?S():structuredClone(Pe(s,d))};async function V(){if(!a||!C.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=v;if(w?.revision===s)return w.loading;let I=O,F=a,P=[...C],E=(async()=>{let y=Ue.parse(await r.evaluateRemote({attributes:structuredClone(d.attributes),features:P}));if(!(I!==O||s!==v||F!==a)){if(r.assertUsable?.(F.generation),y.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(P.some(T=>!Object.hasOwn(y.features,T))||Object.keys(y.features).some(T=>!C.has(T)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!y.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=de.parse({...d.attributes,...y.merchandiseContext})}l=structuredClone(y),d.features={...F.features,...Object.fromEntries(Object.entries(l.features).map(([T,J])=>[T,{defaultValue:J.value}]))},b()}})();w={revision:s,loading:E};try{await E}finally{w?.loading===E&&(w=null)}}function L(){V().catch(s=>{try{r.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=O,I=(async()=>{let F=await r.load(),P="remoteFeatures"in F?Le.parse(F):null,E=P??_e.parse(F);if(E.scope.projectId!==r.scope.projectId||E.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==O)throw new Error("Feature client was reset");if(r.assertUsable&&a?.generation===E.generation){let{evaluatedAt:T,expiresAt:J,...ae}=a,{evaluatedAt:Z,expiresAt:ge,...z}=E;if(_(ae)!==_(z))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=E.evaluatedAt,a.expiresAt=E.expiresAt,b(),(!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())&&L(),structuredClone(a)}let y=new Set(P?.remoteFeatures??[]);if([...y].some(T=>Object.hasOwn(E.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in E&&!a.analyticsConfig.experimentViewsEnabled&&P?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),a=structuredClone(E),C=y,l=null,w=null,v++,d.features=a.features,d.savedGroups=Fe(a.savedGroups),d.trackedFeatureUsage={},b(),L(),structuredClone(a)})();g=I;try{return await I}finally{g===I&&(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 I=de.parse(s);(d.attributes?.merchandise||d.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=I,v++,l=null,w=null,d.features=a?.features??{},d.trackedFeatureUsage={},b(),L()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,I){let F=x(s).value;return structuredClone(F===null?I:F)},reset(){O++,v++,g=null,w=null,a=null,l=null,C.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),b()}}}var Et=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),Q=2*1048576,Ct=100;function Rt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ct(r,a){let g=a===void 0?Rt():a,O=new Map,v=0,C=!1,l=!1,w,m;async function b(S){if(!g)return null;let h;try{let x=await Promise.race([Promise.resolve().then(()=>g.getItem(S)),new Promise(V=>{h=setTimeout(()=>V(null),Ct)})]);return typeof x=="string"&&x.length<=Q&&new TextEncoder().encode(x).byteLength<=Q?x:null}catch{return null}finally{clearTimeout(h)}}function d(){if(m)return m;let S=(async()=>{try{let h=await b(`${r}:artifacts`);if(h)return Et.parse(JSON.parse(h))}catch{}return{}})();return m=S,S.finally(()=>{m===S&&(m=void 0)}),S}return{async readManifest(){return b(r)},writeManifest(S){!g||S.length>Q||new TextEncoder().encode(S).byteLength>Q||(w=S,!l&&(l=!0,Promise.resolve().then(async()=>{try{for(;w!==void 0;){let h=w;try{await g.setItem(r,h)}catch{}w===h&&(w=void 0)}}finally{l=!1}})))},async readArtifact(S){let h=(await d())[S],x=Date.now();return h&&x>=h.at&&x-h.at<=M.retentionMs?h.text:void 0},writeArtifact(S,h){if(!g||h.length>Q)return;let x=O.get(S);if(x?.text===h||!x&&O.size>=128)return;let V=new TextEncoder().encode(h).byteLength;v-(x?.byteLength??0)+V>Q||(O.set(S,{text:h,byteLength:V}),v+=V-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;O.size;){let L=new Map(O);try{let k={...await d()},s=Date.now();for(let[E,y]of L)k[E]={at:s,text:y.text};let I={},F=2,P=0;for(let[E,y]of Object.entries(k).sort(([,T],[,J])=>J.at-T.at)){if(y.at>s||s-y.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[E]:y})).byteLength;F+T>Q||P>=128||(I[E]=y,F+=T,P++)}await g.setItem(`${r}:artifacts`,JSON.stringify(I))}catch{}finally{for(let[k,s]of L)O.get(k)===s&&(O.delete(k),v-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,a)=>new D(r,a),B=()=>performance.now(),lt=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function pn(r){let a=Ge.parse(r.scope),g=new fe(r.origin??Qe);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 u("INVALID_URL","Configuration requires a trusted HTTPS origin");let O=new Set([g.origin,...(r.assetOrigins??[]).map(t=>{let n=new fe(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return n.origin})]),v=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${a.environmentId}`,l=`indiana:configuration:1:${g.origin}:${_(a)}`,w=ct(l,r.storage),m,b=0,d=0,S=!1,h=!1,x=0,V=0,L,k,s,I,F=0,P=new Set,E=new Set,y=new Map,T=new Map,J=0,ae=!1;function Z(){for(let t of P)try{t()}catch{}}function ge(t){try{r.onError?.(t)}catch{}}let z=()=>!h&&!S&&!!m&&B()<b&&Date.now()<d;function re(){if(!z())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(t,n,i){if(!y.has(t)){for(;y.size&&(y.size>=128||J+i>M.maxCacheBytes);){let o=y.entries().next().value;J-=o[1].byteLength,y.delete(o[0])}y.set(t,{text:n,byteLength:i}),J+=i}}function he(t,n,i){return et(t,n,{signal:i,error:o=>u("INVALID_RESPONSE",o==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function ye(t){let n=new fe(t,g);if(!O.has(n.origin)||n.username||n.password||n.hash||n.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return n.href}async function we(t,n,i=!1){let o=await v(ye(t),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:n,headers:{}});if(o.status===429){let f=o.headers.get("retry-after")??"";F=/^\d+$/.test(f)?Number(f)*1e3:Math.max(0,Date.parse(f)-Date.now())||15e3}if(!o.ok&&o.status!==304)throw u(`CONFIGURATION_HTTP_${o.status}`,"Configuration synchronization failed");return o}function ft(t,n,i){let o=Date.parse(t.headers.get("x-indiana-config-validated-at")??""),f=Date.parse(t.headers.get("x-indiana-config-valid-until")??""),p=Date.parse(t.headers.get("date")??""),c=t.headers.get("age"),R=c!==null&&/^\d+(\.\d+)?$/.test(c)?Number(c)*1e3:NaN;if(![o,f,p,R].every(Number.isFinite)||f<=o||f-o>M.maxControlAgeMs||o>p+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let A=Math.min(f-o,i.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(R,p-o,0)-(B()-n);if(A<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return B()+A}function se(){if(clearTimeout(s),clearTimeout(I),h||!P.size||(z()&&(I=setTimeout(()=>{z()?se():Z()},Math.max(1,b-B())),lt(I)),typeof document<"u"&&document.visibilityState==="hidden"))return;let t=V?Math.min(15e3,1e3*2**Math.min(V-1,4)):Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{X().catch(ge)},Math.max(F,t*(.8+Math.random()*.2))),lt(s)}async function X(){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let t=x,n=new AbortController;k=n;let i=(async()=>{if(!ae){ae=!0;try{let ce=await w.readManifest();if(ce&&!m){let $=be.parse(JSON.parse(ce));_($.scope)===_(a)&&(m=$)}}catch{}}n.signal.throwIfAborted();let c=m,R=B(),N=await we(C,n.signal);N.status===304&&(!c||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await we(C,n.signal));let A=N.status===304?c:be.parse(JSON.parse(await he(N,M.maxManifestBytes,n.signal))),{generation:G,...ne}=A,q=N.headers.get("etag");if(_(A.scope)!==_(a)||ze(ne)!==G||q!==`"${G}"`&&q!==`W/"${G}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(c&&(A.revision<c.revision||A.revision===c.revision&&A.generation!==c.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ce,$]of Object.entries(c?.funnels??{})){let W=A.funnels[ce];if(W&&(W.controlRevision<$.controlRevision||W.evaluationRevision<$.evaluationRevision||W.controlRevision===$.controlRevision&&W.state!==$.state||W.evaluationRevision===$.evaluationRevision&&W.evaluationMode!==$.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=ft(N,R,A.policy);if(n.signal.throwIfAborted(),t!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return m=A,b=Y,d=Date.now()+Math.max(0,Y-B()),S=!1,V=0,F=0,w.writeManifest(_(A)),Z(),structuredClone(A)})(),o=setTimeout(()=>n.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),f=new Promise((c,R)=>n.signal.addEventListener("abort",()=>R(n.signal.reason),{once:!0})),p=Promise.race([i,f]).catch(c=>{throw V++,(c instanceof e.ZodError||c instanceof SyntaxError||c instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(c.code))&&(b=0,S=!0,Z()),c}).finally(()=>{clearTimeout(o),L===p&&(L=void 0),se()});return L=p,p}async function ue(t){let n=t.sha256,i=ne=>tt(ne,t);ye(t.url);let o=y.get(n);if(o){if(o.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return y.delete(n),y.set(n,o),o.text}let f=T.get(n);if(f){if(f.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return f.promise}let p=new AbortController;E.add(p);let c=x,R=(async()=>{try{let Y=await w.readArtifact(n);if(Y&&i(Y)){if(p.signal.throwIfAborted(),h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,Y,t.byteLength),Y}}catch{}p.signal.throwIfAborted();let ne=await we(t.url,p.signal,!0),q=await he(ne,t.byteLength,p.signal);if(!i(q))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,q,t.byteLength),w.writeArtifact(n,q),q})(),N=setTimeout(()=>p.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),A=new Promise((ne,q)=>p.signal.addEventListener("abort",()=>q(p.signal.reason),{once:!0})),G=Promise.race([R,A]).finally(()=>{clearTimeout(N),E.delete(p),T.delete(n)});return T.set(n,{promise:G,byteLength:t.byteLength}),G}async function ee(){return z()||await X(),re(),m}async function K(t){let n,i=new Promise((o,f)=>{n=setTimeout(()=>f(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([t(),i])}finally{clearTimeout(n)}}function H(t,n){if(re(),m?.generation!==t.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(n&&m.funnels[n]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Re(t){let n=t.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let o=De.parse(JSON.parse(await ue(i)));if(_(o.scope)!==_({projectId:a.projectId,environment:a.environment})||o.generation!==i.generation||o.remoteFeatures.some(f=>Object.hasOwn(o.features,f)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return H(t),{...o,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,b-B())).toISOString()}}async function Oe(t,n){let i=await ee(),o=i.funnels[t];n&&(!o||o.evaluationMode==="local"&&!o.versions[n])&&(L&&await L,i=await X()),H(i,t);let f=i.funnels[t];if(f.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let p=n??f.currentVersionId,c=f.versions[p];if(!c)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[c.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[R,N]=await Promise.all([ue(i.artifacts[c.artifact]).then(A=>Je(JSON.parse(A))),f.evaluationMode==="local"?Re(i):void 0]);if(N&&_(Be(R,N))!==_(c.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return H(i,t),{document:R,growth:N,versionId:p,control:structuredClone(f),manifest:structuredClone(i)}}async function Ie(t,n){try{return await Oe(t,n)}catch(i){if(!(i instanceof D)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&z()))throw i;let o=m?.generation;if(L&&await L,await X(),i.code!=="CONFIGURATION_CHANGED"&&m?.generation===o)throw i;return Oe(t,n)}}let oe=new Map;async function mt(t,n){let{FUNNEL_ROUTE_LIMITS:i,funnelRouteSchema:o}=await import("./funnel-route-source-O76QSUYU.js"),f=new AbortController;E.add(f);let p=setTimeout(()=>f.abort(u("CONFIGURATION_UNAVAILABLE","Funnel route read timed out")),M.initializationMs);try{let c=await v(ye(`${C}/funnels/${t}/versions/${n}/route`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:f.signal,headers:{}});if(c.status===404)throw u("ROUTE_UNAVAILABLE","This Funnel Version publishes no route");if(!c.ok)throw u(`CONFIGURATION_HTTP_${c.status}`,"Funnel route read failed");let R=await he(c,i.maxBytes,f.signal),N=je(R),A=c.headers.get("etag");if(A!==`"${N}"`&&A!==`W/"${N}"`)throw u("INVALID_RESPONSE","Funnel route identity changed");let G=o.safeParse(JSON.parse(R));if(!G.success||G.data.funnelId!==t||G.data.versionId!==n)throw u("INVALID_RESPONSE","Funnel route does not describe this Version");return G.data}finally{clearTimeout(p),E.delete(f)}}async function pt(t){let n=await ee();H(n,t);let i=n.funnels[t],o=i.currentVersionId,f;if(i.evaluationMode==="local"){let{projectFunnelRoute:p}=await import("./funnel-route-source-O76QSUYU.js"),c=await Ie(t,o),R=Object.entries(c.manifest.paywalls??{});f=p({funnelId:t,versionId:o,document:c.document,experiments:c.growth?.experiments??{},paywallOf:N=>R.find(([,A])=>Object.hasOwn(A.versions,N))?.[0]})}else{let p=`${t}:${o}`,c=oe.get(p);if(!c||B()-c.readAt>=M.maxControlAgeMs){let R={promise:mt(t,o),readAt:B()};oe.set(p,R),R.promise.catch(()=>{oe.get(p)===R&&oe.delete(p)}),c=R}f=await c.promise}return H(n,t),{route:structuredClone(f),control:structuredClone(i),generation:n.generation}}function te(){if(z()||Z(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}X().catch(ge)}function gt(t){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(t),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("focus",te),document.addEventListener("visibilitychange",te)),se()),()=>{P.delete(t),P.size||(clearTimeout(s),clearTimeout(I),Ae())}}function Ae(){typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",te))}return{scope:Object.freeze({...a}),refresh:X,subscribe:gt,assertFresh:re,assertFeatures(t){re();let n=m.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(t!==void 0&&m.artifacts[n].generation!==t)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return z()?Math.max(0,b-B()):0},async features(){return K(async()=>Re(await ee()))},pageExperiments:()=>K(async()=>{let t=await ee(),n=t.gb.pageExperiments;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let o=ut.parse(JSON.parse(await ue(i)));if(o.environmentId!==a.environmentId||o.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return H(t),o}),funnel:(t,n)=>K(()=>Ie(t,n)),funnelControl:t=>K(async()=>{let n=await ee();return H(n,t),structuredClone(n.funnels[t])}),funnelRoute:t=>K(()=>pt(t)),paywall:(t,n)=>K(async()=>{let i=await ee(),o=i.paywalls?.[t];if(!o||!n&&o.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let f=n??o.currentVersionId,p=o.versions[f],c=p&&i.artifacts[p.artifact];if(!c||c.kind!=="paywall"||c.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let R=ke.parse(JSON.parse(await ue(c)));return H(i),{document:R,versionId:f,version:p.version,control:structuredClone(o),manifest:structuredClone(i)}}),async localFunnel(t,n){let i=await K(()=>Ie(t,n));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:o,remoteFeatures:f,...p}=i.growth;return We({scope:{projectId:a.projectId,environment:a.environment},funnelId:t,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:p})},assertFunnel(t,n,i){re();let o=m.funnels[t];if(!o||o.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(o.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(n!==void 0&&o.controlRevision!==n)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!o.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,x++,b=0,k?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(I),Ae(),Z(),P.clear();for(let t of E)t.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));y.clear(),oe.clear(),J=0}}}}function dt(r){let a=le.test(r.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!me.test(r.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let O=U.safeParse({...g,operation:"start"});if(!O.success||O.data.operation!=="start"||(a?O.data.customer!==void 0:O.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let v=O.data,C=Ze({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let l=Xe(r,await C.request("funnels",v));if(!l.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(l.run.source.id!==v.funnelId||l.run.locale!==(v.locale??"en")||!nt(l.run.parameters,v.parameters??{})||(v.customer?!l.customerId||v.customer.type==="id"&&l.customerId!==v.customer.value:l.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...l,runToken:l.runToken}}finally{C.dispose()}}}}async function An(r){r={...r};let a=r.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(r.scope&&_(g)!==_(r.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(r.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let v=me.test(r.credential);if(v?!r.customerId:r.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=dt({...r,scope:g,apiKey:r.credential}),l=(w,m)=>{let b=rt({...r,scope:g,runToken:w,initialResponse:m,...v?{serverKey:r.credential}:{}});return v||b.identify(r.credential),b};return{async start(w){let m=await C.start({...w,funnelId:r.funnelId,...v?{customer:{type:"id",value:r.customerId}}:{}}),b=l(m.runToken,m),d=await b.get();return{...m,...d,controller:b}},async restore(w){let m=l(w),b=await m.get();if(b.run.source.id!==r.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...b,runToken:w,controller:m}}}}export{at as a,bt as b,Dt as c,Ut as d,Vt as e,Mt as f,kt as g,Wt as h,pn as i,dt as j,An as k};
@@ -1 +1 @@
1
- import{b as e}from"./chunk-2ULWP26K.js";var y=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),z=e.discriminatedUnion("type",[e.object({type:e.literal("fixed"),productVersionId:e.string().min(1).max(200)}).strict(),e.object({type:e.literal("picker"),pickerId:y,allowedProductVersionIds:e.array(e.string().min(1).max(200)).min(1).max(20)}).strict().refine(t=>new Set(t.allowedProductVersionIds).size===t.allowedProductVersionIds.length,"Product choices must be unique")]),x=e.strictObject({min:e.number().finite().min(1).max(1800),max:e.number().finite().min(1).max(1800),viewport:e.number().finite().min(1).max(100)}).refine(t=>t.min<=t.max,"Desktop width range is reversed"),f={desktopWidth:x.optional(),mobile:e.enum(["sheet","fullscreen"]).optional(),backdrop:e.enum(["none","scrim","dim","strong-dim","blur"]).optional()},G=e.discriminatedUnion("type",[e.strictObject({type:e.literal("modal"),position:e.enum(["center","top","bottom"]).optional(),size:e.enum(["sm","md","lg"]),...f}),e.strictObject({type:e.literal("sheet"),size:e.enum(["sm","md","lg"]),...f}),e.strictObject({type:e.literal("fullscreen")}),e.strictObject({type:e.literal("inline")})]),V={sm:360,md:420,lg:560};var c=e.json().superRefine((t,i)=>{let s=0;function o(n,r){if(++s>1e4||r>20){i.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof n=="string"&&(n.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(n))&&i.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(n))n.forEach(a=>o(a,r+1));else if(n&&typeof n=="object")for(let[a,u]of Object.entries(n))(a.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(a)||["__proto__","prototype","constructor"].includes(a))&&i.addIssue({code:"custom",message:"Reserved JSON property"}),o(u,r+1)}o(t,0),new TextEncoder().encode(JSON.stringify(t)).byteLength>65536&&i.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),l=e.record(e.string().min(1).max(128),c).superRefine((t,i)=>{(!c.safeParse(t).success||Object.keys(t).length>128||new TextEncoder().encode(JSON.stringify(t)).byteLength>65536||["__proto__","constructor","prototype"].some(s=>Object.hasOwn(t,s)))&&i.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),S=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),d=l.superRefine((t,i)=>{function s(o){if(Array.isArray(o))o.forEach(s);else if(o&&typeof o=="object")for(let[n,r]of Object.entries(o)){if(n==="$savedGroup"&&!e.strictObject({id:e.uuid(),attributeKey:e.string().min(1).max(128).optional()}).safeParse(r).success&&i.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!n.startsWith("$")&&n.split(".").some(a=>["__proto__","prototype","constructor"].includes(a))&&i.addIssue({code:"custom",message:"Reserved attribute path"}),n.startsWith("$")&&!S.has(n)&&i.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${n}`}),["$regex","$regexi"].includes(n)&&typeof r=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(r)||[...r.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(a=>Number(a[1])>255||Number(a[2]||0)>255)||n==="$regexi"&&/[^\x00-\x7f]/.test(r.replace(/\\u([0-9a-f]{4})/gi,(a,u)=>String.fromCharCode(Number.parseInt(u,16)))))&&i.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(r)}catch{i.addIssue({code:"custom",message:"Invalid regular expression"})}}s(r)}}typeof t.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(t.source)&&("operator"in t||"predicates"in t||"groupId"in t)&&i.addIssue({code:"custom",message:"Obsolete condition protocol"}),s(t)}),w=e.discriminatedUnion("type",[e.strictObject({type:e.literal("condition"),condition:d}),e.strictObject({type:e.literal("list"),attributeKey:e.string().min(1).max(128),values:e.array(e.union([e.string(),e.number().finite()])).max(1e5)})]).refine(t=>t.type!=="list"||new TextEncoder().encode(JSON.stringify(t.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function $(t){let i=new Set;function s(o){if(Array.isArray(o))o.forEach(s);else if(o&&typeof o=="object")for(let[n,r]of Object.entries(o))n==="$savedGroup"&&r&&typeof r=="object"&&!Array.isArray(r)&&typeof r.id=="string"?i.add(r.id):["$inGroup","$notInGroup"].includes(n)&&typeof r=="string"?i.add(r):["$eq","$ne","$in","$nin","$ini","$nini"].includes(n)||s(r)}return s(t),[...i]}var O=e.record(e.uuid(),w).superRefine((t,i)=>{let s=new Set,o=new Set;function n(r){if(s.has(r)){i.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(o.has(r))return;let a=t[r];if(!a){i.addIssue({code:"custom",message:"Missing saved group dependency"});return}s.add(r),a.type==="condition"&&$(a.condition).forEach(n),s.delete(r),o.add(r)}Object.keys(t).forEach(n)}),g=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,i])=>t<=i),h=e.strictObject({attribute:e.string().optional(),seed:e.string().min(1),hashVersion:e.literal(2),ranges:e.array(g).min(1).max(100)}),j=e.strictObject({id:e.string().min(1).max(128),condition:d,gate:e.boolean().optional()}),p={id:e.string().max(128).optional(),condition:d.optional(),parentConditions:e.array(j).max(50).optional(),filters:e.array(h).max(20).optional()},v=e.union([e.strictObject({...p}),e.strictObject({...p,force:c,coverage:e.number().min(0).max(1).optional(),range:g.optional(),seed:e.string().min(1).optional(),hashAttribute:e.string().optional(),hashVersion:e.literal(2).optional()}),e.strictObject({...p,type:e.literal("experiment-ref"),experimentId:e.uuid(),values:e.record(e.string().min(1),c),meta:e.record(e.string().min(1),e.strictObject({passthrough:e.boolean()})).optional()})]),k=e.strictObject({defaultValue:c,rules:e.array(v).max(100)}),U=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),k).superRefine((t,i)=>{Object.keys(t).length>100&&i.addIssue({code:"custom",message:"Too many Features"});let s=new Set,o=new Set;function n(r){if(s.has(r)){i.addIssue({code:"custom",message:`Cyclic Feature dependency: ${r}`});return}if(o.has(r))return;let a=t[r];if(!a){i.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${r}`});return}s.add(r);for(let u of a.rules)for(let m of u.parentConditions??[])n(m.id);s.delete(r),o.add(r)}Object.keys(t).forEach(n)}),F=e.strictObject({name:e.string().max(80),reason:e.string().max(500),dateStarted:e.iso.datetime({offset:!0}),dateEnded:e.iso.datetime({offset:!0}).nullable(),coverage:e.number().min(0).max(1),variationWeights:e.array(e.number().min(0).max(1)).min(2).max(20).refine(t=>Math.abs(t.reduce((i,s)=>i+s,0)-1)<=.01),condition:d,savedGroups:e.array(e.strictObject({match:e.enum(["any","all","none"]),ids:e.array(e.uuid()).min(1)})).max(50),namespace:e.strictObject({id:e.uuid(),ranges:e.array(g).min(1)}).nullable(),seed:e.string().min(1).max(128)}),A=e.strictObject({key:e.string().min(1).max(128),name:e.string().min(1).max(80),hypothesis:e.string().max(2e3),status:e.enum(["draft","running","stopped"]),hashAttribute:e.string().min(1).max(128),fallbackAttribute:e.string().max(128).nullable(),hashVersion:e.literal(2),disableStickyBucketing:e.boolean(),bucketVersion:e.number().int().min(0).max(1e3),minBucketVersion:e.number().int().min(0).max(1e3),variations:e.array(e.strictObject({id:e.string().min(1),key:e.string().min(1),name:e.string().max(80),description:e.string().max(500)})).min(2).max(20),phases:e.array(F).min(1).max(100),releasedVariationId:e.string().nullable(),excludeFromPayload:e.boolean(),statusSchedule:e.strictObject({startAt:e.iso.datetime({offset:!0}).nullable(),stopAt:e.iso.datetime({offset:!0}).nullable(),stopAfter:e.strictObject({value:e.number().int().positive().max(36500),unit:e.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((t,i)=>{(t.minBucketVersion>t.bucketVersion||t.statusSchedule?.stopAt&&t.statusSchedule?.stopAfter||t.phases.some((s,o)=>{if(o===0)return!1;let n=t.phases[o-1];return!n?.dateEnded||Date.parse(s.dateStarted)<Date.parse(n.dateStarted)||Date.parse(n.dateEnded)>Date.parse(s.dateStarted)})||new Set(t.variations.map(s=>s.key)).size!==t.variations.length||new Set(t.variations.map(s=>s.id)).size!==t.variations.length||t.releasedVariationId!==null&&!t.variations.some(s=>s.id===t.releasedVariationId)||t.statusSchedule?.startAt&&t.statusSchedule?.stopAt&&Date.parse(t.statusSchedule.startAt)>=Date.parse(t.statusSchedule.stopAt)||t.phases.some(s=>s.dateEnded&&Date.parse(s.dateStarted)>=Date.parse(s.dateEnded)||s.namespace?.ranges.some(([o,n],r,a)=>o>=n||a.some(([u,m],b)=>b!==r&&o<m&&u<n)))||t.phases.some(s=>s.variationWeights.length!==t.variations.length))&&i.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var I=A.safeExtend({filters:e.array(h).optional()}),D=e.strictObject({experiments:e.record(e.uuid(),I),savedGroups:O}),E=e.strictObject({attributeName:e.string(),attributeValue:e.string(),assignments:e.record(e.string(),e.string())}),M=e.strictObject({snapshot:D,attributes:l,results:l,stickyBucketAssignmentDocs:e.record(e.string(),E)}),W=e.strictObject({variantKey:e.string().nullable(),bucketVersion:e.number().int().min(0),source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:e.number().min(0).max(1).optional(),stickyBucketUsed:e.boolean().optional(),hashUsed:e.boolean().optional()});export{z as a,G as b,V as c,c as d,l as e,d as f,$ as g,E as h};
1
+ import{b as e}from"./chunk-GPJF3T43.js";var y=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),z=e.discriminatedUnion("type",[e.object({type:e.literal("fixed"),productVersionId:e.string().min(1).max(200)}).strict(),e.object({type:e.literal("picker"),pickerId:y,allowedProductVersionIds:e.array(e.string().min(1).max(200)).min(1).max(20)}).strict().refine(t=>new Set(t.allowedProductVersionIds).size===t.allowedProductVersionIds.length,"Product choices must be unique")]),x=e.strictObject({min:e.number().finite().min(1).max(1800),max:e.number().finite().min(1).max(1800),viewport:e.number().finite().min(1).max(100)}).refine(t=>t.min<=t.max,"Desktop width range is reversed"),f={desktopWidth:x.optional(),mobile:e.enum(["sheet","fullscreen"]).optional(),backdrop:e.enum(["none","scrim","dim","strong-dim","blur"]).optional()},G=e.discriminatedUnion("type",[e.strictObject({type:e.literal("modal"),position:e.enum(["center","top","bottom"]).optional(),size:e.enum(["sm","md","lg"]),...f}),e.strictObject({type:e.literal("sheet"),size:e.enum(["sm","md","lg"]),...f}),e.strictObject({type:e.literal("fullscreen")}),e.strictObject({type:e.literal("inline")})]),V={sm:360,md:420,lg:560};var c=e.json().superRefine((t,i)=>{let s=0;function o(n,r){if(++s>1e4||r>20){i.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof n=="string"&&(n.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(n))&&i.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(n))n.forEach(a=>o(a,r+1));else if(n&&typeof n=="object")for(let[a,u]of Object.entries(n))(a.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(a)||["__proto__","prototype","constructor"].includes(a))&&i.addIssue({code:"custom",message:"Reserved JSON property"}),o(u,r+1)}o(t,0),new TextEncoder().encode(JSON.stringify(t)).byteLength>65536&&i.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),l=e.record(e.string().min(1).max(128),c).superRefine((t,i)=>{(!c.safeParse(t).success||Object.keys(t).length>128||new TextEncoder().encode(JSON.stringify(t)).byteLength>65536||["__proto__","constructor","prototype"].some(s=>Object.hasOwn(t,s)))&&i.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),S=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),d=l.superRefine((t,i)=>{function s(o){if(Array.isArray(o))o.forEach(s);else if(o&&typeof o=="object")for(let[n,r]of Object.entries(o)){if(n==="$savedGroup"&&!e.strictObject({id:e.uuid(),attributeKey:e.string().min(1).max(128).optional()}).safeParse(r).success&&i.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!n.startsWith("$")&&n.split(".").some(a=>["__proto__","prototype","constructor"].includes(a))&&i.addIssue({code:"custom",message:"Reserved attribute path"}),n.startsWith("$")&&!S.has(n)&&i.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${n}`}),["$regex","$regexi"].includes(n)&&typeof r=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(r)||[...r.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(a=>Number(a[1])>255||Number(a[2]||0)>255)||n==="$regexi"&&/[^\x00-\x7f]/.test(r.replace(/\\u([0-9a-f]{4})/gi,(a,u)=>String.fromCharCode(Number.parseInt(u,16)))))&&i.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(r)}catch{i.addIssue({code:"custom",message:"Invalid regular expression"})}}s(r)}}typeof t.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(t.source)&&("operator"in t||"predicates"in t||"groupId"in t)&&i.addIssue({code:"custom",message:"Obsolete condition protocol"}),s(t)}),w=e.discriminatedUnion("type",[e.strictObject({type:e.literal("condition"),condition:d}),e.strictObject({type:e.literal("list"),attributeKey:e.string().min(1).max(128),values:e.array(e.union([e.string(),e.number().finite()])).max(1e5)})]).refine(t=>t.type!=="list"||new TextEncoder().encode(JSON.stringify(t.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function $(t){let i=new Set;function s(o){if(Array.isArray(o))o.forEach(s);else if(o&&typeof o=="object")for(let[n,r]of Object.entries(o))n==="$savedGroup"&&r&&typeof r=="object"&&!Array.isArray(r)&&typeof r.id=="string"?i.add(r.id):["$inGroup","$notInGroup"].includes(n)&&typeof r=="string"?i.add(r):["$eq","$ne","$in","$nin","$ini","$nini"].includes(n)||s(r)}return s(t),[...i]}var O=e.record(e.uuid(),w).superRefine((t,i)=>{let s=new Set,o=new Set;function n(r){if(s.has(r)){i.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(o.has(r))return;let a=t[r];if(!a){i.addIssue({code:"custom",message:"Missing saved group dependency"});return}s.add(r),a.type==="condition"&&$(a.condition).forEach(n),s.delete(r),o.add(r)}Object.keys(t).forEach(n)}),g=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,i])=>t<=i),h=e.strictObject({attribute:e.string().optional(),seed:e.string().min(1),hashVersion:e.literal(2),ranges:e.array(g).min(1).max(100)}),j=e.strictObject({id:e.string().min(1).max(128),condition:d,gate:e.boolean().optional()}),p={id:e.string().max(128).optional(),condition:d.optional(),parentConditions:e.array(j).max(50).optional(),filters:e.array(h).max(20).optional()},v=e.union([e.strictObject({...p}),e.strictObject({...p,force:c,coverage:e.number().min(0).max(1).optional(),range:g.optional(),seed:e.string().min(1).optional(),hashAttribute:e.string().optional(),hashVersion:e.literal(2).optional()}),e.strictObject({...p,type:e.literal("experiment-ref"),experimentId:e.uuid(),values:e.record(e.string().min(1),c),meta:e.record(e.string().min(1),e.strictObject({passthrough:e.boolean()})).optional()})]),k=e.strictObject({defaultValue:c,rules:e.array(v).max(100)}),U=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),k).superRefine((t,i)=>{Object.keys(t).length>100&&i.addIssue({code:"custom",message:"Too many Features"});let s=new Set,o=new Set;function n(r){if(s.has(r)){i.addIssue({code:"custom",message:`Cyclic Feature dependency: ${r}`});return}if(o.has(r))return;let a=t[r];if(!a){i.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${r}`});return}s.add(r);for(let u of a.rules)for(let m of u.parentConditions??[])n(m.id);s.delete(r),o.add(r)}Object.keys(t).forEach(n)}),F=e.strictObject({name:e.string().max(80),reason:e.string().max(500),dateStarted:e.iso.datetime({offset:!0}),dateEnded:e.iso.datetime({offset:!0}).nullable(),coverage:e.number().min(0).max(1),variationWeights:e.array(e.number().min(0).max(1)).min(2).max(20).refine(t=>Math.abs(t.reduce((i,s)=>i+s,0)-1)<=.01),condition:d,savedGroups:e.array(e.strictObject({match:e.enum(["any","all","none"]),ids:e.array(e.uuid()).min(1)})).max(50),namespace:e.strictObject({id:e.uuid(),ranges:e.array(g).min(1)}).nullable(),seed:e.string().min(1).max(128)}),A=e.strictObject({key:e.string().min(1).max(128),name:e.string().min(1).max(80),hypothesis:e.string().max(2e3),status:e.enum(["draft","running","stopped"]),hashAttribute:e.string().min(1).max(128),fallbackAttribute:e.string().max(128).nullable(),hashVersion:e.literal(2),disableStickyBucketing:e.boolean(),bucketVersion:e.number().int().min(0).max(1e3),minBucketVersion:e.number().int().min(0).max(1e3),variations:e.array(e.strictObject({id:e.string().min(1),key:e.string().min(1),name:e.string().max(80),description:e.string().max(500)})).min(2).max(20),phases:e.array(F).min(1).max(100),releasedVariationId:e.string().nullable(),excludeFromPayload:e.boolean(),statusSchedule:e.strictObject({startAt:e.iso.datetime({offset:!0}).nullable(),stopAt:e.iso.datetime({offset:!0}).nullable(),stopAfter:e.strictObject({value:e.number().int().positive().max(36500),unit:e.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((t,i)=>{(t.minBucketVersion>t.bucketVersion||t.statusSchedule?.stopAt&&t.statusSchedule?.stopAfter||t.phases.some((s,o)=>{if(o===0)return!1;let n=t.phases[o-1];return!n?.dateEnded||Date.parse(s.dateStarted)<Date.parse(n.dateStarted)||Date.parse(n.dateEnded)>Date.parse(s.dateStarted)})||new Set(t.variations.map(s=>s.key)).size!==t.variations.length||new Set(t.variations.map(s=>s.id)).size!==t.variations.length||t.releasedVariationId!==null&&!t.variations.some(s=>s.id===t.releasedVariationId)||t.statusSchedule?.startAt&&t.statusSchedule?.stopAt&&Date.parse(t.statusSchedule.startAt)>=Date.parse(t.statusSchedule.stopAt)||t.phases.some(s=>s.dateEnded&&Date.parse(s.dateStarted)>=Date.parse(s.dateEnded)||s.namespace?.ranges.some(([o,n],r,a)=>o>=n||a.some(([u,m],b)=>b!==r&&o<m&&u<n)))||t.phases.some(s=>s.variationWeights.length!==t.variations.length))&&i.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var I=A.safeExtend({filters:e.array(h).optional()}),D=e.strictObject({experiments:e.record(e.uuid(),I),savedGroups:O}),E=e.strictObject({attributeName:e.string(),attributeValue:e.string(),assignments:e.record(e.string(),e.string())}),M=e.strictObject({snapshot:D,attributes:l,results:l,stickyBucketAssignmentDocs:e.record(e.string(),E)}),W=e.strictObject({variantKey:e.string().nullable(),bucketVersion:e.number().int().min(0),source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:e.number().min(0).max(1).optional(),stickyBucketUsed:e.boolean().optional(),hashUsed:e.boolean().optional()});export{z as a,G as b,V as c,c as d,l as e,d as f,$ as g,E as h};
@@ -1 +1 @@
1
- import{b as Wn}from"./chunk-BWRRZ2NW.js";import{a as xn,b as Gn,c as dn,d as cn,e as Ue,f as Qn,h as Jn,i as jn,j as zn,k as Bn}from"./chunk-EJSDOSP5.js";import{b as kn,c as Yn}from"./chunk-VWRQBQZD.js";import{a as Ln}from"./chunk-W32FI2A2.js";import{c as Hn,e as Vn,f as Un,h as Mn,i as Fe,j as Ze,k as $n,l as Ke}from"./chunk-AQQJPP3P.js";import{K as Xe}from"./chunk-OAAS5LJY.js";import{a as Ve,d as Tn}from"./chunk-PYLX3WF6.js";import{c as An,e as Sn,f as Nn,g as On,h as Fn,i as _n}from"./chunk-W35FZWGG.js";import{b as qn}from"./chunk-RQTYIUWP.js";import{B as un}from"./chunk-7IVLNV5H.js";import{w as Rn}from"./chunk-VJHURKRY.js";import{t as Dn}from"./chunk-KINNES62.js";import{C as En}from"./chunk-Y2HXKANG.js";import{a as m}from"./chunk-G6CWZBT5.js";import{a as Pe}from"./chunk-DSPLGTQI.js";async function pn(t){let{session:v,load:R}=st(t);try{return await R(),v}catch(e){throw v.destroy(),e}}function st(t){let v=t.view;if(!v?.paywall)throw new m("INVALID_REQUEST","The current node is not a Paywall");let R=v.paywall.receiptId,e=v.nodeId,y=v.visit,N=v.paywall.resolution,o=v.paywall,L="document"in N?{document:N.document,offering:N.offering,capabilities:N.capabilities}:null;function d(){let i=o.resolution;return"document"in i?i:L&&{...i,document:L.document,offering:L.offering,capabilities:An(i.capabilities,L.capabilities)}}function I(i){if(!Sn(i,N))throw new m("INVALID_RESPONSE","The pinned Paywall binding changed")}let E=!1,M=new Set,ne=null;function w(){let i=d();if(i&&!E)for(let l of M)Pe(l,structuredClone(i))}async function V(){F();let i=d();if(i)return structuredClone(i);if(!ne){let l=(async()=>{if("document"in o.resolution||!t.resolvePaywall)throw new m("INVALID_RESPONSE","Public Paywall reader is unavailable");let C=await kn(t,o.resolution);return F(),I(C),L={document:C.document,offering:C.offering,capabilities:C.capabilities},w(),d()})();ne=l;let a=()=>{ne===l&&(ne=null)};l.then(a,a)}return ne.then(l=>structuredClone(l))}let s=new AbortController,T=(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===y&&i.input.type==="paywall_quote")?.requestId??v.paywall.purchaseRequestId,W=0,J=null,Q=new Set,D=null,j=new Map;function A(i){if(i.purchase&&i.purchase.receiptId!==R)throw new m("INVALID_RESPONSE","Purchase receipt changed");let l=i.run.paywall;return i.purchase??(l?.receiptId===R?l:null)}function F(){if(E)throw new m("IDENTITY_CHANGED","Paywall presentation has closed")}function _(i,l,a){if(F(),l!==W||a!==void 0&&o.quote?.operationId!==a)return!1;let C=o.selectionGeneration??0,c=i.run.paywall;if(c?.receiptId===R){if((c.selectionGeneration??0)<(o.selectionGeneration??0))return!1;I(c.resolution)}let u=A(i),b=c?.receiptId===R&&(c.selectionGeneration??0)>C,P=b?u?.quote??null:u?.quote??o.quote,Z=u?.operation??(P?.operationId===o.quote?.operationId?o.operation:null);return o.quote&&P&&Fn(o.quote,P),P&&Z&&Nn(Z,{operationId:P.operationId,membershipId:un(P)?P.membershipId:null,...un(P)?{featureQuantities:P.featureQuantities??{}}:{}},"Purchase operation changed"),(b||P?.operationId!==o.quote?.operationId)&&(W++,c?.receiptId===R&&(T=c.purchaseRequestId)),c?.canReselect===!0&&c.purchaseRequestId===D&&!(t.pendingCommands??[t.pendingCommand]).some($=>$?.requestId===D)&&(D=null),o={...o,...c?.receiptId===R?c:{},...a!==void 0&&!b&&u?.canReselect!==void 0?{canReselect:u.canReselect}:{},quote:P,operation:_n(o.operation,Z,!0)},w(),!0}function pe(i,l,a){return new Promise((C,c)=>{let u=!1,b=()=>{clearTimeout(le),s.signal.removeEventListener("abort",$)},P=Ee=>{u||(u=!0,b(),C(Ee))},Z=Ee=>{u||(u=!0,b(),c(Ee))},$=()=>Z(new m("IDENTITY_CHANGED","Paywall presentation has closed")),le=setTimeout(()=>Z(new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a)),Math.max(0,l-Date.now()));s.signal.addEventListener("abort",$,{once:!0}),s.signal.aborted&&$(),i.then(P,Z)})}function Re(i){return new Promise(l=>{let a=()=>{clearTimeout(C),s.signal.removeEventListener("abort",a),l()},C=setTimeout(a,i);s.signal.addEventListener("abort",a,{once:!0}),s.signal.aborted&&a()})}function se(i,l){F();let a=j.get(i)??t.pendingCommands?.find(u=>u.requestId===i)??t.pendingCommand;if(a?.operation==="submit"&&a.requestId===i&&a.nodeId===e&&a.visit===y){l.type==="paywall_quote"&&a.input.type==="paywall_quote"&&a.input.predecessor&&!l.predecessor&&(l={...l,predecessor:a.input.predecessor});let u=Xe.parse(a),b=Xe.parse({...a,input:l});if(u.operation!=="submit"||b.operation!=="submit"||JSON.stringify(u.input)!==JSON.stringify(b.input))throw new m("CONFLICT","A purchase request cannot change its input");return j.set(i,u),u}let C=t.view;if(!C||C.nodeId!==e||C.visit!==y||C.paywall?.receiptId!==R)throw new m("PRECONDITION_FAILED","The Paywall visit has changed");let c=Xe.parse({operation:"submit",requestId:i,nodeId:e,visit:y,revision:C.revision,input:structuredClone(l)});if(c.operation!=="submit")throw new m("INVALID_REQUEST","A purchase submission is required");return j.set(i,c),c}async function te(i,l){F();let{requestId:a,input:C}=i,c=Date.now()+3e4;Q.add(a);try{let u=await pe(t.submit(i),c,a);for(;u.run.pendingRequest?.requestId===a&&Date.now()<c&&!E&&(await Re(Math.min(1e3,c-Date.now())),!(E||Date.now()>=c));)u=await pe(t.resume(a),c,a);if(E)throw new m("IDENTITY_CHANGED","Paywall presentation has closed");if(u.run.pendingRequest?.requestId===a)throw new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a);if(!_(u,l,C.type==="paywall_confirm"||C.type==="paywall_cancel"?C.operationId:void 0))throw new m("PRECONDITION_FAILED","The purchase selection has changed");D===a&&(D=null)}catch(u){if(D=a,C.type==="paywall_quote"&&t.settle&&!E&&u instanceof m&&u.status!==void 0&&![401,425].includes(u.status)&&!u.retryable&&u.recovery!=="recover_operation")try{if((await pe(t.settle(a),c,a)).settlement?.state==="settled"){let P=await pe(t.get(),c,a);_(P,l)&&P.run.paywall?.purchaseRequestId===a&&o.canReselect===!0&&j.delete(a)}}catch{}throw u instanceof m&&u.code==="COMMAND_PENDING"&&u.status===void 0&&j.delete(a),u}finally{Q.delete(a)}}async function we(i){if(!o.quote)throw new m("INVALID_REQUEST","A quoted purchase is required");let l=i==="confirm"?"paywall_confirm":"paywall_cancel",a=[...j.values(),...t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])].find(c=>c.operation==="submit"&&c.input.type===l&&"operationId"in c.input&&c.input.operationId===o.quote.operationId),C=a?.operation==="submit"&&a.input.type===l&&"operationId"in a.input&&a.input.operationId===o.quote.operationId?a.requestId:crypto.randomUUID();if(await te(se(C,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.quote.operationId,...i==="confirm"&&o.quote.merchantTerms?{merchantConfirmation:Rn(o.quote.merchantTerms)}:{}}),W),!o.operation)throw new m("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(o.operation)}let G={get view(){return structuredClone(d())},get quote(){return o.quote?structuredClone(o.quote):null},get operation(){return o.operation?structuredClone(o.operation):null},get webViewUrl(){return t.webViewUrl},get locale(){return t.view?.locale??v.locale},get canReselect(){return o.canReselect===!0&&D===null},get recovery(){let i=t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[]),l=t.pendingPurchase;if(l&&(l.receiptId!==R||l.operationId!==o.quote?.operationId))return{type:"recover",operationId:l.operationId,requestId:i[0]?.requestId??null};let a=Ve({quote:o.quote,operation:o.operation,requestId:i[0]?.requestId??D??T,pending:Q.size>0||i.length>0||D!==null,destroyed:E,canReselect:o.canReselect});return a.type==="recover"&&a.requestId===null&&!E&&t.hasDurableJournal===!0&&!o.quote&&!o.operation&&(o.selectionGeneration??0)===0&&!l&&!i.length&&!Q.size&&!T?{type:"native",operationId:null}:a},get pendingCancellation(){return!E&&(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===y&&i.input.type==="paywall_cancel"&&i.input.operationId===o.quote?.operationId)},subscribe(i){return E?()=>{}:(M.add(i),()=>M.delete(i))},async refresh(){F();let i=W,l=await t.get();if(_(l,i),l.run.paywall?.receiptId!==R)throw new m("PRECONDITION_FAILED","Paywall presentation has changed");return V()},preview(i){let l=d();if(!l)return Promise.reject(new m("PRECONDITION_FAILED","Load the Paywall presentation first"));if(T&&T!==i.requestId&&(J||o.canReselect!==!0))return Promise.reject(new m("COMMAND_PENDING","Retry the original purchase before starting another"));let a=l.document.buttons[i.actionId],C=a?.type==="checkout"?qn(a.product,i.selection,l.capabilities):null;if(!C)return Promise.reject(new m("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let c=Dn(l.document.screen,C,i.selection,l.capabilities),u=T!==i.requestId&&(o.selectionGeneration??0)>0?{operationId:o.quote?.operationId??null,generation:o.selectionGeneration??0}:void 0,b=t.view?.parameters.commerce;if(b&&typeof b=="object"&&!Array.isArray(b)&&b.intent==="subscription_change"&&!i.subscriptionChange)return Promise.reject(new m("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(i.subscriptionChange&&i.nativeOffer)return Promise.reject(new m("INVALID_REQUEST","A web membership change cannot include a store offer"));if(u&&o.canReselect!==!0)return Promise.reject(new m("COMMAND_PENDING","Original purchase requires authoritative termination"));let P;try{P=se(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:C,...Object.keys(c).length?{featureQuantities:c}:{},...u?{predecessor:u}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{},...i.subscriptionChange?{subscriptionChange:i.subscriptionChange}:{}})}catch(le){return Promise.reject(le)}if(T===i.requestId&&J)return J;T!==i.requestId&&W++;let Z=W;T=i.requestId;let $=(async()=>{if(await te(P,Z),!o.quote)throw new m("INVALID_RESPONSE","The accepted quote is missing");return On(o.quote,{productVersionId:C,featureQuantities:c,subscriptionChange:i.subscriptionChange},"The selected purchase changed"),structuredClone(o.quote)})();return J=$,$.then(()=>{J===$&&(J=null)},le=>{J===$&&(J=null),T===i.requestId&&t.pendingCommand?.requestId!==i.requestId&&le instanceof m&&le.status!==void 0&&le.status<500&&![401,425].includes(le.status)&&(T=null)}),$},confirm:()=>we("confirm"),cancel:()=>we("cancel"),async read(){if(F(),!o.quote)throw new m("INVALID_REQUEST","A quoted purchase is required");let i=o.quote.operationId,l=W,a=t.pendingCommands?.find(P=>P.operation==="submit"&&(P.input.type==="paywall_confirm"||P.input.type==="paywall_cancel")&&P.input.operationId===i)??t.pendingCommand;a?.operation==="submit"&&(a.input.type==="paywall_confirm"||a.input.type==="paywall_cancel")&&a.input.operationId===i&&await t.settle?.(a.requestId);let C=await t.get(void 0,{receiptId:R,operationId:i});F();let c=A(C);if(c?.quote&&c.quote.operationId!==i||c?.operation&&c.operation.operationId!==i)throw new m("INVALID_RESPONSE","Purchase operation changed");let u=_(C,l,i),b=u?o.operation:c?.operation;if(!b)throw new m("INVALID_RESPONSE","The current purchase result is missing");return u&&Q.size===0&&!(t.pendingCommands?.length??(t.pendingCommand?1:0))&&(D=null),structuredClone(b)},destroy(){E=!0,S(),M.clear(),s.abort(),j.clear()}},S=t.subscribe(i=>{E||i.nodeId!==e||i.visit!==y||i.paywall?.receiptId!==R||(i.paywall.selectionGeneration??0)<(o.selectionGeneration??0)||(I(i.paywall.resolution),o={...o,resolution:i.paywall.resolution},w())});return{session:G,load:V}}function Xn(t){let v=new Set,R=new Set,e=null;async function y(d,I){let E=!1;for(;!t.stopped&&t.key===d&&t.client.pendingCommand?.requestId===I;){if(!t.client.settle)throw new m("COMMAND_PENDING","The original display acknowledgement is still pending");await t.client.settle(I),E=!0,t.client.pendingCommand?.requestId===I&&await new Promise(M=>setTimeout(M,1500))}t.stopped||t.key!==d||(E&&await t.client.get(),!(t.stopped||t.key!==d)&&v.add(d))}function N(d,I){e=I;let E=()=>{e===I&&(e=null),R.delete(d)};return I.then(E,M=>{E(),t.busy||t.fail(M)}),I}function o(d){if(t.reviewing||v.has(d)||R.has(d)||t.stopped)return;R.add(d);let I=async()=>{if(t.reviewing||t.stopped||t.key!==d||v.has(d)){R.delete(d);return}if(t.busy||t.client.pendingCommand){setTimeout(()=>{I()},250);return}let E=(async()=>{if(t.staleRead){if(await t.staleRead,t.stopped||t.key!==d)return;if(t.client.pendingCommand){setTimeout(()=>{I()},250);return}}let M=t.client.view,ne=t.expected(),w=ne.requestId;try{await t.client.submit({operation:"shown",...ne})}catch(V){if(!(V instanceof m)||V.code!=="CONFLICT"||V.status!==409||t.client.pendingCommand)throw V;await t.client.get();let s=t.client.view;if(t.stopped||t.reviewing||t.key!==d||!s||!M||s.id!==M.id||s.source.versionId!==M.source.versionId||s.nodeId!==ne.nodeId||s.visit!==ne.visit||s.revision<=ne.revision||s.stopped||!s.screen&&(!s.paywall||s.paywall.receiptId!==M.paywall?.receiptId)||!["running","waiting"].includes(s.status)||t.client.pendingCommand)throw V;let q=t.expected();w=q.requestId,await t.client.submit({operation:"shown",...q})}await y(d,w)})();N(d,E)};I()}function L(){if(e)return e;let d=t.client.pendingCommand;if(d?.operation!=="shown")return null;let I=t.key;return R.add(I),N(I,(async()=>{await t.client.retry(),await y(I,d.requestId)})())}return{report:o,settled:L,get inFlight(){return e}}}function Zn(t){let v={},R=new Map;async function e(y){let N=t.client.view,o=N?.screen,L=o?.customerData.nodes[y.nodeId];if(t.stopped||t.busy||!N||!o||!L)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(y.action)){let V=t.document,s=V?En(V,y.nodeId):null,q=s?.type==="customer_data"?s.data.outputs?.[y.action]:void 0;q&&o.outputs.includes(q)?await t.perform(()=>t.client.submit({operation:"submit",...t.expected(),input:{type:"screen",output:q,answers:t.answers,selection:y.value?{[y.nodeId]:y.value}:{}}})):await t.onIntent?.(y,N);return}let I=y.action.startsWith("sources_")?L.resources.find(V=>V.key===y.value):null;if(y.action.startsWith("sources_")&&!I)throw new m("INVALID_REQUEST","Choose a current resource");let E=`${N.visit}:${y.nodeId}:${I?.key??""}`,M=R.get(E)??[null],w=v[y.nodeId]??{page:1,after:null,filter:"all",...I?{resourceKey:I.key}:{}};if(y.action==="filter"){let V=y.value;if(!V||!(L.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(V))throw new m("INVALID_REQUEST","Unknown data filter");w={page:1,after:null,filter:V},M.splice(0,M.length,null)}else if(y.action==="next"||y.action==="sources_next"){let V=I?.sources.at(-1),s=I?V?{kind:"ledger",cursor:{at:V.detail[0],id:V.id,type:"source"}}:null:o.dataCursors[y.nodeId];if(!s||!I&&!L.hasNext)return;M[w.page]=s,w={...w,page:w.page+1,after:s}}else if(y.action==="previous"||y.action==="sources_previous"){if(w.page<=1)return;w={...w,page:w.page-1,after:M[w.page-2]??null}}R.set(E,M),v={...v,[y.nodeId]:w},await t.perform(()=>t.client.get({nodeId:N.nodeId,visit:N.visit,revision:N.revision,components:v}))}return{get queries(){return v},intent:e,reset(){v={},R.clear()}}}function Kn(t){let{doc:v,holder:R,reviewHolder:e,mountScreenPreview:y}=t,N=!1,o,L=0,d=null,I="",E,M=new Map,ne=s=>s?`${s.id}:${s.nodeId}:${s.visit}:${s.revision}:${s.paywall?.quote?.operationId??""}`:"";async function w(s){if(t.stopped||!t.client.review||N&&s===o&&E?.active)return;let q=!N||s!==o;N||(I=ne(t.client.view),M.set(I,structuredClone(t.answers))),N=!0,o=s,R.hidden=!0,t.suspend(!0),e.hidden=!1;let T=++L;q&&(E?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),E=Ze(e,t.loadingOptions,"funnel",()=>{V()}));let W=q?E:void 0;try{if(W?.start(!1,t.client.view?.locale),T!==L||t.stopped)return;let J=t.client.review(s),Q=await(W?.wait(J,Fe)??J);if(t.stopped||T!==L||!N)return;if(!Q.review)throw new m("INVALID_RESPONSE","Historical projection is missing");d?.destroy(),d=null,W||e.replaceChildren();let D=v.createElement("div"),j=W?Ke(D,e):()=>{};e.append(D);let A=Q.run.locale.startsWith("zh"),F=t.chrome;D.style.cssText=F.history;let _=v.createElement("p");_.textContent=A?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",_.style.cssText=F.historyTitle,D.append(_);let pe=v.createElement("p");pe.style.cssText=F.historyNote,pe.textContent=Q.review.pages.length?A?"\u9009\u62E9\u4E00\u9875\u67E5\u770B\u5F53\u65F6\u7684\u5185\u5BB9\uFF0C\u56DE\u770B\u4E0D\u4F1A\u6539\u52A8\u4EFB\u4F55\u4FE1\u606F\u3002":"Choose a page to see it as it was. Nothing here can be changed.":A?"\u8FD8\u6CA1\u6709\u53EF\u56DE\u770B\u7684\u9875\u9762\u3002":"There are no earlier pages yet.",D.append(pe);let Re=Q.review.page?.receiptId,se=v.createElement("div");se.style.cssText=F.historyPages;for(let[G,S]of Q.review.pages.entries()){let i=v.createElement("button");i.type="button",i.textContent=A?`\u7B2C ${G+1} \u9875`:`Page ${G+1}`;let l=Re!==void 0&&S.receiptId===Re;i.style.cssText=l?F.primary:F.secondary,l&&i.setAttribute("aria-current","page"),Ue(i,()=>t.chrome.focus),i.onclick=()=>{w(S.receiptId)},se.append(i)}if(se.childElementCount&&D.append(se),Q.review.page){let G=Q.review.page,S=v.createElement("div");S.inert=!0,S.style.cssText=F.historyPage,D.append(S),d=y(S,{mode:"live",rendererUrl:t.client.webViewUrl,title:G.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{T===L&&!t.stopped&&W?.present(j)},onError:l=>{if(T!==L||t.stopped)return;let a=new Error(l);W?.finish("error",a),d?.destroy(),d=null,D.remove(),t.fail(a)},onEscape:()=>{V()}});let i=d;if(i.update(G.document,Q.run.locale,{serverInput:{bindings:G.inputs,answers:G.answers,values:G.values}}),await i.ready,t.stopped||T!==L||!N)return}let te=A?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},we=v.createElement("div");we.style.cssText=F.historyRecords;for(let G of[...Q.review.coupons.map((S,i)=>`${A?"\u4F18\u60E0\u5238":"Coupon"} ${i+1}: ${te[S.status]}`),...Q.review.purchases.map((S,i)=>`${A?"\u8D2D\u4E70":"Purchase"} ${i+1}: ${Bn(S.status,A)}`)]){let S=v.createElement("p");S.textContent=G,S.style.margin="0",we.append(S)}we.childElementCount&&D.append(we),Q.review.page||W?.present(j),t.client.view&&await t.enqueue(t.client.view)}catch(J){if(T!==L||t.stopped)return;W?.finish("error",J),d?.destroy(),d=null,e.replaceChildren(),t.fail(J)}}async function V(){if(!N||t.stopped||!t.client.review)return;let s=++L;E?.finish("dismissed");try{if(await t.client.review(),t.stopped||s!==L)return;N=!1,L++,E?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),e.hidden=!0,R.hidden=!1;let q=t.client.view;ne(q)!==I?(M.set(I,structuredClone(t.answers)),t.resetScreen()):(M.delete(I),t.suspend(!1)),q&&await t.enqueue(q)}catch(q){if(s!==L||t.stopped)return;d?.destroy(),d=null,e.replaceChildren(),t.fail(q)}}return{get active(){return N},get receipt(){return o},open:w,exit:V,get drafts(){return new Map([...M].map(([s,q])=>[s,structuredClone(q)]))},stop(){N=!1,L++,E?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),e.hidden=!0,R.hidden=!1}}}var fn=5e3;async function at(t,v,R){let e=v,y=e.prepared&&Wn(e.prepared),N=()=>{};function o(){e.prepared&&e.prepared.state!=="adopted"&&y?.release()}let L=()=>e.prepared?.state==="shown"&&!!y?.modal,d=e.client.identitySignal,I;try{I=await Promise.all([import("./screen-renderer-SEJG7A2C.js"),import("./paywall-YZAEI7TF.js")]),e.signal?.throwIfAborted(),d?.throwIfAborted()}catch(n){throw o(),n}let[{mountScreenPreview:E},{showPaywall:M}]=I,ne=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&e.appManifestRelease?Yn({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;ne?.start();let w=t.ownerDocument,V=Mn(w),s=w.createElement("section"),q=w.createElement("div"),T=w.createElement("div"),W=w.createElement("div"),J=w.createElement("button");W.hidden=!0,J.type="button";let Q=w.createElement("p"),D=w.createElement("p"),j=w.createElement("button"),A=w.createElement("button"),F=w.createElement("button"),_=w.createElement("dialog"),pe,Re=!1;s.dataset.indianaFunnel="",s.dataset.longplayCloseOwner="sdk",s.setAttribute("aria-busy","false"),Q.setAttribute("role","status"),D.setAttribute("role","alert"),D.hidden=!0,j.type=A.type=F.type="button",T.append(j,J,Q,D,F,A),s.append(q,W,T),t.append(s);let se=Gn,te=dn(se),we="",G=(w.documentElement.lang||"").startsWith("zh"),S,i="",l;for(let n of[j,J,F,A])Ue(n,()=>te.focus);function a(){let n=G?"\u5173\u95ED":"Close";A.parentElement===_?(A.textContent="\xD7",A.setAttribute("aria-label",n),Un(A,se)):(A.textContent=n,A.removeAttribute("aria-label"),A.style.cssText=te.link+";margin-inline-start:auto")}function C(n){let r=n?.screen?.content.document.theme??se,p=JSON.stringify([r.primary,r.background,r.text,r.radius,r.font,A.parentElement===_]);if(p===we)return;we=p,se=r;let H=A.parentElement===_;te=dn(se,H),s.style.cssText=te.root+";min-width:0"+(H?";display:flex;flex-direction:column;min-height:100%":""),T.style.cssText=te.bar+(H?";margin-top:auto":""),T.hidden&&(T.style.display="none"),j.style.cssText=J.style.cssText=te.secondary,F.style.cssText=te.primary,Q.style.cssText=te.status,D.style.cssText=te.alert,a(),cn(j)}function c(){T.hidden=j.hidden&&J.hidden&&F.hidden&&D.hidden&&!Q.textContent&&(A.hidden||A.parentElement!==T),T.style.display=T.hidden?"none":"flex",S?.responsive&&l!==void 0&&S.setContentHeight(l+T.getBoundingClientRect().height)}C();let u=null,b=null,P=null,Z="",$="",le=!1,Ee="",en="",Me="",g=!1,ue=0,$e=!1,mn="",nn=null,tn=Promise.resolve(),wn=!e.client.view,z=R,Te,_e,xe="",Ge,de=!1,qe=null,ve=!1,Qe=()=>e.client.pendingCommand?.operation==="close",ce=null,Y=null,yn=Ln({document:w,run:async()=>{(!b?.observing||e.client.pendingCommand)&&await on()},delay:()=>{if(!(g||!P||!["running","waiting"].includes(P.status)&&!e.client.pendingCommand)&&!(b?.observing&&!e.client.pendingCommand))return P.pendingRequest||e.client.pendingCommand?1500:fn},hiddenDelay:()=>!g&&e.client.pendingCommand?15e3:void 0}),K=null;function rn(){return Y&&e.client.hasDurableJournal===!0&&K?.acknowledged===!0&&K.operationId===Y.operationId&&e.client.view?.id===K.runId&&e.client.view?.status==="closed"&&e.client.view.revision===K.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?Y:null}function hn(n){let r=n.run.paywall;if(K&&n.settlement?.requestId===K.requestId&&n.settlement.state==="settled"&&n.settlement.operationId===null&&n.run.id===K.runId&&n.run.status==="closed"&&!n.run.pendingRequest&&n.run.revision===K.revision+1&&n.run.nodeId===K.nodeId&&n.run.visit===K.visit&&r?.receiptId===K.receiptId&&r.selectionGeneration===K.selectionGeneration&&(r.quote?.operationId??null)===K.operationId&&(r.operation?.operationId??r.quote?.operationId??null)===K.operationId){let p=K.operationId===null&&r.selectionGeneration===0&&!r.quote&&!r.operation&&!r.purchaseRequestId,H=Ve({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect});(p||r.canReselect===!0&&H.type==="native")&&(K.acknowledged=!0)}}let De=null,Je=new Set,ye={},Ae=!1,fe=(n,r=null)=>{g||(De=r,Ae=!1,D.textContent=Qn(n,G),D.hidden=!1,F.hidden=e.client.pendingCommand===null,c(),Pe(e.onError,n))},gn=()=>{g||(De=null,D.textContent=jn(G),D.hidden=!1,F.hidden=!0,c())};function ke(){let n=e.client.view;if(!n)throw new m("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision}}let O=Kn({client:e.client,doc:w,holder:q,reviewHolder:W,mountScreenPreview:E,loadingOptions:e,get chrome(){return te},get stopped(){return g},get answers(){return ye},suspend(n){b?.setSuspended(n)},resetScreen(){Z="",$="",Ee=""},enqueue:he,fail:fe}),Le=Xn({client:e.client,expected:ke,fail:fe,get stopped(){return g},get reviewing(){return O.active},get key(){return Z},get busy(){return ue},get staleRead(){return nn}}),je=Zn({client:e.client,expected:ke,perform:Ne,onIntent:e.onCustomerDataIntent,get stopped(){return g},get busy(){return ue},get document(){return u?.document},get answers(){return ye}}),ze=n=>`${n.id}:${n.nodeId}:${n.visit}`,Se=n=>n&&(n.screen||n.paywall)?ze(n):"";function Ie(){let n=e.client.view;j.disabled=!O.active&&(ue>0||!!e.client.pendingCommand||!n?.canBack||n.stopped||!["running","waiting"].includes(n.status)||!Se(n)||$!==Se(n)),j.hidden=!O.active&&!n?.canBack,cn(j);let r=!!b&&!O.active;A.hidden=r&&!z?.active||Re&&!O.active,J.hidden=!e.client.review||!O.active&&!n?.canBack,r&&(Q.textContent=""),c()}async function vn(n){if(!n)return;let r=e.client.view;await n;let p=e.client.view;if(!r||!p||p.id!==r.id||p.nodeId!==r.nodeId||p.visit!==r.visit||p.stopped||!["running","waiting"].includes(p.status))throw new m("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Ne(n,r=!1,p){if(!((ue||ve||ce||Y)&&!r||g||O.active&&!r)){ue++,s.setAttribute("aria-busy","true"),D.hidden=!0,De=null,Ae=!1,Ie();try{if(r||await vn(Le.inFlight),g)return;let H=await n();g||await he(e.client.view??H.run)}catch(H){p?.(H)&&e.client.pendingCommand===null?gn():fe(H,e.client.pendingCommand?.requestId??null)}finally{ue=Math.max(0,ue-1),s.setAttribute("aria-busy",String(ue>0)),g||(F.hidden=e.client.pendingCommand===null,Ie())}}}function He(){yn.schedule()}async function on(){if(!(g||$e||ue)){if(O.active){await O.open(O.receipt);return}$e=!0;try{let n=e.client.pendingCommand;n&&e.client.settle&&await e.client.settle(n.requestId);let r=e.client.view,p=je.queries,H=await e.client.get(r?.screen&&Object.keys(p).length?{nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:p}:void 0);Ae&&!g&&(Ae=!1,D.hidden=!0,c()),!g&&p===je.queries&&await he(e.client.view??H.run)}catch(n){fe(n),Ae=!g}finally{$e=!1}}}function Be(n,r,p){if(z?.active){let ae=z;return ae.setDismissHandler(()=>In(ae)),ae}let H=Ze(t,e,"funnel",()=>In(H),xn);return z=H,H.start(n,r,p),H}function In(n){g||de||(de=!0,n.finish("dismissed"),be(),s.hidden=!0,e.client.view?Ce().finally(ie):ie())}function sn(){clearTimeout(Ge?.timeout),Ge=void 0}function be(){Re=!1,sn(),Te?.abort(),Te=void 0,u?.destroy(),u=null,b?.destroy(),b=null,_e?.(),_e=void 0,_.open&&_.close(),q.replaceChildren(),q.style.cssText="",l=void 0,Z="",$="",le=!1,Ee="",Me=""}function bn(){let n=w.defaultView;S?.responsive&&n&&u?.resizeViewport?.(n.innerHeight,n.innerWidth)}function an(){S?.destroy(),S=void 0,i=""}function We(n){let r=n.screen?.presentation;if(!r||r.type==="inline"){_.open&&_.close(),an(),A.parentElement!==T&&T.append(A),s.parentElement!==t&&t.append(s);for(let ae of["flex","display","flex-direction","justify-content"])q.style.removeProperty(ae);C(n),c();return}s.parentElement!==_&&(_.append(A,s),t.append(_)),q.style.flex="1 0 auto",q.style.display="flex",q.style.flexDirection="column",q.style.justifyContent="center",C(n);let p=n.screen.content.document,H=JSON.stringify([r,we]);if(H!==i){an(),i=H;let ae={sm:420,md:640,lg:900},ge="size"in r&&!r.backdrop?",0 0 0 100vmax #16142566":"";_.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${se.background};color:${se.text};`+(r.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ae[r.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${ge};`+(r.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),S=Hn(_,{presentation:r,theme:p.theme,pages:p.pages},bn),S.latch()}c(),_.setAttribute("aria-label",(pe?.screen===n.screen?.content.document.name?pe?.label:void 0)??u?.document?.name??n.screen?.content.document.name??"Funnel")}async function et(n){if(g||de||ve&&(Qe()||["running","waiting"].includes(n.status))||(P=n,De&&e.client.pendingCommand?.requestId!==De&&(D.hidden=!0,De=null),G=n.locale.startsWith("zh"),J.textContent=G?"\u56DE\u770B":"History",j.textContent=O.active?G?"\u8FD4\u56DE\u5F53\u524D":"Return to current":G?"\u8FD4\u56DE":"Back",a(),F.textContent=G?"\u91CD\u8BD5":"Retry",F.hidden=e.client.pendingCommand===null,Q.textContent=n.pendingRequest?G?"\u6B63\u5728\u5904\u7406":"Processing":n.instruction?.type==="wait"?G?"\u7B49\u5F85\u4E2D":"Waiting":"",Ie(),mn!==`${n.revision}:${n.visit}:${n.status}:${n.stopped}`&&(mn=`${n.revision}:${n.visit}:${n.status}:${n.stopped}`,Pe(e.onState,structuredClone(n))),g||de))return;if((!n.pendingRequest||ve&&n.status==="closed")&&["closed","ineligible","failed"].includes(n.status)){ie();return}if(n.stopped&&L()){ie();return}if(n.stopped||e.client.configurationReady===!1){O.stop(),o(),be(),z?.finish("skipped"),s.hidden=!0,He();return}if(s.hidden=!1,O.active){He();return}let r=Se(n),p=e.client.view;if(p&&p.revision>n.revision&&Se(p)!==r)return;let H=!n.instruction&&!n.pendingRequest&&n.nodeType==="screen"&&["running","waiting"].includes(n.status);r!==Z&&(Z&&z?.finish("dismissed"),be(),Z=r,ye={...n.answers},je.reset());let ae=ze(n);if(xe===ae){s.hidden=!0;return}if(H&&!r){s.hidden=!0;let U=e.prepared?.state==="shown"?null:Be(!0,n.locale);!g&&!de&&Ge?.key!==ae&&(sn(),Ge={key:ae,timeout:setTimeout(()=>{let h=e.client.view;if(g||!U?.active&&e.prepared?.state!=="shown"||!h||ze(h)!==ae)return;xe=ae;let B=new Error("Funnel screen preparation timed out");U?.finish("error",B),o(),be(),fe(B)},Fe)}),He();return}sn();let X=U=>{let h=e.client.view;return!g&&!de&&!qe&&!U.aborted&&e.client.configurationReady!==!1&&!!h&&!h.stopped&&!["closed","ineligible","failed"].includes(h.status)&&Se(h)===r},ge=(U,h)=>{X(h)&&(xe=r,z?.finish("error",U),be(),s.hidden=!0,fe(U))};if(r||((n.instruction&&n.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(n.status))&&o(),We(n),n.instruction?.type!=="event"&&n.instruction?.type!=="open_url"&&z?.finish("skipped")),n.screen){o();let U=n.screen.content;if(!u){let x=n.screen.presentation.type!=="inline",re=Be(x,n.locale);if(g||de)return;let ee=(Te=new AbortController).signal;We(n),_e=x?$n(_):Ke(s,t),u=E(q,{mode:"live",closeActions:Array.from(new Set([...e.closeActions??[],...U.document.actions.filter(f=>f.type==="event"&&f.close).map(f=>f.id)])),onAuthoredClose(f){X(ee)&&(Re=f,Ie())},rendererUrl:e.client.webViewUrl,title:U.document.name,...x?{hostPresentation:()=>S?.type??n.screen.presentation.type}:{},onResize:f=>{l=f,S?.responsive&&S.setContentHeight(f+T.getBoundingClientRect().height)},onAction(f,me={},ot={}){if(O.active||!X(ee)||$!==r)return;ye={...ye,...ot};let ln=n.screen?.inputs??[],Pn=Object.fromEntries(ln.filter(({variable:Oe})=>Object.hasOwn(ye,Oe)).map(({variable:Oe})=>[Oe,ye[Oe]]));if(zn(ln,Pn).length){gn();return}Ne(()=>e.client.submit({operation:"submit",...ke(),input:{type:"screen",output:f,answers:Pn,selection:me}}),!1,Oe=>Jn(Oe,ln))},onAnswers:f=>{O.active||!X(ee)||$!==r||(ye={...ye,...f})},onCustomerDataIntent:f=>{O.active||!X(ee)||$!==r||je.intent(f).catch(fe)},onEscape:()=>{!X(ee)||$!==r||O.active||ce||Y||Ce()},onError:f=>{let me=new Error(f);$===r?fe(me):ge(me,ee)},onRendered:f=>{if(!(!X(ee)||$===r))try{re.present(me=>{_e?.(),_e=void 0,f&&(pe={screen:U.document.name,label:f},_.setAttribute("aria-label",f)),x&&(_.showModal(),S?.responsive&&_.focus({preventScroll:!0}),!me&&e.loading!=="host"&&Vn(_,S?.type??n.screen.presentation.type,S?.responsive)),$=r,le=x,Ie()}),X(ee)&&Le.report(r)}catch(me){ge(me,ee)}}}),bn()}let h={capabilities:n.screen.capabilities,customerData:n.screen.customerData,parameters:n.parameters,serverInput:{bindings:n.screen.inputs,answers:ye,values:n.screen.values}},B=JSON.stringify([U,n.locale,h.parameters,n.screen.inputs,n.screen.values]);if(B!==Ee)u.update(U.document,n.locale,h),Ee=B,en=JSON.stringify(h.capabilities),Me=JSON.stringify(h.customerData);else{let x=JSON.stringify(h.capabilities);x!==en&&(u.updateCapabilities(h.capabilities),en=x),JSON.stringify(h.customerData)!==Me&&(u.updateCustomerData(h.customerData),Me=JSON.stringify(h.customerData))}let oe=u;if(oe)try{await(z?.wait(oe.ready)??oe.ready)}catch(x){Te&&ge(x,Te.signal)}}else if(n.paywall&&!b){let U=n.paywall.resolution,h="document"in U?U.document:null,B=y,oe=null,x=(Te=new AbortController).signal,re={loading:"host",signal:x,canInteract:()=>X(x)&&!O.active&&!ce&&!Y,beforeAction:async()=>{ue++;try{await vn(Le.settled()),D.hidden=!0,De=null,Ae=!1,c()}finally{ue=Math.max(0,ue-1)}},start:()=>pn(e.client),onObservationChange:He,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,resumeCheckout:e.resumeCheckout,allowNewPurchase:e.allowNewPurchase,checkoutNavigation:e.checkoutNavigation,terminateCheckout:e.terminateCheckout,confirmOnHostedCheckout:e.confirmOnHostedCheckout,resolveOfferId:e.resolveOfferId,resolveSubscriptionChange:e.resolveSubscriptionChange,claimCoupon:e.claimCoupon,onEvent:e.onEvent,onOpenUrl:f=>e.onOpenUrl?e.onOpenUrl({receiptId:n.paywall.receiptId,url:f,openIn:"same_window"}):w.defaultView?.location.assign(f),onAction:async f=>{if(O.active)return;let me=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:e.client.view?.revision??n.revision,input:{type:"screen",output:f,answers:{}}});await he(e.client.view??me.run)},onError:f=>{$===r?fe(f):ge(f,x)}},ee={quoteError:f=>Pe(e.onError,f),present(f){X(x)&&(oe?.present(()=>{f(),$=r,le=!!q.querySelector("dialog[open]"),Ie()}),X(x)&&Le.report(r))},async dismiss(){if(!(g||x.aborted||O.active||ce||Y||!ve&&!X(x))){if(ve=!0,(e.resumeCheckout||e.terminateCheckout)&&rt()){P=e.client.view,ie();return}await Ce()}}};if(B){let f=await B.adopt(n,{options:re,handoff:ee,start:()=>pn(e.client)});f&&X(x)&&!g?(We(n),b=f,z?.active&&z.present(()=>{}),$=r,le=B.modal,Ie(),Le.report(r),O.active&&b.setSuspended(!0)):(f?.destroy(),o())}if(g||de)return;if(!b){if(oe=Be(!0,n.locale,h),g||de)return;We(n);let f=await M(q,re,ee).catch(me=>(ge(me,x),null));!X(x)&&!(ve&&!g&&!x.aborted)?f?.host?.destroy():f&&(b=f.host,b?.setSuspended(O.active))}}if(g||de)return;Ie();let k=n.instruction;if(k&&(k.type==="open_url"||k.type==="event")&&!Je.has(k.receiptId)){let U=w.createElement("button");U.type="button",U.style.cssText=te.primary,Ue(U,()=>te.focus),q.style.cssText=te.stage,U.textContent=k.type==="open_url"?`${G?"\u524D\u5F80":"Continue to"} ${new URL(k.url).host}`:G?"\u7EE7\u7EED":"Continue",U.onclick=()=>{let h=ke(),B=k.type==="open_url"&&!e.onOpenUrl&&k.openIn==="new_window"?nt(k.url):null;Ne(async()=>{let oe="success";if(k.type==="open_url")if(e.onOpenUrl)try{oe=await e.onOpenUrl({receiptId:k.receiptId,url:k.url,openIn:k.openIn})===!1?"failed":"opened"}catch(re){Pe(e.onError,re),oe="failed"}else oe=k.openIn==="new_window"&&!B?"failed":"opened";if(k.type==="event"){if(!e.onEvent)throw new m("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(k.event)}if(g||e.client.view?.nodeId!==h.nodeId||e.client.view.visit!==h.visit)throw new m("PRECONDITION_FAILED","The client action visit changed");let x=await e.client.submit({operation:"submit",...h,input:{type:"client_action",receiptId:k.receiptId,outcome:oe}});return Je.add(k.receiptId),k.type==="open_url"&&!e.onOpenUrl&&k.openIn==="same_window"&&w.defaultView?.location.assign(k.url),x})},z?.active?z.present(()=>q.replaceChildren(U)):q.replaceChildren(U)}!n.pendingRequest&&n.status==="completed"&&!Je.has(`complete:${n.id}`)&&(Je.add(`complete:${n.id}`),Pe(e.onComplete,structuredClone(n))),He()}function nt(n){let r=w.defaultView?.open(n,"_blank")??null;return r&&(r.opener=null),r}function he(n){return Ie(),tn=tn.catch(()=>{}).then(async()=>{try{await et(n)}catch(r){throw z?.active&&(xe=ze(n),z.finish("error",r),be(),s.hidden=!0),r}}),tn}let tt=e.client.subscribe(n=>{if(!wn){if(n.stopped&&(le||L())&&!ve){P=n,ie();return}!ve&&(n.stopped||e.client.configurationReady===!1||Z&&$!==Z&&(Se(n)!==Z||["closed","ineligible","failed"].includes(n.status)))&&(be(),z?.finish("dismissed"),s.hidden=!0),he(n).catch(fe)}}),it=e.client.subscribeError?.(fe);function rt(){let n=e.client.view,r=n?.paywall;return!!r?.operation&&!!n&&["running","waiting"].includes(n.status)&&Tn(Ve({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect}))}function Ce(n){if(qe)return qe;if(g||!n&&(ce||Y))return Promise.resolve();let r=!n&&Qe();return!r&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(P=e.client.view,ie(),Promise.resolve()):(qe=Ne(async()=>{let p=r?await e.client.retry():await e.client.submit({operation:"close",...n??ke()});return n&&hn(p),p},!0).then(()=>{let p=e.client.view;p?.status==="closed"&&!Qe()&&(P=p,ie())}).finally(()=>{qe=null}),qe)}function ie(){ne?.destroy(),!g&&(g=!0,N(),o(),e.signal?.removeEventListener("abort",ie),d?.removeEventListener("abort",ie),z?.finish("dismissed"),yn.destroy(),tt(),it?.(),be(),an(),O.stop(),_.remove(),s.remove(),V(),Pe(e.onDismiss,P?structuredClone(P):null))}j.onclick=()=>{if(!j.disabled){if(O.active){O.exit();return}Ne(()=>e.client.submit({operation:"back",...ke()}))}},J.onclick=()=>{O.open()},A.onclick=()=>{z?.active?z.dismiss():ce||Ce()},F.onclick=()=>{Qe()?Ce():Ne(()=>e.client.retry())},_.addEventListener("cancel",n=>{n.preventDefault(),z?.active?z.dismiss():ce||Ce()}),e.signal?.addEventListener("abort",ie,{once:!0}),d?.addEventListener("abort",ie,{once:!0});let Ye=!1;y&&(N=y.onClose(()=>{g||de||(de=!0,z?.finish("dismissed"),be(),s.hidden=!0,e.client.view?Ce().finally(ie):Ye=!0)}));let Cn={destroy:ie,refresh:on,get recovery(){let n=rn();if(n)return n;if(!g&&!ue&&!ve&&!ce&&b){let r=b.recovery;if(r.type!=="native")return r}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??Y?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(ce)return ce;let n=rn();if(n)return Promise.resolve(n);let r=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??Y?.operationId??null,p=()=>({type:"recover",operationId:r,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let k=b?.recovery;return Promise.resolve(k&&k.type!=="native"&&k.type!=="cancel"?k:p())}let H=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(k=>k.operation==="close");if(g&&!(H||Y&&e.client.view?.status==="closed")||ue||$e||qe||O.active||!b&&!Y&&!H)return Promise.resolve(p());let ae=b,X=(async()=>{try{if(!Y&&H){let h=await e.client.retry();return await he(e.client.view??h.run),p()}if(!Y){let h=await ae.prepareFallback();if(h.type!=="native")return h;if(e.client.hasDurableJournal!==!0)return p();Y=h}let k=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(k.length){let h=k.find(oe=>oe.operation==="close");if(!h||!K||h.requestId!==K.requestId)return p();let B=await e.client.retry();hn(B),await he(e.client.view??B.run)}else{let h=e.client.view,B=h?.paywall;if(!h||!B||B.selectionGeneration===void 0||(B.quote?.operationId??null)!==Y.operationId||Y.operationId!==null&&B.canReselect!==!0)return p();let oe=B.selectionGeneration,x=await e.client.get();await he(e.client.view??x.run);let re=e.client.view,ee=re?.paywall;if(!re||!ee||!["running","waiting"].includes(re.status)||re.stopped||re.id!==h.id||re.nodeId!==h.nodeId||re.visit!==h.visit||ee.receiptId!==B.receiptId||ee.selectionGeneration!==oe||(ee.quote?.operationId??null)!==Y.operationId||Y.operationId!==null&&ee.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return p();let f=ke();K={runId:re.id,operationId:Y.operationId,revision:f.revision,requestId:f.requestId,nodeId:re.nodeId,visit:re.visit,receiptId:ee.receiptId,selectionGeneration:oe,acknowledged:!1},await Ce(f)}let U=rn();return U?(ie(),U):p()}catch(k){return fe(k),p()}})();ce=X;let ge=()=>{ce===X&&(ce=null)};return X.then(ge,ge),X},review:O.open,exitReview:O.exit,get unappliedDrafts(){return O.drafts}};try{let n=e.client.view;if(n)((e.client.viewAgeMs??fn)>=fn||n.instruction?.type==="evaluate_segment")&&(nn=on().finally(()=>{nn=null})),await he(n);else{if(s.hidden=!0,g)throw new DOMException("Presentation cancelled","AbortError");let r=Ye||e.prepared?.state==="shown"?null:Be(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(g||de&&!Ye)throw new DOMException("Presentation cancelled","AbortError");let p=e.client.get(),H=await(r?r.wait(p,Fe):lt(p,Fe));if(wn=!1,Ye)return g||await Ce().finally(ie),Cn;await he(e.client.view??H.run)}}catch(n){throw z?.finish("error",n),ie(),n}return Cn}function lt(t,v){let R;return Promise.race([t,new Promise((e,y)=>{R=setTimeout(()=>y(new Error("Presentation data timed out")),v)})]).finally(()=>clearTimeout(R))}function Bt(t,v,R){return at(t,v,R)}export{at as a,Bt as b};
1
+ import{b as Wn}from"./chunk-JWTA2OCB.js";import{a as xn,b as Gn,c as dn,d as cn,e as Ue,f as Qn,h as Jn,i as jn,j as zn,k as Bn}from"./chunk-HTXB2WVI.js";import{b as kn,c as Yn}from"./chunk-KEF6HIFK.js";import{a as Ln}from"./chunk-W32FI2A2.js";import{c as Hn,e as Vn,f as Un,h as Mn,i as Fe,j as Ze,k as $n,l as Ke}from"./chunk-P6TNBX2S.js";import{K as Xe}from"./chunk-DCZWNTG2.js";import{a as Ve,d as Tn}from"./chunk-B4AELNLE.js";import{c as An,e as Sn,f as Nn,g as On,h as Fn,i as _n}from"./chunk-AQONMY2H.js";import{b as qn}from"./chunk-RDUKCMST.js";import{B as un}from"./chunk-KP4QI4RX.js";import{w as Rn}from"./chunk-5TJISOWN.js";import{t as Dn}from"./chunk-7MYS52FL.js";import{C as En}from"./chunk-MWICFZUF.js";import{a as m}from"./chunk-TL67SYPH.js";import{a as Pe}from"./chunk-DSPLGTQI.js";async function pn(t){let{session:v,load:R}=st(t);try{return await R(),v}catch(e){throw v.destroy(),e}}function st(t){let v=t.view;if(!v?.paywall)throw new m("INVALID_REQUEST","The current node is not a Paywall");let R=v.paywall.receiptId,e=v.nodeId,y=v.visit,N=v.paywall.resolution,o=v.paywall,L="document"in N?{document:N.document,offering:N.offering,capabilities:N.capabilities}:null;function d(){let i=o.resolution;return"document"in i?i:L&&{...i,document:L.document,offering:L.offering,capabilities:An(i.capabilities,L.capabilities)}}function I(i){if(!Sn(i,N))throw new m("INVALID_RESPONSE","The pinned Paywall binding changed")}let E=!1,M=new Set,ne=null;function w(){let i=d();if(i&&!E)for(let l of M)Pe(l,structuredClone(i))}async function V(){F();let i=d();if(i)return structuredClone(i);if(!ne){let l=(async()=>{if("document"in o.resolution||!t.resolvePaywall)throw new m("INVALID_RESPONSE","Public Paywall reader is unavailable");let C=await kn(t,o.resolution);return F(),I(C),L={document:C.document,offering:C.offering,capabilities:C.capabilities},w(),d()})();ne=l;let a=()=>{ne===l&&(ne=null)};l.then(a,a)}return ne.then(l=>structuredClone(l))}let s=new AbortController,T=(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===y&&i.input.type==="paywall_quote")?.requestId??v.paywall.purchaseRequestId,W=0,J=null,Q=new Set,D=null,j=new Map;function A(i){if(i.purchase&&i.purchase.receiptId!==R)throw new m("INVALID_RESPONSE","Purchase receipt changed");let l=i.run.paywall;return i.purchase??(l?.receiptId===R?l:null)}function F(){if(E)throw new m("IDENTITY_CHANGED","Paywall presentation has closed")}function _(i,l,a){if(F(),l!==W||a!==void 0&&o.quote?.operationId!==a)return!1;let C=o.selectionGeneration??0,c=i.run.paywall;if(c?.receiptId===R){if((c.selectionGeneration??0)<(o.selectionGeneration??0))return!1;I(c.resolution)}let u=A(i),b=c?.receiptId===R&&(c.selectionGeneration??0)>C,P=b?u?.quote??null:u?.quote??o.quote,Z=u?.operation??(P?.operationId===o.quote?.operationId?o.operation:null);return o.quote&&P&&Fn(o.quote,P),P&&Z&&Nn(Z,{operationId:P.operationId,membershipId:un(P)?P.membershipId:null,...un(P)?{featureQuantities:P.featureQuantities??{}}:{}},"Purchase operation changed"),(b||P?.operationId!==o.quote?.operationId)&&(W++,c?.receiptId===R&&(T=c.purchaseRequestId)),c?.canReselect===!0&&c.purchaseRequestId===D&&!(t.pendingCommands??[t.pendingCommand]).some($=>$?.requestId===D)&&(D=null),o={...o,...c?.receiptId===R?c:{},...a!==void 0&&!b&&u?.canReselect!==void 0?{canReselect:u.canReselect}:{},quote:P,operation:_n(o.operation,Z,!0)},w(),!0}function pe(i,l,a){return new Promise((C,c)=>{let u=!1,b=()=>{clearTimeout(le),s.signal.removeEventListener("abort",$)},P=Ee=>{u||(u=!0,b(),C(Ee))},Z=Ee=>{u||(u=!0,b(),c(Ee))},$=()=>Z(new m("IDENTITY_CHANGED","Paywall presentation has closed")),le=setTimeout(()=>Z(new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a)),Math.max(0,l-Date.now()));s.signal.addEventListener("abort",$,{once:!0}),s.signal.aborted&&$(),i.then(P,Z)})}function Re(i){return new Promise(l=>{let a=()=>{clearTimeout(C),s.signal.removeEventListener("abort",a),l()},C=setTimeout(a,i);s.signal.addEventListener("abort",a,{once:!0}),s.signal.aborted&&a()})}function se(i,l){F();let a=j.get(i)??t.pendingCommands?.find(u=>u.requestId===i)??t.pendingCommand;if(a?.operation==="submit"&&a.requestId===i&&a.nodeId===e&&a.visit===y){l.type==="paywall_quote"&&a.input.type==="paywall_quote"&&a.input.predecessor&&!l.predecessor&&(l={...l,predecessor:a.input.predecessor});let u=Xe.parse(a),b=Xe.parse({...a,input:l});if(u.operation!=="submit"||b.operation!=="submit"||JSON.stringify(u.input)!==JSON.stringify(b.input))throw new m("CONFLICT","A purchase request cannot change its input");return j.set(i,u),u}let C=t.view;if(!C||C.nodeId!==e||C.visit!==y||C.paywall?.receiptId!==R)throw new m("PRECONDITION_FAILED","The Paywall visit has changed");let c=Xe.parse({operation:"submit",requestId:i,nodeId:e,visit:y,revision:C.revision,input:structuredClone(l)});if(c.operation!=="submit")throw new m("INVALID_REQUEST","A purchase submission is required");return j.set(i,c),c}async function te(i,l){F();let{requestId:a,input:C}=i,c=Date.now()+3e4;Q.add(a);try{let u=await pe(t.submit(i),c,a);for(;u.run.pendingRequest?.requestId===a&&Date.now()<c&&!E&&(await Re(Math.min(1e3,c-Date.now())),!(E||Date.now()>=c));)u=await pe(t.resume(a),c,a);if(E)throw new m("IDENTITY_CHANGED","Paywall presentation has closed");if(u.run.pendingRequest?.requestId===a)throw new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a);if(!_(u,l,C.type==="paywall_confirm"||C.type==="paywall_cancel"?C.operationId:void 0))throw new m("PRECONDITION_FAILED","The purchase selection has changed");D===a&&(D=null)}catch(u){if(D=a,C.type==="paywall_quote"&&t.settle&&!E&&u instanceof m&&u.status!==void 0&&![401,425].includes(u.status)&&!u.retryable&&u.recovery!=="recover_operation")try{if((await pe(t.settle(a),c,a)).settlement?.state==="settled"){let P=await pe(t.get(),c,a);_(P,l)&&P.run.paywall?.purchaseRequestId===a&&o.canReselect===!0&&j.delete(a)}}catch{}throw u instanceof m&&u.code==="COMMAND_PENDING"&&u.status===void 0&&j.delete(a),u}finally{Q.delete(a)}}async function we(i){if(!o.quote)throw new m("INVALID_REQUEST","A quoted purchase is required");let l=i==="confirm"?"paywall_confirm":"paywall_cancel",a=[...j.values(),...t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])].find(c=>c.operation==="submit"&&c.input.type===l&&"operationId"in c.input&&c.input.operationId===o.quote.operationId),C=a?.operation==="submit"&&a.input.type===l&&"operationId"in a.input&&a.input.operationId===o.quote.operationId?a.requestId:crypto.randomUUID();if(await te(se(C,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.quote.operationId,...i==="confirm"&&o.quote.merchantTerms?{merchantConfirmation:Rn(o.quote.merchantTerms)}:{}}),W),!o.operation)throw new m("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(o.operation)}let G={get view(){return structuredClone(d())},get quote(){return o.quote?structuredClone(o.quote):null},get operation(){return o.operation?structuredClone(o.operation):null},get webViewUrl(){return t.webViewUrl},get locale(){return t.view?.locale??v.locale},get canReselect(){return o.canReselect===!0&&D===null},get recovery(){let i=t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[]),l=t.pendingPurchase;if(l&&(l.receiptId!==R||l.operationId!==o.quote?.operationId))return{type:"recover",operationId:l.operationId,requestId:i[0]?.requestId??null};let a=Ve({quote:o.quote,operation:o.operation,requestId:i[0]?.requestId??D??T,pending:Q.size>0||i.length>0||D!==null,destroyed:E,canReselect:o.canReselect});return a.type==="recover"&&a.requestId===null&&!E&&t.hasDurableJournal===!0&&!o.quote&&!o.operation&&(o.selectionGeneration??0)===0&&!l&&!i.length&&!Q.size&&!T?{type:"native",operationId:null}:a},get pendingCancellation(){return!E&&(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===y&&i.input.type==="paywall_cancel"&&i.input.operationId===o.quote?.operationId)},subscribe(i){return E?()=>{}:(M.add(i),()=>M.delete(i))},async refresh(){F();let i=W,l=await t.get();if(_(l,i),l.run.paywall?.receiptId!==R)throw new m("PRECONDITION_FAILED","Paywall presentation has changed");return V()},preview(i){let l=d();if(!l)return Promise.reject(new m("PRECONDITION_FAILED","Load the Paywall presentation first"));if(T&&T!==i.requestId&&(J||o.canReselect!==!0))return Promise.reject(new m("COMMAND_PENDING","Retry the original purchase before starting another"));let a=l.document.buttons[i.actionId],C=a?.type==="checkout"?qn(a.product,i.selection,l.capabilities):null;if(!C)return Promise.reject(new m("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let c=Dn(l.document.screen,C,i.selection,l.capabilities),u=T!==i.requestId&&(o.selectionGeneration??0)>0?{operationId:o.quote?.operationId??null,generation:o.selectionGeneration??0}:void 0,b=t.view?.parameters.commerce;if(b&&typeof b=="object"&&!Array.isArray(b)&&b.intent==="subscription_change"&&!i.subscriptionChange)return Promise.reject(new m("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(i.subscriptionChange&&i.nativeOffer)return Promise.reject(new m("INVALID_REQUEST","A web membership change cannot include a store offer"));if(u&&o.canReselect!==!0)return Promise.reject(new m("COMMAND_PENDING","Original purchase requires authoritative termination"));let P;try{P=se(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:C,...Object.keys(c).length?{featureQuantities:c}:{},...u?{predecessor:u}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{},...i.subscriptionChange?{subscriptionChange:i.subscriptionChange}:{}})}catch(le){return Promise.reject(le)}if(T===i.requestId&&J)return J;T!==i.requestId&&W++;let Z=W;T=i.requestId;let $=(async()=>{if(await te(P,Z),!o.quote)throw new m("INVALID_RESPONSE","The accepted quote is missing");return On(o.quote,{productVersionId:C,featureQuantities:c,subscriptionChange:i.subscriptionChange},"The selected purchase changed"),structuredClone(o.quote)})();return J=$,$.then(()=>{J===$&&(J=null)},le=>{J===$&&(J=null),T===i.requestId&&t.pendingCommand?.requestId!==i.requestId&&le instanceof m&&le.status!==void 0&&le.status<500&&![401,425].includes(le.status)&&(T=null)}),$},confirm:()=>we("confirm"),cancel:()=>we("cancel"),async read(){if(F(),!o.quote)throw new m("INVALID_REQUEST","A quoted purchase is required");let i=o.quote.operationId,l=W,a=t.pendingCommands?.find(P=>P.operation==="submit"&&(P.input.type==="paywall_confirm"||P.input.type==="paywall_cancel")&&P.input.operationId===i)??t.pendingCommand;a?.operation==="submit"&&(a.input.type==="paywall_confirm"||a.input.type==="paywall_cancel")&&a.input.operationId===i&&await t.settle?.(a.requestId);let C=await t.get(void 0,{receiptId:R,operationId:i});F();let c=A(C);if(c?.quote&&c.quote.operationId!==i||c?.operation&&c.operation.operationId!==i)throw new m("INVALID_RESPONSE","Purchase operation changed");let u=_(C,l,i),b=u?o.operation:c?.operation;if(!b)throw new m("INVALID_RESPONSE","The current purchase result is missing");return u&&Q.size===0&&!(t.pendingCommands?.length??(t.pendingCommand?1:0))&&(D=null),structuredClone(b)},destroy(){E=!0,S(),M.clear(),s.abort(),j.clear()}},S=t.subscribe(i=>{E||i.nodeId!==e||i.visit!==y||i.paywall?.receiptId!==R||(i.paywall.selectionGeneration??0)<(o.selectionGeneration??0)||(I(i.paywall.resolution),o={...o,resolution:i.paywall.resolution},w())});return{session:G,load:V}}function Xn(t){let v=new Set,R=new Set,e=null;async function y(d,I){let E=!1;for(;!t.stopped&&t.key===d&&t.client.pendingCommand?.requestId===I;){if(!t.client.settle)throw new m("COMMAND_PENDING","The original display acknowledgement is still pending");await t.client.settle(I),E=!0,t.client.pendingCommand?.requestId===I&&await new Promise(M=>setTimeout(M,1500))}t.stopped||t.key!==d||(E&&await t.client.get(),!(t.stopped||t.key!==d)&&v.add(d))}function N(d,I){e=I;let E=()=>{e===I&&(e=null),R.delete(d)};return I.then(E,M=>{E(),t.busy||t.fail(M)}),I}function o(d){if(t.reviewing||v.has(d)||R.has(d)||t.stopped)return;R.add(d);let I=async()=>{if(t.reviewing||t.stopped||t.key!==d||v.has(d)){R.delete(d);return}if(t.busy||t.client.pendingCommand){setTimeout(()=>{I()},250);return}let E=(async()=>{if(t.staleRead){if(await t.staleRead,t.stopped||t.key!==d)return;if(t.client.pendingCommand){setTimeout(()=>{I()},250);return}}let M=t.client.view,ne=t.expected(),w=ne.requestId;try{await t.client.submit({operation:"shown",...ne})}catch(V){if(!(V instanceof m)||V.code!=="CONFLICT"||V.status!==409||t.client.pendingCommand)throw V;await t.client.get();let s=t.client.view;if(t.stopped||t.reviewing||t.key!==d||!s||!M||s.id!==M.id||s.source.versionId!==M.source.versionId||s.nodeId!==ne.nodeId||s.visit!==ne.visit||s.revision<=ne.revision||s.stopped||!s.screen&&(!s.paywall||s.paywall.receiptId!==M.paywall?.receiptId)||!["running","waiting"].includes(s.status)||t.client.pendingCommand)throw V;let q=t.expected();w=q.requestId,await t.client.submit({operation:"shown",...q})}await y(d,w)})();N(d,E)};I()}function L(){if(e)return e;let d=t.client.pendingCommand;if(d?.operation!=="shown")return null;let I=t.key;return R.add(I),N(I,(async()=>{await t.client.retry(),await y(I,d.requestId)})())}return{report:o,settled:L,get inFlight(){return e}}}function Zn(t){let v={},R=new Map;async function e(y){let N=t.client.view,o=N?.screen,L=o?.customerData.nodes[y.nodeId];if(t.stopped||t.busy||!N||!o||!L)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(y.action)){let V=t.document,s=V?En(V,y.nodeId):null,q=s?.type==="customer_data"?s.data.outputs?.[y.action]:void 0;q&&o.outputs.includes(q)?await t.perform(()=>t.client.submit({operation:"submit",...t.expected(),input:{type:"screen",output:q,answers:t.answers,selection:y.value?{[y.nodeId]:y.value}:{}}})):await t.onIntent?.(y,N);return}let I=y.action.startsWith("sources_")?L.resources.find(V=>V.key===y.value):null;if(y.action.startsWith("sources_")&&!I)throw new m("INVALID_REQUEST","Choose a current resource");let E=`${N.visit}:${y.nodeId}:${I?.key??""}`,M=R.get(E)??[null],w=v[y.nodeId]??{page:1,after:null,filter:"all",...I?{resourceKey:I.key}:{}};if(y.action==="filter"){let V=y.value;if(!V||!(L.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(V))throw new m("INVALID_REQUEST","Unknown data filter");w={page:1,after:null,filter:V},M.splice(0,M.length,null)}else if(y.action==="next"||y.action==="sources_next"){let V=I?.sources.at(-1),s=I?V?{kind:"ledger",cursor:{at:V.detail[0],id:V.id,type:"source"}}:null:o.dataCursors[y.nodeId];if(!s||!I&&!L.hasNext)return;M[w.page]=s,w={...w,page:w.page+1,after:s}}else if(y.action==="previous"||y.action==="sources_previous"){if(w.page<=1)return;w={...w,page:w.page-1,after:M[w.page-2]??null}}R.set(E,M),v={...v,[y.nodeId]:w},await t.perform(()=>t.client.get({nodeId:N.nodeId,visit:N.visit,revision:N.revision,components:v}))}return{get queries(){return v},intent:e,reset(){v={},R.clear()}}}function Kn(t){let{doc:v,holder:R,reviewHolder:e,mountScreenPreview:y}=t,N=!1,o,L=0,d=null,I="",E,M=new Map,ne=s=>s?`${s.id}:${s.nodeId}:${s.visit}:${s.revision}:${s.paywall?.quote?.operationId??""}`:"";async function w(s){if(t.stopped||!t.client.review||N&&s===o&&E?.active)return;let q=!N||s!==o;N||(I=ne(t.client.view),M.set(I,structuredClone(t.answers))),N=!0,o=s,R.hidden=!0,t.suspend(!0),e.hidden=!1;let T=++L;q&&(E?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),E=Ze(e,t.loadingOptions,"funnel",()=>{V()}));let W=q?E:void 0;try{if(W?.start(!1,t.client.view?.locale),T!==L||t.stopped)return;let J=t.client.review(s),Q=await(W?.wait(J,Fe)??J);if(t.stopped||T!==L||!N)return;if(!Q.review)throw new m("INVALID_RESPONSE","Historical projection is missing");d?.destroy(),d=null,W||e.replaceChildren();let D=v.createElement("div"),j=W?Ke(D,e):()=>{};e.append(D);let A=Q.run.locale.startsWith("zh"),F=t.chrome;D.style.cssText=F.history;let _=v.createElement("p");_.textContent=A?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",_.style.cssText=F.historyTitle,D.append(_);let pe=v.createElement("p");pe.style.cssText=F.historyNote,pe.textContent=Q.review.pages.length?A?"\u9009\u62E9\u4E00\u9875\u67E5\u770B\u5F53\u65F6\u7684\u5185\u5BB9\uFF0C\u56DE\u770B\u4E0D\u4F1A\u6539\u52A8\u4EFB\u4F55\u4FE1\u606F\u3002":"Choose a page to see it as it was. Nothing here can be changed.":A?"\u8FD8\u6CA1\u6709\u53EF\u56DE\u770B\u7684\u9875\u9762\u3002":"There are no earlier pages yet.",D.append(pe);let Re=Q.review.page?.receiptId,se=v.createElement("div");se.style.cssText=F.historyPages;for(let[G,S]of Q.review.pages.entries()){let i=v.createElement("button");i.type="button",i.textContent=A?`\u7B2C ${G+1} \u9875`:`Page ${G+1}`;let l=Re!==void 0&&S.receiptId===Re;i.style.cssText=l?F.primary:F.secondary,l&&i.setAttribute("aria-current","page"),Ue(i,()=>t.chrome.focus),i.onclick=()=>{w(S.receiptId)},se.append(i)}if(se.childElementCount&&D.append(se),Q.review.page){let G=Q.review.page,S=v.createElement("div");S.inert=!0,S.style.cssText=F.historyPage,D.append(S),d=y(S,{mode:"live",rendererUrl:t.client.webViewUrl,title:G.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{T===L&&!t.stopped&&W?.present(j)},onError:l=>{if(T!==L||t.stopped)return;let a=new Error(l);W?.finish("error",a),d?.destroy(),d=null,D.remove(),t.fail(a)},onEscape:()=>{V()}});let i=d;if(i.update(G.document,Q.run.locale,{serverInput:{bindings:G.inputs,answers:G.answers,values:G.values}}),await i.ready,t.stopped||T!==L||!N)return}let te=A?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},we=v.createElement("div");we.style.cssText=F.historyRecords;for(let G of[...Q.review.coupons.map((S,i)=>`${A?"\u4F18\u60E0\u5238":"Coupon"} ${i+1}: ${te[S.status]}`),...Q.review.purchases.map((S,i)=>`${A?"\u8D2D\u4E70":"Purchase"} ${i+1}: ${Bn(S.status,A)}`)]){let S=v.createElement("p");S.textContent=G,S.style.margin="0",we.append(S)}we.childElementCount&&D.append(we),Q.review.page||W?.present(j),t.client.view&&await t.enqueue(t.client.view)}catch(J){if(T!==L||t.stopped)return;W?.finish("error",J),d?.destroy(),d=null,e.replaceChildren(),t.fail(J)}}async function V(){if(!N||t.stopped||!t.client.review)return;let s=++L;E?.finish("dismissed");try{if(await t.client.review(),t.stopped||s!==L)return;N=!1,L++,E?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),e.hidden=!0,R.hidden=!1;let q=t.client.view;ne(q)!==I?(M.set(I,structuredClone(t.answers)),t.resetScreen()):(M.delete(I),t.suspend(!1)),q&&await t.enqueue(q)}catch(q){if(s!==L||t.stopped)return;d?.destroy(),d=null,e.replaceChildren(),t.fail(q)}}return{get active(){return N},get receipt(){return o},open:w,exit:V,get drafts(){return new Map([...M].map(([s,q])=>[s,structuredClone(q)]))},stop(){N=!1,L++,E?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),e.hidden=!0,R.hidden=!1}}}var fn=5e3;async function at(t,v,R){let e=v,y=e.prepared&&Wn(e.prepared),N=()=>{};function o(){e.prepared&&e.prepared.state!=="adopted"&&y?.release()}let L=()=>e.prepared?.state==="shown"&&!!y?.modal,d=e.client.identitySignal,I;try{I=await Promise.all([import("./screen-renderer-RDXKWHYE.js"),import("./paywall-PZ4BBEFG.js")]),e.signal?.throwIfAborted(),d?.throwIfAborted()}catch(n){throw o(),n}let[{mountScreenPreview:E},{showPaywall:M}]=I,ne=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&e.appManifestRelease?Yn({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;ne?.start();let w=t.ownerDocument,V=Mn(w),s=w.createElement("section"),q=w.createElement("div"),T=w.createElement("div"),W=w.createElement("div"),J=w.createElement("button");W.hidden=!0,J.type="button";let Q=w.createElement("p"),D=w.createElement("p"),j=w.createElement("button"),A=w.createElement("button"),F=w.createElement("button"),_=w.createElement("dialog"),pe,Re=!1;s.dataset.indianaFunnel="",s.dataset.longplayCloseOwner="sdk",s.setAttribute("aria-busy","false"),Q.setAttribute("role","status"),D.setAttribute("role","alert"),D.hidden=!0,j.type=A.type=F.type="button",T.append(j,J,Q,D,F,A),s.append(q,W,T),t.append(s);let se=Gn,te=dn(se),we="",G=(w.documentElement.lang||"").startsWith("zh"),S,i="",l;for(let n of[j,J,F,A])Ue(n,()=>te.focus);function a(){let n=G?"\u5173\u95ED":"Close";A.parentElement===_?(A.textContent="\xD7",A.setAttribute("aria-label",n),Un(A,se)):(A.textContent=n,A.removeAttribute("aria-label"),A.style.cssText=te.link+";margin-inline-start:auto")}function C(n){let r=n?.screen?.content.document.theme??se,p=JSON.stringify([r.primary,r.background,r.text,r.radius,r.font,A.parentElement===_]);if(p===we)return;we=p,se=r;let H=A.parentElement===_;te=dn(se,H),s.style.cssText=te.root+";min-width:0"+(H?";display:flex;flex-direction:column;min-height:100%":""),T.style.cssText=te.bar+(H?";margin-top:auto":""),T.hidden&&(T.style.display="none"),j.style.cssText=J.style.cssText=te.secondary,F.style.cssText=te.primary,Q.style.cssText=te.status,D.style.cssText=te.alert,a(),cn(j)}function c(){T.hidden=j.hidden&&J.hidden&&F.hidden&&D.hidden&&!Q.textContent&&(A.hidden||A.parentElement!==T),T.style.display=T.hidden?"none":"flex",S?.responsive&&l!==void 0&&S.setContentHeight(l+T.getBoundingClientRect().height)}C();let u=null,b=null,P=null,Z="",$="",le=!1,Ee="",en="",Me="",g=!1,ue=0,$e=!1,mn="",nn=null,tn=Promise.resolve(),wn=!e.client.view,z=R,Te,_e,xe="",Ge,de=!1,qe=null,ve=!1,Qe=()=>e.client.pendingCommand?.operation==="close",ce=null,Y=null,yn=Ln({document:w,run:async()=>{(!b?.observing||e.client.pendingCommand)&&await on()},delay:()=>{if(!(g||!P||!["running","waiting"].includes(P.status)&&!e.client.pendingCommand)&&!(b?.observing&&!e.client.pendingCommand))return P.pendingRequest||e.client.pendingCommand?1500:fn},hiddenDelay:()=>!g&&e.client.pendingCommand?15e3:void 0}),K=null;function rn(){return Y&&e.client.hasDurableJournal===!0&&K?.acknowledged===!0&&K.operationId===Y.operationId&&e.client.view?.id===K.runId&&e.client.view?.status==="closed"&&e.client.view.revision===K.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?Y:null}function hn(n){let r=n.run.paywall;if(K&&n.settlement?.requestId===K.requestId&&n.settlement.state==="settled"&&n.settlement.operationId===null&&n.run.id===K.runId&&n.run.status==="closed"&&!n.run.pendingRequest&&n.run.revision===K.revision+1&&n.run.nodeId===K.nodeId&&n.run.visit===K.visit&&r?.receiptId===K.receiptId&&r.selectionGeneration===K.selectionGeneration&&(r.quote?.operationId??null)===K.operationId&&(r.operation?.operationId??r.quote?.operationId??null)===K.operationId){let p=K.operationId===null&&r.selectionGeneration===0&&!r.quote&&!r.operation&&!r.purchaseRequestId,H=Ve({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect});(p||r.canReselect===!0&&H.type==="native")&&(K.acknowledged=!0)}}let De=null,Je=new Set,ye={},Ae=!1,fe=(n,r=null)=>{g||(De=r,Ae=!1,D.textContent=Qn(n,G),D.hidden=!1,F.hidden=e.client.pendingCommand===null,c(),Pe(e.onError,n))},gn=()=>{g||(De=null,D.textContent=jn(G),D.hidden=!1,F.hidden=!0,c())};function ke(){let n=e.client.view;if(!n)throw new m("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision}}let O=Kn({client:e.client,doc:w,holder:q,reviewHolder:W,mountScreenPreview:E,loadingOptions:e,get chrome(){return te},get stopped(){return g},get answers(){return ye},suspend(n){b?.setSuspended(n)},resetScreen(){Z="",$="",Ee=""},enqueue:he,fail:fe}),Le=Xn({client:e.client,expected:ke,fail:fe,get stopped(){return g},get reviewing(){return O.active},get key(){return Z},get busy(){return ue},get staleRead(){return nn}}),je=Zn({client:e.client,expected:ke,perform:Ne,onIntent:e.onCustomerDataIntent,get stopped(){return g},get busy(){return ue},get document(){return u?.document},get answers(){return ye}}),ze=n=>`${n.id}:${n.nodeId}:${n.visit}`,Se=n=>n&&(n.screen||n.paywall)?ze(n):"";function Ie(){let n=e.client.view;j.disabled=!O.active&&(ue>0||!!e.client.pendingCommand||!n?.canBack||n.stopped||!["running","waiting"].includes(n.status)||!Se(n)||$!==Se(n)),j.hidden=!O.active&&!n?.canBack,cn(j);let r=!!b&&!O.active;A.hidden=r&&!z?.active||Re&&!O.active,J.hidden=!e.client.review||!O.active&&!n?.canBack,r&&(Q.textContent=""),c()}async function vn(n){if(!n)return;let r=e.client.view;await n;let p=e.client.view;if(!r||!p||p.id!==r.id||p.nodeId!==r.nodeId||p.visit!==r.visit||p.stopped||!["running","waiting"].includes(p.status))throw new m("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Ne(n,r=!1,p){if(!((ue||ve||ce||Y)&&!r||g||O.active&&!r)){ue++,s.setAttribute("aria-busy","true"),D.hidden=!0,De=null,Ae=!1,Ie();try{if(r||await vn(Le.inFlight),g)return;let H=await n();g||await he(e.client.view??H.run)}catch(H){p?.(H)&&e.client.pendingCommand===null?gn():fe(H,e.client.pendingCommand?.requestId??null)}finally{ue=Math.max(0,ue-1),s.setAttribute("aria-busy",String(ue>0)),g||(F.hidden=e.client.pendingCommand===null,Ie())}}}function He(){yn.schedule()}async function on(){if(!(g||$e||ue)){if(O.active){await O.open(O.receipt);return}$e=!0;try{let n=e.client.pendingCommand;n&&e.client.settle&&await e.client.settle(n.requestId);let r=e.client.view,p=je.queries,H=await e.client.get(r?.screen&&Object.keys(p).length?{nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:p}:void 0);Ae&&!g&&(Ae=!1,D.hidden=!0,c()),!g&&p===je.queries&&await he(e.client.view??H.run)}catch(n){fe(n),Ae=!g}finally{$e=!1}}}function Be(n,r,p){if(z?.active){let ae=z;return ae.setDismissHandler(()=>In(ae)),ae}let H=Ze(t,e,"funnel",()=>In(H),xn);return z=H,H.start(n,r,p),H}function In(n){g||de||(de=!0,n.finish("dismissed"),be(),s.hidden=!0,e.client.view?Ce().finally(ie):ie())}function sn(){clearTimeout(Ge?.timeout),Ge=void 0}function be(){Re=!1,sn(),Te?.abort(),Te=void 0,u?.destroy(),u=null,b?.destroy(),b=null,_e?.(),_e=void 0,_.open&&_.close(),q.replaceChildren(),q.style.cssText="",l=void 0,Z="",$="",le=!1,Ee="",Me=""}function bn(){let n=w.defaultView;S?.responsive&&n&&u?.resizeViewport?.(n.innerHeight,n.innerWidth)}function an(){S?.destroy(),S=void 0,i=""}function We(n){let r=n.screen?.presentation;if(!r||r.type==="inline"){_.open&&_.close(),an(),A.parentElement!==T&&T.append(A),s.parentElement!==t&&t.append(s);for(let ae of["flex","display","flex-direction","justify-content"])q.style.removeProperty(ae);C(n),c();return}s.parentElement!==_&&(_.append(A,s),t.append(_)),q.style.flex="1 0 auto",q.style.display="flex",q.style.flexDirection="column",q.style.justifyContent="center",C(n);let p=n.screen.content.document,H=JSON.stringify([r,we]);if(H!==i){an(),i=H;let ae={sm:420,md:640,lg:900},ge="size"in r&&!r.backdrop?",0 0 0 100vmax #16142566":"";_.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${se.background};color:${se.text};`+(r.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ae[r.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${ge};`+(r.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),S=Hn(_,{presentation:r,theme:p.theme,pages:p.pages},bn),S.latch()}c(),_.setAttribute("aria-label",(pe?.screen===n.screen?.content.document.name?pe?.label:void 0)??u?.document?.name??n.screen?.content.document.name??"Funnel")}async function et(n){if(g||de||ve&&(Qe()||["running","waiting"].includes(n.status))||(P=n,De&&e.client.pendingCommand?.requestId!==De&&(D.hidden=!0,De=null),G=n.locale.startsWith("zh"),J.textContent=G?"\u56DE\u770B":"History",j.textContent=O.active?G?"\u8FD4\u56DE\u5F53\u524D":"Return to current":G?"\u8FD4\u56DE":"Back",a(),F.textContent=G?"\u91CD\u8BD5":"Retry",F.hidden=e.client.pendingCommand===null,Q.textContent=n.pendingRequest?G?"\u6B63\u5728\u5904\u7406":"Processing":n.instruction?.type==="wait"?G?"\u7B49\u5F85\u4E2D":"Waiting":"",Ie(),mn!==`${n.revision}:${n.visit}:${n.status}:${n.stopped}`&&(mn=`${n.revision}:${n.visit}:${n.status}:${n.stopped}`,Pe(e.onState,structuredClone(n))),g||de))return;if((!n.pendingRequest||ve&&n.status==="closed")&&["closed","ineligible","failed"].includes(n.status)){ie();return}if(n.stopped&&L()){ie();return}if(n.stopped||e.client.configurationReady===!1){O.stop(),o(),be(),z?.finish("skipped"),s.hidden=!0,He();return}if(s.hidden=!1,O.active){He();return}let r=Se(n),p=e.client.view;if(p&&p.revision>n.revision&&Se(p)!==r)return;let H=!n.instruction&&!n.pendingRequest&&n.nodeType==="screen"&&["running","waiting"].includes(n.status);r!==Z&&(Z&&z?.finish("dismissed"),be(),Z=r,ye={...n.answers},je.reset());let ae=ze(n);if(xe===ae){s.hidden=!0;return}if(H&&!r){s.hidden=!0;let U=e.prepared?.state==="shown"?null:Be(!0,n.locale);!g&&!de&&Ge?.key!==ae&&(sn(),Ge={key:ae,timeout:setTimeout(()=>{let h=e.client.view;if(g||!U?.active&&e.prepared?.state!=="shown"||!h||ze(h)!==ae)return;xe=ae;let B=new Error("Funnel screen preparation timed out");U?.finish("error",B),o(),be(),fe(B)},Fe)}),He();return}sn();let X=U=>{let h=e.client.view;return!g&&!de&&!qe&&!U.aborted&&e.client.configurationReady!==!1&&!!h&&!h.stopped&&!["closed","ineligible","failed"].includes(h.status)&&Se(h)===r},ge=(U,h)=>{X(h)&&(xe=r,z?.finish("error",U),be(),s.hidden=!0,fe(U))};if(r||((n.instruction&&n.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(n.status))&&o(),We(n),n.instruction?.type!=="event"&&n.instruction?.type!=="open_url"&&z?.finish("skipped")),n.screen){o();let U=n.screen.content;if(!u){let x=n.screen.presentation.type!=="inline",re=Be(x,n.locale);if(g||de)return;let ee=(Te=new AbortController).signal;We(n),_e=x?$n(_):Ke(s,t),u=E(q,{mode:"live",closeActions:Array.from(new Set([...e.closeActions??[],...U.document.actions.filter(f=>f.type==="event"&&f.close).map(f=>f.id)])),onAuthoredClose(f){X(ee)&&(Re=f,Ie())},rendererUrl:e.client.webViewUrl,title:U.document.name,...x?{hostPresentation:()=>S?.type??n.screen.presentation.type}:{},onResize:f=>{l=f,S?.responsive&&S.setContentHeight(f+T.getBoundingClientRect().height)},onAction(f,me={},ot={}){if(O.active||!X(ee)||$!==r)return;ye={...ye,...ot};let ln=n.screen?.inputs??[],Pn=Object.fromEntries(ln.filter(({variable:Oe})=>Object.hasOwn(ye,Oe)).map(({variable:Oe})=>[Oe,ye[Oe]]));if(zn(ln,Pn).length){gn();return}Ne(()=>e.client.submit({operation:"submit",...ke(),input:{type:"screen",output:f,answers:Pn,selection:me}}),!1,Oe=>Jn(Oe,ln))},onAnswers:f=>{O.active||!X(ee)||$!==r||(ye={...ye,...f})},onCustomerDataIntent:f=>{O.active||!X(ee)||$!==r||je.intent(f).catch(fe)},onEscape:()=>{!X(ee)||$!==r||O.active||ce||Y||Ce()},onError:f=>{let me=new Error(f);$===r?fe(me):ge(me,ee)},onRendered:f=>{if(!(!X(ee)||$===r))try{re.present(me=>{_e?.(),_e=void 0,f&&(pe={screen:U.document.name,label:f},_.setAttribute("aria-label",f)),x&&(_.showModal(),S?.responsive&&_.focus({preventScroll:!0}),!me&&e.loading!=="host"&&Vn(_,S?.type??n.screen.presentation.type,S?.responsive)),$=r,le=x,Ie()}),X(ee)&&Le.report(r)}catch(me){ge(me,ee)}}}),bn()}let h={capabilities:n.screen.capabilities,customerData:n.screen.customerData,parameters:n.parameters,serverInput:{bindings:n.screen.inputs,answers:ye,values:n.screen.values}},B=JSON.stringify([U,n.locale,h.parameters,n.screen.inputs,n.screen.values]);if(B!==Ee)u.update(U.document,n.locale,h),Ee=B,en=JSON.stringify(h.capabilities),Me=JSON.stringify(h.customerData);else{let x=JSON.stringify(h.capabilities);x!==en&&(u.updateCapabilities(h.capabilities),en=x),JSON.stringify(h.customerData)!==Me&&(u.updateCustomerData(h.customerData),Me=JSON.stringify(h.customerData))}let oe=u;if(oe)try{await(z?.wait(oe.ready)??oe.ready)}catch(x){Te&&ge(x,Te.signal)}}else if(n.paywall&&!b){let U=n.paywall.resolution,h="document"in U?U.document:null,B=y,oe=null,x=(Te=new AbortController).signal,re={loading:"host",signal:x,canInteract:()=>X(x)&&!O.active&&!ce&&!Y,beforeAction:async()=>{ue++;try{await vn(Le.settled()),D.hidden=!0,De=null,Ae=!1,c()}finally{ue=Math.max(0,ue-1)}},start:()=>pn(e.client),onObservationChange:He,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,resumeCheckout:e.resumeCheckout,allowNewPurchase:e.allowNewPurchase,checkoutNavigation:e.checkoutNavigation,terminateCheckout:e.terminateCheckout,confirmOnHostedCheckout:e.confirmOnHostedCheckout,resolveOfferId:e.resolveOfferId,resolveSubscriptionChange:e.resolveSubscriptionChange,claimCoupon:e.claimCoupon,onEvent:e.onEvent,onOpenUrl:f=>e.onOpenUrl?e.onOpenUrl({receiptId:n.paywall.receiptId,url:f,openIn:"same_window"}):w.defaultView?.location.assign(f),onAction:async f=>{if(O.active)return;let me=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:e.client.view?.revision??n.revision,input:{type:"screen",output:f,answers:{}}});await he(e.client.view??me.run)},onError:f=>{$===r?fe(f):ge(f,x)}},ee={quoteError:f=>Pe(e.onError,f),present(f){X(x)&&(oe?.present(()=>{f(),$=r,le=!!q.querySelector("dialog[open]"),Ie()}),X(x)&&Le.report(r))},async dismiss(){if(!(g||x.aborted||O.active||ce||Y||!ve&&!X(x))){if(ve=!0,(e.resumeCheckout||e.terminateCheckout)&&rt()){P=e.client.view,ie();return}await Ce()}}};if(B){let f=await B.adopt(n,{options:re,handoff:ee,start:()=>pn(e.client)});f&&X(x)&&!g?(We(n),b=f,z?.active&&z.present(()=>{}),$=r,le=B.modal,Ie(),Le.report(r),O.active&&b.setSuspended(!0)):(f?.destroy(),o())}if(g||de)return;if(!b){if(oe=Be(!0,n.locale,h),g||de)return;We(n);let f=await M(q,re,ee).catch(me=>(ge(me,x),null));!X(x)&&!(ve&&!g&&!x.aborted)?f?.host?.destroy():f&&(b=f.host,b?.setSuspended(O.active))}}if(g||de)return;Ie();let k=n.instruction;if(k&&(k.type==="open_url"||k.type==="event")&&!Je.has(k.receiptId)){let U=w.createElement("button");U.type="button",U.style.cssText=te.primary,Ue(U,()=>te.focus),q.style.cssText=te.stage,U.textContent=k.type==="open_url"?`${G?"\u524D\u5F80":"Continue to"} ${new URL(k.url).host}`:G?"\u7EE7\u7EED":"Continue",U.onclick=()=>{let h=ke(),B=k.type==="open_url"&&!e.onOpenUrl&&k.openIn==="new_window"?nt(k.url):null;Ne(async()=>{let oe="success";if(k.type==="open_url")if(e.onOpenUrl)try{oe=await e.onOpenUrl({receiptId:k.receiptId,url:k.url,openIn:k.openIn})===!1?"failed":"opened"}catch(re){Pe(e.onError,re),oe="failed"}else oe=k.openIn==="new_window"&&!B?"failed":"opened";if(k.type==="event"){if(!e.onEvent)throw new m("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(k.event)}if(g||e.client.view?.nodeId!==h.nodeId||e.client.view.visit!==h.visit)throw new m("PRECONDITION_FAILED","The client action visit changed");let x=await e.client.submit({operation:"submit",...h,input:{type:"client_action",receiptId:k.receiptId,outcome:oe}});return Je.add(k.receiptId),k.type==="open_url"&&!e.onOpenUrl&&k.openIn==="same_window"&&w.defaultView?.location.assign(k.url),x})},z?.active?z.present(()=>q.replaceChildren(U)):q.replaceChildren(U)}!n.pendingRequest&&n.status==="completed"&&!Je.has(`complete:${n.id}`)&&(Je.add(`complete:${n.id}`),Pe(e.onComplete,structuredClone(n))),He()}function nt(n){let r=w.defaultView?.open(n,"_blank")??null;return r&&(r.opener=null),r}function he(n){return Ie(),tn=tn.catch(()=>{}).then(async()=>{try{await et(n)}catch(r){throw z?.active&&(xe=ze(n),z.finish("error",r),be(),s.hidden=!0),r}}),tn}let tt=e.client.subscribe(n=>{if(!wn){if(n.stopped&&(le||L())&&!ve){P=n,ie();return}!ve&&(n.stopped||e.client.configurationReady===!1||Z&&$!==Z&&(Se(n)!==Z||["closed","ineligible","failed"].includes(n.status)))&&(be(),z?.finish("dismissed"),s.hidden=!0),he(n).catch(fe)}}),it=e.client.subscribeError?.(fe);function rt(){let n=e.client.view,r=n?.paywall;return!!r?.operation&&!!n&&["running","waiting"].includes(n.status)&&Tn(Ve({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect}))}function Ce(n){if(qe)return qe;if(g||!n&&(ce||Y))return Promise.resolve();let r=!n&&Qe();return!r&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(P=e.client.view,ie(),Promise.resolve()):(qe=Ne(async()=>{let p=r?await e.client.retry():await e.client.submit({operation:"close",...n??ke()});return n&&hn(p),p},!0).then(()=>{let p=e.client.view;p?.status==="closed"&&!Qe()&&(P=p,ie())}).finally(()=>{qe=null}),qe)}function ie(){ne?.destroy(),!g&&(g=!0,N(),o(),e.signal?.removeEventListener("abort",ie),d?.removeEventListener("abort",ie),z?.finish("dismissed"),yn.destroy(),tt(),it?.(),be(),an(),O.stop(),_.remove(),s.remove(),V(),Pe(e.onDismiss,P?structuredClone(P):null))}j.onclick=()=>{if(!j.disabled){if(O.active){O.exit();return}Ne(()=>e.client.submit({operation:"back",...ke()}))}},J.onclick=()=>{O.open()},A.onclick=()=>{z?.active?z.dismiss():ce||Ce()},F.onclick=()=>{Qe()?Ce():Ne(()=>e.client.retry())},_.addEventListener("cancel",n=>{n.preventDefault(),z?.active?z.dismiss():ce||Ce()}),e.signal?.addEventListener("abort",ie,{once:!0}),d?.addEventListener("abort",ie,{once:!0});let Ye=!1;y&&(N=y.onClose(()=>{g||de||(de=!0,z?.finish("dismissed"),be(),s.hidden=!0,e.client.view?Ce().finally(ie):Ye=!0)}));let Cn={destroy:ie,refresh:on,get recovery(){let n=rn();if(n)return n;if(!g&&!ue&&!ve&&!ce&&b){let r=b.recovery;if(r.type!=="native")return r}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??Y?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(ce)return ce;let n=rn();if(n)return Promise.resolve(n);let r=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??Y?.operationId??null,p=()=>({type:"recover",operationId:r,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let k=b?.recovery;return Promise.resolve(k&&k.type!=="native"&&k.type!=="cancel"?k:p())}let H=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(k=>k.operation==="close");if(g&&!(H||Y&&e.client.view?.status==="closed")||ue||$e||qe||O.active||!b&&!Y&&!H)return Promise.resolve(p());let ae=b,X=(async()=>{try{if(!Y&&H){let h=await e.client.retry();return await he(e.client.view??h.run),p()}if(!Y){let h=await ae.prepareFallback();if(h.type!=="native")return h;if(e.client.hasDurableJournal!==!0)return p();Y=h}let k=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(k.length){let h=k.find(oe=>oe.operation==="close");if(!h||!K||h.requestId!==K.requestId)return p();let B=await e.client.retry();hn(B),await he(e.client.view??B.run)}else{let h=e.client.view,B=h?.paywall;if(!h||!B||B.selectionGeneration===void 0||(B.quote?.operationId??null)!==Y.operationId||Y.operationId!==null&&B.canReselect!==!0)return p();let oe=B.selectionGeneration,x=await e.client.get();await he(e.client.view??x.run);let re=e.client.view,ee=re?.paywall;if(!re||!ee||!["running","waiting"].includes(re.status)||re.stopped||re.id!==h.id||re.nodeId!==h.nodeId||re.visit!==h.visit||ee.receiptId!==B.receiptId||ee.selectionGeneration!==oe||(ee.quote?.operationId??null)!==Y.operationId||Y.operationId!==null&&ee.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return p();let f=ke();K={runId:re.id,operationId:Y.operationId,revision:f.revision,requestId:f.requestId,nodeId:re.nodeId,visit:re.visit,receiptId:ee.receiptId,selectionGeneration:oe,acknowledged:!1},await Ce(f)}let U=rn();return U?(ie(),U):p()}catch(k){return fe(k),p()}})();ce=X;let ge=()=>{ce===X&&(ce=null)};return X.then(ge,ge),X},review:O.open,exitReview:O.exit,get unappliedDrafts(){return O.drafts}};try{let n=e.client.view;if(n)((e.client.viewAgeMs??fn)>=fn||n.instruction?.type==="evaluate_segment")&&(nn=on().finally(()=>{nn=null})),await he(n);else{if(s.hidden=!0,g)throw new DOMException("Presentation cancelled","AbortError");let r=Ye||e.prepared?.state==="shown"?null:Be(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(g||de&&!Ye)throw new DOMException("Presentation cancelled","AbortError");let p=e.client.get(),H=await(r?r.wait(p,Fe):lt(p,Fe));if(wn=!1,Ye)return g||await Ce().finally(ie),Cn;await he(e.client.view??H.run)}}catch(n){throw z?.finish("error",n),ie(),n}return Cn}function lt(t,v){let R;return Promise.race([t,new Promise((e,y)=>{R=setTimeout(()=>y(new Error("Presentation data timed out")),v)})]).finally(()=>clearTimeout(R))}function Bt(t,v,R){return at(t,v,R)}export{at as a,Bt as b};
@@ -1 +1 @@
1
- import{g as p}from"./chunk-S4P4UUUF.js";import{b as r}from"./chunk-2ULWP26K.js";import{a as i,b as s}from"./chunk-PBBREFS5.js";var b=r.string().regex(/^[a-f0-9]{64}$/),j=r.strictObject({scope:r.strictObject({projectId:r.uuid(),environmentId:r.uuid(),environment:p}),customerId:r.uuid()});function l(u){let n=e=>{if(Array.isArray(e))return`[${e.map(n).join(",")}]`;if(e!==null&&typeof e=="object"){let c=Object.getPrototypeOf(e);if(c!==Object.prototype&&c!==null)throw new TypeError("Commerce protocol digests require JSON objects");return`{${Object.entries(e).filter(([,o])=>o!==void 0).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>`${JSON.stringify(o)}:${n(t)}`).join(",")}}`}if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);throw new TypeError("Commerce protocol digests require JSON values")};return i(s(new TextEncoder().encode(n(u))))}export{b as a,j as b,l as c};
1
+ import{g as p}from"./chunk-6XRXHFM6.js";import{b as r}from"./chunk-GPJF3T43.js";import{a as i,b as s}from"./chunk-WPFTSHP2.js";var b=r.string().regex(/^[a-f0-9]{64}$/),j=r.strictObject({scope:r.strictObject({projectId:r.uuid(),environmentId:r.uuid(),environment:p}),customerId:r.uuid()});function l(u){let n=e=>{if(Array.isArray(e))return`[${e.map(n).join(",")}]`;if(e!==null&&typeof e=="object"){let c=Object.getPrototypeOf(e);if(c!==Object.prototype&&c!==null)throw new TypeError("Commerce protocol digests require JSON objects");return`{${Object.entries(e).filter(([,o])=>o!==void 0).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>`${JSON.stringify(o)}:${n(t)}`).join(",")}}`}if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);throw new TypeError("Commerce protocol digests require JSON values")};return i(s(new TextEncoder().encode(n(u))))}export{b as a,j as b,l as c};