@tinkerlandai/indiana-react-native 0.9.1 → 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.
Files changed (83) hide show
  1. package/IndianaReactNative.podspec +19 -0
  2. package/README.md +61 -4
  3. package/THIRD_PARTY_NOTICES.md +74 -0
  4. package/android/build.gradle +24 -0
  5. package/android/src/main/AndroidManifest.xml +3 -0
  6. package/android/src/main/java/ai/tinkerland/indiana/reactnative/IndianaBridgeModule.kt +237 -0
  7. package/android/src/main/java/ai/tinkerland/indiana/reactnative/IndianaBridgePackage.kt +11 -0
  8. package/dist/index.cjs +17 -1
  9. package/dist/index.d.cts +57408 -604
  10. package/dist/index.d.ts +57408 -604
  11. package/dist/index.js +17 -1
  12. package/ios/IndianaBridge.m +11 -0
  13. package/ios/IndianaBridge.swift +275 -0
  14. package/native-sdk/android/assets/indiana/index.html +268 -0
  15. package/native-sdk/android/java/ai/tinkerland/indiana/BillingAuthorizationTerms.kt +55 -0
  16. package/native-sdk/android/java/ai/tinkerland/indiana/BundledWebView.kt +90 -0
  17. package/native-sdk/android/java/ai/tinkerland/indiana/ContentSession.kt +45 -0
  18. package/native-sdk/android/java/ai/tinkerland/indiana/ContentView.kt +36 -0
  19. package/native-sdk/android/java/ai/tinkerland/indiana/CustomerOperations.generated.kt +84 -0
  20. package/native-sdk/android/java/ai/tinkerland/indiana/CustomerResponseSemantics.kt +193 -0
  21. package/native-sdk/android/java/ai/tinkerland/indiana/CustomerSemantics.kt +120 -0
  22. package/native-sdk/android/java/ai/tinkerland/indiana/CustomerSession.kt +106 -0
  23. package/native-sdk/android/java/ai/tinkerland/indiana/FeatureClient.kt +65 -0
  24. package/native-sdk/android/java/ai/tinkerland/indiana/FunnelCommandStorage.kt +163 -0
  25. package/native-sdk/android/java/ai/tinkerland/indiana/FunnelConfigurationRelay.kt +50 -0
  26. package/native-sdk/android/java/ai/tinkerland/indiana/FunnelSession.kt +208 -0
  27. package/native-sdk/android/java/ai/tinkerland/indiana/FunnelView.kt +71 -0
  28. package/native-sdk/android/java/ai/tinkerland/indiana/GeneratedProtocol.kt +16 -0
  29. package/native-sdk/android/java/ai/tinkerland/indiana/GoogleStorefront.kt +165 -0
  30. package/native-sdk/android/java/ai/tinkerland/indiana/HTTPTransport.kt +43 -0
  31. package/native-sdk/android/java/ai/tinkerland/indiana/IndianaClient.kt +526 -0
  32. package/native-sdk/android/java/ai/tinkerland/indiana/NativePendingKeystore.kt +81 -0
  33. package/native-sdk/android/java/ai/tinkerland/indiana/NativeReceiptRelay.kt +28 -0
  34. package/native-sdk/android/java/ai/tinkerland/indiana/NativeStoreOffer.kt +24 -0
  35. package/native-sdk/android/java/ai/tinkerland/indiana/PaywallContent.kt +75 -0
  36. package/native-sdk/android/java/ai/tinkerland/indiana/PaywallSession.kt +144 -0
  37. package/native-sdk/android/java/ai/tinkerland/indiana/PaywallView.kt +74 -0
  38. package/native-sdk/android/java/ai/tinkerland/indiana/Protocol.kt +28 -0
  39. package/native-sdk/android/java/ai/tinkerland/indiana/PushInstallation.kt +170 -0
  40. package/native-sdk/android/java/ai/tinkerland/indiana/RendererNavigation.kt +13 -0
  41. package/native-sdk/android/java/ai/tinkerland/indiana/SDKVersion.kt +6 -0
  42. package/native-sdk/android/java/ai/tinkerland/indiana/StoreSubscriptionManagement.kt +19 -0
  43. package/native-sdk/android/java/ai/tinkerland/indiana/WireSchema.kt +76 -0
  44. package/native-sdk/android/resources/funnel-wire-schemas.json +1 -0
  45. package/native-sdk/android/resources/indiana-third-party-notices.txt +101 -0
  46. package/native-sdk/android/resources/renderer-data-url.txt +1 -0
  47. package/native-sdk/ios/AnalyticsReceipt.swift +10 -0
  48. package/native-sdk/ios/AppleStorefront.swift +218 -0
  49. package/native-sdk/ios/BillingAuthorizationTerms.swift +57 -0
  50. package/native-sdk/ios/BundledWebView.swift +87 -0
  51. package/native-sdk/ios/ContentSession.swift +48 -0
  52. package/native-sdk/ios/ContentView.swift +51 -0
  53. package/native-sdk/ios/CustomerOperations.generated.swift +166 -0
  54. package/native-sdk/ios/CustomerResponseSemantics.swift +232 -0
  55. package/native-sdk/ios/CustomerSemantics.swift +145 -0
  56. package/native-sdk/ios/CustomerSession.swift +129 -0
  57. package/native-sdk/ios/FeatureClient.swift +86 -0
  58. package/native-sdk/ios/FunnelCommandStorage.swift +163 -0
  59. package/native-sdk/ios/FunnelConfigurationRelay.swift +48 -0
  60. package/native-sdk/ios/FunnelSession.swift +232 -0
  61. package/native-sdk/ios/FunnelView.swift +125 -0
  62. package/native-sdk/ios/GeneratedProtocol.swift +16 -0
  63. package/native-sdk/ios/HTTPTransport.swift +74 -0
  64. package/native-sdk/ios/IndianaClient.swift +601 -0
  65. package/native-sdk/ios/NativePendingKeychain.swift +52 -0
  66. package/native-sdk/ios/NativeReceiptRelay.swift +28 -0
  67. package/native-sdk/ios/NativeStoreOffer.swift +34 -0
  68. package/native-sdk/ios/PaywallContent.swift +75 -0
  69. package/native-sdk/ios/PaywallSession.swift +124 -0
  70. package/native-sdk/ios/PaywallView.swift +87 -0
  71. package/native-sdk/ios/Protocol.swift +49 -0
  72. package/native-sdk/ios/PushInstallation.swift +154 -0
  73. package/native-sdk/ios/RendererNavigation.swift +8 -0
  74. package/native-sdk/ios/Resources.swift +15 -0
  75. package/native-sdk/ios/SDKVersion.swift +4 -0
  76. package/native-sdk/ios/StoreSubscriptionManagement.swift +11 -0
  77. package/native-sdk/ios/WebView/THIRD_PARTY_NOTICES.txt +101 -0
  78. package/native-sdk/ios/WebView/index.html +268 -0
  79. package/native-sdk/ios/WebView/renderer-data-url.txt +1 -0
  80. package/native-sdk/ios/WireSchema.swift +107 -0
  81. package/native-sdk/ios/funnel-wire-schemas.json +1 -0
  82. package/package.json +8 -3
  83. package/react-native.config.cjs +12 -0
package/dist/index.cjs CHANGED
@@ -1 +1,17 @@
1
- "use strict";var mn=Object.defineProperty;var Xd=Object.getOwnPropertyDescriptor;var Jd=Object.getOwnPropertyNames;var zd=Object.prototype.hasOwnProperty;var em=(e,t,r)=>t in e?mn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var tm=(e,t)=>{for(var r in t)mn(e,r,{get:t[r],enumerable:!0})},rm=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Jd(t))!zd.call(e,i)&&i!==r&&mn(e,i,{get:()=>t[i],enumerable:!(n=Xd(t,i))||n.enumerable});return e};var nm=e=>rm(mn({},"__esModule",{value:!0}),e);var wt=(e,t,r)=>em(e,typeof t!="symbol"?t+"":t,r);var Xb={};tm(Xb,{IndianaError:()=>R,createIndianaReactNative:()=>Yd});module.exports=nm(Xb);var pn=require("zod"),im=pn.z.enum(["sandbox","live"]),Xe=pn.z.object({projectId:pn.z.string().min(1),environment:im}).strict();var ue=require("zod"),Cr=ue.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),yo=ue.z.enum(["unknown","denied","provisional","granted"]),So=ue.z.enum(["ios","android"]),fn=ue.z.strictObject({installationId:ue.z.uuid(),publicKey:ue.z.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:ue.z.iso.datetime({offset:!0}),signature:ue.z.string().regex(/^[A-Za-z0-9_-]{86}$/)}),hi=ue.z.string().regex(/^[a-f0-9]{64}$/),_o=fn.extend({sequence:Cr,platform:So,credentialDigest:hi}),xo=fn.extend({credentialDigest:hi}),Io=fn.extend({sequence:Cr,platform:So}),hn=fn.extend({sequence:Cr,credentialDigest:hi,connectionId:ue.z.uuid().nullable(),kind:ue.z.enum(["fcm_token","apns_token"]).nullable(),token:ue.z.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:yo}),vo=hn,Po=hn.extend({challenge:ue.z.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),Ai=ue.z.strictObject({requested:ue.z.literal(!0),expiresAt:ue.z.iso.datetime({offset:!0})}),qt=ue.z.strictObject({installationId:ue.z.uuid(),bound:ue.z.boolean(),identitySeq:Cr,bindingGeneration:Cr,addressSeq:ue.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:ue.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:ue.z.uuid().nullable(),addressStatus:ue.z.enum(["active","invalid"]).nullable(),permission:yo}),gi=ue.z.strictObject({channel:ue.z.enum(["email","sms","voice","push"]),state:ue.z.enum(["unknown","allowed","denied"]),revision:ue.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:ue.z.iso.datetime({offset:!0}).nullable()}),ty=ue.z.strictObject({state:ue.z.enum(["allowed","denied"]),revision:ue.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function Co(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))}var De=require("zod"),Lt=De.z.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"]),ny=De.z.enum([...Lt.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),iy=De.z.enum([...Lt.options,"stale_revision"]),am=De.z.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"]),om=De.z.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),Oo={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 wo={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 sm(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(wo,e)){let n=wo[e];return{retryable:n==="retry_same_request",recovery:n}}let r=Lt.safeParse(e);return r.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:Oo[r.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Eo(e,t){let r=Lt.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):Oo[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 cm(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 jo=De.z.object({retryable:De.z.boolean(),recovery:am,reason:om.optional(),retryAfterSeconds:De.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),bi=De.z.object({requestId:De.z.uuid().optional(),error:De.z.object({code:De.z.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:De.z.string(),...jo.partial().shape})}),ay=De.z.object({error:bi.shape.error.extend({requestId:De.z.uuid().optional()})}),oy=De.z.object({error:De.z.string(),code:De.z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:De.z.uuid(),...jo.shape});function An(e,t,r={}){let n=sm(e,t),i=r.reason==="RESULT_UNKNOWN"?"recover_operation":r.recovery??n.recovery,o=n.retryable&&r.retryable!==!1&&i!=="recover_operation",a=o?cm(r.retryAfter??null):void 0;return{...n,retryable:o,recovery:i,...a===void 0?{}:{retryAfterSeconds:a},...r.reason?{reason:r.reason}:{}}}var yi="X-Indiana-Protocol",To="X-Indiana-SDK-Version";var Si={current:"0.9",unversioned:"0.2",releases:[{protocol:"0.9",firstReleasedAt:null,noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[]},{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"}]}]};var Ro=require("zod"),um=["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"],J=Ro.z.enum(um);function ko(e){let t=J.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}var Bt=require("zod");var Ft=Bt.z.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"),dy=Bt.z.object({amountCents:Bt.z.number().int().min(0).max(1e8),currency:J,interval:Bt.z.enum(["free","month","year"]),currencyOptions:Bt.z.partialRecord(J,Bt.z.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");var g=require("zod/v4");var Do=require("zod/v4"),No=Do.z.registry();var{AppEnv:gn}=(()=>{var e;return(function(t){t.Sandbox="sandbox",t.Live="live"})(e||(e={})),{AppEnv:e}})(),{IGNORE_PAST_DUE_DESCRIPTION:Mo}={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:lm}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{SpendLimitType:dm}=(e=>({SpendLimitType:e.enum(["absolute","usage_percentage"])}))(g.z),{ResetInterval:wr}=(()=>{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:mm}={USAGE_LIMIT_ANCHORS:["billing_cycle","utc"]},{USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:pm}={USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:64},{USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:fm}={USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:128},{USAGE_LIMIT_FILTER_MAX_KEYS:hm}={USAGE_LIMIT_FILTER_MAX_KEYS:4},{UsageAlertThresholdType:Am}=(e=>({UsageAlertThresholdType:e.enum(["usage","usage_percentage","remaining","remaining_percentage"])}))(g.z),{BALANCE_BASES:gm}={BALANCE_BASES:["balance","included","recurring"]},{DEFAULT_USAGE_ALERT_BASIS:Uo}={DEFAULT_USAGE_ALERT_BASIS:"balance"},{DbOverageAllowedSchema:_i}=(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.z),{ProductMetadataSchema:cr}=(e=>({ProductMetadataSchema:e.record(e.string(),e.any())}))(g.z),{findDuplicate:bm}={findDuplicate:t=>{let r=new Set;for(let n of t){if(r.has(n))return n;r.add(n)}}},{BillingInterval:Ot}=(()=>{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:xi}=(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.z),{withSpecDefault:Or}=(e=>({withSpecDefault:({schema:r,defaultValue:n,description:i})=>(e.add(r,{description:i,default:n}),r)}))(No),{COMMON:qo}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:ym}={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:Sm}=(e=>({COMMON_SET:new Set(e)}))(qo),{hasNoDuplicateCurrencies:Lo}={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:Bo}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{IncludedUsageParamsSchema:Ii}=(e=>({IncludedUsageParamsSchema:e.number().max(1e13,{error:"Included usage cannot exceed 10 trillion; use unlimited usage instead"})}))(g.z),{Infinite:bn}={Infinite:"inf"},{TierBehavior:Er}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:yn}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Fo}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{PLAN_ITEM_PRICE_DESCRIPTION:_m}={PLAN_ITEM_PRICE_DESCRIPTION:"Pricing for usage beyond included units. Omit for free features."},{OnIncrease:Sn}=(()=>{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:_n}=(()=>{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:vi}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:Vo}=(()=>{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:xm}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Im}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Pi}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(g.z),{ApiCreditTierSchema:$o}=(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.z),{VIOLATION_MESSAGES:vm}={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:Go}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(g.z),{ModelMarkupsSchema:Ci}=((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.z,Go),{additionalCurrencyPlanItemIssues:Ho}={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:wi}=((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.z,yn,Ot,wr,Ii),{UpdatePlanItemParamsV1Schema:Pm}=((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.z,wi,wr),{FreeTrialDuration:jr}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{laneParam:Cm}=((e,t)=>({laneParam:({schema:n,description:i})=>e({schema:t.array(n).optional(),defaultValue:[],description:i})}))(Or,g.z),{findDuplicateInControls:wm}={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:Om}={featureIdIdentity:t=>t.feature_id||void 0},{usageLimitFilterKey:Ko}={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:Em}=((e,t)=>({usageAlertIdentity:n=>[n.feature_id??"",n.basis??e,t(n.filter),n.threshold_type,n.threshold].join("|")}))(Uo,Ko),{RemovePlanLicenseSchema:jm}=(e=>({RemovePlanLicenseSchema:e.object({license_plan_id:e.string()})}))(g.z),{ApiStripePriceProcessorSchema:Tm}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(g.z),{ApiFeatureType:Rm}=(()=>{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:km}=(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.z),{ApiRevenueCatProductSchema:Dm}=(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.z),{TrialOnEnd:xn}={TrialOnEnd:["bill","revert"]},{EligibilityStatus:Nm}=(()=>{var e;return(function(t){t.Active="active",t.Scheduled="scheduled"})(e||(e={})),{EligibilityStatus:e}})(),{AttachAction:Mm}=(()=>{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:Um}=(()=>{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:qm}=(e=>({UsageWindowDimensionSchema:e.enum(["balance","metered_feature"])}))(g.z),{UsageWindowScopeSchema:Lm}=(e=>({UsageWindowScopeSchema:e.enum(["customer","entity"])}))(g.z),{EntInterval:Wo}=(()=>{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:Bm}=(()=>{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:Fm}=(e=>({FeatureStripeMeterSchema:e.object({id:e.string(),event_name:e.string()})}))(g.z),{FreeTrialSchema:Vm}=((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.z,jr,xn),{BillingType:$m}=(()=>{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:Oi}=((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.z,bn),{IgnoredFixedPriceMetadataSchema:Gm}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(r=>typeof r=="string"?null:r,e.null().or(e.undefined()))}))(g.z),{BillWhen:Hm}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:Zo}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProrationConfigSchema:Km}=((e,t,r)=>({ProrationConfigSchema:e.object({on_increase:e.nativeEnum(t).default(t.ProrateImmediately),on_decrease:e.nativeEnum(r).default(r.ProrateImmediately)})}))(g.z,Sn,_n),{AllowanceType:Wm}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{RolloverConfigSchema:Qo}=((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.z,vi),{CreditDimensionBaseSchema:Zm}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(g.z,Pi),{flatCreditRateShape:Yo}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(g.z),{CreditTierSchema:Qm}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(g.z),{CreditMultiplierSchema:Ym}=((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.z,Pi),{idRegex:In}={idRegex:/^[a-zA-Z0-9_-]+$/},{descriptions:Xo}={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:Xm}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ProductItemFeatureType:Jm}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{ProductItemInterval:zm}=(()=>{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:ep}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{TierInfinite:tp}={TierInfinite:"inf"},{CreateFreeTrialSchema:Jo}=((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.z,jr,xn),{ProductConfigParamsSchema:Ei}=((e,t,r)=>({ProductConfigParamsSchema:e.object({ignore_past_due:t({schema:e.boolean().optional(),defaultValue:!1,description:r})})}))(g.z,Or,Mo),{CREATE_PRODUCT_EXAMPLE:rp}={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:np}=((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.z,jr,xn),{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.z),{isUsageLimitBasisAlert:ip}={isUsageLimitBasisAlert:t=>t.basis==="usage_limit"},{PromoCodeSchema:zo}=(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.z),{RewardType:es}=(()=>{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:ts}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Months="months",t.Forever="forever"})(e||(e={})),{CouponDurationType:e}})(),{FreeProductConfigSchema:rs}=((e,t)=>({FreeProductConfigSchema:e.object({duration_type:e.nativeEnum(t),duration_value:e.number()})}))(g.z,ts),{RewardTriggerEvent:ap}=(()=>{var e;return(function(t){t.CustomerCreation="customer_creation",t.Checkout="checkout"})(e||(e={})),{RewardTriggerEvent:e}})(),{RewardReceivedBy:op}=(()=>{var e;return(function(t){t.Referrer="referrer",t.All="all"})(e||(e={})),{RewardReceivedBy:e}})(),{ProductConfigSchema:vn}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(g.z,Mo),{PurchaseLimitIntervalEnum:sp}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(g.z,lm),{DbSpendLimitSchema:ji}=((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.z,dm),{USAGE_LIMIT_INTERVALS:cp}=(e=>({USAGE_LIMIT_INTERVALS:[e.Day,e.Week,e.Month,e.Year]}))(wr),{UsageLimitAnchorSchema:ns}=((e,t)=>({UsageLimitAnchorSchema:e.enum(t)}))(g.z,mm),{UsageLimitFilterValueSchema:up}=((e,t)=>({UsageLimitFilterValueSchema:e.union([e.string().min(1).max(t),e.number(),e.boolean()]).transform(String).pipe(e.string())}))(g.z,fm),{USAGE_ALERT_BASES:lp}=(e=>({USAGE_ALERT_BASES:[...e,"usage_limit"]}))(gm),{licensePatchIssues:dp}=(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"]}]}}))(bm),{BasePriceSchema:mp}=((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.z,Ot,xi),{CURRENCY_CODES:pp}=((e,t,r)=>({CURRENCY_CODES:[...e,...t.filter(i=>!r.has(i)).sort()]}))(qo,ym,Sm),{AllocatedBillingFieldSchema:is}=((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.z,Fo),{EntitlementExpirySchema:Pn}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(g.z,Vo),{CreditDimensionNameSchema:as}=((e,t,r)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(r),{message:`Dimension names cannot contain "${r}"`})}))(g.z,xm,Im),{ApiCreditMatchSchema:os}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Pi),{findCreditTierViolations:fp}=(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}}))(vm),{ApiCreditMultiplierSchema:hp}=((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.z,os),{ProviderMarkupsSchema:ss}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(g.z,Go),{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 Pe=typeof U=="number",Me=Array.isArray(ie)&&ie.length>0;Pe||Me?Pe&&Me&&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}}))(yn,Ot,Fo,Er,Ho),{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.z,jr,Or),{duplicateCheck:gp}=(e=>({duplicateCheck:({controlKey:r,...n})=>i=>e({controlKey:r,controls:i[r]??[],rule:n})}))(wm),{usageLimitIdentity:Ri}=(e=>({usageLimitIdentity:r=>`${r.feature_id}|${e(r.filter)}`}))(Ko),{ApiPriceProcessorsSchema:cs}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(g.z,Tm),{ApiFeatureV0Schema:us}=((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.z,Rm),{ApiRevenueCatPlanProcessorSchema:bp}=((e,t)=>({ApiRevenueCatPlanProcessorSchema:e.object({products:e.array(t).meta({description:"Every RevenueCat product that maps to this plan. Replaces the current set."})})}))(g.z,Dm),{ApiFreeTrialV2Schema:yp}=((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.z,jr,xn),{CustomerEligibilitySchema:Sp}=((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.z,Nm,Mm,Um),{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.z,qm,Lm,Wo,ns),{FeatureSchema:_p}=((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.z,gn,Bm,Ci,Fm),{PriceCurrencyConfigSchema:ls}=((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.z,Oi),{UsagePriceConfigSchema:xp}=((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.z,Hm,Oi,Ot,ls,Zo),{graduatedCreditRateShape:ds}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(g.z,Qm),{FeatureMarkupsOverrideSchema:Ip}=((e,t,r)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:r})}))(g.z,ss,Ci),{usageAlertTargetLimitIdentity:vp}=(e=>({usageAlertTargetLimitIdentity:r=>e({feature_id:r.feature_id??"",filter:r.filter})}))(Ri),{DiscountConfigSchema:ms}=((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.z,ts),{RewardEntitlementSchema:ps}=((e,t)=>({RewardEntitlementSchema:e.object({internal_feature_id:e.string().min(1),allowance:e.number().nonnegative().optional(),expiry:t.optional()})}))(g.z,Pn),{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.z,zo,es,ms,rs,ps),{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.z,ap,op),{AutoTopupPurchaseLimitSchema:fs}=((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.z,sp),{UsageLimitFilterSchema:hs}=((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.z,pm,up,hm),{UsageAlertBasisSchema:Pp}=((e,t)=>({UsageAlertBasisSchema:e.enum(t)}))(g.z,lp),{refineCustomizePlanV1Schema:As}=(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`})}}))(dp),{SUPPORTED_SET:Cp}=(e=>({SUPPORTED_SET:new Set(e)}))(pp),{ApiCreditDimensionBaseSchema:wp}=((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.z,os),{refineGraduatedTiers:gs}=(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"]})}}))(fp),{ApiFeatureMarkupsOverrideSchema:Op}=((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.z,ss,Ci),{AutoTopupPurchaseLimitParamsSchema:Ep}=((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."})})}))(fs,g.z),{DUPLICATE_CHECKS:jp}=((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"})]}))(gp,Om,Ri,Em),{ApiPlanProcessorsSchema:Tp}=((e,t,r)=>({ApiPlanProcessorsSchema:e.object({stripe:t.nullish(),revenuecat:r.nullish()}).meta({"x-atmn-mapping":!0})}))(g.z,km,bp),{FixedPriceConfigSchema:Rp}=((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.z,Ot,ls,Oi,Gm),{CreditDimensionSchema:kp}=((e,t,r,n)=>({CreditDimensionSchema:e.union([t.extend(r),t.extend(n)])}))(g.z,Zm,Yo,ds),{filterUnresolvableUsageLimitAlerts:Dp}=((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}]:[])}}))(Ri,ip,vp),{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.z,zo,es,ms,rs,ps),{AutoTopupSchema:ki}=((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.z,fs),{DbUsageLimitSchema:Di}=((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.z,cp,ns,hs),{DbUsageAlertSchema:Ni}=((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.z,Am,Pp,Uo,hs),{isValidCurrencyCode:Np}=(e=>({isValidCurrencyCode:r=>!!r&&e.has(r.toLowerCase())}))(Cp),{ApiCreditDimensionSchema:Mp}=((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.z,wp,$o,gs),{AutoTopupParamsSchema:Up}=((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."})})}))(ki,Ep),{findDuplicateBillingControlIssue:qp}=(e=>({findDuplicateBillingControlIssue:r=>{for(let n of e){let i=n(r);if(i)return i}}}))(jp),{CustomerBillingControlsSchema:Mi}=((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.z,ki,ji,Di,Ni,_i),{PriceSchema:Lp}=((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.z,$m,Er,Rp,xp,Km),{CreditSchemaItemBaseSchema:bs}=((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.z,as,kp,Ym),{GraduatedCreditSchemaItemSchema:Bp}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(bs,ds),{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.z,vn,Mi),{DbBillingControlsSchema:Fp}=((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.z,ki,ji,Di,Ni,_i),{CurrencyCodeSchema:ys}=((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.z,Np),{AdditionalCurrencyTierSchema:Vp}=((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.z,ys),{ApiCreditSchemaItemBaseSchema:Ss}=((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.z,as,Mp,hp),{ApiFlatCreditSchemaItemSchema:$p}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Ss,g.z),{rejectDuplicateBillingControls:Gp}=(e=>({rejectDuplicateBillingControls:r=>{let n=e(r.value);n&&r.issues.push(n)}}))(qp),{FlatCreditSchemaItemSchema:Hp}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(bs,Yo),{ProductSchema:Kp}=((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.z,gn,vn,Fp,cr),{AdditionalCurrencyPriceSchema:Wp}=((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.z,ys),{AdditionalCurrencyTierArraySchema:_s}=((e,t,r,n)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(r,{message:n})}))(g.z,Vp,Lo,Bo),{ApiGraduatedCreditSchemaItemSchema:Zp}=((e,t,r,n)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(r).min(1)}).strict().superRefine(n)}))(Ss,g.z,$o,gs),{CustomerBillingControlsParamsSchema:Cn}=((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.z,Cm,Up,ji,Di,Ni,_i,Gp),{CreditSchemaItemSchema:Qp}=((e,t,r)=>({CreditSchemaItemSchema:e.union([t,r])}))(g.z,Hp,Bp),{PriceTierSchema:Yp}=((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.z,tp,_s),{PlanBillingControlsParamsSchema:Xp}=((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"]})})}))(Cn,Dp),{AdditionalCurrencyPriceArraySchema:Tr}=((e,t,r,n)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(r,{message:n})}))(g.z,Wp,Lo,Bo),{ApiUsageTierWithCurrenciesSchema:xs}=((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.z,bn,_s),{ApiCreditSchemaItemSchema:Jp}=((e,t,r)=>({ApiCreditSchemaItemSchema:e.union([t,r])}))(g.z,Zp,$p),{FeatureConfigOverrideSchema:Is}=((e,t,r)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:r.optional()})}))(g.z,Qp,Ip),{ProductItemConfigSchema:zp}=((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.z,Zo,Sn,_n,Qo,Pn,Is),{BasePriceParamsSchema:wn}=((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."})}))(mp,Or,g.z,Tr),{PlanItemPriceParamsSchema:ef}=((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.z,Tr,xs,Er,Ot,yn,is),{ApiFeatureOverrideSchema:vs}=((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.z,Jp,Op),{ApiPlanItemV1Schema:tf}=((e,t,r,n,i,o,a,c,l,p,A,v,k,U,ie,q,Pe)=>({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(j=>{let V=j.value.reset?.interval,X=j.value.price?.interval,he=j.value.reset?.interval_count??1,be=j.value.price?.interval_count??1;if(V&&X&&(String(V)!==String(X)||he!==be)&&j.value.price?.billing_method!==c.Prepaid&&j.issues.push({code:"custom",message:"reset.interval and price.interval can only differ for prepaid prices.",input:j.value}),j.value!==void 0&&j.value.price!==void 0&&j.value.price!==null){j.value.price.amount&&j.value.price.tiers&&j.value.price.tiers.length>0&&j.issues.push({code:"custom",message:"Price amount and tiers are mutually exclusive.",input:j.value});for(let Ve of Pe(j.value.price))j.issues.push({code:"custom",message:Ve,input:j.value.price})}})}))(g.z,us,wr,Tr,xs,Er,Ot,yn,is,cs,xi,vi,Sn,_n,Pn,vs,Ho),{EntitlementSchema:rf}=((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.z,Wm,Wo,Vo,Qo,Is),{ProductItemSchema:Ps}=((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.z,Xm,Jm,us,bn,zm,ep,Yp,Tr,Er,zp),{ProductV2Schema:Cs}=((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.z,gn,np,Ps,vn,Mi,cr),{PlanItemParamsObjectSchema:nf}=((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.z,Ii,wr,Or,ef,_m,Sn,_n,vi,Pn,vs),{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()})}))(Kp,g.z,Lp,rf,_p,Vm),{CreateProductItemParamsSchema:ws}=((e,t,r,n)=>({CreateProductItemParamsSchema:e.extend({included_usage:t.or(r.literal(n)).nullish()})}))(Ps,Ii,g.z,bn),{CreatePlanItemParamsV1Schema:Ui}=((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."})}))(nf,Ap),{LicenseCustomizeSchema:Os}=((e,t,r,n)=>({LicenseCustomizeSchema:e.object({price:t.nullable().optional(),add_items:e.array(r).optional(),remove_items:e.array(n).optional()})}))(g.z,wn,Ui,wi),{PlanLicenseParamsSchema:qi}=((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.z,Os),{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.z,In,Xo,ws,qi,Jo,Ei,Cn,cr),{CreatePlanParamsV1Schema:af}=((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.z,In,wn,Ui,qi,Ti,Ei,Xp,cr),{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."})})}))(af,g.z,wn,Ti,In),{CustomizePlanLicenseSchema:Li}=((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.z,Os),{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.z,In,Xo,ws,qi,Jo,Ei,Cn,cr,rp),{CustomizePlanV1BaseSchema:Es}=((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.z,wn,Ui,wi,Pm,Ti,Cn,Li,jm),{VariantCustomizeSchema:of}=((e,t)=>({VariantCustomizeSchema:e(t.omit({items:!0}).strict(),{includeItems:!1,includeLicenses:!0})}))(As,Es),{DiffedCustomizePlanV1Schema:Py}=((e,t)=>({DiffedCustomizePlanV1Schema:e(t.omit({items:!0}),{includeItems:!1,includeLicenses:!0})}))(As,Es),{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.z,Tr,Ot,xi,cs,tf,Tp,yp,gn,vn,Mi,cr,Sp,of);var S=require("zod"),sf=S.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Rs=S.z.enum(["single_use","continuous_use"]),Bi=S.z.record(S.z.string(),S.z.union([S.z.string(),S.z.number(),S.z.boolean()]).transform(String).pipe(S.z.string())),js=S.z.string().min(1).max(64).refine(e=>!e.includes("::")),ks={credit_amount:S.z.number(),tier_behavior:S.z.never().optional(),tiers:S.z.never().optional()},Ds={credit_amount:S.z.never().optional(),tier_behavior:S.z.literal("graduated"),tiers:S.z.array(S.z.strictObject({to:S.z.union([S.z.number(),S.z.literal("inf")]),credit_amount:S.z.number()}))},cf=S.z.union([S.z.strictObject({match:Bi,priority:S.z.number().int().optional(),...ks}),S.z.strictObject({match:Bi,priority:S.z.number().int().optional(),...Ds})]),uf=S.z.strictObject({match:Bi,factor:S.z.number().positive().optional(),add:S.z.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),Ts={metered_feature_id:S.z.string(),feature_amount:S.z.number().optional(),dimensions:S.z.record(js,cf).optional(),multipliers:S.z.record(js,uf).optional()},Fi=S.z.union([S.z.strictObject({...Ts,...ks}),S.z.strictObject({...Ts,...Ds})]),En=S.z.number().min(-100),Ns=S.z.record(S.z.string(),S.z.strictObject({markup:En})).nullish(),jn=S.z.record(S.z.string().regex(/.+\/.+/),S.z.strictObject({markup:En.optional(),input_cost:S.z.number().min(0).optional(),output_cost:S.z.number().min(0).optional()})).nullish(),lf=S.z.strictObject({default_markup:En.optional(),provider_markups:Ns,model_markups:jn}),Vi=S.z.strictObject({schema:S.z.array(Fi).optional(),markups:lf.optional()}),df=S.z.strictObject({filters:S.z.array(S.z.strictObject({property:S.z.string(),operator:S.z.string(),value:S.z.array(S.z.string())})),aggregate:S.z.strictObject({type:S.z.string(),property:S.z.string().nullable()}),usage_type:Rs}),Ms=S.z.strictObject({schema:S.z.array(Fi).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.z.boolean().optional(),usage_type:Rs.default("single_use").overwrite(()=>"single_use"),default_markup:En.optional(),provider_markups:Ns}),$i=Ms.safeExtend({schema:S.z.array(Fi).length(0)}),On={id:sf,name:S.z.string().min(1),display:S.z.strictObject({singular:S.z.string().optional(),plural:S.z.string().optional()}).nullish(),event_names:S.z.array(S.z.string()).default([]),model_markups:jn,stripe_meter:S.z.strictObject({id:S.z.string(),event_name:S.z.string()}).nullish(),stripe_product_id:S.z.string().nullish()},Gi=e=>S.z.discriminatedUnion("type",[S.z.strictObject({...On,...e,type:S.z.literal("boolean"),config:S.z.null()}),S.z.strictObject({...On,...e,type:S.z.literal("metered"),config:df}),S.z.strictObject({...On,...e,type:S.z.literal("credit_system"),config:Ms}),S.z.strictObject({...On,...e,type:S.z.literal("ai_credit_system"),config:$i})]),Oy=Gi({}),mf=S.z.strictObject({id:S.z.boolean(),type:S.z.boolean(),usage_type:S.z.boolean()}),pf={internal_id:S.z.uuid(),org_id:S.z.uuid(),created_at:S.z.number(),env:S.z.enum(["sandbox","live"]),archived:S.z.boolean(),project_id:S.z.uuid(),environment_id:S.z.uuid(),revision:S.z.number().int().nonnegative(),update_rules:mf},Us=Gi(pf),Ey=S.z.strictObject({rows:S.z.array(Us).max(200),nextCursor:S.z.uuid().nullable()}),qs=S.z.strictObject({features:S.z.array(Us).max(500),limited:S.z.boolean()}),jy=S.z.union([Gi({action:S.z.literal("save"),internal_id:S.z.uuid().nullable(),revision:S.z.number().int().nonnegative()}),S.z.strictObject({action:S.z.enum(["archive","restore","delete"]),internal_id:S.z.uuid(),revision:S.z.number().int().nonnegative()})]);var Vt=require("zod"),Ls=Vt.z.number().int().min(0).max(1e8),Rr=Vt.z.strictObject({kind:Vt.z.enum(["graduated","volume"]),tiers:Vt.z.array(Vt.z.strictObject({upTo:Vt.z.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Ls,flatAmountMinor:Ls.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 Hi(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let r=e.pricing?Rr.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 Tn(e){return Hi({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var C=require("zod");var u=require("zod");var D=require("zod");var Le=require("zod");var b=require("zod");var Ze=b.z.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.z.record(b.z.string().min(1).max(128),Ze).superRefine((e,t)=>{(!Ze.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"})}),ff=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"]),ut=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.z.strictObject({id:b.z.uuid(),attributeKey:b.z.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("$")&&!ff.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)}),hf=b.z.discriminatedUnion("type",[b.z.strictObject({type:b.z.literal("condition"),condition:ut}),b.z.strictObject({type:b.z.literal("list"),attributeKey:b.z.string().min(1).max(128),values:b.z.array(b.z.union([b.z.string(),b.z.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 Wi(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.z.record(b.z.uuid(),hf).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"&&Wi(a.condition).forEach(i),r.delete(o),n.add(o)}Object.keys(e).forEach(i)}),Zi=b.z.tuple([b.z.number().min(0).max(1),b.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),Bs=b.z.strictObject({attribute:b.z.string().optional(),seed:b.z.string().min(1),hashVersion:b.z.literal(2),ranges:b.z.array(Zi).min(1).max(100)}),gf=b.z.strictObject({id:b.z.string().min(1).max(128),condition:ut,gate:b.z.boolean().optional()}),Ki={id:b.z.string().max(128).optional(),condition:ut.optional(),parentConditions:b.z.array(gf).max(50).optional(),filters:b.z.array(Bs).max(20).optional()},bf=b.z.union([b.z.strictObject({...Ki}),b.z.strictObject({...Ki,force:Ze,coverage:b.z.number().min(0).max(1).optional(),range:Zi.optional(),seed:b.z.string().min(1).optional(),hashAttribute:b.z.string().optional(),hashVersion:b.z.literal(2).optional()}),b.z.strictObject({...Ki,type:b.z.literal("experiment-ref"),experimentId:b.z.uuid(),values:b.z.record(b.z.string().min(1),Ze),meta:b.z.record(b.z.string().min(1),b.z.strictObject({passthrough:b.z.boolean()})).optional()})]),yf=b.z.strictObject({defaultValue:Ze,rules:b.z.array(bf).max(100)}),ky=b.z.record(b.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),yf).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)}),Sf=b.z.strictObject({name:b.z.string().max(80),reason:b.z.string().max(500),dateStarted:b.z.iso.datetime({offset:!0}),dateEnded:b.z.iso.datetime({offset:!0}).nullable(),coverage:b.z.number().min(0).max(1),variationWeights:b.z.array(b.z.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,r)=>t+r,0)-1)<=.01),condition:ut,savedGroups:b.z.array(b.z.strictObject({match:b.z.enum(["any","all","none"]),ids:b.z.array(b.z.uuid()).min(1)})).max(50),namespace:b.z.strictObject({id:b.z.uuid(),ranges:b.z.array(Zi).min(1)}).nullable(),seed:b.z.string().min(1).max(128)}),_f=b.z.strictObject({key:b.z.string().min(1).max(128),name:b.z.string().min(1).max(80),hypothesis:b.z.string().max(2e3),status:b.z.enum(["draft","running","stopped"]),hashAttribute:b.z.string().min(1).max(128),fallbackAttribute:b.z.string().max(128).nullable(),hashVersion:b.z.literal(2),disableStickyBucketing:b.z.boolean(),bucketVersion:b.z.number().int().min(0).max(1e3),minBucketVersion:b.z.number().int().min(0).max(1e3),variations:b.z.array(b.z.strictObject({id:b.z.string().min(1),key:b.z.string().min(1),name:b.z.string().max(80),description:b.z.string().max(500)})).min(2).max(20),phases:b.z.array(Sf).min(1).max(100),releasedVariationId:b.z.string().nullable(),excludeFromPayload:b.z.boolean(),statusSchedule:b.z.strictObject({startAt:b.z.iso.datetime({offset:!0}).nullable(),stopAt:b.z.iso.datetime({offset:!0}).nullable(),stopAfter:b.z.strictObject({value:b.z.number().int().positive().max(36500),unit:b.z.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 xf=_f.safeExtend({filters:b.z.array(Bs).optional()}),If=b.z.strictObject({experiments:b.z.record(b.z.uuid(),xf),savedGroups:Af}),vf=b.z.strictObject({attributeName:b.z.string(),attributeValue:b.z.string(),assignments:b.z.record(b.z.string(),b.z.string())}),Dy=b.z.strictObject({snapshot:If,attributes:At,results:At,stickyBucketAssignmentDocs:b.z.record(b.z.string(),vf)}),Ny=b.z.strictObject({variantKey:b.z.string().nullable(),bucketVersion:b.z.number().int().min(0),source:b.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:b.z.number().min(0).max(1).optional(),stickyBucketUsed:b.z.boolean().optional(),hashUsed:b.z.boolean().optional()});function Fs(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 Pf=Le.z.enum(["active","inactive"]),Cf=Le.z.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),wf=Le.z.strictObject({id:Le.z.string().trim().min(1).max(255),name:Le.z.string().trim().min(1).max(255),status:Pf,metadata:Cf}),By=wf.extend({internal_id:Le.z.uuid(),project_id:Le.z.uuid(),environment_id:Le.z.uuid(),created_at:Le.z.iso.datetime({offset:!0}),updated_at:Le.z.iso.datetime({offset:!0})}),$s=Le.z.union([Le.z.strictObject({id:Le.z.string().trim().min(1).max(255)}),Le.z.strictObject({internalId:Le.z.uuid()})]),Fy=Le.z.enum(["customer","merchandise","context"]),Vy=Le.z.enum(["system","stored","request"]),$y=Le.z.enum(["customer","merchandise","mixed"]),Vs=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Qi(e,t={},r=new Set){if(Fs(e).some(Vs))return!0;for(let n of Wi(e)){if(r.has(n))continue;r.add(n);let i=t[n];if(i?.type==="list"&&Vs(i.attributeKey)||i?.type==="condition"&&Qi(i.condition,t,r))return!0}return!1}var Gs=require("zod"),Of=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,lt=Gs.z.string().max(16).regex(Of,"\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 Qy=D.z.enum(["draft","active","paused","archived"]),Et=D.z.discriminatedUnion("type",[D.z.object({type:D.z.literal("percent"),percentOff:D.z.number().int().min(1).max(100)}).strict(),D.z.object({type:D.z.literal("amount"),amountOffCents:D.z.number().int().min(1).max(1e8),currency:J}).strict()]),tt=D.z.discriminatedUnion("type",[D.z.object({type:D.z.literal("once")}).strict(),D.z.object({type:D.z.literal("repeating"),months:D.z.number().int().min(1).max(36)}).strict(),D.z.object({type:D.z.literal("forever")}).strict()]),Hs=[D.z.object({type:D.z.literal("all")}).strict(),D.z.object({type:D.z.literal("plans"),planIds:D.z.array(D.z.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],Ef=D.z.discriminatedUnion("type",[...Hs,D.z.strictObject({type:D.z.literal("merchandise"),scope:D.z.discriminatedUnion("type",[D.z.strictObject({type:D.z.literal("all")}),D.z.strictObject({type:D.z.literal("selected"),merchandiseIds:D.z.array(D.z.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),D.z.strictObject({type:D.z.literal("condition"),condition:ut})])})]),Yi=D.z.discriminatedUnion("type",[...Hs,D.z.strictObject({type:D.z.literal("merchandise"),scope:D.z.strictObject({type:D.z.enum(["all","selected","condition"])})})]),jf=D.z.strictObject({firstPurchaseOnly:D.z.boolean(),condition:ut}),Yy=D.z.object({name:D.z.string().trim().min(1).max(80),description:D.z.string().max(500),discount:Et,duration:tt,appliesTo:Ef,eligibility:jf,selfClaimEnabled:D.z.boolean().default(!1),startsAt:D.z.iso.datetime().nullable(),endsAt:D.z.iso.datetime().nullable(),totalLimit:D.z.number().int().min(1).max(1e6).nullable(),perCustomerLimit:D.z.number().int().min(1).max(10),grantWindowHours:D.z.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=>!Qi(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"]}),Xy=D.z.object({code:D.z.string().trim().transform(e=>e.toUpperCase()).pipe(D.z.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:D.z.number().int().min(1).max(1e6).nullable(),expiresAt:D.z.iso.datetime().nullable(),firstPurchaseOnly:D.z.boolean(),minimumAmountCents:D.z.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:J.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Xi=D.z.object({id:D.z.uuid(),couponId:D.z.uuid(),status:D.z.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:D.z.iso.datetime(),expiresAt:D.z.iso.datetime(),coupon:D.z.object({name:D.z.string(),discount:Et,duration:tt,appliesTo:Yi}).strict()}).strict(),Ks=D.z.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var ve=require("zod"),Je=ve.z.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),Z=ve.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),Rn=ve.z.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=Z.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Ws=ve.z.string().min(1).max(64),$t=ve.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Zs=ve.z.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),Ne=ve.z.record(Ws,ve.z.union([ve.z.string().max(120),ve.z.number().finite(),ve.z.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)]))),Qs=ve.z.record(Ws,ve.z.union([ve.z.string().max(120),ve.z.number().finite(),ve.z.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),ur=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},Ys=ve.z.array(ve.z.object({upTo:Ji.nullable(),cost:Z}).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&&ur(t.upTo)>ur(n))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),Tf=ve.z.object({key:Zs,match:Qs,priority:ve.z.number().int().default(0),cost:Z.optional(),tiers:Ys.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),Rf=ve.z.object({key:Zs,match:Qs,factor:Ji.optional(),add:Rn.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"})),kf=ve.z.object({units:Ji.default("1"),cost:Z,tiers:Ys.optional(),dimensions:ve.z.array(Tf).max(12).optional(),multipliers:ve.z.array(Rf).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=ur(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(Pe=>Object.keys(ie.match).some(Me=>Pe.match[Me]!==void 0&&Pe.match[Me]!==ie.match[Me]))))continue;let p=ur(a),A=BigInt("1"),v=BigInt("0");for(let[ie,q]of n.entries())c&1<<ie&&(p*=ur(q.factor??"1"),A*=BigInt("1000000"),v+=ur(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"})}}),zy=kf.safeExtend({featureKey:$t});var tc=u.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),zi=u.z.string().regex(/^(0|[1-9]\d{0,14})$/),lr=u.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Df=u.z.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),kr=Df,It=Z.refine(e=>/[1-9]/.test(e)),Qe=u.z.iso.datetime({offset:!0}),Gt=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"))},Nf=u.z.array(u.z.object({upTo:It.nullable(),unitAmountMinor:tc,flatAmountMinor:u.z.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&&Gt(t.upTo)>Gt(n))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Mf=u.z.discriminatedUnion("kind",[u.z.object({kind:u.z.literal("flat"),units:It,unitAmountMinor:tc}).strict(),u.z.object({kind:u.z.enum(["graduated","volume"]),units:It,tiers:Nf}).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"),Uf=u.z.strictObject({interval:u.z.enum(["month","year"]),count:u.z.number().int().min(1).max(12),anchor:u.z.enum(["membership","calendar"])}),jt=u.z.object({currency:J,pricing:Mf,billingCycle:Uf.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");function rc(e){return e.pricing.kind==="flat"&&Gt(e.pricing.units)>0n&&Gt(e.pricing.unitAmountMinor)===Gt(e.pricing.units)*BigInt(10**ko(e.currency))}var Xs={requestId:u.z.uuid(),productVersionId:u.z.uuid(),internal_feature_id:u.z.uuid(),currency:J},nc=u.z.strictObject({interval:u.z.enum(["hour","day","week","month"]),intervalCount:u.z.number().int().min(1).max(12),limit:u.z.number().int().min(1).max(1e6)}),ic=u.z.discriminatedUnion("kind",[u.z.object({...Xs,kind:u.z.literal("auto_topup"),threshold:Rn,quantity:It.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:nc.optional()}).strict(),u.z.object({...Xs,kind:u.z.literal("postpaid"),maxAmountMinorPerPeriod:kr,maxOutstandingMinor:kr}).strict()]),Js={productVersionId:u.z.uuid(),internal_feature_id:u.z.uuid(),currency:J},ac=u.z.discriminatedUnion("kind",[u.z.object({...Js,kind:u.z.literal("auto_topup"),threshold:Rn,quantity:It.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:nc.optional(),purchaseAmountMinor:kr,purchaseUnits:It}).strict(),u.z.object({...Js,kind:u.z.literal("postpaid"),maxAmountMinorPerPeriod:kr,maxOutstandingMinor:kr,cashPrice:jt}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),kn=u.z.object({id:u.z.uuid(),terms:ac,status:u.z.enum(["prepared","active","revoked","blocked"]),createdAt:Qe,acceptedAt:Qe.nullable(),effectiveAt:Qe.nullable(),revokedAt:Qe.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"),oc=u.z.object({authorizationId:u.z.uuid(),terms:ac,setupUrl:u.z.url().nullable()}).strict(),sc=u.z.object({authorizationId:u.z.uuid(),accepted:u.z.literal(!0)}).strict(),cc=u.z.object({authorizationId:u.z.uuid(),requestId:u.z.uuid()}).strict(),uc=u.z.object({internal_feature_id:u.z.uuid(),entityId:u.z.uuid().nullable(),interval:u.z.enum(["day","week","month","year"]),anchor:u.z.enum(["billing_cycle","utc"]).optional(),basis:u.z.enum(["usage","credits"]),filter:Ne.optional(),limit:Z.nullable(),thresholds:u.z.array(u.z.number().positive().max(1)).max(8),includedThresholds:u.z.array(u.z.number().positive().max(1)).max(8).optional(),absoluteThresholds:u.z.array(It).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&&Gt(t)>Gt(i)}),"Notification thresholds must increase"),qf=uc.safeExtend({requestId:u.z.uuid()}),zs={control:u.z.literal("overage"),requestId:u.z.uuid(),internal_feature_id:u.z.uuid(),entityId:u.z.uuid().nullable()},Lf=u.z.discriminatedUnion("action",[u.z.strictObject({...zs,action:u.z.literal("set"),allowed:u.z.boolean().nullable(),overageLimit:Z.nullable(),skipOverageBilling:u.z.boolean()}),u.z.strictObject({...zs,action:u.z.literal("remove")})]),lc=u.z.union([qf,Lf]),Bf=u.z.strictObject({internal_feature_id:u.z.uuid(),entityId:u.z.uuid().nullable(),allowed:u.z.boolean().nullable(),overageLimit:Z.nullable(),skipOverageBilling:u.z.boolean(),interval:u.z.enum(["day","week","month","year"]),startsAt:Qe,endsAt:Qe,used:u.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:u.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:u.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Ff=u.z.object({internal_feature_id:u.z.uuid(),entityId:u.z.uuid().nullable(),interval:u.z.enum(["day","week","month","year"]),anchor:u.z.enum(["billing_cycle","utc"]).optional(),basis:u.z.enum(["usage","credits"]),filter:Ne.optional(),startsAt:Qe,endsAt:Qe,used:Je,reserved:Je,limit:Z.nullable(),thresholds:u.z.array(u.z.number().positive().max(1)).max(8),notifiedThresholds:u.z.array(u.z.number().positive().max(1)).max(1024),includedThresholds:u.z.array(u.z.number().positive().max(1)).max(8).optional(),includedAllowance:u.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:u.z.array(u.z.number().positive().max(1)).max(1024).optional(),absoluteThresholds:u.z.array(It).max(8).optional(),notifiedAbsoluteThresholds:u.z.array(It).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||Z.safeParse(e.used).success&&Z.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Vf=u.z.object({authorizationId:u.z.uuid(),status:u.z.enum(["idle","pending","blocked"]),taskId:u.z.uuid().nullable(),invoiceId:u.z.uuid().nullable(),hostedInvoiceUrl:u.z.url().nullable(),purchaseCount:u.z.number().int().nonnegative(),purchaseWindowEndsAt:Qe.nullable(),attemptCount:u.z.number().int().nonnegative(),failedAttemptCount:u.z.number().int().nonnegative(),suspendedAt:Qe.nullable(),nextAttemptAt:Qe.nullable(),failureReason:u.z.string().min(1).max(240).nullable()}).strict(),dc=u.z.object({internal_feature_id:u.z.uuid().optional(),entityId:u.z.uuid().optional()}).strict(),ea=u.z.object({authorizations:u.z.array(kn).max(100),limits:u.z.array(uc).max(100),overages:u.z.array(Bf).max(100).optional(),windows:u.z.array(Ff).max(200),autoTopups:u.z.array(Vf).max(100),limited:u.z.boolean()}).strict(),$f=u.z.object({id:u.z.uuid(),internal_feature_id:u.z.uuid(),productVersionId:u.z.uuid(),authorizationId:u.z.uuid(),entityId:u.z.uuid().nullable(),units:Z,amountMinor:lr,cashPrice:jt}).strict(),Dr=u.z.object({id:u.z.uuid(),sourceKind:u.z.enum(["product","usage","manual"]),providerInvoiceId:u.z.string().min(1).max(240).nullable(),status:u.z.enum(["accruing","open","pending","paid","failed","void"]),currency:J,startsAt:Qe.nullable(),endsAt:Qe.nullable(),amountMinor:u.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:u.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:zi,paidAmountMinor:zi,refundedAmountMinor:zi,createdAt:Qe,hostedInvoiceUrl:u.z.url().nullable(),adjustment:u.z.object({originalInvoiceId:u.z.uuid(),amountMinor:u.z.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:Qe.nullable()}).strict().nullable(),lines:u.z.array($f).max(100),linesLimited:u.z.boolean()}).strict(),mc=u.z.object({invoiceId:u.z.uuid(),accepted:u.z.literal(!0)}).strict(),pc=u.z.object({after:u.z.uuid().nullable(),limit:u.z.number().int().min(1).max(100)}).strict(),fc=u.z.object({rows:u.z.array(Dr).max(100),nextCursor:u.z.uuid().nullable()}).strict(),ec=u.z.strictObject({id:u.z.string(),coupon:u.z.string(),start:u.z.number().nonnegative(),end:u.z.number().nullable()}),Gf=u.z.strictObject({subscriptionId:u.z.string(),customerId:u.z.string(),accountId:u.z.string(),sourceItems:u.z.array(u.z.strictObject({id:u.z.string(),price_id:u.z.string(),quantity:u.z.number().int(),discounts:u.z.array(ec).optional()})).max(100),items:u.z.array(u.z.strictObject({id:u.z.string(),price:u.z.string(),quantity:u.z.number().int(),discounts:u.z.array(u.z.strictObject({coupon:u.z.string().optional(),terms:u.z.strictObject({id:u.z.string(),name:u.z.string().optional(),percent_off:u.z.number().optional(),amount_off:u.z.number().optional(),currency:u.z.string().optional(),duration:u.z.enum(["once","forever","repeating"]),duration_in_months:u.z.number().optional()}).optional(),discount:u.z.string().optional(),receipt:ec.optional()})).max(20)})).max(100)}),hc=u.z.strictObject({membershipId:u.z.uuid(),requestId:u.z.uuid(),grantIds:u.z.array(u.z.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Ac=u.z.strictObject({membershipId:u.z.uuid(),operationId:u.z.uuid(),status:u.z.enum(["pending","effective"]),execution:Gf.nullable(),grants:u.z.array(u.z.strictObject({id:u.z.uuid(),couponId:u.z.uuid(),name:u.z.string(),discount:Et,duration:tt,startedAt:Qe.nullable()})).max(20)});var dr=require("zod");var Nr=dr.z.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Mr=dr.z.number().int().min(1).max(1e3),Ht=dr.z.object({cap:Z.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:dr.z.number().positive().max(1e4).nullable(),cycles:dr.z.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var ta={key:Ft,name:C.z.string().trim().min(1).max(80),description:C.z.string().trim().max(240)},gc=Z.refine(e=>/[1-9]/.test(e)),Dn=C.z.array(C.z.object({currency:J,amountMinor:C.z.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"),ra=C.z.strictObject({units:gc,prices:C.z.array(C.z.strictObject({currency:J,amountMinor:C.z.number().int().min(0).max(1e8),pricing:Rr.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.z.number().int().min(0).max(1e4),maximumQuantity:C.z.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&&Hi({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"),Hf=C.z.discriminatedUnion("kind",[C.z.object({kind:C.z.literal("access"),internal_feature_id:C.z.uuid()}).strict(),C.z.object({kind:C.z.literal("metered"),internal_feature_id:C.z.uuid(),usageUnit:C.z.enum(["count","micro_usd"]),amount:Z.nullable(),reset:Nr,resetCount:Mr,pooled:C.z.boolean(),rollover:Ht.nullable().optional(),cashPrice:jt.nullable().optional(),prepaidPrice:ra.optional(),feature_override:Vi.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 ia(e.amount,e.prepaidPrice.units,e.prepaidPrice.maximumQuantity),!0}catch{return!1}},"The maximum purchased allowance must fit the quantity ledger"),C.z.object({kind:C.z.literal("credit"),internal_feature_id:C.z.uuid(),amount:Z,reset:Nr,resetCount:Mr,rollover:Ht.nullable(),pooled:C.z.boolean(),feature_override:Vi.nullish(),cashPrice:jt.nullable().optional()}).strict().refine(e=>!e.cashPrice||e.reset!=="lifetime"&&!e.rollover&&!e.pooled&&rc(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")]),na=C.z.array(Hf).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"An entitlement can be granted once per product"),bc=C.z.object({days:C.z.number().int().min(1).max(730),cardRequired:C.z.boolean(),allowances:na}).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"),yc=C.z.object({key:Ft,internal_feature_id:C.z.uuid(),productVersionId:C.z.uuid(),includedQuantity:C.z.number().int().min(0).max(1e4),maximumQuantity:C.z.number().int().min(0).max(1e4),prices:Dn,pooled_internal_feature_ids:C.z.array(C.z.uuid()).max(100),requireAssignment:C.z.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"),Sc=C.z.discriminatedUnion("kind",[C.z.object({...ta,kind:C.z.literal("membership"),groupId:C.z.uuid(),membershipType:C.z.enum(["main","addon"]),interval:C.z.enum(["free","week","month","year","one_time"]),intervalCount:C.z.number().int().min(1).max(156).optional(),prices:Dn,allowances:na,trial:bc.nullable(),licenses:C.z.array(yc).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.z.object({...ta,kind:C.z.literal("topup"),interval:C.z.literal("one_time"),prices:Dn,internal_feature_id:C.z.uuid(),amount:gc,expiresDays:C.z.number().int().min(1).max(3660).nullable()}).strict().refine(e=>e.prices.every(t=>t.amountMinor>0),"A topup must have a positive price")]),Kf=C.z.object({interval:C.z.enum(["free","week","month","year","one_time"]).optional(),intervalCount:C.z.number().int().min(1).max(156).nullable().optional(),prices:Dn.optional(),allowances:C.z.object({upsert:na,remove:C.z.array(C.z.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:bc.nullable().optional(),licenses:C.z.array(yc).max(20).optional()}).strict(),Wf=C.z.object({...ta,kind:C.z.literal("variant"),baseProductVersionId:C.z.uuid(),overrides:Kf}).strict(),hS=C.z.union([Sc,Wf]),AS=C.z.object({products:C.z.array(C.z.object({id:C.z.uuid(),productId:C.z.string().min(1),name:C.z.string(),kind:C.z.enum(["membership","topup"]),version:C.z.number().int().positive()}).strict()).max(500),limited:C.z.boolean()}).strict(),Zf=Cs.and(C.z.object({internal_id:C.z.uuid(),revision:C.z.number().int().nonnegative(),licenses:C.z.array(Li)})),gS=C.z.strictObject({rows:C.z.array(Zf).max(200),nextCursor:C.z.uuid().nullable()}),bS=C.z.object({groups:C.z.array(C.z.object({id:C.z.uuid(),name:C.z.string(),defaultProductVersionId:C.z.uuid().nullable()}).strict()).max(500),features:qs.shape.features,products:C.z.array(C.z.object({id:C.z.uuid(),productId:C.z.uuid(),version:C.z.number().int().positive(),configuration:Sc,baseProductVersionId:C.z.uuid().nullable()}).strict()).max(500),limited:C.z.boolean()}).strict();function ia(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:"")}var vt=require("zod");var _c=vt.z.strictObject({itemKey:vt.z.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:vt.z.uuid(),includedAmount:vt.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:vt.z.number().int().min(0).max(1e4),terms:ra,pricing:Rr.optional(),unitAmountMinor:vt.z.number().int().min(0).max(1e8),productId:vt.z.string().min(1).max(255).nullable(),priceId:vt.z.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{ia(e.includedAmount,e.terms.units,e.quantity),Tn({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"})}});var N=require("zod");var Kt=Z.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Ur=N.z.string().min(1).max(120),Nn=N.z.enum(["cap","overflow"]),rt=(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"))},qr=e=>{try{return e()}catch{return!1}},Lr=N.z.discriminatedUnion("operation",[N.z.object({operation:N.z.literal("quote"),overageBehavior:Nn.optional(),internal_feature_id:N.z.uuid(),entityId:N.z.uuid().optional(),quantity:Kt,properties:Ne}).strict(),N.z.object({operation:N.z.literal("consume"),overageBehavior:Nn.optional(),occurredAt:N.z.iso.datetime({offset:!0}).optional(),internal_feature_id:N.z.uuid(),entityId:N.z.uuid().optional(),quantity:Z,properties:Ne,idempotencyKey:Ur}).strict(),N.z.object({operation:N.z.literal("reserve"),occurredAt:N.z.iso.datetime({offset:!0}).optional(),internal_feature_id:N.z.uuid(),entityId:N.z.uuid().optional(),quantity:Kt,properties:Ne,idempotencyKey:Ur,expiresInSeconds:N.z.number().int().min(1).max(86400)}).strict(),N.z.object({operation:N.z.literal("confirm"),operationId:N.z.uuid(),quantity:Kt,properties:Ne.optional(),idempotencyKey:Ur}).strict(),N.z.object({operation:N.z.literal("refund"),operationId:N.z.uuid(),quantity:Kt,idempotencyKey:Ur}).strict(),N.z.object({operation:N.z.literal("release"),operationId:N.z.uuid(),idempotencyKey:Ur}).strict()]),aa=N.z.object({internal_credit_feature_id:N.z.uuid().nullable(),internal_metered_feature_id:N.z.uuid(),dimension:N.z.string().min(1).max(64),counterKey:N.z.string().min(1).max(240),cycleStart:N.z.iso.datetime({offset:!0}),unitCost:Z,units:Kt,amount:Je,tier:N.z.number().int().min(1).max(12).nullable()}).strict(),Wt=N.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function xc(e,t){let r=e.reduce((n,i)=>n+rt(i.units,12),0n)-rt(t,12);return e.some(n=>n.funding==="balance")?r>=-100n&&r<=100n:r===0n}var Ic=N.z.discriminatedUnion("funding",[N.z.strictObject({funding:N.z.literal("balance"),sourceId:N.z.uuid(),rolloverId:N.z.uuid().nullable(),units:Wt.refine(e=>/[1-9]/.test(e)),amount:Je}),N.z.strictObject({funding:N.z.literal("unbilled"),units:Wt.refine(e=>/[1-9]/.test(e))}),N.z.object({funding:N.z.literal("prepaid"),sourceId:N.z.uuid(),units:Kt,amount:Je,pricing:N.z.array(aa).min(1).max(12)}).strict().refine(e=>qr(()=>e.pricing.reduce((t,r)=>t+rt(r.units,6),0n)===rt(e.units,6)&&e.pricing.reduce((t,r)=>t+rt(r.amount,12),0n)===rt(e.amount,12)&&e.pricing.every(t=>rt(t.unitCost,6)*rt(t.units,6)===rt(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),N.z.object({funding:N.z.literal("postpaid"),invoiceLineId:N.z.uuid().nullable(),units:Kt,authorizationId:N.z.uuid()}).strict()]),Mn=N.z.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),vc=N.z.object({allowed:N.z.boolean(),internal_feature_id:N.z.uuid(),quantity:Z,requestedQuantity:Z.optional(),overageBehavior:Nn.optional(),reason:Mn.nullable(),allocations:N.z.array(Ic).max(500)}).strict().refine(e=>qr(()=>e.allowed?e.reason===null&&xc(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>qr(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&rt(e.requestedQuantity,6)>=rt(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Br=N.z.object({id:N.z.uuid(),internal_feature_id:N.z.uuid(),kind:N.z.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:N.z.uuid().nullable(),quantity:Z,requestedQuantity:Z.optional(),overageBehavior:Nn.optional(),accepted:N.z.boolean(),reason:N.z.enum([...Mn.options,"expired"]).nullable(),createdAt:N.z.iso.datetime({offset:!0}),reservationStatus:N.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:N.z.iso.datetime({offset:!0}).nullable(),allocations:N.z.array(Ic).max(500)}).strict().refine(e=>qr(()=>e.accepted?e.reason===null&&xc(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>qr(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&rt(e.requestedQuantity,6)>=rt(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");var oe=require("zod");var Zt=oe.z.iso.datetime({offset:!0}),Pc=Z.refine(e=>/[1-9]/.test(e)),Cc=oe.z.strictObject({interval:Nr.exclude(["lifetime"]),count:Mr}),Qf=oe.z.strictObject({action:oe.z.literal("create"),requestId:oe.z.uuid(),internal_feature_id:oe.z.uuid(),entityId:oe.z.uuid().nullable(),amount:Pc.nullable(),expiresAt:Zt.nullable(),reset:Cc.nullable(),rollover:Ht.nullable(),nextResetAt:Zt.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"),wc=oe.z.discriminatedUnion("action",[Qf,oe.z.strictObject({action:oe.z.literal("update"),requestId:oe.z.uuid(),grantId:oe.z.uuid(),revision:oe.z.number().int().nonnegative(),amount:Pc.nullable(),expiresAt:Zt.nullable(),rollover:Ht.nullable(),nextResetAt:Zt.nullable()}),oe.z.strictObject({action:oe.z.enum(["add","subtract","set_remaining"]),requestId:oe.z.uuid(),grantId:oe.z.uuid(),revision:oe.z.number().int().nonnegative(),amount:Z}),oe.z.strictObject({action:oe.z.literal("revoke"),requestId:oe.z.uuid(),grantId:oe.z.uuid(),revision:oe.z.number().int().nonnegative()})]),oa=oe.z.strictObject({id:oe.z.uuid(),internal_feature_id:oe.z.uuid(),entityId:oe.z.uuid().nullable(),amount:Z.nullable(),reset:Cc.nullable(),rollover:Ht.nullable(),nextResetAt:Zt.nullable(),startsAt:Zt,expiresAt:Zt.nullable(),revision:oe.z.number().int().nonnegative(),revoked:oe.z.boolean(),available:Je,held:Je,spent:Je}),Oc=oe.z.strictObject({customerId:oe.z.uuid(),after:oe.z.uuid().nullable(),limit:oe.z.number().int().min(1).max(100)}),Ec=oe.z.strictObject({rows:oe.z.array(oa).max(100),nextCursor:oe.z.uuid().nullable()});var L=require("zod");var gt=L.z.iso.datetime({offset:!0}),jc=L.z.strictObject({invoiceId:L.z.uuid(),after:L.z.string().min(1).max(180).nullable(),limit:L.z.number().int().min(1).max(100)}),Yf=L.z.strictObject({kind:L.z.literal("product"),key:L.z.string(),productVersionId:L.z.uuid(),productName:L.z.string(),itemKey:L.z.string(),entityId:L.z.uuid().nullable(),quantity:L.z.number().int().positive(),subtotalMinor:L.z.string().regex(/^-?\d+$/),discountMinor:L.z.string().regex(/^\d+$/),taxMinor:L.z.string().regex(/^-?\d+$/).nullable(),totalMinor:L.z.string().regex(/^-?\d+$/),startsAt:gt.nullable(),endsAt:gt.nullable(),providerLineId:L.z.string().nullable(),providerItemId:L.z.string()}),Tc=L.z.strictObject({invoice:Dr,items:L.z.array(L.z.discriminatedUnion("kind",[Yf,L.z.strictObject({kind:L.z.literal("invoice_credit"),key:L.z.string(),internal_feature_id:L.z.uuid(),internal_credit_feature_id:L.z.uuid(),name:L.z.string(),units:Z,reserved:Z,amountMinor:lr,grossAmountMinor:lr,creditsAppliedMinor:lr,properties:Ne,cashPrice:jt,providerItemId:L.z.string().nullable(),creditProviderItemId:L.z.string().nullable()}),L.z.strictObject({kind:L.z.literal("usage"),key:L.z.string(),internal_feature_id:L.z.uuid(),name:L.z.string(),units:Z,reserved:Z,amountMinor:lr,cashPrice:jt})])).max(100),nextCursor:L.z.string().min(1).max(180).nullable()}),Xf=L.z.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),sa=L.z.strictObject({from:gt,to:gt,entityId:L.z.uuid().optional(),snapshotAt:gt.nullable(),after:L.z.strictObject({at:gt,id:L.z.uuid(),position:L.z.number().int().nonnegative()}).nullable(),limit:L.z.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"),Rc=L.z.strictObject({customerId:L.z.uuid(),entityId:L.z.uuid().nullable(),from:gt,to:gt,snapshotAt:gt,totals:L.z.array(L.z.strictObject({internal_credit_feature_id:L.z.uuid(),name:L.z.string(),consumed:Je,refunded:Je,net:Xf})).max(1e3),rows:L.z.array(L.z.strictObject({operationId:L.z.uuid(),position:L.z.number().int().nonnegative(),kind:L.z.enum(["consume","confirm","refund"]),originalId:L.z.uuid().nullable(),occurredAt:gt,internal_feature_id:L.z.uuid(),entitlementName:L.z.string(),sourceId:L.z.uuid(),internal_credit_feature_id:L.z.uuid(),creditName:L.z.string(),units:Wt,amount:Je,pricing:L.z.array(aa).max(12),properties:Ne})).max(100),nextCursor:sa.shape.after});var y=require("zod");var ot=require("zod");var Jf=ot.z.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),zf=ot.z.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Un=ot.z.strictObject({internal_feature_id:ot.z.uuid(),entityId:ot.z.uuid().nullable()}),kc=Un.extend({quantity:Z,expectedRevision:ot.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:ot.z.string().min(1).max(120),properties:Ne.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Fr=Un.extend({operationId:ot.z.uuid().nullable(),usage:Z,capacity:Jf.nullable(),remaining:zf.nullable(),withinLimit:ot.z.boolean(),revision:ot.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:ot.z.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 Ye=y.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),dt=y.z.iso.datetime({offset:!0}),eh=y.z.enum(["access","metered","credit"]),Vr={internal_feature_id:y.z.uuid(),key:$t,name:y.z.string().min(1).max(120),kind:eh},Dc=y.z.object({customerId:y.z.uuid(),snapshotAt:dt,memberships:y.z.array(y.z.object({id:y.z.uuid(),productId:y.z.string().min(1).max(255),productVersionId:y.z.uuid(),billingProductVersionId:y.z.uuid(),version:y.z.number().int().positive(),key:y.z.string().min(1).max(64),name:y.z.string().min(1).max(120),groupId:y.z.string().max(255).nullable(),membershipType:y.z.enum(["main","addon"]),status:y.z.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:y.z.boolean(),accessEnabled:y.z.boolean(),renewalChange:y.z.object({productVersionId:y.z.uuid(),name:y.z.string().min(1).max(120),version:y.z.number().int().positive(),effectiveAt:dt,benefitsAppliedAt:dt.nullable(),timing:y.z.enum(["immediate","renewal"]),changeKind:y.z.enum(["plan","seats","quantity"]),feature:y.z.strictObject({internal_feature_id:y.z.uuid(),name:y.z.string().min(1).max(80),fromQuantity:y.z.number().int().min(0).max(1e4),toQuantity:y.z.number().int().min(0).max(1e4)}).optional(),seat:y.z.object({key:y.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:y.z.number().int().min(0).max(1e4),toQuantity:y.z.number().int().min(0).max(1e4)}).strict().nullable(),status:y.z.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.z.object({phase:y.z.enum(["paid","trial"]),startsAt:dt,endsAt:dt.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:y.z.boolean(),balances:y.z.array(y.z.object({...Vr,usageType:y.z.enum(["consumable","non_consumable"]).nullable(),accessible:y.z.boolean(),unlimited:y.z.boolean(),available:Ye,held:Ye,debt:Ye,nextExpiresAt:dt.nullable(),usage:Fr.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.z.boolean()}).strict(),Nc=y.z.enum(["source","usage","transaction","invoice","debt","settlement"]),Mc=y.z.object({at:dt,id:y.z.uuid(),type:Nc}).strict(),Uc=y.z.object({type:Nc.nullable(),resourceKey:$t.optional(),kind:y.z.enum(["purchase","refund"]).optional(),topup:y.z.boolean().optional(),from:y.z.iso.date().nullable(),to:y.z.iso.date().nullable(),after:Mc.nullable(),limit:y.z.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),mr={id:y.z.uuid(),occurredAt:dt},th=y.z.discriminatedUnion("type",[y.z.strictObject({...mr,type:y.z.literal("invoice"),status:y.z.string().min(1).max(80),paid:Ye,refunded:Ye,currency:J,externalId:y.z.string().nullable()}),y.z.object({...mr,...Vr,type:y.z.literal("source"),reason:y.z.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Ye,unlimited:y.z.boolean(),status:y.z.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:dt,expiresAt:dt.nullable(),orderId:y.z.uuid().nullable(),parentSourceId:y.z.uuid().nullable()}).strict(),y.z.object({...mr,type:y.z.literal("usage"),internal_feature_id:y.z.uuid(),name:y.z.string().min(1).max(120),kind:y.z.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:y.z.uuid().nullable(),quantity:Z,accepted:y.z.boolean(),reason:y.z.enum([...Mn.options,"expired"]).nullable(),properties:Ne,reservationStatus:y.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:dt.nullable(),charges:y.z.array(y.z.discriminatedUnion("funding",[y.z.strictObject({funding:y.z.literal("balance"),sourceId:y.z.uuid(),rolloverId:y.z.uuid().nullable(),units:Wt,amount:Ye}),y.z.strictObject({funding:y.z.literal("unbilled"),units:Wt}),y.z.object({...Vr,funding:y.z.literal("prepaid"),amount:Ye}).strict(),y.z.object({funding:y.z.literal("postpaid"),invoiceId:y.z.uuid(),invoiceLineId:y.z.uuid(),authorizationId:y.z.uuid(),units:Z,currency:J}).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.z.object({...mr,type:y.z.literal("transaction"),purpose:y.z.enum(["product","invoice"]),productVersionId:y.z.uuid().nullable(),productName:y.z.string().min(1).max(120).nullable(),productVersion:y.z.number().int().positive().nullable(),invoiceId:y.z.uuid().nullable(),orderId:y.z.uuid(),originalId:y.z.uuid().nullable(),kind:y.z.enum(["purchase","refund"]),amountMinor:y.z.number().int().nonnegative().max(2e8).nullable(),currency:J.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.z.object({...mr,...Vr,type:y.z.literal("debt"),sourceId:y.z.uuid(),transactionId:y.z.uuid(),amount:Ye}).strict(),y.z.object({...mr,...Vr,type:y.z.literal("settlement"),sourceId:y.z.uuid(),debtId:y.z.uuid(),kind:y.z.enum(["payment","usage_refund","payment_return"]),amount:Ye}).strict()]),qc=y.z.object({customerId:y.z.uuid(),rows:y.z.array(th).max(50),nextCursor:Mc.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");var K=require("zod"),Bc=K.z.object({customerId:K.z.uuid()}).strict(),Fc=K.z.discriminatedUnion("action",[K.z.object({customerId:K.z.uuid(),requestId:K.z.uuid(),action:K.z.literal("assign"),poolId:K.z.uuid(),memberCustomerId:K.z.uuid()}).strict(),K.z.strictObject({customerId:K.z.uuid(),requestId:K.z.uuid(),action:K.z.literal("assign_entity"),poolId:K.z.uuid(),entityId:K.z.uuid()}),K.z.object({customerId:K.z.uuid(),requestId:K.z.uuid(),action:K.z.literal("release"),poolId:K.z.uuid(),slotId:K.z.uuid()}).strict()]),$r=K.z.number().int().nonnegative(),ca=K.z.iso.datetime({offset:!0}),ua=K.z.strictObject({internalId:K.z.uuid(),id:K.z.string(),name:K.z.string().nullable(),version:K.z.number().int().positive()}),Lc=K.z.enum(["active","past_due"]),la=K.z.strictObject({customerId:K.z.uuid(),licenses:K.z.array(K.z.strictObject({id:K.z.uuid(),linkId:K.z.uuid(),parent:K.z.strictObject({customerProductId:K.z.uuid(),status:Lc,product:ua}),product:ua,planLicense:K.z.strictObject({id:K.z.uuid(),prepaidOnly:K.z.boolean(),isCustom:K.z.boolean()}).nullable(),granted:$r,included:$r,paidQuantity:$r,usage:$r,remaining:$r,createdAt:ca}).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.z.array(K.z.strictObject({id:K.z.uuid(),linkId:K.z.uuid(),status:Lc,product:ua,entity:K.z.strictObject({internalId:K.z.uuid(),id:K.z.string().nullable(),name:K.z.string().nullable()}).nullable(),beneficiary:K.z.strictObject({internalId:K.z.uuid(),id:K.z.string().nullable(),name:K.z.string().nullable()}).nullable(),startedAt:ca.nullable(),endedAt:ca.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:K.z.boolean()});var Tt=require("zod"),qn=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,pr=Tt.z.object({customerId:Tt.z.uuid(),sessionId:Tt.z.uuid(),accessToken:Tt.z.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Tt.z.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Tt.z.iso.datetime(),refreshExpiresAt:Tt.z.iso.datetime()});var H=require("zod"),Gr=H.z.enum(["email","sms","voice","push"]),FS=H.z.enum(["resend","twilio","fcm","apns"]);var VS=H.z.string().regex(/^\+[1-9]\d{1,14}$/),rh=H.z.enum(["email_recipient","sms_segment","voice_second","push_device"]);var nh=H.z.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),ih=H.z.strictObject({subject:nh,html:H.z.string().min(1).max(131072).optional(),text:H.z.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),ah=H.z.strictObject({body:H.z.string().min(1).max(1600).refine(e=>e.trim().length>0)}),oh=H.z.strictObject({text:H.z.string().trim().min(1).max(4e3),language:H.z.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:H.z.number().int().min(1).max(900)}),sh=H.z.record(H.z.string().min(1).max(64),H.z.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"),ch=H.z.strictObject({title:H.z.string().trim().min(1).max(200),body:H.z.string().trim().min(1).max(2e3),url:H.z.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:sh.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Vc=H.z.discriminatedUnion("channel",[H.z.strictObject({channel:H.z.literal("email"),content:ih}),H.z.strictObject({channel:H.z.literal("sms"),content:ah}),H.z.strictObject({channel:H.z.literal("voice"),content:oh}),H.z.strictObject({channel:H.z.literal("push"),content:ch})]),$c=H.z.strictObject({requestId:H.z.uuid(),customerId:H.z.uuid(),connectionId:H.z.uuid().optional(),message:Vc,expiresAt:H.z.iso.datetime({offset:!0})}),uh=H.z.array(H.z.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),lh=H.z.discriminatedUnion("kind",[H.z.strictObject({kind:H.z.literal("all")}),H.z.strictObject({kind:H.z.literal("customers"),customerIds:uh})]),$S=H.z.strictObject({name:H.z.string().trim().min(1).max(120),connectionId:H.z.uuid().optional(),message:Vc,audience:lh,frequencyLimit:H.z.number().int().min(1).max(100)}),Gc=H.z.strictObject({requestId:H.z.uuid(),channel:Gr,state:H.z.enum(["allowed","denied"]),expectedRevision:H.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Hc=H.z.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Kc=H.z.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),GS=H.z.strictObject({meter:rh,estimatedUnits:H.z.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:H.z.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var ee=require("zod");var Q=require("zod");var xe=require("zod");var Qc=require("zod");var Qt=require("zod"),Wc=Qt.z.enum(["stripe","apple","google"]),Zc=Qt.z.enum(["membership","credit_pack","lifetime"]),KS=Qt.z.enum(["active","grace","suspended","inactive","revoked"]),WS=Qt.z.strictObject({currency:Qt.z.string().regex(/^[A-Z]{3}$/),micros:Qt.z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var fr=Qc.z.object({provider:Wc,currency:J}).strict();var Rt=xe.z.strictObject({internal_feature_id:xe.z.uuid(),quantity:Z.refine(e=>/[1-9]/.test(e)),properties:Ne,entityId:xe.z.uuid().optional()}),Yc=xe.z.strictObject({requirement:Rt,commerce:fr.optional(),paywallId:xe.z.uuid().optional()}),dh=xe.z.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),da=xe.z.strictObject({productId:xe.z.string().min(1),productVersionId:xe.z.string().min(1),name:xe.z.string().min(1).max(120),action:xe.z.enum(["purchase","upgrade","addon","topup"]),membershipId:xe.z.string().min(1).nullable(),currency:J,amountMinor:xe.z.string().regex(/^(0|[1-9]\d{0,8})$/),interval:xe.z.enum(["free","week","month","year","one_time"]),intervalCount:xe.z.number().int().min(1).max(156)}),Yt=xe.z.strictObject({internal_feature_id:xe.z.string().min(1),name:xe.z.string().min(1).max(120),kind:xe.z.enum(["access","metered","credit"]),quantity:Z,allowed:xe.z.boolean(),reason:dh.nullable(),preview:xe.z.strictObject({scenario:xe.z.enum(["feature_flag","usage_limit"]),candidates:xe.z.array(da).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"})}),t0=xe.z.strictObject({paywallId:xe.z.uuid(),requirement:Rt});var ma=Q.z.object({plan:Q.z.string().min(1).max(200).optional(),coupon:Q.z.uuid().optional(),promotionCode:Q.z.uuid().optional(),picker:Q.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Ln=Q.z.object({text:Q.z.string().optional(),label:Q.z.string().optional(),alt:Q.z.string().optional(),html:Q.z.string().max(32768).optional(),price:Q.z.object({current:Q.z.string(),original:Q.z.string().nullable(),period:Q.z.string()}).optional(),code:Q.z.string().optional(),countdownAt:Q.z.iso.datetime().optional(),planId:Q.z.string().min(1).max(200).optional(),planVersionId:Q.z.string().min(1).max(200).optional(),currency:J.optional(),couponId:Q.z.uuid().optional(),offerId:Q.z.uuid().optional(),unavailable:Q.z.boolean().optional(),unavailableReason:Q.z.string().optional(),missing:Q.z.array(Q.z.string()).optional()}).strict(),Bn=Q.z.object({paywall:Yt.optional(),nodes:Q.z.record(Q.z.string(),Q.z.object({base:Ln,picker:Q.z.string().optional(),byPlan:Q.z.record(Q.z.string(),Ln).optional()}).strict()),plans:Q.z.record(Q.z.string(),Q.z.object({id:Q.z.string().min(1).max(200),versionId:Q.z.string().min(1).max(200),available:Q.z.boolean(),name:Q.z.string(),price:Q.z.string(),period:Q.z.string(),currency:J.optional()}).strict()),pickers:Q.z.record(Q.z.string(),Q.z.object({options:Q.z.array(Q.z.string().min(1).max(200)).max(20),selected:Q.z.string().min(1).max(200).nullable()}).strict()),diagnostics:Q.z.array(Q.z.object({nodeId:Q.z.string(),message:Q.z.string()}).strict())}).strict();function Xc(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}var d=require("zod");function mh(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Jc(e){let t={};function r(n){var i;if(mh(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}var bt=require("zod"),zc=bt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Fn=bt.z.strictObject({tiers:bt.z.array(bt.z.strictObject({id:zc,name:bt.z.string().trim().min(1).max(80)})).min(1).max(8),assignments:bt.z.array(bt.z.strictObject({productVersionId:bt.z.string().min(1).max(200),tierId:zc,period:bt.z.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 Vn(e,t){return e.assignments.length===t.length&&e.assignments.every(r=>t.includes(r.productVersionId))}var $=require("zod");var ph=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],eu=$.z.enum(ph),tu=$.z.object({source:eu,layout:$.z.enum(["full","compact"]),resourceKey:$t.optional(),pageSize:$.z.number().int().min(1).max(50),showSources:$.z.boolean(),allowPurchase:$.z.boolean(),outputs:$.z.object({billing_adjustment:$.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:$.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:$.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:$.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:$.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:$.z.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"})}),Be=$.z.string().max(2e3),ru=$.z.object({id:$.z.string().max(100),label:Be,detail:$.z.array(Be).max(12),value:Be.optional(),status:Be.optional(),facts:$.z.array($.z.object({label:Be,value:Be}).strict()).max(1e3),purchaseId:$.z.uuid().optional(),invoiceUrl:$.z.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:$.z.array($.z.strictObject({action:$.z.literal("invoice_open"),label:Be})).max(1).optional(),membershipActions:$.z.array($.z.object({value:$.z.string().max(100),label:Be}).strict()).max(3).optional()}).strict(),fh=$.z.object({key:$t,name:Be,spendable:Be,reserved:Be,available:Be,expiry:Be.nullable(),sources:$.z.array(ru).max(50),sourceCount:$.z.number().int().nonnegative(),sourcePage:$.z.number().int().positive(),hasNextSources:$.z.boolean(),hasPreviousSources:$.z.boolean()}).strict(),hh=$.z.object({source:eu,status:$.z.enum(["idle","loading","ready","error"]),stale:$.z.boolean(),preview:$.z.boolean(),errorCode:$.z.string().max(80).optional(),errorMessage:Be.optional(),resources:$.z.array(fh).max(500),rows:$.z.array(ru).max(50),hasNext:$.z.boolean(),hasPrevious:$.z.boolean(),page:$.z.number().int().positive(),filter:$.z.string().max(40),updatedAt:$.z.iso.datetime().optional(),buyingId:$.z.uuid().optional(),membershipBusy:$.z.boolean().optional(),billingBusy:$.z.boolean().optional(),membershipReview:$.z.object({title:Be,note:Be,facts:$.z.array($.z.object({label:Be,value:Be}).strict()).max(100)}).strict().optional(),membershipResult:Be.optional()}).strict(),u0=$.z.object({nodes:$.z.record($.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),hh)}).strict(),l0=$.z.object({nodeId:$.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:$.z.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:$.z.string().max(100).optional()}).strict();var gh=4,pt={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Kr=d.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),le=d.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),bh=d.z.enum(["none","xs","sm","md","lg","xl"]),yh=d.z.enum(["none","sm","md","lg","full"]),pa=d.z.string().regex(/^#[0-9a-fA-F]{6}$/),au=d.z.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"),fa=d.z.union([au,d.z.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),d.z.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),d.z.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),nu=d.z.object({primary:pa,background:pa,text:pa,radius:yh,font:d.z.enum(["system","serif","rounded","mono"])}).strict(),Wr=d.z.union([d.z.enum(["primary","text","muted","background","surface"]),d.z.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),me=(e,t)=>d.z.number().int().min(e).max(t),iu=d.z.union([d.z.enum(["fit","fill"]),me(1,1200)]),Sh=d.z.object({top:me(0,200),right:me(0,200),bottom:me(0,200),left:me(0,200)}).strict(),_h=d.z.object({top:me(-100,200),right:me(-100,200),bottom:me(-100,200),left:me(-100,200)}).strict(),ou=d.z.object({x:me(0,100),y:me(0,100)}).strict(),xh=d.z.discriminatedUnion("type",[d.z.object({type:d.z.literal("color"),color:Wr}).strict(),d.z.object({type:d.z.literal("linear"),angle:me(0,360),stops:d.z.array(d.z.object({color:Wr,at:me(0,100)}).strict()).min(2).max(4)}).strict(),d.z.object({type:d.z.literal("image"),src:fa,fit:d.z.enum(["cover","contain"]),position:ou.optional()}).strict()]),Ih=d.z.discriminatedUnion("type",[d.z.object({type:d.z.literal("rect"),radius:d.z.union([me(0,200),d.z.object({topLeft:me(0,200),topRight:me(0,200),bottomRight:me(0,200),bottomLeft:me(0,200)}).strict()])}).strict(),d.z.object({type:d.z.literal("pill")}).strict()]),vh=d.z.object({width:me(0,12),color:Wr,style:d.z.enum(["solid","dashed"])}).strict(),Ph=d.z.object({x:me(-40,40),y:me(-40,40),blur:me(0,80),spread:me(-20,40),color:Wr}).strict(),Ch=d.z.object({font:d.z.enum(["system","serif","rounded","mono"]),size:me(8,96),weight:d.z.number().int().min(100).max(900).multipleOf(100),lineHeight:d.z.number().min(.8).max(3),letterSpacing:d.z.number().min(-5).max(20),color:Wr,align:d.z.enum(["start","center","end"]),italic:d.z.boolean(),decoration:d.z.enum(["none","underline","line-through"]),transform:d.z.enum(["none","uppercase"])}).strict().partial(),Xt=d.z.object({width:iu,height:iu,padding:Sh,margin:_h,gap:me(0,120),grow:d.z.union([d.z.boolean(),d.z.number().min(0).max(12)]),background:xh,opacity:d.z.number().min(0).max(1),clipContent:d.z.boolean(),shape:Ih,border:vh,shadow:Ph,text:Ch}).strict().partial(),nt={id:Kr,name:d.z.string().trim().min(1).max(60).optional(),hidden:d.z.boolean().optional(),style:Xt.optional(),fallback:le.optional()},wh=d.z.object({...nt,type:d.z.literal("text"),productField:d.z.enum(["name","price","trial","period"]).optional(),feature:d.z.object({id:d.z.uuid(),field:d.z.enum(["name","allowance"])}).strict().optional(),text:le,variant:d.z.enum(["title","heading","body","caption"])}).strict(),Oh=d.z.object({...nt,type:d.z.literal("image"),src:fa,localizedSrc:d.z.record(lt,fa).optional(),alt:le,aspect:d.z.enum(["auto","1:1","4:3","16:9","3:1"]),fit:d.z.enum(["cover","contain"]),position:ou.optional()}).strict(),Eh=d.z.object({...nt,type:d.z.literal("button"),label:le,variant:d.z.enum(["primary","secondary","link"]),action:le,purpose:d.z.enum(["purchase","navigation","close"]).optional(),bind:ma.optional()}).strict(),jh=d.z.object({...nt,type:d.z.literal("divider")}).strict(),Th=d.z.object({...nt,type:d.z.literal("customer_data"),title:le,data:tu}).strict(),Rh=d.z.object({...nt,type:d.z.literal("spacer"),size:bh}).strict(),kh=d.z.object({...nt,type:d.z.literal("custom_html"),html:d.z.record(lt,d.z.string().max(pt.customHtml)),css:d.z.string().max(pt.customCss)}).strict(),Dh=d.z.object({...nt,type:d.z.literal("price"),fallback:le,parts:d.z.object({current:Xt.optional(),original:Xt.optional(),period:Xt.optional()}).strict().optional()}).strict(),Nh=d.z.object({...nt,type:d.z.literal("coupon_code"),label:le,fallback:le}).strict(),Mh=d.z.object({...nt,type:d.z.literal("countdown"),source:d.z.enum(["offer.ends_at","offer.expires_at","fixed"]),at:d.z.iso.datetime().optional(),granularity:d.z.enum(["day","hour","minute","second"]),expired:le,fallback:le}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Uh=d.z.object({...nt,type:d.z.literal("plan_picker"),label:le,fallback:le,planIds:d.z.array(d.z.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.z.string().min(1).max(200).optional(),grouping:Fn.safeExtend({monthLabel:le,yearLabel:le,unavailableLabel:le}).optional(),states:d.z.object({selected:Xt.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Vn(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),qh=d.z.discriminatedUnion("type",[d.z.object({type:d.z.literal("input"),label:le,keyboard:d.z.enum(["text","email","tel","url"]),maxLength:me(1,500)}).strict(),d.z.object({type:d.z.literal("multiselect"),label:le,min:me(0,50),max:me(1,50)}).strict(),d.z.object({type:d.z.literal("select"),label:le,defaultIndex:me(0,49),purpose:d.z.enum(["option","product","tier"]).optional(),pickerId:Kr.optional(),selectedStyle:Xt.optional()}).strict(),d.z.object({type:d.z.literal("tabs"),label:le,defaultIndex:me(0,49),purpose:d.z.literal("tier").optional()}).strict(),d.z.object({type:d.z.literal("toggle"),label:le,defaultEnabled:d.z.boolean()}).strict(),d.z.object({type:d.z.literal("carousel"),label:le}).strict()]),mt={...nt,type:d.z.literal("stack"),direction:d.z.enum(["vertical","horizontal","overlay"]),align:d.z.enum(["start","center","end","stretch"]),justify:d.z.enum(["start","center","end","between"]),productSlot:d.z.object({index:me(0,19),period:d.z.enum(["month","year"]).optional(),requireBinding:d.z.boolean().optional()}).strict().optional(),interaction:qh.optional(),states:d.z.object({selected:Xt.optional()}).strict().optional(),purpose:d.z.literal("benefits").optional(),purchaseAction:le.optional(),buttonVariant:d.z.enum(["primary","secondary","link"]).optional(),bind:ma.optional()},su=d.z.lazy(()=>d.z.object({...nt,type:mt.type,direction:mt.direction,align:mt.align,justify:mt.justify,children:d.z.array(Lh).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()),Lh=d.z.lazy(()=>d.z.union([su,wh,Oh,Eh,jh,Rh,kh,Dh,Nh,Mh,Uh,Th])),Bh=d.z.union([d.z.string().max(500),d.z.number().finite(),d.z.boolean(),d.z.null()]),Hr={id:le,event:le,properties:d.z.record(le,Bh).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Fh=d.z.discriminatedUnion("type",[d.z.object({...Hr,type:d.z.literal("navigate"),close:d.z.literal(!1),pageId:Kr}).strict(),d.z.object({...Hr,type:d.z.literal("event"),close:d.z.boolean()}).strict(),d.z.object({...Hr,type:d.z.literal("close"),close:d.z.literal(!0)}).strict(),d.z.object({...Hr,type:d.z.literal("open_url"),close:d.z.boolean(),url:au}).strict(),d.z.object({...Hr,type:d.z.literal("claim_offer"),close:d.z.boolean(),couponId:d.z.uuid()}).strict()]),Vh=d.z.object({defaultLocale:lt,locales:d.z.record(lt,d.z.record(le,d.z.string().max(pt.stringLength)))}).strict(),$h=d.z.enum(["popup","paywall","onboarding","page","banner"]);var Gh=d.z.discriminatedUnion("type",[d.z.object({type:d.z.literal("modal"),size:d.z.enum(["sm","md","lg"])}).strict(),d.z.object({type:d.z.literal("sheet"),size:d.z.enum(["sm","md","lg"])}).strict(),d.z.object({type:d.z.literal("fullscreen")}).strict(),d.z.object({type:d.z.literal("inline")}).strict()]);var Hh=d.z.object({kind:d.z.literal("screen"),schemaVersion:d.z.literal(gh),name:d.z.string().trim().min(1).max(80),surface:$h,initialPageId:Kr.optional(),presentation:Gh,theme:nu,pages:d.z.array(d.z.object({id:Kr,name:d.z.string().trim().min(1).max(60),root:su,theme:nu.optional(),editorPosition:d.z.object({x:d.z.number().finite().min(-1e5).max(1e5),y:d.z.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(pt.pages),strings:Vh,actions:d.z.array(Fh).max(pt.actions)}).strict();function st(e,t){for(let r of e.pages)Zr(r.root,t)}var Jt=Hh.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;st(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 ha(e){let t=[],r=new Set;return st(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 Kh(e,t,r){if(t.field==="html"){let n;return st(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(n=i.html[r])}),n}if(t.field==="src"){let n=Zh(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 hr(e){let t=ha(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=>!Kh(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 Wh(e,t){let r=null;return Zr(e,n=>{if(r)return!1;n.id===t&&(r=n)}),r}function Zh(e,t){for(let r of e.pages){let n=Wh(r.root,t);if(n)return n}return null}function Qh(e){let t=Object.values(e.strings.locales).flatMap(r=>Object.values(r));return st(e,r=>{r.type==="custom_html"&&t.push(...Object.values(r.html))}),[...new Set(t.flatMap(Xc))]}function cu(e){return Qh(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function uu(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 kt=ee.z.enum(["page","popup","banner"]),Yh=3e5,lu=ee.z.strictObject({type:ee.z.enum(["string","number","boolean","strings","json"]),nullable:ee.z.boolean()}),Xh=ee.z.strictObject({inputs:ee.z.record(le,lu.extend({required:ee.z.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:ee.z.record(le,lu).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),Jh=ee.z.strictObject({kind:kt,schemaVersion:ee.z.literal(1),name:ee.z.string().trim().min(1).max(80),screen:Jt,contract:Xh}),$n=Jh.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"]),uu(e)>Yh&&r("Content document exceeds its byte budget",[])});function zh(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 eA=$n.superRefine((e,t)=>{for(let r of cu(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&&!zh(i,n)&&t.addIssue({code:"custom",path:["contract","outputs",r.id],message:"Action value differs from its declared type"})}hr(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),du=ee.z.strictObject({id:ee.z.uuid(),kind:kt,projectId:ee.z.uuid(),environmentId:ee.z.uuid(),name:ee.z.string(),revision:ee.z.number().int().nonnegative(),status:ee.z.enum(["draft","published","archived"]),publishedVersionId:ee.z.uuid().nullable(),createdAt:ee.z.iso.datetime({offset:!0}),updatedAt:ee.z.iso.datetime({offset:!0})}),C0=du.extend({draft:$n}),w0=ee.z.strictObject({rows:ee.z.array(du).max(200),nextCursor:ee.z.uuid().nullable()}),Aa=ee.z.strictObject({id:ee.z.uuid(),kind:kt,resourceId:ee.z.uuid(),projectId:ee.z.uuid(),environmentId:ee.z.uuid(),version:ee.z.number().int().positive(),sourceRevision:ee.z.number().int().nonnegative(),document:eA,createdAt:ee.z.iso.datetime({offset:!0})}),O0=Aa.omit({document:!0}),E0=ee.z.discriminatedUnion("action",[ee.z.strictObject({action:ee.z.literal("create"),kind:kt,id:ee.z.uuid(),document:$n}),ee.z.strictObject({action:ee.z.literal("save"),kind:kt,id:ee.z.uuid(),revision:ee.z.number().int().nonnegative(),document:$n}),ee.z.strictObject({action:ee.z.enum(["publish","archive"]),kind:kt,id:ee.z.uuid(),revision:ee.z.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"})});var ga=require("zod"),Ar={funnelId:ga.z.uuid().optional(),funnelVersionId:ga.z.uuid().optional()};var _e=require("zod");var se=require("zod");var ye=require("zod"),R0=ye.z.discriminatedUnion("action",[ye.z.strictObject({action:ye.z.literal("create"),couponId:ye.z.uuid(),productBindingId:ye.z.uuid(),storeOfferId:ye.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:ye.z.enum(["introductory","promotional"])}),ye.z.strictObject({action:ye.z.literal("set_enabled"),id:ye.z.uuid(),revision:ye.z.number().int().nonnegative(),enabled:ye.z.boolean()})]),k0=ye.z.array(ye.z.strictObject({id:ye.z.uuid(),couponId:ye.z.uuid(),productBindingId:ye.z.uuid(),storeOfferId:ye.z.string().min(1).max(255).nullable(),storeOfferType:ye.z.enum(["introductory","promotional"]),enabled:ye.z.boolean(),revision:ye.z.number().int().nonnegative()})).max(500),Gn=ye.z.strictObject({offerKind:ye.z.enum(["none","introductory","promotional"]),offerId:ye.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:ye.z.number().int().min(0).max(1e8),trialDays:ye.z.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"})}),D0=ye.z.record(ye.z.uuid(),Gn).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var ba=se.z.object({type:se.z.literal("native_purchase"),receiptId:se.z.uuid(),orderId:se.z.uuid(),productVersionId:se.z.uuid(),provider:se.z.enum(["apple","google"]),productId:se.z.string().min(1).max(255),productKind:Zc,replacement:se.z.strictObject({sourceOrderId:se.z.uuid(),sourceProductId:se.z.string().min(1).max(255),policy:se.z.enum(["apple_store","google_full_price"]),sourceAccountTokens:se.z.array(se.z.uuid()).max(50)}).nullable(),appAccountToken:se.z.uuid().optional(),obfuscatedAccountId:se.z.string().min(1).max(64).optional(),obfuscatedProfileId:se.z.uuid().optional(),basePlanId:se.z.string().min(1).max(255).optional(),offerId:se.z.string().min(1).max(255).optional(),offerKind:se.z.enum(["none","introductory","promotional"]),currency:J,catalogAmountMinor:se.z.number().int().nonnegative().max(1e8),discountMinor:se.z.number().int().nonnegative().max(1e8),trialDays:se.z.number().int().min(1).max(730).nullable(),seatBundle:se.z.array(se.z.strictObject({key:se.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:se.z.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:se.z.strictObject({offerId:se.z.string().min(1).max(255),keyId:se.z.string().min(1).max(255),nonce:se.z.uuid(),signature:se.z.string().min(1).max(1024),timestamp:se.z.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"})});var s=require("zod");var re=require("zod/v4"),mu=require("zod/v4"),tA=mu.z.registry(),{BillingInterval:pu}=(()=>{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:rA}=(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.z),{withSpecDefault:nA}=(e=>({withSpecDefault:({schema:r,defaultValue:n,description:i})=>(e.add(r,{description:i,default:n}),r)}))(tA),{COMMON:fu}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:iA}={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:aA}=(e=>({COMMON_SET:new Set(e)}))(fu),{hasNoDuplicateCurrencies:hu}={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:Au}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:oA}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(re.z),{Infinite:sA}={Infinite:"inf"},{TierBehavior:cA}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:gu}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:uA}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:lA}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:dA}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:mA}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(re.z),{ApiCreditTierSchema:bu}=(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.z),{VIOLATION_MESSAGES:pA}={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:yu}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(re.z),{ModelMarkupsSchema:fA}=((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.z,yu),{InvoiceUsageEntrySchema:hA}=(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.z),{AttachDiscountSchema:Su}=(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.z),{CustomLineItemSchema:AA}=(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.z),{UnixMsTimestampSchema:gA}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(re.z),{CreateInvoicePreviewLineSchema:bA}=(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.z),{ReissueInvoiceParamsSchema:ya}=(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.z),{InvoiceModeParamsSchema:zt}=(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.z),{InvoiceTemplateSchema:yA}=(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.z),{BasePriceSchema:SA}=((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.z,pu,rA),{CURRENCY_CODES:_A}=((e,t,r)=>({CURRENCY_CODES:[...e,...t.filter(i=>!r.has(i)).sort()]}))(fu,iA,aA),{ApiPriceProcessorsSchema:_u}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(re.z,oA),{AllocatedBillingFieldSchema:xA}=((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.z,uA),{CreditDimensionNameSchema:IA}=((e,t,r)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(r),{message:`Dimension names cannot contain "${r}"`})}))(re.z,lA,dA),{ApiCreditMatchSchema:xu}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(mA),{findCreditTierViolations:vA}=(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}}))(pA),{ApiCreditMultiplierSchema:PA}=((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.z,xu),{ProviderMarkupsSchema:CA}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(re.z,yu),{InvoiceFeatureQuantitySchema:Iu}=((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.z,gu,hA),{CreateInvoicePreviewSchema:Sa}=((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.z,bA),{SUPPORTED_SET:wA}=(e=>({SUPPORTED_SET:new Set(e)}))(_A),{ApiCreditDimensionBaseSchema:OA}=((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.z,xu),{refineGraduatedTiers:vu}=(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"]})}}))(vA),{ApiFeatureMarkupsOverrideSchema:EA}=((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.z,CA,fA),{isValidCurrencyCode:jA}=(e=>({isValidCurrencyCode:r=>!!r&&e.has(r.toLowerCase())}))(wA),{ApiCreditDimensionSchema:TA}=((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.z,OA,bu,vu),{CurrencyCodeSchema:Pu}=((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.z,jA),{AdditionalCurrencyTierSchema:RA}=((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.z,Pu),{ApiCreditSchemaItemBaseSchema:Cu}=((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.z,IA,TA,PA),{ApiFlatCreditSchemaItemSchema:kA}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Cu,re.z),{AdditionalCurrencyPriceSchema:DA}=((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.z,Pu),{AdditionalCurrencyTierArraySchema:NA}=((e,t,r,n)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(r,{message:n})}))(re.z,RA,hu,Au),{ApiGraduatedCreditSchemaItemSchema:MA}=((e,t,r,n)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(r).min(1)}).strict().superRefine(n)}))(Cu,re.z,bu,vu),{AdditionalCurrencyPriceArraySchema:wu}=((e,t,r,n)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(r,{message:n})}))(re.z,DA,hu,Au),{ApiUsageTierWithCurrenciesSchema:UA}=((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.z,sA,NA),{ApiCreditSchemaItemSchema:qA}=((e,t,r)=>({ApiCreditSchemaItemSchema:e.union([t,r])}))(re.z,MA,kA),{BasePriceParamsSchema:LA}=((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."})}))(SA,nA,re.z,wu),{PlanItemPriceParamsSchema:BA}=((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.z,wu,UA,cA,pu,gu,xA),{ApiFeatureOverrideSchema:FA}=((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.z,qA,EA),{InvoiceBasePriceParamsSchema:Ou}=((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()}))(LA,_u),{InvoiceItemPriceParamsSchema:VA}=((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()}))(BA,_u),{InvoiceLicenseQuantitySchema:$A}=((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.z,Ou,Iu),{InvoiceCustomizeItemSchema:GA}=((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.z,VA,FA),{InvoiceCustomizeSchema:HA}=((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.z,Ou,GA),{InvoicePlanParamsSchema:KA}=((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.z,HA,Iu,$A,Su),{CreateInvoiceParamsSchema:gr}=((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.z,KA,AA,Su,gA);var Tu=s.z.strictObject({requestId:s.z.uuid(),predecessorOperationId:s.z.uuid().optional(),invoiceMode:zt.optional(),entityId:s.z.uuid().optional(),billingSubscriptionId:s.z.uuid().optional(),newBillingSubscription:s.z.literal(!0).optional(),offerId:s.z.uuid().optional(),nativeOffer:Gn.optional(),plans:s.z.array(s.z.strictObject({productVersionId:s.z.uuid(),seatQuantities:s.z.record(Ft,s.z.number().int().min(0).max(1e4)).optional(),featureQuantities:s.z.record(s.z.uuid(),s.z.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.z.enum(["stripe","apple","google"]),currency:J}).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"),tr=s.z.strictObject({operationId:s.z.uuid()}),$e=s.z.number().int().min(0).max(1e8),WA=s.z.strictObject({lineId:s.z.uuid(),productVersionId:s.z.uuid(),productName:s.z.string().min(1).max(80),interval:s.z.enum(["free","week","month","year","one_time"]),intervalCount:s.z.number().int().min(1).max(156).optional(),baseAmountMinor:$e,seats:s.z.array(s.z.strictObject({key:Ft,quantity:s.z.number().int().min(0).max(1e4),includedQuantity:s.z.number().int().min(0).max(1e4),maximumQuantity:s.z.number().int().min(0).max(1e4),unitAmountMinor:$e})).max(20),prepaid:s.z.array(_c).max(100).optional(),catalogAmountMinor:$e,trial:s.z.strictObject({days:s.z.number().int().min(1).max(730),cardRequired:s.z.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+Tn({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"),Ru=s.z.string().regex(/^[A-Za-z0-9_-]{1,200}$/),ZA=s.z.strictObject({id:Ru,name:s.z.string().min(1).max(40),percent_off:s.z.number().gt(0).max(100).optional(),amount_off:s.z.number().int().positive().optional(),currency:s.z.string().regex(/^[a-z]{3}$/).optional(),duration:s.z.enum(["once","repeating","forever"]),duration_in_months:s.z.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"),QA=s.z.strictObject({subscriptionId:s.z.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:s.z.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:s.z.array(s.z.strictObject({id:s.z.string(),price_id:s.z.string(),quantity:s.z.number().int().nonnegative(),discounts:s.z.array(s.z.strictObject({id:s.z.string(),coupon:s.z.string(),start:s.z.number(),end:s.z.number().nullable()})).optional()})).min(1).max(100),prorationDate:s.z.number().int().nonnegative(),amountMinor:s.z.number().int().positive(),periodStartMs:s.z.number(),periodEndMs:s.z.number()}),ku=s.z.strictObject({invoiceMode:zt.optional(),append:QA.optional(),provider:s.z.literal("stripe"),executor:s.z.enum(["indiana","merchant"]),accountId:s.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:s.z.enum(["payment","subscription"]),lineItems:s.z.array(s.z.strictObject({price:s.z.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:s.z.number().int().min(1).max(1e4),priceId:s.z.uuid(),productName:s.z.string().min(1).max(80),amountMinor:s.z.number().int().min(0).max(1e8),currency:s.z.string().regex(/^[a-z]{3}$/),interval:s.z.enum(["week","month","year","one_off"]),intervalCount:s.z.number().int().min(1).max(52),slot:s.z.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:s.z.strictObject({mode:s.z.enum(["graduated","volume"]),tiers:s.z.array(s.z.strictObject({upTo:s.z.number().int().min(1).max(1e6).nullable(),unitAmountMinor:s.z.number().int().min(0).max(1e8),flatAmountMinor:s.z.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:s.z.array(s.z.strictObject({coupon:Ru,terms:ZA})).max(1),trialPeriodDays:s.z.number().int().min(1).max(730).nullable(),metadata:s.z.strictObject({grooveCheckoutId:s.z.uuid(),grooveCustomerId:s.z.uuid()}),expiresAt:s.z.iso.datetime({offset:!0})}),Du=s.z.strictObject({operationId:s.z.uuid(),entityId:s.z.uuid().nullable(),billingSubscriptionId:s.z.uuid().nullable(),discount:s.z.strictObject({offerId:s.z.uuid(),couponId:s.z.uuid(),discount:Et,duration:tt,amountMinor:$e,allocations:s.z.array(s.z.strictObject({productVersionId:s.z.uuid(),amountMinor:$e})).min(1).max(20),expiresAt:s.z.iso.datetime({offset:!0})}).nullable(),charge:s.z.strictObject({effectiveAt:s.z.iso.datetime({offset:!0}),periodEndsAt:s.z.iso.datetime({offset:!0}),debitMinor:$e,discountMinor:$e,taxMinor:$e,totalMinor:$e}).nullable(),expiresAt:s.z.iso.datetime({offset:!0}),provider:s.z.enum(["stripe","apple","google"]),nativeOffer:Gn.optional(),currency:J,lines:s.z.array(WA).min(1).max(20),catalogAmountMinor:$e,automaticTax:s.z.boolean(),execution:ku.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"),_a=s.z.strictObject({operationId:s.z.uuid(),orderId:s.z.uuid(),append:s.z.boolean().optional(),invoiceMode:s.z.boolean().optional(),status:s.z.enum(["pending","complete","cancelled","failed"]),executor:s.z.enum(["indiana","merchant"]),checkoutUrl:s.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:ku.nullable(),currency:J,catalogAmountMinor:$e,taxMinor:$e,totalMinor:s.z.number().int().min(0).max(2e8).nullable(),quoteFinalized:s.z.boolean(),nativePurchase:ba.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"),Kn=s.z.strictObject({enabled:s.z.literal(!0),featureIds:s.z.array(s.z.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Nu=s.z.strictObject({requestId:s.z.uuid(),invoiceMode:zt.optional(),membershipId:s.z.uuid(),carryOverBalances:Kn.optional(),carryOverUsages:Kn.optional(),membershipIds:s.z.array(s.z.uuid()).min(1).max(20).optional(),prorationBehavior:s.z.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:s.z.enum(["immediate","renewal","store"]),change:s.z.discriminatedUnion("type",[s.z.strictObject({type:s.z.literal("plan"),productVersionId:s.z.uuid()}),s.z.strictObject({type:s.z.literal("seats"),licenseKey:Ft,quantity:s.z.number().int().min(0).max(1e4)}),s.z.strictObject({type:s.z.literal("quantity"),internal_feature_id:s.z.uuid(),quantity:s.z.number().int().min(0).max(1e4)}),s.z.strictObject({type:s.z.literal("cancel")}),s.z.strictObject({type:s.z.literal("uncancel")}),s.z.strictObject({type:s.z.literal("billing_cycle"),billingCycleAnchor:s.z.union([s.z.literal("now"),s.z.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"),Hn=s.z.string().regex(/^price_[A-Za-z0-9]+$/),Eu=s.z.strictObject({grooveUpdateId:s.z.uuid(),grooveCustomerId:s.z.uuid()}),ju=s.z.strictObject({price:Hn.nullable(),priceId:s.z.uuid().optional(),quantity:s.z.number().int().min(0).max(1e4)}),Mu=s.z.strictObject({provider:s.z.literal("stripe"),invoiceMode:zt.optional(),executor:s.z.enum(["indiana","merchant"]),accountId:s.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:s.z.string().regex(/^sub_[A-Za-z0-9]+$/),action:s.z.enum(["update","cancel","schedule","release"]),update:s.z.strictObject({items:s.z.array(ju).max(20),remove:s.z.array(Hn).max(20),restoreItems:s.z.array(s.z.strictObject({price:Hn,quantity:s.z.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:s.z.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:s.z.number().int().positive().optional(),paymentBehavior:s.z.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:s.z.boolean().optional(),clearCancelAt:s.z.literal(!0).optional(),billingCycleAnchorNow:s.z.literal(!0).optional(),metadata:Eu}).nullable(),cancel:s.z.strictObject({prorate:s.z.literal(!1),invoiceNow:s.z.literal(!1)}).nullable(),schedule:s.z.strictObject({currentItems:s.z.array(s.z.strictObject({price:Hn,quantity:s.z.number().int().min(0).max(1e4)})).max(20),nextItems:s.z.array(ju).min(1).max(20),switchAt:s.z.number().int().positive(),interval:s.z.enum(["week","month","year"]),intervalCount:s.z.number().int().min(1).max(52),resetBillingCycleAnchor:s.z.literal(!0).optional(),metadata:Eu}).nullable(),release:s.z.strictObject({schedule:s.z.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:s.z.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"),xa=s.z.strictObject({carryOverBalances:Kn.optional(),carryOverUsages:Kn.optional(),operationId:s.z.uuid(),membershipId:s.z.uuid(),productVersionId:s.z.uuid(),timing:s.z.enum(["immediate","renewal"]),effectiveAt:s.z.iso.datetime({offset:!0}),expiresAt:s.z.iso.datetime({offset:!0}),currency:J,creditMinor:$e,debitMinor:$e,discountMinor:$e,taxMinor:$e,totalMinor:$e,retainedProductVersionIds:s.z.array(s.z.uuid()).max(19),execution:Mu}),YA=s.z.strictObject({operationId:s.z.uuid(),invoiceMode:s.z.boolean().optional(),membershipId:s.z.uuid(),productVersionId:s.z.uuid(),status:s.z.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:s.z.enum(["immediate","renewal"]),effectiveAt:s.z.iso.datetime({offset:!0}),checkoutUrl:s.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:s.z.enum(["indiana","merchant"]),execution:Mu.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),XA=s.z.strictObject({operationId:s.z.uuid(),membershipId:s.z.uuid(),productVersionId:s.z.uuid(),timing:s.z.literal("store"),effectiveAt:s.z.null(),expiresAt:s.z.iso.datetime({offset:!0}),currency:J,creditMinor:s.z.null(),debitMinor:s.z.null(),discountMinor:s.z.null(),taxMinor:s.z.null(),totalMinor:s.z.null(),retainedProductVersionIds:s.z.array(s.z.uuid()).max(19),store:s.z.strictObject({provider:s.z.enum(["apple","google"]),productId:s.z.string().min(1).max(255),catalogAmountMinor:$e,policy:s.z.enum(["apple_store","google_full_price"])})}),JA=s.z.strictObject({operationId:s.z.uuid(),membershipId:s.z.uuid(),productVersionId:s.z.uuid(),status:s.z.enum(["prepared","pending","effective","cancelled","failed"]),timing:s.z.literal("store"),effectiveAt:s.z.iso.datetime({offset:!0}).nullable(),checkoutUrl:s.z.null(),nativePurchase:ba.nullable()}),Uu=s.z.union([xa,XA]),Ia=s.z.union([YA,JA]),Qr=s.z.number().int().positive().max(2e8),er=s.z.number().int().min(0).max(2e8),qu=s.z.strictObject({requestId:s.z.uuid(),invoiceId:s.z.uuid(),mode:s.z.enum(["full","partial"]),amountMinor:Qr.optional(),entitlementAction:s.z.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),Lu=s.z.strictObject({provider:s.z.literal("stripe"),executor:s.z.enum(["indiana","merchant"]),accountId:s.z.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:s.z.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Qr,currency:s.z.string().regex(/^[a-z]{3}$/),metadata:s.z.strictObject({indianaRefundId:s.z.uuid()}),idempotencyKey:s.z.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:s.z.array(s.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Bu=s.z.strictObject({operationId:s.z.uuid(),invoiceId:s.z.uuid(),providerInvoiceId:s.z.string().regex(/^in_[A-Za-z0-9]+$/),currency:J,paidMinor:er,refundedMinor:er,pendingMinor:er,amountMinor:Qr,mode:s.z.enum(["full","partial"]),entitlementAction:s.z.enum(["retain","revoke"]),revokes:s.z.strictObject({customerProductIds:s.z.array(s.z.uuid()).max(100),subscriptionIds:s.z.array(s.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),execution:Lu,expiresAt:s.z.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"),Wn=s.z.strictObject({operationId:s.z.uuid(),invoiceId:s.z.uuid(),providerInvoiceId:s.z.string().regex(/^in_[A-Za-z0-9]+$/),status:s.z.enum(["quoted","pending","succeeded","failed","expired"]),executor:s.z.enum(["indiana","merchant"]),currency:J,amountMinor:Qr,mode:s.z.enum(["full","partial"]),entitlementAction:s.z.enum(["retain","revoke"]),refundId:s.z.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:Lu.nullable(),failureReason:s.z.string().min(1).max(200).nullable(),createdAt:s.z.iso.datetime({offset:!0}),completedAt:s.z.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"),Z0=s.z.strictObject({invoiceId:s.z.uuid(),currency:J,paidMinor:er,refundedMinor:er,pendingMinor:er,refundableMinor:er,executor:s.z.enum(["indiana","merchant"]).nullable(),canRefund:s.z.boolean(),operations:s.z.array(Wn).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),Q0=s.z.strictObject({requestId:s.z.uuid(),mode:s.z.enum(["full","partial"]),amountMinor:Qr.optional(),entitlementAction:s.z.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 Fu=_e.z.strictObject({requestId:_e.z.uuid(),targets:_e.z.array(_e.z.strictObject({membershipId:_e.z.uuid(),action:_e.z.enum(["cancel","uncancel"]),timing:_e.z.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"),Zn=_e.z.strictObject({batchId:_e.z.uuid()}),zA=_e.z.strictObject({operationId:_e.z.uuid(),membershipIds:_e.z.array(_e.z.uuid()).min(1).max(20),provider:_e.z.enum(["stripe","apple","google"]),action:_e.z.enum(["cancel","uncancel"]),timing:_e.z.enum(["immediate","renewal"]),status:_e.z.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:xa.nullable(),managementUrl:_e.z.url().nullable(),failureCode:_e.z.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Yr=_e.z.strictObject({batchId:_e.z.uuid(),ready:_e.z.boolean(),status:_e.z.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:_e.z.iso.datetime({offset:!0}),acceptedAt:_e.z.iso.datetime({offset:!0}).nullable(),groups:_e.z.array(zA).min(1).max(100)});var ae=require("zod"),eg=ae.z.string().trim().min(1).max(240),va={requestId:ae.z.uuid(),reason:eg},Qn=ae.z.discriminatedUnion("action",[ae.z.strictObject({...va,action:ae.z.literal("start"),productVersionId:ae.z.uuid(),entityId:ae.z.uuid().optional(),days:ae.z.number().int().min(1).max(730).optional()}),ae.z.strictObject({...va,action:ae.z.literal("extend"),membershipId:ae.z.uuid(),days:ae.z.number().int().min(1).max(730)}),ae.z.strictObject({...va,action:ae.z.literal("end"),membershipId:ae.z.uuid()})]),Vu=ae.z.strictObject({operationId:ae.z.uuid()}),$u=ae.z.iso.datetime({offset:!0}),tg=ae.z.strictObject({provider:ae.z.literal("stripe"),executor:ae.z.enum(["indiana","merchant"]),accountId:ae.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:ae.z.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:ae.z.union([ae.z.literal("now"),$u]),prorationBehavior:ae.z.literal("none")}),Pa=ae.z.strictObject({operationId:ae.z.uuid(),action:ae.z.enum(["start","extend","end"]),status:ae.z.enum(["pending","effective"]),managedBy:ae.z.enum(["indiana","stripe"]),membershipIds:ae.z.array(ae.z.uuid()).min(1).max(20),endsAt:$u.nullable(),execution:tg.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"),z0=ae.z.strictObject({groupId:ae.z.uuid(),productVersionId:ae.z.uuid(),enabled:ae.z.boolean()});var ge=require("zod");var Gu=ge.z.strictObject({requestId:ge.z.uuid(),currency:J,makeDefault:ge.z.boolean()}),Hu=ge.z.strictObject({setupId:ge.z.uuid()}),rg=ge.z.strictObject({provider:ge.z.literal("stripe"),executor:ge.z.literal("merchant"),accountId:ge.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:ge.z.literal("setup"),currency:ge.z.string().regex(/^[a-z]{3}$/),customer:ge.z.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:ge.z.uuid(),metadata:ge.z.strictObject({grooveProjectId:ge.z.uuid(),grooveEnvironmentId:ge.z.uuid(),grooveCustomerId:ge.z.uuid(),groovePaymentSetupId:ge.z.uuid()}),setDefaultPaymentMethod:ge.z.boolean(),expiresAt:ge.z.iso.datetime({offset:!0})}),Ca=ge.z.strictObject({id:ge.z.uuid(),provider:ge.z.literal("stripe"),status:ge.z.enum(["prepared","complete","expired"]),currency:J,makeDefault:ge.z.boolean(),url:ge.z.url().nullable(),createdAt:ge.z.iso.datetime({offset:!0}),expiresAt:ge.z.iso.datetime({offset:!0}),completedAt:ge.z.iso.datetime({offset:!0}).nullable(),execution:rg.nullable()});var Fe=require("zod"),Ku=Fe.z.union([Fe.z.string(),Fe.z.number(),Fe.z.boolean(),Fe.z.null()]),Wu=Fe.z.strictObject({customerId:Fe.z.uuid()}),Zu=Fe.z.strictObject({customerId:Fe.z.uuid(),provider:Fe.z.literal("stripe"),checkedAt:Fe.z.iso.datetime({offset:!0}),status:Fe.z.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Fe.z.number().int().nonnegative(),differences:Fe.z.array(Fe.z.strictObject({subscriptionId:Fe.z.string().startsWith("sub_"),itemId:Fe.z.string().nullable(),field:Fe.z.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Ku,actual:Ku})).max(1e4)});var z=require("zod");var Yn=z.z.iso.datetime({offset:!0}),Xn=z.z.strictObject({createdAt:Yn,id:z.z.uuid()}),Jn=z.z.strictObject({customerId:z.z.uuid().optional(),entityId:z.z.uuid().optional(),productId:z.z.string().min(1).max(256).optional(),provider:z.z.enum(["stripe","apple","google","free"]).optional(),status:z.z.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Xn.optional(),limit:z.z.number().int().min(1).max(100).optional()}),wa={id:z.z.uuid(),customerId:z.z.uuid(),entityId:z.z.uuid().nullable(),productId:z.z.string().min(1).max(256),productVersionId:z.z.uuid(),name:z.z.string().min(1).max(120),provider:z.z.enum(["stripe","apple","google","free"]),createdAt:Yn},ng=z.z.strictObject({...wa,status:z.z.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:z.z.boolean(),billingSubscriptionId:z.z.uuid().nullable()}),ig=z.z.strictObject({...wa,status:z.z.enum(["active","ended","refunded"]),orderId:z.z.uuid().nullable(),transactionId:z.z.uuid().nullable(),currency:J.nullable(),amountMinor:z.z.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),ag=z.z.strictObject({...wa,status:z.z.enum(["blocked","resolved"]),conflict:z.z.strictObject({detectedAt:Yn,blockingMembershipIds:z.z.array(z.z.uuid()).min(1).max(100),transactionId:z.z.uuid()}),resolvedAt:Yn.nullable()}),Qu=Jn.extend({status:z.z.enum(["blocked","resolved"]).optional()}),Yu=z.z.strictObject({customerId:z.z.uuid(),orderId:z.z.uuid()}),Xu=z.z.strictObject({orderId:z.z.uuid(),status:z.z.enum(["blocked","resolved"])}),Ju=z.z.strictObject({items:z.z.array(ng).max(100),nextCursor:Xn.nullable()}),zu=z.z.strictObject({items:z.z.array(ig).max(100),nextCursor:Xn.nullable()}),el=z.z.strictObject({items:z.z.array(ag).max(100),nextCursor:Xn.nullable()});var Se=require("zod");var tl=Se.z.union([Se.z.strictObject({intent:Se.z.literal("read"),requestId:Se.z.uuid(),purchaseIntentId:Se.z.uuid()}),Se.z.strictObject({requestId:Se.z.uuid(),provider:Se.z.literal("apple"),purchaseIntentId:Se.z.uuid(),productId:Se.z.string().min(1).max(255).optional(),signedTransaction:Se.z.string().min(1).max(131072)}),Se.z.strictObject({requestId:Se.z.uuid(),provider:Se.z.literal("google"),purchaseIntentId:Se.z.uuid(),productId:Se.z.string().min(1).max(255).optional(),purchaseToken:Se.z.string().min(1).max(16384)})]),rl=Se.z.strictObject({requestId:Se.z.uuid(),orderId:Se.z.uuid(),purchaseIntentId:Se.z.uuid(),status:Se.z.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:J,refunded:Se.z.boolean(),completion:Se.z.strictObject({transactionIds:Se.z.array(Se.z.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Se.z.boolean()}).nullable()});var w=require("zod"),Ea=w.z.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),og=w.z.record(w.z.string(),w.z.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),sg=3,Xr=20,cg=sg*Xr,Oa=w.z.strictObject({type:w.z.literal("product"),productId:Ea}),nl={type:w.z.literal("group"),key:w.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:w.z.string().trim().min(1).max(80)},ug=w.z.discriminatedUnion("type",[Oa,w.z.strictObject({...nl,items:w.z.array(Oa).max(Xr)})]),lg=w.z.discriminatedUnion("type",[Oa,w.z.strictObject({...nl,items:w.z.array(ug).max(Xr)})]),dg=w.z.array(lg).max(Xr).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>Xr||i>cg)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function ja(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:ja(t))}var br=w.z.strictObject({lookupKey:w.z.string().trim().min(1).max(200),displayName:w.z.string().trim().min(1).max(1500),items:dg,metadata:og}),mg=w.z.strictObject({product:w.z.record(w.z.string(),w.z.json()),prices:w.z.array(w.z.record(w.z.string(),w.z.json())),entitlements:w.z.array(w.z.record(w.z.string(),w.z.json())),freeTrials:w.z.array(w.z.record(w.z.string(),w.z.json())),licenses:w.z.array(w.z.record(w.z.string(),w.z.json()))}),il=br.extend({id:w.z.uuid(),projectId:w.z.uuid(),environmentId:w.z.uuid(),state:w.z.enum(["active","archived"]),isCurrent:w.z.boolean(),revision:w.z.number().int().nonnegative(),publishedVersionId:w.z.uuid().nullable(),createdAt:w.z.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"})}),al=w.z.strictObject({id:w.z.uuid(),offeringId:w.z.uuid(),projectId:w.z.uuid(),environmentId:w.z.uuid(),version:w.z.number().int().positive(),document:br,productEvidence:w.z.record(Ea,mg),createdAt:w.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{let r=ja(e.document);(!r.length||hg(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"})}),pg=w.z.strictObject({rows:w.z.array(il).max(200),versions:w.z.array(al).max(500)}),c_=w.z.discriminatedUnion("action",[w.z.strictObject({action:w.z.literal("create"),document:br}),w.z.strictObject({action:w.z.literal("save"),id:w.z.uuid(),revision:w.z.number().int().nonnegative(),document:br}),w.z.strictObject({action:w.z.enum(["publish","set_current","archive","restore"]),id:w.z.uuid(),revision:w.z.number().int().nonnegative()})]),u_=w.z.strictObject({record:il,version:al.nullable()}),ol=w.z.discriminatedUnion("type",[w.z.strictObject({type:w.z.literal("current")}),w.z.strictObject({type:w.z.literal("id"),id:w.z.uuid()}),w.z.strictObject({type:w.z.literal("lookup_key"),lookupKey:w.z.string().min(1).max(200)}),w.z.strictObject({type:w.z.literal("version"),versionId:w.z.uuid()})]),fg=w.z.strictObject({internalId:Ea,id:w.z.string(),name:w.z.string().nullable(),version:w.z.number().int().positive(),archived:w.z.boolean()}),l_=pg.extend({products:w.z.array(fg).max(500)});function hg(e){let t=[];ja(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}var Jr=require("zod");var sl=Jr.z.strictObject({id:Jr.z.uuid(),offeringId:Jr.z.uuid(),version:Jr.z.number().int().positive(),document:br});var ke=require("zod");var W=require("zod");var rr=require("zod");var zn=rr.z.strictObject({items:rr.z.array(rr.z.strictObject({productVersionId:rr.z.string().min(1).max(200),label:rr.z.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:rr.z.string().min(1).max(200).nullable(),grouping:Fn.optional()});var Re=require("zod"),Ag=Re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ei=Re.z.discriminatedUnion("type",[Re.z.object({type:Re.z.literal("fixed"),productVersionId:Re.z.string().min(1).max(200)}).strict(),Re.z.object({type:Re.z.literal("picker"),pickerId:Ag,allowedProductVersionIds:Re.z.array(Re.z.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")]),zr=Re.z.discriminatedUnion("type",[Re.z.object({type:Re.z.literal("modal"),size:Re.z.enum(["sm","md","lg"])}).strict(),Re.z.object({type:Re.z.literal("sheet"),size:Re.z.enum(["sm","md","lg"])}).strict(),Re.z.object({type:Re.z.literal("fullscreen")}).strict(),Re.z.object({type:Re.z.literal("inline")}).strict()]);var Ta=W.z.discriminatedUnion("type",[W.z.strictObject({type:W.z.literal("event"),event:W.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),W.z.strictObject({type:W.z.literal("open_url"),url:W.z.url().refine(e=>new URL(e).protocol==="https:")})]),gg=Jt,bg=W.z.discriminatedUnion("type",[W.z.object({type:W.z.literal("checkout"),product:ei}).strict(),W.z.object({type:W.z.literal("close")}).strict(),W.z.object({type:W.z.literal("action"),action:Ta}).strict()]),yr=W.z.object({schemaVersion:W.z.literal(3),kind:W.z.literal("paywall"),name:W.z.string().trim().min(1).max(80),presentation:zr,requirement:Rt.optional(),products:zn,offeringVersionId:W.z.uuid().nullable(),offeringId:W.z.uuid(),screen:gg,buttons:W.z.record(W.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),bg)}).strict(),I_=yr.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 Sg(e))t.addIssue({code:"custom",message:n});for(let n of yg(e))t.addIssue({code:"custom",message:n});hr(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 yg(e){let t=e.products.items.map(o=>o.productVersionId),r=Jc(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&&(!Vn(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")),st(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"),st(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 Sg(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 cl=W.z.object({id:W.z.uuid(),projectId:W.z.uuid(),environmentId:W.z.uuid(),revision:W.z.number().int().nonnegative(),state:W.z.enum(["active","archived"]),publishedVersionId:W.z.uuid().nullable(),updatedAt:W.z.iso.datetime({offset:!0}),draft:yr}).strict(),v_=W.z.object({rows:W.z.array(cl).max(200),nextCursor:W.z.uuid().nullable()}).strict(),P_=cl.omit({draft:!0}).extend({name:W.z.string(),productCount:W.z.number().int().nonnegative()}).strict(),C_=W.z.discriminatedUnion("action",[W.z.object({action:W.z.literal("save"),id:W.z.uuid().nullable(),revision:W.z.number().int().nonnegative(),document:yr}).strict(),W.z.object({action:W.z.enum(["publish","archive"]),id:W.z.uuid(),revision:W.z.number().int().nonnegative()}).strict()]),w_=W.z.object({paywalls:W.z.array(W.z.object({id:W.z.uuid(),paywallId:W.z.uuid(),version:W.z.number().int().positive(),name:W.z.string().min(1).max(80),presentation:zr,buttons:yr.shape.buttons}).strict()).max(500),limited:W.z.boolean()}).strict();var ne=require("zod");var He=require("zod");var Sr=He.z.string().regex(/^[a-f0-9]{64}$/),_g=Ln.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),T_=He.z.strictObject({couponDigests:He.z.record(He.z.uuid(),Sr),variables:He.z.record(lt,He.z.record(He.z.uuid(),He.z.partialRecord(He.z.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),He.z.string()))),locales:He.z.record(lt,Bn.extend({nodes:He.z.record(He.z.string(),He.z.strictObject({base:_g})),plans:He.z.object({}).strict(),pickers:He.z.object({}).strict()}).omit({paywall:!0}))});var ce=require("zod");var en=require("zod"),Ra=en.z.strictObject({eventsEnabled:en.z.boolean(),experimentViewsEnabled:en.z.boolean(),featureUsageEnabled:en.z.boolean()}),k_=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});var O=require("zod");var ka=O.z.tuple([O.z.number().min(0).max(1),O.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),xg=O.z.strictObject({attribute:O.z.string().optional(),seed:O.z.string(),hashVersion:O.z.literal(2),ranges:O.z.array(ka).max(100)}),Ig=O.z.strictObject({id:O.z.string().min(1).max(255),condition:ut,gate:O.z.boolean().optional()}),vg=O.z.strictObject({key:O.z.string().optional(),name:O.z.string().optional(),passthrough:O.z.boolean().optional()}),ul={condition:ut.optional(),parentConditions:O.z.array(Ig).max(100).optional(),weights:O.z.array(O.z.number().min(0).max(1)).max(20).optional(),coverage:O.z.number().min(0).max(1).optional(),hashAttribute:O.z.string().optional(),fallbackAttribute:O.z.string().optional(),hashVersion:O.z.literal(2).optional(),disableStickyBucketing:O.z.boolean().optional(),bucketVersion:O.z.number().int().nonnegative().optional(),minBucketVersion:O.z.number().int().nonnegative().optional(),filters:O.z.array(xg).max(100).optional(),ranges:O.z.array(ka).max(20).optional(),meta:O.z.array(vg).max(20).optional(),seed:O.z.string().optional(),name:O.z.string().optional(),phase:O.z.string().optional()},ll=O.z.strictObject({...ul,key:O.z.string().min(1).max(255),variations:O.z.tuple([Ze,Ze]).rest(Ze).refine(e=>e.length<=20),urlPatterns:O.z.array(O.z.strictObject({include:O.z.boolean(),type:O.z.enum(["regex","simple"]),pattern:O.z.string()})).max(100).optional(),force:O.z.number().int().nonnegative().optional(),active:O.z.boolean().optional(),persistQueryString:O.z.boolean().optional()}),Da=O.z.strictObject({value:Ze,variationId:O.z.number().int(),key:O.z.string(),name:O.z.string().optional(),bucket:O.z.number().optional(),passthrough:O.z.boolean().optional(),inExperiment:O.z.boolean(),hashUsed:O.z.boolean().optional(),hashAttribute:O.z.string(),hashValue:O.z.string(),featureId:O.z.string().nullable(),stickyBucketUsed:O.z.boolean().optional()}),Pg=O.z.strictObject({...ul,id:O.z.string().max(255).optional(),force:Ze.optional(),variations:O.z.array(Ze).min(2).max(20).optional(),key:O.z.string().optional(),range:ka.optional(),tracks:O.z.array(O.z.strictObject({experiment:ll,result:Da})).max(100).optional()}),Cg=O.z.strictObject({defaultValue:Ze.optional(),rules:O.z.array(Pg).max(500).optional()}),wg=O.z.record(O.z.string(),O.z.union([O.z.strictObject({type:O.z.literal("hashed"),attributeKey:O.z.string(),values:O.z.array(O.z.string().regex(/^[a-f0-9]{64}$/))}),O.z.strictObject({type:O.z.literal("list"),attributeKey:O.z.string(),values:O.z.array(O.z.union([O.z.string(),O.z.number()]))}),O.z.strictObject({type:O.z.literal("condition"),condition:ut})])),tn=O.z.strictObject({scope:Xe,generation:O.z.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:O.z.iso.datetime({offset:!0}),expiresAt:O.z.iso.datetime({offset:!0}).nullable(),features:O.z.record(O.z.string(),Cg),savedGroups:wg,experiments:O.z.record(O.z.uuid(),ll)});var Na=tn.extend({analyticsConfig:Ra,remoteFeatures:ce.z.array(ce.z.string().min(1).max(255)).max(500)}),F_=Na.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"})}),dl=ce.z.strictObject({attributes:At,features:ce.z.array(ce.z.string().min(1).max(255)).max(500).optional(),customerId:ce.z.uuid().optional()}),Og=ce.z.strictObject({value:Ze,source:ce.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:ce.z.boolean(),off:ce.z.boolean(),ruleId:ce.z.string(),experimentResult:Da.optional()}),ml=ce.z.strictObject({generation:tn.shape.generation,evaluatedAt:tn.shape.evaluatedAt,expiresAt:tn.shape.expiresAt,features:ce.z.record(ce.z.string(),Og),merchandiseContext:ce.z.strictObject({merchandiseId:ce.z.uuid(),merchandise:At}).optional()}),pl=ce.z.strictObject({customerId:ce.z.uuid().optional(),events:ce.z.array(ce.z.strictObject({eventUuid:ce.z.uuid(),timestamp:ce.z.iso.datetime({offset:!0}),name:ce.z.string().min(1).max(255),merchandise:$s.optional(),properties:ce.z.record(ce.z.string(),Ze).default({}),deviceId:ce.z.string().min(1).max(255).optional(),sessionId:ce.z.string().min(1).max(255).optional()})).min(1).max(100)}),fl=ce.z.strictObject({inserted:ce.z.number().int().nonnegative(),duplicates:ce.z.number().int().nonnegative(),rejected:ce.z.number().int().nonnegative(),skipped:ce.z.number().int().nonnegative(),analyticsConfig:Ra});function hl(e,t=[]){let r=[];st(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(ha(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}var G=require("zod");var Ma=G.z.array(G.z.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"),ti=G.z.intersection(At,G.z.looseObject({tags:Ma.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),ri=G.z.string().trim().max(80),ni=G.z.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),ii=G.z.union([G.z.email().max(254),G.z.literal("")]),ai=G.z.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Al=G.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),gl=G.z.object({externalUserId:Al.optional(),name:ri.default(""),email:ii.default(""),phone:ni.optional(),attributes:ti.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),W_=G.z.discriminatedUnion("type",[G.z.strictObject({type:G.z.literal("id"),value:G.z.uuid()}),G.z.strictObject({type:G.z.literal("externalUserId"),value:Al})]),Z_=G.z.strictObject({name:ri.optional(),email:ii.optional(),phone:ni.optional(),attributes:ti.optional(),fingerprint:ai.optional()});var _r=G.z.object({id:G.z.uuid(),externalUserId:G.z.string().min(1).max(255).nullable(),name:ri,email:ii,phone:ni.optional(),attributes:ti,createdAt:G.z.iso.datetime()}).strict(),bl=G.z.object({customer:_r,changed:G.z.boolean(),replayed:G.z.boolean()}).strict(),Eg=G.z.discriminatedUnion("type",[G.z.object({type:G.z.literal("id"),value:G.z.uuid()}).strict(),G.z.object({type:G.z.literal("externalUserId"),value:G.z.string().trim().min(1).max(255)}).strict()]),jg=G.z.object({name:ri.optional(),email:ii.optional(),phone:ni.optional(),attributes:ti.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:G.z.array(G.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:G.z.strictObject({add:Ma,remove:Ma}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Ua=G.z.object({lookup:Eg}).strict(),yl=Ua.extend({requestId:G.z.uuid(),patch:jg}).strict(),Sl=G.z.object({search:G.z.string().trim().max(200).default(""),tag:G.z.string().trim().max(40).default(""),planId:G.z.string().max(200).default(""),versionId:G.z.string().max(200).default(""),holdingStatus:G.z.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:G.z.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:G.z.union([G.z.iso.datetime(),G.z.literal("")]).default(""),createdUntil:G.z.union([G.z.iso.datetime(),G.z.literal("")]).default(""),offset:G.z.coerce.number().int().min(0).max(1e5).default(0),limit:G.z.coerce.number().int().min(1).max(100).default(50)}).strict(),_l=G.z.object({customers:_r.array(),hasMore:G.z.boolean(),total:G.z.number().int().nonnegative().nullable(),evaluatedAt:G.z.iso.datetime()}).strict();var F=require("zod");var xr=require("zod");var xl=xr.z.object({defaultLocale:lt,locales:xr.z.record(lt,xr.z.object({name:xr.z.string().max(80),description:xr.z.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 Tg=["customer_data","coupon_code"],Rg=F.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Il=F.z.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),oi=(e,t)=>new Set(e.map(t)).size===e.length,kg=F.z.strictObject({currency:J,amountMinor:F.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Dg=F.z.strictObject({featureId:F.z.uuid(),name:F.z.string().trim().min(1).max(120),allowance:F.z.string().max(40).nullable(),access:F.z.boolean()}),Ng=F.z.strictObject({stripe:F.z.strictObject({prices:F.z.array(kg).min(1).max(50)}).optional(),apple:F.z.strictObject({productIds:F.z.array(Rg).min(1).max(10)}).optional(),google:F.z.strictObject({products:F.z.array(F.z.strictObject({productId:Il,basePlanId:Il.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!oi(e.stripe.prices,r=>r.currency)||e.apple&&!oi(e.apple.productIds,r=>r)||e.google&&!oi(e.google.products,r=>`${r.productId}:${r.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),Mg=F.z.strictObject({name:F.z.string().trim().min(1).max(80),interval:F.z.enum(["free","week","month","year","one_time"]),intervalCount:F.z.number().int().min(1).max(100),trial:F.z.strictObject({days:F.z.number().int().min(1).max(730),cardRequired:F.z.boolean()}).nullable(),benefits:F.z.array(Dg).max(50).refine(e=>oi(e,t=>t.featureId),"Duplicate benefit"),channels:Ng}),Ug=F.z.strictObject({digest:Sr,content:F.z.strictObject({discount:Et,duration:tt,appliesTo:Yi,displayCopy:xl.nullable(),firstPurchaseOnly:F.z.boolean(),qualificationRequired:F.z.boolean(),startsAt:F.z.iso.datetime().nullable(),endsAt:F.z.iso.datetime().nullable(),grantWindowHours:F.z.number().int().positive(),perCustomerLimit:F.z.number().int().positive()})}),qg=F.z.discriminatedUnion("type",[F.z.strictObject({type:F.z.literal("checkout"),product:ei}),F.z.strictObject({type:F.z.literal("close")}),F.z.strictObject({type:F.z.literal("action"),action:Ta})]),sx=F.z.strictObject({kind:F.z.literal("paywall"),formatVersion:F.z.literal(1),name:F.z.string().trim().min(1).max(80),offeringVersionId:F.z.uuid(),presentation:zr,screen:Jt,products:zn,catalog:F.z.record(F.z.uuid(),Mg),buttons:F.z.record(le,qg),coupons:F.z.record(F.z.uuid(),Ug)}).superRefine((e,t)=>{let r=q=>t.addIssue({code:"custom",message:q}),{screen:n}=e;n.surface!=="paywall"&&r("Screen must be a Paywall"),hl(n,Tg).forEach(r),hr(n).some(q=>!q.complete)&&r("Every published locale must be complete");let i=new Set,o=new Set,a=new Set;st(n,q=>{let Pe="bind"in q?q.bind:void 0;Pe?.promotionCode&&r("Promotion codes must not be published"),Pe?.plan&&i.add(Pe.plan),Pe?.coupon&&o.add(Pe.coupon),q.type==="plan_picker"&&(q.planIds?.forEach(Me=>i.add(Me)),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(Pe=>Pe.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(Me=>!p.has(Me))&&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")}),vl=F.z.strictObject({state:F.z.enum(["published","archived"]),controlRevision:F.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:F.z.uuid(),versions:F.z.record(F.z.uuid(),F.z.strictObject({version:F.z.number().int().positive(),artifact:F.z.string().min(1),sourceDigest:F.z.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var Lg={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},qa=ne.z.string().regex(/^[a-f0-9]{64}$/),La=ne.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Bg=Xe.extend({environmentId:ne.z.uuid()}),Fg=ne.z.strictObject({features:ne.z.array(ne.z.string()).max(500),experiments:ne.z.record(ne.z.uuid(),ne.z.array(ne.z.string()).max(20)),savedGroups:ne.z.array(ne.z.string()).max(1e3)}),Ba=ne.z.strictObject({kind:ne.z.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:ne.z.number().int().positive(),url:ne.z.string().min(1).max(2048),sha256:qa,byteLength:ne.z.number().int().positive().max(Lg.maxArtifactBytes),generation:qa.optional()}),Vg=ne.z.strictObject({state:ne.z.enum(["active","paused","archived"]),controlRevision:La,evaluationMode:ne.z.enum(["local","remote"]),evaluationRevision:La,currentVersionId:ne.z.uuid(),versions:ne.z.record(ne.z.uuid(),ne.z.strictObject({artifact:ne.z.string(),dependencies:Fg,definitionDigest:Sr.optional(),couponDigests:ne.z.record(ne.z.uuid(),Sr).optional()}))}),mx=ne.z.strictObject({kind:ne.z.literal("sdk_configuration"),schemaVersion:ne.z.literal(1),scope:Bg,revision:La,generation:qa,policy:ne.z.strictObject({refreshIntervalSeconds:ne.z.number().positive().max(15),maxControlAgeSeconds:ne.z.number().positive().max(60)}),gb:ne.z.strictObject({features:ne.z.string().nullable(),pageExperiments:ne.z.string().nullable()}),artifacts:ne.z.record(ne.z.string(),Ba),funnels:ne.z.record(ne.z.uuid(),Vg),paywalls:ne.z.record(ne.z.uuid(),vl).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 Cl=ke.z.strictObject({...Ar,selector:ke.z.discriminatedUnion("type",[ke.z.strictObject({type:ke.z.literal("paywall"),paywallId:ke.z.uuid()}),ke.z.strictObject({type:ke.z.literal("version"),versionId:ke.z.uuid()})]),customerId:ke.z.uuid().optional(),commerce:fr,locale:ke.z.string().min(1).max(35),requirement:Rt.optional()}),Pl=ke.z.strictObject({id:ke.z.uuid(),paywallId:ke.z.uuid(),version:ke.z.number().int().positive(),document:yr.omit({requirement:!0,offeringId:!0}),offering:ke.z.strictObject({id:ke.z.uuid()}),content:ke.z.strictObject({environmentId:ke.z.uuid(),offeringVersionId:ke.z.uuid(),artifact:Ba.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Bn,check:Yt.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"})}),wl=ke.z.strictObject(Pl.shape).omit({document:!0,offering:!0}).extend({content:Pl.shape.content.unwrap()});var Ke=require("zod");var Ol={requestId:Ke.z.uuid(),sourceId:Ke.z.uuid(),expectedAvailable:Ye},El=Ke.z.discriminatedUnion("action",[Ke.z.strictObject({...Ol,action:Ke.z.enum(["add","subtract","set_remaining"]),amount:Z}),Ke.z.strictObject({...Ol,action:Ke.z.literal("edit"),granted:Z,expiresAt:Ke.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Ke.z.iso.datetime({offset:!0}).nullable(),expectedRevision:Ke.z.number().int().nonnegative()})]),Fa=Ke.z.strictObject({sourceId:Ke.z.uuid(),available:Ye,held:Ye,spent:Ye,adjustmentGrantId:Ke.z.uuid().nullable()}),jl=Fa.extend({granted:Ye,expiresAt:Ke.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Ke.z.iso.datetime({offset:!0}).nullable(),revision:Ke.z.number().int().nonnegative()});var et=require("zod"),Tl=et.z.discriminatedUnion("action",[et.z.object({action:et.z.literal("upsert"),externalId:et.z.string().min(1).max(128),name:et.z.string().trim().min(1).max(80)}).strict(),et.z.object({action:et.z.literal("archive"),entityId:et.z.uuid()}).strict()]),Rl=et.z.object({id:et.z.uuid(),externalId:et.z.string().min(1).max(128),name:et.z.string().min(1).max(80),archived:et.z.boolean()}).strict();var Ge=require("zod");var Dt=require("zod"),Dl=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],kl=Dt.z.string().regex(/.+\/.+/),Va=Dt.z.number().min(-100),nr=Dt.z.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),$g=Dt.z.strictObject({input:nr,output:nr,cache_read:nr.optional(),cache_write:nr.optional(),reasoning:nr.optional(),input_audio:nr.optional(),output_audio:nr.optional()}),$a=(e,t)=>Dt.z.record(e,t).refine(r=>Object.keys(r).length<=100,"At most 100 AI overrides"),Px=Dt.z.strictObject({defaultMarkup:Va,providerMarkups:$a(Dt.z.string().min(1),Va),modelMarkups:$a(kl,Va),customModels:$a(kl,$g.partial())});var Y=require("zod"),ir=Y.z.iso.datetime({offset:!0}),Nt=Y.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Gg=Y.z.discriminatedUnion("kind",[Y.z.object({kind:Y.z.literal("absolute"),from:ir,to:ir}).strict(),Y.z.object({kind:Y.z.literal("last_days"),days:Y.z.union([Y.z.literal(1),Y.z.literal(7),Y.z.literal(30),Y.z.literal(90)])}).strict(),Y.z.object({kind:Y.z.literal("billing_cycles"),membershipId:Y.z.uuid(),count:Y.z.number().int().min(1).max(12),includeCurrent:Y.z.boolean()}).strict()]),Nl=Y.z.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"),Hg=Y.z.object({key:Y.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:Y.z.array(Y.z.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),ar=Y.z.object({range:Gg,timezone:Nl,filterBy:Y.z.array(Hg).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:Y.z.enum(["hour","day","week","month"]),internal_feature_id:Y.z.uuid().nullable(),entityId:Y.z.uuid().nullable(),topN:Y.z.number().int().min(1).max(50).nullable(),groupBy:Y.z.union([Y.z.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),Y.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Y.z.object({bucket:ir,group:Y.z.string().max(240),isOther:Y.z.boolean(),internal_feature_id:Y.z.uuid(),resourceId:Y.z.uuid()}).strict().nullable(),limit:Y.z.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)"})}),Ml=Y.z.object({from:ir,to:ir,interval:Y.z.enum(["hour","day","week","month"]),timezone:Nl,rows:Y.z.array(Y.z.object({bucket:ir,group:Y.z.string().max(240),isOther:Y.z.boolean(),internal_feature_id:Y.z.uuid(),resourceId:Y.z.uuid(),consumedUnits:Nt,refundedUnits:Nt,reservedUnits:Nt,charged:Nt,refunded:Nt,reserved:Nt,netUnits:Nt,netCharged:Nt}).strict()).max(100),nextCursor:Y.z.object({bucket:ir,group:Y.z.string().max(240),isOther:Y.z.boolean(),internal_feature_id:Y.z.uuid(),resourceId:Y.z.uuid()}).strict().nullable()}).strict();var Ir=Ge.z.string().regex(/^(0|[1-9]\d{0,29})$/),Ul=Ge.z.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Ga=Ge.z.strictObject({bucket:Ge.z.iso.datetime({offset:!0}),group:Ge.z.string().max(240),isOther:Ge.z.boolean(),internal_feature_id:Ge.z.uuid()}),ql=Ge.z.strictObject({...ar.shape,groupBy:Ge.z.union([Ge.z.enum(["customer","entity","entitlement"]),Ge.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Ga.nullable()}).superRefine((e,t)=>{let r=ar.safeParse({...e,after:null});if(!r.success)for(let n of r.error.issues)t.addIssue({code:"custom",path:n.path,message:n.message})}),Ll=Ge.z.strictObject({from:Ge.z.iso.datetime({offset:!0}),to:Ge.z.iso.datetime({offset:!0}),interval:ar.shape.interval,timezone:ar.shape.timezone,rows:Ge.z.array(Ge.z.strictObject({...Ga.shape,eventCount:Ir,units:Ul,tokenEventCount:Ir,tokens:Ge.z.strictObject(Object.fromEntries(Dl.map(e=>[e,Ir]))),totalTokens:Ir,providerCostEventCount:Ir,providerCostUsd:Ul,invalidTelemetryEventCount:Ir})).max(100),nextCursor:Ga.nullable()});var Oe=require("zod");var Bl=Oe.z.object({requestId:Oe.z.uuid(),items:Oe.z.array(Oe.z.object({customerId:Oe.z.uuid(),command:Lr.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"),Fl=Oe.z.object({batchId:Oe.z.uuid(),after:Oe.z.number().int().min(-1).max(999),limit:Oe.z.number().int().min(1).max(100)}).strict(),Vl=Oe.z.object({batchId:Oe.z.uuid(),status:Oe.z.enum(["queued","complete"]),total:Oe.z.number().int().min(1).max(1e3),processed:Oe.z.number().int().min(0).max(1e3),items:Oe.z.array(Oe.z.object({position:Oe.z.number().int().min(0).max(999),customerId:Oe.z.uuid(),idempotencyKey:Oe.z.string().min(1).max(120),status:Oe.z.enum(["queued","accepted","rejected","failed"]),receipt:Br.nullable(),errorCode:Oe.z.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:Oe.z.number().int().min(0).max(999).nullable()}).strict();var h=require("zod");var Kg=h.z.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),$l=h.z.enum(["draft","active","paused","archived"]),Gl=h.z.string().min(1).max(256),Hl=h.z.array(Gl).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),Wg=h.z.strictObject({duration:h.z.enum(["day","week","month","year"]),length:h.z.number().int().min(1).max(3660)}),Zg=h.z.strictObject({internal_feature_id:h.z.uuid(),allowance:h.z.number().nonnegative().max(1e15).nullable(),expiry:Wg.nullable()}),Qg=h.z.discriminatedUnion("type",[h.z.strictObject({type:h.z.literal("feature_grant"),grants:h.z.array(Zg).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),h.z.strictObject({type:h.z.literal("free_product"),productId:Gl,duration:tt}),h.z.strictObject({type:h.z.literal("invoice_credits"),amount:h.z.number().positive().max(1e8),duration:tt,rollover:h.z.boolean(),productIds:Hl})]),Yg=h.z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),Kl=h.z.object({key:Yg,name:h.z.string().trim().min(1).max(80),configuration:Qg}).strict(),Wl=h.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Ha=h.z.object({code:Wl,maxUses:h.z.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:h.z.boolean()}).strict(),Zl=h.z.object({key:h.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:h.z.string().trim().min(1).max(80),rewardId:h.z.uuid(),redeemOn:h.z.enum(["customer_creation","checkout"]),receivedBy:h.z.enum(["referrer","all"]),maxRedemptions:h.z.number().int().min(1).max(1e6).nullable(),productIds:Hl,excludeTrial:h.z.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),Ql={id:h.z.uuid(),projectId:h.z.uuid(),environmentId:h.z.uuid(),revision:h.z.number().int().nonnegative(),status:$l,createdAt:h.z.iso.datetime({offset:!0}),updatedAt:h.z.iso.datetime({offset:!0})},Xg=Kl.extend(Ql).strict(),Jg=Zl.safeExtend(Ql).strict(),Nx=h.z.strictObject({id:h.z.uuid(),key:h.z.string(),name:h.z.string(),type:Kg,status:$l}),Mx=h.z.discriminatedUnion("action",[h.z.object({action:h.z.literal("save"),id:h.z.uuid().nullable(),revision:h.z.number().int().nonnegative(),input:Kl}).strict(),h.z.object({action:h.z.enum(["activate","pause","resume","archive","delete"]),id:h.z.uuid(),revision:h.z.number().int().nonnegative()}).strict()]),Ux=h.z.discriminatedUnion("action",[h.z.object({action:h.z.literal("save"),id:h.z.uuid().nullable(),revision:h.z.number().int().nonnegative(),input:Zl}).strict(),h.z.object({action:h.z.enum(["activate","pause","resume","archive","delete"]),id:h.z.uuid(),revision:h.z.number().int().nonnegative()}).strict()]),Yl=h.z.object({id:h.z.uuid(),rewardId:h.z.uuid(),programId:h.z.uuid().nullable(),customerId:h.z.uuid(),referrerId:h.z.uuid().nullable(),status:h.z.enum(["pending","applied","unavailable"]),result:h.z.record(h.z.string(),h.z.unknown()).nullable(),createdAt:h.z.iso.datetime({offset:!0})}).strict(),Xl=h.z.object({code:Wl,requestId:h.z.uuid()}).strict(),Jl=h.z.strictObject({redemptionId:h.z.uuid(),currency:J,requestId:h.z.uuid(),accepted:h.z.literal(!0)}),zg=h.z.strictObject({type:h.z.literal("checkout"),orderId:h.z.uuid(),productVersionId:h.z.uuid(),currency:J,duration:tt,renewalAmountMinor:h.z.number().int().positive().max(1e8),status:h.z.enum(["created","pending","trialing","paid","cancelled","failed"]),url:h.z.url().nullable()}),zl=h.z.discriminatedUnion("type",[zg,h.z.strictObject({type:h.z.literal("subscription"),operationId:h.z.uuid(),membershipId:h.z.uuid(),productVersionId:h.z.uuid(),currency:J,duration:tt,renewalAmountMinor:h.z.number().int().positive().max(1e8),status:h.z.enum(["pending","running","applied","failed"])})]),ed=h.z.object({programId:h.z.uuid(),requestId:h.z.uuid()}).strict(),td=h.z.object({id:h.z.uuid(),programId:h.z.uuid(),code:Ha.shape.code,createdAt:h.z.iso.datetime({offset:!0})}).strict(),qx=h.z.object({rows:h.z.array(Xg).max(100),nextCursor:h.z.uuid().nullable()}).strict(),Lx=h.z.object({rows:h.z.array(Jg).max(100),nextCursor:h.z.uuid().nullable()}).strict(),eb=Ha.extend({id:h.z.uuid(),redemptions:h.z.number().int().nonnegative()}).strict(),tb=h.z.strictObject({id:h.z.uuid(),programId:h.z.uuid().nullable(),customerId:h.z.uuid().nullable(),referrerId:h.z.uuid().nullable(),code:h.z.string().nullable(),status:h.z.enum(["pending","triggered","applied"]),createdAt:h.z.iso.datetime({offset:!0})}),Bx=h.z.object({codes:h.z.array(eb).max(100),redemptions:h.z.array(tb).max(100),customers:h.z.record(h.z.uuid(),h.z.string()),codesCursor:h.z.uuid().nullable(),redemptionsCursor:h.z.uuid().nullable()}).strict(),Fx=h.z.discriminatedUnion("action",[h.z.object({action:h.z.literal("create"),rewardId:h.z.uuid(),revision:h.z.number().int().nonnegative(),input:Ha}).strict(),h.z.object({action:h.z.literal("remove"),rewardId:h.z.uuid(),revision:h.z.number().int().nonnegative(),codeId:h.z.uuid()}).strict()]);var m=require("zod");var T=require("zod"),yt={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},rn=e=>new Set(e).size===e.length,Ka=T.z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),rb=T.z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),nn=T.z.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"))),nb=T.z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),rd=T.z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var nd=T.z.strictObject({id:T.z.uuid(),repo:rb,platform:T.z.enum(["github","gitlab","bitbucket"]),branches:T.z.array(nn).min(1).max(4).refine(rn),workflow:T.z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:T.z.array(T.z.uuid()).min(1).max(4).refine(rn),include:T.z.array(rd).min(1).max(16),exclude:T.z.array(rd).max(16),methods:T.z.array(T.z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(rn),maxAgeHours:T.z.number().int().min(1).max(720)}),id=nd.extend({revision:T.z.number().int().positive()}),$x=T.z.strictObject({repository:nd,expectedRevision:T.z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),ad=T.z.strictObject({repositoryId:T.z.uuid(),branch:nn}),ib=T.z.array(Ka).max(yt.keys).refine(rn),od=T.z.strictObject({repository:id.omit({keyIds:!0}),branch:nn,keys:ib,keySetHash:T.z.string().regex(/^[a-f0-9]{64}$/)}),ab=T.z.strictObject({filePath:nb,startingLineNumber:T.z.number().int().min(1).max(1e7)}),Wa=T.z.strictObject({protocol:T.z.literal(1),repositoryId:T.z.uuid(),branch:nn,workflow:T.z.string().max(200),configurationRevision:T.z.number().int().positive(),keySetHash:T.z.string().regex(/^[a-f0-9]{64}$/),commit:T.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:T.z.uuid(),runNumber:T.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:T.z.number().int().min(1).max(1e4),scannerVersion:T.z.literal("1"),scannedAt:T.z.iso.datetime({offset:!0}),coverage:T.z.strictObject({complete:T.z.literal(!0),files:T.z.number().int().min(0).max(yt.files),sourceBytes:T.z.number().int().min(0).max(yt.sourceBytes),unresolvedCalls:T.z.number().int().min(0).max(1e6),unsupportedFiles:T.z.number().int().min(0).max(yt.files)}),features:T.z.array(T.z.strictObject({key:Ka,refs:T.z.array(ab).max(yt.referencesPerKey)})).max(yt.keys)}).superRefine((e,t)=>{rn(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)>yt.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Za=T.z.strictObject({scanId:T.z.uuid(),commit:T.z.string(),receivedAt:T.z.string(),references:T.z.number().int().nonnegative(),removedReferences:T.z.number().int().nonnegative()}),ob=Za.extend({repositoryId:T.z.uuid(),branch:nn,workflow:T.z.string(),digest:T.z.string(),configurationRevision:T.z.number().int().positive(),runNumber:T.z.number().int().positive(),runAttempt:T.z.number().int().positive(),scannedAt:T.z.string(),keySetHash:T.z.string(),coverage:Wa.shape.coverage}),sb=T.z.strictObject({repositories:T.z.array(id).max(yt.repositories),scans:T.z.array(ob).max(yt.repositories*yt.branches)}),cb=T.z.strictObject({key:Ka,references:T.z.number().int().nonnegative(),coveredTargets:T.z.number().int().nonnegative(),expiredTargets:T.z.number().int().nonnegative(),uncertainTargets:T.z.number().int().nonnegative()}),Gx=T.z.strictObject({available:T.z.boolean().default(!0),settings:sb,expectedTargets:T.z.number().int().min(0).max(80),features:T.z.array(cb).max(2001),truncated:T.z.boolean()});var We=require("zod"),cd={customerId:We.z.uuid(),eventId:We.z.string().trim().min(1).max(200),grantId:We.z.uuid(),occurredAt:We.z.iso.datetime({offset:!0})},ud=We.z.strictObject({...cd,productVersionId:We.z.uuid(),subscriptionId:We.z.string().trim().min(1).max(255)}),ld=We.z.strictObject({...cd,merchandiseId:We.z.uuid()}),dd=We.z.union([ud,ld]),sd={id:We.z.uuid(),couponId:We.z.uuid(),status:We.z.literal("redeemed"),source:We.z.literal("merchant"),recordedAt:We.z.iso.datetime({offset:!0})},md=We.z.union([ud.extend(sd),ld.extend(sd)]);var B=require("zod");var Qa=B.z.strictObject({name:B.z.string().trim().min(1).max(255),memo:B.z.string().max(1e4).nullable().optional(),footer:B.z.string().max(1e4).nullable().optional(),net_terms_days:B.z.number().int().positive().nullable().optional()}),ub=Qa.extend({id:B.z.string().min(1).max(255),created_at:B.z.number().nullable()}),pd=B.z.strictObject({items:B.z.array(ub).max(50),nextCursor:B.z.uuid().nullable()}),Zx=B.z.discriminatedUnion("action",[B.z.strictObject({action:B.z.literal("create"),requestId:B.z.uuid(),values:Qa}),B.z.strictObject({action:B.z.literal("update"),id:B.z.string().min(1).max(255),values:Qa}),B.z.strictObject({action:B.z.literal("delete"),id:B.z.string().min(1).max(255)})]),fd=B.z.discriminatedUnion("action",[B.z.strictObject({action:B.z.literal("create"),requestId:B.z.uuid(),params:gr}),B.z.strictObject({action:B.z.enum(["finalize","send","pay","void"]),requestId:B.z.uuid(),invoiceId:B.z.uuid()}),B.z.strictObject({action:B.z.literal("reissue"),requestId:B.z.uuid(),invoiceId:B.z.uuid(),params:ya})]),Ya=B.z.strictObject({id:B.z.uuid(),customerId:B.z.uuid(),providerInvoiceId:B.z.string().nullable(),status:B.z.enum(["draft","open","paid","void","uncollectible"]),currency:B.z.string(),totalMinor:B.z.string().regex(/^-?\d+$/),paidMinor:B.z.string().regex(/^\d+$/),refundedMinor:B.z.string().regex(/^\d+$/),hostedInvoiceUrl:B.z.url().nullable(),createdAt:B.z.number(),collectionMethod:B.z.enum(["send_invoice","charge_automatically"]).nullable()}),hd=Ya.extend({lines:B.z.array(B.z.strictObject({id:B.z.uuid(),description:B.z.string(),amountMinor:B.z.string().regex(/^-?\d+$/),netAmountMinor:B.z.string().regex(/^-?\d+$/),quantity:B.z.number().nullable(),periodStart:B.z.number().nullable(),periodEnd:B.z.number().nullable()})).max(1e3)}),an=B.z.strictObject({taskId:B.z.uuid(),status:B.z.enum(["ready","running","done","dead"]),invoice:Ya.nullable(),errorCode:B.z.string().nullable()}),Ad=B.z.strictObject({items:B.z.array(Ya).max(50),nextCursor:B.z.uuid().nullable(),operations:B.z.array(an).max(50),operationsLimited:B.z.boolean()});var lb=m.z.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"]),gd={scope:Xe,permissions:m.z.array(lb),expiresAt:m.z.iso.datetime().nullable()},UI=m.z.discriminatedUnion("kind",[m.z.object({...gd,kind:m.z.literal("server"),keyId:m.z.string().min(1)}),m.z.object({...gd,kind:m.z.literal("customer"),customerId:m.z.string().min(1),identityKind:m.z.enum(["identified","guest"]),expiresAt:m.z.iso.datetime()})]),P=m.z.object({requestId:m.z.uuid(),scope:Xe}).strict(),db=gl.safeExtend({fingerprint:ai.optional()}).strict(),mb=P.extend({customer:_r,created:m.z.boolean()});function bd(){return P.extend({offer:Xi.nullable(),reason:Ks.nullable()})}var _={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:$c,response:P.extend({message:m.z.object({messageId:m.z.uuid(),channel:Gr,acceptedAt:m.z.iso.datetime({offset:!0}),status:m.z.enum(["accepted","sending","completed","canceled"]),replayed:m.z.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:m.z.strictObject({messageId:m.z.uuid()}),response:P.extend({message:m.z.object({id:m.z.uuid(),channel:Gr,status:m.z.enum(["accepted","sending","completed","canceled"]),deliveries:m.z.array(m.z.object({id:m.z.uuid(),status:Hc,attempts:m.z.number().int().nonnegative(),receipts:m.z.array(m.z.object({kind:Kc,occurredAt:m.z.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:_o,response:P.extend({installation:qt})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:xo,response:P.extend({installation:qt})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:hn,response:P.extend({installation:qt})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:m.z.strictObject({channel:Gr}),response:P.extend({preference:gi})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Gc,response:P.extend({preference:gi})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:m.z.strictObject({cursor:m.z.uuid().optional()}),response:P.extend({templates:pd})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),params:gr}),response:P.extend({preview:Sa})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),requestId:m.z.uuid(),params:gr}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:P.extend({operation:an})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),command:fd}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:P.extend({operation:an})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),taskId:m.z.uuid()}),response:P.extend({operation:an})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),cursor:m.z.uuid().optional()}),response:P.extend({invoices:Ad})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),invoiceId:m.z.uuid()}),response:P.extend({invoice:hd})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:ad,response:P.extend({config:od})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Wa,response:P.extend({receipt:Za})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:m.z.strictObject({}),response:P.extend({payload:Na})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:dl,response:P.merge(ml)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:pl,response:P.merge(fl)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),sourceId:m.z.uuid()}),response:P.extend({balance:jl})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),command:El}),response:P.extend({balance:Fa})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:m.z.strictObject({internal_feature_id:m.z.uuid(),customerId:m.z.uuid().optional(),entityId:m.z.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:P.extend({internal_feature_id:m.z.uuid(),config:$i,model_markups:jn})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),query:Un}),response:P.extend({usage:Fr})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),command:kc}),response:P.extend({usage:Fr})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),command:wc}),response:P.extend({grant:oa})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Oc,response:P.extend({grants:Ec})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:m.z.union(tl.options.map(e=>e.extend({customerId:m.z.uuid().optional(),customerToken:m.z.string().regex(qn).optional()}))),response:P.extend({operation:rl})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Gu.extend({customerId:m.z.uuid().optional()}),response:P.extend({setup:Ca})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Hu.extend({customerId:m.z.uuid().optional()}),response:P.extend({setup:Ca})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Fu.safeExtend({customerId:m.z.uuid()}),response:P.extend({batch:Yr})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Zn.extend({customerId:m.z.uuid()}),response:P.extend({batch:Yr})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Zn.extend({customerId:m.z.uuid()}),response:P.extend({batch:Yr})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Zn.extend({customerId:m.z.uuid()}),response:P.extend({batch:Yr})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:m.z.discriminatedUnion("action",[Qn.options[0].extend({customerId:m.z.uuid()}),Qn.options[1].extend({customerId:m.z.uuid()}),Qn.options[2].extend({customerId:m.z.uuid()})]),response:P.extend({trial:Pa})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Vu.extend({customerId:m.z.uuid()}),response:P.extend({trial:Pa})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Jn,response:P.extend({subscriptions:Ju})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Jn,response:P.extend({purchases:zu})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Qu,response:P.extend({conflicts:el})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Yu,response:P.extend({resolution:Xu})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Wu,response:P.extend({verification:Zu})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Tu.safeExtend({...Ar,customerId:m.z.uuid().optional()}),response:P.extend({quote:Du})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:tr.extend({customerId:m.z.uuid().optional(),intent:m.z.enum(["confirm","cancel"]).optional()}),response:P.extend({operation:_a})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:tr.extend({customerId:m.z.uuid().optional()}),response:P.extend({operation:_a})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Nu.safeExtend({customerId:m.z.uuid().optional()}),response:P.extend({quote:Uu})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:tr.extend({customerId:m.z.uuid().optional(),intent:m.z.enum(["confirm","cancel"]).optional()}),response:P.extend({operation:Ia})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:tr.extend({customerId:m.z.uuid().optional()}),response:P.extend({operation:Ia})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:qu.safeExtend({customerId:m.z.uuid()}),response:P.extend({quote:Bu})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:tr.extend({customerId:m.z.uuid()}),response:P.extend({operation:Wn})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:tr.extend({customerId:m.z.uuid()}),response:P.extend({operation:Wn})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:dc,response:P.extend({controls:ea})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:ic,response:P.extend({prepared:oc})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:sc,response:P.extend({authorization:kn})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:hc,response:P.extend({coupons:Ac})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:cc,response:P.extend({authorization:kn})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:pc,response:P.extend({invoices:fc})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:mc,response:P.extend({invoice:Dr})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:m.z.object({customerId:m.z.uuid(),command:lc}).strict(),response:P.extend({controls:ea})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:m.z.object({customerId:m.z.uuid(),command:Tl}).strict(),response:P.extend({entity:Rl})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:m.z.strictObject({customerId:m.z.uuid().nullable(),query:ql}),response:P.extend({analytics:Ll})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:m.z.object({customerId:m.z.uuid().nullable(),query:ar}).strict(),response:P.extend({analytics:Ml})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Bl,response:P.extend({batchId:m.z.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Fl,response:P.extend({batch:Vl})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Yc.extend({customerId:m.z.string().min(1).optional()}),response:P.extend({check:Yt})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:m.z.strictObject({kind:kt,selector:m.z.discriminatedUnion("type",[m.z.strictObject({type:m.z.literal("resource"),id:m.z.uuid()}),m.z.strictObject({type:m.z.literal("version"),id:m.z.uuid()})]),customerId:m.z.string().min(1).optional()}),response:P.extend({content:Aa})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Cl,response:P.extend({paywall:wl})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:m.z.strictObject({...Ar,selector:ol,customerId:m.z.string().min(1).optional(),commerce:fr,requirement:Rt.optional()}),response:P.extend({offering:sl,candidates:m.z.array(da).max(20),availability:m.z.array(m.z.strictObject({productVersionId:m.z.uuid(),available:m.z.boolean(),reason:m.z.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:Yt.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:m.z.object({customerId:m.z.uuid().optional(),entityId:m.z.uuid().optional()}).strict(),response:P.extend({holdings:Dc})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:m.z.object({customerId:m.z.uuid().optional(),query:Uc}).strict(),response:P.extend({ledger:qc})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:jc.extend({customerId:m.z.uuid().optional()}),response:P.extend({detail:Tc})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:sa.safeExtend({customerId:m.z.uuid().optional()}),response:P.extend({statement:Rc})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:m.z.object({customerId:m.z.uuid().optional(),command:Lr.options[0]}).strict(),response:P.extend({quote:vc})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),command:m.z.union([m.z.strictObject({eventName:m.z.string().min(1),quantity:Z.optional(),properties:Ne.optional(),entityId:m.z.uuid().optional(),idempotencyKey:m.z.string().min(1).max(120)}),m.z.strictObject({internal_feature_id:m.z.uuid(),quantity:Z.optional(),properties:Ne.optional(),entityId:m.z.uuid().optional(),idempotencyKey:m.z.string().min(1).max(120)})])}),response:P.extend({receipts:m.z.array(Br).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:m.z.object({customerId:m.z.uuid(),command:Lr.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:P.extend({receipt:Br})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Xl,response:P.extend({redemption:Yl})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:ed,response:P.extend({referralCode:td})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:Jl,response:P.extend({checkout:zl})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Bc,response:P.extend({seats:la})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Fc,response:P.extend({seats:la})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:db,response:mb},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Ua,response:P.extend({customer:_r})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Sl,response:P.extend(_l.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:yl,response:P.extend(bl.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:m.z.object({customerId:m.z.uuid()}).strict(),response:P.extend(pr.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:m.z.strictObject({}),response:P.extend(pr.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:m.z.strictObject({customerId:m.z.uuid(),sessionId:m.z.uuid().optional()}),response:P.extend({revoked:m.z.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:m.z.strictObject({guestToken:m.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:ai.optional()}),response:P.extend({customerId:m.z.uuid(),guestToken:m.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:m.z.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:m.z.strictObject({guestToken:m.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:P.extend(pr.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:m.z.strictObject({guestToken:m.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:m.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:m.z.uuid()}),response:P.extend({customer:_r,switched:m.z.boolean(),replayed:m.z.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:m.z.strictObject({code:m.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:m.z.uuid()}),response:bd()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:m.z.object({}).strict(),response:P.extend({offers:m.z.array(Xi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:m.z.object({customerId:m.z.string().min(1).max(255).optional(),couponId:m.z.uuid(),...Ar,requestId:m.z.uuid(),couponContentDigest:m.z.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:bd()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:dd,response:P.extend({receipt:md})}},qI={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);wt(this,"code",r);wt(this,"status",i);wt(this,"requestId",o);wt(this,"retryable");wt(this,"recovery");wt(this,"retryAfterSeconds");wt(this,"reason");this.name="IndianaError",this.reason=a?.reason;let c=An(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 on=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new R("INVALID_STATE","Installation sequence exhausted");return e+1},pb=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 Pt(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 yd(e,t,r){let n=null,i=0,o=0,a=0,c=Promise.resolve();if(e&&(!r||Xe.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=j=>{if(j!==i)throw new R("IDENTITY_CHANGED","Identity changed during Push operation")};async function A(j){let V=l();if(!V.sha256&&!globalThis.crypto?.subtle)throw new R("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let X=V.sha256?await V.sha256(Uint8Array.from(j,he=>he.charCodeAt(0))):await pb(j);if(!/^[a-f0-9]{64}$/.test(X))throw new R("INVALID_STATE","Push credential digest is invalid");return X}function v(j){let V=qt.parse(j);if(V.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new R("INVALID_RESPONSE","Push response belongs to another installation");return V}async function k(j,V){let X=l(),he={installationId:X.installationId,publicKey:X.publicKey,issuedAt:new Date().toISOString(),...V},be=await X.sign(Co(j,X.scope,he));return{...he,signature:be}}let U=(j,V,X)=>t.requestWithCredential?t.requestWithCredential(j,V,X):t.request(j,V);async function ie(){let j=l(),V=i,X=n?await(t.session?.access()??n):null,he=Pt(j,Ue=>Ue),be;if(he.detachSeq!==null){let Ue=he.detachSeq,Pr=Io.parse(await k("detach",{sequence:Ue,platform:j.platform}));try{let we=await t.request("push/installations/detach",{...j.scope,...Pr},"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!==Ue)throw new R("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(we){if(we instanceof R&&we.status===404)be=we;else if(!(we instanceof R)||we.status!==412)throw we}be||Pt(j,we=>({...we,detachSeq:we.detachSeq===Ue?null:we.detachSeq}))}if(p(V),!X){if(be)throw be;return null}let Ae=_.bindPushInstallation,Ve=Ae.request.parse(await k("bind",{sequence:a,platform:j.platform,credentialDigest:await A(X)}));p(V);let Te=Ae.response.parse(await U(Ae.path,Ve,X));p(V);let ct=v(Te.installation);if(!ct.bound||ct.identitySeq!==a)throw new R("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return be&&he.detachSeq!==null&&a>he.detachSeq&&Pt(j,Ue=>({...Ue,detachSeq:Ue.detachSeq===he.detachSeq?null:Ue.detachSeq})),ct}async function q(){l();let j=i,V=n?await(t.session?.access()??n):null;if(!V)throw new R("NOT_IDENTIFIED","Identify before reading this installation");let X=_.readPushInstallation,he=X.request.parse(await k("read",{credentialDigest:await A(V)}));p(j);let be=X.response.parse(await U(X.path,he,V));return p(j),v(be.installation)}function Pe(j=ie){let V=c.catch(()=>{}).then(j);return c=V,V.catch(X=>{try{e?.onError?.(X instanceof Error?X:new Error("Push synchronization failed"))}catch{}}),V}async function Me(j,V,X){let he=l(),be=V.identity,Ae=V.observation,Ve=n?await(t.session?.access()??n):null;if(p(be),Ae!==o)throw new R("INVALID_STATE","Push observation changed during recovery");if(!Ve)throw new R("NOT_IDENTIFIED","Identify before recovering a Push address");if(!j.connectionId||!j.kind||!j.token||!["granted","provisional"].includes(j.permission))throw new R("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await Pe(async()=>{if(p(be),await ie(),p(be),Ae!==o)throw new R("INVALID_STATE","Push observation changed during recovery");let Te=Pt(he,at=>X?at:{...at,addressSeq:on(at.addressSeq)}),Ue=await k(X?"recovery_confirm":"recovery_request",{...j,sequence:Te.addressSeq,credentialDigest:await A(Ve),...X?{challenge:X}:{}}),Pr=X?Po.parse(Ue):vo.parse(Ue);if(p(be),Ae!==o)throw new R("INVALID_STATE","Push observation changed during recovery");let we=await U(`push/installations/recovery/${X?"confirm":"request"}`,Pr,Ve);if(p(be),Ae!==o||Pt(he,at=>at).addressSeq!==Te.addressSeq)throw new R("INVALID_STATE","Push observation changed during recovery");if(X){let at=_.updatePushAddress.response.parse(we),Ce=v(at.installation);if(!Ce.bound||Ce.identitySeq!==a||Ce.addressSeq!==Te.addressSeq||Ce.connectionId!==j.connectionId||Ce.addressStatus!=="active")throw new R("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return Ce}if(!we||typeof we!="object"||!("recovery"in we))throw new R("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return Ai.parse(we.recovery)})}return{recoveryObserver(){l();let j={identity:i,observation:++o};return{async request(V){return Ai.parse(await Me(V,j))},async confirm(V,X){return qt.parse(await Me(X,j,V))}}},identify(j){if(!e)return;a=Pt(e,X=>({...X,identitySeq:on(X.identitySeq)})).identitySeq,n=j,i++,o++},reset(){if(e)try{Pt(e,j=>{let V=on(j.identitySeq);return{...j,identitySeq:V,detachSeq:V}})}finally{n=null,i++,o++}},start(){e&&Pe()},async sync(){return await Pe()},read:q,async recover(){let j=l(),V=i,X=a;return o++,await Pe(async()=>{p(V);let he=await q();return p(V),a=Pt(j,Ae=>{if(Ae.identitySeq!==X)throw new R("IDENTITY_CHANGED","A newer installation intent exists");return{...Ae,identitySeq:on(Math.max(Ae.identitySeq,he.identitySeq)),addressSeq:Math.max(Ae.addressSeq,he.addressSeq)}}).identitySeq,await ie()})},tokenObserver(){l();let j=++o,V=i;return async X=>{if(j!==o||V!==i)return null;let he=l(),be=n?await(t.session?.access()??n):null;if(!be)throw new R("NOT_IDENTIFIED","Identify before registering a Push token");if(await Pe(),p(V),j!==o)return null;let Ae=Pt(he,Ue=>({...Ue,addressSeq:on(Ue.addressSeq)})),Ve=_.updatePushAddress,Te=Ve.request.parse(await k("address",{...X,sequence:Ae.addressSeq,credentialDigest:await A(be)}));if(p(V),j!==o)return null;let ct=Ve.response.parse(await U(Ve.path,Te,be));return p(V),v(ct.installation)}}}}function Sd(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 fb=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function hb(e){return e.replace(fb,"$1\uFFFD")}function eo(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 Ed(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 _d(e){let t;if(Array.isArray(e)){let r=e.map(fe);if(r.length===2)return r}else if((t=Ed(e))!=null){let r=eo(t.next()),n=eo(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 xd="0123456789ABCDEF",Ab=/(?:%[0-9A-Fa-f]{2})+/g;function St(e){return`%${xd[e>>4&15]}${xd[15&e]}`}function jd(e,t,r=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?r&&e===32?"+":t(e)?St(e):String.fromCharCode(e):e<=2047?St(192|e>>6)+St(128|63&e):e<=65535?St(224|e>>12)+St(128|e>>6&63)+St(128|63&e):St(240|e>>18)+St(128|e>>12&63)+St(128|e>>6&63)+St(128|63&e)}function to(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function ro(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(Ab,n=>{try{return decodeURIComponent(n)}catch{return"\uFFFD".repeat(n.length/3)}})}function un(e){return e<=31||e>126}function gb(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return un(e)}}function uo(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return un(e)}}function bb(e){return uo(e)||e===39}function no(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return uo(e)}}function di(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 no(e)}}function Id(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 di(r)}})(e)}}function Td(e,t){return jd(e=e||0,t)}function _t(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+=jd(a,t,r)}return i}function lo(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([ro(i.slice(0,o),!0),ro(i.slice(o+1),!0)])}if(r=n+1,n===e.length)break}return t}function io(e){let t="";for(let r=0;r<e.length;r++){let n=_t(e[r][0],Id,!0),i=_t(e[r][1],Id,!0);t+=r!==0?`&${n}=${i}`:`${n}=${i}`}return t}var yb=[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],Sb=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],_b=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],xb=[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 Ib(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[vb,Pb,Cb,vd]=[[[],"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 wb(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 Rd(e,t){for(let r=0;r<e.length;r+=2)if(t>=e[r]&&t<=e[r+1])return!0;return!1}function sn(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 Ob(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&&Rd(xb,t[r-1]))continue;if(n===8205)return!1;let i=r-1;for(;i>=0&&sn(vd,t[i]);)i--;let o=r+1;for(;o<t.length&&sn(vd,t[o]);)o++;if(!(i>=0&&o<t.length&&sn(Pb,t[i])&&sn(Cb,t[o])))return!1}return!0}var Eb=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,jb=/\p{Script=Latin}/u;function Tb(e){return!Eb.test(e)||!jb.test(e)}var Mt=36,ci=1,ao=26,Rb=38,kb=700,Db=72,Nb=128,Mb=2147483647;function Pd(e){return String.fromCharCode(e+22+75*+(e<26))}function Ub(e,t,r){let n=0;for(e=r?Math.floor(e/kb):e>>1,e+=Math.floor(e/t);e>(Mt-ci)*ao>>1;n+=Mt)e=Math.floor(e/(Mt-ci));return Math.floor(n+(Mt-ci+1)*e/(e+Rb))}function qb(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=Nb,a=0,c=Db;for(;n<t.length;){let l=Mb;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=Mt;;k+=Mt){let U=k<=c?ci:k>=c+ao?ao:k-c;if(v<U)break;r+=Pd(U+(v-U)%(Mt-U)),v=Math.floor((v-U)/(Mt-U))}r+=Pd(v),c=Ub(a,n+1,n===i),a=0,n++}}a++,o++}return r}function Xa(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=to(e.charCodeAt(n));if(i>=t||i<0)return-1;r=r*t+i}return r}function Cd(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function kd(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Dd(e){return e.length===2&&kd(e.codePointAt(0),e.codePointAt(1))}function wd(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function Ee(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Nd(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function oo(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=to(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+to(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 wd(n)?null:_t(n,un)})(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)&&!Rd(yb,v)||sn(vb,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=wb(v,k);if(U){A+=U;continue}let ie=Sb.indexOf(k);A+=ie<0?v:_b[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(Ib(p)||A&&(/^\p{Mark}/u.test(p)||!Ob(p)||!Tb(p)||p.startsWith("xn--")))return null;A&&(c[l]=`xn--${qb(p)}`)}return(i=c.join("."))!==""?i:null})(e.indexOf("%")===-1?e:ro(e));return r===null||wd(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(Xa(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=Xa(o[p]);if(A<0||A>255)return null;c+=A*(1<<8*(3-p))}let l=Xa(o[a-1]);return l<0||l>=256**(5-a)?null:(c+=l,c)})(r):r}}function so(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 Md(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 Ud(e){return e.username!==""||e.password!==""}function Ja(e){return e.host===null||e.host===""||e.scheme==="file"}var f=0,x="",te="",de=null,I,ui=!1,li=!1,or=!1,je;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,te="",de=r||null,I=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},ui=!1,li=!1,or=!1,je=n||0;let i=Lb;switch(n){case 3:case 4:i=mi;break;case 5:i=po;break;case 6:i=sr;break;case 7:i=Ut;break;case 8:i=xt}return i(E(e,f))!==1?I:null}function M(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 qd(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var Lb=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 te=x.slice(f,r).toLowerCase(),f=r,Bb(r<x.length?e:void 0)}else return je?1:(--f,M(t,e)?Ld(E(x,f)):0)},Bb=e=>{let t=f;if(e===58){if(je){if(Ee(I.scheme)!==Ee(te))return 0;if((Ud(I)||I.port!==null)&&te==="file")return 0;if(I.scheme==="file"&&I.host==="")return 0}return I.scheme=te,je?(I.port===Nd(I.scheme)&&(I.port=null),0):(te="",I.scheme==="file"?M(t,e)?fo(E(x,f)):0:Ee(I.scheme)&&de!==null&&de.scheme===I.scheme?M(t,e)?Fb(E(x,f)):0:Ee(I.scheme)?M(t,e)?$b(E(x,f)):0:E(x,f+1)===47?(f++,M(t,e)?Vb(E(x,f)):0):(I.path=[""],I.opaquePath=!0,M(t,e)?Fd(E(x,f)):0))}else return je?1:(te="",f=-1,M(t,e)?Ld(E(x,f)):0)},Ld=e=>{let t=f;return de===null||de.opaquePath&&e!==35?1:de.opaquePath&&e===35?(I.scheme=de.scheme,I.path=de.path.slice(),I.opaquePath=de.opaquePath,I.query=de.query,I.fragment="",M(t,e)?xt(E(x,f)):0):de.scheme==="file"?(f--,M(t,e)?fo(E(x,f)):0):(f--,M(t,e)?mo(E(x,f)):0)},Fb=e=>{let t=f;return e===47&&E(x,f+1)===47?(++f,M(t,e)?fi(E(x,f)):0):(f--,M(t,e)?mo(E(x,f)):0)},Vb=e=>{let t=f;return e===47?M(t,e)?vr(E(x,f)):0:(f--,M(t,e)?ht(E(x,f)):0)},mo=e=>{let t=f;return I.scheme=de.scheme,e===47||Ee(I.scheme)&&e===92?M(t,e)?Od(E(x,f)):0:(I.username=de.username,I.password=de.password,I.host=de.host,I.port=de.port,I.path=de.path.slice(),I.query=de.query,e===63?(I.query="",M(t,e)?Ut(E(x,f)):0):e===35?(I.fragment="",M(t,e)?xt(E(x,f)):0):e!=null?(I.query=null,I.path.pop(),f--,M(t,e)?ht(E(x,f)):0):M(t,e)?mo(E(x,f)):0)},Od=e=>{let t=f;return Ee(I.scheme)&&(e===47||e===92)?M(t,e)?fi(E(x,f)):0:e===47?M(t,e)?vr(E(x,f)):0:(I.username=de.username,I.password=de.password,I.host=de.host,I.port=de.port,f--,M(t,e)?ht(E(x,f)):0)},$b=e=>{let t=f;return e===47&&E(x,f+1)===47?f++:f--,M(t,e)?fi(E(x,f)):0},fi=e=>{let t=f;return e!==47&&e!==92?(f--,M(t,e)?vr(E(x,f)):0):M(t,e)?fi(E(x,f)):0},vr=e=>{let t=f;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!Ee(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&&Ee(I.scheme))break;r+=ft(n)}return te+=x.slice(f,r),f=r-1,M(t,e)?vr(E(x,f)):0}if(e===64){ui&&(te=`%40${te}`),ui=!0;for(let r=0;r<te.length;r++){let n=te.codePointAt(r);if(n===58&&!li){li=!0;continue}let i=Td(n,di);li?I.password+=i:I.username+=i,n!=null&&n>65535&&r++}return te="",M(t,e)?vr(E(x,f)):0}else return e==null||e===35||e===47||e===63||e===92&&Ee(I.scheme)?ui&&te===""?1:(f-=te.length+1,te="",M(t,e)?mi(E(x,f)):0):(te+=qd(e),M(t,e)?vr(E(x,f)):0)},mi=e=>{let t=f;if(je&&I.scheme==="file")return f--,M(t,e)?ho(E(x,f)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!Ee(I.scheme))){let r=f+ft(e);for(e===91?or=!0:e===93&&(or=!1);r<x.length;){let n=E(x,r);if(n==null||!or&&n===58||n===35||n===47||n===63||n===92&&Ee(I.scheme))break;n===91?or=!0:n===93&&(or=!1),r+=ft(n)}return te+=x.slice(f,r),f=r-1,M(t,e)?mi(E(x,f)):0}else if(e===58&&!or){if(te===""||je===4)return 1;let r=oo(te,!Ee(I.scheme));return r===null?1:(I.host=so(r),te="",M(t,e)?po(E(x,f)):0)}else if(e==null||e===35||e===47||e===63||e===92&&Ee(I.scheme)){if(f--,Ee(I.scheme)&&te==="")return 1;if(je&&te===""&&(Ud(I)||I.port!==null))return 1;let r=oo(te,!Ee(I.scheme));return r===null?1:(I.host=so(r),te="",je?0:M(t,e)?sr(E(x,f)):0)}else return te+=qd(e),M(t,e)?mi(E(x,f)):0},po=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 te+=x.slice(f,r),f=r-1,M(t,e)?po(E(x,f)):0}else if(je||e==null||e===35||e===47||e===63||e===92&&Ee(I.scheme)){if(te!==""){let r=parseInt(te,10);if(r>65535)return 1;if(I.port=r===Nd(I.scheme)?null:r,te="",je)return 0}return je?1:(f--,M(t,e)?sr(E(x,f)):0)}else return 1};function Bd(e,t){let r=e.length-t;if(r<2)return!1;if(kd(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 fo=e=>{let t=f;return I.scheme="file",I.host="",e===47||e===92?M(t,e)?Gb(E(x,f)):0:de?.scheme==="file"?(I.host=de.host,I.path=de.path.slice(),I.opaquePath=de.opaquePath,I.query=de.query,e===63?(I.query="",M(t,e)?Ut(E(x,f)):0):e===35?(I.fragment="",M(t,e)?xt(E(x,f)):0):e!=null?(I.query=null,Bd(x,f)?I.path=[]:Md(I),f--,M(t,e)?ht(E(x,f)):0):M(t,e)?fo(E(x,f)):0):(f--,M(t,e)?ht(E(x,f)):0)},Gb=e=>{let t=f;return e===47||e===92?M(t,e)?ho(E(x,f)):0:(de!==null&&de.scheme==="file"&&(!Bd(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})(de.path[0])&&I.path.push(de.path[0]),I.host=de.host),f--,M(t,e)?ht(E(x,f)):0)},ho=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 te+=x.slice(f,r),f=r-1,M(t,e)?ho(E(x,f)):0}else if(e==null||e===47||e===92||e===63||e===35){if(f--,!je&&Dd(te))return M(t,e)?ht(E(x,f)):0;if(te==="")return I.host="",je?0:M(t,e)?sr(E(x,f)):0;{let r=oo(te,!Ee(I.scheme));return r===null?1:(r==="localhost"&&(r=""),I.host=so(r),te="",je?0:M(t,e)?sr(E(x,f)):0)}}return 1},sr=e=>{let t=f;return Ee(I.scheme)?(e!==92&&e!==47&&f--,M(t,e)?ht(E(x,f)):0):!je&&e===63?(I.query="",M(t,e)?Ut(E(x,f)):0):!je&&e===35?(I.fragment="",M(t,e)?xt(E(x,f)):0):e!=null?(e!==47&&f--,M(t,e)?ht(E(x,f)):0):(je&&I.host===null&&I.path.push(""),M(t,e)?sr(E(x,f)):0)},ht=e=>{let t=f;if(e!=null&&e!==47&&(!Ee(I.scheme)||e!==92)&&(je||e!==63&&e!==35)){let r=f+ft(e);for(;r<x.length;){let n=E(x,r);if(n==null||n===47||Ee(I.scheme)&&n===92||!je&&(n===63||n===35))break;r+=ft(n)}te+=_t(x.slice(f,r),no),f=r,e=E(x,r)}if(e==null||e===47||Ee(I.scheme)&&e===92||!je&&(e===63||e===35)){let r=Ee(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}})(te)?(Md(I),e!==47&&!r&&I.path.push("")):Cd(te)&&e!==47&&!r?I.path.push(""):Cd(te)||(I.scheme==="file"&&I.path.length===0&&Dd(te)&&(te=`${te[0]}:`),I.path.push(te)),te="",e===63?(I.query="",M(t,e)?Ut(E(x,f)):0):e===35?(I.fragment="",M(t,e)?xt(E(x,f)):0):M(t,e)?ht(E(x,f)):0}else return te+=Td(e,no),M(t,e)?ht(E(x,f)):0},Fd=e=>{let t=f;if(e===63)return I.query="",M(t,e)?Ut(E(x,f)):0;if(e===35)return I.fragment="",M(t,e)?xt(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]+=_t(n.slice(0,-1),un)+"%20":I.path[0]+=_t(n,un),f=r,(e=E(x,r))===63)return I.query="",M(t,e)?Ut(E(x,f)):0;if(e===35)return I.fragment="",M(t,e)?xt(E(x,f)):0}return M(t,e)?Fd(E(x,f)):0},Ut=e=>{let t=f,r=f;if(e!=null){if(je)r=x.length;else{let i=x.indexOf("#",f);r=i===-1?x.length:i}let n=Ee(I.scheme)?bb:uo;I.query+=_t(x.slice(f,r),n)}return f=r,E(x,r)===35&&!je?(I.fragment="",M(t,e)?xt(E(x,f)):0):M(t,e)?Ut(E(x,f)):0},xt=e=>{let t=f;return e!=null&&(I.fragment+=_t(x.slice(f),gb),f=x.length),M(t,e)?xt(E(x,f)):0};function co(e){if(e.opaquePath)return e.path[0];{let t="";for(let r of e.path)t+=`/${r}`;return t}}function Vd(e){switch(e.scheme){case"blob":{let t=it(co(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Vd(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"),ln=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+=co(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&&za(this[pe].query,r.query)}get origin(){return Vd(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),Ja(this[pe].url)||(function(n,i){n.username=_t(i,di)})(this[pe].url,t)}get password(){return this[pe].url.password}set password(t){t=fe(t),Ja(this[pe].url)||(function(n,i){n.password=_t(i,di)})(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];Ja(r)||(t?it(t,r,null,5):r.port=null)}get pathname(){return co(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&&za(n,null);else{let i=t[0]==="?"?t.substring(1):t;r.query="",it(i,r,null,7),n&&za(n,r.query)}}get searchParams(){let t=this[pe],r=t.query;return r==null&&(r=t.query=(function(i,o){let a=new pi;return a[Ie].url=i,a[Ie].serialized=o==null,o&&(a[Ie].list=lo(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(ln.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var Ie=Symbol("URLSearchParamsImpl"),Hb=Symbol.dispose||Symbol.for("dispose");function za(e,t){t?e[Ie].list=lo(t):e[Ie].list.length=0,e[Ie].serialized=t==null}function si(e){if(e.url){let t=io(e.list);(function(n,i){n[pe].url.query=i})(e.url,t||null),e.serialized=!0}}var Kb=typeof Iterator<"u"?Iterator:Object,cn=class extends Kb{constructor(t,r){super(),this[Ie]={ptr:t,map:r,index:0}}next(){let t=this[Ie];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}[Hb](){}},pi=class{constructor(t){let r=this[Ie]={list:[],url:null,serialized:!0},n;if(Array.isArray(t))for(let i=0;i<t.length;i++)r.list.push(_d(t[i]));else if((n=Ed(t))!=null){let i;for(;!(i=eo(n.next())).done;)r.list.push(_d(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=hb(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=lo(i)}}get size(){return this[Ie].list.length}append(t,r){t=fe(t),r=fe(r),this[Ie].list.push([t,r]);let n=this[Ie];n.url&&n.serialized?(function(o,a){let c=o[pe].url;c.query=c.query?`${c.query}&${a}`:a})(n.url,io([[t,r]])):si(n)}delete(t,r){t=fe(t),r=r!=null?fe(r):void 0;let{list:n}=this[Ie],i=0;for(;i<n.length;)n[i][0]===t&&(r==null||n[i][1]===r)?n.splice(i,1):i++;si(this[Ie])}get(t){t=fe(t);let{list:r}=this[Ie];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[Ie];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[Ie];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[Ie],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&&si(this[Ie])}sort(){this[Ie].list.sort((t,r)=>t[0]<r[0]?-1:t[0]>r[0]?1:0),si(this[Ie])}forEach(t,r){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:n}=this[Ie];for(let i=0;i<n.length;i++)t.call(r,n[i][1],n[i][0],this)}entries(){return new cn(this[Ie],t=>t)}keys(){return new cn(this[Ie],t=>t[0])}values(){return new cn(this[Ie],t=>t[1])}toString(){return io(this[Ie].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(pi.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var $d={name:"@tinkerlandai/indiana-sdk",version:"0.9.1",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 Gd="https://api.tinker.cash";function Hd(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=pr.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 Kd=Symbol("IndianaNoContent");function Wd(e,t,r=URL){let n=e.configuration?.scope,i=e.scope??(n&&{projectId:n.projectId,environment:n.environment}),o=i?Xe.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??Gd);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??Hd(async j=>{let V=await Me("customer-sessions/refresh",{},"POST",{},j);if(!V||typeof V!="object")throw new R("INVALID_RESPONSE","Invalid refresh response");let{requestId:X,scope:he,...be}=V;return be});function ie(){A+=1,p=null,v=null;for(let j of k)j.abort();k.clear()}let q=U.subscribeIdentity(ie);function Pe(){U.reset()}async function Me(j,V={},X="POST",he={},be){let Ae=he.installationDetach===!0;if(Ae&&(j!=="push/installations/detach"||X!=="POST"))throw new R("INVALID_REQUEST","Installation authority only detaches this installation");if(!be&&!p&&!Ae)throw new R("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let Ve=A,Te=new AbortController;Ae||k.add(Te);let ct=()=>!Ae&&Ve!==A?new R("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new R("TIMEOUT","Indiana request timed out"),Ue,Pr=new Promise((Ce,ze)=>{Ue=()=>ze(ct()),Te.signal.addEventListener("abort",Ue,{once:!0})}),we=setTimeout(()=>Te.abort(),l),at=async()=>{let Ce=await c(`${a.href.replace(/\/$/,"")}/api/v1/${j}`,{method:X,headers:{"Content-Type":"application/json",...Ae?{}:{Authorization:`Bearer ${be??p}`},[yi]:Si.current,[To]:$d.version,...o?{"X-Indiana-Project":o.projectId,"X-Indiana-Environment":o.environment}:{}},body:X==="POST"?JSON.stringify(V):void 0,signal:Te.signal,credentials:"omit",cache:"no-store",redirect:"error",...he.keepalive?{keepalive:!0}:{}});if(Te.signal.aborted)throw ct();let ze;try{ze=Ce.status===204?Kd:await Ce.json()}catch{throw Te.signal.aborted?ct():new R(Ce.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Ce.status,Ce.headers.get("X-Request-Id")??void 0)}if(Te.signal.aborted)throw ct();if(!Ae&&Ve!==A)throw new R("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Ce.ok){let qe=bi.safeParse(ze),Ct=qe.success&&(!Lt.safeParse(qe.data.error.code).success||Eo(qe.data.error.code,Ce.status)),go=Ct?qe.data.error.code:"HTTP_ERROR",bo=An(go,Ce.status,{retryAfter:Ce.headers.get("Retry-After"),recovery:Ct?qe.data.error.recovery:void 0,reason:Ct?qe.data.error.reason:void 0});throw new R(go,Ct?qe.data.error.message:"Indiana request failed",Ce.status,Ce.headers.get("X-Request-Id")??(qe.success?qe.data.requestId:void 0),{...bo,...qe.success&&qe.data.error.retryable===!1?{retryable:!1}:{},...bo.retryAfterSeconds===void 0&&qe.success&&qe.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:qe.data.error.retryAfterSeconds}:{}})}if(Ce.headers.get(yi)!==Si.current)throw new R("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(o&&ze!==Kd){let qe=ze&&typeof ze=="object"&&"scope"in ze?ze:ze&&typeof ze=="object"&&"configuration"in ze?ze.configuration:null;if(!qe||typeof qe!="object"||!("scope"in qe))throw new R("INVALID_RESPONSE","Response is missing its App/environment scope");let Ct=Xe.safeParse(qe.scope);if(!Ct.success||Ct.data.projectId!==o.projectId||Ct.data.environment!==o.environment)throw new R("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let dn=Ce.headers.get("X-Indiana-Telemetry-Subject");if(dn){if(!/^[a-f0-9]{64}$/.test(dn))throw new R("INVALID_RESPONSE","Invalid telemetry identity");v!==dn&&(v=dn,t?.(v))}return ze};try{return await Promise.race([at(),Pr])}catch(Ce){throw!Ae&&Ve!==A?new R("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Ce instanceof R?Ce:new R(Te.signal.aborted?"TIMEOUT":"NETWORK_ERROR",Te.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(we),Te.signal.removeEventListener("abort",Ue),k.delete(Te)}}return{session:U,requestWithCredential(j,V,X){return Me(j,V,"POST",{},X)},subjectKey:()=>v,identify(j){if(o&&typeof j=="object"&&"scope"in j){let V=Xe.safeParse(j.scope);if(!V.success||V.data.projectId!==o.projectId||V.data.environment!==o.environment)throw new R("SCOPE_MISMATCH","Customer session belongs to another App/environment")}U.identify(j),p=U.peek()??null},reset:Pe,dispose(){q(),ie()},request(j,V={},X="POST",he={}){if(he.installationDetach)return Me(j,V,X,he);let be=A;try{let Ae=U.access(),Ve=Te=>{if(be!==A)throw new R("IDENTITY_CHANGED","Customer identity changed before dispatch");return Me(j,V,X,he,Te)};return typeof Ae=="string"?Ve(Ae):Ae.then(Ve)}catch(Ae){return Promise.reject(Ae)}}}}var Qd=require("zod");function Zd(e,t,r,n){try{return e.parse(t)}catch(i){throw n&&i instanceof Qd.ZodError?new R(r,n):i}}async function Ao(e,t,r,n={},i){let o=typeof n=="function"?{}:n,a=Zd(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):Zd(t.response,c,"INVALID_RESPONSE",o.response)}var Zb=_.trackUsage.request.shape.command,Qb=_.trackUsage.response,Yb=_.checkEntitlement.request.omit({customerId:!0}).strict();function Yd(e){let t=Xe.parse(e.scope),r=Wd({...e,scope:t},void 0,ln),n=yd(e.push,r,t),i=0,o=!1;return r.session.subscribeIdentity(()=>{i++,o=!!r.session.peek()}),{...Sd(r.request,n),session:r.session,identify(a){let c=typeof a=="string"?a:a.accessToken;if(!qn.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 Ao(r.request,a,{})},async checkEntitlement(a){let c=_.checkEntitlement;return Ao(r.request,{...c,request:Yb},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=Zb.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=Qb.parse(p);if(A.scope.projectId!==t.projectId||A.scope.environment!==t.environment)throw new R("INVALID_RESPONSE","Usage response scope differs");return A}}}
1
+ "use strict";var po=Object.defineProperty;var sh=Object.getOwnPropertyDescriptor;var ch=Object.getOwnPropertyNames;var uh=Object.prototype.hasOwnProperty;var lh=(e,t,n)=>t in e?po(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var dh=(e,t)=>{for(var n in t)po(e,n,{get:t[n],enumerable:!0})},ph=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ch(t))!uh.call(e,i)&&i!==n&&po(e,i,{get:()=>t[i],enumerable:!(r=sh(t,i))||r.enumerable});return e};var mh=e=>ph(po({},"__esModule",{value:!0}),e);var Ue=(e,t,n)=>lh(e,typeof t!="symbol"?t+"":t,n);var _0={};dh(_0,{IndianaError:()=>y,createConfigurationSync:()=>ih,createFeatureClient:()=>Va,createIndianaReactNative:()=>w0,createLocalFunnelClient:()=>oh});module.exports=mh(_0);var mo=require("zod"),fh=mo.z.enum(["sandbox","live"]),Le=mo.z.object({projectId:mo.z.string().min(1),environment:fh}).strict();var Fe=require("zod"),yi=Fe.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),xu=Fe.z.enum(["unknown","denied","provisional","granted"]),Iu=Fe.z.enum(["ios","android"]),fo=Fe.z.strictObject({installationId:Fe.z.uuid(),publicKey:Fe.z.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:Fe.z.iso.datetime({offset:!0}),signature:Fe.z.string().regex(/^[A-Za-z0-9_-]{86}$/)}),Ka=Fe.z.string().regex(/^[a-f0-9]{64}$/),vu=fo.extend({sequence:yi,platform:Iu,credentialDigest:Ka}),wu=fo.extend({credentialDigest:Ka}),Ou=fo.extend({sequence:yi,platform:Iu}),go=fo.extend({sequence:yi,credentialDigest:Ka,connectionId:Fe.z.uuid().nullable(),kind:Fe.z.enum(["fcm_token","apns_token"]).nullable(),token:Fe.z.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:xu}),Cu=go,Pu=go.extend({challenge:Fe.z.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),Ha=Fe.z.strictObject({requested:Fe.z.literal(!0),expiresAt:Fe.z.iso.datetime({offset:!0})}),dr=Fe.z.strictObject({installationId:Fe.z.uuid(),bound:Fe.z.boolean(),identitySeq:yi,bindingGeneration:yi,addressSeq:Fe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:Fe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:Fe.z.uuid().nullable(),addressStatus:Fe.z.enum(["active","invalid"]).nullable(),permission:xu}),Qa=Fe.z.strictObject({channel:Fe.z.enum(["email","sms","voice","push"]),state:Fe.z.enum(["unknown","allowed","denied"]),revision:Fe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:Fe.z.iso.datetime({offset:!0}).nullable()}),k0=Fe.z.strictObject({state:Fe.z.enum(["allowed","denied"]),revision:Fe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function _u(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))}var gt=require("zod"),pr=gt.z.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"]),T0=gt.z.enum([...pr.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),N0=gt.z.enum([...pr.options,"stale_revision"]),gh=gt.z.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"]),hh=gt.z.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),Ru={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 Eu={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 Ah(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(Eu,e)){let r=Eu[e];return{retryable:r==="retry_same_request",recovery:r}}let n=pr.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:Ru[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function ku(e,t){let n=pr.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):Ru[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 yh(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 ju=gt.z.object({retryable:gt.z.boolean(),recovery:gh,reason:hh.optional(),retryAfterSeconds:gt.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),Ja=gt.z.object({requestId:gt.z.uuid().optional(),error:gt.z.object({code:gt.z.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:gt.z.string(),...ju.partial().shape})}),D0=gt.z.object({error:Ja.shape.error.extend({requestId:gt.z.uuid().optional()})}),F0=gt.z.object({error:gt.z.string(),code:gt.z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:gt.z.uuid(),...ju.shape});function ho(e,t,n={}){let r=Ah(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?yh(n.retryAfter??null):void 0;return{...r,retryable:a,recovery:i,...o===void 0?{}:{retryAfterSeconds:o},...n.reason?{reason:n.reason}:{}}}var Za="X-Indiana-Protocol",Tu="X-Indiana-SDK-Version";var Wa={current:"0.9"};var Nu=require("zod"),bh=["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=Nu.z.enum(bh);var ht=require("zod"),Sh=ht.z.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"]),Du=ht.z.strictObject({provider:ht.z.literal("stripe"),accountId:ht.z.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:ht.z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:Sh,occurredAt:ht.z.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:ht.z.record(ht.z.string(),ht.z.unknown()).and(ht.z.object({id:ht.z.string().min(1).max(255),object:ht.z.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:ht.z.boolean()}))}),Fu=ht.z.strictObject({id:ht.z.uuid(),eventId:ht.z.string().min(1).max(200),source:ht.z.literal("merchant"),providerVerified:ht.z.literal(!1),outcome:ht.z.string().min(1).max(100)});var qn=require("zod"),Dt=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,qr=qn.z.object({customerId:qn.z.uuid(),sessionId:qn.z.uuid(),accessToken:qn.z.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:qn.z.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:qn.z.iso.datetime(),refreshExpiresAt:qn.z.iso.datetime()});var mr=require("zod");var Ao=mr.z.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"),z0=mr.z.object({amountCents:mr.z.number().int().min(0).max(1e8),currency:fe,interval:mr.z.enum(["free","month","year"]),currencyOptions:mr.z.partialRecord(fe,mr.z.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");var T=require("zod"),xh=T.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Vu=T.z.enum(["single_use","continuous_use"]),Ya=T.z.record(T.z.string(),T.z.union([T.z.string(),T.z.number(),T.z.boolean()]).transform(String).pipe(T.z.string())),Mu=T.z.string().min(1).max(64).refine(e=>!e.includes("::")),Uu={credit_amount:T.z.number(),tier_behavior:T.z.never().optional(),tiers:T.z.never().optional()},Lu={credit_amount:T.z.never().optional(),tier_behavior:T.z.literal("graduated"),tiers:T.z.array(T.z.strictObject({to:T.z.union([T.z.number(),T.z.literal("inf")]),credit_amount:T.z.number()}))},Ih=T.z.union([T.z.strictObject({match:Ya,priority:T.z.number().int().optional(),...Uu}),T.z.strictObject({match:Ya,priority:T.z.number().int().optional(),...Lu})]),vh=T.z.strictObject({match:Ya,factor:T.z.number().positive().optional(),add:T.z.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),qu={metered_feature_id:T.z.string(),feature_amount:T.z.number().optional(),dimensions:T.z.record(Mu,Ih).optional(),multipliers:T.z.record(Mu,vh).optional()},Xa=T.z.union([T.z.strictObject({...qu,...Uu}),T.z.strictObject({...qu,...Lu})]),bo=T.z.number().min(-100),Bu=T.z.record(T.z.string(),T.z.strictObject({markup:bo})).nullish(),So=T.z.record(T.z.string().regex(/.+\/.+/),T.z.strictObject({markup:bo.optional(),input_cost:T.z.number().min(0).optional(),output_cost:T.z.number().min(0).optional()})).nullish(),wh=T.z.strictObject({default_markup:bo.optional(),provider_markups:Bu,model_markups:So}),G0=T.z.strictObject({schema:T.z.array(Xa).optional(),markups:wh.optional()}),Oh=T.z.strictObject({filters:T.z.array(T.z.strictObject({property:T.z.string(),operator:T.z.string(),value:T.z.array(T.z.string())})),aggregate:T.z.strictObject({type:T.z.string(),property:T.z.string().nullable()}),usage_type:Vu}),zu=T.z.strictObject({schema:T.z.array(Xa).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.z.boolean().optional(),usage_type:Vu.default("single_use").overwrite(()=>"single_use"),default_markup:bo.optional(),provider_markups:Bu}),es=zu.safeExtend({schema:T.z.array(Xa).length(0)}),yo={id:xh,name:T.z.string().min(1),display:T.z.strictObject({singular:T.z.string().optional(),plural:T.z.string().optional()}).nullish(),event_names:T.z.array(T.z.string()).default([]),model_markups:So,stripe_meter:T.z.strictObject({id:T.z.string(),event_name:T.z.string()}).nullish(),stripe_product_id:T.z.string().nullish()},ts=e=>T.z.discriminatedUnion("type",[T.z.strictObject({...yo,...e,type:T.z.literal("boolean"),config:T.z.null()}),T.z.strictObject({...yo,...e,type:T.z.literal("metered"),config:Oh}),T.z.strictObject({...yo,...e,type:T.z.literal("credit_system"),config:zu}),T.z.strictObject({...yo,...e,type:T.z.literal("ai_credit_system"),config:es})]),K0=ts({}),Ch=T.z.strictObject({id:T.z.boolean(),type:T.z.boolean(),usage_type:T.z.boolean()}),Ph={internal_id:T.z.uuid(),org_id:T.z.uuid(),created_at:T.z.number(),env:T.z.enum(["sandbox","live"]),archived:T.z.boolean(),project_id:T.z.uuid(),environment_id:T.z.uuid(),revision:T.z.number().int().nonnegative(),update_rules:Ch},$u=ts(Ph),H0=T.z.strictObject({rows:T.z.array($u).max(200),nextCursor:T.z.uuid().nullable()}),Q0=T.z.strictObject({features:T.z.array($u).max(500),limited:T.z.boolean()}),J0=T.z.union([ts({action:T.z.literal("save"),internal_id:T.z.uuid().nullable(),revision:T.z.number().int().nonnegative()}),T.z.strictObject({action:T.z.enum(["archive","restore","delete"]),internal_id:T.z.uuid(),revision:T.z.number().int().nonnegative()})]);var hr=require("zod");var nt=require("zod"),Lt=nt.z.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),me=nt.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),xo=nt.z.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}),ns=me.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Gu=nt.z.string().min(1).max(64),fr=nt.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Ku=nt.z.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),At=nt.z.record(Gu,nt.z.union([nt.z.string().max(120),nt.z.number().finite(),nt.z.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)]))),Hu=nt.z.record(Gu,nt.z.union([nt.z.string().max(120),nt.z.number().finite(),nt.z.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),Vr=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},Qu=nt.z.array(nt.z.object({upTo:ns.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&&Vr(t.upTo)>Vr(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),_h=nt.z.object({key:Ku,match:Hu,priority:nt.z.number().int().default(0),cost:me.optional(),tiers:Qu.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),Eh=nt.z.object({key:Ku,match:Hu,factor:ns.optional(),add:xo.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"})),Rh=nt.z.object({units:ns.default("1"),cost:me,tiers:Qu.optional(),dimensions:nt.z.array(_h).max(12).optional(),multipliers:nt.z.array(Eh).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=Vr(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=Vr(o),d=BigInt("1"),m=BigInt("0");for(let[p,g]of r.entries())s&1<<p&&(u*=Vr(g.factor??"1"),d*=BigInt("1000000"),m+=Vr(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"})}}),W0=Rh.safeExtend({featureKey:fr});var gr=require("zod"),Ju=gr.z.number().int().min(0).max(1e8),bi=gr.z.strictObject({kind:gr.z.enum(["graduated","volume"]),tiers:gr.z.array(gr.z.strictObject({upTo:gr.z.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Ju,flatAmountMinor:Ju.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 rs(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?bi.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 Io(e){return rs({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var kh=me.refine(e=>/[1-9]/.test(e)),vo=hr.z.strictObject({units:kh,prices:hr.z.array(hr.z.strictObject({currency:fe,amountMinor:hr.z.number().int().min(0).max(1e8),pricing:bi.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:hr.z.number().int().min(0).max(1e4),maximumQuantity:hr.z.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&&rs({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 Zu(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 Wu(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=Zu(e)+Zu(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:"")}var A=require("zod");var J=require("zod");var St=require("zod");var R=require("zod");function Yu(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 wo(e,t,n){return n===2?Yu(Yu(e+t)+"")%1e4/1e4:null}function jh(e){return e<=0?[]:new Array(e).fill(1/e)}function Oo(e,t){return e>=t[0]&&e<t[1]}function Xu(e,t){for(let[n,r]of t.entries())if(Oo(e,r))return n;return-1}function el(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=jh(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 tl(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 nl(e){try{return e()}catch{return!1}}function Si(e){return typeof e=="string"?e:JSON.stringify(e)}function Jt(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 Th(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function rl(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let a=Fh(e,i.type,i.pattern);if(i.include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function Nh(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 Dh(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=>!Nh(i[0],i[1],i[2]))}catch{return!1}}function Fh(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=Th(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return Dh(r,n);return!1}catch{return!1}}function is(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 Co(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 il(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);Co(e.savedGroups??{})}var Mh=e=>e/2**32|0,qh=e=>e>>>0;function ol(e,t,n,r){let i=Mh(n),a=qh(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function al(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var os=e=>e?`"${e}" `:"";function Vh(e,t=""){if(typeof e!="number")throw new TypeError(os(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(os(t)+"expected integer >= 0, got "+e);return e}function Po(e,t,n=""){if(al(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Vh(t,"length");let r=al(e),i=t!==void 0?` of length ${t}`:"",a=r?`length=${e.length}`:`type=${typeof e}`,o=os(n)+"expected Uint8Array"+i+", got "+a;throw r?new RangeError(o):new TypeError(o)}var Uh=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},sl=(e,t)=>{Uh(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 as(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function cl(e,t){Po(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function ss(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function _o(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function dn(e,t){return e<<32-t|e>>>t}var Lh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Bh=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ur(e){if(Po(e),Lh)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Bh[e[n]];return t}function zh(e,t,n="opts"){return sl(e,"defaults"),t!==void 0&&sl(t,n),Object.assign(Object.create(null),e,t)}function ul(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=zh({},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 ll=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function dl(e,t,n){return e&t^~e&n}function pl(e,t,n){return e&t^e&n^t&n}var Eo=class{constructor(t,n,r,i){Ue(this,"blockLen");Ue(this,"outputLen");Ue(this,"canXOF",!1);Ue(this,"padOffset");Ue(this,"isLE");Ue(this,"buffer");Ue(this,"view");Ue(this,"finished",!1);Ue(this,"length",0);Ue(this,"pos",0);Ue(this,"destroyed",!1);this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=_o(this.buffer)}update(t){as(this),Po(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=_o(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){as(this),cl(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)),ol(r,i-8,this.length*8,a),this.process(r,0),this.roundClean();let s=t===n?r:_o(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()}},ml=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var $h=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]),Vn=new Uint32Array(64),cs=class extends Eo{constructor(n,r){super(64,n,8,!1);Ue(this,"A",0);Ue(this,"B",0);Ue(this,"C",0);Ue(this,"D",0);Ue(this,"E",0);Ue(this,"F",0);Ue(this,"G",0);Ue(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)Vn[w]=n.getUint32(r,!1);for(let w=16;w<64;w++){let I=Vn[w-15],p=Vn[w-2],g=dn(I,7)^dn(I,18)^I>>>3,f=dn(p,17)^dn(p,19)^p>>>10;Vn[w]=f+Vn[w-7]+g+Vn[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=dn(c,6)^dn(c,11)^dn(c,25),p=m+I+dl(c,u,d)+$h[w]+Vn[w]|0,f=(dn(i,2)^dn(i,13)^dn(i,22))+pl(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(){ss(Vn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ss(this.buffer)}},us=class extends cs{constructor(){super(32,ml)}};var Lr=ul(()=>new us,ll(1));var fl=new Map,ls=32,gl=new WeakMap,hl=new WeakMap;function Gh(e){return Ur(Lr(new TextEncoder().encode(String(e))))}var ko=e=>Array.isArray(e)?e.map(ko):typeof e=="string"||typeof e=="number"?Gh(e):null,Ro=e=>typeof e=="string"?e.toLowerCase():e;function xl(e){let t=gl.get(e);return t||(t=new Set(e),gl.set(e,t)),t}function Kh(e){let t=hl.get(e);return t||(t=new Set(e.map(Ro)),hl.set(e,t)),t}function Br(e){Co(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=ls&&xl(n)}return e}function zt(e,t,n,r){n=n||{},r||Co(n),r=r||new Set;for(let[i,a]of Object.entries(t))switch(i){case"$or":if(!Sl(e,a,n,r))return!1;break;case"$nor":if(Sl(e,a,n,r))return!1;break;case"$and":if(!Wh(e,a,n,r))return!1;break;case"$not":if(zt(e,a,n,r))return!1;break;case"$savedGroup":if(!Hh(e,a,n,r))return!1;break;default:if(!xi(a,Il(e,i),n,!1,r))return!1}return!0}function Hh(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=Il(e,c);return Ar(o.type==="hashed"?ko(u):u,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:zt(e,o.condition,n,s):!1}function Il(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 Al(e,t=!1){let n=`${e}${t?"/i":""}`,r=fl.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),fl.set(n,r)),r}function xi(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)||!vl(e))return JSON.stringify(t)===JSON.stringify(e);let a=e;for(let o in a)if(!Zh(o,t,a[o],n,i))return!1;return!0}function vl(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function Qh(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 Jh(e,t,n,r){if(!Array.isArray(e))return!1;let i=vl(t)?a=>xi(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 Ar(e,t,n=!1){if(n){let i;if(t.length>=ls){let a=Kh(t);i=o=>{let s=Ro(o);return!(typeof s=="number"&&Number.isNaN(s))&&a.has(s)}}else i=a=>t.some(o=>Ro(a)===Ro(o));return Array.isArray(e)?e.some(a=>i(a)):i(e)}let r=t.length>=ls?(i=>a=>i.has(a))(xl(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function yl(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function bl(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(xi(t[a],e[s],n,r,i)){o=!0;break}if(!o)return!1}return!0}function Zh(e,t,n,r,i=new Set){let a=t,o=n;switch(e){case"$veq":return Jt(t)===Jt(n);case"$vne":return Jt(t)!==Jt(n);case"$vgt":return Jt(t)>Jt(n);case"$vgte":return Jt(t)>=Jt(n);case"$vlt":return Jt(t)<Jt(n);case"$vlte":return Jt(t)<=Jt(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)?Ar(t,n):!1;case"$ini":return Array.isArray(n)?Ar(t,n,!0):!1;case"$inGroup":{let s=r[n],c=yl(s);return c===null?!1:Ar(s?.type==="hashed"?ko(t):t,c)}case"$notInGroup":{let s=r[n],c=yl(s);return c===null?!1:!Ar(s?.type==="hashed"?ko(t):t,c)}case"$nin":return Array.isArray(n)?!Ar(t,n):!1;case"$nini":return Array.isArray(n)?!Ar(t,n,!0):!1;case"$not":return!xi(n,t,r,!1,i);case"$size":return Array.isArray(t)?xi(n,t.length,r,!1,i):!1;case"$elemMatch":return Jh(t,n,r,i);case"$all":return Array.isArray(n)?bl(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?bl(t,n,r,!0,i):!1;case"$regex":try{return Al(n).test(t)}catch{return!1}case"$regexi":try{return Al(n,!0).test(t)}catch{return!1}case"$type":return Qh(t)===n;default:return!1}}function Sl(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 Wh(e,t,n,r){for(let i of t)if(!zt(e,i,n,r))return!1;return!0}function ds(e){return il(e),{context:e,stack:{evaluatedFeatures:new Set}}}function ps(e){return{...e.attributes,...e.attributeOverrides}}function Un(e,t,n){let r=t||"id",i="",a=ps(e);return a[r]&&(i=a[r]),!i&&n&&(a[n]&&(i=a[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function He(e,t,n){e.context.log?.(t,n)}function jo(e,t){return t=t||0,`${e}__${t}`}function ms(e,t){return`${e}||${t}`}function Yh(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=Un(e,t),o=ms(i,Si(a)),{hashAttribute:s,hashValue:c}=Un(e,n),u=c?ms(s,Si(c)):null,d={};return u&&r[u]&&Object.assign(d,r[u].assignments||{}),r[o]&&Object.assign(d,r[o].assignments||{}),d}function wl({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=jo(t,n),c=Yh(e,r,i);if(a>0)for(let m=0;m<a;m++){let w=jo(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 Ol(e,t,n,r){let i=ms(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 Cl(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function To(e,t){let n=ds(t),r=_l(e,null,n);return t.onExperimentEval?.(e,r),r}function En(e,t){return gs(e,ds(t))}function Xh(e){return e.forcedVariations||{}}function Pl(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=kl(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}fs(()=>r.onExperimentViewed?.(t,n))}function eA(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}fs(()=>r.onFeatureUsage?.(t,n))}function fs(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function gs(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return He(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),Ln(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let a of r?.rules??[])is(a);let i=n.forcedFeatureValues;if(i&&i.has(e))return He(t,"Global override",{id:e,value:i.get(e)}),Ln(t,e,i.get(e),"override");if(!r)return He(t,"Unknown feature",{id:e}),Ln(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=gs(u.id,t);if(d.source==="cyclicPrerequisite")return Ln(t,e,null,"cyclicPrerequisite");let m={value:d.value};if(!zt(m,u.condition||{},n.savedGroups||{})){if(u.gate)return He(t,"Feature blocked by prerequisite",{id:e,rule:o}),Ln(t,e,null,"prerequisite");He(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&Rl(o.filters,t)){He(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!El(o.condition,t)){He(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!tA(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){He(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return He(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(u=>{Pl(t,u.experiment,u.result)}),Ln(t,e,o.force,"force",o.id)}if(!o.variations){He(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=_l(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return Ln(t,e,c.value,"experiment",o.id,s,c)}}return He(t,"Use default value",{id:e,value:r.defaultValue}),Ln(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function _l(e,t,n){let{context:r}=n;is(e);let i=e.key,a=e.variations.length;if(a<2)return He(n,"Invalid experiment",{id:i}),Ct(n,e,-1,!1,t);if(r.enabled===!1)return He(n,"Context disabled",{id:i}),Ct(n,e,-1,!1,t);if(e.urlPatterns&&!rl(r.url||"",e.urlPatterns))return He(n,"Skip because of url targeting",{id:i}),Ct(n,e,-1,!1,t);let o=tl(i,r.url||"",a);if(o!==null)return He(n,"Force via querystring",{id:i,variation:o}),Ct(n,e,o,!1,t);let c=Xh(r)[i];if(c!==void 0)return He(n,"Force via dev tools",{id:i,variation:c}),Ct(n,e,c,!1,t);if(e.active===!1)return He(n,"Skip because inactive",{id:i}),Ct(n,e,-1,!1,t);let{hashAttribute:u,hashValue:d}=Un(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!d)return He(n,"Skip because missing hashAttribute",{id:i}),Ct(n,e,-1,!1,t);let m=-1,w=!1,I=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:f,versionIsBlocked:S}=wl(Cl({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&&Rl(e.filters,n))return He(n,"Skip because of filters",{id:i}),Ct(n,e,-1,!1,t);if(e.include&&!nl(e.include))return He(n,"Skip because of include function",{id:i}),Ct(n,e,-1,!1,t);if(e.condition&&!El(e.condition,n))return He(n,"Skip because of condition exp",{id:i}),Ct(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=gs(S.id,n);if(h.source==="cyclicPrerequisite")return Ct(n,e,-1,!1,t);let P={value:h.value};if(!zt(P,S.condition||{},r.savedGroups||{}))return He(n,"Skip because prerequisite evaluation fails",{id:i}),Ct(n,e,-1,!1,t)}}}let p=wo(e.seed||i,d,e.hashVersion??2);if(p===null)return He(n,"Skip because of invalid hash version",{id:i}),Ct(n,e,-1,!1,t);if(!w){let f=e.ranges||el(a,e.coverage===void 0?1:e.coverage,e.weights);m=Xu(p,f)}if(I)return He(n,"Skip because sticky bucket version is blocked",{id:i}),Ct(n,e,-1,!1,t,void 0,!0);if(m<0)return He(n,"Skip because of coverage",{id:i}),Ct(n,e,-1,!1,t);if("force"in e)return He(n,"Force variation",{id:i,variation:e.force}),Ct(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return He(n,"Skip because QA mode",{id:i}),Ct(n,e,-1,!1,t);let g=Ct(n,e,m,!0,t,p,w);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:f,key:S,doc:h}=Ol(r,u,Si(d),{[jo(e.key,e.bucketVersion)]:g.key});if(f){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[S]=h;let P=r.saveStickyBucketAssignmentDoc;fs(()=>P(h))}}return Pl(n,e,g),He(n,"In experiment",{id:i,variation:g.variationId}),g}function Ln(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"&&eA(e,t,s),s}function El(e,t){return zt(ps(t.context),e,t.context.savedGroups||{})}function Rl(e,t){return e.some(n=>{let{hashValue:r}=Un(t.context,n.attribute);if(!r)return!0;let i=wo(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(a=>Oo(i,a))})}function tA(e,t,n,r,i,a,o){if(!i&&a===void 0)return!0;if(!i&&a===0)return!1;let{hashValue:s}=Un(e.context,n,r);if(!s)return!1;let c=wo(t,s,o??2);return c===null?!1:i?Oo(c,i):a!==void 0?c<=a:!0}function Ct(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}=Un(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 kl(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.z.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"})}),yt=R.z.record(R.z.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"})}),nA=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=yt.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.z.strictObject({id:R.z.uuid(),attributeKey:R.z.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("$")&&!nA.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)}),rA=R.z.discriminatedUnion("type",[R.z.strictObject({type:R.z.literal("condition"),condition:Bt}),R.z.strictObject({type:R.z.literal("list"),attributeKey:R.z.string().min(1).max(128),values:R.z.array(R.z.union([R.z.string(),R.z.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 Rn(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 iA=R.z.record(R.z.uuid(),rA).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"&&Rn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),As=R.z.tuple([R.z.number().min(0).max(1),R.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),jl=R.z.strictObject({attribute:R.z.string().optional(),seed:R.z.string().min(1),hashVersion:R.z.literal(2),ranges:R.z.array(As).min(1).max(100)}),oA=R.z.strictObject({id:R.z.string().min(1).max(128),condition:Bt,gate:R.z.boolean().optional()}),hs={id:R.z.string().max(128).optional(),condition:Bt.optional(),parentConditions:R.z.array(oA).max(50).optional(),filters:R.z.array(jl).max(20).optional()},aA=R.z.union([R.z.strictObject({...hs}),R.z.strictObject({...hs,force:ge,coverage:R.z.number().min(0).max(1).optional(),range:As.optional(),seed:R.z.string().min(1).optional(),hashAttribute:R.z.string().optional(),hashVersion:R.z.literal(2).optional()}),R.z.strictObject({...hs,type:R.z.literal("experiment-ref"),experimentId:R.z.uuid(),values:R.z.record(R.z.string().min(1),ge),meta:R.z.record(R.z.string().min(1),R.z.strictObject({passthrough:R.z.boolean()})).optional()})]),sA=R.z.strictObject({defaultValue:ge,rules:R.z.array(aA).max(100)}),$I=R.z.record(R.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),sA).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)}),cA=R.z.strictObject({name:R.z.string().max(80),reason:R.z.string().max(500),dateStarted:R.z.iso.datetime({offset:!0}),dateEnded:R.z.iso.datetime({offset:!0}).nullable(),coverage:R.z.number().min(0).max(1),variationWeights:R.z.array(R.z.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.z.array(R.z.strictObject({match:R.z.enum(["any","all","none"]),ids:R.z.array(R.z.uuid()).min(1)})).max(50),namespace:R.z.strictObject({id:R.z.uuid(),ranges:R.z.array(As).min(1)}).nullable(),seed:R.z.string().min(1).max(128)}),uA=R.z.strictObject({key:R.z.string().min(1).max(128),name:R.z.string().min(1).max(80),hypothesis:R.z.string().max(2e3),status:R.z.enum(["draft","running","stopped"]),hashAttribute:R.z.string().min(1).max(128),fallbackAttribute:R.z.string().max(128).nullable(),hashVersion:R.z.literal(2),disableStickyBucketing:R.z.boolean(),bucketVersion:R.z.number().int().min(0).max(1e3),minBucketVersion:R.z.number().int().min(0).max(1e3),variations:R.z.array(R.z.strictObject({id:R.z.string().min(1),key:R.z.string().min(1),name:R.z.string().max(80),description:R.z.string().max(500)})).min(2).max(20),phases:R.z.array(cA).min(1).max(100),releasedVariationId:R.z.string().nullable(),excludeFromPayload:R.z.boolean(),statusSchedule:R.z.strictObject({startAt:R.z.iso.datetime({offset:!0}).nullable(),stopAt:R.z.iso.datetime({offset:!0}).nullable(),stopAfter:R.z.strictObject({value:R.z.number().int().positive().max(36500),unit:R.z.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 lA=uA.safeExtend({filters:R.z.array(jl).optional()}),dA=R.z.strictObject({experiments:R.z.record(R.z.uuid(),lA),savedGroups:iA}),Ii=R.z.strictObject({attributeName:R.z.string(),attributeValue:R.z.string(),assignments:R.z.record(R.z.string(),R.z.string())}),GI=R.z.strictObject({snapshot:dA,attributes:yt,results:yt,stickyBucketAssignmentDocs:R.z.record(R.z.string(),Ii)}),KI=R.z.strictObject({variantKey:R.z.string().nullable(),bucketVersion:R.z.number().int().min(0),source:R.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:R.z.number().min(0).max(1).optional(),stickyBucketUsed:R.z.boolean().optional(),hashUsed:R.z.boolean().optional()});function Bn(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 pA=St.z.enum(["active","inactive"]),mA=St.z.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},yt),fA=St.z.strictObject({id:St.z.string().trim().min(1).max(255),name:St.z.string().trim().min(1).max(255),status:pA,metadata:mA}),WI=fA.extend({internal_id:St.z.uuid(),project_id:St.z.uuid(),environment_id:St.z.uuid(),created_at:St.z.iso.datetime({offset:!0}),updated_at:St.z.iso.datetime({offset:!0})}),Nl=St.z.union([St.z.strictObject({id:St.z.string().trim().min(1).max(255)}),St.z.strictObject({internalId:St.z.uuid()})]),YI=St.z.enum(["customer","merchandise","context"]),XI=St.z.enum(["system","stored","request"]),ev=St.z.enum(["customer","merchandise","mixed"]),Tl=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function ys(e,t={},n=new Set){if(Bn(e).some(Tl))return!0;for(let r of Rn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Tl(i.attributeKey)||i?.type==="condition"&&ys(i.condition,t,n))return!0}return!1}var Dl=require("zod"),gA=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,pn=Dl.z.string().max(16).regex(gA,"\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 av=J.z.enum(["draft","active","paused","archived"]),zn=J.z.discriminatedUnion("type",[J.z.object({type:J.z.literal("percent"),percentOff:J.z.number().min(1).max(100).multipleOf(.01)}).strict(),J.z.object({type:J.z.literal("amount"),amountOffCents:J.z.number().int().min(1).max(1e8),currency:fe}).strict()]),Zt=J.z.discriminatedUnion("type",[J.z.object({type:J.z.literal("once")}).strict(),J.z.object({type:J.z.literal("repeating"),months:J.z.number().int().min(1).max(36)}).strict(),J.z.object({type:J.z.literal("forever")}).strict()]),Fl=[J.z.object({type:J.z.literal("all")}).strict(),J.z.object({type:J.z.literal("plans"),planIds:J.z.array(J.z.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],hA=J.z.discriminatedUnion("type",[...Fl,J.z.strictObject({type:J.z.literal("merchandise"),scope:J.z.discriminatedUnion("type",[J.z.strictObject({type:J.z.literal("all")}),J.z.strictObject({type:J.z.literal("selected"),merchandiseIds:J.z.array(J.z.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),J.z.strictObject({type:J.z.literal("condition"),condition:Bt})])})]),bs=J.z.discriminatedUnion("type",[...Fl,J.z.strictObject({type:J.z.literal("merchandise"),scope:J.z.strictObject({type:J.z.enum(["all","selected","condition"])})})]),AA=J.z.strictObject({firstPurchaseOnly:J.z.boolean(),condition:Bt}),sv=J.z.object({name:J.z.string().trim().min(1).max(80),description:J.z.string().max(500),discount:zn,duration:Zt,appliesTo:hA,eligibility:AA,selfClaimEnabled:J.z.boolean().default(!1),startsAt:J.z.iso.datetime().nullable(),endsAt:J.z.iso.datetime().nullable(),totalLimit:J.z.number().int().min(1).max(1e6).nullable(),perCustomerLimit:J.z.number().int().min(1).max(10),grantWindowHours:J.z.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=>!ys(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"]}),cv=J.z.object({code:J.z.string().trim().transform(e=>e.toUpperCase()).pipe(J.z.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:J.z.number().int().min(1).max(1e6).nullable(),expiresAt:J.z.iso.datetime().nullable(),firstPurchaseOnly:J.z.boolean(),minimumAmountCents:J.z.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 vi=J.z.object({id:J.z.uuid(),couponId:J.z.uuid(),status:J.z.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:J.z.iso.datetime(),expiresAt:J.z.iso.datetime(),coupon:J.z.object({name:J.z.string(),discount:zn,duration:Zt,appliesTo:bs}).strict()}).strict(),Ml=J.z.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Bl=A.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Ss=A.z.string().regex(/^(0|[1-9]\d{0,14})$/),zr=A.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),yA=A.z.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),wi=yA,kn=me.refine(e=>/[1-9]/.test(e)),Ft=A.z.iso.datetime({offset:!0}),No=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"))},bA=A.z.array(A.z.object({upTo:kn.nullable(),unitAmountMinor:Bl,flatAmountMinor:A.z.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&&No(t.upTo)>No(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),SA=A.z.discriminatedUnion("kind",[A.z.object({kind:A.z.literal("flat"),units:kn,unitAmountMinor:Bl}).strict(),A.z.object({kind:A.z.enum(["graduated","volume"]),units:kn,tiers:bA}).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"),xA=A.z.strictObject({interval:A.z.enum(["month","year"]),count:A.z.number().int().min(1).max(12),anchor:A.z.enum(["membership","calendar"])}),Oi=A.z.object({currency:fe,pricing:SA,billingCycle:xA.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var ql={requestId:A.z.uuid(),productVersionId:A.z.uuid(),internal_feature_id:A.z.uuid(),currency:fe},zl=A.z.strictObject({interval:A.z.enum(["hour","day","week","month"]),intervalCount:A.z.number().int().min(1).max(12),limit:A.z.number().int().min(1).max(1e6)}),$l=A.z.discriminatedUnion("kind",[A.z.object({...ql,kind:A.z.literal("auto_topup"),threshold:xo,quantity:kn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:zl.optional()}).strict(),A.z.object({...ql,kind:A.z.literal("postpaid"),maxAmountMinorPerPeriod:wi,maxOutstandingMinor:wi}).strict()]),Vl={productVersionId:A.z.uuid(),internal_feature_id:A.z.uuid(),currency:fe},Gl=A.z.discriminatedUnion("kind",[A.z.object({...Vl,kind:A.z.literal("auto_topup"),threshold:xo,quantity:kn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:zl.optional(),purchaseAmountMinor:wi,purchaseUnits:kn}).strict(),A.z.object({...Vl,kind:A.z.literal("postpaid"),maxAmountMinorPerPeriod:wi,maxOutstandingMinor:wi,cashPrice:Oi}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Do=A.z.object({id:A.z.uuid(),terms:Gl,status:A.z.enum(["prepared","active","revoked","blocked"]),createdAt:Ft,acceptedAt:Ft.nullable(),effectiveAt:Ft.nullable(),revokedAt:Ft.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"),Kl=A.z.object({authorizationId:A.z.uuid(),terms:Gl,setupUrl:A.z.url().nullable()}).strict(),Hl=A.z.object({authorizationId:A.z.uuid(),accepted:A.z.literal(!0)}).strict(),Ql=A.z.object({authorizationId:A.z.uuid(),requestId:A.z.uuid()}).strict(),Jl=A.z.object({internal_feature_id:A.z.uuid(),entityId:A.z.uuid().nullable(),interval:A.z.enum(["day","week","month","year"]),anchor:A.z.enum(["billing_cycle","utc"]).optional(),basis:A.z.enum(["usage","credits"]),filter:At.optional(),limit:me.nullable(),thresholds:A.z.array(A.z.number().positive().max(1)).max(8),includedThresholds:A.z.array(A.z.number().positive().max(1)).max(8).optional(),absoluteThresholds:A.z.array(kn).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&&No(t)>No(i)}),"Notification thresholds must increase"),IA=Jl.safeExtend({requestId:A.z.uuid()}),Ul={control:A.z.literal("overage"),requestId:A.z.uuid(),internal_feature_id:A.z.uuid(),entityId:A.z.uuid().nullable()},vA=A.z.discriminatedUnion("action",[A.z.strictObject({...Ul,action:A.z.literal("set"),allowed:A.z.boolean().nullable(),overageLimit:me.nullable(),skipOverageBilling:A.z.boolean()}),A.z.strictObject({...Ul,action:A.z.literal("remove")})]),Zl=A.z.union([IA,vA]),wA=A.z.strictObject({internal_feature_id:A.z.uuid(),entityId:A.z.uuid().nullable(),allowed:A.z.boolean().nullable(),overageLimit:me.nullable(),skipOverageBilling:A.z.boolean(),interval:A.z.enum(["day","week","month","year"]),startsAt:Ft,endsAt:Ft,used:A.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:A.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:A.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),OA=A.z.object({internal_feature_id:A.z.uuid(),entityId:A.z.uuid().nullable(),interval:A.z.enum(["day","week","month","year"]),anchor:A.z.enum(["billing_cycle","utc"]).optional(),basis:A.z.enum(["usage","credits"]),filter:At.optional(),startsAt:Ft,endsAt:Ft,used:Lt,reserved:Lt,limit:me.nullable(),thresholds:A.z.array(A.z.number().positive().max(1)).max(8),notifiedThresholds:A.z.array(A.z.number().positive().max(1)).max(1024),includedThresholds:A.z.array(A.z.number().positive().max(1)).max(8).optional(),includedAllowance:A.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:A.z.array(A.z.number().positive().max(1)).max(1024).optional(),absoluteThresholds:A.z.array(kn).max(8).optional(),notifiedAbsoluteThresholds:A.z.array(kn).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"),CA=A.z.object({authorizationId:A.z.uuid(),status:A.z.enum(["idle","pending","blocked"]),taskId:A.z.uuid().nullable(),invoiceId:A.z.uuid().nullable(),hostedInvoiceUrl:A.z.url().nullable(),purchaseCount:A.z.number().int().nonnegative(),purchaseWindowEndsAt:Ft.nullable(),attemptCount:A.z.number().int().nonnegative(),failedAttemptCount:A.z.number().int().nonnegative(),suspendedAt:Ft.nullable(),nextAttemptAt:Ft.nullable(),failureReason:A.z.string().min(1).max(240).nullable()}).strict(),Wl=A.z.object({internal_feature_id:A.z.uuid().optional(),entityId:A.z.uuid().optional()}).strict(),xs=A.z.object({authorizations:A.z.array(Do).max(100),limits:A.z.array(Jl).max(100),overages:A.z.array(wA).max(100).optional(),windows:A.z.array(OA).max(200),autoTopups:A.z.array(CA).max(100),limited:A.z.boolean()}).strict(),PA=A.z.object({id:A.z.uuid(),internal_feature_id:A.z.uuid(),productVersionId:A.z.uuid(),authorizationId:A.z.uuid(),entityId:A.z.uuid().nullable(),units:me,amountMinor:zr,cashPrice:Oi}).strict(),Ci=A.z.object({id:A.z.uuid(),sourceKind:A.z.enum(["product","usage","manual"]),providerInvoiceId:A.z.string().min(1).max(240).nullable(),status:A.z.enum(["accruing","open","pending","paid","failed","void"]),currency:fe,startsAt:Ft.nullable(),endsAt:Ft.nullable(),amountMinor:A.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:A.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Ss,paidAmountMinor:Ss,refundedAmountMinor:Ss,createdAt:Ft,hostedInvoiceUrl:A.z.url().nullable(),adjustment:A.z.object({originalInvoiceId:A.z.uuid(),amountMinor:A.z.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:Ft.nullable()}).strict().nullable(),lines:A.z.array(PA).max(100),linesLimited:A.z.boolean()}).strict(),Yl=A.z.object({invoiceId:A.z.uuid(),accepted:A.z.literal(!0)}).strict(),Xl=A.z.object({after:A.z.uuid().nullable(),limit:A.z.number().int().min(1).max(100)}).strict(),ed=A.z.object({rows:A.z.array(Ci).max(100),nextCursor:A.z.uuid().nullable()}).strict(),Ll=A.z.strictObject({id:A.z.string(),coupon:A.z.string(),start:A.z.number().nonnegative(),end:A.z.number().nullable()}),_A=A.z.strictObject({subscriptionId:A.z.string(),customerId:A.z.string(),accountId:A.z.string(),sourceItems:A.z.array(A.z.strictObject({id:A.z.string(),price_id:A.z.string(),quantity:A.z.number().int(),discounts:A.z.array(Ll).optional()})).max(100),items:A.z.array(A.z.strictObject({id:A.z.string(),price:A.z.string(),quantity:A.z.number().int(),discounts:A.z.array(A.z.strictObject({coupon:A.z.string().optional(),terms:A.z.strictObject({id:A.z.string(),name:A.z.string().optional(),percent_off:A.z.number().optional(),amount_off:A.z.number().optional(),currency:A.z.string().optional(),duration:A.z.enum(["once","forever","repeating"]),duration_in_months:A.z.number().optional()}).optional(),discount:A.z.string().optional(),receipt:Ll.optional()})).max(20)})).max(100)}),td=A.z.strictObject({membershipId:A.z.uuid(),requestId:A.z.uuid(),grantIds:A.z.array(A.z.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),nd=A.z.strictObject({membershipId:A.z.uuid(),operationId:A.z.uuid(),status:A.z.enum(["pending","effective"]),execution:_A.nullable(),grants:A.z.array(A.z.strictObject({id:A.z.uuid(),couponId:A.z.uuid(),name:A.z.string(),discount:zn,duration:Zt,startedAt:Ft.nullable()})).max(20)});var $r=require("zod");var rd=$r.z.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),id=$r.z.number().int().min(1).max(1e3),Fo=$r.z.object({cap:me.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:$r.z.number().positive().max(1e4).nullable(),cycles:$r.z.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var jn=require("zod");var od=jn.z.strictObject({itemKey:jn.z.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:jn.z.uuid(),includedAmount:jn.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:jn.z.number().int().min(0).max(1e4),terms:vo,pricing:bi.optional(),unitAmountMinor:jn.z.number().int().min(0).max(1e8),productId:jn.z.string().min(1).max(255).nullable(),priceId:jn.z.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{Wu(e.includedAmount,e.terms.units,e.quantity),Io({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"})}});var Z=require("zod");var yr=me.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Pi=Z.z.string().min(1).max(120),Mo=Z.z.enum(["cap","overflow"]),Wt=(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"))},_i=e=>{try{return e()}catch{return!1}},Ei=Z.z.discriminatedUnion("operation",[Z.z.object({operation:Z.z.literal("quote"),overageBehavior:Mo.optional(),internal_feature_id:Z.z.uuid(),entityId:Z.z.uuid().optional(),quantity:yr,properties:At}).strict(),Z.z.object({operation:Z.z.literal("consume"),overageBehavior:Mo.optional(),occurredAt:Z.z.iso.datetime({offset:!0}).optional(),internal_feature_id:Z.z.uuid(),entityId:Z.z.uuid().optional(),quantity:me,properties:At,idempotencyKey:Pi}).strict(),Z.z.object({operation:Z.z.literal("reserve"),occurredAt:Z.z.iso.datetime({offset:!0}).optional(),internal_feature_id:Z.z.uuid(),entityId:Z.z.uuid().optional(),quantity:yr,properties:At,idempotencyKey:Pi,expiresInSeconds:Z.z.number().int().min(1).max(86400)}).strict(),Z.z.object({operation:Z.z.literal("confirm"),operationId:Z.z.uuid(),quantity:yr,properties:At.optional(),idempotencyKey:Pi}).strict(),Z.z.object({operation:Z.z.literal("refund"),operationId:Z.z.uuid(),quantity:yr,idempotencyKey:Pi}).strict(),Z.z.object({operation:Z.z.literal("release"),operationId:Z.z.uuid(),idempotencyKey:Pi}).strict()]),Is=Z.z.object({internal_credit_feature_id:Z.z.uuid().nullable(),internal_metered_feature_id:Z.z.uuid(),dimension:Z.z.string().min(1).max(64),counterKey:Z.z.string().min(1).max(240),cycleStart:Z.z.iso.datetime({offset:!0}),unitCost:me,units:yr,amount:Lt,tier:Z.z.number().int().min(1).max(12).nullable()}).strict(),br=Z.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function ad(e,t){let n=e.reduce((r,i)=>r+Wt(i.units,12),0n)-Wt(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var sd=Z.z.discriminatedUnion("funding",[Z.z.strictObject({funding:Z.z.literal("balance"),sourceId:Z.z.uuid(),rolloverId:Z.z.uuid().nullable(),units:br.refine(e=>/[1-9]/.test(e)),amount:Lt}),Z.z.strictObject({funding:Z.z.literal("unbilled"),units:br.refine(e=>/[1-9]/.test(e))}),Z.z.object({funding:Z.z.literal("prepaid"),sourceId:Z.z.uuid(),units:yr,amount:Lt,pricing:Z.z.array(Is).min(1).max(12)}).strict().refine(e=>_i(()=>e.pricing.reduce((t,n)=>t+Wt(n.units,6),0n)===Wt(e.units,6)&&e.pricing.reduce((t,n)=>t+Wt(n.amount,12),0n)===Wt(e.amount,12)&&e.pricing.every(t=>Wt(t.unitCost,6)*Wt(t.units,6)===Wt(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),Z.z.object({funding:Z.z.literal("postpaid"),invoiceLineId:Z.z.uuid().nullable(),units:yr,authorizationId:Z.z.uuid()}).strict()]),qo=Z.z.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),cd=Z.z.object({allowed:Z.z.boolean(),internal_feature_id:Z.z.uuid(),quantity:me,requestedQuantity:me.optional(),overageBehavior:Mo.optional(),reason:qo.nullable(),allocations:Z.z.array(sd).max(500)}).strict().refine(e=>_i(()=>e.allowed?e.reason===null&&ad(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>_i(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&Wt(e.requestedQuantity,6)>=Wt(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Ri=Z.z.object({id:Z.z.uuid(),internal_feature_id:Z.z.uuid(),kind:Z.z.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:Z.z.uuid().nullable(),quantity:me,requestedQuantity:me.optional(),overageBehavior:Mo.optional(),accepted:Z.z.boolean(),reason:Z.z.enum([...qo.options,"expired"]).nullable(),createdAt:Z.z.iso.datetime({offset:!0}),reservationStatus:Z.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:Z.z.iso.datetime({offset:!0}).nullable(),allocations:Z.z.array(sd).max(500)}).strict().refine(e=>_i(()=>e.accepted?e.reason===null&&ad(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>_i(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&Wt(e.requestedQuantity,6)>=Wt(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");var Pe=require("zod");var Sr=Pe.z.iso.datetime({offset:!0}),ud=me.refine(e=>/[1-9]/.test(e)),ld=Pe.z.strictObject({interval:rd.exclude(["lifetime"]),count:id}),EA=Pe.z.strictObject({action:Pe.z.literal("create"),requestId:Pe.z.uuid(),internal_feature_id:Pe.z.uuid(),entityId:Pe.z.uuid().nullable(),amount:ud.nullable(),expiresAt:Sr.nullable(),reset:ld.nullable(),rollover:Fo.nullable(),nextResetAt:Sr.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"),dd=Pe.z.discriminatedUnion("action",[EA,Pe.z.strictObject({action:Pe.z.literal("update"),requestId:Pe.z.uuid(),grantId:Pe.z.uuid(),revision:Pe.z.number().int().nonnegative(),amount:ud.nullable(),expiresAt:Sr.nullable(),rollover:Fo.nullable(),nextResetAt:Sr.nullable()}),Pe.z.strictObject({action:Pe.z.enum(["add","subtract","set_remaining"]),requestId:Pe.z.uuid(),grantId:Pe.z.uuid(),revision:Pe.z.number().int().nonnegative(),amount:me}),Pe.z.strictObject({action:Pe.z.literal("revoke"),requestId:Pe.z.uuid(),grantId:Pe.z.uuid(),revision:Pe.z.number().int().nonnegative()})]),vs=Pe.z.strictObject({id:Pe.z.uuid(),internal_feature_id:Pe.z.uuid(),entityId:Pe.z.uuid().nullable(),amount:me.nullable(),reset:ld.nullable(),rollover:Fo.nullable(),nextResetAt:Sr.nullable(),startsAt:Sr,expiresAt:Sr.nullable(),revision:Pe.z.number().int().nonnegative(),revoked:Pe.z.boolean(),available:Lt,held:Lt,spent:Lt}),pd=Pe.z.strictObject({customerId:Pe.z.uuid(),after:Pe.z.uuid().nullable(),limit:Pe.z.number().int().min(1).max(100)}),md=Pe.z.strictObject({rows:Pe.z.array(vs).max(100),nextCursor:Pe.z.uuid().nullable()});var ee=require("zod");var xn=ee.z.iso.datetime({offset:!0}),fd=ee.z.strictObject({invoiceId:ee.z.uuid(),after:ee.z.string().min(1).max(180).nullable(),limit:ee.z.number().int().min(1).max(100)}),RA=ee.z.strictObject({kind:ee.z.literal("product"),key:ee.z.string(),productVersionId:ee.z.uuid(),productName:ee.z.string(),itemKey:ee.z.string(),entityId:ee.z.uuid().nullable(),quantity:ee.z.number().positive(),subtotalMinor:ee.z.string().regex(/^-?\d+$/),discountMinor:ee.z.string().regex(/^\d+$/),taxMinor:ee.z.string().regex(/^-?\d+$/).nullable(),totalMinor:ee.z.string().regex(/^-?\d+$/),startsAt:xn.nullable(),endsAt:xn.nullable(),providerLineId:ee.z.string().nullable(),providerItemId:ee.z.string()}),gd=ee.z.strictObject({invoice:Ci,items:ee.z.array(ee.z.discriminatedUnion("kind",[RA,ee.z.strictObject({kind:ee.z.literal("invoice_credit"),key:ee.z.string(),internal_feature_id:ee.z.uuid(),internal_credit_feature_id:ee.z.uuid(),name:ee.z.string(),units:me,reserved:me,amountMinor:zr,grossAmountMinor:zr,creditsAppliedMinor:zr,properties:At,cashPrice:Oi,providerItemId:ee.z.string().nullable(),creditProviderItemId:ee.z.string().nullable()}),ee.z.strictObject({kind:ee.z.literal("usage"),key:ee.z.string(),internal_feature_id:ee.z.uuid(),name:ee.z.string(),units:me,reserved:me,amountMinor:zr,cashPrice:Oi})])).max(100),nextCursor:ee.z.string().min(1).max(180).nullable()}),kA=ee.z.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),ws=ee.z.strictObject({from:xn,to:xn,entityId:ee.z.uuid().optional(),snapshotAt:xn.nullable(),after:ee.z.strictObject({at:xn,id:ee.z.uuid(),position:ee.z.number().int().nonnegative()}).nullable(),limit:ee.z.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"),hd=ee.z.strictObject({customerId:ee.z.uuid(),entityId:ee.z.uuid().nullable(),from:xn,to:xn,snapshotAt:xn,totals:ee.z.array(ee.z.strictObject({internal_credit_feature_id:ee.z.uuid(),name:ee.z.string(),consumed:Lt,refunded:Lt,net:kA})).max(1e3),rows:ee.z.array(ee.z.strictObject({operationId:ee.z.uuid(),position:ee.z.number().int().nonnegative(),kind:ee.z.enum(["consume","confirm","refund"]),originalId:ee.z.uuid().nullable(),occurredAt:xn,internal_feature_id:ee.z.uuid(),entitlementName:ee.z.string(),sourceId:ee.z.uuid(),internal_credit_feature_id:ee.z.uuid(),creditName:ee.z.string(),units:br,amount:Lt,pricing:ee.z.array(Is).max(12),properties:At})).max(100),nextCursor:ws.shape.after});var k=require("zod");var on=require("zod");var jA=on.z.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),TA=on.z.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Vo=on.z.strictObject({internal_feature_id:on.z.uuid(),entityId:on.z.uuid().nullable()}),Ad=Vo.extend({quantity:me,expectedRevision:on.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:on.z.string().min(1).max(120),properties:At.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),ki=Vo.extend({operationId:on.z.uuid().nullable(),usage:me,capacity:jA.nullable(),remaining:TA.nullable(),withinLimit:on.z.boolean(),revision:on.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:on.z.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 Mt=k.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),mn=k.z.iso.datetime({offset:!0}),NA=k.z.enum(["access","metered","credit"]),ji={internal_feature_id:k.z.uuid(),key:fr,name:k.z.string().min(1).max(120),kind:NA},yd=k.z.object({customerId:k.z.uuid(),snapshotAt:mn,memberships:k.z.array(k.z.object({id:k.z.uuid(),productId:k.z.string().min(1).max(255),productVersionId:k.z.uuid(),billingProductVersionId:k.z.uuid(),version:k.z.number().int().positive(),key:k.z.string().min(1).max(64),name:k.z.string().min(1).max(120),groupId:k.z.string().max(255).nullable(),membershipType:k.z.enum(["main","addon"]),status:k.z.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:k.z.boolean(),accessEnabled:k.z.boolean(),renewalChange:k.z.object({productVersionId:k.z.uuid(),name:k.z.string().min(1).max(120),version:k.z.number().int().positive(),effectiveAt:mn,benefitsAppliedAt:mn.nullable(),timing:k.z.enum(["immediate","renewal"]),changeKind:k.z.enum(["plan","seats","quantity"]),feature:k.z.strictObject({internal_feature_id:k.z.uuid(),name:k.z.string().min(1).max(80),fromQuantity:k.z.number().int().min(0).max(1e4),toQuantity:k.z.number().int().min(0).max(1e4)}).optional(),seat:k.z.object({key:k.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:k.z.number().int().min(0).max(1e4),toQuantity:k.z.number().int().min(0).max(1e4)}).strict().nullable(),status:k.z.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.z.object({phase:k.z.enum(["paid","trial"]),startsAt:mn,endsAt:mn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:k.z.boolean(),balances:k.z.array(k.z.object({...ji,usageType:k.z.enum(["consumable","non_consumable"]).nullable(),accessible:k.z.boolean(),unlimited:k.z.boolean(),available:Mt,held:Mt,debt:Mt,nextExpiresAt:mn.nullable(),usage:ki.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.z.boolean()}).strict(),bd=k.z.enum(["source","usage","transaction","invoice","debt","settlement"]),Uo=k.z.object({at:mn,id:k.z.uuid(),type:bd}).strict(),Sd=k.z.object({type:bd.nullable(),resourceKey:fr.optional(),kind:k.z.enum(["purchase","refund"]).optional(),topup:k.z.boolean().optional(),from:k.z.iso.date().nullable(),to:k.z.iso.date().nullable(),after:Uo.nullable(),limit:k.z.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),Gr={id:k.z.uuid(),occurredAt:mn},DA=k.z.discriminatedUnion("type",[k.z.strictObject({...Gr,type:k.z.literal("invoice"),status:k.z.string().min(1).max(80),paid:Mt,refunded:Mt,currency:fe,externalId:k.z.string().nullable()}),k.z.object({...Gr,...ji,type:k.z.literal("source"),reason:k.z.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Mt,unlimited:k.z.boolean(),status:k.z.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:mn,expiresAt:mn.nullable(),orderId:k.z.uuid().nullable(),parentSourceId:k.z.uuid().nullable()}).strict(),k.z.object({...Gr,type:k.z.literal("usage"),internal_feature_id:k.z.uuid(),name:k.z.string().min(1).max(120),kind:k.z.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:k.z.uuid().nullable(),quantity:me,accepted:k.z.boolean(),reason:k.z.enum([...qo.options,"expired"]).nullable(),properties:At,reservationStatus:k.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:mn.nullable(),charges:k.z.array(k.z.discriminatedUnion("funding",[k.z.strictObject({funding:k.z.literal("balance"),sourceId:k.z.uuid(),rolloverId:k.z.uuid().nullable(),units:br,amount:Mt}),k.z.strictObject({funding:k.z.literal("unbilled"),units:br}),k.z.object({...ji,funding:k.z.literal("prepaid"),amount:Mt}).strict(),k.z.object({funding:k.z.literal("postpaid"),invoiceId:k.z.uuid(),invoiceLineId:k.z.uuid(),authorizationId:k.z.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.z.object({...Gr,type:k.z.literal("transaction"),purpose:k.z.enum(["product","invoice"]),productVersionId:k.z.uuid().nullable(),productName:k.z.string().min(1).max(120).nullable(),productVersion:k.z.number().int().positive().nullable(),invoiceId:k.z.uuid().nullable(),orderId:k.z.uuid(),originalId:k.z.uuid().nullable(),kind:k.z.enum(["purchase","refund"]),amountMinor:k.z.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.z.object({...Gr,...ji,type:k.z.literal("debt"),sourceId:k.z.uuid(),transactionId:k.z.uuid(),amount:Mt}).strict(),k.z.object({...Gr,...ji,type:k.z.literal("settlement"),sourceId:k.z.uuid(),debtId:k.z.uuid(),kind:k.z.enum(["payment","usage_refund","payment_return"]),amount:Mt}).strict()]),xd=k.z.object({customerId:k.z.uuid(),rows:k.z.array(DA).max(50),nextCursor:Uo.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");var ce=require("zod"),vd=ce.z.object({customerId:ce.z.uuid()}).strict(),wd=ce.z.discriminatedUnion("action",[ce.z.object({customerId:ce.z.uuid(),requestId:ce.z.uuid(),action:ce.z.literal("assign"),poolId:ce.z.uuid(),memberCustomerId:ce.z.uuid()}).strict(),ce.z.strictObject({customerId:ce.z.uuid(),requestId:ce.z.uuid(),action:ce.z.literal("assign_entity"),poolId:ce.z.uuid(),entityId:ce.z.uuid()}),ce.z.object({customerId:ce.z.uuid(),requestId:ce.z.uuid(),action:ce.z.literal("release"),poolId:ce.z.uuid(),slotId:ce.z.uuid()}).strict()]),Ti=ce.z.number().int().nonnegative(),Os=ce.z.iso.datetime({offset:!0}),Cs=ce.z.strictObject({internalId:ce.z.uuid(),id:ce.z.string(),name:ce.z.string().nullable(),version:ce.z.number().int().positive()}),Id=ce.z.enum(["active","past_due"]),Ps=ce.z.strictObject({customerId:ce.z.uuid(),licenses:ce.z.array(ce.z.strictObject({id:ce.z.uuid(),linkId:ce.z.uuid(),parent:ce.z.strictObject({customerProductId:ce.z.uuid(),status:Id,product:Cs}),product:Cs,planLicense:ce.z.strictObject({id:ce.z.uuid(),prepaidOnly:ce.z.boolean(),isCustom:ce.z.boolean()}).nullable(),granted:Ti,included:Ti,paidQuantity:Ti,usage:Ti,remaining:Ti,createdAt:Os}).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.z.array(ce.z.strictObject({id:ce.z.uuid(),linkId:ce.z.uuid(),status:Id,product:Cs,entity:ce.z.strictObject({internalId:ce.z.uuid(),id:ce.z.string().nullable(),name:ce.z.string().nullable()}).nullable(),beneficiary:ce.z.strictObject({internalId:ce.z.uuid(),id:ce.z.string().nullable(),name:ce.z.string().nullable()}).nullable(),startedAt:Os.nullable(),endedAt:Os.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:ce.z.boolean()});var oe=require("zod"),Ni=oe.z.enum(["email","sms","voice","push"]),Mv=oe.z.enum(["resend","twilio","fcm","apns"]);var qv=oe.z.string().regex(/^\+[1-9]\d{1,14}$/),FA=oe.z.enum(["email_recipient","sms_segment","voice_second","push_device"]);var MA=oe.z.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),qA=oe.z.strictObject({subject:MA,html:oe.z.string().min(1).max(131072).optional(),text:oe.z.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),VA=oe.z.strictObject({body:oe.z.string().min(1).max(1600).refine(e=>e.trim().length>0)}),UA=oe.z.strictObject({text:oe.z.string().trim().min(1).max(4e3),language:oe.z.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:oe.z.number().int().min(1).max(900)}),LA=oe.z.record(oe.z.string().min(1).max(64),oe.z.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"),BA=oe.z.strictObject({title:oe.z.string().trim().min(1).max(200),body:oe.z.string().trim().min(1).max(2e3),url:oe.z.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:LA.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Od=oe.z.discriminatedUnion("channel",[oe.z.strictObject({channel:oe.z.literal("email"),content:qA}),oe.z.strictObject({channel:oe.z.literal("sms"),content:VA}),oe.z.strictObject({channel:oe.z.literal("voice"),content:UA}),oe.z.strictObject({channel:oe.z.literal("push"),content:BA})]),Cd=oe.z.strictObject({requestId:oe.z.uuid(),customerId:oe.z.uuid(),connectionId:oe.z.uuid().optional(),message:Od,expiresAt:oe.z.iso.datetime({offset:!0})}),zA=oe.z.array(oe.z.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),$A=oe.z.discriminatedUnion("kind",[oe.z.strictObject({kind:oe.z.literal("all")}),oe.z.strictObject({kind:oe.z.literal("customers"),customerIds:zA})]),Vv=oe.z.strictObject({name:oe.z.string().trim().min(1).max(120),connectionId:oe.z.uuid().optional(),message:Od,audience:$A,frequencyLimit:oe.z.number().int().min(1).max(100)}),Pd=oe.z.strictObject({requestId:oe.z.uuid(),channel:Ni,state:oe.z.enum(["allowed","denied"]),expectedRevision:oe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),_d=oe.z.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Ed=oe.z.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),Uv=oe.z.strictObject({meter:FA,estimatedUnits:oe.z.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:oe.z.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var ye=require("zod");var X=require("zod");var xr=require("zod");var Di=xr.z.strictObject({internalFeatureId:xr.z.uuid(),name:xr.z.string().min(1).max(120),includedAmount:xr.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:xr.z.enum(["hour","day","week","month","year","lifetime"]),resetCount:xr.z.number().int().min(1).max(100),terms:vo});var Xe=require("zod");var jd=require("zod");var Ir=require("zod"),Rd=Ir.z.enum(["stripe","apple","google"]),kd=Ir.z.enum(["membership","credit_pack","lifetime"]),$v=Ir.z.enum(["active","grace","suspended","inactive","revoked"]),Gv=Ir.z.strictObject({currency:Ir.z.string().regex(/^[A-Z]{3}$/),micros:Ir.z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var Kr=jd.z.object({provider:Rd,currency:fe}).strict();var $n=Xe.z.strictObject({internal_feature_id:Xe.z.uuid(),quantity:me.refine(e=>/[1-9]/.test(e)),properties:At,entityId:Xe.z.uuid().optional()}),Td=Xe.z.strictObject({requirement:$n,commerce:Kr.optional(),paywallId:Xe.z.uuid().optional()}),GA=Xe.z.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),_s=Xe.z.strictObject({productId:Xe.z.string().min(1),productVersionId:Xe.z.string().min(1),name:Xe.z.string().min(1).max(120),action:Xe.z.enum(["purchase","upgrade","addon","topup"]),membershipId:Xe.z.string().min(1).nullable(),currency:fe,amountMinor:Xe.z.string().regex(/^(0|[1-9]\d{0,8})$/),interval:Xe.z.enum(["free","week","month","year","one_time"]),intervalCount:Xe.z.number().int().min(1).max(156)}),vr=Xe.z.strictObject({internal_feature_id:Xe.z.string().min(1),name:Xe.z.string().min(1).max(120),kind:Xe.z.enum(["access","metered","credit"]),quantity:me,allowed:Xe.z.boolean(),reason:GA.nullable(),preview:Xe.z.strictObject({scenario:Xe.z.enum(["feature_flag","usage_limit"]),candidates:Xe.z.array(_s).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"})}),Xv=Xe.z.strictObject({paywallId:Xe.z.uuid(),requirement:$n});var Bo=X.z.object({plan:X.z.string().min(1).max(200).optional(),coupon:X.z.uuid().optional(),promotionCode:X.z.uuid().optional(),picker:X.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Lo=X.z.object({text:X.z.string().optional(),label:X.z.string().optional(),alt:X.z.string().optional(),html:X.z.string().max(32768).optional(),price:X.z.object({current:X.z.string(),original:X.z.string().nullable(),period:X.z.string()}).optional(),code:X.z.string().optional(),countdownAt:X.z.iso.datetime().optional(),planId:X.z.string().min(1).max(200).optional(),planVersionId:X.z.string().min(1).max(200).optional(),currency:fe.optional(),couponId:X.z.uuid().optional(),offerId:X.z.uuid().optional(),unavailable:X.z.boolean().optional(),unavailableReason:X.z.string().optional(),missing:X.z.array(X.z.string()).optional()}).strict(),Hr=X.z.object({paywall:vr.optional(),nodes:X.z.record(X.z.string(),X.z.object({base:Lo,picker:X.z.string().optional(),byPlan:X.z.record(X.z.string(),Lo).optional()}).strict()),plans:X.z.record(X.z.string(),X.z.object({id:X.z.string().min(1).max(200),versionId:X.z.string().min(1).max(200),available:X.z.boolean(),name:X.z.string(),price:X.z.string(),period:X.z.string(),currency:fe.optional(),amountMinor:X.z.number().int().nonnegative().optional(),interval:X.z.enum(["free","week","month","year","one_time"]).optional(),intervalCount:X.z.number().int().positive().optional(),prepaid:X.z.array(Di).max(100).optional()}).strict()),pickers:X.z.record(X.z.string(),X.z.object({options:X.z.array(X.z.string().min(1).max(200)).max(20),selected:X.z.string().min(1).max(200).nullable()}).strict()),quantities:X.z.record(X.z.string(),X.z.strictObject({minimum:X.z.number().int().nonnegative(),maximum:X.z.number().int().nonnegative(),step:X.z.number().int().positive(),value:X.z.number().int().nonnegative(),label:X.z.string(),available:X.z.boolean()})).optional(),diagnostics:X.z.array(X.z.object({nodeId:X.z.string(),message:X.z.string()}).strict())}).strict();function Nd(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}var b=require("zod");function KA(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Dd(e){let t={};function n(r){var i;if(KA(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}var In=require("zod"),Fd=In.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),zo=In.z.strictObject({tiers:In.z.array(In.z.strictObject({id:Fd,name:In.z.string().trim().min(1).max(80)})).min(1).max(8),assignments:In.z.array(In.z.strictObject({productVersionId:In.z.string().min(1).max(200),tierId:Fd,period:In.z.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 $o(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}var re=require("zod");var HA=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Md=re.z.enum(HA),qd=re.z.object({source:Md,layout:re.z.enum(["full","compact"]),resourceKey:fr.optional(),pageSize:re.z.number().int().min(1).max(50),showSources:re.z.boolean(),allowPurchase:re.z.boolean(),outputs:re.z.object({billing_adjustment:re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:re.z.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"})}),xt=re.z.string().max(2e3),Vd=re.z.object({id:re.z.string().max(100),label:xt,detail:re.z.array(xt).max(12),value:xt.optional(),status:xt.optional(),facts:re.z.array(re.z.object({label:xt,value:xt}).strict()).max(1e3),purchaseId:re.z.uuid().optional(),invoiceUrl:re.z.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:re.z.array(re.z.strictObject({action:re.z.literal("invoice_open"),label:xt})).max(1).optional(),membershipActions:re.z.array(re.z.object({value:re.z.string().max(100),label:xt}).strict()).max(3).optional()}).strict(),QA=re.z.object({key:fr,name:xt,spendable:xt,reserved:xt,available:xt,expiry:xt.nullable(),sources:re.z.array(Vd).max(50),sourceCount:re.z.number().int().nonnegative(),sourcePage:re.z.number().int().positive(),hasNextSources:re.z.boolean(),hasPreviousSources:re.z.boolean()}).strict(),JA=re.z.object({source:Md,status:re.z.enum(["idle","loading","ready","error"]),stale:re.z.boolean(),preview:re.z.boolean(),errorCode:re.z.string().max(80).optional(),errorMessage:xt.optional(),resources:re.z.array(QA).max(500),rows:re.z.array(Vd).max(50),hasNext:re.z.boolean(),hasPrevious:re.z.boolean(),page:re.z.number().int().positive(),filter:re.z.string().max(40),updatedAt:re.z.iso.datetime().optional(),buyingId:re.z.uuid().optional(),membershipBusy:re.z.boolean().optional(),billingBusy:re.z.boolean().optional(),membershipReview:re.z.object({title:xt,note:xt,facts:re.z.array(re.z.object({label:xt,value:xt}).strict()).max(100)}).strict().optional(),membershipResult:xt.optional()}).strict(),Ud=re.z.object({nodes:re.z.record(re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),JA)}).strict(),cw=re.z.object({nodeId:re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:re.z.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.z.string().max(100).optional()}).strict();var WA=4,gn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Mi=b.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ke=b.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),YA=b.z.enum(["none","xs","sm","md","lg","xl"]),XA=b.z.enum(["none","sm","md","lg","full"]),Es=b.z.string().regex(/^#[0-9a-fA-F]{6}$/),zd=b.z.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"),Rs=b.z.union([zd,b.z.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),b.z.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),b.z.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Ld=b.z.object({primary:Es,background:Es,text:Es,radius:XA,font:b.z.enum(["system","serif","rounded","mono"])}).strict(),qi=b.z.union([b.z.enum(["primary","text","muted","background","surface"]),b.z.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Re=(e,t)=>b.z.number().int().min(e).max(t),Bd=b.z.union([b.z.enum(["fit","fill"]),Re(1,1200)]),ey=b.z.object({top:Re(0,200),right:Re(0,200),bottom:Re(0,200),left:Re(0,200)}).strict(),ty=b.z.object({top:Re(-100,200),right:Re(-100,200),bottom:Re(-100,200),left:Re(-100,200)}).strict(),$d=b.z.object({x:Re(0,100),y:Re(0,100)}).strict(),ny=b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("color"),color:qi}).strict(),b.z.object({type:b.z.literal("linear"),angle:Re(0,360),stops:b.z.array(b.z.object({color:qi,at:Re(0,100)}).strict()).min(2).max(4)}).strict(),b.z.object({type:b.z.literal("image"),src:Rs,fit:b.z.enum(["cover","contain"]),position:$d.optional()}).strict()]),ry=b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("rect"),radius:b.z.union([Re(0,200),b.z.object({topLeft:Re(0,200),topRight:Re(0,200),bottomRight:Re(0,200),bottomLeft:Re(0,200)}).strict()])}).strict(),b.z.object({type:b.z.literal("pill")}).strict()]),iy=b.z.object({width:Re(0,12),color:qi,style:b.z.enum(["solid","dashed"])}).strict(),oy=b.z.object({x:Re(-40,40),y:Re(-40,40),blur:Re(0,80),spread:Re(-20,40),color:qi}).strict(),ay=b.z.object({font:b.z.enum(["system","serif","rounded","mono"]),size:Re(8,96),weight:b.z.number().int().min(100).max(900).multipleOf(100),lineHeight:b.z.number().min(.8).max(3),letterSpacing:b.z.number().min(-5).max(20),color:qi,align:b.z.enum(["start","center","end"]),italic:b.z.boolean(),decoration:b.z.enum(["none","underline","line-through"]),transform:b.z.enum(["none","uppercase"])}).strict().partial(),wr=b.z.object({width:Bd,height:Bd,padding:ey,margin:ty,gap:Re(0,120),grow:b.z.union([b.z.boolean(),b.z.number().min(0).max(12)]),background:ny,opacity:b.z.number().min(0).max(1),clipContent:b.z.boolean(),shape:ry,border:iy,shadow:oy,text:ay}).strict().partial(),$t={id:Mi,name:b.z.string().trim().min(1).max(60).optional(),hidden:b.z.boolean().optional(),style:wr.optional(),fallback:ke.optional()},sy=b.z.object({...$t,type:b.z.literal("text"),productField:b.z.enum(["name","price","trial","period"]).optional(),feature:b.z.object({id:b.z.uuid(),field:b.z.enum(["name","allowance"])}).strict().optional(),text:ke,variant:b.z.enum(["title","heading","body","caption"])}).strict(),cy=b.z.object({...$t,type:b.z.literal("image"),src:Rs,localizedSrc:b.z.record(pn,Rs).optional(),alt:ke,aspect:b.z.enum(["auto","1:1","4:3","16:9","3:1"]),fit:b.z.enum(["cover","contain"]),position:$d.optional()}).strict(),uy=b.z.object({...$t,type:b.z.literal("button"),label:ke,variant:b.z.enum(["primary","secondary","link"]),action:ke,purpose:b.z.enum(["purchase","navigation","close"]).optional(),bind:Bo.optional()}).strict(),ly=b.z.object({...$t,type:b.z.literal("divider")}).strict(),dy=b.z.object({...$t,type:b.z.literal("customer_data"),title:ke,data:qd}).strict(),py=b.z.object({...$t,type:b.z.literal("spacer"),size:YA}).strict(),my=b.z.object({...$t,type:b.z.literal("custom_html"),html:b.z.record(pn,b.z.string().max(gn.customHtml)),css:b.z.string().max(gn.customCss)}).strict(),fy=b.z.object({...$t,type:b.z.literal("price"),fallback:ke,parts:b.z.object({current:wr.optional(),original:wr.optional(),period:wr.optional()}).strict().optional()}).strict(),gy=b.z.object({...$t,type:b.z.literal("coupon_code"),label:ke,fallback:ke}).strict(),hy=b.z.object({...$t,type:b.z.literal("countdown"),source:b.z.enum(["offer.ends_at","offer.expires_at","fixed"]),at:b.z.iso.datetime().optional(),granularity:b.z.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"),Ay=b.z.object({...$t,type:b.z.literal("plan_picker"),label:ke,fallback:ke,planIds:b.z.array(b.z.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.z.string().min(1).max(200).optional(),grouping:zo.safeExtend({monthLabel:ke,yearLabel:ke,unavailableLabel:ke}).optional(),states:b.z.object({selected:wr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!$o(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),yy=b.z.object({...$t,type:b.z.literal("quantity_picker"),bind:Bo.optional(),label:ke,fallback:ke,internalFeatureId:b.z.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"),by=b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("input"),label:ke,keyboard:b.z.enum(["text","email","tel","url"]),maxLength:Re(1,500)}).strict(),b.z.object({type:b.z.literal("multiselect"),label:ke,min:Re(0,50),max:Re(1,50)}).strict(),b.z.object({type:b.z.literal("select"),label:ke,defaultIndex:Re(0,49),purpose:b.z.enum(["option","product","tier"]).optional(),pickerId:Mi.optional(),selectedStyle:wr.optional()}).strict(),b.z.object({type:b.z.literal("tabs"),label:ke,defaultIndex:Re(0,49),purpose:b.z.literal("tier").optional()}).strict(),b.z.object({type:b.z.literal("toggle"),label:ke,defaultEnabled:b.z.boolean()}).strict(),b.z.object({type:b.z.literal("carousel"),label:ke}).strict()]),fn={...$t,type:b.z.literal("stack"),direction:b.z.enum(["vertical","horizontal","overlay"]),align:b.z.enum(["start","center","end","stretch"]),justify:b.z.enum(["start","center","end","between"]),productSlot:b.z.object({index:Re(0,19),period:b.z.enum(["month","year"]).optional(),requireBinding:b.z.boolean().optional()}).strict().optional(),interaction:by.optional(),states:b.z.object({selected:wr.optional()}).strict().optional(),purpose:b.z.literal("benefits").optional(),purchaseAction:ke.optional(),buttonVariant:b.z.enum(["primary","secondary","link"]).optional(),bind:Bo.optional()},Gd=b.z.lazy(()=>b.z.object({...$t,type:fn.type,direction:fn.direction,align:fn.align,justify:fn.justify,children:b.z.array(Sy).max(gn.children),productSlot:fn.productSlot,interaction:fn.interaction,states:fn.states,purpose:fn.purpose,purchaseAction:fn.purchaseAction,buttonVariant:fn.buttonVariant,bind:fn.bind}).strict()),Sy=b.z.lazy(()=>b.z.union([Gd,sy,cy,uy,ly,py,my,fy,gy,hy,Ay,yy,dy])),xy=b.z.union([b.z.string().max(500),b.z.number().finite(),b.z.boolean(),b.z.null()]),Fi={id:ke,event:ke,properties:b.z.record(ke,xy).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Iy=b.z.discriminatedUnion("type",[b.z.object({...Fi,type:b.z.literal("navigate"),close:b.z.literal(!1),pageId:Mi}).strict(),b.z.object({...Fi,type:b.z.literal("event"),close:b.z.boolean()}).strict(),b.z.object({...Fi,type:b.z.literal("close"),close:b.z.literal(!0)}).strict(),b.z.object({...Fi,type:b.z.literal("open_url"),close:b.z.boolean(),url:zd}).strict(),b.z.object({...Fi,type:b.z.literal("claim_offer"),close:b.z.boolean(),couponId:b.z.uuid()}).strict()]),vy=b.z.object({defaultLocale:pn,locales:b.z.record(pn,b.z.record(ke,b.z.string().max(gn.stringLength)))}).strict(),wy=b.z.enum(["popup","paywall","onboarding","page","banner"]);var Oy=b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("modal"),size:b.z.enum(["sm","md","lg"])}).strict(),b.z.object({type:b.z.literal("sheet"),size:b.z.enum(["sm","md","lg"])}).strict(),b.z.object({type:b.z.literal("fullscreen")}).strict(),b.z.object({type:b.z.literal("inline")}).strict()]);var Cy=b.z.object({kind:b.z.literal("screen"),schemaVersion:b.z.literal(WA),name:b.z.string().trim().min(1).max(80),surface:wy,initialPageId:Mi.optional(),presentation:Oy,theme:Ld,pages:b.z.array(b.z.object({id:Mi,name:b.z.string().trim().min(1).max(60),root:Gd,theme:Ld.optional(),editorPosition:b.z.object({x:b.z.number().finite().min(-1e5).max(1e5),y:b.z.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(gn.pages),strings:vy,actions:b.z.array(Iy).max(gn.actions)}).strict();function qt(e,t){for(let n of e.pages)Gn(n.root,t)}var Yt=Cy.superRefine((e,t)=>{let n=gn;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>gn.locales&&r(`\u6700\u591A ${gn.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;qt(e,(d,m)=>{if(c++,m>gn.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 ${gn.depth} \u5C42`)});function Gn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Gn(i,t,n+1,e)}function Go(e){let t=[],n=new Set;return qt(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 Py(e,t,n){if(t.field==="html"){let r;return qt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=Vi(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 Kn(e){let t=Go(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=>!Py(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 _y(e,t){let n=null;return Gn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Vi(e,t){for(let n of e.pages){let r=_y(n.root,t);if(r)return r}return null}var Pt=require("zod"),dt=Pt.z.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"),ks=Pt.z.strictObject({type:Pt.z.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Pt.z.boolean(),enum:Pt.z.array(Pt.z.string().max(255)).min(1).max(100).optional()}),Qr=ks.extend({type:Pt.z.enum([...ks.shape.type.options,"array"]),items:ks.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"})}),Jr=Qr.safeExtend({source:Pt.z.discriminatedUnion("type",[Pt.z.strictObject({type:Pt.z.literal("input")}),Pt.z.strictObject({type:Pt.z.literal("node")}),Pt.z.strictObject({type:Pt.z.enum(["parameter","attribute"]),key:dt})])}),Aw=Pt.z.record(dt,Jr),js=Pt.z.record(dt,dt).refine(e=>Object.keys(e).length<=20);function an(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=>an(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&&Pt.z.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 Ts(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&&Ts(e.items,t.items)}function Ko(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(!an(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function Zr(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 Kd(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"||!an(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")}var Hn=require("zod");var hn=Hn.z.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"),vn=Hn.z.discriminatedUnion("source",[Hn.z.strictObject({source:Hn.z.literal("literal"),value:ge}),Hn.z.strictObject({source:Hn.z.literal("variable"),key:Hn.z.string().min(1).max(255),path:hn.optional()})]);function Hd(e,t){if(!t)return e;for(let n of hn.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 Ns(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Ko(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ge.parse(Hd(n[e.key],e.path)))}function Ds(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&&!hn.safeParse(r).success?null:{key:n,path:r}}function Fs(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return qt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Nd))]}function Ho(e){return Fs(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function Xt(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 Qn=ye.z.enum(["page","popup","banner"]),Ey=3e5,Qd=ye.z.strictObject({type:ye.z.enum(["string","number","boolean","strings","json"]),nullable:ye.z.boolean()}),Ry=ye.z.strictObject({inputs:ye.z.record(ke,Qd.extend({required:ye.z.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:ye.z.record(ke,Qd).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),ky=ye.z.strictObject({kind:Qn,schemaVersion:ye.z.literal(1),name:ye.z.string().trim().min(1).max(80),screen:Yt,contract:Ry}),Qo=ky.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"]),Xt(e)>Ey&&n("Content document exceeds its byte budget",[])});function jy(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 Ty=Qo.superRefine((e,t)=>{for(let n of Ho(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&&!jy(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}Kn(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),Jd=ye.z.strictObject({id:ye.z.uuid(),kind:Qn,projectId:ye.z.uuid(),environmentId:ye.z.uuid(),name:ye.z.string(),revision:ye.z.number().int().nonnegative(),status:ye.z.enum(["draft","published","archived"]),publishedVersionId:ye.z.uuid().nullable(),createdAt:ye.z.iso.datetime({offset:!0}),updatedAt:ye.z.iso.datetime({offset:!0})}),Rw=Jd.extend({draft:Qo}),kw=ye.z.strictObject({rows:ye.z.array(Jd).max(200),nextCursor:ye.z.uuid().nullable()}),Ms=ye.z.strictObject({id:ye.z.uuid(),kind:Qn,resourceId:ye.z.uuid(),projectId:ye.z.uuid(),environmentId:ye.z.uuid(),version:ye.z.number().int().positive(),sourceRevision:ye.z.number().int().nonnegative(),document:Ty,createdAt:ye.z.iso.datetime({offset:!0})}),jw=Ms.omit({document:!0}),Tw=ye.z.discriminatedUnion("action",[ye.z.strictObject({action:ye.z.literal("create"),kind:Qn,id:ye.z.uuid(),document:Qo}),ye.z.strictObject({action:ye.z.literal("save"),kind:Qn,id:ye.z.uuid(),revision:ye.z.number().int().nonnegative(),document:Qo}),ye.z.strictObject({action:ye.z.enum(["publish","archive"]),kind:Qn,id:ye.z.uuid(),revision:ye.z.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"})});var qs=require("zod"),Wr={funnelId:qs.z.uuid().optional(),funnelVersionId:qs.z.uuid().optional()};var Ye=require("zod");var Te=require("zod");var Qe=require("zod"),Fw=Qe.z.discriminatedUnion("action",[Qe.z.strictObject({action:Qe.z.literal("create"),couponId:Qe.z.uuid(),productBindingId:Qe.z.uuid(),storeOfferId:Qe.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Qe.z.enum(["introductory","promotional"])}),Qe.z.strictObject({action:Qe.z.literal("set_enabled"),id:Qe.z.uuid(),revision:Qe.z.number().int().nonnegative(),enabled:Qe.z.boolean()})]),Mw=Qe.z.array(Qe.z.strictObject({id:Qe.z.uuid(),couponId:Qe.z.uuid(),productBindingId:Qe.z.uuid(),storeOfferId:Qe.z.string().min(1).max(255).nullable(),storeOfferType:Qe.z.enum(["introductory","promotional"]),enabled:Qe.z.boolean(),revision:Qe.z.number().int().nonnegative()})).max(500),Yr=Qe.z.strictObject({offerKind:Qe.z.enum(["none","introductory","promotional"]),offerId:Qe.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Qe.z.number().int().min(0).max(1e8),trialDays:Qe.z.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"})}),qw=Qe.z.record(Qe.z.uuid(),Yr).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Vs=Te.z.object({type:Te.z.literal("native_purchase"),receiptId:Te.z.uuid(),orderId:Te.z.uuid(),productVersionId:Te.z.uuid(),provider:Te.z.enum(["apple","google"]),productId:Te.z.string().min(1).max(255),productKind:kd,replacement:Te.z.strictObject({sourceOrderId:Te.z.uuid(),sourceProductId:Te.z.string().min(1).max(255),policy:Te.z.enum(["apple_store","google_full_price"]),sourceAccountTokens:Te.z.array(Te.z.uuid()).max(50)}).nullable(),appAccountToken:Te.z.uuid().optional(),obfuscatedAccountId:Te.z.string().min(1).max(64).optional(),obfuscatedProfileId:Te.z.uuid().optional(),basePlanId:Te.z.string().min(1).max(255).optional(),offerId:Te.z.string().min(1).max(255).optional(),offerKind:Te.z.enum(["none","introductory","promotional"]),currency:fe,catalogAmountMinor:Te.z.number().int().nonnegative().max(1e8),discountMinor:Te.z.number().int().nonnegative().max(1e8),trialDays:Te.z.number().int().min(1).max(730).nullable(),seatBundle:Te.z.array(Te.z.strictObject({key:Te.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Te.z.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Te.z.strictObject({offerId:Te.z.string().min(1).max(255),keyId:Te.z.string().min(1).max(255),nonce:Te.z.uuid(),signature:Te.z.string().min(1).max(1024),timestamp:Te.z.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"})});var l=require("zod");var Ie=require("zod/v4"),Zd=require("zod/v4"),Ny=Zd.z.registry(),{BillingInterval:Wd}=(()=>{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:Dy}=(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.z),{withSpecDefault:Fy}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Ny),{COMMON:Yd}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:My}={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:qy}=(e=>({COMMON_SET:new Set(e)}))(Yd),{hasNoDuplicateCurrencies:Xd}={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:ep}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Vy}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(Ie.z),{Infinite:Uy}={Infinite:"inf"},{TierBehavior:Ly}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:tp}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:By}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:zy}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:$y}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Gy}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Ie.z),{ApiCreditTierSchema:np}=(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.z),{VIOLATION_MESSAGES:Ky}={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:rp}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(Ie.z),{ModelMarkupsSchema:Hy}=((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.z,rp),{InvoiceUsageEntrySchema:Qy}=(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.z),{AttachDiscountSchema:ip}=(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.z),{CustomLineItemSchema:Jy}=(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.z),{UnixMsTimestampSchema:Zy}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(Ie.z),{CreateInvoicePreviewLineSchema:Wy}=(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.z),{ReissueInvoiceParamsSchema:Us}=(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.z),{InvoiceModeParamsSchema:Or}=(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.z),{InvoiceTemplateSchema:Yy}=(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.z),{BasePriceSchema:Xy}=((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.z,Wd,Dy),{CURRENCY_CODES:eb}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Yd,My,qy),{ApiPriceProcessorsSchema:op}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(Ie.z,Vy),{AllocatedBillingFieldSchema:tb}=((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.z,By),{CreditDimensionNameSchema:nb}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Ie.z,zy,$y),{ApiCreditMatchSchema:ap}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Gy),{findCreditTierViolations:rb}=(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}}))(Ky),{ApiCreditMultiplierSchema:ib}=((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.z,ap),{ProviderMarkupsSchema:ob}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Ie.z,rp),{InvoiceFeatureQuantitySchema:sp}=((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.z,tp,Qy),{CreateInvoicePreviewSchema:Ls}=((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.z,Wy),{SUPPORTED_SET:ab}=(e=>({SUPPORTED_SET:new Set(e)}))(eb),{ApiCreditDimensionBaseSchema:sb}=((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.z,ap),{refineGraduatedTiers:cp}=(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"]})}}))(rb),{ApiFeatureMarkupsOverrideSchema:cb}=((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.z,ob,Hy),{isValidCurrencyCode:ub}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(ab),{ApiCreditDimensionSchema:lb}=((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.z,sb,np,cp),{CurrencyCodeSchema:up}=((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.z,ub),{AdditionalCurrencyTierSchema:db}=((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.z,up),{ApiCreditSchemaItemBaseSchema:lp}=((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.z,nb,lb,ib),{ApiFlatCreditSchemaItemSchema:pb}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(lp,Ie.z),{AdditionalCurrencyPriceSchema:mb}=((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.z,up),{AdditionalCurrencyTierArraySchema:fb}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Ie.z,db,Xd,ep),{ApiGraduatedCreditSchemaItemSchema:gb}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(lp,Ie.z,np,cp),{AdditionalCurrencyPriceArraySchema:dp}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Ie.z,mb,Xd,ep),{ApiUsageTierWithCurrenciesSchema:hb}=((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.z,Uy,fb),{ApiCreditSchemaItemSchema:Ab}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(Ie.z,gb,pb),{BasePriceParamsSchema:yb}=((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."})}))(Xy,Fy,Ie.z,dp),{PlanItemPriceParamsSchema:bb}=((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.z,dp,hb,Ly,Wd,tp,tb),{ApiFeatureOverrideSchema:Sb}=((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.z,Ab,cb),{InvoiceBasePriceParamsSchema:pp}=((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()}))(yb,op),{InvoiceItemPriceParamsSchema:xb}=((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()}))(bb,op),{InvoiceLicenseQuantitySchema:Ib}=((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.z,pp,sp),{InvoiceCustomizeItemSchema:vb}=((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.z,xb,Sb),{InvoiceCustomizeSchema:wb}=((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.z,pp,vb),{InvoicePlanParamsSchema:Ob}=((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.z,wb,sp,Ib,ip),{CreateInvoiceParamsSchema:Xr}=((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.z,Ob,Jy,ip,Zy);var gp=l.z.strictObject({requestId:l.z.uuid(),predecessorOperationId:l.z.uuid().optional(),invoiceMode:Or.optional(),entityId:l.z.uuid().optional(),billingSubscriptionId:l.z.uuid().optional(),newBillingSubscription:l.z.literal(!0).optional(),offerId:l.z.uuid().optional(),nativeOffer:Yr.optional(),plans:l.z.array(l.z.strictObject({productVersionId:l.z.uuid(),seatQuantities:l.z.record(Ao,l.z.number().int().min(0).max(1e4)).optional(),featureQuantities:l.z.record(l.z.uuid(),l.z.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.z.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"),Pr=l.z.strictObject({operationId:l.z.uuid()}),_t=l.z.number().int().min(0).max(1e8),Cb=l.z.strictObject({lineId:l.z.uuid(),productVersionId:l.z.uuid(),productName:l.z.string().min(1).max(80),interval:l.z.enum(["free","week","month","year","one_time"]),intervalCount:l.z.number().int().min(1).max(156).optional(),baseAmountMinor:_t,seats:l.z.array(l.z.strictObject({key:Ao,quantity:l.z.number().int().min(0).max(1e4),includedQuantity:l.z.number().int().min(0).max(1e4),maximumQuantity:l.z.number().int().min(0).max(1e4),unitAmountMinor:_t})).max(20),prepaid:l.z.array(od).max(100).optional(),catalogAmountMinor:_t,trial:l.z.strictObject({days:l.z.number().int().min(1).max(730),cardRequired:l.z.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+Io({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"),hp=l.z.string().regex(/^[A-Za-z0-9_-]{1,200}$/),Pb=l.z.strictObject({id:hp,name:l.z.string().min(1).max(40),percent_off:l.z.number().gt(0).max(100).optional(),amount_off:l.z.number().int().positive().optional(),currency:l.z.string().regex(/^[a-z]{3}$/).optional(),duration:l.z.enum(["once","repeating","forever"]),duration_in_months:l.z.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"),_b=l.z.strictObject({subscriptionId:l.z.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:l.z.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:l.z.array(l.z.strictObject({id:l.z.string(),price_id:l.z.string(),quantity:l.z.number().int().nonnegative(),discounts:l.z.array(l.z.strictObject({id:l.z.string(),coupon:l.z.string(),start:l.z.number(),end:l.z.number().nullable()})).optional()})).min(1).max(100),prorationDate:l.z.number().int().nonnegative(),amountMinor:l.z.number().int().positive(),periodStartMs:l.z.number(),periodEndMs:l.z.number()}),Ap=l.z.strictObject({invoiceMode:Or.optional(),append:_b.optional(),provider:l.z.literal("stripe"),executor:l.z.enum(["indiana","merchant"]),accountId:l.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:l.z.enum(["payment","subscription"]),lineItems:l.z.array(l.z.strictObject({price:l.z.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:l.z.number().int().min(1).max(1e4),priceId:l.z.uuid(),productName:l.z.string().min(1).max(80),amountMinor:l.z.number().int().min(0).max(1e8),currency:l.z.string().regex(/^[a-z]{3}$/),interval:l.z.enum(["week","month","year","one_off"]),intervalCount:l.z.number().int().min(1).max(52),slot:l.z.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:l.z.strictObject({mode:l.z.enum(["graduated","volume"]),tiers:l.z.array(l.z.strictObject({upTo:l.z.number().int().min(1).max(1e6).nullable(),unitAmountMinor:l.z.number().int().min(0).max(1e8),flatAmountMinor:l.z.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:l.z.array(l.z.strictObject({coupon:hp,terms:Pb})).max(1),trialPeriodDays:l.z.number().int().min(1).max(730).nullable(),metadata:l.z.strictObject({grooveCheckoutId:l.z.uuid(),grooveCustomerId:l.z.uuid()}),expiresAt:l.z.iso.datetime({offset:!0})}),Ui=l.z.strictObject({operationId:l.z.uuid(),entityId:l.z.uuid().nullable(),billingSubscriptionId:l.z.uuid().nullable(),discount:l.z.strictObject({offerId:l.z.uuid(),couponId:l.z.uuid(),discount:zn,duration:Zt,amountMinor:_t,allocations:l.z.array(l.z.strictObject({productVersionId:l.z.uuid(),amountMinor:_t})).min(1).max(20),expiresAt:l.z.iso.datetime({offset:!0})}).nullable(),charge:l.z.strictObject({effectiveAt:l.z.iso.datetime({offset:!0}),periodEndsAt:l.z.iso.datetime({offset:!0}),debitMinor:_t,discountMinor:_t,taxMinor:_t,totalMinor:_t}).nullable(),expiresAt:l.z.iso.datetime({offset:!0}),provider:l.z.enum(["stripe","apple","google"]),nativeOffer:Yr.optional(),currency:fe,lines:l.z.array(Cb).min(1).max(20),catalogAmountMinor:_t,automaticTax:l.z.boolean(),execution:Ap.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"),ei=l.z.strictObject({operationId:l.z.uuid(),orderId:l.z.uuid(),append:l.z.boolean().optional(),invoiceMode:l.z.boolean().optional(),status:l.z.enum(["pending","complete","cancelled","failed"]),executor:l.z.enum(["indiana","merchant"]),checkoutUrl:l.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:Ap.nullable(),currency:fe,catalogAmountMinor:_t,taxMinor:_t,totalMinor:l.z.number().int().min(0).max(2e8).nullable(),quoteFinalized:l.z.boolean(),nativePurchase:Vs.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"),Zo=l.z.strictObject({enabled:l.z.literal(!0),featureIds:l.z.array(l.z.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),yp=l.z.strictObject({requestId:l.z.uuid(),invoiceMode:Or.optional(),membershipId:l.z.uuid(),carryOverBalances:Zo.optional(),carryOverUsages:Zo.optional(),membershipIds:l.z.array(l.z.uuid()).min(1).max(20).optional(),prorationBehavior:l.z.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:l.z.enum(["immediate","renewal","store"]),change:l.z.discriminatedUnion("type",[l.z.strictObject({type:l.z.literal("plan"),productVersionId:l.z.uuid()}),l.z.strictObject({type:l.z.literal("seats"),licenseKey:Ao,quantity:l.z.number().int().min(0).max(1e4)}),l.z.strictObject({type:l.z.literal("quantity"),internal_feature_id:l.z.uuid(),quantity:l.z.number().int().min(0).max(1e4)}),l.z.strictObject({type:l.z.literal("cancel")}),l.z.strictObject({type:l.z.literal("uncancel")}),l.z.strictObject({type:l.z.literal("billing_cycle"),billingCycleAnchor:l.z.union([l.z.literal("now"),l.z.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"),Jo=l.z.string().regex(/^price_[A-Za-z0-9]+$/),mp=l.z.strictObject({grooveUpdateId:l.z.uuid(),grooveCustomerId:l.z.uuid()}),fp=l.z.strictObject({price:Jo.nullable(),priceId:l.z.uuid().optional(),quantity:l.z.number().int().min(0).max(1e4)}),bp=l.z.strictObject({provider:l.z.literal("stripe"),invoiceMode:Or.optional(),executor:l.z.enum(["indiana","merchant"]),accountId:l.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:l.z.string().regex(/^sub_[A-Za-z0-9]+$/),action:l.z.enum(["update","cancel","schedule","release"]),update:l.z.strictObject({items:l.z.array(fp).max(20),remove:l.z.array(Jo).max(20),restoreItems:l.z.array(l.z.strictObject({price:Jo,quantity:l.z.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:l.z.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:l.z.number().int().positive().optional(),paymentBehavior:l.z.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:l.z.boolean().optional(),clearCancelAt:l.z.literal(!0).optional(),billingCycleAnchorNow:l.z.literal(!0).optional(),metadata:mp}).nullable(),cancel:l.z.strictObject({prorate:l.z.literal(!1),invoiceNow:l.z.literal(!1)}).nullable(),schedule:l.z.strictObject({currentItems:l.z.array(l.z.strictObject({price:Jo,quantity:l.z.number().int().min(0).max(1e4)})).max(20),nextItems:l.z.array(fp).min(1).max(20),switchAt:l.z.number().int().positive(),interval:l.z.enum(["week","month","year"]),intervalCount:l.z.number().int().min(1).max(52),resetBillingCycleAnchor:l.z.literal(!0).optional(),metadata:mp}).nullable(),release:l.z.strictObject({schedule:l.z.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:l.z.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"),Bs=l.z.strictObject({carryOverBalances:Zo.optional(),carryOverUsages:Zo.optional(),operationId:l.z.uuid(),membershipId:l.z.uuid(),productVersionId:l.z.uuid(),timing:l.z.enum(["immediate","renewal"]),effectiveAt:l.z.iso.datetime({offset:!0}),expiresAt:l.z.iso.datetime({offset:!0}),currency:fe,creditMinor:_t,debitMinor:_t,discountMinor:_t,taxMinor:_t,totalMinor:_t,retainedProductVersionIds:l.z.array(l.z.uuid()).max(19),execution:bp}),Eb=l.z.strictObject({operationId:l.z.uuid(),invoiceMode:l.z.boolean().optional(),membershipId:l.z.uuid(),productVersionId:l.z.uuid(),status:l.z.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:l.z.enum(["immediate","renewal"]),effectiveAt:l.z.iso.datetime({offset:!0}),checkoutUrl:l.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:l.z.enum(["indiana","merchant"]),execution:bp.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),Rb=l.z.strictObject({operationId:l.z.uuid(),membershipId:l.z.uuid(),productVersionId:l.z.uuid(),timing:l.z.literal("store"),effectiveAt:l.z.null(),expiresAt:l.z.iso.datetime({offset:!0}),currency:fe,creditMinor:l.z.null(),debitMinor:l.z.null(),discountMinor:l.z.null(),taxMinor:l.z.null(),totalMinor:l.z.null(),retainedProductVersionIds:l.z.array(l.z.uuid()).max(19),store:l.z.strictObject({provider:l.z.enum(["apple","google"]),productId:l.z.string().min(1).max(255),catalogAmountMinor:_t,policy:l.z.enum(["apple_store","google_full_price"])})}),kb=l.z.strictObject({operationId:l.z.uuid(),membershipId:l.z.uuid(),productVersionId:l.z.uuid(),status:l.z.enum(["prepared","pending","effective","cancelled","failed"]),timing:l.z.literal("store"),effectiveAt:l.z.iso.datetime({offset:!0}).nullable(),checkoutUrl:l.z.null(),nativePurchase:Vs.nullable()}),Sp=l.z.union([Bs,Rb]),zs=l.z.union([Eb,kb]),Li=l.z.number().int().positive().max(2e8),Cr=l.z.number().int().min(0).max(2e8),xp=l.z.strictObject({requestId:l.z.uuid(),invoiceId:l.z.uuid(),mode:l.z.enum(["full","partial"]),amountMinor:Li.optional(),entitlementAction:l.z.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),Ip=l.z.strictObject({provider:l.z.literal("stripe"),executor:l.z.enum(["indiana","merchant"]),accountId:l.z.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:l.z.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Li,currency:l.z.string().regex(/^[a-z]{3}$/),metadata:l.z.strictObject({indianaRefundId:l.z.uuid()}),idempotencyKey:l.z.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:l.z.array(l.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),vp=l.z.strictObject({operationId:l.z.uuid(),invoiceId:l.z.uuid(),providerInvoiceId:l.z.string().regex(/^in_[A-Za-z0-9]+$/),currency:fe,paidMinor:Cr,refundedMinor:Cr,pendingMinor:Cr,amountMinor:Li,mode:l.z.enum(["full","partial"]),entitlementAction:l.z.enum(["retain","revoke"]),revokes:l.z.strictObject({customerProductIds:l.z.array(l.z.uuid()).max(100),subscriptionIds:l.z.array(l.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),execution:Ip,expiresAt:l.z.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"),Wo=l.z.strictObject({operationId:l.z.uuid(),invoiceId:l.z.uuid(),providerInvoiceId:l.z.string().regex(/^in_[A-Za-z0-9]+$/),status:l.z.enum(["quoted","pending","succeeded","failed","expired"]),executor:l.z.enum(["indiana","merchant"]),currency:fe,amountMinor:Li,mode:l.z.enum(["full","partial"]),entitlementAction:l.z.enum(["retain","revoke"]),refundId:l.z.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:Ip.nullable(),failureReason:l.z.string().min(1).max(200).nullable(),createdAt:l.z.iso.datetime({offset:!0}),completedAt:l.z.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"),Yw=l.z.strictObject({invoiceId:l.z.uuid(),currency:fe,paidMinor:Cr,refundedMinor:Cr,pendingMinor:Cr,refundableMinor:Cr,executor:l.z.enum(["indiana","merchant"]).nullable(),canRefund:l.z.boolean(),operations:l.z.array(Wo).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),Xw=l.z.strictObject({requestId:l.z.uuid(),mode:l.z.enum(["full","partial"]),amountMinor:Li.optional(),entitlementAction:l.z.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 wp=Ye.z.strictObject({requestId:Ye.z.uuid(),targets:Ye.z.array(Ye.z.strictObject({membershipId:Ye.z.uuid(),action:Ye.z.enum(["cancel","uncancel"]),timing:Ye.z.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"),Yo=Ye.z.strictObject({batchId:Ye.z.uuid()}),jb=Ye.z.strictObject({operationId:Ye.z.uuid(),membershipIds:Ye.z.array(Ye.z.uuid()).min(1).max(20),provider:Ye.z.enum(["stripe","apple","google"]),action:Ye.z.enum(["cancel","uncancel"]),timing:Ye.z.enum(["immediate","renewal"]),status:Ye.z.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Bs.nullable(),managementUrl:Ye.z.url().nullable(),failureCode:Ye.z.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Bi=Ye.z.strictObject({batchId:Ye.z.uuid(),ready:Ye.z.boolean(),status:Ye.z.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:Ye.z.iso.datetime({offset:!0}),acceptedAt:Ye.z.iso.datetime({offset:!0}).nullable(),groups:Ye.z.array(jb).min(1).max(100)});var Ce=require("zod"),Tb=Ce.z.string().trim().min(1).max(240),$s={requestId:Ce.z.uuid(),reason:Tb},Xo=Ce.z.discriminatedUnion("action",[Ce.z.strictObject({...$s,action:Ce.z.literal("start"),productVersionId:Ce.z.uuid(),entityId:Ce.z.uuid().optional(),days:Ce.z.number().int().min(1).max(730).optional()}),Ce.z.strictObject({...$s,action:Ce.z.literal("extend"),membershipId:Ce.z.uuid(),days:Ce.z.number().int().min(1).max(730)}),Ce.z.strictObject({...$s,action:Ce.z.literal("end"),membershipId:Ce.z.uuid()})]),Op=Ce.z.strictObject({operationId:Ce.z.uuid()}),Cp=Ce.z.iso.datetime({offset:!0}),Nb=Ce.z.strictObject({provider:Ce.z.literal("stripe"),executor:Ce.z.enum(["indiana","merchant"]),accountId:Ce.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Ce.z.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Ce.z.union([Ce.z.literal("now"),Cp]),prorationBehavior:Ce.z.literal("none")}),Gs=Ce.z.strictObject({operationId:Ce.z.uuid(),action:Ce.z.enum(["start","extend","end"]),status:Ce.z.enum(["pending","effective"]),managedBy:Ce.z.enum(["indiana","stripe"]),membershipIds:Ce.z.array(Ce.z.uuid()).min(1).max(20),endsAt:Cp.nullable(),execution:Nb.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"),rO=Ce.z.strictObject({groupId:Ce.z.uuid(),productVersionId:Ce.z.uuid(),enabled:Ce.z.boolean()});var Ge=require("zod");var Pp=Ge.z.strictObject({requestId:Ge.z.uuid(),currency:fe,makeDefault:Ge.z.boolean()}),_p=Ge.z.strictObject({setupId:Ge.z.uuid()}),Db=Ge.z.strictObject({provider:Ge.z.literal("stripe"),executor:Ge.z.literal("merchant"),accountId:Ge.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:Ge.z.literal("setup"),currency:Ge.z.string().regex(/^[a-z]{3}$/),customer:Ge.z.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:Ge.z.uuid(),metadata:Ge.z.strictObject({grooveProjectId:Ge.z.uuid(),grooveEnvironmentId:Ge.z.uuid(),grooveCustomerId:Ge.z.uuid(),groovePaymentSetupId:Ge.z.uuid()}),setDefaultPaymentMethod:Ge.z.boolean(),expiresAt:Ge.z.iso.datetime({offset:!0})}),Ks=Ge.z.strictObject({id:Ge.z.uuid(),provider:Ge.z.literal("stripe"),status:Ge.z.enum(["prepared","complete","expired"]),currency:fe,makeDefault:Ge.z.boolean(),url:Ge.z.url().nullable(),createdAt:Ge.z.iso.datetime({offset:!0}),expiresAt:Ge.z.iso.datetime({offset:!0}),completedAt:Ge.z.iso.datetime({offset:!0}).nullable(),execution:Db.nullable()});var It=require("zod"),Ep=It.z.union([It.z.string(),It.z.number(),It.z.boolean(),It.z.null()]),Rp=It.z.strictObject({customerId:It.z.uuid()}),kp=It.z.strictObject({customerId:It.z.uuid(),provider:It.z.literal("stripe"),checkedAt:It.z.iso.datetime({offset:!0}),status:It.z.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:It.z.number().int().nonnegative(),differences:It.z.array(It.z.strictObject({subscriptionId:It.z.string().startsWith("sub_"),itemId:It.z.string().nullable(),field:It.z.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Ep,actual:Ep})).max(1e4)});var he=require("zod");var ea=he.z.iso.datetime({offset:!0}),ta=he.z.strictObject({createdAt:ea,id:he.z.uuid()}),na=he.z.strictObject({customerId:he.z.uuid().optional(),entityId:he.z.uuid().optional(),productId:he.z.string().min(1).max(256).optional(),provider:he.z.enum(["stripe","apple","google","free"]).optional(),status:he.z.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:ta.optional(),limit:he.z.number().int().min(1).max(100).optional()}),Hs={id:he.z.uuid(),customerId:he.z.uuid(),entityId:he.z.uuid().nullable(),productId:he.z.string().min(1).max(256),productVersionId:he.z.uuid(),name:he.z.string().min(1).max(120),provider:he.z.enum(["stripe","apple","google","free"]),createdAt:ea},Fb=he.z.strictObject({...Hs,status:he.z.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:he.z.boolean(),billingSubscriptionId:he.z.uuid().nullable()}),Mb=he.z.strictObject({...Hs,status:he.z.enum(["active","ended","refunded"]),orderId:he.z.uuid().nullable(),transactionId:he.z.uuid().nullable(),currency:fe.nullable(),amountMinor:he.z.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),qb=he.z.strictObject({...Hs,status:he.z.enum(["blocked","resolved"]),conflict:he.z.strictObject({detectedAt:ea,blockingMembershipIds:he.z.array(he.z.uuid()).min(1).max(100),transactionId:he.z.uuid()}),resolvedAt:ea.nullable()}),jp=na.extend({status:he.z.enum(["blocked","resolved"]).optional()}),Tp=he.z.strictObject({customerId:he.z.uuid(),orderId:he.z.uuid()}),Np=he.z.strictObject({orderId:he.z.uuid(),status:he.z.enum(["blocked","resolved"])}),Dp=he.z.strictObject({items:he.z.array(Fb).max(100),nextCursor:ta.nullable()}),Fp=he.z.strictObject({items:he.z.array(Mb).max(100),nextCursor:ta.nullable()}),Mp=he.z.strictObject({items:he.z.array(qb).max(100),nextCursor:ta.nullable()});var Je=require("zod");var qp=Je.z.union([Je.z.strictObject({intent:Je.z.literal("read"),requestId:Je.z.uuid(),purchaseIntentId:Je.z.uuid()}),Je.z.strictObject({requestId:Je.z.uuid(),provider:Je.z.literal("apple"),purchaseIntentId:Je.z.uuid(),productId:Je.z.string().min(1).max(255).optional(),signedTransaction:Je.z.string().min(1).max(131072)}),Je.z.strictObject({requestId:Je.z.uuid(),provider:Je.z.literal("google"),purchaseIntentId:Je.z.uuid(),productId:Je.z.string().min(1).max(255).optional(),purchaseToken:Je.z.string().min(1).max(16384)})]),Vp=Je.z.strictObject({requestId:Je.z.uuid(),orderId:Je.z.uuid(),purchaseIntentId:Je.z.uuid(),status:Je.z.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:fe,refunded:Je.z.boolean(),completion:Je.z.strictObject({transactionIds:Je.z.array(Je.z.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Je.z.boolean()}).nullable()});var V=require("zod"),Js=V.z.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),Vb=V.z.record(V.z.string(),V.z.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),Ub=3,zi=20,Lb=Ub*zi,Qs=V.z.strictObject({type:V.z.literal("product"),productId:Js}),Up={type:V.z.literal("group"),key:V.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:V.z.string().trim().min(1).max(80)},Bb=V.z.discriminatedUnion("type",[Qs,V.z.strictObject({...Up,items:V.z.array(Qs).max(zi)})]),zb=V.z.discriminatedUnion("type",[Qs,V.z.strictObject({...Up,items:V.z.array(Bb).max(zi)})]),$b=V.z.array(zb).max(zi).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>zi||i>Lb)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Zs(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Zs(t))}var ti=V.z.strictObject({lookupKey:V.z.string().trim().min(1).max(200),displayName:V.z.string().trim().min(1).max(1500),items:$b,metadata:Vb}),Gb=V.z.strictObject({product:V.z.record(V.z.string(),V.z.json()),prices:V.z.array(V.z.record(V.z.string(),V.z.json())),entitlements:V.z.array(V.z.record(V.z.string(),V.z.json())),freeTrials:V.z.array(V.z.record(V.z.string(),V.z.json())),licenses:V.z.array(V.z.record(V.z.string(),V.z.json()))}),Lp=ti.extend({id:V.z.uuid(),projectId:V.z.uuid(),environmentId:V.z.uuid(),state:V.z.enum(["active","archived"]),isCurrent:V.z.boolean(),revision:V.z.number().int().nonnegative(),publishedVersionId:V.z.uuid().nullable(),createdAt:V.z.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"})}),Bp=V.z.strictObject({id:V.z.uuid(),offeringId:V.z.uuid(),projectId:V.z.uuid(),environmentId:V.z.uuid(),version:V.z.number().int().positive(),document:ti,productEvidence:V.z.record(Js,Gb),createdAt:V.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=Zs(e.document);(!n.length||Qb(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"})}),Kb=V.z.strictObject({rows:V.z.array(Lp).max(200),versions:V.z.array(Bp).max(500)}),pO=V.z.discriminatedUnion("action",[V.z.strictObject({action:V.z.literal("create"),document:ti}),V.z.strictObject({action:V.z.literal("save"),id:V.z.uuid(),revision:V.z.number().int().nonnegative(),document:ti}),V.z.strictObject({action:V.z.enum(["publish","set_current","archive","restore"]),id:V.z.uuid(),revision:V.z.number().int().nonnegative()})]),mO=V.z.strictObject({record:Lp,version:Bp.nullable()}),zp=V.z.discriminatedUnion("type",[V.z.strictObject({type:V.z.literal("current")}),V.z.strictObject({type:V.z.literal("id"),id:V.z.uuid()}),V.z.strictObject({type:V.z.literal("lookup_key"),lookupKey:V.z.string().min(1).max(200)}),V.z.strictObject({type:V.z.literal("version"),versionId:V.z.uuid()})]),Hb=V.z.strictObject({internalId:Js,id:V.z.string(),name:V.z.string().nullable(),version:V.z.number().int().positive(),archived:V.z.boolean()}),fO=Kb.extend({products:V.z.array(Hb).max(500),pagination:V.z.strictObject({rows:V.z.string().nullable(),versions:V.z.string().nullable(),products:V.z.string().nullable()}).optional()});function Qb(e){let t=[];Zs(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}var $i=require("zod");var $p=$i.z.strictObject({id:$i.z.uuid(),offeringId:$i.z.uuid(),version:$i.z.number().int().positive(),document:ti});var mt=require("zod");var ue=require("zod");var _r=require("zod");var ra=_r.z.strictObject({items:_r.z.array(_r.z.strictObject({productVersionId:_r.z.string().min(1).max(200),label:_r.z.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:_r.z.string().min(1).max(200).nullable(),grouping:zo.optional()});function Gp(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}var pt=require("zod"),Jb=pt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ia=pt.z.discriminatedUnion("type",[pt.z.object({type:pt.z.literal("fixed"),productVersionId:pt.z.string().min(1).max(200)}).strict(),pt.z.object({type:pt.z.literal("picker"),pickerId:Jb,allowedProductVersionIds:pt.z.array(pt.z.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")]),Tn=pt.z.discriminatedUnion("type",[pt.z.object({type:pt.z.literal("modal"),size:pt.z.enum(["sm","md","lg"])}).strict(),pt.z.object({type:pt.z.literal("sheet"),size:pt.z.enum(["sm","md","lg"])}).strict(),pt.z.object({type:pt.z.literal("fullscreen")}).strict(),pt.z.object({type:pt.z.literal("inline")}).strict()]);var Ws=ue.z.discriminatedUnion("type",[ue.z.strictObject({type:ue.z.literal("event"),event:ue.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ue.z.strictObject({type:ue.z.literal("open_url"),url:ue.z.url().refine(e=>new URL(e).protocol==="https:")})]),Zb=Yt,Wb=ue.z.discriminatedUnion("type",[ue.z.object({type:ue.z.literal("checkout"),product:ia}).strict(),ue.z.object({type:ue.z.literal("close")}).strict(),ue.z.object({type:ue.z.literal("action"),action:Ws}).strict()]),ni=ue.z.object({schemaVersion:ue.z.literal(3),kind:ue.z.literal("paywall"),name:ue.z.string().trim().min(1).max(80),presentation:Tn,requirement:$n.optional(),products:ra,offeringVersionId:ue.z.uuid().nullable(),offeringId:ue.z.uuid(),screen:Zb,buttons:ue.z.record(ue.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Wb)}).strict(),PO=ni.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 Xb(e))t.addIssue({code:"custom",message:r});for(let r of Yb(e))t.addIssue({code:"custom",message:r});Kn(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 Yb(e){let t=e.products.items.map(a=>a.productVersionId),n=Dd(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&&(!$o(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")),qt(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"),qt(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 Xb(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Gn(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 Kp=ue.z.object({id:ue.z.uuid(),projectId:ue.z.uuid(),environmentId:ue.z.uuid(),revision:ue.z.number().int().nonnegative(),state:ue.z.enum(["active","archived"]),publishedVersionId:ue.z.uuid().nullable(),updatedAt:ue.z.iso.datetime({offset:!0}),draft:ni}).strict(),_O=ue.z.object({rows:ue.z.array(Kp).max(200),nextCursor:ue.z.uuid().nullable()}).strict(),EO=Kp.omit({draft:!0}).extend({name:ue.z.string(),productCount:ue.z.number().int().nonnegative()}).strict(),RO=ue.z.discriminatedUnion("action",[ue.z.object({action:ue.z.literal("save"),id:ue.z.uuid().nullable(),revision:ue.z.number().int().nonnegative(),document:ni}).strict(),ue.z.object({action:ue.z.enum(["publish","archive"]),id:ue.z.uuid(),revision:ue.z.number().int().nonnegative()}).strict()]),kO=ue.z.object({paywalls:ue.z.array(ue.z.object({id:ue.z.uuid(),paywallId:ue.z.uuid(),version:ue.z.number().int().positive(),name:ue.z.string().min(1).max(80),presentation:Tn,buttons:ni.shape.buttons}).strict()).max(500),limited:ue.z.boolean()}).strict();var ve=require("zod");var kt=require("zod");var ri=kt.z.string().regex(/^[a-f0-9]{64}$/),eS=Lo.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Hp=kt.z.strictObject({couponDigests:kt.z.record(kt.z.uuid(),ri),variables:kt.z.record(pn,kt.z.record(kt.z.uuid(),kt.z.partialRecord(kt.z.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),kt.z.string()))),locales:kt.z.record(pn,Hr.extend({nodes:kt.z.record(kt.z.string(),kt.z.strictObject({base:eS})),plans:kt.z.object({}).strict(),pickers:kt.z.object({}).strict()}).omit({paywall:!0}))});var Ne=require("zod");var Gi=require("zod"),Ys=Gi.z.strictObject({eventsEnabled:Gi.z.boolean(),experimentViewsEnabled:Gi.z.boolean(),featureUsageEnabled:Gi.z.boolean()}),FO=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Qp(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var B=require("zod");var Xs=B.z.tuple([B.z.number().min(0).max(1),B.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),tS=B.z.strictObject({attribute:B.z.string().optional(),seed:B.z.string(),hashVersion:B.z.literal(2),ranges:B.z.array(Xs).max(100)}),nS=B.z.strictObject({id:B.z.string().min(1).max(255),condition:Bt,gate:B.z.boolean().optional()}),rS=B.z.strictObject({key:B.z.string().optional(),name:B.z.string().optional(),passthrough:B.z.boolean().optional()}),Jp={condition:Bt.optional(),parentConditions:B.z.array(nS).max(100).optional(),weights:B.z.array(B.z.number().min(0).max(1)).max(20).optional(),coverage:B.z.number().min(0).max(1).optional(),hashAttribute:B.z.string().optional(),fallbackAttribute:B.z.string().optional(),hashVersion:B.z.literal(2).optional(),disableStickyBucketing:B.z.boolean().optional(),bucketVersion:B.z.number().int().nonnegative().optional(),minBucketVersion:B.z.number().int().nonnegative().optional(),filters:B.z.array(tS).max(100).optional(),ranges:B.z.array(Xs).max(20).optional(),meta:B.z.array(rS).max(20).optional(),seed:B.z.string().optional(),name:B.z.string().optional(),phase:B.z.string().optional()},ii=B.z.strictObject({...Jp,key:B.z.string().min(1).max(255),variations:B.z.tuple([ge,ge]).rest(ge).refine(e=>e.length<=20),urlPatterns:B.z.array(B.z.strictObject({include:B.z.boolean(),type:B.z.enum(["regex","simple"]),pattern:B.z.string()})).max(100).optional(),force:B.z.number().int().nonnegative().optional(),active:B.z.boolean().optional(),persistQueryString:B.z.boolean().optional()}),ec=B.z.strictObject({value:ge,variationId:B.z.number().int(),key:B.z.string(),name:B.z.string().optional(),bucket:B.z.number().optional(),passthrough:B.z.boolean().optional(),inExperiment:B.z.boolean(),hashUsed:B.z.boolean().optional(),hashAttribute:B.z.string(),hashValue:B.z.string(),featureId:B.z.string().nullable(),stickyBucketUsed:B.z.boolean().optional()}),iS=B.z.strictObject({...Jp,id:B.z.string().max(255).optional(),force:ge.optional(),variations:B.z.array(ge).min(2).max(20).optional(),key:B.z.string().optional(),range:Xs.optional(),tracks:B.z.array(B.z.strictObject({experiment:ii,result:ec})).max(100).optional()}),oS=B.z.strictObject({defaultValue:ge.optional(),rules:B.z.array(iS).max(500).optional()}),Ki=B.z.record(B.z.string(),B.z.union([B.z.strictObject({type:B.z.literal("hashed"),attributeKey:B.z.string(),values:B.z.array(B.z.string().regex(/^[a-f0-9]{64}$/))}),B.z.strictObject({type:B.z.literal("list"),attributeKey:B.z.string(),values:B.z.array(B.z.union([B.z.string(),B.z.number()]))}),B.z.strictObject({type:B.z.literal("condition"),condition:Bt})])),sn=B.z.strictObject({scope:Le,generation:B.z.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:B.z.iso.datetime({offset:!0}),expiresAt:B.z.iso.datetime({offset:!0}).nullable(),features:B.z.record(B.z.string(),oS),savedGroups:Ki,experiments:B.z.record(B.z.uuid(),ii)});var Hi=sn.extend({analyticsConfig:Ys,remoteFeatures:Ne.z.array(Ne.z.string().min(1).max(255)).max(500)}),tc=Hi.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"})}),Zp=Ne.z.strictObject({attributes:yt,features:Ne.z.array(Ne.z.string().min(1).max(255)).max(500).optional(),customerId:Ne.z.uuid().optional()}),aS=Ne.z.strictObject({value:ge,source:Ne.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Ne.z.boolean(),off:Ne.z.boolean(),ruleId:Ne.z.string(),experimentResult:ec.optional()}),oa=Ne.z.strictObject({generation:sn.shape.generation,evaluatedAt:sn.shape.evaluatedAt,expiresAt:sn.shape.expiresAt,features:Ne.z.record(Ne.z.string(),aS),merchandiseContext:Ne.z.strictObject({merchandiseId:Ne.z.uuid(),merchandise:yt}).optional()}),Wp=Ne.z.strictObject({customerId:Ne.z.uuid().optional(),events:Ne.z.array(Ne.z.strictObject({eventUuid:Ne.z.uuid(),timestamp:Ne.z.iso.datetime({offset:!0}),name:Ne.z.string().min(1).max(255),merchandise:Nl.optional(),properties:Ne.z.record(Ne.z.string(),ge).default({}),deviceId:Ne.z.string().min(1).max(255).optional(),sessionId:Ne.z.string().min(1).max(255).optional()})).min(1).max(100)}),Yp=Ne.z.strictObject({inserted:Ne.z.number().int().nonnegative(),duplicates:Ne.z.number().int().nonnegative(),rejected:Ne.z.number().int().nonnegative(),skipped:Ne.z.number().int().nonnegative(),analyticsConfig:Ys});var U=require("zod");function nc(e,t=[]){let n=[];qt(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(Go(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 Xp(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Xp(t)??[])}}function sS(e){let t=e.pages.map(i=>{let a=Xp(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(Go({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 em(e,t=[]){let n=Yt.parse(structuredClone(sS(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=nc(n,t);if(i.length)throw new Error(i.join("; "));return n}var K=require("zod");var N=require("zod");var it=require("zod"),aa=it.z.strictObject({schemaVersion:it.z.literal(1),renderKey:it.z.string().min(1).max(256),routeTemplate:it.z.string().startsWith("/").max(2048),selectors:it.z.array(it.z.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:it.z.array(it.z.number().int().min(0)).min(1),absent:it.z.array(it.z.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"})}),tm=it.z.strictObject({renderKey:it.z.string().min(1).max(256),routeKey:it.z.string().min(1).max(256),stateKey:it.z.string().min(1).max(256),documentKey:it.z.string().min(1).max(256),documentHash:it.z.string().regex(/^[a-f0-9]{64}$/),compositionKey:it.z.string().min(1).max(256),entryMode:it.z.enum(["hard","soft"]),match:it.z.strictObject({present:it.z.array(it.z.number().int().min(0)),absent:it.z.array(it.z.number().int().min(0))})});var Jn=require("zod"),cS=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],rc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",uS=Jn.z.string().regex(new RegExp(`^${rc}/${rc}/${rc}/manifest\\.json$`)),nm=Jn.z.strictObject({kind:Jn.z.literal("gcs-resumable"),url:Jn.z.url(),bucket:Jn.z.enum(cS),objectKey:uS,byteLength:Jn.z.number().int().positive(),expiresAt:Jn.z.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 lt=N.z.string().min(1).max(256),en=N.z.string().regex(/^[a-f0-9]{64}$/),sa=N.z.strictObject({versionId:N.z.uuid(),manifestDigest:en,sourceGraphDigest:en,pageKey:lt,stateKey:lt,documentKey:lt,documentHash:en,elementKey:lt.optional(),nodeId:lt.optional(),contentHash:en.optional(),renderKey:lt.optional()}),rm=N.z.strictObject({pageKey:lt,documentKey:lt,expectedDocumentHash:en,renderKey:lt.optional(),nodeId:lt,elementKey:lt,expectedContentHash:en,property:N.z.enum(["text","fontSize","color"]),value:N.z.union([N.z.string().max(4e3),N.z.number().finite()])}),im=N.z.strictObject({versionId:N.z.uuid(),manifestDigest:en,sourceGraphDigest:en,pageKey:lt,stateKey:lt,documentKey:lt,documentHash:en,renderKey:lt.optional(),patches:N.z.array(rm.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),lS=/^[a-z][a-z0-9-]{0,39}$/,Qi=N.z.string().regex(lS),oc=N.z.enum(["web","ios","android"]),YO=N.z.discriminatedUnion("action",[N.z.strictObject({action:N.z.literal("register"),requestId:N.z.uuid(),client:Qi,platform:oc,label:N.z.string().trim().min(1).max(100),sha256:en,bytes:N.z.number().int().min(1),transferBytes:N.z.number().int().min(1)}),N.z.strictObject({action:N.z.literal("complete"),versionId:N.z.uuid()}),N.z.strictObject({action:N.z.literal("current"),versionId:N.z.uuid(),expectedCurrent:N.z.uuid().nullable()}),N.z.strictObject({action:N.z.literal("delivery"),enabled:N.z.boolean()}),N.z.strictObject({action:N.z.literal("changes"),versionId:N.z.uuid(),experimentId:N.z.uuid(),variationId:lt,changesetId:N.z.uuid().nullable(),expectedRevision:en.nullable(),editorUrl:N.z.string().url().max(2048),patches:N.z.array(rm).max(200)})]),ac=N.z.strictObject({id:N.z.uuid(),projectId:N.z.uuid(),environmentId:N.z.uuid(),clientKey:Qi,platform:oc,label:N.z.string(),sha256:en,bytes:N.z.number().int().positive(),objectKey:N.z.string(),state:N.z.enum(["uploading","ready","rejected"]),isCurrent:N.z.boolean(),revision:N.z.number().int().nonnegative(),createdAt:N.z.string(),expiresAt:N.z.string(),readyAt:N.z.string().nullable(),summary:N.z.record(N.z.string(),N.z.json()),routeTree:N.z.json().nullable(),validation:N.z.record(N.z.string(),N.z.json())}),dS=N.z.strictObject({key:Qi,platform:oc,currentId:N.z.uuid().nullable()}),XO=N.z.strictObject({rows:N.z.array(ac).max(100),nextCursor:N.z.uuid().nullable(),clients:N.z.array(dS).max(20)}),ic=N.z.strictObject({storedBytes:N.z.number().int().nonnegative(),reservedBytes:N.z.number().int().nonnegative(),chargedBytes:N.z.number().int().nonnegative(),versions:N.z.number().int().nonnegative(),objects:N.z.number().int().nonnegative(),orphanObjects:N.z.number().int().nonnegative(),missingReadyObjects:N.z.number().int().nonnegative(),unknownObjectSizes:N.z.number().int().nonnegative(),byteLimit:N.z.number().int().positive(),versionLimit:N.z.number().int().positive(),remainingBytes:N.z.number().int().nonnegative()}),eC=N.z.strictObject({asOf:N.z.iso.datetime({offset:!0}),reclamation:N.z.literal("manual-review-required"),buckets:N.z.strictObject({source:ic,runtime:ic,previews:ic})}),tC=N.z.strictObject({version:ac,actorId:N.z.uuid(),claims:N.z.record(N.z.string(),N.z.json())}),nC=N.z.strictObject({version:ac,upload:nm.nullable()}),rC=N.z.object({format:N.z.literal("indiana-route-state-index"),schemaVersion:N.z.literal(3),routes:N.z.array(N.z.object({routeKey:lt,path:N.z.string(),documentKey:lt,documentHash:en,initialStateKey:lt,initialRenderKey:lt})),renders:N.z.array(tm)}).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"})}),iC=N.z.strictObject({rows:N.z.array(N.z.object({id:N.z.uuid(),name:N.z.string(),status:N.z.string(),variations:N.z.array(N.z.object({id:lt,key:lt,name:N.z.string().optional()}).loose())}).loose()),limited:N.z.boolean()}),oC=N.z.strictObject({enabled:N.z.boolean(),allowedOrigins:N.z.array(N.z.string())});var Er=require("zod");var om=Er.z.strictObject({id:Er.z.uuid(),name:Er.z.string().trim().min(1).max(80),client:Qi,source:sa,event:Er.z.enum(["screen_enter","button_click"]),cooldownSeconds:Er.z.number().int().min(0).max(2592e3),behavior:Er.z.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"})});var Me=require("zod");var sc=ge,pS=["parameters","answers","results","variables"];function cc(e){return pS.some(t=>e===t||e.startsWith(t+"."))}function uc(e){let t={};for(let[r,i]of Object.entries(Ko(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])=>!cc(r))),variables:t}}var at=require("zod");var ca=at.z.discriminatedUnion("kind",[at.z.object({kind:at.z.literal("ledger"),cursor:Uo}).strict(),at.z.object({kind:at.z.literal("billing"),cursor:at.z.uuid()}).strict()]),mS=at.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Zn=at.z.record(at.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),at.z.union([at.z.string().max(500),at.z.boolean(),at.z.array(at.z.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),fS=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function lc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>lc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||fS.test(n)||lc(r,t+1)))}var gS=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,Wn=at.z.record(mS,ge).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!lc(e)&&!gS.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var am=at.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ua=at.z.array(at.z.object({variable:am,componentId:am,required:at.z.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"),gC=at.z.object({bindings:ua,answers:Zn,values:at.z.record(at.z.string(),ge).optional()}).strict();var sm=require("zod"),la=sm.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var dc=Me.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),cm=Me.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),um=Wn.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),pc=Me.z.record(dc,Me.z.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),hS=vn,lm=Me.z.strictObject({type:Me.z.literal("external_task"),endpointId:Me.z.uuid(),taskKey:dc,inputs:Me.z.record(dc,hS).refine(e=>Object.keys(e).length<=20),outputs:pc}),dm=Me.z.strictObject({maxAttempts:Me.z.number().int().min(1).max(5),retryDelaySeconds:Me.z.number().int().min(1).max(30),backoff:Me.z.enum(["fixed","exponential"]),requestTimeoutSeconds:Me.z.number().int().min(1).max(10),timeoutSeconds:Me.z.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var vC=Me.z.strictObject({outcome:Me.z.enum(["success","failure"]),data:um});var wC=Me.z.discriminatedUnion("operation",[Me.z.strictObject({operation:Me.z.literal("signal"),runId:Me.z.uuid(),nodeId:cm,eventName:la,eventId:Me.z.uuid(),data:um}),Me.z.strictObject({operation:Me.z.literal("read_results"),runId:Me.z.uuid()})]),OC=Me.z.strictObject({scope:Le,runId:Me.z.uuid(),eventId:Me.z.uuid(),accepted:Me.z.boolean()}),AS=Me.z.record(cm,sc),CC=Me.z.strictObject({scope:Le,runId:Me.z.uuid(),results:AS});var An={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},pm="00000000-0000-0000-0000-000000000000";var H=require("zod");var Ke=require("zod");var kC=Ke.z.enum(["local","remote"]),mc=Ke.z.strictObject({port:Ke.z.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ge.optional(),sticky:Ke.z.array(Ke.z.strictObject({expected:Ii.nullable(),next:Ii})).max(100),exposures:Ke.z.array(ge).max(100),features:Ke.z.array(ge).max(100)}),mm=Ke.z.strictObject({type:Ke.z.literal("evaluate"),receiptId:Ke.z.uuid(),environmentId:Ke.z.uuid(),policyRevision:Ke.z.number().int().nonnegative(),attributes:yt,sticky:Ke.z.record(Ke.z.string(),Ii)}),fm=mm.extend({runId:Ke.z.uuid(),versionId:Ke.z.uuid(),nodeId:Ke.z.string().min(1).max(64),visit:Ke.z.number().int().nonnegative(),revision:Ke.z.number().int().nonnegative()}),fc=mm.omit({type:!0,receiptId:!0}).extend({type:Ke.z.literal("evaluate_segment")}),gm=Ke.z.strictObject({nodeId:Ke.z.string().min(1).max(64),result:mc}),hm=fc.extend({runId:Ke.z.uuid(),versionId:Ke.z.uuid(),nodeId:Ke.z.string().min(1).max(64),visit:Ke.z.number().int().nonnegative(),revision:Ke.z.number().int().nonnegative(),parameters:Wn,answers:Zn,variables:Ke.z.record(Ke.z.string(),ge)});var ie=require("zod");var gc=ie.z.array(ie.z.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"),da=ie.z.intersection(yt,ie.z.looseObject({tags:gc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),pa=ie.z.string().trim().max(80),ma=ie.z.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),fa=ie.z.union([ie.z.email().max(254),ie.z.literal("")]),ga=ie.z.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Am=ie.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),ym=ie.z.object({externalUserId:Am.optional(),name:pa.default(""),email:fa.default(""),phone:ma.optional(),attributes:da.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),ha=ie.z.discriminatedUnion("type",[ie.z.strictObject({type:ie.z.literal("id"),value:ie.z.uuid()}),ie.z.strictObject({type:ie.z.literal("externalUserId"),value:Am})]),Aa=ie.z.strictObject({name:pa.optional(),email:fa.optional(),phone:ma.optional(),attributes:da.optional(),fingerprint:ga.optional()}),ya=e=>!e.customerData||e.customer?.type==="externalUserId",ba="customerData requires an externalUserId customer",oi=ie.z.object({id:ie.z.uuid(),externalUserId:ie.z.string().min(1).max(255).nullable(),name:pa,email:fa,phone:ma.optional(),attributes:da,createdAt:ie.z.iso.datetime()}).strict(),bm=ie.z.object({customer:oi,changed:ie.z.boolean(),replayed:ie.z.boolean()}).strict(),yS=ie.z.discriminatedUnion("type",[ie.z.object({type:ie.z.literal("id"),value:ie.z.uuid()}).strict(),ie.z.object({type:ie.z.literal("externalUserId"),value:ie.z.string().trim().min(1).max(255)}).strict()]),bS=ie.z.object({name:pa.optional(),email:fa.optional(),phone:ma.optional(),attributes:da.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ie.z.array(ie.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ie.z.strictObject({add:gc,remove:gc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),hc=ie.z.object({lookup:yS}).strict(),Sm=hc.extend({requestId:ie.z.uuid(),patch:bS}).strict(),xm=ie.z.object({search:ie.z.string().trim().max(200).default(""),tag:ie.z.string().trim().max(40).default(""),planId:ie.z.string().max(200).default(""),versionId:ie.z.string().max(200).default(""),holdingStatus:ie.z.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ie.z.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ie.z.union([ie.z.iso.datetime(),ie.z.literal("")]).default(""),createdUntil:ie.z.union([ie.z.iso.datetime(),ie.z.literal("")]).default(""),offset:ie.z.coerce.number().int().min(0).max(1e5).default(0),limit:ie.z.coerce.number().int().min(1).max(100).default(50)}).strict(),Im=ie.z.object({customers:oi.array(),hasMore:ie.z.boolean(),total:ie.z.number().int().nonnegative().nullable(),evaluatedAt:ie.z.iso.datetime()}).strict();var Ji=H.z.discriminatedUnion("type",[H.z.strictObject({type:H.z.literal("literal"),value:ge}),H.z.strictObject({type:H.z.literal("variable"),key:dt,path:hn.optional()}),H.z.strictObject({type:H.z.literal("feature"),featureKey:H.z.string().min(1).max(128)})]),SS=H.z.strictObject({requestId:H.z.uuid(),decisionId:H.z.uuid(),customerId:H.z.uuid(),externalUserId:H.z.string().min(1).max(255).nullable(),versionId:H.z.uuid(),receiptId:H.z.uuid(),value:ge}),xS={funnelId:H.z.uuid(),requestId:H.z.uuid(),customer:ha,customerData:Aa.optional(),attributes:yt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},LC=H.z.discriminatedUnion("operation",[H.z.strictObject({operation:H.z.literal("decide"),...xS}).refine(ya,ba),H.z.strictObject({operation:H.z.literal("read_decision"),decisionId:H.z.uuid()}),H.z.strictObject({operation:H.z.literal("evaluate_decision"),decisionId:H.z.uuid(),requestId:H.z.uuid(),nodeId:H.z.string().min(1).max(64),visit:H.z.number().int().nonnegative(),revision:H.z.number().int().nonnegative(),receiptId:H.z.uuid(),policyRevision:H.z.number().int().nonnegative(),generation:H.z.string().min(1).max(256),result:mc}),H.z.strictObject({operation:H.z.literal("feature_config"),funnelId:H.z.uuid()}),H.z.strictObject({operation:H.z.literal("commit_decision_segment"),decisionId:H.z.uuid(),requestId:H.z.uuid(),nodeId:H.z.string().min(1).max(64),visit:H.z.number().int().nonnegative(),revision:H.z.number().int().nonnegative(),policyRevision:H.z.number().int().nonnegative(),generation:H.z.string().min(1).max(256),steps:H.z.array(gm).max(32),boundary:H.z.strictObject({nodeId:H.z.string().min(1).max(64),visit:H.z.number().int().nonnegative()}).optional()}),H.z.strictObject({operation:H.z.literal("segment_configuration"),funnelId:H.z.uuid(),versionId:H.z.uuid()}),H.z.strictObject({operation:H.z.literal("configuration"),funnelId:H.z.uuid(),versionId:H.z.uuid().optional()}),H.z.strictObject({operation:H.z.literal("local_configuration"),funnelId:H.z.uuid()}),H.z.strictObject({operation:H.z.literal("report_used"),decisionId:H.z.uuid(),eventId:H.z.uuid(),occurredAt:H.z.iso.datetime({offset:!0}),reference:H.z.string().min(1).max(128).optional()})]),BC=H.z.strictObject({scope:Le,decisionId:H.z.uuid(),requestId:H.z.uuid(),status:H.z.enum(["pending","completed","failed"]),decision:SS.nullable(),evaluation:H.z.discriminatedUnion("type",[fm,hm]).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"),zC=H.z.strictObject({scope:Le,decisionId:H.z.uuid(),eventId:H.z.uuid(),source:H.z.literal("caller_reported")});var vt=require("zod");var vm=vt.z.strictObject({type:vt.z.literal("bundle"),paywall:vn.optional(),offering:vn.optional(),coupons:vn,data:vn}),IS=e=>vt.z.strictObject({type:vt.z.literal(e),id:vt.z.uuid()}),QC=vt.z.strictObject({type:vt.z.literal("bundle"),paywallVersionId:vt.z.uuid().optional(),offeringVersionId:vt.z.uuid().optional(),couponIds:vt.z.array(vt.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ge});var JC=vt.z.strictObject({type:vt.z.literal("bundle"),offering:IS("offering_version").nullable(),paywall:vt.z.strictObject({versionId:vt.z.uuid(),paywallId:vt.z.uuid(),offeringVersionId:vt.z.uuid()}).nullable(),coupons:vt.z.array(vi).max(20),data:ge});var cn=require("zod");var tn=require("zod");var wm=tn.z.union([tn.z.string(),tn.z.number().finite(),tn.z.boolean(),tn.z.null()]),vS=tn.z.union([wm,tn.z.array(wm).min(1).max(20)]),wS=tn.z.record(hn,vS).refine(e=>Object.keys(e).length<=10),Om=tn.z.strictObject({path:hn,type:tn.z.enum(["string","number","boolean","strings"]),nullable:tn.z.boolean().optional(),aggregation:tn.z.enum(["count","exists"]).optional(),where:wS.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 OS=["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"],Cm=cn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),CS=vn,Pm=cn.z.discriminatedUnion("type",[lm,cn.z.strictObject({type:cn.z.literal("claim_offer"),coupon:vn}),cn.z.strictObject({type:cn.z.literal("event"),event:Cm}),cn.z.strictObject({type:cn.z.literal("api"),operation:cn.z.enum(OS),inputs:cn.z.record(hn,CS).refine(e=>Object.keys(e).length<=40),outputs:cn.z.record(Cm,Om).refine(e=>Object.keys(e).length<=20)})]);var rt=la,PS=K.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),nn={id:rt,name:K.z.string().trim().min(1).max(80),position:K.z.strictObject({x:K.z.number().finite(),y:K.z.number().finite()}).optional()},_S={success:rt,cancel:rt,unavailable:rt,failure:rt},Ac=K.z.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),yc=K.z.enum(["same_window","new_window"]),ES=K.z.discriminatedUnion("type",[K.z.strictObject({...nn,type:K.z.literal("entry"),next:rt,triggers:K.z.array(om).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),K.z.strictObject({...nn,type:K.z.literal("screen"),screenId:rt,presentation:Tn,outputs:K.z.record(rt,rt),offering:K.z.discriminatedUnion("source",[K.z.strictObject({source:K.z.literal("variable"),key:dt}),K.z.strictObject({source:K.z.literal("fixed"),versionId:K.z.uuid()})]).optional()}),K.z.strictObject({...nn,type:K.z.literal("offering"),configuration:K.z.discriminatedUnion("source",[K.z.strictObject({source:K.z.literal("fixed"),versionId:K.z.uuid()}),K.z.strictObject({source:K.z.literal("feature"),featureKey:K.z.string().min(1).max(128)})]),writes:K.z.strictObject({value:dt}),next:rt}),K.z.strictObject({...nn,type:K.z.literal("coupon"),couponId:K.z.uuid(),writes:K.z.strictObject({value:dt}),next:rt}),K.z.strictObject({...nn,type:K.z.literal("coupons"),couponIds:K.z.array(K.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:K.z.strictObject({value:dt}),next:rt}),K.z.strictObject({...nn,type:K.z.literal("output"),value:K.z.discriminatedUnion("type",[...Ji.options,vm,K.z.strictObject({type:K.z.literal("selection"),screenId:rt,offeringKey:dt})])}),K.z.strictObject({...nn,type:K.z.literal("condition"),cases:K.z.array(K.z.strictObject({condition:Bt,target:rt})).min(1).max(50),default:rt}),K.z.strictObject({...nn,type:K.z.literal("feature"),featureKey:K.z.string().min(1).max(128),writes:K.z.strictObject({value:dt}),next:rt}),K.z.strictObject({...nn,type:K.z.literal("split"),experimentId:K.z.uuid(),applyPageExperiment:K.z.literal(!0).optional(),routes:K.z.record(PS,rt).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:rt}),K.z.strictObject({...nn,type:K.z.literal("action"),..._S,execution:dm,action:Pm,writes:js.optional()}),K.z.strictObject({...nn,type:K.z.literal("external_page"),appManifest:sa.optional(),url:Ac,openIn:yc,opened:rt,failed:rt}),K.z.strictObject({...nn,type:K.z.literal("end"),outcome:K.z.enum(["completed","closed","ineligible","failed"]),output:Ji.optional()}),K.z.strictObject({...nn,type:K.z.literal("wait"),writes:js.optional(),wait:K.z.discriminatedUnion("type",[K.z.strictObject({type:K.z.literal("duration"),delaySeconds:K.z.number().int().min(1).max(2592e3),elapsed:rt}),K.z.strictObject({type:K.z.literal("event"),eventName:rt,outputs:pc,timeoutSeconds:K.z.number().int().min(1).max(2592e3),received:rt,timeout:rt})])})]),bc=K.z.strictObject({version:K.z.literal(5),entry:rt,nodes:K.z.array(ES).min(1).max(An.flowNodes)}),Sc=bc.superRefine((e,t)=>{RS(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Sa(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 RS(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>An.pages||e.nodes.filter(d=>!["screen","entry","end","output"].includes(d.type)).length>An.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let d of e.nodes){for(let m of Sa(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 Sa(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 xc={maxTransitions:1e4,runTimeoutSeconds:2592e3};function _m(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 Bn(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]}var D=require("zod");var ai=D.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),xa=e=>D.z.record(D.z.string(),ge).refine(t=>Xt(t)<=e,"Funnel evidence exceeds its byte budget"),IP=D.z.enum(["local_segment","evaluation","presentation","timer","event","operation"]),vc=D.z.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),wc=D.z.discriminatedUnion("type",[D.z.strictObject({type:D.z.literal("flag"),key:D.z.string().min(1).max(128)}),D.z.strictObject({type:D.z.literal("experiment"),id:D.z.uuid()}),D.z.strictObject({type:D.z.literal("saved_group"),id:D.z.uuid()}),D.z.strictObject({type:D.z.literal("config"),key:D.z.string().min(1).max(128)}),D.z.strictObject({type:D.z.literal("constant"),key:D.z.string().min(1).max(128)}),D.z.strictObject({type:D.z.literal("paywall_version"),id:D.z.uuid()}),D.z.strictObject({type:D.z.literal("offering_version"),id:D.z.uuid()}),D.z.strictObject({type:D.z.literal("reward"),id:D.z.uuid()})]),Zi=D.z.strictObject({schemaVersion:D.z.literal(1),kind:vc,selector:wc.nullable(),context:xa(131072),contract:D.z.strictObject({version:D.z.number().int().positive(),evaluator:D.z.string().min(1).max(128),policyRevision:D.z.number().int().nonnegative()})}).refine(e=>Xt(e)<=131072,"Node input exceeds its byte budget"),Em=D.z.strictObject({schemaVersion:D.z.literal(1),kind:vc,outcome:D.z.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:xa(131072),route:D.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:xa(131072)}).refine(e=>Xt(e)<=131072,"Node result exceeds its byte budget"),vP=D.z.strictObject({schemaVersion:D.z.literal(1),operations:D.z.record(ai,D.z.strictObject({attempts:D.z.number().int().nonnegative(),maxAttempts:D.z.number().int().min(1).max(5),deadlineAt:D.z.iso.datetime({offset:!0}),retryAt:D.z.iso.datetime({offset:!0}).nullable(),error:D.z.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:D.z.strictObject({type:ai,id:D.z.uuid()}).nullable()}))}).refine(e=>Xt(e)<=65536,"Execution state exceeds its byte budget"),Rr={receiptId:D.z.uuid()},Ic=D.z.iso.datetime({offset:!0}),wP=D.z.discriminatedUnion("type",[D.z.strictObject({type:D.z.literal("node_entered"),details:D.z.strictObject({kind:vc})}),D.z.strictObject({type:D.z.literal("presentation_shown"),details:D.z.strictObject({...Rr,source:D.z.literal("client"),occurredAt:Ic.optional()})}),D.z.strictObject({type:D.z.literal("decision_accepted"),details:D.z.strictObject(Rr)}),D.z.strictObject({type:D.z.literal("signal_received"),details:D.z.strictObject({signalId:D.z.uuid(),nodeId:ai,eventName:ai,data:xa(8192),source:D.z.literal("server"),occurredAt:Ic})}),D.z.strictObject({type:D.z.literal("signal_consumed"),details:D.z.strictObject({...Rr,signalId:D.z.uuid()})}),D.z.strictObject({type:D.z.literal("wait_elapsed"),details:D.z.strictObject(Rr)}),D.z.strictObject({type:D.z.literal("wait_timeout"),details:D.z.strictObject(Rr)}),D.z.strictObject({type:D.z.literal("operation_completed"),details:D.z.strictObject({...Rr,operation:ai,reference:D.z.strictObject({type:ai,id:D.z.uuid()}).nullable()})}),D.z.strictObject({type:D.z.literal("execution_recovered"),details:D.z.strictObject({generation:D.z.number().int().positive(),reason:D.z.enum(["interrupted","expired_lease","delivery_failed"])})}),D.z.strictObject({type:D.z.literal("execution_failed"),details:D.z.strictObject({generation:D.z.number().int().positive(),code:D.z.string().regex(/^[a-z_]{1,64}$/)})}),D.z.strictObject({type:D.z.literal("run_completed"),details:D.z.strictObject({outcome:D.z.enum(["completed","ineligible","failed"])})}),D.z.strictObject({type:D.z.literal("run_closed"),details:D.z.strictObject({source:D.z.enum(["client","server","expiry"])})}),D.z.strictObject({type:D.z.literal("treatment_used"),details:D.z.strictObject({...Rr,source:D.z.enum(["client","server"]),occurredAt:Ic,reference:D.z.string().min(1).max(128).optional()})})]);var un=U.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),kS=U.z.discriminatedUnion("type",[U.z.strictObject({id:un,type:U.z.literal("owned"),publicData:Hp.optional(),document:Yt.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.z.strictObject({id:un,type:U.z.literal("paywall"),paywallVersionId:U.z.uuid()})]),Oc={kind:U.z.literal("funnel"),schemaVersion:U.z.literal(4),screens:U.z.array(kS).max(An.pages),references:U.z.record(un,wc).refine(e=>Object.keys(e).length<=500),inputs:U.z.array(U.z.strictObject({variable:un,screenId:un,componentId:un,required:U.z.boolean()})).max(An.questions),variables:U.z.record(dt,Jr).refine(e=>Object.keys(e).length<=An.logicNodes),outputSchema:Qr,execution:U.z.strictObject({runTimeoutSeconds:U.z.number().int().min(1).max(xc.runTimeoutSeconds),maxTransitions:U.z.number().int().min(1).max(xc.maxTransitions)})},BP=U.z.strictObject({...Oc,graph:bc});function jS(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 va(e){return Array.isArray(e)?e.some(va):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===pm:va(n))}function TS(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=em(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&&!Vi(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}),jS(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"&&va(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&va(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Rm(e,t){for(let{message:n,reason:r,path:i}of TS(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function km(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}Kn(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),Gn(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(pe=>pe!==void 0&&!j.has(pe))&&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"&&!an(e.outputSchema,p.output.value)&&n("Terminal output does not match outputSchema","output",g),p.type==="output"&&p.value.type==="literal"&&!an(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&&!Ts(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 Fs(v.document))(/^(input|params)\./.test(E)||E.startsWith("variables.")&&!Ds(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 Rn(v.condition))a("saved_group",E)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let E of Bn(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(pe=>!an({type:E,nullable:!1},pe)||!a(E,pe.id))||v==="coupons"&&new Set(q.map(pe=>pe.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=[..._m(p,c),...g?.type==="owned"?Ho(g.document).map(S=>Ds(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(Se=>Se.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]:[]:Sa(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"?Vi(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)Gn(p.root,()=>{d++});m+=I.document.actions.length}(d>An.components||m>An.actions||Xt(e)>An.documentBytes)&&n("Funnel document exceeds its budget","budget")}var NS=U.z.strictObject({...Oc,graph:Sc}).superRefine(km),si=U.z.strictObject({...Oc,graph:Sc,displayName:U.z.string().trim().min(1).max(80)}).superRefine(km),zP=si.superRefine(Rm),$P=NS.superRefine(Rm),Ia=U.z.string().regex(Dt),Wi={requestId:U.z.uuid(),nodeId:un,visit:U.z.number().int().nonnegative(),revision:U.z.number().int().nonnegative(),customerToken:Ia.optional()},DS=U.z.discriminatedUnion("type",[U.z.strictObject({type:U.z.literal("screen"),output:un,answers:Zn,selection:U.z.record(un,U.z.union([U.z.string().max(200),U.z.boolean(),U.z.number().int().min(0).max(1e4)])).optional()}),U.z.strictObject({type:U.z.literal("paywall_quote"),featureQuantities:U.z.record(U.z.uuid(),U.z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:un,productVersionId:U.z.uuid(),offerId:U.z.uuid().optional(),nativeOffer:Yr.optional(),predecessor:U.z.strictObject({operationId:U.z.uuid().nullable(),generation:U.z.number().int().positive()}).optional()}),U.z.strictObject({type:U.z.literal("paywall_confirm"),operationId:U.z.uuid()}),U.z.strictObject({type:U.z.literal("paywall_cancel"),operationId:U.z.uuid()}),U.z.strictObject({type:U.z.literal("client_action"),receiptId:U.z.uuid(),outcome:U.z.enum(["success","cancel","failure","opened","failed"])})]),FS=U.z.object({nodeId:un,visit:U.z.number().int().nonnegative(),revision:U.z.number().int().nonnegative(),components:U.z.record(un,U.z.object({resourceKey:U.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:U.z.number().int().min(1).max(1e5),after:ca.nullable(),filter:U.z.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Nn=U.z.discriminatedUnion("operation",[U.z.strictObject({operation:U.z.literal("start"),funnelId:U.z.uuid(),requestId:U.z.uuid(),customer:ha.optional(),customerData:Aa.optional(),locale:U.z.string().min(1).max(35),parameters:Wn}).refine(ya,ba),U.z.strictObject({operation:U.z.literal("get"),settlementRequestId:U.z.uuid().optional(),data:FS.optional(),purchase:U.z.strictObject({receiptId:U.z.uuid(),operationId:U.z.uuid()}).optional(),customerToken:Ia.optional()}),U.z.strictObject({operation:U.z.literal("resume"),requestId:U.z.uuid(),customerToken:Ia.optional()}),U.z.strictObject({operation:U.z.literal("submit"),...Wi,input:DS}),U.z.strictObject({operation:U.z.literal("back"),...Wi}),U.z.strictObject({operation:U.z.literal("shown"),...Wi}),U.z.strictObject({operation:U.z.literal("close"),...Wi}),U.z.strictObject({operation:U.z.literal("commit_segment"),...Wi,policyRevision:U.z.number().int().nonnegative(),generation:U.z.string().min(1).max(256)}),U.z.strictObject({operation:U.z.literal("review"),receiptId:U.z.uuid().optional(),customerToken:Ia.optional()})]);function wa(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 Rn(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&&cc(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)}}var ne=require("zod");function jm(e,t){let n=[],r={};qt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&qt(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 Tm(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(qt(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}var ci=require("zod");var Nm=ci.z.object({defaultLocale:pn,locales:ci.z.record(pn,ci.z.object({name:ci.z.string().max(80),description:ci.z.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 MS=["customer_data","coupon_code"],qS=ne.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Dm=ne.z.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),Oa=(e,t)=>new Set(e.map(t)).size===e.length,VS=ne.z.strictObject({currency:fe,amountMinor:ne.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),US=ne.z.strictObject({featureId:ne.z.uuid(),name:ne.z.string().trim().min(1).max(120),allowance:ne.z.string().max(40).nullable(),access:ne.z.boolean()}),LS=ne.z.strictObject({stripe:ne.z.strictObject({prices:ne.z.array(VS).min(1).max(50)}).optional(),apple:ne.z.strictObject({productIds:ne.z.array(qS).min(1).max(10)}).optional(),google:ne.z.strictObject({products:ne.z.array(ne.z.strictObject({productId:Dm,basePlanId:Dm.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!Oa(e.stripe.prices,n=>n.currency)||e.apple&&!Oa(e.apple.productIds,n=>n)||e.google&&!Oa(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),BS=ne.z.strictObject({name:ne.z.string().trim().min(1).max(80),interval:ne.z.enum(["free","week","month","year","one_time"]),intervalCount:ne.z.number().int().min(1).max(100),trial:ne.z.strictObject({days:ne.z.number().int().min(1).max(730),cardRequired:ne.z.boolean()}).nullable(),benefits:ne.z.array(US).max(50).refine(e=>Oa(e,t=>t.featureId),"Duplicate benefit"),channels:LS,prepaid:ne.z.array(Di).max(100).optional()}),zS=ne.z.strictObject({digest:ri,content:ne.z.strictObject({discount:zn,duration:Zt,appliesTo:bs,displayCopy:Nm.nullable(),firstPurchaseOnly:ne.z.boolean(),qualificationRequired:ne.z.boolean(),startsAt:ne.z.iso.datetime().nullable(),endsAt:ne.z.iso.datetime().nullable(),grantWindowHours:ne.z.number().int().positive(),perCustomerLimit:ne.z.number().int().positive()})}),$S=ne.z.discriminatedUnion("type",[ne.z.strictObject({type:ne.z.literal("checkout"),product:ia}),ne.z.strictObject({type:ne.z.literal("close")}),ne.z.strictObject({type:ne.z.literal("action"),action:Ws})]),Ca=ne.z.strictObject({kind:ne.z.literal("paywall"),formatVersion:ne.z.literal(1),name:ne.z.string().trim().min(1).max(80),offeringVersionId:ne.z.uuid(),presentation:Tn,screen:Yt,products:ra,catalog:ne.z.record(ne.z.uuid(),BS),buttons:ne.z.record(ke,$S),coupons:ne.z.record(ne.z.uuid(),zS)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;jm(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),nc(r,MS).forEach(n),Kn(r).some(g=>!g.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;qt(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")}),Fm=ne.z.strictObject({state:ne.z.enum(["published","archived"]),controlRevision:ne.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ne.z.uuid(),versions:ne.z.record(ne.z.uuid(),ne.z.strictObject({version:ne.z.number().int().positive(),artifact:ne.z.string().min(1),sourceDigest:ne.z.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},Cc=ve.z.string().regex(/^[a-f0-9]{64}$/),Pc=ve.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),_c=Le.extend({environmentId:ve.z.uuid()}),Mm=ve.z.strictObject({features:ve.z.array(ve.z.string()).max(500),experiments:ve.z.record(ve.z.uuid(),ve.z.array(ve.z.string()).max(20)),savedGroups:ve.z.array(ve.z.string()).max(1e3)}),Ec=ve.z.strictObject({kind:ve.z.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:ve.z.number().int().positive(),url:ve.z.string().min(1).max(2048),sha256:Cc,byteLength:ve.z.number().int().positive().max(Gt.maxArtifactBytes),generation:Cc.optional()}),GS=ve.z.strictObject({state:ve.z.enum(["active","paused","archived"]),controlRevision:Pc,evaluationMode:ve.z.enum(["local","remote"]),evaluationRevision:Pc,currentVersionId:ve.z.uuid(),versions:ve.z.record(ve.z.uuid(),ve.z.strictObject({artifact:ve.z.string(),dependencies:Mm,definitionDigest:ri.optional(),couponDigests:ve.z.record(ve.z.uuid(),ri).optional()}))}),Rc=ve.z.strictObject({kind:ve.z.literal("sdk_configuration"),schemaVersion:ve.z.literal(1),scope:_c,revision:Pc,generation:Cc,policy:ve.z.strictObject({refreshIntervalSeconds:ve.z.number().positive().max(15),maxControlAgeSeconds:ve.z.number().positive().max(60)}),gb:ve.z.strictObject({features:ve.z.string().nullable(),pageExperiments:ve.z.string().nullable()}),artifacts:ve.z.record(ve.z.string(),Ec),funnels:ve.z.record(ve.z.uuid(),GS),paywalls:ve.z.record(ve.z.uuid(),Fm).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 bt(e){if(Array.isArray(e))return`[${e.map(bt).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)}:${bt(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function kc(e){return Ur(Lr(typeof e=="string"?new TextEncoder().encode(e):e))}function qm(e){return kc(bt(e))}function Vm(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=wa(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||!an(u,m)))throw new Error("GB Feature values violate the Funnel type contract")}let i=new Set,a=o=>{for(let s of Rn(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 Mm.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 Um(e){return si.parse(e)}var Lm=mt.z.strictObject({...Wr,selector:mt.z.discriminatedUnion("type",[mt.z.strictObject({type:mt.z.literal("paywall"),paywallId:mt.z.uuid()}),mt.z.strictObject({type:mt.z.literal("version"),versionId:mt.z.uuid()})]),customerId:mt.z.uuid().optional(),commerce:Kr,locale:mt.z.string().min(1).max(35),requirement:$n.optional()}),Yi=mt.z.strictObject({id:mt.z.uuid(),paywallId:mt.z.uuid(),version:mt.z.number().int().positive(),document:ni.omit({requirement:!0,offeringId:!0}),offering:mt.z.strictObject({id:mt.z.uuid()}),content:mt.z.strictObject({environmentId:mt.z.uuid(),offeringVersionId:mt.z.uuid(),artifact:Ec.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Hr,check:vr.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"})}),kr=mt.z.strictObject(Yi.shape).omit({document:!0,offering:!0}).extend({content:Yi.shape.content.unwrap()});function Bm(e,t){let n=Ca.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 Yi.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}})}var jt=require("zod");var zm={requestId:jt.z.uuid(),sourceId:jt.z.uuid(),expectedAvailable:Mt},$m=jt.z.discriminatedUnion("action",[jt.z.strictObject({...zm,action:jt.z.enum(["add","subtract","set_remaining"]),amount:me}),jt.z.strictObject({...zm,action:jt.z.literal("edit"),granted:me,expiresAt:jt.z.iso.datetime({offset:!0}).nullable(),nextResetAt:jt.z.iso.datetime({offset:!0}).nullable(),expectedRevision:jt.z.number().int().nonnegative()})]),jc=jt.z.strictObject({sourceId:jt.z.uuid(),available:Mt,held:Mt,spent:Mt,adjustmentGrantId:jt.z.uuid().nullable()}),Gm=jc.extend({granted:Mt,expiresAt:jt.z.iso.datetime({offset:!0}).nullable(),nextResetAt:jt.z.iso.datetime({offset:!0}).nullable(),revision:jt.z.number().int().nonnegative()});var Kt=require("zod"),Km=Kt.z.discriminatedUnion("action",[Kt.z.object({action:Kt.z.literal("upsert"),externalId:Kt.z.string().min(1).max(128),name:Kt.z.string().trim().min(1).max(80)}).strict(),Kt.z.object({action:Kt.z.literal("archive"),entityId:Kt.z.uuid()}).strict()]),Hm=Kt.z.object({id:Kt.z.uuid(),externalId:Kt.z.string().min(1).max(128),name:Kt.z.string().min(1).max(80),archived:Kt.z.boolean()}).strict();var Et=require("zod");var Yn=require("zod"),Jm=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Qm=Yn.z.string().regex(/.+\/.+/),Tc=Yn.z.number().min(-100),jr=Yn.z.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),KS=Yn.z.strictObject({input:jr,output:jr,cache_read:jr.optional(),cache_write:jr.optional(),reasoning:jr.optional(),input_audio:jr.optional(),output_audio:jr.optional()}),Nc=(e,t)=>Yn.z.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),N1=Yn.z.strictObject({defaultMarkup:Tc,providerMarkups:Nc(Yn.z.string().min(1),Tc),modelMarkups:Nc(Qm,Tc),customModels:Nc(Qm,KS.partial())});var le=require("zod"),Tr=le.z.iso.datetime({offset:!0}),Xn=le.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),HS=le.z.discriminatedUnion("kind",[le.z.object({kind:le.z.literal("absolute"),from:Tr,to:Tr}).strict(),le.z.object({kind:le.z.literal("last_days"),days:le.z.union([le.z.literal(1),le.z.literal(7),le.z.literal(30),le.z.literal(90)])}).strict(),le.z.object({kind:le.z.literal("billing_cycles"),membershipId:le.z.uuid(),count:le.z.number().int().min(1).max(12),includeCurrent:le.z.boolean()}).strict()]),Zm=le.z.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"),QS=le.z.object({key:le.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:le.z.array(le.z.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Nr=le.z.object({range:HS,timezone:Zm,filterBy:le.z.array(QS).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:le.z.enum(["hour","day","week","month"]),internal_feature_id:le.z.uuid().nullable(),entityId:le.z.uuid().nullable(),topN:le.z.number().int().min(1).max(50).nullable(),groupBy:le.z.union([le.z.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),le.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:le.z.object({bucket:Tr,group:le.z.string().max(240),isOther:le.z.boolean(),internal_feature_id:le.z.uuid(),resourceId:le.z.uuid()}).strict().nullable(),limit:le.z.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)"})}),Wm=le.z.object({from:Tr,to:Tr,interval:le.z.enum(["hour","day","week","month"]),timezone:Zm,rows:le.z.array(le.z.object({bucket:Tr,group:le.z.string().max(240),isOther:le.z.boolean(),internal_feature_id:le.z.uuid(),resourceId:le.z.uuid(),consumedUnits:Xn,refundedUnits:Xn,reservedUnits:Xn,charged:Xn,refunded:Xn,reserved:Xn,netUnits:Xn,netCharged:Xn}).strict()).max(100),nextCursor:le.z.object({bucket:Tr,group:le.z.string().max(240),isOther:le.z.boolean(),internal_feature_id:le.z.uuid(),resourceId:le.z.uuid()}).strict().nullable()}).strict();var ui=Et.z.string().regex(/^(0|[1-9]\d{0,29})$/),Ym=Et.z.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Dc=Et.z.strictObject({bucket:Et.z.iso.datetime({offset:!0}),group:Et.z.string().max(240),isOther:Et.z.boolean(),internal_feature_id:Et.z.uuid()}),Xm=Et.z.strictObject({...Nr.shape,groupBy:Et.z.union([Et.z.enum(["customer","entity","entitlement"]),Et.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Dc.nullable()}).superRefine((e,t)=>{let n=Nr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),ef=Et.z.strictObject({from:Et.z.iso.datetime({offset:!0}),to:Et.z.iso.datetime({offset:!0}),interval:Nr.shape.interval,timezone:Nr.shape.timezone,rows:Et.z.array(Et.z.strictObject({...Dc.shape,eventCount:ui,units:Ym,tokenEventCount:ui,tokens:Et.z.strictObject(Object.fromEntries(Jm.map(e=>[e,ui]))),totalTokens:ui,providerCostEventCount:ui,providerCostUsd:Ym,invalidTelemetryEventCount:ui})).max(100),nextCursor:Dc.nullable()});var st=require("zod");var tf=st.z.object({requestId:st.z.uuid(),items:st.z.array(st.z.object({customerId:st.z.uuid(),command:Ei.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"),nf=st.z.object({batchId:st.z.uuid(),after:st.z.number().int().min(-1).max(999),limit:st.z.number().int().min(1).max(100)}).strict(),rf=st.z.object({batchId:st.z.uuid(),status:st.z.enum(["queued","complete"]),total:st.z.number().int().min(1).max(1e3),processed:st.z.number().int().min(0).max(1e3),items:st.z.array(st.z.object({position:st.z.number().int().min(0).max(999),customerId:st.z.uuid(),idempotencyKey:st.z.string().min(1).max(120),status:st.z.enum(["queued","accepted","rejected","failed"]),receipt:Ri.nullable(),errorCode:st.z.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:st.z.number().int().min(0).max(999).nullable()}).strict();var _=require("zod");var JS=_.z.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),of=_.z.enum(["draft","active","paused","archived"]),af=_.z.string().min(1).max(256),sf=_.z.array(af).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),ZS=_.z.strictObject({duration:_.z.enum(["day","week","month","year"]),length:_.z.number().int().min(1).max(3660)}),WS=_.z.strictObject({internal_feature_id:_.z.uuid(),allowance:_.z.number().nonnegative().max(1e15).nullable(),expiry:ZS.nullable()}),YS=_.z.discriminatedUnion("type",[_.z.strictObject({type:_.z.literal("feature_grant"),grants:_.z.array(WS).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),_.z.strictObject({type:_.z.literal("free_product"),productId:af,duration:Zt}),_.z.strictObject({type:_.z.literal("invoice_credits"),amount:_.z.number().positive().max(1e8),duration:Zt,rollover:_.z.boolean(),productIds:sf})]),XS=_.z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),cf=_.z.object({key:XS,name:_.z.string().trim().min(1).max(80),configuration:YS}).strict(),uf=_.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Fc=_.z.object({code:uf,maxUses:_.z.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:_.z.boolean()}).strict(),lf=_.z.object({key:_.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:_.z.string().trim().min(1).max(80),rewardId:_.z.uuid(),redeemOn:_.z.enum(["customer_creation","checkout"]),receivedBy:_.z.enum(["referrer","all"]),maxRedemptions:_.z.number().int().min(1).max(1e6).nullable(),productIds:sf,excludeTrial:_.z.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),df={id:_.z.uuid(),projectId:_.z.uuid(),environmentId:_.z.uuid(),revision:_.z.number().int().nonnegative(),status:of,createdAt:_.z.iso.datetime({offset:!0}),updatedAt:_.z.iso.datetime({offset:!0})},ex=cf.extend(df).strict(),tx=lf.safeExtend(df).strict(),$1=_.z.strictObject({id:_.z.uuid(),key:_.z.string(),name:_.z.string(),type:JS,status:of}),G1=_.z.discriminatedUnion("action",[_.z.object({action:_.z.literal("save"),id:_.z.uuid().nullable(),revision:_.z.number().int().nonnegative(),input:cf}).strict(),_.z.object({action:_.z.enum(["activate","pause","resume","archive","delete"]),id:_.z.uuid(),revision:_.z.number().int().nonnegative()}).strict()]),K1=_.z.discriminatedUnion("action",[_.z.object({action:_.z.literal("save"),id:_.z.uuid().nullable(),revision:_.z.number().int().nonnegative(),input:lf}).strict(),_.z.object({action:_.z.enum(["activate","pause","resume","archive","delete"]),id:_.z.uuid(),revision:_.z.number().int().nonnegative()}).strict()]),pf=_.z.object({id:_.z.uuid(),rewardId:_.z.uuid(),programId:_.z.uuid().nullable(),customerId:_.z.uuid(),referrerId:_.z.uuid().nullable(),status:_.z.enum(["pending","applied","unavailable"]),result:_.z.record(_.z.string(),_.z.unknown()).nullable(),createdAt:_.z.iso.datetime({offset:!0})}).strict(),mf=_.z.object({code:uf,requestId:_.z.uuid()}).strict(),ff=_.z.strictObject({redemptionId:_.z.uuid(),currency:fe,requestId:_.z.uuid(),accepted:_.z.literal(!0)}),nx=_.z.strictObject({type:_.z.literal("checkout"),orderId:_.z.uuid(),productVersionId:_.z.uuid(),currency:fe,duration:Zt,renewalAmountMinor:_.z.number().int().positive().max(1e8),status:_.z.enum(["created","pending","trialing","paid","cancelled","failed"]),url:_.z.url().nullable()}),gf=_.z.discriminatedUnion("type",[nx,_.z.strictObject({type:_.z.literal("subscription"),operationId:_.z.uuid(),membershipId:_.z.uuid(),productVersionId:_.z.uuid(),currency:fe,duration:Zt,renewalAmountMinor:_.z.number().int().positive().max(1e8),status:_.z.enum(["pending","running","applied","failed"])})]),hf=_.z.object({programId:_.z.uuid(),requestId:_.z.uuid()}).strict(),Af=_.z.object({id:_.z.uuid(),programId:_.z.uuid(),code:Fc.shape.code,createdAt:_.z.iso.datetime({offset:!0})}).strict(),H1=_.z.object({rows:_.z.array(ex).max(100),nextCursor:_.z.uuid().nullable()}).strict(),Q1=_.z.object({rows:_.z.array(tx).max(100),nextCursor:_.z.uuid().nullable()}).strict(),rx=Fc.extend({id:_.z.uuid(),redemptions:_.z.number().int().nonnegative()}).strict(),ix=_.z.strictObject({id:_.z.uuid(),programId:_.z.uuid().nullable(),customerId:_.z.uuid().nullable(),referrerId:_.z.uuid().nullable(),code:_.z.string().nullable(),status:_.z.enum(["pending","triggered","applied"]),createdAt:_.z.iso.datetime({offset:!0})}),J1=_.z.object({codes:_.z.array(rx).max(100),redemptions:_.z.array(ix).max(100),customers:_.z.record(_.z.uuid(),_.z.string()),codesCursor:_.z.uuid().nullable(),redemptionsCursor:_.z.uuid().nullable()}).strict(),Z1=_.z.discriminatedUnion("action",[_.z.object({action:_.z.literal("create"),rewardId:_.z.uuid(),revision:_.z.number().int().nonnegative(),input:Fc}).strict(),_.z.object({action:_.z.literal("remove"),rewardId:_.z.uuid(),revision:_.z.number().int().nonnegative(),codeId:_.z.uuid()}).strict()]);var x=require("zod");var Q=require("zod"),wn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Xi=e=>new Set(e).size===e.length,Mc=Q.z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),ox=Q.z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),eo=Q.z.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"))),ax=Q.z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),yf=Q.z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var bf=Q.z.strictObject({id:Q.z.uuid(),repo:ox,platform:Q.z.enum(["github","gitlab","bitbucket"]),branches:Q.z.array(eo).min(1).max(4).refine(Xi),workflow:Q.z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:Q.z.array(Q.z.uuid()).min(1).max(4).refine(Xi),include:Q.z.array(yf).min(1).max(16),exclude:Q.z.array(yf).max(16),methods:Q.z.array(Q.z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Xi),maxAgeHours:Q.z.number().int().min(1).max(720)}),Sf=bf.extend({revision:Q.z.number().int().positive()}),Y1=Q.z.strictObject({repository:bf,expectedRevision:Q.z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),xf=Q.z.strictObject({repositoryId:Q.z.uuid(),branch:eo}),sx=Q.z.array(Mc).max(wn.keys).refine(Xi),If=Q.z.strictObject({repository:Sf.omit({keyIds:!0}),branch:eo,keys:sx,keySetHash:Q.z.string().regex(/^[a-f0-9]{64}$/)}),cx=Q.z.strictObject({filePath:ax,startingLineNumber:Q.z.number().int().min(1).max(1e7)}),qc=Q.z.strictObject({protocol:Q.z.literal(1),repositoryId:Q.z.uuid(),branch:eo,workflow:Q.z.string().max(200),configurationRevision:Q.z.number().int().positive(),keySetHash:Q.z.string().regex(/^[a-f0-9]{64}$/),commit:Q.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:Q.z.uuid(),runNumber:Q.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:Q.z.number().int().min(1).max(1e4),scannerVersion:Q.z.literal("1"),scannedAt:Q.z.iso.datetime({offset:!0}),coverage:Q.z.strictObject({complete:Q.z.literal(!0),files:Q.z.number().int().min(0).max(wn.files),sourceBytes:Q.z.number().int().min(0).max(wn.sourceBytes),unresolvedCalls:Q.z.number().int().min(0).max(1e6),unsupportedFiles:Q.z.number().int().min(0).max(wn.files)}),features:Q.z.array(Q.z.strictObject({key:Mc,refs:Q.z.array(cx).max(wn.referencesPerKey)})).max(wn.keys)}).superRefine((e,t)=>{Xi(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)>wn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Vc=Q.z.strictObject({scanId:Q.z.uuid(),commit:Q.z.string(),receivedAt:Q.z.string(),references:Q.z.number().int().nonnegative(),removedReferences:Q.z.number().int().nonnegative()}),ux=Vc.extend({repositoryId:Q.z.uuid(),branch:eo,workflow:Q.z.string(),digest:Q.z.string(),configurationRevision:Q.z.number().int().positive(),runNumber:Q.z.number().int().positive(),runAttempt:Q.z.number().int().positive(),scannedAt:Q.z.string(),keySetHash:Q.z.string(),coverage:qc.shape.coverage}),lx=Q.z.strictObject({repositories:Q.z.array(Sf).max(wn.repositories),scans:Q.z.array(ux).max(wn.repositories*wn.branches)}),dx=Q.z.strictObject({key:Mc,references:Q.z.number().int().nonnegative(),coveredTargets:Q.z.number().int().nonnegative(),expiredTargets:Q.z.number().int().nonnegative(),uncertainTargets:Q.z.number().int().nonnegative()}),X1=Q.z.strictObject({available:Q.z.boolean().default(!0),settings:lx,expectedTargets:Q.z.number().int().min(0).max(80),features:Q.z.array(dx).max(2001),truncated:Q.z.boolean()});var Tt=require("zod"),wf={customerId:Tt.z.uuid(),eventId:Tt.z.string().trim().min(1).max(200),grantId:Tt.z.uuid(),occurredAt:Tt.z.iso.datetime({offset:!0})},Of=Tt.z.strictObject({...wf,productVersionId:Tt.z.uuid(),subscriptionId:Tt.z.string().trim().min(1).max(255)}),Cf=Tt.z.strictObject({...wf,merchandiseId:Tt.z.uuid()}),Pf=Tt.z.union([Of,Cf]),vf={id:Tt.z.uuid(),couponId:Tt.z.uuid(),status:Tt.z.literal("redeemed"),source:Tt.z.literal("merchant"),recordedAt:Tt.z.iso.datetime({offset:!0})},_f=Tt.z.union([Of.extend(vf),Cf.extend(vf)]);var te=require("zod");var Uc=te.z.strictObject({name:te.z.string().trim().min(1).max(255),memo:te.z.string().max(1e4).nullable().optional(),footer:te.z.string().max(1e4).nullable().optional(),net_terms_days:te.z.number().int().positive().nullable().optional()}),px=Uc.extend({id:te.z.string().min(1).max(255),created_at:te.z.number().nullable()}),Ef=te.z.strictObject({items:te.z.array(px).max(50),nextCursor:te.z.uuid().nullable()}),r_=te.z.discriminatedUnion("action",[te.z.strictObject({action:te.z.literal("create"),requestId:te.z.uuid(),values:Uc}),te.z.strictObject({action:te.z.literal("update"),id:te.z.string().min(1).max(255),values:Uc}),te.z.strictObject({action:te.z.literal("delete"),id:te.z.string().min(1).max(255)})]),Rf=te.z.discriminatedUnion("action",[te.z.strictObject({action:te.z.literal("create"),requestId:te.z.uuid(),params:Xr}),te.z.strictObject({action:te.z.enum(["finalize","send","pay","void"]),requestId:te.z.uuid(),invoiceId:te.z.uuid()}),te.z.strictObject({action:te.z.literal("reissue"),requestId:te.z.uuid(),invoiceId:te.z.uuid(),params:Us})]),Lc=te.z.strictObject({id:te.z.uuid(),customerId:te.z.uuid(),providerInvoiceId:te.z.string().nullable(),status:te.z.enum(["draft","open","paid","void","uncollectible"]),currency:te.z.string(),totalMinor:te.z.string().regex(/^-?\d+$/),paidMinor:te.z.string().regex(/^\d+$/),refundedMinor:te.z.string().regex(/^\d+$/),hostedInvoiceUrl:te.z.url().nullable(),createdAt:te.z.number(),collectionMethod:te.z.enum(["send_invoice","charge_automatically"]).nullable()}),kf=Lc.extend({lines:te.z.array(te.z.strictObject({id:te.z.uuid(),description:te.z.string(),amountMinor:te.z.string().regex(/^-?\d+$/),netAmountMinor:te.z.string().regex(/^-?\d+$/),quantity:te.z.number().nullable(),periodStart:te.z.number().nullable(),periodEnd:te.z.number().nullable()})).max(1e3)}),to=te.z.strictObject({taskId:te.z.uuid(),status:te.z.enum(["ready","running","done","dead"]),invoice:Lc.nullable(),errorCode:te.z.string().nullable()}),jf=te.z.strictObject({items:te.z.array(Lc).max(50),nextCursor:te.z.uuid().nullable(),operations:te.z.array(to).max(50),operationsLimited:te.z.boolean()});var mx=x.z.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"]),Tf={scope:Le,permissions:x.z.array(mx),expiresAt:x.z.iso.datetime().nullable()},H_=x.z.discriminatedUnion("kind",[x.z.object({...Tf,kind:x.z.literal("server"),keyId:x.z.string().min(1)}),x.z.object({...Tf,kind:x.z.literal("customer"),customerId:x.z.string().min(1),identityKind:x.z.enum(["identified","guest"]),expiresAt:x.z.iso.datetime()})]),L=x.z.object({requestId:x.z.uuid(),scope:Le}).strict(),fx=ym.safeExtend({fingerprint:ga.optional()}).strict(),gx=L.extend({customer:oi,created:x.z.boolean()});function Nf(){return L.extend({offer:vi.nullable(),reason:Ml.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Cd,response:L.extend({message:x.z.object({messageId:x.z.uuid(),channel:Ni,acceptedAt:x.z.iso.datetime({offset:!0}),status:x.z.enum(["accepted","sending","completed","canceled"]),replayed:x.z.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:x.z.strictObject({messageId:x.z.uuid()}),response:L.extend({message:x.z.object({id:x.z.uuid(),channel:Ni,status:x.z.enum(["accepted","sending","completed","canceled"]),deliveries:x.z.array(x.z.object({id:x.z.uuid(),status:_d,attempts:x.z.number().int().nonnegative(),receipts:x.z.array(x.z.object({kind:Ed,occurredAt:x.z.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:vu,response:L.extend({installation:dr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:wu,response:L.extend({installation:dr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:go,response:L.extend({installation:dr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:x.z.strictObject({channel:Ni}),response:L.extend({preference:Qa})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Pd,response:L.extend({preference:Qa})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:x.z.strictObject({cursor:x.z.uuid().optional()}),response:L.extend({templates:Ef})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),params:Xr}),response:L.extend({preview:Ls})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),requestId:x.z.uuid(),params:Xr}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:L.extend({operation:to})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:Rf}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:L.extend({operation:to})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),taskId:x.z.uuid()}),response:L.extend({operation:to})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),cursor:x.z.uuid().optional()}),response:L.extend({invoices:jf})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),invoiceId:x.z.uuid()}),response:L.extend({invoice:kf})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:xf,response:L.extend({config:If})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:qc,response:L.extend({receipt:Vc})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:x.z.strictObject({}),response:L.extend({payload:Hi})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Zp,response:L.merge(oa)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Wp,response:L.merge(Yp)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),sourceId:x.z.uuid()}),response:L.extend({balance:Gm})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:$m}),response:L.extend({balance:jc})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:x.z.strictObject({internal_feature_id:x.z.uuid(),customerId:x.z.uuid().optional(),entityId:x.z.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:L.extend({internal_feature_id:x.z.uuid(),config:es,model_markups:So})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),query:Vo}),response:L.extend({usage:ki})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:Ad}),response:L.extend({usage:ki})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:dd}),response:L.extend({grant:vs})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:pd,response:L.extend({grants:md})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:x.z.union(qp.options.map(e=>e.extend({customerId:x.z.uuid().optional(),customerToken:x.z.string().regex(Dt).optional()}))),response:L.extend({operation:Vp})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Pp.extend({customerId:x.z.uuid().optional()}),response:L.extend({setup:Ks})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:_p.extend({customerId:x.z.uuid().optional()}),response:L.extend({setup:Ks})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:wp.safeExtend({customerId:x.z.uuid()}),response:L.extend({batch:Bi})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Yo.extend({customerId:x.z.uuid()}),response:L.extend({batch:Bi})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Yo.extend({customerId:x.z.uuid()}),response:L.extend({batch:Bi})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Yo.extend({customerId:x.z.uuid()}),response:L.extend({batch:Bi})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:x.z.discriminatedUnion("action",[Xo.options[0].extend({customerId:x.z.uuid()}),Xo.options[1].extend({customerId:x.z.uuid()}),Xo.options[2].extend({customerId:x.z.uuid()})]),response:L.extend({trial:Gs})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Op.extend({customerId:x.z.uuid()}),response:L.extend({trial:Gs})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:na,response:L.extend({subscriptions:Dp})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:na,response:L.extend({purchases:Fp})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:jp,response:L.extend({conflicts:Mp})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Tp,response:L.extend({resolution:Np})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Rp,response:L.extend({verification:kp})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:gp.safeExtend({...Wr,customerId:x.z.uuid().optional()}),response:L.extend({quote:Ui})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:Du,response:L.extend({record:Fu})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Pr.extend({customerId:x.z.uuid().optional(),intent:x.z.enum(["confirm","cancel"]).optional()}),response:L.extend({operation:ei})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Pr.extend({customerId:x.z.uuid().optional()}),response:L.extend({operation:ei})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:yp.safeExtend({customerId:x.z.uuid().optional()}),response:L.extend({quote:Sp})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Pr.extend({customerId:x.z.uuid().optional(),intent:x.z.enum(["confirm","cancel"]).optional()}),response:L.extend({operation:zs})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Pr.extend({customerId:x.z.uuid().optional()}),response:L.extend({operation:zs})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:xp.safeExtend({customerId:x.z.uuid()}),response:L.extend({quote:vp})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Pr.extend({customerId:x.z.uuid()}),response:L.extend({operation:Wo})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Pr.extend({customerId:x.z.uuid()}),response:L.extend({operation:Wo})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Wl,response:L.extend({controls:xs})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:$l,response:L.extend({prepared:Kl})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Hl,response:L.extend({authorization:Do})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:td,response:L.extend({coupons:nd})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Ql,response:L.extend({authorization:Do})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Xl,response:L.extend({invoices:ed})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Yl,response:L.extend({invoice:Ci})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:x.z.object({customerId:x.z.uuid(),command:Zl}).strict(),response:L.extend({controls:xs})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:x.z.object({customerId:x.z.uuid(),command:Km}).strict(),response:L.extend({entity:Hm})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid().nullable(),query:Xm}),response:L.extend({analytics:ef})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:x.z.object({customerId:x.z.uuid().nullable(),query:Nr}).strict(),response:L.extend({analytics:Wm})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:tf,response:L.extend({batchId:x.z.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:nf,response:L.extend({batch:rf})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Td.extend({customerId:x.z.string().min(1).optional()}),response:L.extend({check:vr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:x.z.strictObject({kind:Qn,selector:x.z.discriminatedUnion("type",[x.z.strictObject({type:x.z.literal("resource"),id:x.z.uuid()}),x.z.strictObject({type:x.z.literal("version"),id:x.z.uuid()})]),customerId:x.z.string().min(1).optional()}),response:L.extend({content:Ms})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Lm,response:L.extend({paywall:kr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:x.z.strictObject({...Wr,selector:zp,customerId:x.z.string().min(1).optional(),commerce:Kr,requirement:$n.optional()}),response:L.extend({offering:$p,candidates:x.z.array(_s).max(20),availability:x.z.array(x.z.strictObject({productVersionId:x.z.uuid(),available:x.z.boolean(),reason:x.z.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:vr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:x.z.object({customerId:x.z.uuid().optional(),entityId:x.z.uuid().optional()}).strict(),response:L.extend({holdings:yd})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:x.z.object({customerId:x.z.uuid().optional(),query:Sd}).strict(),response:L.extend({ledger:xd})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:fd.extend({customerId:x.z.uuid().optional()}),response:L.extend({detail:gd})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:ws.safeExtend({customerId:x.z.uuid().optional()}),response:L.extend({statement:hd})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:x.z.object({customerId:x.z.uuid().optional(),command:Ei.options[0]}).strict(),response:L.extend({quote:cd})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:x.z.union([x.z.strictObject({eventName:x.z.string().min(1),quantity:me.optional(),properties:At.optional(),entityId:x.z.uuid().optional(),idempotencyKey:x.z.string().min(1).max(120)}),x.z.strictObject({internal_feature_id:x.z.uuid(),quantity:me.optional(),properties:At.optional(),entityId:x.z.uuid().optional(),idempotencyKey:x.z.string().min(1).max(120)})])}),response:L.extend({receipts:x.z.array(Ri).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:x.z.object({customerId:x.z.uuid(),command:Ei.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:L.extend({receipt:Ri})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:mf,response:L.extend({redemption:pf})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:hf,response:L.extend({referralCode:Af})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:ff,response:L.extend({checkout:gf})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:vd,response:L.extend({seats:Ps})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:wd,response:L.extend({seats:Ps})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:fx,response:gx},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:hc,response:L.extend({customer:oi})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:xm,response:L.extend(Im.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Sm,response:L.extend(bm.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:x.z.object({customerId:x.z.uuid()}).strict(),response:L.extend(qr.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:x.z.strictObject({}),response:L.extend(qr.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),sessionId:x.z.uuid().optional()}),response:L.extend({revoked:x.z.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:x.z.strictObject({guestToken:x.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:ga.optional()}),response:L.extend({customerId:x.z.uuid(),guestToken:x.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:x.z.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:x.z.strictObject({guestToken:x.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:L.extend(qr.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:x.z.strictObject({guestToken:x.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:x.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:x.z.uuid()}),response:L.extend({customer:oi,switched:x.z.boolean(),replayed:x.z.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:x.z.strictObject({code:x.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:x.z.uuid()}),response:Nf()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:x.z.object({}).strict(),response:L.extend({offers:x.z.array(vi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:x.z.object({customerId:x.z.string().min(1).max(255).optional(),couponId:x.z.uuid(),...Wr,requestId:x.z.uuid(),couponContentDigest:x.z.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Nf()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:Pf,response:L.extend({receipt:_f})}},Q_={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};var Pa=require("zod");var no=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function Bc(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 no("Required GB Feature is unavailable");i=En(e.featureKey,t),o=i.value,Object.assign(r,Zr(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new no("Required GB Experiment is unavailable");if(a=To(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 no("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:En(e.configuration.featureKey,t).value;o={type:"offering_version",id:Pa.z.uuid().parse(u)},Object.assign(r,Zr(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,Zr(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 Df(e,t,n){Pa.z.uuid().parse(e),Pa.z.number().int().nonnegative().parse(t);let r=Ur(Lr(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)}`}var $=require("zod");var er=$.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),hx=$.z.enum(["running","waiting","completed","closed","ineligible","failed"]),Ax=$.z.discriminatedUnion("type",[fc,$.z.strictObject({type:$.z.literal("wait"),receiptId:$.z.uuid(),kind:$.z.enum(["timer","event","operation"]),deadline:$.z.iso.datetime({offset:!0}).nullable(),eventName:er.optional()}),$.z.strictObject({type:$.z.literal("open_url"),receiptId:$.z.uuid(),url:Ac,openIn:yc}),$.z.strictObject({type:$.z.literal("event"),receiptId:$.z.uuid(),event:er})]),_a=$.z.strictObject({type:$.z.literal("funnel"),id:$.z.uuid(),versionId:$.z.uuid()}),yx={id:er,presentation:Tn,outputs:$.z.array(er).max(250),inputs:ua,values:$.z.record($.z.string(),ge).optional(),offeringKey:dt.optional(),capabilities:Hr,customerData:Ud,dataCursors:$.z.record(er,ca.nullable())},bx=$.z.strictObject({...yx,content:$.z.strictObject({type:$.z.literal("document"),document:Yt})}),zc=$.z.strictObject({id:$.z.uuid(),source:_a,revision:$.z.number().int().nonnegative(),visit:$.z.number().int().nonnegative(),nodeId:er,nodeType:$.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:hx,stopped:$.z.boolean(),canBack:$.z.boolean(),authenticated:$.z.boolean(),locale:$.z.string().min(1).max(35),answers:Zn,parameters:Wn,variables:$.z.record($.z.string(),ge),output:ge.nullable(),screen:bx.nullable(),paywall:$.z.strictObject({receiptId:$.z.uuid(),resolution:$.z.union([Yi,kr]),quote:Ui.nullable(),operation:ei.nullable(),purchaseRequestId:$.z.uuid().nullable(),selectionGeneration:$.z.number().int().nonnegative().optional(),canReselect:$.z.boolean().optional()}).nullable(),instruction:Ax.nullable(),pendingRequest:$.z.strictObject({requestId:$.z.uuid(),authenticationRequired:$.z.boolean()}).nullable(),runExpiresAt:$.z.iso.datetime({offset:!0}),credentialExpiresAt:$.z.iso.datetime({offset:!0}).nullable()}),ro=$.z.strictObject({scope:Le,run:zc,settlement:$.z.strictObject({requestId:$.z.uuid(),state:$.z.enum(["pending","unknown","settled"]),operationId:$.z.uuid().nullable(),receiptId:$.z.uuid().nullable().optional()}).optional(),purchase:$.z.strictObject({receiptId:$.z.uuid(),quote:Ui.nullable(),operation:ei.nullable(),canReselect:$.z.boolean().optional()}).optional(),review:$.z.strictObject({activeOperationId:$.z.uuid().nullable(),pages:$.z.array($.z.strictObject({receiptId:$.z.uuid(),nodeId:er,visit:$.z.number().int().nonnegative()})).max(100),page:$.z.strictObject({receiptId:$.z.uuid(),nodeId:er,visit:$.z.number().int().nonnegative(),document:Yt,answers:Zn,inputs:ua,values:$.z.record($.z.string(),ge).optional()}).nullable(),coupons:$.z.array($.z.strictObject({grantId:$.z.uuid(),status:$.z.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:$.z.string().nullable()})).max(100),purchases:$.z.array($.z.strictObject({receiptId:$.z.uuid(),operationId:$.z.uuid(),status:$.z.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:$.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:$.z.uuid().optional()}),Ff=ro.extend({run:zc.extend({paywall:zc.shape.paywall.unwrap().extend({resolution:kr}).nullable()})});var Mf="X-Indiana-Server-Key";var _e=require("zod");var li=_e.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Vf=_e.z.strictObject({entry:li,nodes:_e.z.array(_e.z.strictObject({id:li,type:_e.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:_e.z.record(_e.z.string(),li),writes:_e.z.record(dt,dt),resources:_e.z.strictObject({screenId:li.optional(),paywallVersionId:_e.z.uuid().optional(),couponId:_e.z.uuid().optional(),couponIds:_e.z.array(_e.z.uuid()).max(20).optional(),experimentId:_e.z.uuid().optional(),featureKey:_e.z.string().optional(),offeringVersionId:_e.z.uuid().optional()})})).min(1).max(500)}),qf={scope:Le,funnelId:_e.z.uuid(),versionId:_e.z.uuid(),evaluationRevision:_e.z.number().int().nonnegative(),expiresAt:_e.z.iso.datetime({offset:!0}).nullable(),topology:Vf},Ea=_e.z.discriminatedUnion("evaluationMode",[_e.z.strictObject({...qf,evaluationMode:_e.z.literal("local"),growth:sn,conditions:_e.z.record(li,_e.z.array(_e.z.strictObject({condition:Bt,port:_e.z.string()})))}),_e.z.strictObject({...qf,evaluationMode:_e.z.literal("remote")})]),Sx=Ea.options[0].extend({evaluation:_e.z.strictObject({maxTransitions:_e.z.number().int().min(1).max(1e4),variables:_e.z.record(dt,Jr),outputSchema:Qr,terminals:_e.z.record(li,_e.z.strictObject({outcome:_e.z.enum(["completed","closed","ineligible","failed"]),output:Ji.nullable()}))})});function xx(e){return Vf.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=_e.z.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 $c(e){let t=si.parse(e.document),n=e.evaluationMode==="local"?sn.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:xx(t)};return Ea.parse(e.evaluationMode==="remote"?r:{...r,growth:wa(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 Uf(e){let t=$c(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=si.parse(e.document);return Sx.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}]]}))}})}var Ze=require("zod");var Lf=Ze.z.string().regex(/^[a-f0-9]{64}$/),Ix=ii.omit({variations:!0,active:!0}).extend({changeId:Lf,variations:Ze.z.array(Ze.z.strictObject({urlRedirect:Ze.z.string().max(2048)})).min(2).max(20)}),Bf=Ze.z.strictObject({environmentId:Ze.z.uuid(),trackExposures:Ze.z.boolean(),generation:Lf,experiments:Ze.z.array(Ix).max(100),savedGroups:Ki}),vx=Ze.z.strictObject({eventUuid:Ze.z.uuid(),timestamp:Ze.z.iso.datetime({offset:!0}).optional(),deviceId:Ze.z.string().min(1).max(128),sessionId:Ze.z.string().min(1).max(128).optional(),url:Ze.z.url().max(2048),pageTitle:Ze.z.string().max(512).optional(),experimentKey:Ze.z.string().min(1).max(255),variationKey:Ze.z.string().min(1).max(64)}),OE=Ze.z.strictObject({events:Ze.z.array(vx).min(1).max(20)}),CE=Ze.z.strictObject({inserted:Ze.z.number().int().nonnegative(),duplicates:Ze.z.number().int().nonnegative(),skipped:Ze.z.number().int().nonnegative(),rejected:Ze.z.array(Ze.z.strictObject({index:Ze.z.number().int().nonnegative(),reason:Ze.z.string()}))});var ft=require("zod");var wx=ft.z.strictObject({selector:ft.z.string().min(1).max(2048),action:ft.z.enum(["set","append","remove"]),attribute:ft.z.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:ft.z.string().max(5e4).optional(),parentSelector:ft.z.string().max(2048).optional(),insertBeforeSelector:ft.z.string().max(2048).optional()}),Ox=ft.z.strictObject({variation:ft.z.string().min(1).max(128),description:ft.z.string().max(2e3).default(""),css:ft.z.string().max(1e5).default(""),js:ft.z.string().max(1e5).default(""),domMutations:ft.z.array(wx).max(200).default([]),iam:im.optional(),renderGuard:aa.optional()}),Gc=Ox.omit({variation:!0,description:!0,iam:!0}),Cx=ii.omit({variations:!0,active:!0}).extend({changeId:ft.z.string().regex(/^[a-f0-9]{64}$/),variations:ft.z.tuple([Gc,Gc]).rest(Gc).refine(e=>e.length<=20)}),zf=ft.z.strictObject({trackExposures:ft.z.boolean(),environmentId:ft.z.uuid(),generation:ft.z.string().regex(/^[a-f0-9]{64}$/),experiments:ft.z.array(Cx).max(100),savedGroups:Ki});var et=require("zod");var Hc=32,Px=522240;function Qc(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 _x=et.z.strictObject({nodeId:et.z.string().min(1).max(64),visit:et.z.number().int().nonnegative(),revision:et.z.number().int().nonnegative()}),Kc=et.z.record(et.z.string(),ge),Ex=et.z.strictObject({id:et.z.uuid(),nodeId:et.z.string().min(1).max(64),visit:et.z.number().int().nonnegative(),input:et.z.strictObject({schemaVersion:Zi.shape.schemaVersion,kind:Zi.shape.kind,selector:Zi.shape.selector,contract:Zi.shape.contract}),context:Kc,removed:et.z.array(et.z.string()).max(100),attributes:Kc,removedAttributes:et.z.array(et.z.string()).max(100),result:Em,offeringVersionId:et.z.uuid().nullable(),events:et.z.strictObject({entered:et.z.string().regex(/^[1-9][0-9]{0,18}$/),decision:et.z.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),DE=et.z.strictObject({schemaVersion:et.z.literal(1),mode:et.z.enum(["local","remote"]),versionId:et.z.uuid(),generation:et.z.number().int().positive(),base:_x,context:Kc,steps:et.z.array(Ex).min(1).max(Hc)}).refine(e=>Xt(e)<=Px,"Segment exceeds its byte budget");var Jc=class extends Error{constructor(n,r){super(r);Ue(this,"code",n);this.name="FunnelLocalCalculationError"}},$f=(e,t)=>new Jc(e,t),Rx=e=>({experiments:e.experiments,features:e.features});function kx(e,t=$f){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=Br(e.growth.savedGroups),i=Rx(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return En(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=Bc({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=Bc({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 jx(e,t){let n=Ea.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=kx(n,t);return(o,s)=>(i(),Tx(a,o,s))}function Tx(e,t,n){let r=yt.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 Nx(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 Gf(e,t,n,r=$f){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=jx(e,r)),Nx(w,g,{attributes:uc({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let g=0;g<Hc;g++){let f=a.get(u);if(!f||!Qc(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"?Ns({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||!an(t.outputSchema,S.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let P=[...c,{nodeId:u,result:S}];if(Xt({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=Zr(f,{value:v});Kd(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&&!Qc(p)?{boundary:{nodeId:u,visit:d}}:{}}}var Ae=require("zod");var Ra=Ae.z.string().regex(/^[a-f0-9]{64}$/),Dx=Ae.z.strictObject({release:Ra,render:aa,button:Ae.z.strictObject({selector:Ae.z.string().min(1).max(512),elementKey:Ae.z.string().min(1).max(256),tag:Ae.z.enum(["button","a","input"])}).nullable()}),YE=Ae.z.strictObject({scope:Le.extend({environmentId:Ae.z.uuid()}),release:Ra,validatedAt:Ae.z.iso.datetime({offset:!0}),validUntil:Ae.z.iso.datetime({offset:!0}),entries:Ae.z.array(Ae.z.strictObject({id:Ae.z.uuid(),funnelId:Ae.z.uuid(),versionId:Ae.z.uuid(),event:Ae.z.enum(["screen_enter","button_click"]),target:Dx})).max(4e3)}),XE=Ae.z.strictObject({operation:Ae.z.literal("entry_start"),funnelId:Ae.z.uuid(),versionId:Ae.z.uuid(),entryId:Ae.z.uuid(),release:Ra,requestId:Ae.z.uuid(),locale:Ae.z.string().min(1).max(35).default("en")}),eR=Ae.z.strictObject({scope:Le,suppressed:Ae.z.literal(!0),reason:Ae.z.enum(["frequency","in_progress"]),retryAt:Ae.z.iso.datetime({offset:!0}).nullable()}),tR=Ae.z.strictObject({experimentId:Ae.z.uuid(),splitNodeId:Ae.z.string().min(1).max(128)}),Fx=Ae.z.strictObject({experimentId:Ae.z.uuid(),experimentKey:Ae.z.string().min(1).max(128),variationKey:Ae.z.string().min(1).max(128),inExperiment:Ae.z.boolean(),generation:Ae.z.string().min(1).max(256)}),Kf=Ae.z.strictObject({operation:Ae.z.literal("page_experiments"),release:Ra,usedReceiptIds:Ae.z.array(Ae.z.uuid()).max(20).default([]),customerToken:Ae.z.string().regex(Dt).optional()}),Hf=Ae.z.strictObject({scope:Le,runId:Ae.z.uuid(),assignments:Ae.z.array(Fx.extend({receiptId:Ae.z.uuid()})).max(20),payload:zf});var y=class extends Error{constructor(n,r,i,a,o){super(r);Ue(this,"code",n);Ue(this,"status",i);Ue(this,"requestId",a);Ue(this,"retryable");Ue(this,"recovery");Ue(this,"retryAfterSeconds");Ue(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=ho(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 io=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new y("INVALID_STATE","Installation sequence exhausted");return e+1},Mx=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 Dn(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 Qf(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve();if(e&&(!n||Le.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 Mx(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=dr.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(_u(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=Dn(h,xe=>xe),j;if(E.detachSeq!==null){let xe=E.detachSeq,De=Ou.parse(await w("detach",{sequence:xe,platform:h.platform}));try{let Ee=await t.request("push/installations/detach",{...h.scope,...De},"POST",{installationDetach:!0});if(!Ee||typeof Ee!="object"||!("installation"in Ee))throw new y("INVALID_RESPONSE","Push detach acknowledgement is invalid");let Vt=m(Ee.installation);if(Vt.bound||Vt.identitySeq!==xe)throw new y("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Ee){if(Ee instanceof y&&Ee.status===404)j=Ee;else if(!(Ee instanceof y)||Ee.status!==412)throw Ee}j||Dn(h,Ee=>({...Ee,detachSeq:Ee.detachSeq===xe?null:Ee.detachSeq}))}if(u(P),!v){if(j)throw j;return null}let q=O.bindPushInstallation,pe=q.request.parse(await w("bind",{sequence:o,platform:h.platform,credentialDigest:await d(v)}));u(P);let Se=q.response.parse(await I(q.path,pe,v));u(P);let Oe=m(Se.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&&Dn(h,xe=>({...xe,detachSeq:xe.detachSeq===E.detachSeq?null:xe.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,pe=r?await(t.session?.access()??r):null;if(u(j),q!==a)throw new y("INVALID_STATE","Push observation changed during recovery");if(!pe)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 Se=Dn(E,Vt=>v?Vt:{...Vt,addressSeq:io(Vt.addressSeq)}),xe=await w(v?"recovery_confirm":"recovery_request",{...h,sequence:Se.addressSeq,credentialDigest:await d(pe),...v?{challenge:v}:{}}),De=v?Pu.parse(xe):Cu.parse(xe);if(u(j),q!==a)throw new y("INVALID_STATE","Push observation changed during recovery");let Ee=await I(`push/installations/recovery/${v?"confirm":"request"}`,De,pe);if(u(j),q!==a||Dn(E,Vt=>Vt).addressSeq!==Se.addressSeq)throw new y("INVALID_STATE","Push observation changed during recovery");if(v){let Vt=O.updatePushAddress.response.parse(Ee),We=m(Vt.installation);if(!We.bound||We.identitySeq!==o||We.addressSeq!==Se.addressSeq||We.connectionId!==h.connectionId||We.addressStatus!=="active")throw new y("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return We}if(!Ee||typeof Ee!="object"||!("recovery"in Ee))throw new y("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return Ha.parse(Ee.recovery)})}return{recoveryObserver(){c();let h={identity:i,observation:++a};return{async request(P){return Ha.parse(await S(P,h))},async confirm(P,v){return dr.parse(await S(v,h,P))}}},identify(h){if(!e)return;o=Dn(e,v=>({...v,identitySeq:io(v.identitySeq)})).identitySeq,r=h,i++,a++},reset(){if(e)try{Dn(e,h=>{let P=io(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=Dn(h,q=>{if(q.identitySeq!==v)throw new y("IDENTITY_CHANGED","A newer installation intent exists");return{...q,identitySeq:io(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=Dn(E,xe=>({...xe,addressSeq:io(xe.addressSeq)})),pe=O.updatePushAddress,Se=pe.request.parse(await w("address",{...v,sequence:q.addressSeq,credentialDigest:await d(j)}));if(u(P),h!==a)return null;let Oe=pe.response.parse(await I(pe.path,Se,j));return u(P),m(Oe.installation)}}}}function Jf(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 Zf={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 Vx=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function Ux(e){return e.replace(Vx,"$1\uFFFD")}function Xc(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 og(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 Wf(e){let t;if(Array.isArray(e)){let n=e.map(ze);if(n.length===2)return n}else if((t=og(e))!=null){let n=Xc(t.next()),r=Xc(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 Yf="0123456789ABCDEF",Lx=/(?:%[0-9A-Fa-f]{2})+/g;function On(e){return`%${Yf[e>>4&15]}${Yf[15&e]}`}function ag(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?On(e):String.fromCharCode(e):e<=2047?On(192|e>>6)+On(128|63&e):e<=65535?On(224|e>>12)+On(128|e>>6&63)+On(128|63&e):On(240|e>>18)+On(128|e>>12&63)+On(128|e>>6&63)+On(128|63&e)}function eu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function tu(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(Lx,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function so(e){return e<=31||e>126}function Bx(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return so(e)}}function cu(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return so(e)}}function zx(e){return cu(e)||e===39}function nu(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return cu(e)}}function Da(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 nu(e)}}function Xf(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 Da(n)}})(e)}}function sg(e,t){return ag(e=e||0,t)}function Cn(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+=ag(o,t,n)}return i}function uu(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([tu(i.slice(0,a),!0),tu(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function ru(e){let t="";for(let n=0;n<e.length;n++){let r=Cn(e[n][0],Xf,!0),i=Cn(e[n][1],Xf,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var $x=[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],Gx=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],Kx=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],Hx=[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 Qx(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[Jx,Zx,Wx,eg]=[[[],"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 Yx(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 cg(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function oo(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 Xx(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&&cg(Hx,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&oo(eg,t[i]);)i--;let a=n+1;for(;a<t.length&&oo(eg,t[a]);)a++;if(!(i>=0&&a<t.length&&oo(Zx,t[i])&&oo(Wx,t[a])))return!1}return!0}var e0=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,t0=/\p{Script=Latin}/u;function n0(e){return!e0.test(e)||!t0.test(e)}var tr=36,ja=1,iu=26,r0=38,i0=700,o0=72,a0=128,s0=2147483647;function tg(e){return String.fromCharCode(e+22+75*+(e<26))}function c0(e,t,n){let r=0;for(e=n?Math.floor(e/i0):e>>1,e+=Math.floor(e/t);e>(tr-ja)*iu>>1;r+=tr)e=Math.floor(e/(tr-ja));return Math.floor(r+(tr-ja+1)*e/(e+r0))}function u0(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=a0,o=0,s=o0;for(;r<t.length;){let c=s0;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=tr;;w+=tr){let I=w<=s?ja:w>=s+iu?iu:w-s;if(m<I)break;n+=tg(I+(m-I)%(tr-I)),m=Math.floor((m-I)/(tr-I))}n+=tg(m),s=c0(o,r+1,r===i),o=0,r++}}o++,a++}return n}function Zc(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=eu(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function ng(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function ug(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function lg(e){return e.length===2&&ug(e.codePointAt(0),e.codePointAt(1))}function rg(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function ct(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function dg(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function ou(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=eu(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+eu(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 rg(r)?null:Cn(r,so)})(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)&&!cg($x,m)||oo(Jx,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=Yx(m,w);if(I){d+=I;continue}let p=Gx.indexOf(w);d+=p<0?m:Kx[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(Qx(u)||d&&(/^\p{Mark}/u.test(u)||!Xx(u)||!n0(u)||u.startsWith("xn--")))return null;d&&(s[c]=`xn--${u0(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:tu(e));return n===null||rg(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(Zc(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=Zc(a[u]);if(d<0||d>255)return null;s+=d*(1<<8*(3-u))}let c=Zc(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function au(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 pg(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 mg(e){return e.username!==""||e.password!==""}function Wc(e){return e.host===null||e.host===""||e.scheme==="file"}var C=0,F="",be="",qe=null,M,Ta=!1,Na=!1,Dr=!1,ut;function rn(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,be="",qe=n||null,M=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},Ta=!1,Na=!1,Dr=!1,ut=r||0;let i=l0;switch(r){case 3:case 4:i=Fa;break;case 5:i=du;break;case 6:i=Fr;break;case 7:i=nr;break;case 8:i=Pn}return i(z(e,C))!==1?M:null}function W(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 fg(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var l0=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 be=F.slice(C,n).toLowerCase(),C=n,d0(n<F.length?e:void 0)}else return ut?1:(--C,W(t,e)?gg(z(F,C)):0)},d0=e=>{let t=C;if(e===58){if(ut){if(ct(M.scheme)!==ct(be))return 0;if((mg(M)||M.port!==null)&&be==="file")return 0;if(M.scheme==="file"&&M.host==="")return 0}return M.scheme=be,ut?(M.port===dg(M.scheme)&&(M.port=null),0):(be="",M.scheme==="file"?W(t,e)?pu(z(F,C)):0:ct(M.scheme)&&qe!==null&&qe.scheme===M.scheme?W(t,e)?p0(z(F,C)):0:ct(M.scheme)?W(t,e)?f0(z(F,C)):0:z(F,C+1)===47?(C++,W(t,e)?m0(z(F,C)):0):(M.path=[""],M.opaquePath=!0,W(t,e)?Ag(z(F,C)):0))}else return ut?1:(be="",C=-1,W(t,e)?gg(z(F,C)):0)},gg=e=>{let t=C;return qe===null||qe.opaquePath&&e!==35?1:qe.opaquePath&&e===35?(M.scheme=qe.scheme,M.path=qe.path.slice(),M.opaquePath=qe.opaquePath,M.query=qe.query,M.fragment="",W(t,e)?Pn(z(F,C)):0):qe.scheme==="file"?(C--,W(t,e)?pu(z(F,C)):0):(C--,W(t,e)?lu(z(F,C)):0)},p0=e=>{let t=C;return e===47&&z(F,C+1)===47?(++C,W(t,e)?qa(z(F,C)):0):(C--,W(t,e)?lu(z(F,C)):0)},m0=e=>{let t=C;return e===47?W(t,e)?di(z(F,C)):0:(C--,W(t,e)?bn(z(F,C)):0)},lu=e=>{let t=C;return M.scheme=qe.scheme,e===47||ct(M.scheme)&&e===92?W(t,e)?ig(z(F,C)):0:(M.username=qe.username,M.password=qe.password,M.host=qe.host,M.port=qe.port,M.path=qe.path.slice(),M.query=qe.query,e===63?(M.query="",W(t,e)?nr(z(F,C)):0):e===35?(M.fragment="",W(t,e)?Pn(z(F,C)):0):e!=null?(M.query=null,M.path.pop(),C--,W(t,e)?bn(z(F,C)):0):W(t,e)?lu(z(F,C)):0)},ig=e=>{let t=C;return ct(M.scheme)&&(e===47||e===92)?W(t,e)?qa(z(F,C)):0:e===47?W(t,e)?di(z(F,C)):0:(M.username=qe.username,M.password=qe.password,M.host=qe.host,M.port=qe.port,C--,W(t,e)?bn(z(F,C)):0)},f0=e=>{let t=C;return e===47&&z(F,C+1)===47?C++:C--,W(t,e)?qa(z(F,C)):0},qa=e=>{let t=C;return e!==47&&e!==92?(C--,W(t,e)?di(z(F,C)):0):W(t,e)?qa(z(F,C)):0},di=e=>{let t=C;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!ct(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&&ct(M.scheme))break;n+=yn(r)}return be+=F.slice(C,n),C=n-1,W(t,e)?di(z(F,C)):0}if(e===64){Ta&&(be=`%40${be}`),Ta=!0;for(let n=0;n<be.length;n++){let r=be.codePointAt(n);if(r===58&&!Na){Na=!0;continue}let i=sg(r,Da);Na?M.password+=i:M.username+=i,r!=null&&r>65535&&n++}return be="",W(t,e)?di(z(F,C)):0}else return e==null||e===35||e===47||e===63||e===92&&ct(M.scheme)?Ta&&be===""?1:(C-=be.length+1,be="",W(t,e)?Fa(z(F,C)):0):(be+=fg(e),W(t,e)?di(z(F,C)):0)},Fa=e=>{let t=C;if(ut&&M.scheme==="file")return C--,W(t,e)?mu(z(F,C)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!ct(M.scheme))){let n=C+yn(e);for(e===91?Dr=!0:e===93&&(Dr=!1);n<F.length;){let r=z(F,n);if(r==null||!Dr&&r===58||r===35||r===47||r===63||r===92&&ct(M.scheme))break;r===91?Dr=!0:r===93&&(Dr=!1),n+=yn(r)}return be+=F.slice(C,n),C=n-1,W(t,e)?Fa(z(F,C)):0}else if(e===58&&!Dr){if(be===""||ut===4)return 1;let n=ou(be,!ct(M.scheme));return n===null?1:(M.host=au(n),be="",W(t,e)?du(z(F,C)):0)}else if(e==null||e===35||e===47||e===63||e===92&&ct(M.scheme)){if(C--,ct(M.scheme)&&be==="")return 1;if(ut&&be===""&&(mg(M)||M.port!==null))return 1;let n=ou(be,!ct(M.scheme));return n===null?1:(M.host=au(n),be="",ut?0:W(t,e)?Fr(z(F,C)):0)}else return be+=fg(e),W(t,e)?Fa(z(F,C)):0},du=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 be+=F.slice(C,n),C=n-1,W(t,e)?du(z(F,C)):0}else if(ut||e==null||e===35||e===47||e===63||e===92&&ct(M.scheme)){if(be!==""){let n=parseInt(be,10);if(n>65535)return 1;if(M.port=n===dg(M.scheme)?null:n,be="",ut)return 0}return ut?1:(C--,W(t,e)?Fr(z(F,C)):0)}else return 1};function hg(e,t){let n=e.length-t;if(n<2)return!1;if(ug(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 pu=e=>{let t=C;return M.scheme="file",M.host="",e===47||e===92?W(t,e)?g0(z(F,C)):0:qe?.scheme==="file"?(M.host=qe.host,M.path=qe.path.slice(),M.opaquePath=qe.opaquePath,M.query=qe.query,e===63?(M.query="",W(t,e)?nr(z(F,C)):0):e===35?(M.fragment="",W(t,e)?Pn(z(F,C)):0):e!=null?(M.query=null,hg(F,C)?M.path=[]:pg(M),C--,W(t,e)?bn(z(F,C)):0):W(t,e)?pu(z(F,C)):0):(C--,W(t,e)?bn(z(F,C)):0)},g0=e=>{let t=C;return e===47||e===92?W(t,e)?mu(z(F,C)):0:(qe!==null&&qe.scheme==="file"&&(!hg(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})(qe.path[0])&&M.path.push(qe.path[0]),M.host=qe.host),C--,W(t,e)?bn(z(F,C)):0)},mu=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 be+=F.slice(C,n),C=n-1,W(t,e)?mu(z(F,C)):0}else if(e==null||e===47||e===92||e===63||e===35){if(C--,!ut&&lg(be))return W(t,e)?bn(z(F,C)):0;if(be==="")return M.host="",ut?0:W(t,e)?Fr(z(F,C)):0;{let n=ou(be,!ct(M.scheme));return n===null?1:(n==="localhost"&&(n=""),M.host=au(n),be="",ut?0:W(t,e)?Fr(z(F,C)):0)}}return 1},Fr=e=>{let t=C;return ct(M.scheme)?(e!==92&&e!==47&&C--,W(t,e)?bn(z(F,C)):0):!ut&&e===63?(M.query="",W(t,e)?nr(z(F,C)):0):!ut&&e===35?(M.fragment="",W(t,e)?Pn(z(F,C)):0):e!=null?(e!==47&&C--,W(t,e)?bn(z(F,C)):0):(ut&&M.host===null&&M.path.push(""),W(t,e)?Fr(z(F,C)):0)},bn=e=>{let t=C;if(e!=null&&e!==47&&(!ct(M.scheme)||e!==92)&&(ut||e!==63&&e!==35)){let n=C+yn(e);for(;n<F.length;){let r=z(F,n);if(r==null||r===47||ct(M.scheme)&&r===92||!ut&&(r===63||r===35))break;n+=yn(r)}be+=Cn(F.slice(C,n),nu),C=n,e=z(F,n)}if(e==null||e===47||ct(M.scheme)&&e===92||!ut&&(e===63||e===35)){let n=ct(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}})(be)?(pg(M),e!==47&&!n&&M.path.push("")):ng(be)&&e!==47&&!n?M.path.push(""):ng(be)||(M.scheme==="file"&&M.path.length===0&&lg(be)&&(be=`${be[0]}:`),M.path.push(be)),be="",e===63?(M.query="",W(t,e)?nr(z(F,C)):0):e===35?(M.fragment="",W(t,e)?Pn(z(F,C)):0):W(t,e)?bn(z(F,C)):0}else return be+=sg(e,nu),W(t,e)?bn(z(F,C)):0},Ag=e=>{let t=C;if(e===63)return M.query="",W(t,e)?nr(z(F,C)):0;if(e===35)return M.fragment="",W(t,e)?Pn(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]+=Cn(r.slice(0,-1),so)+"%20":M.path[0]+=Cn(r,so),C=n,(e=z(F,n))===63)return M.query="",W(t,e)?nr(z(F,C)):0;if(e===35)return M.fragment="",W(t,e)?Pn(z(F,C)):0}return W(t,e)?Ag(z(F,C)):0},nr=e=>{let t=C,n=C;if(e!=null){if(ut)n=F.length;else{let i=F.indexOf("#",C);n=i===-1?F.length:i}let r=ct(M.scheme)?zx:cu;M.query+=Cn(F.slice(C,n),r)}return C=n,z(F,n)===35&&!ut?(M.fragment="",W(t,e)?Pn(z(F,C)):0):W(t,e)?nr(z(F,C)):0},Pn=e=>{let t=C;return e!=null&&(M.fragment+=Cn(F.slice(C),Bx),C=F.length),W(t,e)?Pn(z(F,C)):0};function su(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function yg(e){switch(e.scheme){case"blob":{let t=rn(su(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":yg(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"),ln=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=rn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=rn(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=rn(n,null,null,0),r==null)?!1:rn(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+=su(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[Be].url)}set href(t){let n=rn(t=ze(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[Be].url=n,this[Be].query&&Yc(this[Be].query,n.query)}get origin(){return yg(this[Be].url)}get protocol(){return`${this[Be].url.scheme}:`}set protocol(t){rn(`${t=ze(t)}:`,this[Be].url,null,2)}get username(){return this[Be].url.username}set username(t){t=ze(t),Wc(this[Be].url)||(function(r,i){r.username=Cn(i,Da)})(this[Be].url,t)}get password(){return this[Be].url.password}set password(t){t=ze(t),Wc(this[Be].url)||(function(r,i){r.password=Cn(i,Da)})(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||rn(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||rn(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];Wc(n)||(t?rn(t,n,null,5):n.port=null)}get pathname(){return su(this[Be].url)}set pathname(t){t=ze(t);let{url:n}=this[Be];n.opaquePath||(n.path=[],rn(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&&Yc(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",rn(i,n,null,7),r&&Yc(r,n.query)}}get searchParams(){let t=this[Be],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new Ma;return o[tt].url=i,o[tt].serialized=a==null,a&&(o[tt].list=uu(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="",rn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(ln.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var tt=Symbol("URLSearchParamsImpl"),h0=Symbol.dispose||Symbol.for("dispose");function Yc(e,t){t?e[tt].list=uu(t):e[tt].list.length=0,e[tt].serialized=t==null}function ka(e){if(e.url){let t=ru(e.list);(function(r,i){r[Be].url.query=i})(e.url,t||null),e.serialized=!0}}var A0=typeof Iterator<"u"?Iterator:Object,ao=class extends A0{constructor(t,n){super(),this[tt]={ptr:t,map:n,index:0}}next(){let t=this[tt];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}[h0](){}},Ma=class{constructor(t){let n=this[tt]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(Wf(t[i]));else if((r=og(t))!=null){let i;for(;!(i=Xc(r.next())).done;)n.list.push(Wf(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=Ux(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=uu(i)}}get size(){return this[tt].list.length}append(t,n){t=ze(t),n=ze(n),this[tt].list.push([t,n]);let r=this[tt];r.url&&r.serialized?(function(a,o){let s=a[Be].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,ru([[t,n]])):ka(r)}delete(t,n){t=ze(t),n=n!=null?ze(n):void 0;let{list:r}=this[tt],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;ka(this[tt])}get(t){t=ze(t);let{list:n}=this[tt];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[tt];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[tt];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[tt],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&&ka(this[tt])}sort(){this[tt].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),ka(this[tt])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[tt];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new ao(this[tt],t=>t)}keys(){return new ao(this[tt],t=>t[0])}values(){return new ao(this[tt],t=>t[1])}toString(){return ru(this[tt].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Ma.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var rr="https://api.tinker.cash";function bg(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=qr.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 Sg=Symbol("IndianaNoContent");function ir(e,t,n=ln){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?Le.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??rr);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??bg(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 pe=d,Se=new AbortController;q||w.add(Se);let Oe=()=>!q&&pe!==d?new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new y("TIMEOUT","Indiana request timed out"),xe,De=new Promise((We,Rt)=>{xe=()=>Rt(Oe()),Se.signal.addEventListener("abort",xe,{once:!0})}),Ee=setTimeout(()=>Se.abort(),c),Vt=async()=>{let We=await s(`${o.href.replace(/\/$/,"")}/api/v1/${h}`,{method:v,headers:{"Content-Type":"application/json",...q?{}:{Authorization:`Bearer ${j??u}`},[Za]:Wa.current,[Tu]:Zf.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(P):void 0,signal:Se.signal,credentials:"omit",cache:"no-store",redirect:"error",...E.keepalive?{keepalive:!0}:{}});if(Se.signal.aborted)throw Oe();let Rt;try{Rt=We.status===204?Sg:await We.json()}catch{throw Se.signal.aborted?Oe():new y(We.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",We.status,We.headers.get("X-Request-Id")??void 0)}if(Se.signal.aborted)throw Oe();if(!q&&pe!==d)throw new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!We.ok){let ot=Ja.safeParse(Rt),Ut=ot.success&&(!pr.safeParse(ot.data.error.code).success||ku(ot.data.error.code,We.status)),sr=Ut?ot.data.error.code:"HTTP_ERROR",cr=ho(sr,We.status,{retryAfter:We.headers.get("Retry-After"),recovery:Ut?ot.data.error.recovery:void 0,reason:Ut?ot.data.error.reason:void 0});throw new y(sr,Ut?ot.data.error.message:"Indiana request failed",We.status,We.headers.get("X-Request-Id")??(ot.success?ot.data.requestId:void 0),{...cr,...ot.success&&ot.data.error.retryable===!1?{retryable:!1}:{},...cr.retryAfterSeconds===void 0&&ot.success&&ot.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:ot.data.error.retryAfterSeconds}:{}})}if(We.headers.get(Za)!==Wa.current)throw new y("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&Rt!==Sg){let ot=Rt&&typeof Rt=="object"&&"scope"in Rt?Rt:Rt&&typeof Rt=="object"&&"configuration"in Rt?Rt.configuration:null;if(!ot||typeof ot!="object"||!("scope"in ot))throw new y("INVALID_RESPONSE","Response is missing its App/environment scope");let Ut=Le.safeParse(ot.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 Mr=We.headers.get("X-Indiana-Telemetry-Subject");if(Mr){if(!/^[a-f0-9]{64}$/.test(Mr))throw new y("INVALID_RESPONSE","Invalid telemetry identity");m!==Mr&&(m=Mr,t?.(m))}return Rt};try{return await Promise.race([Vt(),De])}catch(We){throw!q&&pe!==d?new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):We instanceof y?We:new y(Se.signal.aborted?"TIMEOUT":"NETWORK_ERROR",Se.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(Ee),Se.signal.removeEventListener("abort",xe),w.delete(Se)}}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=Le.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(),pe=Se=>{if(j!==d)throw new y("IDENTITY_CHANGED","Customer identity changed before dispatch");return S(h,P,v,E,Se)};return typeof q=="string"?pe(q):q.then(pe)}catch(q){return Promise.reject(q)}}}}function xg(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(!Dt.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()}}}}}var vg=require("zod");function Ig(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof vg.ZodError?new y(n,r):i}}async function de(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=Ig(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):Ig(t.response,s,"INVALID_RESPONSE",a.response)}function Ve(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new y("INVALID_REQUEST","Customer requests use the verified session identity")}function wg(e){return{async checkEntitlement(t){Ve(t);let n=O.checkEntitlement;return de(e,n,t)},async readHoldings(t={}){let n=O.readHoldings;return de(e,{...n,request:n.request.omit({customerId:!0})},t)}}}function Og(e){return{async readLedger(t){let n=O.readLedger;return de(e,n,{query:t})},async readCreditStatement(t){Ve(t);let n=O.readCreditStatement;return de(e,n,t)},async quoteBalance(t){Ve(t);let n=O.quoteBalance;return de(e,n,{command:t})}}}function Cg(e){return{async setupPayment(t){Ve(t);let n=O.setupPayment;return de(e,n,t)},async readPaymentSetup(t){Ve(t);let n=O.readPaymentSetup;return de(e,n,t)},async readBillingInvoice(t){Ve(t);let n=O.readBillingInvoice;return de(e,n,t)},async readBillingControls(t={}){Ve(t);let n=O.readBillingControls;return de(e,n,t)},async prepareBillingAuthorization(t){Ve(t);let n=O.prepareBillingAuthorization;return de(e,n,t)},async confirmBillingAuthorization(t){Ve(t);let n=O.confirmBillingAuthorization;return de(e,n,t)},async setBillingCoupons(t){Ve(t);let n=O.setBillingCoupons;return de(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Ve(t);let n=O.revokeBillingAuthorization;return de(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Ve(t);let n=O.listBillingInvoices;return de(e,n,t)},async confirmBillingAdjustment(t){Ve(t);let n=O.confirmBillingAdjustment;return de(e,n,t)}}}function Pg(e){return{async previewUpdate(t){Ve(t);let n=O.previewUpdate;return de(e,n,t)},async update(t){Ve(t);let n=O.update;return de(e,n,t)},async readSubscriptionUpdate(t){Ve(t);let n=O.readSubscriptionUpdate;return de(e,n,t)},async restoreNativePurchase(t){Ve(t);let n=O.restoreNativePurchase;return de(e,n,t)},async previewAttach(t){Ve(t);let n=O.previewAttach;return de(e,n,t)},async attach(t){Ve(t);let n=O.attach;return de(e,n,t)},async readSubscriptionOperation(t){Ve(t);let n=O.readSubscriptionOperation;return de(e,n,t)}}}function _g(e){return{async redeemReward(t){return Ve(t),(await de(e,O.redeemReward,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(t){return Ve(t),(await de(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Ve(t),(await de(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 de(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 de(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 de(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function Eg(e){return{...wg(e),...Og(e),...Cg(e),...Pg(e),..._g(e)}}function Rg(e){return{async resolveContent(t){Ve(t);let n=O.resolveContent;return de(e,n,t)},async resolvePaywall(t){Ve(t);let n=O.resolvePaywall;return de(e,n,t)},async resolveOffering(t){Ve(t);let n=O.resolveOffering;return de(e,n,t)}}}var kg=e=>new TextEncoder().encode(JSON.stringify(e)).length,jg=16384;function Tg(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&&!Qp(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(kg({events:[S]})>jg)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&&kg({events:[...P,j]})>jg)break;P.push(j)}let v=O.trackEvents,E=await de(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 Va(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:yt.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(En(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=oa.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(pe=>!Object.hasOwn(q.features,pe))||Object.keys(q.features).some(pe=>!o.has(pe)))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=yt.parse({...m.attributes,...q.merchandiseContext}),a=!0}s=structuredClone(q),m.features={...v.features,...Object.fromEntries(Object.entries(s.features).map(([pe,Se])=>[pe,{defaultValue:Se.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?Hi.parse(v):null,j=E??sn.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:pe,expiresAt:Se,...Oe}=t,{evaluatedAt:xe,expiresAt:De,...Ee}=j;if(bt(Oe)!==bt(Ee))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(pe=>Object.hasOwn(j.features,pe)))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=Br(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=yt.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 Ng(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 y0(e){let t=Ng(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function Dg(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,xe=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await de(e,Oe,{});if(d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");if(r&&(xe.scope.projectId!==r.projectId||xe.scope.environment!==r.environment))throw new y("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(xe.payload.analyticsConfig),xe},I=await w(),p=!0,g,f=Oe=>{try{u.onError?.(Oe)}catch{}},S=(Oe,xe,De)=>{try{let Ee=Ng(De);n.track(Oe,xe,Ee?{merchandise:Ee}:{})}catch(Ee){f(Ee)}},h=Va({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 xe=O.evaluateFeatures,De=await de(e,xe,{...Oe,attributes:y0(Oe.attributes)});if(De.scope.projectId!==I.scope.projectId||De.scope.environment!==I.scope.environment)throw new y("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:De.generation,evaluatedAt:De.evaluatedAt,expiresAt:De.expiresAt,features:De.features,...De.merchandiseContext?{merchandiseContext:De.merchandiseContext}:{}}},onExperimentViewed:(Oe,xe,De)=>S("Experiment Viewed",{experimentId:Oe.key,variationId:xe.key},De),onFeatureUsage:(Oe,xe,De)=>S("Feature Evaluated",{feature:Oe,value:xe.value,source:xe.source,ruleId:xe.ruleId,...xe.experimentResult?{variationId:xe.experimentResult.key}:{}},De)}),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),pe=i?.subscribe(()=>{!m&&i.fresh&&E().catch(f)});function Se(){m||(m=!0,clearTimeout(g),typeof window<"u"&&window.removeEventListener("focus",j),q(),pe?.(),h.reset(),o.delete(Se))}o.add(Se);try{await h.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await h.refreshRemote()}catch(Oe){throw Se(),Oe}return v(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(h,{refresh:E,destroy:Se})}return{features:c,reset(u){a++,u();for(let d of o)d()}}}var Fg=require("zod");function Mg(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=Fg.z.object({funnelId:_a.shape.id,funnelVersionId:_a.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 de(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return de(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return de(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return de(e,s,a(o))}}}function qg(e){let t=ir(e),n=t.request,r=Qf(e.push,t,e.scope??e.configuration?.scope),i=xg(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),a=Tg(n,i.isIdentified),o=Dg(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...Jf(n,r),...Eg(n),...Rg(n),forFunnel(s){return Mg(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 pi(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)=>pi(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)&&pi(a,Reflect.get(t,i)))}async function Ua(e,t){let n=Ff.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 mi=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function La(e){let t=Dt.test(e.apiKey);if(typeof window<"u"&&!t)throw new y("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!mi.test(e.apiKey))throw new y("INVALID_TOKEN","A customer credential or server API key is required");let n=ir({...e,timeoutMs:e.timeoutMs??35e3});return e.session||n.identify(e.apiKey),{async start(r){let i=Nn.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=ro.safeParse(await Ua(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")||!pi(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 fu(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 Vg(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await fu(e,t,n))}function Ba(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&kc(n)===t.sha256}async function za(e,t){let n=kr.parse(t),{artifact:r,environmentId:i}=n.content,a=new ln(e.baseUrl??rr).origin,o=new ln(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 fu(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(!Ba(d,r))throw new y("INVALID_RESPONSE","Public Paywall digest or size changed");return Bm(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)))}finally{clearTimeout(c)}}var Ug=(e,t)=>new y(e,t);async function gu(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=b0(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 b0(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=$c({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:sn.parse(o)}),c=S0(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 S0(e,t,n){return Gf(e,t,n,Ug)}var Sn=require("zod");var Lg=Nn.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}),Bg=Sn.z.strictObject({schemaVersion:Sn.z.literal(1),scope:Le,runId:Sn.z.uuid(),funnelId:Sn.z.uuid(),versionId:Sn.z.uuid(),command:Lg.optional(),closeCommand:Lg.refine(e=>e.operation==="close").optional(),purchase:Sn.z.strictObject({receiptId:Sn.z.uuid(),operationId:Sn.z.uuid(),generation:Sn.z.number().int().nonnegative()}).optional(),closed:Sn.z.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"),Ht=()=>new y("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),$a=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function zg(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:Bg.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 Ht();let m=c(d.entry,d.revision);if($a(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 Ht();t=w;return}}throw Ht()}return{bind(c){let u=JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]);if(n!==null&&n!==u)throw Ht();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=Bg.parse(c),d=u.command;return!d||n!==null&&r(u)!==n?Promise.reject(Ht()):(n??(n=r(u)),o(()=>s((m,w)=>{if(m&&!$a(r(m),r(u)))throw Ht();if(!m){if(w!==t&&d.operation!=="close")throw Ht();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&&!$a(m.closeCommand,d))throw Ht();return{...m,closeCommand:d,closed:!0}}if(!$a(m.command,d))throw Ht();return m})))},observePurchase(c,u,d){return o(()=>s((m,w)=>{if(!m&&w!==t||m&&r(m)!==r({...c,schemaVersion:1}))throw Ht();if(m?.purchase&&m.purchase.generation>u.generation)return m;if(m?.purchase&&m.purchase.generation===u.generation&&m.purchase.operationId!==u.operationId)throw Ht();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 $g(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??rr).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 Gg(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||!pi(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(!Dt.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 or(e){let{customerToken:t,...n}=e;return n}var x0=e=>!(e instanceof y)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function Kg({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=Nn.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:or(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&&!x0(E)&&(t&&await t.settle(S.requestId),h===n.generation&&i===S&&(i=null,c=!1,d=null)),E}}function I(f){let S=Nn.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(or(a))!==JSON.stringify(or(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(or(i))!==JSON.stringify(or(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,pe=j?.operationId??E?.quote?.operationId??q?.operationId,Se=E?.receiptId??q?.receiptId,Oe=v?.selectionGeneration??u?.generation??0;if(t&&pe&&Se&&f.operation!=="review"&&(!n.view||S.run.revision>=n.view.revision)&&(P===void 0||P>=n.readSequence)&&(!u||Oe>=u.generation)){let xe={receiptId:Se,operationId:pe,generation:Oe},De=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},xe,De).then(()=>{n.assertCurrent(h),De?u?.operationId===xe.operationId&&(u=void 0):u=xe})}},stop(){o=!0},submit:I,executePending:w,settle:g,reset(){i=null,a=null,s.close=null,c=!1,s.command=null}}}function fi(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"||!mi.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=ir({...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(Mf,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=Gg(e.funnelId),r=e.session?.subscribeIdentity(()=>{n.reset(),t.reset()}),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?$g(e):void 0),o=a&&zg(a),s=Kg({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=ro.parse(await Ua(e,await t.request("funnels",Nn.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 pe=s.observePurchase(f,j,P,h);if(pe&&await pe,!j.run.stopped&&["running","waiting"].includes(j.run.status)&&f.operation==="get"&&f.settlementRequestId)return j;let Se=S?.(j),Oe=typeof Se=="boolean"?Se:Se?await Se:!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 gu(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 pe=!0;gu(e.configuration,E).then(({prediction:Se})=>{pe&&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=Se)}).catch(()=>{});try{S=await u({operation:"commit_segment",requestId:Df(E.id,E.visit,`segment:${E.revision}`),nodeId:E.nodeId,visit:E.visit,revision:E.revision,...q})}finally{pe=!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(or(f)):null},get pendingCommands(){return[s.pending,s.closing].filter(f=>f!==null).map(f=>structuredClone(or(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 za(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=Hf.parse(await t.request("funnels",Kf.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 Hg(e){if(!Dt.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=La({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=fi({...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 Qg(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 Jg(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new y("INVALID_RESPONSE",n)}function Zg(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 Wg(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 Yg(e,t){if(!Dt.test(t.customerToken))throw new y("INVALID_TOKEN","A verified Customer credential is required");let n=ir(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 de(n.request,p,{...r,selector:i?{type:"version",versionId:i.id}:r.selector}),f={paywall:await za(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&&(!Qg(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 de(n.request,g,{operationId:o.operationId,...p==="read"?{}:{intent:p}});return Jg(f.operation,{operationId:o.operationId,currency:r.commerce.currency},"The purchase operation changed"),s=Wg(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=Gp(g.product,p.selection,i.capabilities);if(!f)throw new y("PRODUCT_UNAVAILABLE","Choose an available Product");let S=Tm(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 de(n.request,E,h);return Zg(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 Xg(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 I0=O.trackUsage.request.shape.command,v0=O.trackUsage.response;function w0(e){let t=Le.parse(e.scope),n=qg({...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:Xg(e,n.session),funnel(){return Hg({...r,customerToken:a()})},resumeFunnel(o){return a(),fi({...r,runToken:o})},paywall(o){return Yg(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=I0.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=v0.parse(u);if(d.scope.projectId!==t.projectId||d.scope.environment!==t.environment)throw new y("INVALID_RESPONSE","Usage response scope differs");return d}}}var rh=require("zod");var gi=require("zod");var O0=gi.z.record(gi.z.string().regex(/^[a-f0-9]{64}$/),gi.z.strictObject({at:gi.z.number(),text:gi.z.string()})),eh=2*1048576,C0=100;function P0(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function th(e,t){let n=t===void 0?P0():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),C0)})])}catch{return null}finally{clearTimeout(s)}}async function a(){try{let o=await i(`${e}:artifacts`);if(o&&o.length<=eh)return O0.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>eh||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),ar=()=>performance.now(),nh=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function ih(e){let t=_c.parse(e.scope),n=new ln(e.origin??rr);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(Y=>{let G=new ln(Y);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}:${bt(t)}`,s=th(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,pe=0,Se=!1;function Oe(){for(let Y of v)try{Y()}catch{}}function xe(Y){try{e.onError?.(Y)}catch{}}let De=()=>!w&&!m&&!!c&&ar()<u&&Date.now()<d;function Ee(){if(!De())throw we("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Vt(Y,G){let ae=new TextEncoder().encode(G).byteLength;if(!j.has(Y)){for(;j.size&&(j.size>=128||pe+ae>Gt.maxCacheBytes);){let se=j.entries().next().value;pe-=new TextEncoder().encode(se[1]).byteLength,j.delete(se[0])}j.set(Y,G),pe+=ae}}function We(Y,G,ae){return Vg(Y,G,{signal:ae,error:se=>we("INVALID_RESPONSE",se==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function Rt(Y){let G=new ln(Y,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 co(Y,G,ae=!1){let se=await i(Rt(Y),{method:"GET",credentials:"omit",redirect:"error",cache:ae?"default":"no-cache",signal:G,headers:{}});if(se.status===429){let je=se.headers.get("retry-after")??"";P=/^\d+$/.test(je)?Number(je)*1e3:Math.max(0,Date.parse(je)-Date.now())||15e3}if(!se.ok&&se.status!==304)throw we(`CONFIGURATION_HTTP_${se.status}`,"Configuration synchronization failed");return se}function Mr(Y,G,ae){let se=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),je=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),wt=Date.parse(Y.headers.get("date")??""),$e=Y.headers.get("age"),Qt=$e!==null&&/^\d+(\.\d+)?$/.test($e)?Number($e)*1e3:NaN;if(![se,je,wt,Qt].every(Number.isFinite)||je<=se||je-se>Gt.maxControlAgeMs||se>wt+1e3)throw we("INVALID_RESPONSE","Configuration freshness evidence is invalid");let Ot=Math.min(je-se,ae.maxControlAgeSeconds*1e3,Gt.maxControlAgeMs)-Math.max(Qt,wt-se,0)-(ar()-G);if(Ot<=0)throw we("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return ar()+Ot}function ot(){if(clearTimeout(S),clearTimeout(h),w||!v.size)return;De()&&(h=setTimeout(()=>{De()?ot():Oe()},Math.max(1,u-ar())),nh(h));let Y=p?Math.min(15e3,1e3*2**Math.min(p-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);S=setTimeout(()=>{Ut().catch(xe)},Math.max(P,Y*(.8+Math.random()*.2))),nh(S)}async function Ut(){if(w)throw we("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(g)return g;let Y=I,G=new AbortController;f=G;let ae=(async()=>{if(!Se){Se=!0;try{let lo=await s.readManifest();if(lo&&!c){let _n=Rc.parse(JSON.parse(lo));bt(_n.scope)===bt(t)&&(c=_n)}}catch{}}G.signal.throwIfAborted();let $e=c,Qt=ar(),Nt=await co(a,G.signal);Nt.status===304&&(!$e||!Nt.headers.has("x-indiana-config-validated-at")||!Nt.headers.has("x-indiana-config-valid-until")||!Nt.headers.has("age"))&&(Nt=await co(a,G.signal));let Ot=Nt.status===304?$e:Rc.parse(JSON.parse(await We(Nt,Gt.maxManifestBytes,G.signal))),{generation:Fn,...Mn}=Ot,ur=Nt.headers.get("etag");if(bt(Ot.scope)!==bt(t)||qm(Mn)!==Fn||ur!==`"${Fn}"`&&ur!==`W/"${Fn}"`)throw we("INVALID_RESPONSE","Configuration scope or content identity changed");if($e&&(Ot.revision<$e.revision||Ot.revision===$e.revision&&Ot.generation!==$e.generation))throw we("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[lo,_n]of Object.entries($e?.funnels??{})){let lr=Ot.funnels[lo];if(lr&&(lr.controlRevision<_n.controlRevision||lr.evaluationRevision<_n.evaluationRevision||lr.controlRevision===_n.controlRevision&&lr.state!==_n.state||lr.evaluationRevision===_n.evaluationRevision&&lr.evaluationMode!==_n.evaluationMode))throw we("INVALID_RESPONSE","Funnel control revision changed identity")}let Su=Mr(Nt,Qt,Ot.policy);if(G.signal.throwIfAborted(),Y!==I)throw we("CONFIGURATION_DISPOSED","Configuration scope changed");return c=Ot,u=Su,d=Date.now()+Math.max(0,Su-ar()),m=!1,p=0,P=0,s.writeManifest(bt(Ot)),Oe(),structuredClone(Ot)})(),se=setTimeout(()=>G.abort(we("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Gt.initializationMs),je=new Promise(($e,Qt)=>G.signal.addEventListener("abort",()=>Qt(G.signal.reason),{once:!0})),wt=Promise.race([ae,je]).catch($e=>{throw p++,($e instanceof rh.z.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(se),g===wt&&(g=void 0),ot()});return g=wt,wt}async function sr(Y){let G=Y.sha256,ae=Fn=>Ba(Fn,Y);Rt(Y.url);let se=j.get(G);if(se&&ae(se))return j.delete(G),j.set(G,se),se;if(q.has(G))return q.get(G);let je=new AbortController;E.add(je);let wt=I,$e=(async()=>{try{let ur=await s.readArtifact(G);if(ur&&ae(ur))return Vt(G,ur),ur}catch{}je.signal.throwIfAborted();let Fn=await co(Y.url,je.signal,!0),Mn=await We(Fn,Y.byteLength,je.signal);if(!ae(Mn))throw we("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(w||wt!==I)throw we("CONFIGURATION_DISPOSED","Configuration scope changed");return Vt(G,Mn),s.writeArtifact(G,Mn),Mn})(),Qt=setTimeout(()=>je.abort(we("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Gt.initializationMs),Nt=new Promise((Fn,Mn)=>je.signal.addEventListener("abort",()=>Mn(je.signal.reason),{once:!0})),Ot=Promise.race([$e,Nt]).finally(()=>{clearTimeout(Qt),E.delete(je),q.delete(G)});return q.set(G,Ot),Ot}async function cr(){return De()||await Ut(),Ee(),c}async function hi(Y){let G,ae=new Promise((se,je)=>{G=setTimeout(()=>je(we("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Gt.initializationMs)});try{return await Promise.race([Y(),ae])}finally{clearTimeout(G)}}function Ai(Y,G){if(Ee(),c?.generation!==Y.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 hu(Y){let G=Y.gb.features;if(!G)throw we("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let ae=Y.artifacts[G];if(ae.formatVersion!==1)throw we("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let se=tc.parse(JSON.parse(await sr(ae)));if(bt(se.scope)!==bt({projectId:t.projectId,environment:t.environment})||se.generation!==ae.generation||se.remoteFeatures.some(je=>Object.hasOwn(se.features,je)))throw we("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Ai(Y),{...se,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-ar())).toISOString()}}async function Au(Y,G){let ae=await cr(),se=ae.funnels[Y];G&&(!se||se.evaluationMode==="local"&&!se.versions[G])&&(g&&await g,ae=await Ut()),Ai(ae,Y);let je=ae.funnels[Y];if(je.evaluationMode!=="local")throw we("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let wt=G??je.currentVersionId,$e=je.versions[wt];if(!$e)throw we("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(ae.artifacts[$e.artifact].formatVersion!==3)throw we("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[Qt,Nt]=await Promise.all([sr(ae.artifacts[$e.artifact]).then(Ot=>Um(JSON.parse(Ot))),je.evaluationMode==="local"?hu(ae):void 0]);if(Nt&&bt(Vm(Qt,Nt))!==bt($e.dependencies))throw we("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Ai(ae,Y),{document:Qt,growth:Nt,versionId:wt,control:structuredClone(je),manifest:structuredClone(ae)}}async function yu(Y,G){try{return await Au(Y,G)}catch(ae){if(!(ae instanceof y)||!(ae.code==="CONFIGURATION_CHANGED"||ae.code==="CONFIGURATION_HTTP_404"&&De()))throw ae;let se=c?.generation;if(g&&await g,await Ut(),ae.code!=="CONFIGURATION_CHANGED"&&c?.generation===se)throw ae;return Au(Y,G)}}function Ga(){m=!0,Oe(),Ut().catch(xe)}let uo=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ga()};function ah(Y){if(w)throw we("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Y),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ga),window.addEventListener("focus",uo),document.addEventListener("visibilitychange",uo)),ot()),()=>{v.delete(Y),v.size||(clearTimeout(S),clearTimeout(h),bu())}}function bu(){typeof window<"u"&&(window.removeEventListener("online",Ga),window.removeEventListener("focus",uo),document.removeEventListener("visibilitychange",uo))}return{scope:Object.freeze({...t}),refresh:Ut,subscribe:ah,assertFresh:Ee,assertFeatures(Y){Ee();let G=c.gb.features;if(!G)throw we("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[G].generation!==Y)throw we("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return De()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return De()?Math.max(0,u-ar()):0},async features(){return hi(async()=>hu(await cr()))},pageExperiments:()=>hi(async()=>{let Y=await cr(),G=Y.gb.pageExperiments;if(!G)throw we("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let ae=Y.artifacts[G];if(ae.formatVersion!==1)throw we("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let se=Bf.parse(JSON.parse(await sr(ae)));if(se.environmentId!==t.environmentId||se.generation!==ae.generation)throw we("INVALID_RESPONSE","Page experiment scope or generation changed");return Ai(Y),se}),funnel:(Y,G)=>hi(()=>yu(Y,G)),paywall:(Y,G)=>hi(async()=>{let ae=await cr(),se=ae.paywalls?.[Y];if(!se||!G&&se.state!=="published")throw we("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let je=G??se.currentVersionId,wt=se.versions[je],$e=wt&&ae.artifacts[wt.artifact];if(!$e||$e.kind!=="paywall"||$e.formatVersion!==1)throw we("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let Qt=Ca.parse(JSON.parse(await sr($e)));return Ai(ae),{document:Qt,versionId:je,version:wt.version,control:structuredClone(se),manifest:structuredClone(ae)}}),async localFunnel(Y,G){let ae=await hi(()=>yu(Y,G));if(!ae.growth)throw we("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:se,remoteFeatures:je,...wt}=ae.growth;return Uf({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:ae.versionId,evaluationMode:"local",evaluationRevision:ae.control.evaluationRevision,document:ae.document,payload:wt})},assertFunnel(Y,G,ae){Ee();let se=c.funnels[Y];if(!se||se.state!=="active")throw we("FUNNEL_STOPPED","Funnel is paused or unavailable");if(se.evaluationMode!=="local")throw we("EVALUATION_MODE","This Funnel now executes at Indiana");if(G!==void 0&&se.controlRevision!==G)throw we("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(ae!==void 0&&!se.versions[ae])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),bu(),Oe(),v.clear();for(let Y of E)Y.abort(we("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),pe=0}}}}async function oh(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&&bt(n)!==bt(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=mi.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=La({...e,scope:n,apiKey:e.credential}),o=s=>{let c=fi({...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}}}}