@tinkerlandai/indiana-react-native 0.9.2 → 0.9.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/IndianaReactNative.podspec +19 -0
- package/README.md +61 -4
- package/THIRD_PARTY_NOTICES.md +74 -0
- package/android/build.gradle +24 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/java/ai/tinkerland/indiana/reactnative/IndianaBridgeModule.kt +237 -0
- package/android/src/main/java/ai/tinkerland/indiana/reactnative/IndianaBridgePackage.kt +11 -0
- package/dist/index.cjs +17 -1
- package/dist/index.d.cts +57408 -604
- package/dist/index.d.ts +57408 -604
- package/dist/index.js +17 -1
- package/ios/IndianaBridge.m +11 -0
- package/ios/IndianaBridge.swift +275 -0
- package/native-sdk/android/assets/indiana/index.html +268 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/BillingAuthorizationTerms.kt +55 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/BundledWebView.kt +90 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/ContentSession.kt +45 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/ContentView.kt +36 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/CustomerOperations.generated.kt +84 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/CustomerResponseSemantics.kt +193 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/CustomerSemantics.kt +120 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/CustomerSession.kt +106 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/FeatureClient.kt +65 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/FunnelCommandStorage.kt +163 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/FunnelConfigurationRelay.kt +50 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/FunnelSession.kt +208 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/FunnelView.kt +71 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/GeneratedProtocol.kt +16 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/GoogleStorefront.kt +165 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/HTTPTransport.kt +43 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/IndianaClient.kt +526 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/NativePendingKeystore.kt +81 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/NativeReceiptRelay.kt +28 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/NativeStoreOffer.kt +24 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/PaywallContent.kt +75 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/PaywallSession.kt +144 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/PaywallView.kt +74 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/Protocol.kt +28 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/PushInstallation.kt +170 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/RendererNavigation.kt +13 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/SDKVersion.kt +6 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/StoreSubscriptionManagement.kt +19 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/WireSchema.kt +76 -0
- package/native-sdk/android/resources/funnel-wire-schemas.json +1 -0
- package/native-sdk/android/resources/indiana-third-party-notices.txt +101 -0
- package/native-sdk/android/resources/renderer-data-url.txt +1 -0
- package/native-sdk/ios/AnalyticsReceipt.swift +10 -0
- package/native-sdk/ios/AppleStorefront.swift +218 -0
- package/native-sdk/ios/BillingAuthorizationTerms.swift +57 -0
- package/native-sdk/ios/BundledWebView.swift +87 -0
- package/native-sdk/ios/ContentSession.swift +48 -0
- package/native-sdk/ios/ContentView.swift +51 -0
- package/native-sdk/ios/CustomerOperations.generated.swift +166 -0
- package/native-sdk/ios/CustomerResponseSemantics.swift +232 -0
- package/native-sdk/ios/CustomerSemantics.swift +145 -0
- package/native-sdk/ios/CustomerSession.swift +129 -0
- package/native-sdk/ios/FeatureClient.swift +86 -0
- package/native-sdk/ios/FunnelCommandStorage.swift +163 -0
- package/native-sdk/ios/FunnelConfigurationRelay.swift +48 -0
- package/native-sdk/ios/FunnelSession.swift +232 -0
- package/native-sdk/ios/FunnelView.swift +125 -0
- package/native-sdk/ios/GeneratedProtocol.swift +16 -0
- package/native-sdk/ios/HTTPTransport.swift +74 -0
- package/native-sdk/ios/IndianaClient.swift +601 -0
- package/native-sdk/ios/NativePendingKeychain.swift +52 -0
- package/native-sdk/ios/NativeReceiptRelay.swift +28 -0
- package/native-sdk/ios/NativeStoreOffer.swift +34 -0
- package/native-sdk/ios/PaywallContent.swift +75 -0
- package/native-sdk/ios/PaywallSession.swift +124 -0
- package/native-sdk/ios/PaywallView.swift +87 -0
- package/native-sdk/ios/Protocol.swift +49 -0
- package/native-sdk/ios/PushInstallation.swift +154 -0
- package/native-sdk/ios/RendererNavigation.swift +8 -0
- package/native-sdk/ios/Resources.swift +15 -0
- package/native-sdk/ios/SDKVersion.swift +4 -0
- package/native-sdk/ios/StoreSubscriptionManagement.swift +11 -0
- package/native-sdk/ios/WebView/THIRD_PARTY_NOTICES.txt +101 -0
- package/native-sdk/ios/WebView/index.html +268 -0
- package/native-sdk/ios/WebView/renderer-data-url.txt +1 -0
- package/native-sdk/ios/WireSchema.swift +107 -0
- package/native-sdk/ios/funnel-wire-schemas.json +1 -0
- package/package.json +8 -3
- package/react-native.config.cjs +12 -0
package/dist/index.js
CHANGED
|
@@ -1 +1,17 @@
|
|
|
1
|
-
var $d=Object.defineProperty;var Gd=(e,t,r)=>t in e?$d(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ct=(e,t,r)=>Gd(e,typeof t!="symbol"?t+"":t,r);import{z as pi}from"zod";var Hd=pi.enum(["sandbox","live"]),Je=pi.object({projectId:pi.string().min(1),environment:Hd}).strict();import{z as de}from"zod";var vr=de.number().int().min(1).max(Number.MAX_SAFE_INTEGER),go=de.enum(["unknown","denied","provisional","granted"]),bo=de.enum(["ios","android"]),ln=de.strictObject({installationId:de.uuid(),publicKey:de.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:de.iso.datetime({offset:!0}),signature:de.string().regex(/^[A-Za-z0-9_-]{86}$/)}),fi=de.string().regex(/^[a-f0-9]{64}$/),yo=ln.extend({sequence:vr,platform:bo,credentialDigest:fi}),So=ln.extend({credentialDigest:fi}),_o=ln.extend({sequence:vr,platform:bo}),dn=ln.extend({sequence:vr,credentialDigest:fi,connectionId:de.uuid().nullable(),kind:de.enum(["fcm_token","apns_token"]).nullable(),token:de.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:go}),xo=dn,Io=dn.extend({challenge:de.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),hi=de.strictObject({requested:de.literal(!0),expiresAt:de.iso.datetime({offset:!0})}),Mt=de.strictObject({installationId:de.uuid(),bound:de.boolean(),identitySeq:vr,bindingGeneration:vr,addressSeq:de.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:de.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:de.uuid().nullable(),addressStatus:de.enum(["active","invalid"]).nullable(),permission:go}),Ai=de.strictObject({channel:de.enum(["email","sms","voice","push"]),state:de.enum(["unknown","allowed","denied"]),revision:de.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:de.iso.datetime({offset:!0}).nullable()}),Yb=de.strictObject({state:de.enum(["allowed","denied"]),revision:de.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function vo(e,t,r){let n=["indiana_push_v1",e,t.projectId,t.environment,r.installationId,r.publicKey,r.issuedAt];e==="bind"?n.push(r.sequence,r.platform,r.credentialDigest):e==="detach"?n.push(r.sequence,r.platform):e==="read"?n.push(r.credentialDigest):n.push(r.sequence,r.credentialDigest,r.connectionId,r.kind,r.token,r.permission),e==="recovery_confirm"&&n.push(r.challenge);let i=JSON.stringify(n);if([...i].some(o=>o.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(i,o=>o.charCodeAt(0))}import{z as qe}from"zod";var Ut=qe.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),zb=qe.enum([...Ut.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),ey=qe.enum([...Ut.options,"stale_revision"]),Kd=qe.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),Zd=qe.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),Co={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};var Po={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function Wd(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(Po,e)){let n=Po[e];return{retryable:n==="retry_same_request",recovery:n}}let r=Ut.safeParse(e);return r.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:Co[r.data].recovery}:{retryable:!1,recovery:"contact_support"}}function wo(e,t){let r=Ut.safeParse(e);if(r.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):Co[r.data].status===t;let n={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(n,e)&&(n[e]?.includes(t)??!1)}function Qd(e,t=Date.now()){if(e===null)return;let r=e.trim();if(/^\d+$/.test(r)){let i=Number(r);return Number.isSafeInteger(i)?i:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(r))return;let n=Date.parse(r);return Number.isFinite(n)?Math.max(0,Math.ceil((n-t)/1e3)):void 0}var Oo=qe.object({retryable:qe.boolean(),recovery:Kd,reason:Zd.optional(),retryAfterSeconds:qe.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),gi=qe.object({requestId:qe.uuid().optional(),error:qe.object({code:qe.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:qe.string(),...Oo.partial().shape})}),ty=qe.object({error:gi.shape.error.extend({requestId:qe.uuid().optional()})}),ry=qe.object({error:qe.string(),code:qe.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:qe.uuid(),...Oo.shape});function mn(e,t,r={}){let n=Wd(e,t),i=r.reason==="RESULT_UNKNOWN"?"recover_operation":r.recovery??n.recovery,o=n.retryable&&r.retryable!==!1&&i!=="recover_operation",a=o?Qd(r.retryAfter??null):void 0;return{...n,retryable:o,recovery:i,...a===void 0?{}:{retryAfterSeconds:a},...r.reason?{reason:r.reason}:{}}}var bi="X-Indiana-Protocol",Eo="X-Indiana-SDK-Version";var yi={current:"0.9",unversioned:"0.2",releases:[{protocol:"0.9",firstReleasedAt:"2026-10-28T16:48:16.303Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.9.1",integrity:"sha512-NKzni3vETR7mpVO+ZGBJF2fd3p6UypfsJ8l1JyiE1TWy4iAhP4qxbHJYI5J8hfeyZQ8Qzc6+kpKwIimHXGZmJA==",sha256:"dc087bb7d126523d3abe33edc246a5ac128fef79076fab1af61148871446faaa"}]},{protocol:"0.2",firstReleasedAt:"2026-10-16T04:05:43.170Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.2.0",integrity:"sha512-kyzHFrt+zuS2hfDZsknCE3AIA9EZXakCDhorO0Ayn2wTpITbm32GMaqVFyhlPufDhkjkV4C0UvXJMyLT5FWIoQ==",sha256:"7e20dd8df9c5e965f67bcdad6c95bf0d0aa5e61a372e5ece88173e32190a1c4c"}]},{protocol:"0.3",firstReleasedAt:"2026-10-16T16:18:04.572Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.3.0",integrity:"sha512-jrh4DH2DBYL5tRkr9BNBVIgD1ts0hUPx8+AhiNkkt2uWV27R8tXGRCW1HBLOw2bfomyuIsAXBAY6niJfjkazCg==",sha256:"33f7ca369d509c44df95c5c8b94775c2afe9d8e3a94163275fe59754739e6815"},{version:"0.3.1",integrity:"sha512-Ifp24kv236advquxa78jx49XKz9oKsg5zZZvFMkId4+KxsylsGxHS44fqYJL/b84PVHl3DLuc+Ru2btdLEctIw==",sha256:"4cc047fe94477e77c5403ce47afea0db2806bd4c3cb94a2dd48c453b4e942163"}]},{protocol:"0.4",firstReleasedAt:"2026-10-18T12:44:12.148Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.4.0",integrity:"sha512-QYuxMdw63RzPLkqmFRc7xv8VWYKYWG+KuKM+f5ZeRX879n6sKyr38bxkMiozFXT+kvH0lDfTF73uJPY2yQX1pQ==",sha256:"ef22d0f6a89897bfbaf71487c4e805997528c8dbad2921ab5c90ed3aa0c01244"}]},{protocol:"0.5",firstReleasedAt:"2026-10-19T08:12:17.954Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.5.0",integrity:"sha512-tzdmoHdvaSoDIvGmg+JpmzE+o1kv7DXpSyvNUSuBj5rHX2pD1GDsMf7ioudUVT5MiKaBDVVtJVE+GpxMOBBLLA==",sha256:"d8b1909bebe1bca0c8c029a68b71477e06ba0c9317c3a2b4bf657951ae3449ca"}]},{protocol:"0.6",firstReleasedAt:"2026-10-21T11:41:57.832Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.6.0",integrity:"sha512-M4szAkM52gqiGPZbtpdhoAvYW2uNRQ2aRw0mdnpr2ErTnuG2i1++76fHjo0qiEMSlePdqu99T1Smecp/FZ2//g==",sha256:"141b058b485fb17b416a2f7961ca55e2da413c9afb7ff22f9fdec2561890bd82"},{version:"0.6.1",integrity:"sha512-KbZUP4XCRblj4mF//JG9t4AAMHSP7uENTi7edxJE55QZjvxH4n1/ypWtKZq32xgt9qGu9o3iZzL8tcHoM3B7Ng==",sha256:"e87930eaec7735629e27e930a462dcecb65fdc4e396cc8ab075845a4f4d22396"},{version:"0.6.2",integrity:"sha512-CUXfh46gSh1S7cdgStI3NAzRROlCQxOcvna2KKlDWFq8L7DXtcILLBOKw5Y1e+QQdDPsXGrsMVBOwIJxFyoIlw==",sha256:"dee5f6e605133ec6c509f390fafdf1d0cb66984a02bea0bb5c05828276c64a15"},{version:"0.6.3",integrity:"sha512-MJXbEoZdLym8a7IHUhY9Oh6eXaSRZPdkwYmfGvfsu5O/kTzfIg+OJuaNrFHYzK76msTxR76IMtQ1R45/FddGdg==",sha256:"fcff156ee9ae90a0f5c906721c8e12715f5fd7a97bca494d64a4303283ec633a"},{version:"0.6.4",integrity:"sha512-djTPwCCgNbp/dt0pFnwEgutZExBZ//wmA2GnObRtXydGrzfi8Z9W7RdeGUFvufblJaGAmcWwVqUgmzEi9SLyjA==",sha256:"bd8e53823728b1e45a27e187c538dcb18af005f24e55120d0cc6b5a618a033f7"}]},{protocol:"0.7",firstReleasedAt:"2026-10-23T09:15:53.572Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.7.0",integrity:"sha512-u2LstlzE8IVFy2dUf/sI9sybNRx3lMF32pjLmeEIFqTdcOXRGdH8GCg5927FwavBpRaWO4a7icmrhYiEjGuYWQ==",sha256:"bb3c3666cbba4ea5018f09e9d050b5db1f71e7a222cdde59c5a93f5ee4a52958"}]},{protocol:"0.8",firstReleasedAt:"2026-10-24T09:44:23.748Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.8.0",integrity:"sha512-w94iNQZo2xG9nVKJ4DcXJ3CpLa7sX8GUQlrIlgWAb+P1x99aXg/pnTeYk+rMaOstO5X/x13eB4xufVcbr8tN+Q==",sha256:"81613ce691331768f0849608fdffc5c78257c763e7cefad9236c4f0351a869ad"},{version:"0.8.1",integrity:"sha512-B07LLUiHHSy6Kxmjg47TBdnpSt7y+Z9tkN3TBBFclY7Fr+AH39Vaavz6eguzxCgb1uSiFQquJONWiKLvEcez+Q==",sha256:"619724c8bc8d8e219ea1ed74b8b4195457e25e92697cdc43b864876fcc004ffe"},{version:"0.8.3",integrity:"sha512-enKlzcLIydk3t3Z74FVXQODv9SNrhq7hfQ0Rcpd6SHBBbfiqFX0h6tWkHJifnJBrTVxAwCNG5aRvZY9x0Hxw1A==",sha256:"63270b8893be90624344ce628cc8d6e3b60cf65d214c9ec7586e71b35ca0dff8"},{version:"0.8.4",integrity:"sha512-pvhQawFj4vv8zLefCMtm4YusAGVxEGpc6OMnO0fM3Y2knnonOC8JBtO/NadEPZA2hb0Rggo0hbrVgNC4mDFBhw==",sha256:"ed8476a40a937875628439a3f5bab056f94a8e3efcb78abd19fd504a4737ddda"},{version:"0.8.5",integrity:"sha512-d89LuMdv8L4hbAv0DeDbT3gPpfZsjdmadd5/zTwd4RwsfiihY7H+RMVjgfciic7BxnT7ZiI94JfsJLqdBBMa1w==",sha256:"0cc92920d29a4279a9c12a0542584f401605dce6e56e39f94ed369dcb02138ec"}]}]};import{z as Yd}from"zod";var Jd=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],Y=Yd.enum(Jd);function To(e){let t=Y.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}import{z as ir}from"zod";var qt=ir.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID \u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u5E76\u4EE5\u5B57\u6BCD\u5F00\u5934"),uy=ir.object({amountCents:ir.number().int().min(0).max(1e8),currency:Y,interval:ir.enum(["free","month","year"]),currencyOptions:ir.partialRecord(Y,ir.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C");import{z as g}from"zod/v4";import{z as Xd}from"zod/v4";var jo=Xd.registry();var{AppEnv:pn}=(()=>{var e;return(function(t){t.Sandbox="sandbox",t.Live="live"})(e||(e={})),{AppEnv:e}})(),{IGNORE_PAST_DUE_DESCRIPTION:Ro}={IGNORE_PAST_DUE_DESCRIPTION:"If true, entitlements attached to this plan will still reset on schedule even when the customer's product is in a past_due state."},{PurchaseLimitInterval:zd}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{SpendLimitType:em}=(e=>({SpendLimitType:e.enum(["absolute","usage_percentage"])}))(g),{ResetInterval:Pr}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Minute="minute",t.Hour="hour",t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{ResetInterval:e}})(),{USAGE_LIMIT_ANCHORS:tm}={USAGE_LIMIT_ANCHORS:["billing_cycle","utc"]},{USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:rm}={USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:64},{USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:nm}={USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:128},{USAGE_LIMIT_FILTER_MAX_KEYS:im}={USAGE_LIMIT_FILTER_MAX_KEYS:4},{UsageAlertThresholdType:am}=(e=>({UsageAlertThresholdType:e.enum(["usage","usage_percentage","remaining","remaining_percentage"])}))(g),{BALANCE_BASES:om}={BALANCE_BASES:["balance","included","recurring"]},{DEFAULT_USAGE_ALERT_BASIS:ko}={DEFAULT_USAGE_ALERT_BASIS:"balance"},{DbOverageAllowedSchema:Si}=(e=>({DbOverageAllowedSchema:e.object({feature_id:e.string().meta({description:"The feature ID this overage allowed control applies to."}),enabled:e.boolean().default(!1).meta({description:"Whether overage is allowed for this feature."})})}))(g),{ProductMetadataSchema:ar}=(e=>({ProductMetadataSchema:e.record(e.string(),e.any())}))(g),{findDuplicate:sm}={findDuplicate:t=>{let r=new Set;for(let n of t){if(r.has(n))return n;r.add(n)}}},{BillingInterval:wt}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:_i}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(g),{withSpecDefault:Cr}=(e=>({withSpecDefault:({schema:r,defaultValue:n,description:i})=>(e.add(r,{description:i,default:n}),r)}))(jo),{COMMON:Do}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:cm}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:um}=(e=>({COMMON_SET:new Set(e)}))(Do),{hasNoDuplicateCurrencies:No}={hasNoDuplicateCurrencies:t=>{let r=new Set;for(let{currency:n}of t){let i=n.toLowerCase();if(r.has(i))return!1;r.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:Mo}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{IncludedUsageParamsSchema:xi}=(e=>({IncludedUsageParamsSchema:e.number().max(1e13,{error:"Included usage cannot exceed 10 trillion; use unlimited usage instead"})}))(g),{Infinite:fn}={Infinite:"inf"},{TierBehavior:wr}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:hn}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Uo}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{PLAN_ITEM_PRICE_DESCRIPTION:lm}={PLAN_ITEM_PRICE_DESCRIPTION:"Pricing for usage beyond included units. Omit for free features."},{OnIncrease:An}=(()=>{var e;return(function(t){t.BillImmediately="bill_immediately",t.ProrateImmediately="prorate_immediately",t.ProrateNextCycle="prorate_next_cycle",t.BillNextCycle="bill_next_cycle"})(e||(e={})),{OnIncrease:e}})(),{OnDecrease:gn}=(()=>{var e;return(function(t){t.Prorate="prorate",t.ProrateImmediately="prorate_immediately",t.ProrateNextCycle="prorate_next_cycle",t.None="none",t.NoProrations="no_prorations"})(e||(e={})),{OnDecrease:e}})(),{RolloverExpiryDurationType:Ii}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:qo}=(()=>{var e;return(function(t){t.Day="day",t.Week="week",t.Month="month",t.Year="year"})(e||(e={})),{EntitlementDuration:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:dm}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:mm}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:vi}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(g),{ApiCreditTierSchema:Lo}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(g),{VIOLATION_MESSAGES:pm}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:Bo}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(g),{ModelMarkupsSchema:Pi}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(g,Bo),{additionalCurrencyPlanItemIssues:Fo}={additionalCurrencyPlanItemIssues:t=>{if(!t)return[];let r=[];t.additional_currencies&&t.additional_currencies.length>0&&(typeof t.amount!="number"||(t.tiers?.length??0)>0)&&r.push("price.additional_currencies requires a flat 'amount'; tiered prices carry per-currency amounts on each tier.");let n=t.tiers;if(n&&n.length>0){let i=a=>(a.additional_currencies??[]).map(c=>c.currency.toLowerCase()),o=new Set(n.flatMap(i));o.size>0&&(n.every(c=>{let l=new Set(i(c));return l.size===o.size&&[...o].every(p=>l.has(p))})||r.push("Each additional currency must be present on every tier or none."))}return r}},{PlanItemFilterSchema:Ci}=((e,t,r,n,i)=>({PlanItemFilterSchema:e.object({feature_id:e.string().optional().meta({description:"Match items linked to this feature."}),billing_method:e.enum(t).optional().meta({description:"Match items with this billing method (prepaid or usage_based)."}),interval:e.union([e.enum(r),e.enum(n)]).optional().meta({description:"Match items with this interval. Accepts either a BillingInterval (price-side) or a ResetInterval (reset-side, includes day/hour/minute) so price-less items keyed by reset.interval can be disambiguated."}),interval_count:e.number().int().positive().optional().meta({description:"Match items with this interval_count. Disambiguates between items that share an interval but differ in count."}),included:i.optional().meta({description:"Match items whose grant equals this included usage. Omitted is a wildcard."})}).refine(a=>a.feature_id!==void 0||a.billing_method!==void 0||a.interval!==void 0||a.interval_count!==void 0,{message:"PlanItemFilter must have at least one field set."}).meta({title:"PlanItemFilter",description:"Filter for matching plan items. All provided fields must match (AND)."})}))(g,hn,wt,Pr,xi),{UpdatePlanItemParamsV1Schema:fm}=((e,t,r)=>({UpdatePlanItemParamsV1Schema:e.object({filter:t.meta({description:"Filter selecting which existing plan item(s) to update. Same shape as remove_items filters."}),included:e.number().nonnegative().optional().meta({description:"Override the matched item's included usage / allowance. Existing usage carries forward."}),interval:e.enum(r).optional().meta({description:"Override the matched item's reset interval. Use 'one_off' for non-resetting balances."})}).meta({title:"UpdatePlanItem",description:"Deprecated. Use remove_items and add_items to replace plan items.",deprecated:!0})}))(g,Ci,Pr),{FreeTrialDuration:Or}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{laneParam:hm}=((e,t)=>({laneParam:({schema:n,description:i})=>e({schema:t.array(n).optional(),defaultValue:[],description:i})}))(Cr,g),{findDuplicateInControls:Am}={findDuplicateInControls:({controlKey:t,controls:r,rule:n})=>{let i=new Set;for(let[o,a]of r.entries()){let c=n.identityOf(a);if(c!==void 0){if(i.has(c))return{code:"custom",message:n.message,input:a[n.field],path:[t,o,n.field]};i.add(c)}}}},{featureIdIdentity:gm}={featureIdIdentity:t=>t.feature_id||void 0},{usageLimitFilterKey:Vo}={usageLimitFilterKey:t=>t?.properties?Object.entries(t.properties).map(([r,n])=>[r,String(n)]).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${r}=${n}`).join("&"):""},{usageAlertIdentity:bm}=((e,t)=>({usageAlertIdentity:n=>[n.feature_id??"",n.basis??e,t(n.filter),n.threshold_type,n.threshold].join("|")}))(ko,Vo),{RemovePlanLicenseSchema:ym}=(e=>({RemovePlanLicenseSchema:e.object({license_plan_id:e.string()})}))(g),{ApiStripePriceProcessorSchema:Sm}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(g),{ApiFeatureType:_m}=(()=>{var e;return(function(t){t.Static="static",t.Boolean="boolean",t.SingleUsage="single_use",t.ContinuousUse="continuous_use",t.CreditSystem="credit_system",t.AiCreditSystem="ai_credit_system"})(e||(e={})),{ApiFeatureType:e}})(),{ApiStripePlanProcessorSchema:xm}=(e=>({ApiStripePlanProcessorSchema:e.object({product_id:e.string().meta({description:"Stripe product ID this plan is billed under."}),additional_product_ids:e.array(e.string()).optional().meta({description:"Extra Stripe product IDs aliased to this plan."})})}))(g),{ApiRevenueCatProductSchema:Im}=(e=>({ApiRevenueCatProductSchema:e.object({product_id:e.string().meta({description:"RevenueCat product ID that grants this plan when purchased."}),feature_quantities:e.array(e.object({feature_id:e.string(),quantity:e.number().nonnegative().optional()})).optional().meta({description:"Prepaid quantities granted when this specific RevenueCat product is purchased, in feature units."})})}))(g),{TrialOnEnd:bn}={TrialOnEnd:["bill","revert"]},{EligibilityStatus:vm}=(()=>{var e;return(function(t){t.Active="active",t.Scheduled="scheduled"})(e||(e={})),{EligibilityStatus:e}})(),{AttachAction:Pm}=(()=>{var e;return(function(t){t.Activate="activate",t.Upgrade="upgrade",t.Downgrade="downgrade",t.None="none",t.Purchase="purchase"})(e||(e={})),{AttachAction:e}})(),{AttachScenario:Cm}=(()=>{var e;return(function(t){t.Scheduled="scheduled",t.Active="active",t.New="new",t.Renew="renew",t.Upgrade="upgrade",t.UpdatePrepaidQuantity="update_prepaid_quantity",t.Downgrade="downgrade",t.Cancel="cancel",t.Expired="expired",t.PastDue="past_due"})(e||(e={})),{AttachScenario:e}})(),{UsageWindowDimensionSchema:wm}=(e=>({UsageWindowDimensionSchema:e.enum(["balance","metered_feature"])}))(g),{UsageWindowScopeSchema:Om}=(e=>({UsageWindowScopeSchema:e.enum(["customer","entity"])}))(g),{EntInterval:$o}=(()=>{var e;return(function(t){t.Lifetime="lifetime",t.Minute="minute",t.Hour="hour",t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{EntInterval:e}})(),{FeatureType:Em}=(()=>{var e;return(function(t){t.Boolean="boolean",t.Metered="metered",t.CreditSystem="credit_system",t.AiCreditSystem="ai_credit_system"})(e||(e={})),{FeatureType:e}})(),{FeatureStripeMeterSchema:Tm}=(e=>({FeatureStripeMeterSchema:e.object({id:e.string(),event_name:e.string()})}))(g),{FreeTrialSchema:jm}=((e,t,r)=>({FreeTrialSchema:e.object({id:e.string(),duration:e.enum(t),length:e.number(),unique_fingerprint:e.boolean(),created_at:e.number(),internal_product_id:e.string(),is_custom:e.boolean(),card_required:e.boolean(),on_end:e.enum(r).nullish()})}))(g,Or,bn),{BillingType:Rm}=(()=>{var e;return(function(t){t.OneOff="one_off",t.FixedCycle="fixed_cycle",t.UsageBelowThreshold="usage_below_threshold",t.UsageInAdvance="usage_in_advance",t.UsageInArrear="usage_in_arrear",t.InArrearProrated="in_arrear_prorated"})(e||(e={})),{BillingType:e}})(),{UsageTierSchema:wi}=((e,t)=>({UsageTierSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional()}).refine(n=>n.amount!==void 0||n.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(n=>({...n,amount:n.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional()}))}))(g,fn),{IgnoredFixedPriceMetadataSchema:km}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(r=>typeof r=="string"?null:r,e.null().or(e.undefined()))}))(g),{BillWhen:Dm}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:Go}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProrationConfigSchema:Nm}=((e,t,r)=>({ProrationConfigSchema:e.object({on_increase:e.nativeEnum(t).default(t.ProrateImmediately),on_decrease:e.nativeEnum(r).default(r.ProrateImmediately)})}))(g,An,gn),{AllowanceType:Mm}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{RolloverConfigSchema:Ho}=((e,t)=>({RolloverConfigSchema:e.object({max:e.number().nullable().optional(),max_percentage:e.number().nullable().optional(),duration:e.enum(t).default(t.Month),length:e.number()})}))(g,Ii),{CreditDimensionBaseSchema:Um}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(g,vi),{flatCreditRateShape:Ko}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(g),{CreditTierSchema:qm}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(g),{CreditMultiplierSchema:Lm}=((e,t)=>({CreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional(),add:e.number().optional()}).refine(n=>n.factor!==void 0||n.add!==void 0,{message:"A multiplier needs a factor or an add"})}))(g,vi),{idRegex:yn}={idRegex:/^[a-zA-Z0-9_-]+$/},{descriptions:Zo}={descriptions:{id:"The ID of the product. Used to identify the product in other API calls like checkout or update product.",name:"The name of the product",description:"The description of the product",is_add_on:"Whether the product is an add-on. Add-on products can be attached multiple times and don't to through upgrade / downgrade flows.",is_default:"Whether the product is the default product. Default products are enabled by default for new customers.",group:"Product group which this product belongs to. Products within a group have upgrade / downgrade logic when the customer moves between them.",items:"Array of product items that define the product's features and pricing",free_trial:"Free trial configuration for this product, if available",metadata:"Arbitrary key-value metadata for your own use (e.g. UI copy, feature highlights). Values can be any JSON-serializable value. Metadata is shared across all versions of a plan.",archived:"Archive this product using this flag. Archived products are hidden on the dashboard."}},{ProductItemType:Bm}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ProductItemFeatureType:Fm}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{ProductItemInterval:Vm}=(()=>{var e;return(function(t){t.Minute="minute",t.Hour="hour",t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{ProductItemInterval:e}})(),{UsageModel:$m}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{TierInfinite:Gm}={TierInfinite:"inf"},{CreateFreeTrialSchema:Wo}=((e,t,r)=>({CreateFreeTrialSchema:e.object({length:e.string().or(e.number()).transform(i=>Number(i)).refine(i=>i>0,{message:"Free trial length must be greater than 0"}),unique_fingerprint:e.boolean().default(!1),duration:e.enum(t).default(t.Day),card_required:e.boolean().default(!0),on_end:e.enum(r).nullish()})}))(g,Or,bn),{ProductConfigParamsSchema:Oi}=((e,t,r)=>({ProductConfigParamsSchema:e.object({ignore_past_due:t({schema:e.boolean().optional(),defaultValue:!1,description:r})})}))(g,Cr,Ro),{CREATE_PRODUCT_EXAMPLE:Hm}={CREATE_PRODUCT_EXAMPLE:{id:"Pro Product",name:"Pro Plan",is_add_on:!1,is_default:!1,items:[{price:20,interval:"month"},{feature_id:"messages",included_usage:1e3,price:.5,interval:"month",usage_model:"pay_per_use"}],free_trial:{duration:"day",length:7,unique_fingerprint:!1,card_required:!0}}},{ApiFreeTrialSchema:Km}=((e,t,r)=>({ApiFreeTrialSchema:e.object({duration:e.enum(t).meta({description:"The duration type of the free trial"}),length:e.number().meta({description:"The length of the duration type specified"}),unique_fingerprint:e.boolean().meta({description:"Whether the free trial is limited to one per customer fingerprint"}),card_required:e.boolean().meta({description:"Whether the free trial requires a card. If false, the customer can attach the product without going through a checkout flow or having a card on file."}),on_end:e.enum(r).nullish().meta({description:"Behavior when the trial ends. 'bill' charges the customer (default). 'revert' expires the trial and restores the customer's previous plan."}),trial_available:e.boolean().default(!0).nullish().meta({description:"Used in customer context. Whether the free trial is available for the customer if they were to attach the product."})})}))(g,Or,bn),{CreateProductSchema:hy}=(e=>({CreateProductSchema:e.object({id:e.string(),name:e.string().min(1,"Product name cannot be empty").default("Untitled Product"),is_add_on:e.boolean().default(!1),is_default:e.boolean().default(!1),version:e.number().optional().default(1),group:e.string().optional().default("")})}))(g),{isUsageLimitBasisAlert:Zm}={isUsageLimitBasisAlert:t=>t.basis==="usage_limit"},{PromoCodeSchema:Qo}=(e=>({PromoCodeSchema:e.object({code:e.string(),global_max_redemption:e.number().positive().optional(),first_time_transaction:e.boolean().optional(),max_redemptions:e.number().positive().optional()})}))(g),{RewardType:Yo}=(()=>{var e;return(function(t){t.PercentageDiscount="percentage_discount",t.FixedDiscount="fixed_discount",t.FreeProduct="free_product",t.InvoiceCredits="invoice_credits",t.FeatureGrant="feature_grant"})(e||(e={})),{RewardType:e}})(),{CouponDurationType:Jo}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Months="months",t.Forever="forever"})(e||(e={})),{CouponDurationType:e}})(),{FreeProductConfigSchema:Xo}=((e,t)=>({FreeProductConfigSchema:e.object({duration_type:e.nativeEnum(t),duration_value:e.number()})}))(g,Jo),{RewardTriggerEvent:Wm}=(()=>{var e;return(function(t){t.CustomerCreation="customer_creation",t.Checkout="checkout"})(e||(e={})),{RewardTriggerEvent:e}})(),{RewardReceivedBy:Qm}=(()=>{var e;return(function(t){t.Referrer="referrer",t.All="all"})(e||(e={})),{RewardReceivedBy:e}})(),{ProductConfigSchema:Sn}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(g,Ro),{PurchaseLimitIntervalEnum:Ym}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(g,zd),{DbSpendLimitSchema:Ei}=((e,t)=>({DbSpendLimitSchema:e.object({feature_id:e.string().optional().meta({description:"Optional feature ID this spend limit applies to."}),enabled:e.boolean().default(!1).meta({description:"Whether the overage spend limit is enabled."}),limit_type:t.optional().meta({description:"How overage_limit is interpreted: an absolute overage cap (default) or a percentage of the main-plan allowance."}),overage_limit:e.number().min(0).optional().meta({description:"Overage cap for the feature: absolute units, or a percent (e.g. 120) when limit_type is usage_percentage."}),skip_overage_billing:e.boolean().optional().meta({description:"When true, overage for this feature is not posted to Stripe. Usage tracking and balance resets still behave normally."})}).refine(n=>n.overage_limit===void 0&&n.skip_overage_billing===void 0||n.feature_id!==void 0,{message:"feature_id is required when overage_limit or skip_overage_billing is provided",path:["feature_id"]})}))(g,em),{USAGE_LIMIT_INTERVALS:Jm}=(e=>({USAGE_LIMIT_INTERVALS:[e.Day,e.Week,e.Month,e.Year]}))(Pr),{UsageLimitAnchorSchema:zo}=((e,t)=>({UsageLimitAnchorSchema:e.enum(t)}))(g,tm),{UsageLimitFilterValueSchema:Xm}=((e,t)=>({UsageLimitFilterValueSchema:e.union([e.string().min(1).max(t),e.number(),e.boolean()]).transform(String).pipe(e.string())}))(g,nm),{USAGE_ALERT_BASES:zm}=(e=>({USAGE_ALERT_BASES:[...e,"usage_limit"]}))(om),{licensePatchIssues:ep}=(e=>({licensePatchIssues:({upsertLicenses:r=[]})=>{let n=e(r.map(i=>i.license_plan_id));return n===void 0?[]:[{message:`Duplicate license ${n} in upsert_licenses`,path:["upsert_licenses"]}]}}))(sm),{BasePriceSchema:tp}=((e,t,r)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:r.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(g,wt,_i),{CURRENCY_CODES:rp}=((e,t,r)=>({CURRENCY_CODES:[...e,...t.filter(i=>!r.has(i)).sort()]}))(Do,cm,um),{AllocatedBillingFieldSchema:es}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(g,Uo),{EntitlementExpirySchema:_n}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(g,qo),{CreditDimensionNameSchema:ts}=((e,t,r)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(r),{message:`Dimension names cannot contain "${r}"`})}))(g,dm,mm),{ApiCreditMatchSchema:rs}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(vi),{findCreditTierViolations:np}=(e=>({findCreditTierViolations:r=>{let n=[],i=(a,c)=>n.push({index:a,reason:c,message:e[c]}),o=0;for(let[a,c]of r.entries()){let l=a===r.length-1;if(c==="inf"){l||i(a,"non_final_infinity");continue}(!Number.isFinite(c)||c<=o)&&i(a,"not_increasing"),o=c,l&&i(a,"final_not_infinity")}return n}}))(pm),{ApiCreditMultiplierSchema:ip}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(n=>n.factor!==void 0||n.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(g,rs),{ProviderMarkupsSchema:ns}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(g,Bo),{planItemParamsIssues:ap}=((e,t,r,n,i)=>({planItemParamsIssues:a=>{let c=[],l=a.reset?.interval,p=a.price?.interval,A=a.reset?.interval_count??1,v=a.price?.interval_count??1;if(l&&p&&(String(l)!==String(p)||A!==v)&&a.price?.billing_method!==e.Prepaid&&c.push({message:"reset.interval and price.interval can only differ for prepaid prices.",input:a}),a.threshold_billing&&(!a.price||a.unlimited)&&c.push({message:"threshold_billing requires a finite usage-based price",input:a.threshold_billing}),a.expiry&&(a.price?.billing_method===e.Prepaid&&String(a.price.interval)===String(t.OneOff)||c.push({message:"expiry is only supported on one-off prepaid items. Recurring items are already bounded by their reset cadence.",input:a.expiry}),a.entity_feature_id&&c.push({message:"expiry is not supported on entity-scoped items; each entity's balance would have to expire on its own clock.",input:a.expiry}),a.pooled&&c.push({message:"expiry is not supported on pooled items; pooled balances have no per-purchase lifetime.",input:a.expiry}),a.expiry.length<=0&&c.push({message:"expiry.length must be greater than 0",input:a.expiry})),a.price){a.threshold_billing&&a.price.billing_method!==e.UsageBased&&c.push({message:"threshold_billing requires a finite usage-based price",input:a.threshold_billing});let{amount:U,tiers:ie}=a.price;a.threshold_billing&&ie?.length&&c.push({message:"threshold_billing currently requires a flat usage price",input:a.threshold_billing});let q=a.price.billing_method===e.UsageBased&&a.price.allocated_billing===r.ProratedLegacy;a.proration&&a.price.billing_method!==e.Prepaid&&!q&&c.push({message:"proration is only supported for prepaid or legacy allocated prices.",input:a.proration});let ve=typeof U=="number",Ne=Array.isArray(ie)&&ie.length>0;ve||Ne?ve&&Ne&&c.push({message:"'amount' and 'tiers' cannot both be defined in 'price'.",input:a.price}):c.push({message:"If 'price' is present, either 'amount' or 'tiers' must be defined.",input:a.price})}if(a.price?.tiers){let U=a.price.tiers.some(ie=>ie.flat_amount&&ie.flat_amount>0);U&&a.price.tier_behavior!==n.VolumeBased&&c.push({message:"flat_amount on tiers is only supported for volume-based pricing.",input:a.price}),U&&a.price.tiers.length<=1&&c.push({message:"flat_amount is not supported on single-tier pricing.",input:a.price}),a.price.tiers.some(ie=>ie.flat_amount!=null&&ie.flat_amount<0)&&c.push({message:"flat_amount must be 0 or greater.",input:a.price}),a.price?.tier_behavior===n.VolumeBased&&a.price?.billing_method!==e.Prepaid&&c.push({message:"volume-based pricing is only supported for prepaid features.",input:a.price}),a.price?.tiers.length===0?c.push({message:"tiers cannot be empty.",input:a.price}):a.included&&typeof a.price?.tiers[0].to=="number"&&a.price?.tiers[0].to<=a.included&&c.push({message:"tiers[0].to must be greater than included.",input:a.price})}for(let U of i(a.price))c.push({message:U,input:a.price});return c}}))(hn,wt,Uo,wr,Fo),{FreeTrialParamsV1Schema:Ti}=((e,t,r)=>({FreeTrialParamsV1Schema:e.object({duration_length:e.number().meta({description:"Number of duration_type periods the trial lasts."}),duration_type:e.enum(t).default(t.Month).meta({description:"Unit of time for the trial ('day', 'month', 'year')."}),card_required:e.boolean().default(!1).meta({description:"If true, a payment method is required to start the trial and the customer is charged when it ends. Defaults to false."}),on_end:r({schema:e.enum(["bill","revert"]).optional(),defaultValue:"bill",description:"Behavior when the trial ends. 'bill' charges the customer (default). 'revert' expires the trial and restores the customer's previous plan."})}).meta({title:"FreeTrialParams",description:"Free trial configuration for a plan."})}))(g,Or,Cr),{duplicateCheck:op}=(e=>({duplicateCheck:({controlKey:r,...n})=>i=>e({controlKey:r,controls:i[r]??[],rule:n})}))(Am),{usageLimitIdentity:ji}=(e=>({usageLimitIdentity:r=>`${r.feature_id}|${e(r.filter)}`}))(Vo),{ApiPriceProcessorsSchema:is}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(g,Sm),{ApiFeatureV0Schema:as}=((e,t)=>({ApiFeatureV0Schema:e.object({id:e.string().meta({description:"The ID of the feature, used to refer to it in other API calls like /track or /check."}),name:e.string().nullish().meta({description:"The name of the feature."}),type:e.enum(t).meta({description:"The type of the feature"}),display:e.object({singular:e.string().meta({description:"The singular display name for the feature."}),plural:e.string().meta({description:"The plural display name for the feature."})}).nullish().meta({description:"Singular and plural display names for the feature."}),credit_schema:e.array(e.object({metered_feature_id:e.string().meta({description:"The ID of the metered feature (should be a single_use feature)."}),credit_cost:e.number().meta({description:"The credit cost of the metered feature."})})).nullish().meta({description:"Credit cost schema for credit system features."}),archived:e.boolean().nullish().meta({description:"Whether or not the feature is archived."})})}))(g,_m),{ApiRevenueCatPlanProcessorSchema:sp}=((e,t)=>({ApiRevenueCatPlanProcessorSchema:e.object({products:e.array(t).meta({description:"Every RevenueCat product that maps to this plan. Replaces the current set."})})}))(g,Im),{ApiFreeTrialV2Schema:cp}=((e,t,r)=>({ApiFreeTrialV2Schema:e.object({duration_length:e.number().meta({description:"Number of duration_type periods the trial lasts."}),duration_type:e.enum(t).meta({description:"Unit of time for the trial duration ('day', 'month', 'year')."}),card_required:e.boolean().meta({description:"Whether a payment method is required to start the trial. If true, customer will be charged after trial ends."}),on_end:e.enum(r).nullish().meta({description:"Behavior when the trial ends. 'bill' charges the customer (default). 'revert' expires the trial and restores the customer's previous plan."})})}))(g,Or,bn),{CustomerEligibilitySchema:up}=((e,t,r,n)=>({CustomerEligibilitySchema:e.object({object:e.literal("customer_eligibility").optional().meta({internal:!0}),trial_available:e.boolean().optional().meta({description:"Whether the trial on this plan is available to this customer. For example, if the customer used the trial in the past, this will be false."}),status:e.enum(t).optional().meta({description:"The customer's current status with this plan. 'active' if attached, 'scheduled' if pending activation."}),canceling:e.boolean().optional().meta({description:"Whether the customer's active instance of this plan is set to cancel."}),trialing:e.boolean().optional().meta({description:"Whether the customer is currently on a free trial of this plan."}),attach_action:e.enum(r).meta({description:"The action that would occur if this plan were attached to the customer."}),scenario:e.enum(n).optional().meta({description:"Legacy attach scenario. Internal use only.",internal:!0})})}))(g,vm,Pm,Cm),{UsageWindowLimitSchema:Ay}=((e,t,r,n,i)=>({UsageWindowLimitSchema:e.object({feature_id:e.string(),internal_feature_id:e.string(),internal_customer_id:e.string(),key:e.string(),dimension_type:t,dimension_feature_id:e.string().nullable(),scope_type:r,entity_id:e.string().nullable(),internal_entity_id:e.string().nullable(),filter_key:e.string().nullable(),filter_properties:e.record(e.string(),e.string()).nullable(),interval:e.enum(n),window_start_at:e.number(),window_end_at:e.number(),limit:e.number(),anchor_customer_entitlement_id:e.string().nullable(),anchor_mode:i.default("billing_cycle"),new_window_id:e.string().optional()})}))(g,wm,Om,$o,zo),{FeatureSchema:lp}=((e,t,r,n,i)=>({FeatureSchema:e.object({internal_id:e.string(),org_id:e.string(),created_at:e.number().nullable(),env:e.nativeEnum(t),id:e.string().nonempty("Features must have an ID"),name:e.string().nonempty("Features must have a name"),type:e.nativeEnum(r,{message:"Features must have a type"}),config:e.any(),display:e.object({singular:e.string().optional(),plural:e.string().optional()}).nullish(),archived:e.boolean(),event_names:e.array(e.string()).default([]),model_markups:n.nullish(),stripe_meter:i.nullish(),stripe_product_id:e.string().nullish()})}))(g,pn,Em,Pi,Tm),{PriceCurrencyConfigSchema:os}=((e,t)=>({PriceCurrencyConfigSchema:e.object({amount:e.number().nullish(),usage_tiers:e.array(t).nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish()})}))(g,wi),{UsagePriceConfigSchema:dp}=((e,t,r,n,i,o)=>({UsagePriceConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish(),type:e.string(),bill_when:e.nativeEnum(t),billing_units:e.number().nullish(),internal_feature_id:e.string(),feature_id:e.string(),usage_tiers:e.array(r),interval:e.enum(n),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),i).nullish(),stripe_meter_id:e.string().nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_event_name:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish(),should_prorate:e.boolean().optional(),allocated_billing_behavior:e.enum(o).optional()})}))(g,Dm,wi,wt,os,Go),{graduatedCreditRateShape:ss}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(g,qm),{FeatureMarkupsOverrideSchema:mp}=((e,t,r)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:r})}))(g,ns,Pi),{usageAlertTargetLimitIdentity:pp}=(e=>({usageAlertTargetLimitIdentity:r=>e({feature_id:r.feature_id??"",filter:r.filter})}))(ji),{DiscountConfigSchema:cs}=((e,t)=>({DiscountConfigSchema:e.object({discount_value:e.number(),duration_type:e.nativeEnum(t),duration_value:e.number(),should_rollover:e.boolean().optional(),apply_to_all:e.boolean().optional(),price_ids:e.array(e.string()).optional(),product_ids:e.array(e.string()).optional()})}))(g,Jo),{RewardEntitlementSchema:us}=((e,t)=>({RewardEntitlementSchema:e.object({internal_feature_id:e.string().min(1),allowance:e.number().nonnegative().optional(),expiry:t.optional()})}))(g,_n),{UpdateRewardSchema:gy}=((e,t,r,n,i,o)=>({UpdateRewardSchema:e.object({name:e.string().nullish(),promo_codes:e.array(t).optional(),id:e.string().optional(),type:e.nativeEnum(r).optional(),discount_config:n.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(o).nullish()})}))(g,Qo,Yo,cs,Xo,us),{CreateRewardProgram:by}=((e,t,r)=>({CreateRewardProgram:e.object({id:e.string(),when:e.enum(t),product_ids:e.array(e.string()).optional(),exclude_trial:e.boolean().optional(),internal_reward_id:e.string(),max_redemptions:e.number().optional(),received_by:e.enum(r)})}))(g,Wm,Qm),{AutoTopupPurchaseLimitSchema:ls}=((e,t)=>({AutoTopupPurchaseLimitSchema:e.object({interval:t.meta({description:"The time interval for the purchase limit window."}),interval_count:e.number().min(1).default(1).meta({description:"Number of intervals in the purchase limit window."}),limit:e.number().min(1).meta({description:"Maximum number of auto top-ups allowed within the interval."})})}))(g,Ym),{UsageLimitFilterSchema:ds}=((e,t,r,n)=>({UsageLimitFilterSchema:e.object({properties:e.record(e.string().min(1).max(t),r).meta({description:"Event property equality conditions. A usage event counts toward this cap only when every listed property matches (AND)."}).check(o=>{let a=Object.keys(o.value).length;(a<1||a>n)&&o.issues.push({code:"custom",message:`filter.properties must have between 1 and ${n} keys`,input:o.value})})})}))(g,rm,Xm,im),{UsageAlertBasisSchema:fp}=((e,t)=>({UsageAlertBasisSchema:e.enum(t)}))(g,zm),{refineCustomizePlanV1Schema:ms}=(e=>({refineCustomizePlanV1Schema:(r,{includeItems:n=!0,includeFreeTrial:i=!0,includeUpdateItems:o=!0,includeLicenses:a=!0}={})=>{let c=["price",n&&"items","add_items","remove_items",o&&"update_items",i&&"free_trial","billing_controls",a&&"upsert_licenses",a&&"remove_licenses"].filter(Boolean),l=p=>p==="update_items"?"deprecated update_items":p;return r.refine(p=>c.some(A=>p[A]!==void 0),{message:`When using customize, at least one of ${c.map(l).join(", ")} must be provided`}).superRefine((p,A)=>{if(a)for(let v of e({upsertLicenses:p.upsert_licenses}))A.addIssue({code:"custom",...v})}).refine(p=>!(p.items!==void 0&&(p.add_items!==void 0||p.remove_items!==void 0||o&&p.update_items!==void 0)),{message:`customize.items (PUT-style) cannot be combined with ${["add_items","remove_items",o?"deprecated update_items":null].filter(Boolean).join(" / ")} (PATCH-style); pick one approach`})}}))(ep),{SUPPORTED_SET:hp}=(e=>({SUPPORTED_SET:new Set(e)}))(rp),{ApiCreditDimensionBaseSchema:Ap}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(g,rs),{refineGraduatedTiers:ps}=(e=>({refineGraduatedTiers:(r,n)=>{let i=e(r.tiers.map(o=>o.to));for(let{index:o,message:a}of i)n.addIssue({code:"custom",message:a,path:["tiers",o,"to"]})}}))(np),{ApiFeatureMarkupsOverrideSchema:gp}=((e,t,r)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:r.meta({description:"Per-model markup overrides for customers on this plan."})})}))(g,ns,Pi),{AutoTopupPurchaseLimitParamsSchema:bp}=((e,t)=>({AutoTopupPurchaseLimitParamsSchema:e.extend({count:t.number().min(0).optional().meta({description:"Set the current window's consumed auto top-up count. Omit to leave runtime state unchanged."})})}))(ls,g),{DUPLICATE_CHECKS:yp}=((e,t,r,n)=>({DUPLICATE_CHECKS:[e({controlKey:"auto_topups",identityOf:t,field:"feature_id",message:"Only one auto top-up entry is allowed per feature_id"}),e({controlKey:"spend_limits",identityOf:t,field:"feature_id",message:"Only one spend limit entry is allowed per feature_id"}),e({controlKey:"usage_limits",identityOf:r,field:"feature_id",message:"Only one usage limit entry is allowed per feature_id and filter"}),e({controlKey:"usage_alerts",identityOf:n,field:"threshold",message:"Only one usage alert entry is allowed per feature_id, basis, filter, threshold_type and threshold"}),e({controlKey:"overage_allowed",identityOf:t,field:"feature_id",message:"Only one overage_allowed entry is allowed per feature_id"})]}))(op,gm,ji,bm),{ApiPlanProcessorsSchema:Sp}=((e,t,r)=>({ApiPlanProcessorsSchema:e.object({stripe:t.nullish(),revenuecat:r.nullish()}).meta({"x-atmn-mapping":!0})}))(g,xm,sp),{FixedPriceConfigSchema:_p}=((e,t,r,n,i)=>({FixedPriceConfigSchema:e.object({type:e.string(),amount:e.number().min(0),interval:e.enum(t),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),r).nullish(),billing_units:e.number().nullish(),usage_tiers:e.array(n).nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),feature_id:i,internal_feature_id:i})}))(g,wt,os,wi,km),{CreditDimensionSchema:xp}=((e,t,r,n)=>({CreditDimensionSchema:e.union([t.extend(r),t.extend(n)])}))(g,Um,Ko,ss),{filterUnresolvableUsageLimitAlerts:Ip}=((e,t,r)=>({filterUnresolvableUsageLimitAlerts:({usageAlerts:i,usageLimitLists:o})=>{let a=new Set(o.flatMap(c=>(c??[]).map(e)));return i.flatMap((c,l)=>t(c)&&!a.has(r(c))?[{index:l,usageAlert:c}]:[])}}))(ji,Zm,pp),{CreateRewardSchema:yy}=((e,t,r,n,i,o)=>({CreateRewardSchema:e.object({name:e.string(),promo_codes:e.array(t),id:e.string(),type:e.nativeEnum(r).nullish(),discount_config:n.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(o).nullish()}).refine(c=>c.type!==r.FeatureGrant?!0:c.entitlements&&c.entitlements.length>0,{message:"Feature grant rewards require at least one entitlement"}).refine(c=>c.type!==r.FeatureGrant?!0:c.promo_codes.some(l=>l.code.length>0),{message:"Feature grant rewards require at least one promo code"})}))(g,Qo,Yo,cs,Xo,us),{AutoTopupSchema:Ri}=((e,t)=>({AutoTopupSchema:e.object({feature_id:e.string().meta({description:"The ID of the feature (credit balance) to auto top-up."}),enabled:e.boolean().default(!1).meta({description:"Whether auto top-up is enabled."}),threshold:e.number().meta({description:"When the balance drops below this threshold, an auto top-up will be purchased."}),quantity:e.number().min(1).meta({description:"Amount of credits to add per auto top-up."}),purchase_limit:t.optional().meta({description:"Optional rate limit to cap how often auto top-ups occur."}),invoice_mode:e.boolean().optional().meta({description:"When true, auto top-up creates a send_invoice invoice instead of auto-charging."})})}))(g,ls),{DbUsageLimitSchema:ki}=((e,t,r,n)=>({DbUsageLimitSchema:e.object({feature_id:e.string().meta({description:"The feature this usage limit applies to."}),enabled:e.boolean().default(!0).meta({description:"Whether this usage limit is enabled."}),limit:e.number().min(0).meta({description:"Maximum units allowed per interval."}),interval:e.enum(t).meta({description:"Interval for the cap, aligned to the customer's billing cycle."}),anchor:r.optional().meta({description:"Window alignment. 'billing_cycle' phases the interval to the customer's renewal time; 'utc' aligns to the UTC calendar."}),filter:n.optional().meta({description:"When set, only usage from events whose properties match counts toward this cap. Omit to count all usage of the feature."})})}))(g,Jm,zo,ds),{DbUsageAlertSchema:Di}=((e,t,r,n,i)=>({DbUsageAlertSchema:e.object({feature_id:e.string().optional().meta({description:"The feature ID this alert applies to."}),enabled:e.boolean().default(!0).meta({description:"Whether this usage alert is enabled."}),threshold:e.number().min(0).meta({description:"The threshold value that triggers the alert. For usage or remaining, this is an absolute count. For usage_percentage or remaining_percentage, this is a percentage (0-100)."}),threshold_type:t.meta({description:"Whether the threshold is an absolute count or a percentage of the usage allowance or remaining balance."}),basis:r.default(n).meta({description:"What 100% means. balance: every grant on the feature. included: the plan allowance only. recurring: grants that reset. usage_limit: the cap of the usage limit with the same feature and filter."}),filter:i.optional().meta({description:"Only valid with basis usage_limit. Points the alert at the usage limit carrying the same filter."}),name:e.string().optional().meta({description:"Optional user-defined label to distinguish multiple alerts on the same feature."})}).check(a=>{let{feature_id:c,threshold_type:l,threshold:p,basis:A,filter:v}=a.value;l==="remaining_percentage"&&p>100&&a.issues.push({code:"custom",input:p,path:["threshold"],message:"Threshold must be between 0 and 100 for remaining_percentage"}),A==="usage_limit"&&!c&&a.issues.push({code:"custom",input:c,path:["feature_id"],message:"feature_id is required when basis is usage_limit"}),v&&A!=="usage_limit"&&a.issues.push({code:"custom",input:v,path:["filter"],message:"filter is only valid when basis is usage_limit"})})}))(g,am,fp,ko,ds),{isValidCurrencyCode:vp}=(e=>({isValidCurrencyCode:r=>!!r&&e.has(r.toLowerCase())}))(hp),{ApiCreditDimensionSchema:Pp}=((e,t,r,n)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(r).min(1)}).strict().superRefine(n),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(g,Ap,Lo,ps),{AutoTopupParamsSchema:Cp}=((e,t)=>({AutoTopupParamsSchema:e.extend({purchase_limit:t.optional().meta({description:"Optional rate limit to cap how often auto top-ups occur. Pass count to set the current window's consumed top-ups."})})}))(Ri,bp),{findDuplicateBillingControlIssue:wp}=(e=>({findDuplicateBillingControlIssue:r=>{for(let n of e){let i=n(r);if(i)return i}}}))(yp),{CustomerBillingControlsSchema:Ni}=((e,t,r,n,i,o)=>({CustomerBillingControlsSchema:e.object({auto_topups:e.array(t).optional().meta({description:"List of auto top-up configurations per feature."}),spend_limits:e.array(r).optional().meta({description:"List of overage spend limits per feature (caps overage spend)."}),usage_limits:e.array(n).optional().meta({description:"List of hard usage caps per feature (max units per interval)."}),usage_alerts:e.array(i).optional().meta({description:"List of usage alert configurations per feature."}),overage_allowed:e.array(o).optional().meta({description:"List of overage allowed controls per feature. When enabled, usage can exceed balance."})})}))(g,Ri,Ei,ki,Di,Si),{PriceSchema:Op}=((e,t,r,n,i,o)=>({PriceSchema:e.object({id:e.string(),internal_product_id:e.string().nullable(),org_id:e.string().optional(),created_at:e.number().optional(),billing_type:e.nativeEnum(t).nullish(),tier_behavior:e.nativeEnum(r).nullish(),is_custom:e.boolean().optional(),config:n.or(i),entitlement_id:e.string().nullish(),proration_config:o.nullable()})}))(g,Rm,wr,_p,dp,Nm),{CreditSchemaItemBaseSchema:fs}=((e,t,r,n)=>({CreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string(),feature_amount:e.number().optional(),dimensions:e.record(t,r).optional(),multipliers:e.record(t,n).optional()})}))(g,ts,xp,Lm),{GraduatedCreditSchemaItemSchema:Ep}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(fs,ss),{UpdateProductSchema:Sy}=((e,t,r)=>({UpdateProductSchema:e.object({id:e.string().nullish(),name:e.string().min(1,"Product name cannot be empty").optional(),description:e.string().nullish(),is_add_on:e.boolean().optional(),is_default:e.boolean().optional(),group:e.string().nullish(),archived:e.boolean().optional(),config:t.partial().optional(),billing_controls:r.optional()})}))(g,Sn,Ni),{DbBillingControlsSchema:Tp}=((e,t,r,n,i,o)=>({DbBillingControlsSchema:e.object({auto_topups:e.array(t).nullish(),spend_limits:e.array(r).nullish(),usage_limits:e.array(n).nullish(),usage_alerts:e.array(i).nullish(),overage_allowed:e.array(o).nullish()})}))(g,Ri,Ei,ki,Di,Si),{CurrencyCodeSchema:hs}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(g,vp),{AdditionalCurrencyTierSchema:jp}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(n=>n.amount!==void 0||n.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(g,hs),{ApiCreditSchemaItemBaseSchema:As}=((e,t,r,n)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,r).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,n).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(g,ts,Pp,ip),{ApiFlatCreditSchemaItemSchema:Rp}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(As,g),{rejectDuplicateBillingControls:kp}=(e=>({rejectDuplicateBillingControls:r=>{let n=e(r.value);n&&r.issues.push(n)}}))(wp),{FlatCreditSchemaItemSchema:Dp}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(fs,Ko),{ProductSchema:Np}=((e,t,r,n,i)=>({ProductSchema:e.object({id:e.string(),name:e.string().min(1,"Product name cannot be empty"),description:e.string().nullable(),is_add_on:e.boolean(),is_default:e.boolean(),version:e.number(),version_slug:e.string().nullable().default(null),active:e.boolean().default(!1),deleted_at:e.number().nullable().default(null),previous_version_slug:e.string().nullable().default(null),group:e.string(),env:e.enum(t),internal_id:e.string(),org_id:e.string(),created_at:e.number(),processor:e.object({type:e.string(),id:e.string(),additional_ids:e.array(e.string()).optional()}).nullish(),base_variant_id:e.string().nullable(),base_internal_product_id:e.string().nullish(),archived:e.boolean().default(!1),config:r.default(()=>({ignore_past_due:!1})),...n.shape,metadata:i.default(()=>({}))})}))(g,pn,Sn,Tp,ar),{AdditionalCurrencyPriceSchema:Mp}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(g,hs),{AdditionalCurrencyTierArraySchema:gs}=((e,t,r,n)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(r,{message:n})}))(g,jp,No,Mo),{ApiGraduatedCreditSchemaItemSchema:Up}=((e,t,r,n)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(r).min(1)}).strict().superRefine(n)}))(As,g,Lo,ps),{CustomerBillingControlsParamsSchema:xn}=((e,t,r,n,i,o,a,c)=>({CustomerBillingControlsParamsSchema:e.object({auto_topups:t({schema:r,description:"List of auto top-up configurations per feature."}),spend_limits:t({schema:n,description:"List of overage spend limits per feature (caps overage spend)."}),usage_limits:t({schema:i,description:"List of hard usage caps per feature (max units per interval)."}),usage_alerts:t({schema:o,description:"List of usage alert configurations per feature."}),overage_allowed:t({schema:a,description:"List of overage allowed controls per feature. When enabled, usage can exceed balance."})}).check(c)}))(g,hm,Cp,Ei,ki,Di,Si,kp),{CreditSchemaItemSchema:qp}=((e,t,r)=>({CreditSchemaItemSchema:e.union([t,r])}))(g,Dp,Ep),{PriceTierSchema:Lp}=((e,t,r)=>({PriceTierSchema:e.object({to:e.number().or(e.literal(t)).meta({description:"The maximum amount of usage for this tier.",example:100}),amount:e.number().optional().meta({description:"The price of the product item for this tier.",example:10}),flat_amount:e.number().optional().meta({description:"A flat fee charged for this tier, in addition to the per-unit amount."}),additional_currencies:r.nullish().meta({description:"Per-currency amounts for this tier. Boundaries ('to') are shared across currencies."})}).refine(i=>i.amount!=null||i.flat_amount!=null,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0}))}))(g,Gm,gs),{PlanBillingControlsParamsSchema:Bp}=((e,t)=>({PlanBillingControlsParamsSchema:e.check(n=>{let i=t({usageAlerts:n.value.usage_alerts??[],usageLimitLists:[n.value.usage_limits??[]]});for(let{index:o,usageAlert:a}of i)n.issues.push({code:"custom",message:`No usage limit on this plan matches the usage_limit alert for feature ${a.feature_id}`,input:a,path:["usage_alerts",o,"basis"]})})}))(xn,Ip),{AdditionalCurrencyPriceArraySchema:Er}=((e,t,r,n)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(r,{message:n})}))(g,Mp,No,Mo),{ApiUsageTierWithCurrenciesSchema:bs}=((e,t,r)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:r.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:r.optional()}))}))(g,fn,gs),{ApiCreditSchemaItemSchema:Fp}=((e,t,r)=>({ApiCreditSchemaItemSchema:e.union([t,r])}))(g,Up,Rp),{FeatureConfigOverrideSchema:ys}=((e,t,r)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:r.optional()})}))(g,qp,mp),{ProductItemConfigSchema:Vp}=((e,t,r,n,i,o,a)=>({ProductItemConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),allocated_billing_behavior:e.enum(t).nullish(),on_increase:e.enum(r).nullish(),on_decrease:e.enum(n).nullish(),rollover:i.nullish(),expiry:o.nullish(),feature_override:a.nullish()})}))(g,Go,An,gn,Ho,_n,ys),{BasePriceParamsSchema:In}=((e,t,r,n)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:r.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:n.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:r.string().optional().meta({internal:!0}),entitlement_id:r.string().optional().meta({internal:!0}),price_id:r.string().optional().meta({internal:!0}),stripe_price_id:r.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(tp,Cr,g,Er),{PlanItemPriceParamsSchema:$p}=((e,t,r,n,i,o,a)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(l=>l??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(r).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(n).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(o).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:a,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(g,Er,bs,wr,wt,hn,es),{ApiFeatureOverrideSchema:Ss}=((e,t,r)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:r.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(g,Fp,gp),{ApiPlanItemV1Schema:Gp}=((e,t,r,n,i,o,a,c,l,p,A,v,k,U,ie,q,ve)=>({ApiPlanItemV1Schema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),feature_id:e.string().meta({description:"The ID of the feature this item configures."}),feature:t.optional().meta({description:"The full feature object if expanded."}),included:e.number().meta({description:"Number of free units included. For consumable features, balance resets to this number each interval."}),unlimited:e.boolean().meta({description:"Whether the customer has unlimited access to this feature."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),reset:e.object({interval:e.enum(r).meta({description:"The interval at which the feature balance resets (e.g. 'month', 'year'). For consumable features, usage resets to 0 and included units are restored."}),interval_count:e.number().optional().meta({description:"Number of intervals between resets. Defaults to 1."})}).nullable().meta({description:"Reset configuration for consumable features. Null for non-consumable features like seats where usage persists across billing cycles."}),price:e.object({amount:e.number().optional().meta({description:"Price per billing_units after included usage is consumed. Mutually exclusive with tiers."}),additional_currencies:n.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers' (tiered prices carry per-currency amounts on each tier)."}),tiers:e.array(i).optional().meta({description:"Tiered pricing configuration. Each tier's 'to' INCLUDES the included amount. Either 'tiers' or 'amount' is required."}),tier_behavior:e.enum(o).optional(),interval:e.enum(a).meta({description:"Billing interval for this price. For consumable features, should match reset.interval."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().meta({description:"Number of units per price increment. Usage is rounded UP to the nearest billing_units when billed (e.g. billing_units=100 means 101 usage rounds to 200)."}),billing_method:e.enum(c).meta({description:"'prepaid' for features like seats where customers pay upfront, 'usage_based' for pay-as-you-go after included usage."}),allocated_billing:l,max_purchase:e.number().nullable().meta({description:"Maximum units a customer can purchase beyond included. E.g. if included=100 and max_purchase=300, customer can use up to 400 total before usage is capped. Null for no limit."}),processors:p.optional().meta({description:"Payment processors this item price is connected to. Omitted when unset."})}).nullable().meta({description:"Pricing configuration for usage beyond included units. Null if feature is entirely free."}),display:A.optional().meta({description:"Display text for showing this item in pricing pages."}),rollover:e.object({max:e.number().nullable().meta({description:"Maximum rollover units. Null for unlimited rollover."}),max_percentage:e.number().nullable().optional().meta({description:"Maximum rollover as a percentage (0-100) of included + prepaid grant. Mutually exclusive with max."}),expiry_duration_type:e.enum(v).meta({description:"When rolled over units expire."}),expiry_duration_length:e.number().optional().meta({description:"Number of periods before expiry."})}).optional().meta({description:"Rollover configuration for unused units. If set, unused included units roll over to the next period."}),proration:e.object({on_increase:e.enum(k).optional().meta({description:"How to handle billing when quantity increases mid-cycle."}),on_decrease:e.enum(U).optional().meta({description:"How to handle credits when quantity decreases mid-cycle."})}).optional().meta({internal:!0}),expiry:ie.nullish().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:q.optional().meta({description:"Overrides fields of this item's feature for customers on this plan (e.g. a credit system's credit_schema)."}),entity_feature_id:e.string().optional().meta({internal:!0}),mapping_identity:e.string().optional().meta({internal:!0}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0})}).check(T=>{let F=T.value.reset?.interval,Q=T.value.price?.interval,he=T.value.reset?.interval_count??1,ge=T.value.price?.interval_count??1;if(F&&Q&&(String(F)!==String(Q)||he!==ge)&&T.value.price?.billing_method!==c.Prepaid&&T.issues.push({code:"custom",message:"reset.interval and price.interval can only differ for prepaid prices.",input:T.value}),T.value!==void 0&&T.value.price!==void 0&&T.value.price!==null){T.value.price.amount&&T.value.price.tiers&&T.value.price.tiers.length>0&&T.issues.push({code:"custom",message:"Price amount and tiers are mutually exclusive.",input:T.value});for(let Be of ve(T.value.price))T.issues.push({code:"custom",message:Be,input:T.value.price})}})}))(g,as,Pr,Er,bs,wr,wt,hn,es,is,_i,Ii,An,gn,_n,Ss,Fo),{EntitlementSchema:Hp}=((e,t,r,n,i,o)=>({EntitlementSchema:e.object({id:e.string(),created_at:e.number(),internal_feature_id:e.string(),internal_product_id:e.string().nullable(),internal_reward_id:e.string().nullish(),is_custom:e.boolean().default(!1),allowance_type:e.nativeEnum(t).optional().nullable(),allowance:e.number().nullish(),interval:e.nativeEnum(r).optional().nullable(),interval_count:e.number().default(1),carry_from_previous:e.boolean().default(!1).optional(),entity_feature_id:e.string().nullish(),pooled:e.boolean().default(!1).optional(),org_id:e.string().optional(),feature_id:e.string().optional(),usage_limit:e.number().nullable().optional().default(null),expiry_duration:e.nativeEnum(n).nullish(),expiry_length:e.number().nullish(),rollover:i.nullish(),feature_override:o.nullish()})}))(g,Mm,$o,qo,Ho,ys),{ProductItemSchema:_s}=((e,t,r,n,i,o,a,c,l,p,A)=>({ProductItemSchema:e.object({type:e.enum(t).nullish().meta({description:"The type of the product item."}),feature_id:e.string().nullish().meta({description:"The feature ID of the product item. Should be null for fixed price items."}),feature_type:e.enum(r).nullish().meta({internal:!0}),feature:n.nullish().meta({internal:!0}),included_usage:e.union([e.number(),e.literal(i)]).nullish().meta({description:"The amount of usage included for this feature (per interval)."}),interval:e.preprocess(k=>{if(k==="")throw new Error("Interval cannot be empty.");return k},e.enum(o).nullish()).meta({description:"The reset or billing interval of the product item. If null, feature will have no reset date, and if there's a price, it will be billed one-off."}),interval_count:e.number().nullish().meta({description:"Interval count of the feature."}),entity_feature_id:e.string().nullish().meta({description:"The feature ID of the entity (like seats) to track sub-balances for."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),usage_model:e.enum(a).nullish().meta({description:"Whether the feature should be prepaid upfront or billed for how much they use end of billing period."}),price:e.number().nullish().meta({description:"The price of the product item. Should be null if tiered pricing is set."}),tiers:e.array(c).nullish().meta({description:"Tiered pricing for the product item. Not applicable for fixed price items."}),base_currency:e.string().nullish().meta({internal:!0}),additional_currencies:l.nullish().meta({description:"Amounts in additional currencies for a flat-priced item. Tiered items carry per-currency amounts on each tier."}),billing_units:e.number().nullish().meta({description:"The billing units of the product item (eg $1 for 30 credits)."}),tier_behavior:e.enum(p).nullish().meta({description:"The type of tiered pricing: graduated or volume-based."}),reset_usage_when_enabled:e.boolean().nullish().meta({description:"Whether the usage should be reset when the product is enabled."}),display:e.object({primary_text:e.string(),secondary_text:e.string().nullish()}).nullish().meta({internal:!0}),usage_limit:e.number().nullish().meta({internal:!0}),config:A.nullish().meta({internal:!0}),created_at:e.number().nullish().meta({internal:!0}),entitlement_id:e.string().nullish().meta({internal:!0}),price_id:e.string().nullish().meta({internal:!0}),stripe_price_id:e.string().nullish().meta({internal:!0}),stripe_prepaid_price_v2_id:e.string().nullish().meta({internal:!0}),price_interval:e.enum(o).nullish().meta({internal:!0}),price_interval_count:e.number().nullish().meta({internal:!0}),price_config:e.any().nullish().meta({internal:!0}),_uid:e.string().nullish().meta({internal:!0})})}))(g,Bm,Fm,as,fn,Vm,$m,Lp,Er,wr,Vp),{ProductV2Schema:xs}=((e,t,r,n,i,o,a)=>({ProductV2Schema:e.object({internal_id:e.string().nullish(),id:e.string(),name:e.string(),description:e.string().nullish(),is_add_on:e.boolean(),is_default:e.boolean(),version:e.number().default(1),version_slug:e.string().nullable().optional(),active:e.boolean().optional(),group:e.string().nullable(),env:e.nativeEnum(t),free_trial:r.nullish(),items:e.array(n),created_at:e.number(),stripe_id:e.string().nullish(),archived:e.boolean().default(!1).nullish(),base_internal_product_id:e.string().nullish(),base_id:e.string().nullish(),config:i.partial().optional(),billing_controls:o.optional(),metadata:a.optional()})}))(g,pn,Km,_s,Sn,Ni,ar),{PlanItemParamsObjectSchema:Kp}=((e,t,r,n,i,o,a,c,l,p,A)=>({PlanItemParamsObjectSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),feature_id:e.string().meta({description:"The ID of the feature to configure."}),included:t.optional().meta({description:"Number of free units included. Balance resets to this each interval for consumable features."}),unlimited:e.boolean().optional().meta({description:"If true, customer has unlimited access to this feature."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),reset:e.object({interval:e.enum(r).meta({description:"Interval at which balance resets (e.g. 'month', 'year'). For consumable features only."}),interval_count:n({schema:e.number().optional(),defaultValue:1,description:"Number of intervals between resets. Defaults to 1."})}).optional().meta({description:"Reset configuration for consumable features. Omit for non-consumable features like seats."}),price:i.optional().meta({description:o}),proration:e.object({on_increase:e.enum(a).meta({description:"Billing behavior when quantity increases mid-cycle."}),on_decrease:e.enum(c).meta({description:"Credit behavior when quantity decreases mid-cycle."})}).optional().meta({description:"Proration settings for prepaid features. Controls mid-cycle quantity change billing."}),rollover:e.object({max:e.number().optional().meta({description:"Max rollover units. Omit for unlimited rollover."}),max_percentage:e.number().optional().meta({description:"Maximum rollover as a percentage (0-100) of included + prepaid grant. Mutually exclusive with max."}),expiry_duration_type:e.enum(l).meta({description:"When rolled over units expire."}),expiry_duration_length:e.number().optional().meta({description:"Number of periods before expiry."})}).optional().meta({description:"Rollover config for unused units. If set, unused included units carry over."}),expiry:p.optional().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:A.optional().meta({description:"Overrides fields of this item's feature for customers on this plan (e.g. a credit system's credit_schema)."}),entity_feature_id:e.string().optional().meta({internal:!0}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0})})}))(g,xi,Pr,Cr,$p,lm,An,gn,Ii,_n,Ss),{FullProductWithoutLicensesSchema:_y}=((e,t,r,n,i,o)=>({FullProductWithoutLicensesSchema:e.extend({description:t.string().nullable().optional().default(null),prices:t.array(r),entitlements:t.array(n.extend({feature:i})),free_trial:o.nullish(),free_trials:t.array(o).nullish(),free_trial_ids:t.array(t.string()).nullish()})}))(Np,g,Op,Hp,lp,jm),{CreateProductItemParamsSchema:Is}=((e,t,r,n)=>({CreateProductItemParamsSchema:e.extend({included_usage:t.or(r.literal(n)).nullish()})}))(_s,xi,g,fn),{CreatePlanItemParamsV1Schema:Mi}=((e,t)=>({CreatePlanItemParamsV1Schema:e.check(n=>{for(let{message:i,input:o}of t(n.value))n.issues.push({code:"custom",message:i,input:o})}).meta({title:"PlanItem",description:"Configuration for a feature item in a plan, including usage limits, pricing, and rollover settings."})}))(Kp,ap),{LicenseCustomizeSchema:vs}=((e,t,r,n)=>({LicenseCustomizeSchema:e.object({price:t.nullable().optional(),add_items:e.array(r).optional(),remove_items:e.array(n).optional()})}))(g,In,Mi,Ci),{PlanLicenseParamsSchema:Ui}=((e,t)=>({PlanLicenseParamsSchema:e.object({license_plan_id:e.string(),version_slug:e.string().optional(),included:e.number().int().min(0).optional(),prepaid_only:e.boolean().optional(),customize:t.nullish(),metadata:e.record(e.string(),e.unknown()).optional()})}))(g,vs),{UpdateProductV2ParamsSchema:xy}=((e,t,r,n,i,o,a,c,l)=>({UpdateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).optional().meta({description:r.id}),name:e.string().refine(A=>A.length>0,{message:"name must be a non-empty string"}).optional().meta({description:r.name}),is_add_on:e.boolean().optional().meta({description:r.is_add_on}),is_default:e.boolean().optional().meta({description:r.is_default}),base_plan_id:e.string().nonempty().regex(t).nullable().optional().meta({description:"The base plan this plan should be linked to as a variant. Set to null to detach it from its base plan."}),description:e.string().nullish().optional().meta({description:r.description}),group:e.string().nonempty().nullable().optional().meta({description:r.group}),archived:e.boolean().optional().meta({description:r.archived}),items:e.array(n).optional(),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:o.nullish().meta({description:r.free_trial}),config:a.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:c.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:l.optional().meta({description:r.metadata})})}))(g,yn,Zo,Is,Ui,Wo,Oi,xn,ar),{CreatePlanParamsV1Schema:Zp}=((e,t,r,n,i,o,a,c,l)=>({CreatePlanParamsV1Schema:e.object({id:e.string().nonempty().regex(t).meta({description:"Unique identifier for the plan."}),group:e.string().default("").meta({description:"Group identifier for organizing related plans. Plans in the same group are mutually exclusive."}),name:e.string().nonempty().meta({description:"Display name of the plan."}),description:e.string().nullable().default(null).meta({description:"Optional description of the plan."}),add_on:e.boolean().default(!1).meta({description:"If true, this plan can be attached alongside other plans. Otherwise, attaching replaces existing plans in the same group."}),auto_enable:e.boolean().default(!1).meta({description:"If true, plan is automatically attached when a customer is created. Use for free tiers."}),price:r.optional().meta({description:"Base recurring price for the plan. Omit for free or usage-only plans."}),items:e.array(n).optional().meta({description:"Feature configurations for this plan. Each item defines included units, pricing, and reset behavior."}),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:o.optional().meta({description:"Free trial configuration. Customers can try this plan before being charged."}),config:a.optional().meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:c.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:l.optional().meta({description:"Arbitrary key-value metadata defined by you for your own use (e.g. UI copy, feature highlights). Values can be any JSON-serializable value. Shared across all versions of the plan."}),create_in_stripe:e.boolean().default(!0).meta({internal:!0})})}))(g,yn,In,Mi,Ui,Ti,Oi,Bp,ar),{UpdatePlanParamsV1Schema:Iy}=((e,t,r,n,i)=>({UpdatePlanParamsV1Schema:e.partial().extend({group:e.shape.group.removeDefault().optional(),version:t.number().optional(),archived:t.boolean().default(!1).optional(),price:r.nullable().optional().meta({description:"The price of the plan. Set to null to remove the base price."}),free_trial:n.nullable().optional().meta({description:"The free trial of the plan. Set to null to remove the free trial."}),base_plan_id:t.string().nonempty().regex(i).nullable().optional().meta({description:"The base plan this plan should be linked to as a variant. Set to null to detach it from its base plan."})})}))(Zp,g,In,Ti,yn),{CustomizePlanLicenseSchema:qi}=((e,t)=>({CustomizePlanLicenseSchema:e.object({license_plan_id:e.string(),version_slug:e.string().optional(),included:e.number().int().min(0).optional(),prepaid_only:e.boolean().optional(),customize:t.nullish(),metadata:e.record(e.string(),e.unknown()).optional()})}))(g,vs),{CreateProductV2ParamsSchema:vy}=((e,t,r,n,i,o,a,c,l,p)=>({CreateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).meta({description:r.id}),name:e.string().refine(v=>v.length>0,{message:"name must be a non-empty string"}).meta({description:r.name}),description:e.string().nullish().meta({description:r.description}),is_add_on:e.boolean().default(!1).meta({description:r.is_add_on}),is_default:e.boolean().default(!1).meta({description:r.is_default}),group:e.string().nullable().default("").meta({description:r.group}),items:e.array(n).optional().meta({description:r.items}),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:o.nullish().default(null).meta({description:r.free_trial}),config:a.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:c.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:l.optional().meta({description:r.metadata}),create_in_stripe:e.boolean().optional().meta({internal:!0}),archived:e.boolean().optional().meta({internal:!0}),base_internal_product_id:e.string().nullable().optional().meta({internal:!0})}).meta({examples:[p]})}))(g,yn,Zo,Is,Ui,Wo,Oi,xn,ar,Hm),{CustomizePlanV1BaseSchema:Ps}=((e,t,r,n,i,o,a,c,l)=>({CustomizePlanV1BaseSchema:e.object({price:t.nullable().optional().meta({description:"Override the base price of the plan. Pass null to remove the base price."}),items:e.array(r).optional().meta({description:"Override the items in the plan (PUT-style \u2014 replaces all existing items). Mutually exclusive with add_items / remove_items / deprecated update_items."}),add_items:e.array(r).optional().meta({description:"Items to add to the plan."}),remove_items:e.array(n).optional().meta({description:"Filters selecting items to remove from the plan."}),update_items:e.array(i).optional().meta({description:"Deprecated. Use remove_items and add_items to replace matched plan items.",internal:!0,deprecated:!0}),free_trial:o.nullable().optional().meta({description:"Override the plan's default free trial. Pass an object to set a custom trial, or null to remove the trial entirely."}),billing_controls:a.optional().meta({description:"Override the plan's billing controls (auto top-ups, spend limits, usage limits, usage alerts, overage allowed) for this customer."}),upsert_licenses:e.array(c).optional().meta({description:"License links to add or override for this customer, keyed by license_plan_id. Omitted fields inherit the plan catalog link (included defaults to 1 when the license is not in the catalog). A bare entry restores the license to pure catalog inheritance."}),remove_licenses:e.array(l).optional().meta({description:"License links to drop, keyed by license_plan_id. Parallel to remove_items."})})}))(g,In,Mi,Ci,fm,Ti,xn,qi,ym),{VariantCustomizeSchema:Wp}=((e,t)=>({VariantCustomizeSchema:e(t.omit({items:!0}).strict(),{includeItems:!1,includeLicenses:!0})}))(ms,Ps),{DiffedCustomizePlanV1Schema:Py}=((e,t)=>({DiffedCustomizePlanV1Schema:e(t.omit({items:!0}),{includeItems:!1,includeLicenses:!0})}))(ms,Ps),{ApiPlanV1Schema:Cy}=((e,t,r,n,i,o,a,c,l,p,A,v,k,U)=>({ApiPlanV1Schema:e.object({id:e.string().meta({description:"Unique identifier for the plan."}),internal_id:e.string().nullable().optional().meta({description:"Stable row id. Survives renames of plan_id and version_slug, so config files address rows by it.",internal:!0}),name:e.string().meta({description:"Display name of the plan."}),description:e.string().nullable().meta({description:"Optional description of the plan."}),group:e.string().nullable().meta({description:"Group identifier for organizing related plans. Plans in the same group are mutually exclusive."}),version:e.number().meta({description:"Version number of the plan. Incremented when plan configuration changes."}),version_slug:e.string().nullable().optional().meta({description:"User-facing version identity. Defaults to v{n} when the version is minted."}),active:e.boolean().optional().meta({description:"Whether this is the active version of the plan. At most one version is active."}),add_on:e.boolean().meta({description:"Whether this is an add-on plan that can be attached alongside a main plan."}),auto_enable:e.boolean().meta({description:"If true, this plan is automatically attached when a customer is created. Used for free plans."}),price:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),additional_currencies:t.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),interval:e.enum(r).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."}),processors:i.optional().meta({description:"Payment processors this base price is connected to. Omitted when unset."})}).nullable().meta({description:"Base recurring price for the plan. Null for free plans or usage-only plans."}),items:e.array(o).meta({description:"Feature configurations included in this plan. Each item defines included units, pricing, and reset behavior for a feature."}),processors:a.optional().meta({description:"Payment processors this plan is connected to. Omitted when unset."}),free_trial:c.optional().meta({description:"Free trial configuration. If set, new customers can try this plan before being charged."}),created_at:e.number().meta({description:"Unix timestamp (ms) when the plan was created."}),env:e.enum(l).meta({description:"Environment this plan belongs to ('sandbox' or 'live')."}),archived:e.boolean().meta({description:"Whether the plan is archived. Archived plans cannot be attached to new customers."}),config:p.meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:A.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:v.meta({description:"Arbitrary key-value metadata defined by you for your own use. Shared across all versions of the plan."}),customer_eligibility:k.optional(),base_variant_id:e.string().nullable().meta({description:"Deprecated. Use variant_details.base_plan_id instead. If this is a variant, the ID of the base plan it was created from.",deprecated:!0}),variant_details:e.object({base_plan_id:e.string().meta({description:"The ID of the base plan this variant was derived from."}),customize:U.optional().meta({description:"The customization that transforms the base plan into this variant."})}).optional().meta({description:"Details about how this variant relates to its latest base plan."})})}))(g,Er,wt,_i,is,Gp,Sp,cp,pn,Sn,Ni,ar,up,Wp);import{z as S}from"zod";var Qp=S.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Os=S.enum(["single_use","continuous_use"]),Li=S.record(S.string(),S.union([S.string(),S.number(),S.boolean()]).transform(String).pipe(S.string())),Cs=S.string().min(1).max(64).refine(e=>!e.includes("::")),Es={credit_amount:S.number(),tier_behavior:S.never().optional(),tiers:S.never().optional()},Ts={credit_amount:S.never().optional(),tier_behavior:S.literal("graduated"),tiers:S.array(S.strictObject({to:S.union([S.number(),S.literal("inf")]),credit_amount:S.number()}))},Yp=S.union([S.strictObject({match:Li,priority:S.number().int().optional(),...Es}),S.strictObject({match:Li,priority:S.number().int().optional(),...Ts})]),Jp=S.strictObject({match:Li,factor:S.number().positive().optional(),add:S.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),ws={metered_feature_id:S.string(),feature_amount:S.number().optional(),dimensions:S.record(Cs,Yp).optional(),multipliers:S.record(Cs,Jp).optional()},Bi=S.union([S.strictObject({...ws,...Es}),S.strictObject({...ws,...Ts})]),Pn=S.number().min(-100),js=S.record(S.string(),S.strictObject({markup:Pn})).nullish(),Cn=S.record(S.string().regex(/.+\/.+/),S.strictObject({markup:Pn.optional(),input_cost:S.number().min(0).optional(),output_cost:S.number().min(0).optional()})).nullish(),Xp=S.strictObject({default_markup:Pn.optional(),provider_markups:js,model_markups:Cn}),Fi=S.strictObject({schema:S.array(Bi).optional(),markups:Xp.optional()}),zp=S.strictObject({filters:S.array(S.strictObject({property:S.string(),operator:S.string(),value:S.array(S.string())})),aggregate:S.strictObject({type:S.string(),property:S.string().nullable()}),usage_type:Os}),Rs=S.strictObject({schema:S.array(Bi).min(1).refine(e=>new Set(e.map(t=>t.metered_feature_id)).size===e.length,"Credit rates must name each metered feature once"),invoice_credit:S.boolean().optional(),usage_type:Os.default("single_use").overwrite(()=>"single_use"),default_markup:Pn.optional(),provider_markups:js}),Vi=Rs.safeExtend({schema:S.array(Bi).length(0)}),vn={id:Qp,name:S.string().min(1),display:S.strictObject({singular:S.string().optional(),plural:S.string().optional()}).nullish(),event_names:S.array(S.string()).default([]),model_markups:Cn,stripe_meter:S.strictObject({id:S.string(),event_name:S.string()}).nullish(),stripe_product_id:S.string().nullish()},$i=e=>S.discriminatedUnion("type",[S.strictObject({...vn,...e,type:S.literal("boolean"),config:S.null()}),S.strictObject({...vn,...e,type:S.literal("metered"),config:zp}),S.strictObject({...vn,...e,type:S.literal("credit_system"),config:Rs}),S.strictObject({...vn,...e,type:S.literal("ai_credit_system"),config:Vi})]),Ey=$i({}),ef=S.strictObject({id:S.boolean(),type:S.boolean(),usage_type:S.boolean()}),tf={internal_id:S.uuid(),org_id:S.uuid(),created_at:S.number(),env:S.enum(["sandbox","live"]),archived:S.boolean(),project_id:S.uuid(),environment_id:S.uuid(),revision:S.number().int().nonnegative(),update_rules:ef},ks=$i(tf),Ty=S.strictObject({rows:S.array(ks).max(200),nextCursor:S.uuid().nullable()}),Ds=S.strictObject({features:S.array(ks).max(500),limited:S.boolean()}),jy=S.union([$i({action:S.literal("save"),internal_id:S.uuid().nullable(),revision:S.number().int().nonnegative()}),S.strictObject({action:S.enum(["archive","restore","delete"]),internal_id:S.uuid(),revision:S.number().int().nonnegative()})]);import{z as or}from"zod";var Ns=or.number().int().min(0).max(1e8),Tr=or.strictObject({kind:or.enum(["graduated","volume"]),tiers:or.array(or.strictObject({upTo:or.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Ns,flatAmountMinor:Ns.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,r)=>{let n=e.tiers[r-1]?.upTo;return t.upTo!==null&&(r===0||n!=null&&t.upTo>n)}),"Tier ceilings must increase and end unbounded").refine(e=>!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function Gi(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let r=e.pricing?Tr.parse(e.pricing):void 0;if(t===0)return 0;let n=0n,i=0;if(!r)n=BigInt(e.amountMinor)*BigInt(t);else for(let o of r.tiers){let a=o.upTo??1e4;if(r.kind==="volume"){if(t<=a){n=BigInt(t)*BigInt(o.unitAmountMinor)+BigInt(o.flatAmountMinor??0);break}}else t>i&&(n+=BigInt(Math.min(t,a)-i)*BigInt(o.unitAmountMinor));i=a}if(n>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(n)}function wn(e){return Gi({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}import{z as C}from"zod";import{z as u}from"zod";import{z as N}from"zod";import{z as Fe}from"zod";import{z as b}from"zod";var He=b.json().superRefine((e,t)=>{let r=0;function n(i,o){if(++r>1e4||o>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(a=>n(a,o+1));else if(i&&typeof i=="object")for(let[a,c]of Object.entries(i))(a.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(a)||["__proto__","prototype","constructor"].includes(a))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),n(c,o+1)}n(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),At=b.record(b.string().min(1).max(128),He).superRefine((e,t)=>{(!He.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(r=>Object.hasOwn(e,r)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),rf=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),ct=At.superRefine((e,t)=>{function r(n){if(Array.isArray(n))n.forEach(r);else if(n&&typeof n=="object")for(let[i,o]of Object.entries(n)){if(i==="$savedGroup"&&!b.strictObject({id:b.uuid(),attributeKey:b.string().min(1).max(128).optional()}).safeParse(o).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(a=>["__proto__","prototype","constructor"].includes(a))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!rf.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof o=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(o)||[...o.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(a=>Number(a[1])>255||Number(a[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(o.replace(/\\u([0-9a-f]{4})/gi,(a,c)=>String.fromCharCode(Number.parseInt(c,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(o)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}r(o)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),r(e)}),nf=b.discriminatedUnion("type",[b.strictObject({type:b.literal("condition"),condition:ct}),b.strictObject({type:b.literal("list"),attributeKey:b.string().min(1).max(128),values:b.array(b.union([b.string(),b.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Ki(e){let t=new Set;function r(n){if(Array.isArray(n))n.forEach(r);else if(n&&typeof n=="object")for(let[i,o]of Object.entries(n))i==="$savedGroup"&&o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.id=="string"?t.add(o.id):["$inGroup","$notInGroup"].includes(i)&&typeof o=="string"?t.add(o):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||r(o)}return r(e),[...t]}var af=b.record(b.uuid(),nf).superRefine((e,t)=>{let r=new Set,n=new Set;function i(o){if(r.has(o)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(n.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}r.add(o),a.type==="condition"&&Ki(a.condition).forEach(i),r.delete(o),n.add(o)}Object.keys(e).forEach(i)}),Zi=b.tuple([b.number().min(0).max(1),b.number().min(0).max(1)]).refine(([e,t])=>e<=t),Ms=b.strictObject({attribute:b.string().optional(),seed:b.string().min(1),hashVersion:b.literal(2),ranges:b.array(Zi).min(1).max(100)}),of=b.strictObject({id:b.string().min(1).max(128),condition:ct,gate:b.boolean().optional()}),Hi={id:b.string().max(128).optional(),condition:ct.optional(),parentConditions:b.array(of).max(50).optional(),filters:b.array(Ms).max(20).optional()},sf=b.union([b.strictObject({...Hi}),b.strictObject({...Hi,force:He,coverage:b.number().min(0).max(1).optional(),range:Zi.optional(),seed:b.string().min(1).optional(),hashAttribute:b.string().optional(),hashVersion:b.literal(2).optional()}),b.strictObject({...Hi,type:b.literal("experiment-ref"),experimentId:b.uuid(),values:b.record(b.string().min(1),He),meta:b.record(b.string().min(1),b.strictObject({passthrough:b.boolean()})).optional()})]),cf=b.strictObject({defaultValue:He,rules:b.array(sf).max(100)}),My=b.record(b.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),cf).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let r=new Set,n=new Set;function i(o){if(r.has(o)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${o}`});return}if(n.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${o}`});return}r.add(o);for(let c of a.rules)for(let l of c.parentConditions??[])i(l.id);r.delete(o),n.add(o)}Object.keys(e).forEach(i)}),uf=b.strictObject({name:b.string().max(80),reason:b.string().max(500),dateStarted:b.iso.datetime({offset:!0}),dateEnded:b.iso.datetime({offset:!0}).nullable(),coverage:b.number().min(0).max(1),variationWeights:b.array(b.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,r)=>t+r,0)-1)<=.01),condition:ct,savedGroups:b.array(b.strictObject({match:b.enum(["any","all","none"]),ids:b.array(b.uuid()).min(1)})).max(50),namespace:b.strictObject({id:b.uuid(),ranges:b.array(Zi).min(1)}).nullable(),seed:b.string().min(1).max(128)}),lf=b.strictObject({key:b.string().min(1).max(128),name:b.string().min(1).max(80),hypothesis:b.string().max(2e3),status:b.enum(["draft","running","stopped"]),hashAttribute:b.string().min(1).max(128),fallbackAttribute:b.string().max(128).nullable(),hashVersion:b.literal(2),disableStickyBucketing:b.boolean(),bucketVersion:b.number().int().min(0).max(1e3),minBucketVersion:b.number().int().min(0).max(1e3),variations:b.array(b.strictObject({id:b.string().min(1),key:b.string().min(1),name:b.string().max(80),description:b.string().max(500)})).min(2).max(20),phases:b.array(uf).min(1).max(100),releasedVariationId:b.string().nullable(),excludeFromPayload:b.boolean(),statusSchedule:b.strictObject({startAt:b.iso.datetime({offset:!0}).nullable(),stopAt:b.iso.datetime({offset:!0}).nullable(),stopAfter:b.strictObject({value:b.number().int().positive().max(36500),unit:b.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((r,n)=>{if(n===0)return!1;let i=e.phases[n-1];return!i?.dateEnded||Date.parse(r.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(r.dateStarted)})||new Set(e.variations.map(r=>r.key)).size!==e.variations.length||new Set(e.variations.map(r=>r.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(r=>r.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(r=>r.dateEnded&&Date.parse(r.dateStarted)>=Date.parse(r.dateEnded)||r.namespace?.ranges.some(([n,i],o,a)=>n>=i||a.some(([c,l],p)=>p!==o&&n<l&&c<i)))||e.phases.some(r=>r.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var df=lf.safeExtend({filters:b.array(Ms).optional()}),mf=b.strictObject({experiments:b.record(b.uuid(),df),savedGroups:af}),pf=b.strictObject({attributeName:b.string(),attributeValue:b.string(),assignments:b.record(b.string(),b.string())}),Uy=b.strictObject({snapshot:mf,attributes:At,results:At,stickyBucketAssignmentDocs:b.record(b.string(),pf)}),qy=b.strictObject({variantKey:b.string().nullable(),bucketVersion:b.number().int().min(0),source:b.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:b.number().min(0).max(1).optional(),stickyBucketUsed:b.boolean().optional(),hashUsed:b.boolean().optional()});function Us(e){let t=new Set,r=o=>o!==null&&typeof o=="object"&&!Array.isArray(o);function n(o,a){if(r(o))for(let[c,l]of Object.entries(o))c==="$elemMatch"?i(l,a):c==="$not"?n(l,a):c==="$all"&&Array.isArray(l)&&l.forEach(p=>n(p,a))}function i(o,a=""){if(r(o)){for(let[c,l]of Object.entries(o))if(["$and","$or","$nor"].includes(c)&&Array.isArray(l))l.forEach(p=>i(p,a));else if(c==="$not")i(l,a);else if(c==="$savedGroup"&&r(l))typeof l.attributeKey=="string"&&t.add(l.attributeKey);else if(!c.startsWith("$")){let p=a?`${a}.${c}`:c;t.add(p),n(l,p)}}}return i(e),[...t]}var ff=Fe.enum(["active","inactive"]),hf=Fe.preprocess((e,t)=>{let r=0;function n(i,o){if(!(++r>1e4||o>20)){if(Array.isArray(i))i.forEach(a=>n(a,o+1));else if(i&&typeof i=="object")for(let[a,c]of Object.entries(i))["__proto__","constructor","prototype"].includes(a)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),n(c,o+1)}}return n(e,0),e},At),Af=Fe.strictObject({id:Fe.string().trim().min(1).max(255),name:Fe.string().trim().min(1).max(255),status:ff,metadata:hf}),Gy=Af.extend({internal_id:Fe.uuid(),project_id:Fe.uuid(),environment_id:Fe.uuid(),created_at:Fe.iso.datetime({offset:!0}),updated_at:Fe.iso.datetime({offset:!0})}),Ls=Fe.union([Fe.strictObject({id:Fe.string().trim().min(1).max(255)}),Fe.strictObject({internalId:Fe.uuid()})]),Hy=Fe.enum(["customer","merchandise","context"]),Ky=Fe.enum(["system","stored","request"]),Zy=Fe.enum(["customer","merchandise","mixed"]),qs=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Wi(e,t={},r=new Set){if(Us(e).some(qs))return!0;for(let n of Ki(e)){if(r.has(n))continue;r.add(n);let i=t[n];if(i?.type==="list"&&qs(i.attributeKey)||i?.type==="condition"&&Wi(i.condition,t,r))return!0}return!1}import{z as gf}from"zod";var bf=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,ut=gf.string().max(16).regex(bf,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");var tS=N.enum(["draft","active","paused","archived"]),Ot=N.discriminatedUnion("type",[N.object({type:N.literal("percent"),percentOff:N.number().int().min(1).max(100)}).strict(),N.object({type:N.literal("amount"),amountOffCents:N.number().int().min(1).max(1e8),currency:Y}).strict()]),et=N.discriminatedUnion("type",[N.object({type:N.literal("once")}).strict(),N.object({type:N.literal("repeating"),months:N.number().int().min(1).max(36)}).strict(),N.object({type:N.literal("forever")}).strict()]),Bs=[N.object({type:N.literal("all")}).strict(),N.object({type:N.literal("plans"),planIds:N.array(N.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],yf=N.discriminatedUnion("type",[...Bs,N.strictObject({type:N.literal("merchandise"),scope:N.discriminatedUnion("type",[N.strictObject({type:N.literal("all")}),N.strictObject({type:N.literal("selected"),merchandiseIds:N.array(N.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),N.strictObject({type:N.literal("condition"),condition:ct})])})]),Qi=N.discriminatedUnion("type",[...Bs,N.strictObject({type:N.literal("merchandise"),scope:N.strictObject({type:N.enum(["all","selected","condition"])})})]),Sf=N.strictObject({firstPurchaseOnly:N.boolean(),condition:ct}),rS=N.object({name:N.string().trim().min(1).max(80),description:N.string().max(500),discount:Ot,duration:et,appliesTo:yf,eligibility:Sf,selfClaimEnabled:N.boolean().default(!1),startsAt:N.iso.datetime().nullable(),endsAt:N.iso.datetime().nullable(),totalLimit:N.number().int().min(1).max(1e6).nullable(),perCustomerLimit:N.number().int().min(1).max(10),grantWindowHours:N.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!Wi(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),nS=N.object({code:N.string().trim().transform(e=>e.toUpperCase()).pipe(N.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:N.number().int().min(1).max(1e6).nullable(),expiresAt:N.iso.datetime().nullable(),firstPurchaseOnly:N.boolean(),minimumAmountCents:N.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:Y.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Yi=N.object({id:N.uuid(),couponId:N.uuid(),status:N.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:N.iso.datetime(),expiresAt:N.iso.datetime(),coupon:N.object({name:N.string(),discount:Ot,duration:et,appliesTo:Qi}).strict()}).strict(),Fs=N.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);import{z as Ce}from"zod";var Xe=Ce.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),W=Ce.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),On=Ce.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),Ji=W.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Vs=Ce.string().min(1).max(64),Lt=Ce.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),$s=Ce.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),Re=Ce.record(Vs,Ce.union([Ce.string().max(120),Ce.number().finite(),Ce.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,String(r)]))),Gs=Ce.record(Vs,Ce.union([Ce.string().max(120),Ce.number().finite(),Ce.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),sr=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[r,n=""]=e.split(".");if(r===void 0||r==="")throw new Error("Invalid decimal value");let i=BigInt(r)*BigInt("1000000")+BigInt(n.padEnd(6,"0"));return t?-i:i},Hs=Ce.array(Ce.object({upTo:Ji.nullable(),cost:W}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,r)=>{let n=e[r-1]?.upTo;return t.upTo!==null&&(r===0||n!=null&&sr(t.upTo)>sr(n))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),_f=Ce.object({key:$s,match:Gs,priority:Ce.number().int().default(0),cost:W.optional(),tiers:Hs.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),xf=Ce.object({key:$s,match:Gs,factor:Ji.optional(),add:On.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),If=Ce.object({units:Ji.default("1"),cost:W,tiers:Hs.optional(),dimensions:Ce.array(_f).max(12).optional(),multipliers:Ce.array(xf).max(4).optional()}).strict().superRefine((e,t)=>{let r=e.dimensions??[],n=e.multipliers??[];(new Set(r.map(a=>a.key)).size!==r.length||new Set(n.map(a=>a.key)).size!==n.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[a,c]of r.entries())for(let l of r.slice(a+1))Object.keys(c.match).length===Object.keys(l.match).length&&c.priority===l.priority&&!Object.keys(c.match).some(p=>l.match[p]!==void 0&&l.match[p]!==c.match[p])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let i=[e.cost,...(e.tiers??[]).map(a=>a.cost),...r.flatMap(a=>[...a.cost===void 0?[]:[a.cost],...(a.tiers??[]).map(c=>c.cost)])],o=sr(e.units);for(let a of i)for(let c=0;c<1<<n.length;c++){let l=n.filter((ie,q)=>c&1<<q);if(l.some((ie,q)=>l.slice(q+1).some(ve=>Object.keys(ie.match).some(Ne=>ve.match[Ne]!==void 0&&ve.match[Ne]!==ie.match[Ne]))))continue;let p=sr(a),A=BigInt("1"),v=BigInt("0");for(let[ie,q]of n.entries())c&1<<ie&&(p*=sr(q.factor??"1"),A*=BigInt("1000000"),v+=sr(q.add??"0"));let k=(p+v*A)*BigInt("1000000"),U=A*o;(k<BigInt("0")||k%U!==BigInt("0")||k/U>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),oS=If.safeExtend({featureKey:Lt});var Ys=u.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Xi=u.string().regex(/^(0|[1-9]\d{0,14})$/),cr=u.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),vf=u.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),jr=vf,xt=W.refine(e=>/[1-9]/.test(e)),Ke=u.iso.datetime({offset:!0}),Bt=e=>{let[t,r=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(r.padEnd(6,"0"))},Pf=u.array(u.object({upTo:xt.nullable(),unitAmountMinor:Ys,flatAmountMinor:u.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,r)=>{let n=e[r-1]?.upTo;return t.upTo!==null&&(r===0||n!=null&&Bt(t.upTo)>Bt(n))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Cf=u.discriminatedUnion("kind",[u.object({kind:u.literal("flat"),units:xt,unitAmountMinor:Ys}).strict(),u.object({kind:u.enum(["graduated","volume"]),units:xt,tiers:Pf}).strict()]).refine(e=>e.kind==="flat"||!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),wf=u.strictObject({interval:u.enum(["month","year"]),count:u.number().int().min(1).max(12),anchor:u.enum(["membership","calendar"])}),Et=u.object({currency:Y,pricing:Cf,billingCycle:wf.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");function Js(e){return e.pricing.kind==="flat"&&Bt(e.pricing.units)>0n&&Bt(e.pricing.unitAmountMinor)===Bt(e.pricing.units)*BigInt(10**To(e.currency))}var Ks={requestId:u.uuid(),productVersionId:u.uuid(),internal_feature_id:u.uuid(),currency:Y},Xs=u.strictObject({interval:u.enum(["hour","day","week","month"]),intervalCount:u.number().int().min(1).max(12),limit:u.number().int().min(1).max(1e6)}),zs=u.discriminatedUnion("kind",[u.object({...Ks,kind:u.literal("auto_topup"),threshold:On,quantity:xt.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Xs.optional()}).strict(),u.object({...Ks,kind:u.literal("postpaid"),maxAmountMinorPerPeriod:jr,maxOutstandingMinor:jr}).strict()]),Zs={productVersionId:u.uuid(),internal_feature_id:u.uuid(),currency:Y},ec=u.discriminatedUnion("kind",[u.object({...Zs,kind:u.literal("auto_topup"),threshold:On,quantity:xt.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Xs.optional(),purchaseAmountMinor:jr,purchaseUnits:xt}).strict(),u.object({...Zs,kind:u.literal("postpaid"),maxAmountMinorPerPeriod:jr,maxOutstandingMinor:jr,cashPrice:Et}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),En=u.object({id:u.uuid(),terms:ec,status:u.enum(["prepared","active","revoked","blocked"]),createdAt:Ke,acceptedAt:Ke.nullable(),effectiveAt:Ke.nullable(),revokedAt:Ke.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),tc=u.object({authorizationId:u.uuid(),terms:ec,setupUrl:u.url().nullable()}).strict(),rc=u.object({authorizationId:u.uuid(),accepted:u.literal(!0)}).strict(),nc=u.object({authorizationId:u.uuid(),requestId:u.uuid()}).strict(),ic=u.object({internal_feature_id:u.uuid(),entityId:u.uuid().nullable(),interval:u.enum(["day","week","month","year"]),anchor:u.enum(["billing_cycle","utc"]).optional(),basis:u.enum(["usage","credits"]),filter:Re.optional(),limit:W.nullable(),thresholds:u.array(u.number().positive().max(1)).max(8),includedThresholds:u.array(u.number().positive().max(1)).max(8).optional(),absoluteThresholds:u.array(xt).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,r)=>{let n=e.thresholds[r-1];return r===0||n!==void 0&&t>n})&&(e.includedThresholds??[]).every((t,r,n)=>{let i=n[r-1];return r===0||i!==void 0&&t>i})&&(e.absoluteThresholds??[]).every((t,r,n)=>{let i=n[r-1];return r===0||i!==void 0&&Bt(t)>Bt(i)}),"Notification thresholds must increase"),Of=ic.safeExtend({requestId:u.uuid()}),Ws={control:u.literal("overage"),requestId:u.uuid(),internal_feature_id:u.uuid(),entityId:u.uuid().nullable()},Ef=u.discriminatedUnion("action",[u.strictObject({...Ws,action:u.literal("set"),allowed:u.boolean().nullable(),overageLimit:W.nullable(),skipOverageBilling:u.boolean()}),u.strictObject({...Ws,action:u.literal("remove")})]),ac=u.union([Of,Ef]),Tf=u.strictObject({internal_feature_id:u.uuid(),entityId:u.uuid().nullable(),allowed:u.boolean().nullable(),overageLimit:W.nullable(),skipOverageBilling:u.boolean(),interval:u.enum(["day","week","month","year"]),startsAt:Ke,endsAt:Ke,used:u.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:u.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:u.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),jf=u.object({internal_feature_id:u.uuid(),entityId:u.uuid().nullable(),interval:u.enum(["day","week","month","year"]),anchor:u.enum(["billing_cycle","utc"]).optional(),basis:u.enum(["usage","credits"]),filter:Re.optional(),startsAt:Ke,endsAt:Ke,used:Xe,reserved:Xe,limit:W.nullable(),thresholds:u.array(u.number().positive().max(1)).max(8),notifiedThresholds:u.array(u.number().positive().max(1)).max(1024),includedThresholds:u.array(u.number().positive().max(1)).max(8).optional(),includedAllowance:u.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:u.array(u.number().positive().max(1)).max(1024).optional(),absoluteThresholds:u.array(xt).max(8).optional(),notifiedAbsoluteThresholds:u.array(xt).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||W.safeParse(e.used).success&&W.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Rf=u.object({authorizationId:u.uuid(),status:u.enum(["idle","pending","blocked"]),taskId:u.uuid().nullable(),invoiceId:u.uuid().nullable(),hostedInvoiceUrl:u.url().nullable(),purchaseCount:u.number().int().nonnegative(),purchaseWindowEndsAt:Ke.nullable(),attemptCount:u.number().int().nonnegative(),failedAttemptCount:u.number().int().nonnegative(),suspendedAt:Ke.nullable(),nextAttemptAt:Ke.nullable(),failureReason:u.string().min(1).max(240).nullable()}).strict(),oc=u.object({internal_feature_id:u.uuid().optional(),entityId:u.uuid().optional()}).strict(),zi=u.object({authorizations:u.array(En).max(100),limits:u.array(ic).max(100),overages:u.array(Tf).max(100).optional(),windows:u.array(jf).max(200),autoTopups:u.array(Rf).max(100),limited:u.boolean()}).strict(),kf=u.object({id:u.uuid(),internal_feature_id:u.uuid(),productVersionId:u.uuid(),authorizationId:u.uuid(),entityId:u.uuid().nullable(),units:W,amountMinor:cr,cashPrice:Et}).strict(),Rr=u.object({id:u.uuid(),sourceKind:u.enum(["product","usage","manual"]),providerInvoiceId:u.string().min(1).max(240).nullable(),status:u.enum(["accruing","open","pending","paid","failed","void"]),currency:Y,startsAt:Ke.nullable(),endsAt:Ke.nullable(),amountMinor:u.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:u.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Xi,paidAmountMinor:Xi,refundedAmountMinor:Xi,createdAt:Ke,hostedInvoiceUrl:u.url().nullable(),adjustment:u.object({originalInvoiceId:u.uuid(),amountMinor:u.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:Ke.nullable()}).strict().nullable(),lines:u.array(kf).max(100),linesLimited:u.boolean()}).strict(),sc=u.object({invoiceId:u.uuid(),accepted:u.literal(!0)}).strict(),cc=u.object({after:u.uuid().nullable(),limit:u.number().int().min(1).max(100)}).strict(),uc=u.object({rows:u.array(Rr).max(100),nextCursor:u.uuid().nullable()}).strict(),Qs=u.strictObject({id:u.string(),coupon:u.string(),start:u.number().nonnegative(),end:u.number().nullable()}),Df=u.strictObject({subscriptionId:u.string(),customerId:u.string(),accountId:u.string(),sourceItems:u.array(u.strictObject({id:u.string(),price_id:u.string(),quantity:u.number().int(),discounts:u.array(Qs).optional()})).max(100),items:u.array(u.strictObject({id:u.string(),price:u.string(),quantity:u.number().int(),discounts:u.array(u.strictObject({coupon:u.string().optional(),terms:u.strictObject({id:u.string(),name:u.string().optional(),percent_off:u.number().optional(),amount_off:u.number().optional(),currency:u.string().optional(),duration:u.enum(["once","forever","repeating"]),duration_in_months:u.number().optional()}).optional(),discount:u.string().optional(),receipt:Qs.optional()})).max(20)})).max(100)}),lc=u.strictObject({membershipId:u.uuid(),requestId:u.uuid(),grantIds:u.array(u.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),dc=u.strictObject({membershipId:u.uuid(),operationId:u.uuid(),status:u.enum(["pending","effective"]),execution:Df.nullable(),grants:u.array(u.strictObject({id:u.uuid(),couponId:u.uuid(),name:u.string(),discount:Ot,duration:et,startedAt:Ke.nullable()})).max(20)});import{z as kr}from"zod";var Dr=kr.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Nr=kr.number().int().min(1).max(1e3),Ft=kr.object({cap:W.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:kr.number().positive().max(1e4).nullable(),cycles:kr.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var ea={key:qt,name:C.string().trim().min(1).max(80),description:C.string().trim().max(240)},mc=W.refine(e=>/[1-9]/.test(e)),Tn=C.array(C.object({currency:Y,amountMinor:C.number().int().min(0).max(1e8)}).strict()).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique"),ta=C.strictObject({units:mc,prices:C.array(C.strictObject({currency:Y,amountMinor:C.number().int().min(0).max(1e8),pricing:Tr.optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique").refine(e=>e.every(t=>!t.pricing||t.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:C.number().int().min(0).max(1e4),maximumQuantity:C.number().int().min(1).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let r of[e.maximumQuantity,...t.pricing?.tiers.flatMap(n=>n.upTo===null?[]:[n.upTo,n.upTo+1])??[]])r<=e.maximumQuantity&&Gi({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},r);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit"),Nf=C.discriminatedUnion("kind",[C.object({kind:C.literal("access"),internal_feature_id:C.uuid()}).strict(),C.object({kind:C.literal("metered"),internal_feature_id:C.uuid(),usageUnit:C.enum(["count","micro_usd"]),amount:W.nullable(),reset:Dr,resetCount:Nr,pooled:C.boolean(),rollover:Ft.nullable().optional(),cashPrice:Et.nullable().optional(),prepaidPrice:ta.optional(),feature_override:Fi.nullish()}).strict().refine(e=>!e.cashPrice||e.amount!==null,"Cash pricing requires a finite prepaid allowance").refine(e=>!e.rollover||e.amount!==null&&e.reset!=="lifetime","Rollover requires a finite recurring consumable allowance").refine(e=>!e.prepaidPrice||e.amount!==null,"Purchased quantities require a finite included allowance").refine(e=>{if(!e.prepaidPrice||e.amount===null)return!0;try{return na(e.amount,e.prepaidPrice.units,e.prepaidPrice.maximumQuantity),!0}catch{return!1}},"The maximum purchased allowance must fit the quantity ledger"),C.object({kind:C.literal("credit"),internal_feature_id:C.uuid(),amount:W,reset:Dr,resetCount:Nr,rollover:Ft.nullable(),pooled:C.boolean(),feature_override:Fi.nullish(),cashPrice:Et.nullable().optional()}).strict().refine(e=>!e.cashPrice||e.reset!=="lifetime"&&!e.rollover&&!e.pooled&&Js(e.cashPrice),"Itemized invoice credits require a recurring, unpooled allowance without rollover priced at one currency unit per credit").refine(e=>!e.rollover||e.reset!=="lifetime","Rollover requires a recurring allowance")]),ra=C.array(Nf).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"An entitlement can be granted once per product"),pc=C.object({days:C.number().int().min(1).max(730),cardRequired:C.boolean(),allowances:ra}).strict().refine(e=>e.allowances.every(t=>t.kind==="access"||!t.cashPrice&&(t.kind!=="metered"||!t.prepaidPrice)),"Trial allowances do not charge cash overages or purchased quantities"),fc=C.object({key:qt,internal_feature_id:C.uuid(),productVersionId:C.uuid(),includedQuantity:C.number().int().min(0).max(1e4),maximumQuantity:C.number().int().min(0).max(1e4),prices:Tn,pooled_internal_feature_ids:C.array(C.uuid()).max(100),requireAssignment:C.boolean()}).strict().refine(e=>e.maximumQuantity>=e.includedQuantity,"Capacity cannot be less than included seats").refine(e=>new Set(e.pooled_internal_feature_ids).size===e.pooled_internal_feature_ids.length,"Shared entitlements must be unique"),hc=C.discriminatedUnion("kind",[C.object({...ea,kind:C.literal("membership"),groupId:C.uuid(),membershipType:C.enum(["main","addon"]),interval:C.enum(["free","week","month","year","one_time"]),intervalCount:C.number().int().min(1).max(156).optional(),prices:Tn,allowances:ra,trial:pc.nullable(),licenses:C.array(fc).max(20).refine(e=>new Set(e.map(t=>t.key)).size===e.length,"License keys must be unique")}).strict().refine(e=>e.interval==="free"?e.prices.every(t=>t.amountMinor===0):e.prices.every(t=>e.interval==="one_time"?t.amountMinor>0||e.allowances.some(r=>r.kind==="metered"&&r.prepaidPrice?.prices.some(n=>n.currency===t.currency&&n.amountMinor>0)):t.amountMinor>=0),"Prices must match the billing interval").refine(e=>e.interval!=="one_time"||e.trial===null,"Lifetime plans cannot have a subscription trial").refine(e=>e.intervalCount===void 0||(e.interval==="week"||e.interval==="month"||e.interval==="year")&&e.intervalCount<=(e.interval==="year"?3:e.interval==="month"?36:156),"Recurring billing intervals cannot exceed three years").refine(e=>e.allowances.every(t=>t.kind!=="metered"||!t.prepaidPrice||e.interval!=="free"&&t.prepaidPrice.prices.length===e.prices.length&&t.prepaidPrice.prices.every(r=>e.prices.some(n=>n.currency===r.currency))),"Purchased features require a paid plan and all its published currencies"),C.object({...ea,kind:C.literal("topup"),interval:C.literal("one_time"),prices:Tn,internal_feature_id:C.uuid(),amount:mc,expiresDays:C.number().int().min(1).max(3660).nullable()}).strict().refine(e=>e.prices.every(t=>t.amountMinor>0),"A topup must have a positive price")]),Mf=C.object({interval:C.enum(["free","week","month","year","one_time"]).optional(),intervalCount:C.number().int().min(1).max(156).nullable().optional(),prices:Tn.optional(),allowances:C.object({upsert:ra,remove:C.array(C.uuid()).max(100)}).strict().refine(e=>new Set(e.remove).size===e.remove.length&&e.upsert.every(t=>!e.remove.includes(t.internal_feature_id)),"An allowance cannot be removed and replaced together").optional(),trial:pc.nullable().optional(),licenses:C.array(fc).max(20).optional()}).strict(),Uf=C.object({...ea,kind:C.literal("variant"),baseProductVersionId:C.uuid(),overrides:Mf}).strict(),PS=C.union([hc,Uf]),CS=C.object({products:C.array(C.object({id:C.uuid(),productId:C.string().min(1),name:C.string(),kind:C.enum(["membership","topup"]),version:C.number().int().positive()}).strict()).max(500),limited:C.boolean()}).strict(),qf=xs.and(C.object({internal_id:C.uuid(),revision:C.number().int().nonnegative(),licenses:C.array(qi)})),wS=C.strictObject({rows:C.array(qf).max(200),nextCursor:C.uuid().nullable()}),OS=C.object({groups:C.array(C.object({id:C.uuid(),name:C.string(),defaultProductVersionId:C.uuid().nullable()}).strict()).max(500),features:Ds.shape.features,products:C.array(C.object({id:C.uuid(),productId:C.uuid(),version:C.number().int().positive(),configuration:hc,baseProductVersionId:C.uuid().nullable()}).strict()).max(500),limited:C.boolean()}).strict();function na(e,t,r){let n=a=>{if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(a))throw new Error("Invalid quantity");let[c,l=""]=a.split(".");if(c===void 0||c==="")throw new Error("Invalid decimal value");return BigInt(c)*1000000n+BigInt(l.padEnd(6,"0"))};if(!Number.isSafeInteger(r)||r<0||r>1e4)throw new Error("Invalid purchased quantity");let i=n(e)+n(t)*BigInt(r);if(i>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let o=(i%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(i/1000000n).toString()+(o?"."+o:"")}import{z as Tt}from"zod";var Ac=Tt.strictObject({itemKey:Tt.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:Tt.uuid(),includedAmount:Tt.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Tt.number().int().min(0).max(1e4),terms:ta,pricing:Tr.optional(),unitAmountMinor:Tt.number().int().min(0).max(1e8),productId:Tt.string().min(1).max(255).nullable(),priceId:Tt.string().min(1).max(255).nullable()}).superRefine((e,t)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&t.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{na(e.includedAmount,e.terms.units,e.quantity),wn({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as M}from"zod";var Vt=W.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Mr=M.string().min(1).max(120),jn=M.enum(["cap","overflow"]),tt=(e,t)=>{let[r,n=""]=e.split(".");if(r===void 0||r==="")throw new Error("Invalid decimal value");return BigInt(r)*10n**BigInt(t)+BigInt(n.padEnd(t,"0"))},Ur=e=>{try{return e()}catch{return!1}},qr=M.discriminatedUnion("operation",[M.object({operation:M.literal("quote"),overageBehavior:jn.optional(),internal_feature_id:M.uuid(),entityId:M.uuid().optional(),quantity:Vt,properties:Re}).strict(),M.object({operation:M.literal("consume"),overageBehavior:jn.optional(),occurredAt:M.iso.datetime({offset:!0}).optional(),internal_feature_id:M.uuid(),entityId:M.uuid().optional(),quantity:W,properties:Re,idempotencyKey:Mr}).strict(),M.object({operation:M.literal("reserve"),occurredAt:M.iso.datetime({offset:!0}).optional(),internal_feature_id:M.uuid(),entityId:M.uuid().optional(),quantity:Vt,properties:Re,idempotencyKey:Mr,expiresInSeconds:M.number().int().min(1).max(86400)}).strict(),M.object({operation:M.literal("confirm"),operationId:M.uuid(),quantity:Vt,properties:Re.optional(),idempotencyKey:Mr}).strict(),M.object({operation:M.literal("refund"),operationId:M.uuid(),quantity:Vt,idempotencyKey:Mr}).strict(),M.object({operation:M.literal("release"),operationId:M.uuid(),idempotencyKey:Mr}).strict()]),ia=M.object({internal_credit_feature_id:M.uuid().nullable(),internal_metered_feature_id:M.uuid(),dimension:M.string().min(1).max(64),counterKey:M.string().min(1).max(240),cycleStart:M.iso.datetime({offset:!0}),unitCost:W,units:Vt,amount:Xe,tier:M.number().int().min(1).max(12).nullable()}).strict(),$t=M.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function gc(e,t){let r=e.reduce((n,i)=>n+tt(i.units,12),0n)-tt(t,12);return e.some(n=>n.funding==="balance")?r>=-100n&&r<=100n:r===0n}var bc=M.discriminatedUnion("funding",[M.strictObject({funding:M.literal("balance"),sourceId:M.uuid(),rolloverId:M.uuid().nullable(),units:$t.refine(e=>/[1-9]/.test(e)),amount:Xe}),M.strictObject({funding:M.literal("unbilled"),units:$t.refine(e=>/[1-9]/.test(e))}),M.object({funding:M.literal("prepaid"),sourceId:M.uuid(),units:Vt,amount:Xe,pricing:M.array(ia).min(1).max(12)}).strict().refine(e=>Ur(()=>e.pricing.reduce((t,r)=>t+tt(r.units,6),0n)===tt(e.units,6)&&e.pricing.reduce((t,r)=>t+tt(r.amount,12),0n)===tt(e.amount,12)&&e.pricing.every(t=>tt(t.unitCost,6)*tt(t.units,6)===tt(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),M.object({funding:M.literal("postpaid"),invoiceLineId:M.uuid().nullable(),units:Vt,authorizationId:M.uuid()}).strict()]),Rn=M.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),yc=M.object({allowed:M.boolean(),internal_feature_id:M.uuid(),quantity:W,requestedQuantity:W.optional(),overageBehavior:jn.optional(),reason:Rn.nullable(),allocations:M.array(bc).max(500)}).strict().refine(e=>Ur(()=>e.allowed?e.reason===null&&gc(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Ur(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&tt(e.requestedQuantity,6)>=tt(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Lr=M.object({id:M.uuid(),internal_feature_id:M.uuid(),kind:M.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:M.uuid().nullable(),quantity:W,requestedQuantity:W.optional(),overageBehavior:jn.optional(),accepted:M.boolean(),reason:M.enum([...Rn.options,"expired"]).nullable(),createdAt:M.iso.datetime({offset:!0}),reservationStatus:M.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:M.iso.datetime({offset:!0}).nullable(),allocations:M.array(bc).max(500)}).strict().refine(e=>Ur(()=>e.accepted?e.reason===null&&gc(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Ur(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&tt(e.requestedQuantity,6)>=tt(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as oe}from"zod";var Gt=oe.iso.datetime({offset:!0}),Sc=W.refine(e=>/[1-9]/.test(e)),_c=oe.strictObject({interval:Dr.exclude(["lifetime"]),count:Nr}),Lf=oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),internal_feature_id:oe.uuid(),entityId:oe.uuid().nullable(),amount:Sc.nullable(),expiresAt:Gt.nullable(),reset:_c.nullable(),rollover:Ft.nullable(),nextResetAt:Gt.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),xc=oe.discriminatedUnion("action",[Lf,oe.strictObject({action:oe.literal("update"),requestId:oe.uuid(),grantId:oe.uuid(),revision:oe.number().int().nonnegative(),amount:Sc.nullable(),expiresAt:Gt.nullable(),rollover:Ft.nullable(),nextResetAt:Gt.nullable()}),oe.strictObject({action:oe.enum(["add","subtract","set_remaining"]),requestId:oe.uuid(),grantId:oe.uuid(),revision:oe.number().int().nonnegative(),amount:W}),oe.strictObject({action:oe.literal("revoke"),requestId:oe.uuid(),grantId:oe.uuid(),revision:oe.number().int().nonnegative()})]),aa=oe.strictObject({id:oe.uuid(),internal_feature_id:oe.uuid(),entityId:oe.uuid().nullable(),amount:W.nullable(),reset:_c.nullable(),rollover:Ft.nullable(),nextResetAt:Gt.nullable(),startsAt:Gt,expiresAt:Gt.nullable(),revision:oe.number().int().nonnegative(),revoked:oe.boolean(),available:Xe,held:Xe,spent:Xe}),Ic=oe.strictObject({customerId:oe.uuid(),after:oe.uuid().nullable(),limit:oe.number().int().min(1).max(100)}),vc=oe.strictObject({rows:oe.array(aa).max(100),nextCursor:oe.uuid().nullable()});import{z as L}from"zod";var gt=L.iso.datetime({offset:!0}),Pc=L.strictObject({invoiceId:L.uuid(),after:L.string().min(1).max(180).nullable(),limit:L.number().int().min(1).max(100)}),Bf=L.strictObject({kind:L.literal("product"),key:L.string(),productVersionId:L.uuid(),productName:L.string(),itemKey:L.string(),entityId:L.uuid().nullable(),quantity:L.number().int().positive(),subtotalMinor:L.string().regex(/^-?\d+$/),discountMinor:L.string().regex(/^\d+$/),taxMinor:L.string().regex(/^-?\d+$/).nullable(),totalMinor:L.string().regex(/^-?\d+$/),startsAt:gt.nullable(),endsAt:gt.nullable(),providerLineId:L.string().nullable(),providerItemId:L.string()}),Cc=L.strictObject({invoice:Rr,items:L.array(L.discriminatedUnion("kind",[Bf,L.strictObject({kind:L.literal("invoice_credit"),key:L.string(),internal_feature_id:L.uuid(),internal_credit_feature_id:L.uuid(),name:L.string(),units:W,reserved:W,amountMinor:cr,grossAmountMinor:cr,creditsAppliedMinor:cr,properties:Re,cashPrice:Et,providerItemId:L.string().nullable(),creditProviderItemId:L.string().nullable()}),L.strictObject({kind:L.literal("usage"),key:L.string(),internal_feature_id:L.uuid(),name:L.string(),units:W,reserved:W,amountMinor:cr,cashPrice:Et})])).max(100),nextCursor:L.string().min(1).max(180).nullable()}),Ff=L.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),oa=L.strictObject({from:gt,to:gt,entityId:L.uuid().optional(),snapshotAt:gt.nullable(),after:L.strictObject({at:gt,id:L.uuid(),position:L.number().int().nonnegative()}).nullable(),limit:L.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),wc=L.strictObject({customerId:L.uuid(),entityId:L.uuid().nullable(),from:gt,to:gt,snapshotAt:gt,totals:L.array(L.strictObject({internal_credit_feature_id:L.uuid(),name:L.string(),consumed:Xe,refunded:Xe,net:Ff})).max(1e3),rows:L.array(L.strictObject({operationId:L.uuid(),position:L.number().int().nonnegative(),kind:L.enum(["consume","confirm","refund"]),originalId:L.uuid().nullable(),occurredAt:gt,internal_feature_id:L.uuid(),entitlementName:L.string(),sourceId:L.uuid(),internal_credit_feature_id:L.uuid(),creditName:L.string(),units:$t,amount:Xe,pricing:L.array(ia).max(12),properties:Re})).max(100),nextCursor:oa.shape.after});import{z as y}from"zod";import{z as lt}from"zod";var Vf=lt.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),$f=lt.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),kn=lt.strictObject({internal_feature_id:lt.uuid(),entityId:lt.uuid().nullable()}),Oc=kn.extend({quantity:W,expectedRevision:lt.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:lt.string().min(1).max(120),properties:Re.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Br=kn.extend({operationId:lt.uuid().nullable(),usage:W,capacity:Vf.nullable(),remaining:$f.nullable(),withinLimit:lt.boolean(),revision:lt.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:lt.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let r=n=>{let i=n.startsWith("-"),[o,a=""]=(i?n.slice(1):n).split(".");if(o===void 0||o==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(o)*10n**12n+BigInt(a.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||r(e.remaining)!==r(e.capacity)-r(e.usage)||e.withinLimit!==r(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var Ze=y.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),dt=y.iso.datetime({offset:!0}),Gf=y.enum(["access","metered","credit"]),Fr={internal_feature_id:y.uuid(),key:Lt,name:y.string().min(1).max(120),kind:Gf},Ec=y.object({customerId:y.uuid(),snapshotAt:dt,memberships:y.array(y.object({id:y.uuid(),productId:y.string().min(1).max(255),productVersionId:y.uuid(),billingProductVersionId:y.uuid(),version:y.number().int().positive(),key:y.string().min(1).max(64),name:y.string().min(1).max(120),groupId:y.string().max(255).nullable(),membershipType:y.enum(["main","addon"]),status:y.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:y.boolean(),accessEnabled:y.boolean(),renewalChange:y.object({productVersionId:y.uuid(),name:y.string().min(1).max(120),version:y.number().int().positive(),effectiveAt:dt,benefitsAppliedAt:dt.nullable(),timing:y.enum(["immediate","renewal"]),changeKind:y.enum(["plan","seats","quantity"]),feature:y.strictObject({internal_feature_id:y.uuid(),name:y.string().min(1).max(80),fromQuantity:y.number().int().min(0).max(1e4),toQuantity:y.number().int().min(0).max(1e4)}).optional(),seat:y.object({key:y.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:y.number().int().min(0).max(1e4),toQuantity:y.number().int().min(0).max(1e4)}).strict().nullable(),status:y.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:y.object({phase:y.enum(["paid","trial"]),startsAt:dt,endsAt:dt.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:y.boolean(),balances:y.array(y.object({...Fr,usageType:y.enum(["consumable","non_consumable"]).nullable(),accessible:y.boolean(),unlimited:y.boolean(),available:Ze,held:Ze,debt:Ze,nextExpiresAt:dt.nullable(),usage:Br.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:y.boolean()}).strict(),Tc=y.enum(["source","usage","transaction","invoice","debt","settlement"]),jc=y.object({at:dt,id:y.uuid(),type:Tc}).strict(),Rc=y.object({type:Tc.nullable(),resourceKey:Lt.optional(),kind:y.enum(["purchase","refund"]).optional(),topup:y.boolean().optional(),from:y.iso.date().nullable(),to:y.iso.date().nullable(),after:jc.nullable(),limit:y.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),ur={id:y.uuid(),occurredAt:dt},Hf=y.discriminatedUnion("type",[y.strictObject({...ur,type:y.literal("invoice"),status:y.string().min(1).max(80),paid:Ze,refunded:Ze,currency:Y,externalId:y.string().nullable()}),y.object({...ur,...Fr,type:y.literal("source"),reason:y.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Ze,unlimited:y.boolean(),status:y.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:dt,expiresAt:dt.nullable(),orderId:y.uuid().nullable(),parentSourceId:y.uuid().nullable()}).strict(),y.object({...ur,type:y.literal("usage"),internal_feature_id:y.uuid(),name:y.string().min(1).max(120),kind:y.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:y.uuid().nullable(),quantity:W,accepted:y.boolean(),reason:y.enum([...Rn.options,"expired"]).nullable(),properties:Re,reservationStatus:y.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:dt.nullable(),charges:y.array(y.discriminatedUnion("funding",[y.strictObject({funding:y.literal("balance"),sourceId:y.uuid(),rolloverId:y.uuid().nullable(),units:$t,amount:Ze}),y.strictObject({funding:y.literal("unbilled"),units:$t}),y.object({...Fr,funding:y.literal("prepaid"),amount:Ze}).strict(),y.object({funding:y.literal("postpaid"),invoiceId:y.uuid(),invoiceLineId:y.uuid(),authorizationId:y.uuid(),units:W,currency:Y}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),y.object({...ur,type:y.literal("transaction"),purpose:y.enum(["product","invoice"]),productVersionId:y.uuid().nullable(),productName:y.string().min(1).max(120).nullable(),productVersion:y.number().int().positive().nullable(),invoiceId:y.uuid().nullable(),orderId:y.uuid(),originalId:y.uuid().nullable(),kind:y.enum(["purchase","refund"]),amountMinor:y.number().int().nonnegative().max(2e8).nullable(),currency:Y.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),y.object({...ur,...Fr,type:y.literal("debt"),sourceId:y.uuid(),transactionId:y.uuid(),amount:Ze}).strict(),y.object({...ur,...Fr,type:y.literal("settlement"),sourceId:y.uuid(),debtId:y.uuid(),kind:y.enum(["payment","usage_refund","payment_return"]),amount:Ze}).strict()]),kc=y.object({customerId:y.uuid(),rows:y.array(Hf).max(50),nextCursor:jc.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as K}from"zod";var Nc=K.object({customerId:K.uuid()}).strict(),Mc=K.discriminatedUnion("action",[K.object({customerId:K.uuid(),requestId:K.uuid(),action:K.literal("assign"),poolId:K.uuid(),memberCustomerId:K.uuid()}).strict(),K.strictObject({customerId:K.uuid(),requestId:K.uuid(),action:K.literal("assign_entity"),poolId:K.uuid(),entityId:K.uuid()}),K.object({customerId:K.uuid(),requestId:K.uuid(),action:K.literal("release"),poolId:K.uuid(),slotId:K.uuid()}).strict()]),Vr=K.number().int().nonnegative(),sa=K.iso.datetime({offset:!0}),ca=K.strictObject({internalId:K.uuid(),id:K.string(),name:K.string().nullable(),version:K.number().int().positive()}),Dc=K.enum(["active","past_due"]),ua=K.strictObject({customerId:K.uuid(),licenses:K.array(K.strictObject({id:K.uuid(),linkId:K.uuid(),parent:K.strictObject({customerProductId:K.uuid(),status:Dc,product:ca}),product:ca,planLicense:K.strictObject({id:K.uuid(),prepaidOnly:K.boolean(),isCustom:K.boolean()}).nullable(),granted:Vr,included:Vr,paidQuantity:Vr,usage:Vr,remaining:Vr,createdAt:sa}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:K.array(K.strictObject({id:K.uuid(),linkId:K.uuid(),status:Dc,product:ca,entity:K.strictObject({internalId:K.uuid(),id:K.string().nullable(),name:K.string().nullable()}).nullable(),beneficiary:K.strictObject({internalId:K.uuid(),id:K.string().nullable(),name:K.string().nullable()}).nullable(),startedAt:sa.nullable(),endedAt:sa.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:K.boolean()});import{z as Ht}from"zod";var Dn=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,lr=Ht.object({customerId:Ht.uuid(),sessionId:Ht.uuid(),accessToken:Ht.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Ht.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Ht.iso.datetime(),refreshExpiresAt:Ht.iso.datetime()});import{z as H}from"zod";var $r=H.enum(["email","sms","voice","push"]),o0=H.enum(["resend","twilio","fcm","apns"]);var s0=H.string().regex(/^\+[1-9]\d{1,14}$/),Kf=H.enum(["email_recipient","sms_segment","voice_second","push_device"]);var Zf=H.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),Wf=H.strictObject({subject:Zf,html:H.string().min(1).max(131072).optional(),text:H.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),Qf=H.strictObject({body:H.string().min(1).max(1600).refine(e=>e.trim().length>0)}),Yf=H.strictObject({text:H.string().trim().min(1).max(4e3),language:H.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:H.number().int().min(1).max(900)}),Jf=H.record(H.string().min(1).max(64),H.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),Xf=H.strictObject({title:H.string().trim().min(1).max(200),body:H.string().trim().min(1).max(2e3),url:H.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:Jf.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Uc=H.discriminatedUnion("channel",[H.strictObject({channel:H.literal("email"),content:Wf}),H.strictObject({channel:H.literal("sms"),content:Qf}),H.strictObject({channel:H.literal("voice"),content:Yf}),H.strictObject({channel:H.literal("push"),content:Xf})]),qc=H.strictObject({requestId:H.uuid(),customerId:H.uuid(),connectionId:H.uuid().optional(),message:Uc,expiresAt:H.iso.datetime({offset:!0})}),zf=H.array(H.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),eh=H.discriminatedUnion("kind",[H.strictObject({kind:H.literal("all")}),H.strictObject({kind:H.literal("customers"),customerIds:zf})]),c0=H.strictObject({name:H.string().trim().min(1).max(120),connectionId:H.uuid().optional(),message:Uc,audience:eh,frequencyLimit:H.number().int().min(1).max(100)}),Lc=H.strictObject({requestId:H.uuid(),channel:$r,state:H.enum(["allowed","denied"]),expectedRevision:H.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Bc=H.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Fc=H.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),u0=H.strictObject({meter:Kf,estimatedUnits:H.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:H.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as te}from"zod";import{z as J}from"zod";import{z as Ie}from"zod";import{z as th}from"zod";import{z as dr}from"zod";var Vc=dr.enum(["stripe","apple","google"]),$c=dr.enum(["membership","credit_pack","lifetime"]),m0=dr.enum(["active","grace","suspended","inactive","revoked"]),p0=dr.strictObject({currency:dr.string().regex(/^[A-Z]{3}$/),micros:dr.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var mr=th.object({provider:Vc,currency:Y}).strict();var jt=Ie.strictObject({internal_feature_id:Ie.uuid(),quantity:W.refine(e=>/[1-9]/.test(e)),properties:Re,entityId:Ie.uuid().optional()}),Gc=Ie.strictObject({requirement:jt,commerce:mr.optional(),paywallId:Ie.uuid().optional()}),rh=Ie.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),la=Ie.strictObject({productId:Ie.string().min(1),productVersionId:Ie.string().min(1),name:Ie.string().min(1).max(120),action:Ie.enum(["purchase","upgrade","addon","topup"]),membershipId:Ie.string().min(1).nullable(),currency:Y,amountMinor:Ie.string().regex(/^(0|[1-9]\d{0,8})$/),interval:Ie.enum(["free","week","month","year","one_time"]),intervalCount:Ie.number().int().min(1).max(156)}),Kt=Ie.strictObject({internal_feature_id:Ie.string().min(1),name:Ie.string().min(1).max(120),kind:Ie.enum(["access","metered","credit"]),quantity:W,allowed:Ie.boolean(),reason:rh.nullable(),preview:Ie.strictObject({scenario:Ie.enum(["feature_flag","usage_limit"]),candidates:Ie.array(la).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(r=>r.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(r=>r.action==="upgrade"!=(r.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),I0=Ie.strictObject({paywallId:Ie.uuid(),requirement:jt});var da=J.object({plan:J.string().min(1).max(200).optional(),coupon:J.uuid().optional(),promotionCode:J.uuid().optional(),picker:J.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Nn=J.object({text:J.string().optional(),label:J.string().optional(),alt:J.string().optional(),html:J.string().max(32768).optional(),price:J.object({current:J.string(),original:J.string().nullable(),period:J.string()}).optional(),code:J.string().optional(),countdownAt:J.iso.datetime().optional(),planId:J.string().min(1).max(200).optional(),planVersionId:J.string().min(1).max(200).optional(),currency:Y.optional(),couponId:J.uuid().optional(),offerId:J.uuid().optional(),unavailable:J.boolean().optional(),unavailableReason:J.string().optional(),missing:J.array(J.string()).optional()}).strict(),Mn=J.object({paywall:Kt.optional(),nodes:J.record(J.string(),J.object({base:Nn,picker:J.string().optional(),byPlan:J.record(J.string(),Nn).optional()}).strict()),plans:J.record(J.string(),J.object({id:J.string().min(1).max(200),versionId:J.string().min(1).max(200),available:J.boolean(),name:J.string(),price:J.string(),period:J.string(),currency:Y.optional()}).strict()),pickers:J.record(J.string(),J.object({options:J.array(J.string().min(1).max(200)).max(20),selected:J.string().min(1).max(200).nullable()}).strict()),diagnostics:J.array(J.object({nodeId:J.string(),message:J.string()}).strict())}).strict();function Hc(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as d}from"zod";function nh(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Kc(e){let t={};function r(n){var i;if(nh(n)){let o=t[i=n.interaction.pickerId]??(t[i]={ids:[],defaultId:null});for(let c of n.children){let l=c.type==="stack"?c.bind?.plan:void 0;l&&!o.ids.includes(l)&&o.ids.push(l)}let a=n.children[n.interaction.defaultIndex];!o.defaultId&&a?.type==="stack"&&(o.defaultId=a.bind?.plan??null)}n.type==="stack"&&n.children.forEach(r)}return e.pages.forEach(n=>r(n.root)),t}import{z as It}from"zod";var Zc=It.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Un=It.strictObject({tiers:It.array(It.strictObject({id:Zc,name:It.string().trim().min(1).max(80)})).min(1).max(8),assignments:It.array(It.strictObject({productVersionId:It.string().min(1).max(200),tierId:Zc,period:It.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let r=e.tiers.map(n=>n.id);(new Set(r).size!==r.length||new Set(e.assignments.map(n=>n.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(n=>`${n.tierId}:${n.period}`)).size!==e.assignments.length||e.assignments.some(n=>!r.includes(n.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function qn(e,t){return e.assignments.length===t.length&&e.assignments.every(r=>t.includes(r.productVersionId))}import{z as $}from"zod";var ih=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Wc=$.enum(ih),Qc=$.object({source:Wc,layout:$.enum(["full","compact"]),resourceKey:Lt.optional(),pageSize:$.number().int().min(1).max(50),showSources:$.boolean(),allowPurchase:$.boolean(),outputs:$.object({billing_adjustment:$.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:$.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:$.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:$.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:$.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:$.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),Le=$.string().max(2e3),Yc=$.object({id:$.string().max(100),label:Le,detail:$.array(Le).max(12),value:Le.optional(),status:Le.optional(),facts:$.array($.object({label:Le,value:Le}).strict()).max(1e3),purchaseId:$.uuid().optional(),invoiceUrl:$.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:$.array($.strictObject({action:$.literal("invoice_open"),label:Le})).max(1).optional(),membershipActions:$.array($.object({value:$.string().max(100),label:Le}).strict()).max(3).optional()}).strict(),ah=$.object({key:Lt,name:Le,spendable:Le,reserved:Le,available:Le,expiry:Le.nullable(),sources:$.array(Yc).max(50),sourceCount:$.number().int().nonnegative(),sourcePage:$.number().int().positive(),hasNextSources:$.boolean(),hasPreviousSources:$.boolean()}).strict(),oh=$.object({source:Wc,status:$.enum(["idle","loading","ready","error"]),stale:$.boolean(),preview:$.boolean(),errorCode:$.string().max(80).optional(),errorMessage:Le.optional(),resources:$.array(ah).max(500),rows:$.array(Yc).max(50),hasNext:$.boolean(),hasPrevious:$.boolean(),page:$.number().int().positive(),filter:$.string().max(40),updatedAt:$.iso.datetime().optional(),buyingId:$.uuid().optional(),membershipBusy:$.boolean().optional(),billingBusy:$.boolean().optional(),membershipReview:$.object({title:Le,note:Le,facts:$.array($.object({label:Le,value:Le}).strict()).max(100)}).strict().optional(),membershipResult:Le.optional()}).strict(),D0=$.object({nodes:$.record($.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),oh)}).strict(),N0=$.object({nodeId:$.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:$.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:$.string().max(100).optional()}).strict();var ch=4,pt={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Hr=d.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),se=d.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),uh=d.enum(["none","xs","sm","md","lg","xl"]),lh=d.enum(["none","sm","md","lg","full"]),ma=d.string().regex(/^#[0-9a-fA-F]{6}$/),zc=d.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),pa=d.union([zc,d.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),d.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),d.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Jc=d.object({primary:ma,background:ma,text:ma,radius:lh,font:d.enum(["system","serif","rounded","mono"])}).strict(),Kr=d.union([d.enum(["primary","text","muted","background","surface"]),d.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),me=(e,t)=>d.number().int().min(e).max(t),Xc=d.union([d.enum(["fit","fill"]),me(1,1200)]),dh=d.object({top:me(0,200),right:me(0,200),bottom:me(0,200),left:me(0,200)}).strict(),mh=d.object({top:me(-100,200),right:me(-100,200),bottom:me(-100,200),left:me(-100,200)}).strict(),eu=d.object({x:me(0,100),y:me(0,100)}).strict(),ph=d.discriminatedUnion("type",[d.object({type:d.literal("color"),color:Kr}).strict(),d.object({type:d.literal("linear"),angle:me(0,360),stops:d.array(d.object({color:Kr,at:me(0,100)}).strict()).min(2).max(4)}).strict(),d.object({type:d.literal("image"),src:pa,fit:d.enum(["cover","contain"]),position:eu.optional()}).strict()]),fh=d.discriminatedUnion("type",[d.object({type:d.literal("rect"),radius:d.union([me(0,200),d.object({topLeft:me(0,200),topRight:me(0,200),bottomRight:me(0,200),bottomLeft:me(0,200)}).strict()])}).strict(),d.object({type:d.literal("pill")}).strict()]),hh=d.object({width:me(0,12),color:Kr,style:d.enum(["solid","dashed"])}).strict(),Ah=d.object({x:me(-40,40),y:me(-40,40),blur:me(0,80),spread:me(-20,40),color:Kr}).strict(),gh=d.object({font:d.enum(["system","serif","rounded","mono"]),size:me(8,96),weight:d.number().int().min(100).max(900).multipleOf(100),lineHeight:d.number().min(.8).max(3),letterSpacing:d.number().min(-5).max(20),color:Kr,align:d.enum(["start","center","end"]),italic:d.boolean(),decoration:d.enum(["none","underline","line-through"]),transform:d.enum(["none","uppercase"])}).strict().partial(),Zt=d.object({width:Xc,height:Xc,padding:dh,margin:mh,gap:me(0,120),grow:d.union([d.boolean(),d.number().min(0).max(12)]),background:ph,opacity:d.number().min(0).max(1),clipContent:d.boolean(),shape:fh,border:hh,shadow:Ah,text:gh}).strict().partial(),rt={id:Hr,name:d.string().trim().min(1).max(60).optional(),hidden:d.boolean().optional(),style:Zt.optional(),fallback:se.optional()},bh=d.object({...rt,type:d.literal("text"),productField:d.enum(["name","price","trial","period"]).optional(),feature:d.object({id:d.uuid(),field:d.enum(["name","allowance"])}).strict().optional(),text:se,variant:d.enum(["title","heading","body","caption"])}).strict(),yh=d.object({...rt,type:d.literal("image"),src:pa,localizedSrc:d.record(ut,pa).optional(),alt:se,aspect:d.enum(["auto","1:1","4:3","16:9","3:1"]),fit:d.enum(["cover","contain"]),position:eu.optional()}).strict(),Sh=d.object({...rt,type:d.literal("button"),label:se,variant:d.enum(["primary","secondary","link"]),action:se,purpose:d.enum(["purchase","navigation","close"]).optional(),bind:da.optional()}).strict(),_h=d.object({...rt,type:d.literal("divider")}).strict(),xh=d.object({...rt,type:d.literal("customer_data"),title:se,data:Qc}).strict(),Ih=d.object({...rt,type:d.literal("spacer"),size:uh}).strict(),vh=d.object({...rt,type:d.literal("custom_html"),html:d.record(ut,d.string().max(pt.customHtml)),css:d.string().max(pt.customCss)}).strict(),Ph=d.object({...rt,type:d.literal("price"),fallback:se,parts:d.object({current:Zt.optional(),original:Zt.optional(),period:Zt.optional()}).strict().optional()}).strict(),Ch=d.object({...rt,type:d.literal("coupon_code"),label:se,fallback:se}).strict(),wh=d.object({...rt,type:d.literal("countdown"),source:d.enum(["offer.ends_at","offer.expires_at","fixed"]),at:d.iso.datetime().optional(),granularity:d.enum(["day","hour","minute","second"]),expired:se,fallback:se}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Oh=d.object({...rt,type:d.literal("plan_picker"),label:se,fallback:se,planIds:d.array(d.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:d.string().min(1).max(200).optional(),grouping:Un.safeExtend({monthLabel:se,yearLabel:se,unavailableLabel:se}).optional(),states:d.object({selected:Zt.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!qn(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Eh=d.discriminatedUnion("type",[d.object({type:d.literal("input"),label:se,keyboard:d.enum(["text","email","tel","url"]),maxLength:me(1,500)}).strict(),d.object({type:d.literal("multiselect"),label:se,min:me(0,50),max:me(1,50)}).strict(),d.object({type:d.literal("select"),label:se,defaultIndex:me(0,49),purpose:d.enum(["option","product","tier"]).optional(),pickerId:Hr.optional(),selectedStyle:Zt.optional()}).strict(),d.object({type:d.literal("tabs"),label:se,defaultIndex:me(0,49),purpose:d.literal("tier").optional()}).strict(),d.object({type:d.literal("toggle"),label:se,defaultEnabled:d.boolean()}).strict(),d.object({type:d.literal("carousel"),label:se}).strict()]),mt={...rt,type:d.literal("stack"),direction:d.enum(["vertical","horizontal","overlay"]),align:d.enum(["start","center","end","stretch"]),justify:d.enum(["start","center","end","between"]),productSlot:d.object({index:me(0,19),period:d.enum(["month","year"]).optional(),requireBinding:d.boolean().optional()}).strict().optional(),interaction:Eh.optional(),states:d.object({selected:Zt.optional()}).strict().optional(),purpose:d.literal("benefits").optional(),purchaseAction:se.optional(),buttonVariant:d.enum(["primary","secondary","link"]).optional(),bind:da.optional()},tu=d.lazy(()=>d.object({...rt,type:mt.type,direction:mt.direction,align:mt.align,justify:mt.justify,children:d.array(Th).max(pt.children),productSlot:mt.productSlot,interaction:mt.interaction,states:mt.states,purpose:mt.purpose,purchaseAction:mt.purchaseAction,buttonVariant:mt.buttonVariant,bind:mt.bind}).strict()),Th=d.lazy(()=>d.union([tu,bh,yh,Sh,_h,Ih,vh,Ph,Ch,wh,Oh,xh])),jh=d.union([d.string().max(500),d.number().finite(),d.boolean(),d.null()]),Gr={id:se,event:se,properties:d.record(se,jh).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Rh=d.discriminatedUnion("type",[d.object({...Gr,type:d.literal("navigate"),close:d.literal(!1),pageId:Hr}).strict(),d.object({...Gr,type:d.literal("event"),close:d.boolean()}).strict(),d.object({...Gr,type:d.literal("close"),close:d.literal(!0)}).strict(),d.object({...Gr,type:d.literal("open_url"),close:d.boolean(),url:zc}).strict(),d.object({...Gr,type:d.literal("claim_offer"),close:d.boolean(),couponId:d.uuid()}).strict()]),kh=d.object({defaultLocale:ut,locales:d.record(ut,d.record(se,d.string().max(pt.stringLength)))}).strict(),Dh=d.enum(["popup","paywall","onboarding","page","banner"]);var Nh=d.discriminatedUnion("type",[d.object({type:d.literal("modal"),size:d.enum(["sm","md","lg"])}).strict(),d.object({type:d.literal("sheet"),size:d.enum(["sm","md","lg"])}).strict(),d.object({type:d.literal("fullscreen")}).strict(),d.object({type:d.literal("inline")}).strict()]);var Mh=d.object({kind:d.literal("screen"),schemaVersion:d.literal(ch),name:d.string().trim().min(1).max(80),surface:Dh,initialPageId:Hr.optional(),presentation:Nh,theme:Jc,pages:d.array(d.object({id:Hr,name:d.string().trim().min(1).max(60),root:tu,theme:Jc.optional(),editorPosition:d.object({x:d.number().finite().min(-1e5).max(1e5),y:d.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(pt.pages),strings:kh,actions:d.array(Rh).max(pt.actions)}).strict();function ot(e,t){for(let r of e.pages)Zr(r.root,t)}var Wt=Mh.superRefine((e,t)=>{let r=pt;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(A=>A.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let A of e.actions)A.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(v=>v.id===A.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>r.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${r.pages} \u4E2A`}),e.actions.length>r.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${r.actions} \u4E2A`});let n=A=>t.addIssue({code:"custom",message:A}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||n("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>pt.locales&&n(`\u6700\u591A ${pt.locales} \u79CD\u8BED\u8A00`);let o=new Set;for(let A of e.actions)o.has(A.id)&&n(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${A.id}`),o.add(A.id);let a=new Set;for(let A of e.pages)["next","back"].includes(A.id)&&n(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${A.id}`),a.has(A.id)&&n(`\u9875\u9762 id \u91CD\u590D\uFF1A${A.id}`),a.add(A.id);let c=new Set,l=0,p=!1;ot(e,(A,v)=>{if(l++,v>pt.depth&&(p=!0),c.has(A.id)&&n(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${A.id}`),c.add(A.id),A.type==="button"&&!o.has(A.action)&&n(`\u6309\u94AE ${A.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${A.action}`),A.type==="custom_html")for(let k of Object.keys(A.html))i.includes(k)||n(`\u81EA\u5B9A\u4E49 HTML ${A.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${k}`);if(A.type==="image")for(let k of Object.keys(A.localizedSrc??{}))i.includes(k)||n(`\u56FE\u7247 ${A.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${k}`)}),l>r.nodes&&n(`\u7EC4\u4EF6\u6700\u591A ${r.nodes} \u4E2A`),p&&n(`\u5C42\u7EA7\u6700\u591A ${pt.depth} \u5C42`)});function Zr(e,t,r=1,n=null){if(t(e,r,n)!==!1&&e.type==="stack")for(let i of e.children)Zr(i,t,r+1,e)}function fa(e){let t=[],r=new Set;return ot(e,n=>{let i=(o,a,c)=>{r.has(o)||(r.add(o),t.push({key:o,nodeId:n.id,nodeType:n.type,field:a,required:c}))};n.type==="stack"&&n.interaction&&i(n.interaction.label,"label",!0),n.fallback&&i(n.fallback,"text",!0),n.type==="text"&&i(n.text,"text",!0),n.type==="customer_data"&&i(n.title,"title",!0),(n.type==="plan_picker"||n.type==="coupon_code")&&i(n.label,"label",!0),n.type==="plan_picker"&&n.grouping&&(i(n.grouping.monthLabel,"label",!0),i(n.grouping.yearLabel,"label",!0),i(n.grouping.unavailableLabel,"text",!0)),n.type==="countdown"&&i(n.expired,"text",!0),n.type==="button"&&i(n.label,"label",!0),n.type==="image"&&(i(`image:${n.id}`,"src",!1),i(n.alt,"alt",!1)),n.type==="custom_html"&&i(`html:${n.id}`,"html",!0)}),t}function Uh(e,t,r){if(t.field==="html"){let n;return ot(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(n=i.html[r])}),n}if(t.field==="src"){let n=Lh(e,t.nodeId);return n?.type==="image"?n.localizedSrc?.[r]??(r===e.strings.defaultLocale?n.src:void 0):void 0}return e.strings.locales[r]?.[t.key]}function pr(e){let t=fa(e).filter(n=>n.required);return Object.keys(e.strings.locales).sort((n,i)=>n===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(n=>{let i=t.filter(o=>!Uh(e,o,n)?.trim()).map(o=>o.key);return{locale:n,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function qh(e,t){let r=null;return Zr(e,n=>{if(r)return!1;n.id===t&&(r=n)}),r}function Lh(e,t){for(let r of e.pages){let n=qh(r.root,t);if(n)return n}return null}function Bh(e){let t=Object.values(e.strings.locales).flatMap(r=>Object.values(r));return ot(e,r=>{r.type==="custom_html"&&t.push(...Object.values(r.html))}),[...new Set(t.flatMap(Hc))]}function ru(e){return Bh(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function nu(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let r=new TextEncoder().encode(t).length,n=!1;for(let i=0;i<t.length;i++){let o=t.charAt(i);if(n)o==="\\"?i++:o==='"'&&(n=!1);else if(o==='"')n=!0;else if(o===":"||o===",")r++;else if(o==="-"||o>="0"&&o<="9"){let a=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let c=t.slice(a,i+1);if(!/[eE]/.test(c))continue;let[l="",p]=c.split(/[eE]/),A=l.replace(/^-/,""),v=A.replace(".","").length,k=(A.includes(".")?A.indexOf("."):v)+Number(p),U=k<=0?2-k+v:k>=v?k:v+1;r+=U+(l.startsWith("-")?1:0)-c.length}}return r}var Rt=te.enum(["page","popup","banner"]),Fh=3e5,iu=te.strictObject({type:te.enum(["string","number","boolean","strings","json"]),nullable:te.boolean()}),Vh=te.strictObject({inputs:te.record(se,iu.extend({required:te.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:te.record(se,iu).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),$h=te.strictObject({kind:Rt,schemaVersion:te.literal(1),name:te.string().trim().min(1).max(80),screen:Wt,contract:Vh}),Ln=$h.superRefine((e,t)=>{let r=(i,o)=>t.addIssue({code:"custom",message:i,path:o});e.screen.surface!==e.kind&&r("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&r("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&r("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&r("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(i=>i.type!=="event"&&i.type!=="navigate")&&r("Content actions must emit host intents or navigate locally",["screen","actions"]);let n=new Set(e.screen.actions.filter(i=>i.type==="event").map(i=>i.id));(Object.keys(e.contract.outputs).some(i=>!n.has(i))||[...n].some(i=>!Object.hasOwn(e.contract.outputs,i)))&&r("Every event needs exactly one output declaration",["contract","outputs"]),nu(e)>Fh&&r("Content document exceeds its byte budget",[])});function Gh(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(r=>typeof r=="string")}}var Hh=Ln.superRefine((e,t)=>{for(let r of ru(e.screen))Object.keys(e.contract.inputs).some(n=>r===n||r.startsWith(n+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let r of e.screen.actions){if(r.type!=="event")continue;let n=e.contract.outputs[r.id],i=Object.hasOwn(r.properties,"value")?r.properties.value:r.properties;n&&!Gh(i,n)&&t.addIssue({code:"custom",path:["contract","outputs",r.id],message:"Action value differs from its declared type"})}pr(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),au=te.strictObject({id:te.uuid(),kind:Rt,projectId:te.uuid(),environmentId:te.uuid(),name:te.string(),revision:te.number().int().nonnegative(),status:te.enum(["draft","published","archived"]),publishedVersionId:te.uuid().nullable(),createdAt:te.iso.datetime({offset:!0}),updatedAt:te.iso.datetime({offset:!0})}),z0=au.extend({draft:Ln}),e_=te.strictObject({rows:te.array(au).max(200),nextCursor:te.uuid().nullable()}),ha=te.strictObject({id:te.uuid(),kind:Rt,resourceId:te.uuid(),projectId:te.uuid(),environmentId:te.uuid(),version:te.number().int().positive(),sourceRevision:te.number().int().nonnegative(),document:Hh,createdAt:te.iso.datetime({offset:!0})}),t_=ha.omit({document:!0}),r_=te.discriminatedUnion("action",[te.strictObject({action:te.literal("create"),kind:Rt,id:te.uuid(),document:Ln}),te.strictObject({action:te.literal("save"),kind:Rt,id:te.uuid(),revision:te.number().int().nonnegative(),document:Ln}),te.strictObject({action:te.enum(["publish","archive"]),kind:Rt,id:te.uuid(),revision:te.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as ou}from"zod";var fr={funnelId:ou.uuid().optional(),funnelVersionId:ou.uuid().optional()};import{z as _e}from"zod";import{z as ce}from"zod";import{z as ye}from"zod";var s_=ye.discriminatedUnion("action",[ye.strictObject({action:ye.literal("create"),couponId:ye.uuid(),productBindingId:ye.uuid(),storeOfferId:ye.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:ye.enum(["introductory","promotional"])}),ye.strictObject({action:ye.literal("set_enabled"),id:ye.uuid(),revision:ye.number().int().nonnegative(),enabled:ye.boolean()})]),c_=ye.array(ye.strictObject({id:ye.uuid(),couponId:ye.uuid(),productBindingId:ye.uuid(),storeOfferId:ye.string().min(1).max(255).nullable(),storeOfferType:ye.enum(["introductory","promotional"]),enabled:ye.boolean(),revision:ye.number().int().nonnegative()})).max(500),Bn=ye.strictObject({offerKind:ye.enum(["none","introductory","promotional"]),offerId:ye.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:ye.number().int().min(0).max(1e8),trialDays:ye.number().int().min(1).max(730).nullable()}).superRefine((e,t)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&t.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),u_=ye.record(ye.uuid(),Bn).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Aa=ce.object({type:ce.literal("native_purchase"),receiptId:ce.uuid(),orderId:ce.uuid(),productVersionId:ce.uuid(),provider:ce.enum(["apple","google"]),productId:ce.string().min(1).max(255),productKind:$c,replacement:ce.strictObject({sourceOrderId:ce.uuid(),sourceProductId:ce.string().min(1).max(255),policy:ce.enum(["apple_store","google_full_price"]),sourceAccountTokens:ce.array(ce.uuid()).max(50)}).nullable(),appAccountToken:ce.uuid().optional(),obfuscatedAccountId:ce.string().min(1).max(64).optional(),obfuscatedProfileId:ce.uuid().optional(),basePlanId:ce.string().min(1).max(255).optional(),offerId:ce.string().min(1).max(255).optional(),offerKind:ce.enum(["none","introductory","promotional"]),currency:Y,catalogAmountMinor:ce.number().int().nonnegative().max(1e8),discountMinor:ce.number().int().nonnegative().max(1e8),trialDays:ce.number().int().min(1).max(730).nullable(),seatBundle:ce.array(ce.strictObject({key:ce.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:ce.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:ce.strictObject({offerId:ce.string().min(1).max(255),keyId:ce.string().min(1).max(255),nonce:ce.uuid(),signature:ce.string().min(1).max(1024),timestamp:ce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let r=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(r?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!r&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(r?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as s}from"zod";import{z as re}from"zod/v4";import{z as Kh}from"zod/v4";var Zh=Kh.registry(),{BillingInterval:su}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:Wh}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(re),{withSpecDefault:Qh}=(e=>({withSpecDefault:({schema:r,defaultValue:n,description:i})=>(e.add(r,{description:i,default:n}),r)}))(Zh),{COMMON:cu}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Yh}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:Jh}=(e=>({COMMON_SET:new Set(e)}))(cu),{hasNoDuplicateCurrencies:uu}={hasNoDuplicateCurrencies:t=>{let r=new Set;for(let{currency:n}of t){let i=n.toLowerCase();if(r.has(i))return!1;r.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:lu}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Xh}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(re),{Infinite:zh}={Infinite:"inf"},{TierBehavior:eA}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:du}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:tA}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:rA}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:nA}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:iA}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(re),{ApiCreditTierSchema:mu}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(re),{VIOLATION_MESSAGES:aA}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:pu}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(re),{ModelMarkupsSchema:oA}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(re,pu),{InvoiceUsageEntrySchema:sA}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(re),{AttachDiscountSchema:fu}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(r=>r.reward_id||r.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(re),{CustomLineItemSchema:cA}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(re),{UnixMsTimestampSchema:uA}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(re),{CreateInvoicePreviewLineSchema:lA}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(re),{ReissueInvoiceParamsSchema:ga}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(re),{InvoiceModeParamsSchema:Qt}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(re),{InvoiceTemplateSchema:dA}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(re),{BasePriceSchema:mA}=((e,t,r)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:r.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(re,su,Wh),{CURRENCY_CODES:pA}=((e,t,r)=>({CURRENCY_CODES:[...e,...t.filter(i=>!r.has(i)).sort()]}))(cu,Yh,Jh),{ApiPriceProcessorsSchema:hu}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(re,Xh),{AllocatedBillingFieldSchema:fA}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(re,tA),{CreditDimensionNameSchema:hA}=((e,t,r)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(r),{message:`Dimension names cannot contain "${r}"`})}))(re,rA,nA),{ApiCreditMatchSchema:Au}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(iA),{findCreditTierViolations:AA}=(e=>({findCreditTierViolations:r=>{let n=[],i=(a,c)=>n.push({index:a,reason:c,message:e[c]}),o=0;for(let[a,c]of r.entries()){let l=a===r.length-1;if(c==="inf"){l||i(a,"non_final_infinity");continue}(!Number.isFinite(c)||c<=o)&&i(a,"not_increasing"),o=c,l&&i(a,"final_not_infinity")}return n}}))(aA),{ApiCreditMultiplierSchema:gA}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(n=>n.factor!==void 0||n.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(re,Au),{ProviderMarkupsSchema:bA}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(re,pu),{InvoiceFeatureQuantitySchema:gu}=((e,t,r)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(r).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(re,du,sA),{CreateInvoicePreviewSchema:ba}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(re,lA),{SUPPORTED_SET:yA}=(e=>({SUPPORTED_SET:new Set(e)}))(pA),{ApiCreditDimensionBaseSchema:SA}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(re,Au),{refineGraduatedTiers:bu}=(e=>({refineGraduatedTiers:(r,n)=>{let i=e(r.tiers.map(o=>o.to));for(let{index:o,message:a}of i)n.addIssue({code:"custom",message:a,path:["tiers",o,"to"]})}}))(AA),{ApiFeatureMarkupsOverrideSchema:_A}=((e,t,r)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:r.meta({description:"Per-model markup overrides for customers on this plan."})})}))(re,bA,oA),{isValidCurrencyCode:xA}=(e=>({isValidCurrencyCode:r=>!!r&&e.has(r.toLowerCase())}))(yA),{ApiCreditDimensionSchema:IA}=((e,t,r,n)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(r).min(1)}).strict().superRefine(n),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(re,SA,mu,bu),{CurrencyCodeSchema:yu}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(re,xA),{AdditionalCurrencyTierSchema:vA}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(n=>n.amount!==void 0||n.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(re,yu),{ApiCreditSchemaItemBaseSchema:Su}=((e,t,r,n)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,r).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,n).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(re,hA,IA,gA),{ApiFlatCreditSchemaItemSchema:PA}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Su,re),{AdditionalCurrencyPriceSchema:CA}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(re,yu),{AdditionalCurrencyTierArraySchema:wA}=((e,t,r,n)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(r,{message:n})}))(re,vA,uu,lu),{ApiGraduatedCreditSchemaItemSchema:OA}=((e,t,r,n)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(r).min(1)}).strict().superRefine(n)}))(Su,re,mu,bu),{AdditionalCurrencyPriceArraySchema:_u}=((e,t,r,n)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(r,{message:n})}))(re,CA,uu,lu),{ApiUsageTierWithCurrenciesSchema:EA}=((e,t,r)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:r.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:r.optional()}))}))(re,zh,wA),{ApiCreditSchemaItemSchema:TA}=((e,t,r)=>({ApiCreditSchemaItemSchema:e.union([t,r])}))(re,OA,PA),{BasePriceParamsSchema:jA}=((e,t,r,n)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:r.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:n.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:r.string().optional().meta({internal:!0}),entitlement_id:r.string().optional().meta({internal:!0}),price_id:r.string().optional().meta({internal:!0}),stripe_price_id:r.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(mA,Qh,re,_u),{PlanItemPriceParamsSchema:RA}=((e,t,r,n,i,o,a)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(l=>l??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(r).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(n).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(o).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:a,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(re,_u,EA,eA,su,du,fA),{ApiFeatureOverrideSchema:kA}=((e,t,r)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:r.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(re,TA,_A),{InvoiceBasePriceParamsSchema:xu}=((e,t)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(jA,hu),{InvoiceItemPriceParamsSchema:DA}=((e,t)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(RA,hu),{InvoiceLicenseQuantitySchema:NA}=((e,t,r)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(r).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(re,xu,gu),{InvoiceCustomizeItemSchema:MA}=((e,t,r)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:r.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(re,DA,kA),{InvoiceCustomizeSchema:UA}=((e,t,r)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(r).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(re,xu,MA),{InvoicePlanParamsSchema:qA}=((e,t,r,n,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(r).optional(),license_quantities:e.array(n).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(re,UA,gu,NA,fu),{CreateInvoiceParamsSchema:hr}=((e,t,r,n,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(r).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(n).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(a=>a.period_start===void 0==(a.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(a=>a.period_start===void 0||a.period_end===void 0||a.period_end>a.period_start,{message:"period_end must be after period_start."})}))(re,qA,cA,fu,uA);var Pu=s.strictObject({requestId:s.uuid(),predecessorOperationId:s.uuid().optional(),invoiceMode:Qt.optional(),entityId:s.uuid().optional(),billingSubscriptionId:s.uuid().optional(),newBillingSubscription:s.literal(!0).optional(),offerId:s.uuid().optional(),nativeOffer:Bn.optional(),plans:s.array(s.strictObject({productVersionId:s.uuid(),seatQuantities:s.record(qt,s.number().int().min(0).max(1e4)).optional(),featureQuantities:s.record(s.uuid(),s.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:s.enum(["stripe","apple","google"]),currency:Y}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(e.provider==="stripe"||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||e.provider!=="stripe"&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||e.provider==="stripe"&&!e.billingSubscriptionId,"A new billing subscription requires Stripe and no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Jt=s.strictObject({operationId:s.uuid()}),Ve=s.number().int().min(0).max(1e8),LA=s.strictObject({lineId:s.uuid(),productVersionId:s.uuid(),productName:s.string().min(1).max(80),interval:s.enum(["free","week","month","year","one_time"]),intervalCount:s.number().int().min(1).max(156).optional(),baseAmountMinor:Ve,seats:s.array(s.strictObject({key:qt,quantity:s.number().int().min(0).max(1e4),includedQuantity:s.number().int().min(0).max(1e4),maximumQuantity:s.number().int().min(0).max(1e4),unitAmountMinor:Ve})).max(20),prepaid:s.array(Ac).max(100).optional(),catalogAmountMinor:Ve,trial:s.strictObject({days:s.number().int().min(1).max(730),cardRequired:s.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,r)=>t+r.unitAmountMinor*(r.quantity-r.includedQuantity),0)+(e.prepaid??[]).reduce((t,r)=>t+wn({quantity:r.quantity,unitAmountMinor:r.unitAmountMinor,...r.pricing===void 0?{}:{pricing:r.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),Cu=s.string().regex(/^[A-Za-z0-9_-]{1,200}$/),BA=s.strictObject({id:Cu,name:s.string().min(1).max(40),percent_off:s.number().gt(0).max(100).optional(),amount_off:s.number().int().positive().optional(),currency:s.string().regex(/^[a-z]{3}$/).optional(),duration:s.enum(["once","repeating","forever"]),duration_in_months:s.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),FA=s.strictObject({subscriptionId:s.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:s.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:s.array(s.strictObject({id:s.string(),price_id:s.string(),quantity:s.number().int().nonnegative(),discounts:s.array(s.strictObject({id:s.string(),coupon:s.string(),start:s.number(),end:s.number().nullable()})).optional()})).min(1).max(100),prorationDate:s.number().int().nonnegative(),amountMinor:s.number().int().positive(),periodStartMs:s.number(),periodEndMs:s.number()}),wu=s.strictObject({invoiceMode:Qt.optional(),append:FA.optional(),provider:s.literal("stripe"),executor:s.enum(["indiana","merchant"]),accountId:s.string().regex(/^acct_[A-Za-z0-9]+$/),mode:s.enum(["payment","subscription"]),lineItems:s.array(s.strictObject({price:s.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:s.number().int().min(1).max(1e4),priceId:s.uuid(),productName:s.string().min(1).max(80),amountMinor:s.number().int().min(0).max(1e8),currency:s.string().regex(/^[a-z]{3}$/),interval:s.enum(["week","month","year","one_off"]),intervalCount:s.number().int().min(1).max(52),slot:s.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:s.strictObject({mode:s.enum(["graduated","volume"]),tiers:s.array(s.strictObject({upTo:s.number().int().min(1).max(1e6).nullable(),unitAmountMinor:s.number().int().min(0).max(1e8),flatAmountMinor:s.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:s.array(s.strictObject({coupon:Cu,terms:BA})).max(1),trialPeriodDays:s.number().int().min(1).max(730).nullable(),metadata:s.strictObject({grooveCheckoutId:s.uuid(),grooveCustomerId:s.uuid()}),expiresAt:s.iso.datetime({offset:!0})}),Ou=s.strictObject({operationId:s.uuid(),entityId:s.uuid().nullable(),billingSubscriptionId:s.uuid().nullable(),discount:s.strictObject({offerId:s.uuid(),couponId:s.uuid(),discount:Ot,duration:et,amountMinor:Ve,allocations:s.array(s.strictObject({productVersionId:s.uuid(),amountMinor:Ve})).min(1).max(20),expiresAt:s.iso.datetime({offset:!0})}).nullable(),charge:s.strictObject({effectiveAt:s.iso.datetime({offset:!0}),periodEndsAt:s.iso.datetime({offset:!0}),debitMinor:Ve,discountMinor:Ve,taxMinor:Ve,totalMinor:Ve}).nullable(),expiresAt:s.iso.datetime({offset:!0}),provider:s.enum(["stripe","apple","google"]),nativeOffer:Bn.optional(),currency:Y,lines:s.array(LA).min(1).max(20),catalogAmountMinor:Ve,automaticTax:s.boolean(),execution:wu.nullable()}).refine(e=>e.provider==="stripe"?e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once")):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(e.provider==="stripe"||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,r)=>{let n=e.lines[r];return n!==void 0&&t.productVersionId===n.productVersionId&&t.amountMinor<=n.catalogAmountMinor})&&e.discount.allocations.reduce((t,r)=>t+r.amountMinor,0)===e.discount.amountMinor)&&(e.provider==="stripe"?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,r)=>t+r.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),ya=s.strictObject({operationId:s.uuid(),orderId:s.uuid(),append:s.boolean().optional(),invoiceMode:s.boolean().optional(),status:s.enum(["pending","complete","cancelled","failed"]),executor:s.enum(["indiana","merchant"]),checkoutUrl:s.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:wu.nullable(),currency:Y,catalogAmountMinor:Ve,taxMinor:Ve,totalMinor:s.number().int().min(0).max(2e8).nullable(),quoteFinalized:s.boolean(),nativePurchase:Aa.nullable()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),Vn=s.strictObject({enabled:s.literal(!0),featureIds:s.array(s.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Eu=s.strictObject({requestId:s.uuid(),invoiceMode:Qt.optional(),membershipId:s.uuid(),carryOverBalances:Vn.optional(),carryOverUsages:Vn.optional(),membershipIds:s.array(s.uuid()).min(1).max(20).optional(),prorationBehavior:s.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:s.enum(["immediate","renewal","store"]),change:s.discriminatedUnion("type",[s.strictObject({type:s.literal("plan"),productVersionId:s.uuid()}),s.strictObject({type:s.literal("seats"),licenseKey:qt,quantity:s.number().int().min(0).max(1e4)}),s.strictObject({type:s.literal("quantity"),internal_feature_id:s.uuid(),quantity:s.number().int().min(0).max(1e4)}),s.strictObject({type:s.literal("cancel")}),s.strictObject({type:s.literal("uncancel")}),s.strictObject({type:s.literal("billing_cycle"),billingCycleAnchor:s.union([s.literal("now"),s.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),Fn=s.string().regex(/^price_[A-Za-z0-9]+$/),Iu=s.strictObject({grooveUpdateId:s.uuid(),grooveCustomerId:s.uuid()}),vu=s.strictObject({price:Fn.nullable(),priceId:s.uuid().optional(),quantity:s.number().int().min(0).max(1e4)}),Tu=s.strictObject({provider:s.literal("stripe"),invoiceMode:Qt.optional(),executor:s.enum(["indiana","merchant"]),accountId:s.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:s.string().regex(/^sub_[A-Za-z0-9]+$/),action:s.enum(["update","cancel","schedule","release"]),update:s.strictObject({items:s.array(vu).max(20),remove:s.array(Fn).max(20),restoreItems:s.array(s.strictObject({price:Fn,quantity:s.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:s.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:s.number().int().positive().optional(),paymentBehavior:s.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:s.boolean().optional(),clearCancelAt:s.literal(!0).optional(),billingCycleAnchorNow:s.literal(!0).optional(),metadata:Iu}).nullable(),cancel:s.strictObject({prorate:s.literal(!1),invoiceNow:s.literal(!1)}).nullable(),schedule:s.strictObject({currentItems:s.array(s.strictObject({price:Fn,quantity:s.number().int().min(0).max(1e4)})).max(20),nextItems:s.array(vu).min(1).max(20),switchAt:s.number().int().positive(),interval:s.enum(["week","month","year"]),intervalCount:s.number().int().min(1).max(52),resetBillingCycleAnchor:s.literal(!0).optional(),metadata:Iu}).nullable(),release:s.strictObject({schedule:s.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:s.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),Sa=s.strictObject({carryOverBalances:Vn.optional(),carryOverUsages:Vn.optional(),operationId:s.uuid(),membershipId:s.uuid(),productVersionId:s.uuid(),timing:s.enum(["immediate","renewal"]),effectiveAt:s.iso.datetime({offset:!0}),expiresAt:s.iso.datetime({offset:!0}),currency:Y,creditMinor:Ve,debitMinor:Ve,discountMinor:Ve,taxMinor:Ve,totalMinor:Ve,retainedProductVersionIds:s.array(s.uuid()).max(19),execution:Tu}),VA=s.strictObject({operationId:s.uuid(),invoiceMode:s.boolean().optional(),membershipId:s.uuid(),productVersionId:s.uuid(),status:s.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:s.enum(["immediate","renewal"]),effectiveAt:s.iso.datetime({offset:!0}),checkoutUrl:s.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:s.enum(["indiana","merchant"]),execution:Tu.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),$A=s.strictObject({operationId:s.uuid(),membershipId:s.uuid(),productVersionId:s.uuid(),timing:s.literal("store"),effectiveAt:s.null(),expiresAt:s.iso.datetime({offset:!0}),currency:Y,creditMinor:s.null(),debitMinor:s.null(),discountMinor:s.null(),taxMinor:s.null(),totalMinor:s.null(),retainedProductVersionIds:s.array(s.uuid()).max(19),store:s.strictObject({provider:s.enum(["apple","google"]),productId:s.string().min(1).max(255),catalogAmountMinor:Ve,policy:s.enum(["apple_store","google_full_price"])})}),GA=s.strictObject({operationId:s.uuid(),membershipId:s.uuid(),productVersionId:s.uuid(),status:s.enum(["prepared","pending","effective","cancelled","failed"]),timing:s.literal("store"),effectiveAt:s.iso.datetime({offset:!0}).nullable(),checkoutUrl:s.null(),nativePurchase:Aa.nullable()}),ju=s.union([Sa,$A]),_a=s.union([VA,GA]),Wr=s.number().int().positive().max(2e8),Yt=s.number().int().min(0).max(2e8),Ru=s.strictObject({requestId:s.uuid(),invoiceId:s.uuid(),mode:s.enum(["full","partial"]),amountMinor:Wr.optional(),entitlementAction:s.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),ku=s.strictObject({provider:s.literal("stripe"),executor:s.enum(["indiana","merchant"]),accountId:s.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:s.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Wr,currency:s.string().regex(/^[a-z]{3}$/),metadata:s.strictObject({indianaRefundId:s.uuid()}),idempotencyKey:s.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:s.array(s.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Du=s.strictObject({operationId:s.uuid(),invoiceId:s.uuid(),providerInvoiceId:s.string().regex(/^in_[A-Za-z0-9]+$/),currency:Y,paidMinor:Yt,refundedMinor:Yt,pendingMinor:Yt,amountMinor:Wr,mode:s.enum(["full","partial"]),entitlementAction:s.enum(["retain","revoke"]),revokes:s.strictObject({customerProductIds:s.array(s.uuid()).max(100),subscriptionIds:s.array(s.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),execution:ku,expiresAt:s.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase()&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),$n=s.strictObject({operationId:s.uuid(),invoiceId:s.uuid(),providerInvoiceId:s.string().regex(/^in_[A-Za-z0-9]+$/),status:s.enum(["quoted","pending","succeeded","failed","expired"]),executor:s.enum(["indiana","merchant"]),currency:Y,amountMinor:Wr,mode:s.enum(["full","partial"]),entitlementAction:s.enum(["retain","revoke"]),refundId:s.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:ku.nullable(),failureReason:s.string().min(1).max(200).nullable(),createdAt:s.iso.datetime({offset:!0}),completedAt:s.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),w_=s.strictObject({invoiceId:s.uuid(),currency:Y,paidMinor:Yt,refundedMinor:Yt,pendingMinor:Yt,refundableMinor:Yt,executor:s.enum(["indiana","merchant"]).nullable(),canRefund:s.boolean(),operations:s.array($n).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),O_=s.strictObject({requestId:s.uuid(),mode:s.enum(["full","partial"]),amountMinor:Wr.optional(),entitlementAction:s.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var Nu=_e.strictObject({requestId:_e.uuid(),targets:_e.array(_e.strictObject({membershipId:_e.uuid(),action:_e.enum(["cancel","uncancel"]),timing:_e.enum(["immediate","renewal"])}).refine(e=>e.action!=="uncancel"||e.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(e=>new Set(e.targets.map(t=>t.membershipId)).size===e.targets.length,"Duplicate batch target"),Gn=_e.strictObject({batchId:_e.uuid()}),HA=_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:Sa.nullable(),managementUrl:_e.url().nullable(),failureCode:_e.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Qr=_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(HA).min(1).max(100)});import{z as ae}from"zod";var KA=ae.string().trim().min(1).max(240),xa={requestId:ae.uuid(),reason:KA},Hn=ae.discriminatedUnion("action",[ae.strictObject({...xa,action:ae.literal("start"),productVersionId:ae.uuid(),entityId:ae.uuid().optional(),days:ae.number().int().min(1).max(730).optional()}),ae.strictObject({...xa,action:ae.literal("extend"),membershipId:ae.uuid(),days:ae.number().int().min(1).max(730)}),ae.strictObject({...xa,action:ae.literal("end"),membershipId:ae.uuid()})]),Mu=ae.strictObject({operationId:ae.uuid()}),Uu=ae.iso.datetime({offset:!0}),ZA=ae.strictObject({provider:ae.literal("stripe"),executor:ae.enum(["indiana","merchant"]),accountId:ae.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:ae.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:ae.union([ae.literal("now"),Uu]),prorationBehavior:ae.literal("none")}),Ia=ae.strictObject({operationId:ae.uuid(),action:ae.enum(["start","extend","end"]),status:ae.enum(["pending","effective"]),managedBy:ae.enum(["indiana","stripe"]),membershipIds:ae.array(ae.uuid()).min(1).max(20),endsAt:Uu.nullable(),execution:ZA.nullable()}).refine(e=>e.execution!==null==(e.managedBy==="stripe"&&e.status==="pending")&&e.action==="end"==(e.endsAt===null)&&(e.action!=="start"||e.managedBy==="indiana")&&(e.execution===null||e.execution.trialEnd==="now"==(e.action==="end")),"Only a pending Stripe trial change carries execution instructions"),D_=ae.strictObject({groupId:ae.uuid(),productVersionId:ae.uuid(),enabled:ae.boolean()});import{z as be}from"zod";var qu=be.strictObject({requestId:be.uuid(),currency:Y,makeDefault:be.boolean()}),Lu=be.strictObject({setupId:be.uuid()}),WA=be.strictObject({provider:be.literal("stripe"),executor:be.literal("merchant"),accountId:be.string().regex(/^acct_[A-Za-z0-9]+$/),mode:be.literal("setup"),currency:be.string().regex(/^[a-z]{3}$/),customer:be.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:be.uuid(),metadata:be.strictObject({grooveProjectId:be.uuid(),grooveEnvironmentId:be.uuid(),grooveCustomerId:be.uuid(),groovePaymentSetupId:be.uuid()}),setDefaultPaymentMethod:be.boolean(),expiresAt:be.iso.datetime({offset:!0})}),va=be.strictObject({id:be.uuid(),provider:be.literal("stripe"),status:be.enum(["prepared","complete","expired"]),currency:Y,makeDefault:be.boolean(),url:be.url().nullable(),createdAt:be.iso.datetime({offset:!0}),expiresAt:be.iso.datetime({offset:!0}),completedAt:be.iso.datetime({offset:!0}).nullable(),execution:WA.nullable()});import{z as $e}from"zod";var Bu=$e.union([$e.string(),$e.number(),$e.boolean(),$e.null()]),Fu=$e.strictObject({customerId:$e.uuid()}),Vu=$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:Bu,actual:Bu})).max(1e4)});import{z}from"zod";var Kn=z.iso.datetime({offset:!0}),Zn=z.strictObject({createdAt:Kn,id:z.uuid()}),Wn=z.strictObject({customerId:z.uuid().optional(),entityId:z.uuid().optional(),productId:z.string().min(1).max(256).optional(),provider:z.enum(["stripe","apple","google","free"]).optional(),status:z.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Zn.optional(),limit:z.number().int().min(1).max(100).optional()}),Pa={id:z.uuid(),customerId:z.uuid(),entityId:z.uuid().nullable(),productId:z.string().min(1).max(256),productVersionId:z.uuid(),name:z.string().min(1).max(120),provider:z.enum(["stripe","apple","google","free"]),createdAt:Kn},QA=z.strictObject({...Pa,status:z.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:z.boolean(),billingSubscriptionId:z.uuid().nullable()}),YA=z.strictObject({...Pa,status:z.enum(["active","ended","refunded"]),orderId:z.uuid().nullable(),transactionId:z.uuid().nullable(),currency:Y.nullable(),amountMinor:z.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),JA=z.strictObject({...Pa,status:z.enum(["blocked","resolved"]),conflict:z.strictObject({detectedAt:Kn,blockingMembershipIds:z.array(z.uuid()).min(1).max(100),transactionId:z.uuid()}),resolvedAt:Kn.nullable()}),$u=Wn.extend({status:z.enum(["blocked","resolved"]).optional()}),Gu=z.strictObject({customerId:z.uuid(),orderId:z.uuid()}),Hu=z.strictObject({orderId:z.uuid(),status:z.enum(["blocked","resolved"])}),Ku=z.strictObject({items:z.array(QA).max(100),nextCursor:Zn.nullable()}),Zu=z.strictObject({items:z.array(YA).max(100),nextCursor:Zn.nullable()}),Wu=z.strictObject({items:z.array(JA).max(100),nextCursor:Zn.nullable()});import{z as Se}from"zod";var Qu=Se.union([Se.strictObject({intent:Se.literal("read"),requestId:Se.uuid(),purchaseIntentId:Se.uuid()}),Se.strictObject({requestId:Se.uuid(),provider:Se.literal("apple"),purchaseIntentId:Se.uuid(),productId:Se.string().min(1).max(255).optional(),signedTransaction:Se.string().min(1).max(131072)}),Se.strictObject({requestId:Se.uuid(),provider:Se.literal("google"),purchaseIntentId:Se.uuid(),productId:Se.string().min(1).max(255).optional(),purchaseToken:Se.string().min(1).max(16384)})]),Yu=Se.strictObject({requestId:Se.uuid(),orderId:Se.uuid(),purchaseIntentId:Se.uuid(),status:Se.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Y,refunded:Se.boolean(),completion:Se.strictObject({transactionIds:Se.array(Se.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Se.boolean()}).nullable()});import{z as w}from"zod";var wa=w.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),XA=w.record(w.string(),w.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),zA=3,Yr=20,eg=zA*Yr,Ca=w.strictObject({type:w.literal("product"),productId:wa}),Ju={type:w.literal("group"),key:w.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:w.string().trim().min(1).max(80)},tg=w.discriminatedUnion("type",[Ca,w.strictObject({...Ju,items:w.array(Ca).max(Yr)})]),rg=w.discriminatedUnion("type",[Ca,w.strictObject({...Ju,items:w.array(tg).max(Yr)})]),ng=w.array(rg).max(Yr).superRefine((e,t)=>{let r=new Set,n=new Set,i=0;function o(a){for(let c of a){i++;let l=c.type==="product"?r:n,p=c.type==="product"?c.productId:c.key;l.has(p)&&t.addIssue({code:"custom",message:c.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),l.add(p),c.type==="group"&&o(c.items)}}o(e),(r.size>Yr||i>eg)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Oa(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Oa(t))}var Ar=w.strictObject({lookupKey:w.string().trim().min(1).max(200),displayName:w.string().trim().min(1).max(1500),items:ng,metadata:XA}),ig=w.strictObject({product:w.record(w.string(),w.json()),prices:w.array(w.record(w.string(),w.json())),entitlements:w.array(w.record(w.string(),w.json())),freeTrials:w.array(w.record(w.string(),w.json())),licenses:w.array(w.record(w.string(),w.json()))}),Xu=Ar.extend({id:w.uuid(),projectId:w.uuid(),environmentId:w.uuid(),state:w.enum(["active","archived"]),isCurrent:w.boolean(),revision:w.number().int().nonnegative(),publishedVersionId:w.uuid().nullable(),createdAt:w.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),zu=w.strictObject({id:w.uuid(),offeringId:w.uuid(),projectId:w.uuid(),environmentId:w.uuid(),version:w.number().int().positive(),document:Ar,productEvidence:w.record(wa,ig),createdAt:w.iso.datetime({offset:!0})}).superRefine((e,t)=>{let r=Oa(e.document);(!r.length||sg(e.document).length>0||Object.keys(e.productEvidence).length!==r.length||r.some(n=>!Object.hasOwn(e.productEvidence,n)))&&t.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),ag=w.strictObject({rows:w.array(Xu).max(200),versions:w.array(zu).max(500)}),W_=w.discriminatedUnion("action",[w.strictObject({action:w.literal("create"),document:Ar}),w.strictObject({action:w.literal("save"),id:w.uuid(),revision:w.number().int().nonnegative(),document:Ar}),w.strictObject({action:w.enum(["publish","set_current","archive","restore"]),id:w.uuid(),revision:w.number().int().nonnegative()})]),Q_=w.strictObject({record:Xu,version:zu.nullable()}),el=w.discriminatedUnion("type",[w.strictObject({type:w.literal("current")}),w.strictObject({type:w.literal("id"),id:w.uuid()}),w.strictObject({type:w.literal("lookup_key"),lookupKey:w.string().min(1).max(200)}),w.strictObject({type:w.literal("version"),versionId:w.uuid()})]),og=w.strictObject({internalId:wa,id:w.string(),name:w.string().nullable(),version:w.number().int().positive(),archived:w.boolean()}),Y_=ag.extend({products:w.array(og).max(500)});function sg(e){let t=[];Oa(e).length||t.push("Select at least one Product before publishing");function r(n){for(let i of n)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),r(i.items))}return r(e.items),t}import{z as Qn}from"zod";var tl=Qn.strictObject({id:Qn.uuid(),offeringId:Qn.uuid(),version:Qn.number().int().positive(),document:Ar});import{z as De}from"zod";import{z as Z}from"zod";import{z as gr}from"zod";var Yn=gr.strictObject({items:gr.array(gr.strictObject({productVersionId:gr.string().min(1).max(200),label:gr.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:gr.string().min(1).max(200).nullable(),grouping:Un.optional()});import{z as ke}from"zod";var cg=ke.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Jn=ke.discriminatedUnion("type",[ke.object({type:ke.literal("fixed"),productVersionId:ke.string().min(1).max(200)}).strict(),ke.object({type:ke.literal("picker"),pickerId:cg,allowedProductVersionIds:ke.array(ke.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),Jr=ke.discriminatedUnion("type",[ke.object({type:ke.literal("modal"),size:ke.enum(["sm","md","lg"])}).strict(),ke.object({type:ke.literal("sheet"),size:ke.enum(["sm","md","lg"])}).strict(),ke.object({type:ke.literal("fullscreen")}).strict(),ke.object({type:ke.literal("inline")}).strict()]);var Ea=Z.discriminatedUnion("type",[Z.strictObject({type:Z.literal("event"),event:Z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),Z.strictObject({type:Z.literal("open_url"),url:Z.url().refine(e=>new URL(e).protocol==="https:")})]),ug=Wt,lg=Z.discriminatedUnion("type",[Z.object({type:Z.literal("checkout"),product:Jn}).strict(),Z.object({type:Z.literal("close")}).strict(),Z.object({type:Z.literal("action"),action:Ea}).strict()]),br=Z.object({schemaVersion:Z.literal(3),kind:Z.literal("paywall"),name:Z.string().trim().min(1).max(80),presentation:Jr,requirement:jt.optional(),products:Yn,offeringVersionId:Z.uuid().nullable(),offeringId:Z.uuid(),screen:ug,buttons:Z.record(Z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),lg)}).strict(),px=br.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(n=>!["event","navigate"].includes(n.type)||n.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let n of mg(e))t.addIssue({code:"custom",message:n});for(let n of dg(e))t.addIssue({code:"custom",message:n});pr(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(n=>n.type!=="navigate").length||e.screen.actions.some(n=>n.type!=="navigate"&&!Object.hasOwn(e.buttons,n.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(n=>n.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function dg(e){let t=e.products.items.map(o=>o.productVersionId),r=Kc(e.screen),n=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),e.offeringVersionId||i.push("offering"),e.products.grouping&&(!qn(e.products.grouping,t)||e.products.grouping.tiers.some(o=>!e.products.grouping.assignments.some(a=>a.tierId===o.id)))&&i.push("grouping");for(let o of Object.values(e.buttons))if(o.type==="checkout"){let a=o.product;if(a.type==="fixed")n.add(a.productVersionId);else{a.allowedProductVersionIds.forEach(p=>n.add(p));let c=!1,l=r[a.pickerId];l&&(c=!0,(a.allowedProductVersionIds.some(p=>!l.ids.includes(p))||l.ids.some(p=>!a.allowedProductVersionIds.includes(p)))&&i.push("picker")),ot(e.screen,p=>{if(p.id!==a.pickerId||p.type!=="plan_picker")return;c=!0,(JSON.stringify(p.planIds)!==JSON.stringify(t)||JSON.stringify(a.allowedProductVersionIds)!==JSON.stringify(t)||p.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let A=p.grouping?{tiers:p.grouping.tiers,assignments:p.grouping.assignments}:void 0;JSON.stringify(A)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),c||i.push("picker")}}return(!n.size||[...n].some(o=>!t.includes(o)))&&i.push("purchase"),ot(e.screen,o=>{o.type==="stack"&&o.productSlot&&!o.bind?.plan&&i.push(`productBinding:${o.id}`),(o.type==="stack"||o.type==="button")&&o.bind?.plan&&!t.includes(o.bind.plan)&&i.push("binding"),o.type==="plan_picker"&&(!o.planIds?.length||o.planIds.some(a=>!t.includes(a)))&&i.push("binding")}),[...new Set(i)]}function mg(e){let t=[],r=e.screen.pages.at(-1),n=new Map;for(let c of e.screen.pages)n.set(c.id,[]),Zr(c.root,l=>{let p=l.type==="button"?l.action:l.type==="stack"?l.purchaseAction:void 0;if(p){let A=e.screen.actions.find(k=>k.id===p);A?.type==="navigate"&&n.get(c.id).push(A.pageId);let v=e.buttons[p];c.id!==r.id&&v&&v.type!=="close"&&t.push(`purchaseScreen:${l.id}`)}c.id!==r.id&&(l.type==="plan_picker"||l.type==="stack"&&l.productSlot)&&t.push(`packageScreen:${l.id}`)});let i=new Set;function o(c){if(!i.has(c)){i.add(c);for(let l of n.get(c)??[])o(l)}}let a=e.screen.initialPageId??e.screen.pages[0]?.id;a?o(a):t.push("initialPage");for(let c of e.screen.pages)i.has(c.id)||t.push(`unreachableScreen:${c.id}`);return[...new Set(t)]}var rl=Z.object({id:Z.uuid(),projectId:Z.uuid(),environmentId:Z.uuid(),revision:Z.number().int().nonnegative(),state:Z.enum(["active","archived"]),publishedVersionId:Z.uuid().nullable(),updatedAt:Z.iso.datetime({offset:!0}),draft:br}).strict(),fx=Z.object({rows:Z.array(rl).max(200),nextCursor:Z.uuid().nullable()}).strict(),hx=rl.omit({draft:!0}).extend({name:Z.string(),productCount:Z.number().int().nonnegative()}).strict(),Ax=Z.discriminatedUnion("action",[Z.object({action:Z.literal("save"),id:Z.uuid().nullable(),revision:Z.number().int().nonnegative(),document:br}).strict(),Z.object({action:Z.enum(["publish","archive"]),id:Z.uuid(),revision:Z.number().int().nonnegative()}).strict()]),gx=Z.object({paywalls:Z.array(Z.object({id:Z.uuid(),paywallId:Z.uuid(),version:Z.number().int().positive(),name:Z.string().min(1).max(80),presentation:Jr,buttons:br.shape.buttons}).strict()).max(500),limited:Z.boolean()}).strict();import{z as ne}from"zod";import{z as We}from"zod";var yr=We.string().regex(/^[a-f0-9]{64}$/),pg=Nn.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),xx=We.strictObject({couponDigests:We.record(We.uuid(),yr),variables:We.record(ut,We.record(We.uuid(),We.partialRecord(We.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),We.string()))),locales:We.record(ut,Mn.extend({nodes:We.record(We.string(),We.strictObject({base:pg})),plans:We.object({}).strict(),pickers:We.object({}).strict()}).omit({paywall:!0}))});import{z as ue}from"zod";import{z as Xn}from"zod";var Ta=Xn.strictObject({eventsEnabled:Xn.boolean(),experimentViewsEnabled:Xn.boolean(),featureUsageEnabled:Xn.boolean()}),Px=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});import{z as O}from"zod";var ja=O.tuple([O.number().min(0).max(1),O.number().min(0).max(1)]).refine(([e,t])=>e<=t),fg=O.strictObject({attribute:O.string().optional(),seed:O.string(),hashVersion:O.literal(2),ranges:O.array(ja).max(100)}),hg=O.strictObject({id:O.string().min(1).max(255),condition:ct,gate:O.boolean().optional()}),Ag=O.strictObject({key:O.string().optional(),name:O.string().optional(),passthrough:O.boolean().optional()}),nl={condition:ct.optional(),parentConditions:O.array(hg).max(100).optional(),weights:O.array(O.number().min(0).max(1)).max(20).optional(),coverage:O.number().min(0).max(1).optional(),hashAttribute:O.string().optional(),fallbackAttribute:O.string().optional(),hashVersion:O.literal(2).optional(),disableStickyBucketing:O.boolean().optional(),bucketVersion:O.number().int().nonnegative().optional(),minBucketVersion:O.number().int().nonnegative().optional(),filters:O.array(fg).max(100).optional(),ranges:O.array(ja).max(20).optional(),meta:O.array(Ag).max(20).optional(),seed:O.string().optional(),name:O.string().optional(),phase:O.string().optional()},il=O.strictObject({...nl,key:O.string().min(1).max(255),variations:O.tuple([He,He]).rest(He).refine(e=>e.length<=20),urlPatterns:O.array(O.strictObject({include:O.boolean(),type:O.enum(["regex","simple"]),pattern:O.string()})).max(100).optional(),force:O.number().int().nonnegative().optional(),active:O.boolean().optional(),persistQueryString:O.boolean().optional()}),Ra=O.strictObject({value:He,variationId:O.number().int(),key:O.string(),name:O.string().optional(),bucket:O.number().optional(),passthrough:O.boolean().optional(),inExperiment:O.boolean(),hashUsed:O.boolean().optional(),hashAttribute:O.string(),hashValue:O.string(),featureId:O.string().nullable(),stickyBucketUsed:O.boolean().optional()}),gg=O.strictObject({...nl,id:O.string().max(255).optional(),force:He.optional(),variations:O.array(He).min(2).max(20).optional(),key:O.string().optional(),range:ja.optional(),tracks:O.array(O.strictObject({experiment:il,result:Ra})).max(100).optional()}),bg=O.strictObject({defaultValue:He.optional(),rules:O.array(gg).max(500).optional()}),yg=O.record(O.string(),O.union([O.strictObject({type:O.literal("hashed"),attributeKey:O.string(),values:O.array(O.string().regex(/^[a-f0-9]{64}$/))}),O.strictObject({type:O.literal("list"),attributeKey:O.string(),values:O.array(O.union([O.string(),O.number()]))}),O.strictObject({type:O.literal("condition"),condition:ct})])),Xr=O.strictObject({scope:Je,generation:O.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:O.iso.datetime({offset:!0}),expiresAt:O.iso.datetime({offset:!0}).nullable(),features:O.record(O.string(),bg),savedGroups:yg,experiments:O.record(O.uuid(),il)});var ka=Xr.extend({analyticsConfig:Ta,remoteFeatures:ue.array(ue.string().min(1).max(255)).max(500)}),Nx=ka.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let r of e.remoteFeatures)Object.hasOwn(e.features,r)&&t.addIssue({code:"custom",path:["features",r],message:"Remote Feature definitions cannot be public"});for(let[r,n]of Object.entries(e.savedGroups))n.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",r],message:"Raw Saved Group lists cannot be public"})}),al=ue.strictObject({attributes:At,features:ue.array(ue.string().min(1).max(255)).max(500).optional(),customerId:ue.uuid().optional()}),Sg=ue.strictObject({value:He,source:ue.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:ue.boolean(),off:ue.boolean(),ruleId:ue.string(),experimentResult:Ra.optional()}),ol=ue.strictObject({generation:Xr.shape.generation,evaluatedAt:Xr.shape.evaluatedAt,expiresAt:Xr.shape.expiresAt,features:ue.record(ue.string(),Sg),merchandiseContext:ue.strictObject({merchandiseId:ue.uuid(),merchandise:At}).optional()}),sl=ue.strictObject({customerId:ue.uuid().optional(),events:ue.array(ue.strictObject({eventUuid:ue.uuid(),timestamp:ue.iso.datetime({offset:!0}),name:ue.string().min(1).max(255),merchandise:Ls.optional(),properties:ue.record(ue.string(),He).default({}),deviceId:ue.string().min(1).max(255).optional(),sessionId:ue.string().min(1).max(255).optional()})).min(1).max(100)}),cl=ue.strictObject({inserted:ue.number().int().nonnegative(),duplicates:ue.number().int().nonnegative(),rejected:ue.number().int().nonnegative(),skipped:ue.number().int().nonnegative(),analyticsConfig:Ta});function ul(e,t=[]){let r=[];ot(e,i=>{i.hidden&&r.push("Hidden components must not be delivered"),t.includes(i.type)&&r.push(`Node type ${i.type} cannot be delivered`)});let n=new Set(fa(e).map(i=>i.key));for(let[i,o]of Object.entries(e.strings.locales))for(let a of Object.keys(o))n.has(a)||r.push(`Unused string ${a} must not be delivered (${i})`);return r}import{z as G}from"zod";var Da=G.array(G.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),zn=G.intersection(At,G.looseObject({tags:Da.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),ei=G.string().trim().max(80),ti=G.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),ri=G.union([G.email().max(254),G.literal("")]),ni=G.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),ll=G.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),dl=G.object({externalUserId:ll.optional(),name:ei.default(""),email:ri.default(""),phone:ti.optional(),attributes:zn.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Vx=G.discriminatedUnion("type",[G.strictObject({type:G.literal("id"),value:G.uuid()}),G.strictObject({type:G.literal("externalUserId"),value:ll})]),$x=G.strictObject({name:ei.optional(),email:ri.optional(),phone:ti.optional(),attributes:zn.optional(),fingerprint:ni.optional()});var Sr=G.object({id:G.uuid(),externalUserId:G.string().min(1).max(255).nullable(),name:ei,email:ri,phone:ti.optional(),attributes:zn,createdAt:G.iso.datetime()}).strict(),ml=G.object({customer:Sr,changed:G.boolean(),replayed:G.boolean()}).strict(),_g=G.discriminatedUnion("type",[G.object({type:G.literal("id"),value:G.uuid()}).strict(),G.object({type:G.literal("externalUserId"),value:G.string().trim().min(1).max(255)}).strict()]),xg=G.object({name:ei.optional(),email:ri.optional(),phone:ti.optional(),attributes:zn.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:G.array(G.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:G.strictObject({add:Da,remove:Da}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Na=G.object({lookup:_g}).strict(),pl=Na.extend({requestId:G.uuid(),patch:xg}).strict(),fl=G.object({search:G.string().trim().max(200).default(""),tag:G.string().trim().max(40).default(""),planId:G.string().max(200).default(""),versionId:G.string().max(200).default(""),holdingStatus:G.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:G.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:G.union([G.iso.datetime(),G.literal("")]).default(""),createdUntil:G.union([G.iso.datetime(),G.literal("")]).default(""),offset:G.coerce.number().int().min(0).max(1e5).default(0),limit:G.coerce.number().int().min(1).max(100).default(50)}).strict(),hl=G.object({customers:Sr.array(),hasMore:G.boolean(),total:G.number().int().nonnegative().nullable(),evaluatedAt:G.iso.datetime()}).strict();import{z as V}from"zod";import{z as zr}from"zod";var Al=zr.object({defaultLocale:ut,locales:zr.record(ut,zr.object({name:zr.string().max(80),description:zr.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let r=Object.keys(e.locales);(!r.length||r.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var Ig=["customer_data","coupon_code"],vg=V.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),gl=V.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),ii=(e,t)=>new Set(e.map(t)).size===e.length,Pg=V.strictObject({currency:Y,amountMinor:V.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Cg=V.strictObject({featureId:V.uuid(),name:V.string().trim().min(1).max(120),allowance:V.string().max(40).nullable(),access:V.boolean()}),wg=V.strictObject({stripe:V.strictObject({prices:V.array(Pg).min(1).max(50)}).optional(),apple:V.strictObject({productIds:V.array(vg).min(1).max(10)}).optional(),google:V.strictObject({products:V.array(V.strictObject({productId:gl,basePlanId:gl.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!ii(e.stripe.prices,r=>r.currency)||e.apple&&!ii(e.apple.productIds,r=>r)||e.google&&!ii(e.google.products,r=>`${r.productId}:${r.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),Og=V.strictObject({name:V.string().trim().min(1).max(80),interval:V.enum(["free","week","month","year","one_time"]),intervalCount:V.number().int().min(1).max(100),trial:V.strictObject({days:V.number().int().min(1).max(730),cardRequired:V.boolean()}).nullable(),benefits:V.array(Cg).max(50).refine(e=>ii(e,t=>t.featureId),"Duplicate benefit"),channels:wg}),Eg=V.strictObject({digest:yr,content:V.strictObject({discount:Ot,duration:et,appliesTo:Qi,displayCopy:Al.nullable(),firstPurchaseOnly:V.boolean(),qualificationRequired:V.boolean(),startsAt:V.iso.datetime().nullable(),endsAt:V.iso.datetime().nullable(),grantWindowHours:V.number().int().positive(),perCustomerLimit:V.number().int().positive()})}),Tg=V.discriminatedUnion("type",[V.strictObject({type:V.literal("checkout"),product:Jn}),V.strictObject({type:V.literal("close")}),V.strictObject({type:V.literal("action"),action:Ea})]),iI=V.strictObject({kind:V.literal("paywall"),formatVersion:V.literal(1),name:V.string().trim().min(1).max(80),offeringVersionId:V.uuid(),presentation:Jr,screen:Wt,products:Yn,catalog:V.record(V.uuid(),Og),buttons:V.record(se,Tg),coupons:V.record(V.uuid(),Eg)}).superRefine((e,t)=>{let r=q=>t.addIssue({code:"custom",message:q}),{screen:n}=e;n.surface!=="paywall"&&r("Screen must be a Paywall"),ul(n,Ig).forEach(r),pr(n).some(q=>!q.complete)&&r("Every published locale must be complete");let i=new Set,o=new Set,a=new Set;ot(n,q=>{let ve="bind"in q?q.bind:void 0;ve?.promotionCode&&r("Promotion codes must not be published"),ve?.plan&&i.add(ve.plan),ve?.coupon&&o.add(ve.coupon),q.type==="plan_picker"&&(q.planIds?.forEach(Ne=>i.add(Ne)),q.defaultPlan&&i.add(q.defaultPlan)),q.type==="text"&&q.feature&&a.add(q.feature.id)});let c=e.products.items.map(q=>q.productVersionId),l=Object.keys(e.catalog);(c.length!==l.length||c.some(q=>!Object.hasOwn(e.catalog,q)))&&r("Catalog must contain exactly the displayed Products");let p=new Set(c);e.products.defaultProductVersionId!==null&&!p.has(e.products.defaultProductVersionId)&&r("Default Product must be displayed");for(let q of i)p.has(q)||r("Screen references a Product that is not displayed");for(let q of Object.values(e.catalog))!q.channels.stripe&&!q.channels.apple&&!q.channels.google&&r("A displayed Product needs at least one sales channel");let A=new Set(Object.values(e.catalog).flatMap(q=>q.benefits.map(ve=>ve.featureId)));for(let q of a)A.has(q)||r("Feature text must read a displayed benefit");let v=n.actions.filter(q=>q.type!=="navigate");n.actions.some(q=>q.type!=="event"&&q.type!=="navigate")&&r("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==v.length||v.some(q=>!Object.hasOwn(e.buttons,q.id)))&&r("Buttons must match the screen's actions");let U=!1;for(let q of Object.values(e.buttons)){if(q.type!=="checkout")continue;U=!0,(q.product.type==="fixed"?[q.product.productVersionId]:q.product.allowedProductVersionIds).some(Ne=>!p.has(Ne))&&r("Checkout may only sell displayed Products")}U||r("A Paywall needs a checkout button");let ie=Object.keys(e.coupons);(ie.length!==o.size||ie.some(q=>!o.has(q)))&&r("Coupons must be exactly the bound Coupons")}),bl=V.strictObject({state:V.enum(["published","archived"]),controlRevision:V.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:V.uuid(),versions:V.record(V.uuid(),V.strictObject({version:V.number().int().positive(),artifact:V.string().min(1),sourceDigest:V.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var jg={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},Ma=ne.string().regex(/^[a-f0-9]{64}$/),Ua=ne.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Rg=Je.extend({environmentId:ne.uuid()}),kg=ne.strictObject({features:ne.array(ne.string()).max(500),experiments:ne.record(ne.uuid(),ne.array(ne.string()).max(20)),savedGroups:ne.array(ne.string()).max(1e3)}),qa=ne.strictObject({kind:ne.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:ne.number().int().positive(),url:ne.string().min(1).max(2048),sha256:Ma,byteLength:ne.number().int().positive().max(jg.maxArtifactBytes),generation:Ma.optional()}),Dg=ne.strictObject({state:ne.enum(["active","paused","archived"]),controlRevision:Ua,evaluationMode:ne.enum(["local","remote"]),evaluationRevision:Ua,currentVersionId:ne.uuid(),versions:ne.record(ne.uuid(),ne.strictObject({artifact:ne.string(),dependencies:kg,definitionDigest:yr.optional(),couponDigests:ne.record(ne.uuid(),yr).optional()}))}),lI=ne.strictObject({kind:ne.literal("sdk_configuration"),schemaVersion:ne.literal(1),scope:Rg,revision:Ua,generation:Ma,policy:ne.strictObject({refreshIntervalSeconds:ne.number().positive().max(15),maxControlAgeSeconds:ne.number().positive().max(60)}),gb:ne.strictObject({features:ne.string().nullable(),pageExperiments:ne.string().nullable()}),artifacts:ne.record(ne.string(),qa),funnels:ne.record(ne.uuid(),Dg),paywalls:ne.record(ne.uuid(),bl).optional()}).superRefine((e,t)=>{let r=(n,i)=>{n!==null&&e.artifacts[n]?.kind!==i&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};r(e.gb.features,"gb_features"),r(e.gb.pageExperiments,"gb_page_experiments");for(let n of Object.values(e.paywalls??{}))for(let i of Object.values(n.versions))r(i.artifact,"paywall");for(let n of Object.values(e.funnels)){n.evaluationMode==="remote"&&Object.keys(n.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),n.evaluationMode==="local"&&!n.versions[n.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let i of Object.values(n.versions))r(i.artifact,"funnel")}});var Sl=De.strictObject({...fr,selector:De.discriminatedUnion("type",[De.strictObject({type:De.literal("paywall"),paywallId:De.uuid()}),De.strictObject({type:De.literal("version"),versionId:De.uuid()})]),customerId:De.uuid().optional(),commerce:mr,locale:De.string().min(1).max(35),requirement:jt.optional()}),yl=De.strictObject({id:De.uuid(),paywallId:De.uuid(),version:De.number().int().positive(),document:br.omit({requirement:!0,offeringId:!0}),offering:De.strictObject({id:De.uuid()}),content:De.strictObject({environmentId:De.uuid(),offeringVersionId:De.uuid(),artifact:qa.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Mn,check:Kt.nullable()}).superRefine((e,t)=>{let r=new Set(e.document.products.items.map(n=>n.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(n=>!r.has(n.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),_l=De.strictObject(yl.shape).omit({document:!0,offering:!0}).extend({content:yl.shape.content.unwrap()});import{z as Qe}from"zod";var xl={requestId:Qe.uuid(),sourceId:Qe.uuid(),expectedAvailable:Ze},Il=Qe.discriminatedUnion("action",[Qe.strictObject({...xl,action:Qe.enum(["add","subtract","set_remaining"]),amount:W}),Qe.strictObject({...xl,action:Qe.literal("edit"),granted:W,expiresAt:Qe.iso.datetime({offset:!0}).nullable(),nextResetAt:Qe.iso.datetime({offset:!0}).nullable(),expectedRevision:Qe.number().int().nonnegative()})]),La=Qe.strictObject({sourceId:Qe.uuid(),available:Ze,held:Ze,spent:Ze,adjustmentGrantId:Qe.uuid().nullable()}),vl=La.extend({granted:Ze,expiresAt:Qe.iso.datetime({offset:!0}).nullable(),nextResetAt:Qe.iso.datetime({offset:!0}).nullable(),revision:Qe.number().int().nonnegative()});import{z as nt}from"zod";var Pl=nt.discriminatedUnion("action",[nt.object({action:nt.literal("upsert"),externalId:nt.string().min(1).max(128),name:nt.string().trim().min(1).max(80)}).strict(),nt.object({action:nt.literal("archive"),entityId:nt.uuid()}).strict()]),Cl=nt.object({id:nt.uuid(),externalId:nt.string().min(1).max(128),name:nt.string().min(1).max(80),archived:nt.boolean()}).strict();import{z as Ge}from"zod";import{z as zt}from"zod";var Ol=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],wl=zt.string().regex(/.+\/.+/),Ba=zt.number().min(-100),Xt=zt.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),Ng=zt.strictObject({input:Xt,output:Xt,cache_read:Xt.optional(),cache_write:Xt.optional(),reasoning:Xt.optional(),input_audio:Xt.optional(),output_audio:Xt.optional()}),Fa=(e,t)=>zt.record(e,t).refine(r=>Object.keys(r).length<=100,"At most 100 AI overrides"),wI=zt.strictObject({defaultMarkup:Ba,providerMarkups:Fa(zt.string().min(1),Ba),modelMarkups:Fa(wl,Ba),customModels:Fa(wl,Ng.partial())});import{z as X}from"zod";var er=X.iso.datetime({offset:!0}),kt=X.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Mg=X.discriminatedUnion("kind",[X.object({kind:X.literal("absolute"),from:er,to:er}).strict(),X.object({kind:X.literal("last_days"),days:X.union([X.literal(1),X.literal(7),X.literal(30),X.literal(90)])}).strict(),X.object({kind:X.literal("billing_cycles"),membershipId:X.uuid(),count:X.number().int().min(1).max(12),includeCurrent:X.boolean()}).strict()]),El=X.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),Ug=X.object({key:X.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:X.array(X.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),tr=X.object({range:Mg,timezone:El,filterBy:X.array(Ug).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:X.enum(["hour","day","week","month"]),internal_feature_id:X.uuid().nullable(),entityId:X.uuid().nullable(),topN:X.number().int().min(1).max(50).nullable(),groupBy:X.union([X.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),X.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:X.object({bucket:er,group:X.string().max(240),isOther:X.boolean(),internal_feature_id:X.uuid(),resourceId:X.uuid()}).strict().nullable(),limit:X.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let r=Date.parse(e.range.to)-Date.parse(e.range.from);(r<=0||r>366*864e5||e.interval==="hour"&&r>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),Tl=X.object({from:er,to:er,interval:X.enum(["hour","day","week","month"]),timezone:El,rows:X.array(X.object({bucket:er,group:X.string().max(240),isOther:X.boolean(),internal_feature_id:X.uuid(),resourceId:X.uuid(),consumedUnits:kt,refundedUnits:kt,reservedUnits:kt,charged:kt,refunded:kt,reserved:kt,netUnits:kt,netCharged:kt}).strict()).max(100),nextCursor:X.object({bucket:er,group:X.string().max(240),isOther:X.boolean(),internal_feature_id:X.uuid(),resourceId:X.uuid()}).strict().nullable()}).strict();var _r=Ge.string().regex(/^(0|[1-9]\d{0,29})$/),jl=Ge.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Va=Ge.strictObject({bucket:Ge.iso.datetime({offset:!0}),group:Ge.string().max(240),isOther:Ge.boolean(),internal_feature_id:Ge.uuid()}),Rl=Ge.strictObject({...tr.shape,groupBy:Ge.union([Ge.enum(["customer","entity","entitlement"]),Ge.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Va.nullable()}).superRefine((e,t)=>{let r=tr.safeParse({...e,after:null});if(!r.success)for(let n of r.error.issues)t.addIssue({code:"custom",path:n.path,message:n.message})}),kl=Ge.strictObject({from:Ge.iso.datetime({offset:!0}),to:Ge.iso.datetime({offset:!0}),interval:tr.shape.interval,timezone:tr.shape.timezone,rows:Ge.array(Ge.strictObject({...Va.shape,eventCount:_r,units:jl,tokenEventCount:_r,tokens:Ge.strictObject(Object.fromEntries(Ol.map(e=>[e,_r]))),totalTokens:_r,providerCostEventCount:_r,providerCostUsd:jl,invalidTelemetryEventCount:_r})).max(100),nextCursor:Va.nullable()});import{z as Te}from"zod";var Dl=Te.object({requestId:Te.uuid(),items:Te.array(Te.object({customerId:Te.uuid(),command:qr.options[1]}).strict()).min(1).max(1e3)}).strict().refine(e=>new Set(e.items.map(t=>t.customerId+":"+t.command.idempotencyKey)).size===e.items.length,"Each logical event must appear once in a batch"),Nl=Te.object({batchId:Te.uuid(),after:Te.number().int().min(-1).max(999),limit:Te.number().int().min(1).max(100)}).strict(),Ml=Te.object({batchId:Te.uuid(),status:Te.enum(["queued","complete"]),total:Te.number().int().min(1).max(1e3),processed:Te.number().int().min(0).max(1e3),items:Te.array(Te.object({position:Te.number().int().min(0).max(999),customerId:Te.uuid(),idempotencyKey:Te.string().min(1).max(120),status:Te.enum(["queued","accepted","rejected","failed"]),receipt:Lr.nullable(),errorCode:Te.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(e=>e.status==="queued"?e.receipt===null&&e.errorCode===null:e.status==="failed"?e.receipt===null&&e.errorCode!==null:e.receipt!==null&&e.errorCode===null&&e.receipt.accepted===(e.status==="accepted"))).max(100),nextAfter:Te.number().int().min(0).max(999).nullable()}).strict();import{z as h}from"zod";var qg=h.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Ul=h.enum(["draft","active","paused","archived"]),ql=h.string().min(1).max(256),Ll=h.array(ql).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),Lg=h.strictObject({duration:h.enum(["day","week","month","year"]),length:h.number().int().min(1).max(3660)}),Bg=h.strictObject({internal_feature_id:h.uuid(),allowance:h.number().nonnegative().max(1e15).nullable(),expiry:Lg.nullable()}),Fg=h.discriminatedUnion("type",[h.strictObject({type:h.literal("feature_grant"),grants:h.array(Bg).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),h.strictObject({type:h.literal("free_product"),productId:ql,duration:et}),h.strictObject({type:h.literal("invoice_credits"),amount:h.number().positive().max(1e8),duration:et,rollover:h.boolean(),productIds:Ll})]),Vg=h.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),Bl=h.object({key:Vg,name:h.string().trim().min(1).max(80),configuration:Fg}).strict(),Fl=h.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),$a=h.object({code:Fl,maxUses:h.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:h.boolean()}).strict(),Vl=h.object({key:h.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:h.string().trim().min(1).max(80),rewardId:h.uuid(),redeemOn:h.enum(["customer_creation","checkout"]),receivedBy:h.enum(["referrer","all"]),maxRedemptions:h.number().int().min(1).max(1e6).nullable(),productIds:Ll,excludeTrial:h.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),$l={id:h.uuid(),projectId:h.uuid(),environmentId:h.uuid(),revision:h.number().int().nonnegative(),status:Ul,createdAt:h.iso.datetime({offset:!0}),updatedAt:h.iso.datetime({offset:!0})},$g=Bl.extend($l).strict(),Gg=Vl.safeExtend($l).strict(),FI=h.strictObject({id:h.uuid(),key:h.string(),name:h.string(),type:qg,status:Ul}),VI=h.discriminatedUnion("action",[h.object({action:h.literal("save"),id:h.uuid().nullable(),revision:h.number().int().nonnegative(),input:Bl}).strict(),h.object({action:h.enum(["activate","pause","resume","archive","delete"]),id:h.uuid(),revision:h.number().int().nonnegative()}).strict()]),$I=h.discriminatedUnion("action",[h.object({action:h.literal("save"),id:h.uuid().nullable(),revision:h.number().int().nonnegative(),input:Vl}).strict(),h.object({action:h.enum(["activate","pause","resume","archive","delete"]),id:h.uuid(),revision:h.number().int().nonnegative()}).strict()]),Gl=h.object({id:h.uuid(),rewardId:h.uuid(),programId:h.uuid().nullable(),customerId:h.uuid(),referrerId:h.uuid().nullable(),status:h.enum(["pending","applied","unavailable"]),result:h.record(h.string(),h.unknown()).nullable(),createdAt:h.iso.datetime({offset:!0})}).strict(),Hl=h.object({code:Fl,requestId:h.uuid()}).strict(),Kl=h.strictObject({redemptionId:h.uuid(),currency:Y,requestId:h.uuid(),accepted:h.literal(!0)}),Hg=h.strictObject({type:h.literal("checkout"),orderId:h.uuid(),productVersionId:h.uuid(),currency:Y,duration:et,renewalAmountMinor:h.number().int().positive().max(1e8),status:h.enum(["created","pending","trialing","paid","cancelled","failed"]),url:h.url().nullable()}),Zl=h.discriminatedUnion("type",[Hg,h.strictObject({type:h.literal("subscription"),operationId:h.uuid(),membershipId:h.uuid(),productVersionId:h.uuid(),currency:Y,duration:et,renewalAmountMinor:h.number().int().positive().max(1e8),status:h.enum(["pending","running","applied","failed"])})]),Wl=h.object({programId:h.uuid(),requestId:h.uuid()}).strict(),Ql=h.object({id:h.uuid(),programId:h.uuid(),code:$a.shape.code,createdAt:h.iso.datetime({offset:!0})}).strict(),GI=h.object({rows:h.array($g).max(100),nextCursor:h.uuid().nullable()}).strict(),HI=h.object({rows:h.array(Gg).max(100),nextCursor:h.uuid().nullable()}).strict(),Kg=$a.extend({id:h.uuid(),redemptions:h.number().int().nonnegative()}).strict(),Zg=h.strictObject({id:h.uuid(),programId:h.uuid().nullable(),customerId:h.uuid().nullable(),referrerId:h.uuid().nullable(),code:h.string().nullable(),status:h.enum(["pending","triggered","applied"]),createdAt:h.iso.datetime({offset:!0})}),KI=h.object({codes:h.array(Kg).max(100),redemptions:h.array(Zg).max(100),customers:h.record(h.uuid(),h.string()),codesCursor:h.uuid().nullable(),redemptionsCursor:h.uuid().nullable()}).strict(),ZI=h.discriminatedUnion("action",[h.object({action:h.literal("create"),rewardId:h.uuid(),revision:h.number().int().nonnegative(),input:$a}).strict(),h.object({action:h.literal("remove"),rewardId:h.uuid(),revision:h.number().int().nonnegative(),codeId:h.uuid()}).strict()]);import{z as m}from"zod";import{z as j}from"zod";var bt={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},en=e=>new Set(e).size===e.length,Ga=j.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),Wg=j.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),tn=j.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),Qg=j.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Yl=j.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var Jl=j.strictObject({id:j.uuid(),repo:Wg,platform:j.enum(["github","gitlab","bitbucket"]),branches:j.array(tn).min(1).max(4).refine(en),workflow:j.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:j.array(j.uuid()).min(1).max(4).refine(en),include:j.array(Yl).min(1).max(16),exclude:j.array(Yl).max(16),methods:j.array(j.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(en),maxAgeHours:j.number().int().min(1).max(720)}),Xl=Jl.extend({revision:j.number().int().positive()}),YI=j.strictObject({repository:Jl,expectedRevision:j.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),zl=j.strictObject({repositoryId:j.uuid(),branch:tn}),Yg=j.array(Ga).max(bt.keys).refine(en),ed=j.strictObject({repository:Xl.omit({keyIds:!0}),branch:tn,keys:Yg,keySetHash:j.string().regex(/^[a-f0-9]{64}$/)}),Jg=j.strictObject({filePath:Qg,startingLineNumber:j.number().int().min(1).max(1e7)}),Ha=j.strictObject({protocol:j.literal(1),repositoryId:j.uuid(),branch:tn,workflow:j.string().max(200),configurationRevision:j.number().int().positive(),keySetHash:j.string().regex(/^[a-f0-9]{64}$/),commit:j.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:j.uuid(),runNumber:j.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:j.number().int().min(1).max(1e4),scannerVersion:j.literal("1"),scannedAt:j.iso.datetime({offset:!0}),coverage:j.strictObject({complete:j.literal(!0),files:j.number().int().min(0).max(bt.files),sourceBytes:j.number().int().min(0).max(bt.sourceBytes),unresolvedCalls:j.number().int().min(0).max(1e6),unsupportedFiles:j.number().int().min(0).max(bt.files)}),features:j.array(j.strictObject({key:Ga,refs:j.array(Jg).max(bt.referencesPerKey)})).max(bt.keys)}).superRefine((e,t)=>{en(e.features.map(r=>r.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((r,n)=>r+n.refs.length,0)>bt.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Ka=j.strictObject({scanId:j.uuid(),commit:j.string(),receivedAt:j.string(),references:j.number().int().nonnegative(),removedReferences:j.number().int().nonnegative()}),Xg=Ka.extend({repositoryId:j.uuid(),branch:tn,workflow:j.string(),digest:j.string(),configurationRevision:j.number().int().positive(),runNumber:j.number().int().positive(),runAttempt:j.number().int().positive(),scannedAt:j.string(),keySetHash:j.string(),coverage:Ha.shape.coverage}),zg=j.strictObject({repositories:j.array(Xl).max(bt.repositories),scans:j.array(Xg).max(bt.repositories*bt.branches)}),eb=j.strictObject({key:Ga,references:j.number().int().nonnegative(),coveredTargets:j.number().int().nonnegative(),expiredTargets:j.number().int().nonnegative(),uncertainTargets:j.number().int().nonnegative()}),JI=j.strictObject({available:j.boolean().default(!0),settings:zg,expectedTargets:j.number().int().min(0).max(80),features:j.array(eb).max(2001),truncated:j.boolean()});import{z as Ye}from"zod";var rd={customerId:Ye.uuid(),eventId:Ye.string().trim().min(1).max(200),grantId:Ye.uuid(),occurredAt:Ye.iso.datetime({offset:!0})},nd=Ye.strictObject({...rd,productVersionId:Ye.uuid(),subscriptionId:Ye.string().trim().min(1).max(255)}),id=Ye.strictObject({...rd,merchandiseId:Ye.uuid()}),ad=Ye.union([nd,id]),td={id:Ye.uuid(),couponId:Ye.uuid(),status:Ye.literal("redeemed"),source:Ye.literal("merchant"),recordedAt:Ye.iso.datetime({offset:!0})},od=Ye.union([nd.extend(td),id.extend(td)]);import{z as B}from"zod";var Za=B.strictObject({name:B.string().trim().min(1).max(255),memo:B.string().max(1e4).nullable().optional(),footer:B.string().max(1e4).nullable().optional(),net_terms_days:B.number().int().positive().nullable().optional()}),tb=Za.extend({id:B.string().min(1).max(255),created_at:B.number().nullable()}),sd=B.strictObject({items:B.array(tb).max(50),nextCursor:B.uuid().nullable()}),nv=B.discriminatedUnion("action",[B.strictObject({action:B.literal("create"),requestId:B.uuid(),values:Za}),B.strictObject({action:B.literal("update"),id:B.string().min(1).max(255),values:Za}),B.strictObject({action:B.literal("delete"),id:B.string().min(1).max(255)})]),cd=B.discriminatedUnion("action",[B.strictObject({action:B.literal("create"),requestId:B.uuid(),params:hr}),B.strictObject({action:B.enum(["finalize","send","pay","void"]),requestId:B.uuid(),invoiceId:B.uuid()}),B.strictObject({action:B.literal("reissue"),requestId:B.uuid(),invoiceId:B.uuid(),params:ga})]),Wa=B.strictObject({id:B.uuid(),customerId:B.uuid(),providerInvoiceId:B.string().nullable(),status:B.enum(["draft","open","paid","void","uncollectible"]),currency:B.string(),totalMinor:B.string().regex(/^-?\d+$/),paidMinor:B.string().regex(/^\d+$/),refundedMinor:B.string().regex(/^\d+$/),hostedInvoiceUrl:B.url().nullable(),createdAt:B.number(),collectionMethod:B.enum(["send_invoice","charge_automatically"]).nullable()}),ud=Wa.extend({lines:B.array(B.strictObject({id:B.uuid(),description:B.string(),amountMinor:B.string().regex(/^-?\d+$/),netAmountMinor:B.string().regex(/^-?\d+$/),quantity:B.number().nullable(),periodStart:B.number().nullable(),periodEnd:B.number().nullable()})).max(1e3)}),rn=B.strictObject({taskId:B.uuid(),status:B.enum(["ready","running","done","dead"]),invoice:Wa.nullable(),errorCode:B.string().nullable()}),ld=B.strictObject({items:B.array(Wa).max(50),nextCursor:B.uuid().nullable(),operations:B.array(rn).max(50),operationsLimited:B.boolean()});var rb=m.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"]),dd={scope:Je,permissions:m.array(rb),expiresAt:m.iso.datetime().nullable()},Zv=m.discriminatedUnion("kind",[m.object({...dd,kind:m.literal("server"),keyId:m.string().min(1)}),m.object({...dd,kind:m.literal("customer"),customerId:m.string().min(1),identityKind:m.enum(["identified","guest"]),expiresAt:m.iso.datetime()})]),P=m.object({requestId:m.uuid(),scope:Je}).strict(),nb=dl.safeExtend({fingerprint:ni.optional()}).strict(),ib=P.extend({customer:Sr,created:m.boolean()});function md(){return P.extend({offer:Yi.nullable(),reason:Fs.nullable()})}var _={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:qc,response:P.extend({message:m.object({messageId:m.uuid(),channel:$r,acceptedAt:m.iso.datetime({offset:!0}),status:m.enum(["accepted","sending","completed","canceled"]),replayed:m.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:m.strictObject({messageId:m.uuid()}),response:P.extend({message:m.object({id:m.uuid(),channel:$r,status:m.enum(["accepted","sending","completed","canceled"]),deliveries:m.array(m.object({id:m.uuid(),status:Bc,attempts:m.number().int().nonnegative(),receipts:m.array(m.object({kind:Fc,occurredAt:m.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:yo,response:P.extend({installation:Mt})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:So,response:P.extend({installation:Mt})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:dn,response:P.extend({installation:Mt})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:m.strictObject({channel:$r}),response:P.extend({preference:Ai})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Lc,response:P.extend({preference:Ai})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:m.strictObject({cursor:m.uuid().optional()}),response:P.extend({templates:sd})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:m.strictObject({customerId:m.uuid(),params:hr}),response:P.extend({preview:ba})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:m.strictObject({customerId:m.uuid(),requestId:m.uuid(),params:hr}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:P.extend({operation:rn})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:m.strictObject({customerId:m.uuid(),command:cd}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:P.extend({operation:rn})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:m.strictObject({customerId:m.uuid(),taskId:m.uuid()}),response:P.extend({operation:rn})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:m.strictObject({customerId:m.uuid(),cursor:m.uuid().optional()}),response:P.extend({invoices:ld})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:m.strictObject({customerId:m.uuid(),invoiceId:m.uuid()}),response:P.extend({invoice:ud})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:zl,response:P.extend({config:ed})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Ha,response:P.extend({receipt:Ka})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:m.strictObject({}),response:P.extend({payload:ka})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:al,response:P.merge(ol)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:sl,response:P.merge(cl)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:m.strictObject({customerId:m.uuid(),sourceId:m.uuid()}),response:P.extend({balance:vl})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:m.strictObject({customerId:m.uuid(),command:Il}),response:P.extend({balance:La})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:m.strictObject({internal_feature_id:m.uuid(),customerId:m.uuid().optional(),entityId:m.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:P.extend({internal_feature_id:m.uuid(),config:Vi,model_markups:Cn})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:m.strictObject({customerId:m.uuid(),query:kn}),response:P.extend({usage:Br})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:m.strictObject({customerId:m.uuid(),command:Oc}),response:P.extend({usage:Br})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:m.strictObject({customerId:m.uuid(),command:xc}),response:P.extend({grant:aa})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Ic,response:P.extend({grants:vc})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:m.union(Qu.options.map(e=>e.extend({customerId:m.uuid().optional(),customerToken:m.string().regex(Dn).optional()}))),response:P.extend({operation:Yu})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:qu.extend({customerId:m.uuid().optional()}),response:P.extend({setup:va})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Lu.extend({customerId:m.uuid().optional()}),response:P.extend({setup:va})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Nu.safeExtend({customerId:m.uuid()}),response:P.extend({batch:Qr})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Gn.extend({customerId:m.uuid()}),response:P.extend({batch:Qr})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Gn.extend({customerId:m.uuid()}),response:P.extend({batch:Qr})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Gn.extend({customerId:m.uuid()}),response:P.extend({batch:Qr})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:m.discriminatedUnion("action",[Hn.options[0].extend({customerId:m.uuid()}),Hn.options[1].extend({customerId:m.uuid()}),Hn.options[2].extend({customerId:m.uuid()})]),response:P.extend({trial:Ia})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Mu.extend({customerId:m.uuid()}),response:P.extend({trial:Ia})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Wn,response:P.extend({subscriptions:Ku})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Wn,response:P.extend({purchases:Zu})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:$u,response:P.extend({conflicts:Wu})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Gu,response:P.extend({resolution:Hu})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Fu,response:P.extend({verification:Vu})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Pu.safeExtend({...fr,customerId:m.uuid().optional()}),response:P.extend({quote:Ou})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Jt.extend({customerId:m.uuid().optional(),intent:m.enum(["confirm","cancel"]).optional()}),response:P.extend({operation:ya})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Jt.extend({customerId:m.uuid().optional()}),response:P.extend({operation:ya})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Eu.safeExtend({customerId:m.uuid().optional()}),response:P.extend({quote:ju})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Jt.extend({customerId:m.uuid().optional(),intent:m.enum(["confirm","cancel"]).optional()}),response:P.extend({operation:_a})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Jt.extend({customerId:m.uuid().optional()}),response:P.extend({operation:_a})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Ru.safeExtend({customerId:m.uuid()}),response:P.extend({quote:Du})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Jt.extend({customerId:m.uuid()}),response:P.extend({operation:$n})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Jt.extend({customerId:m.uuid()}),response:P.extend({operation:$n})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:oc,response:P.extend({controls:zi})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:zs,response:P.extend({prepared:tc})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:rc,response:P.extend({authorization:En})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:lc,response:P.extend({coupons:dc})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:nc,response:P.extend({authorization:En})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:cc,response:P.extend({invoices:uc})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:sc,response:P.extend({invoice:Rr})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:m.object({customerId:m.uuid(),command:ac}).strict(),response:P.extend({controls:zi})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:m.object({customerId:m.uuid(),command:Pl}).strict(),response:P.extend({entity:Cl})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:m.strictObject({customerId:m.uuid().nullable(),query:Rl}),response:P.extend({analytics:kl})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:m.object({customerId:m.uuid().nullable(),query:tr}).strict(),response:P.extend({analytics:Tl})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Dl,response:P.extend({batchId:m.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Nl,response:P.extend({batch:Ml})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Gc.extend({customerId:m.string().min(1).optional()}),response:P.extend({check:Kt})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:m.strictObject({kind:Rt,selector:m.discriminatedUnion("type",[m.strictObject({type:m.literal("resource"),id:m.uuid()}),m.strictObject({type:m.literal("version"),id:m.uuid()})]),customerId:m.string().min(1).optional()}),response:P.extend({content:ha})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Sl,response:P.extend({paywall:_l})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:m.strictObject({...fr,selector:el,customerId:m.string().min(1).optional(),commerce:mr,requirement:jt.optional()}),response:P.extend({offering:tl,candidates:m.array(la).max(20),availability:m.array(m.strictObject({productVersionId:m.uuid(),available:m.boolean(),reason:m.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:Kt.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:m.object({customerId:m.uuid().optional(),entityId:m.uuid().optional()}).strict(),response:P.extend({holdings:Ec})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:m.object({customerId:m.uuid().optional(),query:Rc}).strict(),response:P.extend({ledger:kc})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Pc.extend({customerId:m.uuid().optional()}),response:P.extend({detail:Cc})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:oa.safeExtend({customerId:m.uuid().optional()}),response:P.extend({statement:wc})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:m.object({customerId:m.uuid().optional(),command:qr.options[0]}).strict(),response:P.extend({quote:yc})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:m.strictObject({customerId:m.uuid(),command:m.union([m.strictObject({eventName:m.string().min(1),quantity:W.optional(),properties:Re.optional(),entityId:m.uuid().optional(),idempotencyKey:m.string().min(1).max(120)}),m.strictObject({internal_feature_id:m.uuid(),quantity:W.optional(),properties:Re.optional(),entityId:m.uuid().optional(),idempotencyKey:m.string().min(1).max(120)})])}),response:P.extend({receipts:m.array(Lr).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:m.object({customerId:m.uuid(),command:qr.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:P.extend({receipt:Lr})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Hl,response:P.extend({redemption:Gl})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Wl,response:P.extend({referralCode:Ql})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:Kl,response:P.extend({checkout:Zl})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Nc,response:P.extend({seats:ua})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Mc,response:P.extend({seats:ua})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:nb,response:ib},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Na,response:P.extend({customer:Sr})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:fl,response:P.extend(hl.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:pl,response:P.extend(ml.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:m.object({customerId:m.uuid()}).strict(),response:P.extend(lr.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:m.strictObject({}),response:P.extend(lr.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:m.strictObject({customerId:m.uuid(),sessionId:m.uuid().optional()}),response:P.extend({revoked:m.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:m.strictObject({guestToken:m.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:ni.optional()}),response:P.extend({customerId:m.uuid(),guestToken:m.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:m.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:m.strictObject({guestToken:m.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:P.extend(lr.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:m.strictObject({guestToken:m.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:m.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:m.uuid()}),response:P.extend({customer:Sr,switched:m.boolean(),replayed:m.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:m.strictObject({code:m.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:m.uuid()}),response:md()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:m.object({}).strict(),response:P.extend({offers:m.array(Yi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:m.object({customerId:m.string().min(1).max(255).optional(),couponId:m.uuid(),...fr,requestId:m.uuid(),couponContentDigest:m.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:md()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:ad,response:P.extend({receipt:od})}},Wv={sendMessage:_.sendMessage,readMessage:_.readMessage,bindPushInstallation:_.bindPushInstallation,readPushInstallation:_.readPushInstallation,updatePushAddress:_.updatePushAddress,readMessagingPreference:_.readMessagingPreference,setMessagingPreference:_.setMessagingPreference,listInvoiceTemplates:_.listInvoiceTemplates,previewInvoice:_.previewInvoice,createInvoice:_.createInvoice,manageInvoice:_.manageInvoice,readInvoiceOperation:_.readInvoiceOperation,listInvoices:_.listInvoices,getInvoice:_.getInvoice,getCodeReferenceConfig:_.getCodeReferenceConfig,submitCodeReferences:_.submitCodeReferences,getFeatures:_.getFeatures,evaluateFeatures:_.evaluateFeatures,trackEvents:_.trackEvents,setupPayment:_.setupPayment,readPaymentSetup:_.readPaymentSetup,previewSubscriptionBatch:_.previewSubscriptionBatch,confirmSubscriptionBatch:_.confirmSubscriptionBatch,readSubscriptionBatch:_.readSubscriptionBatch,abandonSubscriptionBatch:_.abandonSubscriptionBatch,manageSubscriptionTrial:_.manageSubscriptionTrial,readSubscriptionTrial:_.readSubscriptionTrial,listSubscriptions:_.listSubscriptions,listPurchases:_.listPurchases,listSubscriptionConflicts:_.listSubscriptionConflicts,retrySubscriptionConflict:_.retrySubscriptionConflict,readAiPricing:_.readAiPricing,readUsage:_.readUsage,setUsage:_.setUsage,previewRefund:_.previewRefund,refund:_.refund,readRefund:_.readRefund,previewUpdate:_.previewUpdate,update:_.update,readSubscriptionUpdate:_.readSubscriptionUpdate,restoreNativePurchase:_.restoreNativePurchase,verifySubscriptions:_.verifySubscriptions,previewAttach:_.previewAttach,attach:_.attach,readSubscriptionOperation:_.readSubscriptionOperation,manageBalanceGrant:_.manageBalanceGrant,readBalanceSource:_.readBalanceSource,adjustBalance:_.adjustBalance,listBalanceGrants:_.listBalanceGrants,readBillingControls:_.readBillingControls,prepareBillingAuthorization:_.prepareBillingAuthorization,confirmBillingAuthorization:_.confirmBillingAuthorization,setBillingCoupons:_.setBillingCoupons,revokeBillingAuthorization:_.revokeBillingAuthorization,listBillingInvoices:_.listBillingInvoices,confirmBillingAdjustment:_.confirmBillingAdjustment,manageBillingLimits:_.manageBillingLimits,createCustomer:_.createCustomer,getCustomer:_.getCustomer,listCustomers:_.listCustomers,updateCustomer:_.updateCustomer,createSession:_.createSession,refreshSession:_.refreshSession,revokeSessions:_.revokeSessions,createGuestCustomer:_.createGuestCustomer,resumeGuestSession:_.resumeGuestSession,claimGuestCustomer:_.claimGuestCustomer,checkEntitlement:_.checkEntitlement,resolveOffering:_.resolveOffering,resolveContent:_.resolveContent,resolvePaywall:_.resolvePaywall,readHoldings:_.readHoldings,readLedger:_.readLedger,readBillingInvoice:_.readBillingInvoice,readCreditStatement:_.readCreditStatement,quoteBalance:_.quoteBalance,trackUsage:_.trackUsage,mutateBalance:_.mutateBalance,manageUsageEntity:_.manageUsageEntity,readUsageAnalytics:_.readUsageAnalytics,readCreditAnalytics:_.readCreditAnalytics,submitUsageBatch:_.submitUsageBatch,readUsageBatch:_.readUsageBatch,listOffers:_.listOffers,grantOffer:_.grantOffer,recordCouponRedemption:_.recordCouponRedemption,redeemCoupon:_.redeemCoupon,redeemReward:_.redeemReward,createReferralCode:_.createReferralCode,claimRewardProduct:_.claimRewardProduct,readSeats:_.readSeats,manageSeat:_.manageSeat};var R=class extends Error{constructor(r,n,i,o,a){super(n);Ct(this,"code",r);Ct(this,"status",i);Ct(this,"requestId",o);Ct(this,"retryable");Ct(this,"recovery");Ct(this,"retryAfterSeconds");Ct(this,"reason");this.name="IndianaError",this.reason=a?.reason;let c=mn(r,i??0,{...a,retryAfter:a?.retryAfterSeconds===void 0?void 0:String(a.retryAfterSeconds)});this.retryable=c.retryable,this.recovery=c.recovery,this.retryAfterSeconds=c.retryAfterSeconds}};var nn=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new R("INVALID_STATE","Installation sequence exhausted");return e+1},ab=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(e,t=>t.charCodeAt(0))))].map(t=>t.toString(16).padStart(2,"0")).join("");function vt(e,t){return e.transaction(r=>{if(!Number.isSafeInteger(r.identitySeq)||r.identitySeq<0||!Number.isSafeInteger(r.addressSeq)||r.addressSeq<0||r.detachSeq!==null&&(!Number.isSafeInteger(r.detachSeq)||r.detachSeq<1||r.detachSeq>r.identitySeq))throw new R("INVALID_STATE","Installation journal is invalid");return t({...r})})}function pd(e,t,r){let n=null,i=0,o=0,a=0,c=Promise.resolve();if(e&&(!r||Je.parse(e.scope).projectId!==r.projectId||e.scope.environment!==r.environment))throw new R("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(!e)throw new R("NOT_CONFIGURED","Configure this client's native Push host first");return e},p=T=>{if(T!==i)throw new R("IDENTITY_CHANGED","Identity changed during Push operation")};async function A(T){let F=l();if(!F.sha256&&!globalThis.crypto?.subtle)throw new R("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let Q=F.sha256?await F.sha256(Uint8Array.from(T,he=>he.charCodeAt(0))):await ab(T);if(!/^[a-f0-9]{64}$/.test(Q))throw new R("INVALID_STATE","Push credential digest is invalid");return Q}function v(T){let F=Mt.parse(T);if(F.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new R("INVALID_RESPONSE","Push response belongs to another installation");return F}async function k(T,F){let Q=l(),he={installationId:Q.installationId,publicKey:Q.publicKey,issuedAt:new Date().toISOString(),...F},ge=await Q.sign(vo(T,Q.scope,he));return{...he,signature:ge}}let U=(T,F,Q)=>t.requestWithCredential?t.requestWithCredential(T,F,Q):t.request(T,F);async function ie(){let T=l(),F=i,Q=n?await(t.session?.access()??n):null,he=vt(T,Me=>Me),ge;if(he.detachSeq!==null){let Me=he.detachSeq,Ir=_o.parse(await k("detach",{sequence:Me,platform:T.platform}));try{let we=await t.request("push/installations/detach",{...T.scope,...Ir},"POST",{installationDetach:!0});if(!we||typeof we!="object"||!("installation"in we))throw new R("INVALID_RESPONSE","Push detach acknowledgement is invalid");let at=v(we.installation);if(at.bound||at.identitySeq!==Me)throw new R("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(we){if(we instanceof R&&we.status===404)ge=we;else if(!(we instanceof R)||we.status!==412)throw we}ge||vt(T,we=>({...we,detachSeq:we.detachSeq===Me?null:we.detachSeq}))}if(p(F),!Q){if(ge)throw ge;return null}let Ae=_.bindPushInstallation,Be=Ae.request.parse(await k("bind",{sequence:a,platform:T.platform,credentialDigest:await A(Q)}));p(F);let je=Ae.response.parse(await U(Ae.path,Be,Q));p(F);let st=v(je.installation);if(!st.bound||st.identitySeq!==a)throw new R("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return ge&&he.detachSeq!==null&&a>he.detachSeq&&vt(T,Me=>({...Me,detachSeq:Me.detachSeq===he.detachSeq?null:Me.detachSeq})),st}async function q(){l();let T=i,F=n?await(t.session?.access()??n):null;if(!F)throw new R("NOT_IDENTIFIED","Identify before reading this installation");let Q=_.readPushInstallation,he=Q.request.parse(await k("read",{credentialDigest:await A(F)}));p(T);let ge=Q.response.parse(await U(Q.path,he,F));return p(T),v(ge.installation)}function ve(T=ie){let F=c.catch(()=>{}).then(T);return c=F,F.catch(Q=>{try{e?.onError?.(Q instanceof Error?Q:new Error("Push synchronization failed"))}catch{}}),F}async function Ne(T,F,Q){let he=l(),ge=F.identity,Ae=F.observation,Be=n?await(t.session?.access()??n):null;if(p(ge),Ae!==o)throw new R("INVALID_STATE","Push observation changed during recovery");if(!Be)throw new R("NOT_IDENTIFIED","Identify before recovering a Push address");if(!T.connectionId||!T.kind||!T.token||!["granted","provisional"].includes(T.permission))throw new R("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await ve(async()=>{if(p(ge),await ie(),p(ge),Ae!==o)throw new R("INVALID_STATE","Push observation changed during recovery");let je=vt(he,at=>Q?at:{...at,addressSeq:nn(at.addressSeq)}),Me=await k(Q?"recovery_confirm":"recovery_request",{...T,sequence:je.addressSeq,credentialDigest:await A(Be),...Q?{challenge:Q}:{}}),Ir=Q?Io.parse(Me):xo.parse(Me);if(p(ge),Ae!==o)throw new R("INVALID_STATE","Push observation changed during recovery");let we=await U(`push/installations/recovery/${Q?"confirm":"request"}`,Ir,Be);if(p(ge),Ae!==o||vt(he,at=>at).addressSeq!==je.addressSeq)throw new R("INVALID_STATE","Push observation changed during recovery");if(Q){let at=_.updatePushAddress.response.parse(we),Pe=v(at.installation);if(!Pe.bound||Pe.identitySeq!==a||Pe.addressSeq!==je.addressSeq||Pe.connectionId!==T.connectionId||Pe.addressStatus!=="active")throw new R("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return Pe}if(!we||typeof we!="object"||!("recovery"in we))throw new R("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return hi.parse(we.recovery)})}return{recoveryObserver(){l();let T={identity:i,observation:++o};return{async request(F){return hi.parse(await Ne(F,T))},async confirm(F,Q){return Mt.parse(await Ne(Q,T,F))}}},identify(T){if(!e)return;a=vt(e,Q=>({...Q,identitySeq:nn(Q.identitySeq)})).identitySeq,n=T,i++,o++},reset(){if(e)try{vt(e,T=>{let F=nn(T.identitySeq);return{...T,identitySeq:F,detachSeq:F}})}finally{n=null,i++,o++}},start(){e&&ve()},async sync(){return await ve()},read:q,async recover(){let T=l(),F=i,Q=a;return o++,await ve(async()=>{p(F);let he=await q();return p(F),a=vt(T,Ae=>{if(Ae.identitySeq!==Q)throw new R("IDENTITY_CHANGED","A newer installation intent exists");return{...Ae,identitySeq:nn(Math.max(Ae.identitySeq,he.identitySeq)),addressSeq:Math.max(Ae.addressSeq,he.addressSeq)}}).identitySeq,await ie()})},tokenObserver(){l();let T=++o,F=i;return async Q=>{if(T!==o||F!==i)return null;let he=l(),ge=n?await(t.session?.access()??n):null;if(!ge)throw new R("NOT_IDENTIFIED","Identify before registering a Push token");if(await ve(),p(F),T!==o)return null;let Ae=vt(he,Me=>({...Me,addressSeq:nn(Me.addressSeq)})),Be=_.updatePushAddress,je=Be.request.parse(await k("address",{...Q,sequence:Ae.addressSeq,credentialDigest:await A(ge)}));if(p(F),T!==o)return null;let st=Be.response.parse(await U(Be.path,je,ge));return p(F),v(st.installation)}}}}function fd(e,t){return{messaging:{async preference(r){let n=_.readMessagingPreference;return n.response.parse(await e(n.path,n.request.parse({channel:r}))).preference},async setPreference(r){let n=_.setMessagingPreference;return n.response.parse(await e(n.path,n.request.parse(r))).preference}},push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){let r=_.readMessagingPreference;return r.response.parse(await e(r.path,{channel:"push"})).preference},async setPreference(r){let n=_.setMessagingPreference;return n.response.parse(await e(n.path,n.request.parse({...r,channel:"push"}))).preference}}}}function fe(e){return typeof e=="string"?e:String(e)}var ob=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function sb(e){return e.replace(ob,"$1\uFFFD")}function Xa(e,t){if(typeof e!="object"||e==null){let r="";throw r+="The provided value is not an object",new TypeError(r)}return e}function Id(e){if(e!=null&&(typeof e=="object"||typeof e=="function")){let t=e[Symbol.iterator];if(t==null)return;if(typeof t!="function")throw new TypeError("The provided value is not iterable");let r=t.call(e);if(!r||typeof r!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return r}}function hd(e){let t;if(Array.isArray(e)){let r=e.map(fe);if(r.length===2)return r}else if((t=Id(e))!=null){let r=Xa(t.next()),n=Xa(t.next());if(!r.done&&!n.done)return[fe(r.value),fe(n.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var Ad="0123456789ABCDEF",cb=/(?:%[0-9A-Fa-f]{2})+/g;function yt(e){return`%${Ad[e>>4&15]}${Ad[15&e]}`}function vd(e,t,r=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?r&&e===32?"+":t(e)?yt(e):String.fromCharCode(e):e<=2047?yt(192|e>>6)+yt(128|63&e):e<=65535?yt(224|e>>12)+yt(128|e>>6&63)+yt(128|63&e):yt(240|e>>18)+yt(128|e>>12&63)+yt(128|e>>6&63)+yt(128|63&e)}function za(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function eo(e,t=!1){let r=0;for(;r<e.length;r++){let n=e.charCodeAt(r);if(n===37||t&&n===43)break}return r===e.length?e:(t?e.replace(/\+/g," "):e).replace(cb,n=>{try{return decodeURIComponent(n)}catch{return"\uFFFD".repeat(n.length/3)}})}function sn(e){return e<=31||e>126}function ub(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return sn(e)}}function so(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return sn(e)}}function lb(e){return so(e)||e===39}function to(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return so(e)}}function ui(e){switch(e){case 47:case 58:case 59:case 61:case 64:case 91:case 92:case 93:case 124:return!0;default:return to(e)}}function gd(e){switch(e){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(r){switch(r){case 36:case 37:case 38:case 43:case 44:return!0;default:return ui(r)}})(e)}}function Pd(e,t){return vd(e=e||0,t)}function St(e,t,r=!1){let n=0;for(;n<e.length;n++){let o=e.charCodeAt(n);if(o>=128||r&&o===32||t(o))break}if(n===e.length)return e;let i=e.slice(0,n);for(;n<e.length;n++){let o=e.charCodeAt(n),a=o;if(o>=55296&&o<=56319&&n+1<e.length){let c=e.charCodeAt(n+1);c>=56320&&c<=57343&&(a=(o-55296<<10)+c-56320+65536,n++)}i+=vd(a,t,r)}return i}function co(e){let t=[],r=0,n=0;for(;n<=e.length;){if(n=e.indexOf("&",r),n<0&&(n=e.length),n!==r){let i=e.slice(r,n),o=i.indexOf("=");o<0&&(o=i.length),t.push([eo(i.slice(0,o),!0),eo(i.slice(o+1),!0)])}if(r=n+1,n===e.length)break}return t}function ro(e){let t="";for(let r=0;r<e.length;r++){let n=St(e[r][0],gd,!0),i=St(e[r][1],gd,!0);t+=r!==0?`&${n}=${i}`:`${n}=${i}`}return t}var db=[2191,2191,3164,3164,3292,3292,6863,6877,6880,6891,8385,8385,11158,11158,42958,42959,42962,42962,42964,42964,42993,42993,64451,64466,64912,64913,64968,64974,67904,67929,69317,69319,69328,69336,69370,69371,72544,72551,73136,73179,73184,73193,93856,93880,93883,93907,94194,94198,100344,100351,101641,101662,101760,101874,118010,118012,118458,118480,118496,118512,124608,124638,124640,124661,124670,124671,128728,128728,128887,128890,129232,129240,129620,129623,129674,129674,129678,129678,129736,129736,129741,129741,129770,129770,129775,129775,130042,130042,177978,177983,183970,183981,205744,210041],mb=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],pb=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],fb=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function hb(e){for(let t=0;t<e.length;t++){let r=e.codePointAt(t);if(r>65535&&t++,r<=32||r===37||r===127||r>=55296&&r<=57343||r>=128&&r<=159||r>=64976&&r<=65007||!(65534&~r)||r===65533)return!0}return!1}var[Ab,gb,bb,bd]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,r,n]){return[t,r.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(n),i=>i.charCodeAt(0))]});function yb(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function Cd(e,t){for(let r=0;r<e.length;r+=2)if(t>=e[r]&&t<=e[r+1])return!0;return!1}function an(e,t){let[r,n,i]=e,o=t>>8;for(let l=0;l<r.length;l+=2)if(o>=r[l]&&o<=r[l+1])return!0;let a=n.indexOf(o);if(a<0)return!1;let c=255&t;return!!(i[32*a+(c>>3)]&1<<(7&c))}function Sb(e){let t=Array.from(e,r=>r.codePointAt(0));for(let r=0;r<t.length;r++){let n=t[r];if(n!==8204&&n!==8205||r>0&&Cd(fb,t[r-1]))continue;if(n===8205)return!1;let i=r-1;for(;i>=0&&an(bd,t[i]);)i--;let o=r+1;for(;o<t.length&&an(bd,t[o]);)o++;if(!(i>=0&&o<t.length&&an(gb,t[i])&&an(bb,t[o])))return!1}return!0}var _b=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,xb=/\p{Script=Latin}/u;function Ib(e){return!_b.test(e)||!xb.test(e)}var Dt=36,oi=1,no=26,vb=38,Pb=700,Cb=72,wb=128,Ob=2147483647;function yd(e){return String.fromCharCode(e+22+75*+(e<26))}function Eb(e,t,r){let n=0;for(e=r?Math.floor(e/Pb):e>>1,e+=Math.floor(e/t);e>(Dt-oi)*no>>1;n+=Dt)e=Math.floor(e/(Dt-oi));return Math.floor(n+(Dt-oi+1)*e/(e+vb))}function Tb(e){let t=Array.from(e,l=>l.codePointAt(0)),r="",n=0;for(let l=0;l<t.length;l++){let p=t[l];p<128&&(r+=String.fromCharCode(p),n++)}let i=n;i&&(r+="-");let o=wb,a=0,c=Cb;for(;n<t.length;){let l=Ob;for(let p=0;p<t.length;p++){let A=t[p];A>=o&&A<l&&(l=A)}a+=(l-o)*(n+1),o=l;for(let p=0;p<t.length;p++){let A=t[p];if(A<o&&a++,A===o){let v=a;for(let k=Dt;;k+=Dt){let U=k<=c?oi:k>=c+no?no:k-c;if(v<U)break;r+=yd(U+(v-U)%(Dt-U)),v=Math.floor((v-U)/(Dt-U))}r+=yd(v),c=Eb(a,n+1,n===i),a=0,n++}}a++,o++}return r}function Qa(e){let t=10;if(e.length>=2&&e[0]==="0"&&(e[1]==="x"||e[1]==="X"))e=e.slice(2),t=16;else if(e.length>=2&&e[0]==="0")e=e.slice(1),t=8;else if(e==="")return-1;let r=0;for(let n=0;n<e.length;n++){let i=za(e.charCodeAt(n));if(i>=t||i<0)return-1;r=r*t+i}return r}function Sd(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function wd(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Od(e){return e.length===2&&wd(e.codePointAt(0),e.codePointAt(1))}function _d(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function Oe(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Ed(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function io(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(n){let i=[0,0,0,0,0,0,0,0],o=null,a=0,c=0,l=Array.from(n,p=>p.codePointAt(0));if(l[c]===58){if(l[c+1]!==58)return null;c+=2,a++,o=a}for(;c<l.length;){if(a===8)return null;if(l[c]===58){if(o!==null)return null;c++,a++,o=a;continue}let p=0,A=0,v=0;for(;v<4&&(p=za(l[c]))>=0;)A=(A<<4)+p,c++,v++;if(l[c]===46){if(v===0||a>6)return null;c-=v;let k=0;for(;l[c]!==void 0;){let U=0;if(k>0)if(l[c]===46&&k<4)c++;else return null;if(l[c]==null||l[c]<48||l[c]>57)return null;for(;l[c]>=48&&l[c]<=57;){if(U=10*U+za(l[c]),U>255)return null;c++}i[a]=256*i[a]+U,k++,k%2==0&&a++}if(k!==4)return null;break}else if(l[c]===58){if(l[++c]===void 0)return null}else if(l[c]!==void 0)return null;i[a]=A,a++}if(o!==null){let p=a-o;for(a=7;a!==0&&p>0;){let A=i[o+p-1];i[o+p-1]=i[a],i[a]=A,a--,p--}}else if(o===null&&a!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(n){return _d(n)?null:St(n,sn)})(e);{let r=(function(i){let o=!1,a=!1;for(let l=0;l<i.length;l++){let p=i.charCodeAt(l);if(p<=32||p===37||p===127)return null;if(p>=128){o=!0;break}p>=65&&p<=90&&(a=!0)}if(!o)return i!==""?a?i.toLowerCase():i:null;if((function(p){for(let A of p){let v=A.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(A)&&!Cd(db,v)||an(Ab,v))return!0}return!1})(i))return null;let c=(i=(function(p){let A="";for(let v of p){let k=v.codePointAt(0);if(k!==8204&&k!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(v))continue;let U=yb(v,k);if(U){A+=U;continue}let ie=mb.indexOf(k);A+=ie<0?v:pb[ie]}return A})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let l=0;l<c.length;l++){let p=c[l];if(p==="")continue;let A=/[^\0-\x7f]/.test(p);if(hb(p)||A&&(/^\p{Mark}/u.test(p)||!Sb(p)||!Ib(p)||p.startsWith("xn--")))return null;A&&(c[l]=`xn--${Tb(p)}`)}return(i=c.join("."))!==""?i:null})(e.indexOf("%")===-1?e:eo(e));return r===null||_d(r)?null:(function(i){let o=i.length,a=i.lastIndexOf(".",o-2)+1;if(i.charCodeAt(o-1)===46&&o--,o<=a)return!1;if(Qa(i.slice(a,o))>=0)return!0;for(;a<o;a++){let c=i.charCodeAt(a);if(c<48||c>57)return!1}return!0})(r)?(function(i){let o=i.split("."),a=o.length;if(o[a-1]||a--,a>4)return null;let c=0;for(let p=0;p<a-1;p++){let A=Qa(o[p]);if(A<0||A>255)return null;c+=A*(1<<8*(3-p))}let l=Qa(o[a-1]);return l<0||l>=256**(5-a)?null:(c+=l,c)})(r):r}}function ao(e){return typeof e=="number"?(function(r){let i="";return i+=`${(r>>>24&255).toString(10)}.`,i+=`${(r>>>16&255).toString(10)}.`,i+=`${(r>>>8&255).toString(10)}.`,i+=(r&255).toString(10),i})(e):Array.isArray(e)?`[${(function(r){let n=(function(c){let l=-1,p=-1,A=1,v=0;for(let k=0;k<c.length;++k)c[k]!==0?(v>A&&(l=p,A=v),p=-1,v=0):(p===-1&&(p=k),++v);return v>A?p:l})(r),i="",o=!1;for(let a=0;a<=7;++a)if(!(o&&r[a]===0)){if(o&&(o=!1),n===a){i+=a===0?"::":":",o=!0;continue}i+=r[a].toString(16),a!==7&&(i+=":")}return i})(e)}]`:e}function Td(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(r){return/^[A-Za-z]:$/u.test(r)})(e.path[0]))&&e.path.pop()}function jd(e){return e.username!==""||e.password!==""}function Ya(e){return e.host===null||e.host===""||e.scheme==="file"}var f=0,x="",ee="",le=null,I,si=!1,ci=!1,rr=!1,Ee;function it(e,t,r,n){t||(e=(function(a){let c=0,l=a.length;for(;c<l&&!(a.charCodeAt(c)>32);++c);for(;l>c&&!(a.charCodeAt(l-1)>32);--l);return a.substring(c,l)})(e)),e=(function(a){let c=0;for(;c<a.length;c++){let p=a.charCodeAt(c);if(p===9||p===10||p===13)break}if(c===a.length)return a;let l=a.slice(0,c);for(;c<a.length;c++){let p=a.charCodeAt(c);p!==9&&p!==10&&p!==13&&(l+=a[c])}return l})(e),f=0,x=e,ee="",le=r||null,I=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},si=!1,ci=!1,rr=!1,Ee=n||0;let i=jb;switch(n){case 3:case 4:i=li;break;case 5:i=lo;break;case 6:i=nr;break;case 7:i=Nt;break;case 8:i=_t}return i(E(e,f))!==1?I:null}function D(e,t){return f+=f===e?ft(t):1,f<=x.length}function E(e,t){return t<e.length?e.codePointAt(t):void 0}function ft(e){return e!=null&&e>65535?2:1}function Rd(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var jb=e=>{let t=f;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let r=f+1;for(e=x.charCodeAt(r);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)r++,e=x.charCodeAt(r);return ee=x.slice(f,r).toLowerCase(),f=r,Rb(r<x.length?e:void 0)}else return Ee?1:(--f,D(t,e)?kd(E(x,f)):0)},Rb=e=>{let t=f;if(e===58){if(Ee){if(Oe(I.scheme)!==Oe(ee))return 0;if((jd(I)||I.port!==null)&&ee==="file")return 0;if(I.scheme==="file"&&I.host==="")return 0}return I.scheme=ee,Ee?(I.port===Ed(I.scheme)&&(I.port=null),0):(ee="",I.scheme==="file"?D(t,e)?mo(E(x,f)):0:Oe(I.scheme)&&le!==null&&le.scheme===I.scheme?D(t,e)?kb(E(x,f)):0:Oe(I.scheme)?D(t,e)?Nb(E(x,f)):0:E(x,f+1)===47?(f++,D(t,e)?Db(E(x,f)):0):(I.path=[""],I.opaquePath=!0,D(t,e)?Nd(E(x,f)):0))}else return Ee?1:(ee="",f=-1,D(t,e)?kd(E(x,f)):0)},kd=e=>{let t=f;return le===null||le.opaquePath&&e!==35?1:le.opaquePath&&e===35?(I.scheme=le.scheme,I.path=le.path.slice(),I.opaquePath=le.opaquePath,I.query=le.query,I.fragment="",D(t,e)?_t(E(x,f)):0):le.scheme==="file"?(f--,D(t,e)?mo(E(x,f)):0):(f--,D(t,e)?uo(E(x,f)):0)},kb=e=>{let t=f;return e===47&&E(x,f+1)===47?(++f,D(t,e)?mi(E(x,f)):0):(f--,D(t,e)?uo(E(x,f)):0)},Db=e=>{let t=f;return e===47?D(t,e)?xr(E(x,f)):0:(f--,D(t,e)?ht(E(x,f)):0)},uo=e=>{let t=f;return I.scheme=le.scheme,e===47||Oe(I.scheme)&&e===92?D(t,e)?xd(E(x,f)):0:(I.username=le.username,I.password=le.password,I.host=le.host,I.port=le.port,I.path=le.path.slice(),I.query=le.query,e===63?(I.query="",D(t,e)?Nt(E(x,f)):0):e===35?(I.fragment="",D(t,e)?_t(E(x,f)):0):e!=null?(I.query=null,I.path.pop(),f--,D(t,e)?ht(E(x,f)):0):D(t,e)?uo(E(x,f)):0)},xd=e=>{let t=f;return Oe(I.scheme)&&(e===47||e===92)?D(t,e)?mi(E(x,f)):0:e===47?D(t,e)?xr(E(x,f)):0:(I.username=le.username,I.password=le.password,I.host=le.host,I.port=le.port,f--,D(t,e)?ht(E(x,f)):0)},Nb=e=>{let t=f;return e===47&&E(x,f+1)===47?f++:f--,D(t,e)?mi(E(x,f)):0},mi=e=>{let t=f;return e!==47&&e!==92?(f--,D(t,e)?xr(E(x,f)):0):D(t,e)?mi(E(x,f)):0},xr=e=>{let t=f;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!Oe(I.scheme))){let r=f+ft(e);for(;r<x.length;){let n=E(x,r);if(n==null||n===64||n===35||n===47||n===63||n===92&&Oe(I.scheme))break;r+=ft(n)}return ee+=x.slice(f,r),f=r-1,D(t,e)?xr(E(x,f)):0}if(e===64){si&&(ee=`%40${ee}`),si=!0;for(let r=0;r<ee.length;r++){let n=ee.codePointAt(r);if(n===58&&!ci){ci=!0;continue}let i=Pd(n,ui);ci?I.password+=i:I.username+=i,n!=null&&n>65535&&r++}return ee="",D(t,e)?xr(E(x,f)):0}else return e==null||e===35||e===47||e===63||e===92&&Oe(I.scheme)?si&&ee===""?1:(f-=ee.length+1,ee="",D(t,e)?li(E(x,f)):0):(ee+=Rd(e),D(t,e)?xr(E(x,f)):0)},li=e=>{let t=f;if(Ee&&I.scheme==="file")return f--,D(t,e)?po(E(x,f)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!Oe(I.scheme))){let r=f+ft(e);for(e===91?rr=!0:e===93&&(rr=!1);r<x.length;){let n=E(x,r);if(n==null||!rr&&n===58||n===35||n===47||n===63||n===92&&Oe(I.scheme))break;n===91?rr=!0:n===93&&(rr=!1),r+=ft(n)}return ee+=x.slice(f,r),f=r-1,D(t,e)?li(E(x,f)):0}else if(e===58&&!rr){if(ee===""||Ee===4)return 1;let r=io(ee,!Oe(I.scheme));return r===null?1:(I.host=ao(r),ee="",D(t,e)?lo(E(x,f)):0)}else if(e==null||e===35||e===47||e===63||e===92&&Oe(I.scheme)){if(f--,Oe(I.scheme)&&ee==="")return 1;if(Ee&&ee===""&&(jd(I)||I.port!==null))return 1;let r=io(ee,!Oe(I.scheme));return r===null?1:(I.host=ao(r),ee="",Ee?0:D(t,e)?nr(E(x,f)):0)}else return ee+=Rd(e),D(t,e)?li(E(x,f)):0},lo=e=>{let t=f;if(e!=null&&e>=48&&e<=57){let r=f+1;for(;r<x.length;){let n=x.charCodeAt(r);if(n<48||n>57)break;r++}return ee+=x.slice(f,r),f=r-1,D(t,e)?lo(E(x,f)):0}else if(Ee||e==null||e===35||e===47||e===63||e===92&&Oe(I.scheme)){if(ee!==""){let r=parseInt(ee,10);if(r>65535)return 1;if(I.port=r===Ed(I.scheme)?null:r,ee="",Ee)return 0}return Ee?1:(f--,D(t,e)?nr(E(x,f)):0)}else return 1};function Dd(e,t){let r=e.length-t;if(r<2)return!1;if(wd(E(e,t),E(e,t+1))){if(r===2)return!0;{let n=E(e,t+2);return n===47||n===92||n===63||n===35}}else return!1}var mo=e=>{let t=f;return I.scheme="file",I.host="",e===47||e===92?D(t,e)?Mb(E(x,f)):0:le?.scheme==="file"?(I.host=le.host,I.path=le.path.slice(),I.opaquePath=le.opaquePath,I.query=le.query,e===63?(I.query="",D(t,e)?Nt(E(x,f)):0):e===35?(I.fragment="",D(t,e)?_t(E(x,f)):0):e!=null?(I.query=null,Dd(x,f)?I.path=[]:Td(I),f--,D(t,e)?ht(E(x,f)):0):D(t,e)?mo(E(x,f)):0):(f--,D(t,e)?ht(E(x,f)):0)},Mb=e=>{let t=f;return e===47||e===92?D(t,e)?po(E(x,f)):0:(le!==null&&le.scheme==="file"&&(!Dd(x,f)&&(function(n){if(n.length===2){let i=n.codePointAt(0),o=n.codePointAt(1);return(i>=65&&i<=90||i>=97&&i<=122)&&o===58}else return!1})(le.path[0])&&I.path.push(le.path[0]),I.host=le.host),f--,D(t,e)?ht(E(x,f)):0)},po=e=>{let t=f;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let r=f+ft(e);for(;r<x.length;){let n=E(x,r);if(n==null||n===47||n===92||n===63||n===35)break;r+=ft(n)}return ee+=x.slice(f,r),f=r-1,D(t,e)?po(E(x,f)):0}else if(e==null||e===47||e===92||e===63||e===35){if(f--,!Ee&&Od(ee))return D(t,e)?ht(E(x,f)):0;if(ee==="")return I.host="",Ee?0:D(t,e)?nr(E(x,f)):0;{let r=io(ee,!Oe(I.scheme));return r===null?1:(r==="localhost"&&(r=""),I.host=ao(r),ee="",Ee?0:D(t,e)?nr(E(x,f)):0)}}return 1},nr=e=>{let t=f;return Oe(I.scheme)?(e!==92&&e!==47&&f--,D(t,e)?ht(E(x,f)):0):!Ee&&e===63?(I.query="",D(t,e)?Nt(E(x,f)):0):!Ee&&e===35?(I.fragment="",D(t,e)?_t(E(x,f)):0):e!=null?(e!==47&&f--,D(t,e)?ht(E(x,f)):0):(Ee&&I.host===null&&I.path.push(""),D(t,e)?nr(E(x,f)):0)},ht=e=>{let t=f;if(e!=null&&e!==47&&(!Oe(I.scheme)||e!==92)&&(Ee||e!==63&&e!==35)){let r=f+ft(e);for(;r<x.length;){let n=E(x,r);if(n==null||n===47||Oe(I.scheme)&&n===92||!Ee&&(n===63||n===35))break;r+=ft(n)}ee+=St(x.slice(f,r),to),f=r,e=E(x,r)}if(e==null||e===47||Oe(I.scheme)&&e===92||!Ee&&(e===63||e===35)){let r=Oe(I.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(ee)?(Td(I),e!==47&&!r&&I.path.push("")):Sd(ee)&&e!==47&&!r?I.path.push(""):Sd(ee)||(I.scheme==="file"&&I.path.length===0&&Od(ee)&&(ee=`${ee[0]}:`),I.path.push(ee)),ee="",e===63?(I.query="",D(t,e)?Nt(E(x,f)):0):e===35?(I.fragment="",D(t,e)?_t(E(x,f)):0):D(t,e)?ht(E(x,f)):0}else return ee+=Pd(e,to),D(t,e)?ht(E(x,f)):0},Nd=e=>{let t=f;if(e===63)return I.query="",D(t,e)?Nt(E(x,f)):0;if(e===35)return I.fragment="",D(t,e)?_t(E(x,f)):0;if(e!=null){let r=f+ft(e);for(;r<x.length;){let i=E(x,r);if(i===63||i===35)break;r+=ft(i)}let n=x.slice(f,r);if(r<x.length&&n.charCodeAt(n.length-1)===32?I.path[0]+=St(n.slice(0,-1),sn)+"%20":I.path[0]+=St(n,sn),f=r,(e=E(x,r))===63)return I.query="",D(t,e)?Nt(E(x,f)):0;if(e===35)return I.fragment="",D(t,e)?_t(E(x,f)):0}return D(t,e)?Nd(E(x,f)):0},Nt=e=>{let t=f,r=f;if(e!=null){if(Ee)r=x.length;else{let i=x.indexOf("#",f);r=i===-1?x.length:i}let n=Oe(I.scheme)?lb:so;I.query+=St(x.slice(f,r),n)}return f=r,E(x,r)===35&&!Ee?(I.fragment="",D(t,e)?_t(E(x,f)):0):D(t,e)?Nt(E(x,f)):0},_t=e=>{let t=f;return e!=null&&(I.fragment+=St(x.slice(f),ub),f=x.length),D(t,e)?_t(E(x,f)):0};function oo(e){if(e.opaquePath)return e.path[0];{let t="";for(let r of e.path)t+=`/${r}`;return t}}function Md(e){switch(e.scheme){case"blob":{let t=it(oo(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Md(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(r){let n=`${r.scheme}://`;return n+=r.host,r.port!==null&&(n+=`:${r.port}`),n})(e);default:return"null"}}var pe=Symbol("URLImpl"),cn=class e{constructor(t,r){if(t===void 0&&r===void 0)throw new TypeError('The "url" argument must be specified.');t=fe(t),r!=null&&(r=fe(r));let n=null;if(r!=null&&(n=it(r,null,null,0),n==null))throw new TypeError(`Invalid base URL: ${r}`);let i=it(t,null,n,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[pe]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,r){t=fe(t),r!==void 0&&(r=fe(r));try{return new e(t,r)}catch{return null}}static canParse(t,r){t=fe(t),r!==void 0&&(r=fe(r));let n=null;return r!=null&&(n=it(r,null,null,0),n==null)?!1:it(t,null,n,0)!=null}get href(){return(function(r){let n=`${r.scheme}:`;return r.host!==null&&(n+="//",(r.username!==""||r.password!=="")&&(n+=r.username,r.password!==""&&(n+=`:${r.password}`),n+="@"),n+=r.host,r.port!==null&&(n+=`:${r.port}`)),r.host===null&&!r.opaquePath&&r.path.length>1&&r.path[0]===""&&(n+="/."),n+=oo(r),r.query!==null&&(n+=`?${r.query}`),r.fragment!==null&&(n+=`#${r.fragment}`),n})(this[pe].url)}set href(t){let r=it(t=fe(t),null,null,0);if(r==null)throw new TypeError(`Invalid URL: ${t}`);this[pe].url=r,this[pe].query&&Ja(this[pe].query,r.query)}get origin(){return Md(this[pe].url)}get protocol(){return`${this[pe].url.scheme}:`}set protocol(t){it(`${t=fe(t)}:`,this[pe].url,null,2)}get username(){return this[pe].url.username}set username(t){t=fe(t),Ya(this[pe].url)||(function(n,i){n.username=St(i,ui)})(this[pe].url,t)}get password(){return this[pe].url.password}set password(t){t=fe(t),Ya(this[pe].url)||(function(n,i){n.password=St(i,ui)})(this[pe].url,t)}get host(){let{url:t}=this[pe];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=fe(t),this[pe].url.opaquePath||it(t,this[pe].url,null,3)}get hostname(){let{url:t}=this[pe];return t.host!=null?t.host:""}set hostname(t){t=fe(t),this[pe].url.opaquePath||it(t,this[pe].url,null,4)}get port(){let{url:t}=this[pe];return t.port!=null?`${t.port}`:""}set port(t){t=fe(t);let{url:r}=this[pe];Ya(r)||(t?it(t,r,null,5):r.port=null)}get pathname(){return oo(this[pe].url)}set pathname(t){t=fe(t);let{url:r}=this[pe];r.opaquePath||(r.path=[],it(t,r,null,6))}get search(){let{url:t}=this[pe];return t.query?`?${t.query}`:""}set search(t){t=fe(t);let{url:r,query:n}=this[pe];if(!t)r.query=null,n&&Ja(n,null);else{let i=t[0]==="?"?t.substring(1):t;r.query="",it(i,r,null,7),n&&Ja(n,r.query)}}get searchParams(){let t=this[pe],r=t.query;return r==null&&(r=t.query=(function(i,o){let a=new di;return a[xe].url=i,a[xe].serialized=o==null,o&&(a[xe].list=co(o)),a})(this,t.url.query)),r}get hash(){let{url:t}=this[pe];return t.fragment?`#${t.fragment}`:""}set hash(t){t=fe(t);let{url:r}=this[pe];if(!t)r.fragment=null;else{let n=t[0]==="#"?t.substring(1):t;r.fragment="",it(n,r,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(cn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var xe=Symbol("URLSearchParamsImpl"),Ub=Symbol.dispose||Symbol.for("dispose");function Ja(e,t){t?e[xe].list=co(t):e[xe].list.length=0,e[xe].serialized=t==null}function ai(e){if(e.url){let t=ro(e.list);(function(n,i){n[pe].url.query=i})(e.url,t||null),e.serialized=!0}}var qb=typeof Iterator<"u"?Iterator:Object,on=class extends qb{constructor(t,r){super(),this[xe]={ptr:t,map:r,index:0}}next(){let t=this[xe];return t.index<t.ptr.list.length?{value:t.map(t.ptr.list[t.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[Ub](){}},di=class{constructor(t){let r=this[xe]={list:[],url:null,serialized:!0},n;if(Array.isArray(t))for(let i=0;i<t.length;i++)r.list.push(hd(t[i]));else if((n=Id(t))!=null){let i;for(;!(i=Xa(n.next())).done;)r.list.push(hd(i.value))}else if((typeof t=="object"||typeof t=="function")&&t!=null){let i=Object.keys(t);for(let o=0;o<i.length;o++){let a=i[o],c=sb(a),l=fe(t[a]),p=r.list.find(A=>A[0]===c);p?p[1]=l:r.list.push([c,l])}}else if(t!==void 0){let i=fe(t);i=i[0]==="?"?i.substring(1):i,r.list=co(i)}}get size(){return this[xe].list.length}append(t,r){t=fe(t),r=fe(r),this[xe].list.push([t,r]);let n=this[xe];n.url&&n.serialized?(function(o,a){let c=o[pe].url;c.query=c.query?`${c.query}&${a}`:a})(n.url,ro([[t,r]])):ai(n)}delete(t,r){t=fe(t),r=r!=null?fe(r):void 0;let{list:n}=this[xe],i=0;for(;i<n.length;)n[i][0]===t&&(r==null||n[i][1]===r)?n.splice(i,1):i++;ai(this[xe])}get(t){t=fe(t);let{list:r}=this[xe];for(let n=0;n<r.length;n++)if(r[n][0]===t)return r[n][1];return null}getAll(t){t=fe(t);let r=[],{list:n}=this[xe];for(let i=0;i<n.length;i++)n[i][0]===t&&r.push(n[i][1]);return r}has(t,r){t=fe(t),r=r!=null?fe(r):void 0;let{list:n}=this[xe];for(let i=0;i<n.length;i++)if(n[i][0]===t&&(r==null||n[i][1]===r))return!0;return!1}set(t,r){t=fe(t),r=fe(r);let{list:n}=this[xe],i=!1,o=!1,a=0;for(;a<n.length;)n[a][0]===t?i?(n.splice(a,1),o=!0):(i=!0,n[a][1]!==r&&(n[a][1]=r,o=!0),a++):a++;i||(n.push([t,r]),o=!0),o&&ai(this[xe])}sort(){this[xe].list.sort((t,r)=>t[0]<r[0]?-1:t[0]>r[0]?1:0),ai(this[xe])}forEach(t,r){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:n}=this[xe];for(let i=0;i<n.length;i++)t.call(r,n[i][1],n[i][0],this)}entries(){return new on(this[xe],t=>t)}keys(){return new on(this[xe],t=>t[0])}values(){return new on(this[xe],t=>t[1])}toString(){return ro(this[xe].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(di.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var Ud={name:"@tinkerlandai/indiana-sdk",version:"0.9.2",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var qd="https://api.tinker.cash";function Ld(e){let t,r,n=0,i,o=new Map,a=()=>{for(let v of o.keys())v()};function c(v,k){let U=++n;i=void 0,t=void 0,r=void 0;for(let ie of o.values())ie?.();U===n&&(t=v,r=k,a())}let l=()=>c();function p(v,k=!1){let U=lr.safeParse(v);if(!U.success||k&&Date.parse(U.data.expiresAt)<=Date.now()||Date.parse(U.data.refreshExpiresAt)<=Date.now()||Date.parse(U.data.refreshExpiresAt)<Date.parse(U.data.expiresAt))throw new R("INVALID_RESPONSE","Invalid customer session credentials");return U.data}async function A(){if(i)return i;let v=t,k=n;if(!v||Date.parse(v.refreshExpiresAt)<=Date.now())throw v&&l(),new R("UNAUTHENTICATED","Customer authentication is required",401);let U=(async()=>{try{let ie=await e(v.refreshToken);if(k!==n)throw new R("IDENTITY_CHANGED","Customer identity changed during refresh");let q=p(ie,!0);if(q.customerId!==v.customerId||q.sessionId!==v.sessionId)throw new R("SCOPE_MISMATCH","Refresh changed the customer session");return t=q,r=q.accessToken,{...q}}catch(ie){throw k!==n?new R("IDENTITY_CHANGED","Customer identity changed during refresh"):(ie instanceof R&&ie.status===401&&l(),ie)}})();i=U;try{return await U}finally{i===U&&(i=void 0)}}return{identify(v){let k=typeof v=="string"?void 0:p(v),U=typeof v=="string"?v:k.accessToken;if(!U.trim()||/\s/.test(U)||U.length>4096)throw new R("INVALID_TOKEN","A server-issued token is required");c(k,U)},reset:l,subscribeIdentity(v,k){return o.set(v,k),()=>{o.delete(v)}},access(){if(t&&Date.parse(t.expiresAt)<=Date.now()+3e4)return A().then(()=>{if(!r)throw new R("NOT_IDENTIFIED","Customer authentication is required");return r});if(!r)throw new R("NOT_IDENTIFIED","Identify a customer session before making a request");return r},peek:()=>r,snapshot:()=>t&&{...t},refresh:A}}var Bd=Symbol("IndianaNoContent");function Fd(e,t,r=URL){let n=e.configuration?.scope,i=e.scope??(n&&{projectId:n.projectId,environment:n.environment}),o=i?Je.parse(i):void 0;if(o&&n&&(o.projectId!==n.projectId||o.environment!==n.environment))throw new R("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=new r(e.baseUrl??qd);if(a.username||a.password||a.search||a.hash)throw new R("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(a.hostname)))throw new R("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let c=e.fetch??globalThis.fetch.bind(globalThis),l=e.timeoutMs??1e4;if(!Number.isFinite(l)||l<1||l>12e4)throw new R("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let p=null,A=0,v=null,k=new Set,U=e.session??Ld(async T=>{let F=await Ne("customer-sessions/refresh",{},"POST",{},T);if(!F||typeof F!="object")throw new R("INVALID_RESPONSE","Invalid refresh response");let{requestId:Q,scope:he,...ge}=F;return ge});function ie(){A+=1,p=null,v=null;for(let T of k)T.abort();k.clear()}let q=U.subscribeIdentity(ie);function ve(){U.reset()}async function Ne(T,F={},Q="POST",he={},ge){let Ae=he.installationDetach===!0;if(Ae&&(T!=="push/installations/detach"||Q!=="POST"))throw new R("INVALID_REQUEST","Installation authority only detaches this installation");if(!ge&&!p&&!Ae)throw new R("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let Be=A,je=new AbortController;Ae||k.add(je);let st=()=>!Ae&&Be!==A?new R("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new R("TIMEOUT","Indiana request timed out"),Me,Ir=new Promise((Pe,ze)=>{Me=()=>ze(st()),je.signal.addEventListener("abort",Me,{once:!0})}),we=setTimeout(()=>je.abort(),l),at=async()=>{let Pe=await c(`${a.href.replace(/\/$/,"")}/api/v1/${T}`,{method:Q,headers:{"Content-Type":"application/json",...Ae?{}:{Authorization:`Bearer ${ge??p}`},[bi]:yi.current,[Eo]:Ud.version,...o?{"X-Indiana-Project":o.projectId,"X-Indiana-Environment":o.environment}:{}},body:Q==="POST"?JSON.stringify(F):void 0,signal:je.signal,credentials:"omit",cache:"no-store",redirect:"error",...he.keepalive?{keepalive:!0}:{}});if(je.signal.aborted)throw st();let ze;try{ze=Pe.status===204?Bd:await Pe.json()}catch{throw je.signal.aborted?st():new R(Pe.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Pe.status,Pe.headers.get("X-Request-Id")??void 0)}if(je.signal.aborted)throw st();if(!Ae&&Be!==A)throw new R("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Pe.ok){let Ue=gi.safeParse(ze),Pt=Ue.success&&(!Ut.safeParse(Ue.data.error.code).success||wo(Ue.data.error.code,Pe.status)),ho=Pt?Ue.data.error.code:"HTTP_ERROR",Ao=mn(ho,Pe.status,{retryAfter:Pe.headers.get("Retry-After"),recovery:Pt?Ue.data.error.recovery:void 0,reason:Pt?Ue.data.error.reason:void 0});throw new R(ho,Pt?Ue.data.error.message:"Indiana request failed",Pe.status,Pe.headers.get("X-Request-Id")??(Ue.success?Ue.data.requestId:void 0),{...Ao,...Ue.success&&Ue.data.error.retryable===!1?{retryable:!1}:{},...Ao.retryAfterSeconds===void 0&&Ue.success&&Ue.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:Ue.data.error.retryAfterSeconds}:{}})}if(Pe.headers.get(bi)!==yi.current)throw new R("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(o&&ze!==Bd){let Ue=ze&&typeof ze=="object"&&"scope"in ze?ze:ze&&typeof ze=="object"&&"configuration"in ze?ze.configuration:null;if(!Ue||typeof Ue!="object"||!("scope"in Ue))throw new R("INVALID_RESPONSE","Response is missing its App/environment scope");let Pt=Je.safeParse(Ue.scope);if(!Pt.success||Pt.data.projectId!==o.projectId||Pt.data.environment!==o.environment)throw new R("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let un=Pe.headers.get("X-Indiana-Telemetry-Subject");if(un){if(!/^[a-f0-9]{64}$/.test(un))throw new R("INVALID_RESPONSE","Invalid telemetry identity");v!==un&&(v=un,t?.(v))}return ze};try{return await Promise.race([at(),Ir])}catch(Pe){throw!Ae&&Be!==A?new R("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Pe instanceof R?Pe:new R(je.signal.aborted?"TIMEOUT":"NETWORK_ERROR",je.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(we),je.signal.removeEventListener("abort",Me),k.delete(je)}}return{session:U,requestWithCredential(T,F,Q){return Ne(T,F,"POST",{},Q)},subjectKey:()=>v,identify(T){if(o&&typeof T=="object"&&"scope"in T){let F=Je.safeParse(T.scope);if(!F.success||F.data.projectId!==o.projectId||F.data.environment!==o.environment)throw new R("SCOPE_MISMATCH","Customer session belongs to another App/environment")}U.identify(T),p=U.peek()??null},reset:ve,dispose(){q(),ie()},request(T,F={},Q="POST",he={}){if(he.installationDetach)return Ne(T,F,Q,he);let ge=A;try{let Ae=U.access(),Be=je=>{if(ge!==A)throw new R("IDENTITY_CHANGED","Customer identity changed before dispatch");return Ne(T,F,Q,he,je)};return typeof Ae=="string"?Be(Ae):Ae.then(Be)}catch(Ae){return Promise.reject(Ae)}}}}import{ZodError as Bb}from"zod";function Vd(e,t,r,n){try{return e.parse(t)}catch(i){throw n&&i instanceof Bb?new R(r,n):i}}async function fo(e,t,r,n={},i){let o=typeof n=="function"?{}:n,a=Vd(t.request,r,"INVALID_REQUEST",o.request),c=await e(t.path,a,t.method,i),l=typeof n=="function"?n:n.parseResponse;return l?l(t.response,c):Vd(t.response,c,"INVALID_RESPONSE",o.response)}var Fb=_.trackUsage.request.shape.command,Vb=_.trackUsage.response,$b=_.checkEntitlement.request.omit({customerId:!0}).strict();function Gb(e){let t=Je.parse(e.scope),r=Fd({...e,scope:t},void 0,cn),n=pd(e.push,r,t),i=0,o=!1;return r.session.subscribeIdentity(()=>{i++,o=!!r.session.peek()}),{...fd(r.request,n),session:r.session,identify(a){let c=typeof a=="string"?a:a.accessToken;if(!Dn.test(c))throw new R("INVALID_TOKEN","A Customer Token is required");n.identify(c),r.identify(a),n.start()},reset(){try{n.reset()}finally{r.reset(),n.start()}},async readHoldings(){let a=_.readHoldings;return fo(r.request,a,{})},async checkEntitlement(a){let c=_.checkEntitlement;return fo(r.request,{...c,request:$b},a)},async trackUsage(a){if(!o)throw new R("UNAUTHENTICATED","Identify the Customer first");if(!e.usageReporter)throw new R("INVALID_REQUEST","Configure your authenticated backend usageReporter");let c=Fb.parse(a),l=i,p;try{p=await e.usageReporter(c)}catch(v){throw l!==i?new R("IDENTITY_CHANGED","Customer identity changed during usage reporting"):v}if(l!==i)throw new R("IDENTITY_CHANGED","Customer identity changed during usage reporting");let A=Vb.parse(p);if(A.scope.projectId!==t.projectId||A.scope.environment!==t.environment)throw new R("INVALID_RESPONSE","Usage response scope differs");return A}}}export{R as IndianaError,Gb as createIndianaReactNative};
|
|
1
|
+
var Zg=Object.defineProperty;var Wg=(e,t,n)=>t in e?Zg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var qe=(e,t,n)=>Wg(e,typeof t!="symbol"?t+"":t,n);import{z as Ba}from"zod";var Yg=Ba.enum(["sandbox","live"]),Ve=Ba.object({projectId:Ba.string().min(1),environment:Yg}).strict();import{z as Ue}from"zod";var gi=Ue.number().int().min(1).max(Number.MAX_SAFE_INTEGER),bu=Ue.enum(["unknown","denied","provisional","granted"]),Su=Ue.enum(["ios","android"]),uo=Ue.strictObject({installationId:Ue.uuid(),publicKey:Ue.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:Ue.iso.datetime({offset:!0}),signature:Ue.string().regex(/^[A-Za-z0-9_-]{86}$/)}),za=Ue.string().regex(/^[a-f0-9]{64}$/),xu=uo.extend({sequence:gi,platform:Su,credentialDigest:za}),Iu=uo.extend({credentialDigest:za}),vu=uo.extend({sequence:gi,platform:Su}),lo=uo.extend({sequence:gi,credentialDigest:za,connectionId:Ue.uuid().nullable(),kind:Ue.enum(["fcm_token","apns_token"]).nullable(),token:Ue.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:bu}),wu=lo,Ou=lo.extend({challenge:Ue.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),$a=Ue.strictObject({requested:Ue.literal(!0),expiresAt:Ue.iso.datetime({offset:!0})}),sr=Ue.strictObject({installationId:Ue.uuid(),bound:Ue.boolean(),identitySeq:gi,bindingGeneration:gi,addressSeq:Ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:Ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:Ue.uuid().nullable(),addressStatus:Ue.enum(["active","invalid"]).nullable(),permission:bu}),Ga=Ue.strictObject({channel:Ue.enum(["email","sms","voice","push"]),state:Ue.enum(["unknown","allowed","denied"]),revision:Ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:Ue.iso.datetime({offset:!0}).nullable()}),O0=Ue.strictObject({state:Ue.enum(["allowed","denied"]),revision:Ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function Cu(e,t,n){let r=["indiana_push_v1",e,t.projectId,t.environment,n.installationId,n.publicKey,n.issuedAt];e==="bind"?r.push(n.sequence,n.platform,n.credentialDigest):e==="detach"?r.push(n.sequence,n.platform):e==="read"?r.push(n.credentialDigest):r.push(n.sequence,n.credentialDigest,n.connectionId,n.kind,n.token,n.permission),e==="recovery_confirm"&&r.push(n.challenge);let i=JSON.stringify(r);if([...i].some(a=>a.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(i,a=>a.charCodeAt(0))}import{z as yt}from"zod";var cr=yt.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),_0=yt.enum([...cr.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),E0=yt.enum([...cr.options,"stale_revision"]),Xg=yt.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),eh=yt.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),_u={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};var Pu={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function th(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(Pu,e)){let r=Pu[e];return{retryable:r==="retry_same_request",recovery:r}}let n=cr.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:_u[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Eu(e,t){let n=cr.safeParse(e);if(n.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):_u[n.data].status===t;let r={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(r,e)&&(r[e]?.includes(t)??!1)}function nh(e,t=Date.now()){if(e===null)return;let n=e.trim();if(/^\d+$/.test(n)){let i=Number(n);return Number.isSafeInteger(i)?i:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let r=Date.parse(n);return Number.isFinite(r)?Math.max(0,Math.ceil((r-t)/1e3)):void 0}var Ru=yt.object({retryable:yt.boolean(),recovery:Xg,reason:eh.optional(),retryAfterSeconds:yt.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),Ka=yt.object({requestId:yt.uuid().optional(),error:yt.object({code:yt.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:yt.string(),...Ru.partial().shape})}),R0=yt.object({error:Ka.shape.error.extend({requestId:yt.uuid().optional()})}),k0=yt.object({error:yt.string(),code:yt.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:yt.uuid(),...Ru.shape});function po(e,t,n={}){let r=th(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?nh(n.retryAfter??null):void 0;return{...r,retryable:a,recovery:i,...o===void 0?{}:{retryAfterSeconds:o},...n.reason?{reason:n.reason}:{}}}var Ha="X-Indiana-Protocol",ku="X-Indiana-SDK-Version";var Qa={current:"0.9"};import{z as rh}from"zod";var ih=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],fe=rh.enum(ih);import{z as bt}from"zod";var oh=bt.enum(["checkout.session.completed","checkout.session.expired","checkout.session.async_payment_succeeded","checkout.session.async_payment_failed","customer.subscription.created","customer.subscription.updated","customer.subscription.deleted","customer.subscription.paused","customer.subscription.resumed","invoice.created","invoice.paid","customer.discount.created","customer.discount.updated","refund.created","refund.updated","refund.failed","charge.refunded"]),ju=bt.strictObject({provider:bt.literal("stripe"),accountId:bt.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:bt.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:oh,occurredAt:bt.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:bt.record(bt.string(),bt.unknown()).and(bt.object({id:bt.string().min(1).max(255),object:bt.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:bt.boolean()}))}),Tu=bt.strictObject({id:bt.uuid(),eventId:bt.string().min(1).max(200),source:bt.literal("merchant"),providerVerified:bt.literal(!1),outcome:bt.string().min(1).max(100)});import{z as ur}from"zod";var jt=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,kr=ur.object({customerId:ur.uuid(),sessionId:ur.uuid(),accessToken:ur.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:ur.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:ur.iso.datetime(),refreshExpiresAt:ur.iso.datetime()});import{z as jr}from"zod";var mo=jr.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID \u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u5E76\u4EE5\u5B57\u6BCD\u5F00\u5934"),B0=jr.object({amountCents:jr.number().int().min(0).max(1e8),currency:fe,interval:jr.enum(["free","month","year"]),currencyOptions:jr.partialRecord(fe,jr.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C");import{z as T}from"zod";var ah=T.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Fu=T.enum(["single_use","continuous_use"]),Ja=T.record(T.string(),T.union([T.string(),T.number(),T.boolean()]).transform(String).pipe(T.string())),Nu=T.string().min(1).max(64).refine(e=>!e.includes("::")),Mu={credit_amount:T.number(),tier_behavior:T.never().optional(),tiers:T.never().optional()},qu={credit_amount:T.never().optional(),tier_behavior:T.literal("graduated"),tiers:T.array(T.strictObject({to:T.union([T.number(),T.literal("inf")]),credit_amount:T.number()}))},sh=T.union([T.strictObject({match:Ja,priority:T.number().int().optional(),...Mu}),T.strictObject({match:Ja,priority:T.number().int().optional(),...qu})]),ch=T.strictObject({match:Ja,factor:T.number().positive().optional(),add:T.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),Du={metered_feature_id:T.string(),feature_amount:T.number().optional(),dimensions:T.record(Nu,sh).optional(),multipliers:T.record(Nu,ch).optional()},Za=T.union([T.strictObject({...Du,...Mu}),T.strictObject({...Du,...qu})]),go=T.number().min(-100),Vu=T.record(T.string(),T.strictObject({markup:go})).nullish(),ho=T.record(T.string().regex(/.+\/.+/),T.strictObject({markup:go.optional(),input_cost:T.number().min(0).optional(),output_cost:T.number().min(0).optional()})).nullish(),uh=T.strictObject({default_markup:go.optional(),provider_markups:Vu,model_markups:ho}),G0=T.strictObject({schema:T.array(Za).optional(),markups:uh.optional()}),lh=T.strictObject({filters:T.array(T.strictObject({property:T.string(),operator:T.string(),value:T.array(T.string())})),aggregate:T.strictObject({type:T.string(),property:T.string().nullable()}),usage_type:Fu}),Uu=T.strictObject({schema:T.array(Za).min(1).refine(e=>new Set(e.map(t=>t.metered_feature_id)).size===e.length,"Credit rates must name each metered feature once"),invoice_credit:T.boolean().optional(),usage_type:Fu.default("single_use").overwrite(()=>"single_use"),default_markup:go.optional(),provider_markups:Vu}),Wa=Uu.safeExtend({schema:T.array(Za).length(0)}),fo={id:ah,name:T.string().min(1),display:T.strictObject({singular:T.string().optional(),plural:T.string().optional()}).nullish(),event_names:T.array(T.string()).default([]),model_markups:ho,stripe_meter:T.strictObject({id:T.string(),event_name:T.string()}).nullish(),stripe_product_id:T.string().nullish()},Ya=e=>T.discriminatedUnion("type",[T.strictObject({...fo,...e,type:T.literal("boolean"),config:T.null()}),T.strictObject({...fo,...e,type:T.literal("metered"),config:lh}),T.strictObject({...fo,...e,type:T.literal("credit_system"),config:Uu}),T.strictObject({...fo,...e,type:T.literal("ai_credit_system"),config:Wa})]),K0=Ya({}),dh=T.strictObject({id:T.boolean(),type:T.boolean(),usage_type:T.boolean()}),ph={internal_id:T.uuid(),org_id:T.uuid(),created_at:T.number(),env:T.enum(["sandbox","live"]),archived:T.boolean(),project_id:T.uuid(),environment_id:T.uuid(),revision:T.number().int().nonnegative(),update_rules:dh},Lu=Ya(ph),H0=T.strictObject({rows:T.array(Lu).max(200),nextCursor:T.uuid().nullable()}),Q0=T.strictObject({features:T.array(Lu).max(500),limited:T.boolean()}),J0=T.union([Ya({action:T.literal("save"),internal_id:T.uuid().nullable(),revision:T.number().int().nonnegative()}),T.strictObject({action:T.enum(["archive","restore","delete"]),internal_id:T.uuid(),revision:T.number().int().nonnegative()})]);import{z as Dr}from"zod";import{z as rt}from"zod";var Lt=rt.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),me=rt.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),Ao=rt.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),Xa=me.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Bu=rt.string().min(1).max(64),lr=rt.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),zu=rt.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),pt=rt.record(Bu,rt.union([rt.string().max(120),rt.number().finite(),rt.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,String(n)]))),$u=rt.record(Bu,rt.union([rt.string().max(120),rt.number().finite(),rt.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),Tr=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");let i=BigInt(n)*BigInt("1000000")+BigInt(r.padEnd(6,"0"));return t?-i:i},Gu=rt.array(rt.object({upTo:Xa.nullable(),cost:me}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&Tr(t.upTo)>Tr(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),mh=rt.object({key:zu,match:$u,priority:rt.number().int().default(0),cost:me.optional(),tiers:Gu.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),fh=rt.object({key:zu,match:$u,factor:Xa.optional(),add:Ao.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),gh=rt.object({units:Xa.default("1"),cost:me,tiers:Gu.optional(),dimensions:rt.array(mh).max(12).optional(),multipliers:rt.array(fh).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],r=e.multipliers??[];(new Set(n.map(o=>o.key)).size!==n.length||new Set(r.map(o=>o.key)).size!==r.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[o,s]of n.entries())for(let c of n.slice(o+1))Object.keys(s.match).length===Object.keys(c.match).length&&s.priority===c.priority&&!Object.keys(s.match).some(u=>c.match[u]!==void 0&&c.match[u]!==s.match[u])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let i=[e.cost,...(e.tiers??[]).map(o=>o.cost),...n.flatMap(o=>[...o.cost===void 0?[]:[o.cost],...(o.tiers??[]).map(s=>s.cost)])],a=Tr(e.units);for(let o of i)for(let s=0;s<1<<r.length;s++){let c=r.filter((p,g)=>s&1<<g);if(c.some((p,g)=>c.slice(g+1).some(f=>Object.keys(p.match).some(S=>f.match[S]!==void 0&&f.match[S]!==p.match[S]))))continue;let u=Tr(o),d=BigInt("1"),m=BigInt("0");for(let[p,g]of r.entries())s&1<<p&&(u*=Tr(g.factor??"1"),d*=BigInt("1000000"),m+=Tr(g.add??"0"));let w=(u+m*d)*BigInt("1000000"),I=d*a;(w<BigInt("0")||w%I!==BigInt("0")||w/I>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),Y0=gh.safeExtend({featureKey:lr});import{z as Nr}from"zod";var Ku=Nr.number().int().min(0).max(1e8),hi=Nr.strictObject({kind:Nr.enum(["graduated","volume"]),tiers:Nr.array(Nr.strictObject({upTo:Nr.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Ku,flatAmountMinor:Ku.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>{let r=e.tiers[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&t.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(e=>!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function es(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?hi.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,i=0;if(!n)r=BigInt(e.amountMinor)*BigInt(t);else for(let a of n.tiers){let o=a.upTo??1e4;if(n.kind==="volume"){if(t<=o){r=BigInt(t)*BigInt(a.unitAmountMinor)+BigInt(a.flatAmountMinor??0);break}}else t>i&&(r+=BigInt(Math.min(t,o)-i)*BigInt(a.unitAmountMinor));i=o}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function yo(e){return es({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var hh=me.refine(e=>/[1-9]/.test(e)),bo=Dr.strictObject({units:hh,prices:Dr.array(Dr.strictObject({currency:fe,amountMinor:Dr.number().int().min(0).max(1e8),pricing:hi.optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique").refine(e=>e.every(t=>!t.pricing||t.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:Dr.number().int().min(0).max(1e4),maximumQuantity:Dr.number().int().min(0).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let n of[e.maximumQuantity,...t.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])n<=e.maximumQuantity&&es({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit");function Hu(e){if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(e))throw new Error("Invalid quantity");let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))}function Qu(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=Hu(e)+Hu(t)*BigInt(n);if(r>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let i=(r%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(r/1000000n).toString()+(i?"."+i:"")}import{z as A}from"zod";import{z as W}from"zod";import{z as wt}from"zod";import{z as R}from"zod";function Ju(e){let t=2166136261,n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function So(e,t,n){return n===2?Ju(Ju(e+t)+"")%1e4/1e4:null}function Ah(e){return e<=0?[]:new Array(e).fill(1/e)}function xo(e,t){return e>=t[0]&&e<t[1]}function Zu(e,t){for(let[n,r]of t.entries())if(xo(e,r))return n;return-1}function Wu(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=Ah(e);n=n||r,n.length!==e&&(n=r);let i=n.reduce((s,c)=>c+s,0);(i<.99||i>1.01)&&(n=r);let a=0,o=t;return n.map(s=>{let c=a;return a+=s,[c,c+o*s]})}function Yu(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let a=r.replace(/#.*/,"").split("&").map(o=>o.split("=",2)).filter(([o])=>o===e).map(([,o])=>o===void 0?NaN:parseInt(o))[0];return a!==void 0&&a>=0&&a<n?a:null}function Xu(e){try{return e()}catch{return!1}}function Ai(e){return typeof e=="string"?e:JSON.stringify(e)}function Qt(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function yh(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function el(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let a=xh(e,i.type,i.pattern);if(i.include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function bh(e,t,n){try{let r=t.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return n&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(e)}catch{return!1}}function Sh(e,t){try{let n=new URL(t.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[e.host,n.host,!1],[e.pathname,n.pathname,!0]];return n.hash&&r.push([e.hash,n.hash,!1]),n.searchParams.forEach((i,a)=>{r.push([e.searchParams.get(a)||"",i,!1])}),!r.some(i=>!bh(i[0],i[1],i[2]))}catch{return!1}}function xh(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=yh(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return Sh(r,n);return!1}catch{return!1}}function ts(e){for(let n of["namespace","status","url","groups"])if(Object.hasOwn(e,n))throw new TypeError(`Retired experiment field: ${n}`);let t=e;if(t.hashVersion!==void 0&&t.hashVersion!==2)throw new TypeError("Only hash version 2 is supported");if(t.filters?.some(n=>n.hashVersion!==2))throw new TypeError("Only hash version 2 is supported")}function Io(e){for(let t of Object.values(e)){if(Array.isArray(t))throw new TypeError("Saved groups require typed list or condition entries");if(t&&Object.hasOwn(t,"useEmptyListGroup"))throw new TypeError("Retired saved group field: useEmptyListGroup")}}function tl(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);Io(e.savedGroups??{})}var Ih=e=>e/2**32|0,vh=e=>e>>>0;function nl(e,t,n,r){let i=Ih(n),a=vh(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function rl(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var ns=e=>e?`"${e}" `:"";function wh(e,t=""){if(typeof e!="number")throw new TypeError(ns(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(ns(t)+"expected integer >= 0, got "+e);return e}function vo(e,t,n=""){if(rl(e)&&(t===void 0||e.length===t))return e;t!==void 0&&wh(t,"length");let r=rl(e),i=t!==void 0?` of length ${t}`:"",a=r?`length=${e.length}`:`type=${typeof e}`,o=ns(n)+"expected Uint8Array"+i+", got "+a;throw r?new RangeError(o):new TypeError(o)}var Oh=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},il=(e,t)=>{Oh(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function rs(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function ol(e,t){vo(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function is(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function wo(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function un(e,t){return e<<32-t|e>>>t}var Ch=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ph=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Fr(e){if(vo(e),Ch)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Ph[e[n]];return t}function _h(e,t,n="opts"){return il(e,"defaults"),t!==void 0&&il(t,n),Object.assign(Object.create(null),e,t)}function al(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=_h({},t,"info");let n=(i,a)=>e(a).update(i).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=i=>e(i),Object.assign(n,t),Object.freeze(n)}var sl=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function cl(e,t,n){return e&t^~e&n}function ul(e,t,n){return e&t^e&n^t&n}var Oo=class{constructor(t,n,r,i){qe(this,"blockLen");qe(this,"outputLen");qe(this,"canXOF",!1);qe(this,"padOffset");qe(this,"isLE");qe(this,"buffer");qe(this,"view");qe(this,"finished",!1);qe(this,"length",0);qe(this,"pos",0);qe(this,"destroyed",!1);this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=wo(this.buffer)}update(t){rs(this),vo(t);let{view:n,buffer:r,blockLen:i}=this,a=t.length,o=!1;for(let s=0;s<a;){let c=Math.min(i-this.pos,a-s);if(c===i){let u=wo(t);for(;i<=a-s;s+=i)this.process(u,s);o=!0;continue}r.set(s===0&&c===a?t:t.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(n,0),this.pos=0,o=!0)}return this.length+=t.length,o&&this.roundClean(),this}digestInto(t){rs(this),ol(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:a}=this,{pos:o}=this;n[o++]=128,n.fill(0,o),this.padOffset>i-o&&(this.process(r,0),n.fill(0)),nl(r,i-8,this.length*8,a),this.process(r,0),this.roundClean();let s=t===n?r:wo(t),c=this.outputLen,u=c/4,d=this.get();if(c%4||u>d.length)throw new Error("invalid outputLen");for(let m=0;m<u;m++)s.setUint32(4*m,d[m],a)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return t.destroyed=a,t.finished=i,t.length=r,t.pos=o,o&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ll=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Eh=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Mn=new Uint32Array(64),os=class extends Oo{constructor(n,r){super(64,n,8,!1);qe(this,"A",0);qe(this,"B",0);qe(this,"C",0);qe(this,"D",0);qe(this,"E",0);qe(this,"F",0);qe(this,"G",0);qe(this,"H",0);this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:u}=this;return[n,r,i,a,o,s,c,u]}set(n,r,i,a,o,s,c,u){this.A=n|0,this.B=r|0,this.C=i|0,this.D=a|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=u|0}_cloneInto(n){return(n||(n=new this.constructor)).set(...this.get()),this._cloneIntoMeta(n)}process(n,r){for(let w=0;w<16;w++,r+=4)Mn[w]=n.getUint32(r,!1);for(let w=16;w<64;w++){let I=Mn[w-15],p=Mn[w-2],g=un(I,7)^un(I,18)^I>>>3,f=un(p,17)^un(p,19)^p>>>10;Mn[w]=f+Mn[w-7]+g+Mn[w-16]|0}let{A:i,B:a,C:o,D:s,E:c,F:u,G:d,H:m}=this;for(let w=0;w<64;w++){let I=un(c,6)^un(c,11)^un(c,25),p=m+I+cl(c,u,d)+Eh[w]+Mn[w]|0,f=(un(i,2)^un(i,13)^un(i,22))+ul(i,a,o)|0;m=d,d=u,u=c,c=s+p|0,s=o,o=a,a=i,i=p+f|0}i=i+this.A|0,a=a+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,u=u+this.F|0,d=d+this.G|0,m=m+this.H|0,this.set(i,a,o,s,c,u,d,m)}roundClean(){is(Mn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),is(this.buffer)}},as=class extends os{constructor(){super(32,ll)}};var Mr=al(()=>new as,sl(1));var dl=new Map,ss=32,pl=new WeakMap,ml=new WeakMap;function Rh(e){return Fr(Mr(new TextEncoder().encode(String(e))))}var Po=e=>Array.isArray(e)?e.map(Po):typeof e=="string"||typeof e=="number"?Rh(e):null,Co=e=>typeof e=="string"?e.toLowerCase():e;function yl(e){let t=pl.get(e);return t||(t=new Set(e),pl.set(e,t)),t}function kh(e){let t=ml.get(e);return t||(t=new Set(e.map(Co)),ml.set(e,t)),t}function qr(e){Io(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=ss&&yl(n)}return e}function zt(e,t,n,r){n=n||{},r||Io(n),r=r||new Set;for(let[i,a]of Object.entries(t))switch(i){case"$or":if(!Al(e,a,n,r))return!1;break;case"$nor":if(Al(e,a,n,r))return!1;break;case"$and":if(!Fh(e,a,n,r))return!1;break;case"$not":if(zt(e,a,n,r))return!1;break;case"$savedGroup":if(!jh(e,a,n,r))return!1;break;default:if(!yi(a,bl(e,i),n,!1,r))return!1}return!0}function jh(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:i,attributeKey:a}=t;if(typeof i!="string"||r.has(i)||a!==void 0&&typeof a!="string")return!1;let o=n[i];if(!o||Array.isArray(o)||typeof o!="object")return!1;let s=new Set(r).add(i);if(o.type==="list"||o.type==="hashed"){let c=a??o.attributeKey;if(typeof c!="string"||!Array.isArray(o.values))return!1;let u=bl(e,c);return dr(o.type==="hashed"?Po(u):u,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:zt(e,o.condition,n,s):!1}function bl(e,t){let n=t.split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return null;return r}function fl(e,t=!1){let n=`${e}${t?"/i":""}`,r=dl.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),dl.set(n,r)),r}function yi(e,t,n,r=!1,i=new Set){if(typeof e=="string")return r?String(t).toLowerCase()===e.toLowerCase():t+""===e;if(typeof e=="number")return t*1===e;if(typeof e=="boolean")return t!==null&&!!t===e;if(e===null)return t===null;if(Array.isArray(e)||!Sl(e))return JSON.stringify(t)===JSON.stringify(e);let a=e;for(let o in a)if(!Dh(o,t,a[o],n,i))return!1;return!0}function Sl(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function Th(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return["string","number","boolean","object","undefined"].includes(t)?t:"unknown"}function Nh(e,t,n,r){if(!Array.isArray(e))return!1;let i=Sl(t)?a=>yi(t,a,n,!1,r):a=>zt(a,t,n,r);for(let a=0;a<e.length;a++)if((e[a]??null)!==null&&i(e[a]))return!0;return!1}function dr(e,t,n=!1){if(n){let i;if(t.length>=ss){let a=kh(t);i=o=>{let s=Co(o);return!(typeof s=="number"&&Number.isNaN(s))&&a.has(s)}}else i=a=>t.some(o=>Co(a)===Co(o));return Array.isArray(e)?e.some(a=>i(a)):i(e)}let r=t.length>=ss?(i=>a=>i.has(a))(yl(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function gl(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function hl(e,t,n,r=!1,i=new Set){if(!Array.isArray(e))return!1;for(let a=0;a<t.length;a++){let o=!1;for(let s=0;s<e.length;s++)if(yi(t[a],e[s],n,r,i)){o=!0;break}if(!o)return!1}return!0}function Dh(e,t,n,r,i=new Set){let a=t,o=n;switch(e){case"$veq":return Qt(t)===Qt(n);case"$vne":return Qt(t)!==Qt(n);case"$vgt":return Qt(t)>Qt(n);case"$vgte":return Qt(t)>=Qt(n);case"$vlt":return Qt(t)<Qt(n);case"$vlte":return Qt(t)<=Qt(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return a<o;case"$lte":return a<=o;case"$gt":return a>o;case"$gte":return a>=o;case"$exists":return n?t!=null:t==null;case"$in":return Array.isArray(n)?dr(t,n):!1;case"$ini":return Array.isArray(n)?dr(t,n,!0):!1;case"$inGroup":{let s=r[n],c=gl(s);return c===null?!1:dr(s?.type==="hashed"?Po(t):t,c)}case"$notInGroup":{let s=r[n],c=gl(s);return c===null?!1:!dr(s?.type==="hashed"?Po(t):t,c)}case"$nin":return Array.isArray(n)?!dr(t,n):!1;case"$nini":return Array.isArray(n)?!dr(t,n,!0):!1;case"$not":return!yi(n,t,r,!1,i);case"$size":return Array.isArray(t)?yi(n,t.length,r,!1,i):!1;case"$elemMatch":return Nh(t,n,r,i);case"$all":return Array.isArray(n)?hl(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?hl(t,n,r,!0,i):!1;case"$regex":try{return fl(n).test(t)}catch{return!1}case"$regexi":try{return fl(n,!0).test(t)}catch{return!1}case"$type":return Th(t)===n;default:return!1}}function Al(e,t,n,r){if(!t.length)return!0;for(let i of t)if(zt(e,i,n,r))return!0;return!1}function Fh(e,t,n,r){for(let i of t)if(!zt(e,i,n,r))return!1;return!0}function cs(e){return tl(e),{context:e,stack:{evaluatedFeatures:new Set}}}function us(e){return{...e.attributes,...e.attributeOverrides}}function qn(e,t,n){let r=t||"id",i="",a=us(e);return a[r]&&(i=a[r]),!i&&n&&(a[n]&&(i=a[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function Ge(e,t,n){e.context.log?.(t,n)}function _o(e,t){return t=t||0,`${e}__${t}`}function ls(e,t){return`${e}||${t}`}function Mh(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=qn(e,t),o=ls(i,Ai(a)),{hashAttribute:s,hashValue:c}=qn(e,n),u=c?ls(s,Ai(c)):null,d={};return u&&r[u]&&Object.assign(d,r[u].assignments||{}),r[o]&&Object.assign(d,r[o].assignments||{}),d}function xl({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:i,expMinBucketVersion:a,expMeta:o}){n=n||0,a=a||0,r=r||"id",o=o||[];let s=_o(t,n),c=Mh(e,r,i);if(a>0)for(let m=0;m<a;m++){let w=_o(t,m);if(c[w]!==void 0)return{variation:-1,versionIsBlocked:!0}}let u=c[s];if(u===void 0)return{variation:-1};let d=o.findIndex(m=>m.key===u);return d<0?{variation:-1}:{variation:d}}function Il(e,t,n,r){let i=ls(t,n),a=e.stickyBucketAssignmentDocs,o=a&&a[i]?a[i].assignments||{}:{},s={...o,...r},c=JSON.stringify(o)!==JSON.stringify(s);return{key:i,doc:{attributeName:t,attributeValue:n,assignments:s},changed:c}}function vl(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Eo(e,t){let n=cs(t),r=Ol(e,null,n);return t.onExperimentEval?.(e,r),r}function _n(e,t){return ps(e,cs(t))}function qh(e){return e.forcedVariations||{}}function wl(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=_l(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}ds(()=>r.onExperimentViewed?.(t,n))}function Vh(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let i=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===i)return;r.trackedFeatureUsage[t]=i}ds(()=>r.onFeatureUsage?.(t,n))}function ds(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function ps(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return Ge(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),Vn(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let a of r?.rules??[])ts(a);let i=n.forcedFeatureValues;if(i&&i.has(e))return Ge(t,"Global override",{id:e,value:i.get(e)}),Vn(t,e,i.get(e),"override");if(!r)return Ge(t,"Unknown feature",{id:e}),Vn(t,e,null,"unknownFeature");if(r.rules){let a=new Set(t.stack.evaluatedFeatures);e:for(let o of r.rules){if(o.parentConditions)for(let u of o.parentConditions){t.stack.evaluatedFeatures=new Set(a);let d=ps(u.id,t);if(d.source==="cyclicPrerequisite")return Vn(t,e,null,"cyclicPrerequisite");let m={value:d.value};if(!zt(m,u.condition||{},n.savedGroups||{})){if(u.gate)return Ge(t,"Feature blocked by prerequisite",{id:e,rule:o}),Vn(t,e,null,"prerequisite");Ge(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&Pl(o.filters,t)){Ge(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!Cl(o.condition,t)){Ge(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!Uh(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){Ge(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return Ge(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(u=>{wl(t,u.experiment,u.result)}),Vn(t,e,o.force,"force",o.id)}if(!o.variations){Ge(t,"Skip invalid rule",{id:e,rule:o});continue}let s={variations:o.variations,key:o.key||e};"coverage"in o&&(s.coverage=o.coverage),o.weights&&(s.weights=o.weights),o.hashAttribute&&(s.hashAttribute=o.hashAttribute),o.fallbackAttribute&&(s.fallbackAttribute=o.fallbackAttribute),o.disableStickyBucketing&&(s.disableStickyBucketing=o.disableStickyBucketing),o.bucketVersion!==void 0&&(s.bucketVersion=o.bucketVersion),o.minBucketVersion!==void 0&&(s.minBucketVersion=o.minBucketVersion),o.meta&&(s.meta=o.meta),o.ranges&&(s.ranges=o.ranges),o.name&&(s.name=o.name),o.phase&&(s.phase=o.phase),o.seed&&(s.seed=o.seed),o.hashVersion&&(s.hashVersion=o.hashVersion),o.filters&&(s.filters=o.filters),o.condition&&(s.condition=o.condition);let c=Ol(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return Vn(t,e,c.value,"experiment",o.id,s,c)}}return Ge(t,"Use default value",{id:e,value:r.defaultValue}),Vn(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Ol(e,t,n){let{context:r}=n;ts(e);let i=e.key,a=e.variations.length;if(a<2)return Ge(n,"Invalid experiment",{id:i}),vt(n,e,-1,!1,t);if(r.enabled===!1)return Ge(n,"Context disabled",{id:i}),vt(n,e,-1,!1,t);if(e.urlPatterns&&!el(r.url||"",e.urlPatterns))return Ge(n,"Skip because of url targeting",{id:i}),vt(n,e,-1,!1,t);let o=Yu(i,r.url||"",a);if(o!==null)return Ge(n,"Force via querystring",{id:i,variation:o}),vt(n,e,o,!1,t);let c=qh(r)[i];if(c!==void 0)return Ge(n,"Force via dev tools",{id:i,variation:c}),vt(n,e,c,!1,t);if(e.active===!1)return Ge(n,"Skip because inactive",{id:i}),vt(n,e,-1,!1,t);let{hashAttribute:u,hashValue:d}=qn(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!d)return Ge(n,"Skip because missing hashAttribute",{id:i}),vt(n,e,-1,!1,t);let m=-1,w=!1,I=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:f,versionIsBlocked:S}=xl(vl({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));w=f>=0,m=f,I=!!S}if(!w){if(e.filters&&Pl(e.filters,n))return Ge(n,"Skip because of filters",{id:i}),vt(n,e,-1,!1,t);if(e.include&&!Xu(e.include))return Ge(n,"Skip because of include function",{id:i}),vt(n,e,-1,!1,t);if(e.condition&&!Cl(e.condition,n))return Ge(n,"Skip because of condition exp",{id:i}),vt(n,e,-1,!1,t);if(e.parentConditions){let f=new Set(n.stack.evaluatedFeatures);for(let S of e.parentConditions){n.stack.evaluatedFeatures=new Set(f);let h=ps(S.id,n);if(h.source==="cyclicPrerequisite")return vt(n,e,-1,!1,t);let P={value:h.value};if(!zt(P,S.condition||{},r.savedGroups||{}))return Ge(n,"Skip because prerequisite evaluation fails",{id:i}),vt(n,e,-1,!1,t)}}}let p=So(e.seed||i,d,e.hashVersion??2);if(p===null)return Ge(n,"Skip because of invalid hash version",{id:i}),vt(n,e,-1,!1,t);if(!w){let f=e.ranges||Wu(a,e.coverage===void 0?1:e.coverage,e.weights);m=Zu(p,f)}if(I)return Ge(n,"Skip because sticky bucket version is blocked",{id:i}),vt(n,e,-1,!1,t,void 0,!0);if(m<0)return Ge(n,"Skip because of coverage",{id:i}),vt(n,e,-1,!1,t);if("force"in e)return Ge(n,"Force variation",{id:i,variation:e.force}),vt(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return Ge(n,"Skip because QA mode",{id:i}),vt(n,e,-1,!1,t);let g=vt(n,e,m,!0,t,p,w);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:f,key:S,doc:h}=Il(r,u,Ai(d),{[_o(e.key,e.bucketVersion)]:g.key});if(f){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[S]=h;let P=r.saveStickyBucketAssignmentDoc;ds(()=>P(h))}}return wl(n,e,g),Ge(n,"In experiment",{id:i,variation:g.variationId}),g}function Vn(e,t,n,r,i,a,o){let s={value:n,on:!!n,off:!n,source:r,ruleId:i||""};return a&&(s.experiment=a),o&&(s.experimentResult=o),r!=="override"&&Vh(e,t,s),s}function Cl(e,t){return zt(us(t.context),e,t.context.savedGroups||{})}function Pl(e,t){return e.some(n=>{let{hashValue:r}=qn(t.context,n.attribute);if(!r)return!0;let i=So(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(a=>xo(i,a))})}function Uh(e,t,n,r,i,a,o){if(!i&&a===void 0)return!0;if(!i&&a===0)return!1;let{hashValue:s}=qn(e.context,n,r);if(!s)return!1;let c=So(t,s,o??2);return c===null?!1:i?xo(c,i):a!==void 0?c<=a:!0}function vt(e,t,n,r,i,a,o){let s=!0;(n<0||n>=t.variations.length)&&(n=0,s=!1);let{hashAttribute:c,hashValue:u}=qn(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),d=t.meta?.[n]??{},m=t.variations[0];for(let[I,p]of t.variations.entries())if(I===n){m=p;break}let w={key:d.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:m,hashAttribute:c,hashValue:u,stickyBucketUsed:!!o};return d.name&&(w.name=d.name),a!==void 0&&(w.bucket=a),d.passthrough&&(w.passthrough=d.passthrough),w}function _l(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
|
|
2
|
+
Copyright (c) 2025 GrowthBook, Inc.
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
|
|
5
|
+
furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all
|
|
8
|
+
copies or substantial portions of the Software.
|
|
9
|
+
|
|
10
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
11
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
12
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
13
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
14
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
15
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
16
|
+
SOFTWARE.
|
|
17
|
+
*/var ge=R.json().superRefine((e,t)=>{let n=0;function r(i,a){if(++n>1e4||a>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,a+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),mt=R.record(R.string().min(1).max(128),ge).superRefine((e,t)=>{(!ge.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),Lh=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),Bt=mt.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r)){if(i==="$savedGroup"&&!R.strictObject({id:R.uuid(),attributeKey:R.string().min(1).max(128).optional()}).safeParse(a).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(o=>["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!Lh.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof a=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(a)||[...a.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(o=>Number(o[1])>255||Number(o[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(a.replace(/\\u([0-9a-f]{4})/gi,(o,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(a)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(a)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),Bh=R.discriminatedUnion("type",[R.strictObject({type:R.literal("condition"),condition:Bt}),R.strictObject({type:R.literal("list"),attributeKey:R.string().min(1).max(128),values:R.array(R.union([R.string(),R.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function En(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r))i==="$savedGroup"&&a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.id=="string"?t.add(a.id):["$inGroup","$notInGroup"].includes(i)&&typeof a=="string"?t.add(a):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(a)}return n(e),[...t]}var zh=R.record(R.uuid(),Bh).superRefine((e,t)=>{let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(a),o.type==="condition"&&En(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),fs=R.tuple([R.number().min(0).max(1),R.number().min(0).max(1)]).refine(([e,t])=>e<=t),El=R.strictObject({attribute:R.string().optional(),seed:R.string().min(1),hashVersion:R.literal(2),ranges:R.array(fs).min(1).max(100)}),$h=R.strictObject({id:R.string().min(1).max(128),condition:Bt,gate:R.boolean().optional()}),ms={id:R.string().max(128).optional(),condition:Bt.optional(),parentConditions:R.array($h).max(50).optional(),filters:R.array(El).max(20).optional()},Gh=R.union([R.strictObject({...ms}),R.strictObject({...ms,force:ge,coverage:R.number().min(0).max(1).optional(),range:fs.optional(),seed:R.string().min(1).optional(),hashAttribute:R.string().optional(),hashVersion:R.literal(2).optional()}),R.strictObject({...ms,type:R.literal("experiment-ref"),experimentId:R.uuid(),values:R.record(R.string().min(1),ge),meta:R.record(R.string().min(1),R.strictObject({passthrough:R.boolean()})).optional()})]),Kh=R.strictObject({defaultValue:ge,rules:R.array(Gh).max(100)}),QI=R.record(R.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Kh).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${a}`});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${a}`});return}n.add(a);for(let s of o.rules)for(let c of s.parentConditions??[])i(c.id);n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),Hh=R.strictObject({name:R.string().max(80),reason:R.string().max(500),dateStarted:R.iso.datetime({offset:!0}),dateEnded:R.iso.datetime({offset:!0}).nullable(),coverage:R.number().min(0).max(1),variationWeights:R.array(R.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Bt,savedGroups:R.array(R.strictObject({match:R.enum(["any","all","none"]),ids:R.array(R.uuid()).min(1)})).max(50),namespace:R.strictObject({id:R.uuid(),ranges:R.array(fs).min(1)}).nullable(),seed:R.string().min(1).max(128)}),Qh=R.strictObject({key:R.string().min(1).max(128),name:R.string().min(1).max(80),hypothesis:R.string().max(2e3),status:R.enum(["draft","running","stopped"]),hashAttribute:R.string().min(1).max(128),fallbackAttribute:R.string().max(128).nullable(),hashVersion:R.literal(2),disableStickyBucketing:R.boolean(),bucketVersion:R.number().int().min(0).max(1e3),minBucketVersion:R.number().int().min(0).max(1e3),variations:R.array(R.strictObject({id:R.string().min(1),key:R.string().min(1),name:R.string().max(80),description:R.string().max(500)})).min(2).max(20),phases:R.array(Hh).min(1).max(100),releasedVariationId:R.string().nullable(),excludeFromPayload:R.boolean(),statusSchedule:R.strictObject({startAt:R.iso.datetime({offset:!0}).nullable(),stopAt:R.iso.datetime({offset:!0}).nullable(),stopAfter:R.strictObject({value:R.number().int().positive().max(36500),unit:R.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let i=e.phases[r-1];return!i?.dateEnded||Date.parse(n.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],a,o)=>r>=i||o.some(([s,c],u)=>u!==a&&r<c&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var Jh=Qh.safeExtend({filters:R.array(El).optional()}),Zh=R.strictObject({experiments:R.record(R.uuid(),Jh),savedGroups:zh}),bi=R.strictObject({attributeName:R.string(),attributeValue:R.string(),assignments:R.record(R.string(),R.string())}),JI=R.strictObject({snapshot:Zh,attributes:mt,results:mt,stickyBucketAssignmentDocs:R.record(R.string(),bi)}),ZI=R.strictObject({variantKey:R.string().nullable(),bucketVersion:R.number().int().min(0),source:R.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:R.number().min(0).max(1).optional(),stickyBucketUsed:R.boolean().optional(),hashUsed:R.boolean().optional()});function Un(e){let t=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function r(a,o){if(n(a))for(let[s,c]of Object.entries(a))s==="$elemMatch"?i(c,o):s==="$not"?r(c,o):s==="$all"&&Array.isArray(c)&&c.forEach(u=>r(u,o))}function i(a,o=""){if(n(a)){for(let[s,c]of Object.entries(a))if(["$and","$or","$nor"].includes(s)&&Array.isArray(c))c.forEach(u=>i(u,o));else if(s==="$not")i(c,o);else if(s==="$savedGroup"&&n(c))typeof c.attributeKey=="string"&&t.add(c.attributeKey);else if(!s.startsWith("$")){let u=o?`${o}.${s}`:s;t.add(u),r(c,u)}}}return i(e),[...t]}var Wh=wt.enum(["active","inactive"]),Yh=wt.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))["__proto__","constructor","prototype"].includes(o)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(s,a+1)}}return r(e,0),e},mt),Xh=wt.strictObject({id:wt.string().trim().min(1).max(255),name:wt.string().trim().min(1).max(255),status:Wh,metadata:Yh}),nv=Xh.extend({internal_id:wt.uuid(),project_id:wt.uuid(),environment_id:wt.uuid(),created_at:wt.iso.datetime({offset:!0}),updated_at:wt.iso.datetime({offset:!0})}),kl=wt.union([wt.strictObject({id:wt.string().trim().min(1).max(255)}),wt.strictObject({internalId:wt.uuid()})]),rv=wt.enum(["customer","merchandise","context"]),iv=wt.enum(["system","stored","request"]),ov=wt.enum(["customer","merchandise","mixed"]),Rl=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function gs(e,t={},n=new Set){if(Un(e).some(Rl))return!0;for(let r of En(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Rl(i.attributeKey)||i?.type==="condition"&&gs(i.condition,t,n))return!0}return!1}import{z as eA}from"zod";var tA=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,ln=eA.string().max(16).regex(tA,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");var mv=W.enum(["draft","active","paused","archived"]),Ln=W.discriminatedUnion("type",[W.object({type:W.literal("percent"),percentOff:W.number().min(1).max(100).multipleOf(.01)}).strict(),W.object({type:W.literal("amount"),amountOffCents:W.number().int().min(1).max(1e8),currency:fe}).strict()]),Jt=W.discriminatedUnion("type",[W.object({type:W.literal("once")}).strict(),W.object({type:W.literal("repeating"),months:W.number().int().min(1).max(36)}).strict(),W.object({type:W.literal("forever")}).strict()]),jl=[W.object({type:W.literal("all")}).strict(),W.object({type:W.literal("plans"),planIds:W.array(W.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],nA=W.discriminatedUnion("type",[...jl,W.strictObject({type:W.literal("merchandise"),scope:W.discriminatedUnion("type",[W.strictObject({type:W.literal("all")}),W.strictObject({type:W.literal("selected"),merchandiseIds:W.array(W.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),W.strictObject({type:W.literal("condition"),condition:Bt})])})]),hs=W.discriminatedUnion("type",[...jl,W.strictObject({type:W.literal("merchandise"),scope:W.strictObject({type:W.enum(["all","selected","condition"])})})]),rA=W.strictObject({firstPurchaseOnly:W.boolean(),condition:Bt}),fv=W.object({name:W.string().trim().min(1).max(80),description:W.string().max(500),discount:Ln,duration:Jt,appliesTo:nA,eligibility:rA,selfClaimEnabled:W.boolean().default(!1),startsAt:W.iso.datetime().nullable(),endsAt:W.iso.datetime().nullable(),totalLimit:W.number().int().min(1).max(1e6).nullable(),perCustomerLimit:W.number().int().min(1).max(10),grantWindowHours:W.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!gs(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),gv=W.object({code:W.string().trim().transform(e=>e.toUpperCase()).pipe(W.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:W.number().int().min(1).max(1e6).nullable(),expiresAt:W.iso.datetime().nullable(),firstPurchaseOnly:W.boolean(),minimumAmountCents:W.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:fe.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Si=W.object({id:W.uuid(),couponId:W.uuid(),status:W.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:W.iso.datetime(),expiresAt:W.iso.datetime(),coupon:W.object({name:W.string(),discount:Ln,duration:Jt,appliesTo:hs}).strict()}).strict(),Tl=W.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var ql=A.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),As=A.string().regex(/^(0|[1-9]\d{0,14})$/),Vr=A.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),iA=A.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),xi=iA,Rn=me.refine(e=>/[1-9]/.test(e)),Tt=A.iso.datetime({offset:!0}),Ro=e=>{let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},oA=A.array(A.object({upTo:Rn.nullable(),unitAmountMinor:ql,flatAmountMinor:A.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&Ro(t.upTo)>Ro(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),aA=A.discriminatedUnion("kind",[A.object({kind:A.literal("flat"),units:Rn,unitAmountMinor:ql}).strict(),A.object({kind:A.enum(["graduated","volume"]),units:Rn,tiers:oA}).strict()]).refine(e=>e.kind==="flat"||!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),sA=A.strictObject({interval:A.enum(["month","year"]),count:A.number().int().min(1).max(12),anchor:A.enum(["membership","calendar"])}),Ii=A.object({currency:fe,pricing:aA,billingCycle:sA.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Nl={requestId:A.uuid(),productVersionId:A.uuid(),internal_feature_id:A.uuid(),currency:fe},Vl=A.strictObject({interval:A.enum(["hour","day","week","month"]),intervalCount:A.number().int().min(1).max(12),limit:A.number().int().min(1).max(1e6)}),Ul=A.discriminatedUnion("kind",[A.object({...Nl,kind:A.literal("auto_topup"),threshold:Ao,quantity:Rn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Vl.optional()}).strict(),A.object({...Nl,kind:A.literal("postpaid"),maxAmountMinorPerPeriod:xi,maxOutstandingMinor:xi}).strict()]),Dl={productVersionId:A.uuid(),internal_feature_id:A.uuid(),currency:fe},Ll=A.discriminatedUnion("kind",[A.object({...Dl,kind:A.literal("auto_topup"),threshold:Ao,quantity:Rn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Vl.optional(),purchaseAmountMinor:xi,purchaseUnits:Rn}).strict(),A.object({...Dl,kind:A.literal("postpaid"),maxAmountMinorPerPeriod:xi,maxOutstandingMinor:xi,cashPrice:Ii}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),ko=A.object({id:A.uuid(),terms:Ll,status:A.enum(["prepared","active","revoked","blocked"]),createdAt:Tt,acceptedAt:Tt.nullable(),effectiveAt:Tt.nullable(),revokedAt:Tt.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),Bl=A.object({authorizationId:A.uuid(),terms:Ll,setupUrl:A.url().nullable()}).strict(),zl=A.object({authorizationId:A.uuid(),accepted:A.literal(!0)}).strict(),$l=A.object({authorizationId:A.uuid(),requestId:A.uuid()}).strict(),Gl=A.object({internal_feature_id:A.uuid(),entityId:A.uuid().nullable(),interval:A.enum(["day","week","month","year"]),anchor:A.enum(["billing_cycle","utc"]).optional(),basis:A.enum(["usage","credits"]),filter:pt.optional(),limit:me.nullable(),thresholds:A.array(A.number().positive().max(1)).max(8),includedThresholds:A.array(A.number().positive().max(1)).max(8).optional(),absoluteThresholds:A.array(Rn).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>{let r=e.thresholds[n-1];return n===0||r!==void 0&&t>r})&&(e.includedThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&t>i})&&(e.absoluteThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&Ro(t)>Ro(i)}),"Notification thresholds must increase"),cA=Gl.safeExtend({requestId:A.uuid()}),Fl={control:A.literal("overage"),requestId:A.uuid(),internal_feature_id:A.uuid(),entityId:A.uuid().nullable()},uA=A.discriminatedUnion("action",[A.strictObject({...Fl,action:A.literal("set"),allowed:A.boolean().nullable(),overageLimit:me.nullable(),skipOverageBilling:A.boolean()}),A.strictObject({...Fl,action:A.literal("remove")})]),Kl=A.union([cA,uA]),lA=A.strictObject({internal_feature_id:A.uuid(),entityId:A.uuid().nullable(),allowed:A.boolean().nullable(),overageLimit:me.nullable(),skipOverageBilling:A.boolean(),interval:A.enum(["day","week","month","year"]),startsAt:Tt,endsAt:Tt,used:A.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:A.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:A.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),dA=A.object({internal_feature_id:A.uuid(),entityId:A.uuid().nullable(),interval:A.enum(["day","week","month","year"]),anchor:A.enum(["billing_cycle","utc"]).optional(),basis:A.enum(["usage","credits"]),filter:pt.optional(),startsAt:Tt,endsAt:Tt,used:Lt,reserved:Lt,limit:me.nullable(),thresholds:A.array(A.number().positive().max(1)).max(8),notifiedThresholds:A.array(A.number().positive().max(1)).max(1024),includedThresholds:A.array(A.number().positive().max(1)).max(8).optional(),includedAllowance:A.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:A.array(A.number().positive().max(1)).max(1024).optional(),absoluteThresholds:A.array(Rn).max(8).optional(),notifiedAbsoluteThresholds:A.array(Rn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||me.safeParse(e.used).success&&me.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),pA=A.object({authorizationId:A.uuid(),status:A.enum(["idle","pending","blocked"]),taskId:A.uuid().nullable(),invoiceId:A.uuid().nullable(),hostedInvoiceUrl:A.url().nullable(),purchaseCount:A.number().int().nonnegative(),purchaseWindowEndsAt:Tt.nullable(),attemptCount:A.number().int().nonnegative(),failedAttemptCount:A.number().int().nonnegative(),suspendedAt:Tt.nullable(),nextAttemptAt:Tt.nullable(),failureReason:A.string().min(1).max(240).nullable()}).strict(),Hl=A.object({internal_feature_id:A.uuid().optional(),entityId:A.uuid().optional()}).strict(),ys=A.object({authorizations:A.array(ko).max(100),limits:A.array(Gl).max(100),overages:A.array(lA).max(100).optional(),windows:A.array(dA).max(200),autoTopups:A.array(pA).max(100),limited:A.boolean()}).strict(),mA=A.object({id:A.uuid(),internal_feature_id:A.uuid(),productVersionId:A.uuid(),authorizationId:A.uuid(),entityId:A.uuid().nullable(),units:me,amountMinor:Vr,cashPrice:Ii}).strict(),vi=A.object({id:A.uuid(),sourceKind:A.enum(["product","usage","manual"]),providerInvoiceId:A.string().min(1).max(240).nullable(),status:A.enum(["accruing","open","pending","paid","failed","void"]),currency:fe,startsAt:Tt.nullable(),endsAt:Tt.nullable(),amountMinor:A.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:A.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:As,paidAmountMinor:As,refundedAmountMinor:As,createdAt:Tt,hostedInvoiceUrl:A.url().nullable(),adjustment:A.object({originalInvoiceId:A.uuid(),amountMinor:A.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:Tt.nullable()}).strict().nullable(),lines:A.array(mA).max(100),linesLimited:A.boolean()}).strict(),Ql=A.object({invoiceId:A.uuid(),accepted:A.literal(!0)}).strict(),Jl=A.object({after:A.uuid().nullable(),limit:A.number().int().min(1).max(100)}).strict(),Zl=A.object({rows:A.array(vi).max(100),nextCursor:A.uuid().nullable()}).strict(),Ml=A.strictObject({id:A.string(),coupon:A.string(),start:A.number().nonnegative(),end:A.number().nullable()}),fA=A.strictObject({subscriptionId:A.string(),customerId:A.string(),accountId:A.string(),sourceItems:A.array(A.strictObject({id:A.string(),price_id:A.string(),quantity:A.number().int(),discounts:A.array(Ml).optional()})).max(100),items:A.array(A.strictObject({id:A.string(),price:A.string(),quantity:A.number().int(),discounts:A.array(A.strictObject({coupon:A.string().optional(),terms:A.strictObject({id:A.string(),name:A.string().optional(),percent_off:A.number().optional(),amount_off:A.number().optional(),currency:A.string().optional(),duration:A.enum(["once","forever","repeating"]),duration_in_months:A.number().optional()}).optional(),discount:A.string().optional(),receipt:Ml.optional()})).max(20)})).max(100)}),Wl=A.strictObject({membershipId:A.uuid(),requestId:A.uuid(),grantIds:A.array(A.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Yl=A.strictObject({membershipId:A.uuid(),operationId:A.uuid(),status:A.enum(["pending","effective"]),execution:fA.nullable(),grants:A.array(A.strictObject({id:A.uuid(),couponId:A.uuid(),name:A.string(),discount:Ln,duration:Jt,startedAt:Tt.nullable()})).max(20)});import{z as wi}from"zod";var Xl=wi.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),ed=wi.number().int().min(1).max(1e3),jo=wi.object({cap:me.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:wi.number().positive().max(1e4).nullable(),cycles:wi.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as Bn}from"zod";var td=Bn.strictObject({itemKey:Bn.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:Bn.uuid(),includedAmount:Bn.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Bn.number().int().min(0).max(1e4),terms:bo,pricing:hi.optional(),unitAmountMinor:Bn.number().int().min(0).max(1e8),productId:Bn.string().min(1).max(255).nullable(),priceId:Bn.string().min(1).max(255).nullable()}).superRefine((e,t)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&t.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{Qu(e.includedAmount,e.terms.units,e.quantity),yo({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as Y}from"zod";var pr=me.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Oi=Y.string().min(1).max(120),To=Y.enum(["cap","overflow"]),Zt=(e,t)=>{let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},Ci=e=>{try{return e()}catch{return!1}},Pi=Y.discriminatedUnion("operation",[Y.object({operation:Y.literal("quote"),overageBehavior:To.optional(),internal_feature_id:Y.uuid(),entityId:Y.uuid().optional(),quantity:pr,properties:pt}).strict(),Y.object({operation:Y.literal("consume"),overageBehavior:To.optional(),occurredAt:Y.iso.datetime({offset:!0}).optional(),internal_feature_id:Y.uuid(),entityId:Y.uuid().optional(),quantity:me,properties:pt,idempotencyKey:Oi}).strict(),Y.object({operation:Y.literal("reserve"),occurredAt:Y.iso.datetime({offset:!0}).optional(),internal_feature_id:Y.uuid(),entityId:Y.uuid().optional(),quantity:pr,properties:pt,idempotencyKey:Oi,expiresInSeconds:Y.number().int().min(1).max(86400)}).strict(),Y.object({operation:Y.literal("confirm"),operationId:Y.uuid(),quantity:pr,properties:pt.optional(),idempotencyKey:Oi}).strict(),Y.object({operation:Y.literal("refund"),operationId:Y.uuid(),quantity:pr,idempotencyKey:Oi}).strict(),Y.object({operation:Y.literal("release"),operationId:Y.uuid(),idempotencyKey:Oi}).strict()]),bs=Y.object({internal_credit_feature_id:Y.uuid().nullable(),internal_metered_feature_id:Y.uuid(),dimension:Y.string().min(1).max(64),counterKey:Y.string().min(1).max(240),cycleStart:Y.iso.datetime({offset:!0}),unitCost:me,units:pr,amount:Lt,tier:Y.number().int().min(1).max(12).nullable()}).strict(),mr=Y.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function nd(e,t){let n=e.reduce((r,i)=>r+Zt(i.units,12),0n)-Zt(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var rd=Y.discriminatedUnion("funding",[Y.strictObject({funding:Y.literal("balance"),sourceId:Y.uuid(),rolloverId:Y.uuid().nullable(),units:mr.refine(e=>/[1-9]/.test(e)),amount:Lt}),Y.strictObject({funding:Y.literal("unbilled"),units:mr.refine(e=>/[1-9]/.test(e))}),Y.object({funding:Y.literal("prepaid"),sourceId:Y.uuid(),units:pr,amount:Lt,pricing:Y.array(bs).min(1).max(12)}).strict().refine(e=>Ci(()=>e.pricing.reduce((t,n)=>t+Zt(n.units,6),0n)===Zt(e.units,6)&&e.pricing.reduce((t,n)=>t+Zt(n.amount,12),0n)===Zt(e.amount,12)&&e.pricing.every(t=>Zt(t.unitCost,6)*Zt(t.units,6)===Zt(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),Y.object({funding:Y.literal("postpaid"),invoiceLineId:Y.uuid().nullable(),units:pr,authorizationId:Y.uuid()}).strict()]),No=Y.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),id=Y.object({allowed:Y.boolean(),internal_feature_id:Y.uuid(),quantity:me,requestedQuantity:me.optional(),overageBehavior:To.optional(),reason:No.nullable(),allocations:Y.array(rd).max(500)}).strict().refine(e=>Ci(()=>e.allowed?e.reason===null&&nd(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Ci(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&Zt(e.requestedQuantity,6)>=Zt(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),_i=Y.object({id:Y.uuid(),internal_feature_id:Y.uuid(),kind:Y.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:Y.uuid().nullable(),quantity:me,requestedQuantity:me.optional(),overageBehavior:To.optional(),accepted:Y.boolean(),reason:Y.enum([...No.options,"expired"]).nullable(),createdAt:Y.iso.datetime({offset:!0}),reservationStatus:Y.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:Y.iso.datetime({offset:!0}).nullable(),allocations:Y.array(rd).max(500)}).strict().refine(e=>Ci(()=>e.accepted?e.reason===null&&nd(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Ci(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&Zt(e.requestedQuantity,6)>=Zt(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as _e}from"zod";var fr=_e.iso.datetime({offset:!0}),od=me.refine(e=>/[1-9]/.test(e)),ad=_e.strictObject({interval:Xl.exclude(["lifetime"]),count:ed}),gA=_e.strictObject({action:_e.literal("create"),requestId:_e.uuid(),internal_feature_id:_e.uuid(),entityId:_e.uuid().nullable(),amount:od.nullable(),expiresAt:fr.nullable(),reset:ad.nullable(),rollover:jo.nullable(),nextResetAt:fr.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),sd=_e.discriminatedUnion("action",[gA,_e.strictObject({action:_e.literal("update"),requestId:_e.uuid(),grantId:_e.uuid(),revision:_e.number().int().nonnegative(),amount:od.nullable(),expiresAt:fr.nullable(),rollover:jo.nullable(),nextResetAt:fr.nullable()}),_e.strictObject({action:_e.enum(["add","subtract","set_remaining"]),requestId:_e.uuid(),grantId:_e.uuid(),revision:_e.number().int().nonnegative(),amount:me}),_e.strictObject({action:_e.literal("revoke"),requestId:_e.uuid(),grantId:_e.uuid(),revision:_e.number().int().nonnegative()})]),Ss=_e.strictObject({id:_e.uuid(),internal_feature_id:_e.uuid(),entityId:_e.uuid().nullable(),amount:me.nullable(),reset:ad.nullable(),rollover:jo.nullable(),nextResetAt:fr.nullable(),startsAt:fr,expiresAt:fr.nullable(),revision:_e.number().int().nonnegative(),revoked:_e.boolean(),available:Lt,held:Lt,spent:Lt}),cd=_e.strictObject({customerId:_e.uuid(),after:_e.uuid().nullable(),limit:_e.number().int().min(1).max(100)}),ud=_e.strictObject({rows:_e.array(Ss).max(100),nextCursor:_e.uuid().nullable()});import{z as ee}from"zod";var Sn=ee.iso.datetime({offset:!0}),ld=ee.strictObject({invoiceId:ee.uuid(),after:ee.string().min(1).max(180).nullable(),limit:ee.number().int().min(1).max(100)}),hA=ee.strictObject({kind:ee.literal("product"),key:ee.string(),productVersionId:ee.uuid(),productName:ee.string(),itemKey:ee.string(),entityId:ee.uuid().nullable(),quantity:ee.number().positive(),subtotalMinor:ee.string().regex(/^-?\d+$/),discountMinor:ee.string().regex(/^\d+$/),taxMinor:ee.string().regex(/^-?\d+$/).nullable(),totalMinor:ee.string().regex(/^-?\d+$/),startsAt:Sn.nullable(),endsAt:Sn.nullable(),providerLineId:ee.string().nullable(),providerItemId:ee.string()}),dd=ee.strictObject({invoice:vi,items:ee.array(ee.discriminatedUnion("kind",[hA,ee.strictObject({kind:ee.literal("invoice_credit"),key:ee.string(),internal_feature_id:ee.uuid(),internal_credit_feature_id:ee.uuid(),name:ee.string(),units:me,reserved:me,amountMinor:Vr,grossAmountMinor:Vr,creditsAppliedMinor:Vr,properties:pt,cashPrice:Ii,providerItemId:ee.string().nullable(),creditProviderItemId:ee.string().nullable()}),ee.strictObject({kind:ee.literal("usage"),key:ee.string(),internal_feature_id:ee.uuid(),name:ee.string(),units:me,reserved:me,amountMinor:Vr,cashPrice:Ii})])).max(100),nextCursor:ee.string().min(1).max(180).nullable()}),AA=ee.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),xs=ee.strictObject({from:Sn,to:Sn,entityId:ee.uuid().optional(),snapshotAt:Sn.nullable(),after:ee.strictObject({at:Sn,id:ee.uuid(),position:ee.number().int().nonnegative()}).nullable(),limit:ee.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),pd=ee.strictObject({customerId:ee.uuid(),entityId:ee.uuid().nullable(),from:Sn,to:Sn,snapshotAt:Sn,totals:ee.array(ee.strictObject({internal_credit_feature_id:ee.uuid(),name:ee.string(),consumed:Lt,refunded:Lt,net:AA})).max(1e3),rows:ee.array(ee.strictObject({operationId:ee.uuid(),position:ee.number().int().nonnegative(),kind:ee.enum(["consume","confirm","refund"]),originalId:ee.uuid().nullable(),occurredAt:Sn,internal_feature_id:ee.uuid(),entitlementName:ee.string(),sourceId:ee.uuid(),internal_credit_feature_id:ee.uuid(),creditName:ee.string(),units:mr,amount:Lt,pricing:ee.array(bs).max(12),properties:pt})).max(100),nextCursor:xs.shape.after});import{z as k}from"zod";import{z as dn}from"zod";var yA=dn.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),bA=dn.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Do=dn.strictObject({internal_feature_id:dn.uuid(),entityId:dn.uuid().nullable()}),md=Do.extend({quantity:me,expectedRevision:dn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:dn.string().min(1).max(120),properties:pt.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Ei=Do.extend({operationId:dn.uuid().nullable(),usage:me,capacity:yA.nullable(),remaining:bA.nullable(),withinLimit:dn.boolean(),revision:dn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:dn.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");if(a===void 0||a==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var Nt=k.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),pn=k.iso.datetime({offset:!0}),SA=k.enum(["access","metered","credit"]),Ri={internal_feature_id:k.uuid(),key:lr,name:k.string().min(1).max(120),kind:SA},fd=k.object({customerId:k.uuid(),snapshotAt:pn,memberships:k.array(k.object({id:k.uuid(),productId:k.string().min(1).max(255),productVersionId:k.uuid(),billingProductVersionId:k.uuid(),version:k.number().int().positive(),key:k.string().min(1).max(64),name:k.string().min(1).max(120),groupId:k.string().max(255).nullable(),membershipType:k.enum(["main","addon"]),status:k.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:k.boolean(),accessEnabled:k.boolean(),renewalChange:k.object({productVersionId:k.uuid(),name:k.string().min(1).max(120),version:k.number().int().positive(),effectiveAt:pn,benefitsAppliedAt:pn.nullable(),timing:k.enum(["immediate","renewal"]),changeKind:k.enum(["plan","seats","quantity"]),feature:k.strictObject({internal_feature_id:k.uuid(),name:k.string().min(1).max(80),fromQuantity:k.number().int().min(0).max(1e4),toQuantity:k.number().int().min(0).max(1e4)}).optional(),seat:k.object({key:k.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:k.number().int().min(0).max(1e4),toQuantity:k.number().int().min(0).max(1e4)}).strict().nullable(),status:k.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:k.object({phase:k.enum(["paid","trial"]),startsAt:pn,endsAt:pn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:k.boolean(),balances:k.array(k.object({...Ri,usageType:k.enum(["consumable","non_consumable"]).nullable(),accessible:k.boolean(),unlimited:k.boolean(),available:Nt,held:Nt,debt:Nt,nextExpiresAt:pn.nullable(),usage:Ei.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:k.boolean()}).strict(),gd=k.enum(["source","usage","transaction","invoice","debt","settlement"]),Fo=k.object({at:pn,id:k.uuid(),type:gd}).strict(),hd=k.object({type:gd.nullable(),resourceKey:lr.optional(),kind:k.enum(["purchase","refund"]).optional(),topup:k.boolean().optional(),from:k.iso.date().nullable(),to:k.iso.date().nullable(),after:Fo.nullable(),limit:k.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),Ur={id:k.uuid(),occurredAt:pn},xA=k.discriminatedUnion("type",[k.strictObject({...Ur,type:k.literal("invoice"),status:k.string().min(1).max(80),paid:Nt,refunded:Nt,currency:fe,externalId:k.string().nullable()}),k.object({...Ur,...Ri,type:k.literal("source"),reason:k.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Nt,unlimited:k.boolean(),status:k.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:pn,expiresAt:pn.nullable(),orderId:k.uuid().nullable(),parentSourceId:k.uuid().nullable()}).strict(),k.object({...Ur,type:k.literal("usage"),internal_feature_id:k.uuid(),name:k.string().min(1).max(120),kind:k.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:k.uuid().nullable(),quantity:me,accepted:k.boolean(),reason:k.enum([...No.options,"expired"]).nullable(),properties:pt,reservationStatus:k.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:pn.nullable(),charges:k.array(k.discriminatedUnion("funding",[k.strictObject({funding:k.literal("balance"),sourceId:k.uuid(),rolloverId:k.uuid().nullable(),units:mr,amount:Nt}),k.strictObject({funding:k.literal("unbilled"),units:mr}),k.object({...Ri,funding:k.literal("prepaid"),amount:Nt}).strict(),k.object({funding:k.literal("postpaid"),invoiceId:k.uuid(),invoiceLineId:k.uuid(),authorizationId:k.uuid(),units:me,currency:fe}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),k.object({...Ur,type:k.literal("transaction"),purpose:k.enum(["product","invoice"]),productVersionId:k.uuid().nullable(),productName:k.string().min(1).max(120).nullable(),productVersion:k.number().int().positive().nullable(),invoiceId:k.uuid().nullable(),orderId:k.uuid(),originalId:k.uuid().nullable(),kind:k.enum(["purchase","refund"]),amountMinor:k.number().int().nonnegative().max(2e8).nullable(),currency:fe.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),k.object({...Ur,...Ri,type:k.literal("debt"),sourceId:k.uuid(),transactionId:k.uuid(),amount:Nt}).strict(),k.object({...Ur,...Ri,type:k.literal("settlement"),sourceId:k.uuid(),debtId:k.uuid(),kind:k.enum(["payment","usage_refund","payment_return"]),amount:Nt}).strict()]),Ad=k.object({customerId:k.uuid(),rows:k.array(xA).max(50),nextCursor:Fo.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as ce}from"zod";var bd=ce.object({customerId:ce.uuid()}).strict(),Sd=ce.discriminatedUnion("action",[ce.object({customerId:ce.uuid(),requestId:ce.uuid(),action:ce.literal("assign"),poolId:ce.uuid(),memberCustomerId:ce.uuid()}).strict(),ce.strictObject({customerId:ce.uuid(),requestId:ce.uuid(),action:ce.literal("assign_entity"),poolId:ce.uuid(),entityId:ce.uuid()}),ce.object({customerId:ce.uuid(),requestId:ce.uuid(),action:ce.literal("release"),poolId:ce.uuid(),slotId:ce.uuid()}).strict()]),ki=ce.number().int().nonnegative(),Is=ce.iso.datetime({offset:!0}),vs=ce.strictObject({internalId:ce.uuid(),id:ce.string(),name:ce.string().nullable(),version:ce.number().int().positive()}),yd=ce.enum(["active","past_due"]),ws=ce.strictObject({customerId:ce.uuid(),licenses:ce.array(ce.strictObject({id:ce.uuid(),linkId:ce.uuid(),parent:ce.strictObject({customerProductId:ce.uuid(),status:yd,product:vs}),product:vs,planLicense:ce.strictObject({id:ce.uuid(),prepaidOnly:ce.boolean(),isCustom:ce.boolean()}).nullable(),granted:ki,included:ki,paidQuantity:ki,usage:ki,remaining:ki,createdAt:Is}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:ce.array(ce.strictObject({id:ce.uuid(),linkId:ce.uuid(),status:yd,product:vs,entity:ce.strictObject({internalId:ce.uuid(),id:ce.string().nullable(),name:ce.string().nullable()}).nullable(),beneficiary:ce.strictObject({internalId:ce.uuid(),id:ce.string().nullable(),name:ce.string().nullable()}).nullable(),startedAt:Is.nullable(),endedAt:Is.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:ce.boolean()});import{z as se}from"zod";var ji=se.enum(["email","sms","voice","push"]),ew=se.enum(["resend","twilio","fcm","apns"]);var tw=se.string().regex(/^\+[1-9]\d{1,14}$/),IA=se.enum(["email_recipient","sms_segment","voice_second","push_device"]);var vA=se.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),wA=se.strictObject({subject:vA,html:se.string().min(1).max(131072).optional(),text:se.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),OA=se.strictObject({body:se.string().min(1).max(1600).refine(e=>e.trim().length>0)}),CA=se.strictObject({text:se.string().trim().min(1).max(4e3),language:se.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:se.number().int().min(1).max(900)}),PA=se.record(se.string().min(1).max(64),se.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),_A=se.strictObject({title:se.string().trim().min(1).max(200),body:se.string().trim().min(1).max(2e3),url:se.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:PA.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),xd=se.discriminatedUnion("channel",[se.strictObject({channel:se.literal("email"),content:wA}),se.strictObject({channel:se.literal("sms"),content:OA}),se.strictObject({channel:se.literal("voice"),content:CA}),se.strictObject({channel:se.literal("push"),content:_A})]),Id=se.strictObject({requestId:se.uuid(),customerId:se.uuid(),connectionId:se.uuid().optional(),message:xd,expiresAt:se.iso.datetime({offset:!0})}),EA=se.array(se.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),RA=se.discriminatedUnion("kind",[se.strictObject({kind:se.literal("all")}),se.strictObject({kind:se.literal("customers"),customerIds:EA})]),nw=se.strictObject({name:se.string().trim().min(1).max(120),connectionId:se.uuid().optional(),message:xd,audience:RA,frequencyLimit:se.number().int().min(1).max(100)}),vd=se.strictObject({requestId:se.uuid(),channel:ji,state:se.enum(["allowed","denied"]),expectedRevision:se.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),wd=se.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Od=se.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),rw=se.strictObject({meter:IA,estimatedUnits:se.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:se.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as xe}from"zod";import{z as X}from"zod";import{z as Lr}from"zod";var Ti=Lr.strictObject({internalFeatureId:Lr.uuid(),name:Lr.string().min(1).max(120),includedAmount:Lr.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:Lr.enum(["hour","day","week","month","year","lifetime"]),resetCount:Lr.number().int().min(1).max(100),terms:bo});import{z as et}from"zod";import{z as kA}from"zod";import{z as Br}from"zod";var Cd=Br.enum(["stripe","apple","google"]),Pd=Br.enum(["membership","credit_pack","lifetime"]),uw=Br.enum(["active","grace","suspended","inactive","revoked"]),lw=Br.strictObject({currency:Br.string().regex(/^[A-Z]{3}$/),micros:Br.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var zr=kA.object({provider:Cd,currency:fe}).strict();var zn=et.strictObject({internal_feature_id:et.uuid(),quantity:me.refine(e=>/[1-9]/.test(e)),properties:pt,entityId:et.uuid().optional()}),_d=et.strictObject({requirement:zn,commerce:zr.optional(),paywallId:et.uuid().optional()}),jA=et.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Os=et.strictObject({productId:et.string().min(1),productVersionId:et.string().min(1),name:et.string().min(1).max(120),action:et.enum(["purchase","upgrade","addon","topup"]),membershipId:et.string().min(1).nullable(),currency:fe,amountMinor:et.string().regex(/^(0|[1-9]\d{0,8})$/),interval:et.enum(["free","week","month","year","one_time"]),intervalCount:et.number().int().min(1).max(156)}),gr=et.strictObject({internal_feature_id:et.string().min(1),name:et.string().min(1).max(120),kind:et.enum(["access","metered","credit"]),quantity:me,allowed:et.boolean(),reason:jA.nullable(),preview:et.strictObject({scenario:et.enum(["feature_flag","usage_limit"]),candidates:et.array(Os).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),Sw=et.strictObject({paywallId:et.uuid(),requirement:zn});var qo=X.object({plan:X.string().min(1).max(200).optional(),coupon:X.uuid().optional(),promotionCode:X.uuid().optional(),picker:X.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Mo=X.object({text:X.string().optional(),label:X.string().optional(),alt:X.string().optional(),html:X.string().max(32768).optional(),price:X.object({current:X.string(),original:X.string().nullable(),period:X.string()}).optional(),code:X.string().optional(),countdownAt:X.iso.datetime().optional(),planId:X.string().min(1).max(200).optional(),planVersionId:X.string().min(1).max(200).optional(),currency:fe.optional(),couponId:X.uuid().optional(),offerId:X.uuid().optional(),unavailable:X.boolean().optional(),unavailableReason:X.string().optional(),missing:X.array(X.string()).optional()}).strict(),$r=X.object({paywall:gr.optional(),nodes:X.record(X.string(),X.object({base:Mo,picker:X.string().optional(),byPlan:X.record(X.string(),Mo).optional()}).strict()),plans:X.record(X.string(),X.object({id:X.string().min(1).max(200),versionId:X.string().min(1).max(200),available:X.boolean(),name:X.string(),price:X.string(),period:X.string(),currency:fe.optional(),amountMinor:X.number().int().nonnegative().optional(),interval:X.enum(["free","week","month","year","one_time"]).optional(),intervalCount:X.number().int().positive().optional(),prepaid:X.array(Ti).max(100).optional()}).strict()),pickers:X.record(X.string(),X.object({options:X.array(X.string().min(1).max(200)).max(20),selected:X.string().min(1).max(200).nullable()}).strict()),quantities:X.record(X.string(),X.strictObject({minimum:X.number().int().nonnegative(),maximum:X.number().int().nonnegative(),step:X.number().int().positive(),value:X.number().int().nonnegative(),label:X.string(),available:X.boolean()})).optional(),diagnostics:X.array(X.object({nodeId:X.string(),message:X.string()}).strict())}).strict();function Ed(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as b}from"zod";function TA(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Rd(e){let t={};function n(r){var i;if(TA(r)){let a=t[i=r.interaction.pickerId]??(t[i]={ids:[],defaultId:null});for(let s of r.children){let c=s.type==="stack"?s.bind?.plan:void 0;c&&!a.ids.includes(c)&&a.ids.push(c)}let o=r.children[r.interaction.defaultIndex];!a.defaultId&&o?.type==="stack"&&(a.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}import{z as kn}from"zod";var kd=kn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Vo=kn.strictObject({tiers:kn.array(kn.strictObject({id:kd,name:kn.string().trim().min(1).max(80)})).min(1).max(8),assignments:kn.array(kn.strictObject({productVersionId:kn.string().min(1).max(200),tierId:kd,period:kn.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Uo(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as re}from"zod";var NA=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],jd=re.enum(NA),Td=re.object({source:jd,layout:re.enum(["full","compact"]),resourceKey:lr.optional(),pageSize:re.number().int().min(1).max(50),showSources:re.boolean(),allowPurchase:re.boolean(),outputs:re.object({billing_adjustment:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),St=re.string().max(2e3),Nd=re.object({id:re.string().max(100),label:St,detail:re.array(St).max(12),value:St.optional(),status:St.optional(),facts:re.array(re.object({label:St,value:St}).strict()).max(1e3),purchaseId:re.uuid().optional(),invoiceUrl:re.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:re.array(re.strictObject({action:re.literal("invoice_open"),label:St})).max(1).optional(),membershipActions:re.array(re.object({value:re.string().max(100),label:St}).strict()).max(3).optional()}).strict(),DA=re.object({key:lr,name:St,spendable:St,reserved:St,available:St,expiry:St.nullable(),sources:re.array(Nd).max(50),sourceCount:re.number().int().nonnegative(),sourcePage:re.number().int().positive(),hasNextSources:re.boolean(),hasPreviousSources:re.boolean()}).strict(),FA=re.object({source:jd,status:re.enum(["idle","loading","ready","error"]),stale:re.boolean(),preview:re.boolean(),errorCode:re.string().max(80).optional(),errorMessage:St.optional(),resources:re.array(DA).max(500),rows:re.array(Nd).max(50),hasNext:re.boolean(),hasPrevious:re.boolean(),page:re.number().int().positive(),filter:re.string().max(40),updatedAt:re.iso.datetime().optional(),buyingId:re.uuid().optional(),membershipBusy:re.boolean().optional(),billingBusy:re.boolean().optional(),membershipReview:re.object({title:St,note:St,facts:re.array(re.object({label:St,value:St}).strict()).max(100)}).strict().optional(),membershipResult:St.optional()}).strict(),Dd=re.object({nodes:re.record(re.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),FA)}).strict(),jw=re.object({nodeId:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:re.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:re.string().max(100).optional()}).strict();var qA=4,fn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Di=b.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ke=b.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),VA=b.enum(["none","xs","sm","md","lg","xl"]),UA=b.enum(["none","sm","md","lg","full"]),Cs=b.string().regex(/^#[0-9a-fA-F]{6}$/),qd=b.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),Ps=b.union([qd,b.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),b.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),b.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Fd=b.object({primary:Cs,background:Cs,text:Cs,radius:UA,font:b.enum(["system","serif","rounded","mono"])}).strict(),Fi=b.union([b.enum(["primary","text","muted","background","surface"]),b.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Re=(e,t)=>b.number().int().min(e).max(t),Md=b.union([b.enum(["fit","fill"]),Re(1,1200)]),LA=b.object({top:Re(0,200),right:Re(0,200),bottom:Re(0,200),left:Re(0,200)}).strict(),BA=b.object({top:Re(-100,200),right:Re(-100,200),bottom:Re(-100,200),left:Re(-100,200)}).strict(),Vd=b.object({x:Re(0,100),y:Re(0,100)}).strict(),zA=b.discriminatedUnion("type",[b.object({type:b.literal("color"),color:Fi}).strict(),b.object({type:b.literal("linear"),angle:Re(0,360),stops:b.array(b.object({color:Fi,at:Re(0,100)}).strict()).min(2).max(4)}).strict(),b.object({type:b.literal("image"),src:Ps,fit:b.enum(["cover","contain"]),position:Vd.optional()}).strict()]),$A=b.discriminatedUnion("type",[b.object({type:b.literal("rect"),radius:b.union([Re(0,200),b.object({topLeft:Re(0,200),topRight:Re(0,200),bottomRight:Re(0,200),bottomLeft:Re(0,200)}).strict()])}).strict(),b.object({type:b.literal("pill")}).strict()]),GA=b.object({width:Re(0,12),color:Fi,style:b.enum(["solid","dashed"])}).strict(),KA=b.object({x:Re(-40,40),y:Re(-40,40),blur:Re(0,80),spread:Re(-20,40),color:Fi}).strict(),HA=b.object({font:b.enum(["system","serif","rounded","mono"]),size:Re(8,96),weight:b.number().int().min(100).max(900).multipleOf(100),lineHeight:b.number().min(.8).max(3),letterSpacing:b.number().min(-5).max(20),color:Fi,align:b.enum(["start","center","end"]),italic:b.boolean(),decoration:b.enum(["none","underline","line-through"]),transform:b.enum(["none","uppercase"])}).strict().partial(),hr=b.object({width:Md,height:Md,padding:LA,margin:BA,gap:Re(0,120),grow:b.union([b.boolean(),b.number().min(0).max(12)]),background:zA,opacity:b.number().min(0).max(1),clipContent:b.boolean(),shape:$A,border:GA,shadow:KA,text:HA}).strict().partial(),$t={id:Di,name:b.string().trim().min(1).max(60).optional(),hidden:b.boolean().optional(),style:hr.optional(),fallback:ke.optional()},QA=b.object({...$t,type:b.literal("text"),productField:b.enum(["name","price","trial","period"]).optional(),feature:b.object({id:b.uuid(),field:b.enum(["name","allowance"])}).strict().optional(),text:ke,variant:b.enum(["title","heading","body","caption"])}).strict(),JA=b.object({...$t,type:b.literal("image"),src:Ps,localizedSrc:b.record(ln,Ps).optional(),alt:ke,aspect:b.enum(["auto","1:1","4:3","16:9","3:1"]),fit:b.enum(["cover","contain"]),position:Vd.optional()}).strict(),ZA=b.object({...$t,type:b.literal("button"),label:ke,variant:b.enum(["primary","secondary","link"]),action:ke,purpose:b.enum(["purchase","navigation","close"]).optional(),bind:qo.optional()}).strict(),WA=b.object({...$t,type:b.literal("divider")}).strict(),YA=b.object({...$t,type:b.literal("customer_data"),title:ke,data:Td}).strict(),XA=b.object({...$t,type:b.literal("spacer"),size:VA}).strict(),ey=b.object({...$t,type:b.literal("custom_html"),html:b.record(ln,b.string().max(fn.customHtml)),css:b.string().max(fn.customCss)}).strict(),ty=b.object({...$t,type:b.literal("price"),fallback:ke,parts:b.object({current:hr.optional(),original:hr.optional(),period:hr.optional()}).strict().optional()}).strict(),ny=b.object({...$t,type:b.literal("coupon_code"),label:ke,fallback:ke}).strict(),ry=b.object({...$t,type:b.literal("countdown"),source:b.enum(["offer.ends_at","offer.expires_at","fixed"]),at:b.iso.datetime().optional(),granularity:b.enum(["day","hour","minute","second"]),expired:ke,fallback:ke}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),iy=b.object({...$t,type:b.literal("plan_picker"),label:ke,fallback:ke,planIds:b.array(b.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:b.string().min(1).max(200).optional(),grouping:Vo.safeExtend({monthLabel:ke,yearLabel:ke,unavailableLabel:ke}).optional(),states:b.object({selected:hr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Uo(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),oy=b.object({...$t,type:b.literal("quantity_picker"),bind:qo.optional(),label:ke,fallback:ke,internalFeatureId:b.uuid(),minimumQuantity:Re(0,1e4),maximumQuantity:Re(0,1e4),defaultQuantity:Re(0,1e4),step:Re(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),ay=b.discriminatedUnion("type",[b.object({type:b.literal("input"),label:ke,keyboard:b.enum(["text","email","tel","url"]),maxLength:Re(1,500)}).strict(),b.object({type:b.literal("multiselect"),label:ke,min:Re(0,50),max:Re(1,50)}).strict(),b.object({type:b.literal("select"),label:ke,defaultIndex:Re(0,49),purpose:b.enum(["option","product","tier"]).optional(),pickerId:Di.optional(),selectedStyle:hr.optional()}).strict(),b.object({type:b.literal("tabs"),label:ke,defaultIndex:Re(0,49),purpose:b.literal("tier").optional()}).strict(),b.object({type:b.literal("toggle"),label:ke,defaultEnabled:b.boolean()}).strict(),b.object({type:b.literal("carousel"),label:ke}).strict()]),mn={...$t,type:b.literal("stack"),direction:b.enum(["vertical","horizontal","overlay"]),align:b.enum(["start","center","end","stretch"]),justify:b.enum(["start","center","end","between"]),productSlot:b.object({index:Re(0,19),period:b.enum(["month","year"]).optional(),requireBinding:b.boolean().optional()}).strict().optional(),interaction:ay.optional(),states:b.object({selected:hr.optional()}).strict().optional(),purpose:b.literal("benefits").optional(),purchaseAction:ke.optional(),buttonVariant:b.enum(["primary","secondary","link"]).optional(),bind:qo.optional()},Ud=b.lazy(()=>b.object({...$t,type:mn.type,direction:mn.direction,align:mn.align,justify:mn.justify,children:b.array(sy).max(fn.children),productSlot:mn.productSlot,interaction:mn.interaction,states:mn.states,purpose:mn.purpose,purchaseAction:mn.purchaseAction,buttonVariant:mn.buttonVariant,bind:mn.bind}).strict()),sy=b.lazy(()=>b.union([Ud,QA,JA,ZA,WA,XA,ey,ty,ny,ry,iy,oy,YA])),cy=b.union([b.string().max(500),b.number().finite(),b.boolean(),b.null()]),Ni={id:ke,event:ke,properties:b.record(ke,cy).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},uy=b.discriminatedUnion("type",[b.object({...Ni,type:b.literal("navigate"),close:b.literal(!1),pageId:Di}).strict(),b.object({...Ni,type:b.literal("event"),close:b.boolean()}).strict(),b.object({...Ni,type:b.literal("close"),close:b.literal(!0)}).strict(),b.object({...Ni,type:b.literal("open_url"),close:b.boolean(),url:qd}).strict(),b.object({...Ni,type:b.literal("claim_offer"),close:b.boolean(),couponId:b.uuid()}).strict()]),ly=b.object({defaultLocale:ln,locales:b.record(ln,b.record(ke,b.string().max(fn.stringLength)))}).strict(),dy=b.enum(["popup","paywall","onboarding","page","banner"]);var py=b.discriminatedUnion("type",[b.object({type:b.literal("modal"),size:b.enum(["sm","md","lg"])}).strict(),b.object({type:b.literal("sheet"),size:b.enum(["sm","md","lg"])}).strict(),b.object({type:b.literal("fullscreen")}).strict(),b.object({type:b.literal("inline")}).strict()]);var my=b.object({kind:b.literal("screen"),schemaVersion:b.literal(qA),name:b.string().trim().min(1).max(80),surface:dy,initialPageId:Di.optional(),presentation:py,theme:Fd,pages:b.array(b.object({id:Di,name:b.string().trim().min(1).max(60),root:Ud,theme:Fd.optional(),editorPosition:b.object({x:b.number().finite().min(-1e5).max(1e5),y:b.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(fn.pages),strings:ly,actions:b.array(uy).max(fn.actions)}).strict();function Dt(e,t){for(let n of e.pages)$n(n.root,t)}var Wt=my.superRefine((e,t)=>{let n=fn;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(d=>d.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let d of e.actions)d.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(m=>m.id===d.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=d=>t.addIssue({code:"custom",message:d}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>fn.locales&&r(`\u6700\u591A ${fn.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let d of e.actions)a.has(d.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${d.id}`),a.add(d.id);let o=new Set;for(let d of e.pages)["next","back"].includes(d.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${d.id}`),o.has(d.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${d.id}`),o.add(d.id);let s=new Set,c=0,u=!1;Dt(e,(d,m)=>{if(c++,m>fn.depth&&(u=!0),s.has(d.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${d.id}`),s.add(d.id),d.type==="button"&&!a.has(d.action)&&r(`\u6309\u94AE ${d.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${d.action}`),d.type==="custom_html")for(let w of Object.keys(d.html))i.includes(w)||r(`\u81EA\u5B9A\u4E49 HTML ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${w}`);if(d.type==="image")for(let w of Object.keys(d.localizedSrc??{}))i.includes(w)||r(`\u56FE\u7247 ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${w}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${fn.depth} \u5C42`)});function $n(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)$n(i,t,n+1,e)}function Lo(e){let t=[],n=new Set;return Dt(e,r=>{let i=(a,o,s)=>{n.has(a)||(n.add(a),t.push({key:a,nodeId:r.id,nodeType:r.type,field:o,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function fy(e,t,n){if(t.field==="html"){let r;return Dt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=Mi(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function Gn(e){let t=Lo(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(a=>!fy(e,a,r)?.trim()).map(a=>a.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function gy(e,t){let n=null;return $n(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Mi(e,t){for(let n of e.pages){let r=gy(n.root,t);if(r)return r}return null}import{z as Et}from"zod";var dt=Et.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),_s=Et.strictObject({type:Et.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Et.boolean(),enum:Et.array(Et.string().max(255)).min(1).max(100).optional()}),Gr=_s.extend({type:Et.enum([..._s.shape.type.options,"array"]),items:_s.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),Kr=Gr.safeExtend({source:Et.discriminatedUnion("type",[Et.strictObject({type:Et.literal("input")}),Et.strictObject({type:Et.literal("node")}),Et.strictObject({type:Et.enum(["parameter","attribute"]),key:dt})])}),zw=Et.record(dt,Kr),Es=Et.record(dt,dt).refine(e=>Object.keys(e).length<=20);function rn(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>rn(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&Et.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function Rs(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&Rs(e.items,t.items)}function Bo(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,o=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,s=a.type==="parameter"||a.type==="attribute"?a.key:r,c=Object.hasOwn(o,s),u=o[s];if(a.type==="attribute"&&s.includes(".")&&(!c||s.startsWith("merchandise."))){u=o,c=!0;for(let d of s.split(".")){if(!u||typeof u!="object"||!Object.hasOwn(u,d)||Array.isArray(u)&&(!/^(0|[1-9]\d*)$/.test(d)||Number(d)>=u.length)){c=!1;break}u=u[d]}}if(!(!c||u===void 0)){if(!rn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function Hr(e,t){let n={};for(let[r,i]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,r))throw new Error(`Node output is missing: ${r}`);if(Object.hasOwn(n,i))throw new Error("Node outputs cannot overwrite one another");n[i]=t[r]}return n}function Ld(e,t,n){let r=new Set(Object.values(t.writes??{}));for(let[i,a]of Object.entries(n))if(!r.has(i)||e[i]?.source.type!=="node"||!rn(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}import{z as Ar}from"zod";var gn=Ar.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(e=>e.split(".").every(t=>!["__proto__","constructor","prototype"].includes(t)),"Reserved value path"),xn=Ar.discriminatedUnion("source",[Ar.strictObject({source:Ar.literal("literal"),value:ge}),Ar.strictObject({source:Ar.literal("variable"),key:Ar.string().min(1).max(255),path:gn.optional()})]);function Bd(e,t){if(!t)return e;for(let n of gn.parse(t).split(".")){if(Array.isArray(e)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=e.length)return;e=e[Number(n)];continue}if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function ks(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Bo(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ge.parse(Bd(n[e.key],e.path)))}function js(e,t){let n=[...t].sort((i,a)=>a.length-i.length).find(i=>e===i||e.startsWith(i+"."));if(!n)return null;let r=e===n?void 0:e.slice(n.length+1);return r&&!gn.safeParse(r).success?null:{key:n,path:r}}function Ts(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Dt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Ed))]}function zo(e){return Ts(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function Yt(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),d=c.replace(/^-/,""),m=d.replace(".","").length,w=(d.includes(".")?d.indexOf("."):m)+Number(u),I=w<=0?2-w+m:w>=m?w:m+1;n+=I+(c.startsWith("-")?1:0)-s.length}}return n}var Kn=xe.enum(["page","popup","banner"]),hy=3e5,zd=xe.strictObject({type:xe.enum(["string","number","boolean","strings","json"]),nullable:xe.boolean()}),Ay=xe.strictObject({inputs:xe.record(ke,zd.extend({required:xe.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:xe.record(ke,zd).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),yy=xe.strictObject({kind:Kn,schemaVersion:xe.literal(1),name:xe.string().trim().min(1).max(80),screen:Wt,contract:Ay}),$o=yy.superRefine((e,t)=>{let n=(i,a)=>t.addIssue({code:"custom",message:i,path:a});e.screen.surface!==e.kind&&n("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&n("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(i=>i.type!=="event"&&i.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let r=new Set(e.screen.actions.filter(i=>i.type==="event").map(i=>i.id));(Object.keys(e.contract.outputs).some(i=>!r.has(i))||[...r].some(i=>!Object.hasOwn(e.contract.outputs,i)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),Yt(e)>hy&&n("Content document exceeds its byte budget",[])});function by(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(n=>typeof n=="string")}}var Sy=$o.superRefine((e,t)=>{for(let n of zo(e.screen))Object.keys(e.contract.inputs).some(r=>n===r||n.startsWith(r+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of e.screen.actions){if(n.type!=="event")continue;let r=e.contract.outputs[n.id],i=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;r&&!by(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}Gn(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),$d=xe.strictObject({id:xe.uuid(),kind:Kn,projectId:xe.uuid(),environmentId:xe.uuid(),name:xe.string(),revision:xe.number().int().nonnegative(),status:xe.enum(["draft","published","archived"]),publishedVersionId:xe.uuid().nullable(),createdAt:xe.iso.datetime({offset:!0}),updatedAt:xe.iso.datetime({offset:!0})}),iO=$d.extend({draft:$o}),oO=xe.strictObject({rows:xe.array($d).max(200),nextCursor:xe.uuid().nullable()}),Ns=xe.strictObject({id:xe.uuid(),kind:Kn,resourceId:xe.uuid(),projectId:xe.uuid(),environmentId:xe.uuid(),version:xe.number().int().positive(),sourceRevision:xe.number().int().nonnegative(),document:Sy,createdAt:xe.iso.datetime({offset:!0})}),aO=Ns.omit({document:!0}),sO=xe.discriminatedUnion("action",[xe.strictObject({action:xe.literal("create"),kind:Kn,id:xe.uuid(),document:$o}),xe.strictObject({action:xe.literal("save"),kind:Kn,id:xe.uuid(),revision:xe.number().int().nonnegative(),document:$o}),xe.strictObject({action:xe.enum(["publish","archive"]),kind:Kn,id:xe.uuid(),revision:xe.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as Gd}from"zod";var Qr={funnelId:Gd.uuid().optional(),funnelVersionId:Gd.uuid().optional()};import{z as Ye}from"zod";import{z as Ne}from"zod";import{z as Qe}from"zod";var pO=Qe.discriminatedUnion("action",[Qe.strictObject({action:Qe.literal("create"),couponId:Qe.uuid(),productBindingId:Qe.uuid(),storeOfferId:Qe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Qe.enum(["introductory","promotional"])}),Qe.strictObject({action:Qe.literal("set_enabled"),id:Qe.uuid(),revision:Qe.number().int().nonnegative(),enabled:Qe.boolean()})]),mO=Qe.array(Qe.strictObject({id:Qe.uuid(),couponId:Qe.uuid(),productBindingId:Qe.uuid(),storeOfferId:Qe.string().min(1).max(255).nullable(),storeOfferType:Qe.enum(["introductory","promotional"]),enabled:Qe.boolean(),revision:Qe.number().int().nonnegative()})).max(500),Jr=Qe.strictObject({offerKind:Qe.enum(["none","introductory","promotional"]),offerId:Qe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Qe.number().int().min(0).max(1e8),trialDays:Qe.number().int().min(1).max(730).nullable()}).superRefine((e,t)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&t.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),fO=Qe.record(Qe.uuid(),Jr).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Ds=Ne.object({type:Ne.literal("native_purchase"),receiptId:Ne.uuid(),orderId:Ne.uuid(),productVersionId:Ne.uuid(),provider:Ne.enum(["apple","google"]),productId:Ne.string().min(1).max(255),productKind:Pd,replacement:Ne.strictObject({sourceOrderId:Ne.uuid(),sourceProductId:Ne.string().min(1).max(255),policy:Ne.enum(["apple_store","google_full_price"]),sourceAccountTokens:Ne.array(Ne.uuid()).max(50)}).nullable(),appAccountToken:Ne.uuid().optional(),obfuscatedAccountId:Ne.string().min(1).max(64).optional(),obfuscatedProfileId:Ne.uuid().optional(),basePlanId:Ne.string().min(1).max(255).optional(),offerId:Ne.string().min(1).max(255).optional(),offerKind:Ne.enum(["none","introductory","promotional"]),currency:fe,catalogAmountMinor:Ne.number().int().nonnegative().max(1e8),discountMinor:Ne.number().int().nonnegative().max(1e8),trialDays:Ne.number().int().min(1).max(730).nullable(),seatBundle:Ne.array(Ne.strictObject({key:Ne.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Ne.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Ne.strictObject({offerId:Ne.string().min(1).max(255),keyId:Ne.string().min(1).max(255),nonce:Ne.uuid(),signature:Ne.string().min(1).max(1024),timestamp:Ne.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as l}from"zod";import{z as Ie}from"zod/v4";import{z as xy}from"zod/v4";var Iy=xy.registry(),{BillingInterval:Kd}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:vy}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(Ie),{withSpecDefault:wy}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Iy),{COMMON:Hd}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Oy}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:Cy}=(e=>({COMMON_SET:new Set(e)}))(Hd),{hasNoDuplicateCurrencies:Qd}={hasNoDuplicateCurrencies:t=>{let n=new Set;for(let{currency:r}of t){let i=r.toLowerCase();if(n.has(i))return!1;n.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:Jd}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Py}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(Ie),{Infinite:_y}={Infinite:"inf"},{TierBehavior:Ey}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Zd}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Ry}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:ky}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:jy}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Ty}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Ie),{ApiCreditTierSchema:Wd}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(Ie),{VIOLATION_MESSAGES:Ny}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:Yd}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(Ie),{ModelMarkupsSchema:Dy}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(Ie,Yd),{InvoiceUsageEntrySchema:Fy}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(Ie),{AttachDiscountSchema:Xd}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(Ie),{CustomLineItemSchema:My}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(Ie),{UnixMsTimestampSchema:qy}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(Ie),{CreateInvoicePreviewLineSchema:Vy}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(Ie),{ReissueInvoiceParamsSchema:Fs}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(Ie),{InvoiceModeParamsSchema:yr}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(Ie),{InvoiceTemplateSchema:Uy}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(Ie),{BasePriceSchema:Ly}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(Ie,Kd,vy),{CURRENCY_CODES:By}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Hd,Oy,Cy),{ApiPriceProcessorsSchema:ep}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(Ie,Py),{AllocatedBillingFieldSchema:zy}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(Ie,Ry),{CreditDimensionNameSchema:$y}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Ie,ky,jy),{ApiCreditMatchSchema:tp}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Ty),{findCreditTierViolations:Gy}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(Ny),{ApiCreditMultiplierSchema:Ky}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(Ie,tp),{ProviderMarkupsSchema:Hy}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Ie,Yd),{InvoiceFeatureQuantitySchema:np}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(Ie,Zd,Fy),{CreateInvoicePreviewSchema:Ms}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(Ie,Vy),{SUPPORTED_SET:Qy}=(e=>({SUPPORTED_SET:new Set(e)}))(By),{ApiCreditDimensionBaseSchema:Jy}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(Ie,tp),{refineGraduatedTiers:rp}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:o}of i)r.addIssue({code:"custom",message:o,path:["tiers",a,"to"]})}}))(Gy),{ApiFeatureMarkupsOverrideSchema:Zy}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(Ie,Hy,Dy),{isValidCurrencyCode:Wy}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Qy),{ApiCreditDimensionSchema:Yy}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(Ie,Jy,Wd,rp),{CurrencyCodeSchema:ip}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(Ie,Wy),{AdditionalCurrencyTierSchema:Xy}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(Ie,ip),{ApiCreditSchemaItemBaseSchema:op}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(Ie,$y,Yy,Ky),{ApiFlatCreditSchemaItemSchema:eb}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(op,Ie),{AdditionalCurrencyPriceSchema:tb}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(Ie,ip),{AdditionalCurrencyTierArraySchema:nb}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Ie,Xy,Qd,Jd),{ApiGraduatedCreditSchemaItemSchema:rb}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(op,Ie,Wd,rp),{AdditionalCurrencyPriceArraySchema:ap}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Ie,tb,Qd,Jd),{ApiUsageTierWithCurrenciesSchema:ib}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(Ie,_y,nb),{ApiCreditSchemaItemSchema:ob}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(Ie,rb,eb),{BasePriceParamsSchema:ab}=((e,t,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(Ly,wy,Ie,ap),{PlanItemPriceParamsSchema:sb}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(Ie,ap,ib,Ey,Kd,Zd,zy),{ApiFeatureOverrideSchema:cb}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(Ie,ob,Zy),{InvoiceBasePriceParamsSchema:sp}=((e,t)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(ab,ep),{InvoiceItemPriceParamsSchema:ub}=((e,t)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(sb,ep),{InvoiceLicenseQuantitySchema:lb}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(Ie,sp,np),{InvoiceCustomizeItemSchema:db}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(Ie,ub,cb),{InvoiceCustomizeSchema:pb}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(Ie,sp,db),{InvoicePlanParamsSchema:mb}=((e,t,n,r,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(Ie,pb,np,lb,Xd),{CreateInvoiceParamsSchema:Zr}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(Ie,mb,My,Xd,qy);var lp=l.strictObject({requestId:l.uuid(),predecessorOperationId:l.uuid().optional(),invoiceMode:yr.optional(),entityId:l.uuid().optional(),billingSubscriptionId:l.uuid().optional(),newBillingSubscription:l.literal(!0).optional(),offerId:l.uuid().optional(),nativeOffer:Jr.optional(),plans:l.array(l.strictObject({productVersionId:l.uuid(),seatQuantities:l.record(mo,l.number().int().min(0).max(1e4)).optional(),featureQuantities:l.record(l.uuid(),l.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:l.enum(["stripe","apple","google"]),currency:fe}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(e.provider==="stripe"||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||e.provider!=="stripe"&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||e.provider==="stripe"&&!e.billingSubscriptionId,"A new billing subscription requires Stripe and no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Sr=l.strictObject({operationId:l.uuid()}),Ot=l.number().int().min(0).max(1e8),fb=l.strictObject({lineId:l.uuid(),productVersionId:l.uuid(),productName:l.string().min(1).max(80),interval:l.enum(["free","week","month","year","one_time"]),intervalCount:l.number().int().min(1).max(156).optional(),baseAmountMinor:Ot,seats:l.array(l.strictObject({key:mo,quantity:l.number().int().min(0).max(1e4),includedQuantity:l.number().int().min(0).max(1e4),maximumQuantity:l.number().int().min(0).max(1e4),unitAmountMinor:Ot})).max(20),prepaid:l.array(td).max(100).optional(),catalogAmountMinor:Ot,trial:l.strictObject({days:l.number().int().min(1).max(730),cardRequired:l.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+yo({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),dp=l.string().regex(/^[A-Za-z0-9_-]{1,200}$/),gb=l.strictObject({id:dp,name:l.string().min(1).max(40),percent_off:l.number().gt(0).max(100).optional(),amount_off:l.number().int().positive().optional(),currency:l.string().regex(/^[a-z]{3}$/).optional(),duration:l.enum(["once","repeating","forever"]),duration_in_months:l.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),hb=l.strictObject({subscriptionId:l.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:l.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:l.array(l.strictObject({id:l.string(),price_id:l.string(),quantity:l.number().int().nonnegative(),discounts:l.array(l.strictObject({id:l.string(),coupon:l.string(),start:l.number(),end:l.number().nullable()})).optional()})).min(1).max(100),prorationDate:l.number().int().nonnegative(),amountMinor:l.number().int().positive(),periodStartMs:l.number(),periodEndMs:l.number()}),pp=l.strictObject({invoiceMode:yr.optional(),append:hb.optional(),provider:l.literal("stripe"),executor:l.enum(["indiana","merchant"]),accountId:l.string().regex(/^acct_[A-Za-z0-9]+$/),mode:l.enum(["payment","subscription"]),lineItems:l.array(l.strictObject({price:l.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:l.number().int().min(1).max(1e4),priceId:l.uuid(),productName:l.string().min(1).max(80),amountMinor:l.number().int().min(0).max(1e8),currency:l.string().regex(/^[a-z]{3}$/),interval:l.enum(["week","month","year","one_off"]),intervalCount:l.number().int().min(1).max(52),slot:l.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:l.strictObject({mode:l.enum(["graduated","volume"]),tiers:l.array(l.strictObject({upTo:l.number().int().min(1).max(1e6).nullable(),unitAmountMinor:l.number().int().min(0).max(1e8),flatAmountMinor:l.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:l.array(l.strictObject({coupon:dp,terms:gb})).max(1),trialPeriodDays:l.number().int().min(1).max(730).nullable(),metadata:l.strictObject({grooveCheckoutId:l.uuid(),grooveCustomerId:l.uuid()}),expiresAt:l.iso.datetime({offset:!0})}),qi=l.strictObject({operationId:l.uuid(),entityId:l.uuid().nullable(),billingSubscriptionId:l.uuid().nullable(),discount:l.strictObject({offerId:l.uuid(),couponId:l.uuid(),discount:Ln,duration:Jt,amountMinor:Ot,allocations:l.array(l.strictObject({productVersionId:l.uuid(),amountMinor:Ot})).min(1).max(20),expiresAt:l.iso.datetime({offset:!0})}).nullable(),charge:l.strictObject({effectiveAt:l.iso.datetime({offset:!0}),periodEndsAt:l.iso.datetime({offset:!0}),debitMinor:Ot,discountMinor:Ot,taxMinor:Ot,totalMinor:Ot}).nullable(),expiresAt:l.iso.datetime({offset:!0}),provider:l.enum(["stripe","apple","google"]),nativeOffer:Jr.optional(),currency:fe,lines:l.array(fb).min(1).max(20),catalogAmountMinor:Ot,automaticTax:l.boolean(),execution:pp.nullable()}).refine(e=>e.provider==="stripe"?e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once")):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(e.provider==="stripe"||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(e.provider==="stripe"?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),Wr=l.strictObject({operationId:l.uuid(),orderId:l.uuid(),append:l.boolean().optional(),invoiceMode:l.boolean().optional(),status:l.enum(["pending","complete","cancelled","failed"]),executor:l.enum(["indiana","merchant"]),checkoutUrl:l.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:pp.nullable(),currency:fe,catalogAmountMinor:Ot,taxMinor:Ot,totalMinor:l.number().int().min(0).max(2e8).nullable(),quoteFinalized:l.boolean(),nativePurchase:Ds.nullable()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),Ko=l.strictObject({enabled:l.literal(!0),featureIds:l.array(l.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),mp=l.strictObject({requestId:l.uuid(),invoiceMode:yr.optional(),membershipId:l.uuid(),carryOverBalances:Ko.optional(),carryOverUsages:Ko.optional(),membershipIds:l.array(l.uuid()).min(1).max(20).optional(),prorationBehavior:l.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:l.enum(["immediate","renewal","store"]),change:l.discriminatedUnion("type",[l.strictObject({type:l.literal("plan"),productVersionId:l.uuid()}),l.strictObject({type:l.literal("seats"),licenseKey:mo,quantity:l.number().int().min(0).max(1e4)}),l.strictObject({type:l.literal("quantity"),internal_feature_id:l.uuid(),quantity:l.number().int().min(0).max(1e4)}),l.strictObject({type:l.literal("cancel")}),l.strictObject({type:l.literal("uncancel")}),l.strictObject({type:l.literal("billing_cycle"),billingCycleAnchor:l.union([l.literal("now"),l.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),Go=l.string().regex(/^price_[A-Za-z0-9]+$/),cp=l.strictObject({grooveUpdateId:l.uuid(),grooveCustomerId:l.uuid()}),up=l.strictObject({price:Go.nullable(),priceId:l.uuid().optional(),quantity:l.number().int().min(0).max(1e4)}),fp=l.strictObject({provider:l.literal("stripe"),invoiceMode:yr.optional(),executor:l.enum(["indiana","merchant"]),accountId:l.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:l.string().regex(/^sub_[A-Za-z0-9]+$/),action:l.enum(["update","cancel","schedule","release"]),update:l.strictObject({items:l.array(up).max(20),remove:l.array(Go).max(20),restoreItems:l.array(l.strictObject({price:Go,quantity:l.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:l.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:l.number().int().positive().optional(),paymentBehavior:l.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:l.boolean().optional(),clearCancelAt:l.literal(!0).optional(),billingCycleAnchorNow:l.literal(!0).optional(),metadata:cp}).nullable(),cancel:l.strictObject({prorate:l.literal(!1),invoiceNow:l.literal(!1)}).nullable(),schedule:l.strictObject({currentItems:l.array(l.strictObject({price:Go,quantity:l.number().int().min(0).max(1e4)})).max(20),nextItems:l.array(up).min(1).max(20),switchAt:l.number().int().positive(),interval:l.enum(["week","month","year"]),intervalCount:l.number().int().min(1).max(52),resetBillingCycleAnchor:l.literal(!0).optional(),metadata:cp}).nullable(),release:l.strictObject({schedule:l.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:l.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),qs=l.strictObject({carryOverBalances:Ko.optional(),carryOverUsages:Ko.optional(),operationId:l.uuid(),membershipId:l.uuid(),productVersionId:l.uuid(),timing:l.enum(["immediate","renewal"]),effectiveAt:l.iso.datetime({offset:!0}),expiresAt:l.iso.datetime({offset:!0}),currency:fe,creditMinor:Ot,debitMinor:Ot,discountMinor:Ot,taxMinor:Ot,totalMinor:Ot,retainedProductVersionIds:l.array(l.uuid()).max(19),execution:fp}),Ab=l.strictObject({operationId:l.uuid(),invoiceMode:l.boolean().optional(),membershipId:l.uuid(),productVersionId:l.uuid(),status:l.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:l.enum(["immediate","renewal"]),effectiveAt:l.iso.datetime({offset:!0}),checkoutUrl:l.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:l.enum(["indiana","merchant"]),execution:fp.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),yb=l.strictObject({operationId:l.uuid(),membershipId:l.uuid(),productVersionId:l.uuid(),timing:l.literal("store"),effectiveAt:l.null(),expiresAt:l.iso.datetime({offset:!0}),currency:fe,creditMinor:l.null(),debitMinor:l.null(),discountMinor:l.null(),taxMinor:l.null(),totalMinor:l.null(),retainedProductVersionIds:l.array(l.uuid()).max(19),store:l.strictObject({provider:l.enum(["apple","google"]),productId:l.string().min(1).max(255),catalogAmountMinor:Ot,policy:l.enum(["apple_store","google_full_price"])})}),bb=l.strictObject({operationId:l.uuid(),membershipId:l.uuid(),productVersionId:l.uuid(),status:l.enum(["prepared","pending","effective","cancelled","failed"]),timing:l.literal("store"),effectiveAt:l.iso.datetime({offset:!0}).nullable(),checkoutUrl:l.null(),nativePurchase:Ds.nullable()}),gp=l.union([qs,yb]),Vs=l.union([Ab,bb]),Vi=l.number().int().positive().max(2e8),br=l.number().int().min(0).max(2e8),hp=l.strictObject({requestId:l.uuid(),invoiceId:l.uuid(),mode:l.enum(["full","partial"]),amountMinor:Vi.optional(),entitlementAction:l.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),Ap=l.strictObject({provider:l.literal("stripe"),executor:l.enum(["indiana","merchant"]),accountId:l.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:l.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Vi,currency:l.string().regex(/^[a-z]{3}$/),metadata:l.strictObject({indianaRefundId:l.uuid()}),idempotencyKey:l.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:l.array(l.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),yp=l.strictObject({operationId:l.uuid(),invoiceId:l.uuid(),providerInvoiceId:l.string().regex(/^in_[A-Za-z0-9]+$/),currency:fe,paidMinor:br,refundedMinor:br,pendingMinor:br,amountMinor:Vi,mode:l.enum(["full","partial"]),entitlementAction:l.enum(["retain","revoke"]),revokes:l.strictObject({customerProductIds:l.array(l.uuid()).max(100),subscriptionIds:l.array(l.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),execution:Ap,expiresAt:l.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase()&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Ho=l.strictObject({operationId:l.uuid(),invoiceId:l.uuid(),providerInvoiceId:l.string().regex(/^in_[A-Za-z0-9]+$/),status:l.enum(["quoted","pending","succeeded","failed","expired"]),executor:l.enum(["indiana","merchant"]),currency:fe,amountMinor:Vi,mode:l.enum(["full","partial"]),entitlementAction:l.enum(["retain","revoke"]),refundId:l.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:Ap.nullable(),failureReason:l.string().min(1).max(200).nullable(),createdAt:l.iso.datetime({offset:!0}),completedAt:l.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),jO=l.strictObject({invoiceId:l.uuid(),currency:fe,paidMinor:br,refundedMinor:br,pendingMinor:br,refundableMinor:br,executor:l.enum(["indiana","merchant"]).nullable(),canRefund:l.boolean(),operations:l.array(Ho).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),TO=l.strictObject({requestId:l.uuid(),mode:l.enum(["full","partial"]),amountMinor:Vi.optional(),entitlementAction:l.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var bp=Ye.strictObject({requestId:Ye.uuid(),targets:Ye.array(Ye.strictObject({membershipId:Ye.uuid(),action:Ye.enum(["cancel","uncancel"]),timing:Ye.enum(["immediate","renewal"])}).refine(e=>e.action!=="uncancel"||e.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(e=>new Set(e.targets.map(t=>t.membershipId)).size===e.targets.length,"Duplicate batch target"),Qo=Ye.strictObject({batchId:Ye.uuid()}),Sb=Ye.strictObject({operationId:Ye.uuid(),membershipIds:Ye.array(Ye.uuid()).min(1).max(20),provider:Ye.enum(["stripe","apple","google"]),action:Ye.enum(["cancel","uncancel"]),timing:Ye.enum(["immediate","renewal"]),status:Ye.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:qs.nullable(),managementUrl:Ye.url().nullable(),failureCode:Ye.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Ui=Ye.strictObject({batchId:Ye.uuid(),ready:Ye.boolean(),status:Ye.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:Ye.iso.datetime({offset:!0}),acceptedAt:Ye.iso.datetime({offset:!0}).nullable(),groups:Ye.array(Sb).min(1).max(100)});import{z as Ce}from"zod";var xb=Ce.string().trim().min(1).max(240),Us={requestId:Ce.uuid(),reason:xb},Jo=Ce.discriminatedUnion("action",[Ce.strictObject({...Us,action:Ce.literal("start"),productVersionId:Ce.uuid(),entityId:Ce.uuid().optional(),days:Ce.number().int().min(1).max(730).optional()}),Ce.strictObject({...Us,action:Ce.literal("extend"),membershipId:Ce.uuid(),days:Ce.number().int().min(1).max(730)}),Ce.strictObject({...Us,action:Ce.literal("end"),membershipId:Ce.uuid()})]),Sp=Ce.strictObject({operationId:Ce.uuid()}),xp=Ce.iso.datetime({offset:!0}),Ib=Ce.strictObject({provider:Ce.literal("stripe"),executor:Ce.enum(["indiana","merchant"]),accountId:Ce.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Ce.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Ce.union([Ce.literal("now"),xp]),prorationBehavior:Ce.literal("none")}),Ls=Ce.strictObject({operationId:Ce.uuid(),action:Ce.enum(["start","extend","end"]),status:Ce.enum(["pending","effective"]),managedBy:Ce.enum(["indiana","stripe"]),membershipIds:Ce.array(Ce.uuid()).min(1).max(20),endsAt:xp.nullable(),execution:Ib.nullable()}).refine(e=>e.execution!==null==(e.managedBy==="stripe"&&e.status==="pending")&&e.action==="end"==(e.endsAt===null)&&(e.action!=="start"||e.managedBy==="indiana")&&(e.execution===null||e.execution.trialEnd==="now"==(e.action==="end")),"Only a pending Stripe trial change carries execution instructions"),VO=Ce.strictObject({groupId:Ce.uuid(),productVersionId:Ce.uuid(),enabled:Ce.boolean()});import{z as Ke}from"zod";var Ip=Ke.strictObject({requestId:Ke.uuid(),currency:fe,makeDefault:Ke.boolean()}),vp=Ke.strictObject({setupId:Ke.uuid()}),vb=Ke.strictObject({provider:Ke.literal("stripe"),executor:Ke.literal("merchant"),accountId:Ke.string().regex(/^acct_[A-Za-z0-9]+$/),mode:Ke.literal("setup"),currency:Ke.string().regex(/^[a-z]{3}$/),customer:Ke.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:Ke.uuid(),metadata:Ke.strictObject({grooveProjectId:Ke.uuid(),grooveEnvironmentId:Ke.uuid(),grooveCustomerId:Ke.uuid(),groovePaymentSetupId:Ke.uuid()}),setDefaultPaymentMethod:Ke.boolean(),expiresAt:Ke.iso.datetime({offset:!0})}),Bs=Ke.strictObject({id:Ke.uuid(),provider:Ke.literal("stripe"),status:Ke.enum(["prepared","complete","expired"]),currency:fe,makeDefault:Ke.boolean(),url:Ke.url().nullable(),createdAt:Ke.iso.datetime({offset:!0}),expiresAt:Ke.iso.datetime({offset:!0}),completedAt:Ke.iso.datetime({offset:!0}).nullable(),execution:vb.nullable()});import{z as Ct}from"zod";var wp=Ct.union([Ct.string(),Ct.number(),Ct.boolean(),Ct.null()]),Op=Ct.strictObject({customerId:Ct.uuid()}),Cp=Ct.strictObject({customerId:Ct.uuid(),provider:Ct.literal("stripe"),checkedAt:Ct.iso.datetime({offset:!0}),status:Ct.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ct.number().int().nonnegative(),differences:Ct.array(Ct.strictObject({subscriptionId:Ct.string().startsWith("sub_"),itemId:Ct.string().nullable(),field:Ct.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:wp,actual:wp})).max(1e4)});import{z as he}from"zod";var Zo=he.iso.datetime({offset:!0}),Wo=he.strictObject({createdAt:Zo,id:he.uuid()}),Yo=he.strictObject({customerId:he.uuid().optional(),entityId:he.uuid().optional(),productId:he.string().min(1).max(256).optional(),provider:he.enum(["stripe","apple","google","free"]).optional(),status:he.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Wo.optional(),limit:he.number().int().min(1).max(100).optional()}),zs={id:he.uuid(),customerId:he.uuid(),entityId:he.uuid().nullable(),productId:he.string().min(1).max(256),productVersionId:he.uuid(),name:he.string().min(1).max(120),provider:he.enum(["stripe","apple","google","free"]),createdAt:Zo},wb=he.strictObject({...zs,status:he.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:he.boolean(),billingSubscriptionId:he.uuid().nullable()}),Ob=he.strictObject({...zs,status:he.enum(["active","ended","refunded"]),orderId:he.uuid().nullable(),transactionId:he.uuid().nullable(),currency:fe.nullable(),amountMinor:he.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),Cb=he.strictObject({...zs,status:he.enum(["blocked","resolved"]),conflict:he.strictObject({detectedAt:Zo,blockingMembershipIds:he.array(he.uuid()).min(1).max(100),transactionId:he.uuid()}),resolvedAt:Zo.nullable()}),Pp=Yo.extend({status:he.enum(["blocked","resolved"]).optional()}),_p=he.strictObject({customerId:he.uuid(),orderId:he.uuid()}),Ep=he.strictObject({orderId:he.uuid(),status:he.enum(["blocked","resolved"])}),Rp=he.strictObject({items:he.array(wb).max(100),nextCursor:Wo.nullable()}),kp=he.strictObject({items:he.array(Ob).max(100),nextCursor:Wo.nullable()}),jp=he.strictObject({items:he.array(Cb).max(100),nextCursor:Wo.nullable()});import{z as Ze}from"zod";var Tp=Ze.union([Ze.strictObject({intent:Ze.literal("read"),requestId:Ze.uuid(),purchaseIntentId:Ze.uuid()}),Ze.strictObject({requestId:Ze.uuid(),provider:Ze.literal("apple"),purchaseIntentId:Ze.uuid(),productId:Ze.string().min(1).max(255).optional(),signedTransaction:Ze.string().min(1).max(131072)}),Ze.strictObject({requestId:Ze.uuid(),provider:Ze.literal("google"),purchaseIntentId:Ze.uuid(),productId:Ze.string().min(1).max(255).optional(),purchaseToken:Ze.string().min(1).max(16384)})]),Np=Ze.strictObject({requestId:Ze.uuid(),orderId:Ze.uuid(),purchaseIntentId:Ze.uuid(),status:Ze.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:fe,refunded:Ze.boolean(),completion:Ze.strictObject({transactionIds:Ze.array(Ze.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Ze.boolean()}).nullable()});import{z as V}from"zod";var Gs=V.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),Pb=V.record(V.string(),V.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),_b=3,Li=20,Eb=_b*Li,$s=V.strictObject({type:V.literal("product"),productId:Gs}),Dp={type:V.literal("group"),key:V.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:V.string().trim().min(1).max(80)},Rb=V.discriminatedUnion("type",[$s,V.strictObject({...Dp,items:V.array($s).max(Li)})]),kb=V.discriminatedUnion("type",[$s,V.strictObject({...Dp,items:V.array(Rb).max(Li)})]),jb=V.array(kb).max(Li).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&a(s.items)}}a(e),(n.size>Li||i>Eb)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Ks(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Ks(t))}var Yr=V.strictObject({lookupKey:V.string().trim().min(1).max(200),displayName:V.string().trim().min(1).max(1500),items:jb,metadata:Pb}),Tb=V.strictObject({product:V.record(V.string(),V.json()),prices:V.array(V.record(V.string(),V.json())),entitlements:V.array(V.record(V.string(),V.json())),freeTrials:V.array(V.record(V.string(),V.json())),licenses:V.array(V.record(V.string(),V.json()))}),Fp=Yr.extend({id:V.uuid(),projectId:V.uuid(),environmentId:V.uuid(),state:V.enum(["active","archived"]),isCurrent:V.boolean(),revision:V.number().int().nonnegative(),publishedVersionId:V.uuid().nullable(),createdAt:V.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),Mp=V.strictObject({id:V.uuid(),offeringId:V.uuid(),projectId:V.uuid(),environmentId:V.uuid(),version:V.number().int().positive(),document:Yr,productEvidence:V.record(Gs,Tb),createdAt:V.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=Ks(e.document);(!n.length||Fb(e.document).length>0||Object.keys(e.productEvidence).length!==n.length||n.some(r=>!Object.hasOwn(e.productEvidence,r)))&&t.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),Nb=V.strictObject({rows:V.array(Fp).max(200),versions:V.array(Mp).max(500)}),XO=V.discriminatedUnion("action",[V.strictObject({action:V.literal("create"),document:Yr}),V.strictObject({action:V.literal("save"),id:V.uuid(),revision:V.number().int().nonnegative(),document:Yr}),V.strictObject({action:V.enum(["publish","set_current","archive","restore"]),id:V.uuid(),revision:V.number().int().nonnegative()})]),eC=V.strictObject({record:Fp,version:Mp.nullable()}),qp=V.discriminatedUnion("type",[V.strictObject({type:V.literal("current")}),V.strictObject({type:V.literal("id"),id:V.uuid()}),V.strictObject({type:V.literal("lookup_key"),lookupKey:V.string().min(1).max(200)}),V.strictObject({type:V.literal("version"),versionId:V.uuid()})]),Db=V.strictObject({internalId:Gs,id:V.string(),name:V.string().nullable(),version:V.number().int().positive(),archived:V.boolean()}),tC=Nb.extend({products:V.array(Db).max(500),pagination:V.strictObject({rows:V.string().nullable(),versions:V.string().nullable(),products:V.string().nullable()}).optional()});function Fb(e){let t=[];Ks(e).length||t.push("Select at least one Product before publishing");function n(r){for(let i of r)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),n(i.items))}return n(e.items),t}import{z as Xo}from"zod";var Vp=Xo.strictObject({id:Xo.uuid(),offeringId:Xo.uuid(),version:Xo.number().int().positive(),document:Yr});import{z as ht}from"zod";import{z as ue}from"zod";import{z as Xr}from"zod";var ea=Xr.strictObject({items:Xr.array(Xr.strictObject({productVersionId:Xr.string().min(1).max(200),label:Xr.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Xr.string().min(1).max(200).nullable(),grouping:Vo.optional()});function Up(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(i=>i.versionId===r&&i.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}import{z as ft}from"zod";var Mb=ft.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ta=ft.discriminatedUnion("type",[ft.object({type:ft.literal("fixed"),productVersionId:ft.string().min(1).max(200)}).strict(),ft.object({type:ft.literal("picker"),pickerId:Mb,allowedProductVersionIds:ft.array(ft.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),jn=ft.discriminatedUnion("type",[ft.object({type:ft.literal("modal"),size:ft.enum(["sm","md","lg"])}).strict(),ft.object({type:ft.literal("sheet"),size:ft.enum(["sm","md","lg"])}).strict(),ft.object({type:ft.literal("fullscreen")}).strict(),ft.object({type:ft.literal("inline")}).strict()]);var Hs=ue.discriminatedUnion("type",[ue.strictObject({type:ue.literal("event"),event:ue.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ue.strictObject({type:ue.literal("open_url"),url:ue.url().refine(e=>new URL(e).protocol==="https:")})]),qb=Wt,Vb=ue.discriminatedUnion("type",[ue.object({type:ue.literal("checkout"),product:ta}).strict(),ue.object({type:ue.literal("close")}).strict(),ue.object({type:ue.literal("action"),action:Hs}).strict()]),ei=ue.object({schemaVersion:ue.literal(3),kind:ue.literal("paywall"),name:ue.string().trim().min(1).max(80),presentation:jn,requirement:zn.optional(),products:ea,offeringVersionId:ue.uuid().nullable(),offeringId:ue.uuid(),screen:qb,buttons:ue.record(ue.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Vb)}).strict(),yC=ei.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(r=>!["event","navigate"].includes(r.type)||r.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let r of Lb(e))t.addIssue({code:"custom",message:r});for(let r of Ub(e))t.addIssue({code:"custom",message:r});Gn(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(r=>r.type!=="navigate").length||e.screen.actions.some(r=>r.type!=="navigate"&&!Object.hasOwn(e.buttons,r.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(r=>r.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function Ub(e){let t=e.products.items.map(a=>a.productVersionId),n=Rd(e.screen),r=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),e.offeringVersionId||i.push("offering"),e.products.grouping&&(!Uo(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[o.pickerId];c&&(s=!0,(o.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!o.allowedProductVersionIds.includes(u)))&&i.push("picker")),Dt(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let d=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(d)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Dt(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(o=>!t.includes(o)))&&i.push("binding")}),[...new Set(i)]}function Lb(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),$n(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let d=e.screen.actions.find(w=>w.id===u);d?.type==="navigate"&&r.get(s.id).push(d.pageId);let m=e.buttons[u];s.id!==n.id&&m&&m.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var Lp=ue.object({id:ue.uuid(),projectId:ue.uuid(),environmentId:ue.uuid(),revision:ue.number().int().nonnegative(),state:ue.enum(["active","archived"]),publishedVersionId:ue.uuid().nullable(),updatedAt:ue.iso.datetime({offset:!0}),draft:ei}).strict(),bC=ue.object({rows:ue.array(Lp).max(200),nextCursor:ue.uuid().nullable()}).strict(),SC=Lp.omit({draft:!0}).extend({name:ue.string(),productCount:ue.number().int().nonnegative()}).strict(),xC=ue.discriminatedUnion("action",[ue.object({action:ue.literal("save"),id:ue.uuid().nullable(),revision:ue.number().int().nonnegative(),document:ei}).strict(),ue.object({action:ue.enum(["publish","archive"]),id:ue.uuid(),revision:ue.number().int().nonnegative()}).strict()]),IC=ue.object({paywalls:ue.array(ue.object({id:ue.uuid(),paywallId:ue.uuid(),version:ue.number().int().positive(),name:ue.string().min(1).max(80),presentation:jn,buttons:ei.shape.buttons}).strict()).max(500),limited:ue.boolean()}).strict();import{z as ve}from"zod";import{z as Ft}from"zod";var ti=Ft.string().regex(/^[a-f0-9]{64}$/),Bb=Mo.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Bp=Ft.strictObject({couponDigests:Ft.record(Ft.uuid(),ti),variables:Ft.record(ln,Ft.record(Ft.uuid(),Ft.partialRecord(Ft.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Ft.string()))),locales:Ft.record(ln,$r.extend({nodes:Ft.record(Ft.string(),Ft.strictObject({base:Bb})),plans:Ft.object({}).strict(),pickers:Ft.object({}).strict()}).omit({paywall:!0}))});import{z as De}from"zod";import{z as na}from"zod";var Qs=na.strictObject({eventsEnabled:na.boolean(),experimentViewsEnabled:na.boolean(),featureUsageEnabled:na.boolean()}),EC=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function zp(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as B}from"zod";var Js=B.tuple([B.number().min(0).max(1),B.number().min(0).max(1)]).refine(([e,t])=>e<=t),zb=B.strictObject({attribute:B.string().optional(),seed:B.string(),hashVersion:B.literal(2),ranges:B.array(Js).max(100)}),$b=B.strictObject({id:B.string().min(1).max(255),condition:Bt,gate:B.boolean().optional()}),Gb=B.strictObject({key:B.string().optional(),name:B.string().optional(),passthrough:B.boolean().optional()}),$p={condition:Bt.optional(),parentConditions:B.array($b).max(100).optional(),weights:B.array(B.number().min(0).max(1)).max(20).optional(),coverage:B.number().min(0).max(1).optional(),hashAttribute:B.string().optional(),fallbackAttribute:B.string().optional(),hashVersion:B.literal(2).optional(),disableStickyBucketing:B.boolean().optional(),bucketVersion:B.number().int().nonnegative().optional(),minBucketVersion:B.number().int().nonnegative().optional(),filters:B.array(zb).max(100).optional(),ranges:B.array(Js).max(20).optional(),meta:B.array(Gb).max(20).optional(),seed:B.string().optional(),name:B.string().optional(),phase:B.string().optional()},ni=B.strictObject({...$p,key:B.string().min(1).max(255),variations:B.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20),urlPatterns:B.array(B.strictObject({include:B.boolean(),type:B.enum(["regex","simple"]),pattern:B.string()})).max(100).optional(),force:B.number().int().nonnegative().optional(),active:B.boolean().optional(),persistQueryString:B.boolean().optional()}),Zs=B.strictObject({value:ge,variationId:B.number().int(),key:B.string(),name:B.string().optional(),bucket:B.number().optional(),passthrough:B.boolean().optional(),inExperiment:B.boolean(),hashUsed:B.boolean().optional(),hashAttribute:B.string(),hashValue:B.string(),featureId:B.string().nullable(),stickyBucketUsed:B.boolean().optional()}),Kb=B.strictObject({...$p,id:B.string().max(255).optional(),force:ge.optional(),variations:B.array(ge).min(2).max(20).optional(),key:B.string().optional(),range:Js.optional(),tracks:B.array(B.strictObject({experiment:ni,result:Zs})).max(100).optional()}),Hb=B.strictObject({defaultValue:ge.optional(),rules:B.array(Kb).max(500).optional()}),Bi=B.record(B.string(),B.union([B.strictObject({type:B.literal("hashed"),attributeKey:B.string(),values:B.array(B.string().regex(/^[a-f0-9]{64}$/))}),B.strictObject({type:B.literal("list"),attributeKey:B.string(),values:B.array(B.union([B.string(),B.number()]))}),B.strictObject({type:B.literal("condition"),condition:Bt})])),on=B.strictObject({scope:Ve,generation:B.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:B.iso.datetime({offset:!0}),expiresAt:B.iso.datetime({offset:!0}).nullable(),features:B.record(B.string(),Hb),savedGroups:Bi,experiments:B.record(B.uuid(),ni)});var zi=on.extend({analyticsConfig:Qs,remoteFeatures:De.array(De.string().min(1).max(255)).max(500)}),Ws=zi.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),Gp=De.strictObject({attributes:mt,features:De.array(De.string().min(1).max(255)).max(500).optional(),customerId:De.uuid().optional()}),Qb=De.strictObject({value:ge,source:De.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:De.boolean(),off:De.boolean(),ruleId:De.string(),experimentResult:Zs.optional()}),ra=De.strictObject({generation:on.shape.generation,evaluatedAt:on.shape.evaluatedAt,expiresAt:on.shape.expiresAt,features:De.record(De.string(),Qb),merchandiseContext:De.strictObject({merchandiseId:De.uuid(),merchandise:mt}).optional()}),Kp=De.strictObject({customerId:De.uuid().optional(),events:De.array(De.strictObject({eventUuid:De.uuid(),timestamp:De.iso.datetime({offset:!0}),name:De.string().min(1).max(255),merchandise:kl.optional(),properties:De.record(De.string(),ge).default({}),deviceId:De.string().min(1).max(255).optional(),sessionId:De.string().min(1).max(255).optional()})).min(1).max(100)}),Hp=De.strictObject({inserted:De.number().int().nonnegative(),duplicates:De.number().int().nonnegative(),rejected:De.number().int().nonnegative(),skipped:De.number().int().nonnegative(),analyticsConfig:Qs});import{z as U}from"zod";function Ys(e,t=[]){let n=[];Dt(e,i=>{i.hidden&&n.push("Hidden components must not be delivered"),t.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let r=new Set(Lo(e).map(i=>i.key));for(let[i,a]of Object.entries(e.strings.locales))for(let o of Object.keys(a))r.has(o)||n.push(`Unused string ${o} must not be delivered (${i})`);return n}function Qp(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Qp(t)??[])}}function Jb(e){let t=e.pages.map(i=>{let a=Qp(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(Lo({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([o])=>n.has(o)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function Jp(e,t=[]){let n=Wt.parse(structuredClone(Jb(e))),r=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(r);for(let a of n.pages)if(!r(a.root))throw new Error(`Page ${a.id} has no visible content`);let i=Ys(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as K}from"zod";import{z as N}from"zod";import{z as ot}from"zod";var ia=ot.strictObject({schemaVersion:ot.literal(1),renderKey:ot.string().min(1).max(256),routeTemplate:ot.string().startsWith("/").max(2048),selectors:ot.array(ot.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:ot.array(ot.number().int().min(0)).min(1),absent:ot.array(ot.number().int().min(0))}).superRefine((e,t)=>{let n=[...e.present,...e.absent];(new Set(e.selectors).size!==e.selectors.length||new Set(n).size!==n.length||n.length!==e.selectors.length||n.some(r=>r>=e.selectors.length))&&t.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),Zp=ot.strictObject({renderKey:ot.string().min(1).max(256),routeKey:ot.string().min(1).max(256),stateKey:ot.string().min(1).max(256),documentKey:ot.string().min(1).max(256),documentHash:ot.string().regex(/^[a-f0-9]{64}$/),compositionKey:ot.string().min(1).max(256),entryMode:ot.enum(["hard","soft"]),match:ot.strictObject({present:ot.array(ot.number().int().min(0)),absent:ot.array(ot.number().int().min(0))})});import{z as xr}from"zod";var Zb=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Xs="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Wb=xr.string().regex(new RegExp(`^${Xs}/${Xs}/${Xs}/manifest\\.json$`)),Wp=xr.strictObject({kind:xr.literal("gcs-resumable"),url:xr.url(),bucket:xr.enum(Zb),objectKey:Wb,byteLength:xr.number().int().positive(),expiresAt:xr.iso.datetime()}).superRefine((e,t)=>{let n=new URL(e.url),r=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${e.bucket}/o`||[...r.keys()].some(a=>!i.includes(a)||r.getAll(a).length!==1)||r.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(r.get("upload_id")??"")||r.has("name")&&r.get("name")!==`app-manifests/${e.objectKey}`||r.has("upload_protocol")&&r.get("upload_protocol")!=="resumable"||r.has("ifGenerationMatch")&&r.get("ifGenerationMatch")!=="0")&&t.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var ct=N.string().min(1).max(256),Xt=N.string().regex(/^[a-f0-9]{64}$/),oa=N.strictObject({versionId:N.uuid(),manifestDigest:Xt,sourceGraphDigest:Xt,pageKey:ct,stateKey:ct,documentKey:ct,documentHash:Xt,elementKey:ct.optional(),nodeId:ct.optional(),contentHash:Xt.optional(),renderKey:ct.optional()}),Yp=N.strictObject({pageKey:ct,documentKey:ct,expectedDocumentHash:Xt,renderKey:ct.optional(),nodeId:ct,elementKey:ct,expectedContentHash:Xt,property:N.enum(["text","fontSize","color"]),value:N.union([N.string().max(4e3),N.number().finite()])}),Xp=N.strictObject({versionId:N.uuid(),manifestDigest:Xt,sourceGraphDigest:Xt,pageKey:ct,stateKey:ct,documentKey:ct,documentHash:Xt,renderKey:ct.optional(),patches:N.array(Yp.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),Yb=/^[a-z][a-z0-9-]{0,39}$/,$i=N.string().regex(Yb),tc=N.enum(["web","ios","android"]),ZC=N.discriminatedUnion("action",[N.strictObject({action:N.literal("register"),requestId:N.uuid(),client:$i,platform:tc,label:N.string().trim().min(1).max(100),sha256:Xt,bytes:N.number().int().min(1),transferBytes:N.number().int().min(1)}),N.strictObject({action:N.literal("complete"),versionId:N.uuid()}),N.strictObject({action:N.literal("current"),versionId:N.uuid(),expectedCurrent:N.uuid().nullable()}),N.strictObject({action:N.literal("delivery"),enabled:N.boolean()}),N.strictObject({action:N.literal("changes"),versionId:N.uuid(),experimentId:N.uuid(),variationId:ct,changesetId:N.uuid().nullable(),expectedRevision:Xt.nullable(),editorUrl:N.string().url().max(2048),patches:N.array(Yp).max(200)})]),nc=N.strictObject({id:N.uuid(),projectId:N.uuid(),environmentId:N.uuid(),clientKey:$i,platform:tc,label:N.string(),sha256:Xt,bytes:N.number().int().positive(),objectKey:N.string(),state:N.enum(["uploading","ready","rejected"]),isCurrent:N.boolean(),revision:N.number().int().nonnegative(),createdAt:N.string(),expiresAt:N.string(),readyAt:N.string().nullable(),summary:N.record(N.string(),N.json()),routeTree:N.json().nullable(),validation:N.record(N.string(),N.json())}),Xb=N.strictObject({key:$i,platform:tc,currentId:N.uuid().nullable()}),WC=N.strictObject({rows:N.array(nc).max(100),nextCursor:N.uuid().nullable(),clients:N.array(Xb).max(20)}),ec=N.strictObject({storedBytes:N.number().int().nonnegative(),reservedBytes:N.number().int().nonnegative(),chargedBytes:N.number().int().nonnegative(),versions:N.number().int().nonnegative(),objects:N.number().int().nonnegative(),orphanObjects:N.number().int().nonnegative(),missingReadyObjects:N.number().int().nonnegative(),unknownObjectSizes:N.number().int().nonnegative(),byteLimit:N.number().int().positive(),versionLimit:N.number().int().positive(),remainingBytes:N.number().int().nonnegative()}),YC=N.strictObject({asOf:N.iso.datetime({offset:!0}),reclamation:N.literal("manual-review-required"),buckets:N.strictObject({source:ec,runtime:ec,previews:ec})}),XC=N.strictObject({version:nc,actorId:N.uuid(),claims:N.record(N.string(),N.json())}),eP=N.strictObject({version:nc,upload:Wp.nullable()}),tP=N.object({format:N.literal("indiana-route-state-index"),schemaVersion:N.literal(3),routes:N.array(N.object({routeKey:ct,path:N.string(),documentKey:ct,documentHash:Xt,initialStateKey:ct,initialRenderKey:ct})),renders:N.array(Zp)}).loose().superRefine((e,t)=>{(!e.renders||e.routes.some(n=>!e.renders?.some(r=>r.renderKey===n.initialRenderKey&&r.routeKey===n.routeKey&&r.documentKey===n.documentKey&&r.stateKey===n.initialStateKey&&r.documentHash===n.documentHash&&r.entryMode==="hard")))&&t.addIssue({code:"custom",message:"Incomplete render catalog"})}),nP=N.strictObject({rows:N.array(N.object({id:N.uuid(),name:N.string(),status:N.string(),variations:N.array(N.object({id:ct,key:ct,name:N.string().optional()}).loose())}).loose()),limited:N.boolean()}),rP=N.strictObject({enabled:N.boolean(),allowedOrigins:N.array(N.string())});import{z as ri}from"zod";var em=ri.strictObject({id:ri.uuid(),name:ri.string().trim().min(1).max(80),client:$i,source:oa,event:ri.enum(["screen_enter","button_click"]),cooldownSeconds:ri.number().int().min(0).max(2592e3),behavior:ri.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});import{z as Le}from"zod";var rc=ge,eS=["parameters","answers","results","variables"];function ic(e){return eS.some(t=>e===t||e.startsWith(t+"."))}function oc(e){let t={};for(let[r,i]of Object.entries(Bo(e.declarations,e))){let a=r.split(".");if(a.some(c=>["__proto__","constructor","prototype"].includes(c)))throw new Error("Reserved result path");let o=t;for(let c of a.slice(0,-1)){Object.hasOwn(o,c)||(o[c]={});let u=o[c];if(!u||typeof u!="object"||Array.isArray(u))throw new Error("Ambiguous result path");o=u}let s=a.at(-1);if(s===void 0)throw new Error("Empty result path");o[s]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!ic(r))),variables:t}}import{z as ut}from"zod";var aa=ut.discriminatedUnion("kind",[ut.object({kind:ut.literal("ledger"),cursor:Fo}).strict(),ut.object({kind:ut.literal("billing"),cursor:ut.uuid()}).strict()]),tS=ut.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Hn=ut.record(ut.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ut.union([ut.string().max(500),ut.boolean(),ut.array(ut.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),nS=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function ac(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>ac(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||nS.test(n)||ac(r,t+1)))}var rS=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,Qn=ut.record(tS,ge).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!ac(e)&&!rS.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var tm=ut.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),sa=ut.array(ut.object({variable:tm,componentId:tm,required:ut.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),gP=ut.object({bindings:sa,answers:Hn,values:ut.record(ut.string(),ge).optional()}).strict();import{z as iS}from"zod";var ca=iS.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var sc=Le.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),nm=Le.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),rm=Qn.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),cc=Le.record(sc,Le.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),oS=xn,im=Le.strictObject({type:Le.literal("external_task"),endpointId:Le.uuid(),taskKey:sc,inputs:Le.record(sc,oS).refine(e=>Object.keys(e).length<=20),outputs:cc}),om=Le.strictObject({maxAttempts:Le.number().int().min(1).max(5),retryDelaySeconds:Le.number().int().min(1).max(30),backoff:Le.enum(["fixed","exponential"]),requestTimeoutSeconds:Le.number().int().min(1).max(10),timeoutSeconds:Le.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var OP=Le.strictObject({outcome:Le.enum(["success","failure"]),data:rm});var CP=Le.discriminatedUnion("operation",[Le.strictObject({operation:Le.literal("signal"),runId:Le.uuid(),nodeId:nm,eventName:ca,eventId:Le.uuid(),data:rm}),Le.strictObject({operation:Le.literal("read_results"),runId:Le.uuid()})]),PP=Le.strictObject({scope:Ve,runId:Le.uuid(),eventId:Le.uuid(),accepted:Le.boolean()}),aS=Le.record(nm,rc),_P=Le.strictObject({scope:Ve,runId:Le.uuid(),results:aS});var hn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},am="00000000-0000-0000-0000-000000000000";import{z as H}from"zod";import{z as He}from"zod";var NP=He.enum(["local","remote"]),uc=He.strictObject({port:He.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ge.optional(),sticky:He.array(He.strictObject({expected:bi.nullable(),next:bi})).max(100),exposures:He.array(ge).max(100),features:He.array(ge).max(100)}),sm=He.strictObject({type:He.literal("evaluate"),receiptId:He.uuid(),environmentId:He.uuid(),policyRevision:He.number().int().nonnegative(),attributes:mt,sticky:He.record(He.string(),bi)}),cm=sm.extend({runId:He.uuid(),versionId:He.uuid(),nodeId:He.string().min(1).max(64),visit:He.number().int().nonnegative(),revision:He.number().int().nonnegative()}),lc=sm.omit({type:!0,receiptId:!0}).extend({type:He.literal("evaluate_segment")}),um=He.strictObject({nodeId:He.string().min(1).max(64),result:uc}),lm=lc.extend({runId:He.uuid(),versionId:He.uuid(),nodeId:He.string().min(1).max(64),visit:He.number().int().nonnegative(),revision:He.number().int().nonnegative(),parameters:Qn,answers:Hn,variables:He.record(He.string(),ge)});import{z as ie}from"zod";var dc=ie.array(ie.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),ua=ie.intersection(mt,ie.looseObject({tags:dc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),la=ie.string().trim().max(80),da=ie.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),pa=ie.union([ie.email().max(254),ie.literal("")]),ma=ie.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),dm=ie.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),pm=ie.object({externalUserId:dm.optional(),name:la.default(""),email:pa.default(""),phone:da.optional(),attributes:ua.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),fa=ie.discriminatedUnion("type",[ie.strictObject({type:ie.literal("id"),value:ie.uuid()}),ie.strictObject({type:ie.literal("externalUserId"),value:dm})]),ga=ie.strictObject({name:la.optional(),email:pa.optional(),phone:da.optional(),attributes:ua.optional(),fingerprint:ma.optional()}),ha=e=>!e.customerData||e.customer?.type==="externalUserId",Aa="customerData requires an externalUserId customer",ii=ie.object({id:ie.uuid(),externalUserId:ie.string().min(1).max(255).nullable(),name:la,email:pa,phone:da.optional(),attributes:ua,createdAt:ie.iso.datetime()}).strict(),mm=ie.object({customer:ii,changed:ie.boolean(),replayed:ie.boolean()}).strict(),sS=ie.discriminatedUnion("type",[ie.object({type:ie.literal("id"),value:ie.uuid()}).strict(),ie.object({type:ie.literal("externalUserId"),value:ie.string().trim().min(1).max(255)}).strict()]),cS=ie.object({name:la.optional(),email:pa.optional(),phone:da.optional(),attributes:ua.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ie.array(ie.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ie.strictObject({add:dc,remove:dc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),pc=ie.object({lookup:sS}).strict(),fm=pc.extend({requestId:ie.uuid(),patch:cS}).strict(),gm=ie.object({search:ie.string().trim().max(200).default(""),tag:ie.string().trim().max(40).default(""),planId:ie.string().max(200).default(""),versionId:ie.string().max(200).default(""),holdingStatus:ie.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ie.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ie.union([ie.iso.datetime(),ie.literal("")]).default(""),createdUntil:ie.union([ie.iso.datetime(),ie.literal("")]).default(""),offset:ie.coerce.number().int().min(0).max(1e5).default(0),limit:ie.coerce.number().int().min(1).max(100).default(50)}).strict(),hm=ie.object({customers:ii.array(),hasMore:ie.boolean(),total:ie.number().int().nonnegative().nullable(),evaluatedAt:ie.iso.datetime()}).strict();var Gi=H.discriminatedUnion("type",[H.strictObject({type:H.literal("literal"),value:ge}),H.strictObject({type:H.literal("variable"),key:dt,path:gn.optional()}),H.strictObject({type:H.literal("feature"),featureKey:H.string().min(1).max(128)})]),uS=H.strictObject({requestId:H.uuid(),decisionId:H.uuid(),customerId:H.uuid(),externalUserId:H.string().min(1).max(255).nullable(),versionId:H.uuid(),receiptId:H.uuid(),value:ge}),lS={funnelId:H.uuid(),requestId:H.uuid(),customer:fa,customerData:ga.optional(),attributes:mt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},KP=H.discriminatedUnion("operation",[H.strictObject({operation:H.literal("decide"),...lS}).refine(ha,Aa),H.strictObject({operation:H.literal("read_decision"),decisionId:H.uuid()}),H.strictObject({operation:H.literal("evaluate_decision"),decisionId:H.uuid(),requestId:H.uuid(),nodeId:H.string().min(1).max(64),visit:H.number().int().nonnegative(),revision:H.number().int().nonnegative(),receiptId:H.uuid(),policyRevision:H.number().int().nonnegative(),generation:H.string().min(1).max(256),result:uc}),H.strictObject({operation:H.literal("feature_config"),funnelId:H.uuid()}),H.strictObject({operation:H.literal("commit_decision_segment"),decisionId:H.uuid(),requestId:H.uuid(),nodeId:H.string().min(1).max(64),visit:H.number().int().nonnegative(),revision:H.number().int().nonnegative(),policyRevision:H.number().int().nonnegative(),generation:H.string().min(1).max(256),steps:H.array(um).max(32),boundary:H.strictObject({nodeId:H.string().min(1).max(64),visit:H.number().int().nonnegative()}).optional()}),H.strictObject({operation:H.literal("segment_configuration"),funnelId:H.uuid(),versionId:H.uuid()}),H.strictObject({operation:H.literal("configuration"),funnelId:H.uuid(),versionId:H.uuid().optional()}),H.strictObject({operation:H.literal("local_configuration"),funnelId:H.uuid()}),H.strictObject({operation:H.literal("report_used"),decisionId:H.uuid(),eventId:H.uuid(),occurredAt:H.iso.datetime({offset:!0}),reference:H.string().min(1).max(128).optional()})]),HP=H.strictObject({scope:Ve,decisionId:H.uuid(),requestId:H.uuid(),status:H.enum(["pending","completed","failed"]),decision:uS.nullable(),evaluation:H.discriminatedUnion("type",[cm,lm]).optional()}).refine(e=>e.status==="completed"==(e.decision!==null)&&(!e.decision||e.decision.decisionId===e.decisionId&&e.decision.requestId===e.requestId),"Completed decisions carry their committed result"),QP=H.strictObject({scope:Ve,decisionId:H.uuid(),eventId:H.uuid(),source:H.literal("caller_reported")});import{z as Pt}from"zod";var Am=Pt.strictObject({type:Pt.literal("bundle"),paywall:xn.optional(),offering:xn.optional(),coupons:xn,data:xn}),dS=e=>Pt.strictObject({type:Pt.literal(e),id:Pt.uuid()}),e1=Pt.strictObject({type:Pt.literal("bundle"),paywallVersionId:Pt.uuid().optional(),offeringVersionId:Pt.uuid().optional(),couponIds:Pt.array(Pt.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ge});var t1=Pt.strictObject({type:Pt.literal("bundle"),offering:dS("offering_version").nullable(),paywall:Pt.strictObject({versionId:Pt.uuid(),paywallId:Pt.uuid(),offeringVersionId:Pt.uuid()}).nullable(),coupons:Pt.array(Si).max(20),data:ge});import{z as An}from"zod";import{z as an}from"zod";var ym=an.union([an.string(),an.number().finite(),an.boolean(),an.null()]),pS=an.union([ym,an.array(ym).min(1).max(20)]),mS=an.record(gn,pS).refine(e=>Object.keys(e).length<=10),bm=an.strictObject({path:gn,type:an.enum(["string","number","boolean","strings"]),nullable:an.boolean().optional(),aggregation:an.enum(["count","exists"]).optional(),where:mS.optional()}).superRefine((e,t)=>{(e.aggregation==="count"&&e.type!=="number"||e.aggregation==="exists"&&e.type!=="boolean"||!e.aggregation&&e.where)&&t.addIssue({code:"custom",message:"Collection summaries require their matching type"})});var fS=["sendMessage","checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","previewAttach","attach","readSubscriptionOperation","previewUpdate","update","readSubscriptionUpdate","setupPayment","readPaymentSetup","verifySubscriptions","previewRefund","refund","readRefund","restoreNativePurchase","readBillingControls","prepareBillingAuthorization","confirmBillingAuthorization","setBillingCoupons","revokeBillingAuthorization","listBillingInvoices","confirmBillingAdjustment","manageBillingLimits","readSeats","manageSeat","quoteBalance","mutateBalance","trackUsage","readUsage","setUsage","adjustBalance","readBalanceSource","manageBalanceGrant","listBalanceGrants","manageUsageEntity","readUsageAnalytics","readCreditAnalytics","submitUsageBatch","readUsageBatch","redeemCoupon","listOffers","grantOffer","redeemReward","createReferralCode","claimRewardProduct"],Sm=An.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),gS=xn,xm=An.discriminatedUnion("type",[im,An.strictObject({type:An.literal("claim_offer"),coupon:xn}),An.strictObject({type:An.literal("event"),event:Sm}),An.strictObject({type:An.literal("api"),operation:An.enum(fS),inputs:An.record(gn,gS).refine(e=>Object.keys(e).length<=40),outputs:An.record(Sm,bm).refine(e=>Object.keys(e).length<=20)})]);var tt=ca,hS=K.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),en={id:tt,name:K.string().trim().min(1).max(80),position:K.strictObject({x:K.number().finite(),y:K.number().finite()}).optional()},AS={success:tt,cancel:tt,unavailable:tt,failure:tt},mc=K.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),fc=K.enum(["same_window","new_window"]),yS=K.discriminatedUnion("type",[K.strictObject({...en,type:K.literal("entry"),next:tt,triggers:K.array(em).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),K.strictObject({...en,type:K.literal("screen"),screenId:tt,presentation:jn,outputs:K.record(tt,tt),offering:K.discriminatedUnion("source",[K.strictObject({source:K.literal("variable"),key:dt}),K.strictObject({source:K.literal("fixed"),versionId:K.uuid()})]).optional()}),K.strictObject({...en,type:K.literal("offering"),configuration:K.discriminatedUnion("source",[K.strictObject({source:K.literal("fixed"),versionId:K.uuid()}),K.strictObject({source:K.literal("feature"),featureKey:K.string().min(1).max(128)})]),writes:K.strictObject({value:dt}),next:tt}),K.strictObject({...en,type:K.literal("coupon"),couponId:K.uuid(),writes:K.strictObject({value:dt}),next:tt}),K.strictObject({...en,type:K.literal("coupons"),couponIds:K.array(K.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:K.strictObject({value:dt}),next:tt}),K.strictObject({...en,type:K.literal("output"),value:K.discriminatedUnion("type",[...Gi.options,Am,K.strictObject({type:K.literal("selection"),screenId:tt,offeringKey:dt})])}),K.strictObject({...en,type:K.literal("condition"),cases:K.array(K.strictObject({condition:Bt,target:tt})).min(1).max(50),default:tt}),K.strictObject({...en,type:K.literal("feature"),featureKey:K.string().min(1).max(128),writes:K.strictObject({value:dt}),next:tt}),K.strictObject({...en,type:K.literal("split"),experimentId:K.uuid(),applyPageExperiment:K.literal(!0).optional(),routes:K.record(hS,tt).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:tt}),K.strictObject({...en,type:K.literal("action"),...AS,execution:om,action:xm,writes:Es.optional()}),K.strictObject({...en,type:K.literal("external_page"),appManifest:oa.optional(),url:mc,openIn:fc,opened:tt,failed:tt}),K.strictObject({...en,type:K.literal("end"),outcome:K.enum(["completed","closed","ineligible","failed"]),output:Gi.optional()}),K.strictObject({...en,type:K.literal("wait"),writes:Es.optional(),wait:K.discriminatedUnion("type",[K.strictObject({type:K.literal("duration"),delaySeconds:K.number().int().min(1).max(2592e3),elapsed:tt}),K.strictObject({type:K.literal("event"),eventName:tt,outputs:cc,timeoutSeconds:K.number().int().min(1).max(2592e3),received:tt,timeout:tt})])})]),gc=K.strictObject({version:K.literal(5),entry:tt,nodes:K.array(yS).min(1).max(hn.flowNodes)}),hc=gc.superRefine((e,t)=>{bS(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function ya(e){switch(e.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[e.next];case"screen":return Object.values(e.outputs);case"condition":return[...e.cases.map(t=>t.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];case"action":return[e.success,e.cancel,e.unavailable,e.failure];case"external_page":return[e.opened,e.failed];case"end":case"output":return[];case"wait":return e.wait.type==="duration"?[e.wait.elapsed]:[e.wait.received,e.wait.timeout]}}function bS(e,t){let n=[],r=new Map(e.nodes.map(d=>[d.id,d])),i=(d,m,w)=>{n.push(d),t?.({message:d,reason:m,path:w?["nodes",e.nodes.indexOf(w)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(d=>d.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(d=>d.type==="screen").length>hn.pages||e.nodes.filter(d=>!["screen","entry","end","output"].includes(d.type)).length>hn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let d of e.nodes){for(let m of ya(d))m===e.entry&&i("An entry cannot be a transition target","entryTarget",d),r.has(m)||i(`Missing target ${m}`,"missingTarget",d);d.type==="screen"&&(a.has(d.screenId)&&i("Every screen has exactly one node owner","screenOwner",d),a.add(d.screenId))}let o=new Set,s=new Set,c=new Set;function u(d){if(o.has(d)){i("Flow edges must not form a cycle","cycle",r.get(d));return}if(!(s.has(d)||!r.has(d))){o.add(d),c.add(d);for(let m of ya(r.get(d)))u(m);o.delete(d),s.add(d)}}u(e.entry);for(let d of e.nodes)c.has(d.id)||i("Every node must be reachable from Entry","unreachable",d);return[...new Set(n)]}var Ac={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Im(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(d=>s===d||c&&s.startsWith(d+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of Un(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}import{z as D}from"zod";var oi=D.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),ba=e=>D.record(D.string(),ge).refine(t=>Yt(t)<=e,"Funnel evidence exceeds its byte budget"),j1=D.enum(["local_segment","evaluation","presentation","timer","event","operation"]),bc=D.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Sc=D.discriminatedUnion("type",[D.strictObject({type:D.literal("flag"),key:D.string().min(1).max(128)}),D.strictObject({type:D.literal("experiment"),id:D.uuid()}),D.strictObject({type:D.literal("saved_group"),id:D.uuid()}),D.strictObject({type:D.literal("config"),key:D.string().min(1).max(128)}),D.strictObject({type:D.literal("constant"),key:D.string().min(1).max(128)}),D.strictObject({type:D.literal("paywall_version"),id:D.uuid()}),D.strictObject({type:D.literal("offering_version"),id:D.uuid()}),D.strictObject({type:D.literal("reward"),id:D.uuid()})]),Ki=D.strictObject({schemaVersion:D.literal(1),kind:bc,selector:Sc.nullable(),context:ba(131072),contract:D.strictObject({version:D.number().int().positive(),evaluator:D.string().min(1).max(128),policyRevision:D.number().int().nonnegative()})}).refine(e=>Yt(e)<=131072,"Node input exceeds its byte budget"),vm=D.strictObject({schemaVersion:D.literal(1),kind:bc,outcome:D.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:ba(131072),route:D.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:ba(131072)}).refine(e=>Yt(e)<=131072,"Node result exceeds its byte budget"),T1=D.strictObject({schemaVersion:D.literal(1),operations:D.record(oi,D.strictObject({attempts:D.number().int().nonnegative(),maxAttempts:D.number().int().min(1).max(5),deadlineAt:D.iso.datetime({offset:!0}),retryAt:D.iso.datetime({offset:!0}).nullable(),error:D.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:D.strictObject({type:oi,id:D.uuid()}).nullable()}))}).refine(e=>Yt(e)<=65536,"Execution state exceeds its byte budget"),Ir={receiptId:D.uuid()},yc=D.iso.datetime({offset:!0}),N1=D.discriminatedUnion("type",[D.strictObject({type:D.literal("node_entered"),details:D.strictObject({kind:bc})}),D.strictObject({type:D.literal("presentation_shown"),details:D.strictObject({...Ir,source:D.literal("client"),occurredAt:yc.optional()})}),D.strictObject({type:D.literal("decision_accepted"),details:D.strictObject(Ir)}),D.strictObject({type:D.literal("signal_received"),details:D.strictObject({signalId:D.uuid(),nodeId:oi,eventName:oi,data:ba(8192),source:D.literal("server"),occurredAt:yc})}),D.strictObject({type:D.literal("signal_consumed"),details:D.strictObject({...Ir,signalId:D.uuid()})}),D.strictObject({type:D.literal("wait_elapsed"),details:D.strictObject(Ir)}),D.strictObject({type:D.literal("wait_timeout"),details:D.strictObject(Ir)}),D.strictObject({type:D.literal("operation_completed"),details:D.strictObject({...Ir,operation:oi,reference:D.strictObject({type:oi,id:D.uuid()}).nullable()})}),D.strictObject({type:D.literal("execution_recovered"),details:D.strictObject({generation:D.number().int().positive(),reason:D.enum(["interrupted","expired_lease","delivery_failed"])})}),D.strictObject({type:D.literal("execution_failed"),details:D.strictObject({generation:D.number().int().positive(),code:D.string().regex(/^[a-z_]{1,64}$/)})}),D.strictObject({type:D.literal("run_completed"),details:D.strictObject({outcome:D.enum(["completed","ineligible","failed"])})}),D.strictObject({type:D.literal("run_closed"),details:D.strictObject({source:D.enum(["client","server","expiry"])})}),D.strictObject({type:D.literal("treatment_used"),details:D.strictObject({...Ir,source:D.enum(["client","server"]),occurredAt:yc,reference:D.string().min(1).max(128).optional()})})]);var sn=U.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),SS=U.discriminatedUnion("type",[U.strictObject({id:sn,type:U.literal("owned"),publicData:Bp.optional(),document:Wt.refine(e=>["page","popup","onboarding"].includes(e.surface)&&e.pages.length===1&&e.actions.every(t=>t.type==="event"&&!t.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),U.strictObject({id:sn,type:U.literal("paywall"),paywallVersionId:U.uuid()})]),xc={kind:U.literal("funnel"),schemaVersion:U.literal(4),screens:U.array(SS).max(hn.pages),references:U.record(sn,Sc).refine(e=>Object.keys(e).length<=500),inputs:U.array(U.strictObject({variable:sn,screenId:sn,componentId:sn,required:U.boolean()})).max(hn.questions),variables:U.record(dt,Kr).refine(e=>Object.keys(e).length<=hn.logicNodes),outputSchema:Gr,execution:U.strictObject({runTimeoutSeconds:U.number().int().min(1).max(Ac.runTimeoutSeconds),maxTransitions:U.number().int().min(1).max(Ac.maxTransitions)})},X1=U.strictObject({...xc,graph:gc});function xS(e,t){let n=!1,r=(i,a)=>{let o=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(e.strings.locales).some(s=>s[i.text]?.includes("{{offer."))&&!(o&&t(o))&&(n=!0),i.type==="stack"&&i.children.forEach(s=>r(s,o))};for(let i of e.pages)r(i.root);return n}function xa(e){return Array.isArray(e)?e.some(xa):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===am:xa(n))}function IS(e){let t=[],n=new Set(Object.values(e.references).flatMap(r=>r.type==="reward"?[r.id]:[]));for(let[r,i]of e.screens.entries()){if(i.type!=="owned")continue;let a;try{a=Jp(i.document)}catch(o){t.push({message:o instanceof Error?o.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[o,s]of e.inputs.entries())s.screenId===i.id&&!Mi(a,s.componentId)&&t.push({message:`Local Funnel input ${s.variable} targets hidden component ${s.componentId} on screen ${s.screenId}`,reason:"inputBinding",path:["inputs",o]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],o=i.type==="screen"?e.screens.find(s=>s.id===i.screenId):void 0;o?.type==="owned"&&(o.document.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),xS(o.document,s=>n.has(s))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&xa(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&xa(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function wm(e,t){for(let{message:n,reason:r,path:i}of IS(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function Om(e,t){let n=(I,p,g=[])=>t.addIssue({code:"custom",message:I,path:g,params:{reason:p}}),r=Object.values(e.references),i=new Map(e.screens.map(I=>[I.id,I])),a=(I,p)=>r.some(g=>g.type===I&&("id"in g?g.id:g.key)===p);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(I=>I.type==="screen");(o.length!==i.size||o.some(I=>!i.has(I.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(I=>c.some(p=>I!==p&&p.startsWith(I+".")))&&n("Variable paths must not overlap","variable");function u(I,p){Object.hasOwn(e.variables,I)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(p)]);let g=s.get(I)??new Set;g.add(p.id),s.set(I,g)}for(let[I,p]of e.graph.nodes.entries()){let g=["graph","nodes",I],f=p.type==="feature"?p.featureKey:p.type==="offering"&&p.configuration.source==="feature"?p.configuration.featureKey:p.type==="output"&&p.value.type==="feature"?p.value.featureKey:p.type==="end"&&p.output?.type==="feature"?p.output.featureKey:null;f&&!a("flag",f)&&n("Flag selectors require an explicit GB resource reference","feature",g);let S=p.type==="feature"||p.type==="offering"||p.type==="coupon"||p.type==="coupons"||p.type==="action"&&p.action.type==="api"?["value"]:p.type==="action"&&p.action.type==="external_task"?Object.keys(p.action.outputs):p.type==="wait"&&p.wait.type==="event"?Object.keys(p.wait.outputs):[],h="writes"in p?p.writes??{}:{};(S.length!==Object.keys(h).length||S.some(v=>!Object.hasOwn(h,v))||new Set(Object.values(h)).size!==Object.values(h).length)&&n("Node writes must map every named output exactly once","variable",g);for(let[v,E]of Object.entries(h)){u(E,p);let j=e.variables[E],q=p.type==="offering"?"offering_version":p.type==="coupon"?"reward":p.type==="action"&&p.action.type==="api"?"json":p.type==="action"&&p.action.type==="external_task"?p.action.outputs[v]:p.type==="wait"&&p.wait.type==="event"?p.wait.outputs[v]:void 0;(j?.source.type!=="node"||q&&j.type!==q)&&n("Node writer source or output type does not match declaration","variable",g)}if(p.type==="coupons"){let v=e.variables[p.writes.value];(v?.type!=="array"||v.items?.type!=="reward"||v.items.nullable||v.nullable)&&n("Coupons output requires a non-null Reward array","variable",g);for(let E of p.couponIds)a("reward",E)||n("Coupons require Reward references","coupon",g)}if(p.type==="split"&&!a("experiment",p.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",g),p.type==="coupon"&&!a("reward",p.couponId)&&n("Coupon selectors require a Reward reference","coupon",g),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="literal"){let v=p.action.coupon.value;(!v||typeof v!="object"||Array.isArray(v)||v.type!=="reward"||typeof v.id!="string"||Object.keys(v).length!==2||!a("reward",v.id))&&n("Coupon claims require a Reward reference","coupon",g)}if(p.type==="offering"&&p.configuration.source==="fixed"&&!a("offering_version",p.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",g),p.type==="screen"&&p.offering?.source==="variable"&&e.variables[p.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",g),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="variable"&&(e.variables[p.action.coupon.key]?.type!=="reward"||p.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",g),p.type==="screen"){let v=i.get(p.screenId);if(p.offering?.source==="fixed"&&!a("offering_version",p.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",g),v?.type==="paywall"&&p.offering&&n("Paywall owns its fixed Offering Version","offering",g),v?.type==="paywall"&&!a("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",g),v?.type==="owned"){let E=v.document.pages[0];if(!E){n("Owned screen requires a page","screen",g);continue}Gn(v.document).some(q=>!q.complete)&&n("Owned screens require complete local content","translations",g);let j=new Set(v.document.actions.map(q=>q.id));(j.size!==Object.keys(p.outputs).length||Object.keys(p.outputs).some(q=>!j.has(q)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",g),$n(E.root,q=>{!p.offering&&(q.type==="plan_picker"||(q.type==="stack"||q.type==="button")&&q.bind?.plan||q.type==="customer_data"&&["customer_plans","credit_packs"].includes(q.data.source))&&n("Product presentation requires an Offering Version","offering",g),q.type==="customer_data"&&Object.values(q.data.outputs??{}).some(de=>de!==void 0&&!j.has(de))&&n("Customer components require declared screen outcomes","componentOutput",g)})}}p.type==="end"&&["completed","ineligible"].includes(p.outcome)&&!p.output&&n("Completed and ineligible ends require a declared output","output",g),p.type==="end"&&p.output?.type==="literal"&&!rn(e.outputSchema,p.output.value)&&n("Terminal output does not match outputSchema","output",g),p.type==="output"&&p.value.type==="literal"&&!rn(e.outputSchema,p.value.value)&&n("Terminal output does not match outputSchema","output",g);let P=p.type==="output"?p.value:p.type==="end"?p.output:void 0;if(P?.type==="variable"&&!P.path){let v=e.variables[P.key];v&&!Rs(v,e.outputSchema)&&n("Variable output does not match outputSchema","output",g)}if(p.type==="screen"){let v=i.get(p.screenId);if(v?.type==="owned")for(let E of Ts(v.document))(/^(input|params)\./.test(E)||E.startsWith("variables.")&&!js(E.slice(10),c))&&n("Screen values must reference registered variables","variable",g)}if(p.type==="condition")for(let v of p.cases){for(let E of En(v.condition))a("saved_group",E)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let E of Un(v.condition))E.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",g)}if(p.type==="output"&&p.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",g);for(let[v,E]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let j=p.value[v];if(j)if(j.source==="literal"){let q=v==="coupons"?j.value:[j.value];(!Array.isArray(q)||q.length>20||q.some(de=>!rn({type:E,nullable:!1},de)||!a(E,de.id))||v==="coupons"&&new Set(q.map(de=>de.id)).size!==q.length)&&n("Bundle requires distinct scoped resource references",v==="coupons"?"coupon":v==="paywall"?"paywall":"offering",[...g,"value",v])}else{let q=e.variables[j.key];(j.path||!q||q.nullable||(v==="coupons"?q.type!=="array"||q.items?.type!=="reward"||q.items.nullable:q.type!==E))&&n("Bundle binding type does not match its slot","output",g)}}}}for(let[I,p]of e.graph.nodes.entries()){let g=p.type==="screen"?i.get(p.screenId):void 0,f=[...Im(p,c),...g?.type==="owned"?zo(g.document).map(S=>js(S,c)?.key??S):[]];for(let S of new Set(f)){let E=function(j){if(j===p.id)return!0;if(v.has(j))return!1;v.add(j);let q=e.graph.nodes.find(be=>be.id===j);return q?(P.has(j)?q.type==="action"?[q.cancel,q.unavailable,q.failure]:q.type==="wait"&&q.wait.type==="event"?[q.wait.timeout]:[]:ya(q)).some(E):!1};var w=E;if(!Object.hasOwn(e.variables,S)){n("Consumed variable is undeclared","variable",["graph","nodes",I]);continue}let h=e.variables[S];if(p.type==="screen"&&h.source.type==="input"&&e.inputs.some(j=>j.screenId===p.screenId&&j.variable===S)||h.source.type==="parameter"||h.source.type==="attribute")continue;let P=h.source.type==="input"?new Set(e.inputs.filter(j=>j.variable===S&&j.required).flatMap(j=>o.filter(q=>q.screenId===j.screenId).map(q=>q.id))):s.get(S)??new Set,v=new Set;(!P.size||E(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",I])}}(new Set(e.inputs.map(I=>I.variable)).size!==e.inputs.length||new Set(e.inputs.map(I=>`${I.screenId}:${I.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[I,p]of e.inputs.entries()){e.variables[p.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",I]);let g=i.get(p.screenId),f=g?.type==="owned"?Mi(g.document,p.componentId):null;if((f?.type!=="stack"||!f.interaction||!["input","toggle","select","multiselect","tabs"].includes(f.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",I]),f?.type==="stack"&&f.interaction){let S=f.interaction.type==="toggle"?"boolean":f.interaction.type==="multiselect"?"strings":"string";e.variables[p.variable]?.type!==S&&n("Input variable type does not match component","inputBinding",["inputs",I]);let h=e.variables[p.variable]?.enum;h&&!f.children.filter(P=>!P.hidden).every(P=>h.includes(P.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",I])}}for(let[I,p]of Object.entries(e.variables))p.enum&&p.type!=="string"&&n("Only string variables support enum","variable",["variables",I]),p.source.type==="input"&&!e.inputs.some(g=>g.variable===I)&&n("Input variable requires a component binding","inputBinding",["variables",I]);let d=0,m=0;for(let I of e.screens)if(I.type==="owned"){for(let p of I.document.pages)$n(p.root,()=>{d++});m+=I.document.actions.length}(d>hn.components||m>hn.actions||Yt(e)>hn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var vS=U.strictObject({...xc,graph:hc}).superRefine(Om),ai=U.strictObject({...xc,graph:hc,displayName:U.string().trim().min(1).max(80)}).superRefine(Om),e_=ai.superRefine(wm),t_=vS.superRefine(wm),Sa=U.string().regex(jt),Hi={requestId:U.uuid(),nodeId:sn,visit:U.number().int().nonnegative(),revision:U.number().int().nonnegative(),customerToken:Sa.optional()},wS=U.discriminatedUnion("type",[U.strictObject({type:U.literal("screen"),output:sn,answers:Hn,selection:U.record(sn,U.union([U.string().max(200),U.boolean(),U.number().int().min(0).max(1e4)])).optional()}),U.strictObject({type:U.literal("paywall_quote"),featureQuantities:U.record(U.uuid(),U.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:sn,productVersionId:U.uuid(),offerId:U.uuid().optional(),nativeOffer:Jr.optional(),predecessor:U.strictObject({operationId:U.uuid().nullable(),generation:U.number().int().positive()}).optional()}),U.strictObject({type:U.literal("paywall_confirm"),operationId:U.uuid()}),U.strictObject({type:U.literal("paywall_cancel"),operationId:U.uuid()}),U.strictObject({type:U.literal("client_action"),receiptId:U.uuid(),outcome:U.enum(["success","cancel","failure","opened","failed"])})]),OS=U.object({nodeId:sn,visit:U.number().int().nonnegative(),revision:U.number().int().nonnegative(),components:U.record(sn,U.object({resourceKey:U.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:U.number().int().min(1).max(1e5),after:aa.nullable(),filter:U.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Tn=U.discriminatedUnion("operation",[U.strictObject({operation:U.literal("start"),funnelId:U.uuid(),requestId:U.uuid(),customer:fa.optional(),customerData:ga.optional(),locale:U.string().min(1).max(35),parameters:Qn}).refine(ha,Aa),U.strictObject({operation:U.literal("get"),settlementRequestId:U.uuid().optional(),data:OS.optional(),purchase:U.strictObject({receiptId:U.uuid(),operationId:U.uuid()}).optional(),customerToken:Sa.optional()}),U.strictObject({operation:U.literal("resume"),requestId:U.uuid(),customerToken:Sa.optional()}),U.strictObject({operation:U.literal("submit"),...Hi,input:wS}),U.strictObject({operation:U.literal("back"),...Hi}),U.strictObject({operation:U.literal("shown"),...Hi}),U.strictObject({operation:U.literal("close"),...Hi}),U.strictObject({operation:U.literal("commit_segment"),...Hi,policyRevision:U.number().int().nonnegative(),generation:U.string().min(1).max(256)}),U.strictObject({operation:U.literal("review"),receiptId:U.uuid().optional(),customerToken:Sa.optional()})]);function Ia(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(p){for(let g of En(p))d(g)}function d(p){if(i.has(p)||!Object.hasOwn(t.savedGroups,p))return;let g=t.savedGroups[p];g&&(i.add(p),c.set(p,g),a.push(()=>{!Array.isArray(g)&&g.type==="condition"&&u(g.condition)}))}function m(p){for(let g of["hashAttribute","fallbackAttribute"])if(p[g]!==void 0&&ic(p[g]))throw new Error(`Funnel GB ${g} uses a reserved flow namespace`);u(p.condition);for(let g of p.parentConditions??[])w(g.id),u(g.condition)}function w(p,g=!1){let f=Object.hasOwn(t.features,p)?t.features[p]:void 0;if(!f){if(g)throw new Error("Required GB Feature is unavailable");return}n.has(p)||(n.add(p),o.set(p,f),a.push(()=>{for(let S of f.rules??[]){m(S);for(let h of S.tracks??[])m(h.experiment)}}))}function I(p){let g=Object.hasOwn(t.experiments,p)?t.experiments[p]:void 0;if(!g)throw new Error("Required GB Experiment is unavailable");r.has(p)||(r.add(p),s.set(p,g),a.push(()=>m(g)))}for(let p of e.graph.nodes){p.type==="feature"&&w(p.featureKey,!0),p.type==="split"&&I(p.experimentId),p.type==="condition"&&p.cases.forEach(f=>u(f.condition)),p.type==="offering"&&p.configuration.source==="feature"&&w(p.configuration.featureKey,!0);let g=p.type==="output"?p.value:p.type==="end"?p.output:null;g?.type==="feature"&&w(g.featureKey,!0)}for(let p of a)p();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as ne}from"zod";function Cm(e,t){let n=[],r={};Dt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Dt(e,o=>{if(o.type==="plan_picker"&&o.id===i.bind?.picker&&a.push(...o.planIds??[]),o.type==="stack"&&o.interaction?.type==="select"&&o.interaction.pickerId===i.bind?.picker)for(let s of o.children)s.type==="stack"&&s.bind?.plan&&a.push(s.bind.plan)}),a.length||n.push(`Quantity control ${i.id} needs a Product binding`);for(let o of new Set(a)){let s=t[o]?.prepaid?.find(u=>u.internalFeatureId===i.internalFeatureId)?.terms,c=r[o]??(r[o]=new Set);(!s||c.has(i.internalFeatureId)||i.minimumQuantity<s.minimumQuantity||i.maximumQuantity>s.maximumQuantity)&&n.push(`Quantity control ${i.id} must match its Product's prepaid Feature and bounds`),c.add(i.internalFeatureId)}});for(let[i,a]of Object.entries(t))for(let o of a.prepaid??[])r[i]?.has(o.internalFeatureId)||n.push(`Product ${i} needs a quantity control for ${o.internalFeatureId}`);return n}function Pm(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Dt(e,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker"||o.hidden||(o.bind?.plan??(o.bind?.picker?n[o.bind.picker]:void 0))!==t)return;let c=i.prepaid?.find(d=>d.internalFeatureId===o.internalFeatureId)?.terms,u=n[o.id];if(!c||typeof u!="number"||!Number.isSafeInteger(u)||u<Math.max(c.minimumQuantity,o.minimumQuantity)||u>Math.min(c.maximumQuantity,o.maximumQuantity)||(u-o.minimumQuantity)%o.step!==0||a[o.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");a[o.internalFeatureId]=u}),(i.prepaid??[]).some(o=>a[o.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return a}import{z as Qi}from"zod";var _m=Qi.object({defaultLocale:ln,locales:Qi.record(ln,Qi.object({name:Qi.string().max(80),description:Qi.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var CS=["customer_data","coupon_code"],PS=ne.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Em=ne.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),va=(e,t)=>new Set(e.map(t)).size===e.length,_S=ne.strictObject({currency:fe,amountMinor:ne.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),ES=ne.strictObject({featureId:ne.uuid(),name:ne.string().trim().min(1).max(120),allowance:ne.string().max(40).nullable(),access:ne.boolean()}),RS=ne.strictObject({stripe:ne.strictObject({prices:ne.array(_S).min(1).max(50)}).optional(),apple:ne.strictObject({productIds:ne.array(PS).min(1).max(10)}).optional(),google:ne.strictObject({products:ne.array(ne.strictObject({productId:Em,basePlanId:Em.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!va(e.stripe.prices,n=>n.currency)||e.apple&&!va(e.apple.productIds,n=>n)||e.google&&!va(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),kS=ne.strictObject({name:ne.string().trim().min(1).max(80),interval:ne.enum(["free","week","month","year","one_time"]),intervalCount:ne.number().int().min(1).max(100),trial:ne.strictObject({days:ne.number().int().min(1).max(730),cardRequired:ne.boolean()}).nullable(),benefits:ne.array(ES).max(50).refine(e=>va(e,t=>t.featureId),"Duplicate benefit"),channels:RS,prepaid:ne.array(Ti).max(100).optional()}),jS=ne.strictObject({digest:ti,content:ne.strictObject({discount:Ln,duration:Jt,appliesTo:hs,displayCopy:_m.nullable(),firstPurchaseOnly:ne.boolean(),qualificationRequired:ne.boolean(),startsAt:ne.iso.datetime().nullable(),endsAt:ne.iso.datetime().nullable(),grantWindowHours:ne.number().int().positive(),perCustomerLimit:ne.number().int().positive()})}),TS=ne.discriminatedUnion("type",[ne.strictObject({type:ne.literal("checkout"),product:ta}),ne.strictObject({type:ne.literal("close")}),ne.strictObject({type:ne.literal("action"),action:Hs})]),wa=ne.strictObject({kind:ne.literal("paywall"),formatVersion:ne.literal(1),name:ne.string().trim().min(1).max(80),offeringVersionId:ne.uuid(),presentation:jn,screen:Wt,products:ea,catalog:ne.record(ne.uuid(),kS),buttons:ne.record(ke,TS),coupons:ne.record(ne.uuid(),jS)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;Cm(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Ys(r,CS).forEach(n),Gn(r).some(g=>!g.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Dt(r,g=>{let f="bind"in g?g.bind:void 0;f?.promotionCode&&n("Promotion codes must not be published"),f?.plan&&i.add(f.plan),f?.coupon&&a.add(f.coupon),g.type==="plan_picker"&&(g.planIds?.forEach(S=>i.add(S)),g.defaultPlan&&i.add(g.defaultPlan)),g.type==="text"&&g.feature&&o.add(g.feature.id)});let s=e.products.items.map(g=>g.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(g=>!Object.hasOwn(e.catalog,g)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let g of i)u.has(g)||n("Screen references a Product that is not displayed");for(let g of Object.values(e.catalog))!g.channels.stripe&&!g.channels.apple&&!g.channels.google&&n("A displayed Product needs at least one sales channel");let d=new Set(Object.values(e.catalog).flatMap(g=>g.benefits.map(f=>f.featureId)));for(let g of o)d.has(g)||n("Feature text must read a displayed benefit");let m=r.actions.filter(g=>g.type!=="navigate");r.actions.some(g=>g.type!=="event"&&g.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==m.length||m.some(g=>!Object.hasOwn(e.buttons,g.id)))&&n("Buttons must match the screen's actions");let I=!1;for(let g of Object.values(e.buttons)){if(g.type!=="checkout")continue;I=!0,(g.product.type==="fixed"?[g.product.productVersionId]:g.product.allowedProductVersionIds).some(S=>!u.has(S))&&n("Checkout may only sell displayed Products")}I||n("A Paywall needs a checkout button");let p=Object.keys(e.coupons);(p.length!==a.size||p.some(g=>!a.has(g)))&&n("Coupons must be exactly the bound Coupons")}),Rm=ne.strictObject({state:ne.enum(["published","archived"]),controlRevision:ne.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ne.uuid(),versions:ne.record(ne.uuid(),ne.strictObject({version:ne.number().int().positive(),artifact:ne.string().min(1),sourceDigest:ne.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var Gt={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},Ic=ve.string().regex(/^[a-f0-9]{64}$/),vc=ve.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),wc=Ve.extend({environmentId:ve.uuid()}),km=ve.strictObject({features:ve.array(ve.string()).max(500),experiments:ve.record(ve.uuid(),ve.array(ve.string()).max(20)),savedGroups:ve.array(ve.string()).max(1e3)}),Oc=ve.strictObject({kind:ve.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:ve.number().int().positive(),url:ve.string().min(1).max(2048),sha256:Ic,byteLength:ve.number().int().positive().max(Gt.maxArtifactBytes),generation:Ic.optional()}),NS=ve.strictObject({state:ve.enum(["active","paused","archived"]),controlRevision:vc,evaluationMode:ve.enum(["local","remote"]),evaluationRevision:vc,currentVersionId:ve.uuid(),versions:ve.record(ve.uuid(),ve.strictObject({artifact:ve.string(),dependencies:km,definitionDigest:ti.optional(),couponDigests:ve.record(ve.uuid(),ti).optional()}))}),Cc=ve.strictObject({kind:ve.literal("sdk_configuration"),schemaVersion:ve.literal(1),scope:wc,revision:vc,generation:Ic,policy:ve.strictObject({refreshIntervalSeconds:ve.number().positive().max(15),maxControlAgeSeconds:ve.number().positive().max(60)}),gb:ve.strictObject({features:ve.string().nullable(),pageExperiments:ve.string().nullable()}),artifacts:ve.record(ve.string(),Oc),funnels:ve.record(ve.uuid(),NS),paywalls:ve.record(ve.uuid(),Rm).optional()}).superRefine((e,t)=>{let n=(r,i)=>{r!==null&&e.artifacts[r]?.kind!==i&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};n(e.gb.features,"gb_features"),n(e.gb.pageExperiments,"gb_page_experiments");for(let r of Object.values(e.paywalls??{}))for(let i of Object.values(r.versions))n(i.artifact,"paywall");for(let r of Object.values(e.funnels)){r.evaluationMode==="remote"&&Object.keys(r.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),r.evaluationMode==="local"&&!r.versions[r.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let i of Object.values(r.versions))n(i.artifact,"funnel")}});function gt(e){if(Array.isArray(e))return`[${e.map(gt).join(",")}]`;if(e!==null&&typeof e=="object")return`{${Object.entries(e).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${gt(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Pc(e){return Fr(Mr(typeof e=="string"?new TextEncoder().encode(e):e))}function jm(e){return Pc(gt(e))}function Tm(e,t){for(let o of Object.values(e.references))if(o.type==="flag"&&(!Object.hasOwn(t.features,o.key)||t.remoteFeatures.includes(o.key))||o.type==="experiment"&&!Object.hasOwn(t.experiments,o.id)||o.type==="saved_group"&&!Object.hasOwn(t.savedGroups,o.id))throw new Error("Funnel dependency is absent from GB public delivery");let n=Ia(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),r=new Set(t.remoteFeatures);for(let o of e.graph.nodes){let s=o.type==="feature"?o.featureKey:o.type==="end"&&o.output?.type==="feature"?o.output.featureKey:o.type==="output"&&o.value.type==="feature"?o.value.featureKey:void 0;if(!s)continue;let c=n.features[s],u=o.type==="feature"?e.variables[o.writes.value]:e.outputSchema;if(!c||!u)throw new Error("Required public Feature declaration is unavailable");if([c.defaultValue,...(c.rules??[]).flatMap(m=>[...Object.hasOwn(m,"force")?[m.force]:[],...m.variations??[],...(m.tracks??[]).flatMap(w=>w.experiment.variations)])].some(m=>m===void 0||!rn(u,m)))throw new Error("GB Feature values violate the Funnel type contract")}let i=new Set,a=o=>{for(let s of En(o)){if(i.has(s))continue;let c=t.savedGroups[s];if(!c)throw new Error("Required public Saved Group is unavailable");i.add(s),!Array.isArray(c)&&c.type==="condition"&&a(c.condition)}};for(let o of e.graph.nodes)if(o.type==="condition")for(let s of o.cases)a(s.condition);for(let o of Object.values(n.features))for(let s of o.rules??[]){a(s.condition);for(let c of[...s.parentConditions??[],...(s.tracks??[]).flatMap(u=>u.experiment.parentConditions??[])]){if(r.has(c.id)||!t.features[c.id])throw new Error("Local Funnel requires public Local prerequisites");a(c.condition)}for(let c of s.tracks??[])a(c.experiment.condition)}for(let o of Object.values(n.experiments)){a(o.condition);for(let s of o.parentConditions??[]){if(r.has(s.id)||!t.features[s.id])throw new Error("Local Funnel requires public Local prerequisites");a(s.condition)}}for(let o of e.graph.nodes)if(o.type==="split"){let s=n.experiments[o.experimentId];if(!s)throw new Error("Local Funnel requires a public Experiment");for(let c=0;c<s.variations.length;c++){let u=s.meta?.[c]?.key??String(c);if(!o.routes[u])throw new Error("Experiment variation has no declared Funnel route")}}return km.parse({features:Object.keys(n.features).sort(),experiments:Object.fromEntries(Object.entries(n.experiments).map(([o,s])=>[o,s.variations.map((c,u)=>s.meta?.[u]?.key??String(u))])),savedGroups:[...i].sort()})}function Nm(e){return ai.parse(e)}var Dm=ht.strictObject({...Qr,selector:ht.discriminatedUnion("type",[ht.strictObject({type:ht.literal("paywall"),paywallId:ht.uuid()}),ht.strictObject({type:ht.literal("version"),versionId:ht.uuid()})]),customerId:ht.uuid().optional(),commerce:zr,locale:ht.string().min(1).max(35),requirement:zn.optional()}),Ji=ht.strictObject({id:ht.uuid(),paywallId:ht.uuid(),version:ht.number().int().positive(),document:ei.omit({requirement:!0,offeringId:!0}),offering:ht.strictObject({id:ht.uuid()}),content:ht.strictObject({environmentId:ht.uuid(),offeringVersionId:ht.uuid(),artifact:Oc.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:$r,check:gr.nullable()}).superRefine((e,t)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),vr=ht.strictObject(Ji.shape).omit({document:!0,offering:!0}).extend({content:Ji.shape.content.unwrap()});function Fm(e,t){let n=wa.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[i,a]of Object.entries(n.catalog)){let o=r.plans[i],s=a.channels.stripe?.prices.find(c=>c.currency===o?.currency);o&&s&&Object.assign(o,{amountMinor:s.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return Ji.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}import{z as Mt}from"zod";var Mm={requestId:Mt.uuid(),sourceId:Mt.uuid(),expectedAvailable:Nt},qm=Mt.discriminatedUnion("action",[Mt.strictObject({...Mm,action:Mt.enum(["add","subtract","set_remaining"]),amount:me}),Mt.strictObject({...Mm,action:Mt.literal("edit"),granted:me,expiresAt:Mt.iso.datetime({offset:!0}).nullable(),nextResetAt:Mt.iso.datetime({offset:!0}).nullable(),expectedRevision:Mt.number().int().nonnegative()})]),_c=Mt.strictObject({sourceId:Mt.uuid(),available:Nt,held:Nt,spent:Nt,adjustmentGrantId:Mt.uuid().nullable()}),Vm=_c.extend({granted:Nt,expiresAt:Mt.iso.datetime({offset:!0}).nullable(),nextResetAt:Mt.iso.datetime({offset:!0}).nullable(),revision:Mt.number().int().nonnegative()});import{z as tn}from"zod";var Um=tn.discriminatedUnion("action",[tn.object({action:tn.literal("upsert"),externalId:tn.string().min(1).max(128),name:tn.string().trim().min(1).max(80)}).strict(),tn.object({action:tn.literal("archive"),entityId:tn.uuid()}).strict()]),Lm=tn.object({id:tn.uuid(),externalId:tn.string().min(1).max(128),name:tn.string().min(1).max(80),archived:tn.boolean()}).strict();import{z as Rt}from"zod";import{z as Or}from"zod";var zm=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Bm=Or.string().regex(/.+\/.+/),Ec=Or.number().min(-100),wr=Or.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),DS=Or.strictObject({input:wr,output:wr,cache_read:wr.optional(),cache_write:wr.optional(),reasoning:wr.optional(),input_audio:wr.optional(),output_audio:wr.optional()}),Rc=(e,t)=>Or.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),Y_=Or.strictObject({defaultMarkup:Ec,providerMarkups:Rc(Or.string().min(1),Ec),modelMarkups:Rc(Bm,Ec),customModels:Rc(Bm,DS.partial())});import{z as pe}from"zod";var Cr=pe.iso.datetime({offset:!0}),Jn=pe.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),FS=pe.discriminatedUnion("kind",[pe.object({kind:pe.literal("absolute"),from:Cr,to:Cr}).strict(),pe.object({kind:pe.literal("last_days"),days:pe.union([pe.literal(1),pe.literal(7),pe.literal(30),pe.literal(90)])}).strict(),pe.object({kind:pe.literal("billing_cycles"),membershipId:pe.uuid(),count:pe.number().int().min(1).max(12),includeCurrent:pe.boolean()}).strict()]),$m=pe.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),MS=pe.object({key:pe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:pe.array(pe.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Pr=pe.object({range:FS,timezone:$m,filterBy:pe.array(MS).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:pe.enum(["hour","day","week","month"]),internal_feature_id:pe.uuid().nullable(),entityId:pe.uuid().nullable(),topN:pe.number().int().min(1).max(50).nullable(),groupBy:pe.union([pe.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),pe.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:pe.object({bucket:Cr,group:pe.string().max(240),isOther:pe.boolean(),internal_feature_id:pe.uuid(),resourceId:pe.uuid()}).strict().nullable(),limit:pe.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),Gm=pe.object({from:Cr,to:Cr,interval:pe.enum(["hour","day","week","month"]),timezone:$m,rows:pe.array(pe.object({bucket:Cr,group:pe.string().max(240),isOther:pe.boolean(),internal_feature_id:pe.uuid(),resourceId:pe.uuid(),consumedUnits:Jn,refundedUnits:Jn,reservedUnits:Jn,charged:Jn,refunded:Jn,reserved:Jn,netUnits:Jn,netCharged:Jn}).strict()).max(100),nextCursor:pe.object({bucket:Cr,group:pe.string().max(240),isOther:pe.boolean(),internal_feature_id:pe.uuid(),resourceId:pe.uuid()}).strict().nullable()}).strict();var si=Rt.string().regex(/^(0|[1-9]\d{0,29})$/),Km=Rt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),kc=Rt.strictObject({bucket:Rt.iso.datetime({offset:!0}),group:Rt.string().max(240),isOther:Rt.boolean(),internal_feature_id:Rt.uuid()}),Hm=Rt.strictObject({...Pr.shape,groupBy:Rt.union([Rt.enum(["customer","entity","entitlement"]),Rt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:kc.nullable()}).superRefine((e,t)=>{let n=Pr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Qm=Rt.strictObject({from:Rt.iso.datetime({offset:!0}),to:Rt.iso.datetime({offset:!0}),interval:Pr.shape.interval,timezone:Pr.shape.timezone,rows:Rt.array(Rt.strictObject({...kc.shape,eventCount:si,units:Km,tokenEventCount:si,tokens:Rt.strictObject(Object.fromEntries(zm.map(e=>[e,si]))),totalTokens:si,providerCostEventCount:si,providerCostUsd:Km,invalidTelemetryEventCount:si})).max(100),nextCursor:kc.nullable()});import{z as lt}from"zod";var Jm=lt.object({requestId:lt.uuid(),items:lt.array(lt.object({customerId:lt.uuid(),command:Pi.options[1]}).strict()).min(1).max(1e3)}).strict().refine(e=>new Set(e.items.map(t=>t.customerId+":"+t.command.idempotencyKey)).size===e.items.length,"Each logical event must appear once in a batch"),Zm=lt.object({batchId:lt.uuid(),after:lt.number().int().min(-1).max(999),limit:lt.number().int().min(1).max(100)}).strict(),Wm=lt.object({batchId:lt.uuid(),status:lt.enum(["queued","complete"]),total:lt.number().int().min(1).max(1e3),processed:lt.number().int().min(0).max(1e3),items:lt.array(lt.object({position:lt.number().int().min(0).max(999),customerId:lt.uuid(),idempotencyKey:lt.string().min(1).max(120),status:lt.enum(["queued","accepted","rejected","failed"]),receipt:_i.nullable(),errorCode:lt.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(e=>e.status==="queued"?e.receipt===null&&e.errorCode===null:e.status==="failed"?e.receipt===null&&e.errorCode!==null:e.receipt!==null&&e.errorCode===null&&e.receipt.accepted===(e.status==="accepted"))).max(100),nextAfter:lt.number().int().min(0).max(999).nullable()}).strict();import{z as _}from"zod";var qS=_.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Ym=_.enum(["draft","active","paused","archived"]),Xm=_.string().min(1).max(256),ef=_.array(Xm).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),VS=_.strictObject({duration:_.enum(["day","week","month","year"]),length:_.number().int().min(1).max(3660)}),US=_.strictObject({internal_feature_id:_.uuid(),allowance:_.number().nonnegative().max(1e15).nullable(),expiry:VS.nullable()}),LS=_.discriminatedUnion("type",[_.strictObject({type:_.literal("feature_grant"),grants:_.array(US).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),_.strictObject({type:_.literal("free_product"),productId:Xm,duration:Jt}),_.strictObject({type:_.literal("invoice_credits"),amount:_.number().positive().max(1e8),duration:Jt,rollover:_.boolean(),productIds:ef})]),BS=_.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),tf=_.object({key:BS,name:_.string().trim().min(1).max(80),configuration:LS}).strict(),nf=_.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),jc=_.object({code:nf,maxUses:_.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:_.boolean()}).strict(),rf=_.object({key:_.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:_.string().trim().min(1).max(80),rewardId:_.uuid(),redeemOn:_.enum(["customer_creation","checkout"]),receivedBy:_.enum(["referrer","all"]),maxRedemptions:_.number().int().min(1).max(1e6).nullable(),productIds:ef,excludeTrial:_.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),of={id:_.uuid(),projectId:_.uuid(),environmentId:_.uuid(),revision:_.number().int().nonnegative(),status:Ym,createdAt:_.iso.datetime({offset:!0}),updatedAt:_.iso.datetime({offset:!0})},zS=tf.extend(of).strict(),$S=rf.safeExtend(of).strict(),pE=_.strictObject({id:_.uuid(),key:_.string(),name:_.string(),type:qS,status:Ym}),mE=_.discriminatedUnion("action",[_.object({action:_.literal("save"),id:_.uuid().nullable(),revision:_.number().int().nonnegative(),input:tf}).strict(),_.object({action:_.enum(["activate","pause","resume","archive","delete"]),id:_.uuid(),revision:_.number().int().nonnegative()}).strict()]),fE=_.discriminatedUnion("action",[_.object({action:_.literal("save"),id:_.uuid().nullable(),revision:_.number().int().nonnegative(),input:rf}).strict(),_.object({action:_.enum(["activate","pause","resume","archive","delete"]),id:_.uuid(),revision:_.number().int().nonnegative()}).strict()]),af=_.object({id:_.uuid(),rewardId:_.uuid(),programId:_.uuid().nullable(),customerId:_.uuid(),referrerId:_.uuid().nullable(),status:_.enum(["pending","applied","unavailable"]),result:_.record(_.string(),_.unknown()).nullable(),createdAt:_.iso.datetime({offset:!0})}).strict(),sf=_.object({code:nf,requestId:_.uuid()}).strict(),cf=_.strictObject({redemptionId:_.uuid(),currency:fe,requestId:_.uuid(),accepted:_.literal(!0)}),GS=_.strictObject({type:_.literal("checkout"),orderId:_.uuid(),productVersionId:_.uuid(),currency:fe,duration:Jt,renewalAmountMinor:_.number().int().positive().max(1e8),status:_.enum(["created","pending","trialing","paid","cancelled","failed"]),url:_.url().nullable()}),uf=_.discriminatedUnion("type",[GS,_.strictObject({type:_.literal("subscription"),operationId:_.uuid(),membershipId:_.uuid(),productVersionId:_.uuid(),currency:fe,duration:Jt,renewalAmountMinor:_.number().int().positive().max(1e8),status:_.enum(["pending","running","applied","failed"])})]),lf=_.object({programId:_.uuid(),requestId:_.uuid()}).strict(),df=_.object({id:_.uuid(),programId:_.uuid(),code:jc.shape.code,createdAt:_.iso.datetime({offset:!0})}).strict(),gE=_.object({rows:_.array(zS).max(100),nextCursor:_.uuid().nullable()}).strict(),hE=_.object({rows:_.array($S).max(100),nextCursor:_.uuid().nullable()}).strict(),KS=jc.extend({id:_.uuid(),redemptions:_.number().int().nonnegative()}).strict(),HS=_.strictObject({id:_.uuid(),programId:_.uuid().nullable(),customerId:_.uuid().nullable(),referrerId:_.uuid().nullable(),code:_.string().nullable(),status:_.enum(["pending","triggered","applied"]),createdAt:_.iso.datetime({offset:!0})}),AE=_.object({codes:_.array(KS).max(100),redemptions:_.array(HS).max(100),customers:_.record(_.uuid(),_.string()),codesCursor:_.uuid().nullable(),redemptionsCursor:_.uuid().nullable()}).strict(),yE=_.discriminatedUnion("action",[_.object({action:_.literal("create"),rewardId:_.uuid(),revision:_.number().int().nonnegative(),input:jc}).strict(),_.object({action:_.literal("remove"),rewardId:_.uuid(),revision:_.number().int().nonnegative(),codeId:_.uuid()}).strict()]);import{z as x}from"zod";import{z as Q}from"zod";var In={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Zi=e=>new Set(e).size===e.length,Tc=Q.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),QS=Q.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Wi=Q.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),JS=Q.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),pf=Q.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var mf=Q.strictObject({id:Q.uuid(),repo:QS,platform:Q.enum(["github","gitlab","bitbucket"]),branches:Q.array(Wi).min(1).max(4).refine(Zi),workflow:Q.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:Q.array(Q.uuid()).min(1).max(4).refine(Zi),include:Q.array(pf).min(1).max(16),exclude:Q.array(pf).max(16),methods:Q.array(Q.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Zi),maxAgeHours:Q.number().int().min(1).max(720)}),ff=mf.extend({revision:Q.number().int().positive()}),xE=Q.strictObject({repository:mf,expectedRevision:Q.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),gf=Q.strictObject({repositoryId:Q.uuid(),branch:Wi}),ZS=Q.array(Tc).max(In.keys).refine(Zi),hf=Q.strictObject({repository:ff.omit({keyIds:!0}),branch:Wi,keys:ZS,keySetHash:Q.string().regex(/^[a-f0-9]{64}$/)}),WS=Q.strictObject({filePath:JS,startingLineNumber:Q.number().int().min(1).max(1e7)}),Nc=Q.strictObject({protocol:Q.literal(1),repositoryId:Q.uuid(),branch:Wi,workflow:Q.string().max(200),configurationRevision:Q.number().int().positive(),keySetHash:Q.string().regex(/^[a-f0-9]{64}$/),commit:Q.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:Q.uuid(),runNumber:Q.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:Q.number().int().min(1).max(1e4),scannerVersion:Q.literal("1"),scannedAt:Q.iso.datetime({offset:!0}),coverage:Q.strictObject({complete:Q.literal(!0),files:Q.number().int().min(0).max(In.files),sourceBytes:Q.number().int().min(0).max(In.sourceBytes),unresolvedCalls:Q.number().int().min(0).max(1e6),unsupportedFiles:Q.number().int().min(0).max(In.files)}),features:Q.array(Q.strictObject({key:Tc,refs:Q.array(WS).max(In.referencesPerKey)})).max(In.keys)}).superRefine((e,t)=>{Zi(e.features.map(n=>n.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((n,r)=>n+r.refs.length,0)>In.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Dc=Q.strictObject({scanId:Q.uuid(),commit:Q.string(),receivedAt:Q.string(),references:Q.number().int().nonnegative(),removedReferences:Q.number().int().nonnegative()}),YS=Dc.extend({repositoryId:Q.uuid(),branch:Wi,workflow:Q.string(),digest:Q.string(),configurationRevision:Q.number().int().positive(),runNumber:Q.number().int().positive(),runAttempt:Q.number().int().positive(),scannedAt:Q.string(),keySetHash:Q.string(),coverage:Nc.shape.coverage}),XS=Q.strictObject({repositories:Q.array(ff).max(In.repositories),scans:Q.array(YS).max(In.repositories*In.branches)}),ex=Q.strictObject({key:Tc,references:Q.number().int().nonnegative(),coveredTargets:Q.number().int().nonnegative(),expiredTargets:Q.number().int().nonnegative(),uncertainTargets:Q.number().int().nonnegative()}),IE=Q.strictObject({available:Q.boolean().default(!0),settings:XS,expectedTargets:Q.number().int().min(0).max(80),features:Q.array(ex).max(2001),truncated:Q.boolean()});import{z as qt}from"zod";var yf={customerId:qt.uuid(),eventId:qt.string().trim().min(1).max(200),grantId:qt.uuid(),occurredAt:qt.iso.datetime({offset:!0})},bf=qt.strictObject({...yf,productVersionId:qt.uuid(),subscriptionId:qt.string().trim().min(1).max(255)}),Sf=qt.strictObject({...yf,merchandiseId:qt.uuid()}),xf=qt.union([bf,Sf]),Af={id:qt.uuid(),couponId:qt.uuid(),status:qt.literal("redeemed"),source:qt.literal("merchant"),recordedAt:qt.iso.datetime({offset:!0})},If=qt.union([bf.extend(Af),Sf.extend(Af)]);import{z as te}from"zod";var Fc=te.strictObject({name:te.string().trim().min(1).max(255),memo:te.string().max(1e4).nullable().optional(),footer:te.string().max(1e4).nullable().optional(),net_terms_days:te.number().int().positive().nullable().optional()}),tx=Fc.extend({id:te.string().min(1).max(255),created_at:te.number().nullable()}),vf=te.strictObject({items:te.array(tx).max(50),nextCursor:te.uuid().nullable()}),_E=te.discriminatedUnion("action",[te.strictObject({action:te.literal("create"),requestId:te.uuid(),values:Fc}),te.strictObject({action:te.literal("update"),id:te.string().min(1).max(255),values:Fc}),te.strictObject({action:te.literal("delete"),id:te.string().min(1).max(255)})]),wf=te.discriminatedUnion("action",[te.strictObject({action:te.literal("create"),requestId:te.uuid(),params:Zr}),te.strictObject({action:te.enum(["finalize","send","pay","void"]),requestId:te.uuid(),invoiceId:te.uuid()}),te.strictObject({action:te.literal("reissue"),requestId:te.uuid(),invoiceId:te.uuid(),params:Fs})]),Mc=te.strictObject({id:te.uuid(),customerId:te.uuid(),providerInvoiceId:te.string().nullable(),status:te.enum(["draft","open","paid","void","uncollectible"]),currency:te.string(),totalMinor:te.string().regex(/^-?\d+$/),paidMinor:te.string().regex(/^\d+$/),refundedMinor:te.string().regex(/^\d+$/),hostedInvoiceUrl:te.url().nullable(),createdAt:te.number(),collectionMethod:te.enum(["send_invoice","charge_automatically"]).nullable()}),Of=Mc.extend({lines:te.array(te.strictObject({id:te.uuid(),description:te.string(),amountMinor:te.string().regex(/^-?\d+$/),netAmountMinor:te.string().regex(/^-?\d+$/),quantity:te.number().nullable(),periodStart:te.number().nullable(),periodEnd:te.number().nullable()})).max(1e3)}),Yi=te.strictObject({taskId:te.uuid(),status:te.enum(["ready","running","done","dead"]),invoice:Mc.nullable(),errorCode:te.string().nullable()}),Cf=te.strictObject({items:te.array(Mc).max(50),nextCursor:te.uuid().nullable(),operations:te.array(Yi).max(50),operationsLimited:te.boolean()});var nx=x.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"]),Pf={scope:Ve,permissions:x.array(nx),expiresAt:x.iso.datetime().nullable()},bR=x.discriminatedUnion("kind",[x.object({...Pf,kind:x.literal("server"),keyId:x.string().min(1)}),x.object({...Pf,kind:x.literal("customer"),customerId:x.string().min(1),identityKind:x.enum(["identified","guest"]),expiresAt:x.iso.datetime()})]),L=x.object({requestId:x.uuid(),scope:Ve}).strict(),rx=pm.safeExtend({fingerprint:ma.optional()}).strict(),ix=L.extend({customer:ii,created:x.boolean()});function _f(){return L.extend({offer:Si.nullable(),reason:Tl.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Id,response:L.extend({message:x.object({messageId:x.uuid(),channel:ji,acceptedAt:x.iso.datetime({offset:!0}),status:x.enum(["accepted","sending","completed","canceled"]),replayed:x.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:x.strictObject({messageId:x.uuid()}),response:L.extend({message:x.object({id:x.uuid(),channel:ji,status:x.enum(["accepted","sending","completed","canceled"]),deliveries:x.array(x.object({id:x.uuid(),status:wd,attempts:x.number().int().nonnegative(),receipts:x.array(x.object({kind:Od,occurredAt:x.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:xu,response:L.extend({installation:sr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Iu,response:L.extend({installation:sr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:lo,response:L.extend({installation:sr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:x.strictObject({channel:ji}),response:L.extend({preference:Ga})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:vd,response:L.extend({preference:Ga})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:x.strictObject({cursor:x.uuid().optional()}),response:L.extend({templates:vf})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:x.strictObject({customerId:x.uuid(),params:Zr}),response:L.extend({preview:Ms})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:x.strictObject({customerId:x.uuid(),requestId:x.uuid(),params:Zr}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:L.extend({operation:Yi})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:x.strictObject({customerId:x.uuid(),command:wf}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:L.extend({operation:Yi})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:x.strictObject({customerId:x.uuid(),taskId:x.uuid()}),response:L.extend({operation:Yi})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:x.strictObject({customerId:x.uuid(),cursor:x.uuid().optional()}),response:L.extend({invoices:Cf})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:x.strictObject({customerId:x.uuid(),invoiceId:x.uuid()}),response:L.extend({invoice:Of})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:gf,response:L.extend({config:hf})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Nc,response:L.extend({receipt:Dc})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:x.strictObject({}),response:L.extend({payload:zi})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Gp,response:L.merge(ra)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Kp,response:L.merge(Hp)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:x.strictObject({customerId:x.uuid(),sourceId:x.uuid()}),response:L.extend({balance:Vm})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:x.strictObject({customerId:x.uuid(),command:qm}),response:L.extend({balance:_c})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:x.strictObject({internal_feature_id:x.uuid(),customerId:x.uuid().optional(),entityId:x.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:L.extend({internal_feature_id:x.uuid(),config:Wa,model_markups:ho})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:x.strictObject({customerId:x.uuid(),query:Do}),response:L.extend({usage:Ei})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:x.strictObject({customerId:x.uuid(),command:md}),response:L.extend({usage:Ei})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:x.strictObject({customerId:x.uuid(),command:sd}),response:L.extend({grant:Ss})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:cd,response:L.extend({grants:ud})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:x.union(Tp.options.map(e=>e.extend({customerId:x.uuid().optional(),customerToken:x.string().regex(jt).optional()}))),response:L.extend({operation:Np})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Ip.extend({customerId:x.uuid().optional()}),response:L.extend({setup:Bs})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:vp.extend({customerId:x.uuid().optional()}),response:L.extend({setup:Bs})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:bp.safeExtend({customerId:x.uuid()}),response:L.extend({batch:Ui})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Qo.extend({customerId:x.uuid()}),response:L.extend({batch:Ui})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Qo.extend({customerId:x.uuid()}),response:L.extend({batch:Ui})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Qo.extend({customerId:x.uuid()}),response:L.extend({batch:Ui})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:x.discriminatedUnion("action",[Jo.options[0].extend({customerId:x.uuid()}),Jo.options[1].extend({customerId:x.uuid()}),Jo.options[2].extend({customerId:x.uuid()})]),response:L.extend({trial:Ls})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Sp.extend({customerId:x.uuid()}),response:L.extend({trial:Ls})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Yo,response:L.extend({subscriptions:Rp})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Yo,response:L.extend({purchases:kp})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Pp,response:L.extend({conflicts:jp})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:_p,response:L.extend({resolution:Ep})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Op,response:L.extend({verification:Cp})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:lp.safeExtend({...Qr,customerId:x.uuid().optional()}),response:L.extend({quote:qi})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:ju,response:L.extend({record:Tu})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Sr.extend({customerId:x.uuid().optional(),intent:x.enum(["confirm","cancel"]).optional()}),response:L.extend({operation:Wr})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Sr.extend({customerId:x.uuid().optional()}),response:L.extend({operation:Wr})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:mp.safeExtend({customerId:x.uuid().optional()}),response:L.extend({quote:gp})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Sr.extend({customerId:x.uuid().optional(),intent:x.enum(["confirm","cancel"]).optional()}),response:L.extend({operation:Vs})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Sr.extend({customerId:x.uuid().optional()}),response:L.extend({operation:Vs})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:hp.safeExtend({customerId:x.uuid()}),response:L.extend({quote:yp})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Sr.extend({customerId:x.uuid()}),response:L.extend({operation:Ho})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Sr.extend({customerId:x.uuid()}),response:L.extend({operation:Ho})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Hl,response:L.extend({controls:ys})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Ul,response:L.extend({prepared:Bl})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:zl,response:L.extend({authorization:ko})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Wl,response:L.extend({coupons:Yl})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:$l,response:L.extend({authorization:ko})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Jl,response:L.extend({invoices:Zl})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Ql,response:L.extend({invoice:vi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:x.object({customerId:x.uuid(),command:Kl}).strict(),response:L.extend({controls:ys})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:x.object({customerId:x.uuid(),command:Um}).strict(),response:L.extend({entity:Lm})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:x.strictObject({customerId:x.uuid().nullable(),query:Hm}),response:L.extend({analytics:Qm})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:x.object({customerId:x.uuid().nullable(),query:Pr}).strict(),response:L.extend({analytics:Gm})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Jm,response:L.extend({batchId:x.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Zm,response:L.extend({batch:Wm})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:_d.extend({customerId:x.string().min(1).optional()}),response:L.extend({check:gr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:x.strictObject({kind:Kn,selector:x.discriminatedUnion("type",[x.strictObject({type:x.literal("resource"),id:x.uuid()}),x.strictObject({type:x.literal("version"),id:x.uuid()})]),customerId:x.string().min(1).optional()}),response:L.extend({content:Ns})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Dm,response:L.extend({paywall:vr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:x.strictObject({...Qr,selector:qp,customerId:x.string().min(1).optional(),commerce:zr,requirement:zn.optional()}),response:L.extend({offering:Vp,candidates:x.array(Os).max(20),availability:x.array(x.strictObject({productVersionId:x.uuid(),available:x.boolean(),reason:x.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:gr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:x.object({customerId:x.uuid().optional(),entityId:x.uuid().optional()}).strict(),response:L.extend({holdings:fd})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:x.object({customerId:x.uuid().optional(),query:hd}).strict(),response:L.extend({ledger:Ad})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:ld.extend({customerId:x.uuid().optional()}),response:L.extend({detail:dd})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:xs.safeExtend({customerId:x.uuid().optional()}),response:L.extend({statement:pd})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:x.object({customerId:x.uuid().optional(),command:Pi.options[0]}).strict(),response:L.extend({quote:id})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:x.strictObject({customerId:x.uuid(),command:x.union([x.strictObject({eventName:x.string().min(1),quantity:me.optional(),properties:pt.optional(),entityId:x.uuid().optional(),idempotencyKey:x.string().min(1).max(120)}),x.strictObject({internal_feature_id:x.uuid(),quantity:me.optional(),properties:pt.optional(),entityId:x.uuid().optional(),idempotencyKey:x.string().min(1).max(120)})])}),response:L.extend({receipts:x.array(_i).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:x.object({customerId:x.uuid(),command:Pi.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:L.extend({receipt:_i})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:sf,response:L.extend({redemption:af})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:lf,response:L.extend({referralCode:df})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:cf,response:L.extend({checkout:uf})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:bd,response:L.extend({seats:ws})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Sd,response:L.extend({seats:ws})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:rx,response:ix},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:pc,response:L.extend({customer:ii})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:gm,response:L.extend(hm.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:fm,response:L.extend(mm.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:x.object({customerId:x.uuid()}).strict(),response:L.extend(kr.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:x.strictObject({}),response:L.extend(kr.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:x.strictObject({customerId:x.uuid(),sessionId:x.uuid().optional()}),response:L.extend({revoked:x.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:x.strictObject({guestToken:x.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:ma.optional()}),response:L.extend({customerId:x.uuid(),guestToken:x.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:x.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:x.strictObject({guestToken:x.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:L.extend(kr.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:x.strictObject({guestToken:x.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:x.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:x.uuid()}),response:L.extend({customer:ii,switched:x.boolean(),replayed:x.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:x.strictObject({code:x.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:x.uuid()}),response:_f()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:x.object({}).strict(),response:L.extend({offers:x.array(Si)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:x.object({customerId:x.string().min(1).max(255).optional(),couponId:x.uuid(),...Qr,requestId:x.uuid(),couponContentDigest:x.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:_f()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:xf,response:L.extend({receipt:If})}},SR={sendMessage:O.sendMessage,readMessage:O.readMessage,bindPushInstallation:O.bindPushInstallation,readPushInstallation:O.readPushInstallation,updatePushAddress:O.updatePushAddress,readMessagingPreference:O.readMessagingPreference,setMessagingPreference:O.setMessagingPreference,listInvoiceTemplates:O.listInvoiceTemplates,previewInvoice:O.previewInvoice,createInvoice:O.createInvoice,manageInvoice:O.manageInvoice,readInvoiceOperation:O.readInvoiceOperation,listInvoices:O.listInvoices,getInvoice:O.getInvoice,getCodeReferenceConfig:O.getCodeReferenceConfig,submitCodeReferences:O.submitCodeReferences,getFeatures:O.getFeatures,evaluateFeatures:O.evaluateFeatures,trackEvents:O.trackEvents,setupPayment:O.setupPayment,readPaymentSetup:O.readPaymentSetup,previewSubscriptionBatch:O.previewSubscriptionBatch,confirmSubscriptionBatch:O.confirmSubscriptionBatch,readSubscriptionBatch:O.readSubscriptionBatch,abandonSubscriptionBatch:O.abandonSubscriptionBatch,manageSubscriptionTrial:O.manageSubscriptionTrial,readSubscriptionTrial:O.readSubscriptionTrial,listSubscriptions:O.listSubscriptions,listPurchases:O.listPurchases,listSubscriptionConflicts:O.listSubscriptionConflicts,retrySubscriptionConflict:O.retrySubscriptionConflict,readAiPricing:O.readAiPricing,readUsage:O.readUsage,setUsage:O.setUsage,previewRefund:O.previewRefund,refund:O.refund,readRefund:O.readRefund,previewUpdate:O.previewUpdate,update:O.update,readSubscriptionUpdate:O.readSubscriptionUpdate,restoreNativePurchase:O.restoreNativePurchase,verifySubscriptions:O.verifySubscriptions,previewAttach:O.previewAttach,attach:O.attach,readSubscriptionOperation:O.readSubscriptionOperation,manageBalanceGrant:O.manageBalanceGrant,readBalanceSource:O.readBalanceSource,adjustBalance:O.adjustBalance,listBalanceGrants:O.listBalanceGrants,readBillingControls:O.readBillingControls,prepareBillingAuthorization:O.prepareBillingAuthorization,confirmBillingAuthorization:O.confirmBillingAuthorization,setBillingCoupons:O.setBillingCoupons,revokeBillingAuthorization:O.revokeBillingAuthorization,listBillingInvoices:O.listBillingInvoices,confirmBillingAdjustment:O.confirmBillingAdjustment,manageBillingLimits:O.manageBillingLimits,createCustomer:O.createCustomer,getCustomer:O.getCustomer,listCustomers:O.listCustomers,updateCustomer:O.updateCustomer,createSession:O.createSession,refreshSession:O.refreshSession,revokeSessions:O.revokeSessions,createGuestCustomer:O.createGuestCustomer,resumeGuestSession:O.resumeGuestSession,claimGuestCustomer:O.claimGuestCustomer,checkEntitlement:O.checkEntitlement,resolveOffering:O.resolveOffering,resolveContent:O.resolveContent,resolvePaywall:O.resolvePaywall,readHoldings:O.readHoldings,readLedger:O.readLedger,readBillingInvoice:O.readBillingInvoice,readCreditStatement:O.readCreditStatement,quoteBalance:O.quoteBalance,trackUsage:O.trackUsage,mutateBalance:O.mutateBalance,manageUsageEntity:O.manageUsageEntity,readUsageAnalytics:O.readUsageAnalytics,readCreditAnalytics:O.readCreditAnalytics,submitUsageBatch:O.submitUsageBatch,readUsageBatch:O.readUsageBatch,listOffers:O.listOffers,grantOffer:O.grantOffer,recordCouponRedemption:O.recordCouponRedemption,redeemCoupon:O.redeemCoupon,redeemReward:O.redeemReward,createReferralCode:O.createReferralCode,claimRewardProduct:O.claimRewardProduct,readSeats:O.readSeats,manageSeat:O.manageSeat};import{z as qc}from"zod";var Xi=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function Vc(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(d=>zt(t.attributes??{},d.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new Xi("Required GB Feature is unavailable");i=_n(e.featureKey,t),o=i.value,Object.assign(r,Hr(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new Xi("Required GB Experiment is unavailable");if(a=Eo(u,t),o=a.value,s=a.inExperiment&&!a.passthrough&&typeof o=="string"?o:"notParticipating",c=s==="notParticipating"?e.notParticipating:e.routes[s],!c)throw new Xi("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:_n(e.configuration.featureKey,t).value;o={type:"offering_version",id:qc.uuid().parse(u)},Object.assign(r,Hr(e,{value:o})),c=e.next;break}case"coupon":case"coupons":o=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,Hr(e,{value:o})),c=e.next;break}return{port:s,target:c,projections:r,...o===void 0?{}:{value:o},...i?{feature:i}:{},...a?{experiment:a}:{}}}function Ef(e,t,n){qc.uuid().parse(e),qc.number().int().nonnegative().parse(t);let r=Fr(Mr(new TextEncoder().encode(JSON.stringify([e,t,n])))).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)}`}import{z as $}from"zod";var Zn=$.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ox=$.enum(["running","waiting","completed","closed","ineligible","failed"]),ax=$.discriminatedUnion("type",[lc,$.strictObject({type:$.literal("wait"),receiptId:$.uuid(),kind:$.enum(["timer","event","operation"]),deadline:$.iso.datetime({offset:!0}).nullable(),eventName:Zn.optional()}),$.strictObject({type:$.literal("open_url"),receiptId:$.uuid(),url:mc,openIn:fc}),$.strictObject({type:$.literal("event"),receiptId:$.uuid(),event:Zn})]),Oa=$.strictObject({type:$.literal("funnel"),id:$.uuid(),versionId:$.uuid()}),sx={id:Zn,presentation:jn,outputs:$.array(Zn).max(250),inputs:sa,values:$.record($.string(),ge).optional(),offeringKey:dt.optional(),capabilities:$r,customerData:Dd,dataCursors:$.record(Zn,aa.nullable())},cx=$.strictObject({...sx,content:$.strictObject({type:$.literal("document"),document:Wt})}),Uc=$.strictObject({id:$.uuid(),source:Oa,revision:$.number().int().nonnegative(),visit:$.number().int().nonnegative(),nodeId:Zn,nodeType:$.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:ox,stopped:$.boolean(),canBack:$.boolean(),authenticated:$.boolean(),locale:$.string().min(1).max(35),answers:Hn,parameters:Qn,variables:$.record($.string(),ge),output:ge.nullable(),screen:cx.nullable(),paywall:$.strictObject({receiptId:$.uuid(),resolution:$.union([Ji,vr]),quote:qi.nullable(),operation:Wr.nullable(),purchaseRequestId:$.uuid().nullable(),selectionGeneration:$.number().int().nonnegative().optional(),canReselect:$.boolean().optional()}).nullable(),instruction:ax.nullable(),pendingRequest:$.strictObject({requestId:$.uuid(),authenticationRequired:$.boolean()}).nullable(),runExpiresAt:$.iso.datetime({offset:!0}),credentialExpiresAt:$.iso.datetime({offset:!0}).nullable()}),eo=$.strictObject({scope:Ve,run:Uc,settlement:$.strictObject({requestId:$.uuid(),state:$.enum(["pending","unknown","settled"]),operationId:$.uuid().nullable(),receiptId:$.uuid().nullable().optional()}).optional(),purchase:$.strictObject({receiptId:$.uuid(),quote:qi.nullable(),operation:Wr.nullable(),canReselect:$.boolean().optional()}).optional(),review:$.strictObject({activeOperationId:$.uuid().nullable(),pages:$.array($.strictObject({receiptId:$.uuid(),nodeId:Zn,visit:$.number().int().nonnegative()})).max(100),page:$.strictObject({receiptId:$.uuid(),nodeId:Zn,visit:$.number().int().nonnegative(),document:Wt,answers:Hn,inputs:sa,values:$.record($.string(),ge).optional()}).nullable(),coupons:$.array($.strictObject({grantId:$.uuid(),status:$.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:$.string().nullable()})).max(100),purchases:$.array($.strictObject({receiptId:$.uuid(),operationId:$.uuid(),status:$.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:$.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:$.uuid().optional()}),Rf=eo.extend({run:Uc.extend({paywall:Uc.shape.paywall.unwrap().extend({resolution:vr}).nullable()})});var kf="X-Indiana-Server-Key";import{z as Ee}from"zod";var ci=Ee.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Tf=Ee.strictObject({entry:ci,nodes:Ee.array(Ee.strictObject({id:ci,type:Ee.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Ee.record(Ee.string(),ci),writes:Ee.record(dt,dt),resources:Ee.strictObject({screenId:ci.optional(),paywallVersionId:Ee.uuid().optional(),couponId:Ee.uuid().optional(),couponIds:Ee.array(Ee.uuid()).max(20).optional(),experimentId:Ee.uuid().optional(),featureKey:Ee.string().optional(),offeringVersionId:Ee.uuid().optional()})})).min(1).max(500)}),jf={scope:Ve,funnelId:Ee.uuid(),versionId:Ee.uuid(),evaluationRevision:Ee.number().int().nonnegative(),expiresAt:Ee.iso.datetime({offset:!0}).nullable(),topology:Tf},Ca=Ee.discriminatedUnion("evaluationMode",[Ee.strictObject({...jf,evaluationMode:Ee.literal("local"),growth:on,conditions:Ee.record(ci,Ee.array(Ee.strictObject({condition:Bt,port:Ee.string()})))}),Ee.strictObject({...jf,evaluationMode:Ee.literal("remote")})]),ux=Ca.options[0].extend({evaluation:Ee.strictObject({maxTransitions:Ee.number().int().min(1).max(1e4),variables:Ee.record(dt,Kr),outputSchema:Gr,terminals:Ee.record(ci,Ee.strictObject({outcome:Ee.enum(["completed","closed","ineligible","failed"]),output:Gi.nullable()}))})});function lx(e){return Tf.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(o=>o.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,o)=>{n[`case:${o}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];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=Ee.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.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:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function Lc(e){let t=ai.parse(e.document),n=e.evaluationMode==="local"?on.parse(e.payload):null;if(n&&(n.scope.projectId!==e.scope.projectId||n.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:n?.expiresAt??null,topology:lx(t)};return Ca.parse(e.evaluationMode==="remote"?r:{...r,growth:Ia(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}function Nf(e){let t=Lc(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=ai.parse(e.document);return ux.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.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}]]}))}})}import{z as We}from"zod";var Df=We.string().regex(/^[a-f0-9]{64}$/),dx=ni.omit({variations:!0,active:!0}).extend({changeId:Df,variations:We.array(We.strictObject({urlRedirect:We.string().max(2048)})).min(2).max(20)}),Ff=We.strictObject({environmentId:We.uuid(),trackExposures:We.boolean(),generation:Df,experiments:We.array(dx).max(100),savedGroups:Bi}),px=We.strictObject({eventUuid:We.uuid(),timestamp:We.iso.datetime({offset:!0}).optional(),deviceId:We.string().min(1).max(128),sessionId:We.string().min(1).max(128).optional(),url:We.url().max(2048),pageTitle:We.string().max(512).optional(),experimentKey:We.string().min(1).max(255),variationKey:We.string().min(1).max(64)}),tk=We.strictObject({events:We.array(px).min(1).max(20)}),nk=We.strictObject({inserted:We.number().int().nonnegative(),duplicates:We.number().int().nonnegative(),skipped:We.number().int().nonnegative(),rejected:We.array(We.strictObject({index:We.number().int().nonnegative(),reason:We.string()}))});import{z as At}from"zod";var mx=At.strictObject({selector:At.string().min(1).max(2048),action:At.enum(["set","append","remove"]),attribute:At.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:At.string().max(5e4).optional(),parentSelector:At.string().max(2048).optional(),insertBeforeSelector:At.string().max(2048).optional()}),fx=At.strictObject({variation:At.string().min(1).max(128),description:At.string().max(2e3).default(""),css:At.string().max(1e5).default(""),js:At.string().max(1e5).default(""),domMutations:At.array(mx).max(200).default([]),iam:Xp.optional(),renderGuard:ia.optional()}),Bc=fx.omit({variation:!0,description:!0,iam:!0}),gx=ni.omit({variations:!0,active:!0}).extend({changeId:At.string().regex(/^[a-f0-9]{64}$/),variations:At.tuple([Bc,Bc]).rest(Bc).refine(e=>e.length<=20)}),Mf=At.strictObject({trackExposures:At.boolean(),environmentId:At.uuid(),generation:At.string().regex(/^[a-f0-9]{64}$/),experiments:At.array(gx).max(100),savedGroups:Bi});import{z as nt}from"zod";var $c=32,hx=522240;function Gc(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 Ax=nt.strictObject({nodeId:nt.string().min(1).max(64),visit:nt.number().int().nonnegative(),revision:nt.number().int().nonnegative()}),zc=nt.record(nt.string(),ge),yx=nt.strictObject({id:nt.uuid(),nodeId:nt.string().min(1).max(64),visit:nt.number().int().nonnegative(),input:nt.strictObject({schemaVersion:Ki.shape.schemaVersion,kind:Ki.shape.kind,selector:Ki.shape.selector,contract:Ki.shape.contract}),context:zc,removed:nt.array(nt.string()).max(100),attributes:zc,removedAttributes:nt.array(nt.string()).max(100),result:vm,offeringVersionId:nt.uuid().nullable(),events:nt.strictObject({entered:nt.string().regex(/^[1-9][0-9]{0,18}$/),decision:nt.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),mk=nt.strictObject({schemaVersion:nt.literal(1),mode:nt.enum(["local","remote"]),versionId:nt.uuid(),generation:nt.number().int().positive(),base:Ax,context:zc,steps:nt.array(yx).min(1).max($c)}).refine(e=>Yt(e)<=hx,"Segment exceeds its byte budget");var Kc=class extends Error{constructor(n,r){super(r);qe(this,"code",n);this.name="FunnelLocalCalculationError"}},qf=(e,t)=>new Kc(e,t),bx=e=>({experiments:e.experiments,features:e.features});function Sx(e,t=qf){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=qr(e.growth.savedGroups),i=bx(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return _n(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,d;if(c.type==="condition"){let w=e.conditions[c.id];if(!w)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=Vc({id:c.id,name:c.id,type:"condition",cases:w.map(I=>({condition:I.condition,target:c.outputs[I.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");d=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let I=Vc({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);d=I.value,u=I.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)d=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let m=c.outputs[u]??(u==="value"?c.id:void 0);if(!m)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:m,...d===void 0?{}:{value:d}}}}}function xx(e,t){let n=Ca.parse(e);if(n.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=n.expiresAt?Date.parse(n.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let a=Sx(n,t);return(o,s)=>(i(),Ix(a,o,s))}function Ix(e,t,n){let r=mt.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:a,onExperimentViewed:o}=n,s={attributes:r,...i?{saveStickyBucketAssignmentDoc:c=>i(structuredClone(c))}:{},...a?{onFeatureUsage:(c,u)=>a(c,structuredClone(u))}:{},...o?{onExperimentViewed:(c,u)=>o(structuredClone(c),structuredClone(u))}:{},features:e.features,savedGroups:e.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,s)}function vx(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(m=>m.next.attributeName===s.attributeName&&m.next.attributeValue===s.attributeValue),u=s.attributeName+"||"+s.attributeValue,d={expected:n.sticky[u]??null,next:s};c<0?r.push(d):r[c]=d},onExperimentViewed(s,c){c.inExperiment&&c.hashUsed&&!c.passthrough&&i.push(ge.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(ge.parse({feature:s,value:c.value,source:c.source,...c.ruleId?{ruleId:c.ruleId}:{}}))}});return{port:o.port,...o.value===void 0?{}:{value:o.value},sticky:r,exposures:i,features:a}}function Vf(e,t,n,r=qf){let i=n,a=new Map(t.graph.nodes.map(g=>[g.id,g])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,d=n.visit,m=!1,w,I=g=>(w??(w=xx(e,r)),vx(w,g,{attributes:oc({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let g=0;g<$c;g++){let f=a.get(u);if(!f||!Gc(f))break;if(d>=t.execution.maxTransitions&&(d>t.execution.maxTransitions||f.type!=="end"&&f.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let S,h;if(["condition","feature","split"].includes(f.type)||f.type==="offering"&&f.configuration.source==="feature")S=I(f.id),f.type==="offering"&&(S.value={type:"offering_version",id:String(S.value)}),f.type==="condition"?h=S.port==="default"?f.default:f.cases[Number(S.port.slice(5))]?.target:f.type==="split"?h=S.port==="notParticipating"?f.notParticipating:f.routes[S.port]:(f.type==="feature"||f.type==="offering")&&(h=f.next);else if(S={port:"next",sticky:[],exposures:[],features:[]},(f.type==="entry"||f.type==="coupon"||f.type==="coupons")&&(h=f.next),f.type==="offering"&&f.configuration.source==="fixed"&&(S.value={type:"offering_version",id:f.configuration.versionId},h=f.next),f.type==="end"||f.type==="output"){let v=f.type==="end"?f.output:f.value;if(S=v?.type==="feature"?I(f.id):{...S,port:"value",value:v?.type==="literal"?v.value:v?.type==="variable"?ks({source:"variable",key:v.key,...v.path?{path:v.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},v&&(S.value===void 0||!rn(t.outputSchema,S.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let P=[...c,{nodeId:u,result:S}];if(Yt({steps:P})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:S}),f.type==="feature"||f.type==="offering"||f.type==="coupon"||f.type==="coupons"){let v=f.type==="coupons"?f.couponIds.map(j=>({type:"reward",id:j})):f.type==="coupon"?{type:"reward",id:f.couponId}:S.value;if(v===void 0)throw r("INVALID_RESPONSE","Node output is missing");let E=Hr(f,{value:v});Ld(t.variables,f,E),Object.assign(o,E)}for(let v of S.sticky)s[`${v.next.attributeName}||${v.next.attributeValue}`]=structuredClone(v.next);if(f.type==="end"||f.type==="output"){m=!0;break}if(!h)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=h,d++}let p=a.get(u);return{steps:c,...!m&&p&&!Gc(p)?{boundary:{nodeId:u,visit:d}}:{}}}import{z as Ae}from"zod";var Pa=Ae.string().regex(/^[a-f0-9]{64}$/),wx=Ae.strictObject({release:Pa,render:ia,button:Ae.strictObject({selector:Ae.string().min(1).max(512),elementKey:Ae.string().min(1).max(256),tag:Ae.enum(["button","a","input"])}).nullable()}),kk=Ae.strictObject({scope:Ve.extend({environmentId:Ae.uuid()}),release:Pa,validatedAt:Ae.iso.datetime({offset:!0}),validUntil:Ae.iso.datetime({offset:!0}),entries:Ae.array(Ae.strictObject({id:Ae.uuid(),funnelId:Ae.uuid(),versionId:Ae.uuid(),event:Ae.enum(["screen_enter","button_click"]),target:wx})).max(4e3)}),jk=Ae.strictObject({operation:Ae.literal("entry_start"),funnelId:Ae.uuid(),versionId:Ae.uuid(),entryId:Ae.uuid(),release:Pa,requestId:Ae.uuid(),locale:Ae.string().min(1).max(35).default("en")}),Tk=Ae.strictObject({scope:Ve,suppressed:Ae.literal(!0),reason:Ae.enum(["frequency","in_progress"]),retryAt:Ae.iso.datetime({offset:!0}).nullable()}),Nk=Ae.strictObject({experimentId:Ae.uuid(),splitNodeId:Ae.string().min(1).max(128)}),Ox=Ae.strictObject({experimentId:Ae.uuid(),experimentKey:Ae.string().min(1).max(128),variationKey:Ae.string().min(1).max(128),inExperiment:Ae.boolean(),generation:Ae.string().min(1).max(256)}),Uf=Ae.strictObject({operation:Ae.literal("page_experiments"),release:Pa,usedReceiptIds:Ae.array(Ae.uuid()).max(20).default([]),customerToken:Ae.string().regex(jt).optional()}),Lf=Ae.strictObject({scope:Ve,runId:Ae.uuid(),assignments:Ae.array(Ox.extend({receiptId:Ae.uuid()})).max(20),payload:Mf});var y=class extends Error{constructor(n,r,i,a,o){super(r);qe(this,"code",n);qe(this,"status",i);qe(this,"requestId",a);qe(this,"retryable");qe(this,"recovery");qe(this,"retryAfterSeconds");qe(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=po(n,i??0,{...o,retryAfter:o?.retryAfterSeconds===void 0?void 0:String(o.retryAfterSeconds)});this.retryable=s.retryable,this.recovery=s.recovery,this.retryAfterSeconds=s.retryAfterSeconds}};var to=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new y("INVALID_STATE","Installation sequence exhausted");return e+1},Cx=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(e,t=>t.charCodeAt(0))))].map(t=>t.toString(16).padStart(2,"0")).join("");function Nn(e,t){return e.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new y("INVALID_STATE","Installation journal is invalid");return t({...n})})}function Bf(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve();if(e&&(!n||Ve.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new y("SCOPE_MISMATCH","Push installation belongs to another scope");let c=()=>{if(!e)throw new y("NOT_CONFIGURED","Configure this client's native Push host first");return e},u=h=>{if(h!==i)throw new y("IDENTITY_CHANGED","Identity changed during Push operation")};async function d(h){let P=c();if(!P.sha256&&!globalThis.crypto?.subtle)throw new y("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let v=P.sha256?await P.sha256(Uint8Array.from(h,E=>E.charCodeAt(0))):await Cx(h);if(!/^[a-f0-9]{64}$/.test(v))throw new y("INVALID_STATE","Push credential digest is invalid");return v}function m(h){let P=sr.parse(h);if(P.installationId.toLowerCase()!==c().installationId.toLowerCase())throw new y("INVALID_RESPONSE","Push response belongs to another installation");return P}async function w(h,P){let v=c(),E={installationId:v.installationId,publicKey:v.publicKey,issuedAt:new Date().toISOString(),...P},j=await v.sign(Cu(h,v.scope,E));return{...E,signature:j}}let I=(h,P,v)=>t.requestWithCredential?t.requestWithCredential(h,P,v):t.request(h,P);async function p(){let h=c(),P=i,v=r?await(t.session?.access()??r):null,E=Nn(h,Se=>Se),j;if(E.detachSeq!==null){let Se=E.detachSeq,Te=vu.parse(await w("detach",{sequence:Se,platform:h.platform}));try{let Pe=await t.request("push/installations/detach",{...h.scope,...Te},"POST",{installationDetach:!0});if(!Pe||typeof Pe!="object"||!("installation"in Pe))throw new y("INVALID_RESPONSE","Push detach acknowledgement is invalid");let Vt=m(Pe.installation);if(Vt.bound||Vt.identitySeq!==Se)throw new y("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Pe){if(Pe instanceof y&&Pe.status===404)j=Pe;else if(!(Pe instanceof y)||Pe.status!==412)throw Pe}j||Nn(h,Pe=>({...Pe,detachSeq:Pe.detachSeq===Se?null:Pe.detachSeq}))}if(u(P),!v){if(j)throw j;return null}let q=O.bindPushInstallation,de=q.request.parse(await w("bind",{sequence:o,platform:h.platform,credentialDigest:await d(v)}));u(P);let be=q.response.parse(await I(q.path,de,v));u(P);let Oe=m(be.installation);if(!Oe.bound||Oe.identitySeq!==o)throw new y("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return j&&E.detachSeq!==null&&o>E.detachSeq&&Nn(h,Se=>({...Se,detachSeq:Se.detachSeq===E.detachSeq?null:Se.detachSeq})),Oe}async function g(){c();let h=i,P=r?await(t.session?.access()??r):null;if(!P)throw new y("NOT_IDENTIFIED","Identify before reading this installation");let v=O.readPushInstallation,E=v.request.parse(await w("read",{credentialDigest:await d(P)}));u(h);let j=v.response.parse(await I(v.path,E,P));return u(h),m(j.installation)}function f(h=p){let P=s.catch(()=>{}).then(h);return s=P,P.catch(v=>{try{e?.onError?.(v instanceof Error?v:new Error("Push synchronization failed"))}catch{}}),P}async function S(h,P,v){let E=c(),j=P.identity,q=P.observation,de=r?await(t.session?.access()??r):null;if(u(j),q!==a)throw new y("INVALID_STATE","Push observation changed during recovery");if(!de)throw new y("NOT_IDENTIFIED","Identify before recovering a Push address");if(!h.connectionId||!h.kind||!h.token||!["granted","provisional"].includes(h.permission))throw new y("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await f(async()=>{if(u(j),await p(),u(j),q!==a)throw new y("INVALID_STATE","Push observation changed during recovery");let be=Nn(E,Vt=>v?Vt:{...Vt,addressSeq:to(Vt.addressSeq)}),Se=await w(v?"recovery_confirm":"recovery_request",{...h,sequence:be.addressSeq,credentialDigest:await d(de),...v?{challenge:v}:{}}),Te=v?Ou.parse(Se):wu.parse(Se);if(u(j),q!==a)throw new y("INVALID_STATE","Push observation changed during recovery");let Pe=await I(`push/installations/recovery/${v?"confirm":"request"}`,Te,de);if(u(j),q!==a||Nn(E,Vt=>Vt).addressSeq!==be.addressSeq)throw new y("INVALID_STATE","Push observation changed during recovery");if(v){let Vt=O.updatePushAddress.response.parse(Pe),Je=m(Vt.installation);if(!Je.bound||Je.identitySeq!==o||Je.addressSeq!==be.addressSeq||Je.connectionId!==h.connectionId||Je.addressStatus!=="active")throw new y("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return Je}if(!Pe||typeof Pe!="object"||!("recovery"in Pe))throw new y("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return $a.parse(Pe.recovery)})}return{recoveryObserver(){c();let h={identity:i,observation:++a};return{async request(P){return $a.parse(await S(P,h))},async confirm(P,v){return sr.parse(await S(v,h,P))}}},identify(h){if(!e)return;o=Nn(e,v=>({...v,identitySeq:to(v.identitySeq)})).identitySeq,r=h,i++,a++},reset(){if(e)try{Nn(e,h=>{let P=to(h.identitySeq);return{...h,identitySeq:P,detachSeq:P}})}finally{r=null,i++,a++}},start(){e&&f()},async sync(){return await f()},read:g,async recover(){let h=c(),P=i,v=o;return a++,await f(async()=>{u(P);let E=await g();return u(P),o=Nn(h,q=>{if(q.identitySeq!==v)throw new y("IDENTITY_CHANGED","A newer installation intent exists");return{...q,identitySeq:to(Math.max(q.identitySeq,E.identitySeq)),addressSeq:Math.max(q.addressSeq,E.addressSeq)}}).identitySeq,await p()})},tokenObserver(){c();let h=++a,P=i;return async v=>{if(h!==a||P!==i)return null;let E=c(),j=r?await(t.session?.access()??r):null;if(!j)throw new y("NOT_IDENTIFIED","Identify before registering a Push token");if(await f(),u(P),h!==a)return null;let q=Nn(E,Se=>({...Se,addressSeq:to(Se.addressSeq)})),de=O.updatePushAddress,be=de.request.parse(await w("address",{...v,sequence:q.addressSeq,credentialDigest:await d(j)}));if(u(P),h!==a)return null;let Oe=de.response.parse(await I(de.path,be,j));return u(P),m(Oe.installation)}}}}function zf(e,t){return{messaging:{async preference(n){let r=O.readMessagingPreference;return r.response.parse(await e(r.path,r.request.parse({channel:n}))).preference},async setPreference(n){let r=O.setMessagingPreference;return r.response.parse(await e(r.path,r.request.parse(n))).preference}},push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){let n=O.readMessagingPreference;return n.response.parse(await e(n.path,{channel:"push"})).preference},async setPreference(n){let r=O.setMessagingPreference;return r.response.parse(await e(r.path,r.request.parse({...n,channel:"push"}))).preference}}}}var $f={name:"@tinkerlandai/indiana-sdk",version:"0.9.5",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};function ze(e){return typeof e=="string"?e:String(e)}var _x=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function Ex(e){return e.replace(_x,"$1\uFFFD")}function Zc(e,t){if(typeof e!="object"||e==null){let n="";throw n+="The provided value is not an object",new TypeError(n)}return e}function Xf(e){if(e!=null&&(typeof e=="object"||typeof e=="function")){let t=e[Symbol.iterator];if(t==null)return;if(typeof t!="function")throw new TypeError("The provided value is not iterable");let n=t.call(e);if(!n||typeof n!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return n}}function Gf(e){let t;if(Array.isArray(e)){let n=e.map(ze);if(n.length===2)return n}else if((t=Xf(e))!=null){let n=Zc(t.next()),r=Zc(t.next());if(!n.done&&!r.done)return[ze(n.value),ze(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var Kf="0123456789ABCDEF",Rx=/(?:%[0-9A-Fa-f]{2})+/g;function vn(e){return`%${Kf[e>>4&15]}${Kf[15&e]}`}function eg(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?vn(e):String.fromCharCode(e):e<=2047?vn(192|e>>6)+vn(128|63&e):e<=65535?vn(224|e>>12)+vn(128|e>>6&63)+vn(128|63&e):vn(240|e>>18)+vn(128|e>>12&63)+vn(128|e>>6&63)+vn(128|63&e)}function Wc(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Yc(e,t=!1){let n=0;for(;n<e.length;n++){let r=e.charCodeAt(n);if(r===37||t&&r===43)break}return n===e.length?e:(t?e.replace(/\+/g," "):e).replace(Rx,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function io(e){return e<=31||e>126}function kx(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return io(e)}}function ou(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return io(e)}}function jx(e){return ou(e)||e===39}function Xc(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return ou(e)}}function ja(e){switch(e){case 47:case 58:case 59:case 61:case 64:case 91:case 92:case 93:case 124:return!0;default:return Xc(e)}}function Hf(e){switch(e){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(n){switch(n){case 36:case 37:case 38:case 43:case 44:return!0;default:return ja(n)}})(e)}}function tg(e,t){return eg(e=e||0,t)}function wn(e,t,n=!1){let r=0;for(;r<e.length;r++){let a=e.charCodeAt(r);if(a>=128||n&&a===32||t(a))break}if(r===e.length)return e;let i=e.slice(0,r);for(;r<e.length;r++){let a=e.charCodeAt(r),o=a;if(a>=55296&&a<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343&&(o=(a-55296<<10)+s-56320+65536,r++)}i+=eg(o,t,n)}return i}function au(e){let t=[],n=0,r=0;for(;r<=e.length;){if(r=e.indexOf("&",n),r<0&&(r=e.length),r!==n){let i=e.slice(n,r),a=i.indexOf("=");a<0&&(a=i.length),t.push([Yc(i.slice(0,a),!0),Yc(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function eu(e){let t="";for(let n=0;n<e.length;n++){let r=wn(e[n][0],Hf,!0),i=wn(e[n][1],Hf,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var Tx=[2191,2191,3164,3164,3292,3292,6863,6877,6880,6891,8385,8385,11158,11158,42958,42959,42962,42962,42964,42964,42993,42993,64451,64466,64912,64913,64968,64974,67904,67929,69317,69319,69328,69336,69370,69371,72544,72551,73136,73179,73184,73193,93856,93880,93883,93907,94194,94198,100344,100351,101641,101662,101760,101874,118010,118012,118458,118480,118496,118512,124608,124638,124640,124661,124670,124671,128728,128728,128887,128890,129232,129240,129620,129623,129674,129674,129678,129678,129736,129736,129741,129741,129770,129770,129775,129775,130042,130042,177978,177983,183970,183981,205744,210041],Nx=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],Dx=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],Fx=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function Mx(e){for(let t=0;t<e.length;t++){let n=e.codePointAt(t);if(n>65535&&t++,n<=32||n===37||n===127||n>=55296&&n<=57343||n>=128&&n<=159||n>=64976&&n<=65007||!(65534&~n)||n===65533)return!0}return!1}var[qx,Vx,Ux,Qf]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,n,r]){return[t,n.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(r),i=>i.charCodeAt(0))]});function Lx(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function ng(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function no(e,t){let[n,r,i]=e,a=t>>8;for(let c=0;c<n.length;c+=2)if(a>=n[c]&&a<=n[c+1])return!0;let o=r.indexOf(a);if(o<0)return!1;let s=255&t;return!!(i[32*o+(s>>3)]&1<<(7&s))}function Bx(e){let t=Array.from(e,n=>n.codePointAt(0));for(let n=0;n<t.length;n++){let r=t[n];if(r!==8204&&r!==8205||n>0&&ng(Fx,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&no(Qf,t[i]);)i--;let a=n+1;for(;a<t.length&&no(Qf,t[a]);)a++;if(!(i>=0&&a<t.length&&no(Vx,t[i])&&no(Ux,t[a])))return!1}return!0}var zx=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,$x=/\p{Script=Latin}/u;function Gx(e){return!zx.test(e)||!$x.test(e)}var Wn=36,Ea=1,tu=26,Kx=38,Hx=700,Qx=72,Jx=128,Zx=2147483647;function Jf(e){return String.fromCharCode(e+22+75*+(e<26))}function Wx(e,t,n){let r=0;for(e=n?Math.floor(e/Hx):e>>1,e+=Math.floor(e/t);e>(Wn-Ea)*tu>>1;r+=Wn)e=Math.floor(e/(Wn-Ea));return Math.floor(r+(Wn-Ea+1)*e/(e+Kx))}function Yx(e){let t=Array.from(e,c=>c.codePointAt(0)),n="",r=0;for(let c=0;c<t.length;c++){let u=t[c];u<128&&(n+=String.fromCharCode(u),r++)}let i=r;i&&(n+="-");let a=Jx,o=0,s=Qx;for(;r<t.length;){let c=Zx;for(let u=0;u<t.length;u++){let d=t[u];d>=a&&d<c&&(c=d)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let d=t[u];if(d<a&&o++,d===a){let m=o;for(let w=Wn;;w+=Wn){let I=w<=s?Ea:w>=s+tu?tu:w-s;if(m<I)break;n+=Jf(I+(m-I)%(Wn-I)),m=Math.floor((m-I)/(Wn-I))}n+=Jf(m),s=Wx(o,r+1,r===i),o=0,r++}}o++,a++}return n}function Hc(e){let t=10;if(e.length>=2&&e[0]==="0"&&(e[1]==="x"||e[1]==="X"))e=e.slice(2),t=16;else if(e.length>=2&&e[0]==="0")e=e.slice(1),t=8;else if(e==="")return-1;let n=0;for(let r=0;r<e.length;r++){let i=Wc(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function Zf(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function rg(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function ig(e){return e.length===2&&rg(e.codePointAt(0),e.codePointAt(1))}function Wf(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function at(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function og(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function nu(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(r){let i=[0,0,0,0,0,0,0,0],a=null,o=0,s=0,c=Array.from(r,u=>u.codePointAt(0));if(c[s]===58){if(c[s+1]!==58)return null;s+=2,o++,a=o}for(;s<c.length;){if(o===8)return null;if(c[s]===58){if(a!==null)return null;s++,o++,a=o;continue}let u=0,d=0,m=0;for(;m<4&&(u=Wc(c[s]))>=0;)d=(d<<4)+u,s++,m++;if(c[s]===46){if(m===0||o>6)return null;s-=m;let w=0;for(;c[s]!==void 0;){let I=0;if(w>0)if(c[s]===46&&w<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(I=10*I+Wc(c[s]),I>255)return null;s++}i[o]=256*i[o]+I,w++,w%2==0&&o++}if(w!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=d,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let d=i[a+u-1];i[a+u-1]=i[o],i[o]=d,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return Wf(r)?null:wn(r,io)})(e);{let n=(function(i){let a=!1,o=!1;for(let c=0;c<i.length;c++){let u=i.charCodeAt(c);if(u<=32||u===37||u===127)return null;if(u>=128){a=!0;break}u>=65&&u<=90&&(o=!0)}if(!a)return i!==""?o?i.toLowerCase():i:null;if((function(u){for(let d of u){let m=d.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(d)&&!ng(Tx,m)||no(qx,m))return!0}return!1})(i))return null;let s=(i=(function(u){let d="";for(let m of u){let w=m.codePointAt(0);if(w!==8204&&w!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(m))continue;let I=Lx(m,w);if(I){d+=I;continue}let p=Nx.indexOf(w);d+=p<0?m:Dx[p]}return d})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let c=0;c<s.length;c++){let u=s[c];if(u==="")continue;let d=/[^\0-\x7f]/.test(u);if(Mx(u)||d&&(/^\p{Mark}/u.test(u)||!Bx(u)||!Gx(u)||u.startsWith("xn--")))return null;d&&(s[c]=`xn--${Yx(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Yc(e));return n===null||Wf(n)?null:(function(i){let a=i.length,o=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=o)return!1;if(Hc(i.slice(o,a))>=0)return!0;for(;o<a;o++){let s=i.charCodeAt(o);if(s<48||s>57)return!1}return!0})(n)?(function(i){let a=i.split("."),o=a.length;if(a[o-1]||o--,o>4)return null;let s=0;for(let u=0;u<o-1;u++){let d=Hc(a[u]);if(d<0||d>255)return null;s+=d*(1<<8*(3-u))}let c=Hc(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function ru(e){return typeof e=="number"?(function(n){let i="";return i+=`${(n>>>24&255).toString(10)}.`,i+=`${(n>>>16&255).toString(10)}.`,i+=`${(n>>>8&255).toString(10)}.`,i+=(n&255).toString(10),i})(e):Array.isArray(e)?`[${(function(n){let r=(function(s){let c=-1,u=-1,d=1,m=0;for(let w=0;w<s.length;++w)s[w]!==0?(m>d&&(c=u,d=m),u=-1,m=0):(u===-1&&(u=w),++m);return m>d?u:c})(n),i="",a=!1;for(let o=0;o<=7;++o)if(!(a&&n[o]===0)){if(a&&(a=!1),r===o){i+=o===0?"::":":",a=!0;continue}i+=n[o].toString(16),o!==7&&(i+=":")}return i})(e)}]`:e}function ag(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(n){return/^[A-Za-z]:$/u.test(n)})(e.path[0]))&&e.path.pop()}function sg(e){return e.username!==""||e.password!==""}function Qc(e){return e.host===null||e.host===""||e.scheme==="file"}var C=0,F="",ye="",Fe=null,M,Ra=!1,ka=!1,_r=!1,st;function nn(e,t,n,r){t||(e=(function(o){let s=0,c=o.length;for(;s<c&&!(o.charCodeAt(s)>32);++s);for(;c>s&&!(o.charCodeAt(c-1)>32);--c);return o.substring(s,c)})(e)),e=(function(o){let s=0;for(;s<o.length;s++){let u=o.charCodeAt(s);if(u===9||u===10||u===13)break}if(s===o.length)return o;let c=o.slice(0,s);for(;s<o.length;s++){let u=o.charCodeAt(s);u!==9&&u!==10&&u!==13&&(c+=o[s])}return c})(e),C=0,F=e,ye="",Fe=n||null,M=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},Ra=!1,ka=!1,_r=!1,st=r||0;let i=Xx;switch(r){case 3:case 4:i=Ta;break;case 5:i=cu;break;case 6:i=Er;break;case 7:i=Yn;break;case 8:i=On}return i(z(e,C))!==1?M:null}function J(e,t){return C+=C===e?yn(t):1,C<=F.length}function z(e,t){return t<e.length?e.codePointAt(t):void 0}function yn(e){return e!=null&&e>65535?2:1}function cg(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var Xx=e=>{let t=C;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=C+1;for(e=F.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=F.charCodeAt(n);return ye=F.slice(C,n).toLowerCase(),C=n,e0(n<F.length?e:void 0)}else return st?1:(--C,J(t,e)?ug(z(F,C)):0)},e0=e=>{let t=C;if(e===58){if(st){if(at(M.scheme)!==at(ye))return 0;if((sg(M)||M.port!==null)&&ye==="file")return 0;if(M.scheme==="file"&&M.host==="")return 0}return M.scheme=ye,st?(M.port===og(M.scheme)&&(M.port=null),0):(ye="",M.scheme==="file"?J(t,e)?uu(z(F,C)):0:at(M.scheme)&&Fe!==null&&Fe.scheme===M.scheme?J(t,e)?t0(z(F,C)):0:at(M.scheme)?J(t,e)?r0(z(F,C)):0:z(F,C+1)===47?(C++,J(t,e)?n0(z(F,C)):0):(M.path=[""],M.opaquePath=!0,J(t,e)?dg(z(F,C)):0))}else return st?1:(ye="",C=-1,J(t,e)?ug(z(F,C)):0)},ug=e=>{let t=C;return Fe===null||Fe.opaquePath&&e!==35?1:Fe.opaquePath&&e===35?(M.scheme=Fe.scheme,M.path=Fe.path.slice(),M.opaquePath=Fe.opaquePath,M.query=Fe.query,M.fragment="",J(t,e)?On(z(F,C)):0):Fe.scheme==="file"?(C--,J(t,e)?uu(z(F,C)):0):(C--,J(t,e)?su(z(F,C)):0)},t0=e=>{let t=C;return e===47&&z(F,C+1)===47?(++C,J(t,e)?Da(z(F,C)):0):(C--,J(t,e)?su(z(F,C)):0)},n0=e=>{let t=C;return e===47?J(t,e)?ui(z(F,C)):0:(C--,J(t,e)?bn(z(F,C)):0)},su=e=>{let t=C;return M.scheme=Fe.scheme,e===47||at(M.scheme)&&e===92?J(t,e)?Yf(z(F,C)):0:(M.username=Fe.username,M.password=Fe.password,M.host=Fe.host,M.port=Fe.port,M.path=Fe.path.slice(),M.query=Fe.query,e===63?(M.query="",J(t,e)?Yn(z(F,C)):0):e===35?(M.fragment="",J(t,e)?On(z(F,C)):0):e!=null?(M.query=null,M.path.pop(),C--,J(t,e)?bn(z(F,C)):0):J(t,e)?su(z(F,C)):0)},Yf=e=>{let t=C;return at(M.scheme)&&(e===47||e===92)?J(t,e)?Da(z(F,C)):0:e===47?J(t,e)?ui(z(F,C)):0:(M.username=Fe.username,M.password=Fe.password,M.host=Fe.host,M.port=Fe.port,C--,J(t,e)?bn(z(F,C)):0)},r0=e=>{let t=C;return e===47&&z(F,C+1)===47?C++:C--,J(t,e)?Da(z(F,C)):0},Da=e=>{let t=C;return e!==47&&e!==92?(C--,J(t,e)?ui(z(F,C)):0):J(t,e)?Da(z(F,C)):0},ui=e=>{let t=C;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!at(M.scheme))){let n=C+yn(e);for(;n<F.length;){let r=z(F,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&at(M.scheme))break;n+=yn(r)}return ye+=F.slice(C,n),C=n-1,J(t,e)?ui(z(F,C)):0}if(e===64){Ra&&(ye=`%40${ye}`),Ra=!0;for(let n=0;n<ye.length;n++){let r=ye.codePointAt(n);if(r===58&&!ka){ka=!0;continue}let i=tg(r,ja);ka?M.password+=i:M.username+=i,r!=null&&r>65535&&n++}return ye="",J(t,e)?ui(z(F,C)):0}else return e==null||e===35||e===47||e===63||e===92&&at(M.scheme)?Ra&&ye===""?1:(C-=ye.length+1,ye="",J(t,e)?Ta(z(F,C)):0):(ye+=cg(e),J(t,e)?ui(z(F,C)):0)},Ta=e=>{let t=C;if(st&&M.scheme==="file")return C--,J(t,e)?lu(z(F,C)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!at(M.scheme))){let n=C+yn(e);for(e===91?_r=!0:e===93&&(_r=!1);n<F.length;){let r=z(F,n);if(r==null||!_r&&r===58||r===35||r===47||r===63||r===92&&at(M.scheme))break;r===91?_r=!0:r===93&&(_r=!1),n+=yn(r)}return ye+=F.slice(C,n),C=n-1,J(t,e)?Ta(z(F,C)):0}else if(e===58&&!_r){if(ye===""||st===4)return 1;let n=nu(ye,!at(M.scheme));return n===null?1:(M.host=ru(n),ye="",J(t,e)?cu(z(F,C)):0)}else if(e==null||e===35||e===47||e===63||e===92&&at(M.scheme)){if(C--,at(M.scheme)&&ye==="")return 1;if(st&&ye===""&&(sg(M)||M.port!==null))return 1;let n=nu(ye,!at(M.scheme));return n===null?1:(M.host=ru(n),ye="",st?0:J(t,e)?Er(z(F,C)):0)}else return ye+=cg(e),J(t,e)?Ta(z(F,C)):0},cu=e=>{let t=C;if(e!=null&&e>=48&&e<=57){let n=C+1;for(;n<F.length;){let r=F.charCodeAt(n);if(r<48||r>57)break;n++}return ye+=F.slice(C,n),C=n-1,J(t,e)?cu(z(F,C)):0}else if(st||e==null||e===35||e===47||e===63||e===92&&at(M.scheme)){if(ye!==""){let n=parseInt(ye,10);if(n>65535)return 1;if(M.port=n===og(M.scheme)?null:n,ye="",st)return 0}return st?1:(C--,J(t,e)?Er(z(F,C)):0)}else return 1};function lg(e,t){let n=e.length-t;if(n<2)return!1;if(rg(z(e,t),z(e,t+1))){if(n===2)return!0;{let r=z(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var uu=e=>{let t=C;return M.scheme="file",M.host="",e===47||e===92?J(t,e)?i0(z(F,C)):0:Fe?.scheme==="file"?(M.host=Fe.host,M.path=Fe.path.slice(),M.opaquePath=Fe.opaquePath,M.query=Fe.query,e===63?(M.query="",J(t,e)?Yn(z(F,C)):0):e===35?(M.fragment="",J(t,e)?On(z(F,C)):0):e!=null?(M.query=null,lg(F,C)?M.path=[]:ag(M),C--,J(t,e)?bn(z(F,C)):0):J(t,e)?uu(z(F,C)):0):(C--,J(t,e)?bn(z(F,C)):0)},i0=e=>{let t=C;return e===47||e===92?J(t,e)?lu(z(F,C)):0:(Fe!==null&&Fe.scheme==="file"&&(!lg(F,C)&&(function(r){if(r.length===2){let i=r.codePointAt(0),a=r.codePointAt(1);return(i>=65&&i<=90||i>=97&&i<=122)&&a===58}else return!1})(Fe.path[0])&&M.path.push(Fe.path[0]),M.host=Fe.host),C--,J(t,e)?bn(z(F,C)):0)},lu=e=>{let t=C;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=C+yn(e);for(;n<F.length;){let r=z(F,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=yn(r)}return ye+=F.slice(C,n),C=n-1,J(t,e)?lu(z(F,C)):0}else if(e==null||e===47||e===92||e===63||e===35){if(C--,!st&&ig(ye))return J(t,e)?bn(z(F,C)):0;if(ye==="")return M.host="",st?0:J(t,e)?Er(z(F,C)):0;{let n=nu(ye,!at(M.scheme));return n===null?1:(n==="localhost"&&(n=""),M.host=ru(n),ye="",st?0:J(t,e)?Er(z(F,C)):0)}}return 1},Er=e=>{let t=C;return at(M.scheme)?(e!==92&&e!==47&&C--,J(t,e)?bn(z(F,C)):0):!st&&e===63?(M.query="",J(t,e)?Yn(z(F,C)):0):!st&&e===35?(M.fragment="",J(t,e)?On(z(F,C)):0):e!=null?(e!==47&&C--,J(t,e)?bn(z(F,C)):0):(st&&M.host===null&&M.path.push(""),J(t,e)?Er(z(F,C)):0)},bn=e=>{let t=C;if(e!=null&&e!==47&&(!at(M.scheme)||e!==92)&&(st||e!==63&&e!==35)){let n=C+yn(e);for(;n<F.length;){let r=z(F,n);if(r==null||r===47||at(M.scheme)&&r===92||!st&&(r===63||r===35))break;n+=yn(r)}ye+=wn(F.slice(C,n),Xc),C=n,e=z(F,n)}if(e==null||e===47||at(M.scheme)&&e===92||!st&&(e===63||e===35)){let n=at(M.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(ye)?(ag(M),e!==47&&!n&&M.path.push("")):Zf(ye)&&e!==47&&!n?M.path.push(""):Zf(ye)||(M.scheme==="file"&&M.path.length===0&&ig(ye)&&(ye=`${ye[0]}:`),M.path.push(ye)),ye="",e===63?(M.query="",J(t,e)?Yn(z(F,C)):0):e===35?(M.fragment="",J(t,e)?On(z(F,C)):0):J(t,e)?bn(z(F,C)):0}else return ye+=tg(e,Xc),J(t,e)?bn(z(F,C)):0},dg=e=>{let t=C;if(e===63)return M.query="",J(t,e)?Yn(z(F,C)):0;if(e===35)return M.fragment="",J(t,e)?On(z(F,C)):0;if(e!=null){let n=C+yn(e);for(;n<F.length;){let i=z(F,n);if(i===63||i===35)break;n+=yn(i)}let r=F.slice(C,n);if(n<F.length&&r.charCodeAt(r.length-1)===32?M.path[0]+=wn(r.slice(0,-1),io)+"%20":M.path[0]+=wn(r,io),C=n,(e=z(F,n))===63)return M.query="",J(t,e)?Yn(z(F,C)):0;if(e===35)return M.fragment="",J(t,e)?On(z(F,C)):0}return J(t,e)?dg(z(F,C)):0},Yn=e=>{let t=C,n=C;if(e!=null){if(st)n=F.length;else{let i=F.indexOf("#",C);n=i===-1?F.length:i}let r=at(M.scheme)?jx:ou;M.query+=wn(F.slice(C,n),r)}return C=n,z(F,n)===35&&!st?(M.fragment="",J(t,e)?On(z(F,C)):0):J(t,e)?Yn(z(F,C)):0},On=e=>{let t=C;return e!=null&&(M.fragment+=wn(F.slice(C),kx),C=F.length),J(t,e)?On(z(F,C)):0};function iu(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function pg(e){switch(e.scheme){case"blob":{let t=nn(iu(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":pg(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(n){let r=`${n.scheme}://`;return r+=n.host,n.port!==null&&(r+=`:${n.port}`),r})(e);default:return"null"}}var Be=Symbol("URLImpl"),cn=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=ze(t),n!=null&&(n=ze(n));let r=null;if(n!=null&&(r=nn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=nn(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[Be]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=ze(t),n!==void 0&&(n=ze(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=ze(t),n!==void 0&&(n=ze(n));let r=null;return n!=null&&(r=nn(n,null,null,0),r==null)?!1:nn(t,null,r,0)!=null}get href(){return(function(n){let r=`${n.scheme}:`;return n.host!==null&&(r+="//",(n.username!==""||n.password!=="")&&(r+=n.username,n.password!==""&&(r+=`:${n.password}`),r+="@"),r+=n.host,n.port!==null&&(r+=`:${n.port}`)),n.host===null&&!n.opaquePath&&n.path.length>1&&n.path[0]===""&&(r+="/."),r+=iu(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[Be].url)}set href(t){let n=nn(t=ze(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[Be].url=n,this[Be].query&&Jc(this[Be].query,n.query)}get origin(){return pg(this[Be].url)}get protocol(){return`${this[Be].url.scheme}:`}set protocol(t){nn(`${t=ze(t)}:`,this[Be].url,null,2)}get username(){return this[Be].url.username}set username(t){t=ze(t),Qc(this[Be].url)||(function(r,i){r.username=wn(i,ja)})(this[Be].url,t)}get password(){return this[Be].url.password}set password(t){t=ze(t),Qc(this[Be].url)||(function(r,i){r.password=wn(i,ja)})(this[Be].url,t)}get host(){let{url:t}=this[Be];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=ze(t),this[Be].url.opaquePath||nn(t,this[Be].url,null,3)}get hostname(){let{url:t}=this[Be];return t.host!=null?t.host:""}set hostname(t){t=ze(t),this[Be].url.opaquePath||nn(t,this[Be].url,null,4)}get port(){let{url:t}=this[Be];return t.port!=null?`${t.port}`:""}set port(t){t=ze(t);let{url:n}=this[Be];Qc(n)||(t?nn(t,n,null,5):n.port=null)}get pathname(){return iu(this[Be].url)}set pathname(t){t=ze(t);let{url:n}=this[Be];n.opaquePath||(n.path=[],nn(t,n,null,6))}get search(){let{url:t}=this[Be];return t.query?`?${t.query}`:""}set search(t){t=ze(t);let{url:n,query:r}=this[Be];if(!t)n.query=null,r&&Jc(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",nn(i,n,null,7),r&&Jc(r,n.query)}}get searchParams(){let t=this[Be],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new Na;return o[Xe].url=i,o[Xe].serialized=a==null,a&&(o[Xe].list=au(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[Be];return t.fragment?`#${t.fragment}`:""}set hash(t){t=ze(t);let{url:n}=this[Be];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",nn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(cn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var Xe=Symbol("URLSearchParamsImpl"),o0=Symbol.dispose||Symbol.for("dispose");function Jc(e,t){t?e[Xe].list=au(t):e[Xe].list.length=0,e[Xe].serialized=t==null}function _a(e){if(e.url){let t=eu(e.list);(function(r,i){r[Be].url.query=i})(e.url,t||null),e.serialized=!0}}var a0=typeof Iterator<"u"?Iterator:Object,ro=class extends a0{constructor(t,n){super(),this[Xe]={ptr:t,map:n,index:0}}next(){let t=this[Xe];return t.index<t.ptr.list.length?{value:t.map(t.ptr.list[t.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[o0](){}},Na=class{constructor(t){let n=this[Xe]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(Gf(t[i]));else if((r=Xf(t))!=null){let i;for(;!(i=Zc(r.next())).done;)n.list.push(Gf(i.value))}else if((typeof t=="object"||typeof t=="function")&&t!=null){let i=Object.keys(t);for(let a=0;a<i.length;a++){let o=i[a],s=Ex(o),c=ze(t[o]),u=n.list.find(d=>d[0]===s);u?u[1]=c:n.list.push([s,c])}}else if(t!==void 0){let i=ze(t);i=i[0]==="?"?i.substring(1):i,n.list=au(i)}}get size(){return this[Xe].list.length}append(t,n){t=ze(t),n=ze(n),this[Xe].list.push([t,n]);let r=this[Xe];r.url&&r.serialized?(function(a,o){let s=a[Be].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,eu([[t,n]])):_a(r)}delete(t,n){t=ze(t),n=n!=null?ze(n):void 0;let{list:r}=this[Xe],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;_a(this[Xe])}get(t){t=ze(t);let{list:n}=this[Xe];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=ze(t);let n=[],{list:r}=this[Xe];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=ze(t),n=n!=null?ze(n):void 0;let{list:r}=this[Xe];for(let i=0;i<r.length;i++)if(r[i][0]===t&&(n==null||r[i][1]===n))return!0;return!1}set(t,n){t=ze(t),n=ze(n);let{list:r}=this[Xe],i=!1,a=!1,o=0;for(;o<r.length;)r[o][0]===t?i?(r.splice(o,1),a=!0):(i=!0,r[o][1]!==n&&(r[o][1]=n,a=!0),o++):o++;i||(r.push([t,n]),a=!0),a&&_a(this[Xe])}sort(){this[Xe].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),_a(this[Xe])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[Xe];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new ro(this[Xe],t=>t)}keys(){return new ro(this[Xe],t=>t[0])}values(){return new ro(this[Xe],t=>t[1])}toString(){return eu(this[Xe].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Na.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var Xn="https://api.tinker.cash";function mg(e){let t,n,r=0,i,a=new Map,o=()=>{for(let m of[...a.keys()])try{m()}catch{}};function s(m,w){let I=++r;i=void 0,t=void 0,n=void 0;for(let p of[...a.values()])try{p?.()}catch{}I===r&&(t=m,n=w,o())}let c=()=>s();function u(m,w=!1){let I=kr.safeParse(m);if(!I.success||w&&Date.parse(I.data.expiresAt)<=Date.now()||Date.parse(I.data.refreshExpiresAt)<=Date.now()||Date.parse(I.data.refreshExpiresAt)<Date.parse(I.data.expiresAt))throw new y("INVALID_RESPONSE","Invalid customer session credentials");return I.data}async function d(){if(i)return i;let m=t,w=r;if(!m||Date.parse(m.refreshExpiresAt)<=Date.now())throw m&&c(),new y("UNAUTHENTICATED","Customer authentication is required",401);let I=(async()=>{try{let p=await e(m.refreshToken);if(w!==r)throw new y("IDENTITY_CHANGED","Customer identity changed during refresh");let g=u(p,!0);if(g.customerId!==m.customerId||g.sessionId!==m.sessionId)throw new y("SCOPE_MISMATCH","Refresh changed the customer session");return t=g,n=g.accessToken,{...g}}catch(p){throw w!==r?new y("IDENTITY_CHANGED","Customer identity changed during refresh"):(p instanceof y&&p.status===401&&c(),p)}})();i=I;try{return await I}finally{i===I&&(i=void 0)}}return{identify(m){let w=typeof m=="string"?void 0:u(m),I=typeof m=="string"?m:w.accessToken;if(!I.trim()||/\s/.test(I)||I.length>4096)throw new y("INVALID_TOKEN","A server-issued token is required");s(w,I)},reset:c,subscribeIdentity(m,w){return a.set(m,w),()=>{a.delete(m)}},access(){if(t&&Date.parse(t.expiresAt)<=Date.now()+3e4)return d().then(()=>{if(!n)throw new y("NOT_IDENTIFIED","Customer authentication is required");return n});if(!n)throw new y("NOT_IDENTIFIED","Identify a customer session before making a request");return n},peek:()=>n,snapshot:()=>t&&{...t},refresh:d}}var fg=Symbol("IndianaNoContent");function er(e,t,n=cn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?Ve.parse(i):void 0;if(a&&r&&(a.projectId!==r.projectId||a.environment!==r.environment))throw new y("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=new n(e.baseUrl??Xn);if(o.username||o.password||o.search||o.hash)throw new y("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new y("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new y("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=null,d=0,m=null,w=new Set,I=e.session??mg(async h=>{let P=await S("customer-sessions/refresh",{},"POST",{},h);if(!P||typeof P!="object")throw new y("INVALID_RESPONSE","Invalid refresh response");let{requestId:v,scope:E,...j}=P;return j});function p(){d+=1,u=null,m=null;for(let h of w)h.abort();w.clear()}let g=I.subscribeIdentity(p);function f(){I.reset()}async function S(h,P={},v="POST",E={},j){let q=E.installationDetach===!0;if(q&&(h!=="push/installations/detach"||v!=="POST"))throw new y("INVALID_REQUEST","Installation authority only detaches this installation");if(!j&&!u&&!q)throw new y("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let de=d,be=new AbortController;q||w.add(be);let Oe=()=>!q&&de!==d?new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new y("TIMEOUT","Indiana request timed out"),Se,Te=new Promise((Je,_t)=>{Se=()=>_t(Oe()),be.signal.addEventListener("abort",Se,{once:!0})}),Pe=setTimeout(()=>be.abort(),c),Vt=async()=>{let Je=await s(`${o.href.replace(/\/$/,"")}/api/v1/${h}`,{method:v,headers:{"Content-Type":"application/json",...q?{}:{Authorization:`Bearer ${j??u}`},[Ha]:Qa.current,[ku]:$f.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(P):void 0,signal:be.signal,credentials:"omit",cache:"no-store",redirect:"error",...E.keepalive?{keepalive:!0}:{}});if(be.signal.aborted)throw Oe();let _t;try{_t=Je.status===204?fg:await Je.json()}catch{throw be.signal.aborted?Oe():new y(Je.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Je.status,Je.headers.get("X-Request-Id")??void 0)}if(be.signal.aborted)throw Oe();if(!q&&de!==d)throw new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Je.ok){let it=Ka.safeParse(_t),Ut=it.success&&(!cr.safeParse(it.data.error.code).success||Eu(it.data.error.code,Je.status)),rr=Ut?it.data.error.code:"HTTP_ERROR",ir=po(rr,Je.status,{retryAfter:Je.headers.get("Retry-After"),recovery:Ut?it.data.error.recovery:void 0,reason:Ut?it.data.error.reason:void 0});throw new y(rr,Ut?it.data.error.message:"Indiana request failed",Je.status,Je.headers.get("X-Request-Id")??(it.success?it.data.requestId:void 0),{...ir,...it.success&&it.data.error.retryable===!1?{retryable:!1}:{},...ir.retryAfterSeconds===void 0&&it.success&&it.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:it.data.error.retryAfterSeconds}:{}})}if(Je.headers.get(Ha)!==Qa.current)throw new y("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&_t!==fg){let it=_t&&typeof _t=="object"&&"scope"in _t?_t:_t&&typeof _t=="object"&&"configuration"in _t?_t.configuration:null;if(!it||typeof it!="object"||!("scope"in it))throw new y("INVALID_RESPONSE","Response is missing its App/environment scope");let Ut=Ve.safeParse(it.scope);if(!Ut.success||Ut.data.projectId!==a.projectId||Ut.data.environment!==a.environment)throw new y("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let Rr=Je.headers.get("X-Indiana-Telemetry-Subject");if(Rr){if(!/^[a-f0-9]{64}$/.test(Rr))throw new y("INVALID_RESPONSE","Invalid telemetry identity");m!==Rr&&(m=Rr,t?.(m))}return _t};try{return await Promise.race([Vt(),Te])}catch(Je){throw!q&&de!==d?new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Je instanceof y?Je:new y(be.signal.aborted?"TIMEOUT":"NETWORK_ERROR",be.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(Pe),be.signal.removeEventListener("abort",Se),w.delete(be)}}return{session:I,requestWithCredential(h,P,v){return S(h,P,"POST",{},v)},subjectKey:()=>m,identify(h){if(a&&typeof h=="object"&&"scope"in h){let P=Ve.safeParse(h.scope);if(!P.success||P.data.projectId!==a.projectId||P.data.environment!==a.environment)throw new y("SCOPE_MISMATCH","Customer session belongs to another App/environment")}I.identify(h),u=I.peek()??null},reset:f,dispose(){g(),p()},request(h,P={},v="POST",E={}){if(E.installationDetach)return S(h,P,v,E);let j=d;try{let q=I.access(),de=be=>{if(j!==d)throw new y("IDENTITY_CHANGED","Customer identity changed before dispatch");return S(h,P,v,E,be)};return typeof q=="string"?de(q):q.then(de)}catch(q){return Promise.reject(q)}}}}function gg(e,t,n={}){let r=!!e.session.peek(),i=new Set,a=o=>{for(let s of i)try{s(o)}catch{}};return e.session.subscribeIdentity(()=>{r=!!e.session.peek(),a(r),n.afterChange?.()},()=>{r=!1,t()}),{isIdentified:()=>r,methods:{subscribeIdentity(o){return i.add(o),()=>{i.delete(o)}},identify(o){let s=typeof o=="string"?o:o.accessToken;if(!jt.test(s))throw new y("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(s),e.identify(o)},reset(){try{n.beforeReset?.()}finally{e.reset()}}}}}import{ZodError as s0}from"zod";function hg(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof s0?new y(n,r):i}}async function le(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=hg(t.request,n,"INVALID_REQUEST",a.request),s=await e(t.path,o,t.method,i),c=typeof r=="function"?r:r.parseResponse;return c?c(t.response,s):hg(t.response,s,"INVALID_RESPONSE",a.response)}function Me(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new y("INVALID_REQUEST","Customer requests use the verified session identity")}function Ag(e){return{async checkEntitlement(t){Me(t);let n=O.checkEntitlement;return le(e,n,t)},async readHoldings(t={}){let n=O.readHoldings;return le(e,{...n,request:n.request.omit({customerId:!0})},t)}}}function yg(e){return{async readLedger(t){let n=O.readLedger;return le(e,n,{query:t})},async readCreditStatement(t){Me(t);let n=O.readCreditStatement;return le(e,n,t)},async quoteBalance(t){Me(t);let n=O.quoteBalance;return le(e,n,{command:t})}}}function bg(e){return{async setupPayment(t){Me(t);let n=O.setupPayment;return le(e,n,t)},async readPaymentSetup(t){Me(t);let n=O.readPaymentSetup;return le(e,n,t)},async readBillingInvoice(t){Me(t);let n=O.readBillingInvoice;return le(e,n,t)},async readBillingControls(t={}){Me(t);let n=O.readBillingControls;return le(e,n,t)},async prepareBillingAuthorization(t){Me(t);let n=O.prepareBillingAuthorization;return le(e,n,t)},async confirmBillingAuthorization(t){Me(t);let n=O.confirmBillingAuthorization;return le(e,n,t)},async setBillingCoupons(t){Me(t);let n=O.setBillingCoupons;return le(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Me(t);let n=O.revokeBillingAuthorization;return le(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Me(t);let n=O.listBillingInvoices;return le(e,n,t)},async confirmBillingAdjustment(t){Me(t);let n=O.confirmBillingAdjustment;return le(e,n,t)}}}function Sg(e){return{async previewUpdate(t){Me(t);let n=O.previewUpdate;return le(e,n,t)},async update(t){Me(t);let n=O.update;return le(e,n,t)},async readSubscriptionUpdate(t){Me(t);let n=O.readSubscriptionUpdate;return le(e,n,t)},async restoreNativePurchase(t){Me(t);let n=O.restoreNativePurchase;return le(e,n,t)},async previewAttach(t){Me(t);let n=O.previewAttach;return le(e,n,t)},async attach(t){Me(t);let n=O.attach;return le(e,n,t)},async readSubscriptionOperation(t){Me(t);let n=O.readSubscriptionOperation;return le(e,n,t)}}}function xg(e){return{async redeemReward(t){return Me(t),(await le(e,O.redeemReward,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(t){return Me(t),(await le(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Me(t),(await le(e,O.createReferralCode,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(t,n=crypto.randomUUID()){let r=await le(e,O.redeemCoupon,{code:t,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(t,n=crypto.randomUUID()){let r=await le(e,O.grantOffer,{couponId:t,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await le(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function Ig(e){return{...Ag(e),...yg(e),...bg(e),...Sg(e),...xg(e)}}function vg(e){return{async resolveContent(t){Me(t);let n=O.resolveContent;return le(e,n,t)},async resolvePaywall(t){Me(t);let n=O.resolvePaywall;return le(e,n,t)},async resolveOffering(t){Me(t);let n=O.resolveOffering;return le(e,n,t)}}}var wg=e=>new TextEncoder().encode(JSON.stringify(e)).length,Og=16384;function Cg(e,t){let n=0,r,i=p=>{r={config:structuredClone(p),until:Date.now()+3e4}},a=[],o=null,s;function c(){if(!t())throw new y("NOT_IDENTIFIED","Call identify before using Features or events")}function u(){s||!a.length||(s=setTimeout(()=>{s=void 0,m().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function d(p,g={},f={}){if(c(),r&&Date.now()<r.until&&!zp(r.config,p))return;I();let S=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:p,properties:g,...f}]}).events[0];if(wg({events:[S]})>Og)throw new y("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new y("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(S)),u()}async function m(p=!1){if(c(),o)return o;let g=n,f=(async()=>{let S={inserted:0,duplicates:0,rejected:0,skipped:0},h=a.length;for(;h&&g===n;){let P=[];for(let j of a.slice(0,Math.min(h,100))){if(P.length&&wg({events:[...P,j]})>Og)break;P.push(j)}let v=O.trackEvents,E=await le(e,v,{events:P},void 0,{keepalive:p});if(g!==n)throw new y("IDENTITY_CHANGED","Event identity changed during delivery");if(E.inserted+E.duplicates+E.rejected+E.skipped!==P.length)throw new y("INVALID_RESPONSE","Incomplete event acknowledgement");i(E.analyticsConfig),a.splice(0,P.length),h-=P.length,S.inserted+=E.inserted,S.duplicates+=E.duplicates,S.rejected+=E.rejected,S.skipped+=E.skipped}return S})();o=f;try{return await f}finally{o===f&&(o=null)}}let w;function I(){if(w||typeof document>"u")return;let p=()=>{document.visibilityState==="hidden"&&t()&&a.length&&m(!0).catch(()=>{})};document.addEventListener("visibilitychange",p),w=()=>document.removeEventListener("visibilitychange",p)}return{rememberConfiguration:i,track(p,g,f={}){return I(),d(p,g,f)},flush:m,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){w?.(),w=void 0}}}function du(e){let t=null,n=null,r=0,i=0,a=!1,o=new Set,s=null,c=null,u=new Set,d=()=>{for(let h of u)try{h()}catch{}},m={attributes:mt.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(h,P)=>{!o.has(h)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(h,structuredClone(P),structuredClone(m.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(h,P)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(h),structuredClone(P),structuredClone(m.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?h=>e.saveStickyBucketAssignmentDoc(structuredClone(h)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function I(h,P=new Set){return o.has(h)?!s||!s.features[h]||["unknownFeature","cyclicPrerequisite"].includes(s.features[h].source):P.has(h)?!1:(P.add(h),(t?.features[h]?.rules??[]).some(v=>[...v.parentConditions??[],...(v.tracks??[]).flatMap(E=>E.experiment.parentConditions??[])].some(E=>I(E.id,P))))}let p=h=>{if(e.assertUsable?.(t?.generation),!t)throw new Error("Initialize the Feature client before evaluation");if(t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return s?.expiresAt&&Date.parse(s.expiresAt)<=Date.now()&&(s=null,m.features=t.features),o.has(h)?!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now()?w():structuredClone(s.features[h]??w()):e.evaluateRemote&&(m.attributes?.merchandise||m.attributes?.merchandiseId)&&!a||I(h)?w():structuredClone(_n(h,m))};async function g(){if(!t||!o.size&&!m.attributes?.merchandise&&!m.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(o.size)throw new Error("Remote Feature evaluation requires a server loader");return}let h=i;if(c?.revision===h)return c.loading;let P=r,v=t,E=[...o],j=(async()=>{let q=ra.parse(await e.evaluateRemote({attributes:structuredClone(m.attributes),features:E}));if(!(P!==r||h!==i||v!==t)){if(e.assertUsable?.(v.generation),q.generation!==v.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(E.some(de=>!Object.hasOwn(q.features,de))||Object.keys(q.features).some(de=>!o.has(de)))throw new Error("Invalid remote Feature results");if(m.attributes?.merchandise||m.attributes?.merchandiseId){if(!q.merchandiseContext)throw new Error("Server did not resolve merchandise context");m.attributes=mt.parse({...m.attributes,...q.merchandiseContext}),a=!0}s=structuredClone(q),m.features={...v.features,...Object.fromEntries(Object.entries(s.features).map(([de,be])=>[de,{defaultValue:be.value}]))},d()}})();c={revision:h,loading:j};try{await j}finally{c?.loading===j&&(c=null)}}function f(){g().catch(h=>{try{e.onError?.(h)}catch{}})}async function S(){if(n)return n;let h=r,P=(async()=>{let v=await e.load(),E="remoteFeatures"in v?zi.parse(v):null,j=E??on.parse(v);if(j.scope.projectId!==e.scope.projectId||j.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(h!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===j.generation){let{evaluatedAt:de,expiresAt:be,...Oe}=t,{evaluatedAt:Se,expiresAt:Te,...Pe}=j;if(gt(Oe)!==gt(Pe))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=j.evaluatedAt,t.expiresAt=j.expiresAt,d(),(!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now())&&f(),structuredClone(t)}let q=new Set(E?.remoteFeatures??[]);if([...q].some(de=>Object.hasOwn(j.features,de)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in j&&!t.analyticsConfig.experimentViewsEnabled&&E?.analyticsConfig.experimentViewsEnabled&&m.trackedExperiments?.clear(),t=structuredClone(j),o=q,s=null,c=null,i++,m.features=t.features,m.savedGroups=qr(t.savedGroups),m.trackedFeatureUsage={},d(),f(),structuredClone(t)})();n=P;try{return await P}finally{n===P&&(n=null)}}return{init:S,refresh:S,refreshRemote:g,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(h){return u.add(h),()=>{u.delete(h)}},setAttributes(h){let P=mt.parse(h);(m.attributes?.merchandise||m.attributes?.merchandiseId||h.merchandise||h.merchandiseId)&&m.trackedExperiments?.clear(),m.attributes=P,i++,a=!1,s=null,c=null,m.features=t?.features??{},m.trackedFeatureUsage={},d(),f()},evalFeature:p,isOn(h){return p(h).on},isOff(h){return p(h).off},getFeatureValue(h,P){let v=p(h).value;return structuredClone(v===null?P:v)},reset(){r++,i++,n=null,c=null,t=null,s=null,o.clear(),m.features={},m.savedGroups={},m.stickyBucketAssignmentDocs={},m.attributes={},m.trackedFeatureUsage={},m.trackedExperiments?.clear(),d()}}}function Pg(e){let t=e.merchandise;if(typeof e.merchandiseId=="string")return{internalId:e.merchandiseId};if(!(!t||typeof t!="object"||Array.isArray(t))){if(typeof t.internalId=="string")return{internalId:t.internalId};if(typeof t.externalId=="string")return{id:t.externalId};if(typeof t.id=="string")return{id:t.id}}}function c0(e){let t=Pg(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function _g(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new y("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new y("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let d=a,m=!1,w=async()=>{if(m||d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");let Oe=O.getFeatures,Se=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await le(e,Oe,{});if(d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");if(r&&(Se.scope.projectId!==r.projectId||Se.scope.environment!==r.environment))throw new y("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(Se.payload.analyticsConfig),Se},I=await w(),p=!0,g,f=Oe=>{try{u.onError?.(Oe)}catch{}},S=(Oe,Se,Te)=>{try{let Pe=Pg(Te);n.track(Oe,Se,Pe?{merchandise:Pe}:{})}catch(Pe){f(Pe)}},h=du({assertUsable:i?.assertFeatures,scope:I.scope,attributes:u.attributes,onError:u.onError,load:async()=>p?(p=!1,I.payload):(await w()).payload,evaluateRemote:async Oe=>{if(d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");let Se=O.evaluateFeatures,Te=await le(e,Se,{...Oe,attributes:c0(Oe.attributes)});if(Te.scope.projectId!==I.scope.projectId||Te.scope.environment!==I.scope.environment)throw new y("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:Te.generation,evaluatedAt:Te.evaluatedAt,expiresAt:Te.expiresAt,features:Te.features,...Te.merchandiseContext?{merchandiseContext:Te.merchandiseContext}:{}}},onExperimentViewed:(Oe,Se,Te)=>S("Experiment Viewed",{experimentId:Oe.key,variationId:Se.key},Te),onFeatureUsage:(Oe,Se,Te)=>S("Feature Evaluated",{feature:Oe,value:Se.value,source:Se.source,ruleId:Se.ruleId,...Se.experimentResult?{variationId:Se.experimentResult.key}:{}},Te)}),P=h.refresh;function v(){clearTimeout(g),!i&&(m||d!==a||!h.expiresAt||(g=setTimeout(()=>{E().catch(f)},Math.min(2147483647,Math.max(1e3,Date.parse(h.expiresAt)-Date.now()))),typeof g=="object"&&"unref"in g&&g.unref()))}async function E(){try{return await P()}finally{v()}}let j=()=>{m||E().catch(f)},q=h.subscribe(v),de=i?.subscribe(()=>{!m&&i.fresh&&E().catch(f)});function be(){m||(m=!0,clearTimeout(g),typeof window<"u"&&window.removeEventListener("focus",j),q(),de?.(),h.reset(),o.delete(be))}o.add(be);try{await h.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await h.refreshRemote()}catch(Oe){throw be(),Oe}return v(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(h,{refresh:E,destroy:be})}return{features:c,reset(u){a++,u();for(let d of o)d()}}}import{z as u0}from"zod";function Eg(e,t){let n="source"in t?{funnelId:t.source.id,funnelVersionId:t.source.versionId}:"versionId"in t?{funnelId:t.funnelId,funnelVersionId:t.versionId}:t,r=u0.object({funnelId:Oa.shape.id,funnelVersionId:Oa.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new y("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new y("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in o&&o.funnelId!==void 0&&o.funnelId!==i.funnelId||"funnelVersionId"in o&&o.funnelVersionId!==void 0&&o.funnelVersionId!==i.funnelVersionId)throw new y("SCOPE_MISMATCH","The original Funnel source cannot change");return{...o,...i}}return{async claimCoupon(o,s=crypto.randomUUID()){let c=O.grantOffer,u=await le(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return le(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return le(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return le(e,s,a(o))}}}function Rg(e){let t=er(e),n=t.request,r=Bf(e.push,t,e.scope??e.configuration?.scope),i=gg(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),a=Cg(n,i.isIdentified),o=_g(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...zf(n,r),...Ig(n),...vg(n),forFunnel(s){return Eg(n,s)},async features(s={}){return o.features(s)},track(s,c,u={}){return a.track(s,c,u)},flush(){return a.flush()},...i.methods}}function li(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,a)=>li(i,t[a]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([i,a])=>Object.hasOwn(t,i)&&li(a,Reflect.get(t,i)))}async function Fa(e,t){let n=Rf.safeParse(t);if(!n.success)throw new y("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new y("SCOPE_MISMATCH","Funnel scope changed");return r}var di=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function Ma(e){let t=jt.test(e.apiKey);if(typeof window<"u"&&!t)throw new y("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!di.test(e.apiKey))throw new y("INVALID_TOKEN","A customer credential or server API key is required");let n=er({...e,timeoutMs:e.timeoutMs??35e3});return e.session||n.identify(e.apiKey),{async start(r){let i=Tn.safeParse({...r,operation:"start"});if(!i.success||i.data.operation!=="start"||(t?i.data.customer!==void 0:i.data.customer===void 0))throw new y("INVALID_REQUEST","Invalid current Funnel start");let a=i.data,o=eo.safeParse(await Fa(e,await n.request("funnels",a)));if(!o.success||!o.data.runToken)throw new y("INVALID_RESPONSE","Funnel start credentials are missing");let s=o.data;if(s.run.source.id!==a.funnelId||s.run.locale!==(a.locale??"en")||!li(s.run.parameters,a.parameters??{})||(a.customer?!s.customerId||a.customer.type==="id"&&s.customerId!==a.customer.value:s.customerId!==void 0))throw new y("INVALID_RESPONSE","Funnel start contract changed");return{...s,runToken:s.runToken}}}}async function pu(e,t,n){if(Number(e.headers.get("content-length"))>t)throw n.error("limit");let r=e.body?.getReader();if(!r)throw n.error("missing");let i=[],a=0;try{for(;;){n.signal?.throwIfAborted();let c=await r.read();if(c.done)break;if(a+=c.value.length,a>t)throw n.error("limit");i.push(c.value)}}finally{await r.cancel().catch(()=>{})}n.signal?.throwIfAborted();let o=new Uint8Array(a),s=0;for(let c of i)o.set(c,s),s+=c.length;return o}async function kg(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await pu(e,t,n))}function qa(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&Pc(n)===t.sha256}async function Va(e,t){let n=vr.parse(t),{artifact:r,environmentId:i}=n.content,a=new cn(e.baseUrl??Xn).origin,o=new cn(r.url,a);if(o.origin!==a||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${i}/artifacts/${r.sha256}`)throw new y("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,c=setTimeout(()=>s.abort(),Gt.initializationMs);try{let u=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(!u.ok||!u.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(u.headers.get("content-length"))>r.byteLength)throw new y("INVALID_RESPONSE","Public Paywall is unavailable");let d=await pu(u,r.byteLength,{signal:s.signal,error:m=>new y("INVALID_RESPONSE",m==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!qa(d,r))throw new y("INVALID_RESPONSE","Public Paywall digest or size changed");return Fm(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)))}finally{clearTimeout(c)}}var jg=(e,t)=>new y(e,t);async function mu(e,t,{predict:n=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new y("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new y("SCOPE_MISMATCH","Evaluation environment changed");let i=null,a;if(n)try{let o=await e.funnel(t.source.id,t.source.versionId);a=o.manifest.generation,i=l0(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await e.refresh()).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function l0(e,t,n){let r=t.instruction;if(r?.type!=="evaluate_segment"||!n.growth||n.control.evaluationMode!=="local"||n.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:a,...o}=n.growth,s=Lc({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:n.document,payload:on.parse(o)}),c=d0(s,n.document,{...t,...r}),u=c.steps.at(-1),d=c.boundary??(u?.result.port==="value"?{nodeId:u.nodeId,visit:t.visit+c.steps.length-1}:null);return d?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:d.nodeId,visit:d.visit,terminal:!c.boundary}:null}function d0(e,t,n){return Vf(e,t,n,jg)}import{z as Cn}from"zod";var Tg=Tn.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 y("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),Ng=Cn.strictObject({schemaVersion:Cn.literal(1),scope:Ve,runId:Cn.uuid(),funnelId:Cn.uuid(),versionId:Cn.uuid(),command:Tg.optional(),closeCommand:Tg.refine(e=>e.operation==="close").optional(),purchase:Cn.strictObject({receiptId:Cn.uuid(),operationId:Cn.uuid(),generation:Cn.number().int().nonnegative()}).optional(),closed:Cn.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"),Kt=()=>new y("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Ua=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Dg(e){let t=0,n=null,r=c=>JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]),i=Promise.resolve();async function a(){let c=await e.read();if(!Number.isSafeInteger(c.revision)||c.revision<0)throw new y("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:c.revision,entry:c.entry===null?null:Ng.parse(c.entry)}}function o(c){let u=i.then(c);return i=u.catch(()=>{}),u}async function s(c){for(let u=0;u<4;u++){let d=await a();if(d.entry&&n!==null&&r(d.entry)!==n)throw Kt();let m=c(d.entry,d.revision);if(Ua(d.entry,m)){t=d.revision;return}let w=await e.write(d.revision,m);if(w!==null){if(!Number.isSafeInteger(w)||w<=d.revision)throw Kt();t=w;return}}throw Kt()}return{bind(c){let u=JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]);if(n!==null&&n!==u)throw Kt();n=u},async load(){let c=await a();return t=c.revision,n=c.entry?r(c.entry):null,c.entry},retain(c){let u=Ng.parse(c),d=u.command;return!d||n!==null&&r(u)!==n?Promise.reject(Kt()):(n??(n=r(u)),o(()=>s((m,w)=>{if(m&&!Ua(r(m),r(u)))throw Kt();if(!m){if(w!==t&&d.operation!=="close")throw Kt();return u}if(!m.command)return{...m,command:d,...d.operation==="close"?{closed:!0}:{}};if(d.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===d.requestId||m.closeCommand&&!Ua(m.closeCommand,d))throw Kt();return{...m,closeCommand:d,closed:!0}}if(!Ua(m.command,d))throw Kt();return m})))},observePurchase(c,u,d){return o(()=>s((m,w)=>{if(!m&&w!==t||m&&r(m)!==r({...c,schemaVersion:1}))throw Kt();if(m?.purchase&&m.purchase.generation>u.generation)return m;if(m?.purchase&&m.purchase.generation===u.generation&&m.purchase.operationId!==u.operationId)throw Kt();return d?!m?.purchase||m.purchase.operationId!==u.operationId?m:m.command?{...m,purchase:void 0}:null:{schemaVersion:1,...c,...m,purchase:u}}))},settle(c){return o(()=>s(u=>u?u.command&&"requestId"in u.command&&u.command.requestId===c?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand&&"requestId"in u.closeCommand&&u.closeCommand.requestId===c?{...u,closeCommand:void 0}:u:null))}}}function Fg(e){let t,n,r=()=>new y("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??Xn).href,e.runToken])),c=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(c,u=>u.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function a(s){try{let c=await i;return await n.request(c,{mode:"exclusive"},()=>s(c))}catch(c){throw c instanceof y?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function Mg(e){let t=null,n=0,r=!1,i,a=0,o=new Set;return{get view(){return t},get generation(){return n},get disposed(){return r},get customerToken(){return i},get readSequence(){return a},nextRead(){return++a},assertCurrent(s,c="Run identity changed during the request"){if(s!==n||r)throw new y("IDENTITY_CHANGED",c)},assertRun(s){if(t&&(s.id!==t.id||s.source.type!==t.source.type||s.source.id!==t.source.id||s.source.versionId!==t.source.versionId||s.locale!==t.locale||!li(s.parameters,t.parameters)))throw new y("INVALID_RESPONSE","Run version changed");if(e&&s.source.id!==e)throw new y("INVALID_RESPONSE","Run belongs to another Funnel")},publish(s,c,u,d,m){if(!(s.operation==="review"&&t&&t!==u&&c.run.revision<=t.revision)&&!(t&&c.run.revision===t.revision&&d!==void 0&&d<a)&&(s.operation==="review"&&!c.run.stopped&&["running","waiting"].includes(c.run.status)&&t&&c.run.nodeId===t.nodeId&&c.run.visit===t.visit&&c.run.revision===t.revision&&(c.run.screen=t.screen,(t.paywall?.quote?.operationId===c.review?.activeOperationId||!t.paywall?.quote&&c.review?.activeOperationId===null)&&(c.run.paywall=t.paywall)),!(t?.paywall&&c.run.paywall&&t.paywall.receiptId===c.run.paywall.receiptId&&(c.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))){if(!t||c.run.revision>=t.revision)t=c.run;else if(!m)return;if(t)for(let w of o)try{w(structuredClone(t))}catch{}}},identify(s){if(!jt.test(s))throw new y("INVALID_TOKEN","Customer credential required");n++,i=s},subscribe(s){return o.add(s),()=>o.delete(s)},reset(){r=!0,n++,i=void 0,t=null,o.clear()}}}function tr(e){let{customerToken:t,...n}=e;return n}var p0=e=>!(e instanceof y)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function qg({options:e,journal:t,state:n,call:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=!1,u,d=null,m=t?t.load().then(f=>{if(n.disposed)throw new y("IDENTITY_CHANGED","Controller was reset during command restoration");if(d=f,!f)return;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new y("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=f.purchase,o=f.closed===!0,!f.command)return;let S=Tn.parse(f.command);if(S.operation==="start"||S.operation==="get"||S.operation==="review")throw new y("COMMAND_STORAGE_INVALID","Stored mutation required");i=S,f.closeCommand&&(a=f.closeCommand,o=!0),S.operation==="close"&&(o=!0),c=!0}):Promise.resolve();m.catch(()=>{});async function w(f=i){if(t&&await m,!f)throw new y("INVALID_REQUEST","No command is pending");let S=f,h=n.generation;if(t){if(!n.view||!e.scope)throw new y("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await t.retain({schemaVersion:1,scope:e.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:tr(S)})}if(h!==n.generation||i!==S&&a!==S)throw new y("IDENTITY_CHANGED","Run changed before command dispatch");let P={...S,...n.customerToken?{customerToken:n.customerToken}:{}},v=c;c=!0;try{return await r(P,E=>{if(!E.settlement)throw new y("INVALID_RESPONSE","Exact command settlement is missing");if(E.settlement.requestId!==S.requestId)throw new y("INVALID_RESPONSE","Command settlement identity changed");if(h===n.generation&&(i===S||a===S)&&E.run.pendingRequest?.requestId!==S.requestId&&E.settlement.state==="settled"&&(!o||S.operation==="close"||E.settlement?.state==="settled"&&!["running","waiting"].includes(E.run.status))){let j=()=>h!==n.generation||i!==S&&a!==S?!1:(i===S&&(i=null),a===S&&(a=null),c=i!==null,d=null,!0);return t?t.settle(S.requestId).then(j):j()}return!1})}catch(E){throw h===n.generation&&i===S&&!v&&!p0(E)&&(t&&await t.settle(S.requestId),h===n.generation&&i===S&&(i=null,c=!1,d=null)),E}}function I(f){let S=Tn.parse(f);if(S.operation==="start"||S.operation==="get"||S.operation==="review")throw new y("INVALID_REQUEST","Mutation required");if(o&&S.operation!=="close"){if(i?.requestId===S.requestId)return g(S.requestId);throw new y("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(S.operation==="close"&&i?.operation!=="close"){if(o=!0,a&&JSON.stringify(tr(a))!==JSON.stringify(tr(S)))throw new y("COMMAND_PENDING","Retry the original Close");return a??(a=S),s.close?s.close:p(a,"close")}if(i){if(JSON.stringify(tr(i))!==JSON.stringify(tr(S)))throw new y("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=S,c=!1;return p(i,"command")}function p(f,S){let h=w(f);s[S]=h;let P=()=>{s[S]===h&&(s[S]=null)};return h.then(P,P),h}async function g(f){let S=await r({operation:"get",settlementRequestId:f,...n.customerToken?{customerToken:n.customerToken}:{}});if(S.settlement?.requestId!==f)throw new y("INVALID_RESPONSE","Exact command settlement is missing");return S.settlement.state==="settled"&&(t&&await t.settle(f),i?.requestId===f&&(i=null,c=!1),a?.requestId===f&&(a=null)),S}return{ready:m,get pending(){return i},get closing(){return a},get closeRequested(){return o},get inFlight(){return s.command},get closeFlight(){return s.close},get purchase(){return u},assertBinding(f){if(d&&(f.run.id!==d.runId||f.run.source.id!==d.funnelId||f.run.source.versionId!==d.versionId))throw new y("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(f,S,h,P){t?.bind({scope:S.scope,runId:S.run.id,funnelId:S.run.source.id,versionId:S.run.source.versionId}),t&&!e.scope&&(e.scope=S.scope);let v=S.run.paywall,E=v??S.purchase,j=E?.operation,q=S.settlement&&(!v||v.purchaseRequestId===S.settlement.requestId)&&(!u||u.operationId===S.settlement.operationId)?S.settlement:void 0,de=j?.operationId??E?.quote?.operationId??q?.operationId,be=E?.receiptId??q?.receiptId,Oe=v?.selectionGeneration??u?.generation??0;if(t&&de&&be&&f.operation!=="review"&&(!n.view||S.run.revision>=n.view.revision)&&(P===void 0||P>=n.readSequence)&&(!u||Oe>=u.generation)){let Se={receiptId:be,operationId:de,generation:Oe},Te=j?.status==="complete"||E?.canReselect===!0;return t.observePurchase({scope:S.scope,runId:S.run.id,funnelId:S.run.source.id,versionId:S.run.source.versionId},Se,Te).then(()=>{n.assertCurrent(h),Te?u?.operationId===Se.operationId&&(u=void 0):u=Se})}},stop(){o=!0},submit:I,executePending:w,settle:g,reset(){i=null,a=null,s.close=null,c=!1,s.command=null}}}function pi(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new y("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!di.test(e.serverKey)))throw new y("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new y("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=er({...e,session:void 0,...e.serverKey?{fetch:(f,S)=>{let h=new Headers(S?.headers),P=typeof S?.body=="string"?JSON.parse(S.body):null;return P!==null&&typeof P=="object"&&"customerToken"in P&&typeof P.customerToken=="string"&&P.customerToken.length>0||h.set(kf,e.serverKey),(e.fetch??globalThis.fetch)(f,{...S,headers:h})}}:{},...e.session?{fetch:async(f,S)=>{let h=await e.session.access(),P=typeof S?.body=="string"?JSON.parse(S.body):{};if(!P||typeof P!="object"||Array.isArray(P))throw new y("INVALID_REQUEST","Run command must be an object");return(e.fetch??globalThis.fetch)(f,{...S,body:JSON.stringify({...P,customerToken:h})})}}:{},timeoutMs:e.timeoutMs??35e3});t.identify(e.runToken);let n=Mg(e.funnelId),r=e.session?.subscribeIdentity(()=>{n.reset(),t.reset()}),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Fg(e):void 0),o=a&&Dg(a),s=qg({options:e,journal:o,state:n,call:c});async function c(f,S,h){let P=n.generation,v=()=>n.assertCurrent(P);o&&await s.ready,v();let E=n.view,j=eo.parse(await Fa(e,await t.request("funnels",Tn.parse(f))));if(f.operation==="review"&&!j.review)throw new y("INVALID_RESPONSE","Historical projection is missing");if(v(),j.runToken&&j.runToken!==e.runToken)throw new y("INVALID_RESPONSE","Run credential changed");let q=f.operation==="get"?f.settlementRequestId:"requestId"in f&&f.operation!=="start"?f.requestId:void 0;if(q&&j.settlement?.requestId!==q)throw new y("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(j),n.assertRun(j.run);let de=s.observePurchase(f,j,P,h);if(de&&await de,!j.run.stopped&&["running","waiting"].includes(j.run.status)&&f.operation==="get"&&f.settlementRequestId)return j;let be=S?.(j),Oe=typeof be=="boolean"?be:be?await be:!1;return v(),["running","waiting"].includes(j.run.status)||s.stop(),n.publish(f,j,E,h,Oe),j}let u=s.submit,d=null,m=new WeakMap;function w(f){let S=m.get(f);if(S)return S;let h=p(f);return m.set(f,h),h}let I=!1;async function p(f){let S=await f;if(S.run.instruction?.type!=="evaluate_segment")return S;if(d)return d;I=!0;let h=n.generation,P=(async()=>{for(let v=0;v<32&&S.run.instruction?.type==="evaluate_segment";v++){if(s.pending||s.closeRequested)return S;let E=S.run;if(S.run.instruction?.type==="evaluate_segment"){let{advance:q}=await mu(e.configuration,E,{predict:!1});if(h!==n.generation)throw new y("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return S;if(n.view&&(n.view.revision!==E.revision||n.view.visit!==E.visit||n.view.nodeId!==E.nodeId))return c({operation:"get",...n.customerToken?{customerToken:n.customerToken}:{}});let de=!0;mu(e.configuration,E).then(({prediction:be})=>{de&&h===n.generation&&!s.closeRequested&&n.view?.id===E.id&&!n.view.stopped&&n.view.nodeId===E.nodeId&&n.view.visit===E.visit&&n.view.revision===E.revision&&(i=be)}).catch(()=>{});try{S=await u({operation:"commit_segment",requestId:Ef(E.id,E.visit,`segment:${E.revision}`),nodeId:E.nodeId,visit:E.visit,revision:E.revision,...q})}finally{de=!1,i=null}}}return S})();d=P;try{return await P}finally{d===P&&(d=null)}}let g={get configuration(){return I?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let f=s.closing??s.pending;return f?structuredClone(tr(f)):null},get pendingCommands(){return[s.pending,s.closing].filter(f=>f!==null).map(f=>structuredClone(tr(f)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get prediction(){let f=n.view;return i&&f&&!f.stopped&&["running","waiting"].includes(f.status)&&f.id===i.runId&&f.nodeId===i.from.nodeId&&f.visit===i.from.visit&&f.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(f){return Va(e,f)},async pageExperiments(f,S=[]){let h=n.generation;n.assertCurrent(h);let P=n.view?.id;if(!P)throw new y("INVALID_REQUEST","Read the Run before its page experiments");let v=Lf.parse(await t.request("funnels",Uf.parse({operation:"page_experiments",release:f,usedReceiptIds:S,...n.customerToken?{customerToken:n.customerToken}:{}})));if(n.assertCurrent(h),v.runId!==P||v.scope.projectId!==e.scope?.projectId||v.scope.environment!==e.scope?.environment)throw new y("SCOPE_MISMATCH","Page experiment Run changed");return v},review(f){return c({operation:"review",...f?{receiptId:f}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,n.nextRead())},async get(f,S){o&&await s.ready,S??(S=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let h=n.nextRead();return w(c({operation:"get",...f?{data:f}:{},...S?{purchase:S}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,h))},resume(f=n.view?.pendingRequest?.requestId){return f?s.closeRequested?g.settle(f):s.pending?.requestId===f?w(u(s.pending)):w(u({operation:"resume",requestId:f})):Promise.reject(new y("INVALID_REQUEST","No interrupted command is available"))},submit(f){return w(u(f))},retry(){return s.closeFlight?s.closeFlight:s.closing?s.executePending(s.closing):s.closeRequested&&s.pending?g.settle(s.pending.requestId):s.inFlight?w(s.inFlight):s.pending?w(u(s.pending)):Promise.reject(new y("INVALID_REQUEST","No command is pending"))},identify(f){n.identify(f),i=null,t.identify(e.runToken)},subscribe:n.subscribe,reset(){r?.(),n.reset(),s.reset(),i=null,t.reset()}};return g}function Vg(e){if(!jt.test(e.customerToken))throw new y("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new y("INVALID_REQUEST","An explicit App and environment scope is required");let t=Ma({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=pi({...e,runToken:r.runToken});i.identify(e.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await i.get():r;return{...r,...a,controller:i}}}}function Ug(e,t){let n=r=>"document"in r?r.offering.id:r.content.offeringVersionId;return e.id===t.id&&n(e)===n(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function Lg(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new y("INVALID_RESPONSE",n)}function Bg(e,t,n){let r=Object.fromEntries((e.lines[0]?.prepaid??[]).map(i=>[i.internal_feature_id,i.quantity]));if(t.featureQuantities&&(Object.keys(r).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([i,a])=>r[i]!==a)))throw new y("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider)throw new y("INVALID_RESPONSE",n)}function zg(e,t,n=!1){return!e||e.operationId!==t?.operationId?t:e.status==="complete"&&t.status!=="complete"||e.status!=="pending"&&(t.status==="pending"||n&&t.status!=="complete")?e:t}async function $g(e,t){if(!jt.test(t.customerToken))throw new y("INVALID_TOKEN","A verified Customer credential is required");let n=er(e);if(!e.session)n.identify(t.customerToken);else if(e.session.peek()!==t.customerToken)throw new y("SCOPE_MISMATCH","Paywall credential does not match the shared session");let r=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),i=null,a=!1,o=null,s=null,c=null,u=null,d=e.session?.subscribeIdentity(()=>{a=!0,n.dispose(),i=null,o=null,s=null,c=null});async function m(){if(a)throw new y("IDENTITY_CHANGED","Paywall is closed");let p=O.resolvePaywall,g=await le(n.request,p,{...r,selector:i?{type:"version",versionId:i.id}:r.selector}),f={paywall:await Va(e,g.paywall)};if(a)throw new y("IDENTITY_CHANGED","Paywall is closed");if(t.paywallVersionId?f.paywall.id!==t.paywallVersionId:f.paywall.paywallId!==t.paywallId)throw new y("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!Ug(f.paywall,i)||f.paywall.paywallId!==i.paywallId))throw new y("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=f.paywall,structuredClone(i)}async function w(p){if(!o)throw new y("INVALID_REQUEST","A quoted purchase is required");let g=p==="read"?O.readSubscriptionOperation:O.attach,f=await le(n.request,g,{operationId:o.operationId,...p==="read"?{}:{intent:p}});return Lg(f.operation,{operationId:o.operationId,currency:r.commerce.currency},"The purchase operation changed"),s=zg(s,f.operation),structuredClone(s)}let I={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},refresh:m,async preview(p){if(!i)throw new y("INVALID_REQUEST","Load the Paywall first");let g=i.document.buttons[p.actionId];if(g?.type!=="checkout")throw new y("INVALID_REQUEST","Choose an authored purchase action");let f=Up(g.product,p.selection,i.capabilities);if(!f)throw new y("PRODUCT_UNAVAILABLE","Choose an available Product");let S=Pm(i.document.screen,f,p.selection,i.capabilities),h=O.previewAttach.request.parse({funnelId:r.funnelId,funnelVersionId:r.funnelVersionId,requestId:p.requestId,plans:[{productVersionId:f,...Object.keys(S).length?{featureQuantities:S}:{}}],provider:r.commerce.provider,currency:r.commerce.currency,...p.offerId?{offerId:p.offerId}:{},...p.nativeOffer?{nativeOffer:p.nativeOffer}:{}}),P=JSON.stringify(h);if(c&&c!==P&&(!s||s.status==="pending"))throw new y("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===P){if(u)return u;if(o)return structuredClone(o)}c=P;let v=(async()=>{let E=O.previewAttach,j=await le(n.request,E,h);return Bg(j.quote,{productVersionId:f,featureQuantities:S,currency:r.commerce.currency,provider:r.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=j.quote,s=null,structuredClone(o)})();u=v;try{return await v}finally{u===v&&(u=null)}},confirm:()=>w("confirm"),cancel:()=>w("cancel"),read:()=>w("read"),destroy(){d?.(),a=!0,n.dispose(),i=null,o=null,s=null,c=null}};return await m(),I}function Gg(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new y("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new y("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new y("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let I=r;n&&e.nativeModule&&n.then(p=>e.nativeModule.reset(p,I)).catch(()=>{})}),d=e.nativeEvents?.(I=>{!n||!e.nativeModule||typeof I?.requestId!="string"||(async()=>{let p=await n;if(I.instanceId!==p)return;if(I.kind==="credential"){let S=r,h=null;try{if(!o&&I.revision===S){let P=await t.access();!o&&r===S&&(h=P)}}finally{await e.nativeModule.provideCredential(p,I.requestId,h)}return}let g=!1,f=r;try{if(o||I.revision!==f||!e.onNativeAction)throw c();await e.onNativeAction(I.action),g=!o&&r===f}finally{await e.nativeModule.acknowledge(p,I.requestId,g)}})().catch(()=>{})});async function m(I,p={}){let g=s();if(t.snapshot()&&!e.nativeEvents)throw new y("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let f=r,S=await t.access();if(o||r!==f)throw c();if(!n){let v=g.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.tinker.cash",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let h=await n;if(o||r!==f)throw c();if(i!==f){if(!a||a.epoch!==f){let E=(async()=>{if(await g.identify(h,JSON.stringify({revision:f,credentials:S})),o||r!==f)throw await g.reset(h,f),c();i=f})();a={epoch:f,task:E}}let v=a;try{await v.task}finally{a===v&&(a=void 0)}}let P=await g.invoke(h,I,JSON.stringify(p));if(o||r!==f)throw c();try{return JSON.parse(P)}catch{throw new y("INVALID_RESPONSE","Native host returned invalid JSON")}}async function w(I,p){let g=await m(I,p);if(!g||typeof g!="object"||Array.isArray(g)||g.status!=="complete"&&g.status!=="dismissed")throw new y("INVALID_RESPONSE","Native presentation returned an invalid result");return g}return{showFunnel(I){return w("showFunnel",{runToken:I})},showPaywall(I){return w("showPaywall",I)},showContent(I){return w("showContent",I)},purchaseSubscription(I,p){return m("purchaseSubscription",{operationId:I,accepted:p})},switchSubscription(I,p){return m("switchSubscription",{operationId:I,accepted:p})},restorePurchases(){return m("restorePurchases")},manageSubscriptions(I){return m("manageSubscriptions",I?{productId:I}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),d?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var m0=O.trackUsage.request.shape.command,f0=O.trackUsage.response;function NN(e){let t=Ve.parse(e.scope),n=Rg({...e,scope:t}),r={...e,scope:t,session:n.session},i=0;n.subscribeIdentity(()=>{i++});let a=()=>{let o=n.session.peek();if(!o)throw new y("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:Gg(e,n.session),funnel(){return Vg({...r,customerToken:a()})},resumeFunnel(o){return a(),pi({...r,runToken:o})},paywall(o){return $g(r,{...o,customerToken:a()})},async trackUsage(o){if(!n.session.peek())throw new y("UNAUTHENTICATED","Identify the Customer first");if(!e.usageReporter)throw new y("INVALID_REQUEST","Configure your authenticated backend usageReporter");let s=m0.parse(o),c=i,u;try{u=await e.usageReporter(s)}catch(m){throw c!==i?new y("IDENTITY_CHANGED","Customer identity changed during usage reporting"):m}if(c!==i)throw new y("IDENTITY_CHANGED","Customer identity changed during usage reporting");let d=f0.parse(u);if(d.scope.projectId!==t.projectId||d.scope.environment!==t.environment)throw new y("INVALID_RESPONSE","Usage response scope differs");return d}}}import{z as y0}from"zod";import{z as oo}from"zod";var g0=oo.record(oo.string().regex(/^[a-f0-9]{64}$/),oo.strictObject({at:oo.number(),text:oo.string()})),Kg=2*1048576,h0=100;function A0(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Hg(e,t){let n=t===void 0?A0():t,r=Promise.resolve();async function i(o){if(!n)return null;let s;try{return await Promise.race([Promise.resolve().then(()=>n.getItem(o)),new Promise(c=>{s=setTimeout(()=>c(null),h0)})])}catch{return null}finally{clearTimeout(s)}}async function a(){try{let o=await i(`${e}:artifacts`);if(o&&o.length<=Kg)return g0.parse(JSON.parse(o))}catch{}return{}}return{async readManifest(){return i(e)},writeManifest(o){Promise.resolve().then(()=>n?.setItem(e,o)).catch(()=>{})},async readArtifact(o){let s=(await a())[o];return s&&Date.now()>=s.at&&Date.now()-s.at<=Gt.retentionMs?s.text:void 0},writeArtifact(o,s){n&&(r=r.catch(()=>{}).then(async()=>{let c=await a(),u=Date.now();c[o]={at:u,text:s};let d={},m=2,w=0;for(let[I,p]of Object.entries(c).sort(([,g],[,f])=>f.at-g.at)){if(p.at>u||u-p.at>Gt.retentionMs)continue;let g=new TextEncoder().encode(JSON.stringify({[I]:p})).byteLength;m+g>Kg||w>=128||(d[I]=p,m+=g,w++)}await n.setItem(`${e}:artifacts`,JSON.stringify(d))}).catch(()=>{}))}}}var we=(e,t)=>new y(e,t),nr=()=>performance.now(),Qg=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function b0(e){let t=wc.parse(e.scope),n=new cn(e.origin??Xn);if(n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw we("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(Z=>{let G=new cn(Z);if(G.protocol!=="https:"||G.username||G.password||G.search||G.hash||G.pathname!=="/")throw we("INVALID_URL","Invalid configuration asset origin");return G.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${gt(t)}`,s=Hg(o,e.storage),c,u=0,d=0,m=!1,w=!1,I=0,p=0,g,f,S,h,P=0,v=new Set,E=new Set,j=new Map,q=new Map,de=0,be=!1;function Oe(){for(let Z of v)try{Z()}catch{}}function Se(Z){try{e.onError?.(Z)}catch{}}let Te=()=>!w&&!m&&!!c&&nr()<u&&Date.now()<d;function Pe(){if(!Te())throw we("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Vt(Z,G){let oe=new TextEncoder().encode(G).byteLength;if(!j.has(Z)){for(;j.size&&(j.size>=128||de+oe>Gt.maxCacheBytes);){let ae=j.entries().next().value;de-=new TextEncoder().encode(ae[1]).byteLength,j.delete(ae[0])}j.set(Z,G),de+=oe}}function Je(Z,G,oe){return kg(Z,G,{signal:oe,error:ae=>we("INVALID_RESPONSE",ae==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function _t(Z){let G=new cn(Z,n);if(!r.has(G.origin)||G.username||G.password||G.hash||G.search)throw we("INVALID_URL","Configuration artifact origin is not trusted");return G.href}async function ao(Z,G,oe=!1){let ae=await i(_t(Z),{method:"GET",credentials:"omit",redirect:"error",cache:oe?"default":"no-cache",signal:G,headers:{}});if(ae.status===429){let je=ae.headers.get("retry-after")??"";P=/^\d+$/.test(je)?Number(je)*1e3:Math.max(0,Date.parse(je)-Date.now())||15e3}if(!ae.ok&&ae.status!==304)throw we(`CONFIGURATION_HTTP_${ae.status}`,"Configuration synchronization failed");return ae}function Rr(Z,G,oe){let ae=Date.parse(Z.headers.get("x-indiana-config-validated-at")??""),je=Date.parse(Z.headers.get("x-indiana-config-valid-until")??""),xt=Date.parse(Z.headers.get("date")??""),$e=Z.headers.get("age"),Ht=$e!==null&&/^\d+(\.\d+)?$/.test($e)?Number($e)*1e3:NaN;if(![ae,je,xt,Ht].every(Number.isFinite)||je<=ae||je-ae>Gt.maxControlAgeMs||ae>xt+1e3)throw we("INVALID_RESPONSE","Configuration freshness evidence is invalid");let It=Math.min(je-ae,oe.maxControlAgeSeconds*1e3,Gt.maxControlAgeMs)-Math.max(Ht,xt-ae,0)-(nr()-G);if(It<=0)throw we("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return nr()+It}function it(){if(clearTimeout(S),clearTimeout(h),w||!v.size)return;Te()&&(h=setTimeout(()=>{Te()?it():Oe()},Math.max(1,u-nr())),Qg(h));let Z=p?Math.min(15e3,1e3*2**Math.min(p-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);S=setTimeout(()=>{Ut().catch(Se)},Math.max(P,Z*(.8+Math.random()*.2))),Qg(S)}async function Ut(){if(w)throw we("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(g)return g;let Z=I,G=new AbortController;f=G;let oe=(async()=>{if(!be){be=!0;try{let co=await s.readManifest();if(co&&!c){let Pn=Cc.parse(JSON.parse(co));gt(Pn.scope)===gt(t)&&(c=Pn)}}catch{}}G.signal.throwIfAborted();let $e=c,Ht=nr(),kt=await ao(a,G.signal);kt.status===304&&(!$e||!kt.headers.has("x-indiana-config-validated-at")||!kt.headers.has("x-indiana-config-valid-until")||!kt.headers.has("age"))&&(kt=await ao(a,G.signal));let It=kt.status===304?$e:Cc.parse(JSON.parse(await Je(kt,Gt.maxManifestBytes,G.signal))),{generation:Dn,...Fn}=It,or=kt.headers.get("etag");if(gt(It.scope)!==gt(t)||jm(Fn)!==Dn||or!==`"${Dn}"`&&or!==`W/"${Dn}"`)throw we("INVALID_RESPONSE","Configuration scope or content identity changed");if($e&&(It.revision<$e.revision||It.revision===$e.revision&&It.generation!==$e.generation))throw we("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[co,Pn]of Object.entries($e?.funnels??{})){let ar=It.funnels[co];if(ar&&(ar.controlRevision<Pn.controlRevision||ar.evaluationRevision<Pn.evaluationRevision||ar.controlRevision===Pn.controlRevision&&ar.state!==Pn.state||ar.evaluationRevision===Pn.evaluationRevision&&ar.evaluationMode!==Pn.evaluationMode))throw we("INVALID_RESPONSE","Funnel control revision changed identity")}let yu=Rr(kt,Ht,It.policy);if(G.signal.throwIfAborted(),Z!==I)throw we("CONFIGURATION_DISPOSED","Configuration scope changed");return c=It,u=yu,d=Date.now()+Math.max(0,yu-nr()),m=!1,p=0,P=0,s.writeManifest(gt(It)),Oe(),structuredClone(It)})(),ae=setTimeout(()=>G.abort(we("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Gt.initializationMs),je=new Promise(($e,Ht)=>G.signal.addEventListener("abort",()=>Ht(G.signal.reason),{once:!0})),xt=Promise.race([oe,je]).catch($e=>{throw p++,($e instanceof y0.ZodError||$e instanceof SyntaxError||$e instanceof y&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes($e.code))&&(u=0,m=!0,Oe()),$e}).finally(()=>{clearTimeout(ae),g===xt&&(g=void 0),it()});return g=xt,xt}async function rr(Z){let G=Z.sha256,oe=Dn=>qa(Dn,Z);_t(Z.url);let ae=j.get(G);if(ae&&oe(ae))return j.delete(G),j.set(G,ae),ae;if(q.has(G))return q.get(G);let je=new AbortController;E.add(je);let xt=I,$e=(async()=>{try{let or=await s.readArtifact(G);if(or&&oe(or))return Vt(G,or),or}catch{}je.signal.throwIfAborted();let Dn=await ao(Z.url,je.signal,!0),Fn=await Je(Dn,Z.byteLength,je.signal);if(!oe(Fn))throw we("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(w||xt!==I)throw we("CONFIGURATION_DISPOSED","Configuration scope changed");return Vt(G,Fn),s.writeArtifact(G,Fn),Fn})(),Ht=setTimeout(()=>je.abort(we("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Gt.initializationMs),kt=new Promise((Dn,Fn)=>je.signal.addEventListener("abort",()=>Fn(je.signal.reason),{once:!0})),It=Promise.race([$e,kt]).finally(()=>{clearTimeout(Ht),E.delete(je),q.delete(G)});return q.set(G,It),It}async function ir(){return Te()||await Ut(),Pe(),c}async function mi(Z){let G,oe=new Promise((ae,je)=>{G=setTimeout(()=>je(we("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Gt.initializationMs)});try{return await Promise.race([Z(),oe])}finally{clearTimeout(G)}}function fi(Z,G){if(Pe(),c?.generation!==Z.generation)throw we("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(G&&c.funnels[G]?.state!=="active")throw we("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function fu(Z){let G=Z.gb.features;if(!G)throw we("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let oe=Z.artifacts[G];if(oe.formatVersion!==1)throw we("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let ae=Ws.parse(JSON.parse(await rr(oe)));if(gt(ae.scope)!==gt({projectId:t.projectId,environment:t.environment})||ae.generation!==oe.generation||ae.remoteFeatures.some(je=>Object.hasOwn(ae.features,je)))throw we("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return fi(Z),{...ae,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-nr())).toISOString()}}async function gu(Z,G){let oe=await ir(),ae=oe.funnels[Z];G&&(!ae||ae.evaluationMode==="local"&&!ae.versions[G])&&(g&&await g,oe=await Ut()),fi(oe,Z);let je=oe.funnels[Z];if(je.evaluationMode!=="local")throw we("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let xt=G??je.currentVersionId,$e=je.versions[xt];if(!$e)throw we("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(oe.artifacts[$e.artifact].formatVersion!==3)throw we("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[Ht,kt]=await Promise.all([rr(oe.artifacts[$e.artifact]).then(It=>Nm(JSON.parse(It))),je.evaluationMode==="local"?fu(oe):void 0]);if(kt&>(Tm(Ht,kt))!==gt($e.dependencies))throw we("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return fi(oe,Z),{document:Ht,growth:kt,versionId:xt,control:structuredClone(je),manifest:structuredClone(oe)}}async function hu(Z,G){try{return await gu(Z,G)}catch(oe){if(!(oe instanceof y)||!(oe.code==="CONFIGURATION_CHANGED"||oe.code==="CONFIGURATION_HTTP_404"&&Te()))throw oe;let ae=c?.generation;if(g&&await g,await Ut(),oe.code!=="CONFIGURATION_CHANGED"&&c?.generation===ae)throw oe;return gu(Z,G)}}function La(){m=!0,Oe(),Ut().catch(Se)}let so=()=>{(typeof document>"u"||document.visibilityState==="visible")&&La()};function Jg(Z){if(w)throw we("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Z),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",La),window.addEventListener("focus",so),document.addEventListener("visibilitychange",so)),it()),()=>{v.delete(Z),v.size||(clearTimeout(S),clearTimeout(h),Au())}}function Au(){typeof window<"u"&&(window.removeEventListener("online",La),window.removeEventListener("focus",so),document.removeEventListener("visibilitychange",so))}return{scope:Object.freeze({...t}),refresh:Ut,subscribe:Jg,assertFresh:Pe,assertFeatures(Z){Pe();let G=c.gb.features;if(!G)throw we("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Z!==void 0&&c.artifacts[G].generation!==Z)throw we("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return Te()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return Te()?Math.max(0,u-nr()):0},async features(){return mi(async()=>fu(await ir()))},pageExperiments:()=>mi(async()=>{let Z=await ir(),G=Z.gb.pageExperiments;if(!G)throw we("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let oe=Z.artifacts[G];if(oe.formatVersion!==1)throw we("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let ae=Ff.parse(JSON.parse(await rr(oe)));if(ae.environmentId!==t.environmentId||ae.generation!==oe.generation)throw we("INVALID_RESPONSE","Page experiment scope or generation changed");return fi(Z),ae}),funnel:(Z,G)=>mi(()=>hu(Z,G)),paywall:(Z,G)=>mi(async()=>{let oe=await ir(),ae=oe.paywalls?.[Z];if(!ae||!G&&ae.state!=="published")throw we("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let je=G??ae.currentVersionId,xt=ae.versions[je],$e=xt&&oe.artifacts[xt.artifact];if(!$e||$e.kind!=="paywall"||$e.formatVersion!==1)throw we("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let Ht=wa.parse(JSON.parse(await rr($e)));return fi(oe),{document:Ht,versionId:je,version:xt.version,control:structuredClone(ae),manifest:structuredClone(oe)}}),async localFunnel(Z,G){let oe=await mi(()=>hu(Z,G));if(!oe.growth)throw we("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:ae,remoteFeatures:je,...xt}=oe.growth;return Nf({scope:{projectId:t.projectId,environment:t.environment},funnelId:Z,versionId:oe.versionId,evaluationMode:"local",evaluationRevision:oe.control.evaluationRevision,document:oe.document,payload:xt})},assertFunnel(Z,G,oe){Pe();let ae=c.funnels[Z];if(!ae||ae.state!=="active")throw we("FUNNEL_STOPPED","Funnel is paused or unavailable");if(ae.evaluationMode!=="local")throw we("EVALUATION_MODE","This Funnel now executes at Indiana");if(G!==void 0&&ae.controlRevision!==G)throw we("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(oe!==void 0&&!ae.versions[oe])throw we("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!w){w=!0,I++,u=0,f?.abort(we("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(S),clearTimeout(h),Au(),Oe(),v.clear();for(let Z of E)Z.abort(we("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),de=0}}}}async function S0(e){e={...e};let t=e.configuration;if(!t)throw new y("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let n={projectId:t.scope.projectId,environment:t.scope.environment};if(e.scope&>(n)!==gt(e.scope))throw new y("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new y("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=di.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new y("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=Ma({...e,scope:n,apiKey:e.credential}),o=s=>{let c=pi({...e,scope:n,runToken:s,...i?{serverKey:e.credential}:{}});return i||c.identify(e.credential),c};return{async start(s){let c=await a.start({...s,funnelId:e.funnelId,...i?{customer:{type:"id",value:e.customerId}}:{}}),u=o(c.runToken),d=await u.get();return{...c,...d,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new y("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}export{y as IndianaError,b0 as createConfigurationSync,du as createFeatureClient,NN as createIndianaReactNative,S0 as createLocalFunnelClient};
|