@tinkerlandai/indiana-sdk 0.3.0 → 0.4.0

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 CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  Release facts and artifact evidence: [SDK release ledger](../../docs/sdk-releases.md). Earlier personal-package versions are preserved in [@houzhen888/groove-grow history](../../docs/sdk-changelog-groove-grow.md). The two packages have independent version histories.
4
4
 
5
+ ## Unreleased
6
+
7
+ - Separate remote Screen navigation (10 seconds), bridge handshake (5 seconds) and first render (5 seconds) startup budgets. Count visible time only, identify the timed-out phase and cancel timers/listeners on render or disposal. A slow valid document no longer consumes the bridge budget before it loads.
8
+
9
+ ## 0.4.0 — 2026-10-18
10
+
11
+ - Use protocol 0.4 with environment-scoped behavior, experiment-exposure and Feature-usage collection policies. New required delivery and tracking acknowledgement fields require a matching service release.
12
+ - Acknowledge disabled categories through `skipped`; preserve UUID/timestamp replay identity and keep database enforcement authoritative. Collection settings do not delete history or affect billable usage.
13
+ - Cache SDK collection hints for 30 seconds and refresh on demand after expiry. Identity changes clear hints; re-enabling collection resumes eligible exposure/Feature-usage recording without repeating visual changes.
14
+ - Publish on `beta`; keep `latest` unchanged. Production and native package/store rollout remain separate.
15
+
16
+ ## 0.3.1 — 2026-10-17
17
+
18
+ - Make English the default package README and include a separately linked Simplified Chinese translation.
19
+ - Update the package and SDK request version identifiers to 0.3.1; wire protocol 0.3 and business behavior are unchanged from the immutable 0.3.0 release.
20
+
5
21
  ## 0.3.0
6
22
 
7
23
  - 0.3.0 uses wire protocol 0.3 for published screen render references. Obsolete 0.2 and its fixed headerless identity are explicitly refused before business execution; no pre-1.0 compatibility adapter is provided. Existing 0.2.0 publication evidence remains immutable.
package/README.md CHANGED
@@ -1,33 +1,38 @@
1
1
  # @tinkerlandai/indiana-sdk
2
2
 
3
- Indiana 的 JavaScript/TypeScript SDK,包含浏览器、Node.js、屏幕渲染与可选 AI 用量集成。本包版本为 `0.3.0`,使用协议 `0.3`;服务端和数据库必须使用匹配的当前协议。本版本有破坏性变更,不提供旧名称、旧输入或旧数据模型的兼容层。
3
+ [简体中文](./README.zh-CN.md)
4
4
 
5
- **0.3.0 / 协议 0.3** 包含独立 Feature 下发、屏幕 render reference 与当前请求头校验。历史 0.2.0 包不能连接使用协议 0.3 的 HTTP handlers;显式或无版本头的旧 0.2 请求都在业务执行前被拒绝。
5
+ Version `0.4.0` uses protocol `0.4` for environment analytics collection controls and requires a matching Indiana server and database deployment. It is distributed on the `beta` tag; the `latest` tag remains unchanged.
6
+
7
+ Indiana's JavaScript and TypeScript SDK for browsers, Node.js, screen rendering, and optional AI usage integrations. Version `0.4.0` uses protocol `0.4` and requires a matching Indiana server and database deployment.
8
+
9
+ Protocol `0.4` includes collection policy in Feature/page/visual delivery and `skipped` tracking acknowledgements. Disabled collection keeps existing history and does not change billable usage. SDKs cache the policy for 30 seconds; the database checks each batch. Older `0.x` clients, including requests without a protocol header, are rejected before business operations run.
6
10
 
7
11
  ```sh
8
- npm install @tinkerlandai/indiana-sdk@0.3.0
12
+ npm install @tinkerlandai/indiana-sdk@0.4.0
9
13
  ```
10
14
 
11
- ## 版本兼容与支持
15
+ ## Version compatibility and support
12
16
 
13
- 当前 0.x 仅支持当前协议;1.0 起同一主版本内保持兼容。新稳定主版本发布后,旧稳定主版本至少继续支持 12 个日历月,停止支持提前至少 180 天公开通知,实际日期取两者中较晚者。详见 [版本与支持政策](../../docs/sdk-versioning-and-support.md) 和公开开发文档 `/docs/release-notes#support-policy`。
17
+ 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).
14
18
 
15
- 0.3.0 发送协议及 SDK 版本请求头,并校验成功响应的协议声明。历史 0.2.0 不发送这些请求头;服务端将无版本头的请求固定识别为 0.2,不自动跟随新协议。源码更新不会修改已有 npm 包,也不会自动部署服务端。
19
+ Version `0.4.0` 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.
16
20
 
17
- ## 一个 npm 包,六个入口
21
+ ## One package, seven entry points
18
22
 
19
- | 导入入口 | 用途 |
20
- | ---------------------------------------- | ----------------------------------------------------------- |
21
- | `@tinkerlandai/indiana-sdk` | 浏览器 Customer、Funnel、Feature 与独立 Paywall 客户端 |
22
- | `@tinkerlandai/indiana-sdk/server` | 可信 Node.js 后端、Customer Session、业务写入和 Funnel 决策 |
23
- | `@tinkerlandai/indiana-sdk/popup` | 独立屏幕渲染、清洗和预览 |
24
- | `@tinkerlandai/indiana-sdk/openrouter` | 可选 OpenRouter 用量集成,需要安装对应 peer dependency |
25
- | `@tinkerlandai/indiana-sdk/native-shell` | 原生 WebView 的静态 Funnel shell 资源;不代表商店购买验收 |
26
- | `@tinkerlandai/indiana-sdk/page` | 匿名商户页面的网址实验;使用公开的 App environment ID |
23
+ | Import | Purpose |
24
+ | ---------------------------------------- | ---------------------------------------------------------------------------------- |
25
+ | `@tinkerlandai/indiana-sdk` | Browser Customer, Funnel, Feature, and standalone Paywall clients |
26
+ | `@tinkerlandai/indiana-sdk/server` | Trusted Node.js backend, Customer Sessions, business writes, and Funnel decisions |
27
+ | `@tinkerlandai/indiana-sdk/popup` | Standalone screen rendering, sanitization, and previews |
28
+ | `@tinkerlandai/indiana-sdk/openrouter` | Optional OpenRouter usage integration; requires its peer dependency |
29
+ | `@tinkerlandai/indiana-sdk/native-shell` | Static Funnel shell assets for native WebViews |
30
+ | `@tinkerlandai/indiana-sdk/page` | Anonymous website URL experiments using a public App environment ID |
31
+ | `@tinkerlandai/indiana-sdk/visual` | Anonymous visual experiments and exposure collection using a public environment ID |
27
32
 
