@tinkerlandai/longplay-sdk 0.10.35 → 0.10.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +42 -3
  3. package/README.zh-CN.md +14 -0
  4. package/dist/{ai-usage-T62xehqa.d.ts → ai-usage-DXwAGTxT.d.ts} +1 -1
  5. package/dist/{api-Do-6AyWa.d.ts → api-r6FfVQpg.d.ts} +6 -1
  6. package/dist/check-response-N22NNTIT.js +1 -0
  7. package/dist/chunk-2HBIBIOF.js +1 -0
  8. package/dist/{chunk-73NP72FV.js → chunk-2KJLN65C.js} +1 -1
  9. package/dist/{chunk-RML52BOR.js → chunk-2VMEDQHT.js} +1 -1
  10. package/dist/{chunk-CIP5SQ5Y.js → chunk-4KLXQKNO.js} +1 -1
  11. package/dist/{chunk-FMDC6N4W.js → chunk-6F4JS3RK.js} +1 -1
  12. package/dist/{chunk-56BYGPQ6.js → chunk-7XDQKZYA.js} +1 -1
  13. package/dist/{chunk-VEX2FOFZ.js → chunk-AB7GEGZ2.js} +1 -1
  14. package/dist/{chunk-EM3MGDPG.js → chunk-AHUYZ6IW.js} +1 -1
  15. package/dist/chunk-AOGDCT4T.js +1 -0
  16. package/dist/{chunk-EUTWY7A2.js → chunk-CY7OKV7E.js} +1 -1
  17. package/dist/{chunk-7MNJH5GB.js → chunk-D3OYXTMC.js} +1 -1
  18. package/dist/chunk-DDLSQSWO.js +10 -0
  19. package/dist/{chunk-5HJYR6Z4.js → chunk-E7CCHUSO.js} +1 -1
  20. package/dist/{chunk-BOVN2BE3.js → chunk-ECKVJGXQ.js} +1 -1
  21. package/dist/chunk-GH6FM44P.js +1 -0
  22. package/dist/{chunk-TJGIT5CU.js → chunk-HEHLFHW7.js} +1 -1
  23. package/dist/chunk-HKXFCRVT.js +1 -0
  24. package/dist/chunk-KFIL73QY.js +1 -0
  25. package/dist/{chunk-44U3FOBB.js → chunk-LC6UCDWE.js} +1 -1
  26. package/dist/{chunk-KE26KWIU.js → chunk-LOLMUXHW.js} +1 -1
  27. package/dist/{chunk-7QL4GF4C.js → chunk-O4KXODTJ.js} +1 -1
  28. package/dist/{chunk-TLZP7BW6.js → chunk-OCWSWXCW.js} +1 -1
  29. package/dist/chunk-OQRMAU2B.js +1 -0
  30. package/dist/{chunk-SXBM3DWK.js → chunk-OX2A3UD2.js} +1 -1
  31. package/dist/{chunk-LF2UIJYD.js → chunk-PW5PIBSO.js} +1 -1
  32. package/dist/chunk-Q676H74B.js +1 -0
  33. package/dist/chunk-RE4OLOOT.js +1 -0
  34. package/dist/{chunk-CKKIB2HC.js → chunk-S43TYW3V.js} +1 -1
  35. package/dist/{chunk-U4RSRFZY.js → chunk-T2KWLYCW.js} +1 -1
  36. package/dist/chunk-TASEZY5T.js +1 -0
  37. package/dist/{chunk-OX7PA64E.js → chunk-U7NX5ET2.js} +1 -1
  38. package/dist/{chunk-WZR2XCSJ.js → chunk-UV4H6VCS.js} +1 -1
  39. package/dist/{chunk-MSK3VZ3A.js → chunk-VIBJNB5B.js} +1 -1
  40. package/dist/chunk-VLSP3LRH.js +1 -0
  41. package/dist/{chunk-W6OQTXLL.js → chunk-W74JLL2O.js} +1 -1
  42. package/dist/chunk-WQ3O5RXN.js +1 -0
  43. package/dist/chunk-WZMZMJCK.js +1 -0
  44. package/dist/chunk-XGNXZWZL.js +1 -0
  45. package/dist/{chunk-VYFSRHXM.js → chunk-XJRDO3NI.js} +1 -1
  46. package/dist/chunk-YV6UFESO.js +1 -0
  47. package/dist/{chunk-KPDHY76A.js → chunk-ZYOZSUZS.js} +1 -1
  48. package/dist/chunk-ZZIBLQCJ.js +1 -0
  49. package/dist/{configuration-sync-DdTRUv7A.d.ts → configuration-sync-BHrAf-ql.d.ts} +10 -1
  50. package/dist/content-QNBATPA2.js +1 -0
  51. package/dist/{funnel-host-purchase-Z7FCJ5CX.js → funnel-host-purchase-FVYPBPET.js} +1 -1
  52. package/dist/{funnel-local-client-Dz1dTgES.d.ts → funnel-local-client-DR8OpKGU.d.ts} +145 -3
  53. package/dist/funnel-paywall-prerender-Z7RA4YDY.js +1 -0
  54. package/dist/{funnel-process-client-D6qjStm2.d.ts → funnel-process-client-C87U4r_G.d.ts} +17 -3
  55. package/dist/funnel-runtime-host-TJPF3FJS.js +1 -0
  56. package/dist/index.d.ts +49 -12
  57. package/dist/index.js +1 -1
  58. package/dist/merchant-bridge-contracts-67AYXZFI.js +1 -0
  59. package/dist/native-shell.js +1 -1
  60. package/dist/openrouter.d.ts +3 -3
  61. package/dist/openrouter.js +1 -1
  62. package/dist/operation-contracts-EK4RCUWJ.js +1 -0
  63. package/dist/page.d.ts +2 -2
  64. package/dist/page.js +1 -1
  65. package/dist/paywall-OAVC654P.js +1 -0
  66. package/dist/paywall-content-75XEM7K3.js +1 -0
  67. package/dist/paywall-session-U6SPRJRS.js +1 -0
  68. package/dist/popup.d.ts +4 -4
  69. package/dist/popup.js +1 -1
  70. package/dist/{presentation-loading-CFSiS0VX.d.ts → presentation-loading-B_v5XZtM.d.ts} +11 -1
  71. package/dist/react-native.d.ts +7 -7
  72. package/dist/react-native.js +1 -1
  73. package/dist/{screen-CGCJ46b1.d.ts → screen-qUBRsUi9.d.ts} +26 -21
  74. package/dist/screen-renderer-YIIT742O.js +1 -0
  75. package/dist/server.d.ts +37 -7
  76. package/dist/server.js +1 -1
  77. package/dist/{visual-dom-6DCUZGPB.js → visual-dom-5LUN4AHO.js} +1 -1
  78. package/dist/visual.js +1 -1
  79. package/package.json +10 -9
  80. package/dist/check-response-GZZRWBEA.js +0 -1
  81. package/dist/chunk-2FE4FTPH.js +0 -1
  82. package/dist/chunk-BLVBUN2R.js +0 -1
  83. package/dist/chunk-BQRS7Y4K.js +0 -1
  84. package/dist/chunk-ETK6GC5P.js +0 -1
  85. package/dist/chunk-GZRRVHYK.js +0 -1
  86. package/dist/chunk-PUR5CYWX.js +0 -1
  87. package/dist/chunk-RNEF4MZW.js +0 -1
  88. package/dist/chunk-SFHIFCXG.js +0 -1
  89. package/dist/chunk-TAFALMQN.js +0 -1
  90. package/dist/chunk-TOTRALYQ.js +0 -10
  91. package/dist/chunk-UVRT4MY6.js +0 -1
  92. package/dist/chunk-V7MMTILA.js +0 -1
  93. package/dist/chunk-V7PFLFHE.js +0 -1
  94. package/dist/chunk-XUGEOELU.js +0 -1
  95. package/dist/chunk-YVXLCQGM.js +0 -1
  96. package/dist/chunk-ZGCKQWQ5.js +0 -1
  97. package/dist/content-AJDTSI7A.js +0 -1
  98. package/dist/funnel-paywall-prerender-QHCUZZY3.js +0 -1
  99. package/dist/funnel-runtime-host-UKSOOA4H.js +0 -1
  100. package/dist/merchant-bridge-contracts-EAE4HQE4.js +0 -1
  101. package/dist/operation-contracts-HS4M2UXN.js +0 -1
  102. package/dist/paywall-VYUBYBUI.js +0 -1
  103. package/dist/paywall-content-YQAVSO2T.js +0 -1
  104. package/dist/paywall-session-E5V42XUT.js +0 -1
  105. package/dist/screen-renderer-R5GH7XLV.js +0 -1
  106. /package/dist/{chunk-BID4UGWB.js → chunk-CILM5XMH.js} +0 -0
  107. /package/dist/{chunk-VF6QMMEA.js → chunk-CR2XJ2CX.js} +0 -0
  108. /package/dist/{chunk-UKMEW5I7.js → chunk-OJM6ORHE.js} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.37
