@tinkerlandai/indiana-sdk 0.6.0 → 0.6.2
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 +15 -1
- package/README.md +17 -11
- package/README.zh-CN.md +21 -16
- package/dist/{chunk-OK2Q6IJD.js → chunk-ET4NANGB.js} +1 -1
- package/dist/{chunk-5WY3AXSS.js → chunk-J7M7UH74.js} +1 -1
- package/dist/{chunk-PCVQHHEE.js → chunk-M3DG6ZCT.js} +1 -1
- package/dist/chunk-N6UIDDAX.js +4 -0
- package/dist/chunk-VMLGV5OS.js +11 -0
- package/dist/funnel-runtime-host-3STQUS6F.js +1 -0
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/page.d.ts +2 -1
- package/dist/page.js +1 -1
- package/dist/{paywall-TCE5DE5T.js → paywall-LBDMGVWZ.js} +1 -1
- package/dist/popup.d.ts +10 -6
- package/dist/popup.js +176 -6
- package/dist/server.js +1 -1
- package/dist/src-X6KT6WIH.js +1 -0
- package/dist/visual.js +1 -1
- package/package.json +10 -9
- package/dist/chunk-4JBIKJMU.js +0 -4
- package/dist/chunk-HU2HIDVT.js +0 -11
- package/dist/funnel-runtime-host-L3WILUHK.js +0 -1
- package/dist/src-VGIVVM27.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
Release facts and artifact evidence: [SDK release ledger](../../docs/sdk-releases.md).
|
|
3
|
+
Release facts and artifact evidence: [SDK release ledger](../../docs/sdk-releases.md). The two packages have independent version histories.
|
|
4
|
+
|
|
5
|
+
## 0.6.2 — 2026-10-22
|
|
6
|
+
|
|
7
|
+
- Publish checked artifacts through GitHub Actions with npm Trusted Publishing and verify the public package bytes and independent installation after publication.
|
|
8
|
+
- Export the deterministic hosted renderer shell, content address and CSP from the popup entry so SDK consumers share the same renderer identity.
|
|
9
|
+
- Keep protocol 0.6, the existing API origin and the Customer, entitlement and usage contracts. The 0.6.1 Funnel input, command settlement and Back recovery fixes remain included.
|
|
10
|
+
|
|
11
|
+
## 0.6.1 — 2026-10-22
|
|
12
|
+
|
|
13
|
+
- Submit only the current Funnel screen's declared input bindings. Preserve historical answers, unsaved drafts during refresh and values when navigating Back.
|
|
14
|
+
- Validate public Local Funnel Feature dependencies against their declared write variables.
|
|
15
|
+
- Settle the original accepted command during host polling so background completion releases the next screen and terminal recovery.
|
|
16
|
+
- Recover a rejected screen display acknowledgement after Back without resubmitting the user's action.
|
|
17
|
+
- Keep protocol 0.6 and the existing immutable renderer identity. Runtime and production acceptance are recorded separately in the release ledger.
|
|
4
18
|
|
|
5
19
|
## 0.6.0 — 2026-10-21
|
|
6
20
|
|
package/README.md
CHANGED
|
@@ -2,12 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
[简体中文](./README.zh-CN.md)
|
|
4
4
|
|
|
5
|
-
Version **0.6.
|
|
5
|
+
Version **0.6.2 / protocol 0.6** requires a matching Indiana runtime and database. Remote Funnel responses contain the current page's `ScreenDocument` JSON; Local and Remote use the same renderer, canonical Run, business receipts and Queue recovery. Remote graphs and private rules stay on the server.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Version 0.6.2 adds a shared deterministic hosted renderer shell and uses GitHub Actions with npm Trusted Publishing. It retains the 0.6.1 fixes for current-screen input patches, Local Feature dependency validation, original-command settlement during host polling and display acknowledgement recovery after Back. Complete production browser and Stripe acceptance remains separate; see the [repair report](../../docs/deployment-receipts/20261022-sdk-funnel-repair/README.md).
|
|
8
|
+
|
|
9
|
+
Pin this package to a matching protocol 0.6 service. The published npm 0.6.0 package passes 21 foundation operations through `https://api.dev.tinker.cash`, with readiness 200 and correlated Go request logs; remaining capabilities and production business dependencies have separate gates. npm publication does not extend that accepted scope. Actual publication, tags and environment state are recorded in the [release ledger](../../docs/sdk-releases.md).
|
|
8
10
|
|
|
9
11
|
```sh
|
|
10
|
-
npm install --save-exact @tinkerlandai/indiana-sdk@0.6.
|
|
12
|
+
npm install --save-exact @tinkerlandai/indiana-sdk@0.6.2
|
|
11
13
|
```
|
|
12
14
|
|
|
13
15
|
Indiana's JavaScript and TypeScript SDK supports browsers, Node.js, screen rendering and optional AI usage integrations. Environment collection controls and existing Invoice/billing-window contracts remain available. Older 0.x protocols are rejected before business execution.
|
|
@@ -16,7 +18,7 @@ Indiana's JavaScript and TypeScript SDK supports browsers, Node.js, screen rende
|
|
|
16
18
|
|
|
17
19
|
During `0.x`, only the current protocol is supported. Starting with `1.0`, compatibility is preserved within each stable major version. Once the next stable major is published, the preceding stable major remains supported for at least 12 calendar months, with at least 180 days' public notice before retirement. The later deadline applies. See the [support policy](https://tinker.cash/docs/release-notes#support-policy).
|
|
18
20
|
|
|
19
|
-
Version `0.6.
|
|
21
|
+
Version `0.6.2` sends protocol and SDK version headers and validates the protocol declared by successful responses. Headerless historical clients retain the fixed identity `0.2`; they do not follow the current protocol automatically. Updating source code does not change an existing npm artifact or deploy a server.
|
|
20
22
|
|
|
21
23
|
## One package, seven entry points
|
|
22
24
|
|
|
@@ -32,6 +34,10 @@ Version `0.6.0` sends protocol and SDK version headers and validates the protoco
|
|
|
32
34
|
|
|
33
35
|
The same package supports JavaScript and TypeScript and includes type declarations. Internal `@indiana/contracts` code is bundled; consumers do not install private workspace packages. Swift and Kotlin use their own package ecosystems and are released separately.
|
|
34
36
|
|
|
37
|
+
The separate [Python server SDK](../python/README.md) provides synchronous and asynchronous Customer, holdings, entitlement-check and usage clients against the same current HTTP protocol. Its source, local wheel and eventual PyPI publication have independent acceptance; it is not part of this npm package.
|
|
38
|
+
|
|
39
|
+
The [Go server SDK](../go/README.md) provides the same initial capabilities with typed responses, Context cancellation and goroutine-safe client reuse. Its source is a module inside this repository; distribution and publication are separate from this npm package.
|
|
40
|
+
|
|
35
41
|
## API origin and test services
|
|
36
42
|
|
|
37
43
|
The canonical repository policy, including production/test domain roles, package tags and test-host configuration, is [SDK API entry and development testing](../../docs/sdk-endpoints-and-testing.md).
|
|
@@ -42,7 +48,7 @@ Both `beta` and `latest` versions published with this default use the production
|
|
|
42
48
|
|
|
43
49
|
For our own testing, always require a test-service address instead of relying on the production default:
|
|
44
50
|
|
|
45
|
-
The
|
|
51
|
+
The test API origin is `https://api.dev.tinker.cash`; `dev.tinker.cash` is the test site/Admin entry. Set `INDIANA_TEST_BASE_URL=https://api.dev.tinker.cash` and use the native Cloud SQL test App/Key. The legacy active dev Admin has its original database binding, so its old keys do not automatically authenticate against Go. Foundation acceptance covers 21 operations; Funnel, public configuration and provider execution remain closed. Future `beta` and `latest` SDK releases share the production default; the test host supplies the override.
|
|
46
52
|
|
|
47
53
|
```ts
|
|
48
54
|
const testBaseUrl = process.env.INDIANA_TEST_BASE_URL;
|
|
@@ -63,7 +69,7 @@ const configuration = createConfigurationSync({
|
|
|
63
69
|
|
|
64
70
|
Use the same explicit address for every client in a test run, including Funnel start/controllers and page/visual clients. Environment variables are read by the host, not automatically by the SDK. Sandbox/Live selects business scope inside the chosen service; it does not select a deployment or database. Never retry against another service automatically after an error or unknown command result.
|
|
65
71
|
|
|
66
|
-
Offline tests inject `fetch` and assert the default address, overrides and failure behavior without reaching the public API. Integration tests consume a fixed local SDK tarball against an explicitly selected, protocol-compatible test runtime and retain its version/hash and request IDs.
|
|
72
|
+
Offline tests inject `fetch` and assert the default address, overrides and failure behavior without reaching the public API. Integration tests consume a fixed local SDK tarball against an explicitly selected, protocol-compatible test runtime and retain its version/hash and request IDs. The published-0.6 test API acceptance covers the 21-operation native foundation, including idempotent business results and permission refusals; broader capabilities, browsers and production require separate acceptance. See the [maintainer testing procedure](../../docs/sdk-selfserve.md#maintainer-api-origin-testing).
|
|
67
73
|
|
|
68
74
|
## Create a Customer Session from a trusted backend
|
|
69
75
|
|
|
@@ -124,7 +130,7 @@ await indiana.createGuestCustomer({
|
|
|
124
130
|
|
|
125
131
|
Indiana keeps the first supplied signal as an environment-scoped hash; later values do not replace it. Missing input is valid and retains per-Customer trial deduplication. `unique_fingerprint` additionally deduplicates the configured Product trial across Customers sharing the signal. Business user IDs do not identify an installation; Customer/Guest/session tokens and request IDs have their own lifecycles and should not be fingerprints.
|
|
126
132
|
|
|
127
|
-
On Web, an independent first-party installation cookie can retain the signal. Clearing it or changing browser storage can produce a new value; sign-out need not reset it. Native hosts persist a random installation signal and define reinstall, restore and reset behavior. This signal is separate from device attestation and authentication.
|
|
133
|
+
On Web, an independent first-party installation cookie can retain the signal. Clearing it or changing browser storage can produce a new value; sign-out need not reset it. Native hosts persist a random installation signal and define reinstall, restore and reset behavior. This signal is separate from device attestation and authentication. Trial conflicts remain generic to clients; retain `X-Request-Id` for server-side diagnosis.
|
|
128
134
|
|
|
129
135
|
## Funnel, Feature, and standalone Paywall
|
|
130
136
|
|
|
@@ -132,7 +138,7 @@ A trusted backend calls `createFunnelStartClient().start()` with `funnelId`, a r
|
|
|
132
138
|
|
|
133
139
|
`createFunnelClient({ customerToken, ...options })` is for clients that already hold a Customer credential. Its `start()` omits `customer` and `customerData` and runs as the credential's Customer. After response loss, retry with the same request ID and input. Put commercial parameters in `parameters.commerce`. Each Run has its own Run Token, which cannot switch Customer identity.
|
|
134
140
|
|
|
135
|
-
`createFunnelDecisionClient.submit/decide` and the server entry's `createFunnelCampaignClient` use the same explicit Customer reference. Campaign `decide
|
|
141
|
+
`createFunnelDecisionClient.submit/decide` and the server entry's `createFunnelCampaignClient` use the same explicit Customer reference. Campaign `decide()` waits for a `FunnelDecision`; a lookup can return the original accepted decision and its original request ID. Campaign `start()` returns either Run credentials or `{ suppressed: true, reason, retryAt }` when frequency or an active Run blocks a new start, without fabricating Run credentials. Report `shown` only after the Run is actually displayed; page closure or local storage cannot replace a durable presentation fact.
|
|
136
142
|
|
|
137
143
|
In a browser, use `createFunnelRunController` and `showFunnelRun`. The controller handles current-protocol commands, reads, retries, recovery, and subscriptions. Presentation handles provide `refresh()` and `destroy()`. Published nodes delegate business operations to the server. A client assertion or redirect is not payment evidence.
|
|
138
144
|
|
|
@@ -146,7 +152,7 @@ For Customer-based evaluation, `id` means the Indiana Customer UUID (`customer.i
|
|
|
146
152
|
|
|
147
153
|
`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. 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#跨消费方求值边界与分桶身份).
|
|
148
154
|
|
|
149
|
-
### Server-side local Funnel evaluation
|
|
155
|
+
### Server-side local Funnel evaluation
|
|
150
156
|
|
|
151
157
|
For a Local Funnel containing only Entry, Condition, Feature, Split and literal/Feature End or Output nodes, use the explicit local evaluator. Reuse the client/evaluator across requests; create a session for one verified identity and attribute/parameter snapshot:
|
|
152
158
|
|
|
@@ -231,7 +237,7 @@ See the [SDK release ledger](https://github.com/tinkerlandai/Indiana/blob/main/d
|
|
|
231
237
|
|
|
232
238
|
## Shared public configuration (Indiana-test candidate)
|
|
233
239
|
|
|
234
|
-
Use one manager per trusted origin and exact App/environment for Features, canonical Funnel files and enabled page experiments. This source addition is opt-in and requires the matching Indiana-test gateway plus an explicitly reviewed publication. It is
|
|
240
|
+
Use one manager per trusted origin and exact App/environment for Features, canonical Funnel files and enabled page experiments. This source addition is opt-in and requires the matching Indiana-test gateway plus an explicitly reviewed publication. It is included in published packages since 0.6.0.
|
|
235
241
|
|
|
236
242
|
```ts
|
|
237
243
|
import {
|
|
@@ -308,7 +314,7 @@ Screens, live Customer/Coupon data, shown acknowledgements, Paywall and external
|
|
|
308
314
|
|
|
309
315
|
Old host checkpoints must be reconciled or drained with their original business identities before switching clients. Do not turn an old execution into a fresh start/request ID. The SDK does not import old checkpoints. On existing test targets the retirement candidate moves the original observation relation into a private read-only archive, preserves every row and continues refusing scoped legacy execution IDs; already accepted managed Runs retain exact replay. It accepts no new observations and creates no new business model. The production packet adds no observation or archive table. A mode change does not rewrite a Run's original policy or accepted commands. New results against a stale policy fail closed; close/reconcile that original Run before starting another intent.
|
|
310
316
|
|
|
311
|
-
The native renderer shell uses the same pure JavaScript calculation adapter and native Run-command bridge; credentials remain in the native session. A headless Swift/Kotlin session exposes the pending calculation and does not silently calculate it remotely. Wire schemas and the renderer shell are generated together. Installing the package does not migrate a database or deploy a runtime. Browser, provider, capacity and native-store acceptance remain separate. See the
|
|
317
|
+
The native renderer shell uses the same pure JavaScript calculation adapter and native Run-command bridge; credentials remain in the native session. A headless Swift/Kotlin session exposes the pending calculation and does not silently calculate it remotely. Wire schemas and the renderer shell are generated together. Installing the package does not migrate a database or deploy a runtime. Browser, provider, capacity and native-store acceptance remain separate. See the unification receipt.
|
|
312
318
|
|
|
313
319
|
## Funnel-scoped resource requests
|
|
314
320
|
|
package/README.zh-CN.md
CHANGED
|
@@ -10,12 +10,14 @@ Local / Remote 只区分纯条件、Feature / 实验和 Feature 选择在哪里
|
|
|
10
10
|
|
|
11
11
|
条件结果尚未提交时,Run 停车并释放 Worker,仍需 Local 宿主返回;条件结果已受理后,后台业务操作可以通过原来的 Queue / Cron 脱离宿主恢复。Local SDK 不再直接调用发券服务来推进图,也没有第二套宿主业务执行器、定时器和展示状态。独立 Coupon API 保留自己的自领政策、权限、资格、库存、幂等和原有效期,不要求创建 Funnel。
|
|
12
12
|
|
|
13
|
-
步骤记录共用后端限制;历史 `report_progress` 仍是调用方观察,不能当成发券证明。原生渲染壳复用同一个 JS 纯求值器及原生 Run bridge;无界面 Swift/Kotlin 会明确返回待本地求值,不自动切换 Remote。详细使用和迁移边界见[英文说明](README.md#local-funnel-execution)
|
|
13
|
+
步骤记录共用后端限制;历史 `report_progress` 仍是调用方观察,不能当成发券证明。原生渲染壳复用同一个 JS 纯求值器及原生 Run bridge;无界面 Swift/Kotlin 会明确返回待本地求值,不自动切换 Remote。详细使用和迁移边界见[英文说明](README.md#local-funnel-execution)及统一回执。安装本包不会自动迁移数据库或部署服务;浏览器、支付渠道、容量和原生商店验收分别记录。
|
|
14
14
|
|
|
15
|
-
本包版本为 **0.6.
|
|
15
|
+
本包版本为 **0.6.2/协议 0.6**,须配套同协议运行时和数据库。Remote Funnel 返回当前页面 JSON,与 Local 共用渲染器,完整 Remote 图和私有规则仍在服务端。公开 npm 0.6.0 已通过 `api.dev.tinker.cash` 的 21 项基础操作,foundation readiness 为 200;Funnel、公共配置、支付执行和生产业务仍有独立验收边界。实际发布、标签和环境状态见[SDK 发布总账](../../docs/sdk-releases.md)。
|
|
16
|
+
|
|
17
|
+
0.6.2 增加共享的确定性托管渲染 shell,并通过 GitHub Actions 与 npm Trusted Publishing 发布;继续包含 0.6.1 的当前 Screen 输入 patch、Local Feature 依赖校验、host 轮询时原命令结算和 Back 后展示确认恢复修复。完整生产浏览器与 Stripe 验收分别记录,见[修复报告](../../docs/deployment-receipts/20261022-sdk-funnel-repair/README.md)。
|
|
16
18
|
|
|
17
19
|
```sh
|
|
18
|
-
npm install --save-exact @tinkerlandai/indiana-sdk@0.6.
|
|
20
|
+
npm install --save-exact @tinkerlandai/indiana-sdk@0.6.2
|
|
19
21
|
```
|
|
20
22
|
|
|
21
23
|
## 版本兼容与支持
|
|
@@ -38,6 +40,10 @@ npm install --save-exact @tinkerlandai/indiana-sdk@0.6.0
|
|
|
38
40
|
|
|
39
41
|
JavaScript 与 TypeScript 共用本包,声明文件随包提供。内部 `@indiana/contracts` 在构建时内联,接入方无需安装私有包。Swift 和 Kotlin 使用各自的包管理生态,不在本次 npm 发布范围内。
|
|
40
42
|
|
|
43
|
+
独立的 [Python 服务端 SDK](../python/README.md) 使用同一当前 HTTP 协议,提供同步、异步 Customer、持仓/权益检查和用量上报。Python 源码、本地 wheel 与后续 PyPI 发布分别验证,不属于这个 npm 包。
|
|
44
|
+
|
|
45
|
+
[Go 服务端 SDK](../go/README.md) 提供同样的首版能力,使用类型化响应、Context 取消和 goroutine 并发复用客户端。源码作为模块放在当前仓库内,分发和发布与 npm 包分开处理。
|
|
46
|
+
|
|
41
47
|
## API 默认地址与自测
|
|
42
48
|
|
|
43
49
|
默认地址、四个域名、版本标签和测试配置的持续规范见 [SDK API 入口与开发测试规范](../../docs/sdk-endpoints-and-testing.md)。
|
|
@@ -50,7 +56,7 @@ JavaScript 与 TypeScript 共用本包,声明文件随包提供。内部 `@ind
|
|
|
50
56
|
|
|
51
57
|
测试 API 地址为 `https://api.dev.tinker.cash`,测试主站/Admin 使用 `dev.tinker.cash`。测试应用配置 `INDIANA_TEST_BASE_URL=https://api.dev.tinker.cash`,业务验收仍须等待测试服务就绪。默认地址保持生产 `https://api.tinker.cash`,由测试应用显式覆盖。
|
|
52
58
|
|
|
53
|
-
离线测试注入 `fetch`,验证默认地址、覆盖、renderer 地址和网络失败不换服务;集成测试用固定本地 tarball 连接明确选定、协议匹配的测试 runtime,记录包哈希、服务版本和 requestId
|
|
59
|
+
离线测试注入 `fetch`,验证默认地址、覆盖、renderer 地址和网络失败不换服务;集成测试用固定本地 tarball 连接明确选定、协议匹配的测试 runtime,记录包哈希、服务版本和 requestId。公开 0.6.0 的原生 GCP 测试已覆盖 21 项基础能力、原请求重放与权限拒绝;完整能力、浏览器和生产另行验收,不自动切回 JS。当前旧 dev Admin 仍有原数据库绑定,不能将其生成的 Key 当作 Go 原生测试 Key。具体命令见[维护者测试流程](../../docs/sdk-selfserve.md#maintainer-api-origin-testing)。
|
|
54
60
|
|
|
55
61
|
## 从可信后端创建 Customer Session
|
|
56
62
|
|
|
@@ -91,28 +97,27 @@ Indiana 在普通 SDK 请求中自动延续同一 Customer 会话和 Token,默
|
|
|
91
97
|
|
|
92
98
|
Customer 使用原始业务字段;资料更新是部分 patch,没有 Customer revision。Guest 登录到已有 Customer 时返回 `switched: true`,资源和历史保留原归属,接入方应为目标 Customer 创建新 Session/Funnel;不合并旧 Guest 的财务事实。
|
|
93
99
|
|
|
94
|
-
##
|
|
100
|
+
## 可选的稳定 fingerprint
|
|
95
101
|
|
|
96
|
-
`fingerprint`
|
|
102
|
+
`fingerprint` 是宿主提供的稳定去重信号,例如安装标识。首次 Guest/Customer 请求之前初始化并保留它,独立于登录和凭据;Guest 识别、账号切换和会话续期共用同一信号。SDK 不采集或生成它。
|
|
97
103
|
|
|
98
104
|
```ts
|
|
99
|
-
//
|
|
100
|
-
// verifiedUser.id
|
|
105
|
+
// 可信后端:installationSignal 由宿主独立保留;
|
|
106
|
+
// verifiedUser.id 来自宿主已验证的登录会话。
|
|
101
107
|
const { customer } = await indiana.getOrCreateCustomer({
|
|
102
108
|
externalUserId: verifiedUser.id,
|
|
103
109
|
fingerprint: installationSignal,
|
|
104
110
|
});
|
|
105
|
-
//
|
|
106
|
-
// retain/reuse guestToken for creation retries.
|
|
111
|
+
// Guest 创建使用同一安装信号;创建重试另行保留并复用 guestToken。
|
|
107
112
|
await indiana.createGuestCustomer({
|
|
108
113
|
guestToken: retainedGuestToken,
|
|
109
114
|
fingerprint: installationSignal,
|
|
110
115
|
});
|
|
111
116
|
```
|
|
112
117
|
|
|
113
|
-
Indiana
|
|
118
|
+
Indiana 将首次提供的信号保存为环境内的哈希,后续值不替换它。可以省略输入,保留按 Customer 去重 Trial 的行为;`unique_fingerprint` 进一步在共享信号的 Customer 之间去重所配置的 Product Trial。业务用户 ID 不是安装标识;Customer/Guest/会话 Token 和请求 ID 各有自己的生命周期,不应充当 fingerprint。
|
|
114
119
|
|
|
115
|
-
|
|
120
|
+
Web 宿主可以用独立的第一方安装 cookie 保留信号。清除 cookie 或更换浏览器存储可能产生新值;退出登录无需重置它。原生宿主持久保存随机安装信号,并定义重装、恢复和重置行为。该信号独立于设备证明和身份认证。客户端只收到通用的 Trial 冲突信息;保留 `X-Request-Id` 供服务端排查。
|
|
116
121
|
|
|
117
122
|
## Funnel、Feature 与独立 Paywall
|
|
118
123
|
|
|
@@ -120,7 +125,7 @@ On Web, an independent first-party installation cookie can retain the signal. Cl
|
|
|
120
125
|
|
|
121
126
|
`createFunnelClient({ customerToken, ...options })` 用于已持有 Customer 凭据的客户端;其 `start()` 不指定 `customer` 或 `customerData`,始终以凭据所属 Customer 运行。响应丢失时保留原编号和输入重试,商业参数放在 `parameters.commerce`。运行有独立的 Run Token,不能据此切换 Customer。
|
|
122
127
|
|
|
123
|
-
`createFunnelDecisionClient` 的 `submit/decide` 与 `/server` 的 `createFunnelCampaignClient` 同样使用明确的 `customer` 引用。Campaign
|
|
128
|
+
`createFunnelDecisionClient` 的 `submit/decide` 与 `/server` 的 `createFunnelCampaignClient` 同样使用明确的 `customer` 引用。Campaign `decide()` 等待返回 `FunnelDecision`;查询可能返回原已接受的决策及其原 request ID。Campaign `start()` 返回 Run 凭据,或在频率/进行中 Run 阻止新启动时返回 `{ suppressed: true, reason, retryAt }`,不伪造 Run 凭据。Run 实际展示后才提交 `shown`,不能用页面关闭或本地存储代替持久的展示事实。
|
|
124
129
|
|
|
125
130
|
浏览器使用 `createFunnelRunController` 与 `showFunnelRun`。控制器负责当前协议的命令、读取、重试、恢复和订阅;展示句柄提供 `refresh()` 和 `destroy()`。业务操作按当前发布节点委派给服务端,客户端声明或重定向不构成付款证明。
|
|
126
131
|
|
|
@@ -134,7 +139,7 @@ Customer 求值中的 `id` 是 Indiana Customer UUID(`customer.id`),`exter
|
|
|
134
139
|
|
|
135
140
|
`setAttributes()` 替换整个对象,每次更新都保留分桶字段。匿名页面/视觉实验默认的 `id` 和 `deviceId` 来自共用的第一方设备 cookie,不自动与账号实验同组。各适配器的 Sticky 能力有区别:共用 Run 的 Local 指令读取服务端状态,纯本地工具的持久 Sticky 使用已有宿主适配器,不新增共享状态。完整要求见[架构边界](../../docs/growthbook-sdk-delivery.md#跨消费方求值边界与分桶身份)。
|
|
136
141
|
|
|
137
|
-
### 服务端 SDK 本地 Funnel
|
|
142
|
+
### 服务端 SDK 本地 Funnel 求值
|
|
138
143
|
|
|
139
144
|
纯 Local Funnel 支持 Entry、Condition、Feature、Split,以及普通值或 Feature 值的 End/Output。复用 client/evaluator,每个可信身份及属性、参数快照创建独立计算会话:
|
|
140
145
|
|
|
@@ -219,13 +224,13 @@ npm 发布不部署 Web 服务、不应用数据库迁移,也不发布 Swift
|
|
|
219
224
|
|
|
220
225
|
源码新增 `createConfigurationSync({ origin, scope })`;`scope` 必须明确包含 `projectId`、`environment` 和 `environmentId`。将同一个实例作为 `configuration` 传给 `createIndiana`、Funnel start/Run controller 和 `createPageExperiments`,共用清单、文件缓存、并发请求和更新通知。`/server` 导出的 `createSynchronizedFunnelLocalEvaluator(configuration, funnelId)` 使用同一份规范 Funnel 文件与 GB 代次进行纯判断,保留仅可信服务端执行的边界。
|
|
221
226
|
|
|
222
|
-
此能力需要匹配的 Indiana-test
|
|
227
|
+
此能力需要匹配的 Indiana-test 网关及已审核发布的配置,自 npm 0.6.0 起包含在公开包中。公共文件不需要 Customer 凭据;业务操作沿用现有凭据和服务端资格检查。完整调用示例见[英文说明](README.md#shared-public-configuration-indiana-test-candidate)。
|
|
223
228
|
|
|
224
229
|
初始化总等待不超过 5 秒;活跃消费者共用 12–15 秒轮询,并在回前台/联网后刷新。Local 控制状态自源站验证起最多有效 60 秒,旧 304 或失败不能续期。暂停/过期后停止新本地判断及客户屏幕;冷启动离线时,仅凭持久缓存不能恢复 active 权限。Indiana Run 的命令与观察直接读取服务端状态,独立于 CDN 控制有效期。
|
|
225
230
|
|
|
226
231
|
内存缓存上限 128 项/32 MiB,浏览器默认 localStorage 的公共文件缓存上限 128 项/2 MiB/7 天。可设置 `storage: null` 或提供 `ConfigurationStorage`;额度不足时退回内存。单文件上限 1 MiB,清单上限 512 KiB,使用前校验作用域、schema 和哈希。共享缓存不存凭据、用户属性、Sticky 或已接受的决策。共享实例由宿主统一 `destroy()`,单个消费者退出不会销毁其他消费者的同步能力。
|
|
227
232
|
|
|
228
|
-
## 共享 Funnel UI
|
|
233
|
+
## 共享 Funnel UI 宿主
|
|
229
234
|
|
|
230
235
|
`showFunnelRun(container, { client: started.controller })` 在 Local / Remote 都接收同一个服务器 Run controller。屏幕、Customer / Product / Coupon 数据、shown 回执、Paywall、外部任务和未知结果重试共用后端路径。宿主销毁只卸载 UI;停止一个 Run 需要显式提交 Close。Console 私有预览仍是无真实业务效果的模拟。
|
|
231
236
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e}from"./chunk-5TEZEOHX.js";import{a as j}from"./chunk-S5TVMQRC.js";import{kb as T,lb as P,ob as S}from"./chunk-
|
|
1
|
+
import{a as e}from"./chunk-5TEZEOHX.js";import{a as j}from"./chunk-S5TVMQRC.js";import{kb as T,lb as P,ob as S}from"./chunk-VMLGV5OS.js";import{D as _,G as C,J as k,v as O}from"./chunk-RMJJOSVZ.js";import{b as E}from"./chunk-OHDY27EI.js";var L={name:"@tinkerlandai/indiana-sdk",version:"0.6.2",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.5"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var X=Symbol("IndianaNoContent");function Q(a,V){let v=a.webView??"hosted";if(!["hosted","embedded"].includes(v))throw new e("INVALID_REQUEST","Invalid Web View mode");let d=a.scope?E.parse(a.scope):void 0,s=new URL(a.baseUrl??j);if(s.username||s.password||s.search||s.hash)throw new e("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(s.protocol!=="https:"&&!(s.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(s.hostname)))throw new e("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let U=a.fetch??globalThis.fetch.bind(globalThis),u=a.timeoutMs??1e4;if(!Number.isFinite(u)||u<=0||u>12e4)throw new e("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let p=null,g,c=0,l=null,f=new Set;function R(){c+=1,p=null,l=null;for(let i of f)i.abort();f.clear()}async function M(i,H={},N="POST",q={}){if(!p)throw new e("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let I=c,n=new AbortController;f.add(n);let m=()=>I!==c?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new e("TIMEOUT","Indiana request timed out"),y,K=new Promise((t,o)=>{y=()=>o(m()),n.signal.addEventListener("abort",y,{once:!0})}),x=setTimeout(()=>n.abort(),u),F=async()=>{let t=await U(`${s.href.replace(/\/$/,"")}/api/v1/${i}`,{method:N,headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`,[T]:S.current,[P]:L.version,...d?{"X-Indiana-Project":d.projectId,"X-Indiana-Environment":d.environment}:{}},body:N==="POST"?JSON.stringify(H):void 0,signal:n.signal,credentials:"omit",cache:"no-store",redirect:"error",...q.keepalive?{keepalive:!0}:{}});if(n.signal.aborted)throw m();let o;try{o=t.status===204?X:await t.json()}catch{throw n.signal.aborted?m():new e(t.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",t.status,t.headers.get("X-Request-Id")??void 0)}if(n.signal.aborted)throw m();if(I!==c)throw new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!t.ok){let r=C.safeParse(o),w=r.success&&(!O.safeParse(r.data.error.code).success||_(r.data.error.code,t.status)),A=w?r.data.error.code:"HTTP_ERROR",D=k(A,t.status,{retryAfter:t.headers.get("Retry-After"),recovery:w?r.data.error.recovery:void 0,reason:w?r.data.error.reason:void 0});throw new e(A,w?r.data.error.message:"Indiana request failed",t.status,t.headers.get("X-Request-Id")??(r.success?r.data.requestId:void 0),{...D,...r.success&&r.data.error.retryable===!1?{retryable:!1}:{},...D.retryAfterSeconds===void 0&&r.success&&r.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:r.data.error.retryAfterSeconds}:{}})}if(t.headers.get(T)!==S.current)throw new e("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(d&&o&&typeof o=="object"&&"scope"in o){let r=E.safeParse(o.scope);if(!r.success||r.data.projectId!==d.projectId||r.data.environment!==d.environment)throw new e("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let b=t.headers.get("X-Indiana-Web-View");if(b){if(!/^\/web-view\/renderer\/[a-f0-9]{64}$/.test(b))throw new e("INVALID_RESPONSE","Invalid Web View renderer metadata");g=b}let h=t.headers.get("X-Indiana-Telemetry-Subject");if(h){if(!/^[a-f0-9]{64}$/.test(h))throw new e("INVALID_RESPONSE","Invalid telemetry identity");l!==h&&(l=h,V?.(l))}return o};try{return await Promise.race([F(),K])}catch(t){throw I!==c?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):t instanceof e?t:new e(n.signal.aborted?"TIMEOUT":"NETWORK_ERROR",n.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(x),n.signal.removeEventListener("abort",y),f.delete(n)}}return{subjectKey:()=>l,webViewUrl(){if(v!=="embedded"){if(!g)throw new e("INVALID_RESPONSE","The gateway did not provide a hosted Web View renderer");return new URL(g,s).href}},identify(i){if(!i.trim()||/\s/.test(i)||i.length>4096)throw new e("INVALID_TOKEN","A nonempty server-issued token is required");R(),p=i},reset:R,request:M}}export{Q as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as ge}from"./chunk-OK2Q6IJD.js";import{a as l}from"./chunk-5TEZEOHX.js";import{a as Ne}from"./chunk-S5TVMQRC.js";import{Bf as Ge,Ck as xe,Dk as k,Ei as Qe,Ek as Xe,Fk as en,Gd as Me,Gk as nn,Hi as be,Hk as tn,Ig as Be,Ii as Ye,Ik as rn,Kg as Je,Kk as De,Lg as ze,Ng as He,Pk as on,Qh as _e,Rh as Te,Tg as Ke,Vf as ce,ag as je,ak as Ze,ni as te,xf as Ue,xi as Ae,xk as H,yf as qe,yi as $e,yk as We}from"./chunk-HU2HIDVT.js";import{b as ke,h as me}from"./chunk-OHDY27EI.js";import{f as Ce,j as Se,l as Oe,m as he}from"./chunk-S2MSIA57.js";function An(e){let n=null,i=null,o=0,d=0,p=new Set,r=null,a=null,t=new Set,s=()=>{for(let h of t)try{h()}catch{}},g={attributes:he.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(h,F)=>{!p.has(h)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(h,structuredClone(F))}:void 0,onExperimentViewed:e.onExperimentViewed?(h,F)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(h),structuredClone(F)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?h=>e.saveStickyBucketAssignmentDoc(structuredClone(h)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function R(h,F=new Set){return p.has(h)?!r||!r.features[h]||["unknownFeature","cyclicPrerequisite"].includes(r.features[h].source):F.has(h)?!1:(F.add(h),(n?.features[h]?.rules??[]).some(E=>[...E.parentConditions??[],...(E.tracks??[]).flatMap(x=>x.experiment.parentConditions??[])].some(x=>R(x.id,F))))}let A=h=>{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 r?.expiresAt&&Date.parse(r.expiresAt)<=Date.now()&&(r=null,g.features=n.features),p.has(h)?!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now()?w():structuredClone(r.features[h]??w()):R(h)?w():structuredClone(Se(h,g))};async function c(){if(!n||!p.size)return;if(!e.evaluateRemote)throw new Error("Remote Feature evaluation requires a server loader");let h=d;if(a?.revision===h)return a.loading;let F=o,E=n,x=[...p],_=(async()=>{let D=Ge.parse(await e.evaluateRemote({attributes:structuredClone(g.attributes),features:x}));if(!(F!==o||h!==d||E!==n)){if(e.assertUsable?.(E.generation),D.generation!==E.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(x.some(M=>!Object.hasOwn(D.features,M))||Object.keys(D.features).some(M=>!p.has(M)))throw new Error("Invalid remote Feature results");r=structuredClone(D),g.features={...E.features,...Object.fromEntries(Object.entries(r.features).map(([M,j])=>[M,{defaultValue:j.value}]))},s()}})();a={revision:h,loading:_};try{await _}finally{a?.loading===_&&(a=null)}}function N(){c().catch(h=>{try{e.onError?.(h)}catch{}})}async function b(){if(i)return i;let h=o,F=(async()=>{let E=await e.load(),x="remoteFeatures"in E?Ue.parse(E):null,_=x??me.parse(E);if(_.scope.projectId!==e.scope.projectId||_.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(h!==o)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===_.generation){let{evaluatedAt:M,expiresAt:j,...oe}=n,{evaluatedAt:X,expiresAt:ee,...f}=_;if(k(oe)!==k(f))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=_.evaluatedAt,n.expiresAt=_.expiresAt,s(),(!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now())&&N(),structuredClone(n)}let D=new Set(x?.remoteFeatures??[]);if([...D].some(M=>Object.hasOwn(_.features,M)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in _&&!n.analyticsConfig.experimentViewsEnabled&&x?.analyticsConfig.experimentViewsEnabled&&g.trackedExperiments?.clear(),n=structuredClone(_),p=D,r=null,a=null,d++,g.features=n.features,g.savedGroups=Ce(n.savedGroups),g.trackedFeatureUsage={},s(),N(),structuredClone(n)})();i=F;try{return await F}finally{i===F&&(i=null)}}return{init:b,refresh:b,refreshRemote:c,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(h){return t.add(h),()=>{t.delete(h)}},setAttributes(h){g.attributes=he.parse(h),d++,r=null,a=null,g.features=n?.features??{},g.trackedFeatureUsage={},s(),N()},evalFeature:A,isOn(h){return A(h).on},isOff(h){return A(h).off},getFeatureValue(h,F){let E=A(h).value;return structuredClone(E===null?F:E)},reset(){o++,d++,i=null,a=null,n=null,r=null,p.clear(),g.features={},g.savedGroups={},g.stickyBucketAssignmentDocs={},g.attributes={},g.trackedFeatureUsage={},g.trackedExperiments?.clear(),s()}}}function an(e){let n=new Map(e.topology.nodes.map(d=>[d.id,d])),i=Ce(e.growth.savedGroups);function o(d,p){if(!Object.hasOwn(e.growth.features,d))throw new l("INVALID_RESPONSE","Required GB Feature is unavailable");return Se(d,p).value}return{nodes:n,savedGroups:i,features:e.growth.features,feature:o,evaluate(d,p){let r=n.get(d);if(!r)throw new l("NOT_FOUND","Funnel node is unavailable");let a,t;if(r.type==="condition"){let g=e.conditions[r.id];if(!g)throw new l("INVALID_RESPONSE","Local condition rules are unavailable");a=_e({id:r.id,name:r.id,type:"condition",cases:g.map(w=>({condition:w.condition,target:r.outputs[w.port]})),default:r.outputs.default},p,e.growth.experiments).port}else if(r.type==="feature"){if(!r.resources.featureKey)throw new l("INVALID_RESPONSE","Feature reference is unavailable");t=o(r.resources.featureKey,p),a="next"}else if(r.type==="split"){if(!(r.resources.experimentId?e.growth.experiments[r.resources.experimentId]:void 0))throw new l("INVALID_RESPONSE","Experiment reference is unavailable");let w=_e({id:r.id,name:r.id,type:"split",experimentId:r.resources.experimentId,routes:r.outputs,notParticipating:r.outputs.notParticipating},p,e.growth.experiments);t=w.value,a=w.port}else if(["offering","end","output"].includes(r.type)&&r.resources.featureKey)t=o(r.resources.featureKey,p),a=r.type==="offering"?"next":"value";else throw new l("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let s=r.outputs[a]??(a==="value"?r.id:void 0);if(!s)throw new l("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:d,port:a,target:s,...t===void 0?{}:{value:t}}}}}function sn(e,n,i){let o=Qe.parse(e);if(o.evaluationMode!=="local")throw new l("EVALUATION_MODE","Remote nodes are evaluated by Grow");if(o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())throw new l("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition");let d=an(o),r={attributes:he.parse(i.attributes??{}),saveStickyBucketAssignmentDoc:i.saveStickyBucketAssignmentDoc?a=>i.saveStickyBucketAssignmentDoc(structuredClone(a)):void 0,onFeatureUsage:i.onFeatureUsage?(a,t)=>i.onFeatureUsage(a,structuredClone(t)):void 0,onExperimentViewed:i.onExperimentViewed?(a,t)=>i.onExperimentViewed(structuredClone(a),structuredClone(t)):void 0,features:d.features,savedGroups:d.savedGroups,stickyBucketAssignmentDocs:structuredClone(i.stickyBucketAssignmentDocs)};return d.evaluate(n,r)}function un(e){let n,i,o=()=>new l("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),d=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,i=e.locks??globalThis.navigator?.locks,!n||!i||!globalThis.crypto?.subtle)throw o();let a=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??Ne).href,e.runToken])),t=new Uint8Array(await crypto.subtle.digest("SHA-256",a));return"indiana.funnel.commands.v1."+Array.from(t,s=>s.toString(16).padStart(2,"0")).join("")});d.catch(()=>{});async function p(a){try{let t=await d;return await i.request(t,{mode:"exclusive"},()=>a(t))}catch(t){throw t instanceof l?t:o()}}function r(a){let t=n.getItem(a);if(t===null)return{revision:0,entry:null};if(t.length>1048576)throw o();let s=JSON.parse(t);if(!s||typeof s!="object"||!("revision"in s)||!("entry"in s)||!Number.isSafeInteger(s.revision)||Number(s.revision)<0)throw o();return{revision:Number(s.revision),entry:s.entry}}return{read:()=>p(r),write:(a,t)=>p(s=>{if(r(s).revision!==a)return null;if(!Number.isSafeInteger(a+1))throw o();return n.setItem(s,JSON.stringify({revision:a+1,entry:t})),a+1})}}function kn(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ye(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,p)=>ye(d,n[p]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let i=Object.entries(e),o=Object.entries(n);return i.length===o.length&&i.every(([d,p])=>Object.hasOwn(n,d)&&ye(p,Reflect.get(n,d)))}function Fe(e,n,i){let o=[],d=[],p=[],r=sn(e,n,{attributes:i.attributes,stickyBucketAssignmentDocs:i.sticky,saveStickyBucketAssignmentDoc(a){let t=a.attributeName+"||"+a.attributeValue,s=o.findIndex(w=>w.next.attributeName===a.attributeName&&w.next.attributeValue===a.attributeValue),g={expected:i.sticky[t]??null,next:a};s<0?o.push(g):o[s]=g},onExperimentViewed(a,t){t.inExperiment&&t.hashUsed&&!t.passthrough&&d.push(Oe.parse({key:a.key,variationId:t.variationId,keyUsed:t.key,hashAttribute:t.hashAttribute,hashValue:t.hashValue}))},onFeatureUsage(a,t){p.push(Oe.parse({feature:a,value:t.value,source:t.source,...t.ruleId?{ruleId:t.ruleId}:{}}))}});return{port:r.port,...r.value===void 0?{}:{value:r.value},sticky:o,exposures:d,features:p}}async function ln(e,n){let i=n.instruction;if(i?.type!=="evaluate")throw new Error("Evaluation instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require the shared public configuration manager");let o=await e.funnel(n.source.id,n.source.versionId);if(!o.growth||o.control.evaluationMode!=="local"||o.control.evaluationRevision!==i.policyRevision)throw new l("EVALUATION_MODE","Refresh the original Funnel evaluation policy");let{analyticsConfig:d,remoteFeatures:p,...r}=o.growth,a=be({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:o.document,payload:me.parse(r)});if(e.scope.environmentId!==i.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let t=Fe(a,n.nodeId,i);return e.assertFunnel(n.source.id,void 0,n.source.versionId),{generation:o.manifest.generation,result:t}}async function cn(e,n){let i=n.instruction;if(i?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");let o=await e.funnel(n.source.id,n.source.versionId);if(!o.growth||o.control.evaluationMode!=="local"||o.control.evaluationRevision!==i.policyRevision)throw new l("EVALUATION_MODE","Refresh the original Funnel evaluation policy");if(e.scope.environmentId!==i.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let{analyticsConfig:d,remoteFeatures:p,...r}=o.growth,a=be({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:o.document,payload:me.parse(r)}),t=hn(a,o.document,{...n,...i});return e.assertFunnel(n.source.id,void 0,n.source.versionId),{...t,generation:o.manifest.generation,policyRevision:i.policyRevision}}function hn(e,n,i){let o=i,d=new Map(n.graph.nodes.map(A=>[A.id,A])),p=structuredClone(i.variables),r=structuredClone(o.sticky),a=[],t=e.evaluationMode==="local"&&on(e.growth),s=i.nodeId,g=i.visit,w=!1;for(let A=0;A<rn;A++){let c=d.get(s);if(!c||!De(c))break;if(g>=n.execution.maxTransitions)throw new l("TRANSITION_LIMIT","Local Funnel transition budget exceeded");let N={attributes:c.type==="condition"?He({declarations:n.variables,attributes:o.attributes,parameters:i.parameters,answers:i.answers,results:p,savedGroups:{}}):{...o.attributes,parameters:i.parameters,answers:i.answers,results:p},sticky:r},b,h;if(["condition","feature","split"].includes(c.type)||c.type==="offering"&&c.configuration.source==="feature")b=Fe(e,c.id,N),c.type==="offering"&&(b.value={type:"offering_version",id:String(b.value)}),c.type==="condition"?h=b.port==="default"?c.default:c.cases[Number(b.port.slice(5))]?.target:c.type==="split"?h=b.port==="notParticipating"?c.notParticipating:c.routes[b.port]:(c.type==="feature"||c.type==="offering")&&(h=c.next);else if(b={port:"next",sticky:[],exposures:[],features:[]},(c.type==="entry"||c.type==="coupon"||c.type==="coupons")&&(h=c.next),c.type==="offering"&&c.configuration.source==="fixed"&&(b.value={type:"offering_version",id:c.configuration.versionId},h=c.next),c.type==="end"||c.type==="output"){let E=c.type==="end"?c.output:c.value;if(b=E?.type==="feature"?Fe(e,c.id,N):{...b,port:"value",value:E?.type==="literal"?E.value:E?.type==="variable"?Ke({source:"variable",key:E.key,...E.path?{path:E.path}:{}},{declarations:n.variables,answers:i.answers,results:p,parameters:i.parameters,attributes:o.attributes,savedGroups:{}}):null},E&&(b.value===void 0||!Be(n.outputSchema,b.value)))throw new l("INVALID_RESPONSE","Local terminal violates its declared output")}let F=[...a,{nodeId:s,result:b}];if(je({steps:F})>6e4){if(!a.length)throw new l("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:s,result:b}),c.type==="feature"||c.type==="offering"||c.type==="coupon"||c.type==="coupons"){let E=c.type==="coupons"?c.couponIds.map(_=>({type:"reward",id:_})):c.type==="coupon"?{type:"reward",id:c.couponId}:b.value;if(E===void 0)throw new l("INVALID_RESPONSE","Node output is missing");let x=Je(c,{value:E});ze(n.variables,c,x),Object.assign(p,x)}for(let E of b.sticky)r[`${E.next.attributeName}||${E.next.attributeValue}`]=structuredClone(E.next);if(c.type==="end"||c.type==="output"){w=!0;break}if(!h)throw new l("INVALID_RESPONSE","Local pure exit is unavailable");if(s=h,g++,t&&["feature","offering","coupon","coupons"].includes(c.type))break}let R=d.get(s);return{steps:a,...!w&&R&&!De(R)?{boundary:{nodeId:s,visit:g}}:{}}}import{z as Q}from"zod";var dn=te.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 l("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),fn=Q.strictObject({schemaVersion:Q.literal(1),scope:ke,runId:Q.uuid(),funnelId:Q.uuid(),versionId:Q.uuid(),command:dn.optional(),closeCommand:dn.refine(e=>e.operation==="close").optional(),purchase:Q.strictObject({receiptId:Q.uuid(),operationId:Q.uuid(),generation:Q.number().int().nonnegative()}).optional(),closed:Q.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"),B=()=>new l("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Pe=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function pn(e){let n=0,i=null,o=t=>JSON.stringify([t.scope,t.runId,t.funnelId,t.versionId]),d=Promise.resolve();async function p(){let t=await e.read();if(!Number.isSafeInteger(t.revision)||t.revision<0)throw new l("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:t.revision,entry:t.entry===null?null:fn.parse(t.entry)}}function r(t){let s=d.then(t);return d=s.catch(()=>{}),s}async function a(t){for(let s=0;s<4;s++){let g=await p();if(g.entry&&i!==null&&o(g.entry)!==i)throw B();let w=t(g.entry,g.revision);if(Pe(g.entry,w)){n=g.revision;return}let R=await e.write(g.revision,w);if(R!==null){if(!Number.isSafeInteger(R)||R<=g.revision)throw B();n=R;return}}throw B()}return{bind(t){let s=JSON.stringify([t.scope,t.runId,t.funnelId,t.versionId]);if(i!==null&&i!==s)throw B();i=s},async load(){let t=await p();return n=t.revision,i=t.entry?o(t.entry):null,t.entry},retain(t){let s=fn.parse(t),g=s.command;return!g||i!==null&&o(s)!==i?Promise.reject(B()):(i??=o(s),r(()=>a((w,R)=>{if(w&&!Pe(o(w),o(s)))throw B();if(!w){if(R!==n&&g.operation!=="close")throw B();return s}if(!w.command)return{...w,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&w.command.operation!=="close"){if(w.command.requestId===g.requestId||w.closeCommand&&!Pe(w.closeCommand,g))throw B();return{...w,closeCommand:g,closed:!0}}if(!Pe(w.command,g))throw B();return w})))},observePurchase(t,s,g){return r(()=>a((w,R)=>{if(!w&&R!==n||w&&o(w)!==o({...t,schemaVersion:1}))throw B();if(w?.purchase&&w.purchase.generation>s.generation)return w;if(w?.purchase&&w.purchase.generation===s.generation&&w.purchase.operationId!==s.operationId)throw B();return g?!w?.purchase||w.purchase.operationId!==s.operationId?w:w.command?{...w,purchase:void 0}:null:{schemaVersion:1,...t,...w,purchase:s}}))},settle(t){return r(()=>a(s=>s?s.command&&"requestId"in s.command&&s.command.requestId===t?s.closeCommand?{...s,command:s.closeCommand,closeCommand:void 0}:s.purchase?{...s,command:void 0}:null:s.closeCommand&&"requestId"in s.closeCommand&&s.closeCommand.requestId===t?{...s,closeCommand:void 0}:s:null))}}}function de(e){let{customerToken:n,...i}=e;return i}var vn=e=>!(e instanceof l)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function mn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new l("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.serverKey)))throw new l("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");let n=ge({...e,...e.serverKey?{fetch:(f,m)=>{let P=new Headers(m?.headers);return P.set($e,e.serverKey),(e.fetch??globalThis.fetch)(f,{...m,headers:P})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let i,o=null,d=0,p=0,r=null,a=null,t=!1,s=null,g=!1,w=null,R=new Set,A=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?un(e):void 0),c=A&&pn(A),N,b=null,h=!1,F=c?c.load().then(f=>{if(h)throw new l("IDENTITY_CHANGED","Controller was reset during command restoration");if(b=f,!f)return;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Pending command belongs to another scope");if(N=f.purchase,t=f.closed===!0,!f.command)return;let m=te.parse(f.command);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");r=m,f.closeCommand&&(a=f.closeCommand,t=!0),m.operation==="close"&&(t=!0),g=!0}):Promise.resolve();F.catch(()=>{});async function E(f,m,P){c&&await F;let U=d,Y=o,u=Ae.parse(await n.request("funnels",te.parse(f)));if(f.operation==="review"&&!u.review)throw new l("INVALID_RESPONSE","Historical projection is missing");if(U!==d)throw new l("IDENTITY_CHANGED","Run identity changed during the request");if(u.runToken&&u.runToken!==e.runToken)throw new l("INVALID_RESPONSE","Run credential changed");let J=f.operation==="get"?f.settlementRequestId:"requestId"in f&&f.operation!=="start"?f.requestId:void 0;if(J&&u.settlement?.requestId!==J)throw new l("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");if(b&&(u.run.id!==b.runId||u.run.source.id!==b.funnelId||u.run.source.versionId!==b.versionId))throw new l("SCOPE_MISMATCH","Stored command belongs to another Run or Version");if(o&&(u.run.id!==o.id||u.run.source.type!==o.source.type||u.run.source.id!==o.source.id||u.run.source.versionId!==o.source.versionId||u.run.locale!==o.locale||!ye(u.run.parameters,o.parameters)))throw new l("INVALID_RESPONSE","Run version changed");if(e.funnelId&&u.run.source.id!==e.funnelId)throw new l("INVALID_RESPONSE","Run belongs to another Funnel");c?.bind({scope:u.scope,runId:u.run.id,funnelId:u.run.source.id,versionId:u.run.source.versionId}),A&&!e.scope&&(e.scope=u.scope);let K=u.run.paywall,z=K??u.purchase,fe=z?.operation,pe=u.settlement&&(!K||K.purchaseRequestId===u.settlement.requestId)&&(!N||N.operationId===u.settlement.operationId)?u.settlement:void 0,ie=fe?.operationId??z?.quote?.operationId??pe?.operationId,ae=z?.receiptId??pe?.receiptId,we=K?.selectionGeneration??N?.generation??0;if(c&&ie&&ae&&f.operation!=="review"&&(!o||u.run.revision>=o.revision)&&(P===void 0||P>=p)&&(!N||we>=N.generation)){let $={receiptId:ae,operationId:ie,generation:we},Ee=fe?.status==="complete"||z?.canReselect===!0;await c.observePurchase({scope:u.scope,runId:u.run.id,funnelId:u.run.source.id,versionId:u.run.source.versionId},$,Ee),Ee?N?.operationId===$.operationId&&(N=void 0):N=$}if(!u.run.stopped&&["running","waiting"].includes(u.run.status)&&f.operation==="get"&&f.settlementRequestId)return u;let se=m?.(u),Ie=typeof se=="boolean"?se:se?await se:!1;if(["running","waiting"].includes(u.run.status)||(t=!0),f.operation==="review"&&o&&o!==Y&&u.run.revision<=o.revision||o&&u.run.revision===o.revision&&P!==void 0&&P<p||(f.operation==="review"&&!u.run.stopped&&["running","waiting"].includes(u.run.status)&&o&&u.run.nodeId===o.nodeId&&u.run.visit===o.visit&&u.run.revision===o.revision&&(u.run.screen=o.screen,(o.paywall?.quote?.operationId===u.review?.activeOperationId||!o.paywall?.quote&&u.review?.activeOperationId===null)&&(u.run.paywall=o.paywall)),o?.paywall&&u.run.paywall&&o.paywall.receiptId===u.run.paywall.receiptId&&(u.run.paywall.selectionGeneration??0)<(o.paywall.selectionGeneration??0)))return u;if(!o||u.run.revision>=o.revision)o=u.run;else if(!Ie)return u;if(o)for(let $ of R)try{$(structuredClone(o))}catch{}return u}async function x(f=r){if(c&&await F,!f)throw new l("INVALID_REQUEST","No command is pending");let m=f,P=d;if(c){if(!o||!e.scope)throw new l("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await c.retain({schemaVersion:1,scope:e.scope,runId:o.id,funnelId:o.source.id,versionId:o.source.versionId,command:de(m)})}if(P!==d||r!==m&&a!==m)throw new l("IDENTITY_CHANGED","Run changed before command dispatch");let U={...m,...i?{customerToken:i}:{}},Y=g;g=!0;try{return await E(U,u=>{if(!u.settlement)throw new l("INVALID_RESPONSE","Exact command settlement is missing");if(u.settlement.requestId!==m.requestId)throw new l("INVALID_RESPONSE","Command settlement identity changed");if(P===d&&(r===m||a===m)&&u.run.pendingRequest?.requestId!==m.requestId&&u.settlement.state==="settled"&&(!t||m.operation==="close"||u.settlement?.state==="settled"&&!["running","waiting"].includes(u.run.status))){let J=()=>P!==d||r!==m&&a!==m?!1:(r===m&&(r=null),a===m&&(a=null),g=r!==null,b=null,!0);return c?c.settle(m.requestId).then(J):J()}return!1})}catch(u){throw P===d&&r===m&&!Y&&!vn(u)&&(c&&await c.settle(m.requestId),P===d&&r===m&&(r=null,g=!1,b=null)),u}}function _(f){let m=te.parse(f);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new l("INVALID_REQUEST","Mutation required");if(o?.recoveryRestricted&&m.operation!=="close"&&m.operation!=="resume"&&r?.requestId!==m.requestId)throw new l("PRECONDITION_FAILED","Original Run requires restricted recovery");if(t&&m.operation!=="close"){if(r?.requestId===m.requestId)return ee.settle(m.requestId);throw new l("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"&&r?.operation!=="close"){if(t=!0,a&&JSON.stringify(de(a))!==JSON.stringify(de(m)))throw new l("COMMAND_PENDING","Retry the original Close");if(a??=m,s)return s;let U=x(a);return s=U,U.then(()=>{s===U&&(s=null)},()=>{s===U&&(s=null)}),U}if(r){if(JSON.stringify(de(r))!==JSON.stringify(de(m)))throw new l("COMMAND_PENDING","Retry the original command before sending another");if(w)return w}else r=m,g=!1;let P=x();return w=P,P.then(()=>{w===P&&(w=null)},()=>{w===P&&(w=null)}),P}let D=null,M=new WeakMap;function j(f){let m=M.get(f);if(m)return m;let P=X(f);return M.set(f,P),P}let oe=!1;async function X(f){let m=await f;if(m.run.recoveryRestricted||!["evaluate","evaluate_segment"].includes(m.run.instruction?.type??""))return m;if(D)return D;oe=!0;let P=d,U=(async()=>{for(let Y=0;Y<32&&["evaluate","evaluate_segment"].includes(m.run.instruction?.type??"");Y++){if(r||t)return m;let u=m.run,J=m.run.instruction;if(J?.type==="evaluate_segment"){let z=await cn(e.configuration,u);if(P!==d)throw new l("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r||t)return m;if(o&&(o.revision!==u.revision||o.visit!==u.visit||o.nodeId!==u.nodeId))return E({operation:"get",...i?{customerToken:i}:{}});m=await _({operation:"commit_segment",requestId:Te(u.id,u.visit,`segment:${u.revision}`),nodeId:u.nodeId,visit:u.visit,revision:u.revision,...z});continue}if(J?.type!=="evaluate")return m;let K=await ln(e.configuration,u);if(P!==d)throw new l("IDENTITY_CHANGED","Run identity changed during evaluation");if(r||t)return m;if(o&&(o.revision!==u.revision||o.visit!==u.visit||o.nodeId!==u.nodeId))return E({operation:"get",...i?{customerToken:i}:{}});m=await _({operation:"evaluate",requestId:Te(u.id,u.visit,"evaluation"),nodeId:u.nodeId,visit:u.visit,revision:u.revision,receiptId:J.receiptId,policyRevision:J.policyRevision,...K})}return m})();D=U;try{return await U}finally{D===U&&(D=null)}}let ee={get configuration(){return oe?e.configuration:void 0},get configurationReady(){return!0},get view(){return o?structuredClone(o):null},get pendingCommand(){let f=a??r;return f?structuredClone(de(f)):null},get pendingCommands(){return[r,a].filter(f=>f!==null).map(f=>structuredClone(de(f)))},get pendingPurchase(){return N?structuredClone(N):null},async settle(f){let m=await E({operation:"get",settlementRequestId:f,...i?{customerToken:i}:{}});if(m.settlement?.requestId!==f)throw new l("INVALID_RESPONSE","Exact command settlement is missing");return m.settlement.state==="settled"&&(c&&await c.settle(f),r?.requestId===f&&(r=null,g=!1),a?.requestId===f&&(a=null)),m},get webViewUrl(){return n.webViewUrl()},review(f){return E({operation:"review",...f?{receiptId:f}:{},...i?{customerToken:i}:{}},void 0,++p)},async get(f,m){c&&await F,m??=N&&{receiptId:N.receiptId,operationId:N.operationId};let P=++p;return j(E({operation:"get",...f?{data:f}:{},...m?{purchase:m}:{},...i?{customerToken:i}:{}},void 0,P))},resume(f=o?.pendingRequest?.requestId){return f?t?ee.settle(f):r?.requestId===f?j(_(r)):j(_({operation:"resume",requestId:f})):Promise.reject(new l("INVALID_REQUEST","No interrupted command is available"))},submit(f){return j(_(f))},retry(){return s||(a?x(a):t&&r?ee.settle(r.requestId):w?j(w):r?j(_(r)):Promise.reject(new l("INVALID_REQUEST","No command is pending")))},identify(f){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(f))throw new l("INVALID_TOKEN","Customer credential required");d++,i=f,n.identify(e.runToken)},subscribe(f){return R.add(f),()=>R.delete(f)},reset(){h=!0,d++,i=void 0,o=null,r=null,a=null,s=null,g=!1,w=null,n.reset(),R.clear()}};return ee}async function ut(e,n){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(n.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");let i=ge(e);i.identify(n.customerToken);let o=ce.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}:{}}),d=null,p=null,r=null,a=null,t=null;async function s(){let R=ce.resolvePaywall,A=R.response.parse(await i.request(R.path,R.request.parse({...o,selector:d?{type:"version",versionId:d.id}:o.selector})));if(n.paywallVersionId?A.paywall.id!==n.paywallVersionId:A.paywall.paywallId!==n.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(d&&(A.paywall.id!==d.id||A.paywall.paywallId!==d.paywallId||A.paywall.offering.id!==d.offering.id))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return d=A.paywall,structuredClone(d)}async function g(R){if(!p)throw new l("INVALID_REQUEST","A quoted purchase is required");let A=R==="read"?ce.readSubscriptionOperation:ce.attach,c=A.response.parse(await i.request(A.path,A.request.parse({operationId:p.operationId,...R==="read"?{}:{intent:R}})));if(c.operation.operationId!==p.operationId||c.operation.currency!==o.commerce.currency)throw new l("INVALID_RESPONSE","The purchase operation changed");return r?.status==="complete"&&c.operation.status!=="complete"||r&&r.status!=="pending"&&c.operation.status==="pending"||(r=c.operation),structuredClone(r)}let w={get view(){return d?structuredClone(d):null},get quote(){return p?structuredClone(p):null},get operation(){return r?structuredClone(r):null},get webViewUrl(){return i.webViewUrl()},refresh:s,async preview(R){if(!d)throw new l("INVALID_REQUEST","Load the Paywall first");let A=d.document.buttons[R.actionId];if(A?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let c=Me(A.product,R.selection,d.capabilities);if(!c)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let N=ce.previewAttach.request.parse({funnelId:o.funnelId,funnelVersionId:o.funnelVersionId,requestId:R.requestId,plans:[{productVersionId:c}],provider:o.commerce.provider,currency:o.commerce.currency,...R.offerId?{offerId:R.offerId}:{},...R.nativeOffer?{nativeOffer:R.nativeOffer}:{}}),b=JSON.stringify(N);if(a&&a!==b&&(!r||r.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(a===b){if(t)return t;if(p)return structuredClone(p)}a=b;let h=(async()=>{let F=ce.previewAttach,E=F.response.parse(await i.request(F.path,N));if(E.quote.currency!==o.commerce.currency||E.quote.provider!==o.commerce.provider||E.quote.lines.length!==1||E.quote.lines[0].productVersionId!==c)throw new l("INVALID_RESPONSE","The purchase quote changed its selected Product or presentment");return p=E.quote,r=null,structuredClone(p)})();t=h;try{return await h}finally{t===h&&(t=null)}},confirm:()=>g("confirm"),cancel:()=>g("cancel"),read:()=>g("read"),destroy(){i.reset(),d=null,p=null,r=null,a=null}};return await s(),w}import{z as Cn}from"zod";import{z as ve}from"zod";var En=ve.record(ve.string().regex(/^[a-f0-9]{64}$/),ve.strictObject({at:ve.number(),text:ve.string()})),gn=2*1048576;function Rn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function yn(e,n){let i=n===void 0?Rn():n,o=Promise.resolve();async function d(){try{let p=await i?.getItem(`${e}:artifacts`);if(p&&p.length<=gn)return En.parse(JSON.parse(p))}catch{}return{}}return{async readManifest(){try{return await i?.getItem(e)}catch{return}},writeManifest(p){Promise.resolve().then(()=>i?.setItem(e,p)).catch(()=>{})},async readArtifact(p){let r=(await d())[p];return r&&Date.now()>=r.at&&Date.now()-r.at<=H.retentionMs?r.text:void 0},writeArtifact(p,r){i&&(o=o.catch(()=>{}).then(async()=>{let a=await d(),t=Date.now();a[p]={at:t,text:r};let s={},g=2,w=0;for(let[R,A]of Object.entries(a).sort(([,c],[,N])=>N.at-c.at)){if(A.at>t||t-A.at>H.retentionMs)continue;let c=new TextEncoder().encode(JSON.stringify({[R]:A})).byteLength;g+c>gn||w>=128||(s[R]=A,g+=c,w++)}await i.setItem(`${e}:artifacts`,JSON.stringify(s))}).catch(()=>{}))}}}var S=(e,n)=>new l(e,n),re=()=>performance.now(),wn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function It(e){let n=We.parse(e.scope),i=new URL(e.origin??Ne);if(i.username||i.password||i.search||i.hash||i.pathname!=="/"||i.protocol!=="https:"&&!(i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname)))throw S("INVALID_URL","Configuration requires a trusted HTTPS origin");let o=new Set([i.origin,...(e.assetOrigins??[]).map(I=>{let y=new URL(I);if(y.protocol!=="https:"||y.username||y.password||y.search||y.hash||y.pathname!=="/")throw S("INVALID_URL","Invalid configuration asset origin");return y.origin})]),d=e.fetch??globalThis.fetch.bind(globalThis),p=`/api/v1/configuration/${n.environmentId}`,r=`indiana:configuration:1:${i.origin}:${k(n)}`,a=yn(r,e.storage),t,s=0,g=0,w=!1,R=!1,A=0,c=0,N,b,h,F,E=0,x=new Set,_=new Set,D=new Map,M=new Map,j=0,oe=!1;function X(){for(let I of x)try{I()}catch{}}function ee(I){try{e.onError?.(I)}catch{}}let f=()=>!R&&!w&&!!t&&re()<s&&Date.now()<g;function m(){if(!f())throw S("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function P(I,y){let C=new TextEncoder().encode(y).byteLength;if(!D.has(I)){for(;D.size&&(D.size>=128||j+C>H.maxCacheBytes);){let v=D.entries().next().value;j-=new TextEncoder().encode(v[1]).byteLength,D.delete(v[0])}D.set(I,y),j+=C}}async function U(I,y,C){if(Number(I.headers.get("content-length"))>y)throw S("INVALID_RESPONSE","Configuration exceeds its byte limit");let v=I.body?.getReader();if(!v)throw S("INVALID_RESPONSE","Configuration body is missing");let O=[],V=0;try{for(;;){C.throwIfAborted();let L=await v.read();if(L.done)break;if(V+=L.value.length,V>y)throw S("INVALID_RESPONSE","Configuration exceeds its byte limit");O.push(L.value)}}finally{await v.cancel().catch(()=>{})}C.throwIfAborted();let T=new Uint8Array(V),G=0;for(let L of O)T.set(L,G),G+=L.length;return new TextDecoder("utf-8",{fatal:!0}).decode(T)}function Y(I){let y=new URL(I,i);if(!o.has(y.origin)||y.username||y.password||y.hash||y.search)throw S("INVALID_URL","Configuration artifact origin is not trusted");return y.href}async function u(I,y,C=!1){let v=await d(Y(I),{method:"GET",credentials:"omit",redirect:"error",cache:C?"default":"no-cache",signal:y,headers:{}});if(v.status===429){let O=v.headers.get("retry-after")??"";E=/^\d+$/.test(O)?Number(O)*1e3:Math.max(0,Date.parse(O)-Date.now())||15e3}if(!v.ok&&v.status!==304)throw S(`CONFIGURATION_HTTP_${v.status}`,"Configuration synchronization failed");return v}function J(I,y,C){let v=Date.parse(I.headers.get("x-indiana-config-validated-at")??""),O=Date.parse(I.headers.get("x-indiana-config-valid-until")??""),V=Date.parse(I.headers.get("date")??""),T=I.headers.get("age"),G=T!==null&&/^\d+(\.\d+)?$/.test(T)?Number(T)*1e3:NaN;if(![v,O,V,G].every(Number.isFinite)||O<=v||O-v>H.maxControlAgeMs||v>V+1e3)throw S("INVALID_RESPONSE","Configuration freshness evidence is invalid");let q=Math.min(O-v,C.maxControlAgeSeconds*1e3,H.maxControlAgeMs)-Math.max(G,V-v,0)-(re()-y);if(q<=0)throw S("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return re()+q}function K(){if(clearTimeout(h),clearTimeout(F),R||!x.size)return;f()&&(F=setTimeout(()=>{f()?K():X()},Math.max(1,s-re())),wn(F));let I=c?Math.min(15e3,1e3*2**Math.min(c-1,4)):Math.min(15e3,(t?.policy.refreshIntervalSeconds??15)*1e3);h=setTimeout(()=>{z().catch(ee)},Math.max(E,I*(.8+Math.random()*.2))),wn(h)}async function z(){if(R)throw S("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(N)return N;let I=A,y=new AbortController;b=y;let C=(async()=>{if(!oe){oe=!0;try{let Re=await a.readManifest();if(Re&&!t){let W=xe.parse(JSON.parse(Re));k(W.scope)===k(n)&&(t=W)}}catch{}}y.signal.throwIfAborted();let T=t,G=re(),L=await u(p,y.signal);L.status===304&&(!T||!L.headers.has("x-indiana-config-validated-at")||!L.headers.has("x-indiana-config-valid-until")||!L.headers.has("age"))&&(L=await u(p,y.signal));let q=L.status===304?T:xe.parse(JSON.parse(await U(L,H.maxManifestBytes,y.signal))),{generation:Z,...ne}=q,ue=L.headers.get("etag");if(k(q.scope)!==k(n)||en(ne)!==Z||ue!==`"${Z}"`&&ue!==`W/"${Z}"`)throw S("INVALID_RESPONSE","Configuration scope or content identity changed");if(T&&(q.revision<T.revision||q.revision===T.revision&&q.generation!==T.generation))throw S("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Re,W]of Object.entries(T?.funnels??{})){let le=q.funnels[Re];if(le&&(le.controlRevision<W.controlRevision||le.evaluationRevision<W.evaluationRevision||le.controlRevision===W.controlRevision&&le.state!==W.state||le.evaluationRevision===W.evaluationRevision&&le.evaluationMode!==W.evaluationMode))throw S("INVALID_RESPONSE","Funnel control revision changed identity")}let Le=J(L,G,q.policy);if(y.signal.throwIfAborted(),I!==A)throw S("CONFIGURATION_DISPOSED","Configuration scope changed");return t=q,s=Le,g=Date.now()+Math.max(0,Le-re()),w=!1,c=0,E=0,a.writeManifest(k(q)),X(),structuredClone(q)})(),v=setTimeout(()=>y.abort(S("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs),O=new Promise((T,G)=>y.signal.addEventListener("abort",()=>G(y.signal.reason),{once:!0})),V=Promise.race([C,O]).catch(T=>{throw c++,(T instanceof Cn.ZodError||T instanceof SyntaxError||T instanceof l&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(T.code))&&(s=0,w=!0,X()),T}).finally(()=>{clearTimeout(v),N===V&&(N=void 0),K()});return N=V,V}async function fe(I){let y=I.sha256,C=Z=>new TextEncoder().encode(Z).byteLength===I.byteLength&&Xe(Z)===y;Y(I.url);let v=D.get(y);if(v&&C(v))return D.delete(y),D.set(y,v),v;if(M.has(y))return M.get(y);let O=new AbortController;_.add(O);let V=A,T=(async()=>{try{let ue=await a.readArtifact(y);if(ue&&C(ue))return P(y,ue),ue}catch{}O.signal.throwIfAborted();let Z=await u(I.url,O.signal,!0),ne=await U(Z,I.byteLength,O.signal);if(!C(ne))throw S("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(R||V!==A)throw S("CONFIGURATION_DISPOSED","Configuration scope changed");return P(y,ne),a.writeArtifact(y,ne),ne})(),G=setTimeout(()=>O.abort(S("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),H.initializationMs),L=new Promise((Z,ne)=>O.signal.addEventListener("abort",()=>ne(O.signal.reason),{once:!0})),q=Promise.race([T,L]).finally(()=>{clearTimeout(G),_.delete(O),M.delete(y)});return M.set(y,q),q}async function pe(){return f()||await z(),m(),t}async function ie(I){let y,C=new Promise((v,O)=>{y=setTimeout(()=>O(S("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs)});try{return await Promise.race([I(),C])}finally{clearTimeout(y)}}function ae(I,y){if(m(),t?.generation!==I.generation)throw S("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(y&&t.funnels[y]?.state!=="active")throw S("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function we(I){let y=I.gb.features;if(!y)throw S("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let C=I.artifacts[y];if(C.formatVersion!==1)throw S("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let v=qe.parse(JSON.parse(await fe(C)));if(k(v.scope)!==k({projectId:n.projectId,environment:n.environment})||v.generation!==C.generation||v.remoteFeatures.some(O=>Object.hasOwn(v.features,O)))throw S("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return ae(I),{...v,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,s-re())).toISOString()}}async function se(I,y){let C=await pe();ae(C,I);let v=C.funnels[I];if(v.evaluationMode!=="local")throw S("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let O=y??v.currentVersionId,V=v.versions[O];if(!V)throw S("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(C.artifacts[V.artifact].formatVersion!==3)throw S("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let T=tn(JSON.parse(await fe(C.artifacts[V.artifact]))),G=v.evaluationMode==="local"?await we(C):void 0;if(G&&k(nn(T,G))!==k(V.dependencies))throw S("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return ae(C,I),{document:T,growth:G,versionId:O,control:structuredClone(v),manifest:structuredClone(C)}}function Ie(){w=!0,X(),z().catch(ee)}let $=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ie()};function Ee(I){if(R)throw S("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return x.add(I),x.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ie),window.addEventListener("focus",$),document.addEventListener("visibilitychange",$)),K()),()=>{x.delete(I),x.size||(clearTimeout(h),clearTimeout(F),Ve())}}function Ve(){typeof window<"u"&&(window.removeEventListener("online",Ie),window.removeEventListener("focus",$),document.removeEventListener("visibilitychange",$))}return{scope:Object.freeze({...n}),refresh:z,subscribe:Ee,assertFresh:m,assertFeatures(I){m();let y=t.gb.features;if(!y)throw S("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(I!==void 0&&t.artifacts[y].generation!==I)throw S("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return f()},get snapshot(){return t?structuredClone(t):null},get remainingMs(){return f()?Math.max(0,s-re()):0},async features(){return ie(async()=>we(await pe()))},pageExperiments:()=>ie(async()=>{let I=await pe(),y=I.gb.pageExperiments;if(!y)throw S("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let C=I.artifacts[y];if(C.formatVersion!==1)throw S("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let v=Ze.parse(JSON.parse(await fe(C)));if(v.environmentId!==n.environmentId||v.generation!==C.generation)throw S("INVALID_RESPONSE","Page experiment scope or generation changed");return ae(I),v}),funnel:(I,y)=>ie(()=>se(I,y)),async localFunnel(I,y){let C=await ie(()=>se(I,y));if(!C.growth)throw S("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:v,remoteFeatures:O,...V}=C.growth;return Ye({scope:{projectId:n.projectId,environment:n.environment},funnelId:I,versionId:C.versionId,evaluationMode:"local",evaluationRevision:C.control.evaluationRevision,document:C.document,payload:V})},assertFunnel(I,y,C){m();let v=t.funnels[I];if(!v||v.state!=="active")throw S("FUNNEL_STOPPED","Funnel is paused or unavailable");if(v.evaluationMode!=="local")throw S("EVALUATION_MODE","This Funnel now executes at Indiana");if(y!==void 0&&v.controlRevision!==y)throw S("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(C!==void 0&&!v.versions[C])throw S("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!R){R=!0,A++,s=0,b?.abort(S("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(h),clearTimeout(F),Ve(),X(),x.clear();for(let I of _)I.abort(S("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));D.clear(),j=0}}}}function In(e){let n=/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey);if(typeof window<"u"&&!n)throw new l("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new l("INVALID_TOKEN","A customer credential or server API key is required");let i=ge({...e,timeoutMs:e.timeoutMs??35e3});return i.identify(e.apiKey),{async start(o){let d=te.safeParse({...o,operation:"start"});if(!d.success||d.data.operation!=="start"||(n?d.data.customer!==void 0:d.data.customer===void 0))throw new l("INVALID_REQUEST","Invalid current Funnel start");let p=d.data,r=Ae.safeParse(await i.request("funnels",p));if(!r.success||!r.data.runToken)throw new l("INVALID_RESPONSE","Funnel start credentials are missing");let a=r.data;if(a.run.source.id!==p.funnelId||a.run.locale!==(p.locale??"en")||!ye(a.run.parameters,p.parameters??{})||(p.customer?!a.customerId||p.customer.type==="id"&&a.customerId!==p.customer.value:a.customerId!==void 0))throw new l("INVALID_RESPONSE","Funnel start contract changed");return{...a,runToken:a.runToken}}}}async function Ft(e){e={...e};let n=e.configuration;if(!n)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let i={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&k(i)!==k(e.scope))throw new l("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new l("EVALUATION_MODE","This Funnel uses Remote evaluation");let d=/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.credential);if(d?!e.customerId:e.customerId!==void 0)throw new l("INVALID_REQUEST","Only Server-Key starts name their Customer");let p=In({...e,scope:i,apiKey:e.credential}),r=a=>{let t=mn({...e,scope:i,runToken:a,...d?{serverKey:e.credential}:{}});return d||t.identify(e.credential),t};return{async start(a){let t=await p.start({...a,funnelId:e.funnelId,...d?{customer:{type:"id",value:e.customerId}}:{}}),s=r(t.runToken),g=await s.get();return{...t,...g,controller:s}},async restore(a){let t=r(a),s=await t.get();if(s.run.source.id!==e.funnelId)throw t.reset(),new l("SCOPE_MISMATCH","Run belongs to another Funnel");return{...s,runToken:a,controller:t}}}}export{An as a,kn as b,ye as c,an as d,sn as e,Fe as f,hn as g,un as h,mn as i,ut as j,It as k,In as l,Ft as m};
|
|
1
|
+
import{a as ge}from"./chunk-ET4NANGB.js";import{a as l}from"./chunk-5TEZEOHX.js";import{a as Ne}from"./chunk-S5TVMQRC.js";import{Bf as Ge,Bi as Ae,Bk as H,Ci as $e,Ck as We,Gd as Me,Gk as xe,Hk as k,Ig as Be,Ii as Qe,Ik as Xe,Jk as en,Kg as Je,Kk as nn,Lg as ze,Li as be,Lk as tn,Mi as Ye,Mk as rn,Ng as He,Ok as De,Qh as _e,Rh as Te,Tg as Ke,Tk as on,Vf as ce,ag as je,ek as Ze,ri as te,xf as Ue,yf as qe}from"./chunk-VMLGV5OS.js";import{b as ke,h as me}from"./chunk-OHDY27EI.js";import{f as Ce,j as Se,l as Oe,m as he}from"./chunk-S2MSIA57.js";function An(e){let n=null,i=null,o=0,d=0,p=new Set,r=null,a=null,t=new Set,s=()=>{for(let h of t)try{h()}catch{}},g={attributes:he.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(h,F)=>{!p.has(h)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(h,structuredClone(F))}:void 0,onExperimentViewed:e.onExperimentViewed?(h,F)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(h),structuredClone(F)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?h=>e.saveStickyBucketAssignmentDoc(structuredClone(h)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function R(h,F=new Set){return p.has(h)?!r||!r.features[h]||["unknownFeature","cyclicPrerequisite"].includes(r.features[h].source):F.has(h)?!1:(F.add(h),(n?.features[h]?.rules??[]).some(E=>[...E.parentConditions??[],...(E.tracks??[]).flatMap(x=>x.experiment.parentConditions??[])].some(x=>R(x.id,F))))}let A=h=>{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 r?.expiresAt&&Date.parse(r.expiresAt)<=Date.now()&&(r=null,g.features=n.features),p.has(h)?!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now()?w():structuredClone(r.features[h]??w()):R(h)?w():structuredClone(Se(h,g))};async function c(){if(!n||!p.size)return;if(!e.evaluateRemote)throw new Error("Remote Feature evaluation requires a server loader");let h=d;if(a?.revision===h)return a.loading;let F=o,E=n,x=[...p],_=(async()=>{let D=Ge.parse(await e.evaluateRemote({attributes:structuredClone(g.attributes),features:x}));if(!(F!==o||h!==d||E!==n)){if(e.assertUsable?.(E.generation),D.generation!==E.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(x.some(M=>!Object.hasOwn(D.features,M))||Object.keys(D.features).some(M=>!p.has(M)))throw new Error("Invalid remote Feature results");r=structuredClone(D),g.features={...E.features,...Object.fromEntries(Object.entries(r.features).map(([M,j])=>[M,{defaultValue:j.value}]))},s()}})();a={revision:h,loading:_};try{await _}finally{a?.loading===_&&(a=null)}}function N(){c().catch(h=>{try{e.onError?.(h)}catch{}})}async function b(){if(i)return i;let h=o,F=(async()=>{let E=await e.load(),x="remoteFeatures"in E?Ue.parse(E):null,_=x??me.parse(E);if(_.scope.projectId!==e.scope.projectId||_.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(h!==o)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===_.generation){let{evaluatedAt:M,expiresAt:j,...oe}=n,{evaluatedAt:X,expiresAt:ee,...f}=_;if(k(oe)!==k(f))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=_.evaluatedAt,n.expiresAt=_.expiresAt,s(),(!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now())&&N(),structuredClone(n)}let D=new Set(x?.remoteFeatures??[]);if([...D].some(M=>Object.hasOwn(_.features,M)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in _&&!n.analyticsConfig.experimentViewsEnabled&&x?.analyticsConfig.experimentViewsEnabled&&g.trackedExperiments?.clear(),n=structuredClone(_),p=D,r=null,a=null,d++,g.features=n.features,g.savedGroups=Ce(n.savedGroups),g.trackedFeatureUsage={},s(),N(),structuredClone(n)})();i=F;try{return await F}finally{i===F&&(i=null)}}return{init:b,refresh:b,refreshRemote:c,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(h){return t.add(h),()=>{t.delete(h)}},setAttributes(h){g.attributes=he.parse(h),d++,r=null,a=null,g.features=n?.features??{},g.trackedFeatureUsage={},s(),N()},evalFeature:A,isOn(h){return A(h).on},isOff(h){return A(h).off},getFeatureValue(h,F){let E=A(h).value;return structuredClone(E===null?F:E)},reset(){o++,d++,i=null,a=null,n=null,r=null,p.clear(),g.features={},g.savedGroups={},g.stickyBucketAssignmentDocs={},g.attributes={},g.trackedFeatureUsage={},g.trackedExperiments?.clear(),s()}}}function an(e){let n=new Map(e.topology.nodes.map(d=>[d.id,d])),i=Ce(e.growth.savedGroups);function o(d,p){if(!Object.hasOwn(e.growth.features,d))throw new l("INVALID_RESPONSE","Required GB Feature is unavailable");return Se(d,p).value}return{nodes:n,savedGroups:i,features:e.growth.features,feature:o,evaluate(d,p){let r=n.get(d);if(!r)throw new l("NOT_FOUND","Funnel node is unavailable");let a,t;if(r.type==="condition"){let g=e.conditions[r.id];if(!g)throw new l("INVALID_RESPONSE","Local condition rules are unavailable");a=_e({id:r.id,name:r.id,type:"condition",cases:g.map(w=>({condition:w.condition,target:r.outputs[w.port]})),default:r.outputs.default},p,e.growth.experiments).port}else if(r.type==="feature"){if(!r.resources.featureKey)throw new l("INVALID_RESPONSE","Feature reference is unavailable");t=o(r.resources.featureKey,p),a="next"}else if(r.type==="split"){if(!(r.resources.experimentId?e.growth.experiments[r.resources.experimentId]:void 0))throw new l("INVALID_RESPONSE","Experiment reference is unavailable");let w=_e({id:r.id,name:r.id,type:"split",experimentId:r.resources.experimentId,routes:r.outputs,notParticipating:r.outputs.notParticipating},p,e.growth.experiments);t=w.value,a=w.port}else if(["offering","end","output"].includes(r.type)&&r.resources.featureKey)t=o(r.resources.featureKey,p),a=r.type==="offering"?"next":"value";else throw new l("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let s=r.outputs[a]??(a==="value"?r.id:void 0);if(!s)throw new l("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:d,port:a,target:s,...t===void 0?{}:{value:t}}}}}function sn(e,n,i){let o=Qe.parse(e);if(o.evaluationMode!=="local")throw new l("EVALUATION_MODE","Remote nodes are evaluated by Grow");if(o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())throw new l("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition");let d=an(o),r={attributes:he.parse(i.attributes??{}),saveStickyBucketAssignmentDoc:i.saveStickyBucketAssignmentDoc?a=>i.saveStickyBucketAssignmentDoc(structuredClone(a)):void 0,onFeatureUsage:i.onFeatureUsage?(a,t)=>i.onFeatureUsage(a,structuredClone(t)):void 0,onExperimentViewed:i.onExperimentViewed?(a,t)=>i.onExperimentViewed(structuredClone(a),structuredClone(t)):void 0,features:d.features,savedGroups:d.savedGroups,stickyBucketAssignmentDocs:structuredClone(i.stickyBucketAssignmentDocs)};return d.evaluate(n,r)}function un(e){let n,i,o=()=>new l("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),d=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,i=e.locks??globalThis.navigator?.locks,!n||!i||!globalThis.crypto?.subtle)throw o();let a=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??Ne).href,e.runToken])),t=new Uint8Array(await crypto.subtle.digest("SHA-256",a));return"indiana.funnel.commands.v1."+Array.from(t,s=>s.toString(16).padStart(2,"0")).join("")});d.catch(()=>{});async function p(a){try{let t=await d;return await i.request(t,{mode:"exclusive"},()=>a(t))}catch(t){throw t instanceof l?t:o()}}function r(a){let t=n.getItem(a);if(t===null)return{revision:0,entry:null};if(t.length>1048576)throw o();let s=JSON.parse(t);if(!s||typeof s!="object"||!("revision"in s)||!("entry"in s)||!Number.isSafeInteger(s.revision)||Number(s.revision)<0)throw o();return{revision:Number(s.revision),entry:s.entry}}return{read:()=>p(r),write:(a,t)=>p(s=>{if(r(s).revision!==a)return null;if(!Number.isSafeInteger(a+1))throw o();return n.setItem(s,JSON.stringify({revision:a+1,entry:t})),a+1})}}function kn(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ye(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,p)=>ye(d,n[p]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let i=Object.entries(e),o=Object.entries(n);return i.length===o.length&&i.every(([d,p])=>Object.hasOwn(n,d)&&ye(p,Reflect.get(n,d)))}function Fe(e,n,i){let o=[],d=[],p=[],r=sn(e,n,{attributes:i.attributes,stickyBucketAssignmentDocs:i.sticky,saveStickyBucketAssignmentDoc(a){let t=a.attributeName+"||"+a.attributeValue,s=o.findIndex(w=>w.next.attributeName===a.attributeName&&w.next.attributeValue===a.attributeValue),g={expected:i.sticky[t]??null,next:a};s<0?o.push(g):o[s]=g},onExperimentViewed(a,t){t.inExperiment&&t.hashUsed&&!t.passthrough&&d.push(Oe.parse({key:a.key,variationId:t.variationId,keyUsed:t.key,hashAttribute:t.hashAttribute,hashValue:t.hashValue}))},onFeatureUsage(a,t){p.push(Oe.parse({feature:a,value:t.value,source:t.source,...t.ruleId?{ruleId:t.ruleId}:{}}))}});return{port:r.port,...r.value===void 0?{}:{value:r.value},sticky:o,exposures:d,features:p}}async function ln(e,n){let i=n.instruction;if(i?.type!=="evaluate")throw new Error("Evaluation instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require the shared public configuration manager");let o=await e.funnel(n.source.id,n.source.versionId);if(!o.growth||o.control.evaluationMode!=="local"||o.control.evaluationRevision!==i.policyRevision)throw new l("EVALUATION_MODE","Refresh the original Funnel evaluation policy");let{analyticsConfig:d,remoteFeatures:p,...r}=o.growth,a=be({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:o.document,payload:me.parse(r)});if(e.scope.environmentId!==i.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let t=Fe(a,n.nodeId,i);return e.assertFunnel(n.source.id,void 0,n.source.versionId),{generation:o.manifest.generation,result:t}}async function cn(e,n){let i=n.instruction;if(i?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");let o=await e.funnel(n.source.id,n.source.versionId);if(!o.growth||o.control.evaluationMode!=="local"||o.control.evaluationRevision!==i.policyRevision)throw new l("EVALUATION_MODE","Refresh the original Funnel evaluation policy");if(e.scope.environmentId!==i.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let{analyticsConfig:d,remoteFeatures:p,...r}=o.growth,a=be({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:o.document,payload:me.parse(r)}),t=hn(a,o.document,{...n,...i});return e.assertFunnel(n.source.id,void 0,n.source.versionId),{...t,generation:o.manifest.generation,policyRevision:i.policyRevision}}function hn(e,n,i){let o=i,d=new Map(n.graph.nodes.map(A=>[A.id,A])),p=structuredClone(i.variables),r=structuredClone(o.sticky),a=[],t=e.evaluationMode==="local"&&on(e.growth),s=i.nodeId,g=i.visit,w=!1;for(let A=0;A<rn;A++){let c=d.get(s);if(!c||!De(c))break;if(g>=n.execution.maxTransitions)throw new l("TRANSITION_LIMIT","Local Funnel transition budget exceeded");let N={attributes:c.type==="condition"?He({declarations:n.variables,attributes:o.attributes,parameters:i.parameters,answers:i.answers,results:p,savedGroups:{}}):{...o.attributes,parameters:i.parameters,answers:i.answers,results:p},sticky:r},b,h;if(["condition","feature","split"].includes(c.type)||c.type==="offering"&&c.configuration.source==="feature")b=Fe(e,c.id,N),c.type==="offering"&&(b.value={type:"offering_version",id:String(b.value)}),c.type==="condition"?h=b.port==="default"?c.default:c.cases[Number(b.port.slice(5))]?.target:c.type==="split"?h=b.port==="notParticipating"?c.notParticipating:c.routes[b.port]:(c.type==="feature"||c.type==="offering")&&(h=c.next);else if(b={port:"next",sticky:[],exposures:[],features:[]},(c.type==="entry"||c.type==="coupon"||c.type==="coupons")&&(h=c.next),c.type==="offering"&&c.configuration.source==="fixed"&&(b.value={type:"offering_version",id:c.configuration.versionId},h=c.next),c.type==="end"||c.type==="output"){let E=c.type==="end"?c.output:c.value;if(b=E?.type==="feature"?Fe(e,c.id,N):{...b,port:"value",value:E?.type==="literal"?E.value:E?.type==="variable"?Ke({source:"variable",key:E.key,...E.path?{path:E.path}:{}},{declarations:n.variables,answers:i.answers,results:p,parameters:i.parameters,attributes:o.attributes,savedGroups:{}}):null},E&&(b.value===void 0||!Be(n.outputSchema,b.value)))throw new l("INVALID_RESPONSE","Local terminal violates its declared output")}let F=[...a,{nodeId:s,result:b}];if(je({steps:F})>6e4){if(!a.length)throw new l("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:s,result:b}),c.type==="feature"||c.type==="offering"||c.type==="coupon"||c.type==="coupons"){let E=c.type==="coupons"?c.couponIds.map(_=>({type:"reward",id:_})):c.type==="coupon"?{type:"reward",id:c.couponId}:b.value;if(E===void 0)throw new l("INVALID_RESPONSE","Node output is missing");let x=Je(c,{value:E});ze(n.variables,c,x),Object.assign(p,x)}for(let E of b.sticky)r[`${E.next.attributeName}||${E.next.attributeValue}`]=structuredClone(E.next);if(c.type==="end"||c.type==="output"){w=!0;break}if(!h)throw new l("INVALID_RESPONSE","Local pure exit is unavailable");if(s=h,g++,t&&["feature","offering","coupon","coupons"].includes(c.type))break}let R=d.get(s);return{steps:a,...!w&&R&&!De(R)?{boundary:{nodeId:s,visit:g}}:{}}}import{z as Q}from"zod";var dn=te.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 l("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),fn=Q.strictObject({schemaVersion:Q.literal(1),scope:ke,runId:Q.uuid(),funnelId:Q.uuid(),versionId:Q.uuid(),command:dn.optional(),closeCommand:dn.refine(e=>e.operation==="close").optional(),purchase:Q.strictObject({receiptId:Q.uuid(),operationId:Q.uuid(),generation:Q.number().int().nonnegative()}).optional(),closed:Q.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"),B=()=>new l("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Pe=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function pn(e){let n=0,i=null,o=t=>JSON.stringify([t.scope,t.runId,t.funnelId,t.versionId]),d=Promise.resolve();async function p(){let t=await e.read();if(!Number.isSafeInteger(t.revision)||t.revision<0)throw new l("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:t.revision,entry:t.entry===null?null:fn.parse(t.entry)}}function r(t){let s=d.then(t);return d=s.catch(()=>{}),s}async function a(t){for(let s=0;s<4;s++){let g=await p();if(g.entry&&i!==null&&o(g.entry)!==i)throw B();let w=t(g.entry,g.revision);if(Pe(g.entry,w)){n=g.revision;return}let R=await e.write(g.revision,w);if(R!==null){if(!Number.isSafeInteger(R)||R<=g.revision)throw B();n=R;return}}throw B()}return{bind(t){let s=JSON.stringify([t.scope,t.runId,t.funnelId,t.versionId]);if(i!==null&&i!==s)throw B();i=s},async load(){let t=await p();return n=t.revision,i=t.entry?o(t.entry):null,t.entry},retain(t){let s=fn.parse(t),g=s.command;return!g||i!==null&&o(s)!==i?Promise.reject(B()):(i??=o(s),r(()=>a((w,R)=>{if(w&&!Pe(o(w),o(s)))throw B();if(!w){if(R!==n&&g.operation!=="close")throw B();return s}if(!w.command)return{...w,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&w.command.operation!=="close"){if(w.command.requestId===g.requestId||w.closeCommand&&!Pe(w.closeCommand,g))throw B();return{...w,closeCommand:g,closed:!0}}if(!Pe(w.command,g))throw B();return w})))},observePurchase(t,s,g){return r(()=>a((w,R)=>{if(!w&&R!==n||w&&o(w)!==o({...t,schemaVersion:1}))throw B();if(w?.purchase&&w.purchase.generation>s.generation)return w;if(w?.purchase&&w.purchase.generation===s.generation&&w.purchase.operationId!==s.operationId)throw B();return g?!w?.purchase||w.purchase.operationId!==s.operationId?w:w.command?{...w,purchase:void 0}:null:{schemaVersion:1,...t,...w,purchase:s}}))},settle(t){return r(()=>a(s=>s?s.command&&"requestId"in s.command&&s.command.requestId===t?s.closeCommand?{...s,command:s.closeCommand,closeCommand:void 0}:s.purchase?{...s,command:void 0}:null:s.closeCommand&&"requestId"in s.closeCommand&&s.closeCommand.requestId===t?{...s,closeCommand:void 0}:s:null))}}}function de(e){let{customerToken:n,...i}=e;return i}var vn=e=>!(e instanceof l)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function mn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new l("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.serverKey)))throw new l("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");let n=ge({...e,...e.serverKey?{fetch:(f,m)=>{let P=new Headers(m?.headers);return P.set($e,e.serverKey),(e.fetch??globalThis.fetch)(f,{...m,headers:P})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let i,o=null,d=0,p=0,r=null,a=null,t=!1,s=null,g=!1,w=null,R=new Set,A=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?un(e):void 0),c=A&&pn(A),N,b=null,h=!1,F=c?c.load().then(f=>{if(h)throw new l("IDENTITY_CHANGED","Controller was reset during command restoration");if(b=f,!f)return;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Pending command belongs to another scope");if(N=f.purchase,t=f.closed===!0,!f.command)return;let m=te.parse(f.command);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");r=m,f.closeCommand&&(a=f.closeCommand,t=!0),m.operation==="close"&&(t=!0),g=!0}):Promise.resolve();F.catch(()=>{});async function E(f,m,P){c&&await F;let U=d,Y=o,u=Ae.parse(await n.request("funnels",te.parse(f)));if(f.operation==="review"&&!u.review)throw new l("INVALID_RESPONSE","Historical projection is missing");if(U!==d)throw new l("IDENTITY_CHANGED","Run identity changed during the request");if(u.runToken&&u.runToken!==e.runToken)throw new l("INVALID_RESPONSE","Run credential changed");let J=f.operation==="get"?f.settlementRequestId:"requestId"in f&&f.operation!=="start"?f.requestId:void 0;if(J&&u.settlement?.requestId!==J)throw new l("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");if(b&&(u.run.id!==b.runId||u.run.source.id!==b.funnelId||u.run.source.versionId!==b.versionId))throw new l("SCOPE_MISMATCH","Stored command belongs to another Run or Version");if(o&&(u.run.id!==o.id||u.run.source.type!==o.source.type||u.run.source.id!==o.source.id||u.run.source.versionId!==o.source.versionId||u.run.locale!==o.locale||!ye(u.run.parameters,o.parameters)))throw new l("INVALID_RESPONSE","Run version changed");if(e.funnelId&&u.run.source.id!==e.funnelId)throw new l("INVALID_RESPONSE","Run belongs to another Funnel");c?.bind({scope:u.scope,runId:u.run.id,funnelId:u.run.source.id,versionId:u.run.source.versionId}),A&&!e.scope&&(e.scope=u.scope);let K=u.run.paywall,z=K??u.purchase,fe=z?.operation,pe=u.settlement&&(!K||K.purchaseRequestId===u.settlement.requestId)&&(!N||N.operationId===u.settlement.operationId)?u.settlement:void 0,ie=fe?.operationId??z?.quote?.operationId??pe?.operationId,ae=z?.receiptId??pe?.receiptId,we=K?.selectionGeneration??N?.generation??0;if(c&&ie&&ae&&f.operation!=="review"&&(!o||u.run.revision>=o.revision)&&(P===void 0||P>=p)&&(!N||we>=N.generation)){let $={receiptId:ae,operationId:ie,generation:we},Ee=fe?.status==="complete"||z?.canReselect===!0;await c.observePurchase({scope:u.scope,runId:u.run.id,funnelId:u.run.source.id,versionId:u.run.source.versionId},$,Ee),Ee?N?.operationId===$.operationId&&(N=void 0):N=$}if(!u.run.stopped&&["running","waiting"].includes(u.run.status)&&f.operation==="get"&&f.settlementRequestId)return u;let se=m?.(u),Ie=typeof se=="boolean"?se:se?await se:!1;if(["running","waiting"].includes(u.run.status)||(t=!0),f.operation==="review"&&o&&o!==Y&&u.run.revision<=o.revision||o&&u.run.revision===o.revision&&P!==void 0&&P<p||(f.operation==="review"&&!u.run.stopped&&["running","waiting"].includes(u.run.status)&&o&&u.run.nodeId===o.nodeId&&u.run.visit===o.visit&&u.run.revision===o.revision&&(u.run.screen=o.screen,(o.paywall?.quote?.operationId===u.review?.activeOperationId||!o.paywall?.quote&&u.review?.activeOperationId===null)&&(u.run.paywall=o.paywall)),o?.paywall&&u.run.paywall&&o.paywall.receiptId===u.run.paywall.receiptId&&(u.run.paywall.selectionGeneration??0)<(o.paywall.selectionGeneration??0)))return u;if(!o||u.run.revision>=o.revision)o=u.run;else if(!Ie)return u;if(o)for(let $ of R)try{$(structuredClone(o))}catch{}return u}async function x(f=r){if(c&&await F,!f)throw new l("INVALID_REQUEST","No command is pending");let m=f,P=d;if(c){if(!o||!e.scope)throw new l("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await c.retain({schemaVersion:1,scope:e.scope,runId:o.id,funnelId:o.source.id,versionId:o.source.versionId,command:de(m)})}if(P!==d||r!==m&&a!==m)throw new l("IDENTITY_CHANGED","Run changed before command dispatch");let U={...m,...i?{customerToken:i}:{}},Y=g;g=!0;try{return await E(U,u=>{if(!u.settlement)throw new l("INVALID_RESPONSE","Exact command settlement is missing");if(u.settlement.requestId!==m.requestId)throw new l("INVALID_RESPONSE","Command settlement identity changed");if(P===d&&(r===m||a===m)&&u.run.pendingRequest?.requestId!==m.requestId&&u.settlement.state==="settled"&&(!t||m.operation==="close"||u.settlement?.state==="settled"&&!["running","waiting"].includes(u.run.status))){let J=()=>P!==d||r!==m&&a!==m?!1:(r===m&&(r=null),a===m&&(a=null),g=r!==null,b=null,!0);return c?c.settle(m.requestId).then(J):J()}return!1})}catch(u){throw P===d&&r===m&&!Y&&!vn(u)&&(c&&await c.settle(m.requestId),P===d&&r===m&&(r=null,g=!1,b=null)),u}}function _(f){let m=te.parse(f);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new l("INVALID_REQUEST","Mutation required");if(o?.recoveryRestricted&&m.operation!=="close"&&m.operation!=="resume"&&r?.requestId!==m.requestId)throw new l("PRECONDITION_FAILED","Original Run requires restricted recovery");if(t&&m.operation!=="close"){if(r?.requestId===m.requestId)return ee.settle(m.requestId);throw new l("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"&&r?.operation!=="close"){if(t=!0,a&&JSON.stringify(de(a))!==JSON.stringify(de(m)))throw new l("COMMAND_PENDING","Retry the original Close");if(a??=m,s)return s;let U=x(a);return s=U,U.then(()=>{s===U&&(s=null)},()=>{s===U&&(s=null)}),U}if(r){if(JSON.stringify(de(r))!==JSON.stringify(de(m)))throw new l("COMMAND_PENDING","Retry the original command before sending another");if(w)return w}else r=m,g=!1;let P=x();return w=P,P.then(()=>{w===P&&(w=null)},()=>{w===P&&(w=null)}),P}let D=null,M=new WeakMap;function j(f){let m=M.get(f);if(m)return m;let P=X(f);return M.set(f,P),P}let oe=!1;async function X(f){let m=await f;if(m.run.recoveryRestricted||!["evaluate","evaluate_segment"].includes(m.run.instruction?.type??""))return m;if(D)return D;oe=!0;let P=d,U=(async()=>{for(let Y=0;Y<32&&["evaluate","evaluate_segment"].includes(m.run.instruction?.type??"");Y++){if(r||t)return m;let u=m.run,J=m.run.instruction;if(J?.type==="evaluate_segment"){let z=await cn(e.configuration,u);if(P!==d)throw new l("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r||t)return m;if(o&&(o.revision!==u.revision||o.visit!==u.visit||o.nodeId!==u.nodeId))return E({operation:"get",...i?{customerToken:i}:{}});m=await _({operation:"commit_segment",requestId:Te(u.id,u.visit,`segment:${u.revision}`),nodeId:u.nodeId,visit:u.visit,revision:u.revision,...z});continue}if(J?.type!=="evaluate")return m;let K=await ln(e.configuration,u);if(P!==d)throw new l("IDENTITY_CHANGED","Run identity changed during evaluation");if(r||t)return m;if(o&&(o.revision!==u.revision||o.visit!==u.visit||o.nodeId!==u.nodeId))return E({operation:"get",...i?{customerToken:i}:{}});m=await _({operation:"evaluate",requestId:Te(u.id,u.visit,"evaluation"),nodeId:u.nodeId,visit:u.visit,revision:u.revision,receiptId:J.receiptId,policyRevision:J.policyRevision,...K})}return m})();D=U;try{return await U}finally{D===U&&(D=null)}}let ee={get configuration(){return oe?e.configuration:void 0},get configurationReady(){return!0},get view(){return o?structuredClone(o):null},get pendingCommand(){let f=a??r;return f?structuredClone(de(f)):null},get pendingCommands(){return[r,a].filter(f=>f!==null).map(f=>structuredClone(de(f)))},get pendingPurchase(){return N?structuredClone(N):null},async settle(f){let m=await E({operation:"get",settlementRequestId:f,...i?{customerToken:i}:{}});if(m.settlement?.requestId!==f)throw new l("INVALID_RESPONSE","Exact command settlement is missing");return m.settlement.state==="settled"&&(c&&await c.settle(f),r?.requestId===f&&(r=null,g=!1),a?.requestId===f&&(a=null)),m},get webViewUrl(){return n.webViewUrl()},review(f){return E({operation:"review",...f?{receiptId:f}:{},...i?{customerToken:i}:{}},void 0,++p)},async get(f,m){c&&await F,m??=N&&{receiptId:N.receiptId,operationId:N.operationId};let P=++p;return j(E({operation:"get",...f?{data:f}:{},...m?{purchase:m}:{},...i?{customerToken:i}:{}},void 0,P))},resume(f=o?.pendingRequest?.requestId){return f?t?ee.settle(f):r?.requestId===f?j(_(r)):j(_({operation:"resume",requestId:f})):Promise.reject(new l("INVALID_REQUEST","No interrupted command is available"))},submit(f){return j(_(f))},retry(){return s||(a?x(a):t&&r?ee.settle(r.requestId):w?j(w):r?j(_(r)):Promise.reject(new l("INVALID_REQUEST","No command is pending")))},identify(f){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(f))throw new l("INVALID_TOKEN","Customer credential required");d++,i=f,n.identify(e.runToken)},subscribe(f){return R.add(f),()=>R.delete(f)},reset(){h=!0,d++,i=void 0,o=null,r=null,a=null,s=null,g=!1,w=null,n.reset(),R.clear()}};return ee}async function ut(e,n){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(n.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");let i=ge(e);i.identify(n.customerToken);let o=ce.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}:{}}),d=null,p=null,r=null,a=null,t=null;async function s(){let R=ce.resolvePaywall,A=R.response.parse(await i.request(R.path,R.request.parse({...o,selector:d?{type:"version",versionId:d.id}:o.selector})));if(n.paywallVersionId?A.paywall.id!==n.paywallVersionId:A.paywall.paywallId!==n.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(d&&(A.paywall.id!==d.id||A.paywall.paywallId!==d.paywallId||A.paywall.offering.id!==d.offering.id))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return d=A.paywall,structuredClone(d)}async function g(R){if(!p)throw new l("INVALID_REQUEST","A quoted purchase is required");let A=R==="read"?ce.readSubscriptionOperation:ce.attach,c=A.response.parse(await i.request(A.path,A.request.parse({operationId:p.operationId,...R==="read"?{}:{intent:R}})));if(c.operation.operationId!==p.operationId||c.operation.currency!==o.commerce.currency)throw new l("INVALID_RESPONSE","The purchase operation changed");return r?.status==="complete"&&c.operation.status!=="complete"||r&&r.status!=="pending"&&c.operation.status==="pending"||(r=c.operation),structuredClone(r)}let w={get view(){return d?structuredClone(d):null},get quote(){return p?structuredClone(p):null},get operation(){return r?structuredClone(r):null},get webViewUrl(){return i.webViewUrl()},refresh:s,async preview(R){if(!d)throw new l("INVALID_REQUEST","Load the Paywall first");let A=d.document.buttons[R.actionId];if(A?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let c=Me(A.product,R.selection,d.capabilities);if(!c)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let N=ce.previewAttach.request.parse({funnelId:o.funnelId,funnelVersionId:o.funnelVersionId,requestId:R.requestId,plans:[{productVersionId:c}],provider:o.commerce.provider,currency:o.commerce.currency,...R.offerId?{offerId:R.offerId}:{},...R.nativeOffer?{nativeOffer:R.nativeOffer}:{}}),b=JSON.stringify(N);if(a&&a!==b&&(!r||r.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(a===b){if(t)return t;if(p)return structuredClone(p)}a=b;let h=(async()=>{let F=ce.previewAttach,E=F.response.parse(await i.request(F.path,N));if(E.quote.currency!==o.commerce.currency||E.quote.provider!==o.commerce.provider||E.quote.lines.length!==1||E.quote.lines[0].productVersionId!==c)throw new l("INVALID_RESPONSE","The purchase quote changed its selected Product or presentment");return p=E.quote,r=null,structuredClone(p)})();t=h;try{return await h}finally{t===h&&(t=null)}},confirm:()=>g("confirm"),cancel:()=>g("cancel"),read:()=>g("read"),destroy(){i.reset(),d=null,p=null,r=null,a=null}};return await s(),w}import{z as Cn}from"zod";import{z as ve}from"zod";var En=ve.record(ve.string().regex(/^[a-f0-9]{64}$/),ve.strictObject({at:ve.number(),text:ve.string()})),gn=2*1048576;function Rn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function yn(e,n){let i=n===void 0?Rn():n,o=Promise.resolve();async function d(){try{let p=await i?.getItem(`${e}:artifacts`);if(p&&p.length<=gn)return En.parse(JSON.parse(p))}catch{}return{}}return{async readManifest(){try{return await i?.getItem(e)}catch{return}},writeManifest(p){Promise.resolve().then(()=>i?.setItem(e,p)).catch(()=>{})},async readArtifact(p){let r=(await d())[p];return r&&Date.now()>=r.at&&Date.now()-r.at<=H.retentionMs?r.text:void 0},writeArtifact(p,r){i&&(o=o.catch(()=>{}).then(async()=>{let a=await d(),t=Date.now();a[p]={at:t,text:r};let s={},g=2,w=0;for(let[R,A]of Object.entries(a).sort(([,c],[,N])=>N.at-c.at)){if(A.at>t||t-A.at>H.retentionMs)continue;let c=new TextEncoder().encode(JSON.stringify({[R]:A})).byteLength;g+c>gn||w>=128||(s[R]=A,g+=c,w++)}await i.setItem(`${e}:artifacts`,JSON.stringify(s))}).catch(()=>{}))}}}var S=(e,n)=>new l(e,n),re=()=>performance.now(),wn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function It(e){let n=We.parse(e.scope),i=new URL(e.origin??Ne);if(i.username||i.password||i.search||i.hash||i.pathname!=="/"||i.protocol!=="https:"&&!(i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname)))throw S("INVALID_URL","Configuration requires a trusted HTTPS origin");let o=new Set([i.origin,...(e.assetOrigins??[]).map(I=>{let y=new URL(I);if(y.protocol!=="https:"||y.username||y.password||y.search||y.hash||y.pathname!=="/")throw S("INVALID_URL","Invalid configuration asset origin");return y.origin})]),d=e.fetch??globalThis.fetch.bind(globalThis),p=`/api/v1/configuration/${n.environmentId}`,r=`indiana:configuration:1:${i.origin}:${k(n)}`,a=yn(r,e.storage),t,s=0,g=0,w=!1,R=!1,A=0,c=0,N,b,h,F,E=0,x=new Set,_=new Set,D=new Map,M=new Map,j=0,oe=!1;function X(){for(let I of x)try{I()}catch{}}function ee(I){try{e.onError?.(I)}catch{}}let f=()=>!R&&!w&&!!t&&re()<s&&Date.now()<g;function m(){if(!f())throw S("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function P(I,y){let C=new TextEncoder().encode(y).byteLength;if(!D.has(I)){for(;D.size&&(D.size>=128||j+C>H.maxCacheBytes);){let v=D.entries().next().value;j-=new TextEncoder().encode(v[1]).byteLength,D.delete(v[0])}D.set(I,y),j+=C}}async function U(I,y,C){if(Number(I.headers.get("content-length"))>y)throw S("INVALID_RESPONSE","Configuration exceeds its byte limit");let v=I.body?.getReader();if(!v)throw S("INVALID_RESPONSE","Configuration body is missing");let O=[],V=0;try{for(;;){C.throwIfAborted();let L=await v.read();if(L.done)break;if(V+=L.value.length,V>y)throw S("INVALID_RESPONSE","Configuration exceeds its byte limit");O.push(L.value)}}finally{await v.cancel().catch(()=>{})}C.throwIfAborted();let T=new Uint8Array(V),G=0;for(let L of O)T.set(L,G),G+=L.length;return new TextDecoder("utf-8",{fatal:!0}).decode(T)}function Y(I){let y=new URL(I,i);if(!o.has(y.origin)||y.username||y.password||y.hash||y.search)throw S("INVALID_URL","Configuration artifact origin is not trusted");return y.href}async function u(I,y,C=!1){let v=await d(Y(I),{method:"GET",credentials:"omit",redirect:"error",cache:C?"default":"no-cache",signal:y,headers:{}});if(v.status===429){let O=v.headers.get("retry-after")??"";E=/^\d+$/.test(O)?Number(O)*1e3:Math.max(0,Date.parse(O)-Date.now())||15e3}if(!v.ok&&v.status!==304)throw S(`CONFIGURATION_HTTP_${v.status}`,"Configuration synchronization failed");return v}function J(I,y,C){let v=Date.parse(I.headers.get("x-indiana-config-validated-at")??""),O=Date.parse(I.headers.get("x-indiana-config-valid-until")??""),V=Date.parse(I.headers.get("date")??""),T=I.headers.get("age"),G=T!==null&&/^\d+(\.\d+)?$/.test(T)?Number(T)*1e3:NaN;if(![v,O,V,G].every(Number.isFinite)||O<=v||O-v>H.maxControlAgeMs||v>V+1e3)throw S("INVALID_RESPONSE","Configuration freshness evidence is invalid");let q=Math.min(O-v,C.maxControlAgeSeconds*1e3,H.maxControlAgeMs)-Math.max(G,V-v,0)-(re()-y);if(q<=0)throw S("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return re()+q}function K(){if(clearTimeout(h),clearTimeout(F),R||!x.size)return;f()&&(F=setTimeout(()=>{f()?K():X()},Math.max(1,s-re())),wn(F));let I=c?Math.min(15e3,1e3*2**Math.min(c-1,4)):Math.min(15e3,(t?.policy.refreshIntervalSeconds??15)*1e3);h=setTimeout(()=>{z().catch(ee)},Math.max(E,I*(.8+Math.random()*.2))),wn(h)}async function z(){if(R)throw S("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(N)return N;let I=A,y=new AbortController;b=y;let C=(async()=>{if(!oe){oe=!0;try{let Re=await a.readManifest();if(Re&&!t){let W=xe.parse(JSON.parse(Re));k(W.scope)===k(n)&&(t=W)}}catch{}}y.signal.throwIfAborted();let T=t,G=re(),L=await u(p,y.signal);L.status===304&&(!T||!L.headers.has("x-indiana-config-validated-at")||!L.headers.has("x-indiana-config-valid-until")||!L.headers.has("age"))&&(L=await u(p,y.signal));let q=L.status===304?T:xe.parse(JSON.parse(await U(L,H.maxManifestBytes,y.signal))),{generation:Z,...ne}=q,ue=L.headers.get("etag");if(k(q.scope)!==k(n)||en(ne)!==Z||ue!==`"${Z}"`&&ue!==`W/"${Z}"`)throw S("INVALID_RESPONSE","Configuration scope or content identity changed");if(T&&(q.revision<T.revision||q.revision===T.revision&&q.generation!==T.generation))throw S("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Re,W]of Object.entries(T?.funnels??{})){let le=q.funnels[Re];if(le&&(le.controlRevision<W.controlRevision||le.evaluationRevision<W.evaluationRevision||le.controlRevision===W.controlRevision&&le.state!==W.state||le.evaluationRevision===W.evaluationRevision&&le.evaluationMode!==W.evaluationMode))throw S("INVALID_RESPONSE","Funnel control revision changed identity")}let Le=J(L,G,q.policy);if(y.signal.throwIfAborted(),I!==A)throw S("CONFIGURATION_DISPOSED","Configuration scope changed");return t=q,s=Le,g=Date.now()+Math.max(0,Le-re()),w=!1,c=0,E=0,a.writeManifest(k(q)),X(),structuredClone(q)})(),v=setTimeout(()=>y.abort(S("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs),O=new Promise((T,G)=>y.signal.addEventListener("abort",()=>G(y.signal.reason),{once:!0})),V=Promise.race([C,O]).catch(T=>{throw c++,(T instanceof Cn.ZodError||T instanceof SyntaxError||T instanceof l&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(T.code))&&(s=0,w=!0,X()),T}).finally(()=>{clearTimeout(v),N===V&&(N=void 0),K()});return N=V,V}async function fe(I){let y=I.sha256,C=Z=>new TextEncoder().encode(Z).byteLength===I.byteLength&&Xe(Z)===y;Y(I.url);let v=D.get(y);if(v&&C(v))return D.delete(y),D.set(y,v),v;if(M.has(y))return M.get(y);let O=new AbortController;_.add(O);let V=A,T=(async()=>{try{let ue=await a.readArtifact(y);if(ue&&C(ue))return P(y,ue),ue}catch{}O.signal.throwIfAborted();let Z=await u(I.url,O.signal,!0),ne=await U(Z,I.byteLength,O.signal);if(!C(ne))throw S("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(R||V!==A)throw S("CONFIGURATION_DISPOSED","Configuration scope changed");return P(y,ne),a.writeArtifact(y,ne),ne})(),G=setTimeout(()=>O.abort(S("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),H.initializationMs),L=new Promise((Z,ne)=>O.signal.addEventListener("abort",()=>ne(O.signal.reason),{once:!0})),q=Promise.race([T,L]).finally(()=>{clearTimeout(G),_.delete(O),M.delete(y)});return M.set(y,q),q}async function pe(){return f()||await z(),m(),t}async function ie(I){let y,C=new Promise((v,O)=>{y=setTimeout(()=>O(S("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs)});try{return await Promise.race([I(),C])}finally{clearTimeout(y)}}function ae(I,y){if(m(),t?.generation!==I.generation)throw S("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(y&&t.funnels[y]?.state!=="active")throw S("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function we(I){let y=I.gb.features;if(!y)throw S("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let C=I.artifacts[y];if(C.formatVersion!==1)throw S("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let v=qe.parse(JSON.parse(await fe(C)));if(k(v.scope)!==k({projectId:n.projectId,environment:n.environment})||v.generation!==C.generation||v.remoteFeatures.some(O=>Object.hasOwn(v.features,O)))throw S("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return ae(I),{...v,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,s-re())).toISOString()}}async function se(I,y){let C=await pe();ae(C,I);let v=C.funnels[I];if(v.evaluationMode!=="local")throw S("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let O=y??v.currentVersionId,V=v.versions[O];if(!V)throw S("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(C.artifacts[V.artifact].formatVersion!==3)throw S("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let T=tn(JSON.parse(await fe(C.artifacts[V.artifact]))),G=v.evaluationMode==="local"?await we(C):void 0;if(G&&k(nn(T,G))!==k(V.dependencies))throw S("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return ae(C,I),{document:T,growth:G,versionId:O,control:structuredClone(v),manifest:structuredClone(C)}}function Ie(){w=!0,X(),z().catch(ee)}let $=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ie()};function Ee(I){if(R)throw S("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return x.add(I),x.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ie),window.addEventListener("focus",$),document.addEventListener("visibilitychange",$)),K()),()=>{x.delete(I),x.size||(clearTimeout(h),clearTimeout(F),Ve())}}function Ve(){typeof window<"u"&&(window.removeEventListener("online",Ie),window.removeEventListener("focus",$),document.removeEventListener("visibilitychange",$))}return{scope:Object.freeze({...n}),refresh:z,subscribe:Ee,assertFresh:m,assertFeatures(I){m();let y=t.gb.features;if(!y)throw S("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(I!==void 0&&t.artifacts[y].generation!==I)throw S("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return f()},get snapshot(){return t?structuredClone(t):null},get remainingMs(){return f()?Math.max(0,s-re()):0},async features(){return ie(async()=>we(await pe()))},pageExperiments:()=>ie(async()=>{let I=await pe(),y=I.gb.pageExperiments;if(!y)throw S("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let C=I.artifacts[y];if(C.formatVersion!==1)throw S("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let v=Ze.parse(JSON.parse(await fe(C)));if(v.environmentId!==n.environmentId||v.generation!==C.generation)throw S("INVALID_RESPONSE","Page experiment scope or generation changed");return ae(I),v}),funnel:(I,y)=>ie(()=>se(I,y)),async localFunnel(I,y){let C=await ie(()=>se(I,y));if(!C.growth)throw S("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:v,remoteFeatures:O,...V}=C.growth;return Ye({scope:{projectId:n.projectId,environment:n.environment},funnelId:I,versionId:C.versionId,evaluationMode:"local",evaluationRevision:C.control.evaluationRevision,document:C.document,payload:V})},assertFunnel(I,y,C){m();let v=t.funnels[I];if(!v||v.state!=="active")throw S("FUNNEL_STOPPED","Funnel is paused or unavailable");if(v.evaluationMode!=="local")throw S("EVALUATION_MODE","This Funnel now executes at Indiana");if(y!==void 0&&v.controlRevision!==y)throw S("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(C!==void 0&&!v.versions[C])throw S("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!R){R=!0,A++,s=0,b?.abort(S("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(h),clearTimeout(F),Ve(),X(),x.clear();for(let I of _)I.abort(S("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));D.clear(),j=0}}}}function In(e){let n=/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey);if(typeof window<"u"&&!n)throw new l("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new l("INVALID_TOKEN","A customer credential or server API key is required");let i=ge({...e,timeoutMs:e.timeoutMs??35e3});return i.identify(e.apiKey),{async start(o){let d=te.safeParse({...o,operation:"start"});if(!d.success||d.data.operation!=="start"||(n?d.data.customer!==void 0:d.data.customer===void 0))throw new l("INVALID_REQUEST","Invalid current Funnel start");let p=d.data,r=Ae.safeParse(await i.request("funnels",p));if(!r.success||!r.data.runToken)throw new l("INVALID_RESPONSE","Funnel start credentials are missing");let a=r.data;if(a.run.source.id!==p.funnelId||a.run.locale!==(p.locale??"en")||!ye(a.run.parameters,p.parameters??{})||(p.customer?!a.customerId||p.customer.type==="id"&&a.customerId!==p.customer.value:a.customerId!==void 0))throw new l("INVALID_RESPONSE","Funnel start contract changed");return{...a,runToken:a.runToken}}}}async function Ft(e){e={...e};let n=e.configuration;if(!n)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let i={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&k(i)!==k(e.scope))throw new l("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new l("EVALUATION_MODE","This Funnel uses Remote evaluation");let d=/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.credential);if(d?!e.customerId:e.customerId!==void 0)throw new l("INVALID_REQUEST","Only Server-Key starts name their Customer");let p=In({...e,scope:i,apiKey:e.credential}),r=a=>{let t=mn({...e,scope:i,runToken:a,...d?{serverKey:e.credential}:{}});return d||t.identify(e.credential),t};return{async start(a){let t=await p.start({...a,funnelId:e.funnelId,...d?{customer:{type:"id",value:e.customerId}}:{}}),s=r(t.runToken),g=await s.get();return{...t,...g,controller:s}},async restore(a){let t=r(a),s=await t.get();if(s.run.source.id!==e.funnelId)throw t.reset(),new l("SCOPE_MISMATCH","Run belongs to another Funnel");return{...s,runToken:a,controller:t}}}}export{An as a,kn as b,ye as c,an as d,sn as e,Fe as f,hn as g,un as h,mn as i,ut as j,It as k,In as l,Ft as m};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as u}from"./chunk-5TEZEOHX.js";import{$d as M,_d as E,ae as j,be as O,ce as T}from"./chunk-
|
|
1
|
+
import{a as u}from"./chunk-5TEZEOHX.js";import{$d as M,_d as E,ae as j,be as O,ce as T}from"./chunk-VMLGV5OS.js";import{h as w}from"./chunk-RMJJOSVZ.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
|