@tinkerlandai/longplay-sdk 0.10.33 → 0.10.35

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 (96) hide show
  1. package/CHANGELOG.md +12 -3
  2. package/README.md +58 -9
  3. package/README.zh-CN.md +22 -5
  4. package/dist/check-response-GZZRWBEA.js +1 -0
  5. package/dist/chunk-2FE4FTPH.js +1 -0
  6. package/dist/chunk-3NCMYTNG.js +1 -0
  7. package/dist/chunk-44U3FOBB.js +1 -0
  8. package/dist/chunk-56BYGPQ6.js +1 -0
  9. package/dist/chunk-73NP72FV.js +1 -0
  10. package/dist/{chunk-KR3KDTVD.js → chunk-BLVBUN2R.js} +1 -1
  11. package/dist/chunk-BOVN2BE3.js +1 -0
  12. package/dist/chunk-BQRS7Y4K.js +1 -0
  13. package/dist/chunk-CIP5SQ5Y.js +1 -0
  14. package/dist/chunk-CKKIB2HC.js +1 -0
  15. package/dist/chunk-EM3MGDPG.js +1 -0
  16. package/dist/chunk-ETK6GC5P.js +1 -0
  17. package/dist/chunk-EUTWY7A2.js +1 -0
  18. package/dist/{chunk-NVHIGAO3.js → chunk-FMDC6N4W.js} +1 -1
  19. package/dist/chunk-GZRRVHYK.js +1 -0
  20. package/dist/{chunk-MIBRUDIS.js → chunk-KE26KWIU.js} +1 -1
  21. package/dist/{chunk-GGRDM54V.js → chunk-KPDHY76A.js} +1 -1
  22. package/dist/{chunk-FYQXSGRT.js → chunk-LF2UIJYD.js} +1 -1
  23. package/dist/{chunk-UWLEGMWX.js → chunk-MSK3VZ3A.js} +1 -1
  24. package/dist/{chunk-X4W22IH6.js → chunk-OX7PA64E.js} +1 -1
  25. package/dist/chunk-PUR5CYWX.js +1 -0
  26. package/dist/{chunk-XLSDL4D3.js → chunk-RML52BOR.js} +1 -1
  27. package/dist/chunk-RNEF4MZW.js +1 -0
  28. package/dist/chunk-SFHIFCXG.js +1 -0
  29. package/dist/{chunk-HQITRRHF.js → chunk-SXBM3DWK.js} +1 -1
  30. package/dist/chunk-TAFALMQN.js +1 -0
  31. package/dist/chunk-TJGIT5CU.js +1 -0
  32. package/dist/{chunk-KIMX3OIV.js → chunk-TLZP7BW6.js} +1 -1
  33. package/dist/chunk-TOTRALYQ.js +10 -0
  34. package/dist/chunk-U4RSRFZY.js +1 -0
  35. package/dist/chunk-UVRT4MY6.js +1 -0
  36. package/dist/chunk-V7MMTILA.js +1 -0
  37. package/dist/chunk-V7PFLFHE.js +1 -0
  38. package/dist/{chunk-BXPXJARS.js → chunk-VEX2FOFZ.js} +1 -1
  39. package/dist/chunk-W32FI2A2.js +1 -0
  40. package/dist/chunk-W6OQTXLL.js +1 -0
  41. package/dist/{chunk-EQPEUPMG.js → chunk-WZR2XCSJ.js} +1 -1
  42. package/dist/chunk-XUGEOELU.js +1 -0
  43. package/dist/chunk-YVXLCQGM.js +1 -0
  44. package/dist/content-AJDTSI7A.js +1 -0
  45. package/dist/funnel-host-purchase-Z7FCJ5CX.js +1 -0
  46. package/dist/{funnel-local-client-BeGBvi3z.d.ts → funnel-local-client-Dz1dTgES.d.ts} +22 -22
  47. package/dist/funnel-paywall-prerender-QHCUZZY3.js +1 -0
  48. package/dist/{funnel-process-client-C6QKDZun.d.ts → funnel-process-client-D6qjStm2.d.ts} +1 -1
  49. package/dist/funnel-runtime-host-UKSOOA4H.js +1 -0
  50. package/dist/index.d.ts +196 -61
  51. package/dist/index.js +1 -1
  52. package/dist/merchant-bridge-contracts-EAE4HQE4.js +1 -0
  53. package/dist/native-shell.js +1 -1
  54. package/dist/openrouter.js +1 -1
  55. package/dist/operation-contracts-HS4M2UXN.js +1 -0
  56. package/dist/page.js +1 -1
  57. package/dist/paywall-VYUBYBUI.js +1 -0
  58. package/dist/paywall-content-YQAVSO2T.js +1 -0
  59. package/dist/paywall-session-E5V42XUT.js +1 -0
  60. package/dist/popup.d.ts +20 -2
  61. package/dist/popup.js +1 -1
  62. package/dist/{presentation-loading-CiEQbUDk.d.ts → presentation-loading-CFSiS0VX.d.ts} +3 -1
  63. package/dist/react-native.d.ts +4 -4
  64. package/dist/react-native.js +1 -1
  65. package/dist/screen-renderer-R5GH7XLV.js +1 -0
  66. package/dist/server.d.ts +32 -2
  67. package/dist/server.js +3 -3
  68. package/dist/visual.js +1 -1
  69. package/package.json +1 -1
  70. package/dist/chunk-BRAVNBCC.js +0 -1
  71. package/dist/chunk-EHDHWYVJ.js +0 -1
  72. package/dist/chunk-ENZBWR3Y.js +0 -1
  73. package/dist/chunk-HQPP76BS.js +0 -1
  74. package/dist/chunk-ILEDKSRQ.js +0 -1
  75. package/dist/chunk-JN6JEKWN.js +0 -1
  76. package/dist/chunk-MPYJRLKB.js +0 -10
  77. package/dist/chunk-N7YXDSQL.js +0 -1
  78. package/dist/chunk-NAZU3EEJ.js +0 -1
  79. package/dist/chunk-NVIHK5GE.js +0 -1
  80. package/dist/chunk-R23IGK5U.js +0 -1
  81. package/dist/chunk-R4FDIYMN.js +0 -1
  82. package/dist/chunk-SCC3O2RD.js +0 -1
  83. package/dist/chunk-THMGTRXP.js +0 -1
  84. package/dist/chunk-U2R7MG3J.js +0 -1
  85. package/dist/chunk-U6E6CM7Z.js +0 -1
  86. package/dist/chunk-U6GWWCUS.js +0 -1
  87. package/dist/chunk-UHQGO6OR.js +0 -1
  88. package/dist/chunk-YTZQ5BMP.js +0 -1
  89. package/dist/content-CFX2L2BP.js +0 -1
  90. package/dist/funnel-host-purchase-MSPLT3ZV.js +0 -1
  91. package/dist/funnel-runtime-host-ATOA7MGC.js +0 -1
  92. package/dist/merchant-bridge-contracts-ZUQ6SGXZ.js +0 -1
  93. package/dist/operation-contracts-443N2P3A.js +0 -1
  94. package/dist/paywall-XAXSMLDU.js +0 -1
  95. package/dist/paywall-session-MB7BD2XP.js +0 -1
  96. package/dist/screen-renderer-3CBREMIS.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,10 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.35
4
+
5
+ - 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.
6
+ - Restore an unfinished Checkout in its original Paywall, including after signing in on another browser. A recovery-only host can resume the same selection. Replacing a plan or prepaid quantity requires the merchant to confirm the original Checkout is closed and unpaid.
7
+ - Keep a recoverable Checkout available when the customer dismisses its Paywall. Reopening restores its original selection and displays Continue checkout.
8
+ - Reuse cached CORS permissions for browser POSTs. The wire protocol remains `0.10`.
9
+
10
+ ## 0.10.34
11
+
12
+ - Pass the submitted prepaid Feature quantities to Paywall and Funnel offer callbacks. A retry keeps the original selection.
13
+
3
14
  ## 0.10.33
4
15
 
5
- - Pass the published Paywall design as `loadingDocument` to use its layout and responsive dimensions during loading.
6
- - Dismissing the loading view prevents a late result from opening the Paywall.
7
- - A visible, actionable Close control in the Paywall hides the SDK Close button. The SDK brings its button back when the authored control is unavailable.
16
+ - Render the loading skeleton using a published Paywall layout when it is available, keep it dismissible, and give the current Paywall page one available Close control.
8
17
 
9
18
  ## 0.10.32
10
19
 
package/README.md CHANGED
@@ -97,19 +97,17 @@ 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
-
102
100
  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.
103
101
 
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 shares the release version with the other business SDKs.
102
+ 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)).
105
103
 
106
104
  ## API origin and test services
107
105
 
108
106
  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).
109
107
 
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 = ...)` uses the same default and shared release 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.
108
+ 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.
111
109
 
112
- Both `beta` 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.
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.
113
111
 
114
112
  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).
115
113
 
@@ -190,7 +188,7 @@ When a customer dismisses a Funnel Paywall, the Web host keeps the dialog open u
190
188
 
191
189
  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.
192
190
 
193
- ### Managed Funnel purchase recovery (source API, not yet published)
191
+ ### Managed Funnel purchase recovery
194
192
 
195
193
  `createFunnelPurchaseClient` adds durable purchase ownership to the existing `funnel-run/1` Controller and Host. It requires the full backend-issued Customer Session in the shared `session`; it does not use merchant user IDs as proof. The browser default uses Web Locks and localStorage revision CAS, partitioned by API origin, App/environment and Customer. A non-browser host supplies `FunnelPurchaseStorage` with atomic compare-and-swap semantics. Neither adapter stores Customer access/refresh tokens or Run Tokens. Start inputs and purchase references are durable business data.
196
194
 
@@ -242,17 +240,68 @@ renderRecoveryButtons(purchase.recovery.actions, recoveryActions);
242
240
  purchase.destroy();
243
241
  ```
244
242
 
243
+ `resolveOfferId` receives the selected action and Product Version together with
244
+ `featureQuantities`, keyed by prepaid Feature ID. The quantities come from the
245
+ submitted Paywall selection. Products without prepaid Features send an empty object.
246
+
245
247
  `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.
246
248
 
247
249
  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.
248
250
 
249
251
  `showFunnelPurchase` uses the existing Paywall's `after_confirmation` navigation policy. An active explicit confirmation can open its Checkout once, including when that original URL arrives on a later observation. Reopening, restoring, polling or retrying a recovery read never automatically navigates: a verified unfinished Checkout offers **Continue checkout**. That action reads the original Operation again before navigation; a paid, expired or uncertain result is observed without opening the old URL. Recovery pages can also call `purchase.continueCheckout(openAllowedCheckout)`. Neither path creates a new quote or confirms another purchase. Standalone Paywalls and low-level Funnel hosts retain their existing `automatic` default unless explicitly configured otherwise.
250
252
 
253
+ When the merchant's targeting is off, omit `start` and set `allowNewPurchase: false` to offer only the original Checkout. Discovery uses the signed-in Customer, so it can restore their Checkout in another browser. A Paywall opened in this mode can resume only the matching Product Version and prepaid quantities. Closing the Paywall while that purchase is still recoverable dismisses the presentation and leaves the purchase available for the next opening.
254
+
251
255
  `mode` distinguishes `run`, `operation`, `blocked` and `idle`; `status` is `ready`, `waiting_result`, `checkout`, `fulfillment`, `recording`, `complete`, `blocked` or `idle`. `actions` names allowed SDK actions. `confirmation` supplies the original quote when Operation-only confirmation is possible. The `purchases` entries reuse `PaywallRecovery`. Original purchase reads use `recover_purchase` with the retained Run/Receipt/Operation reference and server `canReselect` decision. Confirmation uses the legal original Customer, original Operation ID and existing subscriptions API; an outstanding Run command prevents a separate Operation confirmation. A lost Operation-confirmation reply retains its original Operation command, and reads settle it from server acceptance. Commercial completion in Operation-only mode does not silently settle an unknown Run/Close command or authorize a replacement attempt.
252
256
 
253
257
  `merchant` permits merchant-provider quotes; `record_only` permits Stripe quotes executed by the merchant; `indiana` permits platform execution; `native` permits Apple/Google execution. The original and current policies are intersected. The Controller checks the original quote before confirmation, including Host automatic confirmation and log retry; a policy refusal sends no commercial command. Checkout URLs and external business destinations remain merchant policy. The existing Host owns Run observation and loading/ready/dismissal; one recovery observer handles Operation-only or post-termination work. `onDismiss` releases presentation ownership before merchant code runs, so immediate reopening does not wait on a merchant lock.
254
258
 
255
- The matching [Customer-session recovery protocol](../../docs/funnel-storage-design.md#customer-session-recovery-protocol) uses the current original Customer's access token, including a new login session, without issuing another Run Token. For an unknown Start, `refresh()` only performs `recover_start` with `intent: "lookup"`; a missing result remains blocked. Initial `start()` and explicit `retry()` use `intent: "resume"` with the retained original ID and full input. Known Runs use `recover_run`; exact retained commands use `settle_command`, and the same Controller continues through `run_command`. Operation-only recovery retains original references and unresolved commands, and reads `recover_purchase` for the existing SQL reselection decision. A false decision is preserved even when the Operation reports failure or cancellation; commercial completion does not mark recovery complete while an original command remains unsettled. A missing receipt never authorizes replacement. This unpublished source API requires matching GOP and SQL functions. Offline simulated results do not establish deployment, native RLS, concurrent SQL locking or Sandbox acceptance.
259
+ The matching Customer-session recovery protocol ([Indianapolis API reference](https://github.com/tinkerlandai/Indianapolis/blob/dev/docs/sdk-api-reference.md), FRC-001/002) uses the current original Customer's access token, including a new login session, without issuing another Run Token. For an unknown Start, `refresh()` only performs `recover_start` with `intent: "lookup"`; a missing result remains blocked. Initial `start()` and explicit `retry()` use `intent: "resume"` with the retained original ID and full input. Known Runs use `recover_run`; exact retained commands use `settle_command`, and the same Controller continues through `run_command`. Operation-only recovery retains original references and unresolved commands, and reads `recover_purchase` for the existing SQL reselection decision. A false decision is preserved even when the Operation reports failure or cancellation; commercial completion does not mark recovery complete while an original command remains unsettled. A missing receipt never authorizes replacement. Managed recovery requires matching Indianapolis runtime and SQL functions. Offline simulated results do not establish deployment, native RLS, concurrent SQL locking or Sandbox acceptance.
260
+
261
+ #### Pre-render the first Paywall
262
+
263
+ `prerenderFunnelPurchase` renders, hidden and before the click, the Paywall the purchase Start presents first, so the opening click only reveals it. It starts nothing: no Run, receipt, exposure or quote. The Run started at the click takes the revealed Paywall over when its first Paywall is the same published Version and untouched.
264
+
265
+ ```ts
266
+ import {
267
+ prerenderFunnelPurchase,
268
+ showFunnelPurchase,
269
+ type PreparedFunnelPurchase,
270
+ } from "@tinkerlandai/longplay-sdk";
271
+
272
+ const start = { funnelId, locale: "en", parameters: merchantParameters };
273
+ // Ahead of the click (page load, or when the purchase button appears).
274
+ let prepared: PreparedFunnelPurchase | undefined =
275
+ await prerenderFunnelPurchase(
276
+ document.body, // keep this element in place for the page's lifetime
277
+ { client: purchase, start, paywallVersionId },
278
+ );
279
+
280
+ button.onclick = () => {
281
+ // Synchronously in the click, before any await: reveals the Paywall in this frame.
282
+ prepared?.open();
283
+ void showFunnelPurchase(container, {
284
+ client: purchase,
285
+ start, // the same Start the copy was rendered for
286
+ prepared, // handed to the SDK from here
287
+ onDismiss: () => void prepareNext(),
288
+ // ...the same callbacks as without a pre-render
289
+ });
290
+ prepared = undefined;
291
+ };
292
+ // On unmount: prepared?.destroy();
293
+ ```
294
+
295
+ - `paywallVersionId` (one exact Version) or `paywallId` (its current published Version) names the Paywall the Funnel presents first. The copy is read with `purchase.readPaywall()` as a standalone Paywall would be, for the Start's `parameters.commerce` and `locale`.
296
+ - `start` can be a promise while the merchant's own checks run: rendering starts at once and the copy becomes ready only with the Start. Pass `commerce` and `locale` then; a Start with other commerce or locale, `null` or a rejection leaves it `unavailable`.
297
+ - `state` is `preparing`, `ready`, `unavailable` (see `reason`), `shown`, `adopted`, `released` or `closed`; `ready` resolves `true` once it can be revealed and `false` when it never will be; `onState` reports each change.
298
+ - Call `open()` synchronously from the opening click. It returns `"shown"` (revealed now), `"pending"` (still rendering: pass it anyway; it is revealed only if it is ready before the Run presents anything, so the click never waits for it) or `false` (show the purchase the normal way). Pass the same Start to `showFunnelPurchase`; `matches(start)` says whether a Start would present this copy (the request ID may differ).
299
+ - Passing `prepared` to `showFunnelPurchase` (or `showFunnelRun`) hands it to the SDK. When the SDK cannot use it (a presentation for the client is already open, another or no Start, no Run, operation-only or blocked recovery, a failure, an instruction or another presentation first), it releases it, so a revealed copy is never left on screen. A revealed presentation that ends without a Run reports `onDismiss(null)`, or `onError` for a failure; a Funnel paused before the takeover dismisses a revealed dialog for good, as it does one the Run presented. Do not reuse a copy you passed; pre-render a new one.
300
+ - A tap before the takeover waits for the Run. A tap made on plans the Run no longer offers is refused (`CONFLICT`) and dropped: the Customer chooses again, and the old selection is never quoted. Closing the revealed Paywall before the takeover closes the Run started for that click, once; another click on the same client waits for that Close and starts afresh.
301
+ - A copy is revealed only within `maxAgeMs` (5 minutes by default) of its render. It is never prepared while `purchase.retained()` reports a pending purchase, and until a click takes it a ready copy becomes `unavailable` when this Customer's purchase is left pending, by the same purchase client or, through the default browser purchase store, by another tab; the Run's own recovery stays the final guard. A Customer change, `signal` or `destroy()` releases it; after the takeover the Run host owns it.
302
+ - Keep `container` attached and in place: moving it restarts the Paywall's frame.
303
+
304
+ `purchase.retained()` reads storage only and says whether a new Start would begin afresh (`"none"`, `"finished"`, `"replaceable"`) or recover a pending original purchase (`"pending"`). `purchase.readPaywall({ paywallVersionId | paywallId, commerce, locale })` reads one published Paywall with its content for the current Customer, starting nothing; it refuses another Version or Paywall than requested and a Customer change during the read.
256
305
 
257
306
  ### Guest entry and same-Run login
258
307
 
@@ -398,7 +447,7 @@ In Stripe environments, Longplay executes `longplay` mode; `record_only` returns
398
447
 
399
448
  Customer `claimCoupon`, `redeemCoupon`, `redeemReward` and `createReferralCode` retain their optional request-ID arguments. If a dispatched call fails, `LongplayError.commandRequestId` exposes the original command ID, including an automatically generated ID; `LongplayError.requestId` remains the HTTP trace ID. Retry the same method with that command ID and unchanged input, for example `longplay.claimCoupon(couponId, error.commandRequestId)`. For recovery across app crashes, generate and persist the command ID and input before the first call. The error does not establish whether the command was accepted.
400
449
 
401
- This beta does not certify complete commercial or production operation. Remaining service gaps include:
450
+ This release does not certify complete commercial or production operation. Remaining service gaps include:
402
451
 
403
452
  - Subscription batch processing. Conflict queries and retries have services but still require a matching deployment and business prerequisites.
404
453
  - Postpaid Billing Authorization, Billing Coupon lists, and billing-adjustment confirmation. AutoTopup consent preparation/confirmation/revocation is implemented independently.
@@ -639,4 +688,4 @@ Handlers must durably reserve the original operation before external effects and
639
688
 
640
689
  The Server entry adds `createMerchantBridgeProtocol` for the explicit v4 T0 wire slice: signed discovery, `requirement.check` and `operation.prepare`. It encodes/validates bounded messages and correlates replies; it performs no HTTP, confirmation or native execution. Supply the scoped v4 Manifest and backend HMAC credentials. The Server entry also exports `merchantPreparationRequestDigest`, `merchantQuoteTermsDigest` and `entitlementRequirementDigest` so adapters use the same normalized digest rules. The signed, read-only preparation request carries the saved preparation authority and complete intent so the merchant can quote its original selection. Responses bind to that request, quote digest and validity; preparation never supplies user confirmation or execution authority. Prepared `subscriptionTerms` carries the merchant's recurring amounts, intervals and shared trial terms independently of the operation's money lines. Zero-charge subscription changes may have no money lines; full refunds ask the merchant for the remaining amount, while partial refunds preserve the explicitly chosen amount. These terms are covered by the same confirmation digest. The existing `createMerchantBridge` and receiver remain v3; there is no automatic protocol fallback.
641
690
 
642
- `checkEntitlement` remains the shared Customer/Server API for every payment provider. Its optional `observation` contains the authoritative subject, source, revision, observation time and complete requirement digest; v4 merchant checks require that group. Standalone and embedded Offering/Paywall/Funnel checks share the original-requirement validation; a requested embedded check must be present. Enriched responses are checked against the original requirement, and Paywall rechecks reject changed subject/authority/requirements or missing previously supplied observation metadata. Current runtime responses without observations remain readable. Business ownership selects authority; `commerce.provider` only selects purchase presentment. Shared quote responses and operation authority expose full `merchantTerms`; the Paywall confirmation presents the merchant charge, recurring/trial terms, expected effects and required consents. The [GOP runtime source](../../../Indianapolis/docs/sdk-runtime.md#merchant-execution-and-billing) owns quote preparation, confirmation and execution. SDK generation does not install SQL, update GOP’s pinned artifact or deploy a merchant adapter. See the [generic contract](../../docs/growth-integration.md#merchant-executed-orchestration).
691
+ `checkEntitlement` remains the shared Customer/Server API for every payment provider. Its optional `observation` contains the authoritative subject, source, revision, observation time and complete requirement digest; v4 merchant checks require that group. Standalone and embedded Offering/Paywall/Funnel checks share the original-requirement validation; a requested embedded check must be present. Enriched responses are checked against the original requirement, and Paywall rechecks reject changed subject/authority/requirements or missing previously supplied observation metadata. Current runtime responses without observations remain readable. Business ownership selects authority; `commerce.provider` only selects purchase presentment. Shared quote responses and operation authority expose full `merchantTerms`; the Paywall confirmation presents the merchant charge, recurring/trial terms, expected effects and required consents. The [GOP runtime source](../../../Indianapolis/docs/sdk-runtime.md#merchant-execution-and-billing) owns quote preparation, confirmation and execution. SDK generation does not install SQL, update GOP’s pinned artifact or deploy a merchant adapter. See [merchant-executed commerce](../../docs/growth-integration.md#merchant-executed-commerce).
package/README.zh-CN.md CHANGED
@@ -107,8 +107,6 @@ 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
-
112
110
  独立的 [Python 服务端 SDK](../python/README.md) 使用同一当前 HTTP 协议,提供同步、异步 Customer、持仓/权益检查和用量上报。它从 `https://cdn.longplayai.com/sdk/python` 分发(不在 PyPI),不属于这个 npm 包。