4
+
5
+ - Add `preloadFunnelPurchase()`. It downloads the code a Funnel purchase presents with, before any Customer is known, and makes no request and no DOM change.
6
+ - A purchase button can carry the Coupon its Paywall displays. With `claimCoupon`, the SDK claims that Coupon at the click, quotes with its offer, and refuses a quote that did not apply it. A button bound to a Coupon does not call `resolveOfferId`.
7
+ - A prepaid quantity that adds nothing to the price keeps the plan's discounted price on the Paywall.
8
+ - A Funnel Content screen with its own usable Close control hides the SDK's Close button, and shows it again when that control goes away.
9
+ - An empty purchase pre-read stays behind the host's loading state until the Run presents its Paywall.
10
+ - Wire protocol remains `0.10`.
11
+
3
12
  ## 0.10.35
4
13
 
5
14
  - Pre-render the first Funnel Paywall before opening. The matching Run takes over the rendered Paywall. The published layout supplies a loading skeleton while the Paywall is getting ready.
package/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  # @tinkerlandai/longplay-sdk
8
8
 
9
- The SDK release version is the `version` field in [`package.json`](package.json); the wire protocol is 0.10. These examples use `https://api.longplayai.com` with a Sandbox App and credentials issued by the production deployment. Sandbox still contains production data; do not reuse credentials from the separate test deployment. Confirm runtime readiness in [environment state](../../docs/development-status.md) before running them.
9
+ The SDK release version is the `version` field in [`package.json`](package.json); the wire protocol is 0.10. These examples use `https://api.longplayai.com` with a Sandbox App and credentials issued by the production deployment. Sandbox still contains production data. Confirm runtime readiness in [environment state](../../docs/development-status.md) before running them.
10
10
 
11
11
  [简体中文](./README.zh-CN.md)
12
12
 
@@ -97,17 +97,19 @@ For an independent **Page, Popup or Banner resource**, import `createLongplay` a
97
97
 