28
- JavaScript 与 TypeScript 共用本包,声明文件随包提供。内部 `@indiana/contracts` 在构建时内联,接入方无需安装私有包。Swift 和 Kotlin 使用各自的包管理生态,不在本次 npm 发布范围内。
33
+ 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.
29
34
 
30
- ## 从可信后端创建 Customer Session
35
+ ## Create a Customer Session from a trusted backend
31
36
 
32
37
  ```ts
33
38
  import { createIndianaServer } from "@tinkerlandai/indiana-sdk/server";
@@ -47,7 +52,7 @@ const { customer } = await indiana.getOrCreateCustomer({
47
52
  const { customerToken } = await indiana.createCustomerSession(customer.id);
48
53
  ```
49
54
 
50
- Secret Key 仅保存在可信后端。浏览器传入的 Customer ID 不能作为登录证明;将 Customer Token 交给对应的已登录用户。App、Sandbox/Live、Customer、权限和允许来源分别校验。SDK 在内存中持有客户凭据;退出或切换身份时销毁旧视图并清理凭据。
55
+ Keep the Secret Key on your trusted backend. A Customer ID supplied by a browser is not proof of login. Give each Customer Token only to the corresponding authenticated user. App, Sandbox/Live environment, Customer identity, permissions, and allowed origins are checked independently. The SDK holds Customer credentials in memory; destroy the previous view and clear credentials when signing out or changing accounts.
51
56
 
52
57
  ```ts
53
58
  import { createIndiana } from "@tinkerlandai/indiana-sdk";
@@ -58,25 +63,24 @@ const indiana = createIndiana({
58
63
  });
59
64
  indiana.identify(customerToken);
60
65
  const { holdings } = await indiana.readHoldings();
61
- // 退出账号时:
66
+ // On sign-out:
62
67
  indiana.reset();
63
68
  ```
64
69
 
65
- Customer 使用原始业务字段;资料更新是部分 patch,没有 Customer revision。Guest 登录到已有 Customer 时返回 `switched: true`,资源和历史保留原归属,接入方应为目标 Customer 创建新 Session/Funnel;不合并旧 Guest 的财务事实。
70
+ Customer updates are partial patches and do not use a Customer revision. When a Guest signs in to an existing Customer, the response reports `switched: true`. Resources and history keep their original owner; create a new Session/Funnel for the target Customer. Guest financial facts are not merged.
66
71
 
67
72
  ## Optional stable fingerprint
68
73
 
69
74
  `fingerprint` is a host-supplied stable deduplication signal, such as an installation identifier. Initialize and retain it before the first Guest/Customer request, independently of login and credentials. Reuse it across Guest identification, account changes and session renewal. The SDK does not collect or generate it.
70
75
 