113
111
 
114
112
  [Go 服务端 SDK](../go/README.md) 提供同样的首版能力,使用类型化响应、Context 取消和 goroutine 并发复用客户端。通过 Go 默认模块代理以 `go get longplayai.com/sdk/go` 安装,与其他业务 SDK 共用发行版本。
@@ -202,21 +200,40 @@ Web 宿主可以用独立的第一方安装 cookie 保留信号。清除 cookie
202
200
 
203
201
  Local/Remote 求值策略由每个 Funnel 决定。`createFunnelDecisionClient` 支持当前 `configuration()`、`features()`、提交和结果读取;`createFeatureClient` 以 `generation` 标识配置。Local 下载的规则对客户端可见;敏感决策应使用 Remote 和可信业务事实。
204
202
 
205
- ### Funnel 购买托管恢复(源码 API,尚未发布)
203
+ ### Funnel 购买托管恢复
206
204
 
207
- 使用 `createFunnelPurchaseClient({ baseUrl, scope, session: customer.session, executionPolicy: { allowed: ["merchant", "record_only"] }, onRecovery })`,再通过 `showFunnelPurchase(container, { client: purchase, start: { funnelId, locale, parameters }, ...页面回调 })` 打开或恢复。`session` 必须持有后端签发的完整 Customer Session;商户用户 ID 不能代替身份证明。完整公开用法及协议边界见[英文 API 说明](README.md#managed-funnel-purchase-recovery-source-api-not-yet-published)。
205
+ 使用 `createFunnelPurchaseClient({ baseUrl, scope, session: customer.session, executionPolicy: { allowed: ["merchant", "record_only"] }, onRecovery })`,再通过 `showFunnelPurchase(container, { client: purchase, start: { funnelId, locale, parameters }, ...页面回调 })` 打开或恢复。`session` 必须持有后端签发的完整 Customer Session;商户用户 ID 不能代替身份证明。完整公开用法及协议边界见[英文 API 说明](README.md#managed-funnel-purchase-recovery)。
208
206
 
209
207
  SDK 在首次派发前保存原 Start 请求 ID 和完整输入;同一未决尝试忽略后续输入变化,拒绝换 Funnel。浏览器默认复用 Web Locks 与 revision CAS,按 API 地址、App/环境和 Customer 隔离,Start、购买引用和现有 Controller 命令日志共用一条记录。持久记录不保存 Customer access/refresh token 或 Run Token;非浏览器宿主提供原子 CAS 存储适配器。只有原 Run 已到终态、命令已结算且所有购买都有服务端终态时,才允许下一次新建;确认 Run 终止后的未执行报价由 SDK 通过原 Customer API 取消。
210
208
 
211
209
  `start()`/`refresh()` 后,`purchase.attempt` 提供原 `requestId / funnelId / locale / parameters` 的独立只读快照;加载前为 null。`resolveOfferId(selection, original)` 的第二参数提供同一原尝试上下文,领券可复用原请求身份,无需另存日志。恢复所需的商户选择应保存在首次 `parameters` 中,不能用当前配置猜回旧输入。回调结果返回时若展示已关闭、身份或尝试已变化,则拒绝继续报价。
212
210
 
211
+ `resolveOfferId` 还会收到 `featureQuantities`,按预付 Feature ID 提供本次提交的数量。无预付 Feature 的商品会传入空对象。
212
+
213
213
  购买 Host 复用 Paywall 的 `after_confirmation` 跳转策略:当前明确确认后可以打开原 Checkout 一次;重开、恢复和查询不会自动跳转。界面提供“继续付款”,点击后重读原 Operation,再决定是否打开;付款已完成、已过期或结果未知时不会打开旧地址。恢复页也可使用 `continueCheckout()`。原低层 Host 的默认行为保持兼容,完整用法见英文说明。
214
214
 
215
+ 商户关闭新购定向后,省略 `start` 并传入 `allowNewPurchase: false`,仅允许续付原单。SDK 按已登录顾客查找原单,换浏览器也能恢复。顾客只能继续原商品版本和原加购数量对应的 Checkout。关闭 Paywall 会收起界面,原单仍可在下次打开时恢复。
216
+
215
217
  `recovery.mode` 明确区分可恢复 Run、仅恢复 Operation、受阻和无原单;`status` 给出 `ready`、`waiting_result`、`checkout`、`fulfillment`、`recording`、`complete` 等状态,`actions` 给出允许动作,`confirmation` 提供可确认的原报价,`purchases` 复用 `PaywallRecovery`。恢复页可以直接调用 `refresh()`、`confirm()`、`retry()`、`continueCheckout(商户地址校验与跳转回调)`;不需要解析终态字段组合或维护锁/命令标记。退出或卸载调用 `destroy()`;共享身份切换也会终止旧消费者。
216
218
 
217
219
  `merchant` 允许 merchant Provider,`record_only` 允许商户执行的 Stripe 报价,`indiana` 允许平台执行,`native` 允许 Apple/Google。首次确认、Host 自动流程和原日志重试共用 Controller 派发边界检查;恢复时取原策略与当前策略的交集。展示继续使用现有 loading/ready/dismissed/error 生命周期,`onDismiss` 前已释放展示入口,未知 Close 和未决购买保留原单保护。Operation 购买完成不替代未知 Run/Close 的服务端结算。
218
220
 
219
- 配套的 [Customer Session 恢复协议](../../docs/funnel-storage-design.md#customer-session-recovery-protocol)使用当前原 Customer 的 Access Token;新登录会话可恢复同一原 Run,不补发 Run Token。`refresh()` 对未知 Start 只执行 `recover_start/lookup`,查不到仍受阻;首次 `start()` 和显式 `retry()` 才以原 ID、原完整输入执行 `resume`。已知 Run 使用 `recover_run`,原日志经 `settle_command` 结算后,由同一 Controller 通过 `run_command` 继续。仅可恢复 Operation 时,通过 `recover_purchase` 读取原 Receipt/Operation 及服务端重选裁决,保留原引用和未决命令;失败/取消状态不能覆盖 `canReselect: false`,命令未结算时也不提前报告完成;没有服务端负证明便不能开启替代购买。此源码要求配套 GOP 和函数迁移,尚未发布或执行远端安装;离线模拟不代表真实 Sandbox、原生 RLS 或事务锁并发验收。
221
+ 配套的 [Customer Session 恢复协议](../../docs/funnel-storage-design.md#customer-session-recovery-protocol)使用当前原 Customer 的 Access Token;新登录会话可恢复同一原 Run,不补发 Run Token。`refresh()` 对未知 Start 只执行 `recover_start/lookup`,查不到仍受阻;首次 `start()` 和显式 `retry()` 才以原 ID、原完整输入执行 `resume`。已知 Run 使用 `recover_run`,原日志经 `settle_command` 结算后,由同一 Controller 通过 `run_command` 继续。仅可恢复 Operation 时,通过 `recover_purchase` 读取原 Receipt/Operation 及服务端重选裁决,保留原引用和未决命令;失败/取消状态不能覆盖 `canReselect: false`,命令未结算时也不提前报告完成;没有服务端负证明便不能开启替代购买。托管恢复需要配套的 Indianapolis 运行时和 SQL 函数;离线模拟不代表真实 Sandbox、原生 RLS 或事务锁并发验收。
222
+
223
+ #### 预渲染首个 Paywall
224
+
225
+ `prerenderFunnelPurchase(container, { client: purchase, start, paywallVersionId 或 paywallId })` 在点击之前隐藏渲染购买 Start 首先展示的 Paywall,点击时只需显示它。预渲染不启动任何东西:没有 Run、回执、曝光或报价。点击时启动的 Run 若首个 Paywall 是同一发布版本且未被操作过,就接管这份已显示的 Paywall。完整示例见[英文说明](README.md#pre-render-the-first-paywall)。
226
+
227
+ - 公开入口的 `prerenderFunnelPurchase` 返回 Promise,需在点击前 await 得到 `PreparedFunnelPurchase`。`paywallVersionId` 指定一个确切版本,`paywallId` 指定其当前发布版本;内容通过 `purchase.readPaywall()` 按 Start 的 `parameters.commerce` 和 `locale` 读取。
228
+ - 商户自己的校验尚未完成时,`start` 可以传 Promise:渲染立即开始,拿到 Start 后才变为 ready。此时必须同时传 `commerce` 和 `locale`;最终 Start 的 commerce 或 locale 不同、为 `null` 或被拒绝时,状态为 `unavailable`。
229
+ - `state` 依次为 `preparing`、`ready`、`unavailable`(原因见 `reason`)、`shown`、`adopted`、`released`、`closed`;`ready` 在可显示时解析为 `true`,永远不能显示时为 `false`;`onState` 报告每次变化。
230
+ - 必须在点击处理函数里同步调用 `open()`(任何 await 之前):`"shown"` 表示本帧已显示;`"pending"` 表示仍在渲染,照样传给 `showFunnelPurchase`,只有在 Run 展示任何内容之前准备好才会显示,点击不会等它;`false` 表示按普通方式打开。传给 `showFunnelPurchase` 的 Start 必须与预渲染时相同(请求 ID 可以不同),`matches(start)` 可用于判断。
231
+ - 把 `prepared` 传给 `showFunnelPurchase`(或 `showFunnelRun`)即交给 SDK 管理。SDK 用不上时(该 client 已有展示、Start 不同或缺失、没有 Run、仅恢复 Operation 或受阻、失败、Run 先展示指令或其他内容)会释放它,已显示的副本不会留在屏幕上。已显示的展示在没有 Run 的情况下结束时,商户收到 `onDismiss(null)`,失败时收到 `onError`;接管前 Funnel 被暂停时,已显示的对话框与 Run 自己展示的一样被永久关闭。传出后不要再复用,需要时重新预渲染。
232
+ - 接管前的点击会等待 Run。若点击时的套餐已不是 Run 提供的套餐,该点击被拒绝(`CONFLICT`)并丢弃,Customer 需重新选择,旧选择不会被报价。接管前关闭已显示的 Paywall,会关闭为这次点击启动的 Run,且只关闭一次;同一 client 的下一次点击等该 Close 完成后重新开始。
233
+ - 渲染后超过 `maxAgeMs`(默认 5 分钟)不再显示。`purchase.retained()` 报告有未决购买时不会预渲染;在点击接手之前,若该 Customer 留下未决购买(同一个购买 client,或通过默认浏览器购买存储的其他标签页),ready 状态的副本变为 `unavailable`,Run 自身的恢复仍是最终保障。Customer 变化、`signal` 或 `destroy()` 会释放它;接管后由 Run 宿主负责。卸载时调用 `destroy()`。
234
+ - `container` 必须一直挂载且不移动,移动会重启 Paywall 的 frame。
235
+
236
+ `purchase.retained()` 只读存储,判断新的 Start 会重新开始(`"none"`、`"finished"`、`"replaceable"`)还是恢复未决原购买(`"pending"`)。`purchase.readPaywall({ paywallVersionId 或 paywallId, commerce, locale })` 为当前 Customer 读取一个已发布 Paywall 及其内容,不启动任何东西;返回的版本或 Paywall 与请求不符、或读取中 Customer 变化时拒绝。
220
237
 
221
238
  ### 独立消费方的分桶身份
222
239
 
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-LF2UIJYD.js";import"./chunk-U4RSRFZY.js";import"./chunk-KE26KWIU.js";import"./chunk-TJGIT5CU.js";import"./chunk-OX7PA64E.js";import"./chunk-V7MMTILA.js";import"./chunk-VF6QMMEA.js";import"./chunk-BID4UGWB.js";import"./chunk-WOT6VMZA.js";export{a as validateEntitlementCheck,b as validateResourceCheck};
@@ -0,0 +1 @@
1
+ import{f as ue,g as se}from"./chunk-CIP5SQ5Y.js";import{b as rn}from"./chunk-W6OQTXLL.js";import{d as nn,e as pe}from"./chunk-BOVN2BE3.js";import{c as Be,d as Ke,e as J,l as en}from"./chunk-PUR5CYWX.js";import{$ as U,D as Qe,R as Ye,W as Ze,X as We,Y as $,Z as Xe,_ as de,a as j,b as qe,c as Me,d as je,e as G,f as Ge,g as Ue,i as X,w as ee,x as ze,z as Je}from"./chunk-TAFALMQN.js";import{b as on}from"./chunk-3NCMYTNG.js";import{b as ne}from"./chunk-56BYGPQ6.js";import{a as W}from"./chunk-VYFSRHXM.js";import{$ as ce,H as L,I as De,J as Le,Y as $e,Z as le,_ as He,g as Oe,m as Ae,q as Te,y as ae}from"./chunk-BQRS7Y4K.js";import{b as D}from"./chunk-TJGIT5CU.js";import{a as f}from"./chunk-OX7PA64E.js";import{b as tn}from"./chunk-EM3MGDPG.js";import{b as n}from"./chunk-VF6QMMEA.js";import{c as _e,d as ke,e as Ve,f as z}from"./chunk-7QL4GF4C.js";import{a as Pe,b as Ne}from"./chunk-BID4UGWB.js";function an(e){return En({...e,namespace:"commands",identity:[e.runToken]})}function En(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let d=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??tn).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",d));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,o=>o.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function p(d){try{let a=await i;return await u.request(a,{mode:"exclusive"},()=>d(a))}catch(a){throw a instanceof f?a:r()}}function c(d){let a=t.getItem(d);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let o=JSON.parse(a);if(!o||typeof o!="object"||!("revision"in o)||!("entry"in o)||!Number.isSafeInteger(o.revision)||Number(o.revision)<0)throw r();return{revision:Number(o.revision),entry:o.entry}}return{read:()=>p(c),write:(d,a)=>p(o=>{if(c(o).revision!==d)return null;if(!Number.isSafeInteger(d+1))throw r();let y=JSON.stringify({revision:d+1,entry:a});if(y.length>1048576)throw r();return t.setItem(o,y),d+1})}}var un=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var q=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Pn=n.discriminatedUnion("type",[Qe,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:q.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:Ze,openIn:We}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:q})]),Nn={id:q,presentation:Te,outputs:n.array(q).max(250),inputs:ce,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Oe,customerData:Ae,dataCursors:n.record(q,$e.nullable())},On=n.strictObject({...Nn,content:n.strictObject({type:n.literal("document"),document:ae})}),me=n.strictObject({id:n.uuid(),source:un,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:q,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Cn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:le,parameters:He,variables:n.record(n.string(),L),output:L.nullable(),screen:On.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([nn,pe]),quote:ue.nullable(),operation:se.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Pn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),An=n.strictObject({scope:D,run:me,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:ue.nullable(),operation:se.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:q,visit:n.number().int().nonnegative(),document:ae,answers:le,inputs:ce,values:n.record(n.string(),L).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),sn=An.extend({run:me.extend({paywall:me.shape.paywall.unwrap().extend({resolution:pe}).nullable()})});var ln="X-Indiana-Server-Key";var H=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fe(e,t,u){let r={},i,p,c,d="next",a;switch(e.type){case"entry":a=e.next;break;case"condition":{let o=e.cases.findIndex(g=>ke(t.attributes??{},g.condition,t.savedGroups??{}));d=o<0?"default":`case:${o}`,a=o<0?e.default:e.cases[o].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new H("Required GB Feature is unavailable");i=z(e.featureKey,t),c=i.value,Object.assign(r,G(e,{value:c})),a=e.next;break;case"split":{let o=u[e.experimentId];if(!o)throw new H("Required GB Experiment is unavailable");if(p=Ve(o,t),c=p.value,d=p.inExperiment&&!p.passthrough&&typeof c=="string"?c:"notParticipating",a=d==="notParticipating"?e.notParticipating:e.routes[d],!a)throw new H("Experiment Variation has no published route");break}case"offering":{let o=e.configuration.source==="fixed"?e.configuration.versionId:z(e.configuration.featureKey,t).value;c={type:"offering_version",id:n.uuid().parse(o)},Object.assign(r,G(e,{value:c})),a=e.next;break}case"coupon":case"coupons":c=e.type==="coupons"?e.couponIds.map(o=>({type:"reward",id:o})):{type:"reward",id:e.couponId},Object.assign(r,G(e,{value:c})),a=e.next;break}return{port:d,target:a,projections:r,...c===void 0?{}:{value:c},...i?{feature:i}:{},...p?{experiment:p}:{}}}function cn(e,t,u){n.uuid().parse(e),n.number().int().nonnegative().parse(t);let r=Pe(Ne(new TextEncoder().encode(JSON.stringify([e,t,u])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var Tn=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),_n=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(Tn).max(200).default([]),iam:ze.optional(),renderGuard:ee.optional()}),ge=_n.omit({variation:!0,description:!0,iam:!0}),kn=Be.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20)}),dn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(kn).max(100),savedGroups:Ke});var Q=n.string().regex(/^[a-f0-9]{64}$/),qt=n.strictObject({iam:Q,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Vn=n.strictObject({release:Q,render:ee,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),Mt=n.strictObject({scope:D.extend({environmentId:n.uuid()}),release:Q,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),target:Vn})).max(4e3)}),jt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:Q,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),Gt=n.strictObject({scope:D,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),Ut=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),Dn=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),ye=n.strictObject({operation:n.literal("page_experiments"),release:Q,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(W).optional()}),pn=n.strictObject({scope:D,runId:n.uuid(),assignments:n.array(Dn.extend({receiptId:n.uuid()})).max(100),payload:dn});var B=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fn=n.strictObject({entry:B,nodes:n.array(n.strictObject({id:B,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),B),writes:n.record(j,j),resources:n.strictObject({screenId:B.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),mn={scope:D,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:fn},te=n.discriminatedUnion("evaluationMode",[n.strictObject({...mn,evaluationMode:n.literal("local"),growth:J,conditions:n.record(B,n.array(n.strictObject({condition:Le,port:n.string()})))}),n.strictObject({...mn,evaluationMode:n.literal("remote")})]),Ln=te.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,Me),outputSchema:qe,terminals:n.record(B,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Ye.nullable()}))})});function qn(e){return fn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let p=e.screens.find(c=>c.id===t.screenId);p?.type==="paywall"&&(r.paywallVersionId=p.paywallVersionId)}break;case"condition":t.cases.forEach((p,c)=>{u[`case:${c}`]=p.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let p of["success","cancel","unavailable","failure"])u[p]=t[p];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ve(e){let t=de.parse(e.document),u=e.evaluationMode==="local"?J.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:qn(t)};return te.parse(e.evaluationMode==="remote"?r:{...r,growth:en(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((p,c)=>({condition:p.condition,port:`case:${c}`}))]))})}function Wt(e){let t=ve(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=de.parse(e.document);return Ln.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var he=32,Mn=522240;function we(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var jn=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),Ie=n.record(n.string(),L),Gn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:$.shape.schemaVersion,kind:$.shape.kind,selector:$.shape.selector,contract:$.shape.contract}),context:Ie,removed:n.array(n.string()).max(100),attributes:Ie,removedAttributes:n.array(n.string()).max(100),result:Xe,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),or=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:jn,context:Ie,steps:n.array(Gn).min(1).max(he)}).refine(e=>X(e)<=Mn,"Segment exceeds its byte budget");var Un=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Y(e){return Array.isArray(e)?e.some(Y):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Y(u):!Un.test(t))}function gn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(d=>d.id===t.screenId&&d.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(d=>Y(d.condition)))return"customer_required";let p=JSON.stringify([t,t.type==="screen"?e.screens.find(d=>d.id===t.screenId):null]);for(let[d,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(p.includes(`variables.${d}`)||p.includes(JSON.stringify(d))))return"customer_required";if(t.type==="split"){let d=u.experiments?.[t.experimentId];if((d?.hashAttribute??"id")!=="funnelParticipantId"||Y(d?.condition)||d?.parentConditions?.length)return"customer_experiment_required"}let c=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return c&&u.features?.[c]?.rules?.some(d=>(d.hashAttribute??"id")!=="funnelParticipantId"||Y(d.condition)||d.parentConditions?.length)?"customer_experiment_required":null}var be=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},re=(e,t)=>new be(e,t),Bn=e=>({experiments:e.experiments,features:e.features});function xe(e,t=re){let u=new Map(e.topology.nodes.map(c=>[c.id,c])),r=_e(e.growth.savedGroups),i=Bn(e.growth);function p(c,d){if(!Object.hasOwn(e.growth.features,c))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return z(c,d).value}return{nodes:u,savedGroups:r,features:i.features,feature:p,evaluate(c,d){let a=u.get(c);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let o,g;if(a.type==="condition"){let I=e.conditions[a.id];if(!I)throw t("INVALID_RESPONSE","Local condition rules are unavailable");o=fe({id:a.id,name:a.id,type:"condition",cases:I.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},d,i.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=p(a.resources.featureKey,d),o="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=fe({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},d,i.experiments);g=h.value,o=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=p(a.resources.featureKey,d),o=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[o]??(o==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:c,port:o,target:y,...g===void 0?{}:{value:g}}}}}function vr(e,t,u,r=re){return Re(e,r)(t,u)}function Re(e,t){let u=te.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let p=xe(u,t);return(c,d)=>(i(),Kn(p,c,d))}function Kn(e,t,u){let r=De.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:p,onExperimentViewed:c}=u,d={attributes:r,...i?{saveStickyBucketAssignmentDoc:a=>i(structuredClone(a))}:{},...p?{onFeatureUsage:(a,o)=>p(a,structuredClone(o))}:{},...c?{onExperimentViewed:(a,o)=>c(structuredClone(a),structuredClone(o))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,d)}function Ir(e,t,u,r=re){return yn(Re(e,r),t,u)}function yn(e,t,u){let r=[],i=[],p=[],c=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(d){let a=r.findIndex(y=>y.next.attributeName===d.attributeName&&y.next.attributeValue===d.attributeValue),o=d.attributeName+"||"+d.attributeValue,g={expected:u.sticky[o]??null,next:d};a<0?r.push(g):r[a]=g},onExperimentViewed(d,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&i.push(L.parse({key:d.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(d,a){p.push(L.parse({feature:d,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:c.port,...c.value===void 0?{}:{value:c.value},sticky:r,exposures:i,features:p}}function vn(e,t,u,r=re){let i=u,p=new Map(t.graph.nodes.map(O=>[O.id,O])),c=structuredClone(u.variables),d=structuredClone(i.sticky),a=[],o=u.nodeId,g=u.visit,y=!1,I,h=O=>gn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),b=O=>(I??=Re(e,r),yn(I,O,{attributes:Je({declarations:t.variables,attributes:i.attributes,parameters:u.parameters,answers:u.answers,results:c,savedGroups:{}}),sticky:d}));for(let O=0;O<he;O++){let s=p.get(o);if(!s||!we(s)||h(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let m,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")m=b(s.id),s.type==="offering"&&(m.value={type:"offering_version",id:String(m.value)}),s.type==="condition"?x=m.port==="default"?s.default:s.cases[Number(m.port.slice(5))]?.target:s.type==="split"?x=m.port==="notParticipating"?s.notParticipating:s.routes[m.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(m={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(m.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let R=s.type==="end"?s.output:s.value;if(m=R?.type==="feature"?b(s.id):{...m,port:"value",value:R?.type==="literal"?R.value:R?.type==="variable"?Ue({source:"variable",key:R.key,...R.path?{path:R.path}:{}},{declarations:t.variables,answers:u.answers,results:c,parameters:u.parameters,attributes:i.attributes,savedGroups:{}}):null},R&&(m.value===void 0||!je(t.outputSchema,m.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let C=[...a,{nodeId:o,result:m}];if(X({steps:C})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:o,result:m}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let R=s.type==="coupons"?s.couponIds.map(V=>({type:"reward",id:V})):s.type==="coupon"?{type:"reward",id:s.couponId}:m.value;if(R===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=G(s,{value:R});Ge(t.variables,s,_),Object.assign(c,_)}for(let R of m.sticky)d[`${R.next.attributeName}||${R.next.attributeValue}`]=structuredClone(R.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");o=x,g++}let T=p.get(o);return{steps:a,...!y&&T&&(!we(T)||h(T))?{boundary:{nodeId:o,visit:g}}:{}}}function In(e,t){let u=sn.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var Se=(e,t)=>new f(e,t);function Fr(e){return xe(e,Se)}var zn=3,Jn=2e3;function $n(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Hn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===zn||!$n(u))throw u;await new Promise(r=>setTimeout(r,t*Jn))}}async function Fe(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let i=null,p;if(u)try{let c=await e.funnel(t.source.id,t.source.versionId);p=c.manifest.generation,i=Qn(e,t,c)}catch{i=null}return p??=e.snapshot?.generation??(await Hn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:p},prediction:i}}function Qn(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:p,...c}=u.growth,d=ve({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:J.parse(c)}),a=Yn(d,u.document,{...t,...r}),o=a.steps.at(-1),g=a.boundary??(o?.result.port==="value"?{nodeId:o.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Yn(e,t,u){return vn(e,t,u,Se)}var hn=U.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),wn=n.strictObject({schemaVersion:n.literal(1),scope:D,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:hn.optional(),closeCommand:hn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),oe=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Z(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function bn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),i=Promise.resolve();async function p(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:wn.parse(a.entry)}}function c(a){let o=i.then(a);return i=o.catch(()=>{}),o}async function d(a){for(let o=0;o<4;o++){let g=await p();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(oe(g.entry,y)){t=g.revision;return}let I=await e.write(g.revision,y);if(I!==null){if(!Number.isSafeInteger(I)||I<=g.revision)throw A();t=I;return}}throw A()}return{bind(a){let o=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==o)throw A();u=o},async load(){let a=await p();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let o=wn.parse(a),g=o.command;return!g||u!==null&&r(o)!==u?Promise.reject(A()):(u??=r(o),c(()=>d((y,I)=>{if(y&&!oe(r(y),r(o)))throw A();if(y&&o.processBindingIds){for(let[h,b]of Object.entries(o.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==b)throw A();y={...y,processBindingIds:{...y.processBindingIds,...o.processBindingIds}}}if(!y){if(I!==t&&g.operation!=="close")throw A();return o}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!oe(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!oe(y.command,g))throw A();return y})))},observePurchase(a,o,g,y){return c(()=>d((I,h)=>{if(!I&&h!==t||I&&r(I)!==r({...a,schemaVersion:1}))throw A();if(I?.purchase&&I.purchase.generation>o.generation)return Z(I,y);if(I?.purchase&&I.purchase.generation===o.generation&&I.purchase.operationId!==o.operationId)throw A();return g?!I?.purchase||I.purchase.operationId!==o.operationId?Z(I,y):Z(I.command?{...I,purchase:void 0}:null,y):Z({schemaVersion:1,...a,...I,purchase:o},y)}))},settle(a){return c(()=>d(o=>Z(o,a)))}}}function qr(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function ie(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,p)=>ie(i,t[p]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([i,p])=>Object.hasOwn(t,i)&&ie(p,Reflect.get(t,i)))}function xn(e,t){let u=t&&{...t},r=null,i=0,p=-1,c=0,d=new AbortController;function a(){c++,d.abort(new f("IDENTITY_CHANGED","Run identity changed")),d=new AbortController}let o=!1,g,y=0,I=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new f("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return p===c?r:null},get viewAgeMs(){return r&&p===c?performance.now()-i:void 0},get generation(){return c},get signal(){return d.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,b="Run identity changed during the request"){if(h!==c||o)throw new f("IDENTITY_CHANGED",b)},assertRun(h){if(r&&(h.id!==r.id||h.source.type!==r.source.type||h.source.id!==r.source.id||h.source.versionId!==r.source.versionId||h.locale!==r.locale||!ie(h.parameters,r.parameters)))throw new f("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,b,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&p===c&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,i=performance.now(),p=c;else if(!s)return;if(r&&p===c)for(let m of I)try{m(structuredClone(r))}catch{}}},identify(h){if(o)throw new f("IDENTITY_CHANGED","Controller was reset");if(!W.test(h))throw new f("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return I.add(h),()=>I.delete(h)},reset(){o||(o=!0,a(),g=void 0,r=null,I.clear())}}}var Ee=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function zr(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Ee.test(e))throw new f("INVALID_TOKEN",u)}function Jr(e){let t=ne(e);return t.identify(e.apiKey),t}function Rn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&["apple","google"].includes(t.provider)?"native":t?.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function M(e){let{customerToken:t,...u}=e;return u}var Zn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function Sn({journal:e,state:t,call:u,processIdentity:r}){let i=null,p=null,c=!1,d={command:null,close:null},a=new Set,o,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(o=s.purchase,c=s.closed===!0,!s.command)return;let m=s.command;i=m.operation==="close"?null:m,p=m.operation==="close"?m:s.closeCommand?.operation==="close"?s.closeCommand:null,p&&(c=!0);for(let x of[i,p])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function I(s){e&&await y;let m=t.generation;if(e){if(!t.view||!t.scope)throw new f("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:M(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(m!==t.generation||i!==s&&p!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(C){let R=s.operation==="submit"&&s.input.type==="paywall_quote",_=!x&&!Zn(C),V=!1;if(R&&_&&m===t.generation&&i===s&&C instanceof f&&C.status!==void 0){let l=await T(s.requestId).catch(()=>{});V=l?.settlement?.state==="unknown"&&l.settlement.operationId===null}throw m===t.generation&&(i===s||p===s)&&_&&(!R||!(C instanceof f)||C.status===void 0||V)&&(e&&await e.settle(s.requestId),m===t.generation&&O(s)),C}}function h(s){let m=U.parse(s);if(m.operation==="start"||m.operation==="get"||m.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(c&&m.operation!=="close"){if(i?.requestId===m.requestId)return T(m.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(m.operation==="close"){if(i?.requestId===m.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(c=!0,p&&JSON.stringify(M(p))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original Close");return p??=m,d.close?d.close:b(p,"close")}if(i){if(JSON.stringify(M(i))!==JSON.stringify(M(m)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(d.command)return d.command}else i=m;return b(i,"command")}function b(s,m){let x=I(s);d[m]=x;let C=()=>{d[m]===x&&(d[m]=null)};return x.then(C,C),x}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||i!==s&&p!==s?!1:(i===s&&(i=null),p===s&&(p=null),a.delete(s.requestId),!i&&!p&&(g=null),!0)}return{ready:y,get pending(){return i},get closing(){return p},get closeRequested(){return c},get inFlight(){return d.command},get closeFlight(){return d.close},get purchase(){return o},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,m,x,C){let R=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=R&&m.settlement?.state==="settled"&&m.run.pendingRequest?.requestId!==R&&(s.operation==="get"||!c||s.operation==="close"||!["running","waiting"].includes(m.run.status))?R:void 0,V=i?.requestId===_?i:p?.requestId===_?p:void 0;e?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId});let l=m.run.paywall,v=l??m.purchase,P=v?.operation,E=m.settlement&&(!l||l.purchaseRequestId===m.settlement.requestId)&&(!o||o.operationId===m.settlement.operationId)?m.settlement:void 0,S=P?.operationId??v?.quote?.operationId??E?.operationId,F=v?.receiptId??E?.receiptId,w=l?.selectionGeneration??o?.generation??0;if(e&&S&&F&&s.operation!=="review"&&(!t.view||m.run.revision>=t.view.revision)&&(C===void 0||C>=t.readSequence)&&(!o||w>=o.generation)){let N={receiptId:F,operationId:S,generation:w},k=on(P,v?.canReselect===!0);await e.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},N,k,_),t.assertCurrent(x),(!o||N.generation>=o.generation)&&(C===void 0||C>=t.readSequence)&&(k?o?.operationId===N.operationId&&(o=void 0):o=N)}else e&&_&&await e.settle(_);return t.assertCurrent(x),_?O(V):!1},stop(){c=!0},submit:h,settle:T,reset(){c=!0,i=null,p=null,o=void 0,g=null,d.close=null,a.clear(),d.command=null}}}function Wn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Ee.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=ne({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),i=xn(e.funnelId,e.scope??e.configuration?.scope),p=e.session?.subscribeIdentity(b),c=null,d=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?an(e):void 0),a=d&&bn(d),o=Sn({journal:a,state:i,call:T,processIdentity:e.process}),g=0,y=new Map;function I(){g++,y.clear(),t=void 0}async function h(l){let v=l.operation==="resume"?o.pending?.operation==="resume"?null:o.pending:l;if(u&&l.operation==="resume"&&!v&&l.requestId!==e.customerRun?.startRequestId)throw new f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(v?.operation==="submit"&&v.input.type==="paywall_confirm"){let N=i.view?.paywall;Rn(u,N?.quote?.operationId===v.input.operationId?N.quote:void 0)}if(e.process)return e.process.request(l);let P=i.generation;i.assertCurrent(P);let E=performance.now()+(e.timeoutMs??35e3),S=i.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let N=i.signal,k,K=()=>{},Fn=new Promise((Xn,Ce)=>{K=()=>Ce(N.reason),N.addEventListener("abort",K,{once:!0}),k=setTimeout(()=>Ce(new f("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{S=await Promise.race([Promise.resolve().then(()=>(i.assertCurrent(P),e.session.access())),Fn])}finally{clearTimeout(k),N.removeEventListener("abort",K)}}i.assertCurrent(P);let F={...l,...S?{customerToken:S}:{}},w=l.operation==="page_experiments"?ye.parse(F):U.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!S)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let N={...w};return"customerToken"in N&&delete N.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:N},S,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!S?{[ln]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function b(){I(),p?.(),i.reset(),o.reset(),c=null,r.dispose()}async function T(l,v){let P=t;t=void 0;let E=i.generation,S=()=>i.assertCurrent(E);a&&await o.ready,S();let F=i.view,w=In(e,P!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?P:await h(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(S(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let N=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(N&&w.settlement?.requestId!==N)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(w),i.assertRun(w.run),i.bindScope(w.scope);let k=await o.observe(l,w,E,v);return(!i.view||w.run.revision>=i.view.revision)&&(v===void 0||v>=i.readSequence)&&(await e.onAcceptedResponse?.(w),S()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(S(),["running","waiting"].includes(w.run.status)||o.stop(),i.publish(l,w,F,v,k)),w}function O(l){let v=i.generation;I();let P=l(),E=()=>{i.generation===v&&I()};return P.then(E,E),P}let s=l=>O(()=>o.submit(l)),m=null,x=new WeakMap;function C(l){let v=x.get(l);if(v)return v;let P=_(l);return x.set(l,P),P}let R=!1;async function _(l){let v=await l;if(v.run.instruction?.type!=="evaluate_segment")return v;if(m)return m;R=!0;let P=i.generation,E=(async()=>{for(let S=0;S<32&&v.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return v;let F=v.run;if(v.run.instruction?.type==="evaluate_segment"){let{advance:N}=await Fe(e.configuration,F,{predict:!1});if(P!==i.generation)throw new f("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return v;if(i.view&&(i.view.revision!==F.revision||i.view.visit!==F.visit||i.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Fe(e.configuration,F).then(({prediction:K})=>{k&&P===i.generation&&!o.closeRequested&&i.view?.id===F.id&&!i.view.stopped&&i.view.nodeId===F.nodeId&&i.view.visit===F.visit&&i.view.revision===F.revision&&(c=K)}).catch(()=>{});try{v=await s({operation:"commit_segment",requestId:cn(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...N})}finally{k=!1,c=null}}}return v})();m=E;try{return await E}finally{m===E&&(m=null)}}let V={get configuration(){return R?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=i.currentView;return l?structuredClone(l):null},get viewAgeMs(){return i.viewAgeMs},get pendingCommand(){let l=o.closing??o.pending;return l?structuredClone(M(l)):null},get pendingCommands(){return[o.pending,o.closing].filter(l=>l!==null).map(l=>structuredClone(M(l)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=i.view;return c&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===c.runId&&l.nodeId===c.from.nodeId&&l.visit===c.from.visit&&l.revision===c.from.revision&&!o.closeRequested?structuredClone(c):null},settle:(...l)=>O(()=>o.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return rn(e,l)},async pageExperiments(l,v=[]){let P=i.generation;i.assertCurrent(P);let E=i.view?.id;if(!E)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let S=pn.parse(await h(ye.parse({operation:"page_experiments",release:l,usedReceiptIds:v})));if(i.assertCurrent(P),S.runId!==E||S.scope.projectId!==i.scope?.projectId||S.scope.environment!==i.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return S},review(l){return T({operation:"review",...l?{receiptId:l}:{}},i.nextRead())},async get(l,v){let P=i.generation;l=l&&structuredClone(l),v=v&&{...v},a&&await o.ready,i.assertCurrent(P),v??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let E=JSON.stringify([i.generation,g,l??null,v??null]),S=y.get(E);if(S)return S.then(k=>structuredClone(k));let F=i.nextRead(),w=C(T({operation:"get",...l?{data:l}:{},...v?{purchase:v}:{}},F));y.set(E,w);let N=()=>{y.get(E)===w&&y.delete(E)};return w.then(N,N),w.then(k=>structuredClone(k))},resume(l=i.view?.pendingRequest?.requestId){return l?o.closeRequested?V.settle(l):o.pending?.requestId===l?C(s(o.pending)):C(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return C(s(l))},async retry(){if(o.closeFlight)return o.closeFlight;if(o.closing)return s(o.closing);if(o.closeRequested&&o.pending)return V.settle(o.pending.requestId);if(o.inFlight)return C(o.inFlight);if(!o.pending)throw new f("INVALID_REQUEST","No command is pending");let l=o.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let v=i.generation;if(await V.settle(l.requestId),i.assertCurrent(v),!o.pending)return V.get();if(o.pending!==l||o.closeRequested)throw new f("COMMAND_PENDING","The original quote is being recovered")}return C(s(l))},identify(l){let v=i.customerToken?void 0:t;I(),i.identify(l),t=v,c=null,r.reset()},get identitySignal(){return i.signal},subscribe:i.subscribe,reset:b};return V}function go(e,t){return Wn({...e,runToken:"",initialResponse:t})}export{cn as a,un as b,Pn as c,me as d,An as e,sn as f,Vn as g,Mt as h,jt as i,Gt as j,ye as k,pn as l,te as m,Ln as n,Wt as o,vr as p,Ir as q,In as r,Se as s,Fr as t,Yn as u,wn as v,Z as w,an as x,En as y,qr as z,ie as A,Ee as B,zr as C,Jr as D,Rn as E,Wn as F,go as G};
@@ -0,0 +1 @@
1
+ function d(t){let{quote:o,operation:e,requestId:p}=t,a={type:"recover",operationId:e?.operationId??o?.operationId??null,requestId:p};if(t.destroyed||t.pending)return a;if(!e)return o?{type:"cancel",operationId:o.operationId}:a;let r=e.merchantExecution;if(r?.type==="purchase"){if(["succeeded","not_required"].includes(r.paymentStatus))return!["applied","not_applicable"].includes(r.fulfillmentStatus)||e.problem?.phase==="fulfillment"||r.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:r.recordingStatus==="accepted"&&e.status==="complete"&&!e.problem&&!r.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&e.checkoutUrl&&!e.problem&&!r.problem&&r.checkoutUrl===e.checkoutUrl&&r.checkoutExpiresAt&&Date.parse(r.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(r.paymentStatus))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl}}if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&!e.nativePurchase&&(!o||Date.parse(o.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let c=[e.problem,r?.problem],l=c.every(i=>!i||i.phase==="execution"&&i.reason!=="RESULT_UNKNOWN"),u=e.status==="cancelled"&&!c.some(Boolean)&&r?.type==="purchase"&&["pending","not_started","expired"].includes(r.paymentStatus)&&["not_started","not_applicable"].includes(r.fulfillmentStatus);return t.canReselect===!0&&l&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"||!r||r.type==="purchase"&&!["succeeded","not_required"].includes(r.paymentStatus)&&(u||r.recordingStatus==="accepted"&&r.fulfillmentStatus==="not_applicable"))?{type:"native",operationId:e.operationId}:!c.some(Boolean)&&e.status==="complete"&&e.executor!=="merchant"?{type:"complete",operationId:e.operationId}:l&&t.canReselect!==!1&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"?!e.confirmedAt&&(e.status==="cancelled"||!e.quoteFinalized):!r&&!e.quoteFinalized||r?.type==="purchase"&&["failed","expired"].includes(r.paymentStatus)&&r.fulfillmentStatus==="not_applicable"&&r.recordingStatus==="accepted")?{type:"native",operationId:e.operationId}:e.status==="pending"&&l&&!e.quoteFinalized&&!r&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase?{type:"cancel",operationId:e.operationId}:a}function y(t,o=!0){if(!t)return!1;let e=d({quote:t.quote??null,operation:t,requestId:null,pending:!1,destroyed:!1,canReselect:o});return e.type==="complete"||e.type==="native"}function n(t){return t.recovery??{type:"recover",operationId:t.operation?.operationId??t.quote?.operationId??null,requestId:null}}function f(t){return!!(t?.operationId&&(t.type==="checkout"||t.type==="recover"||t.type==="fulfillment"||t.type==="recording"))}async function m(t){let o=n(t);if(o.type==="recover"&&t.quote)try{await t.read(),o=n(t)}catch{return o}if(o.type!=="cancel"&&!(o.type==="recover"&&t.pendingCancellation))return o;try{await t.cancel();let e=n(t);return e.type==="cancel"?{type:"recover",operationId:o.operationId,requestId:null}:e}catch{let e=n(t);return e.type==="recover"?e:{type:"recover",operationId:o.operationId,requestId:null}}}export{d as a,y as b,n as c,f as d,m as e};
@@ -0,0 +1 @@
1
+ import{a as tt,b as it}from"./chunk-WZR2XCSJ.js";import{a as Ut,b as Mt,d as Et,h as Z,i as fe}from"./chunk-7MNJH5GB.js";import{a as st,b as de,c as P,d as ot,e as I,f as ct,g as me,h as ut,i as dt,j as mt,k as pe,l as pt,m as lt,n as le}from"./chunk-CIP5SQ5Y.js";import{i as f,j as He,u as N}from"./chunk-CKKIB2HC.js";import{a as V,b as rt,c as Tt,e as kt}from"./chunk-BOVN2BE3.js";import{f as gt,h as ht,i as ft,j as bt,k as xt}from"./chunk-PUR5CYWX.js";import{F as he,G as Ct,L as Q,M as _t,N as Rt,O as wt,P as Bt,Q as qt,o as nt,p as y,r as ue,s as at}from"./chunk-TAFALMQN.js";import{a as zt}from"./chunk-5HJYR6Z4.js";import{a as We,b as F}from"./chunk-VYFSRHXM.js";import{M as B,N as St,O as yt,P as It,Q as q,R as vt,S as Ot,T as ge,U as j,V as At,W as Pt,X as jt}from"./chunk-BQRS7Y4K.js";import{a as c,e as Xe,f as Je,g as Ye,h as et,j as ce}from"./chunk-U4RSRFZY.js";import{b as se,c as p,d as s,e as oe,g as h}from"./chunk-TJGIT5CU.js";import{b as e}from"./chunk-VF6QMMEA.js";var be=e.strictObject({operationId:e.uuid(),customerId:e.uuid(),externalUserId:e.string().min(1).max(256),modelId:e.string().min(1).max(256),quantity:e.number().int().min(1).max(1e6),validForDays:e.number().int().min(1).max(3660)}),Dt=e.strictObject({operationId:e.uuid(),customerId:e.uuid(),status:e.literal("applied"),voucherId:e.uuid(),modelId:e.string().min(1).max(256),quantity:e.number().int().positive(),issuedAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0})}).refine(t=>Date.parse(t.expiresAt)>Date.parse(t.issuedAt),{message:"A benefit must expire after it is issued"}),Gt=e.strictObject({operationId:e.uuid(),customerId:e.uuid()}),xa=e.discriminatedUnion("lookup",[Gt.extend({lookup:e.literal("not_received")}),Gt.extend({lookup:e.literal("found"),result:Dt}).refine(t=>t.result.operationId===t.operationId&&t.result.customerId===t.customerId)]),$t=e.strictObject({customerId:e.string().min(1).max(256),modelId:e.string().min(1).max(256),quantity:be.shape.quantity,validForDays:be.shape.validForDays,requestId:e.uuid()}),Lt=e.strictObject({customerId:e.string().min(1).max(256),operationId:e.uuid()}),xe=e.strictObject({operationId:e.uuid(),customerId:e.uuid(),taskId:e.uuid(),status:e.enum(["pending","applied","rejected"]),terms:be,receipt:Dt.nullable(),failureCode:e.enum(["INVALID_REQUEST","CONNECTION_CHANGED"]).nullable()}).superRefine((t,n)=>{(t.terms.operationId!==t.operationId||t.terms.customerId!==t.customerId||t.status==="applied"!=(t.receipt!==null)||t.status==="rejected"!=(t.failureCode!==null)||t.receipt&&(t.receipt.operationId!==t.operationId||t.receipt.customerId!==t.customerId||t.receipt.modelId!==t.terms.modelId||t.receipt.quantity!==t.terms.quantity))&&n.addIssue({code:"custom",message:"Benefit result differs from the original accepted operation"})});var T=e.enum(["email","sms","voice","push"]),Ia=e.enum(["resend","twilio","fcm","apns"]);var va=e.string().regex(/^\+[1-9]\d{1,14}$/),Qr=e.enum(["email_recipient","sms_segment","voice_second","push_device"]);var Zr=e.string().trim().min(1).max(200).refine(t=>!/[\r\n\0]/.test(t),"Invalid email header"),Kr=e.strictObject({subject:Zr,html:e.string().min(1).max(131072).optional(),text:e.string().min(1).max(65536).optional()}).refine(t=>t.html!==void 0||t.text!==void 0,{message:"Email requires HTML or text content"}),Wr=e.strictObject({body:e.string().min(1).max(1600).refine(t=>t.trim().length>0)}),Hr=e.strictObject({text:e.string().trim().min(1).max(4e3),language:e.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:e.number().int().min(1).max(900)}),Xr=e.record(e.string().min(1).max(64),e.string().max(256)).refine(t=>Object.keys(t).length<=20&&Object.keys(t).every(n=>!/^(?:indiana_|google\.|gcm\.)/i.test(n)&&n!=="aps"),"Push data contains reserved fields or too many entries"),Jr=e.strictObject({title:e.string().trim().min(1).max(200),body:e.string().trim().min(1).max(2e3),url:e.url().max(2048).refine(t=>!/^(?:javascript|data|file|vbscript):/i.test(t)).optional(),data:Xr.optional()}).refine(t=>new TextEncoder().encode(JSON.stringify(t)).length<=3072,"Push content exceeds the provider payload budget"),Ft=e.discriminatedUnion("channel",[e.strictObject({channel:e.literal("email"),content:Kr}),e.strictObject({channel:e.literal("sms"),content:Wr}),e.strictObject({channel:e.literal("voice"),content:Hr}),e.strictObject({channel:e.literal("push"),content:Jr})]),Nt=e.strictObject({requestId:e.uuid(),customerId:e.uuid(),connectionId:e.uuid().optional(),message:Ft,expiresAt:e.iso.datetime({offset:!0})}),Yr=e.array(e.uuid()).min(1).max(1e4).refine(t=>new Set(t).size===t.length,"Duplicate Customer"),en=e.discriminatedUnion("kind",[e.strictObject({kind:e.literal("all")}),e.strictObject({kind:e.literal("customers"),customerIds:Yr})]),Oa=e.strictObject({name:e.string().trim().min(1).max(120),connectionId:e.uuid().optional(),message:Ft,audience:en,frequencyLimit:e.number().int().min(1).max(100)}),Vt=e.strictObject({requestId:e.uuid(),channel:T,state:e.enum(["allowed","denied"]),expectedRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Qt=e.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Zt=e.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),Aa=e.strictObject({meter:Qr,estimatedUnits:e.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:e.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var Kt=e.strictObject({requestId:e.uuid(),targets:e.array(e.strictObject({membershipId:e.uuid(),action:e.enum(["cancel","uncancel"]),timing:e.enum(["immediate","renewal"])}).refine(t=>t.action!=="uncancel"||t.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(t=>new Set(t.targets.map(n=>n.membershipId)).size===t.targets.length,"Duplicate batch target"),K=e.strictObject({batchId:e.uuid()}),tn=e.strictObject({operationId:e.uuid(),membershipIds:e.array(e.uuid()).min(1).max(20),provider:e.enum(["stripe","apple","google"]),action:e.enum(["cancel","uncancel"]),timing:e.enum(["immediate","renewal"]),status:e.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:dt.nullable(),managementUrl:e.url().nullable(),failureCode:e.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),k=e.strictObject({batchId:e.uuid(),ready:e.boolean(),status:e.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:e.iso.datetime({offset:!0}),acceptedAt:e.iso.datetime({offset:!0}).nullable(),groups:e.array(tn).min(1).max(100)});var rn=e.string().trim().min(1).max(240),Se={requestId:e.uuid(),reason:rn},W=e.discriminatedUnion("action",[e.strictObject({...Se,action:e.literal("start"),productVersionId:e.uuid(),entityId:e.uuid().optional(),days:e.number().int().min(1).max(730).optional()}),e.strictObject({...Se,action:e.literal("extend"),membershipId:e.uuid(),days:e.number().int().min(1).max(730)}),e.strictObject({...Se,action:e.literal("end"),membershipId:e.uuid()})]),Wt=e.strictObject({operationId:e.uuid()}),Ht=e.iso.datetime({offset:!0}),nn=e.strictObject({provider:e.literal("stripe"),executor:e.enum(["indiana","merchant"]),accountId:e.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:e.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:e.union([e.literal("now"),Ht]),prorationBehavior:e.literal("none")}),ye=e.strictObject({operationId:e.uuid(),action:e.enum(["start","extend","end"]),status:e.enum(["pending","effective"]),managedBy:e.enum(["indiana","stripe"]),membershipIds:e.array(e.uuid()).min(1).max(20),endsAt:Ht.nullable(),execution:nn.nullable()}).refine(t=>t.execution!==null==(t.managedBy==="stripe"&&t.status==="pending")&&t.action==="end"==(t.endsAt===null)&&(t.action!=="start"||t.managedBy==="indiana")&&(t.execution===null||t.execution.trialEnd==="now"==(t.action==="end")),"Only a pending Stripe trial change carries execution instructions"),wa=e.strictObject({groupId:e.uuid(),productVersionId:e.uuid(),enabled:e.boolean()});var Xt=e.strictObject({requestId:e.uuid(),currency:c,makeDefault:e.boolean()}),Jt=e.strictObject({setupId:e.uuid()}),an=e.strictObject({provider:e.literal("stripe"),executor:e.literal("merchant"),accountId:e.string().regex(/^acct_[A-Za-z0-9]+$/),mode:e.literal("setup"),currency:e.string().regex(/^[a-z]{3}$/),customer:e.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:e.uuid(),metadata:e.strictObject({grooveProjectId:e.uuid(),grooveEnvironmentId:e.uuid(),grooveCustomerId:e.uuid(),groovePaymentSetupId:e.uuid()}),setDefaultPaymentMethod:e.boolean(),expiresAt:e.iso.datetime({offset:!0})}),Ie=e.strictObject({id:e.uuid(),provider:e.literal("stripe"),status:e.enum(["prepared","complete","expired"]),currency:c,makeDefault:e.boolean(),url:e.url().nullable(),createdAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0}),completedAt:e.iso.datetime({offset:!0}).nullable(),execution:an.nullable()});var Yt=e.union([e.string(),e.number(),e.boolean(),e.null()]),ei=e.strictObject({customerId:e.uuid()}),ti=e.strictObject({customerId:e.uuid(),provider:e.literal("stripe"),checkedAt:e.iso.datetime({offset:!0}),status:e.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:e.number().int().nonnegative(),differences:e.array(e.strictObject({subscriptionId:e.string().startsWith("sub_"),itemId:e.string().nullable(),field:e.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Yt,actual:Yt})).max(1e4)});var H=e.iso.datetime({offset:!0}),X=e.strictObject({createdAt:H,id:e.uuid()}),J=e.strictObject({customerId:e.uuid().optional(),entityId:e.uuid().optional(),productId:e.string().min(1).max(256).optional(),provider:e.enum(["stripe","apple","google","merchant","free"]).optional(),status:e.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:X.optional(),limit:e.number().int().min(1).max(100).optional()}),ve={id:e.uuid(),customerId:e.uuid(),entityId:e.uuid().nullable(),productId:e.string().min(1).max(256),productVersionId:e.uuid(),name:e.string().min(1).max(120),provider:e.enum(["stripe","apple","google","merchant","free"]),createdAt:H},sn=e.strictObject({...ve,status:e.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:e.boolean(),billingSubscriptionId:e.uuid().nullable()}),on=e.strictObject({...ve,status:e.enum(["active","ended","refunded"]),orderId:e.uuid().nullable(),transactionId:e.uuid().nullable(),currency:c.nullable(),amountMinor:e.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),cn=e.strictObject({...ve,status:e.enum(["blocked","resolved"]),conflict:e.strictObject({detectedAt:H,blockingMembershipIds:e.array(e.uuid()).min(1).max(100),transactionId:e.uuid()}),resolvedAt:H.nullable()}),ii=J.extend({status:e.enum(["blocked","resolved"]).optional()}),ri=e.strictObject({customerId:e.uuid(),orderId:e.uuid()}),ni=e.strictObject({orderId:e.uuid(),status:e.enum(["blocked","resolved"])}),ai=e.strictObject({items:e.array(sn).max(100),nextCursor:X.nullable()}),si=e.strictObject({items:e.array(on).max(100),nextCursor:X.nullable()}),oi=e.strictObject({items:e.array(cn).max(100),nextCursor:X.nullable()});var ci=e.union([e.strictObject({intent:e.literal("read"),requestId:e.uuid(),purchaseIntentId:e.uuid()}),e.strictObject({requestId:e.uuid(),provider:e.literal("apple"),purchaseIntentId:e.uuid(),productId:e.string().min(1).max(255).optional(),signedTransaction:e.string().min(1).max(131072)}),e.strictObject({requestId:e.uuid(),provider:e.literal("google"),purchaseIntentId:e.uuid(),productId:e.string().min(1).max(255).optional(),purchaseToken:e.string().min(1).max(16384)})]),ui=e.strictObject({requestId:e.uuid(),orderId:e.uuid(),purchaseIntentId:e.uuid(),status:e.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:c,refunded:e.boolean(),completion:e.strictObject({transactionIds:e.array(e.string().min(1).max(255)).min(1).max(50).refine(t=>new Set(t).size===t.length),membership:e.boolean()}).nullable()});var un=e.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),pi=e.enum(["single_use","continuous_use"]),Oe=e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string())),di=e.string().min(1).max(64).refine(t=>!t.includes("::")),li={credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()},gi={credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(e.strictObject({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()}))},dn=e.union([e.strictObject({match:Oe,priority:e.number().int().optional(),...li}),e.strictObject({match:Oe,priority:e.number().int().optional(),...gi})]),mn=e.strictObject({match:Oe,factor:e.number().positive().optional(),add:e.number().optional()}).refine(t=>t.factor!==void 0||t.add!==void 0),mi={metered_feature_id:e.string(),feature_amount:e.number().optional(),dimensions:e.record(di,dn).optional(),multipliers:e.record(di,mn).optional()},Ae=e.union([e.strictObject({...mi,...li}),e.strictObject({...mi,...gi})]),ee=e.number().min(-100),hi=e.record(e.string(),e.strictObject({markup:ee})).nullish(),te=e.record(e.string().regex(/.+\/.+/),e.strictObject({markup:ee.optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish(),pn=e.strictObject({default_markup:ee.optional(),provider_markups:hi,model_markups:te}),Na=e.strictObject({schema:e.array(Ae).optional(),markups:pn.optional()}),ln=e.strictObject({filters:e.array(e.strictObject({property:e.string(),operator:e.string(),value:e.array(e.string())})),aggregate:e.strictObject({type:e.string(),property:e.string().nullable()}),usage_type:pi}),fi=e.strictObject({schema:e.array(Ae).min(1).refine(t=>new Set(t.map(n=>n.metered_feature_id)).size===t.length,"Credit rates must name each metered feature once"),invoice_credit:e.boolean().optional(),usage_type:pi.default("single_use").overwrite(()=>"single_use"),default_markup:ee.optional(),provider_markups:hi}),Pe=fi.safeExtend({schema:e.array(Ae).length(0)}),Y={id:un,name:e.string().min(1),display:e.strictObject({singular:e.string().optional(),plural:e.string().optional()}).nullish(),event_names:e.array(e.string()).default([]),model_markups:te,stripe_meter:e.strictObject({id:e.string(),event_name:e.string()}).nullish(),stripe_product_id:e.string().nullish()},je=t=>e.discriminatedUnion("type",[e.strictObject({...Y,...t,type:e.literal("boolean"),config:e.null()}),e.strictObject({...Y,...t,type:e.literal("metered"),config:ln}),e.strictObject({...Y,...t,type:e.literal("credit_system"),config:fi}),e.strictObject({...Y,...t,type:e.literal("ai_credit_system"),config:Pe})]),Va=je({}),gn=e.strictObject({id:e.boolean(),type:e.boolean(),usage_type:e.boolean()}),hn={internal_id:e.uuid(),org_id:e.uuid(),created_at:e.number(),env:e.enum(["sandbox","live"]),archived:e.boolean(),project_id:e.uuid(),environment_id:e.uuid(),revision:e.number().int().nonnegative(),update_rules:gn},bi=je(hn),Qa=e.strictObject({rows:e.array(bi).max(200),nextCursor:e.uuid().nullable()}),Za=e.strictObject({features:e.array(bi).max(500),limited:e.boolean()}),Ka=e.union([je({action:e.literal("save"),internal_id:e.uuid().nullable(),revision:e.number().int().nonnegative()}),e.strictObject({action:e.enum(["archive","restore","delete"]),internal_id:e.uuid(),revision:e.number().int().nonnegative()})]);var _e=e.uuid().refine(t=>t===t.toLowerCase(),"Product references require canonical lowercase UUIDs"),fn=e.record(e.string(),e.json()).refine(t=>Array.from(JSON.stringify(t)).length<=4e3,"Offering metadata exceeds 4000 characters"),bn=3,z=20,xn=bn*z,Ce=e.strictObject({type:e.literal("product"),productId:_e}),xi={type:e.literal("group"),key:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:e.string().trim().min(1).max(80)},Sn=e.discriminatedUnion("type",[Ce,e.strictObject({...xi,items:e.array(Ce).max(z)})]),yn=e.discriminatedUnion("type",[Ce,e.strictObject({...xi,items:e.array(Sn).max(z)})]),In=e.array(yn).max(z).superRefine((t,n)=>{let a=new Set,o=new Set,m=0;function Qe(Vr){for(let S of Vr){m++;let Ze=S.type==="product"?a:o,Ke=S.type==="product"?S.productId:S.key;Ze.has(Ke)&&n.addIssue({code:"custom",message:S.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),Ze.add(Ke),S.type==="group"&&Qe(S.items)}}Qe(t),(a.size>z||m>xn)&&n.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Re(t){return t.items.flatMap(n=>n.type==="product"?[n.productId]:Re(n))}var C=e.strictObject({lookupKey:e.string().trim().min(1).max(200),displayName:e.string().trim().min(1).max(1500),items:In,metadata:fn}),vn=e.strictObject({product:e.record(e.string(),e.json()),prices:e.array(e.record(e.string(),e.json())),entitlements:e.array(e.record(e.string(),e.json())),freeTrials:e.array(e.record(e.string(),e.json())),licenses:e.array(e.record(e.string(),e.json()))}),Si=C.extend({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),state:e.enum(["active","archived"]),isCurrent:e.boolean(),revision:e.number().int().nonnegative(),publishedVersionId:e.uuid().nullable(),createdAt:e.iso.datetime({offset:!0})}).superRefine((t,n)=>{t.isCurrent&&(t.state!=="active"||!t.publishedVersionId)&&n.addIssue({code:"custom",message:"Current Offering must be active and published"})}),yi=e.strictObject({id:e.uuid(),offeringId:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),version:e.number().int().positive(),document:C,productEvidence:e.record(_e,vn),createdAt:e.iso.datetime({offset:!0})}).superRefine((t,n)=>{let a=Re(t.document);(!a.length||Pn(t.document).length>0||Object.keys(t.productEvidence).length!==a.length||a.some(o=>!Object.hasOwn(t.productEvidence,o)))&&n.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),On=e.strictObject({rows:e.array(Si).max(200),versions:e.array(yi).max(500)}),Xa=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),document:C}),e.strictObject({action:e.literal("save"),id:e.uuid(),revision:e.number().int().nonnegative(),document:C}),e.strictObject({action:e.enum(["publish","set_current","archive","restore"]),id:e.uuid(),revision:e.number().int().nonnegative()})]),Ja=e.strictObject({record:Si,version:yi.nullable()}),Ii=e.discriminatedUnion("type",[e.strictObject({type:e.literal("current")}),e.strictObject({type:e.literal("id"),id:e.uuid()}),e.strictObject({type:e.literal("lookup_key"),lookupKey:e.string().min(1).max(200)}),e.strictObject({type:e.literal("version"),versionId:e.uuid()})]),An=e.strictObject({internalId:_e,id:e.string(),name:e.string().nullable(),version:e.number().int().positive(),archived:e.boolean()}),Ya=On.extend({products:e.array(An).max(500),pagination:e.strictObject({rows:e.string().nullable(),versions:e.string().nullable(),products:e.string().nullable()}).optional()});function Pn(t){let n=[];Re(t).length||n.push("Select at least one Product before publishing");function a(o){for(let m of o)m.type==="group"&&(m.items.length||n.push("Every published group requires a Product"),a(m.items))}return a(t.items),n}var vi=e.strictObject({id:e.uuid(),offeringId:e.uuid(),version:e.number().int().positive(),document:C});var Oi={requestId:e.uuid(),sourceId:e.uuid(),expectedAvailable:j},Ai=e.discriminatedUnion("action",[e.strictObject({...Oi,action:e.enum(["add","subtract","set_remaining"]),amount:s}),e.strictObject({...Oi,action:e.literal("edit"),granted:s,expiresAt:e.iso.datetime({offset:!0}).nullable(),nextResetAt:e.iso.datetime({offset:!0}).nullable(),expectedRevision:e.number().int().nonnegative()})]),we=e.strictObject({sourceId:e.uuid(),available:j,held:j,spent:j,adjustmentGrantId:e.uuid().nullable()}),Pi=we.extend({granted:j,expiresAt:e.iso.datetime({offset:!0}).nullable(),nextResetAt:e.iso.datetime({offset:!0}).nullable(),revision:e.number().int().nonnegative()});var ji=e.discriminatedUnion("action",[e.object({action:e.literal("upsert"),externalId:e.string().min(1).max(128),name:e.string().trim().min(1).max(80)}).strict(),e.object({action:e.literal("archive"),entityId:e.uuid()}).strict()]),Ci=e.object({id:e.uuid(),externalId:e.string().min(1).max(128),name:e.string().min(1).max(80),archived:e.boolean()}).strict();var _i=e.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Ri=e.number().int().min(1).max(1e3),ie=e.object({cap:s.refine(t=>/[1-9]/.test(t)).nullable(),capPercentage:e.number().positive().max(1e4).nullable(),cycles:e.number().int().min(1).max(1200).nullable()}).strict().refine(t=>t.cap===null||t.capPercentage===null,"Choose a fixed or percentage cap");var v=e.iso.datetime({offset:!0}),wi=s.refine(t=>/[1-9]/.test(t)),Bi=e.strictObject({interval:_i.exclude(["lifetime"]),count:Ri}),jn=e.strictObject({action:e.literal("create"),requestId:e.uuid(),internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),amount:wi.nullable(),expiresAt:v.nullable(),reset:Bi.nullable(),rollover:ie.nullable(),nextResetAt:v.nullable()}).refine(t=>t.amount!==null||t.reset===null&&t.rollover===null,"Unlimited grants cannot reset or roll over").refine(t=>!t.rollover||t.reset!==null,"Rollover requires a recurring grant").refine(t=>t.nextResetAt===null||t.reset!==null&&(t.expiresAt===null||Date.parse(t.nextResetAt)<Date.parse(t.expiresAt)),"The first reset needs a reset interval and must precede expiry"),qi=e.discriminatedUnion("action",[jn,e.strictObject({action:e.literal("update"),requestId:e.uuid(),grantId:e.uuid(),revision:e.number().int().nonnegative(),amount:wi.nullable(),expiresAt:v.nullable(),rollover:ie.nullable(),nextResetAt:v.nullable()}),e.strictObject({action:e.enum(["add","subtract","set_remaining"]),requestId:e.uuid(),grantId:e.uuid(),revision:e.number().int().nonnegative(),amount:s}),e.strictObject({action:e.literal("revoke"),requestId:e.uuid(),grantId:e.uuid(),revision:e.number().int().nonnegative()})]),Be=e.strictObject({id:e.uuid(),internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),amount:s.nullable(),reset:Bi.nullable(),rollover:ie.nullable(),nextResetAt:v.nullable(),startsAt:v,expiresAt:v.nullable(),revision:e.number().int().nonnegative(),revoked:e.boolean(),available:p,held:p,spent:p}),Ti=e.strictObject({customerId:e.uuid(),after:e.uuid().nullable(),limit:e.number().int().min(1).max(100)}),ki=e.strictObject({rows:e.array(Be).max(100),nextCursor:e.uuid().nullable()});var O=e.iso.datetime({offset:!0}),x=e.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Cn=e.discriminatedUnion("kind",[e.object({kind:e.literal("absolute"),from:O,to:O}).strict(),e.object({kind:e.literal("last_days"),days:e.union([e.literal(1),e.literal(7),e.literal(30),e.literal(90)])}).strict(),e.object({kind:e.literal("billing_cycles"),membershipId:e.uuid(),count:e.number().int().min(1).max(12),includeCurrent:e.boolean()}).strict()]),zi=e.string().max(100).refine(t=>{if(t!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(t))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:t}),!0}catch{return!1}},"Use an IANA timezone"),_n=e.object({key:e.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:e.array(e.string().max(120)).min(1).max(20).refine(t=>new Set(t).size===t.length)}).strict(),A=e.object({range:Cn,timezone:zi,filterBy:e.array(_n).max(5).refine(t=>new Set(t.map(n=>n.key)).size===t.length),interval:e.enum(["hour","day","week","month"]),internal_feature_id:e.uuid().nullable(),entityId:e.uuid().nullable(),topN:e.number().int().min(1).max(50).nullable(),groupBy:e.union([e.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),e.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:e.object({bucket:O,group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid(),resourceId:e.uuid()}).strict().nullable(),limit:e.number().int().min(1).max(100)}).strict().superRefine((t,n)=>{if(t.range.kind!=="absolute"){t.interval==="hour"&&t.range.kind==="last_days"&&t.range.days>31&&n.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let a=Date.parse(t.range.to)-Date.parse(t.range.from);(a<=0||a>366*864e5||t.interval==="hour"&&a>31*864e5)&&n.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),Ui=e.object({from:O,to:O,interval:e.enum(["hour","day","week","month"]),timezone:zi,rows:e.array(e.object({bucket:O,group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid(),resourceId:e.uuid(),consumedUnits:x,refundedUnits:x,reservedUnits:x,charged:x,refunded:x,reserved:x,netUnits:x,netCharged:x}).strict()).max(100),nextCursor:e.object({bucket:O,group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid(),resourceId:e.uuid()}).strict().nullable()}).strict();var _=e.string().regex(/^(0|[1-9]\d{0,29})$/),Mi=e.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),qe=e.strictObject({bucket:e.iso.datetime({offset:!0}),group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid()}),Ei=e.strictObject({...A.shape,groupBy:e.union([e.enum(["customer","entity","entitlement"]),e.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:qe.nullable()}).superRefine((t,n)=>{let a=A.safeParse({...t,after:null});if(!a.success)for(let o of a.error.issues)n.addIssue({code:"custom",path:o.path,message:o.message})}),Gi=e.strictObject({from:e.iso.datetime({offset:!0}),to:e.iso.datetime({offset:!0}),interval:A.shape.interval,timezone:A.shape.timezone,rows:e.array(e.strictObject({...qe.shape,eventCount:_,units:Mi,tokenEventCount:_,tokens:e.strictObject(Object.fromEntries(zt.map(t=>[t,_]))),totalTokens:_,providerCostEventCount:_,providerCostUsd:Mi,invalidTelemetryEventCount:_})).max(100),nextCursor:qe.nullable()});var Di=e.object({requestId:e.uuid(),items:e.array(e.object({customerId:e.uuid(),command:B.options[1]}).strict()).min(1).max(1e3)}).strict().refine(t=>new Set(t.items.map(n=>n.customerId+":"+n.command.idempotencyKey)).size===t.items.length,"Each logical event must appear once in a batch"),$i=e.object({batchId:e.uuid(),after:e.number().int().min(-1).max(999),limit:e.number().int().min(1).max(100)}).strict(),Li=e.object({batchId:e.uuid(),status:e.enum(["queued","complete"]),total:e.number().int().min(1).max(1e3),processed:e.number().int().min(0).max(1e3),items:e.array(e.object({position:e.number().int().min(0).max(999),customerId:e.uuid(),idempotencyKey:e.string().min(1).max(120),status:e.enum(["queued","accepted","rejected","failed"]),receipt:q.nullable(),errorCode:e.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(t=>t.status==="queued"?t.receipt===null&&t.errorCode===null:t.status==="failed"?t.receipt===null&&t.errorCode!==null:t.receipt!==null&&t.errorCode===null&&t.receipt.accepted===(t.status==="accepted"))).max(100),nextAfter:e.number().int().min(0).max(999).nullable()}).strict();var Rn=e.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Fi=e.enum(["draft","active","paused","archived"]),Ni=e.string().min(1).max(256),Vi=e.array(Ni).max(50).refine(t=>new Set(t).size===t.length,"Duplicate products"),wn=e.strictObject({duration:e.enum(["day","week","month","year"]),length:e.number().int().min(1).max(3660)}),Bn=e.strictObject({internal_feature_id:e.uuid(),allowance:e.number().nonnegative().max(1e15).nullable(),expiry:wn.nullable()}),qn=e.discriminatedUnion("type",[e.strictObject({type:e.literal("feature_grant"),grants:e.array(Bn).min(1).max(100).refine(t=>new Set(t.map(n=>n.internal_feature_id)).size===t.length,"Duplicate entitlement grants")}),e.strictObject({type:e.literal("free_product"),productId:Ni,duration:y}),e.strictObject({type:e.literal("invoice_credits"),amount:e.number().positive().max(1e8),duration:y,rollover:e.boolean(),productIds:Vi})]),Tn=e.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),Qi=e.object({key:Tn,name:e.string().trim().min(1).max(80),configuration:qn}).strict(),Zi=e.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Te=e.object({code:Zi,maxUses:e.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:e.boolean()}).strict(),Ki=e.object({key:e.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:e.string().trim().min(1).max(80),rewardId:e.uuid(),redeemOn:e.enum(["customer_creation","checkout"]),receivedBy:e.enum(["referrer","all"]),maxRedemptions:e.number().int().min(1).max(1e6).nullable(),productIds:Vi,excludeTrial:e.boolean()}).strict().refine(t=>t.redeemOn==="checkout"||t.productIds.length===0&&!t.excludeTrial,"Purchase restrictions require checkout trigger"),Wi={id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),revision:e.number().int().nonnegative(),status:Fi,createdAt:e.iso.datetime({offset:!0}),updatedAt:e.iso.datetime({offset:!0})},kn=Qi.extend(Wi).strict(),zn=Ki.safeExtend(Wi).strict(),Rs=e.strictObject({id:e.uuid(),key:e.string(),name:e.string(),type:Rn,status:Fi,ended:e.boolean()}),ws=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),input:Qi}).strict(),e.object({action:e.enum(["activate","pause","resume","archive","delete"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Bs=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),input:Ki}).strict(),e.object({action:e.enum(["activate","pause","resume","archive","delete"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Hi=e.object({id:e.uuid(),rewardId:e.uuid(),programId:e.uuid().nullable(),customerId:e.uuid(),referrerId:e.uuid().nullable(),status:e.enum(["pending","applied","unavailable"]),result:e.record(e.string(),e.unknown()).nullable(),createdAt:e.iso.datetime({offset:!0})}).strict(),Xi=e.object({code:Zi,requestId:e.uuid()}).strict(),Ji=e.strictObject({redemptionId:e.uuid(),currency:c,requestId:e.uuid(),accepted:e.literal(!0)}),Un=e.strictObject({type:e.literal("checkout"),orderId:e.uuid(),productVersionId:e.uuid(),currency:c,duration:y,renewalAmountMinor:e.number().int().positive().max(1e8),status:e.enum(["created","pending","trialing","paid","cancelled","failed"]),url:e.url().nullable()}),Yi=e.discriminatedUnion("type",[Un,e.strictObject({type:e.literal("subscription"),operationId:e.uuid(),membershipId:e.uuid(),productVersionId:e.uuid(),currency:c,duration:y,renewalAmountMinor:e.number().int().positive().max(1e8),status:e.enum(["pending","running","applied","failed"])})]),er=e.object({programId:e.uuid(),requestId:e.uuid()}).strict(),tr=e.object({id:e.uuid(),programId:e.uuid(),code:Te.shape.code,createdAt:e.iso.datetime({offset:!0})}).strict(),qs=e.object({rows:e.array(kn).max(100),nextCursor:e.uuid().nullable()}).strict(),Ts=e.object({rows:e.array(zn).max(100),nextCursor:e.uuid().nullable()}).strict(),Mn=Te.extend({id:e.uuid(),redemptions:e.number().int().nonnegative()}).strict(),En=e.strictObject({id:e.uuid(),programId:e.uuid().nullable(),customerId:e.uuid().nullable(),referrerId:e.uuid().nullable(),code:e.string().nullable(),status:e.enum(["pending","triggered","applied"]),createdAt:e.iso.datetime({offset:!0})}),ks=e.object({codes:e.array(Mn).max(100),redemptions:e.array(En).max(100),customers:e.record(e.uuid(),e.string()),codesCursor:e.uuid().nullable(),redemptionsCursor:e.uuid().nullable()}).strict(),zs=e.discriminatedUnion("action",[e.object({action:e.literal("create"),rewardId:e.uuid(),revision:e.number().int().nonnegative(),input:Te}).strict(),e.object({action:e.literal("remove"),rewardId:e.uuid(),revision:e.number().int().nonnegative(),codeId:e.uuid()}).strict()]);var rr=e.object({customerId:e.uuid()}).strict(),nr=e.discriminatedUnion("action",[e.object({customerId:e.uuid(),requestId:e.uuid(),action:e.literal("assign"),poolId:e.uuid(),memberCustomerId:e.uuid()}).strict(),e.strictObject({customerId:e.uuid(),requestId:e.uuid(),action:e.literal("assign_entity"),poolId:e.uuid(),entityId:e.uuid()}),e.object({customerId:e.uuid(),requestId:e.uuid(),action:e.literal("release"),poolId:e.uuid(),slotId:e.uuid()}).strict()]),U=e.number().int().nonnegative(),ke=e.iso.datetime({offset:!0}),ze=e.strictObject({internalId:e.uuid(),id:e.string(),name:e.string().nullable(),version:e.number().int().positive()}),ir=e.enum(["active","past_due"]),Ue=e.strictObject({customerId:e.uuid(),licenses:e.array(e.strictObject({id:e.uuid(),linkId:e.uuid(),parent:e.strictObject({customerProductId:e.uuid(),status:ir,product:ze}),product:ze,planLicense:e.strictObject({id:e.uuid(),prepaidOnly:e.boolean(),isCustom:e.boolean()}).nullable(),granted:U,included:U,paidQuantity:U,usage:U,remaining:U,createdAt:ke}).refine(t=>t.granted===t.included+t.paidQuantity&&t.granted===t.usage+t.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:e.array(e.strictObject({id:e.uuid(),linkId:e.uuid(),status:ir,product:ze,entity:e.strictObject({internalId:e.uuid(),id:e.string().nullable(),name:e.string().nullable()}).nullable(),beneficiary:e.strictObject({internalId:e.uuid(),id:e.string().nullable(),name:e.string().nullable()}).nullable(),startedAt:ke.nullable(),endedAt:ke.nullable()}).refine(t=>t.entity!==null||t.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:e.boolean()});var ur=e.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Me=e.string().regex(/^(0|[1-9]\d{0,14})$/),R=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Gn=e.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),M=Gn,b=s.refine(t=>/[1-9]/.test(t)),u=e.iso.datetime({offset:!0}),re=t=>{let[n,a=""]=t.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*1000000n+BigInt(a.padEnd(6,"0"))},Dn=e.array(e.object({upTo:b.nullable(),unitAmountMinor:ur,flatAmountMinor:e.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(t=>{try{return t.at(-1)?.upTo===null&&t.slice(0,-1).every((n,a)=>{let o=t[a-1]?.upTo;return n.upTo!==null&&(a===0||o!=null&&re(n.upTo)>re(o))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),$n=e.discriminatedUnion("kind",[e.object({kind:e.literal("flat"),units:b,unitAmountMinor:ur}).strict(),e.object({kind:e.enum(["graduated","volume"]),units:b,tiers:Dn}).strict()]).refine(t=>t.kind==="flat"||!t.tiers.some(n=>(n.flatAmountMinor??0)>0)||t.kind==="volume"&&t.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),Ln=e.strictObject({interval:e.enum(["month","year"]),count:e.number().int().min(1).max(12),anchor:e.enum(["membership","calendar"])}),E=e.object({currency:c,pricing:$n,billingCycle:Ln.optional()}).strict().refine(t=>t.pricing.kind!=="volume"||t.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var ar={requestId:e.uuid(),productVersionId:e.uuid(),internal_feature_id:e.uuid(),currency:c},dr=e.strictObject({interval:e.enum(["hour","day","week","month"]),intervalCount:e.number().int().min(1).max(12),limit:e.number().int().min(1).max(1e6)}),mr=e.discriminatedUnion("kind",[e.object({...ar,kind:e.literal("auto_topup"),threshold:oe,quantity:b.refine(t=>Number(t)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:dr.optional()}).strict(),e.object({...ar,kind:e.literal("postpaid"),maxAmountMinorPerPeriod:M,maxOutstandingMinor:M}).strict()]),sr={productVersionId:e.uuid(),internal_feature_id:e.uuid(),currency:c},pr=e.discriminatedUnion("kind",[e.object({...sr,kind:e.literal("auto_topup"),threshold:oe,quantity:b.refine(t=>Number(t)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:dr.optional(),purchaseAmountMinor:M,purchaseUnits:b}).strict(),e.object({...sr,kind:e.literal("postpaid"),maxAmountMinorPerPeriod:M,maxOutstandingMinor:M,cashPrice:E}).strict().refine(t=>t.cashPrice.currency===t.currency,"Currency must match")]),ne=e.object({id:e.uuid(),terms:pr,status:e.enum(["prepared","active","revoked","blocked"]),createdAt:u,acceptedAt:u.nullable(),effectiveAt:u.nullable(),revokedAt:u.nullable()}).strict().refine(t=>(t.status==="prepared"?t.acceptedAt===null:!0)&&(t.status==="active"?t.acceptedAt!==null&&t.effectiveAt!==null:!0)&&(t.status==="revoked"?t.revokedAt!==null:t.revokedAt===null),"Authorization consent and revocation must be explicit"),lr=e.object({authorizationId:e.uuid(),terms:pr,setupUrl:e.url().nullable()}).strict(),gr=e.object({authorizationId:e.uuid(),accepted:e.literal(!0)}).strict(),hr=e.object({authorizationId:e.uuid(),requestId:e.uuid()}).strict(),fr=e.object({internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),interval:e.enum(["day","week","month","year"]),anchor:e.enum(["billing_cycle","utc"]).optional(),basis:e.enum(["usage","credits"]),filter:h.optional(),limit:s.nullable(),thresholds:e.array(e.number().positive().max(1)).max(8),includedThresholds:e.array(e.number().positive().max(1)).max(8).optional(),absoluteThresholds:e.array(b).max(8).optional()}).strict().refine(t=>t.thresholds.every((n,a)=>{let o=t.thresholds[a-1];return a===0||o!==void 0&&n>o})&&(t.includedThresholds??[]).every((n,a,o)=>{let m=o[a-1];return a===0||m!==void 0&&n>m})&&(t.absoluteThresholds??[]).every((n,a,o)=>{let m=o[a-1];return a===0||m!==void 0&&re(n)>re(m)}),"Notification thresholds must increase"),Fn=fr.safeExtend({requestId:e.uuid()}),or={control:e.literal("overage"),requestId:e.uuid(),internal_feature_id:e.uuid(),entityId:e.uuid().nullable()},Nn=e.discriminatedUnion("action",[e.strictObject({...or,action:e.literal("set"),allowed:e.boolean().nullable(),overageLimit:s.nullable(),skipOverageBilling:e.boolean()}),e.strictObject({...or,action:e.literal("remove")})]),br=e.union([Fn,Nn]),Vn=e.strictObject({internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),allowed:e.boolean().nullable(),overageLimit:s.nullable(),skipOverageBilling:e.boolean(),interval:e.enum(["day","week","month","year"]),startsAt:u,endsAt:u,used:e.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:e.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:e.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Qn=e.object({internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),interval:e.enum(["day","week","month","year"]),anchor:e.enum(["billing_cycle","utc"]).optional(),basis:e.enum(["usage","credits"]),filter:h.optional(),startsAt:u,endsAt:u,used:p,reserved:p,limit:s.nullable(),thresholds:e.array(e.number().positive().max(1)).max(8),notifiedThresholds:e.array(e.number().positive().max(1)).max(1024),includedThresholds:e.array(e.number().positive().max(1)).max(8).optional(),includedAllowance:e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:e.array(e.number().positive().max(1)).max(1024).optional(),absoluteThresholds:e.array(b).max(8).optional(),notifiedAbsoluteThresholds:e.array(b).max(1024).optional()}).strict().refine(t=>t.basis!=="usage"||s.safeParse(t.used).success&&s.safeParse(t.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Zn=e.object({authorizationId:e.uuid(),status:e.enum(["idle","pending","blocked"]),taskId:e.uuid().nullable(),invoiceId:e.uuid().nullable(),hostedInvoiceUrl:e.url().nullable(),purchaseCount:e.number().int().nonnegative(),purchaseWindowEndsAt:u.nullable(),attemptCount:e.number().int().nonnegative(),failedAttemptCount:e.number().int().nonnegative(),suspendedAt:u.nullable(),nextAttemptAt:u.nullable(),failureReason:e.string().min(1).max(240).nullable()}).strict(),xr=e.object({internal_feature_id:e.uuid().optional(),entityId:e.uuid().optional()}).strict(),Ee=e.object({authorizations:e.array(ne).max(100),limits:e.array(fr).max(100),overages:e.array(Vn).max(100).optional(),windows:e.array(Qn).max(200),autoTopups:e.array(Zn).max(100),limited:e.boolean()}).strict(),Kn=e.object({id:e.uuid(),internal_feature_id:e.uuid(),productVersionId:e.uuid(),authorizationId:e.uuid(),entityId:e.uuid().nullable(),units:s,amountMinor:R,cashPrice:E}).strict(),G=e.object({id:e.uuid(),sourceKind:e.enum(["product","usage","manual"]),providerInvoiceId:e.string().min(1).max(240).nullable(),status:e.enum(["accruing","open","pending","paid","failed","void"]),currency:c,startsAt:u.nullable(),endsAt:u.nullable(),amountMinor:e.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:e.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Me,paidAmountMinor:Me,refundedAmountMinor:Me,createdAt:u,hostedInvoiceUrl:e.url().nullable(),adjustment:e.object({originalInvoiceId:e.uuid(),amountMinor:e.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(t=>t!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(t)&&BigInt(t)>=-200000000n&&BigInt(t)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:u.nullable(),reason:e.string().min(1).max(500).optional()}).strict().nullable(),lines:e.array(Kn).max(100),linesLimited:e.boolean()}).strict(),Sr=e.object({invoiceId:e.uuid(),accepted:e.literal(!0)}).strict(),yr=e.strictObject({requestId:e.uuid(),originalInvoiceId:e.uuid(),amountMinor:e.string().regex(/^[1-9]\d{0,8}$/).refine(t=>/^[1-9]\d{0,8}$/.test(t)&&BigInt(t)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:e.string().trim().min(1).max(500)}),Ir=e.object({after:e.uuid().nullable(),limit:e.number().int().min(1).max(100)}).strict(),vr=e.object({rows:e.array(G).max(100),nextCursor:e.uuid().nullable()}).strict(),cr=e.strictObject({id:e.string(),coupon:e.string(),start:e.number().nonnegative(),end:e.number().nullable()}),Wn=e.strictObject({subscriptionId:e.string(),customerId:e.string(),accountId:e.string(),sourceItems:e.array(e.strictObject({id:e.string(),price_id:e.string(),quantity:e.number().int(),discounts:e.array(cr).optional()})).max(100),items:e.array(e.strictObject({id:e.string(),price:e.string(),quantity:e.number().int(),discounts:e.array(e.strictObject({coupon:e.string().optional(),terms:e.strictObject({id:e.string(),name:e.string().optional(),percent_off:e.number().optional(),amount_off:e.number().optional(),currency:e.string().optional(),duration:e.enum(["once","forever","repeating"]),duration_in_months:e.number().optional()}).optional(),discount:e.string().optional(),receipt:cr.optional()})).max(20)})).max(100)}),Or=e.strictObject({membershipId:e.uuid(),requestId:e.uuid(),grantIds:e.array(e.uuid()).max(20).refine(t=>new Set(t).size===t.length,"Duplicate Coupon grants")}),Ar=e.strictObject({membershipId:e.uuid(),operationId:e.uuid(),status:e.enum(["pending","effective"]),execution:Wn.nullable(),grants:e.array(e.strictObject({id:e.uuid(),couponId:e.uuid(),name:e.string(),discount:nt,duration:y,startedAt:u.nullable()})).max(20)});var l={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},D=t=>new Set(t).size===t.length,Ge=e.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),Hn=e.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(t=>!t.split("/").some(n=>n==="."||n==="..")),$=e.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(t=>!t.includes("..")&&!t.endsWith(".")&&!t.split("/").some(n=>!n||n.startsWith(".")||n.endsWith(".lock"))),Xn=e.string().min(1).max(512).refine(t=>!/[\\\u0000-\u001f\u007f]/.test(t)&&!t.startsWith("/")&&!t.split("/").some(n=>!n||n==="."||n==="..")),Pr=e.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(t=>!t.startsWith("/")&&!t.split("/").some(n=>!n||n==="."||n===".."));var jr=e.strictObject({id:e.uuid(),repo:Hn,platform:e.enum(["github","gitlab","bitbucket"]),branches:e.array($).min(1).max(4).refine(D),workflow:e.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:e.array(e.uuid()).min(1).max(4).refine(D),include:e.array(Pr).min(1).max(16),exclude:e.array(Pr).max(16),methods:e.array(e.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(D),maxAgeHours:e.number().int().min(1).max(720)}),Cr=jr.extend({revision:e.number().int().positive()}),Qs=e.strictObject({repository:jr,expectedRevision:e.number().int().min(0)}).refine(({repository:t})=>t.platform==="gitlab"||t.repo.split("/").length===2,{path:["repository","repo"]}),_r=e.strictObject({repositoryId:e.uuid(),branch:$}),Jn=e.array(Ge).max(l.keys).refine(D),Rr=e.strictObject({repository:Cr.omit({keyIds:!0}),branch:$,keys:Jn,keySetHash:e.string().regex(/^[a-f0-9]{64}$/)}),Yn=e.strictObject({filePath:Xn,startingLineNumber:e.number().int().min(1).max(1e7)}),De=e.strictObject({protocol:e.literal(1),repositoryId:e.uuid(),branch:$,workflow:e.string().max(200),configurationRevision:e.number().int().positive(),keySetHash:e.string().regex(/^[a-f0-9]{64}$/),commit:e.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:e.uuid(),runNumber:e.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:e.number().int().min(1).max(1e4),scannerVersion:e.literal("1"),scannedAt:e.iso.datetime({offset:!0}),coverage:e.strictObject({complete:e.literal(!0),files:e.number().int().min(0).max(l.files),sourceBytes:e.number().int().min(0).max(l.sourceBytes),unresolvedCalls:e.number().int().min(0).max(1e6),unsupportedFiles:e.number().int().min(0).max(l.files)}),features:e.array(e.strictObject({key:Ge,refs:e.array(Yn).max(l.referencesPerKey)})).max(l.keys)}).superRefine((t,n)=>{D(t.features.map(a=>a.key))||n.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),t.features.reduce((a,o)=>a+o.refs.length,0)>l.references&&n.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),$e=e.strictObject({scanId:e.uuid(),commit:e.string(),receivedAt:e.string(),references:e.number().int().nonnegative(),removedReferences:e.number().int().nonnegative()}),ea=$e.extend({repositoryId:e.uuid(),branch:$,workflow:e.string(),digest:e.string(),configurationRevision:e.number().int().positive(),runNumber:e.number().int().positive(),runAttempt:e.number().int().positive(),scannedAt:e.string(),keySetHash:e.string(),coverage:De.shape.coverage}),ta=e.strictObject({repositories:e.array(Cr).max(l.repositories),scans:e.array(ea).max(l.repositories*l.branches)}),ia=e.strictObject({key:Ge,references:e.number().int().nonnegative(),coveredTargets:e.number().int().nonnegative(),expiredTargets:e.number().int().nonnegative(),uncertainTargets:e.number().int().nonnegative()}),Zs=e.strictObject({available:e.boolean().default(!0),settings:ta,expectedTargets:e.number().int().min(0).max(80),features:e.array(ia).max(2001),truncated:e.boolean()});var g=e.iso.datetime({offset:!0}),wr=e.strictObject({invoiceId:e.uuid(),after:e.string().min(1).max(180).nullable(),limit:e.number().int().min(1).max(100)}),ra=e.strictObject({kind:e.literal("product"),key:e.string(),productVersionId:e.uuid(),productName:e.string(),itemKey:e.string(),entityId:e.uuid().nullable(),quantity:e.number().positive(),subtotalMinor:e.string().regex(/^-?\d+$/),discountMinor:e.string().regex(/^\d+$/),taxMinor:e.string().regex(/^-?\d+$/).nullable(),totalMinor:e.string().regex(/^-?\d+$/),startsAt:g.nullable(),endsAt:g.nullable(),providerLineId:e.string().nullable(),providerItemId:e.string()}),Br=e.strictObject({invoice:G,items:e.array(e.discriminatedUnion("kind",[ra,e.strictObject({kind:e.literal("invoice_credit"),key:e.string(),internal_feature_id:e.uuid(),internal_credit_feature_id:e.uuid(),name:e.string(),units:s,reserved:s,amountMinor:R,grossAmountMinor:R,creditsAppliedMinor:R,properties:h,cashPrice:E,providerItemId:e.string().nullable(),creditProviderItemId:e.string().nullable()}),e.strictObject({kind:e.literal("usage"),key:e.string(),internal_feature_id:e.uuid(),name:e.string(),units:s,reserved:s,amountMinor:R,cashPrice:E})])).max(100),nextCursor:e.string().min(1).max(180).nullable()}),na=e.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(t=>!/^\-0(?:\.0+)?$/.test(t)),Le=e.strictObject({from:g,to:g,entityId:e.uuid().optional(),snapshotAt:g.nullable(),after:e.strictObject({at:g,id:e.uuid(),position:e.number().int().nonnegative()}).nullable(),limit:e.number().int().min(1).max(100)}).refine(t=>Date.parse(t.from)<Date.parse(t.to)&&Date.parse(t.to)-Date.parse(t.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(t=>t.after===null||t.snapshotAt!==null,"A cursor requires the original snapshot time"),qr=e.strictObject({customerId:e.uuid(),entityId:e.uuid().nullable(),from:g,to:g,snapshotAt:g,totals:e.array(e.strictObject({internal_credit_feature_id:e.uuid(),name:e.string(),consumed:p,refunded:p,net:na})).max(1e3),rows:e.array(e.strictObject({operationId:e.uuid(),position:e.number().int().nonnegative(),kind:e.enum(["consume","confirm","refund"]),originalId:e.uuid().nullable(),occurredAt:g,internal_feature_id:e.uuid(),entitlementName:e.string(),sourceId:e.uuid(),internal_credit_feature_id:e.uuid(),creditName:e.string(),units:yt,amount:p,pricing:e.array(St).max(12),properties:h})).max(100),nextCursor:Le.shape.after});var d=e.string().min(1).max(200),ae=e.iso.datetime({offset:!0}),L=e.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Fe=e.number().int().min(0).max(1e12),zr=e.number().int().min(1).max(1e12),Tr={...f,type:e.literal("coupon.redeemed"),grantId:e.uuid()},kr={...f,type:e.literal("usage.observed"),merchantTransactionId:d,resource:d,unit:d,quantity:zr},aa=e.strictObject({...f,type:e.literal("fulfillment.updated"),operationId:e.uuid(),merchantFulfillmentId:d,status:e.enum(["pending","applied","failed"])}),sa=e.strictObject({...f,type:e.literal("benefit.claimed"),merchantBenefitId:d,resource:d,unit:d,quantity:zr,expiresAt:ae.nullable(),revision:L}),oa=e.strictObject({...f,type:e.literal("benefit.closed"),merchantBenefitId:d,status:e.enum(["failed","expired","canceled"]),revision:L}),ca=e.strictObject({...f,type:e.literal("benefit.updated"),merchantBenefitId:d,status:e.enum(["active","expired","revoked"]),remainingQuantity:Fe.nullable(),expiresAt:ae.nullable(),revision:L}),ua=e.strictObject({...f,type:e.literal("authorization.updated"),merchantAuthorizationId:d,kind:e.literal("auto_topup"),status:e.enum(["pending","effective","revoked","failed"]),termsReference:d.nullable(),revision:L}),da=e.strictObject({...f,type:e.literal("balance.observed"),resource:d,unit:d,availableQuantity:Fe,reservedQuantity:Fe,periodStartsAt:ae.nullable(),periodEndsAt:ae.nullable(),revision:L}),Ur=e.union([e.discriminatedUnion("type",[...He,aa,sa,oa,ca,ua,da]),e.strictObject({...Tr,productVersionId:e.uuid(),subscriptionId:e.string().trim().min(1).max(255)}),e.strictObject({...Tr,merchandiseId:e.uuid()}),e.strictObject({...kr,operation:e.literal("consume")}),e.strictObject({...kr,operation:e.literal("reverse"),reversalOf:d})]),Mr=e.strictObject({id:e.uuid(),eventId:e.string().min(1).max(200),source:e.literal("merchant"),providerVerified:e.literal(!1),outcome:e.string().min(1).max(100)});var Er=st,pa=Er.extend({invoice_id:Er.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),Ne=e.strictObject({name:e.string().trim().min(1).max(255),memo:e.string().max(1e4).nullable().optional(),footer:e.string().max(1e4).nullable().optional(),net_terms_days:e.number().int().positive().nullable().optional()}),la=Ne.extend({id:e.string().min(1).max(255),created_at:e.number().nullable()}),Gr=e.strictObject({items:e.array(la).max(50),nextCursor:e.uuid().nullable()}),so=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),requestId:e.uuid(),values:Ne}),e.strictObject({action:e.literal("update"),id:e.string().min(1).max(255),values:Ne}),e.strictObject({action:e.literal("delete"),id:e.string().min(1).max(255)})]),Dr=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),requestId:e.uuid(),params:P}),e.strictObject({action:e.enum(["finalize","send","pay","void"]),requestId:e.uuid(),invoiceId:e.uuid()}),e.strictObject({action:e.literal("reissue"),requestId:e.uuid(),invoiceId:e.uuid(),params:pa})]),Ve=e.strictObject({id:e.uuid(),customerId:e.uuid(),providerInvoiceId:e.string().nullable(),status:e.enum(["draft","open","paid","void","uncollectible"]),currency:e.string(),totalMinor:e.string().regex(/^-?\d+$/),paidMinor:e.string().regex(/^\d+$/),refundedMinor:e.string().regex(/^\d+$/),hostedInvoiceUrl:e.url().nullable(),createdAt:e.number(),collectionMethod:e.enum(["send_invoice","charge_automatically"]).nullable()}),$r=Ve.extend({lines:e.array(e.strictObject({id:e.uuid(),description:e.string(),amountMinor:e.string().regex(/^-?\d+$/),netAmountMinor:e.string().regex(/^-?\d+$/),quantity:e.number().nullable(),periodStart:e.number().nullable(),periodEnd:e.number().nullable()})).max(1e3)}),w=e.strictObject({taskId:e.uuid(),status:e.enum(["ready","running","done","dead"]),invoice:Ve.nullable(),errorCode:e.string().nullable()}),Lr=e.strictObject({items:e.array(Ve).max(50),nextCursor:e.uuid().nullable(),operations:e.array(w).max(50),operationsLimited:e.boolean()});var ga=e.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Fr={scope:se,permissions:e.array(ga),expiresAt:e.iso.datetime().nullable()},ec=e.discriminatedUnion("kind",[e.object({...Fr,kind:e.literal("server"),keyId:e.string().min(1)}),e.object({...Fr,kind:e.literal("customer"),customerId:e.string().min(1),identityKind:e.enum(["identified","guest"]),expiresAt:e.iso.datetime()})]),r=e.object({requestId:e.uuid(),scope:se}).strict(),ha=Ct.safeExtend({fingerprint:he.optional()}).strict(),fa=r.extend({customer:Q,created:e.boolean()});function Nr(){return r.extend({offer:ue.nullable(),reason:at.nullable()})}var i={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Nt,response:r.extend({message:e.object({messageId:e.uuid(),channel:T,acceptedAt:e.iso.datetime({offset:!0}),status:e.enum(["accepted","sending","completed","canceled"]),replayed:e.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:e.strictObject({messageId:e.uuid()}),response:r.extend({message:e.object({id:e.uuid(),channel:T,status:e.enum(["accepted","sending","completed","canceled"]),deliveries:e.array(e.object({id:e.uuid(),status:Qt,attempts:e.number().int().nonnegative(),receipts:e.array(e.object({kind:Zt,occurredAt:e.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Ut,response:r.extend({installation:Z})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Mt,response:r.extend({installation:Z})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:Et,response:r.extend({installation:Z})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:e.strictObject({channel:T}),response:r.extend({preference:fe})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Vt,response:r.extend({preference:fe})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:e.strictObject({cursor:e.uuid().optional()}),response:r.extend({templates:Gr})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:e.strictObject({customerId:e.uuid(),params:P}),response:r.extend({preview:de})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:e.strictObject({customerId:e.uuid(),requestId:e.uuid(),params:P}).refine(t=>t.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:r.extend({operation:w})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:e.strictObject({customerId:e.uuid(),command:Dr}).refine(t=>t.command.action!=="create"||t.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:r.extend({operation:w})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:e.strictObject({customerId:e.uuid(),taskId:e.uuid()}),response:r.extend({operation:w})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:e.strictObject({customerId:e.uuid(),cursor:e.uuid().optional()}),response:r.extend({invoices:Lr})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:e.strictObject({customerId:e.uuid(),invoiceId:e.uuid()}),response:r.extend({invoice:$r})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:_r,response:r.extend({config:Rr})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:De,response:r.extend({receipt:$e})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:e.strictObject({}),response:r.extend({payload:gt})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:ht,response:r.merge(ft)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:bt,response:r.merge(xt)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:e.strictObject({customerId:e.uuid(),sourceId:e.uuid()}),response:r.extend({balance:Pi})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:e.strictObject({customerId:e.uuid(),command:Ai}),response:r.extend({balance:we})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:e.strictObject({internal_feature_id:e.uuid(),customerId:e.uuid().optional(),entityId:e.uuid().optional()}).refine(t=>!t.entityId||!!t.customerId,"Entity pricing requires a customer"),response:r.extend({internal_feature_id:e.uuid(),config:Pe,model_markups:te})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:e.strictObject({customerId:e.uuid(),query:vt}),response:r.extend({usage:ge})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:e.strictObject({customerId:e.uuid(),command:Ot}),response:r.extend({usage:ge})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:e.strictObject({customerId:e.uuid(),command:qi}),response:r.extend({grant:Be})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Ti,response:r.extend({grants:ki})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:e.union(ci.options.map(t=>t.extend({customerId:e.uuid().optional(),customerToken:e.string().regex(We).optional()}))),response:r.extend({operation:ui})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Xt.extend({customerId:e.uuid().optional()}),response:r.extend({setup:Ie})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Jt.extend({customerId:e.uuid().optional()}),response:r.extend({setup:Ie})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Kt.safeExtend({customerId:e.uuid()}),response:r.extend({batch:k})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:K.extend({customerId:e.uuid()}),response:r.extend({batch:k})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:K.extend({customerId:e.uuid()}),response:r.extend({batch:k})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:K.extend({customerId:e.uuid()}),response:r.extend({batch:k})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:e.discriminatedUnion("action",[W.options[0].extend({customerId:e.uuid()}),W.options[1].extend({customerId:e.uuid()}),W.options[2].extend({customerId:e.uuid()})]),response:r.extend({trial:ye})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Wt.extend({customerId:e.uuid()}),response:r.extend({trial:ye})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:J,response:r.extend({subscriptions:ai})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:J,response:r.extend({purchases:si})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:ii,response:r.extend({conflicts:oi})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:ri,response:r.extend({resolution:ni})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:ei,response:r.extend({verification:ti})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:ot.safeExtend({...V,customerId:e.uuid().optional()}),response:r.extend({quote:ct})},recordMerchantEvent:{replay:"immutable_event",method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:Ur,response:r.extend({record:Mr})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:I.extend({customerId:e.uuid().optional(),intent:e.enum(["confirm","cancel"]).optional(),merchantConfirmation:N.optional()}),response:r.extend({operation:me})},readSubscriptionOperation:{replay:"read",method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:I.extend({customerId:e.uuid().optional()}),response:r.extend({operation:me})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:ut.safeExtend({customerId:e.uuid().optional()}),response:r.extend({quote:mt})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:I.extend({customerId:e.uuid().optional(),intent:e.enum(["confirm","cancel"]).optional(),merchantConfirmation:N.optional()}),response:r.extend({operation:pe})},readSubscriptionUpdate:{replay:"read",method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:I.extend({customerId:e.uuid().optional()}),response:r.extend({operation:pe})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:pt.safeExtend({customerId:e.uuid()}),response:r.extend({quote:lt})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:I.extend({customerId:e.uuid(),merchantConfirmation:N.optional()}),response:r.extend({operation:le})},readRefund:{replay:"read",method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:I.extend({customerId:e.uuid()}),response:r.extend({operation:le})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:xr,response:r.extend({controls:Ee})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:mr,response:r.extend({prepared:lr})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:gr,response:r.extend({authorization:ne})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Or,response:r.extend({coupons:Ar})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:hr,response:r.extend({authorization:ne})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Ir,response:r.extend({invoices:vr})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:yr.extend({customerId:e.uuid()}),response:r.extend({operation:w})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Sr,response:r.extend({invoice:G})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:e.object({customerId:e.uuid(),command:br}).strict(),response:r.extend({controls:Ee})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:e.object({customerId:e.uuid(),command:ji}).strict(),response:r.extend({entity:Ci})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:e.strictObject({customerId:e.uuid().nullable(),query:Ei}),response:r.extend({analytics:Gi})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:e.object({customerId:e.uuid().nullable(),query:A}).strict(),response:r.extend({analytics:Ui})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Di,response:r.extend({batchId:e.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:$i,response:r.extend({batch:Li})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Ye.extend({customerId:e.string().min(1).optional()}),response:r.extend({check:ce})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:e.strictObject({kind:tt,selector:e.discriminatedUnion("type",[e.strictObject({type:e.literal("resource"),id:e.uuid()}),e.strictObject({type:e.literal("version"),id:e.uuid()})]),customerId:e.string().min(1).optional()}),response:r.extend({content:it})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Tt,response:r.extend({paywall:kt})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:e.strictObject({processContext:rt.optional(),...V,selector:Ii,customerId:e.string().min(1).optional(),commerce:Xe,requirement:Je.optional()}),response:r.extend({offering:vi,candidates:e.array(et).max(20),availability:e.array(e.strictObject({productVersionId:e.uuid(),available:e.boolean(),reason:e.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:ce.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:e.object({customerId:e.uuid().optional(),entityId:e.uuid().optional()}).strict(),response:r.extend({holdings:At})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:e.object({customerId:e.uuid().optional(),query:Pt}).strict(),response:r.extend({ledger:jt})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:wr.extend({customerId:e.uuid().optional()}),response:r.extend({detail:Br})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Le.safeExtend({customerId:e.uuid().optional()}),response:r.extend({statement:qr})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:e.object({customerId:e.uuid().optional(),command:B.options[0]}).strict(),response:r.extend({quote:It})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:e.strictObject({customerId:e.uuid(),command:e.union([e.strictObject({eventName:e.string().min(1),quantity:s.optional(),properties:h.optional(),entityId:e.uuid().optional(),idempotencyKey:e.string().min(1).max(120)}),e.strictObject({internal_feature_id:e.uuid(),quantity:s.optional(),properties:h.optional(),entityId:e.uuid().optional(),idempotencyKey:e.string().min(1).max(120)})])}),response:r.extend({receipts:e.array(q).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:e.object({customerId:e.uuid(),command:B.refine(t=>t.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:r.extend({receipt:q})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Xi,response:r.extend({redemption:Hi})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:er,response:r.extend({referralCode:tr})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:Ji,response:r.extend({checkout:Yi})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:rr,response:r.extend({seats:Ue})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:nr,response:r.extend({seats:Ue})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:ha,response:fa},getCustomer:{replay:"read",method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Rt,response:r.extend({customer:Q})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Bt,response:r.extend(qt.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:wt,response:r.extend(_t.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:e.object({customerId:e.uuid()}).strict(),response:r.extend(F.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:e.strictObject({}),response:r.extend(F.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:e.strictObject({customerId:e.uuid(),sessionId:e.uuid().optional()}),response:r.extend({revoked:e.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:e.strictObject({guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:he.optional()}),response:r.extend({customerId:e.uuid(),guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:e.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:e.strictObject({guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:r.extend(F.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:e.strictObject({guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:e.string().trim().min(1).max(255).refine(t=>!t.startsWith("gg_guest_")),requestId:e.uuid()}),response:r.extend({customer:Q,switched:e.boolean(),replayed:e.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:e.strictObject({code:e.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:e.uuid()}),response:Nr()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:e.object({}).strict(),response:r.extend({offers:e.array(ue)})},grantModelBenefit:{method:"POST",path:"benefits/model-usage/grant",permission:"offers:grant",audience:"server",request:$t,response:r.extend({operation:xe})},readModelBenefit:{method:"POST",path:"benefits/model-usage/read",permission:"offers:grant",audience:"server",request:Lt,response:r.extend({operation:xe})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:e.object({customerId:e.string().min(1).max(255).optional(),couponId:e.uuid(),...V,requestId:e.uuid(),couponContentDigest:e.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Nr()}},tc={recordMerchantEvent:i.recordMerchantEvent,sendMessage:i.sendMessage,readMessage:i.readMessage,bindPushInstallation:i.bindPushInstallation,readPushInstallation:i.readPushInstallation,updatePushAddress:i.updatePushAddress,readMessagingPreference:i.readMessagingPreference,setMessagingPreference:i.setMessagingPreference,listInvoiceTemplates:i.listInvoiceTemplates,previewInvoice:i.previewInvoice,createInvoice:i.createInvoice,manageInvoice:i.manageInvoice,readInvoiceOperation:i.readInvoiceOperation,listInvoices:i.listInvoices,getInvoice:i.getInvoice,getCodeReferenceConfig:i.getCodeReferenceConfig,submitCodeReferences:i.submitCodeReferences,getFeatures:i.getFeatures,evaluateFeatures:i.evaluateFeatures,trackEvents:i.trackEvents,setupPayment:i.setupPayment,readPaymentSetup:i.readPaymentSetup,previewSubscriptionBatch:i.previewSubscriptionBatch,confirmSubscriptionBatch:i.confirmSubscriptionBatch,readSubscriptionBatch:i.readSubscriptionBatch,abandonSubscriptionBatch:i.abandonSubscriptionBatch,manageSubscriptionTrial:i.manageSubscriptionTrial,readSubscriptionTrial:i.readSubscriptionTrial,listSubscriptions:i.listSubscriptions,listPurchases:i.listPurchases,listSubscriptionConflicts:i.listSubscriptionConflicts,retrySubscriptionConflict:i.retrySubscriptionConflict,readAiPricing:i.readAiPricing,readUsage:i.readUsage,setUsage:i.setUsage,previewRefund:i.previewRefund,refund:i.refund,readRefund:i.readRefund,previewUpdate:i.previewUpdate,update:i.update,readSubscriptionUpdate:i.readSubscriptionUpdate,restoreNativePurchase:i.restoreNativePurchase,verifySubscriptions:i.verifySubscriptions,previewAttach:i.previewAttach,attach:i.attach,readSubscriptionOperation:i.readSubscriptionOperation,manageBalanceGrant:i.manageBalanceGrant,readBalanceSource:i.readBalanceSource,adjustBalance:i.adjustBalance,listBalanceGrants:i.listBalanceGrants,readBillingControls:i.readBillingControls,prepareBillingAuthorization:i.prepareBillingAuthorization,confirmBillingAuthorization:i.confirmBillingAuthorization,setBillingCoupons:i.setBillingCoupons,revokeBillingAuthorization:i.revokeBillingAuthorization,listBillingInvoices:i.listBillingInvoices,confirmBillingAdjustment:i.confirmBillingAdjustment,prepareBillingAdjustment:i.prepareBillingAdjustment,manageBillingLimits:i.manageBillingLimits,createCustomer:i.createCustomer,getCustomer:i.getCustomer,listCustomers:i.listCustomers,updateCustomer:i.updateCustomer,createSession:i.createSession,refreshSession:i.refreshSession,revokeSessions:i.revokeSessions,createGuestCustomer:i.createGuestCustomer,resumeGuestSession:i.resumeGuestSession,claimGuestCustomer:i.claimGuestCustomer,checkEntitlement:i.checkEntitlement,resolveOffering:i.resolveOffering,resolveContent:i.resolveContent,resolvePaywall:i.resolvePaywall,readHoldings:i.readHoldings,readLedger:i.readLedger,readBillingInvoice:i.readBillingInvoice,readCreditStatement:i.readCreditStatement,quoteBalance:i.quoteBalance,trackUsage:i.trackUsage,mutateBalance:i.mutateBalance,manageUsageEntity:i.manageUsageEntity,readUsageAnalytics:i.readUsageAnalytics,readCreditAnalytics:i.readCreditAnalytics,submitUsageBatch:i.submitUsageBatch,readUsageBatch:i.readUsageBatch,listOffers:i.listOffers,grantOffer:i.grantOffer,grantModelBenefit:i.grantModelBenefit,readModelBenefit:i.readModelBenefit,redeemCoupon:i.redeemCoupon,redeemReward:i.redeemReward,createReferralCode:i.createReferralCode,claimRewardProduct:i.claimRewardProduct,readSeats:i.readSeats,manageSeat:i.manageSeat};export{be as a,Dt as b,Gt as c,xa as d,i as e};