98
98
  The Web SDK displays a local placeholder while a Paywall, Funnel screen, Page, Popup or Banner prepares its first render. To supply a merchant placeholder, pass `loading: "host"` and use `onPresentationState`. The `loading` event provides `dismiss()`. Remove the placeholder on `ready`, `dismissed`, `skipped` or `error`. Use `ready` for the visual handoff even when the mount promise has already returned. Pass an `AbortSignal` as `signal` when the host can unmount or change Customers. Content resolved separately begins this lifecycle at `mountContent`. Preparation through `prepareContent` or `preparePopup` stays hidden until `show()`. Purchase progress and original-operation recovery continue through their existing APIs.
99
99
 
100
+ To show a skeleton that matches a published Paywall, load the layout ahead of time with `configuration.paywall(paywallId)` and pass its `document` as `loadingDocument` to `showPaywall` or `showFunnelPurchase`. The SDK renders the layout with inert controls and provides a Close button while loading. The live Paywall supplies the actionable content. When its current page has a usable Close button, that button takes over from the SDK's Close control.
101
+
100
102
  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. It is distributed from `https://cdn.longplayai.com/sdk/python` (not PyPI) and is not part of this npm package.
101
103
 
102
104
  The [Go server SDK](../go/README.md) provides the same initial capabilities with typed responses, Context cancellation and goroutine-safe client reuse. It is installed with `go get longplayai.com/sdk/go` through the default Go module proxy and has its own independent package version ([SDK distribution](../../docs/sdk-releases.md)).
103
105
 
104
- ## API origin and test services
106
+ ## API origin
105
107
 
106
108
  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).
107
109
 
108
110
  Omitting `baseUrl` selects `https://api.longplayai.com`. This applies to Customer/Server, Funnel, Feature, Paywall, page and visual clients. `createConfigurationSync` also defaults its optional `origin` to that address. Swift `LongplayConfiguration(scope: ...)` and Kotlin `LongplayConfiguration(scope = ...)` use the same default; each package keeps its own independent version. Explicit `baseURL` / `baseUrl` still overrides it. Funnel and Paywall shells and renderers are packaged locally; their executable code is not downloaded from that API origin.
109
111
 
110
- Both `next` (candidate) and `latest` versions published with this default use the production API address. Tags select package versions, not deployments. The separate test API at `https://api.dev.longplayai.com` requires its own credentials and a runtime serving the current protocol 0.10.
112
+ Both `next` (candidate) and `latest` versions published with this default use the production API address. Tags select package versions, not deployments.
111
113
 
