@tinkerlandai/longplay-sdk 0.10.97 → 0.10.98
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.
- package/README.md +20 -6
- package/README.zh-CN.md +7 -3
- package/dist/check-response-RG4OLOMY.js +1 -0
- package/dist/{chunk-F4AIEI5N.js → chunk-2VAQ56S2.js} +1 -1
- package/dist/{chunk-AO56DGNZ.js → chunk-2VK44BOH.js} +1 -1
- package/dist/{chunk-Y3W5G4BF.js → chunk-2XX7L5VK.js} +1 -1
- package/dist/{chunk-UGATOG2T.js → chunk-355B3KPL.js} +1 -1
- package/dist/{chunk-6XRQR43F.js → chunk-3I6OZU2J.js} +1 -1
- package/dist/{chunk-7ZAM4YRK.js → chunk-45PGU2HW.js} +1 -1
- package/dist/{chunk-BT7IC765.js → chunk-4AJTBYKE.js} +1 -1
- package/dist/{chunk-KCG7GZXO.js → chunk-6HOH7LOK.js} +1 -1
- package/dist/{chunk-EQUVI5QU.js → chunk-6RQJNL7B.js} +1 -1
- package/dist/{chunk-PBHOJKKG.js → chunk-6WOVMXJE.js} +1 -1
- package/dist/{chunk-CKMSSBJM.js → chunk-AHXR2QO2.js} +1 -1
- package/dist/{chunk-C4KLIT5L.js → chunk-CKUMSWUN.js} +1 -1
- package/dist/{chunk-LQV7EC5H.js → chunk-CNV22MDH.js} +1 -1
- package/dist/{chunk-XWVK4SJA.js → chunk-CV67DHPD.js} +1 -1
- package/dist/{chunk-67WFVDTV.js → chunk-DCKPSRMT.js} +1 -1
- package/dist/chunk-DS2AOHZY.js +1 -0
- package/dist/{chunk-2OBXRQMW.js → chunk-EEJPKNED.js} +1 -1
- package/dist/{chunk-Y6KA56V2.js → chunk-F467W5SE.js} +1 -1
- package/dist/{chunk-LFR2LWYC.js → chunk-FEZWUYEK.js} +1 -1
- package/dist/{chunk-WLO2GDRF.js → chunk-GGWIHM2N.js} +1 -1
- package/dist/{chunk-HKLAHQKF.js → chunk-GJTXTEZG.js} +1 -1
- package/dist/{chunk-A5WUQLAO.js → chunk-GRY5G7X3.js} +1 -1
- package/dist/{chunk-7CZEXBQY.js → chunk-HHKX7P4Q.js} +1 -1
- package/dist/{chunk-FYUMVOCV.js → chunk-HN46A5SD.js} +1 -1
- package/dist/chunk-IESVRPTI.js +1 -0
- package/dist/{chunk-XLGNBPGF.js → chunk-JHVEOUIF.js} +1 -1
- package/dist/{chunk-7QPCNDIY.js → chunk-JSRB6RDU.js} +1 -1
- package/dist/{chunk-JLKODCRG.js → chunk-JYE7LLEH.js} +2 -2
- package/dist/{chunk-MOIVJERE.js → chunk-JZYZHMCT.js} +1 -1
- package/dist/{chunk-BANN2HQH.js → chunk-L42BXSWX.js} +1 -1
- package/dist/{chunk-VXNN3RV3.js → chunk-LRJJNIUQ.js} +1 -1
- package/dist/{chunk-KCUE2VFJ.js → chunk-O33ABKTL.js} +1 -1
- package/dist/{chunk-6VVQWTHV.js → chunk-OC3IODWG.js} +1 -1
- package/dist/{chunk-33EKLIMB.js → chunk-OI4KRTEM.js} +1 -1
- package/dist/{chunk-3532HSBP.js → chunk-OILQZX5V.js} +1 -1
- package/dist/{chunk-CO6HDNOC.js → chunk-OJ6CPUN4.js} +1 -1
- package/dist/{chunk-BQFIJCBA.js → chunk-ORQ5RR4J.js} +1 -1
- package/dist/chunk-PVNZFREQ.js +1 -0
- package/dist/{chunk-Y55OBV7D.js → chunk-Q7TQHM5N.js} +1 -1
- package/dist/{chunk-BOT6ZDLK.js → chunk-QNJPFX5F.js} +1 -1
- package/dist/{chunk-CHRNCOXJ.js → chunk-RXHGIDNM.js} +1 -1
- package/dist/{chunk-ME6QTD5Y.js → chunk-SEBMCCXY.js} +1 -1
- package/dist/{chunk-55B6CYG6.js → chunk-SK73TK7R.js} +1 -1
- package/dist/{chunk-SX7U2ONB.js → chunk-UFO6XHFZ.js} +1 -1
- package/dist/{chunk-DUS5V65Z.js → chunk-VCRDA5R3.js} +1 -1
- package/dist/{chunk-KX67ZM7H.js → chunk-VID3LHBO.js} +1 -1
- package/dist/{chunk-FYMVNLQN.js → chunk-VPT5MFDG.js} +2 -2
- package/dist/{chunk-PUDTOCQF.js → chunk-WEORY7PV.js} +1 -1
- package/dist/{chunk-S2S4ROGY.js → chunk-XF746ACV.js} +1 -1
- package/dist/{chunk-XAPMQRVJ.js → chunk-YRVK3UDS.js} +1 -1
- package/dist/{chunk-FPJ3FE26.js → chunk-YTBCR2KU.js} +1 -1
- package/dist/{content-IDQO7TKS.js → content-N7THX3DD.js} +1 -1
- package/dist/funnel-host-purchase-FQLL3MCD.js +1 -0
- package/dist/funnel-host-purchase-entry-ONAAZZV6.js +1 -0
- package/dist/funnel-host-recovery-paywall-WYK3N5WY.js +1 -0
- package/dist/{funnel-paywall-copies-LPOTYSTS.js → funnel-paywall-copies-4K6FMGCP.js} +1 -1
- package/dist/{funnel-paywall-pins-source-ZK2DZWY3.js → funnel-paywall-pins-source-MJIRVW5F.js} +1 -1
- package/dist/funnel-paywall-prerender-WEB5AEVM.js +1 -0
- package/dist/funnel-route-prediction-YOS2OMCA.js +1 -0
- package/dist/funnel-route-source-WZ35NDNG.js +1 -0
- package/dist/funnel-runtime-host-TYQ4CQ7T.js +1 -0
- package/dist/index.d.ts +13 -17
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-DPNCMPVN.js +1 -0
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-NLZ5ENTM.js +1 -0
- package/dist/page.js +1 -1
- package/dist/paywall-UGS2LKLH.js +1 -0
- package/dist/paywall-content-Y4SCPZRG.js +1 -0
- package/dist/paywall-session-J2VVRCZF.js +1 -0
- package/dist/popup.d.ts +2 -2
- package/dist/popup.js +1 -1
- package/dist/{presentation-loading-CU4c-koG.d.ts → presentation-loading-EAIPC1d3.d.ts} +2 -2
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-4VYPU7X6.js +1 -0
- package/dist/server.js +1 -1
- package/dist/{visual-dom-KUABNJV6.js → visual-dom-5LUN4AHO.js} +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/check-response-XGOTG3KL.js +0 -1
- package/dist/chunk-7DQV2EUW.js +0 -1
- package/dist/chunk-GFH7OK3S.js +0 -1
- package/dist/chunk-JYTUTIBB.js +0 -1
- package/dist/funnel-host-purchase-7IYZRPYA.js +0 -1
- package/dist/funnel-host-purchase-entry-FFZUEX4Q.js +0 -1
- package/dist/funnel-host-recovery-paywall-DGCR4IBQ.js +0 -1
- package/dist/funnel-paywall-prerender-QHEGZSPT.js +0 -1
- package/dist/funnel-route-prediction-Q4HMRAVQ.js +0 -1
- package/dist/funnel-route-source-HYWJWEM3.js +0 -1
- package/dist/funnel-runtime-host-CFDI4AWM.js +0 -1
- package/dist/merchant-bridge-contracts-OIYML3DE.js +0 -1
- package/dist/operation-contracts-YJM6772C.js +0 -1
- package/dist/paywall-2Z3FUN2M.js +0 -1
- package/dist/paywall-content-JXWPOE3Y.js +0 -1
- package/dist/paywall-session-RNEEPYPG.js +0 -1
- package/dist/screen-renderer-HJOKBOZH.js +0 -1
- /package/dist/{chunk-FRK6322O.js → chunk-CILM5XMH.js} +0 -0
- /package/dist/{chunk-JLKODCRG.js.LEGAL.txt → chunk-JYE7LLEH.js.LEGAL.txt} +0 -0
- /package/dist/{chunk-KV5MZ4NI.js → chunk-OJM6ORHE.js} +0 -0
- /package/dist/{chunk-W22ESUYY.js → chunk-TDOPU2RH.js} +0 -0
- /package/dist/{chunk-FYMVNLQN.js.LEGAL.txt → chunk-VPT5MFDG.js.LEGAL.txt} +0 -0
package/README.md
CHANGED
|
@@ -393,15 +393,18 @@ button.onclick = () => {
|
|
|
393
393
|
#### Prepare a merchant purchase entry
|
|
394
394
|
|
|
395
395
|
`createFunnelPurchaseEntry(container, options)` prepares a Paywall while a merchant entry is
|
|
396
|
-
available. Register it after the container is attached. Pass the Funnel, commerce context
|
|
397
|
-
locale
|
|
398
|
-
|
|
399
|
-
|
|
396
|
+
available. Register it after the container is attached. Pass the Funnel, commerce context
|
|
397
|
+
and locale. A Paywall ID or Version ID is optional. Without either, published configuration
|
|
398
|
+
can predict the first Paywall once the Start is known. Without a known Paywall or configuration,
|
|
399
|
+
the SDK warms the renderer and uses the Run's first screen. The entry reuses a matching device
|
|
400
|
+
copy and prepares again after dismissal. At the click pass the actual Start to
|
|
400
401
|
`entry.open({ start })`. The purchase host checks recovery and matches the Start before it
|
|
401
402
|
adopts the copy. Call `entry.destroy()` when the entry is removed or its context changes.
|
|
402
403
|
Ending the client's identity also releases the entry.
|
|
403
|
-
The entry
|
|
404
|
-
|
|
404
|
+
The entry starts replacing its copy before the copy's price age runs out. A transient
|
|
405
|
+
preparation failure gets one retry; the current copy remains usable within its own age.
|
|
406
|
+
Entries using the same purchase client join an already open presentation. Pass
|
|
407
|
+
`onEvent` to observe an opening: `copy`
|
|
405
408
|
(state, reason, whether it came from the device copy), `renewed`, `open` (what the click found
|
|
406
409
|
and whether it was used) and `end`, each stamped with `performance.now()`.
|
|
407
410
|
The next copy is painted as soon as the Run of an opening is on screen, so a click right after
|
|
@@ -412,6 +415,17 @@ the close reveals it. `result` reports once per opening whether the Customer saw
|
|
|
412
415
|
merchant's checks have not settled: the copy is shown first and confirmed after. It is taken
|
|
413
416
|
away again when the checks refuse the Start or settle on a Start for another scope.
|
|
414
417
|
|
|
418
|
+
If the opening is still waiting after the loading delay, the default is a cancellable,
|
|
419
|
+
non-modal notice. The page stays usable until the first screen is ready. Pass
|
|
420
|
+
`loading: "sdk"` to use the SDK's layout placeholder or `loading: "host"` to provide
|
|
421
|
+
your own. A visible preview is separate from purchase readiness. Register the normal
|
|
422
|
+
merchant purchase handler on `entry.open()` so the Run handles its activation.
|
|
423
|
+
|
|
424
|
+
With published configuration, an observed change to this Funnel or Paywall retires its
|
|
425
|
+
unused preview and keeps the next device copy under the new selection. A paused Funnel
|
|
426
|
+
or expired observed selection opens through the Run without that preview. With a fixed
|
|
427
|
+
Paywall Version, re-register the entry when a new Funnel Version requires a different hint.
|
|
428
|
+
|
|
415
429
|
#### Predict the first screen
|
|
416
430
|
|
|
417
431
|
`predictFunnelStart(configuration, { funnelId, customerId, parameters })` says which first screen a Run of the Funnel would present for this Customer and these Start parameters: `paywall` (with `paywallId`, `paywallVersionId` and `presentation`), `screen` (a Funnel-owned `page`, `popup` or `onboarding`), `external_page`, `end` (with its `outcome`, such as `ineligible`), `unknown` (a step only the server can decide) or `unavailable` (no published route, a paused Funnel, unreadable configuration). It is computed on the device from the Funnel Version's routing program and records nothing: no Run, exposure, Sticky assignment or Coupon. `customerId` is the session's Customer ID, which Splits bucket by. The Run started at the click still decides; a Customer with an earlier Sticky assignment, or a Funnel or Experiment changed since the last configuration refresh, can be routed differently, and the pre-rendered copy is then released as before. `predictedPaywallLoadingDocument(configuration, prediction)` returns the predicted Paywall's published design for a loading state.
|
package/README.zh-CN.md
CHANGED
|
@@ -234,17 +234,21 @@ SDK 在首次派发前保存原 Start 请求 ID 和完整输入;同一未决
|
|
|
234
234
|
|
|
235
235
|
#### 注册购买入口
|
|
236
236
|
|
|
237
|
-
容器挂载后调用 `createFunnelPurchaseEntry(container, options)`。传入 Funnel
|
|
238
|
-
SDK
|
|
237
|
+
容器挂载后调用 `createFunnelPurchaseEntry(container, options)`。传入 Funnel、购买场景和语言。Paywall ID 或版本 ID 可选。省略时,如果提供了发布配置,SDK 可在 Start 确定后预测首个 Paywall。缺少确定的 Paywall 和发布配置时,SDK 预加载渲染代码,打开时显示正式 Run 的首屏。
|
|
238
|
+
SDK 在入口可用时准备套餐墙,复用匹配的设备副本,并在关闭后为下一次打开做准备。
|
|
239
239
|
实际点击时把这次的 Start 交给 `entry.open({ start })`,由购买宿主核对原订单并接管匹配的副本。
|
|
240
240
|
移除入口或切换场景时调用 `entry.destroy()`。当前身份结束时,SDK 也会释放该入口。
|
|
241
|
-
|
|
241
|
+
副本到期前,入口开始准备下一份。若准备暂时失败,SDK 重试一次,旧副本在自身有效期内仍可使用。共用同一个购买 client 的入口会复用已经打开的展示。
|
|
242
242
|
传入 `onEvent` 可以观察入口:`copy`(状态、原因、是否来自设备副本)、`renewed`、`open`(点击时找到了什么、是否用上)和 `end`,每条都带 `performance.now()` 时间。
|
|
243
243
|
打开的 Run 一显示,入口就在它后面画好下一份副本,所以关闭后立刻再点也能直接显示。
|
|
244
244
|
`result` 每次打开报告一次:用户是否看到了副本(`revealed`)、Run 是否接管了它(`adopted`)。命中率按 `result.adopted` 统计,`open.used` 只表示这次打开尝试了副本。
|
|
245
245
|
`open()` 在点击当下就显示已就绪的副本,即使 `start` 还是一个等待商户检查的 Promise:先显示,后确认。
|
|
246
246
|
检查拒绝了 Start,或最终的 Start 属于别的范围时,副本会被收回。
|
|
247
247
|
|
|
248
|
+
等待超过加载延迟时,SDK 默认显示可取消的非模态提示,首屏就绪前原页面仍可操作。传入 `loading: "sdk"` 可使用 SDK 的布局占位,传入 `loading: "host"` 可由宿主管理提示。预览可见和购买就绪是两个时刻。将正常的商户购买回调传给 `entry.open()`,由正式 Run 管理其触发时机。
|
|
249
|
+
|
|
250
|
+
传入发布配置后,SDK 观察到该 Funnel 或 Paywall 的发布选择变化时,会释放尚未使用的预览,并按新发布选择保存设备副本。已观察到的选择过期或 Funnel 暂停时,打开流程继续交给正式 Run。若入口使用固定的 Paywall Version 提示,新的 Funnel Version 需要不同提示时请重新注册入口。
|
|
251
|
+
|
|
248
252
|
#### 预渲染首个 Paywall
|
|
249
253
|
|
|
250
254
|
`commerce.intent: "subscription_change"` 的购买页只需至少一个套餐可用即可预渲染;当前订阅及其他不可用选项保留服务端的禁用状态。没有可升级选项时不展示预渲染副本。普通新购仍要求所有套餐可用,购买操作始终等待 Run 自己的会话。
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b}from"./chunk-WEORY7PV.js";import"./chunk-VCRDA5R3.js";import"./chunk-QNJPFX5F.js";import"./chunk-355B3KPL.js";import"./chunk-FEZWUYEK.js";import"./chunk-TDOPU2RH.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as validateEntitlementCheck,b as validateResourceCheck};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as s}from"./chunk-
|
|
1
|
+
import{a as s}from"./chunk-355B3KPL.js";var p=new WeakMap;function P(i,n){p.set(i,n)}function v(i){let n,l=!1,d=new AbortController,u=e=>(i.client.pendingCommands??(i.client.pendingCommand?[i.client.pendingCommand]:[])).some(r=>r.requestId===e.command.requestId),m=()=>i.document.defaultView?.navigator.onLine!==!1,C=e=>new Promise((r,t)=>{let o=()=>{clearTimeout(c),d.signal.removeEventListener("abort",a),r()},a=()=>{clearTimeout(c),d.signal.removeEventListener("abort",a),t(new s("IDENTITY_CHANGED","Closing presentation was released"))},c=setTimeout(o,e);d.signal.addEventListener("abort",a,{once:!0}),d.signal.aborted&&a()});async function b(e,r){try{let t;for(let o=0;o<3;o++){if(l)throw new s("IDENTITY_CHANGED","Closing presentation was released");if(o&&(!m()||(await C(o===1?500:2e3),!m())))break;try{let a=p.get(i.client),c=r&&o===0?await(a?a(e.command,()=>{l||n!==e||(e.retained=!0,i.conceal())}):i.client.submit(e.command)):await i.client.retry();if(l)return c;if(!e.retained||!u(e))return n===e&&(n=void 0),await i.receive(c),c;t=new s("COMMAND_PENDING","Closing is still being confirmed. Retry the original request.")}catch(a){if(t=a,!e.retained||!u(e))throw a}}throw t??new s("COMMAND_PENDING","Closing is still being confirmed. Retry the original request.")}catch(t){throw!u(e)&&n===e&&(n=void 0),!l&&e.retained&&i.failed(t),t}}function f(e,r){if(e.flight)return e.flight;let t=b(e,r);e.flight=t;let o=()=>{e.flight===t&&(e.flight=void 0)};return t.then(o,o),t}function g(){if(l)return Promise.reject(new s("IDENTITY_CHANGED","Closing presentation was released"));let e=n;return!e||!u(e)?Promise.reject(new s("INVALID_REQUEST","No closing command is pending")):(!e.flight&&e.retained&&i.conceal(),f(e,!1))}let w=()=>{!l&&n?.retained&&!n.flight&&u(n)&&g().catch(()=>{})};return i.document.defaultView?.addEventListener("online",w),{get pending(){return n?.retained===!0},observe(){n&&!n.flight&&!u(n)&&(n=void 0)},submit(e){if(e.operation==="submit"&&e.input.type!=="screen")return Promise.reject(new s("INVALID_REQUEST","Presentation closure cannot execute a purchase"));if(l)return Promise.reject(new s("IDENTITY_CHANGED","Closing presentation was released"));if(n&&u(n)){let t=n.command;return t.operation===e.operation&&t.nodeId===e.nodeId&&t.visit===e.visit&&(t.operation==="close"||t.operation==="submit"&&e.operation==="submit"&&JSON.stringify(t.input)===JSON.stringify(e.input))?f(n,!n.retained):Promise.reject(new s("COMMAND_PENDING","Recover the original closing command"))}let r={command:e,retained:!1};return n=r,f(r,!0)},retry:g,destroy(){l=!0,d.abort(),i.document.defaultView?.removeEventListener("online",w)}}}export{P as a,v as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var s={name:"@tinkerlandai/longplay-sdk",version:"0.10.
|
|
1
|
+
var s={name:"@tinkerlandai/longplay-sdk",version:"0.10.98",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md","native-funnel-host.NOTICES.txt"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};export{s as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as K,b as U,d as D,v as _}from"./chunk-FYUMVOCV.js";import{a as z,c as F}from"./chunk-DUS5V65Z.js";import{d as $}from"./chunk-A5WUQLAO.js";import{i as C,j as m,l as O,m as g}from"./chunk-LFR2LWYC.js";import{b as e}from"./chunk-W22ESUYY.js";var I=m.refine(t=>/[1-9]/.test(t),"Quantity must be positive"),j=e.string().min(1).max(120),R=e.enum(["cap","overflow"]),p=(t,n)=>{let[i,u=""]=t.split(".");if(i===void 0||i==="")throw new Error("Invalid decimal value");return BigInt(i)*10n**BigInt(n)+BigInt(u.padEnd(n,"0"))},A=t=>{try{return t()}catch{return!1}},le=e.discriminatedUnion("operation",[e.object({operation:e.literal("quote"),overageBehavior:R.optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g}).strict(),e.object({operation:e.literal("consume"),overageBehavior:R.optional(),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:m,properties:g,idempotencyKey:j}).strict(),e.object({operation:e.literal("reserve"),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g,idempotencyKey:j,expiresInSeconds:e.number().int().min(1).max(86400)}).strict(),e.object({operation:e.literal("confirm"),operationId:e.uuid(),quantity:I,properties:g.optional(),idempotencyKey:j}).strict(),e.object({operation:e.literal("refund"),operationId:e.uuid(),quantity:I,idempotencyKey:j}).strict(),e.object({operation:e.literal("release"),operationId:e.uuid(),idempotencyKey:j}).strict()]),J=e.object({internal_credit_feature_id:e.uuid().nullable(),internal_metered_feature_id:e.uuid(),dimension:e.string().min(1).max(64),counterKey:e.string().min(1).max(240),cycleStart:e.iso.datetime({offset:!0}),unitCost:m,units:I,amount:C,tier:e.number().int().min(1).max(12).nullable()}).strict(),Q=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function N(t,n){let i=t.reduce((u,a)=>u+p(a.units,12),0n)-p(n,12);return t.some(u=>u.funding==="balance")?i>=-100n&&i<=100n:i===0n}var v=e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q.refine(t=>/[1-9]/.test(t)),amount:C}),e.strictObject({funding:e.literal("unbilled"),units:Q.refine(t=>/[1-9]/.test(t))}),e.object({funding:e.literal("prepaid"),sourceId:e.uuid(),units:I,amount:C,pricing:e.array(J).min(1).max(12)}).strict().refine(t=>A(()=>t.pricing.reduce((n,i)=>n+p(i.units,6),0n)===p(t.units,6)&&t.pricing.reduce((n,i)=>n+p(i.amount,12),0n)===p(t.amount,12)&&t.pricing.every(n=>p(n.unitCost,6)*p(n.units,6)===p(n.amount,12))),"Frozen pricing must conserve allocated units and amounts"),e.object({funding:e.literal("postpaid"),invoiceLineId:e.uuid().nullable(),units:I,authorizationId:e.uuid()}).strict()]),B=e.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),de=e.object({allowed:e.boolean(),internal_feature_id:e.uuid(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),reason:B.nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.allowed?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"A quote must conserve its accepted units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0&&/[1-9]/.test(t.quantity):t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Explicit overage behavior must retain the requested quantity"),me=e.object({id:e.uuid(),internal_feature_id:e.uuid(),kind:e.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),createdAt:e.iso.datetime({offset:!0}),reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:e.iso.datetime({offset:!0}).nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.accepted?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"An operation must conserve its requested units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0:t.kind==="consume"&&t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(t=>/[1-9]/.test(t.quantity)||t.kind==="consume","Only consumption can record a zero cost event").refine(t=>t.allocations.every(n=>n.funding!=="postpaid"||n.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(t=>t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null)&&(t.kind!=="reserve"||!t.accepted||t.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var X=e.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Y=e.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),T=e.strictObject({internal_feature_id:e.uuid(),entityId:e.uuid().nullable()}),ye=T.extend({quantity:m,expectedRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:e.string().min(1).max(120),properties:g.refine(t=>Object.keys(t).length<=13&&!Object.keys(t).some(n=>n.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),V=T.extend({operationId:e.uuid().nullable(),usage:m,capacity:X.nullable(),remaining:Y.nullable(),withinLimit:e.boolean(),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:e.iso.datetime({offset:!0}).nullable()}).strict().superRefine((t,n)=>{let i=u=>{let a=u.startsWith("-"),[s,r=""]=(a?u.slice(1):u).split(".");if(s===void 0||s==="")throw new Error("Invalid decimal value");return(a?-1n:1n)*(BigInt(s)*10n**12n+BigInt(r.padEnd(12,"0")))};(t.capacity===null!=(t.remaining===null)||(t.capacity===null?!t.withinLimit:t.remaining===null||i(t.remaining)!==i(t.capacity)-i(t.usage)||t.withinLimit!==i(t.remaining)>=0n)||t.revision===0!=(t.operationId===null)||t.operationId===null!=(t.updatedAt===null))&&n.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var y=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),f=e.iso.datetime({offset:!0}),ee=e.enum(["access","metered","credit"]),q={internal_feature_id:e.uuid(),key:O,name:e.string().min(1).max(120),kind:ee},we=e.object({customerId:e.uuid(),snapshotAt:f,memberships:e.array(e.object({id:e.uuid(),productId:e.string().min(1).max(255),productVersionId:e.uuid(),billingProductVersionId:e.uuid(),version:e.number().int().positive(),key:e.string().min(1).max(64),name:e.string().min(1).max(120),groupId:e.string().max(255).nullable(),membershipType:e.enum(["main","addon"]),status:e.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:e.boolean(),accessEnabled:e.boolean(),renewalChange:e.object({productVersionId:e.uuid(),name:e.string().min(1).max(120),version:e.number().int().positive(),effectiveAt:f,benefitsAppliedAt:f.nullable(),timing:e.enum(["immediate","renewal"]),changeKind:e.enum(["plan","seats","quantity"]),feature:e.strictObject({internal_feature_id:e.uuid(),name:e.string().min(1).max(80),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).optional(),seat:e.object({key:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).strict().nullable(),status:e.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(t=>t.changeKind==="seats"==(t.seat!==null)&&t.changeKind==="quantity"==(t.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:e.object({phase:e.enum(["paid","trial"]),startsAt:f,endsAt:f.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:e.boolean(),balances:e.array(e.object({...q,usageType:e.enum(["consumable","non_consumable"]).nullable(),accessible:e.boolean(),unlimited:e.boolean(),available:y,held:y,debt:y,nextExpiresAt:f.nullable(),usage:V.nullable()}).strict().refine(t=>t.kind==="metered"==(t.usageType!==null)&&(t.accessible||t.available==="0"&&t.held==="0")&&(t.usageType==="non_consumable"?t.usage!==null&&t.usage.internal_feature_id===t.internal_feature_id&&t.unlimited===(t.usage.capacity===null)&&t.available===(t.usage.remaining===null||t.usage.remaining.startsWith("-")?"0":t.usage.remaining)&&t.held==="0"&&t.debt==="0":t.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:e.boolean()}).strict(),Z=e.enum(["source","usage","transaction","invoice","debt","settlement"]),E=e.object({at:f,id:e.uuid(),type:Z}).strict(),ke=e.object({type:Z.nullable(),resourceKey:O.optional(),kind:e.enum(["purchase","refund"]).optional(),topup:e.boolean().optional(),from:e.iso.date().nullable(),to:e.iso.date().nullable(),after:E.nullable(),limit:e.number().int().min(1).max(50)}).strict().refine(t=>!t.from||!t.to||t.from<=t.to,"Date range is reversed"),w={id:e.uuid(),occurredAt:f},te=e.discriminatedUnion("type",[e.strictObject({...w,type:e.literal("invoice"),status:e.string().min(1).max(80),paid:y,refunded:y,currency:z,externalId:e.string().nullable()}),e.object({...w,...q,type:e.literal("source"),reason:e.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:y,unlimited:e.boolean(),status:e.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:f,expiresAt:f.nullable(),orderId:e.uuid().nullable(),parentSourceId:e.uuid().nullable()}).strict(),e.object({...w,type:e.literal("usage"),internal_feature_id:e.uuid(),name:e.string().min(1).max(120),kind:e.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),properties:g,reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:f.nullable(),charges:e.array(e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q,amount:y}),e.strictObject({funding:e.literal("unbilled"),units:Q}),e.object({...q,funding:e.literal("prepaid"),amount:y}).strict(),e.object({funding:e.literal("postpaid"),invoiceId:e.uuid(),invoiceLineId:e.uuid(),authorizationId:e.uuid(),units:m,currency:z}).strict()])).max(500)}).strict().refine(t=>(t.kind==="set_usage"||t.kind==="consume"&&t.quantity==="0"?t.accepted&&t.reason===null&&t.charges.length===0&&t.reservationStatus===null:t.accepted?t.reason===null&&t.charges.length>0:t.reason!==null&&t.charges.length===0)&&t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),e.object({...w,type:e.literal("transaction"),purpose:e.enum(["product","invoice"]),productVersionId:e.uuid().nullable(),productName:e.string().min(1).max(120).nullable(),productVersion:e.number().int().positive().nullable(),invoiceId:e.uuid().nullable(),orderId:e.uuid(),originalId:e.uuid().nullable(),kind:e.enum(["purchase","refund"]),amountMinor:e.number().int().nonnegative().max(2e8).nullable(),currency:z.nullable()}).strict().refine(t=>t.currency===null==(t.amountMinor===null)&&(t.purpose==="product"?t.productVersionId!==null&&t.productName!==null&&t.productVersion!==null&&t.invoiceId===null:t.productVersionId===null&&t.productName===null&&t.productVersion===null&&t.invoiceId!==null)&&t.kind==="refund"==(t.originalId!==null)&&(t.kind!=="refund"||t.amountMinor===null||t.amountMinor>0),"Payment fact provenance is incomplete"),e.object({...w,...q,type:e.literal("debt"),sourceId:e.uuid(),transactionId:e.uuid(),amount:y}).strict(),e.object({...w,...q,type:e.literal("settlement"),sourceId:e.uuid(),debtId:e.uuid(),kind:e.enum(["payment","usage_refund","payment_return"]),amount:y}).strict()]),je=e.object({customerId:e.uuid(),rows:e.array(te).max(50),nextCursor:E.nullable()}).strict().refine(t=>new Set(t.rows.map(n=>n.type+n.id)).size===t.rows.length,"A page cannot repeat a fact").refine(t=>{let n=t.rows.at(-1);return!t.nextCursor||!!(n&&n.id===t.nextCursor.id&&n.type===t.nextCursor.type&&n.occurredAt===t.nextCursor.at)},"Cursor must name the final displayed fact");var Ce=e.discriminatedUnion("kind",[e.object({kind:e.literal("ledger"),cursor:E}).strict(),e.object({kind:e.literal("billing"),cursor:e.uuid()}).strict()]),ne=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ie=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),e.union([e.string().max(500),e.boolean(),e.array(e.string().max(500)).max(50)])).refine(t=>Object.keys(t).length<=40,"Too many answers"),re=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function L(t,n=0){return n>20?!0:!!t&&typeof t=="object"&&(Array.isArray(t)?t.some(i=>L(i,n+1)):Object.entries(t).some(([i,u])=>["__proto__","constructor","prototype"].includes(i)||re.test(i)||L(u,n+1)))}var ae=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,ze=e.record(ne,$).refine(t=>Object.keys(t).length<=20,"Too many parameters").refine(t=>!L(t)&&!ae.test(JSON.stringify(t)),"Credentials cannot be screen parameters");var W=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),oe=e.array(e.object({variable:W,componentId:W,required:e.boolean()}).strict()).max(40).refine(t=>new Set(t.map(n=>n.variable)).size===t.length&&new Set(t.map(n=>n.componentId)).size===t.length,"Input bindings must be unique"),Re=e.object({bindings:oe,answers:ie,values:e.record(e.string(),$).optional()}).strict();function H(t,n,i=1){if(t==="free")return"";if(t==="one_time")return n.startsWith("zh")?" · 一次付款":" · one-time";let u=n.split("-")[0]??"en",a={zh:["/月","/年"],en:["/month","/year"],ja:["/月","/年"],ko:["/월","/년"],es:["/mes","/año"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/mês","/ano"],it:["/mese","/anno"],ar:["/شهر","/سنة"]},s={zh:"周",en:"week",ja:"週",ko:"주",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"أسبوع"},r=t==="week"?`/${s[u]??s.en}`:(a[u]??a.en)[t==="month"?0:1];return i===1?r:`/${i} ${r.slice(1)}${u==="en"?"s":""}`}function De(t,n){let i=[],u={};_(t,a=>{if(a.hidden)return!1;if(a.type!=="quantity_picker")return;let s=a.bind?.plan?[a.bind.plan]:[];a.bind?.picker&&_(t,r=>{if(r.type==="plan_picker"&&r.id===a.bind?.picker&&s.push(...r.planIds??[]),r.type==="stack"&&r.interaction?.type==="select"&&r.interaction.pickerId===a.bind?.picker)for(let o of r.children)o.type==="stack"&&o.bind?.plan&&s.push(o.bind.plan)}),s.length||i.push(`Quantity control ${a.id} needs a Product binding`);for(let r of new Set(s)){let o=n[r]?.prepaid?.find(c=>c.internalFeatureId===a.internalFeatureId)?.terms,d=u[r]??=new Set;(!o||d.has(a.internalFeatureId)||a.minimumQuantity<o.minimumQuantity||a.maximumQuantity>o.maximumQuantity)&&i.push(`Quantity control ${a.id} must match its Product's prepaid Feature and bounds`),d.add(a.internalFeatureId)}});for(let[a,s]of Object.entries(n))for(let r of s.prepaid??[])u[a]?.has(r.internalFeatureId)||i.push(`Product ${a} needs a quantity control for ${r.internalFeatureId}`);return i}function Ke(t,n,i,u){let a=u.plans[n];if(!a?.available)throw new Error("Selected Product is unavailable");let s={};if(_(t,r=>{if(r.hidden)return!1;if(r.type!=="quantity_picker"||r.hidden||(r.bind?.plan??(r.bind?.picker?i[r.bind.picker]:void 0))!==n)return;if(u.quantities?.[r.id]?.available===!1)throw new Error("This prepaid Feature is unavailable");let d=a.prepaid?.find(l=>l.internalFeatureId===r.internalFeatureId)?.terms,c=i[r.id];if(!d||typeof c!="number"||!Number.isSafeInteger(c)||c<Math.max(d.minimumQuantity,r.minimumQuantity)||c>Math.min(d.maximumQuantity,r.maximumQuantity)||(c-r.minimumQuantity)%r.step!==0||s[r.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");s[r.internalFeatureId]=c}),(a.prepaid??[]).some(r=>s[r.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return s}function ue(t,n,i){let u=t.terms.prices.find(a=>a.currency===n);if(!u||i<t.terms.minimumQuantity||i>t.terms.maximumQuantity)throw new Error("Quantity or currency is unavailable");return{amountMinor:U({quantity:i,unitAmountMinor:u.amountMinor,...u.pricing?{pricing:u.pricing}:{}}),allowance:D(t.includedAmount,t.terms.units,i)}}function Ne(t,n,i,u){let a=!1;if(_(t,o=>{o.type==="quantity_picker"&&(a=!0)}),!a)return n;let s=structuredClone(n);s.quantities={};let r=new Map;_(t,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker")return;let d=o.bind?.plan??(o.bind?.picker?i[o.bind.picker]??s.pickers[o.bind.picker]?.selected:void 0),c=typeof d=="string"?s.plans[d]:void 0,l=c?.prepaid?.find(G=>G.internalFeatureId===o.internalFeatureId),k=Math.max(o.minimumQuantity,l?.terms.minimumQuantity??0),x=Math.min(o.maximumQuantity,l?.terms.maximumQuantity??0),b=i[o.id]??o.defaultQuantity,h=typeof b=="number"&&Number.isSafeInteger(b)?b:o.defaultQuantity,S=!!l&&!!c?.available&&n.quantities?.[o.id]?.available!==!1&&h>=k&&h<=x&&(h-o.minimumQuantity)%o.step===0,P=s.quantities[o.id]={minimum:k,maximum:Math.max(k,x),step:o.step,value:h,label:"",available:S};if(!S||!l||!c?.currency||c.amountMinor===void 0)return;let M=ue(l,c.currency,h);P.label=`${new Intl.NumberFormat(u).format(Number(M.allowance))} ${l.name}${["week","month","year"].includes(l.reset)?H(l.reset,u,l.resetCount):l.reset==="lifetime"?"":` / ${l.resetCount} ${l.reset}`}`,M.amountMinor!==0&&r.set(String(d),(r.get(String(d))??c.amountMinor)+M.amountMinor)});for(let[o,d]of r){let c=s.plans[o];if(!c?.currency)continue;let l=F(d,c.currency,u);c.price=l;for(let[k,x]of Object.entries(s.nodes)){let b=K(t,k),h=S=>{if(S.price&&(S.price={...S.price,current:l,original:null}),b?.type==="text"){let P=t.strings.locales[u]?.[b.text]??t.strings.locales[t.strings.defaultLocale]?.[b.text];P?.includes("{{plan.price")&&(S.text=P.replace(/\{\{\s*plan.price\s*\}\}/g,l).replace(/\{\{\s*plan.price_per_month\s*\}\}/g,F(Math.round(d/((c.interval==="year"?12:1)*(c.intervalCount??1))),c.currency,u)))}};x.byPlan?.[o]&&h(x.byPlan[o]),(x.base.planVersionId===o||b&&"bind"in b&&b.bind?.plan===o)&&h(x.base)}}return s}export{le as a,J as b,Q as c,de as d,me as e,T as f,ye as g,V as h,y as i,we as j,ke as k,je as l,Ce as m,ie as n,ze as o,oe as p,Re as q,H as r,De as s,Ke as t,Ne as u};
|
|
1
|
+
import{C as K,b as U,d as D,v as _}from"./chunk-HN46A5SD.js";import{a as z,c as F}from"./chunk-VCRDA5R3.js";import{d as $}from"./chunk-GRY5G7X3.js";import{i as C,j as m,l as O,m as g}from"./chunk-FEZWUYEK.js";import{b as e}from"./chunk-TDOPU2RH.js";var I=m.refine(t=>/[1-9]/.test(t),"Quantity must be positive"),j=e.string().min(1).max(120),R=e.enum(["cap","overflow"]),p=(t,n)=>{let[i,u=""]=t.split(".");if(i===void 0||i==="")throw new Error("Invalid decimal value");return BigInt(i)*10n**BigInt(n)+BigInt(u.padEnd(n,"0"))},A=t=>{try{return t()}catch{return!1}},le=e.discriminatedUnion("operation",[e.object({operation:e.literal("quote"),overageBehavior:R.optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g}).strict(),e.object({operation:e.literal("consume"),overageBehavior:R.optional(),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:m,properties:g,idempotencyKey:j}).strict(),e.object({operation:e.literal("reserve"),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g,idempotencyKey:j,expiresInSeconds:e.number().int().min(1).max(86400)}).strict(),e.object({operation:e.literal("confirm"),operationId:e.uuid(),quantity:I,properties:g.optional(),idempotencyKey:j}).strict(),e.object({operation:e.literal("refund"),operationId:e.uuid(),quantity:I,idempotencyKey:j}).strict(),e.object({operation:e.literal("release"),operationId:e.uuid(),idempotencyKey:j}).strict()]),J=e.object({internal_credit_feature_id:e.uuid().nullable(),internal_metered_feature_id:e.uuid(),dimension:e.string().min(1).max(64),counterKey:e.string().min(1).max(240),cycleStart:e.iso.datetime({offset:!0}),unitCost:m,units:I,amount:C,tier:e.number().int().min(1).max(12).nullable()}).strict(),Q=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function N(t,n){let i=t.reduce((u,a)=>u+p(a.units,12),0n)-p(n,12);return t.some(u=>u.funding==="balance")?i>=-100n&&i<=100n:i===0n}var v=e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q.refine(t=>/[1-9]/.test(t)),amount:C}),e.strictObject({funding:e.literal("unbilled"),units:Q.refine(t=>/[1-9]/.test(t))}),e.object({funding:e.literal("prepaid"),sourceId:e.uuid(),units:I,amount:C,pricing:e.array(J).min(1).max(12)}).strict().refine(t=>A(()=>t.pricing.reduce((n,i)=>n+p(i.units,6),0n)===p(t.units,6)&&t.pricing.reduce((n,i)=>n+p(i.amount,12),0n)===p(t.amount,12)&&t.pricing.every(n=>p(n.unitCost,6)*p(n.units,6)===p(n.amount,12))),"Frozen pricing must conserve allocated units and amounts"),e.object({funding:e.literal("postpaid"),invoiceLineId:e.uuid().nullable(),units:I,authorizationId:e.uuid()}).strict()]),B=e.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),de=e.object({allowed:e.boolean(),internal_feature_id:e.uuid(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),reason:B.nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.allowed?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"A quote must conserve its accepted units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0&&/[1-9]/.test(t.quantity):t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Explicit overage behavior must retain the requested quantity"),me=e.object({id:e.uuid(),internal_feature_id:e.uuid(),kind:e.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),createdAt:e.iso.datetime({offset:!0}),reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:e.iso.datetime({offset:!0}).nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.accepted?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"An operation must conserve its requested units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0:t.kind==="consume"&&t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(t=>/[1-9]/.test(t.quantity)||t.kind==="consume","Only consumption can record a zero cost event").refine(t=>t.allocations.every(n=>n.funding!=="postpaid"||n.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(t=>t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null)&&(t.kind!=="reserve"||!t.accepted||t.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var X=e.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Y=e.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),T=e.strictObject({internal_feature_id:e.uuid(),entityId:e.uuid().nullable()}),ye=T.extend({quantity:m,expectedRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:e.string().min(1).max(120),properties:g.refine(t=>Object.keys(t).length<=13&&!Object.keys(t).some(n=>n.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),V=T.extend({operationId:e.uuid().nullable(),usage:m,capacity:X.nullable(),remaining:Y.nullable(),withinLimit:e.boolean(),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:e.iso.datetime({offset:!0}).nullable()}).strict().superRefine((t,n)=>{let i=u=>{let a=u.startsWith("-"),[s,r=""]=(a?u.slice(1):u).split(".");if(s===void 0||s==="")throw new Error("Invalid decimal value");return(a?-1n:1n)*(BigInt(s)*10n**12n+BigInt(r.padEnd(12,"0")))};(t.capacity===null!=(t.remaining===null)||(t.capacity===null?!t.withinLimit:t.remaining===null||i(t.remaining)!==i(t.capacity)-i(t.usage)||t.withinLimit!==i(t.remaining)>=0n)||t.revision===0!=(t.operationId===null)||t.operationId===null!=(t.updatedAt===null))&&n.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var y=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),f=e.iso.datetime({offset:!0}),ee=e.enum(["access","metered","credit"]),q={internal_feature_id:e.uuid(),key:O,name:e.string().min(1).max(120),kind:ee},we=e.object({customerId:e.uuid(),snapshotAt:f,memberships:e.array(e.object({id:e.uuid(),productId:e.string().min(1).max(255),productVersionId:e.uuid(),billingProductVersionId:e.uuid(),version:e.number().int().positive(),key:e.string().min(1).max(64),name:e.string().min(1).max(120),groupId:e.string().max(255).nullable(),membershipType:e.enum(["main","addon"]),status:e.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:e.boolean(),accessEnabled:e.boolean(),renewalChange:e.object({productVersionId:e.uuid(),name:e.string().min(1).max(120),version:e.number().int().positive(),effectiveAt:f,benefitsAppliedAt:f.nullable(),timing:e.enum(["immediate","renewal"]),changeKind:e.enum(["plan","seats","quantity"]),feature:e.strictObject({internal_feature_id:e.uuid(),name:e.string().min(1).max(80),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).optional(),seat:e.object({key:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).strict().nullable(),status:e.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(t=>t.changeKind==="seats"==(t.seat!==null)&&t.changeKind==="quantity"==(t.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:e.object({phase:e.enum(["paid","trial"]),startsAt:f,endsAt:f.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:e.boolean(),balances:e.array(e.object({...q,usageType:e.enum(["consumable","non_consumable"]).nullable(),accessible:e.boolean(),unlimited:e.boolean(),available:y,held:y,debt:y,nextExpiresAt:f.nullable(),usage:V.nullable()}).strict().refine(t=>t.kind==="metered"==(t.usageType!==null)&&(t.accessible||t.available==="0"&&t.held==="0")&&(t.usageType==="non_consumable"?t.usage!==null&&t.usage.internal_feature_id===t.internal_feature_id&&t.unlimited===(t.usage.capacity===null)&&t.available===(t.usage.remaining===null||t.usage.remaining.startsWith("-")?"0":t.usage.remaining)&&t.held==="0"&&t.debt==="0":t.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:e.boolean()}).strict(),Z=e.enum(["source","usage","transaction","invoice","debt","settlement"]),E=e.object({at:f,id:e.uuid(),type:Z}).strict(),ke=e.object({type:Z.nullable(),resourceKey:O.optional(),kind:e.enum(["purchase","refund"]).optional(),topup:e.boolean().optional(),from:e.iso.date().nullable(),to:e.iso.date().nullable(),after:E.nullable(),limit:e.number().int().min(1).max(50)}).strict().refine(t=>!t.from||!t.to||t.from<=t.to,"Date range is reversed"),w={id:e.uuid(),occurredAt:f},te=e.discriminatedUnion("type",[e.strictObject({...w,type:e.literal("invoice"),status:e.string().min(1).max(80),paid:y,refunded:y,currency:z,externalId:e.string().nullable()}),e.object({...w,...q,type:e.literal("source"),reason:e.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:y,unlimited:e.boolean(),status:e.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:f,expiresAt:f.nullable(),orderId:e.uuid().nullable(),parentSourceId:e.uuid().nullable()}).strict(),e.object({...w,type:e.literal("usage"),internal_feature_id:e.uuid(),name:e.string().min(1).max(120),kind:e.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),properties:g,reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:f.nullable(),charges:e.array(e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q,amount:y}),e.strictObject({funding:e.literal("unbilled"),units:Q}),e.object({...q,funding:e.literal("prepaid"),amount:y}).strict(),e.object({funding:e.literal("postpaid"),invoiceId:e.uuid(),invoiceLineId:e.uuid(),authorizationId:e.uuid(),units:m,currency:z}).strict()])).max(500)}).strict().refine(t=>(t.kind==="set_usage"||t.kind==="consume"&&t.quantity==="0"?t.accepted&&t.reason===null&&t.charges.length===0&&t.reservationStatus===null:t.accepted?t.reason===null&&t.charges.length>0:t.reason!==null&&t.charges.length===0)&&t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),e.object({...w,type:e.literal("transaction"),purpose:e.enum(["product","invoice"]),productVersionId:e.uuid().nullable(),productName:e.string().min(1).max(120).nullable(),productVersion:e.number().int().positive().nullable(),invoiceId:e.uuid().nullable(),orderId:e.uuid(),originalId:e.uuid().nullable(),kind:e.enum(["purchase","refund"]),amountMinor:e.number().int().nonnegative().max(2e8).nullable(),currency:z.nullable()}).strict().refine(t=>t.currency===null==(t.amountMinor===null)&&(t.purpose==="product"?t.productVersionId!==null&&t.productName!==null&&t.productVersion!==null&&t.invoiceId===null:t.productVersionId===null&&t.productName===null&&t.productVersion===null&&t.invoiceId!==null)&&t.kind==="refund"==(t.originalId!==null)&&(t.kind!=="refund"||t.amountMinor===null||t.amountMinor>0),"Payment fact provenance is incomplete"),e.object({...w,...q,type:e.literal("debt"),sourceId:e.uuid(),transactionId:e.uuid(),amount:y}).strict(),e.object({...w,...q,type:e.literal("settlement"),sourceId:e.uuid(),debtId:e.uuid(),kind:e.enum(["payment","usage_refund","payment_return"]),amount:y}).strict()]),je=e.object({customerId:e.uuid(),rows:e.array(te).max(50),nextCursor:E.nullable()}).strict().refine(t=>new Set(t.rows.map(n=>n.type+n.id)).size===t.rows.length,"A page cannot repeat a fact").refine(t=>{let n=t.rows.at(-1);return!t.nextCursor||!!(n&&n.id===t.nextCursor.id&&n.type===t.nextCursor.type&&n.occurredAt===t.nextCursor.at)},"Cursor must name the final displayed fact");var Ce=e.discriminatedUnion("kind",[e.object({kind:e.literal("ledger"),cursor:E}).strict(),e.object({kind:e.literal("billing"),cursor:e.uuid()}).strict()]),ne=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ie=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),e.union([e.string().max(500),e.boolean(),e.array(e.string().max(500)).max(50)])).refine(t=>Object.keys(t).length<=40,"Too many answers"),re=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function L(t,n=0){return n>20?!0:!!t&&typeof t=="object"&&(Array.isArray(t)?t.some(i=>L(i,n+1)):Object.entries(t).some(([i,u])=>["__proto__","constructor","prototype"].includes(i)||re.test(i)||L(u,n+1)))}var ae=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,ze=e.record(ne,$).refine(t=>Object.keys(t).length<=20,"Too many parameters").refine(t=>!L(t)&&!ae.test(JSON.stringify(t)),"Credentials cannot be screen parameters");var W=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),oe=e.array(e.object({variable:W,componentId:W,required:e.boolean()}).strict()).max(40).refine(t=>new Set(t.map(n=>n.variable)).size===t.length&&new Set(t.map(n=>n.componentId)).size===t.length,"Input bindings must be unique"),Re=e.object({bindings:oe,answers:ie,values:e.record(e.string(),$).optional()}).strict();function H(t,n,i=1){if(t==="free")return"";if(t==="one_time")return n.startsWith("zh")?" · 一次付款":" · one-time";let u=n.split("-")[0]??"en",a={zh:["/月","/年"],en:["/month","/year"],ja:["/月","/年"],ko:["/월","/년"],es:["/mes","/año"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/mês","/ano"],it:["/mese","/anno"],ar:["/شهر","/سنة"]},s={zh:"周",en:"week",ja:"週",ko:"주",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"أسبوع"},r=t==="week"?`/${s[u]??s.en}`:(a[u]??a.en)[t==="month"?0:1];return i===1?r:`/${i} ${r.slice(1)}${u==="en"?"s":""}`}function De(t,n){let i=[],u={};_(t,a=>{if(a.hidden)return!1;if(a.type!=="quantity_picker")return;let s=a.bind?.plan?[a.bind.plan]:[];a.bind?.picker&&_(t,r=>{if(r.type==="plan_picker"&&r.id===a.bind?.picker&&s.push(...r.planIds??[]),r.type==="stack"&&r.interaction?.type==="select"&&r.interaction.pickerId===a.bind?.picker)for(let o of r.children)o.type==="stack"&&o.bind?.plan&&s.push(o.bind.plan)}),s.length||i.push(`Quantity control ${a.id} needs a Product binding`);for(let r of new Set(s)){let o=n[r]?.prepaid?.find(c=>c.internalFeatureId===a.internalFeatureId)?.terms,d=u[r]??=new Set;(!o||d.has(a.internalFeatureId)||a.minimumQuantity<o.minimumQuantity||a.maximumQuantity>o.maximumQuantity)&&i.push(`Quantity control ${a.id} must match its Product's prepaid Feature and bounds`),d.add(a.internalFeatureId)}});for(let[a,s]of Object.entries(n))for(let r of s.prepaid??[])u[a]?.has(r.internalFeatureId)||i.push(`Product ${a} needs a quantity control for ${r.internalFeatureId}`);return i}function Ke(t,n,i,u){let a=u.plans[n];if(!a?.available)throw new Error("Selected Product is unavailable");let s={};if(_(t,r=>{if(r.hidden)return!1;if(r.type!=="quantity_picker"||r.hidden||(r.bind?.plan??(r.bind?.picker?i[r.bind.picker]:void 0))!==n)return;if(u.quantities?.[r.id]?.available===!1)throw new Error("This prepaid Feature is unavailable");let d=a.prepaid?.find(l=>l.internalFeatureId===r.internalFeatureId)?.terms,c=i[r.id];if(!d||typeof c!="number"||!Number.isSafeInteger(c)||c<Math.max(d.minimumQuantity,r.minimumQuantity)||c>Math.min(d.maximumQuantity,r.maximumQuantity)||(c-r.minimumQuantity)%r.step!==0||s[r.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");s[r.internalFeatureId]=c}),(a.prepaid??[]).some(r=>s[r.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return s}function ue(t,n,i){let u=t.terms.prices.find(a=>a.currency===n);if(!u||i<t.terms.minimumQuantity||i>t.terms.maximumQuantity)throw new Error("Quantity or currency is unavailable");return{amountMinor:U({quantity:i,unitAmountMinor:u.amountMinor,...u.pricing?{pricing:u.pricing}:{}}),allowance:D(t.includedAmount,t.terms.units,i)}}function Ne(t,n,i,u){let a=!1;if(_(t,o=>{o.type==="quantity_picker"&&(a=!0)}),!a)return n;let s=structuredClone(n);s.quantities={};let r=new Map;_(t,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker")return;let d=o.bind?.plan??(o.bind?.picker?i[o.bind.picker]??s.pickers[o.bind.picker]?.selected:void 0),c=typeof d=="string"?s.plans[d]:void 0,l=c?.prepaid?.find(G=>G.internalFeatureId===o.internalFeatureId),k=Math.max(o.minimumQuantity,l?.terms.minimumQuantity??0),x=Math.min(o.maximumQuantity,l?.terms.maximumQuantity??0),b=i[o.id]??o.defaultQuantity,h=typeof b=="number"&&Number.isSafeInteger(b)?b:o.defaultQuantity,S=!!l&&!!c?.available&&n.quantities?.[o.id]?.available!==!1&&h>=k&&h<=x&&(h-o.minimumQuantity)%o.step===0,P=s.quantities[o.id]={minimum:k,maximum:Math.max(k,x),step:o.step,value:h,label:"",available:S};if(!S||!l||!c?.currency||c.amountMinor===void 0)return;let M=ue(l,c.currency,h);P.label=`${new Intl.NumberFormat(u).format(Number(M.allowance))} ${l.name}${["week","month","year"].includes(l.reset)?H(l.reset,u,l.resetCount):l.reset==="lifetime"?"":` / ${l.resetCount} ${l.reset}`}`,M.amountMinor!==0&&r.set(String(d),(r.get(String(d))??c.amountMinor)+M.amountMinor)});for(let[o,d]of r){let c=s.plans[o];if(!c?.currency)continue;let l=F(d,c.currency,u);c.price=l;for(let[k,x]of Object.entries(s.nodes)){let b=K(t,k),h=S=>{if(S.price&&(S.price={...S.price,current:l,original:null}),b?.type==="text"){let P=t.strings.locales[u]?.[b.text]??t.strings.locales[t.strings.defaultLocale]?.[b.text];P?.includes("{{plan.price")&&(S.text=P.replace(/\{\{\s*plan.price\s*\}\}/g,l).replace(/\{\{\s*plan.price_per_month\s*\}\}/g,F(Math.round(d/((c.interval==="year"?12:1)*(c.intervalCount??1))),c.currency,u)))}};x.byPlan?.[o]&&h(x.byPlan[o]),(x.base.planVersionId===o||b&&"bind"in b&&b.bind?.plan===o)&&h(x.base)}}return s}export{le as a,J as b,Q as c,de as d,me as e,T as f,ye as g,V as h,y as i,we as j,ke as k,je as l,Ce as m,ie as n,ze as o,oe as p,Re as q,H as r,De as s,Ke as t,Ne as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as o}from"./chunk-
|
|
1
|
+
import{f as o}from"./chunk-FEZWUYEK.js";var n=class extends Error{constructor(t,s,y,i,r){super(s);this.code=t;this.status=y;this.requestId=i;this.name="IndianaError",this.reason=r?.reason;let e=o(t,y??0,{...r,retryAfter:r?.retryAfterSeconds===void 0?void 0:String(r.retryAfterSeconds)});this.retryable=e.retryable,this.recovery=e.recovery,this.retryAfterSeconds=e.retryAfterSeconds}code;status;requestId;commandRequestId;retryable;recovery;retryAfterSeconds;reason};export{n as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{k as c}from"./chunk-
|
|
1
|
+
import{k as c}from"./chunk-HN46A5SD.js";import{b as r}from"./chunk-TDOPU2RH.js";var s=r.strictObject({items:r.array(r.strictObject({productVersionId:r.string().min(1).max(200),label:r.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:r.string().min(1).max(200).nullable(),grouping:c.optional()});function p(e,t,n){let i=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof i!="string"||!Object.values(n.plans).some(o=>o.versionId===i&&o.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(i)||!n.pickers[e.pickerId]?.options.includes(i))?null:i}export{s as a,p as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as L}from"./chunk-W32FI2A2.js";import{b as q,e as A}from"./chunk-SLUA7ABW.js";import{d as N}from"./chunk-MB2U2GWJ.js";import{a as g}from"./chunk-DSPLGTQI.js";import{b as J}from"./chunk-
|
|
1
|
+
import{a as L}from"./chunk-W32FI2A2.js";import{b as q,e as A}from"./chunk-SLUA7ABW.js";import{d as N}from"./chunk-MB2U2GWJ.js";import{a as g}from"./chunk-DSPLGTQI.js";import{b as J}from"./chunk-VPT5MFDG.js";function _(n){if(!n.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let $=n.client.pageExperiments.bind(n.client),r=!1,o=!1,i=0,y=!1,w=!1,h="",E=()=>{let e=n.client.view;return JSON.stringify([e?.id,e?.source.versionId,e?.visit,e?.revision,e?.status,e?.stopped])},s=new Map,b=new Set,O={},c=new Map,U=q(n.appManifestRelease),M=()=>{for(let e of s.values())e.effect.revert();s.clear()},u=()=>{M();for(let e of c.values())e();c.clear()};function x(e){if(r||b.has(e))return;b.add(e);let p=i;$(n.appManifestRelease,[e]).catch(R=>{b.delete(e),!r&&p===i&&g(n.onError,R)})}async function d(){if(r)return;h=E();let e=n.client.view;if(!e||e.stopped||!["running","waiting"].includes(e.status)){i++,u();return}if(document.visibilityState==="hidden")return;if(y){w=!0;return}y=!0;let p=++i,R=`${e.id}:${e.visit}:${e.revision}`,j=location.href;try{let[m,{applyVisualVariation:z}]=await Promise.all([$(n.appManifestRelease),import("./visual-dom-5LUN4AHO.js")]),l=n.client.view;if(r||p!==i||!l||l.stopped||!["running","waiting"].includes(l.status)||`${l.id}:${l.visit}:${l.revision}`!==R||location.href!==j)return;let I=new Set,K=new Set;for(let t of m.assignments){let a=`${m.payload.environmentId}:${t.experimentKey}`;if(K.add(a),c.has(a)||c.set(a,A(a,O)),!!t.inExperiment)for(let f of m.payload.experiments){if(f.key!==t.experimentKey||!J(location.href,f.urlPatterns??[]))continue;let B=f.meta?.findIndex(k=>k.key===t.variationKey)??-1,V=f.variations[B];if(!V?.renderGuard)continue;let v=t.receiptId+":"+f.changeId,P=JSON.stringify([t.variationKey,V]);I.add(v);let F=s.get(v);if(F?.signature===P){F.effect.applied&&x(t.receiptId);continue}s.get(v)?.effect.revert(),s.delete(v);let T=z(V,{requireUniqueTargets:!0,boundVariations:f.variations,allowJs:!1,onApplied:()=>x(t.receiptId),onError:k=>g(n.onError,k)});s.set(v,{signature:P,effect:T}),T.applied&&x(t.receiptId)}}for(let[t,a]of s)I.has(t)||(a.effect.revert(),s.delete(t));for(let[t,a]of c)K.has(t)||(a(),c.delete(t))}catch(m){p===i&&u(),!r&&p===i&&g(n.onError,m)}finally{y=!1,w&&!r&&(w=!1,d())}}let G=n.client.subscribe(()=>{if(E()===h)return;h=E(),i++;let e=n.client.view;(!e||e.stopped||!["running","waiting"].includes(e.status))&&u(),o&&d()}),H=N(()=>{i++,u(),o&&d()}),S=()=>{i++,M()};document.addEventListener("visibilitychange",S);let C=L({document,run:async()=>{o&&await d()},delay:()=>o&&!r?15e3:void 0});return{async start(){o||r||(o=!0,await C.refresh())},refresh:d,destroy(){r=!0,i++,C.destroy(),document.removeEventListener("visibilitychange",S),G(),H(),u(),U.destroy()}}}export{_ as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{J as se,d as O,f as ie}from"./chunk-ME6QTD5Y.js";import{a as F}from"./chunk-6XRQR43F.js";import{b as te,f as ne,g as re,h as oe}from"./chunk-3532HSBP.js";import{e as ee,k as ae}from"./chunk-6VVQWTHV.js";import{s as ce}from"./chunk-Y3W5G4BF.js";import{C as Y,e as J,j as Z,l as W,p as R,s as X,t as H,v as w,w as P,x as Q,z as k}from"./chunk-FYUMVOCV.js";import{a as T,f as K}from"./chunk-DUS5V65Z.js";import{a as I,b as S,d as h,e as D,f as C,g as A}from"./chunk-A5WUQLAO.js";import{h as j}from"./chunk-LFR2LWYC.js";import{b as e}from"./chunk-W22ESUYY.js";import{a as L,b as U}from"./chunk-FRK6322O.js";var V=e.strictObject({eventsEnabled:e.boolean(),experimentViewsEnabled:e.boolean(),featureUsageEnabled:e.boolean()}),Ze=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function We(t,r){return r==="experiment_exposure"?t.experimentViewsEnabled:r==="feature_usage"?t.featureUsageEnabled:t.eventsEnabled}var z=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,r])=>t<=r),Se=e.strictObject({attribute:e.string().optional(),seed:e.string(),hashVersion:e.literal(2),ranges:e.array(z).max(100)}),we=e.strictObject({id:e.string().min(1).max(255),condition:C,gate:e.boolean().optional()}),Oe=e.strictObject({key:e.string().optional(),name:e.string().optional(),passthrough:e.boolean().optional()}),ue={condition:C.optional(),parentConditions:e.array(we).max(100).optional(),weights:e.array(e.number().min(0).max(1)).max(20).optional(),coverage:e.number().min(0).max(1).optional(),hashAttribute:e.string().optional(),fallbackAttribute:e.string().optional(),hashVersion:e.literal(2).optional(),disableStickyBucketing:e.boolean().optional(),bucketVersion:e.number().int().nonnegative().optional(),minBucketVersion:e.number().int().nonnegative().optional(),filters:e.array(Se).max(100).optional(),ranges:e.array(z).max(20).optional(),meta:e.array(Oe).max(20).optional(),seed:e.string().optional(),name:e.string().optional(),phase:e.string().optional()},pe=e.strictObject({...ue,key:e.string().min(1).max(255),variations:e.tuple([h,h]).rest(h).refine(t=>t.length<=20),urlPatterns:e.array(e.strictObject({include:e.boolean(),type:e.enum(["regex","simple"]),pattern:e.string()})).max(100).optional(),force:e.number().int().nonnegative().optional(),active:e.boolean().optional(),persistQueryString:e.boolean().optional()}),G=e.strictObject({value:h,variationId:e.number().int(),key:e.string(),name:e.string().optional(),bucket:e.number().optional(),passthrough:e.boolean().optional(),inExperiment:e.boolean(),hashUsed:e.boolean().optional(),hashAttribute:e.string(),hashValue:e.string(),featureId:e.string().nullable(),stickyBucketUsed:e.boolean().optional()}),je=e.strictObject({...ue,id:e.string().max(255).optional(),force:h.optional(),variations:e.array(h).min(2).max(20).optional(),key:e.string().optional(),range:z.optional(),tracks:e.array(e.strictObject({experiment:pe,result:G})).max(100).optional()}),Ie=e.strictObject({defaultValue:h.optional(),rules:e.array(je).max(500).optional()}),Pe=e.record(e.string(),e.union([e.strictObject({type:e.literal("hashed"),attributeKey:e.string(),values:e.array(e.string().regex(/^[a-f0-9]{64}$/))}),e.strictObject({type:e.literal("list"),attributeKey:e.string(),values:e.array(e.union([e.string(),e.number()]))}),e.strictObject({type:e.literal("condition"),condition:C})])),v=e.strictObject({scope:j,generation:e.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0}).nullable(),features:e.record(e.string(),Ie),savedGroups:Pe,experiments:e.record(e.uuid(),pe)});var ke=v.extend({analyticsConfig:V,remoteFeatures:e.array(e.string().min(1).max(255)).max(500)}),it=ke.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((t,r)=>{for(let a of t.remoteFeatures)Object.hasOwn(t.features,a)&&r.addIssue({code:"custom",path:["features",a],message:"Remote Feature definitions cannot be public"});for(let[a,o]of Object.entries(t.savedGroups))o.type==="list"&&r.addIssue({code:"custom",path:["savedGroups",a],message:"Raw Saved Group lists cannot be public"})}),at=e.strictObject({attributes:D,features:e.array(e.string().min(1).max(255)).max(500).optional(),customerId:e.uuid().optional()}),me=e.strictObject({value:h,source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:e.boolean(),off:e.boolean(),ruleId:e.string(),experimentResult:G.optional()}),st=e.strictObject({generation:v.shape.generation,evaluatedAt:v.shape.evaluatedAt,expiresAt:v.shape.expiresAt,features:e.record(e.string(),me),merchandiseContext:e.strictObject({merchandiseId:e.uuid(),merchandise:D}).optional()}),de={eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}),merchandise:te.optional(),deviceId:e.string().min(1).max(255).optional(),sessionId:e.string().min(1).max(255).optional()},le={...de,generation:v.shape.generation},Ce=e.discriminatedUnion("kind",[e.strictObject({...de,kind:e.literal("custom"),name:e.string().min(1).max(255),properties:e.record(e.string(),h).default({})}),e.strictObject({...le,kind:e.literal("experiment_exposure"),experimentId:e.string().min(1).max(255),variationId:e.string().min(1).max(255)}),e.strictObject({...le,kind:e.literal("feature_usage"),feature:e.string().min(1).max(255),value:h,source:me.shape.source,ruleId:e.string().max(255),variationId:e.string().min(1).max(255).optional()})]),ct=e.strictObject({customerId:e.uuid().optional(),events:e.array(Ce).min(1).max(100)}),Ae=e.strictObject({eventUuid:e.uuid(),reason:e.enum(["invalid_event","invalid_merchandise","not_delivered","reserved_name"])}),ut=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),rejected:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejections:e.array(Ae).max(100),analyticsConfig:V});function fe(t,r){let a=new Set,o=new Set,c=new Set,p=[],g=new Map,f=new Map,d=new Map;function m(s){for(let n of A(s))i(n)}function i(s){if(c.has(s)||!Object.hasOwn(r.savedGroups,s))return;let n=r.savedGroups[s];n&&(c.add(s),d.set(s,n),p.push(()=>{!Array.isArray(n)&&n.type==="condition"&&m(n.condition)}))}function u(s){for(let n of["hashAttribute","fallbackAttribute"])if(s[n]!==void 0&&ae(s[n]))throw new Error(`Funnel GB ${n} uses a reserved flow namespace`);m(s.condition);for(let n of s.parentConditions??[])l(n.id),m(n.condition)}function l(s,n=!1){let b=Object.hasOwn(r.features,s)?r.features[s]:void 0;if(!b){if(n)throw new Error("Required GB Feature is unavailable");return}a.has(s)||(a.add(s),g.set(s,b),p.push(()=>{for(let x of b.rules??[]){u(x);for(let ve of x.tracks??[])u(ve.experiment)}}))}function y(s){let n=Object.hasOwn(r.experiments,s)?r.experiments[s]:void 0;if(!n)throw new Error("Required GB Experiment is unavailable");o.has(s)||(o.add(s),f.set(s,n),p.push(()=>u(n)))}for(let s of t.graph.nodes){s.type==="feature"&&l(s.featureKey,!0),s.type==="split"&&y(s.experimentId),s.type==="condition"&&s.cases.forEach(b=>m(b.condition)),s.type==="offering"&&s.configuration.source==="feature"&&l(s.configuration.featureKey,!0);let n=s.type==="output"?s.value:s.type==="end"?s.output:null;n?.type==="feature"&&l(n.featureKey,!0)}for(let s of p)s();return{...r,features:Object.fromEntries(g),experiments:Object.fromEntries(f),savedGroups:Object.fromEntries(d)}}var ge=e.object({defaultLocale:R,locales:e.record(R,e.object({name:e.string().max(80),description:e.string().max(500)}).strict())}).strict().superRefine((t,r)=>{let a=Object.keys(t.locales);(!a.length||a.length>20||!t.locales[t.defaultLocale])&&r.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(t)).length>5e4&&r.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var M=e.discriminatedUnion("type",[e.strictObject({type:e.literal("event"),event:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),e.strictObject({type:e.literal("open_url"),url:e.url().refine(t=>new URL(t).protocol==="https:")})]),Fe=P,Ee=e.discriminatedUnion("type",[e.object({type:e.literal("checkout"),product:I}).strict(),e.object({type:e.literal("close")}).strict(),e.object({type:e.literal("action"),action:M}).strict()]),E=e.object({schemaVersion:e.literal(3),kind:e.literal("paywall"),name:e.string().trim().min(1).max(80),presentation:S,requirement:K.optional(),products:F,offeringVersionId:e.uuid().nullable(),offeringId:e.uuid(),screen:Fe,buttons:e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ee)}).strict(),Pt=E.superRefine((t,r)=>{(t.screen.surface!=="paywall"||t.screen.actions.some(o=>!["event","navigate"].includes(o.type)||o.close))&&r.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let o of Re(t))r.addIssue({code:"custom",message:o});for(let o of _e(t))r.addIssue({code:"custom",message:o});for(let o of t.screen.actions){let c=o.properties.closeControl;c!==void 0&&(c!=="content"||t.buttons[o.id]?.type!=="close")&&r.addIssue({code:"custom",path:["screen","actions",o.id],message:'Only a close button can carry closeControl, and its value is "content"'})}for(let o of t.screen.actions){let c=o.properties.couponBinding;c!==void 0&&(typeof c!="string"||!X.safeParse(c).success||t.buttons[o.id]?.type!=="checkout"||Y(t.screen,c)?.type!=="text")&&r.addIssue({code:"custom",path:["screen","actions",o.id],message:"Choose a Coupon text binding for this checkout action"})}k(t.screen).some(o=>!o.complete)&&r.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(t.buttons).length!==t.screen.actions.filter(o=>o.type!=="navigate").length||t.screen.actions.some(o=>o.type!=="navigate"&&!Object.hasOwn(t.buttons,o.id)))&&r.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(t.buttons).some(o=>o.type==="checkout")||r.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function _e(t){let r=t.products.items.map(p=>p.productVersionId),a=Z(t.screen),o=new Set,c=[];(!r.length||!t.products.defaultProductVersionId||!r.includes(t.products.defaultProductVersionId))&&c.push("products"),t.offeringVersionId||c.push("offering"),t.products.grouping&&(!W(t.products.grouping,r)||t.products.grouping.tiers.some(p=>!t.products.grouping.assignments.some(g=>g.tierId===p.id)))&&c.push("grouping");for(let p of Object.values(t.buttons))if(p.type==="checkout"){let g=p.product;if(g.type==="fixed")o.add(g.productVersionId);else{g.allowedProductVersionIds.forEach(m=>o.add(m));let f=!1,d=a[g.pickerId];d&&(f=!0,(g.allowedProductVersionIds.some(m=>!d.ids.includes(m))||d.ids.some(m=>!g.allowedProductVersionIds.includes(m)))&&c.push("picker")),w(t.screen,m=>{if(m.id!==g.pickerId||m.type!=="plan_picker")return;f=!0,(JSON.stringify(m.planIds)!==JSON.stringify(r)||JSON.stringify(g.allowedProductVersionIds)!==JSON.stringify(r)||m.defaultPlan!==t.products.defaultProductVersionId)&&c.push("picker");let i=m.grouping?{tiers:m.grouping.tiers,assignments:m.grouping.assignments}:void 0;JSON.stringify(i)!==JSON.stringify(t.products.grouping)&&c.push("grouping")}),f||c.push("picker")}}return(!o.size||[...o].some(p=>!r.includes(p)))&&c.push("purchase"),w(t.screen,p=>{p.type==="stack"&&p.productSlot&&!p.bind?.plan&&c.push(`productBinding:${p.id}`),(p.type==="stack"||p.type==="button")&&p.bind?.plan&&!r.includes(p.bind.plan)&&c.push("binding"),p.type==="plan_picker"&&(!p.planIds?.length||p.planIds.some(g=>!r.includes(g)))&&c.push("binding")}),[...new Set(c)]}function Re(t){let r=[],a=t.screen.pages.at(-1),o=new Map;for(let f of t.screen.pages)o.set(f.id,[]),Q(f.root,d=>{let m=d.type==="button"?d.action:d.type==="stack"?d.purchaseAction:void 0;if(m){let i=t.screen.actions.find(l=>l.id===m);i?.type==="navigate"&&o.get(f.id).push(i.pageId);let u=t.buttons[m];f.id!==a.id&&u&&u.type!=="close"&&r.push(`purchaseScreen:${d.id}`)}f.id!==a.id&&(d.type==="plan_picker"||d.type==="stack"&&d.productSlot)&&r.push(`packageScreen:${d.id}`)});let c=new Set;function p(f){if(!c.has(f)){c.add(f);for(let d of o.get(f)??[])p(d)}}let g=t.screen.initialPageId??t.screen.pages[0]?.id;g?p(g):r.push("initialPage");for(let f of t.screen.pages)c.has(f.id)||r.push(`unreachableScreen:${f.id}`);return[...new Set(r)]}var ye=e.object({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),revision:e.number().int().nonnegative(),state:e.enum(["active","archived"]),publishedVersionId:e.uuid().nullable(),updatedAt:e.iso.datetime({offset:!0}),draft:E}).strict(),kt=e.object({rows:e.array(ye).max(200),nextCursor:e.uuid().nullable()}).strict(),Ct=ye.omit({draft:!0}).extend({name:e.string(),productCount:e.number().int().nonnegative()}).strict(),At=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),document:E}).strict(),e.object({action:e.enum(["publish","archive"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Ft=e.object({paywalls:e.array(e.object({id:e.uuid(),paywallId:e.uuid(),version:e.number().int().positive(),name:e.string().min(1).max(80),presentation:S,buttons:E.shape.buttons}).strict()).max(500),limited:e.boolean()}).strict();var De=["customer_data","coupon_code"],be=e.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Ve=e.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),_=(t,r)=>new Set(t.map(r)).size===t.length,ze=e.strictObject({currency:T,amountMinor:e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Ge=e.strictObject({featureId:e.uuid(),name:e.string().trim().min(1).max(120),allowance:e.string().max(40).nullable(),access:e.boolean()}),Me=e.strictObject({stripe:e.strictObject({prices:e.array(ze).min(1).max(50)}).optional(),apple:e.strictObject({productIds:e.array(be).min(1).max(10)}).optional(),google:e.strictObject({products:e.array(e.strictObject({productId:be,basePlanId:Ve.nullable()})).min(1).max(10)}).optional()}).superRefine((t,r)=>{(t.stripe&&!_(t.stripe.prices,a=>a.currency)||t.apple&&!_(t.apple.productIds,a=>a)||t.google&&!_(t.google.products,a=>`${a.productId}:${a.basePlanId}`))&&r.addIssue({code:"custom",message:"Duplicate channel entry"})}),qe=e.strictObject({name:e.string().trim().min(1).max(80),interval:e.enum(["free","week","month","year","one_time"]),intervalCount:e.number().int().min(1).max(100),trial:e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}).nullable(),benefits:e.array(Ge).max(50).refine(t=>_(t,r=>r.featureId),"Duplicate benefit"),channels:Me,prepaid:e.array(J).max(100).optional()}),Be=e.strictObject({digest:O,content:e.strictObject({discount:ne,duration:re,appliesTo:oe,displayCopy:ge.nullable(),firstPurchaseOnly:e.boolean(),qualificationRequired:e.boolean(),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),grantWindowHours:e.number().int().positive(),perCustomerLimit:e.number().int().positive()})}),Ne=e.discriminatedUnion("type",[e.strictObject({type:e.literal("checkout"),product:I}),e.strictObject({type:e.literal("close")}),e.strictObject({type:e.literal("action"),action:M})]),Lt=e.strictObject({kind:e.literal("paywall"),formatVersion:e.literal(1),name:e.string().trim().min(1).max(80),offeringVersionId:e.uuid(),presentation:S,screen:P,products:F,catalog:e.record(e.uuid(),qe),buttons:e.record(H,Ne),coupons:e.record(e.uuid(),Be)}).superRefine((t,r)=>{let a=n=>r.addIssue({code:"custom",message:n}),{screen:o}=t;ce(o,t.catalog).forEach(a),o.surface!=="paywall"&&a("Screen must be a Paywall"),ie(o,De).forEach(a),k(o).some(n=>!n.complete)&&a("Every published locale must be complete");let c=new Set,p=new Set,g=new Set;w(o,n=>{let b="bind"in n?n.bind:void 0;b?.promotionCode&&a("Promotion codes must not be published"),b?.plan&&c.add(b.plan),b?.coupon&&p.add(b.coupon),n.type==="plan_picker"&&(n.planIds?.forEach(x=>c.add(x)),n.defaultPlan&&c.add(n.defaultPlan)),n.type==="text"&&n.feature&&g.add(n.feature.id)});let f=t.products.items.map(n=>n.productVersionId),d=Object.keys(t.catalog);(f.length!==d.length||f.some(n=>!Object.hasOwn(t.catalog,n)))&&a("Catalog must contain exactly the displayed Products");let m=new Set(f);t.products.defaultProductVersionId!==null&&!m.has(t.products.defaultProductVersionId)&&a("Default Product must be displayed");for(let n of c)m.has(n)||a("Screen references a Product that is not displayed");for(let n of Object.values(t.catalog))!n.channels.stripe&&!n.channels.apple&&!n.channels.google&&a("A displayed Product needs at least one sales channel");let i=new Set(Object.values(t.catalog).flatMap(n=>n.benefits.map(b=>b.featureId)));for(let n of g)i.has(n)||a("Feature text must read a displayed benefit");let u=o.actions.filter(n=>n.type!=="navigate");o.actions.some(n=>n.type!=="event"&&n.type!=="navigate")&&a("Paywall actions are events or navigation"),(Object.keys(t.buttons).length!==u.length||u.some(n=>!Object.hasOwn(t.buttons,n.id)))&&a("Buttons must match the screen's actions");let y=!1;for(let n of Object.values(t.buttons)){if(n.type!=="checkout")continue;y=!0,(n.product.type==="fixed"?[n.product.productVersionId]:n.product.allowedProductVersionIds).some(x=>!m.has(x))&&a("Checkout may only sell displayed Products")}y||a("A Paywall needs a checkout button");let s=Object.keys(t.coupons);(s.length!==p.size||s.some(n=>!p.has(n)))&&a("Coupons must be exactly the bound Coupons")}),he=e.strictObject({state:e.enum(["published","archived"]),controlRevision:e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:e.uuid(),versions:e.record(e.uuid(),e.strictObject({version:e.number().int().positive(),artifact:e.string().min(1),sourceDigest:e.string().regex(/^[a-f0-9]{64}$/)}))}).refine(t=>Object.keys(t.versions).length>0,"Reviewed Paywall Versions are required");var $e={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},q=e.string().regex(/^[a-f0-9]{64}$/),B=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Le=j.extend({environmentId:e.uuid()}),xe=e.strictObject({features:e.array(e.string()).max(500),experiments:e.record(e.uuid(),e.array(e.string()).max(20)),savedGroups:e.array(e.string()).max(1e3)}),Ue=e.strictObject({kind:e.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:e.number().int().positive(),url:e.string().min(1).max(2048),sha256:q,byteLength:e.number().int().positive().max($e.maxArtifactBytes),generation:q.optional()}),Te=e.strictObject({state:e.enum(["active","paused","archived"]),controlRevision:B,evaluationMode:e.enum(["local","remote"]),evaluationRevision:B,currentVersionId:e.uuid(),versions:e.record(e.uuid(),e.strictObject({artifact:e.string(),dependencies:xe,definitionDigest:O.optional(),couponDigests:e.record(e.uuid(),O).optional()}))}),en=e.strictObject({kind:e.literal("sdk_configuration"),schemaVersion:e.literal(1),scope:Le,revision:B,generation:q,policy:e.strictObject({refreshIntervalSeconds:e.number().positive().max(15),maxControlAgeSeconds:e.number().positive().max(60)}),gb:e.strictObject({features:e.string().nullable(),pageExperiments:e.string().nullable()}),artifacts:e.record(e.string(),Ue),funnels:e.record(e.uuid(),Te),paywalls:e.record(e.uuid(),he).optional()}).superRefine((t,r)=>{let a=(o,c)=>{o!==null&&t.artifacts[o]?.kind!==c&&r.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};a(t.gb.features,"gb_features"),a(t.gb.pageExperiments,"gb_page_experiments");for(let o of Object.values(t.paywalls??{}))for(let c of Object.values(o.versions))a(c.artifact,"paywall");for(let o of Object.values(t.funnels)){o.evaluationMode==="remote"&&Object.keys(o.versions).length&&r.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),o.evaluationMode==="local"&&!o.versions[o.currentVersionId]&&r.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let c of Object.values(o.versions))a(c.artifact,"funnel")}});function N(t){if(Array.isArray(t))return`[${t.map(N).join(",")}]`;if(t!==null&&typeof t=="object")return`{${Object.entries(t).sort(([a],[o])=>a<o?-1:a>o?1:0).map(([a,o])=>`${JSON.stringify(a)}:${N(o)}`).join(",")}}`;let r=JSON.stringify(t);if(r===void 0)throw new Error("Configuration must contain JSON values");return r}function Je(t){return L(U(typeof t=="string"?new TextEncoder().encode(t):t))}function tn(t){return Je(N(t))}var $=class extends Error{constructor(a,o){super(a);this.dependency=o}dependency};function nn(t,r){let a=i=>i.type==="feature"?i.featureKey:i.type==="end"&&i.output?.type==="feature"?i.output.featureKey:i.type==="output"&&i.value.type==="feature"?i.value.featureKey:void 0,o=(i,u)=>t.graph.nodes.find(l=>i==="experiment"?l.type==="split"&&l.experimentId===u:i==="feature"&&a(l)===u)?.name,c=(i,u,l=o(u.type,u.resource))=>new $(i,{...u,...l?{step:l}:{}});for(let i of Object.values(t.references)){let u=i.type==="flag"?!Object.hasOwn(r.features,i.key)||r.remoteFeatures.includes(i.key)?{type:"feature",resource:i.key}:null:i.type==="experiment"?Object.hasOwn(r.experiments,i.id)?null:{type:"experiment",resource:i.id}:i.type==="saved_group"&&!Object.hasOwn(r.savedGroups,i.id)?{type:"saved_group",resource:i.id}:null;if(u)throw c("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...u})}let p=fe(t,{...r,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),g=new Set(r.remoteFeatures);for(let i of t.graph.nodes){let u=a(i);if(!u)continue;let l=p.features[u],y=i.type==="feature"?t.variables[i.writes.value]:t.outputSchema,s={type:"feature",resource:u};if(!l||!y)throw c("Required public Feature declaration is unavailable",{reason:"unavailable",...s},i.name);if([l.defaultValue,...(l.rules??[]).flatMap(b=>[...Object.hasOwn(b,"force")?[b.force]:[],...b.variations??[],...(b.tracks??[]).flatMap(x=>x.experiment.variations)])].some(b=>b===void 0||!ee(y,b)))throw c("GB Feature values violate the Funnel type contract",{reason:"value_type",...s},i.name)}let f=new Set,d=(i,u)=>{for(let l of A(i)){if(f.has(l))continue;let y=r.savedGroups[l];if(!y)throw c("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:l},u);f.add(l),!Array.isArray(y)&&y.type==="condition"&&d(y.condition,u)}},m=(i,u)=>{if(g.has(i)||!r.features[i])throw c("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:i},u)};for(let i of t.graph.nodes)if(i.type==="condition")for(let u of i.cases)d(u.condition,i.name);for(let[i,u]of Object.entries(p.features)){let l=o("feature",i);for(let y of u.rules??[]){d(y.condition,l);for(let s of[...y.parentConditions??[],...(y.tracks??[]).flatMap(n=>n.experiment.parentConditions??[])])m(s.id,l),d(s.condition,l);for(let s of y.tracks??[])d(s.experiment.condition,l)}}for(let[i,u]of Object.entries(p.experiments)){let l=o("experiment",i);d(u.condition,l);for(let y of u.parentConditions??[])m(y.id,l),d(y.condition,l)}for(let i of t.graph.nodes)if(i.type==="split"){let u=p.experiments[i.experimentId],l={type:"experiment",resource:i.experimentId};if(!u)throw c("Local Funnel requires a public Experiment",{reason:"unavailable",...l},i.name);for(let y of u.variations)if(typeof y!="string"||!Object.hasOwn(i.routes,y))throw c("Experiment variation has no declared Funnel route",{reason:"variation_route",...l},i.name)}return xe.parse({features:Object.keys(p.features).sort(),experiments:Object.fromEntries(Object.entries(p.experiments).map(([i,u])=>[i,u.variations.map(String)])),savedGroups:[...f].sort()})}function rn(t){return se.parse(t)}export{E as a,We as b,pe as c,Pe as d,v as e,ke as f,it as g,at as h,st as i,ct as j,ut as k,fe as l,Lt as m,$e as n,Le as o,Ue as p,en as q,N as r,Je as s,tn as t,nn as u,rn as v};
|
|
1
|
+
import{J as se,d as O,f as ie}from"./chunk-SEBMCCXY.js";import{a as F}from"./chunk-3I6OZU2J.js";import{b as te,f as ne,g as re,h as oe}from"./chunk-OILQZX5V.js";import{e as ee,k as ae}from"./chunk-OC3IODWG.js";import{s as ce}from"./chunk-2XX7L5VK.js";import{C as Y,e as J,j as Z,l as W,p as R,s as X,t as H,v as w,w as P,x as Q,z as k}from"./chunk-HN46A5SD.js";import{a as T,f as K}from"./chunk-VCRDA5R3.js";import{a as I,b as S,d as h,e as D,f as C,g as A}from"./chunk-GRY5G7X3.js";import{h as j}from"./chunk-FEZWUYEK.js";import{b as e}from"./chunk-TDOPU2RH.js";import{a as L,b as U}from"./chunk-CILM5XMH.js";var V=e.strictObject({eventsEnabled:e.boolean(),experimentViewsEnabled:e.boolean(),featureUsageEnabled:e.boolean()}),Ze=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function We(t,r){return r==="experiment_exposure"?t.experimentViewsEnabled:r==="feature_usage"?t.featureUsageEnabled:t.eventsEnabled}var z=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,r])=>t<=r),Se=e.strictObject({attribute:e.string().optional(),seed:e.string(),hashVersion:e.literal(2),ranges:e.array(z).max(100)}),we=e.strictObject({id:e.string().min(1).max(255),condition:C,gate:e.boolean().optional()}),Oe=e.strictObject({key:e.string().optional(),name:e.string().optional(),passthrough:e.boolean().optional()}),ue={condition:C.optional(),parentConditions:e.array(we).max(100).optional(),weights:e.array(e.number().min(0).max(1)).max(20).optional(),coverage:e.number().min(0).max(1).optional(),hashAttribute:e.string().optional(),fallbackAttribute:e.string().optional(),hashVersion:e.literal(2).optional(),disableStickyBucketing:e.boolean().optional(),bucketVersion:e.number().int().nonnegative().optional(),minBucketVersion:e.number().int().nonnegative().optional(),filters:e.array(Se).max(100).optional(),ranges:e.array(z).max(20).optional(),meta:e.array(Oe).max(20).optional(),seed:e.string().optional(),name:e.string().optional(),phase:e.string().optional()},pe=e.strictObject({...ue,key:e.string().min(1).max(255),variations:e.tuple([h,h]).rest(h).refine(t=>t.length<=20),urlPatterns:e.array(e.strictObject({include:e.boolean(),type:e.enum(["regex","simple"]),pattern:e.string()})).max(100).optional(),force:e.number().int().nonnegative().optional(),active:e.boolean().optional(),persistQueryString:e.boolean().optional()}),G=e.strictObject({value:h,variationId:e.number().int(),key:e.string(),name:e.string().optional(),bucket:e.number().optional(),passthrough:e.boolean().optional(),inExperiment:e.boolean(),hashUsed:e.boolean().optional(),hashAttribute:e.string(),hashValue:e.string(),featureId:e.string().nullable(),stickyBucketUsed:e.boolean().optional()}),je=e.strictObject({...ue,id:e.string().max(255).optional(),force:h.optional(),variations:e.array(h).min(2).max(20).optional(),key:e.string().optional(),range:z.optional(),tracks:e.array(e.strictObject({experiment:pe,result:G})).max(100).optional()}),Ie=e.strictObject({defaultValue:h.optional(),rules:e.array(je).max(500).optional()}),Pe=e.record(e.string(),e.union([e.strictObject({type:e.literal("hashed"),attributeKey:e.string(),values:e.array(e.string().regex(/^[a-f0-9]{64}$/))}),e.strictObject({type:e.literal("list"),attributeKey:e.string(),values:e.array(e.union([e.string(),e.number()]))}),e.strictObject({type:e.literal("condition"),condition:C})])),v=e.strictObject({scope:j,generation:e.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0}).nullable(),features:e.record(e.string(),Ie),savedGroups:Pe,experiments:e.record(e.uuid(),pe)});var ke=v.extend({analyticsConfig:V,remoteFeatures:e.array(e.string().min(1).max(255)).max(500)}),it=ke.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((t,r)=>{for(let a of t.remoteFeatures)Object.hasOwn(t.features,a)&&r.addIssue({code:"custom",path:["features",a],message:"Remote Feature definitions cannot be public"});for(let[a,o]of Object.entries(t.savedGroups))o.type==="list"&&r.addIssue({code:"custom",path:["savedGroups",a],message:"Raw Saved Group lists cannot be public"})}),at=e.strictObject({attributes:D,features:e.array(e.string().min(1).max(255)).max(500).optional(),customerId:e.uuid().optional()}),me=e.strictObject({value:h,source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:e.boolean(),off:e.boolean(),ruleId:e.string(),experimentResult:G.optional()}),st=e.strictObject({generation:v.shape.generation,evaluatedAt:v.shape.evaluatedAt,expiresAt:v.shape.expiresAt,features:e.record(e.string(),me),merchandiseContext:e.strictObject({merchandiseId:e.uuid(),merchandise:D}).optional()}),de={eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}),merchandise:te.optional(),deviceId:e.string().min(1).max(255).optional(),sessionId:e.string().min(1).max(255).optional()},le={...de,generation:v.shape.generation},Ce=e.discriminatedUnion("kind",[e.strictObject({...de,kind:e.literal("custom"),name:e.string().min(1).max(255),properties:e.record(e.string(),h).default({})}),e.strictObject({...le,kind:e.literal("experiment_exposure"),experimentId:e.string().min(1).max(255),variationId:e.string().min(1).max(255)}),e.strictObject({...le,kind:e.literal("feature_usage"),feature:e.string().min(1).max(255),value:h,source:me.shape.source,ruleId:e.string().max(255),variationId:e.string().min(1).max(255).optional()})]),ct=e.strictObject({customerId:e.uuid().optional(),events:e.array(Ce).min(1).max(100)}),Ae=e.strictObject({eventUuid:e.uuid(),reason:e.enum(["invalid_event","invalid_merchandise","not_delivered","reserved_name"])}),ut=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),rejected:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejections:e.array(Ae).max(100),analyticsConfig:V});function fe(t,r){let a=new Set,o=new Set,c=new Set,p=[],g=new Map,f=new Map,d=new Map;function m(s){for(let n of A(s))i(n)}function i(s){if(c.has(s)||!Object.hasOwn(r.savedGroups,s))return;let n=r.savedGroups[s];n&&(c.add(s),d.set(s,n),p.push(()=>{!Array.isArray(n)&&n.type==="condition"&&m(n.condition)}))}function u(s){for(let n of["hashAttribute","fallbackAttribute"])if(s[n]!==void 0&&ae(s[n]))throw new Error(`Funnel GB ${n} uses a reserved flow namespace`);m(s.condition);for(let n of s.parentConditions??[])l(n.id),m(n.condition)}function l(s,n=!1){let b=Object.hasOwn(r.features,s)?r.features[s]:void 0;if(!b){if(n)throw new Error("Required GB Feature is unavailable");return}a.has(s)||(a.add(s),g.set(s,b),p.push(()=>{for(let x of b.rules??[]){u(x);for(let ve of x.tracks??[])u(ve.experiment)}}))}function y(s){let n=Object.hasOwn(r.experiments,s)?r.experiments[s]:void 0;if(!n)throw new Error("Required GB Experiment is unavailable");o.has(s)||(o.add(s),f.set(s,n),p.push(()=>u(n)))}for(let s of t.graph.nodes){s.type==="feature"&&l(s.featureKey,!0),s.type==="split"&&y(s.experimentId),s.type==="condition"&&s.cases.forEach(b=>m(b.condition)),s.type==="offering"&&s.configuration.source==="feature"&&l(s.configuration.featureKey,!0);let n=s.type==="output"?s.value:s.type==="end"?s.output:null;n?.type==="feature"&&l(n.featureKey,!0)}for(let s of p)s();return{...r,features:Object.fromEntries(g),experiments:Object.fromEntries(f),savedGroups:Object.fromEntries(d)}}var ge=e.object({defaultLocale:R,locales:e.record(R,e.object({name:e.string().max(80),description:e.string().max(500)}).strict())}).strict().superRefine((t,r)=>{let a=Object.keys(t.locales);(!a.length||a.length>20||!t.locales[t.defaultLocale])&&r.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(t)).length>5e4&&r.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var M=e.discriminatedUnion("type",[e.strictObject({type:e.literal("event"),event:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),e.strictObject({type:e.literal("open_url"),url:e.url().refine(t=>new URL(t).protocol==="https:")})]),Fe=P,Ee=e.discriminatedUnion("type",[e.object({type:e.literal("checkout"),product:I}).strict(),e.object({type:e.literal("close")}).strict(),e.object({type:e.literal("action"),action:M}).strict()]),E=e.object({schemaVersion:e.literal(3),kind:e.literal("paywall"),name:e.string().trim().min(1).max(80),presentation:S,requirement:K.optional(),products:F,offeringVersionId:e.uuid().nullable(),offeringId:e.uuid(),screen:Fe,buttons:e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ee)}).strict(),Pt=E.superRefine((t,r)=>{(t.screen.surface!=="paywall"||t.screen.actions.some(o=>!["event","navigate"].includes(o.type)||o.close))&&r.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let o of Re(t))r.addIssue({code:"custom",message:o});for(let o of _e(t))r.addIssue({code:"custom",message:o});for(let o of t.screen.actions){let c=o.properties.closeControl;c!==void 0&&(c!=="content"||t.buttons[o.id]?.type!=="close")&&r.addIssue({code:"custom",path:["screen","actions",o.id],message:'Only a close button can carry closeControl, and its value is "content"'})}for(let o of t.screen.actions){let c=o.properties.couponBinding;c!==void 0&&(typeof c!="string"||!X.safeParse(c).success||t.buttons[o.id]?.type!=="checkout"||Y(t.screen,c)?.type!=="text")&&r.addIssue({code:"custom",path:["screen","actions",o.id],message:"Choose a Coupon text binding for this checkout action"})}k(t.screen).some(o=>!o.complete)&&r.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(t.buttons).length!==t.screen.actions.filter(o=>o.type!=="navigate").length||t.screen.actions.some(o=>o.type!=="navigate"&&!Object.hasOwn(t.buttons,o.id)))&&r.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(t.buttons).some(o=>o.type==="checkout")||r.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function _e(t){let r=t.products.items.map(p=>p.productVersionId),a=Z(t.screen),o=new Set,c=[];(!r.length||!t.products.defaultProductVersionId||!r.includes(t.products.defaultProductVersionId))&&c.push("products"),t.offeringVersionId||c.push("offering"),t.products.grouping&&(!W(t.products.grouping,r)||t.products.grouping.tiers.some(p=>!t.products.grouping.assignments.some(g=>g.tierId===p.id)))&&c.push("grouping");for(let p of Object.values(t.buttons))if(p.type==="checkout"){let g=p.product;if(g.type==="fixed")o.add(g.productVersionId);else{g.allowedProductVersionIds.forEach(m=>o.add(m));let f=!1,d=a[g.pickerId];d&&(f=!0,(g.allowedProductVersionIds.some(m=>!d.ids.includes(m))||d.ids.some(m=>!g.allowedProductVersionIds.includes(m)))&&c.push("picker")),w(t.screen,m=>{if(m.id!==g.pickerId||m.type!=="plan_picker")return;f=!0,(JSON.stringify(m.planIds)!==JSON.stringify(r)||JSON.stringify(g.allowedProductVersionIds)!==JSON.stringify(r)||m.defaultPlan!==t.products.defaultProductVersionId)&&c.push("picker");let i=m.grouping?{tiers:m.grouping.tiers,assignments:m.grouping.assignments}:void 0;JSON.stringify(i)!==JSON.stringify(t.products.grouping)&&c.push("grouping")}),f||c.push("picker")}}return(!o.size||[...o].some(p=>!r.includes(p)))&&c.push("purchase"),w(t.screen,p=>{p.type==="stack"&&p.productSlot&&!p.bind?.plan&&c.push(`productBinding:${p.id}`),(p.type==="stack"||p.type==="button")&&p.bind?.plan&&!r.includes(p.bind.plan)&&c.push("binding"),p.type==="plan_picker"&&(!p.planIds?.length||p.planIds.some(g=>!r.includes(g)))&&c.push("binding")}),[...new Set(c)]}function Re(t){let r=[],a=t.screen.pages.at(-1),o=new Map;for(let f of t.screen.pages)o.set(f.id,[]),Q(f.root,d=>{let m=d.type==="button"?d.action:d.type==="stack"?d.purchaseAction:void 0;if(m){let i=t.screen.actions.find(l=>l.id===m);i?.type==="navigate"&&o.get(f.id).push(i.pageId);let u=t.buttons[m];f.id!==a.id&&u&&u.type!=="close"&&r.push(`purchaseScreen:${d.id}`)}f.id!==a.id&&(d.type==="plan_picker"||d.type==="stack"&&d.productSlot)&&r.push(`packageScreen:${d.id}`)});let c=new Set;function p(f){if(!c.has(f)){c.add(f);for(let d of o.get(f)??[])p(d)}}let g=t.screen.initialPageId??t.screen.pages[0]?.id;g?p(g):r.push("initialPage");for(let f of t.screen.pages)c.has(f.id)||r.push(`unreachableScreen:${f.id}`);return[...new Set(r)]}var ye=e.object({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),revision:e.number().int().nonnegative(),state:e.enum(["active","archived"]),publishedVersionId:e.uuid().nullable(),updatedAt:e.iso.datetime({offset:!0}),draft:E}).strict(),kt=e.object({rows:e.array(ye).max(200),nextCursor:e.uuid().nullable()}).strict(),Ct=ye.omit({draft:!0}).extend({name:e.string(),productCount:e.number().int().nonnegative()}).strict(),At=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),document:E}).strict(),e.object({action:e.enum(["publish","archive"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Ft=e.object({paywalls:e.array(e.object({id:e.uuid(),paywallId:e.uuid(),version:e.number().int().positive(),name:e.string().min(1).max(80),presentation:S,buttons:E.shape.buttons}).strict()).max(500),limited:e.boolean()}).strict();var De=["customer_data","coupon_code"],be=e.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Ve=e.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),_=(t,r)=>new Set(t.map(r)).size===t.length,ze=e.strictObject({currency:T,amountMinor:e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Ge=e.strictObject({featureId:e.uuid(),name:e.string().trim().min(1).max(120),allowance:e.string().max(40).nullable(),access:e.boolean()}),Me=e.strictObject({stripe:e.strictObject({prices:e.array(ze).min(1).max(50)}).optional(),apple:e.strictObject({productIds:e.array(be).min(1).max(10)}).optional(),google:e.strictObject({products:e.array(e.strictObject({productId:be,basePlanId:Ve.nullable()})).min(1).max(10)}).optional()}).superRefine((t,r)=>{(t.stripe&&!_(t.stripe.prices,a=>a.currency)||t.apple&&!_(t.apple.productIds,a=>a)||t.google&&!_(t.google.products,a=>`${a.productId}:${a.basePlanId}`))&&r.addIssue({code:"custom",message:"Duplicate channel entry"})}),qe=e.strictObject({name:e.string().trim().min(1).max(80),interval:e.enum(["free","week","month","year","one_time"]),intervalCount:e.number().int().min(1).max(100),trial:e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}).nullable(),benefits:e.array(Ge).max(50).refine(t=>_(t,r=>r.featureId),"Duplicate benefit"),channels:Me,prepaid:e.array(J).max(100).optional()}),Be=e.strictObject({digest:O,content:e.strictObject({discount:ne,duration:re,appliesTo:oe,displayCopy:ge.nullable(),firstPurchaseOnly:e.boolean(),qualificationRequired:e.boolean(),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),grantWindowHours:e.number().int().positive(),perCustomerLimit:e.number().int().positive()})}),Ne=e.discriminatedUnion("type",[e.strictObject({type:e.literal("checkout"),product:I}),e.strictObject({type:e.literal("close")}),e.strictObject({type:e.literal("action"),action:M})]),Lt=e.strictObject({kind:e.literal("paywall"),formatVersion:e.literal(1),name:e.string().trim().min(1).max(80),offeringVersionId:e.uuid(),presentation:S,screen:P,products:F,catalog:e.record(e.uuid(),qe),buttons:e.record(H,Ne),coupons:e.record(e.uuid(),Be)}).superRefine((t,r)=>{let a=n=>r.addIssue({code:"custom",message:n}),{screen:o}=t;ce(o,t.catalog).forEach(a),o.surface!=="paywall"&&a("Screen must be a Paywall"),ie(o,De).forEach(a),k(o).some(n=>!n.complete)&&a("Every published locale must be complete");let c=new Set,p=new Set,g=new Set;w(o,n=>{let b="bind"in n?n.bind:void 0;b?.promotionCode&&a("Promotion codes must not be published"),b?.plan&&c.add(b.plan),b?.coupon&&p.add(b.coupon),n.type==="plan_picker"&&(n.planIds?.forEach(x=>c.add(x)),n.defaultPlan&&c.add(n.defaultPlan)),n.type==="text"&&n.feature&&g.add(n.feature.id)});let f=t.products.items.map(n=>n.productVersionId),d=Object.keys(t.catalog);(f.length!==d.length||f.some(n=>!Object.hasOwn(t.catalog,n)))&&a("Catalog must contain exactly the displayed Products");let m=new Set(f);t.products.defaultProductVersionId!==null&&!m.has(t.products.defaultProductVersionId)&&a("Default Product must be displayed");for(let n of c)m.has(n)||a("Screen references a Product that is not displayed");for(let n of Object.values(t.catalog))!n.channels.stripe&&!n.channels.apple&&!n.channels.google&&a("A displayed Product needs at least one sales channel");let i=new Set(Object.values(t.catalog).flatMap(n=>n.benefits.map(b=>b.featureId)));for(let n of g)i.has(n)||a("Feature text must read a displayed benefit");let u=o.actions.filter(n=>n.type!=="navigate");o.actions.some(n=>n.type!=="event"&&n.type!=="navigate")&&a("Paywall actions are events or navigation"),(Object.keys(t.buttons).length!==u.length||u.some(n=>!Object.hasOwn(t.buttons,n.id)))&&a("Buttons must match the screen's actions");let y=!1;for(let n of Object.values(t.buttons)){if(n.type!=="checkout")continue;y=!0,(n.product.type==="fixed"?[n.product.productVersionId]:n.product.allowedProductVersionIds).some(x=>!m.has(x))&&a("Checkout may only sell displayed Products")}y||a("A Paywall needs a checkout button");let s=Object.keys(t.coupons);(s.length!==p.size||s.some(n=>!p.has(n)))&&a("Coupons must be exactly the bound Coupons")}),he=e.strictObject({state:e.enum(["published","archived"]),controlRevision:e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:e.uuid(),versions:e.record(e.uuid(),e.strictObject({version:e.number().int().positive(),artifact:e.string().min(1),sourceDigest:e.string().regex(/^[a-f0-9]{64}$/)}))}).refine(t=>Object.keys(t.versions).length>0,"Reviewed Paywall Versions are required");var $e={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},q=e.string().regex(/^[a-f0-9]{64}$/),B=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Le=j.extend({environmentId:e.uuid()}),xe=e.strictObject({features:e.array(e.string()).max(500),experiments:e.record(e.uuid(),e.array(e.string()).max(20)),savedGroups:e.array(e.string()).max(1e3)}),Ue=e.strictObject({kind:e.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:e.number().int().positive(),url:e.string().min(1).max(2048),sha256:q,byteLength:e.number().int().positive().max($e.maxArtifactBytes),generation:q.optional()}),Te=e.strictObject({state:e.enum(["active","paused","archived"]),controlRevision:B,evaluationMode:e.enum(["local","remote"]),evaluationRevision:B,currentVersionId:e.uuid(),versions:e.record(e.uuid(),e.strictObject({artifact:e.string(),dependencies:xe,definitionDigest:O.optional(),couponDigests:e.record(e.uuid(),O).optional()}))}),en=e.strictObject({kind:e.literal("sdk_configuration"),schemaVersion:e.literal(1),scope:Le,revision:B,generation:q,policy:e.strictObject({refreshIntervalSeconds:e.number().positive().max(15),maxControlAgeSeconds:e.number().positive().max(60)}),gb:e.strictObject({features:e.string().nullable(),pageExperiments:e.string().nullable()}),artifacts:e.record(e.string(),Ue),funnels:e.record(e.uuid(),Te),paywalls:e.record(e.uuid(),he).optional()}).superRefine((t,r)=>{let a=(o,c)=>{o!==null&&t.artifacts[o]?.kind!==c&&r.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};a(t.gb.features,"gb_features"),a(t.gb.pageExperiments,"gb_page_experiments");for(let o of Object.values(t.paywalls??{}))for(let c of Object.values(o.versions))a(c.artifact,"paywall");for(let o of Object.values(t.funnels)){o.evaluationMode==="remote"&&Object.keys(o.versions).length&&r.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),o.evaluationMode==="local"&&!o.versions[o.currentVersionId]&&r.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let c of Object.values(o.versions))a(c.artifact,"funnel")}});function N(t){if(Array.isArray(t))return`[${t.map(N).join(",")}]`;if(t!==null&&typeof t=="object")return`{${Object.entries(t).sort(([a],[o])=>a<o?-1:a>o?1:0).map(([a,o])=>`${JSON.stringify(a)}:${N(o)}`).join(",")}}`;let r=JSON.stringify(t);if(r===void 0)throw new Error("Configuration must contain JSON values");return r}function Je(t){return L(U(typeof t=="string"?new TextEncoder().encode(t):t))}function tn(t){return Je(N(t))}var $=class extends Error{constructor(a,o){super(a);this.dependency=o}dependency};function nn(t,r){let a=i=>i.type==="feature"?i.featureKey:i.type==="end"&&i.output?.type==="feature"?i.output.featureKey:i.type==="output"&&i.value.type==="feature"?i.value.featureKey:void 0,o=(i,u)=>t.graph.nodes.find(l=>i==="experiment"?l.type==="split"&&l.experimentId===u:i==="feature"&&a(l)===u)?.name,c=(i,u,l=o(u.type,u.resource))=>new $(i,{...u,...l?{step:l}:{}});for(let i of Object.values(t.references)){let u=i.type==="flag"?!Object.hasOwn(r.features,i.key)||r.remoteFeatures.includes(i.key)?{type:"feature",resource:i.key}:null:i.type==="experiment"?Object.hasOwn(r.experiments,i.id)?null:{type:"experiment",resource:i.id}:i.type==="saved_group"&&!Object.hasOwn(r.savedGroups,i.id)?{type:"saved_group",resource:i.id}:null;if(u)throw c("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...u})}let p=fe(t,{...r,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),g=new Set(r.remoteFeatures);for(let i of t.graph.nodes){let u=a(i);if(!u)continue;let l=p.features[u],y=i.type==="feature"?t.variables[i.writes.value]:t.outputSchema,s={type:"feature",resource:u};if(!l||!y)throw c("Required public Feature declaration is unavailable",{reason:"unavailable",...s},i.name);if([l.defaultValue,...(l.rules??[]).flatMap(b=>[...Object.hasOwn(b,"force")?[b.force]:[],...b.variations??[],...(b.tracks??[]).flatMap(x=>x.experiment.variations)])].some(b=>b===void 0||!ee(y,b)))throw c("GB Feature values violate the Funnel type contract",{reason:"value_type",...s},i.name)}let f=new Set,d=(i,u)=>{for(let l of A(i)){if(f.has(l))continue;let y=r.savedGroups[l];if(!y)throw c("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:l},u);f.add(l),!Array.isArray(y)&&y.type==="condition"&&d(y.condition,u)}},m=(i,u)=>{if(g.has(i)||!r.features[i])throw c("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:i},u)};for(let i of t.graph.nodes)if(i.type==="condition")for(let u of i.cases)d(u.condition,i.name);for(let[i,u]of Object.entries(p.features)){let l=o("feature",i);for(let y of u.rules??[]){d(y.condition,l);for(let s of[...y.parentConditions??[],...(y.tracks??[]).flatMap(n=>n.experiment.parentConditions??[])])m(s.id,l),d(s.condition,l);for(let s of y.tracks??[])d(s.experiment.condition,l)}}for(let[i,u]of Object.entries(p.experiments)){let l=o("experiment",i);d(u.condition,l);for(let y of u.parentConditions??[])m(y.id,l),d(y.condition,l)}for(let i of t.graph.nodes)if(i.type==="split"){let u=p.experiments[i.experimentId],l={type:"experiment",resource:i.experimentId};if(!u)throw c("Local Funnel requires a public Experiment",{reason:"unavailable",...l},i.name);for(let y of u.variations)if(typeof y!="string"||!Object.hasOwn(i.routes,y))throw c("Experiment variation has no declared Funnel route",{reason:"variation_route",...l},i.name)}return xe.parse({features:Object.keys(p.features).sort(),experiments:Object.fromEntries(Object.entries(p.experiments).map(([i,u])=>[i,u.variations.map(String)])),savedGroups:[...f].sort()})}function rn(t){return se.parse(t)}export{E as a,We as b,pe as c,Pe as d,v as e,ke as f,it as g,at as h,st as i,ct as j,ut as k,fe as l,Lt as m,$e as n,Le as o,Ue as p,en as q,N as r,Je as s,tn as t,nn as u,rn as v};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as C}from"./chunk-
|
|
1
|
+
import{a as C}from"./chunk-YRVK3UDS.js";import{a as I}from"./chunk-CKUMSWUN.js";import{h as v}from"./chunk-OJ6CPUN4.js";import{b as g}from"./chunk-3I6OZU2J.js";import{t as b}from"./chunk-2XX7L5VK.js";import{a as d}from"./chunk-355B3KPL.js";async function T(s,t){if(!s.closest("dialog")?.open)return null;let r=AbortSignal.any([t.signal,t.client.identitySignal]);r.throwIfAborted();let o=t.operationId?await t.client.recoverPurchasePaywall(void 0,t.operationId):await t.client.recoverPurchasePaywall();if(!o)return null;let c=o.view;if(!c||c.document.presentation.type!=="modal"||r.aborted)return o.destroy(),null;let l=t.upgradeReplacement,{session:h,prepare:y}=A({client:t.client,session:o,start:l?.start,signal:r}),p=v(s);if(!p)return o.destroy(),null;let n,i=new Promise(e=>{n=e}),w=!1,u=()=>n(!1);r.addEventListener("abort",u,{once:!0});try{let{host:e}=await C(s,{signal:r,start:async()=>h,loading:"host",checkoutNavigation:"after_confirmation",allowNewPurchase:!1,...l&&{beforeCheckoutReplacement:l.beforeCheckoutReplacement,resolveOfferId:l.resolveOfferId,resolveSubscriptionChange:l.resolveSubscriptionChange,terminateCheckout:a=>t.client.terminateCheckout(a),prepareUpgradeReplacement:y},resumeCheckout:a=>t.client.continueCheckout(t.onCheckoutUrl,a),onComplete:t.onComplete,onError(a){w?t.onError?.(a):n(!1)}},{retainedDialog:p,present(a){a(!0),w=!0,n(!0)},async dismiss(){t.onDismiss()}});return!e||!await i||r.aborted?(e?.destroy(),null):{document:c.document,destroy:()=>e.destroy()}}finally{r.removeEventListener("abort",u)}}function A(s){let t=s.start;if(!t)return{session:s.session};let{client:m,signal:r}=s,o=s.session,c=o,l;return{session:new Proxy(o,{get(p,n){let i=c[n];return typeof i=="function"?i.bind(c):i}}),prepare:async(p,n)=>{if(r.throwIfAborted(),o.operation?.operationId!==p||!o.canReselect)throw new d("PURCHASE_PENDING","The original purchase has not been closed");if(!l){let e=await t();if(!e)throw new d("PRODUCT_UNAVAILABLE","The selected plan is unavailable");l={...e,requestId:e.requestId??crypto.randomUUID()}}r.throwIfAborted();let i=await m.start(l),w=m.controller;if(i.mode!=="run"||i.status!=="ready"||!w?.view?.paywall)throw new d("PURCHASE_PENDING","The current Paywall could not be opened for the replacement");let u=await I(w);try{r.throwIfAborted();let e=u.view,a=e?.document.buttons[n.actionId],f=e&&a?.type==="checkout"?g(a.product,n.selection,e.capabilities):null;if(!e||f!==n.productVersionId)throw new d("PRODUCT_UNAVAILABLE","The selected plan is no longer available");let P=b(e.document.screen,f,n.selection,e.capabilities);if(Object.keys(P).length!==Object.keys(n.featureQuantities).length||Object.entries(P).some(([S,k])=>n.featureQuantities[S]!==k))throw new d("PRODUCT_UNAVAILABLE","The selected plan quantities have changed");return c=u,o.destroy(),e}catch(e){throw u.destroy(),e}}}}export{T as a,A as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as n}from"./chunk-
|
|
1
|
+
import{a as n}from"./chunk-355B3KPL.js";function o(r,e){try{return r.parse(e)}catch{throw new n("INVALID_RESPONSE","Invalid gateway response")}}export{o as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as ge,E as it,b as He,c as Ke,d as Ee,h as Ye,i as We,j as Qe,n as Xe,q as tt,z as ot}from"./chunk-BQFIJCBA.js";import{a as rt}from"./chunk-BANN2HQH.js";import{c as _e,d as Le,e as De,f as Ue,g as Ve,i as Me,m as Ge,n as M,o as Be,q as be,r as _,s as ze,t as $e,u as Je,v as qe}from"./chunk-BT7IC765.js";import{K as U,e as ke,q as Se,r as je}from"./chunk-ME6QTD5Y.js";import{a as pe,b as et}from"./chunk-55B6CYG6.js";import{a as fe}from"./chunk-KCUE2VFJ.js";import{e as me}from"./chunk-A5WUQLAO.js";import{a as D}from"./chunk-UGATOG2T.js";import{h as ie}from"./chunk-LFR2LWYC.js";import{b as nt}from"./chunk-3VUPVXAV.js";import{a as Ze}from"./chunk-5MRSFLQA.js";import{b as n}from"./chunk-W22ESUYY.js";import{c as Ne,f as Te}from"./chunk-FYMVNLQN.js";var j=n.literal(ke),vt=n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=n.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),at=n.discriminatedUnion("type",[n.strictObject({type:n.literal("guest"),guestToken:xe}),n.strictObject({type:n.literal("customer"),customer:Se,customerData:je.optional()})]),Ae=n.strictObject({id:n.uuid(),runId:n.uuid(),customerId:n.uuid(),requestId:n.uuid(),acceptedAt:n.iso.datetime({offset:!0})}),St=n.strictObject({participantId:n.uuid(),startedAs:n.enum(["guest","identified"]),binding:Ae.omit({runId:!0,requestId:!0}).nullable()}),bt=n.union([He,n.strictObject({type:n.literal("authentication_required"),reason:n.enum(["customer_required","customer_experiment_required"]),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative()})]),Et=Ke.omit({authenticated:!0}).extend({identity:St,instruction:bt.nullable()}),xt=n.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),he={contract:j,customerToken:n.string().regex(fe)},st={contract:j,requestId:n.uuid(),runToken:vt,externalUserId:Se.options[1].shape.value},ut=n.discriminatedUnion("operation",[n.strictObject({contract:j,operation:n.literal("describe")}),n.strictObject({contract:j,operation:n.literal("start"),source:at,funnelId:U.options[0].shape.funnelId,requestId:n.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),Ye.omit({operation:!0}).extend({contract:j,operation:n.literal("entry_start"),source:at}),n.strictObject({...st,operation:n.literal("bind_customer"),guestToken:xe,claimRequestId:n.uuid(),expectedBindingId:n.null()}),n.strictObject({...st,operation:n.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...he,operation:n.literal("get"),settlementBindingId:n.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...he,operation:n.literal("review")}),Qe.omit({customerToken:!0}).extend(he),n.strictObject({...he,operation:n.literal("command"),identity:n.strictObject({bindingId:n.uuid().nullable()}),command:xt})]),At=Ee.omit({run:!0}).extend({contract:j,run:Et,settlement:Ee.shape.settlement.unwrap().extend({accepted:n.boolean().nullable().optional()}).optional()}),Gt=We.extend({contract:j}),Bt=n.discriminatedUnion("operation",[ut.options[1].omit({contract:!0,source:!0,requestId:!0}),ut.options[2].omit({contract:!0,source:!0,requestId:!0})]),zt=At.extend({binding:Ae,outcome:n.enum(["bound","already_bound"]),replayed:n.boolean()}),$t=n.discriminatedUnion("state",[n.strictObject({contract:j,scope:ie,state:n.literal("not_accepted")}),n.strictObject({contract:j,scope:ie,state:n.literal("conflict")}),n.strictObject({contract:j,scope:ie,state:n.literal("bound"),binding:Ae})]),Jt=n.strictObject({contract:j,scope:ie,keyId:n.uuid(),operations:n.array(n.string()).max(20)});var ct=n.string().regex(/^[a-f0-9]{64}$/),Ct=_e.omit({variations:!0,active:!0}).extend({changeId:ct,variations:n.array(n.strictObject({urlRedirect:n.string().max(2048)})).min(2).max(20)}),lt=n.strictObject({environmentId:n.uuid(),trackExposures:n.boolean(),generation:ct,experiments:n.array(Ct).max(100),savedGroups:Le}),Pt=n.strictObject({eventUuid:n.uuid(),timestamp:n.iso.datetime({offset:!0}).optional(),deviceId:n.string().min(1).max(128),sessionId:n.string().min(1).max(128).optional(),url:n.url().max(2048),pageTitle:n.string().max(512).optional(),experimentKey:n.string().min(1).max(255),variationKey:n.string().min(1).max(64)}),Yt=n.strictObject({events:n.array(Pt).min(1).max(20)}),Wt=n.strictObject({inserted:n.number().int().nonnegative(),duplicates:n.number().int().nonnegative(),skipped:n.number().int().nonnegative(),rejected:n.array(n.strictObject({index:n.number().int().nonnegative(),reason:n.string()}))});function nn(i){let a=null,g=null,x=0,I=0,v=new Set,d=null,y=null,m=new Set,S=()=>{for(let s of m)try{s()}catch{}},p={attributes:me.parse(i.attributes??{}),onFeatureUsage:i.onFeatureUsage?(s,E)=>{!v.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&i.onFeatureUsage(s,structuredClone(E),structuredClone(p.attributes),a.generation)}:void 0,onExperimentViewed:i.onExperimentViewed?(s,E)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&i.onExperimentViewed(structuredClone(s),structuredClone(E),structuredClone(p.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(i.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:i.saveStickyBucketAssignmentDoc?s=>i.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},A=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,E=new Set){return v.has(s)?!d||!d.features[s]||["unknownFeature","cyclicPrerequisite"].includes(d.features[s].source):E.has(s)?!1:(E.add(s),(a?.features[s]?.rules??[]).some(O=>[...O.parentConditions??[],...(O.tracks??[]).flatMap(F=>F.experiment.parentConditions??[])].some(F=>h(F.id,E))))}let C=s=>{if(i.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return d?.expiresAt&&Date.parse(d.expiresAt)<=Date.now()&&(d=null,p.features=a.features),v.has(s)?!d||d.expiresAt&&Date.parse(d.expiresAt)<=Date.now()?A():structuredClone(d.features[s]??A()):i.evaluateRemote&&(p.attributes?.merchandise||p.attributes?.merchandiseId)&&!d||h(s)?A():structuredClone(Te(s,p))};async function V(){if(!a||!v.size&&!p.attributes?.merchandise&&!p.attributes?.merchandiseId)return;if(!i.evaluateRemote){if(v.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=I;if(y?.revision===s)return y.loading;let E=x,O=a,F=[...v],P=(async()=>{let b=Me.parse(await i.evaluateRemote({attributes:structuredClone(p.attributes),features:F}));if(!(E!==x||s!==I||O!==a)){if(i.assertUsable?.(O.generation),b.generation!==O.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(F.some(T=>!Object.hasOwn(b.features,T))||Object.keys(b.features).some(T=>!v.has(T)))throw new Error("Invalid remote Feature results");if(p.attributes?.merchandise||p.attributes?.merchandiseId){if(!b.merchandiseContext)throw new Error("Server did not resolve merchandise context");p.attributes=me.parse({...p.attributes,...b.merchandiseContext})}d=structuredClone(b),p.features={...O.features,...Object.fromEntries(Object.entries(d.features).map(([T,$])=>[T,{defaultValue:$.value}]))},S()}})();y={revision:s,loading:P};try{await P}finally{y?.loading===P&&(y=null)}}function L(){V().catch(s=>{try{i.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=x,E=(async()=>{let O=await i.load(),F="remoteFeatures"in O?Ue.parse(O):null,P=F??De.parse(O);if(P.scope.projectId!==i.scope.projectId||P.scope.environment!==i.scope.environment)throw new Error("Feature payload scope changed");if(s!==x)throw new Error("Feature client was reset");if(i.assertUsable&&a?.generation===P.generation){let{evaluatedAt:T,expiresAt:$,...ae}=a,{evaluatedAt:X,expiresAt:ye,...G}=P;if(_(ae)!==_(G))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=P.evaluatedAt,a.expiresAt=P.expiresAt,S(),(!d||d.expiresAt&&Date.parse(d.expiresAt)<=Date.now())&&L(),structuredClone(a)}let b=new Set(F?.remoteFeatures??[]);if([...b].some(T=>Object.hasOwn(P.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in P&&!a.analyticsConfig.experimentViewsEnabled&&F?.analyticsConfig.experimentViewsEnabled&&p.trackedExperiments?.clear(),a=structuredClone(P),v=b,d=null,y=null,I++,p.features=a.features,p.savedGroups=Ne(a.savedGroups),p.trackedFeatureUsage={},S(),L(),structuredClone(a)})();g=E;try{return await E}finally{g===E&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let E=me.parse(s);(p.attributes?.merchandise||p.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&p.trackedExperiments?.clear(),p.attributes=E,I++,d=null,y=null,p.features=a?.features??{},p.trackedFeatureUsage={},S(),L()},evalFeature:C,isOn(s){return C(s).on},isOff(s){return C(s).off},getFeatureValue(s,E){let O=C(s).value;return structuredClone(O===null?E:O)},reset(){x++,I++,g=null,y=null,a=null,d=null,v.clear(),p.features={},p.savedGroups={},p.stickyBucketAssignmentDocs={},p.attributes={},p.trackedFeatureUsage={},p.trackedExperiments?.clear(),S()}}}var Rt=n.record(n.string().regex(/^[a-f0-9]{64}$/),n.strictObject({at:n.number(),text:n.string()})),Q=2*1048576,Ot=100;function Ft(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function dt(i,a){let g=a===void 0?Ft():a,x=new Map,I=0,v=!1,d=!1,y,m;async function S(A){if(!g)return null;let h;try{let C=await Promise.race([Promise.resolve().then(()=>g.getItem(A)),new Promise(V=>{h=setTimeout(()=>V(null),Ot)})]);return typeof C=="string"&&C.length<=Q&&new TextEncoder().encode(C).byteLength<=Q?C:null}catch{return null}finally{clearTimeout(h)}}function p(){if(m)return m;let A=(async()=>{try{let h=await S(`${i}:artifacts`);if(h)return Rt.parse(JSON.parse(h))}catch{}return{}})();return m=A,A.finally(()=>{m===A&&(m=void 0)}),A}return{async readManifest(){return S(i)},writeManifest(A){!g||A.length>Q||new TextEncoder().encode(A).byteLength>Q||(y=A,!d&&(d=!0,Promise.resolve().then(async()=>{try{for(;y!==void 0;){let h=y;try{await g.setItem(i,h)}catch{}y===h&&(y=void 0)}}finally{d=!1}})))},async readArtifact(A){let h=(await p())[A],C=Date.now();return h&&C>=h.at&&C-h.at<=M.retentionMs?h.text:void 0},writeArtifact(A,h){if(!g||h.length>Q)return;let C=x.get(A);if(C?.text===h||!C&&x.size>=128)return;let V=new TextEncoder().encode(h).byteLength;I-(C?.byteLength??0)+V>Q||(x.set(A,{text:h,byteLength:V}),I+=V-(C?.byteLength??0),!v&&(v=!0,Promise.resolve().then(async()=>{try{for(;x.size;){let L=new Map(x);try{let k={...await p()},s=Date.now();for(let[P,b]of L)k[P]={at:s,text:b.text};let E={},O=2,F=0;for(let[P,b]of Object.entries(k).sort(([,T],[,$])=>$.at-T.at)){if(b.at>s||s-b.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[P]:b})).byteLength;O+T>Q||F>=128||(E[P]=b,O+=T,F++)}await g.setItem(`${i}:artifacts`,JSON.stringify(E))}catch{}finally{for(let[k,s]of L)x.get(k)===s&&(x.delete(k),I-=s.byteLength)}}}finally{v=!1}})))}}}var c=(i,a)=>new D(i,a),z=()=>performance.now(),ft=i=>{typeof i=="object"&&"unref"in i&&i.unref()},Nt=12e4;function Tt(i,a,g,x){let I=Object.entries(x.paywalls??{}),v={};for(let d of g.screens){if(d.type!=="paywall")continue;let y=I.find(([,S])=>Object.hasOwn(S.versions,d.paywallVersionId))?.[0];if(!y)continue;let m=v[y]??=[];m.includes(d.paywallVersionId)||m.push(d.paywallVersionId)}for(let d of Object.values(v))d.sort();return{kind:"funnel_paywall_pins",formatVersion:1,funnelId:i,versionId:a,paywalls:v}}function vn(i){let a=Be.parse(i.scope),g=new pe(i.origin??Ze);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw c("INVALID_URL","Configuration requires a trusted HTTPS origin");let x=new Set([g.origin,...(i.assetOrigins??[]).map(e=>{let t=new pe(e);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw c("INVALID_URL","Invalid configuration asset origin");return t.origin})]),I=i.fetch??globalThis.fetch.bind(globalThis),v=`/api/v1/configuration/${a.environmentId}`,d=`indiana:configuration:1:${g.origin}:${_(a)}`,y=dt(d,i.storage),m,S=0,p=0,A=!1,h=!1,C=0,V=0,L,k,s,E,O=0,F=new Set,P=new Set,b=new Map,T=new Map,$=0,ae=!1;function X(){for(let e of F)try{e()}catch{}}function ye(e){try{i.onError?.(e)}catch{}}let G=()=>!h&&!A&&!!m&&z()<S&&Date.now()<p;function re(){if(!G())throw c("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(e,t,o){if(!b.has(e)){for(;b.size&&(b.size>=128||$+o>M.maxCacheBytes);){let r=b.entries().next().value;$-=r[1].byteLength,b.delete(r[0])}b.set(e,{text:t,byteLength:o}),$+=o}}function we(e,t,o){return nt(e,t,{signal:o,error:r=>c("INVALID_RESPONSE",r==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function Ie(e){let t=new pe(e,g);if(!x.has(t.origin)||t.username||t.password||t.hash||t.search)throw c("INVALID_URL","Configuration artifact origin is not trusted");return t.href}async function ve(e,t,o=!1){let r=await I(Ie(e),{method:"GET",credentials:"omit",redirect:"error",cache:o?"default":"no-cache",signal:t,headers:{}});if(r.status===429){let u=r.headers.get("retry-after")??"";O=/^\d+$/.test(u)?Number(u)*1e3:Math.max(0,Date.parse(u)-Date.now())||15e3}if(!r.ok&&r.status!==304)throw c(`CONFIGURATION_HTTP_${r.status}`,"Configuration synchronization failed");return r}function pt(e,t,o){let r=Date.parse(e.headers.get("x-indiana-config-validated-at")??""),u=Date.parse(e.headers.get("x-indiana-config-valid-until")??""),f=Date.parse(e.headers.get("date")??""),l=e.headers.get("age"),w=l!==null&&/^\d+(\.\d+)?$/.test(l)?Number(l)*1e3:NaN;if(![r,u,f,w].every(Number.isFinite)||u<=r||u-r>M.maxControlAgeMs||r>f+1e3)throw c("INVALID_RESPONSE","Configuration freshness evidence is invalid");let R=Math.min(u-r,o.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(w,f-r,0)-(z()-t);if(R<=0)throw c("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return z()+R}function se(){if(clearTimeout(s),clearTimeout(E),h||!F.size||(G()&&(E=setTimeout(()=>{G()?se():X()},Math.max(1,S-z())),ft(E)),typeof document<"u"&&document.visibilityState==="hidden"))return;let e=Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3),t=V>2?Math.min(Nt,e*2**(V-2)):e;s=setTimeout(()=>{Z().catch(ye)},Math.max(O,t*(.8+Math.random()*.2))),ft(s)}async function Z(){if(h)throw c("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let e=C,t=new AbortController;k=t;let o=(async()=>{if(!ae){ae=!0;try{let de=await y.readManifest();if(de&&!m){let q=be.parse(JSON.parse(de));_(q.scope)===_(a)&&(m=q)}}catch{}}t.signal.throwIfAborted();let l=m,w=z(),N=await ve(v,t.signal);N.status===304&&(!l||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await ve(v,t.signal));let R=N.status===304?l:be.parse(JSON.parse(await we(N,M.maxManifestBytes,t.signal))),{generation:te,...ne}=R,J=N.headers.get("etag");if(_(R.scope)!==_(a)||$e(ne)!==te||J!==`"${te}"`&&J!==`W/"${te}"`)throw c("INVALID_RESPONSE","Configuration scope or content identity changed");if(l&&(R.revision<l.revision||R.revision===l.revision&&R.generation!==l.generation))throw c("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[de,q]of Object.entries(l?.funnels??{})){let W=R.funnels[de];if(W&&(W.controlRevision<q.controlRevision||W.evaluationRevision<q.evaluationRevision||W.controlRevision===q.controlRevision&&W.state!==q.state||W.evaluationRevision===q.evaluationRevision&&W.evaluationMode!==q.evaluationMode))throw c("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=pt(N,w,R.policy);if(t.signal.throwIfAborted(),e!==C)throw c("CONFIGURATION_DISPOSED","Configuration scope changed");return m=R,S=Y,p=Date.now()+Math.max(0,Y-z()),A=!1,V=0,O=0,y.writeManifest(_(R)),X(),structuredClone(R)})(),r=setTimeout(()=>t.abort(c("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),u=new Promise((l,w)=>t.signal.addEventListener("abort",()=>w(t.signal.reason),{once:!0})),f=Promise.race([o,u]).catch(l=>{throw V++,(l instanceof n.ZodError||l instanceof SyntaxError||l instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(l.code))&&(S=0,A=!0,X()),l}).finally(()=>{clearTimeout(r),L===f&&(L=void 0),se()});return L=f,f}async function ue(e){let t=e.sha256,o=ne=>rt(ne,e);Ie(e.url);let r=b.get(t);if(r){if(r.byteLength!==e.byteLength)throw c("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return b.delete(t),b.set(t,r),r.text}let u=T.get(t);if(u){if(u.byteLength!==e.byteLength)throw c("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return u.promise}let f=new AbortController;P.add(f);let l=C,w=(async()=>{try{let Y=await y.readArtifact(t);if(Y&&o(Y)){if(f.signal.throwIfAborted(),h||l!==C)throw c("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(t,Y,e.byteLength),Y}}catch{}f.signal.throwIfAborted();let ne=await ve(e.url,f.signal,!0),J=await we(ne,e.byteLength,f.signal);if(!o(J))throw c("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||l!==C)throw c("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(t,J,e.byteLength),y.writeArtifact(t,J),J})(),N=setTimeout(()=>f.abort(c("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),R=new Promise((ne,J)=>f.signal.addEventListener("abort",()=>J(f.signal.reason),{once:!0})),te=Promise.race([w,R]).finally(()=>{clearTimeout(N),P.delete(f),T.delete(t)});return T.set(t,{promise:te,byteLength:e.byteLength}),te}async function K(){return G()||await Z(),re(),m}async function H(e){let t,o=new Promise((r,u)=>{t=setTimeout(()=>u(c("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([e(),o])}finally{clearTimeout(t)}}function B(e,t){if(re(),m?.generation!==e.generation)throw c("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(t&&m.funnels[t]?.state!=="active")throw c("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Pe(e){let t=e.gb.features;if(!t)throw c("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let o=e.artifacts[t];if(o.formatVersion!==1)throw c("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let r=Ve.parse(JSON.parse(await ue(o)));if(_(r.scope)!==_({projectId:a.projectId,environment:a.environment})||r.generation!==o.generation||r.remoteFeatures.some(u=>Object.hasOwn(r.features,u)))throw c("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return B(e),{...r,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,S-z())).toISOString()}}async function Re(e,t){let o=await K(),r=o.funnels[e];t&&(!r||r.evaluationMode==="local"&&!r.versions[t])&&(L&&await L,o=await Z()),B(o,e);let u=o.funnels[e];if(u.evaluationMode!=="local")throw c("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let f=t??u.currentVersionId,l=u.versions[f];if(!l)throw c("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(o.artifacts[l.artifact].formatVersion!==3)throw c("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[w,N]=await Promise.all([ue(o.artifacts[l.artifact]).then(R=>qe(JSON.parse(R))),u.evaluationMode==="local"?Pe(o):void 0]);if(N&&_(Je(w,N))!==_(l.dependencies))throw c("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return B(o,e),{document:w,growth:N,versionId:f,control:structuredClone(u),manifest:structuredClone(o)}}async function ce(e,t){try{return await Re(e,t)}catch(o){if(!(o instanceof D)||!(o.code==="CONFIGURATION_CHANGED"||o.code==="CONFIGURATION_HTTP_404"&&G()))throw o;let r=m?.generation;if(L&&await L,await Z(),o.code!=="CONFIGURATION_CHANGED"&&m?.generation===r)throw o;return Re(e,t)}}let oe=new Map;async function Oe(e,t,o,r){let u=new AbortController;P.add(u);let f=setTimeout(()=>u.abort(c("CONFIGURATION_UNAVAILABLE",`${o} read timed out`)),M.initializationMs);try{let l=await I(Ie(`${v}/${e}`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:u.signal,headers:{}});if(l.status===404)throw c(...r);if(!l.ok)throw c(`CONFIGURATION_HTTP_${l.status}`,`${o} read failed`);let w=await we(l,t,u.signal),N=ze(w),R=l.headers.get("etag");if(R!==`"${N}"`&&R!==`W/"${N}"`)throw c("INVALID_RESPONSE",`${o} identity changed`);return JSON.parse(w)}finally{clearTimeout(f),P.delete(u)}}async function gt(e,t){let{FUNNEL_ROUTE_LIMITS:o,funnelRouteSchema:r}=await import("./funnel-route-source-HYWJWEM3.js"),u=r.safeParse(await Oe(`funnels/${e}/versions/${t}/route`,o.maxBytes,"Funnel route",["ROUTE_UNAVAILABLE","This Funnel Version publishes no route"]));if(!u.success||u.data.funnelId!==e||u.data.versionId!==t)throw c("INVALID_RESPONSE","Funnel route does not describe this Version");return u.data}async function ht(e,t){let{FUNNEL_PAYWALL_PINS_LIMITS:o,funnelPaywallPinsSchema:r}=await import("./funnel-paywall-pins-source-ZK2DZWY3.js"),u=r.safeParse(await Oe(`funnels/${e}/versions/${t}/paywalls`,o.maxBytes,"Funnel Paywall pins",["PAYWALL_PINS_UNAVAILABLE","This Funnel Version publishes no Paywall pins"]));if(!u.success||u.data.funnelId!==e||u.data.versionId!==t)throw c("INVALID_RESPONSE","Funnel Paywall pins do not describe this Version");return u.data}let le=new Map;async function yt(e){let t=await K();B(t,e);let o=t.funnels[e],r=o.currentVersionId,u;if(o.evaluationMode==="local"){let f=await ce(e,r);u=Tt(e,r,f.document,f.manifest)}else{let f=`${e}:${r}`,l=le.get(f);if(!l){let w=ht(e,r);le.set(f,w),w.catch(()=>{le.get(f)===w&&le.delete(f)}),l=w}u=await l}return B(t,e),{pins:structuredClone(u),generation:t.generation}}async function wt(e){let t=await K();B(t,e);let o=t.funnels[e],r=o.currentVersionId,u;if(o.evaluationMode==="local"){let{projectFunnelRoute:f}=await import("./funnel-route-source-HYWJWEM3.js"),l=await ce(e,r),w=Object.entries(l.manifest.paywalls??{});u=f({funnelId:e,versionId:r,document:l.document,experiments:l.growth?.experiments??{},paywallOf:N=>w.find(([,R])=>Object.hasOwn(R.versions,N))?.[0]})}else{let f=`${e}:${r}`,l=oe.get(f);if(!l||z()-l.readAt>=M.maxControlAgeMs){let w={promise:gt(e,r),readAt:z()};oe.set(f,w),w.promise.catch(()=>{oe.get(f)===w&&oe.delete(f)}),l=w}u=await l.promise}return B(t,e),{route:structuredClone(u),control:structuredClone(o),generation:t.generation}}function ee(){if(G()||X(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}Z().catch(ye)}function It(e){if(h)throw c("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return F.add(e),F.size===1&&(typeof window<"u"&&(window.addEventListener("online",ee),window.addEventListener("focus",ee),document.addEventListener("visibilitychange",ee)),se()),()=>{F.delete(e),F.size||(clearTimeout(s),clearTimeout(E),Fe())}}function Fe(){typeof window<"u"&&(window.removeEventListener("online",ee),window.removeEventListener("focus",ee),document.removeEventListener("visibilitychange",ee))}return{scope:Object.freeze({...a}),refresh:Z,subscribe:It,assertFresh:re,assertFeatures(e){re();let t=m.gb.features;if(!t)throw c("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(e!==void 0&&m.artifacts[t].generation!==e)throw c("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return G()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return G()?Math.max(0,S-z()):0},async features(){return H(async()=>Pe(await K()))},pageExperiments:()=>H(async()=>{let e=await K(),t=e.gb.pageExperiments;if(!t)throw c("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let o=e.artifacts[t];if(o.formatVersion!==1)throw c("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let r=lt.parse(JSON.parse(await ue(o)));if(r.environmentId!==a.environmentId||r.generation!==o.generation)throw c("INVALID_RESPONSE","Page experiment scope or generation changed");return B(e),r}),funnel:(e,t)=>H(()=>ce(e,t)),funnelControl:e=>H(async()=>{let t=await K();return B(t,e),structuredClone(t.funnels[e])}),funnelRoute:e=>H(()=>wt(e)),funnelPaywallPins:e=>H(()=>yt(e)),paywall:(e,t)=>H(async()=>{let o=await K(),r=o.paywalls?.[e];if(!r||!t&&r.state!=="published")throw c("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let u=t??r.currentVersionId,f=r.versions[u],l=f&&o.artifacts[f.artifact];if(!l||l.kind!=="paywall"||l.formatVersion!==1)throw c("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let w=Ge.parse(JSON.parse(await ue(l)));return B(o),{document:w,versionId:u,version:f.version,control:structuredClone(r),manifest:structuredClone(o)}}),async localFunnel(e,t){let o=await H(()=>ce(e,t));if(!o.growth)throw c("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:r,remoteFeatures:u,...f}=o.growth;return Xe({scope:{projectId:a.projectId,environment:a.environment},funnelId:e,versionId:o.versionId,evaluationMode:"local",evaluationRevision:o.control.evaluationRevision,document:o.document,payload:f})},assertFunnel(e,t,o){re();let r=m.funnels[e];if(!r||r.state!=="active")throw c("FUNNEL_STOPPED","Funnel is paused or unavailable");if(r.evaluationMode!=="local")throw c("EVALUATION_MODE","This Funnel now executes at Longplay");if(t!==void 0&&r.controlRevision!==t)throw c("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(o!==void 0&&!r.versions[o])throw c("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,C++,S=0,k?.abort(c("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(E),Fe(),X(),F.clear();for(let e of P)e.abort(c("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));b.clear(),oe.clear(),$=0}}}}function mt(i){let a=fe.test(i.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!ge.test(i.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let x=U.safeParse({...g,operation:"start"});if(!x.success||x.data.operation!=="start"||(a?x.data.customer!==void 0:x.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let I=x.data,v=et({...i,timeoutMs:i.timeoutMs??35e3});try{i.session||v.identify(i.apiKey);let d=tt(i,await v.request("funnels",I));if(!d.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(d.run.source.id!==I.funnelId||d.run.locale!==(I.locale??"en")||!ot(d.run.parameters,I.parameters??{})||(I.customer?!d.customerId||I.customer.type==="id"&&d.customerId!==I.customer.value:d.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...d,runToken:d.runToken}}finally{v.dispose()}}}}async function Ln(i){i={...i};let a=i.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(i.scope&&_(g)!==_(i.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(i.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let I=ge.test(i.credential);if(I?!i.customerId:i.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let v=mt({...i,scope:g,apiKey:i.credential}),d=(y,m)=>{let S=it({...i,scope:g,runToken:y,initialResponse:m,...I?{serverKey:i.credential}:{}});return I||S.identify(i.credential),S};return{async start(y){let m=await v.start({...y,funnelId:i.funnelId,...I?{customer:{type:"id",value:i.customerId}}:{}}),S=d(m.runToken,m),p=await S.get();return{...m,...p,controller:S}},async restore(y){let m=d(y),S=await m.get();if(S.run.source.id!==i.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...S,runToken:y,controller:m}}}}export{ut as a,At as b,Gt as c,Bt as d,zt as e,$t as f,Jt as g,nn as h,vn as i,mt as j,Ln as k};
|
|
1
|
+
import{A as ge,E as it,b as He,c as Ke,d as Ee,h as Ye,i as We,j as Qe,n as Xe,q as tt,z as ot}from"./chunk-ORQ5RR4J.js";import{a as rt}from"./chunk-L42BXSWX.js";import{c as _e,d as Le,e as De,f as Ue,g as Ve,i as Me,m as Ge,n as M,o as Be,q as be,r as _,s as ze,t as $e,u as Je,v as qe}from"./chunk-4AJTBYKE.js";import{K as U,e as ke,q as Se,r as je}from"./chunk-SEBMCCXY.js";import{a as pe,b as et}from"./chunk-SK73TK7R.js";import{a as fe}from"./chunk-O33ABKTL.js";import{e as me}from"./chunk-GRY5G7X3.js";import{a as D}from"./chunk-355B3KPL.js";import{h as ie}from"./chunk-FEZWUYEK.js";import{b as nt}from"./chunk-3VUPVXAV.js";import{a as Ze}from"./chunk-5MRSFLQA.js";import{b as n}from"./chunk-TDOPU2RH.js";import{c as Ne,f as Te}from"./chunk-VPT5MFDG.js";var j=n.literal(ke),vt=n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=n.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),at=n.discriminatedUnion("type",[n.strictObject({type:n.literal("guest"),guestToken:xe}),n.strictObject({type:n.literal("customer"),customer:Se,customerData:je.optional()})]),Ae=n.strictObject({id:n.uuid(),runId:n.uuid(),customerId:n.uuid(),requestId:n.uuid(),acceptedAt:n.iso.datetime({offset:!0})}),St=n.strictObject({participantId:n.uuid(),startedAs:n.enum(["guest","identified"]),binding:Ae.omit({runId:!0,requestId:!0}).nullable()}),bt=n.union([He,n.strictObject({type:n.literal("authentication_required"),reason:n.enum(["customer_required","customer_experiment_required"]),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative()})]),Et=Ke.omit({authenticated:!0}).extend({identity:St,instruction:bt.nullable()}),xt=n.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),he={contract:j,customerToken:n.string().regex(fe)},st={contract:j,requestId:n.uuid(),runToken:vt,externalUserId:Se.options[1].shape.value},ut=n.discriminatedUnion("operation",[n.strictObject({contract:j,operation:n.literal("describe")}),n.strictObject({contract:j,operation:n.literal("start"),source:at,funnelId:U.options[0].shape.funnelId,requestId:n.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),Ye.omit({operation:!0}).extend({contract:j,operation:n.literal("entry_start"),source:at}),n.strictObject({...st,operation:n.literal("bind_customer"),guestToken:xe,claimRequestId:n.uuid(),expectedBindingId:n.null()}),n.strictObject({...st,operation:n.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...he,operation:n.literal("get"),settlementBindingId:n.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...he,operation:n.literal("review")}),Qe.omit({customerToken:!0}).extend(he),n.strictObject({...he,operation:n.literal("command"),identity:n.strictObject({bindingId:n.uuid().nullable()}),command:xt})]),At=Ee.omit({run:!0}).extend({contract:j,run:Et,settlement:Ee.shape.settlement.unwrap().extend({accepted:n.boolean().nullable().optional()}).optional()}),Gt=We.extend({contract:j}),Bt=n.discriminatedUnion("operation",[ut.options[1].omit({contract:!0,source:!0,requestId:!0}),ut.options[2].omit({contract:!0,source:!0,requestId:!0})]),zt=At.extend({binding:Ae,outcome:n.enum(["bound","already_bound"]),replayed:n.boolean()}),$t=n.discriminatedUnion("state",[n.strictObject({contract:j,scope:ie,state:n.literal("not_accepted")}),n.strictObject({contract:j,scope:ie,state:n.literal("conflict")}),n.strictObject({contract:j,scope:ie,state:n.literal("bound"),binding:Ae})]),Jt=n.strictObject({contract:j,scope:ie,keyId:n.uuid(),operations:n.array(n.string()).max(20)});var ct=n.string().regex(/^[a-f0-9]{64}$/),Ct=_e.omit({variations:!0,active:!0}).extend({changeId:ct,variations:n.array(n.strictObject({urlRedirect:n.string().max(2048)})).min(2).max(20)}),lt=n.strictObject({environmentId:n.uuid(),trackExposures:n.boolean(),generation:ct,experiments:n.array(Ct).max(100),savedGroups:Le}),Pt=n.strictObject({eventUuid:n.uuid(),timestamp:n.iso.datetime({offset:!0}).optional(),deviceId:n.string().min(1).max(128),sessionId:n.string().min(1).max(128).optional(),url:n.url().max(2048),pageTitle:n.string().max(512).optional(),experimentKey:n.string().min(1).max(255),variationKey:n.string().min(1).max(64)}),Yt=n.strictObject({events:n.array(Pt).min(1).max(20)}),Wt=n.strictObject({inserted:n.number().int().nonnegative(),duplicates:n.number().int().nonnegative(),skipped:n.number().int().nonnegative(),rejected:n.array(n.strictObject({index:n.number().int().nonnegative(),reason:n.string()}))});function nn(i){let a=null,g=null,x=0,I=0,v=new Set,d=null,y=null,m=new Set,S=()=>{for(let s of m)try{s()}catch{}},p={attributes:me.parse(i.attributes??{}),onFeatureUsage:i.onFeatureUsage?(s,E)=>{!v.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&i.onFeatureUsage(s,structuredClone(E),structuredClone(p.attributes),a.generation)}:void 0,onExperimentViewed:i.onExperimentViewed?(s,E)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&i.onExperimentViewed(structuredClone(s),structuredClone(E),structuredClone(p.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(i.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:i.saveStickyBucketAssignmentDoc?s=>i.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},A=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,E=new Set){return v.has(s)?!d||!d.features[s]||["unknownFeature","cyclicPrerequisite"].includes(d.features[s].source):E.has(s)?!1:(E.add(s),(a?.features[s]?.rules??[]).some(O=>[...O.parentConditions??[],...(O.tracks??[]).flatMap(F=>F.experiment.parentConditions??[])].some(F=>h(F.id,E))))}let C=s=>{if(i.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return d?.expiresAt&&Date.parse(d.expiresAt)<=Date.now()&&(d=null,p.features=a.features),v.has(s)?!d||d.expiresAt&&Date.parse(d.expiresAt)<=Date.now()?A():structuredClone(d.features[s]??A()):i.evaluateRemote&&(p.attributes?.merchandise||p.attributes?.merchandiseId)&&!d||h(s)?A():structuredClone(Te(s,p))};async function V(){if(!a||!v.size&&!p.attributes?.merchandise&&!p.attributes?.merchandiseId)return;if(!i.evaluateRemote){if(v.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=I;if(y?.revision===s)return y.loading;let E=x,O=a,F=[...v],P=(async()=>{let b=Me.parse(await i.evaluateRemote({attributes:structuredClone(p.attributes),features:F}));if(!(E!==x||s!==I||O!==a)){if(i.assertUsable?.(O.generation),b.generation!==O.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(F.some(T=>!Object.hasOwn(b.features,T))||Object.keys(b.features).some(T=>!v.has(T)))throw new Error("Invalid remote Feature results");if(p.attributes?.merchandise||p.attributes?.merchandiseId){if(!b.merchandiseContext)throw new Error("Server did not resolve merchandise context");p.attributes=me.parse({...p.attributes,...b.merchandiseContext})}d=structuredClone(b),p.features={...O.features,...Object.fromEntries(Object.entries(d.features).map(([T,$])=>[T,{defaultValue:$.value}]))},S()}})();y={revision:s,loading:P};try{await P}finally{y?.loading===P&&(y=null)}}function L(){V().catch(s=>{try{i.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=x,E=(async()=>{let O=await i.load(),F="remoteFeatures"in O?Ue.parse(O):null,P=F??De.parse(O);if(P.scope.projectId!==i.scope.projectId||P.scope.environment!==i.scope.environment)throw new Error("Feature payload scope changed");if(s!==x)throw new Error("Feature client was reset");if(i.assertUsable&&a?.generation===P.generation){let{evaluatedAt:T,expiresAt:$,...ae}=a,{evaluatedAt:X,expiresAt:ye,...G}=P;if(_(ae)!==_(G))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=P.evaluatedAt,a.expiresAt=P.expiresAt,S(),(!d||d.expiresAt&&Date.parse(d.expiresAt)<=Date.now())&&L(),structuredClone(a)}let b=new Set(F?.remoteFeatures??[]);if([...b].some(T=>Object.hasOwn(P.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in P&&!a.analyticsConfig.experimentViewsEnabled&&F?.analyticsConfig.experimentViewsEnabled&&p.trackedExperiments?.clear(),a=structuredClone(P),v=b,d=null,y=null,I++,p.features=a.features,p.savedGroups=Ne(a.savedGroups),p.trackedFeatureUsage={},S(),L(),structuredClone(a)})();g=E;try{return await E}finally{g===E&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let E=me.parse(s);(p.attributes?.merchandise||p.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&p.trackedExperiments?.clear(),p.attributes=E,I++,d=null,y=null,p.features=a?.features??{},p.trackedFeatureUsage={},S(),L()},evalFeature:C,isOn(s){return C(s).on},isOff(s){return C(s).off},getFeatureValue(s,E){let O=C(s).value;return structuredClone(O===null?E:O)},reset(){x++,I++,g=null,y=null,a=null,d=null,v.clear(),p.features={},p.savedGroups={},p.stickyBucketAssignmentDocs={},p.attributes={},p.trackedFeatureUsage={},p.trackedExperiments?.clear(),S()}}}var Rt=n.record(n.string().regex(/^[a-f0-9]{64}$/),n.strictObject({at:n.number(),text:n.string()})),Q=2*1048576,Ot=100;function Ft(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function dt(i,a){let g=a===void 0?Ft():a,x=new Map,I=0,v=!1,d=!1,y,m;async function S(A){if(!g)return null;let h;try{let C=await Promise.race([Promise.resolve().then(()=>g.getItem(A)),new Promise(V=>{h=setTimeout(()=>V(null),Ot)})]);return typeof C=="string"&&C.length<=Q&&new TextEncoder().encode(C).byteLength<=Q?C:null}catch{return null}finally{clearTimeout(h)}}function p(){if(m)return m;let A=(async()=>{try{let h=await S(`${i}:artifacts`);if(h)return Rt.parse(JSON.parse(h))}catch{}return{}})();return m=A,A.finally(()=>{m===A&&(m=void 0)}),A}return{async readManifest(){return S(i)},writeManifest(A){!g||A.length>Q||new TextEncoder().encode(A).byteLength>Q||(y=A,!d&&(d=!0,Promise.resolve().then(async()=>{try{for(;y!==void 0;){let h=y;try{await g.setItem(i,h)}catch{}y===h&&(y=void 0)}}finally{d=!1}})))},async readArtifact(A){let h=(await p())[A],C=Date.now();return h&&C>=h.at&&C-h.at<=M.retentionMs?h.text:void 0},writeArtifact(A,h){if(!g||h.length>Q)return;let C=x.get(A);if(C?.text===h||!C&&x.size>=128)return;let V=new TextEncoder().encode(h).byteLength;I-(C?.byteLength??0)+V>Q||(x.set(A,{text:h,byteLength:V}),I+=V-(C?.byteLength??0),!v&&(v=!0,Promise.resolve().then(async()=>{try{for(;x.size;){let L=new Map(x);try{let k={...await p()},s=Date.now();for(let[P,b]of L)k[P]={at:s,text:b.text};let E={},O=2,F=0;for(let[P,b]of Object.entries(k).sort(([,T],[,$])=>$.at-T.at)){if(b.at>s||s-b.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[P]:b})).byteLength;O+T>Q||F>=128||(E[P]=b,O+=T,F++)}await g.setItem(`${i}:artifacts`,JSON.stringify(E))}catch{}finally{for(let[k,s]of L)x.get(k)===s&&(x.delete(k),I-=s.byteLength)}}}finally{v=!1}})))}}}var c=(i,a)=>new D(i,a),z=()=>performance.now(),ft=i=>{typeof i=="object"&&"unref"in i&&i.unref()},Nt=12e4;function Tt(i,a,g,x){let I=Object.entries(x.paywalls??{}),v={};for(let d of g.screens){if(d.type!=="paywall")continue;let y=I.find(([,S])=>Object.hasOwn(S.versions,d.paywallVersionId))?.[0];if(!y)continue;let m=v[y]??=[];m.includes(d.paywallVersionId)||m.push(d.paywallVersionId)}for(let d of Object.values(v))d.sort();return{kind:"funnel_paywall_pins",formatVersion:1,funnelId:i,versionId:a,paywalls:v}}function vn(i){let a=Be.parse(i.scope),g=new pe(i.origin??Ze);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw c("INVALID_URL","Configuration requires a trusted HTTPS origin");let x=new Set([g.origin,...(i.assetOrigins??[]).map(e=>{let t=new pe(e);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw c("INVALID_URL","Invalid configuration asset origin");return t.origin})]),I=i.fetch??globalThis.fetch.bind(globalThis),v=`/api/v1/configuration/${a.environmentId}`,d=`indiana:configuration:1:${g.origin}:${_(a)}`,y=dt(d,i.storage),m,S=0,p=0,A=!1,h=!1,C=0,V=0,L,k,s,E,O=0,F=new Set,P=new Set,b=new Map,T=new Map,$=0,ae=!1;function X(){for(let e of F)try{e()}catch{}}function ye(e){try{i.onError?.(e)}catch{}}let G=()=>!h&&!A&&!!m&&z()<S&&Date.now()<p;function re(){if(!G())throw c("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(e,t,o){if(!b.has(e)){for(;b.size&&(b.size>=128||$+o>M.maxCacheBytes);){let r=b.entries().next().value;$-=r[1].byteLength,b.delete(r[0])}b.set(e,{text:t,byteLength:o}),$+=o}}function we(e,t,o){return nt(e,t,{signal:o,error:r=>c("INVALID_RESPONSE",r==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function Ie(e){let t=new pe(e,g);if(!x.has(t.origin)||t.username||t.password||t.hash||t.search)throw c("INVALID_URL","Configuration artifact origin is not trusted");return t.href}async function ve(e,t,o=!1){let r=await I(Ie(e),{method:"GET",credentials:"omit",redirect:"error",cache:o?"default":"no-cache",signal:t,headers:{}});if(r.status===429){let u=r.headers.get("retry-after")??"";O=/^\d+$/.test(u)?Number(u)*1e3:Math.max(0,Date.parse(u)-Date.now())||15e3}if(!r.ok&&r.status!==304)throw c(`CONFIGURATION_HTTP_${r.status}`,"Configuration synchronization failed");return r}function pt(e,t,o){let r=Date.parse(e.headers.get("x-indiana-config-validated-at")??""),u=Date.parse(e.headers.get("x-indiana-config-valid-until")??""),f=Date.parse(e.headers.get("date")??""),l=e.headers.get("age"),w=l!==null&&/^\d+(\.\d+)?$/.test(l)?Number(l)*1e3:NaN;if(![r,u,f,w].every(Number.isFinite)||u<=r||u-r>M.maxControlAgeMs||r>f+1e3)throw c("INVALID_RESPONSE","Configuration freshness evidence is invalid");let R=Math.min(u-r,o.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(w,f-r,0)-(z()-t);if(R<=0)throw c("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return z()+R}function se(){if(clearTimeout(s),clearTimeout(E),h||!F.size||(G()&&(E=setTimeout(()=>{G()?se():X()},Math.max(1,S-z())),ft(E)),typeof document<"u"&&document.visibilityState==="hidden"))return;let e=Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3),t=V>2?Math.min(Nt,e*2**(V-2)):e;s=setTimeout(()=>{Z().catch(ye)},Math.max(O,t*(.8+Math.random()*.2))),ft(s)}async function Z(){if(h)throw c("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let e=C,t=new AbortController;k=t;let o=(async()=>{if(!ae){ae=!0;try{let de=await y.readManifest();if(de&&!m){let q=be.parse(JSON.parse(de));_(q.scope)===_(a)&&(m=q)}}catch{}}t.signal.throwIfAborted();let l=m,w=z(),N=await ve(v,t.signal);N.status===304&&(!l||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await ve(v,t.signal));let R=N.status===304?l:be.parse(JSON.parse(await we(N,M.maxManifestBytes,t.signal))),{generation:te,...ne}=R,J=N.headers.get("etag");if(_(R.scope)!==_(a)||$e(ne)!==te||J!==`"${te}"`&&J!==`W/"${te}"`)throw c("INVALID_RESPONSE","Configuration scope or content identity changed");if(l&&(R.revision<l.revision||R.revision===l.revision&&R.generation!==l.generation))throw c("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[de,q]of Object.entries(l?.funnels??{})){let W=R.funnels[de];if(W&&(W.controlRevision<q.controlRevision||W.evaluationRevision<q.evaluationRevision||W.controlRevision===q.controlRevision&&W.state!==q.state||W.evaluationRevision===q.evaluationRevision&&W.evaluationMode!==q.evaluationMode))throw c("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=pt(N,w,R.policy);if(t.signal.throwIfAborted(),e!==C)throw c("CONFIGURATION_DISPOSED","Configuration scope changed");return m=R,S=Y,p=Date.now()+Math.max(0,Y-z()),A=!1,V=0,O=0,y.writeManifest(_(R)),X(),structuredClone(R)})(),r=setTimeout(()=>t.abort(c("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),u=new Promise((l,w)=>t.signal.addEventListener("abort",()=>w(t.signal.reason),{once:!0})),f=Promise.race([o,u]).catch(l=>{throw V++,(l instanceof n.ZodError||l instanceof SyntaxError||l instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(l.code))&&(S=0,A=!0,X()),l}).finally(()=>{clearTimeout(r),L===f&&(L=void 0),se()});return L=f,f}async function ue(e){let t=e.sha256,o=ne=>rt(ne,e);Ie(e.url);let r=b.get(t);if(r){if(r.byteLength!==e.byteLength)throw c("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return b.delete(t),b.set(t,r),r.text}let u=T.get(t);if(u){if(u.byteLength!==e.byteLength)throw c("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return u.promise}let f=new AbortController;P.add(f);let l=C,w=(async()=>{try{let Y=await y.readArtifact(t);if(Y&&o(Y)){if(f.signal.throwIfAborted(),h||l!==C)throw c("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(t,Y,e.byteLength),Y}}catch{}f.signal.throwIfAborted();let ne=await ve(e.url,f.signal,!0),J=await we(ne,e.byteLength,f.signal);if(!o(J))throw c("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||l!==C)throw c("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(t,J,e.byteLength),y.writeArtifact(t,J),J})(),N=setTimeout(()=>f.abort(c("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),R=new Promise((ne,J)=>f.signal.addEventListener("abort",()=>J(f.signal.reason),{once:!0})),te=Promise.race([w,R]).finally(()=>{clearTimeout(N),P.delete(f),T.delete(t)});return T.set(t,{promise:te,byteLength:e.byteLength}),te}async function K(){return G()||await Z(),re(),m}async function H(e){let t,o=new Promise((r,u)=>{t=setTimeout(()=>u(c("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([e(),o])}finally{clearTimeout(t)}}function B(e,t){if(re(),m?.generation!==e.generation)throw c("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(t&&m.funnels[t]?.state!=="active")throw c("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Pe(e){let t=e.gb.features;if(!t)throw c("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let o=e.artifacts[t];if(o.formatVersion!==1)throw c("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let r=Ve.parse(JSON.parse(await ue(o)));if(_(r.scope)!==_({projectId:a.projectId,environment:a.environment})||r.generation!==o.generation||r.remoteFeatures.some(u=>Object.hasOwn(r.features,u)))throw c("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return B(e),{...r,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,S-z())).toISOString()}}async function Re(e,t){let o=await K(),r=o.funnels[e];t&&(!r||r.evaluationMode==="local"&&!r.versions[t])&&(L&&await L,o=await Z()),B(o,e);let u=o.funnels[e];if(u.evaluationMode!=="local")throw c("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let f=t??u.currentVersionId,l=u.versions[f];if(!l)throw c("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(o.artifacts[l.artifact].formatVersion!==3)throw c("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[w,N]=await Promise.all([ue(o.artifacts[l.artifact]).then(R=>qe(JSON.parse(R))),u.evaluationMode==="local"?Pe(o):void 0]);if(N&&_(Je(w,N))!==_(l.dependencies))throw c("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return B(o,e),{document:w,growth:N,versionId:f,control:structuredClone(u),manifest:structuredClone(o)}}async function ce(e,t){try{return await Re(e,t)}catch(o){if(!(o instanceof D)||!(o.code==="CONFIGURATION_CHANGED"||o.code==="CONFIGURATION_HTTP_404"&&G()))throw o;let r=m?.generation;if(L&&await L,await Z(),o.code!=="CONFIGURATION_CHANGED"&&m?.generation===r)throw o;return Re(e,t)}}let oe=new Map;async function Oe(e,t,o,r){let u=new AbortController;P.add(u);let f=setTimeout(()=>u.abort(c("CONFIGURATION_UNAVAILABLE",`${o} read timed out`)),M.initializationMs);try{let l=await I(Ie(`${v}/${e}`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:u.signal,headers:{}});if(l.status===404)throw c(...r);if(!l.ok)throw c(`CONFIGURATION_HTTP_${l.status}`,`${o} read failed`);let w=await we(l,t,u.signal),N=ze(w),R=l.headers.get("etag");if(R!==`"${N}"`&&R!==`W/"${N}"`)throw c("INVALID_RESPONSE",`${o} identity changed`);return JSON.parse(w)}finally{clearTimeout(f),P.delete(u)}}async function gt(e,t){let{FUNNEL_ROUTE_LIMITS:o,funnelRouteSchema:r}=await import("./funnel-route-source-WZ35NDNG.js"),u=r.safeParse(await Oe(`funnels/${e}/versions/${t}/route`,o.maxBytes,"Funnel route",["ROUTE_UNAVAILABLE","This Funnel Version publishes no route"]));if(!u.success||u.data.funnelId!==e||u.data.versionId!==t)throw c("INVALID_RESPONSE","Funnel route does not describe this Version");return u.data}async function ht(e,t){let{FUNNEL_PAYWALL_PINS_LIMITS:o,funnelPaywallPinsSchema:r}=await import("./funnel-paywall-pins-source-MJIRVW5F.js"),u=r.safeParse(await Oe(`funnels/${e}/versions/${t}/paywalls`,o.maxBytes,"Funnel Paywall pins",["PAYWALL_PINS_UNAVAILABLE","This Funnel Version publishes no Paywall pins"]));if(!u.success||u.data.funnelId!==e||u.data.versionId!==t)throw c("INVALID_RESPONSE","Funnel Paywall pins do not describe this Version");return u.data}let le=new Map;async function yt(e){let t=await K();B(t,e);let o=t.funnels[e],r=o.currentVersionId,u;if(o.evaluationMode==="local"){let f=await ce(e,r);u=Tt(e,r,f.document,f.manifest)}else{let f=`${e}:${r}`,l=le.get(f);if(!l){let w=ht(e,r);le.set(f,w),w.catch(()=>{le.get(f)===w&&le.delete(f)}),l=w}u=await l}return B(t,e),{pins:structuredClone(u),generation:t.generation}}async function wt(e){let t=await K();B(t,e);let o=t.funnels[e],r=o.currentVersionId,u;if(o.evaluationMode==="local"){let{projectFunnelRoute:f}=await import("./funnel-route-source-WZ35NDNG.js"),l=await ce(e,r),w=Object.entries(l.manifest.paywalls??{});u=f({funnelId:e,versionId:r,document:l.document,experiments:l.growth?.experiments??{},paywallOf:N=>w.find(([,R])=>Object.hasOwn(R.versions,N))?.[0]})}else{let f=`${e}:${r}`,l=oe.get(f);if(!l||z()-l.readAt>=M.maxControlAgeMs){let w={promise:gt(e,r),readAt:z()};oe.set(f,w),w.promise.catch(()=>{oe.get(f)===w&&oe.delete(f)}),l=w}u=await l.promise}return B(t,e),{route:structuredClone(u),control:structuredClone(o),generation:t.generation}}function ee(){if(G()||X(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}Z().catch(ye)}function It(e){if(h)throw c("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return F.add(e),F.size===1&&(typeof window<"u"&&(window.addEventListener("online",ee),window.addEventListener("focus",ee),document.addEventListener("visibilitychange",ee)),se()),()=>{F.delete(e),F.size||(clearTimeout(s),clearTimeout(E),Fe())}}function Fe(){typeof window<"u"&&(window.removeEventListener("online",ee),window.removeEventListener("focus",ee),document.removeEventListener("visibilitychange",ee))}return{scope:Object.freeze({...a}),refresh:Z,subscribe:It,assertFresh:re,assertFeatures(e){re();let t=m.gb.features;if(!t)throw c("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(e!==void 0&&m.artifacts[t].generation!==e)throw c("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return G()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return G()?Math.max(0,S-z()):0},async features(){return H(async()=>Pe(await K()))},pageExperiments:()=>H(async()=>{let e=await K(),t=e.gb.pageExperiments;if(!t)throw c("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let o=e.artifacts[t];if(o.formatVersion!==1)throw c("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let r=lt.parse(JSON.parse(await ue(o)));if(r.environmentId!==a.environmentId||r.generation!==o.generation)throw c("INVALID_RESPONSE","Page experiment scope or generation changed");return B(e),r}),funnel:(e,t)=>H(()=>ce(e,t)),funnelControl:e=>H(async()=>{let t=await K();return B(t,e),structuredClone(t.funnels[e])}),funnelRoute:e=>H(()=>wt(e)),funnelPaywallPins:e=>H(()=>yt(e)),paywall:(e,t)=>H(async()=>{let o=await K(),r=o.paywalls?.[e];if(!r||!t&&r.state!=="published")throw c("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let u=t??r.currentVersionId,f=r.versions[u],l=f&&o.artifacts[f.artifact];if(!l||l.kind!=="paywall"||l.formatVersion!==1)throw c("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let w=Ge.parse(JSON.parse(await ue(l)));return B(o),{document:w,versionId:u,version:f.version,control:structuredClone(r),manifest:structuredClone(o)}}),async localFunnel(e,t){let o=await H(()=>ce(e,t));if(!o.growth)throw c("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:r,remoteFeatures:u,...f}=o.growth;return Xe({scope:{projectId:a.projectId,environment:a.environment},funnelId:e,versionId:o.versionId,evaluationMode:"local",evaluationRevision:o.control.evaluationRevision,document:o.document,payload:f})},assertFunnel(e,t,o){re();let r=m.funnels[e];if(!r||r.state!=="active")throw c("FUNNEL_STOPPED","Funnel is paused or unavailable");if(r.evaluationMode!=="local")throw c("EVALUATION_MODE","This Funnel now executes at Longplay");if(t!==void 0&&r.controlRevision!==t)throw c("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(o!==void 0&&!r.versions[o])throw c("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,C++,S=0,k?.abort(c("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(E),Fe(),X(),F.clear();for(let e of P)e.abort(c("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));b.clear(),oe.clear(),$=0}}}}function mt(i){let a=fe.test(i.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!ge.test(i.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let x=U.safeParse({...g,operation:"start"});if(!x.success||x.data.operation!=="start"||(a?x.data.customer!==void 0:x.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let I=x.data,v=et({...i,timeoutMs:i.timeoutMs??35e3});try{i.session||v.identify(i.apiKey);let d=tt(i,await v.request("funnels",I));if(!d.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(d.run.source.id!==I.funnelId||d.run.locale!==(I.locale??"en")||!ot(d.run.parameters,I.parameters??{})||(I.customer?!d.customerId||I.customer.type==="id"&&d.customerId!==I.customer.value:d.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...d,runToken:d.runToken}}finally{v.dispose()}}}}async function Ln(i){i={...i};let a=i.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(i.scope&&_(g)!==_(i.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(i.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let I=ge.test(i.credential);if(I?!i.customerId:i.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let v=mt({...i,scope:g,apiKey:i.credential}),d=(y,m)=>{let S=it({...i,scope:g,runToken:y,initialResponse:m,...I?{serverKey:i.credential}:{}});return I||S.identify(i.credential),S};return{async start(y){let m=await v.start({...y,funnelId:i.funnelId,...I?{customer:{type:"id",value:i.customerId}}:{}}),S=d(m.runToken,m),p=await S.get();return{...m,...p,controller:S}},async restore(y){let m=d(y),S=await m.get();if(S.run.source.id!==i.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...S,runToken:y,controller:m}}}}export{ut as a,At as b,Gt as c,Bt as d,zt as e,$t as f,Jt as g,nn as h,vn as i,mt as j,Ln as k};
|