71
76
  ```ts
72
- // Trusted backend fragment: installationSignal is retained by the host;
73
- // verifiedUser.id comes from the host's authenticated login.
77
+ // Trusted backend: retain installationSignal independently of login.
78
+ // verifiedUser.id comes from your application's authenticated session.
74
79
  const { customer } = await indiana.getOrCreateCustomer({
75
80
  externalUserId: verifiedUser.id,
76
81
  fingerprint: installationSignal,
77
82
  });
78
- // On Guest creation, use that same installationSignal and separately
79
- // retain/reuse guestToken for creation retries.
83
+ // Reuse the signal on Guest creation. Retain guestToken separately for retries.
80
84
  await indiana.createGuestCustomer({
81
85
  guestToken: retainedGuestToken,
82
86
  fingerprint: installationSignal,
@@ -85,23 +89,23 @@ await indiana.createGuestCustomer({
85
89
 
86
90
  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.
87
91
 
88
- 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. See the Web developer documentation's `/docs/identity#fingerprint` guide for executable HTTP host examples. Trial conflicts remain generic to clients; retain `X-Request-Id` for server-side diagnosis.
92
+ 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. See the [identity guide](https://tinker.cash/docs/identity#fingerprint) for HTTP host examples. Trial conflicts remain generic to clients; retain `X-Request-Id` for server-side diagnosis.
89
93
 
90
- ## Funnel、Feature 与独立 Paywall
94
+ ## Funnel, Feature, and standalone Paywall
91
95
 
92
- 可信后端通过 `createFunnelStartClient().start()` 提交 `funnelId`、持久保留的 `requestId`、`customer`、`locale` 和 `parameters`。`customer` 为 `{ type: "id", value: customerId }` 或 `{ type: "externalUserId", value: verifiedUser.id }`。后者可以同时提供仅用于新建的 `customerData`,需要 `customers:write` 权限;已有 Customer 不因此更新。服务端响应返回 `customerId`,后端再为它签发 Customer Session。旧的 start-body `customerToken` 和 decision `customerId` 明确拒绝。
96
+ A trusted backend calls `createFunnelStartClient().start()` with `funnelId`, a retained `requestId`, `customer`, `locale`, and `parameters`. The Customer reference is `{ type: "id", value: customerId }` or `{ type: "externalUserId", value: verifiedUser.id }`. The latter supports creation-only `customerData` and requires `customers:write`; an existing Customer is not updated. The response includes `customerId`, which your backend can use to issue a Customer Session. Historical start-body `customerToken` and decision-body `customerId` inputs are rejected.
93
97
 
94
- `createFunnelClient({ customerToken, ...options })` 用于已持有 Customer 凭据的客户端;其 `start()` 不指定 `customer` 或 `customerData`,始终以凭据所属 Customer 运行。响应丢失时保留原编号和输入重试,商业参数放在 `parameters.commerce`。运行有独立的 Run Token,不能据此切换 Customer。
98
+ `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.
95
99
 
96
- `createFunnelDecisionClient` 的 `submit/decide` 与 `/server` 的 `createFunnelCampaignClient` 同样使用明确的 `customer` 引用。Campaign 客户端提供显式 `decide/start`;受频率或进行中运行限制时,`start` 返回 `suppressed` 和重试时间,不伪造 Run 凭据。Run 实际展示后才提交 `shown`,不能用页面关闭或本地存储代替持久的展示事实。
100
+ `createFunnelDecisionClient.submit/decide` and the server entry's `createFunnelCampaignClient` use the same explicit Customer reference. Campaign `decide/start` operations report durable frequency or active-Run suppression as `suppressed` with a retry time. Report `shown` only after the Run is actually displayed; page closure or local storage cannot replace a durable presentation fact.
97
101
 
98
- 浏览器使用 `createFunnelRunController` 与 `showFunnelRun`。控制器负责当前协议的命令、读取、重试、恢复和订阅;展示句柄提供 `refresh()` 和 `destroy()`。业务操作按当前发布节点委派给服务端,客户端声明或重定向不构成付款证明。
102
+ 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.
99
103
 
100
- Local/Remote 求值策略由每个 Funnel 决定。`createFunnelDecisionClient` 支持当前 `configuration()`、`features()`、提交和结果读取;`createFeatureClient` 以 `generation` 标识配置。Local 下载的规则对客户端可见;敏感决策应使用 Remote 和可信业务事实。
104
+ Each Funnel chooses local or remote evaluation. `createFunnelDecisionClient` supports `configuration()`, `features()`, submission, and result reads. `createFeatureClient` identifies configuration by `generation`. Downloaded local rules are visible to clients; use remote evaluation and verified business facts for sensitive decisions.
101
105
 
102
- ### 独立 Feature(0.3 源码候选)
106
+ ### Standalone Feature delivery
103
107
 
104
- 后端 Key 显式授予 `features:read` / `events:write`,通过现有 Customer/Guest Session 交给浏览器,不使用新的凭证种类。
108
+ Explicitly grant a backend Key `features:read` / `events:write` and issue existing Customer/Guest Sessions to browser clients.
105
109
 
106
110
  ```ts
107
111
  const flags = await indiana.features({ attributes: { country: "CA" } });
@@ -112,36 +116,38 @@ const unsubscribe = flags.subscribe(() =>
112
116
  flags.setAttributes({ country: "US" });
113
117
  indiana.track("Checkout Viewed", { source: "pricing" });
114
118
  await indiana.flush();
115
- // 页面卸载时:
119
+ // On page teardown:
116
120
  unsubscribe();
117
121
  flags.destroy();
118
122
  ```
119
123
 
120
- 每个 flag 默认本地计算,Owner/Admin 可切换为服务器计算。服务器 flag 只下发键与结果,首次结果到达前使用调用方默认值;属性变化立即丢弃旧结果。名单哈希不等于保密,敏感规则应使用服务器计算。本地 Funnel 不得依赖服务器 flag,切换时也会校验仍在运行的历史版本。`identify` / `reset` 会释放旧身份的功能实例和事件队列。
124
+ In the unpublished 0.4 candidate, the selected environment's integration settings control behavior events, experiment exposures and Feature usage independently. New environments enable only exposure collection; existing environments retain all three. `flush()` includes a `skipped` count for intentionally disabled collection. The database rechecks every batch, including direct SDK/server and Funnel ingestion. Running experiment/Bandit dependencies prevent incompatible collection changes. These controls do not delete history or affect commercial usage accounting.
125
+
126
+ Flags default to local evaluation; Owner/Admin can switch each flag to server evaluation. Server-evaluated flags deliver only keys and results, using the caller's fallback until the first result arrives. Attribute changes immediately discard old results. List hashes are not a secrecy boundary. Local Funnels cannot depend on server-evaluated flags; mode switches also check active historical Runs. `identify` / `reset` release the previous identity's Feature instances and event queue.
121
127
 
122
- Offering 固定 Product Version 的范围与层级。Paywall 固定已发布 Offering Version,并独立选择显示的 Product 子集、分组、顺序和默认项。`createPaywallStartClient`、`createPaywallSession`、`showPaywall` 使用独立 Paywall Session,不创建占位 Funnel。付款完成后重新查询权益,业务后端仍须重新鉴权并幂等扣减用量。
128
+ Offering pins the Product Version scope and hierarchy. Paywall pins a published Offering Version and independently chooses its displayed Product subset, groups, ordering, and default selection. `createPaywallStartClient`, `createPaywallSession`, and `showPaywall` use a standalone Paywall Session. After payment, read Entitlements again. Your backend still authorizes requests and consumes usage idempotently.
123
129
 
124
- ## Web 商业能力与当前服务边界
130
+ ## Commercial capabilities and current service boundaries
125
131
 
126
- 当前服务端实现了 Customer/Guest、Entitlement 检查、持有与账本读取、用量和余额、Coupon/推荐码、Offering/独立 Paywall,以及配置后的 Stripe Sandbox attach、支付方式收集、订阅验证/更新/退款/Trial 和 License 分配路径。每个操作仍受已配置的支付账号、执行模式、Product/Price 条款和当前实现范围约束;接口存在不表示任意组合已验收。
132
+ The server implements Customer/Guest identity, Entitlement checks, holdings and ledger reads, usage and balances, Coupons/referral codes, Offering/standalone Paywall, and configured Stripe Sandbox attach, payment-method collection, subscription validation/updates/refunds/Trial, and License allocation. Each operation depends on configured payment accounts, execution mode, Product/Price terms, and its implemented scope. An API's presence does not certify every combination.
127
133
 
128
- Stripe 环境的 `autumn` 模式由 Indiana 执行;`record_only` 返回交给商户后端执行的指令。两种模式都从验证后的 Stripe 事实写入财务与权益。支付方式收集本身不产生扣款、Invoice 或额外权益。报价/确认/读取使用各自持久操作 ID;同一请求编号不能更换输入。
134
+ In Stripe environments, Indiana executes `autumn` mode; `record_only` returns instructions for the merchant backend to execute. Both record financial and Entitlement facts from verified Stripe evidence. Collecting a payment method does not itself charge, create an Invoice, or grant extra Entitlements. Quotes, confirmations, and reads retain their durable operation IDs; a request ID cannot be reused with different input.
129
135
 
130
- 本 Beta **不认证完整商业功能或生产运行**。当前仍未接通的服务包括:
136
+ This beta does not certify complete commercial or production operation. Remaining service gaps include:
131
137
 
132
- - 订阅批处理。冲突查询/重试已有对应服务,但仍需匹配部署及业务前置条件。
133
- - Postpaid Billing Authorization、Billing Coupon 列表和账单调整确认。当前 AutoTopup consent 的准备/确认/撤销已有服务,不能据此推定其他授权类型可用。
134
- - `claimRewardProduct` 的完整交付。
135
- - Apple/Google 真实商店验收。当前独立购买/恢复的协议及部分服务实现不代表商店已验收;`createNativeReceiptClient().recover()` 使用 `subscriptions/native/restore`,不再发送旧 Funnel 原生恢复命令。
138
+ - Subscription batch processing. Conflict queries and retries have services but still require a matching deployment and business prerequisites.
139
+ - Postpaid Billing Authorization, Billing Coupon lists, and billing-adjustment confirmation. AutoTopup consent preparation/confirmation/revocation is implemented independently.
140
+ - Complete delivery for `claimRewardProduct`.
141
+ - Real Apple/Google store acceptance. Independent purchase/restore contracts and partial services do not certify store acceptance. `createNativeReceiptClient().recover()` uses `subscriptions/native/restore`.
136
142
 
137
- Live 商业执行仍有显式服务端门禁。其他 Product/Price、Entity、订阅追加和数量组合,以匹配服务端的实际能力为准;不自动回退到旧实现。
143
+ Live commercial execution remains subject to explicit server gates. Other Product/Price, Entity, subscription-addition, and quantity combinations depend on the matching server's actual capabilities.
138
144
 
139
- ## AI 用量
145
+ ## AI usage
140
146
 
141
- `/server` 提供 AI SDK 用量中间件;`/openrouter` 提供 OpenRouter 包装器。宿主必须提供每次调用的持久幂等键、usage/quote 存储及恢复回调。恢复时重放原报价的扣款,不重新运行模型。密钥始终留在可信后端。
147
+ The server entry provides AI SDK usage middleware; the OpenRouter entry provides a wrapper. Your host supplies a persistent idempotency key per invocation, usage/quote storage, and recovery callbacks. Recovery replays the original quoted charge without running the model again. Keep provider keys on your trusted backend.
142
148
 
143
- ## 发布与验收
149
+ ## Publication and verification
144
150
 
145
- npm 发布不部署 Web 服务、不应用数据库迁移,也不发布 Swift/Kotlin 包。安装消费、类型、离线单元和构建检查,与真实 Auth/RLS、Stripe、原生商店、浏览器和线上部署分别记录;局部通过不代表整套产品验收。
151
+ Publishing to npm does not deploy Web services, apply database migrations, or release Swift/Kotlin packages. Package installation, types, offline unit tests, and builds are recorded separately from real Auth/RLS, Stripe, native stores, browser checks, and hosted deployment acceptance.
146
152
 
147
- 版本、冻结产物哈希和 registry 回读见 [发布总账](../../docs/sdk-releases.md);当前架构与实现边界见 [开发状态](../../docs/development-status.md)。
153
+ See the [SDK release ledger](https://github.com/tinkerlandai/Indiana/blob/main/docs/sdk-releases.md) for versions and immutable publication evidence, and the [developer documentation](https://tinker.cash/docs?lang=en) for integration guides.
@@ -0,0 +1,152 @@
1
+ [English](./README.md)
2
+
3
+ # @tinkerlandai/indiana-sdk
4
+
5
+ SDK `0.4.0` 使用协议 `0.4`,通过 `beta` 标签分发,`latest` 保持不变。服务端与数据库必须使用匹配的版本。
6
+
7
+ 当前环境的接入设置分别控制行为事件、实验曝光和 Feature 求值记录。新环境默认只开启实验曝光,已有环境保持三类全部开启。`flush()` 的 `skipped` 表示配置明确关闭的采集;SDK 将配置缓存 30 秒,数据库对每批再次检查。运行中的实验/Bandit 所需采集不能关闭。开关不删除历史,也不影响业务计费用量。
8
+
9
+ Indiana 的 JavaScript/TypeScript SDK,包含浏览器、Node.js、屏幕渲染与可选 AI 用量集成。0.x 服务只接受当前协议;旧 0.x 请求和固定为 0.2 的无版本头请求会在业务执行前被拒绝。
10
+
11
+ ```sh
12
+ npm install @tinkerlandai/indiana-sdk@0.4.0
13
+ ```
14
+
15
+ ## 版本兼容与支持
16
+
17
+ 当前 0.x 仅支持当前协议;1.0 起同一主版本内保持兼容。新稳定主版本发布后,旧稳定主版本至少继续支持 12 个日历月,停止支持提前至少 180 天公开通知,实际日期取两者中较晚者。详见 [版本与支持政策](../../docs/sdk-versioning-and-support.md) 和公开开发文档 `/docs/release-notes#support-policy`。
18
+
19
+ 0.3.0 发送协议及 SDK 版本请求头,并校验成功响应的协议声明。历史 0.2.0 不发送这些请求头;服务端将无版本头的请求固定识别为 0.2,不自动跟随新协议。源码更新不会修改已有 npm 包,也不会自动部署服务端。
20
+
21
+ ## 一个 npm 包,七个入口
22
+
23
+ | 导入入口 | 用途 |
24
+ | ---------------------------------------- | ----------------------------------------------------------- |
25
+ | `@tinkerlandai/indiana-sdk` | 浏览器 Customer、Funnel、Feature 与独立 Paywall 客户端 |
26
+ | `@tinkerlandai/indiana-sdk/server` | 可信 Node.js 后端、Customer Session、业务写入和 Funnel 决策 |
27
+ | `@tinkerlandai/indiana-sdk/popup` | 独立屏幕渲染、清洗和预览 |
28
+ | `@tinkerlandai/indiana-sdk/openrouter` | 可选 OpenRouter 用量集成,需要安装对应 peer dependency |
29
+ | `@tinkerlandai/indiana-sdk/native-shell` | 原生 WebView 的静态 Funnel shell 资源;不代表商店购买验收 |
30
+ | `@tinkerlandai/indiana-sdk/page` | 匿名商户页面的网址实验;使用公开的 App environment ID |
31
+ | `@tinkerlandai/indiana-sdk/visual` | 匿名商户页面的视觉实验及曝光采集;使用公开的环境 ID |
32
+
33
+ JavaScript 与 TypeScript 共用本包,声明文件随包提供。内部 `@indiana/contracts` 在构建时内联,接入方无需安装私有包。Swift 和 Kotlin 使用各自的包管理生态,不在本次 npm 发布范围内。
34
+
35
+ ## 从可信后端创建 Customer Session
36
+
37
+ ```ts
38
+ import { createIndianaServer } from "@tinkerlandai/indiana-sdk/server";
39
+
40
+ const indiana = createIndianaServer({
41
+ baseUrl: process.env.INDIANA_BASE_URL!,
42
+ apiKey: process.env.INDIANA_SECRET_KEY!,
43
+ scope: {
44
+ projectId: process.env.INDIANA_PROJECT_ID!,
45
+ environment: "sandbox",
46
+ },
47
+ });
48
+ const user = await requireSignedInUser(request);
49
+ const { customer } = await indiana.getOrCreateCustomer({
50
+ externalUserId: user.id,
51
+ });
52
+ const { customerToken } = await indiana.createCustomerSession(customer.id);
53
+ ```
54
+
55
+ Secret Key 仅保存在可信后端。浏览器传入的 Customer ID 不能作为登录证明;将 Customer Token 交给对应的已登录用户。App、Sandbox/Live、Customer、权限和允许来源分别校验。SDK 在内存中持有客户凭据;退出或切换身份时销毁旧视图并清理凭据。
56
+
57
+ ```ts
58
+ import { createIndiana } from "@tinkerlandai/indiana-sdk";
59
+
60
+ const indiana = createIndiana({
61
+ baseUrl,
62
+ scope: { projectId, environment: "sandbox" },
63
+ });
64
+ indiana.identify(customerToken);
65
+ const { holdings } = await indiana.readHoldings();
66
+ // 退出账号时:
67
+ indiana.reset();
68
+ ```
69
+
70
+ Customer 使用原始业务字段;资料更新是部分 patch,没有 Customer revision。Guest 登录到已有 Customer 时返回 `switched: true`,资源和历史保留原归属,接入方应为目标 Customer 创建新 Session/Funnel;不合并旧 Guest 的财务事实。
71
+
72
+ ## Optional stable fingerprint
73
+
74
+ `fingerprint` is a host-supplied stable deduplication signal, such as an installation identifier. Initialize and retain it before the first Guest/Customer request, independently of login and credentials. Reuse it across Guest identification, account changes and session renewal. The SDK does not collect or generate it.
75
+
76
+ ```ts
77
+ // Trusted backend fragment: installationSignal is retained by the host;
78
+ // verifiedUser.id comes from the host's authenticated login.
79
+ const { customer } = await indiana.getOrCreateCustomer({
80
+ externalUserId: verifiedUser.id,
81
+ fingerprint: installationSignal,
82
+ });
83
+ // On Guest creation, use that same installationSignal and separately
84
+ // retain/reuse guestToken for creation retries.
85
+ await indiana.createGuestCustomer({
86
+ guestToken: retainedGuestToken,
87
+ fingerprint: installationSignal,
88
+ });
89
+ ```
90
+
91
+ 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.
92
+
93
+ 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. See the Web developer documentation's `/docs/identity#fingerprint` guide for executable HTTP host examples. Trial conflicts remain generic to clients; retain `X-Request-Id` for server-side diagnosis.
94
+
95
+ ## Funnel、Feature 与独立 Paywall
96
+
97
+ 可信后端通过 `createFunnelStartClient().start()` 提交 `funnelId`、持久保留的 `requestId`、`customer`、`locale` 和 `parameters`。`customer` 为 `{ type: "id", value: customerId }` 或 `{ type: "externalUserId", value: verifiedUser.id }`。后者可以同时提供仅用于新建的 `customerData`,需要 `customers:write` 权限;已有 Customer 不因此更新。服务端响应返回 `customerId`,后端再为它签发 Customer Session。旧的 start-body `customerToken` 和 decision `customerId` 明确拒绝。
98
+
99
+ `createFunnelClient({ customerToken, ...options })` 用于已持有 Customer 凭据的客户端;其 `start()` 不指定 `customer` 或 `customerData`,始终以凭据所属 Customer 运行。响应丢失时保留原编号和输入重试,商业参数放在 `parameters.commerce`。运行有独立的 Run Token,不能据此切换 Customer。
100
+
101
+ `createFunnelDecisionClient` 的 `submit/decide` 与 `/server` 的 `createFunnelCampaignClient` 同样使用明确的 `customer` 引用。Campaign 客户端提供显式 `decide/start`;受频率或进行中运行限制时,`start` 返回 `suppressed` 和重试时间,不伪造 Run 凭据。Run 实际展示后才提交 `shown`,不能用页面关闭或本地存储代替持久的展示事实。
102
+
103
+ 浏览器使用 `createFunnelRunController` 与 `showFunnelRun`。控制器负责当前协议的命令、读取、重试、恢复和订阅;展示句柄提供 `refresh()` 和 `destroy()`。业务操作按当前发布节点委派给服务端,客户端声明或重定向不构成付款证明。
104
+
105
+ Local/Remote 求值策略由每个 Funnel 决定。`createFunnelDecisionClient` 支持当前 `configuration()`、`features()`、提交和结果读取;`createFeatureClient` 以 `generation` 标识配置。Local 下载的规则对客户端可见;敏感决策应使用 Remote 和可信业务事实。
106
+
107
+ ### 独立 Feature
108
+
109
+ 后端 Key 显式授予 `features:read` / `events:write`,通过现有 Customer/Guest Session 交给浏览器,不使用新的凭证种类。
110
+
111
+ ```ts
112
+ const flags = await indiana.features({ attributes: { country: "CA" } });
113
+ const enabled = flags.getFeatureValue("new-checkout", false);
114
+ const unsubscribe = flags.subscribe(() =>
115
+ updateView(flags.isOn("new-checkout")),
116
+ );
117
+ flags.setAttributes({ country: "US" });
118
+ indiana.track("Checkout Viewed", { source: "pricing" });
119
+ await indiana.flush();
120
+ // 页面卸载时:
121
+ unsubscribe();
122
+ flags.destroy();
123
+ ```
124
+
125
+ 每个 flag 默认本地计算,Owner/Admin 可切换为服务器计算。服务器 flag 只下发键与结果,首次结果到达前使用调用方默认值;属性变化立即丢弃旧结果。名单哈希不等于保密,敏感规则应使用服务器计算。本地 Funnel 不得依赖服务器 flag,切换时也会校验仍在运行的历史版本。`identify` / `reset` 会释放旧身份的功能实例和事件队列。
126
+
127
+ Offering 固定 Product Version 的范围与层级。Paywall 固定已发布 Offering Version,并独立选择显示的 Product 子集、分组、顺序和默认项。`createPaywallStartClient`、`createPaywallSession`、`showPaywall` 使用独立 Paywall Session,不创建占位 Funnel。付款完成后重新查询权益,业务后端仍须重新鉴权并幂等扣减用量。
128
+
129
+ ## Web 商业能力与当前服务边界
130
+
131
+ 当前服务端实现了 Customer/Guest、Entitlement 检查、持有与账本读取、用量和余额、Coupon/推荐码、Offering/独立 Paywall,以及配置后的 Stripe Sandbox attach、支付方式收集、订阅验证/更新/退款/Trial 和 License 分配路径。每个操作仍受已配置的支付账号、执行模式、Product/Price 条款和当前实现范围约束;接口存在不表示任意组合已验收。
132
+
133
+ Stripe 环境的 `autumn` 模式由 Indiana 执行;`record_only` 返回交给商户后端执行的指令。两种模式都从验证后的 Stripe 事实写入财务与权益。支付方式收集本身不产生扣款、Invoice 或额外权益。报价/确认/读取使用各自持久操作 ID;同一请求编号不能更换输入。
134
+
135
+ 本 Beta **不认证完整商业功能或生产运行**。当前仍未接通的服务包括:
136
+
137
+ - 订阅批处理。冲突查询/重试已有对应服务,但仍需匹配部署及业务前置条件。
138
+ - Postpaid Billing Authorization、Billing Coupon 列表和账单调整确认。当前 AutoTopup consent 的准备/确认/撤销已有服务,不能据此推定其他授权类型可用。
139
+ - `claimRewardProduct` 的完整交付。
140
+ - Apple/Google 真实商店验收。当前独立购买/恢复的协议及部分服务实现不代表商店已验收;`createNativeReceiptClient().recover()` 使用 `subscriptions/native/restore`,不再发送旧 Funnel 原生恢复命令。
141
+
142
+ Live 商业执行仍有显式服务端门禁。其他 Product/Price、Entity、订阅追加和数量组合,以匹配服务端的实际能力为准;不自动回退到旧实现。
143
+
144
+ ## AI 用量
145
+
146
+ `/server` 提供 AI SDK 用量中间件;`/openrouter` 提供 OpenRouter 包装器。宿主必须提供每次调用的持久幂等键、usage/quote 存储及恢复回调。恢复时重放原报价的扣款,不重新运行模型。密钥始终留在可信后端。
147
+
148
+ ## 发布与验收
149
+
150
+ npm 发布不部署 Web 服务、不应用数据库迁移,也不发布 Swift/Kotlin 包。安装消费、类型、离线单元和构建检查,与真实 Auth/RLS、Stripe、原生商店、浏览器和线上部署分别记录;局部通过不代表整套产品验收。
151
+
152
+ 版本、冻结产物哈希和 registry 回读见 [发布总账](../../docs/sdk-releases.md);当前架构与实现边界见 [开发状态](../../docs/development-status.md)。
@@ -44,3 +44,31 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44
44
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
45
45
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
46
46
  THE SOFTWARE.
47
+
48
+
49
+ # dom-mutator 0.7.0
50
+
51
+ GrowthBook declarative DOM mutations use the original `dom-mutator` package.
52
+ Source: https://github.com/growthbook/dom-mutator
53
+
54
+ MIT License
55
+
56
+ Copyright (c) 2021 Jeremy Dorn
57
+
58
+ Permission is hereby granted, free of charge, to any person obtaining a copy
59
+ of this software and associated documentation files (the "Software"), to deal
60
+ in the Software without restriction, including without limitation the rights
61
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
62
+ copies of the Software, and to permit persons to whom the Software is
63
+ furnished to do so, subject to the following conditions:
64
+
65
+ The above copyright notice and this permission notice shall be included in all
66
+ copies or substantial portions of the Software.
67
+
68
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
69
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
70
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
71
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
72
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
73
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
74
+ SOFTWARE.
@@ -197,6 +197,11 @@ declare const apiOperations: {
197
197
  name: z.ZodOptional<z.ZodString>;
198
198
  phase: z.ZodOptional<z.ZodString>;
199
199
  }, z.core.$strict>>;
200
+ analyticsConfig: z.ZodObject<{
201
+ eventsEnabled: z.ZodBoolean;
202
+ experimentViewsEnabled: z.ZodBoolean;
203
+ featureUsageEnabled: z.ZodBoolean;
204
+ }, z.core.$strict>;
200
205
  remoteFeatures: z.ZodArray<z.ZodString>;
201
206
  }, z.core.$strict>;
202
207
  }, z.core.$strict>;