112
114
  Use the same API origin for every client and configuration-sync instance in one integration. Sandbox/Live selects business scope inside that deployment, not a different service or database. Never retry against another service automatically after an error or unknown command result. Maintainer test runs require an explicit target and must not fall back to production; follow the [SDK testing guide](../../docs/sdk-selfserve.md#maintainer-api-origin-testing).
113
115
 
@@ -244,6 +246,10 @@ purchase.destroy();
244
246
  `featureQuantities`, keyed by prepaid Feature ID. The quantities come from the
245
247
  submitted Paywall selection. Products without prepaid Features send an empty object.
246
248
 
249
+ A purchase button can be bound to the Coupon its Paywall displays. Pass `claimCoupon`, for example `longplay.forFunnel({ funnelId, versionId }).claimCoupon`, to use it: the SDK claims that Coupon at the click and quotes with its offer. Such a button does not call `resolveOfferId`, and a quote that did not apply the Coupon is refused.
250
+
251
+ `preloadFunnelPurchase()` downloads the code a Funnel purchase presents with. It needs no Customer, sends no request and changes no DOM; call it when the page can spare the download.
252
+
247
253
  `start()` persists the complete original request before dispatch. An unresolved attempt retains its request ID, locale, parameters and execution policy even if later calls supply different inputs; another Funnel is refused. `refresh()` allocates nothing. The Controller's existing command journal shares the purchase CAS row, so unknown confirmation/Close results retain their original identities. A new attempt is permitted only after the original Run is terminal, its commands are settled and all retained purchases have server-confirmed outcomes. An untouched quote can be cancelled through the existing Customer API after confirmed Run termination. Clearing browser storage cannot prove an unknown purchase absent and is not a fallback procedure.
248
254
 
249
255
  After `start()` or `refresh()`, `purchase.attempt` supplies a detached, read-only snapshot of the retained `requestId`, `funnelId`, `locale` and `parameters`, including when the Start result is unknown. It is `null` before recovery loads an attempt. `resolveOfferId(selection, original)` receives this same original context, so merchant coupon claims can reuse the original request identity after a reload or a new Customer session. Changing a returned snapshot cannot change the durable input. Keep any merchant choices needed on recovery in the original `parameters`; the SDK does not reconstruct them from current configuration. A dismissed presentation, changed identity or superseded attempt rejects a late offer result before quoting.
@@ -433,6 +439,33 @@ merchandiseFlags.destroy();
433
439
 
434
440
  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.
435
441
 
442
+ `createPaywallSession` requires `commerce` and `locale` (a BCP 47 tag such as `"en"` or `"zh-CN"`, at most 35 characters); omitting `locale` rejects the call before any request is sent.
443
+
444
+ ```ts
445
+ import { createPaywallSession, showPaywall } from "@tinkerlandai/longplay-sdk";
446
+
447
+ const options = {
448
+ baseUrl: "https://api.longplayai.com",
449
+ scope: { projectId: "<APP_UUID>", environment: "sandbox" as const },
450
+ };
451
+
452
+ export function openPaywall(container: HTMLElement, customerToken: string) {
453
+ return showPaywall(container, {
454
+ start: () =>
455
+ createPaywallSession(options, {
456
+ paywallId: "<PAYWALL_UUID>",
457
+ customerToken,
458
+ commerce: { provider: "stripe", currency: "USD" },
459
+ locale: "en",
460
+ }),
461
+ onCheckoutUrl: (url) => window.location.assign(url),
462
+ onAccessGranted: (check) => console.log("access", check.allowed),
463
+ });
464
+ }
465
+ ```
466
+
467
+ `await preloadPaywall()` loads the Paywall presentation code and returns the public `showPaywall` factory without starting a session or purchase. To keep host Coupon or Checkout controls inside the same Paywall shell, provide `mountControls(container)`. The callback receives a connected element before the ready notification; return a synchronous cleanup function, which the SDK calls once on destruction, cancellation or startup failure. Portal content can be rendered after ready. No second dialog or private DOM lookup is required.
468
+
436
469
  To render a Paywall while handing purchase selection to your own app, pass `onPurchaseIntent` to `showPaywall`. It receives
437
470
  `actionId`, the selected `productVersionId`, a copy of the UI `selection`, and validated `featureQuantities`. That callback
438
471
  replaces quote creation for the clicked purchase button; it neither charges nor grants access. Share the identified
@@ -549,6 +582,8 @@ The native renderer shell uses the same pure JavaScript calculation adapter and
549
582
 
550
583
  ## Web IAM entries and Funnel page experiments
551
584
 
585
+ Popup content versions may set `screen.presentation.position` to `center`, `top` or `bottom` on a `modal`. The default is `center`. Web and bundled native renderers use this position. An authored mobile sheet or fullscreen layout takes precedence on mobile. Banner placement follows its supplied inline container.
586
+
552
587
  Install the entry host once, then configure screen-entry or button/link triggers on a Funnel's Entry node in the App page map. Save and publish through the existing Funnel lifecycle. Use the merchant build's verified IAM digest and the same Customer session as other SDK clients:
553
588
 
554
589
  ```ts
@@ -570,6 +605,10 @@ await entries.retry();
570
605
  entries.destroy();
571
606
  ```
572
607
 
608
+ An entry's delivered `delivery.delaySeconds` starts when its screen becomes eligible or its button is clicked. Leaving the scene, changing identity, hiding the tab or destroying the host cancels the pending delay. Repeated clicks share the first pending deadline. `delivery.maxPerSession` counts accepted entry Runs in the current tab, across host recreation and reloads. Counts and in-flight claims are isolated by API origin, App, environment, identity, Funnel and Entry. Replaying an original accepted Run counts once. A refused start counts zero. The server enforces `maxPerDay` against its UTC day.
609
+
610
+ The Customer entry host uses `session.snapshot().customerId` for capped entries. A process entry host must supply `deliveryIdentity: () => ({type: "customer", id: customerId})` or `{type: "guest", id: tabGuestId}` from its merchant identity state. Update that state before calling `syncIdentity()` after login or logout. Supply stable identifiers without credentials. Both hosts accept `deliveryStorage` for a tab-scoped `Storage` adapter, defaulting to `sessionStorage`. A configured session limit whose identity or storage is unavailable suppresses a new start and reports `delivery_unavailable`.
611
+
573
612
  The host observes original button behavior, matches unique render/element guards and attempts automatic entries once per pathname visit. GOP selects the Funnel, checks entry publication, suppresses an existing Customer/Funnel Run and enforces the automatic-entry cooldown. With a full Customer Session, the host retains the original entry request and verified source target in tab-scoped `sessionStorage`. On reload it replays that exact request under the same logical Customer Session to recover the same Run, including background Waits and unresolved starts, without another Split allocation. The merchant must restore that session before installing the host, renew it with its Refresh Token, and isolate its credential storage by native account and App/environment. SDK credentials are memory-only by default; use `session.snapshot()` to retain the latest rotated pair and clear it on account/workspace changes or sign-out. Issuing a new session changes the Run credential derived for a replayed start. Records are bound to API origin, App, environment, Customer and IAM release, and contain no Customer or Run credentials. Recovery waits for the original scene and also works when the accepted publication is paused or superseded. A bare-token session has no stable Customer binding and remains memory-only. Set `recoveryStorage: false` to disable persistence, or supply a `Storage` adapter; unavailable storage reports `recovery_unavailable`. When the page unloads, the host is destroyed or the Customer changes while a screen is shown, the host closes that Run (with `keepalive` on unload), so a later entry is not suppressed until the Run expires; Paywall, in-flight and background steps continue. When a Run is stopped from Console or expires, the host removes its UI and reports `run_ended`, whether the Run reads `closed` or its next command is refused with `FORBIDDEN`; a later trigger can then start again. An IAM binding supplies no Customer credential or business permission.
574
613
 
575
614
  The entry scope is the route template plus render, covering every matching dynamic URL instance. Query/hash changes do not create a new visit. Supported anchor and inline-display changes recheck delayed scenes; hidden retained pages do not block the single active button. The clicked control itself must still be the unique active target; a replacement with the same selector cannot authorize an obsolete click. Multiple active targets remain refused. Configuration fetch/body reads default to a five-second deadline (`timeoutMs` overrides it), recover on the next 15-second poll, and discard late responses. Inspect `onStatus` for `identity_required`, `configuration_unavailable`, `incompatible` and `start_failed`. Definitively refused entries and accepted Runs whose first read is refused with a revoked credential allow the next matching entry in delivered order; transient read failures and pending unknown starts retain the original request for `retry()`. Automatic entries present at most once per pathname visit: entries matched while a Run is shown, or after it ends, wait for the next visit, so dismissal or completion never chains another Funnel. Explicit button clicks still start. A Run that is paused or waiting on a timer/event step stays hidden, reports `run_background` and no longer blocks other entries; it shows again when it has a screen and yields its slot when another Run mounts. Original button navigation continues, so full-page navigation can prevent presentation.
package/README.zh-CN.md CHANGED
@@ -107,6 +107,8 @@ JavaScript 与 TypeScript 共用本包,声明文件随包提供。内部 `@ind
107
107
 
108
108
  Web SDK 在 Paywall、Funnel Screen、Page、Popup 或 Banner 准备首屏时展示本地骨架。宿主可传入 `loading: "host"`,通过 `onPresentationState` 接管占位。收到 `loading` 时可保存 `dismiss()` 用于关闭,收到 `ready`、`dismissed`、`skipped` 或 `error` 时撤下占位。挂载 Promise 返回后仍应等 `ready` 再交接。宿主卸载或切换 Customer 时,可通过传入的 `signal` 取消展示。单独解析的 Content 从 `mountContent` 开始加载。通过 `prepareContent` 或 `preparePopup` 预渲染的内容会保持隐藏,直到调用 `show()`。购买进度和原单恢复继续使用各自的现有 API。
109
109
 
110
+ 要展示与已发布 Paywall 一致的骨架,可提前用 `configuration.paywall(paywallId)` 取布局,将返回的 `document` 作为 `loadingDocument` 传给 `showPaywall` 或 `showFunnelPurchase`。SDK 渲染布局、禁用其中的交互,并在加载时提供关闭按钮。可操作内容以正式 Paywall 为准。正式页有可用的关闭按钮时,由它接管关闭操作。
111
+
110
112
  独立的 [Python 服务端 SDK](../python/README.md) 使用同一当前 HTTP 协议,提供同步、异步 Customer、持仓/权益检查和用量上报。它从 `https://cdn.longplayai.com/sdk/python` 分发(不在 PyPI),不属于这个 npm 包。
111
113
 
112
114
  [Go 服务端 SDK](../go/README.md) 提供同样的首版能力,使用类型化响应、Context 取消和 goroutine 并发复用客户端。通过 Go 默认模块代理以 `go get longplayai.com/sdk/go` 安装,与其他业务 SDK 共用发行版本。
@@ -210,6 +212,10 @@ SDK 在首次派发前保存原 Start 请求 ID 和完整输入;同一未决
210
212
 
211
213
  `resolveOfferId` 还会收到 `featureQuantities`,按预付 Feature ID 提供本次提交的数量。无预付 Feature 的商品会传入空对象。
212
214
 
215
+ 购买按钮可以绑定 Paywall 上展示的 Coupon。传入 `claimCoupon` 后,SDK 在点击时为 Customer 领取该 Coupon,并用领到的 offer 报价。这类按钮不再调用 `resolveOfferId`;报价没有应用该 Coupon 时不会进入确认。
216
+
217
+ `preloadFunnelPurchase()` 提前下载 Funnel 购买展示所需的代码。它不需要 Customer,不发请求,也不改动页面,可在页面空闲时调用。
218
+
213
219
  购买 Host 复用 Paywall 的 `after_confirmation` 跳转策略:当前明确确认后可以打开原 Checkout 一次;重开、恢复和查询不会自动跳转。界面提供“继续付款”,点击后重读原 Operation,再决定是否打开;付款已完成、已过期或结果未知时不会打开旧地址。恢复页也可使用 `continueCheckout()`。原低层 Host 的默认行为保持兼容,完整用法见英文说明。
214
220
 
215
221
  商户关闭新购定向后,省略 `start` 并传入 `allowNewPurchase: false`,仅允许续付原单。SDK 按已登录顾客查找原单,换浏览器也能恢复。顾客只能继续原商品版本和原加购数量对应的 Checkout。关闭 Paywall 会收起界面,原单仍可在下次打开时恢复。
@@ -305,6 +311,8 @@ flags.destroy();
305
311
 
306
312
  Offering 固定 Product Version 的范围与层级。Paywall 固定已发布 Offering Version,并独立选择显示的 Product 子集、分组、顺序和默认项。`createPaywallStartClient`、`createPaywallSession`、`showPaywall` 使用独立 Paywall Session,不创建占位 Funnel。付款完成后重新查询权益,业务后端仍须重新鉴权并幂等扣减用量。
307
313
 
314
+ `await preloadPaywall()` 仅预加载 Paywall 展示代码并返回公开的 `showPaywall` 工厂,不创建 Session 或购买。将宿主的 Coupon、Checkout 控件放入同一个 Paywall 外壳时,可传入 `mountControls(container)`:SDK 在 ready 通知前提供已连接的专用节点;回调返回同步清理函数,SDK 在销毁、取消或启动失败时调用一次。宿主可在 ready 后渲染 Portal,无需额外对话框或查询 SDK 私有 DOM。
315
+
308
316
  仅渲染并将购买选择交给宿主时,向 `showPaywall` 传入 `onPurchaseIntent`。回调接收 `actionId`、选中的
309
317
  `productVersionId`、UI `selection` 副本和已校验的 `featureQuantities`;这条路径不创建报价、扣款或发放权益。
310
318
  将已识别客户端的 `session` 传给 `createPaywallSession`,以共用 Access/Refresh 自动轮换。宿主会话接口必须先验证
@@ -357,6 +365,12 @@ npm 发布不部署 Web 服务、不应用数据库迁移,也不发布 Swift
357
365
 
358
366
  ## Web IAM 入口与 Funnel 页面实验
359
367
 
368
+ Popup 内容版本可在 `screen.presentation.type: "modal"` 下设置 `position: "center" | "top" | "bottom"`,默认居中。Web 和原生包内渲染器共同执行,移动端配置的 sheet/fullscreen 优先。Banner 由传入的 inline 容器定位。
369
+
370
+ 投放规则的 `delivery.delaySeconds` 从场景匹配或按钮点击时开始,重复点击沿用首个待展示事件的截止时间。离页、切换身份、隐藏标签页或销毁宿主会取消延迟。`maxPerSession` 在同一标签页按已接受的 Entry Run 计数,跨刷新和宿主重建保留,重放同一 Run 计一次,拒绝的启动不计数。状态按 API origin、App、环境、Customer/Guest、Funnel 和 Entry 隔离。服务端按 UTC 日期执行 `maxPerDay`。
371
+
372
+ Customer 入口用完整 `session.snapshot().customerId` 隔离频率。Process 入口需提供 `deliveryIdentity: () => ({type: "customer", id: customerId})`,Guest 使用 `{type: "guest", id: tabGuestId}`。登录或退出后先更新身份再调用 `syncIdentity()`,标识中只放稳定 ID。两种宿主可用 `deliveryStorage` 指定当前标签页的 `Storage`,默认 `sessionStorage`。配置了会话频率但身份或存储不可用时,宿主暂停新启动并报告 `delivery_unavailable`。
373
+
360
374
  `createIamFunnelEntries({scope, environmentId, baseUrl, appManifestRelease, session: longplay.session, container})` 安装一次后,通过 `start()` 启动监听,即可在 IAM 页面地图配置现有 Funnel Entry 节点的「进入屏幕」和「按钮/链接点击」入口。配置保存到 Funnel 草稿,随 Funnel 一起发布、暂停。`appManifestRelease` 必须来自当前构建的 IAM release descriptor。描述文件的请求头和正文读取共用两秒超时,fetch 忽略取消时也会释放等待。原页面点击处理继续执行;点击的原节点本身必须仍是唯一活动目标,具有相同选择器的替代节点不能证明旧点击有效。自动入口每次 pathname 访问尝试一次,查询参数、hash 和重新渲染不制造新访问。
361
375
 
362
376
  服务端选择 Funnel,验证发布状态,并按原 Customer/Funnel 检查进行中的 Run 和自动入口冷却时间。未知响应或 Run 首次读取的暂时失败通过 `retry()` 复用内存中的原请求;完整 Customer Session 下,入口宿主将原 `entry_start` 请求及已验证目标保存到当前标签页的 `sessionStorage`,按 API origin、App、环境、Customer 和 IAM release 隔离,不保存 Customer 或 Run 凭据。刷新后回到原场景时,以当前 Customer 凭据重放同一请求,恢复原 Run、后台 Wait 和未知启动结果,不重新分组;原发布已暂停或换版也可恢复。裸 Token 会话仍仅保留内存状态;`recoveryStorage: false` 可关闭持久化,或传入 `Storage` 适配器;存储不可用时报告 `recovery_unavailable`。页面卸载、宿主销毁或 Customer 切换时,若正在展示普通屏幕,宿主会关闭该 Run(页面卸载时使用 `keepalive`),避免之后的入口在 Run 过期前一直被判为进行中。Paywall、进行中的请求和后台步骤不受影响。已接受 Run 在首次读取或离开页面后的关闭请求中被撤销凭据拒绝时,会释放入口等待。Run 被 Console 终止或过期后,无论读取到 `closed` 状态还是后续命令被 `FORBIDDEN` 拒绝,入口宿主都会移除界面并上报 `run_ended`,之后的入口可以重新启动。自动入口每次 pathname 访问最多展示一次:某个 Run 正在展示或已经展示后,同一访问内匹配的其他自动入口留到下一次访问,关闭或完成不会接着弹出另一个 Funnel;用户明确点击按钮仍可启动。Funnel 暂停或 Run 停在定时/事件等待步骤时,界面隐藏并上报 `run_background`,不再阻挡其他入口;之后有画面会重新显示,另一个 Run 挂载时让出位置。卸载时调用 `destroy()`。IAM 不提供 Customer 凭据或业务权限。
@@ -1,5 +1,5 @@
1
1
  import { LanguageModelV4Usage, LanguageModelV4Middleware } from '@ai-sdk/provider';
2
- import { F as FoundationApi, A as ApiInput } from './api-Do-6AyWa.js';
2
+ import { F as FoundationApi, A as ApiInput } from './api-r6FfVQpg.js';
3
3
  import { z } from 'zod';
4
4
 
5
5
  declare const tokenCounts: z.ZodObject<{
@@ -1,4 +1,4 @@
1
- import { S as StackNode } from './screen-CGCJ46b1.js';
1
+ import { S as StackNode } from './screen-qUBRsUi9.js';
2
2
  import { z } from 'zod/v4';
3
3
  import { z as z$1 } from 'zod';
4
4
 
@@ -19006,6 +19006,11 @@ declare const apiOperations: {
19006
19006
  blur: "blur";
19007
19007
  }>>;
19008
19008
  type: z$1.ZodLiteral<"modal">;
19009
+ position: z$1.ZodOptional<z$1.ZodEnum<{
19010
+ center: "center";
19011
+ top: "top";
19012
+ bottom: "bottom";
19013
+ }>>;
19009
19014
  size: z$1.ZodEnum<{
19010
19015
  sm: "sm";
19011
19016
  md: "md";
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-PW5PIBSO.js";import"./chunk-T2KWLYCW.js";import"./chunk-LOLMUXHW.js";import"./chunk-HEHLFHW7.js";import"./chunk-U7NX5ET2.js";import"./chunk-VLSP3LRH.js";import"./chunk-CR2XJ2CX.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as validateEntitlementCheck,b as validateResourceCheck};
@@ -0,0 +1 @@
1
+ import{p as n,s as t}from"./chunk-KFIL73QY.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
@@ -1 +1 @@
1
- import{a as A}from"./chunk-W32FI2A2.js";import{b as D,e as L}from"./chunk-SLUA7ABW.js";import{d as T}from"./chunk-TLZP7BW6.js";import{b as O}from"./chunk-7QL4GF4C.js";import{a as R}from"./chunk-DSPLGTQI.js";var m=new WeakMap;function B(e){let o=e.view,n=o?.paywall?.resolution;if(!o||!["running","waiting"].includes(o.status)||o.stopped||!n||"document"in n||!e.resolvePaywall||e.identitySignal?.aborted)return;let a=JSON.stringify(n);if(m.get(e)?.key===a)return;let i=JSON.parse(a),c=e.identitySignal,u=Promise.resolve().then(async()=>{c?.throwIfAborted();let v=await e.resolvePaywall(i);return c?.throwIfAborted(),v}),f={key:a,content:u};return m.set(e,f),u.catch(()=>{}),()=>{m.get(e)===f&&m.delete(e)}}function Q(e,o){let n=m.get(e);return m.delete(e),n?.key===JSON.stringify(o)?n.content:e.resolvePaywall(o)}function re(e){if(!e.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let o=e.client.pageExperiments.bind(e.client),n=!1,a=!1,i=0,c=!1,u=!1,f="",v=()=>{let t=e.client.view;return JSON.stringify([t?.id,t?.source.versionId,t?.visit,t?.revision,t?.status,t?.stopped])},s=new Map,x=new Set,q={},d=new Map,U=D(e.appManifestRelease),C=()=>{for(let t of s.values())t.effect.revert();s.clear()},g=()=>{C();for(let t of d.values())t();d.clear()};function E(t){if(n||x.has(t))return;x.add(t);let h=i;o(e.appManifestRelease,[t]).catch(k=>{x.delete(t),!n&&h===i&&R(e.onError,k)})}async function w(){if(n)return;f=v();let t=e.client.view;if(!t||t.stopped||!["running","waiting"].includes(t.status)){i++,g();return}if(document.visibilityState==="hidden")return;if(c){u=!0;return}c=!0;let h=++i,k=`${t.id}:${t.visit}:${t.revision}`,W=location.href;try{let[P,{applyVisualVariation:j}]=await Promise.all([o(e.appManifestRelease),import("./visual-dom-6DCUZGPB.js")]),p=e.client.view;if(n||h!==i||!p||p.stopped||!["running","waiting"].includes(p.status)||`${p.id}:${p.visit}:${p.revision}`!==k||location.href!==W)return;let $=new Set,I=new Set;for(let r of P.assignments){let l=`${P.payload.environmentId}:${r.experimentKey}`;if(I.add(l),d.has(l)||d.set(l,L(l,q)),!!r.inExperiment)for(let y of P.payload.experiments){if(y.key!==r.experimentKey||!O(location.href,y.urlPatterns??[]))continue;let z=y.meta?.findIndex(F=>F.key===r.variationKey)??-1,S=y.variations[z];if(!S?.renderGuard)continue;let b=r.receiptId+":"+y.changeId,J=JSON.stringify([r.variationKey,S]);$.add(b);let N=s.get(b);if(N?.signature===J){N.effect.applied&&E(r.receiptId);continue}s.get(b)?.effect.revert(),s.delete(b);let K=j(S,{requireUniqueTargets:!0,boundVariations:y.variations,allowJs:!1,onApplied:()=>E(r.receiptId),onError:F=>R(e.onError,F)});s.set(b,{signature:J,effect:K}),K.applied&&E(r.receiptId)}}for(let[r,l]of s)$.has(r)||(l.effect.revert(),s.delete(r));for(let[r,l]of d)I.has(r)||(l(),d.delete(r))}catch(P){h===i&&g(),!n&&h===i&&R(e.onError,P)}finally{c=!1,u&&!n&&(u=!1,w())}}let G=e.client.subscribe(()=>{if(v()===f)return;f=v(),i++;let t=e.client.view;(!t||t.stopped||!["running","waiting"].includes(t.status))&&g(),a&&w()}),H=T(()=>{i++,g(),a&&w()}),V=()=>{i++,C()};document.addEventListener("visibilitychange",V);let M=A({document,run:async()=>{a&&await w()},delay:()=>a&&!n?15e3:void 0});return{async start(){a||n||(a=!0,await M.refresh())},refresh:w,destroy(){n=!0,i++,M.destroy(),document.removeEventListener("visibilitychange",V),G(),H(),g(),U.destroy()}}}export{B as a,Q as b,re as c};
1
+ import{a as A}from"./chunk-W32FI2A2.js";import{b as D,e as L}from"./chunk-SLUA7ABW.js";import{d as T}from"./chunk-OCWSWXCW.js";import{b as O}from"./chunk-O4KXODTJ.js";import{a as R}from"./chunk-DSPLGTQI.js";var m=new WeakMap;function B(e){let o=e.view,n=o?.paywall?.resolution;if(!o||!["running","waiting"].includes(o.status)||o.stopped||!n||"document"in n||!e.resolvePaywall||e.identitySignal?.aborted)return;let a=JSON.stringify(n);if(m.get(e)?.key===a)return;let i=JSON.parse(a),c=e.identitySignal,u=Promise.resolve().then(async()=>{c?.throwIfAborted();let v=await e.resolvePaywall(i);return c?.throwIfAborted(),v}),f={key:a,content:u};return m.set(e,f),u.catch(()=>{}),()=>{m.get(e)===f&&m.delete(e)}}function Q(e,o){let n=m.get(e);return m.delete(e),n?.key===JSON.stringify(o)?n.content:e.resolvePaywall(o)}function re(e){if(!e.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let o=e.client.pageExperiments.bind(e.client),n=!1,a=!1,i=0,c=!1,u=!1,f="",v=()=>{let t=e.client.view;return JSON.stringify([t?.id,t?.source.versionId,t?.visit,t?.revision,t?.status,t?.stopped])},s=new Map,x=new Set,q={},d=new Map,U=D(e.appManifestRelease),C=()=>{for(let t of s.values())t.effect.revert();s.clear()},g=()=>{C();for(let t of d.values())t();d.clear()};function E(t){if(n||x.has(t))return;x.add(t);let h=i;o(e.appManifestRelease,[t]).catch(k=>{x.delete(t),!n&&h===i&&R(e.onError,k)})}async function w(){if(n)return;f=v();let t=e.client.view;if(!t||t.stopped||!["running","waiting"].includes(t.status)){i++,g();return}if(document.visibilityState==="hidden")return;if(c){u=!0;return}c=!0;let h=++i,k=`${t.id}:${t.visit}:${t.revision}`,W=location.href;try{let[P,{applyVisualVariation:j}]=await Promise.all([o(e.appManifestRelease),import("./visual-dom-5LUN4AHO.js")]),p=e.client.view;if(n||h!==i||!p||p.stopped||!["running","waiting"].includes(p.status)||`${p.id}:${p.visit}:${p.revision}`!==k||location.href!==W)return;let $=new Set,I=new Set;for(let r of P.assignments){let l=`${P.payload.environmentId}:${r.experimentKey}`;if(I.add(l),d.has(l)||d.set(l,L(l,q)),!!r.inExperiment)for(let y of P.payload.experiments){if(y.key!==r.experimentKey||!O(location.href,y.urlPatterns??[]))continue;let z=y.meta?.findIndex(F=>F.key===r.variationKey)??-1,S=y.variations[z];if(!S?.renderGuard)continue;let b=r.receiptId+":"+y.changeId,J=JSON.stringify([r.variationKey,S]);$.add(b);let N=s.get(b);if(N?.signature===J){N.effect.applied&&E(r.receiptId);continue}s.get(b)?.effect.revert(),s.delete(b);let K=j(S,{requireUniqueTargets:!0,boundVariations:y.variations,allowJs:!1,onApplied:()=>E(r.receiptId),onError:F=>R(e.onError,F)});s.set(b,{signature:J,effect:K}),K.applied&&E(r.receiptId)}}for(let[r,l]of s)$.has(r)||(l.effect.revert(),s.delete(r));for(let[r,l]of d)I.has(r)||(l(),d.delete(r))}catch(P){h===i&&g(),!n&&h===i&&R(e.onError,P)}finally{c=!1,u&&!n&&(u=!1,w())}}let G=e.client.subscribe(()=>{if(v()===f)return;f=v(),i++;let t=e.client.view;(!t||t.stopped||!["running","waiting"].includes(t.status))&&g(),a&&w()}),H=T(()=>{i++,g(),a&&w()}),V=()=>{i++,C()};document.addEventListener("visibilitychange",V);let M=A({document,run:async()=>{a&&await w()},delay:()=>a&&!n?15e3:void 0});return{async start(){a||n||(a=!0,await M.refresh())},refresh:w,destroy(){n=!0,i++,M.destroy(),document.removeEventListener("visibilitychange",V),G(),H(),g(),U.destroy()}}}export{B as a,Q as b,re as c};
@@ -1 +1 @@
1
- import{a as T,b as se}from"./chunk-KPDHY76A.js";import{b as re,h as ae,j as ce}from"./chunk-BLVBUN2R.js";import{F as M,b as J}from"./chunk-2FE4FTPH.js";import{a as b,b as f,c as m}from"./chunk-EUTWY7A2.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-7MNJH5GB.js";import{a as oe,b as j}from"./chunk-LF2UIJYD.js";import{b as W,j as X}from"./chunk-PUR5CYWX.js";import{E as $}from"./chunk-TAFALMQN.js";import{b as ie}from"./chunk-56BYGPQ6.js";import{a as B}from"./chunk-VYFSRHXM.js";import{b as Q}from"./chunk-TJGIT5CU.js";import{a as s}from"./chunk-OX7PA64E.js";import{b as K}from"./chunk-VF6QMMEA.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-HS4M2UXN.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-HS4M2UXN.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-HS4M2UXN.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-HS4M2UXN.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};
1
+ import{a as T,b as se}from"./chunk-ZYOZSUZS.js";import{b as re,h as ae,j as ce}from"./chunk-ZZIBLQCJ.js";import{F as M,b as J}from"./chunk-KFIL73QY.js";import{a as b,b as f,c as m}from"./chunk-CY7OKV7E.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-D3OYXTMC.js";import{a as oe,b as j}from"./chunk-PW5PIBSO.js";import{b as W,j as X}from"./chunk-GH6FM44P.js";import{F as $}from"./chunk-YV6UFESO.js";import{b as ie}from"./chunk-7XDQKZYA.js";import{a as B}from"./chunk-XJRDO3NI.js";import{b as Q}from"./chunk-HEHLFHW7.js";import{a as s}from"./chunk-U7NX5ET2.js";import{b as K}from"./chunk-CR2XJ2CX.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-EK4RCUWJ.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-EK4RCUWJ.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-EK4RCUWJ.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-EK4RCUWJ.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};