@tinkerlandai/longplay-sdk 0.10.19-rc.3 → 0.10.20-rc.1
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/CHANGELOG.md +8 -0
- package/README.md +6 -2
- package/README.zh-CN.md +4 -2
- package/dist/{ai-usage-DPGx5otD.d.ts → ai-usage-wsrO7M2I.d.ts} +1 -1
- package/dist/{api-G8EA_ueL.d.ts → api-BDUQ1udV.d.ts} +54 -5
- package/dist/{chunk-C5WDTSOQ.js → chunk-ERBSYWX7.js} +1 -1
- package/dist/chunk-FG4NDDQZ.js +1 -0
- package/dist/chunk-JVH4ZNEK.js +1 -0
- package/dist/{chunk-DTJKESGC.js → chunk-LIAMO3LU.js} +1 -1
- package/dist/chunk-ML4U33AO.js +6 -0
- package/dist/chunk-TKNTHNKH.js +1 -0
- package/dist/{chunk-YSW3DGSR.js → chunk-UTESNVQG.js} +1 -1
- package/dist/{chunk-JUY6II6H.js → chunk-V3XYYTS6.js} +1 -1
- package/dist/{chunk-FSUP7HMS.js → chunk-VYYMUZAR.js} +1 -1
- package/dist/{chunk-SR6CERFC.js → chunk-YGU2GL6L.js} +1 -1
- package/dist/{content-UR3NHWAB.js → content-ULBLRM7L.js} +1 -1
- package/dist/{funnel-local-client-DjvVzCfH.d.ts → funnel-local-client-DInl0SJb.d.ts} +5 -3
- package/dist/{funnel-process-client-bO9Wfumi.d.ts → funnel-process-client-DRztj2Cb.d.ts} +4 -2
- package/dist/funnel-runtime-host-MLOXV7OC.js +1 -0
- package/dist/index.d.ts +5 -5
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +2 -2
- package/dist/openrouter.js +1 -1
- package/dist/page.js +1 -1
- package/dist/{paywall-5RZ3NFHB.js → paywall-P4TRVOBV.js} +1 -1
- package/dist/react-native.d.ts +5 -5
- package/dist/react-native.js +1 -1
- package/dist/server.d.ts +4 -4
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-5PRFQQ6G.js +0 -1
- package/dist/chunk-CJMHP3S7.js +0 -1
- package/dist/chunk-DBBUN53B.js +0 -6
- package/dist/chunk-PZPTJ4Q5.js +0 -1
- package/dist/funnel-runtime-host-CM3O4CZK.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.20 — 2026-11-06
|
|
4
|
+
|
|
5
|
+
- **Breaking:** tracked events now declare their type. `track()` is unchanged, but direct `trackEvents` callers in JavaScript, Python and Go must send `kind`: `custom`, `experiment_exposure` or `feature_usage`. Exposure and Feature usage reports also name the Feature `generation` that produced them. Once the runtime serves this contract, earlier SDKs cannot record events. Wire protocol stays `0.10`, and only this route changes.
|
|
6
|
+
- One refused event no longer refuses its batch. `flush()` and `trackEvents` return `rejections`, one `{ eventUuid, reason }` for each refused event, and a refused event is not resent.
|
|
7
|
+
- Event queues no longer wait on an answer that cannot change. A batch the server refuses is dropped at once. During an outage a batch is retried with growing delays and given up after five attempts.
|
|
8
|
+
- iOS and Android send at most 16 KiB per request and hold 500 queued events, and a failed background delivery no longer fails `track`. A full queue raises `eventQueueFull` on iOS and `event_queue_full` on Android.
|
|
9
|
+
- Keep verified Customer attributes out of Remote evaluation. `id`, `externalUserId`, `createdAt`, `ageDays` and `subscription` passed for Local bucketing no longer break Remote Features for a Customer.
|
|
10
|
+
|
|
3
11
|
## 0.10.19 — 2026-11-06
|
|
4
12
|
|
|
5
13
|
- Restore explicit confirmation for the original unconfirmed Paywall quote after interruption or reload, retaining request identity and the existing recovery path for confirmed purchases.
|
package/README.md
CHANGED
|
@@ -215,7 +215,7 @@ Web IAM hosts opt in with `createIamFunnelProcessEntries`. React Native exports
|
|
|
215
215
|
|
|
216
216
|
Funnel, standalone Features and page experiments evaluate independently. Matching App/environment, experiment definition, attributes, hash identity and Sticky state produce matching results; different refresh times or inputs may produce different variations. A Remote Funnel still evaluates on Longplay when its referenced code Experiment allows Local definition delivery. Accepted Funnel decisions retain their original results. There is no cross-feature result synchronization.
|
|
217
217
|
|
|
218
|
-
For Customer-based evaluation, `id` means the Longplay Customer UUID (`customer.id`); `externalUserId` means the merchant account ID (`customer.externalUserId`). Choose the experiment's `hashAttribute` explicitly when creating it and preserve that meaning in every consumer. Do not put the merchant account ID into `attributes.id`. Supply local attributes from your trusted backend's Customer data; `identify(customerToken)` authenticates requests but does not populate local bucketing attributes. These attributes are evaluation data, not authorization.
|
|
218
|
+
For Customer-based evaluation, `id` means the Longplay Customer UUID (`customer.id`); `externalUserId` means the merchant account ID (`customer.externalUserId`). Choose the experiment's `hashAttribute` explicitly when creating it and preserve that meaning in every consumer. Do not put the merchant account ID into `attributes.id`. Supply local attributes from your trusted backend's Customer data; `identify(customerToken)` authenticates requests but does not populate local bucketing attributes. These attributes are evaluation data, not authorization. Local rules read them. Remote rules read the verified Customer, so the SDK leaves `id`, `externalUserId`, `createdAt`, `ageDays` and `subscription` out of Remote requests.
|
|
219
219
|
|
|
220
220
|
`setAttributes()` replaces the complete object, so retain the bucketing fields on every update. Anonymous page/visual experiments instead default `id` and `deviceId` to the shared first-party device cookie; they do not automatically match an account-based experiment. An open visual client rereads its payload every 60 seconds while visible, so a stopped experiment or disabled delivery reverts without a page reload. Sticky capabilities differ by adapter: managed Local Run instructions receive server state, while pure local tools require their existing host persistence adapter for durable Sticky. No new shared state is introduced. See the [architecture boundary](../../docs/growthbook-sdk-delivery.md#cross-consumer-evaluation-and-bucketing-identity).
|
|
221
221
|
|
|
@@ -271,9 +271,13 @@ unsubscribe();
|
|
|
271
271
|
flags.destroy();
|
|
272
272
|
```
|
|
273
273
|
|
|
274
|
+
`flush()` resolves with `inserted`, `duplicates`, `skipped` and `rejected` counts, plus `rejections`: one `{ eventUuid, reason }` for each event the server refused. A refused event is final and does not affect the rest of its batch. The queue holds 500 events; if the service stays unavailable, a batch is given up after five attempts so later events are not held back.
|
|
275
|
+
|
|
274
276
|
The selected environment's integration settings control behavior events, experiment exposures and Feature usage independently. New environments enable behavior events, experiment exposures and Feature usage collection. `flush()` includes a `skipped` count for intentionally disabled collection. The database rechecks every batch, including direct SDK/server and Funnel ingestion. Running experiment/Bandit dependencies prevent incompatible collection changes. These controls do not delete history or affect commercial usage accounting.
|
|
275
277
|
|
|
276
|
-
Flags default to local evaluation; Owner/Admin can switch each flag to server evaluation. Server-evaluated flags deliver only keys and results, using the caller's fallback until the first result arrives. Attribute changes immediately discard old results. List hashes are not a secrecy boundary. Local Funnels cannot depend on server-evaluated flags; mode switches also check active historical Runs. `identify` / `reset` release the previous identity's Feature instances and event queue.
|
|
278
|
+
Flags default to local evaluation; Owner/Admin can switch each flag to server evaluation. Server-evaluated flags deliver only keys and results, using the caller's fallback until the first result arrives. A failed evaluation keeps the fallback and reports to the `onError` option of `features()`. Attribute changes immediately discard old results. List hashes are not a secrecy boundary. Local Funnels cannot depend on server-evaluated flags; mode switches also check active historical Runs. `identify` / `reset` release the previous identity's Feature instances and event queue.
|
|
279
|
+
|
|
280
|
+
A direct `evaluateFeatures` call for a Customer sends request context only: a Customer session or a Server Key with `customerId` gets `INVALID_REQUEST` naming any of those five fields it sends. A Server Key without `customerId` evaluates its attributes as sent.
|
|
277
281
|
|
|
278
282
|
Merchandise targeting resolves a trusted item in the selected App/environment. Register its attributes and maintain the
|
|
279
283
|
item in Console, then pass a reference rather than item metadata. The SDK resolves the initial SKU before returning;
|
package/README.zh-CN.md
CHANGED
|
@@ -187,7 +187,7 @@ Local/Remote 求值策略由每个 Funnel 决定。`createFunnelDecisionClient
|
|
|
187
187
|
|
|
188
188
|
Funnel、独立 Feature 和页面实验各自求值、各自使用结果。App/环境、实验定义、属性、分桶身份及 Sticky 状态相同时结果应一致;刷新时间或输入不同时允许不同组。Remote Funnel 引用允许 Local 定义投递的代码 Experiment 时,仍由 Longplay 计算。已接受的 Funnel 决定保留原结果,不做跨功能结果同步。
|
|
189
189
|
|
|
190
|
-
Customer 求值中的 `id` 是 Longplay Customer UUID(`customer.id`),`externalUserId` 是商户账号 ID(`customer.externalUserId`)。创建实验时明确选择 `hashAttribute`,每个消费方保持相同语义;不要把商户账号 ID 填进 `attributes.id`。本地属性来自可信后端给当前用户的 Customer 数据;`identify(customerToken)`
|
|
190
|
+
Customer 求值中的 `id` 是 Longplay Customer UUID(`customer.id`),`externalUserId` 是商户账号 ID(`customer.externalUserId`)。创建实验时明确选择 `hashAttribute`,每个消费方保持相同语义;不要把商户账号 ID 填进 `attributes.id`。本地属性来自可信后端给当前用户的 Customer 数据;`identify(customerToken)` 负责请求认证,不会自动补齐本地分桶属性。属性仅用于求值,不构成授权。本地规则读取这些属性;远程规则读取已验证的 Customer,因此 SDK 不会把 `id`、`externalUserId`、`createdAt`、`ageDays` 和 `subscription` 放进远程请求。
|
|
191
191
|
|
|
192
192
|
`setAttributes()` 替换整个对象,每次更新都保留分桶字段。匿名页面/视觉实验默认的 `id` 和 `deviceId` 来自共用的第一方设备 cookie,不自动与账号实验同组。已打开的页面在可见时每 60 秒重新读取视觉配置,实验停止或关闭投放后无需刷新页面即可撤销修改。各适配器的 Sticky 能力有区别:共用 Run 的 Local 指令读取服务端状态,纯本地工具的持久 Sticky 使用已有宿主适配器,不新增共享状态。完整要求见[架构边界](../../docs/growthbook-sdk-delivery.md#cross-consumer-evaluation-and-bucketing-identity)。
|
|
193
193
|
|
|
@@ -243,7 +243,9 @@ unsubscribe();
|
|
|
243
243
|
flags.destroy();
|
|
244
244
|
```
|
|
245
245
|
|
|
246
|
-
每个 flag 默认本地计算,Owner/Admin 可切换为服务器计算。服务器 flag
|
|
246
|
+
每个 flag 默认本地计算,Owner/Admin 可切换为服务器计算。服务器 flag 只下发键与结果,首次结果到达前使用调用方默认值;求值失败时保留默认值,并通过 `features()` 的 `onError` 选项报告;属性变化立即丢弃旧结果。名单哈希不等于保密,敏感规则应使用服务器计算。本地 Funnel 不得依赖服务器 flag,切换时也会校验仍在运行的历史版本。`identify` / `reset` 会释放旧身份的功能实例和事件队列。
|
|
247
|
+
|
|
248
|
+
为 Customer 直接调用 `evaluateFeatures` 时只传请求上下文:Customer 会话或带 `customerId` 的 Server Key 传入上述五个字段时,返回写明字段名的 `INVALID_REQUEST`。不带 `customerId` 的 Server Key 按传入的属性求值。
|
|
247
249
|
|
|
248
250
|
商品定向使用当前 App/环境的可信商品主档。在 Console 登记属性并维护商品后,传入 `merchandise: { id: "sku-outdoor" }` 引用;SDK 在返回 Feature 客户端之前解析商品。切换商品后,先调用 `setAttributes({ ...bucketingIdentity, merchandise: { id: "sku-indoor" } })`,再等待 `refreshRemote()` 后读取决策。商品实验使用服务端解析的 `merchandiseId`(内部 UUID),不能回退到人的分桶标识。请求中的商品属性不能覆盖主档。
|
|
249
251
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { LanguageModelV4Usage, LanguageModelV4Middleware } from '@ai-sdk/provider';
|
|
2
|
-
import { F as FoundationApi, A as ApiInput } from './api-
|
|
2
|
+
import { F as FoundationApi, A as ApiInput } from './api-BDUQ1udV.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
|
|
5
5
|
declare const tokenCounts: z.ZodObject<{
|
|
@@ -1663,19 +1663,59 @@ declare const apiOperations: {
|
|
|
1663
1663
|
readonly audience: "mixed";
|
|
1664
1664
|
readonly request: z$1.ZodObject<{
|
|
1665
1665
|
customerId: z$1.ZodOptional<z$1.ZodUUID>;
|
|
1666
|
-
events: z$1.ZodArray<z$1.ZodObject<{
|
|
1666
|
+
events: z$1.ZodArray<z$1.ZodDiscriminatedUnion<[z$1.ZodObject<{
|
|
1667
|
+
kind: z$1.ZodLiteral<"custom">;
|
|
1668
|
+
name: z$1.ZodString;
|
|
1669
|
+
properties: z$1.ZodDefault<z$1.ZodRecord<z$1.ZodString, z$1.ZodJSONSchema>>;
|
|
1667
1670
|
eventUuid: z$1.ZodUUID;
|
|
1668
1671
|
timestamp: z$1.ZodISODateTime;
|
|
1669
|
-
name: z$1.ZodString;
|
|
1670
1672
|
merchandise: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodObject<{
|
|
1671
1673
|
id: z$1.ZodString;
|
|
1672
1674
|
}, z$1.core.$strict>, z$1.ZodObject<{
|
|
1673
1675
|
internalId: z$1.ZodUUID;
|
|
1674
1676
|
}, z$1.core.$strict>]>>;
|
|
1675
|
-
properties: z$1.ZodDefault<z$1.ZodRecord<z$1.ZodString, z$1.ZodJSONSchema>>;
|
|
1676
1677
|
deviceId: z$1.ZodOptional<z$1.ZodString>;
|
|
1677
1678
|
sessionId: z$1.ZodOptional<z$1.ZodString>;
|
|
1678
|
-
}, z$1.core.$strict
|
|
1679
|
+
}, z$1.core.$strict>, z$1.ZodObject<{
|
|
1680
|
+
kind: z$1.ZodLiteral<"experiment_exposure">;
|
|
1681
|
+
experimentId: z$1.ZodString;
|
|
1682
|
+
variationId: z$1.ZodString;
|
|
1683
|
+
generation: z$1.ZodString;
|
|
1684
|
+
eventUuid: z$1.ZodUUID;
|
|
1685
|
+
timestamp: z$1.ZodISODateTime;
|
|
1686
|
+
merchandise: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodObject<{
|
|
1687
|
+
id: z$1.ZodString;
|
|
1688
|
+
}, z$1.core.$strict>, z$1.ZodObject<{
|
|
1689
|
+
internalId: z$1.ZodUUID;
|
|
1690
|
+
}, z$1.core.$strict>]>>;
|
|
1691
|
+
deviceId: z$1.ZodOptional<z$1.ZodString>;
|
|
1692
|
+
sessionId: z$1.ZodOptional<z$1.ZodString>;
|
|
1693
|
+
}, z$1.core.$strict>, z$1.ZodObject<{
|
|
1694
|
+
kind: z$1.ZodLiteral<"feature_usage">;
|
|
1695
|
+
feature: z$1.ZodString;
|
|
1696
|
+
value: z$1.ZodJSONSchema;
|
|
1697
|
+
source: z$1.ZodEnum<{
|
|
1698
|
+
override: "override";
|
|
1699
|
+
unknownFeature: "unknownFeature";
|
|
1700
|
+
defaultValue: "defaultValue";
|
|
1701
|
+
force: "force";
|
|
1702
|
+
experiment: "experiment";
|
|
1703
|
+
prerequisite: "prerequisite";
|
|
1704
|
+
cyclicPrerequisite: "cyclicPrerequisite";
|
|
1705
|
+
}>;
|
|
1706
|
+
ruleId: z$1.ZodString;
|
|
1707
|
+
variationId: z$1.ZodOptional<z$1.ZodString>;
|
|
1708
|
+
generation: z$1.ZodString;
|
|
1709
|
+
eventUuid: z$1.ZodUUID;
|
|
1710
|
+
timestamp: z$1.ZodISODateTime;
|
|
1711
|
+
merchandise: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodObject<{
|
|
1712
|
+
id: z$1.ZodString;
|
|
1713
|
+
}, z$1.core.$strict>, z$1.ZodObject<{
|
|
1714
|
+
internalId: z$1.ZodUUID;
|
|
1715
|
+
}, z$1.core.$strict>]>>;
|
|
1716
|
+
deviceId: z$1.ZodOptional<z$1.ZodString>;
|
|
1717
|
+
sessionId: z$1.ZodOptional<z$1.ZodString>;
|
|
1718
|
+
}, z$1.core.$strict>], "kind">>;
|
|
1679
1719
|
}, z$1.core.$strict>;
|
|
1680
1720
|
readonly response: z$1.ZodObject<{
|
|
1681
1721
|
requestId: z$1.ZodUUID;
|
|
@@ -1690,6 +1730,15 @@ declare const apiOperations: {
|
|
|
1690
1730
|
duplicates: z$1.ZodNumber;
|
|
1691
1731
|
rejected: z$1.ZodNumber;
|
|
1692
1732
|
skipped: z$1.ZodNumber;
|
|
1733
|
+
rejections: z$1.ZodArray<z$1.ZodObject<{
|
|
1734
|
+
eventUuid: z$1.ZodUUID;
|
|
1735
|
+
reason: z$1.ZodEnum<{
|
|
1736
|
+
invalid_event: "invalid_event";
|
|
1737
|
+
invalid_merchandise: "invalid_merchandise";
|
|
1738
|
+
not_delivered: "not_delivered";
|
|
1739
|
+
reserved_name: "reserved_name";
|
|
1740
|
+
}>;
|
|
1741
|
+
}, z$1.core.$strict>>;
|
|
1693
1742
|
analyticsConfig: z$1.ZodObject<{
|
|
1694
1743
|
eventsEnabled: z$1.ZodBoolean;
|
|
1695
1744
|
experimentViewsEnabled: z$1.ZodBoolean;
|
|
@@ -20438,4 +20487,4 @@ interface FoundationApi {
|
|
|
20438
20487
|
readModelBenefit(input: ApiInput<"readModelBenefit">): Promise<ApiOutput<"readModelBenefit">>;
|
|
20439
20488
|
}
|
|
20440
20489
|
|
|
20441
|
-
export type { ApiInput as A, FoundationApi as F, InvoiceModeParams as I, OfferingItem as O,
|
|
20490
|
+
export type { ApiInput as A, FoundationApi as F, InvoiceModeParams as I, OfferingItem as O, ApiOutput as a, InvoiceModeParamsInput as b };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as Ne}from"./chunk-XIYNQHN7.js";import{a as qe,b as De,c as ke,d as Fe,e as Se,f as ye}from"./chunk-FISFN5IY.js";import{a as w}from"./chunk-KHIQQNTR.js";import{b as Oe,e as _e}from"./chunk-SLUA7ABW.js";import{d as Te}from"./chunk-SR6CERFC.js";import{a as K}from"./chunk-DSPLGTQI.js";import{Z as Pe,la as we}from"./chunk-DBBUN53B.js";import{Da as Re,I as Ce,Na as Ee}from"./chunk-4SWGHICJ.js";function Ae(n){let O=n.view;if(!O?.paywall)throw new w("INVALID_REQUEST","The current node is not a Paywall");let e=O.paywall.receiptId,C=O.nodeId,c=O.visit,R=O.paywall.resolution,s=O.paywall,S="document"in R?{document:R.document,offering:R.offering,capabilities:R.capabilities}:null;function a(){let i=s.resolution;return"document"in i?i:S&&{...i,document:S.document,offering:S.offering,capabilities:qe(i.capabilities,S.capabilities)}}function p(i){if(!De(i,R))throw new w("INVALID_RESPONSE","The pinned Paywall binding changed")}let D=!1,v=new AbortController,y=(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===C&&i.visit===c&&i.input.type==="paywall_quote")?.requestId??O.paywall.purchaseRequestId,u=0,d=null,k=new Set,U=null,P=new Map;function A(i){if(i.purchase&&i.purchase.receiptId!==e)throw new w("INVALID_RESPONSE","Purchase receipt changed");let o=i.run.paywall;return i.purchase??(o?.receiptId===e?o:null)}function E(){if(D)throw new w("IDENTITY_CHANGED","Paywall presentation has closed")}function I(i,o,r){if(E(),o!==u||r!==void 0&&s.quote?.operationId!==r)return!1;let g=s.selectionGeneration??0,m=i.run.paywall;if(m?.receiptId===e){if((m.selectionGeneration??0)<(s.selectionGeneration??0))return!1;p(m.resolution)}let f=A(i),L=m?.receiptId===e&&(m.selectionGeneration??0)>g,$=L?f?.quote??null:f?.quote??s.quote,F=f?.operation??($?.operationId===s.quote?.operationId?s.operation:null);return $&&F&&ke(F,{operationId:$.operationId},"Purchase operation changed"),(L||$?.operationId!==s.quote?.operationId)&&(u++,m?.receiptId===e&&(y=m.purchaseRequestId)),s={...s,...m?.receiptId===e?m:{},quote:$,operation:Se(s.operation,F,!0)},!0}function V(i,o,r){return new Promise((g,m)=>{let f=!1,L=()=>{clearTimeout(T),v.signal.removeEventListener("abort",b)},$=te=>{f||(f=!0,L(),g(te))},F=te=>{f||(f=!0,L(),m(te))},b=()=>F(new w("IDENTITY_CHANGED","Paywall presentation has closed")),T=setTimeout(()=>F(new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,r)),Math.max(0,o-Date.now()));v.signal.addEventListener("abort",b,{once:!0}),v.signal.aborted&&b(),i.then($,F)})}function M(i){return new Promise(o=>{let r=()=>{clearTimeout(g),v.signal.removeEventListener("abort",r),o()},g=setTimeout(r,i);v.signal.addEventListener("abort",r,{once:!0}),v.signal.aborted&&r()})}function z(i,o){E();let r=P.get(i)??n.pendingCommands?.find(f=>f.requestId===i)??n.pendingCommand;if(r?.operation==="submit"&&r.requestId===i&&r.nodeId===C&&r.visit===c){o.type==="paywall_quote"&&r.input.type==="paywall_quote"&&r.input.predecessor&&!o.predecessor&&(o={...o,predecessor:r.input.predecessor});let f=we.parse(r),L=we.parse({...r,input:o});if(f.operation!=="submit"||L.operation!=="submit"||JSON.stringify(f.input)!==JSON.stringify(L.input))throw new w("CONFLICT","A purchase request cannot change its input");return P.set(i,f),f}let g=n.view;if(!g||g.nodeId!==C||g.visit!==c||g.paywall?.receiptId!==e)throw new w("PRECONDITION_FAILED","The Paywall visit has changed");let m=we.parse({operation:"submit",requestId:i,nodeId:C,visit:c,revision:g.revision,input:structuredClone(o)});if(m.operation!=="submit")throw new w("INVALID_REQUEST","A purchase submission is required");return P.set(i,m),m}async function J(i,o){E();let{requestId:r,input:g}=i,m=Date.now()+3e4;k.add(r);try{let f=await V(n.submit(i),m,r);for(;f.run.pendingRequest?.requestId===r&&Date.now()<m&&!D&&(await M(Math.min(1e3,m-Date.now())),!(D||Date.now()>=m));)f=await V(n.resume(r),m,r);if(D)throw new w("IDENTITY_CHANGED","Paywall presentation has closed");if(f.run.pendingRequest?.requestId===r)throw new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,r);if(!I(f,o,g.type==="paywall_confirm"||g.type==="paywall_cancel"?g.operationId:void 0))throw new w("PRECONDITION_FAILED","The purchase selection has changed");U===r&&(U=null)}catch(f){throw U=r,f instanceof w&&f.code==="COMMAND_PENDING"&&f.status===void 0&&P.delete(r),f}finally{k.delete(r)}}async function X(i){if(!s.quote)throw new w("INVALID_REQUEST","A quoted purchase is required");let o=i==="confirm"?"paywall_confirm":"paywall_cancel",r=[...P.values(),...n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])].find(m=>m.operation==="submit"&&m.input.type===o&&"operationId"in m.input&&m.input.operationId===s.quote.operationId),g=r?.operation==="submit"&&r.input.type===o&&"operationId"in r.input&&r.input.operationId===s.quote.operationId?r.requestId:crypto.randomUUID();if(await J(z(g,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:s.quote.operationId}),u),!s.operation)throw new w("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(s.operation)}return{get view(){return structuredClone(a())},get quote(){return s.quote?structuredClone(s.quote):null},get operation(){return s.operation?structuredClone(s.operation):null},get webViewUrl(){return n.webViewUrl},get canReselect(){return s.canReselect===!0},get recovery(){let i=n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[]),o=n.pendingPurchase;if(o&&(o.receiptId!==e||o.operationId!==s.quote?.operationId))return{type:"recover",operationId:o.operationId,requestId:i[0]?.requestId??null};let r=ye({quote:s.quote,operation:s.operation,requestId:i[0]?.requestId??U??y,pending:k.size>0||i.length>0||U!==null,destroyed:D,canReselect:s.canReselect});return r.type==="recover"&&r.requestId===null&&!D&&n.hasDurableJournal===!0&&!s.quote&&!s.operation&&(s.selectionGeneration??0)===0&&!o&&!i.length&&!k.size&&!y?{type:"native",operationId:null}:r},get pendingCancellation(){return!D&&(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===C&&i.visit===c&&i.input.type==="paywall_cancel"&&i.input.operationId===s.quote?.operationId)},async refresh(){E();let i=u,o=await n.get();if(I(o,i),o.run.paywall?.receiptId!==e)throw new w("PRECONDITION_FAILED","Paywall presentation has changed");if(!a()){if("document"in s.resolution||!n.resolvePaywall)throw new w("INVALID_RESPONSE","Public Paywall reader is unavailable");let r=await n.resolvePaywall(s.resolution);E(),p(r),S={document:r.document,offering:r.offering,capabilities:r.capabilities}}return structuredClone(a())},preview(i){let o=a();if(!o)return Promise.reject(new w("PRECONDITION_FAILED","Load the Paywall presentation first"));if(y&&y!==i.requestId&&(d||s.canReselect!==!0))return Promise.reject(new w("COMMAND_PENDING","Retry the original purchase before starting another"));let r=o.document.buttons[i.actionId],g=r?.type==="checkout"?Pe(r.product,i.selection,o.capabilities):null;if(!g)return Promise.reject(new w("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let m=Ee(o.document.screen,g,i.selection,o.capabilities),f=y!==i.requestId&&(s.selectionGeneration??0)>0?{operationId:s.quote?.operationId??null,generation:s.selectionGeneration??0}:void 0;if(f&&s.canReselect!==!0)return Promise.reject(new w("COMMAND_PENDING","Original purchase requires authoritative termination"));let L;try{L=z(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:g,...Object.keys(m).length?{featureQuantities:m}:{},...f?{predecessor:f}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}})}catch(b){return Promise.reject(b)}if(y===i.requestId&&d)return d;y!==i.requestId&&u++;let $=u;y=i.requestId;let F=(async()=>{if(await J(L,$),!s.quote)throw new w("INVALID_RESPONSE","The accepted quote is missing");return Fe(s.quote,{productVersionId:g,featureQuantities:m},"The selected purchase changed"),structuredClone(s.quote)})();return d=F,F.then(()=>{d===F&&(d=null)},b=>{d===F&&(d=null),y===i.requestId&&n.pendingCommand?.requestId!==i.requestId&&b instanceof w&&b.status!==void 0&&b.status<500&&![401,425].includes(b.status)&&(y=null)}),F},confirm:()=>X("confirm"),cancel:()=>X("cancel"),async read(){if(E(),!s.quote)throw new w("INVALID_REQUEST","A quoted purchase is required");let i=s.quote.operationId,o=u,r=n.pendingCommands?.find($=>$.operation==="submit"&&($.input.type==="paywall_confirm"||$.input.type==="paywall_cancel")&&$.input.operationId===i)??n.pendingCommand;r?.operation==="submit"&&(r.input.type==="paywall_confirm"||r.input.type==="paywall_cancel")&&r.input.operationId===i&&await n.settle?.(r.requestId);let g=await n.get(void 0,{receiptId:e,operationId:i});E();let m=A(g);if(m?.quote&&m.quote.operationId!==i||m?.operation&&m.operation.operationId!==i)throw new w("INVALID_RESPONSE","Purchase operation changed");let f=I(g,o,i),L=f?s.operation:m?.operation;if(!L)throw new w("INVALID_RESPONSE","The current purchase result is missing");return f&&k.size===0&&!(n.pendingCommands?.length??(n.pendingCommand?1:0))&&(U=null),structuredClone(L)},destroy(){D=!0,v.abort(),P.clear()}}}function Ve(n){let O=new Set,e=new Set,C=null;async function c(a,p){let D=!1;for(;!n.stopped&&n.key===a&&n.client.pendingCommand?.requestId===p;){if(!n.client.settle)throw new w("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(p),D=!0,n.client.pendingCommand?.requestId===p&&await new Promise(v=>setTimeout(v,1500))}n.stopped||n.key!==a||(D&&await n.client.get(),!(n.stopped||n.key!==a)&&O.add(a))}function R(a,p){C=p;let D=()=>{C===p&&(C=null),e.delete(a)};return p.then(D,v=>{D(),n.busy||n.fail(v)}),p}function s(a){if(n.reviewing||O.has(a)||e.has(a)||n.stopped)return;e.add(a);let p=async()=>{if(n.reviewing||n.stopped||n.key!==a||O.has(a)){e.delete(a);return}if(n.busy||n.client.pendingCommand){setTimeout(()=>{p()},250);return}let D=(async()=>{let v=n.client.view,G=n.expected(),y=G.requestId;try{await n.client.submit({operation:"shown",...G})}catch(u){if(!(u instanceof w)||u.code!=="CONFLICT"||u.status!==409||n.client.pendingCommand)throw u;await n.client.get();let d=n.client.view;if(n.stopped||n.reviewing||n.key!==a||!d||!v||d.id!==v.id||d.source.versionId!==v.source.versionId||d.nodeId!==G.nodeId||d.visit!==G.visit||d.revision<=G.revision||d.stopped||!d.screen&&(!d.paywall||d.paywall.receiptId!==v.paywall?.receiptId)||!["running","waiting"].includes(d.status)||n.client.pendingCommand)throw u;let k=n.expected();y=k.requestId,await n.client.submit({operation:"shown",...k})}await c(a,y)})();R(a,D)};p()}function S(){if(C)return C;let a=n.client.pendingCommand;if(a?.operation!=="shown")return null;let p=n.key;return e.add(p),R(p,(async()=>{await n.client.retry(),await c(p,a.requestId)})())}return{report:s,settled:S,get inFlight(){return C}}}function Le(n){let O={},e=new Map;async function C(c){let R=n.client.view,s=R?.screen,S=s?.customerData.nodes[c.nodeId];if(n.stopped||n.busy||!R||!s||!S)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(c.action)){let u=n.document,d=u?Re(u,c.nodeId):null,k=d?.type==="customer_data"?d.data.outputs?.[c.action]:void 0;k&&s.outputs.includes(k)?await n.perform(()=>n.client.submit({operation:"submit",...n.expected(),input:{type:"screen",output:k,answers:n.answers,selection:c.value?{[c.nodeId]:c.value}:{}}})):await n.onIntent?.(c,R);return}let p=c.action.startsWith("sources_")?S.resources.find(u=>u.key===c.value):null;if(c.action.startsWith("sources_")&&!p)throw new w("INVALID_REQUEST","Choose a current resource");let D=`${R.visit}:${c.nodeId}:${p?.key??""}`,v=e.get(D)??[null],y=O[c.nodeId]??{page:1,after:null,filter:"all",...p?{resourceKey:p.key}:{}};if(c.action==="filter"){let u=c.value;if(!u||!(S.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(u))throw new w("INVALID_REQUEST","Unknown data filter");y={page:1,after:null,filter:u},v.splice(0,v.length,null)}else if(c.action==="next"||c.action==="sources_next"){let u=p?.sources.at(-1),d=p?u?{kind:"ledger",cursor:{at:u.detail[0],id:u.id,type:"source"}}:null:s.dataCursors[c.nodeId];if(!d||!p&&!S.hasNext)return;v[y.page]=d,y={...y,page:y.page+1,after:d}}else if(c.action==="previous"||c.action==="sources_previous"){if(y.page<=1)return;y={...y,page:y.page-1,after:v[y.page-2]??null}}e.set(D,v),O={...O,[c.nodeId]:y},await n.perform(()=>n.client.get({nodeId:R.nodeId,visit:R.visit,revision:R.revision,components:O}))}return{get queries(){return O},intent:C,reset(){O={},e.clear()}}}function $e(n){let{doc:O,holder:e,reviewHolder:C,mountScreenPreview:c}=n,R=!1,s,S=0,a=null,p="",D=new Map,v=u=>u?`${u.id}:${u.nodeId}:${u.visit}:${u.revision}:${u.paywall?.quote?.operationId??""}`:"";async function G(u){if(n.stopped||!n.client.review)return;R||(p=v(n.client.view),D.set(p,structuredClone(n.answers))),R=!0,s=u,e.hidden=!0,n.suspend(!0),C.hidden=!1;let d=++S;try{let k=await n.client.review(u);if(n.stopped||d!==S||!R)return;if(!k.review)throw new w("INVALID_RESPONSE","Historical projection is missing");a?.destroy(),a=null,C.replaceChildren();let U=k.run.locale.startsWith("zh"),P=O.createElement("p");P.textContent=U?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",C.append(P);for(let[I,V]of k.review.pages.entries()){let M=O.createElement("button");M.type="button",M.textContent=U?`\u7B2C ${I+1} \u9875`:`Page ${I+1}`,M.onclick=()=>{G(V.receiptId)},C.append(M)}if(k.review.page){let I=k.review.page,V=O.createElement("div");if(V.inert=!0,C.append(V),a=c(V,{mode:"live",rendererUrl:n.client.webViewUrl,title:I.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{y()}}),a.update(I.document,k.run.locale,{serverInput:{bindings:I.inputs,answers:I.answers,values:I.values}}),await a.ready,n.stopped||d!==S||!R)return}let A=U?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},E=U?{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"};for(let I of[...k.review.coupons.map((V,M)=>`${U?"\u4F18\u60E0\u5238":"Coupon"} ${M+1}: ${A[V.status]}`),...k.review.purchases.map((V,M)=>`${U?"\u8D2D\u4E70":"Purchase"} ${M+1}: ${E[V.status]}`)]){let V=O.createElement("p");V.textContent=I,C.append(V)}n.client.view&&await n.enqueue(n.client.view)}catch(k){if(d!==S||n.stopped)return;a?.destroy(),a=null,C.replaceChildren(),n.fail(k)}}async function y(){if(!R||n.stopped||!n.client.review)return;let u=++S;try{if(await n.client.review(),n.stopped||u!==S)return;R=!1,S++,a?.destroy(),a=null,C.replaceChildren(),C.hidden=!0,e.hidden=!1;let d=n.client.view;v(d)!==p?(D.set(p,structuredClone(n.answers)),n.resetScreen()):(D.delete(p),n.suspend(!1)),d&&await n.enqueue(d)}catch(d){if(u!==S||n.stopped)return;a?.destroy(),a=null,C.replaceChildren(),n.fail(d)}}return{get active(){return R},get receipt(){return s},open:G,exit:y,get drafts(){return new Map([...D].map(([u,d])=>[u,structuredClone(d)]))},stop(){R=!1,S++,a?.destroy(),a=null,C.replaceChildren(),C.hidden=!0,e.hidden=!1}}}function Ue(n){if(!n.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let O=n.client.pageExperiments.bind(n.client),e=!1,C=!1,c=0,R=!1,s=!1,S,a=new Map,p=new Set,D={},v=new Map,G=Oe(n.appManifestRelease),y=()=>{for(let A of a.values())A.effect.revert();a.clear();for(let A of v.values())A();v.clear()};function u(A){if(e||p.has(A))return;p.add(A);let E=c;O(n.appManifestRelease,[A]).catch(I=>{p.delete(A),!e&&E===c&&K(n.onError,I)})}async function d(){if(e)return;let A=n.client.view;if(!A||A.stopped||!["running","waiting"].includes(A.status)){c++,y();return}if(R){s=!0;return}R=!0;let E=++c,I=`${A.id}:${A.visit}:${A.revision}`,V=location.href;try{let[M,{applyVisualVariation:z}]=await Promise.all([O(n.appManifestRelease),import("./visual-dom-7IF7ITAK.js")]),J=n.client.view;if(e||E!==c||!J||J.stopped||!["running","waiting"].includes(J.status)||`${J.id}:${J.visit}:${J.revision}`!==I||location.href!==V)return;let X=new Set,i=new Set;for(let o of M.assignments){let r=`${M.payload.environmentId}:${o.experimentKey}`;if(i.add(r),v.has(r)||v.set(r,_e(r,D)),!!o.inExperiment)for(let g of M.payload.experiments){if(g.key!==o.experimentKey||!Ce(location.href,g.urlPatterns??[]))continue;let m=g.meta?.findIndex(T=>T.key===o.variationKey)??-1,f=g.variations[m];if(!f?.renderGuard)continue;let L=o.receiptId+":"+g.changeId,$=JSON.stringify([o.variationKey,f]);X.add(L);let F=a.get(L);if(F?.signature===$){F.effect.applied&&u(o.receiptId);continue}a.get(L)?.effect.revert(),a.delete(L);let b=z(f,{requireUniqueTargets:!0,boundVariations:g.variations,allowJs:!1,onApplied:()=>u(o.receiptId),onError:T=>K(n.onError,T)});a.set(L,{signature:$,effect:b}),b.applied&&u(o.receiptId)}}for(let[o,r]of a)X.has(o)||(r.effect.revert(),a.delete(o));for(let[o,r]of v)i.has(o)||(r(),v.delete(o))}catch(M){E===c&&y(),!e&&E===c&&K(n.onError,M)}finally{R=!1,s&&!e&&(s=!1,d())}}let k=n.client.subscribe(()=>{c++,d()}),U=Te(()=>{c++,y(),d()}),P=async()=>{await d(),e||(S=setTimeout(()=>{P()},15e3))};return{async start(){C||e||(C=!0,await P())},refresh:d,destroy(){e=!0,c++,clearTimeout(S),k(),U(),y(),G.destroy()}}}async function hn(n,O){let e=O,{mountScreenPreview:C}=await import("./screen-renderer-ZNELQB64.js"),{showPaywall:c}=await import("./paywall-5RZ3NFHB.js"),R=e.appManifestRelease?Ue({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;R?.start();let s=n.ownerDocument,S=s.activeElement,a=s.createElement("section"),p=s.createElement("div"),D=s.createElement("div"),v=s.createElement("div"),G=s.createElement("button");v.hidden=!0,G.type="button";let y=s.createElement("p"),u=s.createElement("p"),d=s.createElement("button"),k=s.createElement("button"),U=s.createElement("button"),P=s.createElement("dialog"),A;a.dataset.indianaFunnel="",a.setAttribute("aria-busy","false"),a.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",D.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",y.setAttribute("role","status"),u.setAttribute("role","alert"),u.hidden=!0,d.type=k.type=U.type="button",D.append(d,y,u,U,G,k),a.append(p,v,D),n.append(a);let E=null,I=null,V=null,M="",z="",J="",X="",i="",o=!1,r=0,g=!1,m="",f=null,L=Promise.resolve(),$=null,F=null,b=null,T=null;function te(){return b&&e.client.hasDurableJournal===!0&&T?.acknowledged===!0&&T.operationId===b.operationId&&e.client.view?.id===T.runId&&e.client.view?.status==="closed"&&e.client.view.revision===T.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?b:null}function Ie(t){let l=t.run.paywall;if(T&&t.settlement?.requestId===T.requestId&&t.settlement.state==="settled"&&t.settlement.operationId===null&&t.run.id===T.runId&&t.run.status==="closed"&&!t.run.pendingRequest&&t.run.revision===T.revision+1&&t.run.nodeId===T.nodeId&&t.run.visit===T.visit&&l?.receiptId===T.receiptId&&l.selectionGeneration===T.selectionGeneration&&(l.quote?.operationId??null)===T.operationId&&(l.operation?.operationId??l.quote?.operationId??null)===T.operationId){let h=T.operationId===null&&l.selectionGeneration===0&&!l.quote&&!l.operation&&!l.purchaseRequestId,N=ye({quote:l.quote,operation:l.operation,requestId:l.purchaseRequestId,pending:!1,destroyed:!1,canReselect:l.canReselect});(h||l.canReselect===!0&&N.type==="native")&&(T.acknowledged=!0)}}let re=null,pe=new Set,B={},W=(t,l=null)=>{o||(re=l,u.textContent=t instanceof Error?t.message:"Request failed",u.hidden=!1,U.hidden=e.client.pendingCommand===null,K(e.onError,t))};function ie(){let t=e.client.view;if(!t)throw new w("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let _=$e({client:e.client,doc:s,holder:p,reviewHolder:v,mountScreenPreview:C,get stopped(){return o},get answers(){return B},suspend(t){I?.setSuspended(t)},resetScreen(){M="",z="",J=""},enqueue:Z,fail:W}),ue=Ve({client:e.client,expected:ie,fail:W,get stopped(){return o},get reviewing(){return _.active},get key(){return M},get busy(){return r}}),fe=Le({client:e.client,expected:ie,perform:oe,onIntent:e.onCustomerDataIntent,get stopped(){return o},get busy(){return r},get document(){return E?.document},get answers(){return B}}),ge=t=>t&&(t.screen||t.paywall)?`${t.id}:${t.nodeId}:${t.visit}`:"";function de(){let t=e.client.view;d.disabled=!_.active&&(r>0||!!e.client.pendingCommand||!t?.canBack||t.stopped||!["running","waiting"].includes(t.status)||!ge(t)||z!==ge(t))}async function he(t){if(!t)return;let l=e.client.view;await t;let h=e.client.view;if(!l||!h||h.id!==l.id||h.nodeId!==l.nodeId||h.visit!==l.visit||h.stopped||!["running","waiting"].includes(h.status))throw new w("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function oe(t,l=!1){if(!((r||F||b)&&!l||o||_.active&&!l)){r++,a.setAttribute("aria-busy","true"),de(),u.hidden=!0,re=null;try{if(l||await he(ue.inFlight),o)return;let h=await t();o||await Z(e.client.view??h.run)}catch(h){W(h,e.client.pendingCommand?.requestId??null)}finally{r=Math.max(0,r-1),a.setAttribute("aria-busy",String(r>0)),o||(U.hidden=e.client.pendingCommand===null,de())}}}function me(){f&&clearTimeout(f),!(o||!V||!["running","waiting"].includes(V.status)&&!e.client.pendingCommand)&&(f=setTimeout(()=>{f=null,be().finally(me)},V.pendingRequest||e.client.pendingCommand?1500:5e3))}async function be(){if(!(o||g||r)){if(_.active){await _.open(_.receipt);return}g=!0;try{let t=e.client.pendingCommand;t&&e.client.settle&&await e.client.settle(t.requestId);let l=e.client.view,h=fe.queries,N=await e.client.get(l?.screen&&Object.keys(h).length?{nodeId:l.nodeId,visit:l.visit,revision:l.revision,components:h}:void 0);!o&&h===fe.queries&&await Z(e.client.view??N.run)}catch(t){W(t)}finally{g=!1}}}function Me(t){let l=t.screen?.presentation;if(!l||l.type==="inline"){P.open&&P.close(),a.parentElement!==n&&n.append(a);return}a.parentElement!==P&&(P.append(a),n.append(P));let h={sm:420,md:640,lg:900};P.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in l?h[l.size]+"px":"100vw"}`,P.setAttribute("aria-label",(A?.screen===t.screen?.content.document.name?A?.label:void 0)??E?.document?.name??t.screen?.content.document.name??"Funnel"),P.open||(P.showModal(),Ne(P,l.type))}async function He(t){if(o)return;V=t,re&&e.client.pendingCommand?.requestId!==re&&(u.hidden=!0,re=null);let l=t.locale.startsWith("zh");if(G.textContent=l?"\u56DE\u770B":"History",G.hidden=!e.client.review,d.textContent=_.active?l?"\u8FD4\u56DE\u5F53\u524D":"Return to current":l?"\u8FD4\u56DE":"Back",k.textContent=l?"\u5173\u95ED":"Close",U.textContent=l?"\u91CD\u8BD5":"Retry",de(),U.hidden=e.client.pendingCommand===null,y.textContent=t.pendingRequest?l?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?l?"\u7B49\u5F85\u4E2D":"Waiting":"",m!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(m=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,K(e.onState,structuredClone(t))),!t.pendingRequest&&["closed","ineligible","failed"].includes(t.status)){se();return}if(t.stopped||e.client.configurationReady===!1){_.stop(),E?.destroy(),E=null,I?.destroy(),I=null,p.replaceChildren(),M="",z="",J="",i="",P.open&&P.close(),a.hidden=!0,me();return}if(a.hidden=!1,_.active){me();return}let h=ge(t);if(h!==M&&(z="",E?.destroy(),E=null,I?.destroy(),I=null,p.replaceChildren(),M=h,J="",i="",B={...t.answers},fe.reset()),Me(t),t.screen){let x=t.screen.content;E||(E=C(p,{mode:"live",rendererUrl:e.client.webViewUrl,title:x.document.name,onAction(q,ae={},Q={}){if(_.active)return;B={...B,...Q};let j=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:ne})=>Object.hasOwn(B,ne)).map(({variable:ne})=>[ne,B[ne]]));oe(()=>e.client.submit({operation:"submit",...ie(),input:{type:"screen",output:q,answers:j,selection:ae}}))},onAnswers:q=>{_.active||(B={...B,...q})},onCustomerDataIntent:q=>{_.active||fe.intent(q).catch(W)},onEscape:()=>{_.active||F||b||ce()},onError:q=>W(new Error(q)),onRendered:q=>{if(!q)return ue.report(h);A={screen:x.document.name,label:q},P.open&&P.setAttribute("aria-label",q),ue.report(h)}}));let H={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:B,values:t.screen.values}},ee=JSON.stringify([x,t.locale,H.parameters,t.screen.inputs,t.screen.values]);if(ee!==J)E.update(x.document,t.locale,H),J=ee,X=JSON.stringify(H.capabilities),i=JSON.stringify(H.customerData);else{let q=JSON.stringify(H.capabilities);q!==X&&(E.updateCapabilities(H.capabilities),X=q),JSON.stringify(H.customerData)!==i&&(E.updateCustomerData(H.customerData),i=JSON.stringify(H.customerData))}await E.ready}else if(t.paywall&&!I){let x=await c(p,{canInteract:()=>!_.active&&!o&&!F&&!b,beforeAction:async()=>{r++;try{await he(ue.settled()),u.hidden=!0,re=null}finally{r=Math.max(0,r-1)}},start:async()=>Ae(e.client),onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,resolveOfferId:e.resolveOfferId,onEvent:e.onEvent,onOpenUrl:H=>e.onOpenUrl?e.onOpenUrl({receiptId:t.paywall.receiptId,url:H,openIn:"same_window"}):s.defaultView?.location.assign(H),onAction:async H=>{if(_.active)return;let ee=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:e.client.view?.revision??t.revision,input:{type:"screen",output:H,answers:{}}});await Z(e.client.view??ee.run)},onError:W,onDismiss:()=>{!_.active&&!o&&!F&&!b&&e.client.view?.visit===t.visit&&ce()}});o?x.host?.destroy():(I=x.host,I?.setSuspended(_.active)),ue.report(h)}if(o)return;z=h,de();let N=t.instruction;if(N&&(N.type==="open_url"||N.type==="event")&&!pe.has(N.receiptId)){let x=s.createElement("button");x.type="button",x.textContent=N.type==="open_url"?`${l?"\u524D\u5F80":"Continue to"} ${new URL(N.url).host}`:l?"\u7EE7\u7EED":"Continue",x.onclick=()=>{let H=ie(),ee=N.type==="open_url"&&!e.onOpenUrl&&N.openIn==="new_window"?Ge(N.url):null;oe(async()=>{let q="success";if(N.type==="open_url")if(e.onOpenUrl)try{q=await e.onOpenUrl({receiptId:N.receiptId,url:N.url,openIn:N.openIn})===!1?"failed":"opened"}catch(Q){K(e.onError,Q),q="failed"}else q=N.openIn==="new_window"&&!ee?"failed":"opened";if(N.type==="event"){if(!e.onEvent)throw new w("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(N.event)}if(o||e.client.view?.nodeId!==H.nodeId||e.client.view.visit!==H.visit)throw new w("PRECONDITION_FAILED","The client action visit changed");let ae=await e.client.submit({operation:"submit",...H,input:{type:"client_action",receiptId:N.receiptId,outcome:q}});return pe.add(N.receiptId),N.type==="open_url"&&!e.onOpenUrl&&N.openIn==="same_window"&&s.defaultView?.location.assign(N.url),ae})},p.replaceChildren(x)}!t.pendingRequest&&t.status==="completed"&&!pe.has(`complete:${t.id}`)&&(pe.add(`complete:${t.id}`),K(e.onComplete,structuredClone(t))),me()}function Ge(t){let l=s.defaultView?.open(t,"_blank")??null;return l&&(l.opener=null),l}function Z(t){return de(),L=L.catch(()=>{}).then(()=>He(t)),L}let Qe=e.client.subscribe(t=>{e.client.configurationReady===!1&&(a.hidden=!0,E?.destroy(),E=null,I?.destroy(),I=null,p.replaceChildren(),M="",z="",J="",i="",P.open&&P.close()),Z(t).catch(W)}),Je=e.client.subscribeError?.(W);function ce(t){return $||(o||!t&&(F||b)?Promise.resolve():e.client.view&&!["running","waiting"].includes(e.client.view.status)?(se(),Promise.resolve()):($=oe(async()=>{let l=await e.client.submit({operation:"close",...t??ie()});return t&&Ie(l),l},!0).then(()=>{e.client.view?.status==="closed"&&se()}).finally(()=>{$=null}),$))}function se(){R?.destroy(),!o&&(o=!0,f&&clearTimeout(f),Qe(),Je?.(),E?.destroy(),_.stop(),I?.destroy(),P.close(),P.remove(),a.remove(),S instanceof HTMLElement&&S.isConnected&&S.focus(),K(e.onDismiss,V?structuredClone(V):null))}d.onclick=()=>{if(!d.disabled){if(_.active){_.exit();return}oe(()=>e.client.submit({operation:"back",...ie()}))}},G.onclick=()=>{_.open()},k.onclick=()=>{F||ce()},U.onclick=()=>{oe(()=>e.client.retry())},P.addEventListener("cancel",t=>{t.preventDefault(),F||ce()});try{let t=await e.client.get();await Z(e.client.view??t.run)}catch(t){throw se(),t}return{destroy:se,refresh:be,get recovery(){let t=te();if(t)return t;if(!o&&!r&&!F&&I){let l=I.recovery;if(l.type!=="native")return l}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??b?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(F)return F;let t=te();if(t)return Promise.resolve(t);let l=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??b?.operationId??null,h=()=>({type:"recover",operationId:l,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let q=I?.recovery;return Promise.resolve(q&&q.type!=="native"&&q.type!=="cancel"?q:h())}let N=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(q=>q.operation==="close");if(o&&!(N||b&&e.client.view?.status==="closed")||r||g||$||_.active||!I&&!b&&!N)return Promise.resolve(h());let x=I,H=(async()=>{try{if(!b&&N){let Q=await e.client.retry();return await Z(e.client.view??Q.run),h()}if(!b){let Q=await x.prepareFallback();if(Q.type!=="native")return Q;if(e.client.hasDurableJournal!==!0)return h();b=Q}let q=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(q.length){let Q=q.find(ne=>ne.operation==="close");if(!Q||!T||Q.requestId!==T.requestId)return h();let j=await e.client.retry();Ie(j),await Z(e.client.view??j.run)}else{let Q=e.client.view,j=Q?.paywall;if(!Q||!j||j.selectionGeneration===void 0||(j.quote?.operationId??null)!==b.operationId||b.operationId!==null&&j.canReselect!==!0)return h();let ne=j.selectionGeneration,xe=await e.client.get();await Z(e.client.view??xe.run);let Y=e.client.view,le=Y?.paywall;if(!Y||!le||!["running","waiting"].includes(Y.status)||Y.stopped||Y.id!==Q.id||Y.nodeId!==Q.nodeId||Y.visit!==Q.visit||le.receiptId!==j.receiptId||le.selectionGeneration!==ne||(le.quote?.operationId??null)!==b.operationId||b.operationId!==null&&le.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return h();let ve=ie();T={runId:Y.id,operationId:b.operationId,revision:ve.revision,requestId:ve.requestId,nodeId:Y.nodeId,visit:Y.visit,receiptId:le.receiptId,selectionGeneration:ne,acknowledged:!1},await ce(ve)}let ae=te();return ae?(se(),ae):h()}catch(q){return W(q),h()}})();F=H;let ee=()=>{F===H&&(F=null)};return H.then(ee,ee),H},review:_.open,exitReview:_.exit,get unappliedDrafts(){return _.drafts}}}export{Ue as a,hn as b};
|
|
1
|
+
import{c as Ne}from"./chunk-XIYNQHN7.js";import{a as qe,b as De,c as ke,d as Fe,e as Se,f as ye}from"./chunk-FISFN5IY.js";import{a as w}from"./chunk-KHIQQNTR.js";import{b as Oe,e as _e}from"./chunk-SLUA7ABW.js";import{d as Te}from"./chunk-YGU2GL6L.js";import{a as K}from"./chunk-DSPLGTQI.js";import{Z as Pe,ma as we}from"./chunk-ML4U33AO.js";import{Da as Re,I as Ce,Na as Ee}from"./chunk-4SWGHICJ.js";function Ae(n){let O=n.view;if(!O?.paywall)throw new w("INVALID_REQUEST","The current node is not a Paywall");let e=O.paywall.receiptId,C=O.nodeId,c=O.visit,R=O.paywall.resolution,s=O.paywall,S="document"in R?{document:R.document,offering:R.offering,capabilities:R.capabilities}:null;function a(){let i=s.resolution;return"document"in i?i:S&&{...i,document:S.document,offering:S.offering,capabilities:qe(i.capabilities,S.capabilities)}}function p(i){if(!De(i,R))throw new w("INVALID_RESPONSE","The pinned Paywall binding changed")}let D=!1,v=new AbortController,y=(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===C&&i.visit===c&&i.input.type==="paywall_quote")?.requestId??O.paywall.purchaseRequestId,u=0,d=null,k=new Set,U=null,P=new Map;function A(i){if(i.purchase&&i.purchase.receiptId!==e)throw new w("INVALID_RESPONSE","Purchase receipt changed");let o=i.run.paywall;return i.purchase??(o?.receiptId===e?o:null)}function E(){if(D)throw new w("IDENTITY_CHANGED","Paywall presentation has closed")}function I(i,o,r){if(E(),o!==u||r!==void 0&&s.quote?.operationId!==r)return!1;let g=s.selectionGeneration??0,m=i.run.paywall;if(m?.receiptId===e){if((m.selectionGeneration??0)<(s.selectionGeneration??0))return!1;p(m.resolution)}let f=A(i),L=m?.receiptId===e&&(m.selectionGeneration??0)>g,$=L?f?.quote??null:f?.quote??s.quote,F=f?.operation??($?.operationId===s.quote?.operationId?s.operation:null);return $&&F&&ke(F,{operationId:$.operationId},"Purchase operation changed"),(L||$?.operationId!==s.quote?.operationId)&&(u++,m?.receiptId===e&&(y=m.purchaseRequestId)),s={...s,...m?.receiptId===e?m:{},quote:$,operation:Se(s.operation,F,!0)},!0}function V(i,o,r){return new Promise((g,m)=>{let f=!1,L=()=>{clearTimeout(T),v.signal.removeEventListener("abort",b)},$=te=>{f||(f=!0,L(),g(te))},F=te=>{f||(f=!0,L(),m(te))},b=()=>F(new w("IDENTITY_CHANGED","Paywall presentation has closed")),T=setTimeout(()=>F(new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,r)),Math.max(0,o-Date.now()));v.signal.addEventListener("abort",b,{once:!0}),v.signal.aborted&&b(),i.then($,F)})}function M(i){return new Promise(o=>{let r=()=>{clearTimeout(g),v.signal.removeEventListener("abort",r),o()},g=setTimeout(r,i);v.signal.addEventListener("abort",r,{once:!0}),v.signal.aborted&&r()})}function z(i,o){E();let r=P.get(i)??n.pendingCommands?.find(f=>f.requestId===i)??n.pendingCommand;if(r?.operation==="submit"&&r.requestId===i&&r.nodeId===C&&r.visit===c){o.type==="paywall_quote"&&r.input.type==="paywall_quote"&&r.input.predecessor&&!o.predecessor&&(o={...o,predecessor:r.input.predecessor});let f=we.parse(r),L=we.parse({...r,input:o});if(f.operation!=="submit"||L.operation!=="submit"||JSON.stringify(f.input)!==JSON.stringify(L.input))throw new w("CONFLICT","A purchase request cannot change its input");return P.set(i,f),f}let g=n.view;if(!g||g.nodeId!==C||g.visit!==c||g.paywall?.receiptId!==e)throw new w("PRECONDITION_FAILED","The Paywall visit has changed");let m=we.parse({operation:"submit",requestId:i,nodeId:C,visit:c,revision:g.revision,input:structuredClone(o)});if(m.operation!=="submit")throw new w("INVALID_REQUEST","A purchase submission is required");return P.set(i,m),m}async function J(i,o){E();let{requestId:r,input:g}=i,m=Date.now()+3e4;k.add(r);try{let f=await V(n.submit(i),m,r);for(;f.run.pendingRequest?.requestId===r&&Date.now()<m&&!D&&(await M(Math.min(1e3,m-Date.now())),!(D||Date.now()>=m));)f=await V(n.resume(r),m,r);if(D)throw new w("IDENTITY_CHANGED","Paywall presentation has closed");if(f.run.pendingRequest?.requestId===r)throw new w("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,r);if(!I(f,o,g.type==="paywall_confirm"||g.type==="paywall_cancel"?g.operationId:void 0))throw new w("PRECONDITION_FAILED","The purchase selection has changed");U===r&&(U=null)}catch(f){throw U=r,f instanceof w&&f.code==="COMMAND_PENDING"&&f.status===void 0&&P.delete(r),f}finally{k.delete(r)}}async function X(i){if(!s.quote)throw new w("INVALID_REQUEST","A quoted purchase is required");let o=i==="confirm"?"paywall_confirm":"paywall_cancel",r=[...P.values(),...n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])].find(m=>m.operation==="submit"&&m.input.type===o&&"operationId"in m.input&&m.input.operationId===s.quote.operationId),g=r?.operation==="submit"&&r.input.type===o&&"operationId"in r.input&&r.input.operationId===s.quote.operationId?r.requestId:crypto.randomUUID();if(await J(z(g,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:s.quote.operationId}),u),!s.operation)throw new w("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(s.operation)}return{get view(){return structuredClone(a())},get quote(){return s.quote?structuredClone(s.quote):null},get operation(){return s.operation?structuredClone(s.operation):null},get webViewUrl(){return n.webViewUrl},get canReselect(){return s.canReselect===!0},get recovery(){let i=n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[]),o=n.pendingPurchase;if(o&&(o.receiptId!==e||o.operationId!==s.quote?.operationId))return{type:"recover",operationId:o.operationId,requestId:i[0]?.requestId??null};let r=ye({quote:s.quote,operation:s.operation,requestId:i[0]?.requestId??U??y,pending:k.size>0||i.length>0||U!==null,destroyed:D,canReselect:s.canReselect});return r.type==="recover"&&r.requestId===null&&!D&&n.hasDurableJournal===!0&&!s.quote&&!s.operation&&(s.selectionGeneration??0)===0&&!o&&!i.length&&!k.size&&!y?{type:"native",operationId:null}:r},get pendingCancellation(){return!D&&(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===C&&i.visit===c&&i.input.type==="paywall_cancel"&&i.input.operationId===s.quote?.operationId)},async refresh(){E();let i=u,o=await n.get();if(I(o,i),o.run.paywall?.receiptId!==e)throw new w("PRECONDITION_FAILED","Paywall presentation has changed");if(!a()){if("document"in s.resolution||!n.resolvePaywall)throw new w("INVALID_RESPONSE","Public Paywall reader is unavailable");let r=await n.resolvePaywall(s.resolution);E(),p(r),S={document:r.document,offering:r.offering,capabilities:r.capabilities}}return structuredClone(a())},preview(i){let o=a();if(!o)return Promise.reject(new w("PRECONDITION_FAILED","Load the Paywall presentation first"));if(y&&y!==i.requestId&&(d||s.canReselect!==!0))return Promise.reject(new w("COMMAND_PENDING","Retry the original purchase before starting another"));let r=o.document.buttons[i.actionId],g=r?.type==="checkout"?Pe(r.product,i.selection,o.capabilities):null;if(!g)return Promise.reject(new w("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let m=Ee(o.document.screen,g,i.selection,o.capabilities),f=y!==i.requestId&&(s.selectionGeneration??0)>0?{operationId:s.quote?.operationId??null,generation:s.selectionGeneration??0}:void 0;if(f&&s.canReselect!==!0)return Promise.reject(new w("COMMAND_PENDING","Original purchase requires authoritative termination"));let L;try{L=z(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:g,...Object.keys(m).length?{featureQuantities:m}:{},...f?{predecessor:f}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}})}catch(b){return Promise.reject(b)}if(y===i.requestId&&d)return d;y!==i.requestId&&u++;let $=u;y=i.requestId;let F=(async()=>{if(await J(L,$),!s.quote)throw new w("INVALID_RESPONSE","The accepted quote is missing");return Fe(s.quote,{productVersionId:g,featureQuantities:m},"The selected purchase changed"),structuredClone(s.quote)})();return d=F,F.then(()=>{d===F&&(d=null)},b=>{d===F&&(d=null),y===i.requestId&&n.pendingCommand?.requestId!==i.requestId&&b instanceof w&&b.status!==void 0&&b.status<500&&![401,425].includes(b.status)&&(y=null)}),F},confirm:()=>X("confirm"),cancel:()=>X("cancel"),async read(){if(E(),!s.quote)throw new w("INVALID_REQUEST","A quoted purchase is required");let i=s.quote.operationId,o=u,r=n.pendingCommands?.find($=>$.operation==="submit"&&($.input.type==="paywall_confirm"||$.input.type==="paywall_cancel")&&$.input.operationId===i)??n.pendingCommand;r?.operation==="submit"&&(r.input.type==="paywall_confirm"||r.input.type==="paywall_cancel")&&r.input.operationId===i&&await n.settle?.(r.requestId);let g=await n.get(void 0,{receiptId:e,operationId:i});E();let m=A(g);if(m?.quote&&m.quote.operationId!==i||m?.operation&&m.operation.operationId!==i)throw new w("INVALID_RESPONSE","Purchase operation changed");let f=I(g,o,i),L=f?s.operation:m?.operation;if(!L)throw new w("INVALID_RESPONSE","The current purchase result is missing");return f&&k.size===0&&!(n.pendingCommands?.length??(n.pendingCommand?1:0))&&(U=null),structuredClone(L)},destroy(){D=!0,v.abort(),P.clear()}}}function Ve(n){let O=new Set,e=new Set,C=null;async function c(a,p){let D=!1;for(;!n.stopped&&n.key===a&&n.client.pendingCommand?.requestId===p;){if(!n.client.settle)throw new w("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(p),D=!0,n.client.pendingCommand?.requestId===p&&await new Promise(v=>setTimeout(v,1500))}n.stopped||n.key!==a||(D&&await n.client.get(),!(n.stopped||n.key!==a)&&O.add(a))}function R(a,p){C=p;let D=()=>{C===p&&(C=null),e.delete(a)};return p.then(D,v=>{D(),n.busy||n.fail(v)}),p}function s(a){if(n.reviewing||O.has(a)||e.has(a)||n.stopped)return;e.add(a);let p=async()=>{if(n.reviewing||n.stopped||n.key!==a||O.has(a)){e.delete(a);return}if(n.busy||n.client.pendingCommand){setTimeout(()=>{p()},250);return}let D=(async()=>{let v=n.client.view,G=n.expected(),y=G.requestId;try{await n.client.submit({operation:"shown",...G})}catch(u){if(!(u instanceof w)||u.code!=="CONFLICT"||u.status!==409||n.client.pendingCommand)throw u;await n.client.get();let d=n.client.view;if(n.stopped||n.reviewing||n.key!==a||!d||!v||d.id!==v.id||d.source.versionId!==v.source.versionId||d.nodeId!==G.nodeId||d.visit!==G.visit||d.revision<=G.revision||d.stopped||!d.screen&&(!d.paywall||d.paywall.receiptId!==v.paywall?.receiptId)||!["running","waiting"].includes(d.status)||n.client.pendingCommand)throw u;let k=n.expected();y=k.requestId,await n.client.submit({operation:"shown",...k})}await c(a,y)})();R(a,D)};p()}function S(){if(C)return C;let a=n.client.pendingCommand;if(a?.operation!=="shown")return null;let p=n.key;return e.add(p),R(p,(async()=>{await n.client.retry(),await c(p,a.requestId)})())}return{report:s,settled:S,get inFlight(){return C}}}function Le(n){let O={},e=new Map;async function C(c){let R=n.client.view,s=R?.screen,S=s?.customerData.nodes[c.nodeId];if(n.stopped||n.busy||!R||!s||!S)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(c.action)){let u=n.document,d=u?Re(u,c.nodeId):null,k=d?.type==="customer_data"?d.data.outputs?.[c.action]:void 0;k&&s.outputs.includes(k)?await n.perform(()=>n.client.submit({operation:"submit",...n.expected(),input:{type:"screen",output:k,answers:n.answers,selection:c.value?{[c.nodeId]:c.value}:{}}})):await n.onIntent?.(c,R);return}let p=c.action.startsWith("sources_")?S.resources.find(u=>u.key===c.value):null;if(c.action.startsWith("sources_")&&!p)throw new w("INVALID_REQUEST","Choose a current resource");let D=`${R.visit}:${c.nodeId}:${p?.key??""}`,v=e.get(D)??[null],y=O[c.nodeId]??{page:1,after:null,filter:"all",...p?{resourceKey:p.key}:{}};if(c.action==="filter"){let u=c.value;if(!u||!(S.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(u))throw new w("INVALID_REQUEST","Unknown data filter");y={page:1,after:null,filter:u},v.splice(0,v.length,null)}else if(c.action==="next"||c.action==="sources_next"){let u=p?.sources.at(-1),d=p?u?{kind:"ledger",cursor:{at:u.detail[0],id:u.id,type:"source"}}:null:s.dataCursors[c.nodeId];if(!d||!p&&!S.hasNext)return;v[y.page]=d,y={...y,page:y.page+1,after:d}}else if(c.action==="previous"||c.action==="sources_previous"){if(y.page<=1)return;y={...y,page:y.page-1,after:v[y.page-2]??null}}e.set(D,v),O={...O,[c.nodeId]:y},await n.perform(()=>n.client.get({nodeId:R.nodeId,visit:R.visit,revision:R.revision,components:O}))}return{get queries(){return O},intent:C,reset(){O={},e.clear()}}}function $e(n){let{doc:O,holder:e,reviewHolder:C,mountScreenPreview:c}=n,R=!1,s,S=0,a=null,p="",D=new Map,v=u=>u?`${u.id}:${u.nodeId}:${u.visit}:${u.revision}:${u.paywall?.quote?.operationId??""}`:"";async function G(u){if(n.stopped||!n.client.review)return;R||(p=v(n.client.view),D.set(p,structuredClone(n.answers))),R=!0,s=u,e.hidden=!0,n.suspend(!0),C.hidden=!1;let d=++S;try{let k=await n.client.review(u);if(n.stopped||d!==S||!R)return;if(!k.review)throw new w("INVALID_RESPONSE","Historical projection is missing");a?.destroy(),a=null,C.replaceChildren();let U=k.run.locale.startsWith("zh"),P=O.createElement("p");P.textContent=U?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",C.append(P);for(let[I,V]of k.review.pages.entries()){let M=O.createElement("button");M.type="button",M.textContent=U?`\u7B2C ${I+1} \u9875`:`Page ${I+1}`,M.onclick=()=>{G(V.receiptId)},C.append(M)}if(k.review.page){let I=k.review.page,V=O.createElement("div");if(V.inert=!0,C.append(V),a=c(V,{mode:"live",rendererUrl:n.client.webViewUrl,title:I.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{y()}}),a.update(I.document,k.run.locale,{serverInput:{bindings:I.inputs,answers:I.answers,values:I.values}}),await a.ready,n.stopped||d!==S||!R)return}let A=U?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},E=U?{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"};for(let I of[...k.review.coupons.map((V,M)=>`${U?"\u4F18\u60E0\u5238":"Coupon"} ${M+1}: ${A[V.status]}`),...k.review.purchases.map((V,M)=>`${U?"\u8D2D\u4E70":"Purchase"} ${M+1}: ${E[V.status]}`)]){let V=O.createElement("p");V.textContent=I,C.append(V)}n.client.view&&await n.enqueue(n.client.view)}catch(k){if(d!==S||n.stopped)return;a?.destroy(),a=null,C.replaceChildren(),n.fail(k)}}async function y(){if(!R||n.stopped||!n.client.review)return;let u=++S;try{if(await n.client.review(),n.stopped||u!==S)return;R=!1,S++,a?.destroy(),a=null,C.replaceChildren(),C.hidden=!0,e.hidden=!1;let d=n.client.view;v(d)!==p?(D.set(p,structuredClone(n.answers)),n.resetScreen()):(D.delete(p),n.suspend(!1)),d&&await n.enqueue(d)}catch(d){if(u!==S||n.stopped)return;a?.destroy(),a=null,C.replaceChildren(),n.fail(d)}}return{get active(){return R},get receipt(){return s},open:G,exit:y,get drafts(){return new Map([...D].map(([u,d])=>[u,structuredClone(d)]))},stop(){R=!1,S++,a?.destroy(),a=null,C.replaceChildren(),C.hidden=!0,e.hidden=!1}}}function Ue(n){if(!n.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let O=n.client.pageExperiments.bind(n.client),e=!1,C=!1,c=0,R=!1,s=!1,S,a=new Map,p=new Set,D={},v=new Map,G=Oe(n.appManifestRelease),y=()=>{for(let A of a.values())A.effect.revert();a.clear();for(let A of v.values())A();v.clear()};function u(A){if(e||p.has(A))return;p.add(A);let E=c;O(n.appManifestRelease,[A]).catch(I=>{p.delete(A),!e&&E===c&&K(n.onError,I)})}async function d(){if(e)return;let A=n.client.view;if(!A||A.stopped||!["running","waiting"].includes(A.status)){c++,y();return}if(R){s=!0;return}R=!0;let E=++c,I=`${A.id}:${A.visit}:${A.revision}`,V=location.href;try{let[M,{applyVisualVariation:z}]=await Promise.all([O(n.appManifestRelease),import("./visual-dom-7IF7ITAK.js")]),J=n.client.view;if(e||E!==c||!J||J.stopped||!["running","waiting"].includes(J.status)||`${J.id}:${J.visit}:${J.revision}`!==I||location.href!==V)return;let X=new Set,i=new Set;for(let o of M.assignments){let r=`${M.payload.environmentId}:${o.experimentKey}`;if(i.add(r),v.has(r)||v.set(r,_e(r,D)),!!o.inExperiment)for(let g of M.payload.experiments){if(g.key!==o.experimentKey||!Ce(location.href,g.urlPatterns??[]))continue;let m=g.meta?.findIndex(T=>T.key===o.variationKey)??-1,f=g.variations[m];if(!f?.renderGuard)continue;let L=o.receiptId+":"+g.changeId,$=JSON.stringify([o.variationKey,f]);X.add(L);let F=a.get(L);if(F?.signature===$){F.effect.applied&&u(o.receiptId);continue}a.get(L)?.effect.revert(),a.delete(L);let b=z(f,{requireUniqueTargets:!0,boundVariations:g.variations,allowJs:!1,onApplied:()=>u(o.receiptId),onError:T=>K(n.onError,T)});a.set(L,{signature:$,effect:b}),b.applied&&u(o.receiptId)}}for(let[o,r]of a)X.has(o)||(r.effect.revert(),a.delete(o));for(let[o,r]of v)i.has(o)||(r(),v.delete(o))}catch(M){E===c&&y(),!e&&E===c&&K(n.onError,M)}finally{R=!1,s&&!e&&(s=!1,d())}}let k=n.client.subscribe(()=>{c++,d()}),U=Te(()=>{c++,y(),d()}),P=async()=>{await d(),e||(S=setTimeout(()=>{P()},15e3))};return{async start(){C||e||(C=!0,await P())},refresh:d,destroy(){e=!0,c++,clearTimeout(S),k(),U(),y(),G.destroy()}}}async function hn(n,O){let e=O,{mountScreenPreview:C}=await import("./screen-renderer-ZNELQB64.js"),{showPaywall:c}=await import("./paywall-P4TRVOBV.js"),R=e.appManifestRelease?Ue({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;R?.start();let s=n.ownerDocument,S=s.activeElement,a=s.createElement("section"),p=s.createElement("div"),D=s.createElement("div"),v=s.createElement("div"),G=s.createElement("button");v.hidden=!0,G.type="button";let y=s.createElement("p"),u=s.createElement("p"),d=s.createElement("button"),k=s.createElement("button"),U=s.createElement("button"),P=s.createElement("dialog"),A;a.dataset.indianaFunnel="",a.setAttribute("aria-busy","false"),a.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",D.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",y.setAttribute("role","status"),u.setAttribute("role","alert"),u.hidden=!0,d.type=k.type=U.type="button",D.append(d,y,u,U,G,k),a.append(p,v,D),n.append(a);let E=null,I=null,V=null,M="",z="",J="",X="",i="",o=!1,r=0,g=!1,m="",f=null,L=Promise.resolve(),$=null,F=null,b=null,T=null;function te(){return b&&e.client.hasDurableJournal===!0&&T?.acknowledged===!0&&T.operationId===b.operationId&&e.client.view?.id===T.runId&&e.client.view?.status==="closed"&&e.client.view.revision===T.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?b:null}function Ie(t){let l=t.run.paywall;if(T&&t.settlement?.requestId===T.requestId&&t.settlement.state==="settled"&&t.settlement.operationId===null&&t.run.id===T.runId&&t.run.status==="closed"&&!t.run.pendingRequest&&t.run.revision===T.revision+1&&t.run.nodeId===T.nodeId&&t.run.visit===T.visit&&l?.receiptId===T.receiptId&&l.selectionGeneration===T.selectionGeneration&&(l.quote?.operationId??null)===T.operationId&&(l.operation?.operationId??l.quote?.operationId??null)===T.operationId){let h=T.operationId===null&&l.selectionGeneration===0&&!l.quote&&!l.operation&&!l.purchaseRequestId,N=ye({quote:l.quote,operation:l.operation,requestId:l.purchaseRequestId,pending:!1,destroyed:!1,canReselect:l.canReselect});(h||l.canReselect===!0&&N.type==="native")&&(T.acknowledged=!0)}}let re=null,pe=new Set,B={},W=(t,l=null)=>{o||(re=l,u.textContent=t instanceof Error?t.message:"Request failed",u.hidden=!1,U.hidden=e.client.pendingCommand===null,K(e.onError,t))};function ie(){let t=e.client.view;if(!t)throw new w("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let _=$e({client:e.client,doc:s,holder:p,reviewHolder:v,mountScreenPreview:C,get stopped(){return o},get answers(){return B},suspend(t){I?.setSuspended(t)},resetScreen(){M="",z="",J=""},enqueue:Z,fail:W}),ue=Ve({client:e.client,expected:ie,fail:W,get stopped(){return o},get reviewing(){return _.active},get key(){return M},get busy(){return r}}),fe=Le({client:e.client,expected:ie,perform:oe,onIntent:e.onCustomerDataIntent,get stopped(){return o},get busy(){return r},get document(){return E?.document},get answers(){return B}}),ge=t=>t&&(t.screen||t.paywall)?`${t.id}:${t.nodeId}:${t.visit}`:"";function de(){let t=e.client.view;d.disabled=!_.active&&(r>0||!!e.client.pendingCommand||!t?.canBack||t.stopped||!["running","waiting"].includes(t.status)||!ge(t)||z!==ge(t))}async function he(t){if(!t)return;let l=e.client.view;await t;let h=e.client.view;if(!l||!h||h.id!==l.id||h.nodeId!==l.nodeId||h.visit!==l.visit||h.stopped||!["running","waiting"].includes(h.status))throw new w("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function oe(t,l=!1){if(!((r||F||b)&&!l||o||_.active&&!l)){r++,a.setAttribute("aria-busy","true"),de(),u.hidden=!0,re=null;try{if(l||await he(ue.inFlight),o)return;let h=await t();o||await Z(e.client.view??h.run)}catch(h){W(h,e.client.pendingCommand?.requestId??null)}finally{r=Math.max(0,r-1),a.setAttribute("aria-busy",String(r>0)),o||(U.hidden=e.client.pendingCommand===null,de())}}}function me(){f&&clearTimeout(f),!(o||!V||!["running","waiting"].includes(V.status)&&!e.client.pendingCommand)&&(f=setTimeout(()=>{f=null,be().finally(me)},V.pendingRequest||e.client.pendingCommand?1500:5e3))}async function be(){if(!(o||g||r)){if(_.active){await _.open(_.receipt);return}g=!0;try{let t=e.client.pendingCommand;t&&e.client.settle&&await e.client.settle(t.requestId);let l=e.client.view,h=fe.queries,N=await e.client.get(l?.screen&&Object.keys(h).length?{nodeId:l.nodeId,visit:l.visit,revision:l.revision,components:h}:void 0);!o&&h===fe.queries&&await Z(e.client.view??N.run)}catch(t){W(t)}finally{g=!1}}}function Me(t){let l=t.screen?.presentation;if(!l||l.type==="inline"){P.open&&P.close(),a.parentElement!==n&&n.append(a);return}a.parentElement!==P&&(P.append(a),n.append(P));let h={sm:420,md:640,lg:900};P.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in l?h[l.size]+"px":"100vw"}`,P.setAttribute("aria-label",(A?.screen===t.screen?.content.document.name?A?.label:void 0)??E?.document?.name??t.screen?.content.document.name??"Funnel"),P.open||(P.showModal(),Ne(P,l.type))}async function He(t){if(o)return;V=t,re&&e.client.pendingCommand?.requestId!==re&&(u.hidden=!0,re=null);let l=t.locale.startsWith("zh");if(G.textContent=l?"\u56DE\u770B":"History",G.hidden=!e.client.review,d.textContent=_.active?l?"\u8FD4\u56DE\u5F53\u524D":"Return to current":l?"\u8FD4\u56DE":"Back",k.textContent=l?"\u5173\u95ED":"Close",U.textContent=l?"\u91CD\u8BD5":"Retry",de(),U.hidden=e.client.pendingCommand===null,y.textContent=t.pendingRequest?l?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?l?"\u7B49\u5F85\u4E2D":"Waiting":"",m!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(m=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,K(e.onState,structuredClone(t))),!t.pendingRequest&&["closed","ineligible","failed"].includes(t.status)){se();return}if(t.stopped||e.client.configurationReady===!1){_.stop(),E?.destroy(),E=null,I?.destroy(),I=null,p.replaceChildren(),M="",z="",J="",i="",P.open&&P.close(),a.hidden=!0,me();return}if(a.hidden=!1,_.active){me();return}let h=ge(t);if(h!==M&&(z="",E?.destroy(),E=null,I?.destroy(),I=null,p.replaceChildren(),M=h,J="",i="",B={...t.answers},fe.reset()),Me(t),t.screen){let x=t.screen.content;E||(E=C(p,{mode:"live",rendererUrl:e.client.webViewUrl,title:x.document.name,onAction(q,ae={},Q={}){if(_.active)return;B={...B,...Q};let j=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:ne})=>Object.hasOwn(B,ne)).map(({variable:ne})=>[ne,B[ne]]));oe(()=>e.client.submit({operation:"submit",...ie(),input:{type:"screen",output:q,answers:j,selection:ae}}))},onAnswers:q=>{_.active||(B={...B,...q})},onCustomerDataIntent:q=>{_.active||fe.intent(q).catch(W)},onEscape:()=>{_.active||F||b||ce()},onError:q=>W(new Error(q)),onRendered:q=>{if(!q)return ue.report(h);A={screen:x.document.name,label:q},P.open&&P.setAttribute("aria-label",q),ue.report(h)}}));let H={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:B,values:t.screen.values}},ee=JSON.stringify([x,t.locale,H.parameters,t.screen.inputs,t.screen.values]);if(ee!==J)E.update(x.document,t.locale,H),J=ee,X=JSON.stringify(H.capabilities),i=JSON.stringify(H.customerData);else{let q=JSON.stringify(H.capabilities);q!==X&&(E.updateCapabilities(H.capabilities),X=q),JSON.stringify(H.customerData)!==i&&(E.updateCustomerData(H.customerData),i=JSON.stringify(H.customerData))}await E.ready}else if(t.paywall&&!I){let x=await c(p,{canInteract:()=>!_.active&&!o&&!F&&!b,beforeAction:async()=>{r++;try{await he(ue.settled()),u.hidden=!0,re=null}finally{r=Math.max(0,r-1)}},start:async()=>Ae(e.client),onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,resolveOfferId:e.resolveOfferId,onEvent:e.onEvent,onOpenUrl:H=>e.onOpenUrl?e.onOpenUrl({receiptId:t.paywall.receiptId,url:H,openIn:"same_window"}):s.defaultView?.location.assign(H),onAction:async H=>{if(_.active)return;let ee=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:e.client.view?.revision??t.revision,input:{type:"screen",output:H,answers:{}}});await Z(e.client.view??ee.run)},onError:W,onDismiss:()=>{!_.active&&!o&&!F&&!b&&e.client.view?.visit===t.visit&&ce()}});o?x.host?.destroy():(I=x.host,I?.setSuspended(_.active)),ue.report(h)}if(o)return;z=h,de();let N=t.instruction;if(N&&(N.type==="open_url"||N.type==="event")&&!pe.has(N.receiptId)){let x=s.createElement("button");x.type="button",x.textContent=N.type==="open_url"?`${l?"\u524D\u5F80":"Continue to"} ${new URL(N.url).host}`:l?"\u7EE7\u7EED":"Continue",x.onclick=()=>{let H=ie(),ee=N.type==="open_url"&&!e.onOpenUrl&&N.openIn==="new_window"?Ge(N.url):null;oe(async()=>{let q="success";if(N.type==="open_url")if(e.onOpenUrl)try{q=await e.onOpenUrl({receiptId:N.receiptId,url:N.url,openIn:N.openIn})===!1?"failed":"opened"}catch(Q){K(e.onError,Q),q="failed"}else q=N.openIn==="new_window"&&!ee?"failed":"opened";if(N.type==="event"){if(!e.onEvent)throw new w("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(N.event)}if(o||e.client.view?.nodeId!==H.nodeId||e.client.view.visit!==H.visit)throw new w("PRECONDITION_FAILED","The client action visit changed");let ae=await e.client.submit({operation:"submit",...H,input:{type:"client_action",receiptId:N.receiptId,outcome:q}});return pe.add(N.receiptId),N.type==="open_url"&&!e.onOpenUrl&&N.openIn==="same_window"&&s.defaultView?.location.assign(N.url),ae})},p.replaceChildren(x)}!t.pendingRequest&&t.status==="completed"&&!pe.has(`complete:${t.id}`)&&(pe.add(`complete:${t.id}`),K(e.onComplete,structuredClone(t))),me()}function Ge(t){let l=s.defaultView?.open(t,"_blank")??null;return l&&(l.opener=null),l}function Z(t){return de(),L=L.catch(()=>{}).then(()=>He(t)),L}let Qe=e.client.subscribe(t=>{e.client.configurationReady===!1&&(a.hidden=!0,E?.destroy(),E=null,I?.destroy(),I=null,p.replaceChildren(),M="",z="",J="",i="",P.open&&P.close()),Z(t).catch(W)}),Je=e.client.subscribeError?.(W);function ce(t){return $||(o||!t&&(F||b)?Promise.resolve():e.client.view&&!["running","waiting"].includes(e.client.view.status)?(se(),Promise.resolve()):($=oe(async()=>{let l=await e.client.submit({operation:"close",...t??ie()});return t&&Ie(l),l},!0).then(()=>{e.client.view?.status==="closed"&&se()}).finally(()=>{$=null}),$))}function se(){R?.destroy(),!o&&(o=!0,f&&clearTimeout(f),Qe(),Je?.(),E?.destroy(),_.stop(),I?.destroy(),P.close(),P.remove(),a.remove(),S instanceof HTMLElement&&S.isConnected&&S.focus(),K(e.onDismiss,V?structuredClone(V):null))}d.onclick=()=>{if(!d.disabled){if(_.active){_.exit();return}oe(()=>e.client.submit({operation:"back",...ie()}))}},G.onclick=()=>{_.open()},k.onclick=()=>{F||ce()},U.onclick=()=>{oe(()=>e.client.retry())},P.addEventListener("cancel",t=>{t.preventDefault(),F||ce()});try{let t=await e.client.get();await Z(e.client.view??t.run)}catch(t){throw se(),t}return{destroy:se,refresh:be,get recovery(){let t=te();if(t)return t;if(!o&&!r&&!F&&I){let l=I.recovery;if(l.type!=="native")return l}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??b?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(F)return F;let t=te();if(t)return Promise.resolve(t);let l=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??b?.operationId??null,h=()=>({type:"recover",operationId:l,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let q=I?.recovery;return Promise.resolve(q&&q.type!=="native"&&q.type!=="cancel"?q:h())}let N=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(q=>q.operation==="close");if(o&&!(N||b&&e.client.view?.status==="closed")||r||g||$||_.active||!I&&!b&&!N)return Promise.resolve(h());let x=I,H=(async()=>{try{if(!b&&N){let Q=await e.client.retry();return await Z(e.client.view??Q.run),h()}if(!b){let Q=await x.prepareFallback();if(Q.type!=="native")return Q;if(e.client.hasDurableJournal!==!0)return h();b=Q}let q=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(q.length){let Q=q.find(ne=>ne.operation==="close");if(!Q||!T||Q.requestId!==T.requestId)return h();let j=await e.client.retry();Ie(j),await Z(e.client.view??j.run)}else{let Q=e.client.view,j=Q?.paywall;if(!Q||!j||j.selectionGeneration===void 0||(j.quote?.operationId??null)!==b.operationId||b.operationId!==null&&j.canReselect!==!0)return h();let ne=j.selectionGeneration,xe=await e.client.get();await Z(e.client.view??xe.run);let Y=e.client.view,le=Y?.paywall;if(!Y||!le||!["running","waiting"].includes(Y.status)||Y.stopped||Y.id!==Q.id||Y.nodeId!==Q.nodeId||Y.visit!==Q.visit||le.receiptId!==j.receiptId||le.selectionGeneration!==ne||(le.quote?.operationId??null)!==b.operationId||b.operationId!==null&&le.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return h();let ve=ie();T={runId:Y.id,operationId:b.operationId,revision:ve.revision,requestId:ve.requestId,nodeId:Y.nodeId,visit:Y.visit,receiptId:le.receiptId,selectionGeneration:ne,acknowledged:!1},await ce(ve)}let ae=te();return ae?(se(),ae):h()}catch(q){return W(q),h()}})();F=H;let ee=()=>{F===H&&(F=null)};return H.then(ee,ee),H},review:_.open,exitReview:_.exit,get unappliedDrafts(){return _.drafts}}}export{Ue as a,hn as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as p,b as ne,c as j,d as re,n as B,q as ie}from"./chunk-JVH4ZNEK.js";import{b as te}from"./chunk-LIAMO3LU.js";import{a as o}from"./chunk-KHIQQNTR.js";import{a as J}from"./chunk-DSPLGTQI.js";import{Da as c,Fa as G,Qa as ee,_ as $,a as K,b as Q,c as W,d as M,e as H,f as X,ia as Z,q as L}from"./chunk-ML4U33AO.js";import{a as Y}from"./chunk-4SWGHICJ.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new o("INVALID_STATE","Installation sequence exhausted");return t+1},ve=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function F(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new o("INVALID_STATE","Installation journal is invalid");return e({...n})})}function se(t,e,n){let r=null,s=0,a=0,l=0,y=Promise.resolve(),h=!1;if(t&&(!n||Y.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new o("SCOPE_MISMATCH","Push installation belongs to another scope");let f=()=>{if(h)throw new o("CLOSED","SDK client was destroyed");if(!t)throw new o("NOT_CONFIGURED","Configure this client's native Push host first");return t},S=i=>{if(i!==s)throw new o("IDENTITY_CHANGED","Identity changed during Push operation")};async function D(i){let d=f();if(!d.sha256&&!globalThis.crypto?.subtle)throw new o("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=d.sha256?await d.sha256(Uint8Array.from(i,O=>O.charCodeAt(0))):await ve(i);if(!/^[a-f0-9]{64}$/.test(u))throw new o("INVALID_STATE","Push credential digest is invalid");return u}function m(i){let d=H.parse(i);if(d.installationId.toLowerCase()!==f().installationId.toLowerCase())throw new o("INVALID_RESPONSE","Push response belongs to another installation");return d}async function C(i,d){let u=f(),O={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...d},T=await u.sign(X(i,u.scope,O));return{...O,signature:T}}let I=(i,d,u)=>e.requestWithCredential?e.requestWithCredential(i,d,u):e.request(i,d);async function E(){let i=f(),d=s,u=r?await(e.session?.access()??r):null,O=F(i,w=>w),T;if(O.detachSeq!==null){let w=O.detachSeq,x=K.parse(await C("detach",{sequence:w,platform:i.platform}));try{let N=await e.request("push/installations/detach",{...i.scope,...x},"POST",{installationDetach:!0});if(!N||typeof N!="object"||!("installation"in N))throw new o("INVALID_RESPONSE","Push detach acknowledgement is invalid");let _=m(N.installation);if(_.bound||_.identitySeq!==w)throw new o("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(N){if(N instanceof o&&N.status===404)T=N;else if(!(N instanceof o)||N.status!==412)throw N}T||F(i,N=>({...N,detachSeq:N.detachSeq===w?null:N.detachSeq}))}if(S(d),!u){if(T)throw T;return null}let A=c.bindPushInstallation,k=A.request.parse(await C("bind",{sequence:l,platform:i.platform,credentialDigest:await D(u)}));S(d);let q=A.response.parse(await I(A.path,k,u));S(d);let R=m(q.installation);if(!R.bound||R.identitySeq!==l)throw new o("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return T&&O.detachSeq!==null&&l>O.detachSeq&&F(i,w=>({...w,detachSeq:w.detachSeq===O.detachSeq?null:w.detachSeq})),R}async function v(){f();let i=s,d=r?await(e.session?.access()??r):null;if(!d)throw new o("NOT_IDENTIFIED","Identify before reading this installation");let u=c.readPushInstallation,O=u.request.parse(await C("read",{credentialDigest:await D(d)}));S(i);let T=u.response.parse(await I(u.path,O,d));return S(i),m(T.installation)}function g(i=E){let d=y.catch(()=>{}).then(i);return y=d,d.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),d}async function P(i,d,u){let O=f(),T=d.identity,A=d.observation,k=r?await(e.session?.access()??r):null;if(S(T),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");if(!k)throw new o("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new o("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await g(async()=>{if(S(T),await E(),S(T),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let q=F(O,_=>u?_:{..._,addressSeq:U(_.addressSeq)}),w=await C(u?"recovery_confirm":"recovery_request",{...i,sequence:q.addressSeq,credentialDigest:await D(k),...u?{challenge:u}:{}}),x=u?W.parse(w):Q.parse(w);if(S(T),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let N=await I(`push/installations/recovery/${u?"confirm":"request"}`,x,k);if(S(T),A!==a||F(O,_=>_).addressSeq!==q.addressSeq)throw new o("INVALID_STATE","Push observation changed during recovery");if(u){let _=c.updatePushAddress.response.parse(N),V=m(_.installation);if(!V.bound||V.identitySeq!==l||V.addressSeq!==q.addressSeq||V.connectionId!==i.connectionId||V.addressStatus!=="active")throw new o("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return V}if(!N||typeof N!="object"||!("recovery"in N))throw new o("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return M.parse(N.recovery)})}return{recoveryObserver(){f();let i={identity:s,observation:++a};return{async request(d){return M.parse(await P(d,i))},async confirm(d,u){return H.parse(await P(u,i,d))}}},identify(i){if(!t)return;l=F(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,s++,a++},reset(){if(t)try{F(t,i=>{let d=U(i.identitySeq);return{...i,identitySeq:d,detachSeq:d}})}finally{r=null,s++,a++}},start(){t&&!h&&g()},destroy(){h=!0,r=null,s++,a++},async sync(){return await g()},read:v,async recover(){let i=f(),d=s,u=l;return a++,await g(async()=>{S(d);let O=await v();return S(d),l=F(i,A=>{if(A.identitySeq!==u)throw new o("IDENTITY_CHANGED","A newer installation intent exists");return{...A,identitySeq:U(Math.max(A.identitySeq,O.identitySeq)),addressSeq:Math.max(A.addressSeq,O.addressSeq)}}).identitySeq,await E()})},tokenObserver(){f();let i=++a,d=s;return async u=>{if(i!==a||d!==s)return null;let O=f(),T=r?await(e.session?.access()??r):null;if(!T)throw new o("NOT_IDENTIFIED","Identify before registering a Push token");if(await g(),S(d),i!==a)return null;let A=F(O,w=>({...w,addressSeq:U(w.addressSeq)})),k=c.updatePushAddress,q=k.request.parse(await C("address",{...u,sequence:A.addressSeq,credentialDigest:await D(T)}));if(S(d),i!==a)return null;let R=await I(k.path,q,T);return S(d),i!==a||F(O,w=>w).addressSeq!==A.addressSeq?null:m(k.response.parse(R).installation)}}}}function oe(t,e){let n={async preference(r){let s=c.readMessagingPreference;return(await p(t,s,{channel:r})).preference},async setPreference(r){let s=c.setMessagingPreference;return(await p(t,s,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}function ae(t,e,n={}){let r=!1;function s(){if(r)throw new o("CLOSED","SDK client was destroyed")}let a=new Set,l=h=>{for(let f of a)try{f(h)}catch{}},y=t.session.subscribeIdentity(()=>{l(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:s,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(h){return s(),a.add(h),()=>{a.delete(h)}},identify(h){s();let f=typeof h=="string"?h:h.accessToken;if(!L.test(f))throw new o("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(f),t.identify(h)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function b(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new o("INVALID_REQUEST","Customer requests use the verified session identity")}var Ae={...c.readHoldings,request:c.readHoldings.request.omit({customerId:!0})};function ce(t){return{async checkEntitlement(e){b(e);let n=c.checkEntitlement,r=n.request.parse(e),s=await p(t,n,r);return ne(r.requirement,s.check,void 0,s.scope),s},async readHoldings(e={}){return p(t,Ae,e)}}}function ue(t){return{async readLedger(e){let n=c.readLedger;return p(t,n,{query:e})},async readCreditStatement(e){b(e);let n=c.readCreditStatement;return p(t,n,e)},async quoteBalance(e){b(e);let n=c.quoteBalance;return p(t,n,{command:e})}}}function de(t){return{async setupPayment(e){b(e);let n=c.setupPayment;return p(t,n,e)},async readPaymentSetup(e){b(e);let n=c.readPaymentSetup;return p(t,n,e)},async readBillingInvoice(e){b(e);let n=c.readBillingInvoice;return p(t,n,e)},async readBillingControls(e={}){b(e);let n=c.readBillingControls;return p(t,n,e)},async prepareBillingAuthorization(e){b(e);let n=c.prepareBillingAuthorization;return p(t,n,e)},async confirmBillingAuthorization(e){b(e);let n=c.confirmBillingAuthorization;return p(t,n,e)},async setBillingCoupons(e){b(e);let n=c.setBillingCoupons;return p(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){b(e);let n=c.revokeBillingAuthorization;return p(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){b(e);let n=c.listBillingInvoices;return p(t,n,e)},async confirmBillingAdjustment(e){b(e);let n=c.confirmBillingAdjustment;return p(t,n,e)}}}function pe(t){return{async previewUpdate(e){b(e);let n=c.previewUpdate;return p(t,n,e)},async update(e){b(e);let n=c.update;return p(t,n,e)},async readSubscriptionUpdate(e){b(e);let n=c.readSubscriptionUpdate;return p(t,n,e)},async restoreNativePurchase(e){b(e);let n=c.restoreNativePurchase;return p(t,n,e)},async previewAttach(e){b(e);let n=c.previewAttach;return p(t,n,e)},async attach(e){b(e);let n=c.attach;return p(t,n,e)},async readSubscriptionOperation(e){b(e);let n=c.readSubscriptionOperation;return p(t,n,e)}}}function le(t){return{async redeemReward(e){return b(e),(await p(t,c.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return b(e),(await p(t,c.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return b(e),(await p(t,c.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await p(t,c.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await p(t,c.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await p(t,c.listOffers,{},{response:"Invalid offers response"})).offers}}}function fe(t){return{...ce(t),...ue(t),...de(t),...pe(t),...le(t)}}function me(t){return{async resolveContent(e){b(e);let n=c.resolveContent;return p(t,n,e)},async resolvePaywall(e){b(e);let n=c.resolvePaywall,r=n.request.parse(e),s=await p(t,n,r);return j(r,s.paywall.check,s.scope),s},async resolveOffering(e){b(e);let n=c.resolveOffering,r=n.request.parse(e),s=await p(t,n,r);return j(r,s.check,s.scope),s}}}var z=t=>new TextEncoder().encode(JSON.stringify(t)).length,ye=16384,be=5e3,Ee=6e4,Oe=5;function Se(t){return t instanceof o&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function Ie(t,e){let n=0,r,s=v=>{r={config:structuredClone(v),until:Date.now()+3e4}},a=[],l=null,y,h=0;function f(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}function S(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,C().catch(()=>{}).finally(S)},Math.min(be*2**h,Ee)),typeof y=="object"&&"unref"in y&&y.unref())}function D(v){if(f(),r&&Date.now()<r.until&&!$(r.config,v.kind))return;E();let g=c.trackEvents.request.parse({events:[{...v,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(z({events:[g]})>ye)throw new o("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new o("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(g)),S()}function m(v,g={},P={}){D({kind:"custom",name:v,properties:g,...P})}async function C(v=!1){if(f(),l)return l;let g=n,P=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},d=a.length;for(;d&&g===n;){let u=[],O=z({events:[]});for(let k of a.slice(0,Math.min(d,100))){let q=z(k)+(u.length?1:0);if(u.length&&O+q>ye)break;u.push(k),O+=q}let T=c.trackEvents,A;try{if(A=await p(t,T,{events:u},void 0,{keepalive:v}),g!==n)throw new o("IDENTITY_CHANGED","Event identity changed during delivery");if(A.inserted+A.duplicates+A.rejected+A.skipped!==u.length||A.rejections.length!==A.rejected)throw new o("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(k){throw g===n&&(h++,(Se(k)||h>=Oe)&&(a.splice(0,u.length),h=0)),k}h=0,s(A.analyticsConfig),a.splice(0,u.length),d-=u.length,i.inserted+=A.inserted,i.duplicates+=A.duplicates,i.rejected+=A.rejected,i.skipped+=A.skipped,i.rejections.push(...A.rejections)}return i})();l=P;try{return await P}finally{l===P&&(l=null)}}let I;function E(){if(I||typeof document>"u")return;let v=()=>{document.visibilityState==="hidden"&&e()&&a.length&&C(!0).catch(()=>{})};document.addEventListener("visibilitychange",v),I=()=>document.removeEventListener("visibilitychange",v)}return{rememberConfiguration:s,track:m,observe:D,flush:C,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],h=0,l=null},detachVisibility(){I?.(),I=void 0}}}function he(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var Pe=new Set([...Z,"merchandiseId","merchandise"]);function Ce(t){let e=he(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!Pe.has(r))),...e?{merchandise:e}:{}}}function ge(t,e,n,r,s){if(s&&r&&(s.scope.projectId!==r.projectId||s.scope.environment!==r.environment))throw new o("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,l=new Set;function y(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}async function h(f={}){s||y();let S=a,D=!1,m=async()=>{if(D||S!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let q=c.getFeatures,R=s?{scope:{projectId:s.scope.projectId,environment:s.scope.environment},payload:await s.features()}:await p(t,q,{});if(S!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new o("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},C=await m(),I=!0,E,v=q=>{try{f.onError?.(q)}catch{}},g=(q,R)=>{try{let w=he(R);n.observe({...q,...w?{merchandise:w}:{}})}catch(w){v(w)}},P=re({assertUsable:s?.assertFeatures,scope:C.scope,attributes:f.attributes,onError:f.onError,load:async()=>I?(I=!1,C.payload):(await m()).payload,evaluateRemote:async q=>{if(S!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let R=c.evaluateFeatures,w=await p(t,R,{...q,attributes:Ce(q.attributes)});if(w.scope.projectId!==C.scope.projectId||w.scope.environment!==C.scope.environment)throw new o("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:w.generation,evaluatedAt:w.evaluatedAt,expiresAt:w.expiresAt,features:w.features,...w.merchandiseContext?{merchandiseContext:w.merchandiseContext}:{}}},onExperimentViewed:(q,R,w,x)=>g({kind:"experiment_exposure",generation:x,experimentId:q.key,variationId:R.key},w),onFeatureUsage:(q,R,w,x)=>g({kind:"feature_usage",generation:x,feature:q,value:R.value??null,source:R.source,ruleId:R.ruleId,...R.experimentResult?{variationId:R.experimentResult.key}:{}},w)}),i=P.refresh;function d(){clearTimeout(E),!s&&(D||S!==a||!P.expiresAt||(E=setTimeout(()=>{u().catch(v)},Math.min(2147483647,Math.max(1e3,Date.parse(P.expiresAt)-Date.now()))),typeof E=="object"&&"unref"in E&&E.unref()))}async function u(){try{return await i()}finally{d()}}let O=()=>{D||u().catch(v)},T=P.subscribe(d),A=s?.subscribe(()=>{!D&&s.fresh&&u().catch(v)});function k(){D||(D=!0,clearTimeout(E),typeof window<"u"&&window.removeEventListener("focus",O),T(),A?.(),P.reset(),l.delete(k))}l.add(k);try{await P.init(),(f.attributes?.merchandise||f.attributes?.merchandiseId)&&await P.refreshRemote()}catch(q){throw k(),q}return d(),!s&&typeof window<"u"&&window.addEventListener("focus",O),Object.assign(P,{refresh:u,destroy:k})}return{features:h,reset(f){a++,f();for(let S of l)S()}}}import{z as Te}from"zod";function we(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=Te.object({funnelId:G.shape.id,funnelVersionId:G.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new o("INVALID_REQUEST","A valid Funnel source is required");let s=Object.freeze(r.data);function a(l){if("customerId"in l)throw new o("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in l&&l.funnelId!==void 0&&l.funnelId!==s.funnelId||"funnelVersionId"in l&&l.funnelVersionId!==void 0&&l.funnelVersionId!==s.funnelVersionId)throw new o("SCOPE_MISMATCH","The original Funnel source cannot change");return{...l,...s}}return{async claimCoupon(l,y=crypto.randomUUID()){let h=c.grantOffer,f=await p(t,h,a({couponId:l,requestId:y}));return{offer:f.offer,reason:f.reason}},async resolveOffering(l){let y=c.resolveOffering,h=y.request.parse(a(l)),f=await p(t,y,h);return j(h,f.check,f.scope),f},async resolvePaywall(l){let y=c.resolvePaywall,h=y.request.parse(a(l)),f=await p(t,y,h);return j(h,f.paywall.check,f.scope),f},async previewAttach(l){let y=c.previewAttach;return p(t,y,a(l))}}}function Ht(t){return qe(t)}function qe(t){let e=te(t),n=e.request,r;try{r=se(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let s=ae(e,()=>{l.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Ie(n,s.isIdentified),l=ge(n,s.isIdentified,a,t.scope,t.configuration);return{session:e.session,...oe(n,r),...fe(n),...me(n),forFunnel(y){return s.assertActive(),we(n,y)},async features(y={}){return s.assertActive(),l.features(y)},track(y,h,f={}){return a.track(y,h,f)},flush(){return a.flush()},...s.methods}}function Qt(t){if(!L.test(t.customerToken))throw new o("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new o("INVALID_REQUEST","An explicit App and environment scope is required");let e=ie({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),s=B({...t,runToken:r.runToken});s.identify(t.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await s.get():r;return{...r,...a,controller:s}}}}function tn(t){if(!t.scope)throw new o("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new o("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,s=new Set,a=new Map,l=new Map;async function y(m){let C,I=new Promise((E,v)=>{C=setTimeout(()=>v(new o("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(m),I])}finally{clearTimeout(C)}}function h(m){throw m instanceof o&&(m.status===401||m.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear()),m}function f(m,C){if(C!==r)throw new o("IDENTITY_CHANGED","Process was detached during a request");let I=ee.parse(m);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new o("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new o("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new o("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let O of s)J(O,I.run);I.run.instruction?.type==="authentication_required"&&J(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&l.set(I.settlement.requestId,I.settlement.accepted);let{identity:E,instruction:v,...g}=I.run,{contract:P,settlement:i,...d}=I,u=i&&(({accepted:O,...T})=>T)(i);return{...d,run:{...g,authenticated:E.binding!==null,instruction:v?.type==="authentication_required"?null:v},...u?{settlement:u}:{}}}let S=m=>(a.has(m)||a.set(m,e?.run.identity.binding?.id??null),a.get(m));async function D(m){let C=r,I=e?.run.identity.binding?.id??null,E=g=>{if(I!==(e?.run.identity.binding?.id??null))throw g;return h(g)};if(m.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new o("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(m.release,m.usedReceiptIds)).catch(E)}let v;if(m.operation==="get"){let{operation:g,customerToken:P,...i}=m;v=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:S(i.settlementRequestId)}:{}})).catch(E)}else if(m.operation==="review")v=await y(()=>t.adapter.review(m.receiptId)).catch(E);else{if(m.operation==="start")throw new o("INVALID_REQUEST","Use process.open for entry");{let{customerToken:g,...P}=m;v=await y(()=>t.adapter.command(P,S(P.requestId))).catch(E)}}return f(v,C)}return{get view(){return e?.run??null},get controller(){return n},async open(m){let C=r,I=await y(()=>t.adapter.open(m)).catch(h);if(f(I,C),!n){n=B({...t,runToken:I.runToken,process:{request:D,binding:S,restore(g){for(let[P,i]of Object.entries(g))a.set(P,i)}}});let E=n,v=E.submit;E.submit=async g=>{try{return await v(g)}catch(P){if(!(P instanceof o)||P.reason!=="IDENTITY_CONTEXT_CHANGED"||g.operation!=="submit"||g.input.type!=="screen"||a.get(g.requestId)!==null)throw P;await E.settle?.(g.requestId),await E.get();let i=E.view;if(l.get(g.requestId)!==!1||!i||i.id!==e?.run.id||i.nodeId!==g.nodeId||i.visit!==g.visit||!e?.run.identity.binding)throw P;return v({...g,requestId:crypto.randomUUID(),revision:i.revision})}}}await n.get();for(let E of n.pendingCommands??[])a.has(E.requestId)&&a.get(E.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(E.requestId);return{run:e.run,controller:n}},async syncIdentity(){let m=r;f(await y(()=>t.adapter.syncIdentity()).catch(h),m),await n?.get();for(let C of n?.pendingCommands??[])a.has(C.requestId)&&a.get(C.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(C.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),await y(()=>t.adapter.detach())},forProcess(m){if(!e?.run.identity.binding)throw new o("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:m}},subscribe(m){return s.add(m),()=>{s.delete(m)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),s.clear()}}}export{Ht as a,qe as b,Qt as c,tn as d};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as mn,c as pn,d as gn,e as yn,f as wn}from"./chunk-FISFN5IY.js";import{a as te,b as Y}from"./chunk-LIAMO3LU.js";import{a as m}from"./chunk-KHIQQNTR.js";import{a as dn,b as fn,c as Ce}from"./chunk-VYYMUZAR.js";import{$ as Re,Da as ne,Ea as nn,Ha as tn,Ia as rn,Na as Te,Oa as on,Z as je,aa as Je,ab as an,ba as He,bb as sn,ca as ze,eb as un,fb as ln,ib as cn,lb as le,ma as Q,na as Qe,o as Ue,oa as j,pa as Ye,q as ue,qa as Oe,ra as M,ta as $e,ua as We,va as Ze,wa as Xe,xa as en}from"./chunk-ML4U33AO.js";import{C as ke,J as Ge,M as Be,Na as Ke,P as ve,a as qe}from"./chunk-4SWGHICJ.js";function zn(e){let n=null,t=null,a=0,d=0,w=new Set,f=null,o=null,g=new Set,i=()=>{for(let s of g)try{s()}catch{}},l={attributes:ve.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(s,r)=>{!w.has(s)&&n&&(!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(s,structuredClone(r),structuredClone(l.attributes),n.generation)}:void 0,onExperimentViewed:e.onExperimentViewed?(s,r)=>n&&(!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(s),structuredClone(r),structuredClone(l.attributes),n.generation):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?s=>e.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},u=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function c(s,r=new Set){return w.has(s)?!f||!f.features[s]||["unknownFeature","cyclicPrerequisite"].includes(f.features[s].source):r.has(s)?!1:(r.add(s),(n?.features[s]?.rules??[]).some(p=>[...p.parentConditions??[],...(p.tracks??[]).flatMap(v=>v.experiment.parentConditions??[])].some(v=>c(v.id,r))))}let h=s=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return f?.expiresAt&&Date.parse(f.expiresAt)<=Date.now()&&(f=null,l.features=n.features),w.has(s)?!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now()?u():structuredClone(f.features[s]??u()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!f||c(s)?u():structuredClone(Be(s,l))};async function A(){if(!n||!w.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(w.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=d;if(o?.revision===s)return o.loading;let r=a,p=n,v=[...w],C=(async()=>{let S=ze.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:v}));if(!(r!==a||s!==d||p!==n)){if(e.assertUsable?.(p.generation),S.generation!==p.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(v.some(R=>!Object.hasOwn(S.features,R))||Object.keys(S.features).some(R=>!w.has(R)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!S.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=ve.parse({...l.attributes,...S.merchandiseContext})}f=structuredClone(S),l.features={...p.features,...Object.fromEntries(Object.entries(f.features).map(([R,O])=>[R,{defaultValue:O.value}]))},i()}})();o={revision:s,loading:C};try{await C}finally{o?.loading===C&&(o=null)}}function N(){A().catch(s=>{try{e.onError?.(s)}catch{}})}async function x(){if(t)return t;let s=a,r=(async()=>{let p=await e.load(),v="remoteFeatures"in p?Je.parse(p):null,C=v??Re.parse(p);if(C.scope.projectId!==e.scope.projectId||C.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(s!==a)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===C.generation){let{evaluatedAt:R,expiresAt:O,...D}=n,{evaluatedAt:L,expiresAt:k,...G}=C;if(M(D)!==M(G))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=C.evaluatedAt,n.expiresAt=C.expiresAt,i(),(!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now())&&N(),structuredClone(n)}let S=new Set(v?.remoteFeatures??[]);if([...S].some(R=>Object.hasOwn(C.features,R)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in C&&!n.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),n=structuredClone(C),w=S,f=null,o=null,d++,l.features=n.features,l.savedGroups=Ge(n.savedGroups),l.trackedFeatureUsage={},i(),N(),structuredClone(n)})();t=r;try{return await r}finally{t===r&&(t=null)}}return{init:x,refresh:x,refreshRemote:A,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(s){return g.add(s),()=>{g.delete(s)}},setAttributes(s){let r=ve.parse(s);(l.attributes?.merchandise||l.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=r,d++,f=null,o=null,l.features=n?.features??{},l.trackedFeatureUsage={},i(),N()},evalFeature:h,isOn(s){return h(s).on},isOff(s){return h(s).off},getFeatureValue(s,r){let p=h(s).value;return structuredClone(p===null?r:p)},reset(){a++,d++,t=null,o=null,n=null,f=null,w.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),i()}}}function In(e){let n,t,a=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),d=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,t=e.locks??globalThis.navigator?.locks,!n||!t||!globalThis.crypto?.subtle)throw a();let o=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??le).href,e.runToken])),g=new Uint8Array(await crypto.subtle.digest("SHA-256",o));return"indiana.funnel.commands.v1."+Array.from(g,i=>i.toString(16).padStart(2,"0")).join("")});d.catch(()=>{});async function w(o){try{let g=await d;return await t.request(g,{mode:"exclusive"},()=>o(g))}catch(g){throw g instanceof m?g:a()}}function f(o){let g=n.getItem(o);if(g===null)return{revision:0,entry:null};if(g.length>1048576)throw a();let i=JSON.parse(g);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw a();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>w(f),write:(o,g)=>w(i=>{if(f(i).revision!==o)return null;if(!Number.isSafeInteger(o+1))throw a();return n.setItem(i,JSON.stringify({revision:o+1,entry:g})),o+1})}}function be(e,n){let t=tn.safeParse(n);if(!t.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let a=t.data;if(e.scope&&(a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return a}async function Pe(e,n){let t=Xe.parse(n),{artifact:a,environmentId:d}=t.content,w=new te(e.baseUrl??le).origin,f=new te(a.url,w);if(f.origin!==w||f.username||f.password||f.search||f.hash||f.pathname!==`/api/v1/configuration/${d}/artifacts/${a.sha256}`)throw new m("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,g,i=new Promise((u,c)=>{g=setTimeout(()=>{let h=new m("TIMEOUT","Public Paywall read timed out");o.abort(h),c(h)},j.initializationMs)}),l=(async()=>{let u=await(e.fetch??globalThis.fetch)(f,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(u.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!u.ok||!u.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(u.headers.get("content-length"))>a.byteLength)throw u.body?.cancel().catch(()=>{}),new m("INVALID_RESPONSE","Public Paywall is unavailable");let c=await dn(u,a.byteLength,{signal:o.signal,error:h=>new m("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ce(c,a))throw new m("INVALID_RESPONSE","Public Paywall digest or size changed");return en(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c)))})();try{return await Promise.race([l,i])}finally{clearTimeout(g)}}var _e=(e,n)=>new m(e,n);function ut(e){return ln(e,_e)}var _n=3,Dn=2e3;function Ln(e){return e instanceof TypeError||e instanceof m&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function xn(e){for(let n=1;;n++)try{return await e.refresh()}catch(t){if(n===_n||!Ln(t))throw t;await new Promise(a=>setTimeout(a,n*Dn))}}async function De(e,n,{predict:t=!0}={}){let a=n.instruction;if(a?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==a.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let d=null,w;if(t)try{let f=await e.funnel(n.source.id,n.source.versionId);w=f.manifest.generation,d=Vn(e,n,f)}catch{d=null}return w??=e.snapshot?.generation??(await xn(e)).generation,{advance:{policyRevision:a.policyRevision,generation:w},prediction:d}}function Vn(e,n,t){let a=n.instruction;if(a?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==a.policyRevision)return null;let{analyticsConfig:d,remoteFeatures:w,...f}=t.growth,o=an({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:a.policyRevision,document:t.document,payload:Re.parse(f)}),g=Mn(o,t.document,{...n,...a}),i=g.steps.at(-1),l=g.boundary??(i?.result.port==="value"?{nodeId:i.nodeId,visit:n.visit+g.steps.length-1}:null);return l?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:l.nodeId,visit:l.visit,terminal:!g.boundary}:null}function Mn(e,n,t){return cn(e,n,t,_e)}import{z as J}from"zod";var hn=Q.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),vn=J.strictObject({schemaVersion:J.literal(1),scope:qe,runId:J.uuid(),funnelId:J.uuid(),versionId:J.uuid(),processBindingIds:J.record(J.uuid(),J.uuid().nullable()).optional(),command:hn.optional(),closeCommand:hn.refine(e=>e.operation==="close").optional(),purchase:J.strictObject({receiptId:J.uuid(),operationId:J.uuid(),generation:J.number().int().nonnegative()}).optional(),closed:J.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),U=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Se=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function Rn(e){let n=0,t=null,a=i=>JSON.stringify([i.scope,i.runId,i.funnelId,i.versionId]),d=Promise.resolve();async function w(){let i=await e.read();if(!Number.isSafeInteger(i.revision)||i.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:i.revision,entry:i.entry===null?null:vn.parse(i.entry)}}function f(i){let l=d.then(i);return d=l.catch(()=>{}),l}async function o(i){for(let l=0;l<4;l++){let u=await w();if(u.entry&&t!==null&&a(u.entry)!==t)throw U();let c=i(u.entry,u.revision);if(Se(u.entry,c)){n=u.revision;return}let h=await e.write(u.revision,c);if(h!==null){if(!Number.isSafeInteger(h)||h<=u.revision)throw U();n=h;return}}throw U()}function g(i,l){if(!i||!l)return i;if(i.processBindingIds&&Object.hasOwn(i.processBindingIds,l)){let u={...i.processBindingIds};delete u[l],i={...i,processBindingIds:u}}return i.command?.requestId===l?i.closeCommand?{...i,command:i.closeCommand,closeCommand:void 0}:i.purchase?{...i,command:void 0}:null:i.closeCommand?.requestId===l?{...i,closeCommand:void 0}:i}return{bind(i){let l=JSON.stringify([i.scope,i.runId,i.funnelId,i.versionId]);if(t!==null&&t!==l)throw U();t=l},async load(){let i=await w();return n=i.revision,t=i.entry?a(i.entry):null,i.entry},retain(i){let l=vn.parse(i),u=l.command;return!u||t!==null&&a(l)!==t?Promise.reject(U()):(t??=a(l),f(()=>o((c,h)=>{if(c&&!Se(a(c),a(l)))throw U();if(c&&l.processBindingIds){for(let[A,N]of Object.entries(l.processBindingIds))if(c.processBindingIds&&Object.hasOwn(c.processBindingIds,A)&&c.processBindingIds[A]!==N)throw U();c={...c,processBindingIds:{...c.processBindingIds,...l.processBindingIds}}}if(!c){if(h!==n&&u.operation!=="close")throw U();return l}if(!c.command)return{...c,command:u,...u.operation==="close"?{closed:!0}:{}};if(u.operation==="close"&&c.command.operation!=="close"){if(c.command.requestId===u.requestId||c.closeCommand&&!Se(c.closeCommand,u))throw U();return{...c,closeCommand:u,closed:!0}}if(!Se(c.command,u))throw U();return c})))},observePurchase(i,l,u,c){return f(()=>o((h,A)=>{if(!h&&A!==n||h&&a(h)!==a({...i,schemaVersion:1}))throw U();if(h?.purchase&&h.purchase.generation>l.generation)return g(h,c);if(h?.purchase&&h.purchase.generation===l.generation&&h.purchase.operationId!==l.operationId)throw U();return u?!h?.purchase||h.purchase.operationId!==l.operationId?g(h,c):g(h.command?{...h,purchase:void 0}:null,c):g({schemaVersion:1,...i,...h,purchase:l},c)}))},settle(i){return f(()=>o(l=>g(l,i)))}}}function It(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ce(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((d,w)=>ce(d,n[w]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let t=Object.entries(e),a=Object.entries(n);return t.length===a.length&&t.every(([d,w])=>Object.hasOwn(n,d)&&ce(w,Reflect.get(n,d)))}function Cn(e,n){let t=n&&{...n},a=null,d=0,w=new AbortController;function f(){d++,w.abort(new m("IDENTITY_CHANGED","Run identity changed")),w=new AbortController}let o=!1,g,i=0,l=new Set;return{get scope(){return t},bindScope(u){if(t&&(t.projectId!==u.projectId||t.environment!==u.environment))throw new m("SCOPE_MISMATCH","Run scope changed");t??={...u}},get view(){return a},get generation(){return d},get signal(){return w.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return i},nextRead(){return++i},assertCurrent(u,c="Run identity changed during the request"){if(u!==d||o)throw new m("IDENTITY_CHANGED",c)},assertRun(u){if(a&&(u.id!==a.id||u.source.type!==a.source.type||u.source.id!==a.source.id||u.source.versionId!==a.source.versionId||u.locale!==a.locale||!ce(u.parameters,a.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&u.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(u,c,h,A,N){if(!(u.operation==="review"&&a&&a!==h&&c.run.revision<=a.revision)&&!(a&&c.run.revision===a.revision&&A!==void 0&&A<i)&&(u.operation==="review"&&!c.run.stopped&&["running","waiting"].includes(c.run.status)&&a&&c.run.nodeId===a.nodeId&&c.run.visit===a.visit&&c.run.revision===a.revision&&(c.run.screen=a.screen,(a.paywall?.quote?.operationId===c.review?.activeOperationId||!a.paywall?.quote&&c.review?.activeOperationId===null)&&(c.run.paywall=a.paywall)),!(a?.paywall&&c.run.paywall&&a.paywall.receiptId===c.run.paywall.receiptId&&(c.run.paywall.selectionGeneration??0)<(a.paywall.selectionGeneration??0)))){if(!a||c.run.revision>=a.revision)a=c.run;else if(!N)return;if(a)for(let x of l)try{x(structuredClone(a))}catch{}}},identify(u){if(o)throw new m("IDENTITY_CHANGED","Controller was reset");if(!ue.test(u))throw new m("INVALID_TOKEN","Customer credential required");f(),g=u},subscribe(u){return l.add(u),()=>l.delete(u)},reset(){o||(o=!0,f(),g=void 0,a=null,l.clear())}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function St(e,n,t="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",n);if(!re.test(e))throw new m("INVALID_TOKEN",t)}function Et(e){let n=Y(e);return n.identify(e.apiKey),n}function $(e){let{customerToken:n,...t}=e;return t}var qn=e=>!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function bn({journal:e,state:n,call:t,processIdentity:a}){let d=null,w=null,f=!1,o={command:null,close:null},g=new Set,i,l=null,u=e?e.load().then(s=>{if(n.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=s,!s)return;if(a){if([s.command,s.closeCommand].some(p=>p&&!Object.hasOwn(s.processBindingIds??{},p.requestId)))throw new m("COMMAND_STORAGE_INVALID","The original process identity is missing");a.restore(s.processBindingIds??{})}if(n.scope&&(s.scope.projectId!==n.scope.projectId||s.scope.environment!==n.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=s.purchase,f=s.closed===!0,!s.command)return;let r=s.command;d=r.operation==="close"?null:r,w=r.operation==="close"?r:s.closeCommand?.operation==="close"?s.closeCommand:null,w&&(f=!0);for(let p of[d,w])p&&g.add(p.requestId)}):Promise.resolve();u.catch(()=>{});async function c(s){e&&await u;let r=n.generation;if(e){if(!n.view||!n.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:$(s),...a?{processBindingIds:{[s.requestId]:a.binding(s.requestId)}}:{}})}if(r!==n.generation||d!==s&&w!==s)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let p=g.has(s.requestId);g.add(s.requestId);try{return await t(s)}catch(v){throw r===n.generation&&(d===s||w===s)&&!p&&!qn(v)&&(e&&await e.settle(s.requestId),r===n.generation&&x(s)),v}}function h(s){let r=Q.parse(s);if(r.operation==="start"||r.operation==="get"||r.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(f&&r.operation!=="close"){if(d?.requestId===r.requestId)return N(r.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(r.operation==="close"){if(d?.requestId===r.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(f=!0,w&&JSON.stringify($(w))!==JSON.stringify($(r)))throw new m("COMMAND_PENDING","Retry the original Close");return w??=r,o.close?o.close:A(w,"close")}if(d){if(JSON.stringify($(d))!==JSON.stringify($(r)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(o.command)return o.command}else d=r;return A(d,"command")}function A(s,r){let p=c(s);o[r]=p;let v=()=>{o[r]===p&&(o[r]=null)};return p.then(v,v),p}function N(s){return t({operation:"get",settlementRequestId:s})}function x(s){return!s||d!==s&&w!==s?!1:(d===s&&(d=null),w===s&&(w=null),g.delete(s.requestId),!d&&!w&&(l=null),!0)}return{ready:u,get pending(){return d},get closing(){return w},get closeRequested(){return f},get inFlight(){return o.command},get closeFlight(){return o.close},get purchase(){return i},assertBinding(s){if(l&&(s.run.id!==l.runId||s.run.source.id!==l.funnelId||s.run.source.versionId!==l.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,r,p,v){let C=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,S=C&&r.settlement?.state==="settled"&&r.run.pendingRequest?.requestId!==C&&(s.operation==="get"||!f||s.operation==="close"||!["running","waiting"].includes(r.run.status))?C:void 0,R=d?.requestId===S?d:w?.requestId===S?w:void 0;e?.bind({scope:r.scope,runId:r.run.id,funnelId:r.run.source.id,versionId:r.run.source.versionId});let O=r.run.paywall,D=O??r.purchase,L=D?.operation,k=r.settlement&&(!O||O.purchaseRequestId===r.settlement.requestId)&&(!i||i.operationId===r.settlement.operationId)?r.settlement:void 0,G=L?.operationId??D?.quote?.operationId??k?.operationId,H=D?.receiptId??k?.receiptId,de=O?.selectionGeneration??i?.generation??0;if(e&&G&&H&&s.operation!=="review"&&(!n.view||r.run.revision>=n.view.revision)&&(v===void 0||v>=n.readSequence)&&(!i||de>=i.generation)){let Z={receiptId:H,operationId:G,generation:de},fe=L?.status==="complete"||D?.canReselect===!0;await e.observePurchase({scope:r.scope,runId:r.run.id,funnelId:r.run.source.id,versionId:r.run.source.versionId},Z,fe,S),n.assertCurrent(p),(!i||Z.generation>=i.generation)&&(v===void 0||v>=n.readSequence)&&(fe?i?.operationId===Z.operationId&&(i=void 0):i=Z)}else e&&S&&await e.settle(S);return n.assertCurrent(p),S?x(R):!1},stop(){f=!0},submit:h,settle:N,reset(){f=!0,d=null,w=null,i=void 0,l=null,o.close=null,g.clear(),o.command=null}}}function Pn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new m("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Y({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),t=Cn(e.funnelId,e.scope??e.configuration?.scope),a=e.session?.subscribeIdentity(i),d=null,w=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?In(e):void 0),f=w&&Rn(w),o=bn({journal:f,state:t,call:l,processIdentity:e.process});async function g(r){if(e.process)return e.process.request(r);let p=t.generation;t.assertCurrent(p);let v=performance.now()+(e.timeoutMs??35e3),C=t.customerToken??("customerToken"in r?r.customerToken:void 0);if(e.session){let O=t.signal,D,L=()=>{},k=new Promise((G,H)=>{L=()=>H(O.reason),O.addEventListener("abort",L,{once:!0}),D=setTimeout(()=>H(new m("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{C=await Promise.race([Promise.resolve().then(()=>(t.assertCurrent(p),e.session.access())),k])}finally{clearTimeout(D),O.removeEventListener("abort",L)}}t.assertCurrent(p);let S={...r,...C?{customerToken:C}:{}},R=r.operation==="page_experiments"?Te.parse(S):Q.parse(S);return n.requestWithCredential("funnels",R,e.runToken,{headers:e.serverKey&&!C?{[rn]:e.serverKey}:void 0,timeoutMs:Math.max(1,v-performance.now())})}function i(){a?.(),t.reset(),o.reset(),d=null,n.dispose()}async function l(r,p){let v=t.generation,C=()=>t.assertCurrent(v);f&&await o.ready,C();let S=t.view,R=be(e,await g(r));if(r.operation==="review"&&!R.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(C(),R.runToken&&R.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let O=r.operation==="get"?r.settlementRequestId:"requestId"in r&&r.operation!=="start"?r.requestId:void 0;if(O&&R.settlement?.requestId!==O)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(R),t.assertRun(R.run),t.bindScope(R.scope);let D=await o.observe(r,R,v,p);return!R.run.stopped&&["running","waiting"].includes(R.run.status)&&r.operation==="get"&&r.settlementRequestId||(C(),["running","waiting"].includes(R.run.status)||o.stop(),t.publish(r,R,S,p,D)),R}let u=o.submit,c=null,h=new WeakMap;function A(r){let p=h.get(r);if(p)return p;let v=x(r);return h.set(r,v),v}let N=!1;async function x(r){let p=await r;if(p.run.instruction?.type!=="evaluate_segment")return p;if(c)return c;N=!0;let v=t.generation,C=(async()=>{for(let S=0;S<32&&p.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return p;let R=p.run;if(p.run.instruction?.type==="evaluate_segment"){let{advance:D}=await De(e.configuration,R,{predict:!1});if(v!==t.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return p;if(t.view&&(t.view.revision!==R.revision||t.view.visit!==R.visit||t.view.nodeId!==R.nodeId))return l({operation:"get"});let L=!0;De(e.configuration,R).then(({prediction:k})=>{L&&v===t.generation&&!o.closeRequested&&t.view?.id===R.id&&!t.view.stopped&&t.view.nodeId===R.nodeId&&t.view.visit===R.visit&&t.view.revision===R.revision&&(d=k)}).catch(()=>{});try{p=await u({operation:"commit_segment",requestId:nn(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...D})}finally{L=!1,d=null}}}return p})();c=C;try{return await C}finally{c===C&&(c=null)}}let s={get configuration(){return N?e.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let r=o.closing??o.pending;return r?structuredClone($(r)):null},get pendingCommands(){return[o.pending,o.closing].filter(r=>r!==null).map(r=>structuredClone($(r)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return f!==void 0},get prediction(){let r=t.view;return d&&r&&!r.stopped&&["running","waiting"].includes(r.status)&&r.id===d.runId&&r.nodeId===d.from.nodeId&&r.visit===d.from.visit&&r.revision===d.from.revision&&!o.closeRequested?structuredClone(d):null},settle:o.settle,get webViewUrl(){return"bundled"},resolvePaywall(r){return Pe(e,r)},async pageExperiments(r,p=[]){let v=t.generation;t.assertCurrent(v);let C=t.view?.id;if(!C)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let S=on.parse(await g(Te.parse({operation:"page_experiments",release:r,usedReceiptIds:p})));if(t.assertCurrent(v),S.runId!==C||S.scope.projectId!==t.scope?.projectId||S.scope.environment!==t.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return S},review(r){return l({operation:"review",...r?{receiptId:r}:{}},t.nextRead())},async get(r,p){f&&await o.ready,p??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let v=t.nextRead();return A(l({operation:"get",...r?{data:r}:{},...p?{purchase:p}:{}},v))},resume(r=t.view?.pendingRequest?.requestId){return r?o.closeRequested?s.settle(r):o.pending?.requestId===r?A(u(o.pending)):A(u({operation:"resume",requestId:r})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(r){return A(u(r))},retry(){return o.closeFlight?o.closeFlight:o.closing?u(o.closing):o.closeRequested&&o.pending?s.settle(o.pending.requestId):o.inFlight?A(o.inFlight):o.pending?A(u(o.pending)):Promise.reject(new m("INVALID_REQUEST","No command is pending"))},identify(r){t.identify(r),d=null,n.reset()},subscribe:t.subscribe,reset:i};return s}function Un(e,n,t,a){if(!ke(e,n)||t!==void 0&&n.observation&&n.observation.subject.customerId!==t||a!==void 0&&n.observation!==void 0&&(n.observation.subject.scope.projectId!==a.projectId||n.observation.subject.scope.environment!==a.environment))throw new m("INVALID_RESPONSE","The access requirement or Customer changed");return n}function Sn(e,n,t){if(e.requirement){if(!n)throw new m("INVALID_RESPONSE","The requested access check is missing");Un(e.requirement,n,e.customerId,t)}}import{ZodError as kn}from"zod";function En(e,n,t,a){try{return e.parse(n)}catch(d){throw a&&d instanceof kn?new m(t,a):d}}async function Ee(e,n,t,a={},d){let w=typeof a=="function"?{}:a,f=En(n.request,t,"INVALID_REQUEST",w.request);try{let o=await e(n.path,f,n.method,d),g=typeof a=="function"?a:a.parseResponse;return g?g(n.response,o):En(n.response,o,"INVALID_RESPONSE",w.response)}catch(o){throw o instanceof m&&f!==null&&typeof f=="object"&&"requestId"in f&&typeof f.requestId=="string"&&(o.commandRequestId??=f.requestId),o}}async function rr(e,n){if(!ue.test(n.customerToken))throw new m("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==n.customerToken)throw new m("SCOPE_MISMATCH","Paywall credential does not match the shared session");let t=ne.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),a=Y(e);e.session||a.identify(n.customerToken);let d=null,w=!1,f=null,o=null,g=null,i=null,l=null,u=null,c=null,h=0;function A(){if(w)throw new m("IDENTITY_CHANGED","Paywall is closed")}async function N(){A();let p=ne.resolvePaywall,v=await Ee(a.request,p,{...t,selector:d?{type:"version",versionId:d.id}:t.selector});Sn(t,v.paywall.check,v.scope);let C=await Pe(e,v.paywall);if(A(),n.paywallVersionId?C.id!==n.paywallVersionId:C.paywallId!==n.paywallId)throw new m("INVALID_RESPONSE","The requested Paywall changed");if(d&&(!mn(C,d)||C.paywallId!==d.paywallId))throw new m("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return d=C,structuredClone(d)}async function x(p){if(A(),i&&p!=="read")throw new m("COMMAND_PENDING","Wait for the original quote");if(!f)throw new m("INVALID_REQUEST","A quoted purchase is required");let v=f;if(p!=="read"){if(c){if(u===p)return c;throw new m("COMMAND_PENDING","Wait for the original purchase command")}if(u&&u!==p)throw new m("COMMAND_PENDING","Read the original purchase before changing an uncertain command");u=p,h++}let C=u,S=h,R=p==="read"&&c===null,O=p==="read"?ne.readSubscriptionOperation:ne.attach,D=(async()=>{let L=await Ee(a.request,O,{operationId:v.operationId,...p==="read"?{}:{intent:p},...p==="confirm"&&v.merchantTerms?{merchantConfirmation:Ue(v.merchantTerms)}:{}});return pn(L.operation,{operationId:v.operationId,currency:t.commerce.currency},"The purchase operation changed"),A(),f?.operationId!==v.operationId?structuredClone(L.operation):(o=yn(o,L.operation),(p!=="read"||R&&c===null)&&h===S&&u===C&&(u=null),structuredClone(o))})();if(p!=="read"){c=D;let L=()=>{c===D&&(c=null)};D.then(L,L)}return D}let s={get view(){return d?structuredClone(d):null},get quote(){return f?structuredClone(f):null},get operation(){return o?structuredClone(o):null},get webViewUrl(){return"bundled"},get recovery(){return wn({quote:f,operation:o,requestId:l,pending:i!==null||u!==null,destroyed:w})},get pendingCancellation(){return!w&&u==="cancel"},refresh:N,async preview(p){if(A(),!d)throw new m("INVALID_REQUEST","Load the Paywall first");let v=d.document.buttons[p.actionId];if(v?.type!=="checkout")throw new m("INVALID_REQUEST","Choose an authored purchase action");let C=je(v.product,p.selection,d.capabilities);if(!C)throw new m("PRODUCT_UNAVAILABLE","Choose an available Product");let S=Ke(d.document.screen,C,p.selection,d.capabilities),R=ne.previewAttach.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,requestId:p.requestId,plans:[{productVersionId:C,...Object.keys(S).length?{featureQuantities:S}:{}}],provider:t.commerce.provider,currency:t.commerce.currency,...p.offerId?{offerId:p.offerId}:{},...p.nativeOffer?{nativeOffer:p.nativeOffer}:{}}),O=JSON.stringify(R);if(g&&g!==O&&(i||u||!o||o.status==="pending"))throw new m("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(g===O){if(i)return i;if(f)return structuredClone(f)}g!==O&&(f=null,o=null),g=O,l=R.requestId;let D=(async()=>{let L=ne.previewAttach,k=await Ee(a.request,L,R);return A(),gn(k.quote,{productVersionId:C,featureQuantities:S,currency:t.commerce.currency,provider:t.commerce.provider},"The purchase quote changed its selected Product or presentment"),f=k.quote,o=null,structuredClone(f)})();i=D;try{return await D}finally{i===D&&(i=null)}},confirm:()=>x("confirm"),cancel:()=>x("cancel"),read:()=>x("read"),destroy(){w||(w=!0,r?.(),a.dispose(),d=null,f=null,o=null,g=null,l=null)}},r=e.session?.subscribeIdentity(s.destroy);try{return await N(),s}catch(p){throw s.destroy(),p}}import{z as Jn}from"zod";import{z as ge}from"zod";var Gn=ge.record(ge.string().regex(/^[a-f0-9]{64}$/),ge.strictObject({at:ge.number(),text:ge.string()})),oe=2*1048576,Bn=100;function jn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function An(e,n){let t=n===void 0?jn():n,a=new Map,d=0,w=!1,f=!1,o,g;async function i(u){if(!t)return null;let c;try{let h=await Promise.race([Promise.resolve().then(()=>t.getItem(u)),new Promise(A=>{c=setTimeout(()=>A(null),Bn)})]);return typeof h=="string"&&h.length<=oe&&new TextEncoder().encode(h).byteLength<=oe?h:null}catch{return null}finally{clearTimeout(c)}}function l(){if(g)return g;let u=(async()=>{try{let c=await i(`${e}:artifacts`);if(c)return Gn.parse(JSON.parse(c))}catch{}return{}})();return g=u,u.finally(()=>{g===u&&(g=void 0)}),u}return{async readManifest(){return i(e)},writeManifest(u){!t||u.length>oe||new TextEncoder().encode(u).byteLength>oe||(o=u,!f&&(f=!0,Promise.resolve().then(async()=>{try{for(;o!==void 0;){let c=o;try{await t.setItem(e,c)}catch{}o===c&&(o=void 0)}}finally{f=!1}})))},async readArtifact(u){let c=(await l())[u],h=Date.now();return c&&h>=c.at&&h-c.at<=j.retentionMs?c.text:void 0},writeArtifact(u,c){if(!t||c.length>oe)return;let h=a.get(u);if(h?.text===c||!h&&a.size>=128)return;let A=new TextEncoder().encode(c).byteLength;d-(h?.byteLength??0)+A>oe||(a.set(u,{text:c,byteLength:A}),d+=A-(h?.byteLength??0),!w&&(w=!0,Promise.resolve().then(async()=>{try{for(;a.size;){let N=new Map(a);try{let x={...await l()},s=Date.now();for(let[C,S]of N)x[C]={at:s,text:S.text};let r={},p=2,v=0;for(let[C,S]of Object.entries(x).sort(([,R],[,O])=>O.at-R.at)){if(S.at>s||s-S.at>j.retentionMs)continue;let R=new TextEncoder().encode(JSON.stringify({[C]:S})).byteLength;p+R>oe||v>=128||(r[C]=S,p+=R,v++)}await t.setItem(`${e}:artifacts`,JSON.stringify(r))}catch{}finally{for(let[x,s]of N)a.get(x)===s&&(a.delete(x),d-=s.byteLength)}}}finally{w=!1}})))}}}var E=(e,n)=>new m(e,n),W=()=>performance.now(),Fn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function gr(e){let n=Ye.parse(e.scope),t=new te(e.origin??le);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw E("INVALID_URL","Configuration requires a trusted HTTPS origin");let a=new Set([t.origin,...(e.assetOrigins??[]).map(I=>{let y=new te(I);if(y.protocol!=="https:"||y.username||y.password||y.search||y.hash||y.pathname!=="/")throw E("INVALID_URL","Invalid configuration asset origin");return y.origin})]),d=e.fetch??globalThis.fetch.bind(globalThis),w=`/api/v1/configuration/${n.environmentId}`,f=`indiana:configuration:1:${t.origin}:${M(n)}`,o=An(f,e.storage),g,i=0,l=0,u=!1,c=!1,h=0,A=0,N,x,s,r,p=0,v=new Set,C=new Set,S=new Map,R=new Map,O=0,D=!1;function L(){for(let I of v)try{I()}catch{}}function k(I){try{e.onError?.(I)}catch{}}let G=()=>!c&&!u&&!!g&&W()<i&&Date.now()<l;function H(){if(!G())throw E("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function de(I,y,b){if(!S.has(I)){for(;S.size&&(S.size>=128||O+b>j.maxCacheBytes);){let P=S.entries().next().value;O-=P[1].byteLength,S.delete(P[0])}S.set(I,{text:y,byteLength:b}),O+=b}}function Z(I,y,b){return fn(I,y,{signal:b,error:P=>E("INVALID_RESPONSE",P==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function fe(I){let y=new te(I,t);if(!a.has(y.origin)||y.username||y.password||y.hash||y.search)throw E("INVALID_URL","Configuration artifact origin is not trusted");return y.href}async function Ae(I,y,b=!1){let P=await d(fe(I),{method:"GET",credentials:"omit",redirect:"error",cache:b?"default":"no-cache",signal:y,headers:{}});if(P.status===429){let T=P.headers.get("retry-after")??"";p=/^\d+$/.test(T)?Number(T)*1e3:Math.max(0,Date.parse(T)-Date.now())||15e3}if(!P.ok&&P.status!==304)throw E(`CONFIGURATION_HTTP_${P.status}`,"Configuration synchronization failed");return P}function On(I,y,b){let P=Date.parse(I.headers.get("x-indiana-config-validated-at")??""),T=Date.parse(I.headers.get("x-indiana-config-valid-until")??""),_=Date.parse(I.headers.get("date")??""),F=I.headers.get("age"),B=F!==null&&/^\d+(\.\d+)?$/.test(F)?Number(F)*1e3:NaN;if(![P,T,_,B].every(Number.isFinite)||T<=P||T-P>j.maxControlAgeMs||P>_+1e3)throw E("INVALID_RESPONSE","Configuration freshness evidence is invalid");let V=Math.min(T-P,b.maxControlAgeSeconds*1e3,j.maxControlAgeMs)-Math.max(B,_-P,0)-(W()-y);if(V<=0)throw E("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return W()+V}function Fe(){if(clearTimeout(s),clearTimeout(r),c||!v.size)return;G()&&(r=setTimeout(()=>{G()?Fe():L()},Math.max(1,i-W())),Fn(r));let I=A?Math.min(15e3,1e3*2**Math.min(A-1,4)):Math.min(15e3,(g?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{ie().catch(k)},Math.max(p,I*(.8+Math.random()*.2))),Fn(s)}async function ie(){if(c)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(N)return N;let I=h,y=new AbortController;x=y;let b=(async()=>{if(!D){D=!0;try{let he=await o.readManifest();if(he&&!g){let K=Oe.parse(JSON.parse(he));M(K.scope)===M(n)&&(g=K)}}catch{}}y.signal.throwIfAborted();let F=g,B=W(),q=await Ae(w,y.signal);q.status===304&&(!F||!q.headers.has("x-indiana-config-validated-at")||!q.headers.has("x-indiana-config-valid-until")||!q.headers.has("age"))&&(q=await Ae(w,y.signal));let V=q.status===304?F:Oe.parse(JSON.parse(await Z(q,j.maxManifestBytes,y.signal))),{generation:ae,...se}=V,z=q.headers.get("etag");if(M(V.scope)!==M(n)||$e(se)!==ae||z!==`"${ae}"`&&z!==`W/"${ae}"`)throw E("INVALID_RESPONSE","Configuration scope or content identity changed");if(F&&(V.revision<F.revision||V.revision===F.revision&&V.generation!==F.generation))throw E("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[he,K]of Object.entries(F?.funnels??{})){let ee=V.funnels[he];if(ee&&(ee.controlRevision<K.controlRevision||ee.evaluationRevision<K.evaluationRevision||ee.controlRevision===K.controlRevision&&ee.state!==K.state||ee.evaluationRevision===K.evaluationRevision&&ee.evaluationMode!==K.evaluationMode))throw E("INVALID_RESPONSE","Funnel control revision changed identity")}let X=On(q,B,V.policy);if(y.signal.throwIfAborted(),I!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return g=V,i=X,l=Date.now()+Math.max(0,X-W()),u=!1,A=0,p=0,o.writeManifest(M(V)),L(),structuredClone(V)})(),P=setTimeout(()=>y.abort(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),j.initializationMs),T=new Promise((F,B)=>y.signal.addEventListener("abort",()=>B(y.signal.reason),{once:!0})),_=Promise.race([b,T]).catch(F=>{throw A++,(F instanceof Jn.ZodError||F instanceof SyntaxError||F instanceof m&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(F.code))&&(i=0,u=!0,L()),F}).finally(()=>{clearTimeout(P),N===_&&(N=void 0),Fe()});return N=_,_}async function ye(I){let y=I.sha256,b=se=>Ce(se,I);fe(I.url);let P=S.get(y);if(P){if(P.byteLength!==I.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return S.delete(y),S.set(y,P),P.text}let T=R.get(y);if(T){if(T.byteLength!==I.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return T.promise}let _=new AbortController;C.add(_);let F=h,B=(async()=>{try{let X=await o.readArtifact(y);if(X&&b(X)){if(_.signal.throwIfAborted(),c||F!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(y,X,I.byteLength),X}}catch{}_.signal.throwIfAborted();let se=await Ae(I.url,_.signal,!0),z=await Z(se,I.byteLength,_.signal);if(!b(z))throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(c||F!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(y,z,I.byteLength),o.writeArtifact(y,z),z})(),q=setTimeout(()=>_.abort(E("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),j.initializationMs),V=new Promise((se,z)=>_.signal.addEventListener("abort",()=>z(_.signal.reason),{once:!0})),ae=Promise.race([B,V]).finally(()=>{clearTimeout(q),C.delete(_),R.delete(y)});return R.set(y,{promise:ae,byteLength:I.byteLength}),ae}async function we(){return G()||await ie(),H(),g}async function me(I){let y,b=new Promise((P,T)=>{y=setTimeout(()=>T(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),j.initializationMs)});try{return await Promise.race([I(),b])}finally{clearTimeout(y)}}function pe(I,y){if(H(),g?.generation!==I.generation)throw E("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(y&&g.funnels[y]?.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Le(I){let y=I.gb.features;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let b=I.artifacts[y];if(b.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let P=He.parse(JSON.parse(await ye(b)));if(M(P.scope)!==M({projectId:n.projectId,environment:n.environment})||P.generation!==b.generation||P.remoteFeatures.some(T=>Object.hasOwn(P.features,T)))throw E("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return pe(I),{...P,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,i-W())).toISOString()}}async function xe(I,y){let b=await we(),P=b.funnels[I];y&&(!P||P.evaluationMode==="local"&&!P.versions[y])&&(N&&await N,b=await ie()),pe(b,I);let T=b.funnels[I];if(T.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let _=y??T.currentVersionId,F=T.versions[_];if(!F)throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(b.artifacts[F.artifact].formatVersion!==3)throw E("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[B,q]=await Promise.all([ye(b.artifacts[F.artifact]).then(V=>Ze(JSON.parse(V))),T.evaluationMode==="local"?Le(b):void 0]);if(q&&M(We(B,q))!==M(F.dependencies))throw E("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return pe(b,I),{document:B,growth:q,versionId:_,control:structuredClone(T),manifest:structuredClone(b)}}async function Ve(I,y){try{return await xe(I,y)}catch(b){if(!(b instanceof m)||!(b.code==="CONFIGURATION_CHANGED"||b.code==="CONFIGURATION_HTTP_404"&&G()))throw b;let P=g?.generation;if(N&&await N,await ie(),b.code!=="CONFIGURATION_CHANGED"&&g?.generation===P)throw b;return xe(I,y)}}function Ne(){u=!0,L(),ie().catch(k)}let Ie=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ne()};function Tn(I){if(c)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(I),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ne),window.addEventListener("focus",Ie),document.addEventListener("visibilitychange",Ie)),Fe()),()=>{v.delete(I),v.size||(clearTimeout(s),clearTimeout(r),Me())}}function Me(){typeof window<"u"&&(window.removeEventListener("online",Ne),window.removeEventListener("focus",Ie),document.removeEventListener("visibilitychange",Ie))}return{scope:Object.freeze({...n}),refresh:ie,subscribe:Tn,assertFresh:H,assertFeatures(I){H();let y=g.gb.features;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(I!==void 0&&g.artifacts[y].generation!==I)throw E("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return G()},get snapshot(){return g?structuredClone(g):null},get remainingMs(){return G()?Math.max(0,i-W()):0},async features(){return me(async()=>Le(await we()))},pageExperiments:()=>me(async()=>{let I=await we(),y=I.gb.pageExperiments;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let b=I.artifacts[y];if(b.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let P=un.parse(JSON.parse(await ye(b)));if(P.environmentId!==n.environmentId||P.generation!==b.generation)throw E("INVALID_RESPONSE","Page experiment scope or generation changed");return pe(I),P}),funnel:(I,y)=>me(()=>Ve(I,y)),paywall:(I,y)=>me(async()=>{let b=await we(),P=b.paywalls?.[I];if(!P||!y&&P.state!=="published")throw E("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let T=y??P.currentVersionId,_=P.versions[T],F=_&&b.artifacts[_.artifact];if(!F||F.kind!=="paywall"||F.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let B=Qe.parse(JSON.parse(await ye(F)));return pe(b),{document:B,versionId:T,version:_.version,control:structuredClone(P),manifest:structuredClone(b)}}),async localFunnel(I,y){let b=await me(()=>Ve(I,y));if(!b.growth)throw E("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:P,remoteFeatures:T,..._}=b.growth;return sn({scope:{projectId:n.projectId,environment:n.environment},funnelId:I,versionId:b.versionId,evaluationMode:"local",evaluationRevision:b.control.evaluationRevision,document:b.document,payload:_})},assertFunnel(I,y,b){H();let P=g.funnels[I];if(!P||P.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable");if(P.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel now executes at Longplay");if(y!==void 0&&P.controlRevision!==y)throw E("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(b!==void 0&&!P.versions[b])throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!c){c=!0,h++,i=0,x?.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(r),Me(),L(),v.clear();for(let I of C)I.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));S.clear(),O=0}}}}function Nn(e){let n=ue.test(e.apiKey);if(typeof window<"u"&&!n)throw new m("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new m("INVALID_TOKEN","A customer credential or server API key is required");return{async start(t){let a=Q.safeParse({...t,operation:"start"});if(!a.success||a.data.operation!=="start"||(n?a.data.customer!==void 0:a.data.customer===void 0))throw new m("INVALID_REQUEST","Invalid current Funnel start");let d=a.data,w=Y({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||w.identify(e.apiKey);let f=be(e,await w.request("funnels",d));if(!f.runToken)throw new m("INVALID_RESPONSE","Funnel start credentials are missing");if(f.run.source.id!==d.funnelId||f.run.locale!==(d.locale??"en")||!ce(f.run.parameters,d.parameters??{})||(d.customer?!f.customerId||d.customer.type==="id"&&f.customerId!==d.customer.value:f.customerId!==void 0))throw new m("INVALID_RESPONSE","Funnel start contract changed");return{...f,runToken:f.runToken}}finally{w.dispose()}}}}async function Fr(e){e={...e};let n=e.configuration;if(!n)throw new m("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&M(t)!==M(e.scope))throw new m("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new m("EVALUATION_MODE","This Funnel uses Remote evaluation");let d=re.test(e.credential);if(d?!e.customerId:e.customerId!==void 0)throw new m("INVALID_REQUEST","Only Server-Key starts name their Customer");let w=Nn({...e,scope:t,apiKey:e.credential}),f=o=>{let g=Pn({...e,scope:t,runToken:o,...d?{serverKey:e.credential}:{}});return d||g.identify(e.credential),g};return{async start(o){let g=await w.start({...o,funnelId:e.funnelId,...d?{customer:{type:"id",value:e.customerId}}:{}}),i=f(g.runToken),l=await i.get();return{...g,...l,controller:i}},async restore(o){let g=f(o),i=await g.get();if(i.run.source.id!==e.funnelId)throw g.reset(),new m("SCOPE_MISMATCH","Run belongs to another Funnel");return{...i,runToken:o,controller:g}}}}export{Ee as a,Un as b,Sn as c,zn as d,be as e,_e as f,ut as g,Mn as h,In as i,It as j,ce as k,St as l,Et as m,Pn as n,rr as o,gr as p,Nn as q,Fr as r};
|