@@ -282,6 +287,12 @@ declare const apiOperations: {
282
287
  inserted: z.ZodNumber;
283
288
  duplicates: z.ZodNumber;
284
289
  rejected: z.ZodNumber;
290
+ skipped: z.ZodNumber;
291
+ analyticsConfig: z.ZodObject<{
292
+ eventsEnabled: z.ZodBoolean;
293
+ experimentViewsEnabled: z.ZodBoolean;
294
+ featureUsageEnabled: z.ZodBoolean;
295
+ }, z.core.$strict>;
285
296
  }, z.core.$strict>;
286
297
  };
287
298
  readonly readBalanceSource: {
@@ -0,0 +1,4 @@
1
+ import{c as U,d as L,g as A}from"./chunk-TZ6REIUE.js";function T(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let i of document.cookie.split(";"))if(i.trim().startsWith(`${e}=`))try{t=decodeURIComponent(i.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function V(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function $(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var v=new Set,x;function D(e){if(v.add(e),!x){let t=history.pushState,i=history.replaceState,r=()=>{for(let s of v)s()},o=function(...s){t.apply(this,s),r()},c=function(...s){i.apply(this,s),r()};history.pushState=o,history.replaceState=c,addEventListener("popstate",r),addEventListener("hashchange",r),x=()=>{history.pushState===o&&(history.pushState=t),history.replaceState===c&&(history.replaceState=i),removeEventListener("popstate",r),removeEventListener("hashchange",r)}}return()=>{v.delete(e),v.size||(x?.(),x=void 0)}}var C="__indiana_visual_editor",d;function M(e,t){if(d&&d.origin===e&&d.environmentId===t&&d.expiresAt>Date.now())return d;try{let i=new URL(location.href).searchParams.get(C);if(!i||i.length>2048)return null;let r=JSON.parse(i);return r.origin!==e||r.environmentId!==t||!/^[a-f0-9-]{36}$/i.test(r.nonce)||r.expiresAt<=Date.now()||r.expiresAt>Date.now()+900*1e3?null:(d=r,r)}catch{return null}}function O(e,t){return!!M(e,t)}function Q(){let e=new URL(location.href);e.searchParams.delete(C),history.replaceState(history.state,"",e.href)}/*!
2
+ Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
3
+ plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
4
+ */function z(e,t){let i,r;try{i=new URL(e),r=new URL(t)}catch{return t}return i.searchParams.forEach((o,c)=>{r.searchParams.has(c)||r.searchParams.set(c,o)}),r.toString()}function W(e,t){let i=navigator.userAgent,r=new URLSearchParams(t.search),o={};for(let c of["source","medium","campaign","term","content"]){let s=r.get(`utm_${c}`);s!==null&&(o[`utm${c[0].toUpperCase()}${c.slice(1)}`]=s)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(i)?"edge":/Chrome/.test(i)?"chrome":/Firefox/.test(i)?"firefox":/Safari/.test(i)?"safari":"unknown",deviceType:/Mobi/.test(i)?"mobile":"desktop",...o}}function F(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(r=>!!r&&!["namespace","status","url","groups"].some(o=>Object.hasOwn(r,o))&&(r.hashVersion===void 0||r.hashVersion===2)&&typeof r.key=="string"&&Array.isArray(r.variations)&&r.variations.length>=2&&r.variations.every(o=>!!o&&typeof o.urlRedirect=="string")&&(r.urlPatterns===void 0||Array.isArray(r.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function ee(e){let t=$(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let i=e.fetch??globalThis.fetch.bind(globalThis),r=`${t}/api/v1/page-experiments/${e.environmentId}`,o=T(e.deviceIdCookie??"indiana_did"),c=V(),s=null,R={...e.attributes??{}},m="",E=!1,I=new Map,P=[],g;function _(n){return n.length?i(`${r}/events`,{method:"POST",body:JSON.stringify({events:n}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"}).then(()=>{}).catch(a=>e.log?.("Exposure not sent",{error:a})):Promise.resolve()}function f(){return clearTimeout(g),g=void 0,_(P.splice(0,20))}let l={trackedExperiments:new Set,log:e.log,onExperimentViewed:(n,a)=>{e.trackExposures===!1||s?.trackExposures===!1||(P.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:o,...c?{sessionId:c}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:n.key,variationKey:a.key}),g||(g=setTimeout(()=>{f()},1e3)))}},N=()=>{l.url=location.href,l.attributes={...W(o,location),...R}};function G(n){if(!e.disableCrossOriginUrlRedirects)return!1;try{let a=new URL(location.href);return n.variations.some(u=>{if(!u.urlRedirect)return!1;let y=new URL(u.urlRedirect);return y.protocol!==a.protocol||y.host!==a.host})}catch{return!0}}function J(n,a){m=n;let u=e.navigate??(p=>location.replace(p)),y=e.navigateDelay??(e.navigate?0:100),q=e.maxNavigateDelay??1e3;Promise.all([Promise.race([a,new Promise(p=>setTimeout(p,q))]),new Promise(p=>setTimeout(p,y))]).then(()=>{E||u(n)})}function h(){if(!(!s||E||O(t,e.environmentId))){N();for(let n of s.experiments){if(G(n)){e.log?.("Auto experiment blocked",{id:n.key});continue}let a;try{a=A(n,l)}catch(u){e.log?.("Skipping page experiment",{id:n.key,error:String(u)});continue}if(I.set(n.key,a),!!a.inExperiment){if(a.value.urlRedirect){let u=n.persistQueryString?z(location.href,a.value.urlRedirect):a.value.urlRedirect;U(u,n.urlPatterns??[])?e.log?.("Skipping redirect because original URL matches redirect URL",{id:n.key}):u!==m&&J(u,f())}break}}}}let w="",H=()=>{location.href!==w&&(w=location.href,m="",h())},b;function j(){b??=D(H),addEventListener("pagehide",S)}let S=()=>{f()};async function k(){let n=await i(r,{cache:"no-cache",credentials:"omit"});if(!n.ok)throw new Error(`Page experiments unavailable (${n.status})`);let a=F(await n.json());if(a.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");s?.trackExposures===!1&&a.trackExposures&&l.trackedExperiments?.clear(),s=a,l.savedGroups=L(a.savedGroups)}return{async start(){await k(),j(),w=location.href,h()},async refresh(){await k(),m="",h()},setAttributes(n){R={...n},h()},getResults(){return new Map(I)},get generation(){return s?.generation??null},destroy(){E=!0,b?.(),removeEventListener("pagehide",S),f()}}}export{T as a,V as b,$ as c,D as d,M as e,Q as f,z as g,W as h,F as i,ee as j};
@@ -0,0 +1 @@
1
+ import{Y as S,_b as C,gc as k,jc as L,mc as T,nc as v,oc as j,rc as R,yi as V}from"./chunk-PVJKOUNE.js";var U={name:"@tinkerlandai/indiana-sdk",version:"0.4.0",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"},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 e=class extends Error{constructor(h,d,n,N,i){super(d);this.code=h;this.status=n;this.requestId=N;this.name="IndianaError",this.reason=i?.reason;let c=T(h,n??0,{...i,retryAfter:i?.retryAfterSeconds===void 0?void 0:String(i.retryAfterSeconds)});this.retryable=c.retryable,this.recovery=c.recovery,this.retryAfterSeconds=c.retryAfterSeconds}code;status;requestId;retryable;recovery;retryAfterSeconds;reason},$=Symbol("IndianaNoContent");function J(l,A){let h=l.webView??"hosted";if(!["hosted","embedded"].includes(h))throw new e("INVALID_REQUEST","Invalid Web View mode");let d=l.scope?S.parse(l.scope):void 0,n=new URL(l.baseUrl);if(n.username||n.password||n.search||n.hash)throw new e("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw new e("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let N=l.fetch??globalThis.fetch.bind(globalThis),i=l.timeoutMs??1e4;if(!Number.isFinite(i)||i<=0||i>12e4)throw new e("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let c=null,b,u=0,p=null,f=new Set;function D(){u+=1,c=null,p=null;for(let s of f)s.abort();f.clear()}async function M(s,q={},O="POST",H={}){if(!c)throw new e("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let g=u,o=new AbortController;f.add(o);let y=()=>g!==u?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new e("TIMEOUT","Indiana request timed out"),I,x=new Promise((r,a)=>{I=()=>a(y()),o.signal.addEventListener("abort",I,{once:!0})}),K=setTimeout(()=>o.abort(),i),G=async()=>{let r=await N(`${n.href.replace(/\/$/,"")}/api/v1/${s}`,{method:O,headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`,[v]:R.current,[j]:U.version,...d?{"X-Indiana-Project":d.projectId,"X-Indiana-Environment":d.environment}:{}},body:O==="POST"?JSON.stringify(q):void 0,signal:o.signal,credentials:"omit",cache:"no-store",redirect:"error",...H.keepalive?{keepalive:!0}:{}});if(o.signal.aborted)throw y();let a;try{a=r.status===204?$:await r.json()}catch{throw o.signal.aborted?y():new e(r.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",r.status,r.headers.get("X-Request-Id")??void 0)}if(o.signal.aborted)throw y();if(g!==u)throw new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!r.ok){let t=L.safeParse(a),m=t.success&&(!C.safeParse(t.data.error.code).success||k(t.data.error.code,r.status)),_=m?t.data.error.code:"HTTP_ERROR",P=T(_,r.status,{retryAfter:r.headers.get("Retry-After"),recovery:m?t.data.error.recovery:void 0,reason:m?t.data.error.reason:void 0});throw new e(_,m?t.data.error.message:"Indiana request failed",r.status,r.headers.get("X-Request-Id")??(t.success?t.data.requestId:void 0),{...P,...t.success&&t.data.error.retryable===!1?{retryable:!1}:{},...P.retryAfterSeconds===void 0&&t.success&&t.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:t.data.error.retryAfterSeconds}:{}})}if(r.headers.get(v)!==R.current)throw new e("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(d&&a&&typeof a=="object"&&"scope"in a){let t=S.safeParse(a.scope);if(!t.success||t.data.projectId!==d.projectId||t.data.environment!==d.environment)throw new e("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let E=r.headers.get("X-Indiana-Web-View");if(E){if(!/^\/web-view\/renderer\/[a-f0-9]{64}$/.test(E))throw new e("INVALID_RESPONSE","Invalid Web View renderer metadata");b=E}let w=r.headers.get("X-Indiana-Telemetry-Subject");if(w){if(!/^[a-f0-9]{64}$/.test(w))throw new e("INVALID_RESPONSE","Invalid telemetry identity");p!==w&&(p=w,A?.(p))}return a};try{return await Promise.race([G(),x])}catch(r){throw g!==u?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):r instanceof e?r:new e(o.signal.aborted?"TIMEOUT":"NETWORK_ERROR",o.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(K),o.signal.removeEventListener("abort",I),f.delete(o)}}return{subjectKey:()=>p,screenUrl(s){if(!V.safeParse(s).success)throw new e("INVALID_RESPONSE","Invalid published screen render address");return new URL(s,n).href},webViewUrl(){if(h!=="embedded"){if(!b)throw new e("INVALID_RESPONSE","The gateway did not provide a hosted Web View renderer");return new URL(b,n).href}},identify(s){if(!s.trim()||/\s/.test(s)||s.length>4096)throw new e("INVALID_TOKEN","A nonempty server-issued token is required");D(),c=s},reset:D,request:M}}export{e as a,J as b};