@tinkerlandai/longplay-sdk 0.10.69 → 0.10.71

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 (102) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +1 -1
  3. package/dist/check-response-3EFQG3PL.js +1 -0
  4. package/dist/{chunk-VMYLTNDS.js → chunk-24Z5QET3.js} +1 -1
  5. package/dist/{chunk-YDPF2ZZW.js → chunk-3KIATB75.js} +1 -1
  6. package/dist/{chunk-3NV6NBQB.js → chunk-44SX4C3G.js} +1 -1
  7. package/dist/{chunk-ZRU7WONE.js → chunk-4C4L3JER.js} +1 -1
  8. package/dist/{chunk-BGCCW5QX.js → chunk-4HMPCJOG.js} +2 -2
  9. package/dist/chunk-4XDMBMDA.js +1 -0
  10. package/dist/{chunk-DXNTXCSI.js → chunk-5M2IIZB6.js} +1 -1
  11. package/dist/{chunk-5MOJUGMA.js → chunk-5XMHY7QX.js} +1 -1
  12. package/dist/{chunk-G3YIPDT6.js → chunk-6A4NV4ET.js} +1 -1
  13. package/dist/{chunk-USH4WN6W.js → chunk-6ZUJCHBI.js} +1 -1
  14. package/dist/{chunk-44ZJPQM6.js → chunk-AFQHUBKJ.js} +1 -1
  15. package/dist/chunk-BZRDECZJ.js +10 -0
  16. package/dist/{chunk-DZYMD4MJ.js → chunk-DGMRFL7K.js} +1 -1
  17. package/dist/{chunk-KJTHMRSH.js → chunk-DJTMSBQN.js} +1 -1
  18. package/dist/{chunk-ULED3B5P.js → chunk-EPQUD3S5.js} +1 -1
  19. package/dist/{chunk-LBYMDTGD.js → chunk-EU4NTVRT.js} +1 -1
  20. package/dist/{chunk-T5SCW4IA.js → chunk-F46VXI3Q.js} +1 -1
  21. package/dist/{chunk-6C3ARFEL.js → chunk-G7JQNJM4.js} +1 -1
  22. package/dist/{chunk-GBUGEL6M.js → chunk-IR6ELT3D.js} +1 -1
  23. package/dist/{chunk-NEW77IDA.js → chunk-IUX4CJZM.js} +1 -1
  24. package/dist/{chunk-UFTKCFNI.js → chunk-IXYVLURA.js} +1 -1
  25. package/dist/{chunk-TFPLIX5E.js → chunk-IYVJOUO7.js} +1 -1
  26. package/dist/chunk-KNZ3WTQ5.js +1 -0
  27. package/dist/{chunk-QTXHF27F.js → chunk-LHUZRVAC.js} +1 -1
  28. package/dist/{chunk-6GY2YT3U.js → chunk-LQ2XY26R.js} +1 -1
  29. package/dist/{chunk-SGOVJD5P.js → chunk-MAKRT62V.js} +1 -1
  30. package/dist/{chunk-Q4GG33R5.js → chunk-MUW3SOTB.js} +1 -1
  31. package/dist/{chunk-NNJ7W4KY.js → chunk-NCMKY7D6.js} +1 -1
  32. package/dist/{chunk-WVTKVQLZ.js → chunk-ONYG4VQI.js} +1 -1
  33. package/dist/{chunk-ECUGL7AO.js → chunk-PYM47Z55.js} +1 -1
  34. package/dist/{chunk-2ZMIM4MO.js → chunk-Q5DB34R4.js} +1 -1
  35. package/dist/chunk-QIV2YOVB.js +1 -0
  36. package/dist/{chunk-CQ5EQNQA.js → chunk-RZ7WFYWY.js} +1 -1
  37. package/dist/{chunk-MT4OQFDI.js → chunk-TDMXEI2U.js} +1 -1
  38. package/dist/chunk-TFGIDUGW.js +1 -0
  39. package/dist/{chunk-LUVTP4VU.js → chunk-TLQUUC3G.js} +1 -1
  40. package/dist/{chunk-JW4MSBYN.js → chunk-TNWZWEEY.js} +1 -1
  41. package/dist/{chunk-5NCQOJR2.js → chunk-TYIAPLQP.js} +1 -1
  42. package/dist/{chunk-ST7XO45I.js → chunk-ULJJTIL5.js} +1 -1
  43. package/dist/chunk-UOJSZMKN.js +1 -0
  44. package/dist/chunk-UR2PWRLG.js +1 -0
  45. package/dist/{chunk-26QYDE7V.js → chunk-UWHTCMMF.js} +1 -1
  46. package/dist/{chunk-TYJWRPJY.js → chunk-VCUJMMEM.js} +1 -1
  47. package/dist/{chunk-EJSTRCBQ.js → chunk-YV4HA2DV.js} +1 -1
  48. package/dist/{chunk-2SSOV3OG.js → chunk-ZFNSXRQY.js} +1 -1
  49. package/dist/{chunk-EQ64JD4L.js → chunk-ZJXQTMBW.js} +1 -1
  50. package/dist/{chunk-RMR64P6V.js → chunk-ZVVDPXHC.js} +1 -1
  51. package/dist/content-F3LHKR2S.js +1 -0
  52. package/dist/funnel-host-purchase-WJ2GKXKT.js +1 -0
  53. package/dist/{funnel-host-recovery-paywall-KHBGMNS5.js → funnel-host-recovery-paywall-OANZILW3.js} +1 -1
  54. package/dist/{funnel-local-client-Cb9jJGpo.d.ts → funnel-local-client-2Yx0Q_lF.d.ts} +27 -0
  55. package/dist/{funnel-paywall-copies-A76T5V7B.js → funnel-paywall-copies-ZI6BLXH7.js} +1 -1
  56. package/dist/funnel-paywall-prerender-36ER2LYV.js +1 -0
  57. package/dist/{funnel-process-client-DE650LzB.d.ts → funnel-process-client-BTusJtqx.d.ts} +10 -1
  58. package/dist/funnel-route-prediction-IO6TEHFN.js +1 -0
  59. package/dist/funnel-route-source-VQQIKYXL.js +1 -0
  60. package/dist/funnel-runtime-host-LXIT2QY7.js +1 -0
  61. package/dist/index.d.ts +22 -6
  62. package/dist/index.js +1 -1
  63. package/dist/merchant-bridge-contracts-CJY7TX6J.js +1 -0
  64. package/dist/native-shell.js +1 -1
  65. package/dist/openrouter.js +1 -1
  66. package/dist/operation-contracts-FAW24KGA.js +1 -0
  67. package/dist/page.js +1 -1
  68. package/dist/paywall-TVYLGNDU.js +1 -0
  69. package/dist/paywall-content-NLEGSOUT.js +1 -0
  70. package/dist/paywall-session-ADXZWQPU.js +1 -0
  71. package/dist/popup.d.ts +56 -3
  72. package/dist/popup.js +1 -1
  73. package/dist/{presentation-loading-B8W6a9WB.d.ts → presentation-loading-CU4c-koG.d.ts} +3 -1
  74. package/dist/react-native.d.ts +4 -4
  75. package/dist/react-native.js +1 -1
  76. package/dist/screen-renderer-EWRXGDWQ.js +1 -0
  77. package/dist/server.d.ts +20 -2
  78. package/dist/server.js +1 -1
  79. package/dist/visual.js +1 -1
  80. package/package.json +1 -1
  81. package/dist/check-response-754GDUOJ.js +0 -1
  82. package/dist/chunk-2BSDXKQS.js +0 -1
  83. package/dist/chunk-57ZXT7AS.js +0 -1
  84. package/dist/chunk-5U7LC2NL.js +0 -1
  85. package/dist/chunk-CWBBW6QS.js +0 -10
  86. package/dist/chunk-F5ABUGHD.js +0 -1
  87. package/dist/chunk-JAH62B6J.js +0 -1
  88. package/dist/chunk-UIR5CBCC.js +0 -1
  89. package/dist/content-66BI72XB.js +0 -1
  90. package/dist/funnel-host-purchase-YPAWZLXP.js +0 -1
  91. package/dist/funnel-paywall-prerender-PNJXR4VC.js +0 -1
  92. package/dist/funnel-route-prediction-KFUCAJLL.js +0 -1
  93. package/dist/funnel-route-source-WEYKNM2C.js +0 -1
  94. package/dist/funnel-runtime-host-RWU52BJ7.js +0 -1
  95. package/dist/merchant-bridge-contracts-RWNJHBTR.js +0 -1
  96. package/dist/operation-contracts-NNWS467N.js +0 -1
  97. package/dist/paywall-BSY67NQL.js +0 -1
  98. package/dist/paywall-content-RAB5S6KB.js +0 -1
  99. package/dist/paywall-session-CRIGHMOQ.js +0 -1
  100. package/dist/screen-renderer-H3FBGJZB.js +0 -1
  101. /package/dist/{chunk-BGCCW5QX.js.LEGAL.txt → chunk-4HMPCJOG.js.LEGAL.txt} +0 -0
  102. /package/dist/{chunk-S7NHVERO.js → chunk-CTCK5BUY.js} +0 -0
@@ -1 +1 @@
1
- import{b as He}from"./chunk-NEW77IDA.js";import{a as $}from"./chunk-YDPF2ZZW.js";import{D as K,F as Qe,c as Te,e as z,j as xe,u as Le,v as Me,x as Ge,z as ze}from"./chunk-UIR5CBCC.js";import{a as Ne,b as je,c as Ue}from"./chunk-T5SCW4IA.js";import{a as se}from"./chunk-LBYMDTGD.js";import{i as ue}from"./chunk-CQ5EQNQA.js";import{K as G}from"./chunk-3NV6NBQB.js";import{A as ae,B as ie,C as J,E as Fe}from"./chunk-WVTKVQLZ.js";import{x as ye}from"./chunk-QTXHF27F.js";import{b as Ve}from"./chunk-MT4OQFDI.js";import{a as l}from"./chunk-ZRU7WONE.js";import{h as oe}from"./chunk-TFPLIX5E.js";import{a as De}from"./chunk-5MRSFLQA.js";import{b as r}from"./chunk-S7NHVERO.js";import{a as ge}from"./chunk-DSPLGTQI.js";var R=G.options,st=r.discriminatedUnion("operation",[R[1].omit({customerToken:!0}),R[2].omit({customerToken:!0}),R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0}),R[8].omit({customerToken:!0}),xe.omit({customerToken:!0})]),Pe=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),yt=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:R[0].shape.requestId,funnelId:R[0].shape.funnelId,locale:R[0].shape.locale,parameters:R[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0})]).optional()}).refine(i=>!i.command||i.requestId===i.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:st})]),ce=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:z.shape.run.shape.status}),H={scope:oe,customerId:r.uuid()},Be=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...H,outcome:r.literal("resolved"),target:ce,view:z.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((i,d)=>{i.outcome==="resolved"&&(i.access.type==="customer"!=(i.view!==null)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Ye=r.strictObject({...H,target:ce,view:z.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:z.shape.purchase.unwrap().nullable()}).superRefine((i,d)=>{let f=i.settlement;(f.acceptance==="accepted"!=(f.receiptPhase!==null)||f.acceptance==="accepted"&&f.basis!=="receipt"||f.acceptance==="unknown"&&(f.state!=="unknown"||f.basis!=="none")||f.acceptance!=="accepted"&&(f.operationId!==null||f.receiptId!==null)||f.acceptance==="not_accepted"&&(f.state!=="settled"||!["run_terminal","position_advanced"].includes(f.basis))||i.purchase&&(i.purchase.receiptId!==f.receiptId||i.purchase.operation&&i.purchase.operation.operationId!==f.operationId||i.purchase.quote&&i.purchase.quote.operationId!==f.operationId)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Je=r.strictObject({...H,target:ce,purchase:z.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((i,d)=>{(!i.purchase.operation||typeof i.purchase.canReselect!="boolean"||i.purchase.quote&&i.purchase.quote.operationId!==i.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Ke=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("none")}),r.strictObject({...H,outcome:r.literal("blocked")}),r.strictObject({...H,outcome:r.literal("found"),target:ce,start:r.strictObject({locale:R[0].shape.locale,parameters:R[0].shape.parameters}),purchase:Pe})]);var ut=G.options[0].refine(i=>!i.customer&&!i.customerData),ct=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),$e=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:oe,customerId:r.uuid(),sessionId:r.uuid(),start:ut,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Te.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ct).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:Le.nullable()})});function We(i){return Ge({...i,namespace:"purchases",identity:[i.scope.projectId,i.scope.environment,i.customerId]})}function Xe(i){let d=new URL(i.baseUrl??De).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){i.assertCurrent();try{let E=await i.storage.read();if(i.assertCurrent(),!Number.isSafeInteger(E.revision)||E.revision<0)throw f();let c=E.entry===null?null:$e.parse(E.entry);if(c&&(c.baseUrl!==d||c.customerId!==i.customerId||c.scope.projectId!==i.scope.projectId||c.scope.environment!==i.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(c?.journal.entry&&(c.journal.entry.scope.projectId!==c.scope.projectId||c.journal.entry.scope.environment!==c.scope.environment||c.journal.entry.funnelId!==c.start.funnelId||c.journal.entry.runId!==c.run?.id||c.journal.entry.versionId!==c.run?.versionId)||c?.operationCommand&&!c.purchases.some(k=>k.operationId===c.operationCommand?.operationId))throw f();return{revision:E.revision,entry:c}}catch(E){throw E instanceof l?E:f()}}async function W(E){for(let c=0;c<8;c++){let k=await S(),q=E(structuredClone(k.entry));if(JSON.stringify(q)===JSON.stringify(k.entry))return q;q&&$e.parse(q),i.assertCurrent();let j;try{j=await i.storage.write(k.revision,q)}catch{throw f()}if(i.assertCurrent(),j!==null){if(!Number.isSafeInteger(j)||j<=k.revision)throw f();return q}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:W,baseUrl:d}}var lt=5*6e4,dt=2e3;function pt(i,d){let f=i.purchases.find(S=>S.type==="checkout");if(!i.actions.includes("continue_checkout")||f?.type!=="checkout"||d!==void 0&&f.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function Qt(i){let d={...i,scope:{...i.scope},executionPolicy:structuredClone(i.executionPolicy)},f=d.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:S,sessionId:W}=f,E=!1,c=null,k,q,j=null,F=!1,U,X,Z,b={mode:"idle",status:"idle",actions:["start"],purchases:[]},g=new Map,ve=new Map,T=new Map,le=new AbortController,ee=new Set,Q=Ve(d),te=He(Q.request);function B(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function P(){if(E||d.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Xe({...d,customerId:S,assertCurrent:P,storage:d.storage??We({baseUrl:d.baseUrl,scope:d.scope,customerId:S})}),Ze,Re=()=>Ze??=import("./funnel-paywall-copies-A76T5V7B.js").then(({createPaywallCopies:e})=>e({baseUrl:d.baseUrl,scope:d.scope,customerId:S})),et={read:async e=>(await Re()).read(e),write:async(e,t)=>(await Re()).write(e,t)},tt=d.session.subscribeIdentity(Se);function Se(){E||(E=!0,clearTimeout(Z),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),tt(),c?.reset(),c=null,j=null,Q.dispose(),ee.clear(),g.clear(),T.clear())}function v(e){P();let t=JSON.stringify(e)!==JSON.stringify(b);b=e,clearTimeout(Z),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Z=setTimeout(()=>{M().catch(()=>{})},5e3)),t&&ge(d.onRecovery,structuredClone(e));for(let n of t?ee:[]){if(E)break;ge(n,structuredClone(e))}return structuredClone(e)}function y(e){if(P(),!e||e.start.requestId!==q)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function Ce(e){return!e.run&&!O(e).length&&!e.journal.entry&&!e.operationCommand}function O(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function x(e){let t=O(e),n=F&&t.length>0&&t.every(o=>o.terminal==="native"&&D(g.get(o.operationId))==="native")&&t.some(o=>{let s=g.get(o.operationId);return!!s&&J(s)&&T.get(o.operationId)===!0});return e.run&&(n||!["running","waiting"].includes(e.run.status))&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&t.every(o=>o.terminal!==null)}function A(e,t){let n=e.journal.entry?.command??e.journal.entry?.closeCommand,o=O(e).map(I=>{let C=g.get(I.operationId);return I.terminal&&!C?{type:I.terminal,operationId:I.operationId}:se({quote:C?.quote??null,operation:C??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(I.operationId)===!0})}),s=o.filter(I=>!["complete","native"].includes(I.type)),u=s[0],a=s.length===1&&u?.operationId?g.get(u.operationId):void 0;if(a&&(u?.type==="checkout"||u?.type==="cancel"))try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote)}catch(I){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:B(I)}}let m;if(t==="operation"&&!n&&u?.type==="cancel"&&a?.quote&&!a.problem&&!a.confirmedAt)try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote),Date.parse(a.quote.expiresAt)>Date.now()&&(m={operationId:a.operationId,quote:a.quote})}catch{}let p=o.length>0&&s.length===0,h=x(e)||t==="operation"&&p&&!n&&!e.operationCommand?"complete":u?.type==="checkout"?"checkout":u?.type==="fulfillment"?"fulfillment":u?.type==="recording"?"recording":n||e.operationCommand||u&&u.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:h,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...x(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...s.length===1&&u?.type==="checkout"?["continue_checkout"]:[]]}}function D(e){let t=se({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function de(e){if(!e.operation)return;let t=ae.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=ue(g.get(t.operationId)??null,t);g.set(t.operationId,n),n===t&&T.set(t.operationId,e.canReselect===!0)}async function nt(e){P();for(let n of[e.purchase,e.run.paywall])n&&de(n);let t=await w.update(n=>{if(y(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=O(n);for(let s of[e.purchase,e.run.paywall]){let u=s?.operation?.operationId??s?.quote?.operationId;if(!s||!u)continue;let a=o.find(p=>p.operationId===u);if(a&&a.receiptId!==s.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=D(g.get(u));a?a.terminal??=m:o.push({receiptId:s.receiptId,operationId:u,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});y(t),t.run&&!["running","waiting"].includes(t.run.status)&&O(t).some(n=>!n.terminal)&&(t=await L(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),y(t),v(A(t,"run"))}function rt(){return{async read(){let{entry:e}=await w.read();return y(e),structuredClone(e.journal)},async write(e,t){let n=null;return await w.update(o=>{if(y(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function L(e,t=!1,n=new Set){y(e);let o=O(e);for(let u of o){if(u.terminal)continue;let a=n.has(u.operationId)?g.get(u.operationId):void 0;if(a??=await V(e,u),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(a.merchantExecution&&a.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&se({quote:a.quote??null,operation:a,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=J(a)?await te.update({operationId:u.operationId,intent:"cancel"}):await te.attach({operationId:u.operationId,intent:"cancel"});if(a=ae.parse(m.operation),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");a=await V(e,u)}g.set(u.operationId,ue(g.get(u.operationId)??null,a))}let s=await w.update(u=>{y(u);let a=u.operationCommand&&g.get(u.operationCommand.operationId);return{...u,...a&&(a.confirmedAt||a.merchantExecution||!Fe(a))?{operationCommand:void 0}:{},purchases:O(u).map(m=>({...m,terminal:m.terminal??D(g.get(m.operationId))}))}});return y(s),s}async function Y(e){P();let t=await Q.request("funnels",e);return P(),t}async function ot(e){try{return await Y(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return Y({...e,intent:"resume"})}}async function at(){let e=$(Ke,await Y({operation:"find_purchase"}));if(e.customerId!==S||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:n}=e;return await w.update(o=>o&&!x(o)?o:{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...n,terminal:null}],journal:{revision:0,entry:null}}),"found"}let ne;function pe(e){let t=ne;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<lt))return t.job;let n={at:Date.now(),job:at().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw ne===n&&(ne=void 0),o})};return ne=n,n.job}async function V(e,t,n="recover_purchase",o=!1){let s=$(Je,await Y({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(me(e,s),s.purchase.receiptId!==t.receiptId||s.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return de(s.purchase),o&&s.paywallVersionId&&ve.set(t.operationId,s.paywallVersionId),g.get(t.operationId)}async function Ee(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=$(Ye,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(me(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&de(n.purchase);let o=await w.update(s=>{y(s);let u=O(s),{receiptId:a,operationId:m}=n.settlement;if(a&&m){let h=u.find(I=>I.operationId===m);if(h&&h.receiptId!==a)throw new l("INVALID_RESPONSE","Original Receipt changed");h||u.push({receiptId:a,operationId:m,terminal:D(g.get(m))})}let p=n.settlement.state==="settled"?Me(s.journal.entry,t.requestId):s.journal.entry;return{...s,purchases:u,journal:p===s.journal.entry?s.journal:{revision:s.journal.revision+1,entry:p}}});y(o),e=o}return e}function me(e,t){if(t.customerId!==S||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function fe(e,t){if(y(e),e.run&&(e=await Ee(e)),!O(e).length&&x(e))return v(A(e,"operation"));if(!O(e).length)return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(t)});F=!0;let n=O(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(s=>s.terminal==="native"))for(let s of n)D(g.get(s.operationId))!=="native"&&await V(e,s);let o=await L(e);return v(A(o,"operation"))}async function re(e,t=!1,n=!0,o=!1){if(q=e.start.requestId,j=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!c){let s=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ot(s)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:B(h)});throw h}let a=$(Be,u);if(a.customerId!==S||a.scope.projectId!==d.scope.projectId||a.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(a.outcome==="unknown"){if(!t&&Ce(e)){let h=e.start.requestId;if(!await w.update(C=>C&&C.start.requestId===h&&Ce(C)?null:C))return v({mode:"idle",status:"idle",actions:["start"],purchases:[]})}return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}})}me(e,a);let m=await w.update(h=>(y(h),{...h,run:{id:a.target.runId,versionId:a.target.versionId,status:a.target.status,revision:a.view?.revision??h.run?.revision??0,runExpiresAt:a.target.runExpiresAt}}));if(y(m),e=m,a.access.type==="operation_only")return fe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ee(e);let p=a.view;if(p.locale!==e.start.locale||!ze(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");c=Qe({...d,customerRun:{runId:a.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:rt(),onAcceptedResponse:nt},{scope:a.scope,run:p})}try{let s=o&&k?.controller===c?performance.now()-k.at:1/0;(s>=dt||c.pendingCommands?.length||(c.viewAgeMs??0)<s)&&(k=void 0,await c.get(),k={controller:c,at:performance.now()}),c.view?.pendingRequest?.requestId===e.start.requestId&&!c.pendingCommands?.length&&await c.resume(c.view.pendingRequest.requestId);for(let a of c.pendingCommands??[])a.operation!=="close"&&await c.settle?.(a.requestId);c.pendingCommands?.length&&await c.retry(),P();let u=(await w.read()).entry;return y(u),v(A(u,"run"))}catch(s){if(P(),n&&s instanceof l&&(s.status===401||s.status===409&&s.reason==="STATE_CHANGED")){c.reset(),c=null;let u=(await w.read()).entry;return y(u),re(u,!1,!1,!1)}throw s}}function N(e,t="read",n){if(P(),U)return t==="read"||t===X?U:U.then(()=>N(e,t,n),()=>N(e,t,n));clearTimeout(Z);let o=e().catch(s=>{throw!E&&!n?.(s)&&v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:b.purchases,error:B(s)}),s});return U=o,X=t,o.then(()=>{U===o&&(U=void 0,X=void 0)},()=>{U===o&&(U=void 0,X=void 0)}),o}function M(e){let t=e?.reuseRecentRead===!0;return N(async()=>{let{entry:n}=await w.read();if(!n||x(n)){if(await pe(!1)==="blocked")return be();({entry:n}=await w.read())}return n?(q&&n.start.requestId!==q&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F&&q===n.start.requestId?fe(n,b.error):re(n,!1,!0,t)):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function be(){return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function Oe(){let e=await M();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:N(async()=>{let t=(await w.read()).entry;if(y(t),!F){if(!c?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=c.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(J(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return v(A(t,"run"));if(c.pendingCommands?.length)await c.retry();else{let I=c.view;await c.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:I.nodeId,visit:I.visit,revision:I.revision,input:{type:"paywall_confirm",operationId:I.paywall.quote.operationId,...I.paywall.quote.merchantTerms?{merchantConfirmation:ye(I.paywall.quote.merchantTerms)}:{}}})}let h=(await w.read()).entry;return y(h),v(A(h,"run"))}let n=t.operationCommand?.operationId??b.confirmation?.operationId,o=n&&g.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");K({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await w.update(p=>{if(y(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:n,intent:"confirm"}}});let s={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:ye(o.quote.merchantTerms)}:{}},u=J(o)?await te.update(s):await te.attach(s),a=ae.parse(u.operation);if(P(),u.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");g.set(n,ue(o,a));let m=(await w.read()).entry;return y(m),v(A(await L(m,!1,new Set([n])),"operation"))},"confirm")}function it(e){let t=e?.quote;return t&&ie(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function _e(){if(b.mode!=="operation"||b.status==="blocked")return null;let e=b.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?it(g.get(t)):null}async function qe(){P();let{entry:e}=await w.read();return e?x(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(b)},get attempt(){return P(),structuredClone(j)},get identitySignal(){return le.signal},get customerId(){return S},retained:qe,get paywallCopies(){return et},async findPurchase(){let e=await qe();if(e==="pending")return e;let t=await pe(!0);return P(),t==="none"?e:t},async readPaywall(e){P();let t=Ne(e),[n,{readPaywallContent:o},{validateResourceCheck:s}]=await Promise.all([je(Q.request,"resolvePaywall"),import("./paywall-content-RAB5S6KB.js"),import("./check-response-754GDUOJ.js")]);P();let u=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),a=await Ue(Q.request,n,u);s(u,a.paywall.check,a.scope);let m=await o(d,a.paywall);if(P(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return _e()!==null},recoverUpgradePaywall(){let e=_e();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(b.mode!=="operation"||b.status==="blocked")return null;let{entry:n}=await w.read();if(!n?.run)return null;y(n);let o=O(n),s=o.filter(_=>!_.terminal),u=o.filter(_=>_.terminal==="complete"),a=s.length===1?s[0]:s.length?void 0:u.find(_=>e&&e.runId===n.run?.id&&_.receiptId===e.receiptId)??(u.length===1?u[0]:void 0);if(!a||t&&a.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===a.receiptId?e.view:void 0,p;try{p=await V(n,a,"recover_purchase",!0)}catch(_){if(!(_ instanceof l&&_.status===400&&_.code==="INVALID_REQUEST"))throw _;if(!m)return null;p=await V(n,a)}let h=p.quote;if(!h||ie(h)&&(h.timing!=="immediate"||h.execution.provider!=="merchant")||!(p.confirmedAt||p.merchantExecution||p.checkoutUrl||D(p)==="complete"))return null;D(p)!=="complete"&&K({allowed:n.allowed.filter(_=>d.executionPolicy.allowed.includes(_))},h);let I=ve.get(a.operationId),C=n.start.parameters?.commerce,ke=n.start.locale??"en",he=m;if(I){if(typeof C!="object"||!C||!("provider"in C)||typeof C.provider!="string"||!("currency"in C)||typeof C.currency!="string")return null;he=await this.readPaywall({paywallVersionId:I,locale:ke,commerce:{provider:C.provider,currency:C.currency,...ie(h)?{intent:"subscription_change"}:{}}})}if(!he)return null;P();let Ae=he,we=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:le.signal,view:Ae,quote:h,locale:ke,get operation(){return p},get canReselect(){return T.get(a.operationId)===!0},async refresh(){return Ae},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(we)throw new DOMException("Purchase view closed","AbortError");p=await V(n,a);let _=await L(n,!1,new Set([a.operationId]));return we||v(A(_,"operation")),structuredClone(p)},destroy(){we=!0}}},start(e){let t=G.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return N(async()=>{let n=(await w.read()).entry;if((!n||x(n))&&await pe(!0)==="blocked")return be();let o=await w.update(s=>{if(s&&!x(s)){if(s.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return s}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return q!==o.start.requestId&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F?fe(o,b.error):re(o,!0,!0,!0)},`start:${t.funnelId}`)},refresh:M,confirm:Oe,retry:()=>F?Oe():N(async()=>{let{entry:e}=await w.read();return e?re(e,!0):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return c?.view?N(async()=>{if(!c?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(c.pendingCommands?.find(n=>n.operation==="close"))await c.retry();else if(["running","waiting"].includes(c.view.status)){let n=c.view;await c.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await w.read()).entry;return y(t),v(A(t,"run"))},"close"):M()},async continueCheckout(e,t){let n=t?await N(async()=>{let{entry:o}=await w.read();if(y(o),!o.run||!O(o).some(u=>u.operationId===t&&!u.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let s=await L(o);return v(A(s,F?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await M();P(),await e(pt(n,t))},async terminateCheckout(e){let t=await M();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return N(async()=>{let{entry:o}=await w.read();y(o);let s=O(o).find(a=>a.operationId===e&&!a.terminal);if(!s||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(o,s,"terminate_checkout");let u=await L(o,!1,new Set([e]));return v(A(u,F?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return ee.add(e),()=>{ee.delete(e)}},destroy:Se}}export{We as a,pt as b,Qt as c};
1
+ import{b as He}from"./chunk-IUX4CJZM.js";import{a as $}from"./chunk-3KIATB75.js";import{D as K,F as Qe,c as Te,e as z,j as xe,u as Le,v as Me,x as Ge,z as ze}from"./chunk-UOJSZMKN.js";import{a as Ne,b as je,c as Ue}from"./chunk-F46VXI3Q.js";import{a as se}from"./chunk-EU4NTVRT.js";import{i as ue}from"./chunk-RZ7WFYWY.js";import{K as G}from"./chunk-44SX4C3G.js";import{A as ae,B as ie,C as J,E as Fe}from"./chunk-ONYG4VQI.js";import{x as ye}from"./chunk-LHUZRVAC.js";import{b as Ve}from"./chunk-TDMXEI2U.js";import{a as l}from"./chunk-4C4L3JER.js";import{h as oe}from"./chunk-IYVJOUO7.js";import{a as De}from"./chunk-5MRSFLQA.js";import{b as r}from"./chunk-CTCK5BUY.js";import{a as ge}from"./chunk-DSPLGTQI.js";var R=G.options,st=r.discriminatedUnion("operation",[R[1].omit({customerToken:!0}),R[2].omit({customerToken:!0}),R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0}),R[8].omit({customerToken:!0}),xe.omit({customerToken:!0})]),Pe=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),yt=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:R[0].shape.requestId,funnelId:R[0].shape.funnelId,locale:R[0].shape.locale,parameters:R[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0})]).optional()}).refine(i=>!i.command||i.requestId===i.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:st})]),ce=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:z.shape.run.shape.status}),H={scope:oe,customerId:r.uuid()},Be=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...H,outcome:r.literal("resolved"),target:ce,view:z.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((i,d)=>{i.outcome==="resolved"&&(i.access.type==="customer"!=(i.view!==null)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Ye=r.strictObject({...H,target:ce,view:z.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:z.shape.purchase.unwrap().nullable()}).superRefine((i,d)=>{let f=i.settlement;(f.acceptance==="accepted"!=(f.receiptPhase!==null)||f.acceptance==="accepted"&&f.basis!=="receipt"||f.acceptance==="unknown"&&(f.state!=="unknown"||f.basis!=="none")||f.acceptance!=="accepted"&&(f.operationId!==null||f.receiptId!==null)||f.acceptance==="not_accepted"&&(f.state!=="settled"||!["run_terminal","position_advanced"].includes(f.basis))||i.purchase&&(i.purchase.receiptId!==f.receiptId||i.purchase.operation&&i.purchase.operation.operationId!==f.operationId||i.purchase.quote&&i.purchase.quote.operationId!==f.operationId)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Je=r.strictObject({...H,target:ce,purchase:z.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((i,d)=>{(!i.purchase.operation||typeof i.purchase.canReselect!="boolean"||i.purchase.quote&&i.purchase.quote.operationId!==i.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Ke=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("none")}),r.strictObject({...H,outcome:r.literal("blocked")}),r.strictObject({...H,outcome:r.literal("found"),target:ce,start:r.strictObject({locale:R[0].shape.locale,parameters:R[0].shape.parameters}),purchase:Pe})]);var ut=G.options[0].refine(i=>!i.customer&&!i.customerData),ct=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),$e=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:oe,customerId:r.uuid(),sessionId:r.uuid(),start:ut,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Te.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ct).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:Le.nullable()})});function We(i){return Ge({...i,namespace:"purchases",identity:[i.scope.projectId,i.scope.environment,i.customerId]})}function Xe(i){let d=new URL(i.baseUrl??De).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){i.assertCurrent();try{let E=await i.storage.read();if(i.assertCurrent(),!Number.isSafeInteger(E.revision)||E.revision<0)throw f();let c=E.entry===null?null:$e.parse(E.entry);if(c&&(c.baseUrl!==d||c.customerId!==i.customerId||c.scope.projectId!==i.scope.projectId||c.scope.environment!==i.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(c?.journal.entry&&(c.journal.entry.scope.projectId!==c.scope.projectId||c.journal.entry.scope.environment!==c.scope.environment||c.journal.entry.funnelId!==c.start.funnelId||c.journal.entry.runId!==c.run?.id||c.journal.entry.versionId!==c.run?.versionId)||c?.operationCommand&&!c.purchases.some(k=>k.operationId===c.operationCommand?.operationId))throw f();return{revision:E.revision,entry:c}}catch(E){throw E instanceof l?E:f()}}async function W(E){for(let c=0;c<8;c++){let k=await S(),q=E(structuredClone(k.entry));if(JSON.stringify(q)===JSON.stringify(k.entry))return q;q&&$e.parse(q),i.assertCurrent();let j;try{j=await i.storage.write(k.revision,q)}catch{throw f()}if(i.assertCurrent(),j!==null){if(!Number.isSafeInteger(j)||j<=k.revision)throw f();return q}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:W,baseUrl:d}}var lt=5*6e4,dt=2e3;function pt(i,d){let f=i.purchases.find(S=>S.type==="checkout");if(!i.actions.includes("continue_checkout")||f?.type!=="checkout"||d!==void 0&&f.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function Qt(i){let d={...i,scope:{...i.scope},executionPolicy:structuredClone(i.executionPolicy)},f=d.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:S,sessionId:W}=f,E=!1,c=null,k,q,j=null,F=!1,U,X,Z,b={mode:"idle",status:"idle",actions:["start"],purchases:[]},g=new Map,ve=new Map,T=new Map,le=new AbortController,ee=new Set,Q=Ve(d),te=He(Q.request);function B(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function P(){if(E||d.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Xe({...d,customerId:S,assertCurrent:P,storage:d.storage??We({baseUrl:d.baseUrl,scope:d.scope,customerId:S})}),Ze,Re=()=>Ze??=import("./funnel-paywall-copies-ZI6BLXH7.js").then(({createPaywallCopies:e})=>e({baseUrl:d.baseUrl,scope:d.scope,customerId:S})),et={read:async e=>(await Re()).read(e),write:async(e,t)=>(await Re()).write(e,t)},tt=d.session.subscribeIdentity(Se);function Se(){E||(E=!0,clearTimeout(Z),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),tt(),c?.reset(),c=null,j=null,Q.dispose(),ee.clear(),g.clear(),T.clear())}function v(e){P();let t=JSON.stringify(e)!==JSON.stringify(b);b=e,clearTimeout(Z),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Z=setTimeout(()=>{M().catch(()=>{})},5e3)),t&&ge(d.onRecovery,structuredClone(e));for(let n of t?ee:[]){if(E)break;ge(n,structuredClone(e))}return structuredClone(e)}function y(e){if(P(),!e||e.start.requestId!==q)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function Ce(e){return!e.run&&!O(e).length&&!e.journal.entry&&!e.operationCommand}function O(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function x(e){let t=O(e),n=F&&t.length>0&&t.every(o=>o.terminal==="native"&&D(g.get(o.operationId))==="native")&&t.some(o=>{let s=g.get(o.operationId);return!!s&&J(s)&&T.get(o.operationId)===!0});return e.run&&(n||!["running","waiting"].includes(e.run.status))&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&t.every(o=>o.terminal!==null)}function A(e,t){let n=e.journal.entry?.command??e.journal.entry?.closeCommand,o=O(e).map(I=>{let C=g.get(I.operationId);return I.terminal&&!C?{type:I.terminal,operationId:I.operationId}:se({quote:C?.quote??null,operation:C??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(I.operationId)===!0})}),s=o.filter(I=>!["complete","native"].includes(I.type)),u=s[0],a=s.length===1&&u?.operationId?g.get(u.operationId):void 0;if(a&&(u?.type==="checkout"||u?.type==="cancel"))try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote)}catch(I){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:B(I)}}let m;if(t==="operation"&&!n&&u?.type==="cancel"&&a?.quote&&!a.problem&&!a.confirmedAt)try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote),Date.parse(a.quote.expiresAt)>Date.now()&&(m={operationId:a.operationId,quote:a.quote})}catch{}let p=o.length>0&&s.length===0,h=x(e)||t==="operation"&&p&&!n&&!e.operationCommand?"complete":u?.type==="checkout"?"checkout":u?.type==="fulfillment"?"fulfillment":u?.type==="recording"?"recording":n||e.operationCommand||u&&u.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:h,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...x(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...s.length===1&&u?.type==="checkout"?["continue_checkout"]:[]]}}function D(e){let t=se({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function de(e){if(!e.operation)return;let t=ae.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=ue(g.get(t.operationId)??null,t);g.set(t.operationId,n),n===t&&T.set(t.operationId,e.canReselect===!0)}async function nt(e){P();for(let n of[e.purchase,e.run.paywall])n&&de(n);let t=await w.update(n=>{if(y(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=O(n);for(let s of[e.purchase,e.run.paywall]){let u=s?.operation?.operationId??s?.quote?.operationId;if(!s||!u)continue;let a=o.find(p=>p.operationId===u);if(a&&a.receiptId!==s.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=D(g.get(u));a?a.terminal??=m:o.push({receiptId:s.receiptId,operationId:u,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});y(t),t.run&&!["running","waiting"].includes(t.run.status)&&O(t).some(n=>!n.terminal)&&(t=await L(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),y(t),v(A(t,"run"))}function rt(){return{async read(){let{entry:e}=await w.read();return y(e),structuredClone(e.journal)},async write(e,t){let n=null;return await w.update(o=>{if(y(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function L(e,t=!1,n=new Set){y(e);let o=O(e);for(let u of o){if(u.terminal)continue;let a=n.has(u.operationId)?g.get(u.operationId):void 0;if(a??=await V(e,u),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(a.merchantExecution&&a.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&se({quote:a.quote??null,operation:a,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=J(a)?await te.update({operationId:u.operationId,intent:"cancel"}):await te.attach({operationId:u.operationId,intent:"cancel"});if(a=ae.parse(m.operation),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");a=await V(e,u)}g.set(u.operationId,ue(g.get(u.operationId)??null,a))}let s=await w.update(u=>{y(u);let a=u.operationCommand&&g.get(u.operationCommand.operationId);return{...u,...a&&(a.confirmedAt||a.merchantExecution||!Fe(a))?{operationCommand:void 0}:{},purchases:O(u).map(m=>({...m,terminal:m.terminal??D(g.get(m.operationId))}))}});return y(s),s}async function Y(e){P();let t=await Q.request("funnels",e);return P(),t}async function ot(e){try{return await Y(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return Y({...e,intent:"resume"})}}async function at(){let e=$(Ke,await Y({operation:"find_purchase"}));if(e.customerId!==S||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:n}=e;return await w.update(o=>o&&!x(o)?o:{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...n,terminal:null}],journal:{revision:0,entry:null}}),"found"}let ne;function pe(e){let t=ne;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<lt))return t.job;let n={at:Date.now(),job:at().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw ne===n&&(ne=void 0),o})};return ne=n,n.job}async function V(e,t,n="recover_purchase",o=!1){let s=$(Je,await Y({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(me(e,s),s.purchase.receiptId!==t.receiptId||s.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return de(s.purchase),o&&s.paywallVersionId&&ve.set(t.operationId,s.paywallVersionId),g.get(t.operationId)}async function Ee(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=$(Ye,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(me(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&de(n.purchase);let o=await w.update(s=>{y(s);let u=O(s),{receiptId:a,operationId:m}=n.settlement;if(a&&m){let h=u.find(I=>I.operationId===m);if(h&&h.receiptId!==a)throw new l("INVALID_RESPONSE","Original Receipt changed");h||u.push({receiptId:a,operationId:m,terminal:D(g.get(m))})}let p=n.settlement.state==="settled"?Me(s.journal.entry,t.requestId):s.journal.entry;return{...s,purchases:u,journal:p===s.journal.entry?s.journal:{revision:s.journal.revision+1,entry:p}}});y(o),e=o}return e}function me(e,t){if(t.customerId!==S||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function fe(e,t){if(y(e),e.run&&(e=await Ee(e)),!O(e).length&&x(e))return v(A(e,"operation"));if(!O(e).length)return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(t)});F=!0;let n=O(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(s=>s.terminal==="native"))for(let s of n)D(g.get(s.operationId))!=="native"&&await V(e,s);let o=await L(e);return v(A(o,"operation"))}async function re(e,t=!1,n=!0,o=!1){if(q=e.start.requestId,j=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!c){let s=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ot(s)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:B(h)});throw h}let a=$(Be,u);if(a.customerId!==S||a.scope.projectId!==d.scope.projectId||a.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(a.outcome==="unknown"){if(!t&&Ce(e)){let h=e.start.requestId;if(!await w.update(C=>C&&C.start.requestId===h&&Ce(C)?null:C))return v({mode:"idle",status:"idle",actions:["start"],purchases:[]})}return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}})}me(e,a);let m=await w.update(h=>(y(h),{...h,run:{id:a.target.runId,versionId:a.target.versionId,status:a.target.status,revision:a.view?.revision??h.run?.revision??0,runExpiresAt:a.target.runExpiresAt}}));if(y(m),e=m,a.access.type==="operation_only")return fe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ee(e);let p=a.view;if(p.locale!==e.start.locale||!ze(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");c=Qe({...d,customerRun:{runId:a.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:rt(),onAcceptedResponse:nt},{scope:a.scope,run:p})}try{let s=o&&k?.controller===c?performance.now()-k.at:1/0;(s>=dt||c.pendingCommands?.length||(c.viewAgeMs??0)<s)&&(k=void 0,await c.get(),k={controller:c,at:performance.now()}),c.view?.pendingRequest?.requestId===e.start.requestId&&!c.pendingCommands?.length&&await c.resume(c.view.pendingRequest.requestId);for(let a of c.pendingCommands??[])a.operation!=="close"&&await c.settle?.(a.requestId);c.pendingCommands?.length&&await c.retry(),P();let u=(await w.read()).entry;return y(u),v(A(u,"run"))}catch(s){if(P(),n&&s instanceof l&&(s.status===401||s.status===409&&s.reason==="STATE_CHANGED")){c.reset(),c=null;let u=(await w.read()).entry;return y(u),re(u,!1,!1,!1)}throw s}}function N(e,t="read",n){if(P(),U)return t==="read"||t===X?U:U.then(()=>N(e,t,n),()=>N(e,t,n));clearTimeout(Z);let o=e().catch(s=>{throw!E&&!n?.(s)&&v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:b.purchases,error:B(s)}),s});return U=o,X=t,o.then(()=>{U===o&&(U=void 0,X=void 0)},()=>{U===o&&(U=void 0,X=void 0)}),o}function M(e){let t=e?.reuseRecentRead===!0;return N(async()=>{let{entry:n}=await w.read();if(!n||x(n)){if(await pe(!1)==="blocked")return be();({entry:n}=await w.read())}return n?(q&&n.start.requestId!==q&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F&&q===n.start.requestId?fe(n,b.error):re(n,!1,!0,t)):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function be(){return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function Oe(){let e=await M();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:N(async()=>{let t=(await w.read()).entry;if(y(t),!F){if(!c?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=c.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(J(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return v(A(t,"run"));if(c.pendingCommands?.length)await c.retry();else{let I=c.view;await c.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:I.nodeId,visit:I.visit,revision:I.revision,input:{type:"paywall_confirm",operationId:I.paywall.quote.operationId,...I.paywall.quote.merchantTerms?{merchantConfirmation:ye(I.paywall.quote.merchantTerms)}:{}}})}let h=(await w.read()).entry;return y(h),v(A(h,"run"))}let n=t.operationCommand?.operationId??b.confirmation?.operationId,o=n&&g.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");K({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await w.update(p=>{if(y(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:n,intent:"confirm"}}});let s={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:ye(o.quote.merchantTerms)}:{}},u=J(o)?await te.update(s):await te.attach(s),a=ae.parse(u.operation);if(P(),u.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");g.set(n,ue(o,a));let m=(await w.read()).entry;return y(m),v(A(await L(m,!1,new Set([n])),"operation"))},"confirm")}function it(e){let t=e?.quote;return t&&ie(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function _e(){if(b.mode!=="operation"||b.status==="blocked")return null;let e=b.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?it(g.get(t)):null}async function qe(){P();let{entry:e}=await w.read();return e?x(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(b)},get attempt(){return P(),structuredClone(j)},get identitySignal(){return le.signal},get customerId(){return S},retained:qe,get paywallCopies(){return et},async findPurchase(){let e=await qe();if(e==="pending")return e;let t=await pe(!0);return P(),t==="none"?e:t},async readPaywall(e){P();let t=Ne(e),[n,{readPaywallContent:o},{validateResourceCheck:s}]=await Promise.all([je(Q.request,"resolvePaywall"),import("./paywall-content-NLEGSOUT.js"),import("./check-response-3EFQG3PL.js")]);P();let u=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),a=await Ue(Q.request,n,u);s(u,a.paywall.check,a.scope);let m=await o(d,a.paywall);if(P(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return _e()!==null},recoverUpgradePaywall(){let e=_e();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(b.mode!=="operation"||b.status==="blocked")return null;let{entry:n}=await w.read();if(!n?.run)return null;y(n);let o=O(n),s=o.filter(_=>!_.terminal),u=o.filter(_=>_.terminal==="complete"),a=s.length===1?s[0]:s.length?void 0:u.find(_=>e&&e.runId===n.run?.id&&_.receiptId===e.receiptId)??(u.length===1?u[0]:void 0);if(!a||t&&a.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===a.receiptId?e.view:void 0,p;try{p=await V(n,a,"recover_purchase",!0)}catch(_){if(!(_ instanceof l&&_.status===400&&_.code==="INVALID_REQUEST"))throw _;if(!m)return null;p=await V(n,a)}let h=p.quote;if(!h||ie(h)&&(h.timing!=="immediate"||h.execution.provider!=="merchant")||!(p.confirmedAt||p.merchantExecution||p.checkoutUrl||D(p)==="complete"))return null;D(p)!=="complete"&&K({allowed:n.allowed.filter(_=>d.executionPolicy.allowed.includes(_))},h);let I=ve.get(a.operationId),C=n.start.parameters?.commerce,ke=n.start.locale??"en",he=m;if(I){if(typeof C!="object"||!C||!("provider"in C)||typeof C.provider!="string"||!("currency"in C)||typeof C.currency!="string")return null;he=await this.readPaywall({paywallVersionId:I,locale:ke,commerce:{provider:C.provider,currency:C.currency,...ie(h)?{intent:"subscription_change"}:{}}})}if(!he)return null;P();let Ae=he,we=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:le.signal,view:Ae,quote:h,locale:ke,get operation(){return p},get canReselect(){return T.get(a.operationId)===!0},async refresh(){return Ae},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(we)throw new DOMException("Purchase view closed","AbortError");p=await V(n,a);let _=await L(n,!1,new Set([a.operationId]));return we||v(A(_,"operation")),structuredClone(p)},destroy(){we=!0}}},start(e){let t=G.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return N(async()=>{let n=(await w.read()).entry;if((!n||x(n))&&await pe(!0)==="blocked")return be();let o=await w.update(s=>{if(s&&!x(s)){if(s.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return s}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return q!==o.start.requestId&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F?fe(o,b.error):re(o,!0,!0,!0)},`start:${t.funnelId}`)},refresh:M,confirm:Oe,retry:()=>F?Oe():N(async()=>{let{entry:e}=await w.read();return e?re(e,!0):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return c?.view?N(async()=>{if(!c?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(c.pendingCommands?.find(n=>n.operation==="close"))await c.retry();else if(["running","waiting"].includes(c.view.status)){let n=c.view;await c.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await w.read()).entry;return y(t),v(A(t,"run"))},"close"):M()},async continueCheckout(e,t){let n=t?await N(async()=>{let{entry:o}=await w.read();if(y(o),!o.run||!O(o).some(u=>u.operationId===t&&!u.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let s=await L(o);return v(A(s,F?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await M();P(),await e(pt(n,t))},async terminateCheckout(e){let t=await M();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return N(async()=>{let{entry:o}=await w.read();y(o);let s=O(o).find(a=>a.operationId===e&&!a.terminal);if(!s||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(o,s,"terminate_checkout");let u=await L(o,!1,new Set([e]));return v(A(u,F?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return ee.add(e),()=>{ee.delete(e)}},destroy:Se}}export{We as a,pt as b,Qt as c};
@@ -1 +1 @@
1
- var s={name:"@tinkerlandai/longplay-sdk",version:"0.10.69",description:"Framework-independent Longplay 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","native-funnel-host.NOTICES.txt"],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 && tsc --noEmit -p tsconfig.test.json",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}}};export{s as a};
1
+ var s={name:"@tinkerlandai/longplay-sdk",version:"0.10.71",description:"Framework-independent Longplay 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","native-funnel-host.NOTICES.txt"],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 && tsc --noEmit -p tsconfig.test.json",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}}};export{s as a};
@@ -1 +1 @@
1
- import{a as tt,b as it}from"./chunk-NNJ7W4KY.js";import{a as Ut,b as Mt,d as Et,h as Z,i as fe}from"./chunk-2SSOV3OG.js";import{a as V,b as rt,c as Tt,e as kt}from"./chunk-ULED3B5P.js";import{f as gt,h as ht,i as ft,j as bt,k as xt}from"./chunk-ECUGL7AO.js";import{o as he,p as Ct,u as Q,v as _t,w as Rt,x as wt,y as Bt,z as qt}from"./chunk-3NV6NBQB.js";import{f as nt,g as y,i as ue,j as at,k as st,l as de,m as P,n as ot,o as I,p as ct,q as me,r as ut,s as dt,t as mt,u as pe,v as pt,w as lt,x as le}from"./chunk-WVTKVQLZ.js";import{k as f,l as He,w as N}from"./chunk-QTXHF27F.js";import{a as zt}from"./chunk-5NCQOJR2.js";import{a as We,b as F}from"./chunk-KJTHMRSH.js";import{a as B,b as St,c as yt,d as It,e as q,f as vt,g as Ot,h as ge,i as j,j as At,k as Pt,l as jt}from"./chunk-JW4MSBYN.js";import{a as c,e as Xe,f as Je,g as Ye,h as et,j as ce}from"./chunk-26QYDE7V.js";import{h as se,i as p,j as s,k as oe,m as h}from"./chunk-TFPLIX5E.js";import{b as e}from"./chunk-S7NHVERO.js";var be=e.strictObject({operationId:e.uuid(),customerId:e.uuid(),externalUserId:e.string().min(1).max(256),modelId:e.string().min(1).max(256),quantity:e.number().int().min(1).max(1e6),validForDays:e.number().int().min(1).max(3660)}),Dt=e.strictObject({operationId:e.uuid(),customerId:e.uuid(),status:e.literal("applied"),voucherId:e.uuid(),modelId:e.string().min(1).max(256),quantity:e.number().int().positive(),issuedAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0})}).refine(t=>Date.parse(t.expiresAt)>Date.parse(t.issuedAt),{message:"A benefit must expire after it is issued"}),Gt=e.strictObject({operationId:e.uuid(),customerId:e.uuid()}),xa=e.discriminatedUnion("lookup",[Gt.extend({lookup:e.literal("not_received")}),Gt.extend({lookup:e.literal("found"),result:Dt}).refine(t=>t.result.operationId===t.operationId&&t.result.customerId===t.customerId)]),$t=e.strictObject({customerId:e.string().min(1).max(256),modelId:e.string().min(1).max(256),quantity:be.shape.quantity,validForDays:be.shape.validForDays,requestId:e.uuid()}),Lt=e.strictObject({customerId:e.string().min(1).max(256),operationId:e.uuid()}),xe=e.strictObject({operationId:e.uuid(),customerId:e.uuid(),taskId:e.uuid(),status:e.enum(["pending","applied","rejected"]),terms:be,receipt:Dt.nullable(),failureCode:e.enum(["INVALID_REQUEST","CONNECTION_CHANGED"]).nullable()}).superRefine((t,n)=>{(t.terms.operationId!==t.operationId||t.terms.customerId!==t.customerId||t.status==="applied"!=(t.receipt!==null)||t.status==="rejected"!=(t.failureCode!==null)||t.receipt&&(t.receipt.operationId!==t.operationId||t.receipt.customerId!==t.customerId||t.receipt.modelId!==t.terms.modelId||t.receipt.quantity!==t.terms.quantity))&&n.addIssue({code:"custom",message:"Benefit result differs from the original accepted operation"})});var T=e.enum(["email","sms","voice","push"]),Ia=e.enum(["resend","twilio","fcm","apns"]);var va=e.string().regex(/^\+[1-9]\d{1,14}$/),Qr=e.enum(["email_recipient","sms_segment","voice_second","push_device"]);var Zr=e.string().trim().min(1).max(200).refine(t=>!/[\r\n\0]/.test(t),"Invalid email header"),Kr=e.strictObject({subject:Zr,html:e.string().min(1).max(131072).optional(),text:e.string().min(1).max(65536).optional()}).refine(t=>t.html!==void 0||t.text!==void 0,{message:"Email requires HTML or text content"}),Wr=e.strictObject({body:e.string().min(1).max(1600).refine(t=>t.trim().length>0)}),Hr=e.strictObject({text:e.string().trim().min(1).max(4e3),language:e.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:e.number().int().min(1).max(900)}),Xr=e.record(e.string().min(1).max(64),e.string().max(256)).refine(t=>Object.keys(t).length<=20&&Object.keys(t).every(n=>!/^(?:indiana_|google\.|gcm\.)/i.test(n)&&n!=="aps"),"Push data contains reserved fields or too many entries"),Jr=e.strictObject({title:e.string().trim().min(1).max(200),body:e.string().trim().min(1).max(2e3),url:e.url().max(2048).refine(t=>!/^(?:javascript|data|file|vbscript):/i.test(t)).optional(),data:Xr.optional()}).refine(t=>new TextEncoder().encode(JSON.stringify(t)).length<=3072,"Push content exceeds the provider payload budget"),Ft=e.discriminatedUnion("channel",[e.strictObject({channel:e.literal("email"),content:Kr}),e.strictObject({channel:e.literal("sms"),content:Wr}),e.strictObject({channel:e.literal("voice"),content:Hr}),e.strictObject({channel:e.literal("push"),content:Jr})]),Nt=e.strictObject({requestId:e.uuid(),customerId:e.uuid(),connectionId:e.uuid().optional(),message:Ft,expiresAt:e.iso.datetime({offset:!0})}),Yr=e.array(e.uuid()).min(1).max(1e4).refine(t=>new Set(t).size===t.length,"Duplicate Customer"),en=e.discriminatedUnion("kind",[e.strictObject({kind:e.literal("all")}),e.strictObject({kind:e.literal("customers"),customerIds:Yr})]),Oa=e.strictObject({name:e.string().trim().min(1).max(120),connectionId:e.uuid().optional(),message:Ft,audience:en,frequencyLimit:e.number().int().min(1).max(100)}),Vt=e.strictObject({requestId:e.uuid(),channel:T,state:e.enum(["allowed","denied"]),expectedRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Qt=e.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Zt=e.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),Aa=e.strictObject({meter:Qr,estimatedUnits:e.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:e.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var Kt=e.strictObject({requestId:e.uuid(),targets:e.array(e.strictObject({membershipId:e.uuid(),action:e.enum(["cancel","uncancel"]),timing:e.enum(["immediate","renewal"])}).refine(t=>t.action!=="uncancel"||t.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(t=>new Set(t.targets.map(n=>n.membershipId)).size===t.targets.length,"Duplicate batch target"),K=e.strictObject({batchId:e.uuid()}),tn=e.strictObject({operationId:e.uuid(),membershipIds:e.array(e.uuid()).min(1).max(20),provider:e.enum(["stripe","apple","google"]),action:e.enum(["cancel","uncancel"]),timing:e.enum(["immediate","renewal"]),status:e.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:dt.nullable(),managementUrl:e.url().nullable(),failureCode:e.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),k=e.strictObject({batchId:e.uuid(),ready:e.boolean(),status:e.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:e.iso.datetime({offset:!0}),acceptedAt:e.iso.datetime({offset:!0}).nullable(),groups:e.array(tn).min(1).max(100)});var rn=e.string().trim().min(1).max(240),Se={requestId:e.uuid(),reason:rn},W=e.discriminatedUnion("action",[e.strictObject({...Se,action:e.literal("start"),productVersionId:e.uuid(),entityId:e.uuid().optional(),days:e.number().int().min(1).max(730).optional()}),e.strictObject({...Se,action:e.literal("extend"),membershipId:e.uuid(),days:e.number().int().min(1).max(730)}),e.strictObject({...Se,action:e.literal("end"),membershipId:e.uuid()})]),Wt=e.strictObject({operationId:e.uuid()}),Ht=e.iso.datetime({offset:!0}),nn=e.strictObject({provider:e.literal("stripe"),executor:e.enum(["indiana","merchant"]),accountId:e.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:e.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:e.union([e.literal("now"),Ht]),prorationBehavior:e.literal("none")}),ye=e.strictObject({operationId:e.uuid(),action:e.enum(["start","extend","end"]),status:e.enum(["pending","effective"]),managedBy:e.enum(["indiana","stripe"]),membershipIds:e.array(e.uuid()).min(1).max(20),endsAt:Ht.nullable(),execution:nn.nullable()}).refine(t=>t.execution!==null==(t.managedBy==="stripe"&&t.status==="pending")&&t.action==="end"==(t.endsAt===null)&&(t.action!=="start"||t.managedBy==="indiana")&&(t.execution===null||t.execution.trialEnd==="now"==(t.action==="end")),"Only a pending Stripe trial change carries execution instructions"),wa=e.strictObject({groupId:e.uuid(),productVersionId:e.uuid(),enabled:e.boolean()});var Xt=e.strictObject({requestId:e.uuid(),currency:c,makeDefault:e.boolean()}),Jt=e.strictObject({setupId:e.uuid()}),an=e.strictObject({provider:e.literal("stripe"),executor:e.literal("merchant"),accountId:e.string().regex(/^acct_[A-Za-z0-9]+$/),mode:e.literal("setup"),currency:e.string().regex(/^[a-z]{3}$/),customer:e.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:e.uuid(),metadata:e.strictObject({grooveProjectId:e.uuid(),grooveEnvironmentId:e.uuid(),grooveCustomerId:e.uuid(),groovePaymentSetupId:e.uuid()}),setDefaultPaymentMethod:e.boolean(),expiresAt:e.iso.datetime({offset:!0})}),Ie=e.strictObject({id:e.uuid(),provider:e.literal("stripe"),status:e.enum(["prepared","complete","expired"]),currency:c,makeDefault:e.boolean(),url:e.url().nullable(),createdAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0}),completedAt:e.iso.datetime({offset:!0}).nullable(),execution:an.nullable()});var Yt=e.union([e.string(),e.number(),e.boolean(),e.null()]),ei=e.strictObject({customerId:e.uuid()}),ti=e.strictObject({customerId:e.uuid(),provider:e.literal("stripe"),checkedAt:e.iso.datetime({offset:!0}),status:e.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:e.number().int().nonnegative(),differences:e.array(e.strictObject({subscriptionId:e.string().startsWith("sub_"),itemId:e.string().nullable(),field:e.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Yt,actual:Yt})).max(1e4)});var H=e.iso.datetime({offset:!0}),X=e.strictObject({createdAt:H,id:e.uuid()}),J=e.strictObject({customerId:e.uuid().optional(),entityId:e.uuid().optional(),productId:e.string().min(1).max(256).optional(),provider:e.enum(["stripe","apple","google","merchant","free"]).optional(),status:e.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:X.optional(),limit:e.number().int().min(1).max(100).optional()}),ve={id:e.uuid(),customerId:e.uuid(),entityId:e.uuid().nullable(),productId:e.string().min(1).max(256),productVersionId:e.uuid(),name:e.string().min(1).max(120),provider:e.enum(["stripe","apple","google","merchant","free"]),createdAt:H},sn=e.strictObject({...ve,status:e.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:e.boolean(),billingSubscriptionId:e.uuid().nullable()}),on=e.strictObject({...ve,status:e.enum(["active","ended","refunded"]),orderId:e.uuid().nullable(),transactionId:e.uuid().nullable(),currency:c.nullable(),amountMinor:e.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),cn=e.strictObject({...ve,status:e.enum(["blocked","resolved"]),conflict:e.strictObject({detectedAt:H,blockingMembershipIds:e.array(e.uuid()).min(1).max(100),transactionId:e.uuid()}),resolvedAt:H.nullable()}),ii=J.extend({status:e.enum(["blocked","resolved"]).optional()}),ri=e.strictObject({customerId:e.uuid(),orderId:e.uuid()}),ni=e.strictObject({orderId:e.uuid(),status:e.enum(["blocked","resolved"])}),ai=e.strictObject({items:e.array(sn).max(100),nextCursor:X.nullable()}),si=e.strictObject({items:e.array(on).max(100),nextCursor:X.nullable()}),oi=e.strictObject({items:e.array(cn).max(100),nextCursor:X.nullable()});var ci=e.union([e.strictObject({intent:e.literal("read"),requestId:e.uuid(),purchaseIntentId:e.uuid()}),e.strictObject({requestId:e.uuid(),provider:e.literal("apple"),purchaseIntentId:e.uuid(),productId:e.string().min(1).max(255).optional(),signedTransaction:e.string().min(1).max(131072)}),e.strictObject({requestId:e.uuid(),provider:e.literal("google"),purchaseIntentId:e.uuid(),productId:e.string().min(1).max(255).optional(),purchaseToken:e.string().min(1).max(16384)})]),ui=e.strictObject({requestId:e.uuid(),orderId:e.uuid(),purchaseIntentId:e.uuid(),status:e.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:c,refunded:e.boolean(),completion:e.strictObject({transactionIds:e.array(e.string().min(1).max(255)).min(1).max(50).refine(t=>new Set(t).size===t.length),membership:e.boolean()}).nullable()});var un=e.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),pi=e.enum(["single_use","continuous_use"]),Oe=e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string())),di=e.string().min(1).max(64).refine(t=>!t.includes("::")),li={credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()},gi={credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(e.strictObject({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()}))},dn=e.union([e.strictObject({match:Oe,priority:e.number().int().optional(),...li}),e.strictObject({match:Oe,priority:e.number().int().optional(),...gi})]),mn=e.strictObject({match:Oe,factor:e.number().positive().optional(),add:e.number().optional()}).refine(t=>t.factor!==void 0||t.add!==void 0),mi={metered_feature_id:e.string(),feature_amount:e.number().optional(),dimensions:e.record(di,dn).optional(),multipliers:e.record(di,mn).optional()},Ae=e.union([e.strictObject({...mi,...li}),e.strictObject({...mi,...gi})]),ee=e.number().min(-100),hi=e.record(e.string(),e.strictObject({markup:ee})).nullish(),te=e.record(e.string().regex(/.+\/.+/),e.strictObject({markup:ee.optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish(),pn=e.strictObject({default_markup:ee.optional(),provider_markups:hi,model_markups:te}),Na=e.strictObject({schema:e.array(Ae).optional(),markups:pn.optional()}),ln=e.strictObject({filters:e.array(e.strictObject({property:e.string(),operator:e.string(),value:e.array(e.string())})),aggregate:e.strictObject({type:e.string(),property:e.string().nullable()}),usage_type:pi}),fi=e.strictObject({schema:e.array(Ae).min(1).refine(t=>new Set(t.map(n=>n.metered_feature_id)).size===t.length,"Credit rates must name each metered feature once"),invoice_credit:e.boolean().optional(),usage_type:pi.default("single_use").overwrite(()=>"single_use"),default_markup:ee.optional(),provider_markups:hi}),Pe=fi.safeExtend({schema:e.array(Ae).length(0)}),Y={id:un,name:e.string().min(1),display:e.strictObject({singular:e.string().optional(),plural:e.string().optional()}).nullish(),event_names:e.array(e.string()).default([]),model_markups:te,stripe_meter:e.strictObject({id:e.string(),event_name:e.string()}).nullish(),stripe_product_id:e.string().nullish()},je=t=>e.discriminatedUnion("type",[e.strictObject({...Y,...t,type:e.literal("boolean"),config:e.null()}),e.strictObject({...Y,...t,type:e.literal("metered"),config:ln}),e.strictObject({...Y,...t,type:e.literal("credit_system"),config:fi}),e.strictObject({...Y,...t,type:e.literal("ai_credit_system"),config:Pe})]),Va=je({}),gn=e.strictObject({id:e.boolean(),type:e.boolean(),usage_type:e.boolean()}),hn={internal_id:e.uuid(),org_id:e.uuid(),created_at:e.number(),env:e.enum(["sandbox","live"]),archived:e.boolean(),project_id:e.uuid(),environment_id:e.uuid(),revision:e.number().int().nonnegative(),update_rules:gn},bi=je(hn),Qa=e.strictObject({rows:e.array(bi).max(200),nextCursor:e.uuid().nullable()}),Za=e.strictObject({features:e.array(bi).max(500),limited:e.boolean()}),Ka=e.union([je({action:e.literal("save"),internal_id:e.uuid().nullable(),revision:e.number().int().nonnegative()}),e.strictObject({action:e.enum(["archive","restore","delete"]),internal_id:e.uuid(),revision:e.number().int().nonnegative()})]);var _e=e.uuid().refine(t=>t===t.toLowerCase(),"Product references require canonical lowercase UUIDs"),fn=e.record(e.string(),e.json()).refine(t=>Array.from(JSON.stringify(t)).length<=4e3,"Offering metadata exceeds 4000 characters"),bn=3,z=20,xn=bn*z,Ce=e.strictObject({type:e.literal("product"),productId:_e}),xi={type:e.literal("group"),key:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:e.string().trim().min(1).max(80)},Sn=e.discriminatedUnion("type",[Ce,e.strictObject({...xi,items:e.array(Ce).max(z)})]),yn=e.discriminatedUnion("type",[Ce,e.strictObject({...xi,items:e.array(Sn).max(z)})]),In=e.array(yn).max(z).superRefine((t,n)=>{let a=new Set,o=new Set,m=0;function Qe(Vr){for(let S of Vr){m++;let Ze=S.type==="product"?a:o,Ke=S.type==="product"?S.productId:S.key;Ze.has(Ke)&&n.addIssue({code:"custom",message:S.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),Ze.add(Ke),S.type==="group"&&Qe(S.items)}}Qe(t),(a.size>z||m>xn)&&n.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Re(t){return t.items.flatMap(n=>n.type==="product"?[n.productId]:Re(n))}var C=e.strictObject({lookupKey:e.string().trim().min(1).max(200),displayName:e.string().trim().min(1).max(1500),items:In,metadata:fn}),vn=e.strictObject({product:e.record(e.string(),e.json()),prices:e.array(e.record(e.string(),e.json())),entitlements:e.array(e.record(e.string(),e.json())),freeTrials:e.array(e.record(e.string(),e.json())),licenses:e.array(e.record(e.string(),e.json()))}),Si=C.extend({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),state:e.enum(["active","archived"]),isCurrent:e.boolean(),revision:e.number().int().nonnegative(),publishedVersionId:e.uuid().nullable(),createdAt:e.iso.datetime({offset:!0})}).superRefine((t,n)=>{t.isCurrent&&(t.state!=="active"||!t.publishedVersionId)&&n.addIssue({code:"custom",message:"Current Offering must be active and published"})}),yi=e.strictObject({id:e.uuid(),offeringId:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),version:e.number().int().positive(),document:C,productEvidence:e.record(_e,vn),createdAt:e.iso.datetime({offset:!0})}).superRefine((t,n)=>{let a=Re(t.document);(!a.length||Pn(t.document).length>0||Object.keys(t.productEvidence).length!==a.length||a.some(o=>!Object.hasOwn(t.productEvidence,o)))&&n.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),On=e.strictObject({rows:e.array(Si).max(200),versions:e.array(yi).max(500)}),Xa=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),document:C}),e.strictObject({action:e.literal("save"),id:e.uuid(),revision:e.number().int().nonnegative(),document:C}),e.strictObject({action:e.enum(["publish","set_current","archive","restore"]),id:e.uuid(),revision:e.number().int().nonnegative()})]),Ja=e.strictObject({record:Si,version:yi.nullable()}),Ii=e.discriminatedUnion("type",[e.strictObject({type:e.literal("current")}),e.strictObject({type:e.literal("id"),id:e.uuid()}),e.strictObject({type:e.literal("lookup_key"),lookupKey:e.string().min(1).max(200)}),e.strictObject({type:e.literal("version"),versionId:e.uuid()})]),An=e.strictObject({internalId:_e,id:e.string(),name:e.string().nullable(),version:e.number().int().positive(),archived:e.boolean()}),Ya=On.extend({products:e.array(An).max(500),pagination:e.strictObject({rows:e.string().nullable(),versions:e.string().nullable(),products:e.string().nullable()}).optional()});function Pn(t){let n=[];Re(t).length||n.push("Select at least one Product before publishing");function a(o){for(let m of o)m.type==="group"&&(m.items.length||n.push("Every published group requires a Product"),a(m.items))}return a(t.items),n}var vi=e.strictObject({id:e.uuid(),offeringId:e.uuid(),version:e.number().int().positive(),document:C});var Oi={requestId:e.uuid(),sourceId:e.uuid(),expectedAvailable:j},Ai=e.discriminatedUnion("action",[e.strictObject({...Oi,action:e.enum(["add","subtract","set_remaining"]),amount:s}),e.strictObject({...Oi,action:e.literal("edit"),granted:s,expiresAt:e.iso.datetime({offset:!0}).nullable(),nextResetAt:e.iso.datetime({offset:!0}).nullable(),expectedRevision:e.number().int().nonnegative()})]),we=e.strictObject({sourceId:e.uuid(),available:j,held:j,spent:j,adjustmentGrantId:e.uuid().nullable()}),Pi=we.extend({granted:j,expiresAt:e.iso.datetime({offset:!0}).nullable(),nextResetAt:e.iso.datetime({offset:!0}).nullable(),revision:e.number().int().nonnegative()});var ji=e.discriminatedUnion("action",[e.object({action:e.literal("upsert"),externalId:e.string().min(1).max(128),name:e.string().trim().min(1).max(80)}).strict(),e.object({action:e.literal("archive"),entityId:e.uuid()}).strict()]),Ci=e.object({id:e.uuid(),externalId:e.string().min(1).max(128),name:e.string().min(1).max(80),archived:e.boolean()}).strict();var _i=e.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Ri=e.number().int().min(1).max(1e3),ie=e.object({cap:s.refine(t=>/[1-9]/.test(t)).nullable(),capPercentage:e.number().positive().max(1e4).nullable(),cycles:e.number().int().min(1).max(1200).nullable()}).strict().refine(t=>t.cap===null||t.capPercentage===null,"Choose a fixed or percentage cap");var v=e.iso.datetime({offset:!0}),wi=s.refine(t=>/[1-9]/.test(t)),Bi=e.strictObject({interval:_i.exclude(["lifetime"]),count:Ri}),jn=e.strictObject({action:e.literal("create"),requestId:e.uuid(),internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),amount:wi.nullable(),expiresAt:v.nullable(),reset:Bi.nullable(),rollover:ie.nullable(),nextResetAt:v.nullable()}).refine(t=>t.amount!==null||t.reset===null&&t.rollover===null,"Unlimited grants cannot reset or roll over").refine(t=>!t.rollover||t.reset!==null,"Rollover requires a recurring grant").refine(t=>t.nextResetAt===null||t.reset!==null&&(t.expiresAt===null||Date.parse(t.nextResetAt)<Date.parse(t.expiresAt)),"The first reset needs a reset interval and must precede expiry"),qi=e.discriminatedUnion("action",[jn,e.strictObject({action:e.literal("update"),requestId:e.uuid(),grantId:e.uuid(),revision:e.number().int().nonnegative(),amount:wi.nullable(),expiresAt:v.nullable(),rollover:ie.nullable(),nextResetAt:v.nullable()}),e.strictObject({action:e.enum(["add","subtract","set_remaining"]),requestId:e.uuid(),grantId:e.uuid(),revision:e.number().int().nonnegative(),amount:s}),e.strictObject({action:e.literal("revoke"),requestId:e.uuid(),grantId:e.uuid(),revision:e.number().int().nonnegative()})]),Be=e.strictObject({id:e.uuid(),internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),amount:s.nullable(),reset:Bi.nullable(),rollover:ie.nullable(),nextResetAt:v.nullable(),startsAt:v,expiresAt:v.nullable(),revision:e.number().int().nonnegative(),revoked:e.boolean(),available:p,held:p,spent:p}),Ti=e.strictObject({customerId:e.uuid(),after:e.uuid().nullable(),limit:e.number().int().min(1).max(100)}),ki=e.strictObject({rows:e.array(Be).max(100),nextCursor:e.uuid().nullable()});var O=e.iso.datetime({offset:!0}),x=e.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Cn=e.discriminatedUnion("kind",[e.object({kind:e.literal("absolute"),from:O,to:O}).strict(),e.object({kind:e.literal("last_days"),days:e.union([e.literal(1),e.literal(7),e.literal(30),e.literal(90)])}).strict(),e.object({kind:e.literal("billing_cycles"),membershipId:e.uuid(),count:e.number().int().min(1).max(12),includeCurrent:e.boolean()}).strict()]),zi=e.string().max(100).refine(t=>{if(t!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(t))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:t}),!0}catch{return!1}},"Use an IANA timezone"),_n=e.object({key:e.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:e.array(e.string().max(120)).min(1).max(20).refine(t=>new Set(t).size===t.length)}).strict(),A=e.object({range:Cn,timezone:zi,filterBy:e.array(_n).max(5).refine(t=>new Set(t.map(n=>n.key)).size===t.length),interval:e.enum(["hour","day","week","month"]),internal_feature_id:e.uuid().nullable(),entityId:e.uuid().nullable(),topN:e.number().int().min(1).max(50).nullable(),groupBy:e.union([e.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),e.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:e.object({bucket:O,group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid(),resourceId:e.uuid()}).strict().nullable(),limit:e.number().int().min(1).max(100)}).strict().superRefine((t,n)=>{if(t.range.kind!=="absolute"){t.interval==="hour"&&t.range.kind==="last_days"&&t.range.days>31&&n.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let a=Date.parse(t.range.to)-Date.parse(t.range.from);(a<=0||a>366*864e5||t.interval==="hour"&&a>31*864e5)&&n.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),Ui=e.object({from:O,to:O,interval:e.enum(["hour","day","week","month"]),timezone:zi,rows:e.array(e.object({bucket:O,group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid(),resourceId:e.uuid(),consumedUnits:x,refundedUnits:x,reservedUnits:x,charged:x,refunded:x,reserved:x,netUnits:x,netCharged:x}).strict()).max(100),nextCursor:e.object({bucket:O,group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid(),resourceId:e.uuid()}).strict().nullable()}).strict();var _=e.string().regex(/^(0|[1-9]\d{0,29})$/),Mi=e.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),qe=e.strictObject({bucket:e.iso.datetime({offset:!0}),group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid()}),Ei=e.strictObject({...A.shape,groupBy:e.union([e.enum(["customer","entity","entitlement"]),e.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:qe.nullable()}).superRefine((t,n)=>{let a=A.safeParse({...t,after:null});if(!a.success)for(let o of a.error.issues)n.addIssue({code:"custom",path:o.path,message:o.message})}),Gi=e.strictObject({from:e.iso.datetime({offset:!0}),to:e.iso.datetime({offset:!0}),interval:A.shape.interval,timezone:A.shape.timezone,rows:e.array(e.strictObject({...qe.shape,eventCount:_,units:Mi,tokenEventCount:_,tokens:e.strictObject(Object.fromEntries(zt.map(t=>[t,_]))),totalTokens:_,providerCostEventCount:_,providerCostUsd:Mi,invalidTelemetryEventCount:_})).max(100),nextCursor:qe.nullable()});var Di=e.object({requestId:e.uuid(),items:e.array(e.object({customerId:e.uuid(),command:B.options[1]}).strict()).min(1).max(1e3)}).strict().refine(t=>new Set(t.items.map(n=>n.customerId+":"+n.command.idempotencyKey)).size===t.items.length,"Each logical event must appear once in a batch"),$i=e.object({batchId:e.uuid(),after:e.number().int().min(-1).max(999),limit:e.number().int().min(1).max(100)}).strict(),Li=e.object({batchId:e.uuid(),status:e.enum(["queued","complete"]),total:e.number().int().min(1).max(1e3),processed:e.number().int().min(0).max(1e3),items:e.array(e.object({position:e.number().int().min(0).max(999),customerId:e.uuid(),idempotencyKey:e.string().min(1).max(120),status:e.enum(["queued","accepted","rejected","failed"]),receipt:q.nullable(),errorCode:e.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(t=>t.status==="queued"?t.receipt===null&&t.errorCode===null:t.status==="failed"?t.receipt===null&&t.errorCode!==null:t.receipt!==null&&t.errorCode===null&&t.receipt.accepted===(t.status==="accepted"))).max(100),nextAfter:e.number().int().min(0).max(999).nullable()}).strict();var Rn=e.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Fi=e.enum(["draft","active","paused","archived"]),Ni=e.string().min(1).max(256),Vi=e.array(Ni).max(50).refine(t=>new Set(t).size===t.length,"Duplicate products"),wn=e.strictObject({duration:e.enum(["day","week","month","year"]),length:e.number().int().min(1).max(3660)}),Bn=e.strictObject({internal_feature_id:e.uuid(),allowance:e.number().nonnegative().max(1e15).nullable(),expiry:wn.nullable()}),qn=e.discriminatedUnion("type",[e.strictObject({type:e.literal("feature_grant"),grants:e.array(Bn).min(1).max(100).refine(t=>new Set(t.map(n=>n.internal_feature_id)).size===t.length,"Duplicate entitlement grants")}),e.strictObject({type:e.literal("free_product"),productId:Ni,duration:y}),e.strictObject({type:e.literal("invoice_credits"),amount:e.number().positive().max(1e8),duration:y,rollover:e.boolean(),productIds:Vi})]),Tn=e.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),Qi=e.object({key:Tn,name:e.string().trim().min(1).max(80),configuration:qn}).strict(),Zi=e.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Te=e.object({code:Zi,maxUses:e.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:e.boolean()}).strict(),Ki=e.object({key:e.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:e.string().trim().min(1).max(80),rewardId:e.uuid(),redeemOn:e.enum(["customer_creation","checkout"]),receivedBy:e.enum(["referrer","all"]),maxRedemptions:e.number().int().min(1).max(1e6).nullable(),productIds:Vi,excludeTrial:e.boolean()}).strict().refine(t=>t.redeemOn==="checkout"||t.productIds.length===0&&!t.excludeTrial,"Purchase restrictions require checkout trigger"),Wi={id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),revision:e.number().int().nonnegative(),status:Fi,createdAt:e.iso.datetime({offset:!0}),updatedAt:e.iso.datetime({offset:!0})},kn=Qi.extend(Wi).strict(),zn=Ki.safeExtend(Wi).strict(),Rs=e.strictObject({id:e.uuid(),key:e.string(),name:e.string(),type:Rn,status:Fi,ended:e.boolean()}),ws=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),input:Qi}).strict(),e.object({action:e.enum(["activate","pause","resume","archive","delete"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Bs=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),input:Ki}).strict(),e.object({action:e.enum(["activate","pause","resume","archive","delete"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Hi=e.object({id:e.uuid(),rewardId:e.uuid(),programId:e.uuid().nullable(),customerId:e.uuid(),referrerId:e.uuid().nullable(),status:e.enum(["pending","applied","unavailable"]),result:e.record(e.string(),e.unknown()).nullable(),createdAt:e.iso.datetime({offset:!0})}).strict(),Xi=e.object({code:Zi,requestId:e.uuid()}).strict(),Ji=e.strictObject({redemptionId:e.uuid(),currency:c,requestId:e.uuid(),accepted:e.literal(!0)}),Un=e.strictObject({type:e.literal("checkout"),orderId:e.uuid(),productVersionId:e.uuid(),currency:c,duration:y,renewalAmountMinor:e.number().int().positive().max(1e8),status:e.enum(["created","pending","trialing","paid","cancelled","failed"]),url:e.url().nullable()}),Yi=e.discriminatedUnion("type",[Un,e.strictObject({type:e.literal("subscription"),operationId:e.uuid(),membershipId:e.uuid(),productVersionId:e.uuid(),currency:c,duration:y,renewalAmountMinor:e.number().int().positive().max(1e8),status:e.enum(["pending","running","applied","failed"])})]),er=e.object({programId:e.uuid(),requestId:e.uuid()}).strict(),tr=e.object({id:e.uuid(),programId:e.uuid(),code:Te.shape.code,createdAt:e.iso.datetime({offset:!0})}).strict(),qs=e.object({rows:e.array(kn).max(100),nextCursor:e.uuid().nullable()}).strict(),Ts=e.object({rows:e.array(zn).max(100),nextCursor:e.uuid().nullable()}).strict(),Mn=Te.extend({id:e.uuid(),redemptions:e.number().int().nonnegative()}).strict(),En=e.strictObject({id:e.uuid(),programId:e.uuid().nullable(),customerId:e.uuid().nullable(),referrerId:e.uuid().nullable(),code:e.string().nullable(),status:e.enum(["pending","triggered","applied"]),createdAt:e.iso.datetime({offset:!0})}),ks=e.object({codes:e.array(Mn).max(100),redemptions:e.array(En).max(100),customers:e.record(e.uuid(),e.string()),codesCursor:e.uuid().nullable(),redemptionsCursor:e.uuid().nullable()}).strict(),zs=e.discriminatedUnion("action",[e.object({action:e.literal("create"),rewardId:e.uuid(),revision:e.number().int().nonnegative(),input:Te}).strict(),e.object({action:e.literal("remove"),rewardId:e.uuid(),revision:e.number().int().nonnegative(),codeId:e.uuid()}).strict()]);var rr=e.object({customerId:e.uuid()}).strict(),nr=e.discriminatedUnion("action",[e.object({customerId:e.uuid(),requestId:e.uuid(),action:e.literal("assign"),poolId:e.uuid(),memberCustomerId:e.uuid()}).strict(),e.strictObject({customerId:e.uuid(),requestId:e.uuid(),action:e.literal("assign_entity"),poolId:e.uuid(),entityId:e.uuid()}),e.object({customerId:e.uuid(),requestId:e.uuid(),action:e.literal("release"),poolId:e.uuid(),slotId:e.uuid()}).strict()]),U=e.number().int().nonnegative(),ke=e.iso.datetime({offset:!0}),ze=e.strictObject({internalId:e.uuid(),id:e.string(),name:e.string().nullable(),version:e.number().int().positive()}),ir=e.enum(["active","past_due"]),Ue=e.strictObject({customerId:e.uuid(),licenses:e.array(e.strictObject({id:e.uuid(),linkId:e.uuid(),parent:e.strictObject({customerProductId:e.uuid(),status:ir,product:ze}),product:ze,planLicense:e.strictObject({id:e.uuid(),prepaidOnly:e.boolean(),isCustom:e.boolean()}).nullable(),granted:U,included:U,paidQuantity:U,usage:U,remaining:U,createdAt:ke}).refine(t=>t.granted===t.included+t.paidQuantity&&t.granted===t.usage+t.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:e.array(e.strictObject({id:e.uuid(),linkId:e.uuid(),status:ir,product:ze,entity:e.strictObject({internalId:e.uuid(),id:e.string().nullable(),name:e.string().nullable()}).nullable(),beneficiary:e.strictObject({internalId:e.uuid(),id:e.string().nullable(),name:e.string().nullable()}).nullable(),startedAt:ke.nullable(),endedAt:ke.nullable()}).refine(t=>t.entity!==null||t.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:e.boolean()});var ur=e.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Me=e.string().regex(/^(0|[1-9]\d{0,14})$/),R=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Gn=e.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),M=Gn,b=s.refine(t=>/[1-9]/.test(t)),u=e.iso.datetime({offset:!0}),re=t=>{let[n,a=""]=t.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*1000000n+BigInt(a.padEnd(6,"0"))},Dn=e.array(e.object({upTo:b.nullable(),unitAmountMinor:ur,flatAmountMinor:e.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(t=>{try{return t.at(-1)?.upTo===null&&t.slice(0,-1).every((n,a)=>{let o=t[a-1]?.upTo;return n.upTo!==null&&(a===0||o!=null&&re(n.upTo)>re(o))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),$n=e.discriminatedUnion("kind",[e.object({kind:e.literal("flat"),units:b,unitAmountMinor:ur}).strict(),e.object({kind:e.enum(["graduated","volume"]),units:b,tiers:Dn}).strict()]).refine(t=>t.kind==="flat"||!t.tiers.some(n=>(n.flatAmountMinor??0)>0)||t.kind==="volume"&&t.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),Ln=e.strictObject({interval:e.enum(["month","year"]),count:e.number().int().min(1).max(12),anchor:e.enum(["membership","calendar"])}),E=e.object({currency:c,pricing:$n,billingCycle:Ln.optional()}).strict().refine(t=>t.pricing.kind!=="volume"||t.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var ar={requestId:e.uuid(),productVersionId:e.uuid(),internal_feature_id:e.uuid(),currency:c},dr=e.strictObject({interval:e.enum(["hour","day","week","month"]),intervalCount:e.number().int().min(1).max(12),limit:e.number().int().min(1).max(1e6)}),mr=e.discriminatedUnion("kind",[e.object({...ar,kind:e.literal("auto_topup"),threshold:oe,quantity:b.refine(t=>Number(t)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:dr.optional()}).strict(),e.object({...ar,kind:e.literal("postpaid"),maxAmountMinorPerPeriod:M,maxOutstandingMinor:M}).strict()]),sr={productVersionId:e.uuid(),internal_feature_id:e.uuid(),currency:c},pr=e.discriminatedUnion("kind",[e.object({...sr,kind:e.literal("auto_topup"),threshold:oe,quantity:b.refine(t=>Number(t)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:dr.optional(),purchaseAmountMinor:M,purchaseUnits:b}).strict(),e.object({...sr,kind:e.literal("postpaid"),maxAmountMinorPerPeriod:M,maxOutstandingMinor:M,cashPrice:E}).strict().refine(t=>t.cashPrice.currency===t.currency,"Currency must match")]),ne=e.object({id:e.uuid(),terms:pr,status:e.enum(["prepared","active","revoked","blocked"]),createdAt:u,acceptedAt:u.nullable(),effectiveAt:u.nullable(),revokedAt:u.nullable()}).strict().refine(t=>(t.status==="prepared"?t.acceptedAt===null:!0)&&(t.status==="active"?t.acceptedAt!==null&&t.effectiveAt!==null:!0)&&(t.status==="revoked"?t.revokedAt!==null:t.revokedAt===null),"Authorization consent and revocation must be explicit"),lr=e.object({authorizationId:e.uuid(),terms:pr,setupUrl:e.url().nullable()}).strict(),gr=e.object({authorizationId:e.uuid(),accepted:e.literal(!0)}).strict(),hr=e.object({authorizationId:e.uuid(),requestId:e.uuid()}).strict(),fr=e.object({internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),interval:e.enum(["day","week","month","year"]),anchor:e.enum(["billing_cycle","utc"]).optional(),basis:e.enum(["usage","credits"]),filter:h.optional(),limit:s.nullable(),thresholds:e.array(e.number().positive().max(1)).max(8),includedThresholds:e.array(e.number().positive().max(1)).max(8).optional(),absoluteThresholds:e.array(b).max(8).optional()}).strict().refine(t=>t.thresholds.every((n,a)=>{let o=t.thresholds[a-1];return a===0||o!==void 0&&n>o})&&(t.includedThresholds??[]).every((n,a,o)=>{let m=o[a-1];return a===0||m!==void 0&&n>m})&&(t.absoluteThresholds??[]).every((n,a,o)=>{let m=o[a-1];return a===0||m!==void 0&&re(n)>re(m)}),"Notification thresholds must increase"),Fn=fr.safeExtend({requestId:e.uuid()}),or={control:e.literal("overage"),requestId:e.uuid(),internal_feature_id:e.uuid(),entityId:e.uuid().nullable()},Nn=e.discriminatedUnion("action",[e.strictObject({...or,action:e.literal("set"),allowed:e.boolean().nullable(),overageLimit:s.nullable(),skipOverageBilling:e.boolean()}),e.strictObject({...or,action:e.literal("remove")})]),br=e.union([Fn,Nn]),Vn=e.strictObject({internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),allowed:e.boolean().nullable(),overageLimit:s.nullable(),skipOverageBilling:e.boolean(),interval:e.enum(["day","week","month","year"]),startsAt:u,endsAt:u,used:e.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:e.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:e.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Qn=e.object({internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),interval:e.enum(["day","week","month","year"]),anchor:e.enum(["billing_cycle","utc"]).optional(),basis:e.enum(["usage","credits"]),filter:h.optional(),startsAt:u,endsAt:u,used:p,reserved:p,limit:s.nullable(),thresholds:e.array(e.number().positive().max(1)).max(8),notifiedThresholds:e.array(e.number().positive().max(1)).max(1024),includedThresholds:e.array(e.number().positive().max(1)).max(8).optional(),includedAllowance:e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:e.array(e.number().positive().max(1)).max(1024).optional(),absoluteThresholds:e.array(b).max(8).optional(),notifiedAbsoluteThresholds:e.array(b).max(1024).optional()}).strict().refine(t=>t.basis!=="usage"||s.safeParse(t.used).success&&s.safeParse(t.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Zn=e.object({authorizationId:e.uuid(),status:e.enum(["idle","pending","blocked"]),taskId:e.uuid().nullable(),invoiceId:e.uuid().nullable(),hostedInvoiceUrl:e.url().nullable(),purchaseCount:e.number().int().nonnegative(),purchaseWindowEndsAt:u.nullable(),attemptCount:e.number().int().nonnegative(),failedAttemptCount:e.number().int().nonnegative(),suspendedAt:u.nullable(),nextAttemptAt:u.nullable(),failureReason:e.string().min(1).max(240).nullable()}).strict(),xr=e.object({internal_feature_id:e.uuid().optional(),entityId:e.uuid().optional()}).strict(),Ee=e.object({authorizations:e.array(ne).max(100),limits:e.array(fr).max(100),overages:e.array(Vn).max(100).optional(),windows:e.array(Qn).max(200),autoTopups:e.array(Zn).max(100),limited:e.boolean()}).strict(),Kn=e.object({id:e.uuid(),internal_feature_id:e.uuid(),productVersionId:e.uuid(),authorizationId:e.uuid(),entityId:e.uuid().nullable(),units:s,amountMinor:R,cashPrice:E}).strict(),G=e.object({id:e.uuid(),sourceKind:e.enum(["product","usage","manual"]),providerInvoiceId:e.string().min(1).max(240).nullable(),status:e.enum(["accruing","open","pending","paid","failed","void"]),currency:c,startsAt:u.nullable(),endsAt:u.nullable(),amountMinor:e.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:e.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Me,paidAmountMinor:Me,refundedAmountMinor:Me,createdAt:u,hostedInvoiceUrl:e.url().nullable(),adjustment:e.object({originalInvoiceId:e.uuid(),amountMinor:e.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(t=>t!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(t)&&BigInt(t)>=-200000000n&&BigInt(t)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:u.nullable(),reason:e.string().min(1).max(500).optional()}).strict().nullable(),lines:e.array(Kn).max(100),linesLimited:e.boolean()}).strict(),Sr=e.object({invoiceId:e.uuid(),accepted:e.literal(!0)}).strict(),yr=e.strictObject({requestId:e.uuid(),originalInvoiceId:e.uuid(),amountMinor:e.string().regex(/^[1-9]\d{0,8}$/).refine(t=>/^[1-9]\d{0,8}$/.test(t)&&BigInt(t)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:e.string().trim().min(1).max(500)}),Ir=e.object({after:e.uuid().nullable(),limit:e.number().int().min(1).max(100)}).strict(),vr=e.object({rows:e.array(G).max(100),nextCursor:e.uuid().nullable()}).strict(),cr=e.strictObject({id:e.string(),coupon:e.string(),start:e.number().nonnegative(),end:e.number().nullable()}),Wn=e.strictObject({subscriptionId:e.string(),customerId:e.string(),accountId:e.string(),sourceItems:e.array(e.strictObject({id:e.string(),price_id:e.string(),quantity:e.number().int(),discounts:e.array(cr).optional()})).max(100),items:e.array(e.strictObject({id:e.string(),price:e.string(),quantity:e.number().int(),discounts:e.array(e.strictObject({coupon:e.string().optional(),terms:e.strictObject({id:e.string(),name:e.string().optional(),percent_off:e.number().optional(),amount_off:e.number().optional(),currency:e.string().optional(),duration:e.enum(["once","forever","repeating"]),duration_in_months:e.number().optional()}).optional(),discount:e.string().optional(),receipt:cr.optional()})).max(20)})).max(100)}),Or=e.strictObject({membershipId:e.uuid(),requestId:e.uuid(),grantIds:e.array(e.uuid()).max(20).refine(t=>new Set(t).size===t.length,"Duplicate Coupon grants")}),Ar=e.strictObject({membershipId:e.uuid(),operationId:e.uuid(),status:e.enum(["pending","effective"]),execution:Wn.nullable(),grants:e.array(e.strictObject({id:e.uuid(),couponId:e.uuid(),name:e.string(),discount:nt,duration:y,startedAt:u.nullable()})).max(20)});var l={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},D=t=>new Set(t).size===t.length,Ge=e.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),Hn=e.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(t=>!t.split("/").some(n=>n==="."||n==="..")),$=e.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(t=>!t.includes("..")&&!t.endsWith(".")&&!t.split("/").some(n=>!n||n.startsWith(".")||n.endsWith(".lock"))),Xn=e.string().min(1).max(512).refine(t=>!/[\\\u0000-\u001f\u007f]/.test(t)&&!t.startsWith("/")&&!t.split("/").some(n=>!n||n==="."||n==="..")),Pr=e.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(t=>!t.startsWith("/")&&!t.split("/").some(n=>!n||n==="."||n===".."));var jr=e.strictObject({id:e.uuid(),repo:Hn,platform:e.enum(["github","gitlab","bitbucket"]),branches:e.array($).min(1).max(4).refine(D),workflow:e.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:e.array(e.uuid()).min(1).max(4).refine(D),include:e.array(Pr).min(1).max(16),exclude:e.array(Pr).max(16),methods:e.array(e.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(D),maxAgeHours:e.number().int().min(1).max(720)}),Cr=jr.extend({revision:e.number().int().positive()}),Qs=e.strictObject({repository:jr,expectedRevision:e.number().int().min(0)}).refine(({repository:t})=>t.platform==="gitlab"||t.repo.split("/").length===2,{path:["repository","repo"]}),_r=e.strictObject({repositoryId:e.uuid(),branch:$}),Jn=e.array(Ge).max(l.keys).refine(D),Rr=e.strictObject({repository:Cr.omit({keyIds:!0}),branch:$,keys:Jn,keySetHash:e.string().regex(/^[a-f0-9]{64}$/)}),Yn=e.strictObject({filePath:Xn,startingLineNumber:e.number().int().min(1).max(1e7)}),De=e.strictObject({protocol:e.literal(1),repositoryId:e.uuid(),branch:$,workflow:e.string().max(200),configurationRevision:e.number().int().positive(),keySetHash:e.string().regex(/^[a-f0-9]{64}$/),commit:e.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:e.uuid(),runNumber:e.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:e.number().int().min(1).max(1e4),scannerVersion:e.literal("1"),scannedAt:e.iso.datetime({offset:!0}),coverage:e.strictObject({complete:e.literal(!0),files:e.number().int().min(0).max(l.files),sourceBytes:e.number().int().min(0).max(l.sourceBytes),unresolvedCalls:e.number().int().min(0).max(1e6),unsupportedFiles:e.number().int().min(0).max(l.files)}),features:e.array(e.strictObject({key:Ge,refs:e.array(Yn).max(l.referencesPerKey)})).max(l.keys)}).superRefine((t,n)=>{D(t.features.map(a=>a.key))||n.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),t.features.reduce((a,o)=>a+o.refs.length,0)>l.references&&n.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),$e=e.strictObject({scanId:e.uuid(),commit:e.string(),receivedAt:e.string(),references:e.number().int().nonnegative(),removedReferences:e.number().int().nonnegative()}),ea=$e.extend({repositoryId:e.uuid(),branch:$,workflow:e.string(),digest:e.string(),configurationRevision:e.number().int().positive(),runNumber:e.number().int().positive(),runAttempt:e.number().int().positive(),scannedAt:e.string(),keySetHash:e.string(),coverage:De.shape.coverage}),ta=e.strictObject({repositories:e.array(Cr).max(l.repositories),scans:e.array(ea).max(l.repositories*l.branches)}),ia=e.strictObject({key:Ge,references:e.number().int().nonnegative(),coveredTargets:e.number().int().nonnegative(),expiredTargets:e.number().int().nonnegative(),uncertainTargets:e.number().int().nonnegative()}),Zs=e.strictObject({available:e.boolean().default(!0),settings:ta,expectedTargets:e.number().int().min(0).max(80),features:e.array(ia).max(2001),truncated:e.boolean()});var g=e.iso.datetime({offset:!0}),wr=e.strictObject({invoiceId:e.uuid(),after:e.string().min(1).max(180).nullable(),limit:e.number().int().min(1).max(100)}),ra=e.strictObject({kind:e.literal("product"),key:e.string(),productVersionId:e.uuid(),productName:e.string(),itemKey:e.string(),entityId:e.uuid().nullable(),quantity:e.number().positive(),subtotalMinor:e.string().regex(/^-?\d+$/),discountMinor:e.string().regex(/^\d+$/),taxMinor:e.string().regex(/^-?\d+$/).nullable(),totalMinor:e.string().regex(/^-?\d+$/),startsAt:g.nullable(),endsAt:g.nullable(),providerLineId:e.string().nullable(),providerItemId:e.string()}),Br=e.strictObject({invoice:G,items:e.array(e.discriminatedUnion("kind",[ra,e.strictObject({kind:e.literal("invoice_credit"),key:e.string(),internal_feature_id:e.uuid(),internal_credit_feature_id:e.uuid(),name:e.string(),units:s,reserved:s,amountMinor:R,grossAmountMinor:R,creditsAppliedMinor:R,properties:h,cashPrice:E,providerItemId:e.string().nullable(),creditProviderItemId:e.string().nullable()}),e.strictObject({kind:e.literal("usage"),key:e.string(),internal_feature_id:e.uuid(),name:e.string(),units:s,reserved:s,amountMinor:R,cashPrice:E})])).max(100),nextCursor:e.string().min(1).max(180).nullable()}),na=e.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(t=>!/^\-0(?:\.0+)?$/.test(t)),Le=e.strictObject({from:g,to:g,entityId:e.uuid().optional(),snapshotAt:g.nullable(),after:e.strictObject({at:g,id:e.uuid(),position:e.number().int().nonnegative()}).nullable(),limit:e.number().int().min(1).max(100)}).refine(t=>Date.parse(t.from)<Date.parse(t.to)&&Date.parse(t.to)-Date.parse(t.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(t=>t.after===null||t.snapshotAt!==null,"A cursor requires the original snapshot time"),qr=e.strictObject({customerId:e.uuid(),entityId:e.uuid().nullable(),from:g,to:g,snapshotAt:g,totals:e.array(e.strictObject({internal_credit_feature_id:e.uuid(),name:e.string(),consumed:p,refunded:p,net:na})).max(1e3),rows:e.array(e.strictObject({operationId:e.uuid(),position:e.number().int().nonnegative(),kind:e.enum(["consume","confirm","refund"]),originalId:e.uuid().nullable(),occurredAt:g,internal_feature_id:e.uuid(),entitlementName:e.string(),sourceId:e.uuid(),internal_credit_feature_id:e.uuid(),creditName:e.string(),units:yt,amount:p,pricing:e.array(St).max(12),properties:h})).max(100),nextCursor:Le.shape.after});var d=e.string().min(1).max(200),ae=e.iso.datetime({offset:!0}),L=e.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Fe=e.number().int().min(0).max(1e12),zr=e.number().int().min(1).max(1e12),Tr={...f,type:e.literal("coupon.redeemed"),grantId:e.uuid()},kr={...f,type:e.literal("usage.observed"),merchantTransactionId:d,resource:d,unit:d,quantity:zr},aa=e.strictObject({...f,type:e.literal("fulfillment.updated"),operationId:e.uuid(),merchantFulfillmentId:d,status:e.enum(["pending","applied","failed"])}),sa=e.strictObject({...f,type:e.literal("benefit.claimed"),merchantBenefitId:d,resource:d,unit:d,quantity:zr,expiresAt:ae.nullable(),revision:L}),oa=e.strictObject({...f,type:e.literal("benefit.closed"),merchantBenefitId:d,status:e.enum(["failed","expired","canceled"]),revision:L}),ca=e.strictObject({...f,type:e.literal("benefit.updated"),merchantBenefitId:d,status:e.enum(["active","expired","revoked"]),remainingQuantity:Fe.nullable(),expiresAt:ae.nullable(),revision:L}),ua=e.strictObject({...f,type:e.literal("authorization.updated"),merchantAuthorizationId:d,kind:e.literal("auto_topup"),status:e.enum(["pending","effective","revoked","failed"]),termsReference:d.nullable(),revision:L}),da=e.strictObject({...f,type:e.literal("balance.observed"),resource:d,unit:d,availableQuantity:Fe,reservedQuantity:Fe,periodStartsAt:ae.nullable(),periodEndsAt:ae.nullable(),revision:L}),Ur=e.union([e.discriminatedUnion("type",[...He,aa,sa,oa,ca,ua,da]),e.strictObject({...Tr,productVersionId:e.uuid(),subscriptionId:e.string().trim().min(1).max(255)}),e.strictObject({...Tr,merchandiseId:e.uuid()}),e.strictObject({...kr,operation:e.literal("consume")}),e.strictObject({...kr,operation:e.literal("reverse"),reversalOf:d})]),Mr=e.strictObject({id:e.uuid(),eventId:e.string().min(1).max(200),source:e.literal("merchant"),providerVerified:e.literal(!1),outcome:e.string().min(1).max(100)});var Er=st,pa=Er.extend({invoice_id:Er.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),Ne=e.strictObject({name:e.string().trim().min(1).max(255),memo:e.string().max(1e4).nullable().optional(),footer:e.string().max(1e4).nullable().optional(),net_terms_days:e.number().int().positive().nullable().optional()}),la=Ne.extend({id:e.string().min(1).max(255),created_at:e.number().nullable()}),Gr=e.strictObject({items:e.array(la).max(50),nextCursor:e.uuid().nullable()}),so=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),requestId:e.uuid(),values:Ne}),e.strictObject({action:e.literal("update"),id:e.string().min(1).max(255),values:Ne}),e.strictObject({action:e.literal("delete"),id:e.string().min(1).max(255)})]),Dr=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),requestId:e.uuid(),params:P}),e.strictObject({action:e.enum(["finalize","send","pay","void"]),requestId:e.uuid(),invoiceId:e.uuid()}),e.strictObject({action:e.literal("reissue"),requestId:e.uuid(),invoiceId:e.uuid(),params:pa})]),Ve=e.strictObject({id:e.uuid(),customerId:e.uuid(),providerInvoiceId:e.string().nullable(),status:e.enum(["draft","open","paid","void","uncollectible"]),currency:e.string(),totalMinor:e.string().regex(/^-?\d+$/),paidMinor:e.string().regex(/^\d+$/),refundedMinor:e.string().regex(/^\d+$/),hostedInvoiceUrl:e.url().nullable(),createdAt:e.number(),collectionMethod:e.enum(["send_invoice","charge_automatically"]).nullable()}),$r=Ve.extend({lines:e.array(e.strictObject({id:e.uuid(),description:e.string(),amountMinor:e.string().regex(/^-?\d+$/),netAmountMinor:e.string().regex(/^-?\d+$/),quantity:e.number().nullable(),periodStart:e.number().nullable(),periodEnd:e.number().nullable()})).max(1e3)}),w=e.strictObject({taskId:e.uuid(),status:e.enum(["ready","running","done","dead"]),invoice:Ve.nullable(),errorCode:e.string().nullable()}),Lr=e.strictObject({items:e.array(Ve).max(50),nextCursor:e.uuid().nullable(),operations:e.array(w).max(50),operationsLimited:e.boolean()});var ga=e.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Fr={scope:se,permissions:e.array(ga),expiresAt:e.iso.datetime().nullable()},ec=e.discriminatedUnion("kind",[e.object({...Fr,kind:e.literal("server"),keyId:e.string().min(1)}),e.object({...Fr,kind:e.literal("customer"),customerId:e.string().min(1),identityKind:e.enum(["identified","guest"]),expiresAt:e.iso.datetime()})]),r=e.object({requestId:e.uuid(),scope:se}).strict(),ha=Ct.safeExtend({fingerprint:he.optional()}).strict(),fa=r.extend({customer:Q,created:e.boolean()});function Nr(){return r.extend({offer:ue.nullable(),reason:at.nullable()})}var i={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Nt,response:r.extend({message:e.object({messageId:e.uuid(),channel:T,acceptedAt:e.iso.datetime({offset:!0}),status:e.enum(["accepted","sending","completed","canceled"]),replayed:e.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:e.strictObject({messageId:e.uuid()}),response:r.extend({message:e.object({id:e.uuid(),channel:T,status:e.enum(["accepted","sending","completed","canceled"]),deliveries:e.array(e.object({id:e.uuid(),status:Qt,attempts:e.number().int().nonnegative(),receipts:e.array(e.object({kind:Zt,occurredAt:e.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Ut,response:r.extend({installation:Z})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Mt,response:r.extend({installation:Z})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:Et,response:r.extend({installation:Z})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:e.strictObject({channel:T}),response:r.extend({preference:fe})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Vt,response:r.extend({preference:fe})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:e.strictObject({cursor:e.uuid().optional()}),response:r.extend({templates:Gr})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:e.strictObject({customerId:e.uuid(),params:P}),response:r.extend({preview:de})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:e.strictObject({customerId:e.uuid(),requestId:e.uuid(),params:P}).refine(t=>t.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:r.extend({operation:w})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:e.strictObject({customerId:e.uuid(),command:Dr}).refine(t=>t.command.action!=="create"||t.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:r.extend({operation:w})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:e.strictObject({customerId:e.uuid(),taskId:e.uuid()}),response:r.extend({operation:w})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:e.strictObject({customerId:e.uuid(),cursor:e.uuid().optional()}),response:r.extend({invoices:Lr})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:e.strictObject({customerId:e.uuid(),invoiceId:e.uuid()}),response:r.extend({invoice:$r})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:_r,response:r.extend({config:Rr})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:De,response:r.extend({receipt:$e})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:e.strictObject({}),response:r.extend({payload:gt})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:ht,response:r.merge(ft)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:bt,response:r.merge(xt)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:e.strictObject({customerId:e.uuid(),sourceId:e.uuid()}),response:r.extend({balance:Pi})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:e.strictObject({customerId:e.uuid(),command:Ai}),response:r.extend({balance:we})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:e.strictObject({internal_feature_id:e.uuid(),customerId:e.uuid().optional(),entityId:e.uuid().optional()}).refine(t=>!t.entityId||!!t.customerId,"Entity pricing requires a customer"),response:r.extend({internal_feature_id:e.uuid(),config:Pe,model_markups:te})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:e.strictObject({customerId:e.uuid(),query:vt}),response:r.extend({usage:ge})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:e.strictObject({customerId:e.uuid(),command:Ot}),response:r.extend({usage:ge})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:e.strictObject({customerId:e.uuid(),command:qi}),response:r.extend({grant:Be})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Ti,response:r.extend({grants:ki})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:e.union(ci.options.map(t=>t.extend({customerId:e.uuid().optional(),customerToken:e.string().regex(We).optional()}))),response:r.extend({operation:ui})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Xt.extend({customerId:e.uuid().optional()}),response:r.extend({setup:Ie})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Jt.extend({customerId:e.uuid().optional()}),response:r.extend({setup:Ie})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Kt.safeExtend({customerId:e.uuid()}),response:r.extend({batch:k})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:K.extend({customerId:e.uuid()}),response:r.extend({batch:k})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:K.extend({customerId:e.uuid()}),response:r.extend({batch:k})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:K.extend({customerId:e.uuid()}),response:r.extend({batch:k})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:e.discriminatedUnion("action",[W.options[0].extend({customerId:e.uuid()}),W.options[1].extend({customerId:e.uuid()}),W.options[2].extend({customerId:e.uuid()})]),response:r.extend({trial:ye})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Wt.extend({customerId:e.uuid()}),response:r.extend({trial:ye})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:J,response:r.extend({subscriptions:ai})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:J,response:r.extend({purchases:si})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:ii,response:r.extend({conflicts:oi})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:ri,response:r.extend({resolution:ni})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:ei,response:r.extend({verification:ti})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:ot.safeExtend({...V,customerId:e.uuid().optional()}),response:r.extend({quote:ct})},recordMerchantEvent:{replay:"immutable_event",method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:Ur,response:r.extend({record:Mr})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:I.extend({customerId:e.uuid().optional(),intent:e.enum(["confirm","cancel"]).optional(),merchantConfirmation:N.optional()}),response:r.extend({operation:me})},readSubscriptionOperation:{replay:"read",method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:I.extend({customerId:e.uuid().optional()}),response:r.extend({operation:me})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:ut.safeExtend({customerId:e.uuid().optional()}),response:r.extend({quote:mt})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:I.extend({customerId:e.uuid().optional(),intent:e.enum(["confirm","cancel"]).optional(),merchantConfirmation:N.optional()}),response:r.extend({operation:pe})},readSubscriptionUpdate:{replay:"read",method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:I.extend({customerId:e.uuid().optional()}),response:r.extend({operation:pe})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:pt.safeExtend({customerId:e.uuid()}),response:r.extend({quote:lt})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:I.extend({customerId:e.uuid(),merchantConfirmation:N.optional()}),response:r.extend({operation:le})},readRefund:{replay:"read",method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:I.extend({customerId:e.uuid()}),response:r.extend({operation:le})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:xr,response:r.extend({controls:Ee})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:mr,response:r.extend({prepared:lr})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:gr,response:r.extend({authorization:ne})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Or,response:r.extend({coupons:Ar})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:hr,response:r.extend({authorization:ne})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Ir,response:r.extend({invoices:vr})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:yr.extend({customerId:e.uuid()}),response:r.extend({operation:w})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Sr,response:r.extend({invoice:G})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:e.object({customerId:e.uuid(),command:br}).strict(),response:r.extend({controls:Ee})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:e.object({customerId:e.uuid(),command:ji}).strict(),response:r.extend({entity:Ci})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:e.strictObject({customerId:e.uuid().nullable(),query:Ei}),response:r.extend({analytics:Gi})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:e.object({customerId:e.uuid().nullable(),query:A}).strict(),response:r.extend({analytics:Ui})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Di,response:r.extend({batchId:e.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:$i,response:r.extend({batch:Li})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Ye.extend({customerId:e.string().min(1).optional()}),response:r.extend({check:ce})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:e.strictObject({kind:tt,selector:e.discriminatedUnion("type",[e.strictObject({type:e.literal("resource"),id:e.uuid()}),e.strictObject({type:e.literal("version"),id:e.uuid()})]),customerId:e.string().min(1).optional()}),response:r.extend({content:it})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Tt,response:r.extend({paywall:kt})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:e.strictObject({processContext:rt.optional(),...V,selector:Ii,customerId:e.string().min(1).optional(),commerce:Xe,requirement:Je.optional()}),response:r.extend({offering:vi,candidates:e.array(et).max(20),availability:e.array(e.strictObject({productVersionId:e.uuid(),available:e.boolean(),reason:e.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:ce.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:e.object({customerId:e.uuid().optional(),entityId:e.uuid().optional()}).strict(),response:r.extend({holdings:At})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:e.object({customerId:e.uuid().optional(),query:Pt}).strict(),response:r.extend({ledger:jt})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:wr.extend({customerId:e.uuid().optional()}),response:r.extend({detail:Br})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Le.safeExtend({customerId:e.uuid().optional()}),response:r.extend({statement:qr})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:e.object({customerId:e.uuid().optional(),command:B.options[0]}).strict(),response:r.extend({quote:It})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:e.strictObject({customerId:e.uuid(),command:e.union([e.strictObject({eventName:e.string().min(1),quantity:s.optional(),properties:h.optional(),entityId:e.uuid().optional(),idempotencyKey:e.string().min(1).max(120)}),e.strictObject({internal_feature_id:e.uuid(),quantity:s.optional(),properties:h.optional(),entityId:e.uuid().optional(),idempotencyKey:e.string().min(1).max(120)})])}),response:r.extend({receipts:e.array(q).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:e.object({customerId:e.uuid(),command:B.refine(t=>t.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:r.extend({receipt:q})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Xi,response:r.extend({redemption:Hi})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:er,response:r.extend({referralCode:tr})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:Ji,response:r.extend({checkout:Yi})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:rr,response:r.extend({seats:Ue})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:nr,response:r.extend({seats:Ue})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:ha,response:fa},getCustomer:{replay:"read",method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Rt,response:r.extend({customer:Q})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Bt,response:r.extend(qt.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:wt,response:r.extend(_t.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:e.object({customerId:e.uuid()}).strict(),response:r.extend(F.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:e.strictObject({}),response:r.extend(F.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:e.strictObject({customerId:e.uuid(),sessionId:e.uuid().optional()}),response:r.extend({revoked:e.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:e.strictObject({guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:he.optional()}),response:r.extend({customerId:e.uuid(),guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:e.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:e.strictObject({guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:r.extend(F.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:e.strictObject({guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:e.string().trim().min(1).max(255).refine(t=>!t.startsWith("gg_guest_")),requestId:e.uuid()}),response:r.extend({customer:Q,switched:e.boolean(),replayed:e.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:e.strictObject({code:e.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:e.uuid()}),response:Nr()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:e.object({}).strict(),response:r.extend({offers:e.array(ue)})},grantModelBenefit:{method:"POST",path:"benefits/model-usage/grant",permission:"offers:grant",audience:"server",request:$t,response:r.extend({operation:xe})},readModelBenefit:{method:"POST",path:"benefits/model-usage/read",permission:"offers:grant",audience:"server",request:Lt,response:r.extend({operation:xe})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:e.object({customerId:e.string().min(1).max(255).optional(),couponId:e.uuid(),...V,requestId:e.uuid(),couponContentDigest:e.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Nr()}},tc={recordMerchantEvent:i.recordMerchantEvent,sendMessage:i.sendMessage,readMessage:i.readMessage,bindPushInstallation:i.bindPushInstallation,readPushInstallation:i.readPushInstallation,updatePushAddress:i.updatePushAddress,readMessagingPreference:i.readMessagingPreference,setMessagingPreference:i.setMessagingPreference,listInvoiceTemplates:i.listInvoiceTemplates,previewInvoice:i.previewInvoice,createInvoice:i.createInvoice,manageInvoice:i.manageInvoice,readInvoiceOperation:i.readInvoiceOperation,listInvoices:i.listInvoices,getInvoice:i.getInvoice,getCodeReferenceConfig:i.getCodeReferenceConfig,submitCodeReferences:i.submitCodeReferences,getFeatures:i.getFeatures,evaluateFeatures:i.evaluateFeatures,trackEvents:i.trackEvents,setupPayment:i.setupPayment,readPaymentSetup:i.readPaymentSetup,previewSubscriptionBatch:i.previewSubscriptionBatch,confirmSubscriptionBatch:i.confirmSubscriptionBatch,readSubscriptionBatch:i.readSubscriptionBatch,abandonSubscriptionBatch:i.abandonSubscriptionBatch,manageSubscriptionTrial:i.manageSubscriptionTrial,readSubscriptionTrial:i.readSubscriptionTrial,listSubscriptions:i.listSubscriptions,listPurchases:i.listPurchases,listSubscriptionConflicts:i.listSubscriptionConflicts,retrySubscriptionConflict:i.retrySubscriptionConflict,readAiPricing:i.readAiPricing,readUsage:i.readUsage,setUsage:i.setUsage,previewRefund:i.previewRefund,refund:i.refund,readRefund:i.readRefund,previewUpdate:i.previewUpdate,update:i.update,readSubscriptionUpdate:i.readSubscriptionUpdate,restoreNativePurchase:i.restoreNativePurchase,verifySubscriptions:i.verifySubscriptions,previewAttach:i.previewAttach,attach:i.attach,readSubscriptionOperation:i.readSubscriptionOperation,manageBalanceGrant:i.manageBalanceGrant,readBalanceSource:i.readBalanceSource,adjustBalance:i.adjustBalance,listBalanceGrants:i.listBalanceGrants,readBillingControls:i.readBillingControls,prepareBillingAuthorization:i.prepareBillingAuthorization,confirmBillingAuthorization:i.confirmBillingAuthorization,setBillingCoupons:i.setBillingCoupons,revokeBillingAuthorization:i.revokeBillingAuthorization,listBillingInvoices:i.listBillingInvoices,confirmBillingAdjustment:i.confirmBillingAdjustment,prepareBillingAdjustment:i.prepareBillingAdjustment,manageBillingLimits:i.manageBillingLimits,createCustomer:i.createCustomer,getCustomer:i.getCustomer,listCustomers:i.listCustomers,updateCustomer:i.updateCustomer,createSession:i.createSession,refreshSession:i.refreshSession,revokeSessions:i.revokeSessions,createGuestCustomer:i.createGuestCustomer,resumeGuestSession:i.resumeGuestSession,claimGuestCustomer:i.claimGuestCustomer,checkEntitlement:i.checkEntitlement,resolveOffering:i.resolveOffering,resolveContent:i.resolveContent,resolvePaywall:i.resolvePaywall,readHoldings:i.readHoldings,readLedger:i.readLedger,readBillingInvoice:i.readBillingInvoice,readCreditStatement:i.readCreditStatement,quoteBalance:i.quoteBalance,trackUsage:i.trackUsage,mutateBalance:i.mutateBalance,manageUsageEntity:i.manageUsageEntity,readUsageAnalytics:i.readUsageAnalytics,readCreditAnalytics:i.readCreditAnalytics,submitUsageBatch:i.submitUsageBatch,readUsageBatch:i.readUsageBatch,listOffers:i.listOffers,grantOffer:i.grantOffer,grantModelBenefit:i.grantModelBenefit,readModelBenefit:i.readModelBenefit,redeemCoupon:i.redeemCoupon,redeemReward:i.redeemReward,createReferralCode:i.createReferralCode,claimRewardProduct:i.claimRewardProduct,readSeats:i.readSeats,manageSeat:i.manageSeat};export{be as a,Dt as b,Gt as c,xa as d,i as e};
1
+ import{a as tt,b as it}from"./chunk-NCMKY7D6.js";import{a as Ut,b as Mt,d as Et,h as Z,i as fe}from"./chunk-ZFNSXRQY.js";import{a as V,b as rt,c as Tt,e as kt}from"./chunk-EPQUD3S5.js";import{f as gt,h as ht,i as ft,j as bt,k as xt}from"./chunk-PYM47Z55.js";import{o as he,p as Ct,u as Q,v as _t,w as Rt,x as wt,y as Bt,z as qt}from"./chunk-44SX4C3G.js";import{f as nt,g as y,i as ue,j as at,k as st,l as de,m as P,n as ot,o as I,p as ct,q as me,r as ut,s as dt,t as mt,u as pe,v as pt,w as lt,x as le}from"./chunk-ONYG4VQI.js";import{k as f,l as He,w as N}from"./chunk-LHUZRVAC.js";import{a as zt}from"./chunk-TYIAPLQP.js";import{a as We,b as F}from"./chunk-DJTMSBQN.js";import{a as B,b as St,c as yt,d as It,e as q,f as vt,g as Ot,h as ge,i as j,j as At,k as Pt,l as jt}from"./chunk-TNWZWEEY.js";import{a as c,e as Xe,f as Je,g as Ye,h as et,j as ce}from"./chunk-UWHTCMMF.js";import{h as se,i as p,j as s,k as oe,m as h}from"./chunk-IYVJOUO7.js";import{b as e}from"./chunk-CTCK5BUY.js";var be=e.strictObject({operationId:e.uuid(),customerId:e.uuid(),externalUserId:e.string().min(1).max(256),modelId:e.string().min(1).max(256),quantity:e.number().int().min(1).max(1e6),validForDays:e.number().int().min(1).max(3660)}),Dt=e.strictObject({operationId:e.uuid(),customerId:e.uuid(),status:e.literal("applied"),voucherId:e.uuid(),modelId:e.string().min(1).max(256),quantity:e.number().int().positive(),issuedAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0})}).refine(t=>Date.parse(t.expiresAt)>Date.parse(t.issuedAt),{message:"A benefit must expire after it is issued"}),Gt=e.strictObject({operationId:e.uuid(),customerId:e.uuid()}),xa=e.discriminatedUnion("lookup",[Gt.extend({lookup:e.literal("not_received")}),Gt.extend({lookup:e.literal("found"),result:Dt}).refine(t=>t.result.operationId===t.operationId&&t.result.customerId===t.customerId)]),$t=e.strictObject({customerId:e.string().min(1).max(256),modelId:e.string().min(1).max(256),quantity:be.shape.quantity,validForDays:be.shape.validForDays,requestId:e.uuid()}),Lt=e.strictObject({customerId:e.string().min(1).max(256),operationId:e.uuid()}),xe=e.strictObject({operationId:e.uuid(),customerId:e.uuid(),taskId:e.uuid(),status:e.enum(["pending","applied","rejected"]),terms:be,receipt:Dt.nullable(),failureCode:e.enum(["INVALID_REQUEST","CONNECTION_CHANGED"]).nullable()}).superRefine((t,n)=>{(t.terms.operationId!==t.operationId||t.terms.customerId!==t.customerId||t.status==="applied"!=(t.receipt!==null)||t.status==="rejected"!=(t.failureCode!==null)||t.receipt&&(t.receipt.operationId!==t.operationId||t.receipt.customerId!==t.customerId||t.receipt.modelId!==t.terms.modelId||t.receipt.quantity!==t.terms.quantity))&&n.addIssue({code:"custom",message:"Benefit result differs from the original accepted operation"})});var T=e.enum(["email","sms","voice","push"]),Ia=e.enum(["resend","twilio","fcm","apns"]);var va=e.string().regex(/^\+[1-9]\d{1,14}$/),Qr=e.enum(["email_recipient","sms_segment","voice_second","push_device"]);var Zr=e.string().trim().min(1).max(200).refine(t=>!/[\r\n\0]/.test(t),"Invalid email header"),Kr=e.strictObject({subject:Zr,html:e.string().min(1).max(131072).optional(),text:e.string().min(1).max(65536).optional()}).refine(t=>t.html!==void 0||t.text!==void 0,{message:"Email requires HTML or text content"}),Wr=e.strictObject({body:e.string().min(1).max(1600).refine(t=>t.trim().length>0)}),Hr=e.strictObject({text:e.string().trim().min(1).max(4e3),language:e.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:e.number().int().min(1).max(900)}),Xr=e.record(e.string().min(1).max(64),e.string().max(256)).refine(t=>Object.keys(t).length<=20&&Object.keys(t).every(n=>!/^(?:indiana_|google\.|gcm\.)/i.test(n)&&n!=="aps"),"Push data contains reserved fields or too many entries"),Jr=e.strictObject({title:e.string().trim().min(1).max(200),body:e.string().trim().min(1).max(2e3),url:e.url().max(2048).refine(t=>!/^(?:javascript|data|file|vbscript):/i.test(t)).optional(),data:Xr.optional()}).refine(t=>new TextEncoder().encode(JSON.stringify(t)).length<=3072,"Push content exceeds the provider payload budget"),Ft=e.discriminatedUnion("channel",[e.strictObject({channel:e.literal("email"),content:Kr}),e.strictObject({channel:e.literal("sms"),content:Wr}),e.strictObject({channel:e.literal("voice"),content:Hr}),e.strictObject({channel:e.literal("push"),content:Jr})]),Nt=e.strictObject({requestId:e.uuid(),customerId:e.uuid(),connectionId:e.uuid().optional(),message:Ft,expiresAt:e.iso.datetime({offset:!0})}),Yr=e.array(e.uuid()).min(1).max(1e4).refine(t=>new Set(t).size===t.length,"Duplicate Customer"),en=e.discriminatedUnion("kind",[e.strictObject({kind:e.literal("all")}),e.strictObject({kind:e.literal("customers"),customerIds:Yr})]),Oa=e.strictObject({name:e.string().trim().min(1).max(120),connectionId:e.uuid().optional(),message:Ft,audience:en,frequencyLimit:e.number().int().min(1).max(100)}),Vt=e.strictObject({requestId:e.uuid(),channel:T,state:e.enum(["allowed","denied"]),expectedRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Qt=e.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Zt=e.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),Aa=e.strictObject({meter:Qr,estimatedUnits:e.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:e.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var Kt=e.strictObject({requestId:e.uuid(),targets:e.array(e.strictObject({membershipId:e.uuid(),action:e.enum(["cancel","uncancel"]),timing:e.enum(["immediate","renewal"])}).refine(t=>t.action!=="uncancel"||t.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(t=>new Set(t.targets.map(n=>n.membershipId)).size===t.targets.length,"Duplicate batch target"),K=e.strictObject({batchId:e.uuid()}),tn=e.strictObject({operationId:e.uuid(),membershipIds:e.array(e.uuid()).min(1).max(20),provider:e.enum(["stripe","apple","google"]),action:e.enum(["cancel","uncancel"]),timing:e.enum(["immediate","renewal"]),status:e.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:dt.nullable(),managementUrl:e.url().nullable(),failureCode:e.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),k=e.strictObject({batchId:e.uuid(),ready:e.boolean(),status:e.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:e.iso.datetime({offset:!0}),acceptedAt:e.iso.datetime({offset:!0}).nullable(),groups:e.array(tn).min(1).max(100)});var rn=e.string().trim().min(1).max(240),Se={requestId:e.uuid(),reason:rn},W=e.discriminatedUnion("action",[e.strictObject({...Se,action:e.literal("start"),productVersionId:e.uuid(),entityId:e.uuid().optional(),days:e.number().int().min(1).max(730).optional()}),e.strictObject({...Se,action:e.literal("extend"),membershipId:e.uuid(),days:e.number().int().min(1).max(730)}),e.strictObject({...Se,action:e.literal("end"),membershipId:e.uuid()})]),Wt=e.strictObject({operationId:e.uuid()}),Ht=e.iso.datetime({offset:!0}),nn=e.strictObject({provider:e.literal("stripe"),executor:e.enum(["indiana","merchant"]),accountId:e.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:e.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:e.union([e.literal("now"),Ht]),prorationBehavior:e.literal("none")}),ye=e.strictObject({operationId:e.uuid(),action:e.enum(["start","extend","end"]),status:e.enum(["pending","effective"]),managedBy:e.enum(["indiana","stripe"]),membershipIds:e.array(e.uuid()).min(1).max(20),endsAt:Ht.nullable(),execution:nn.nullable()}).refine(t=>t.execution!==null==(t.managedBy==="stripe"&&t.status==="pending")&&t.action==="end"==(t.endsAt===null)&&(t.action!=="start"||t.managedBy==="indiana")&&(t.execution===null||t.execution.trialEnd==="now"==(t.action==="end")),"Only a pending Stripe trial change carries execution instructions"),wa=e.strictObject({groupId:e.uuid(),productVersionId:e.uuid(),enabled:e.boolean()});var Xt=e.strictObject({requestId:e.uuid(),currency:c,makeDefault:e.boolean()}),Jt=e.strictObject({setupId:e.uuid()}),an=e.strictObject({provider:e.literal("stripe"),executor:e.literal("merchant"),accountId:e.string().regex(/^acct_[A-Za-z0-9]+$/),mode:e.literal("setup"),currency:e.string().regex(/^[a-z]{3}$/),customer:e.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:e.uuid(),metadata:e.strictObject({grooveProjectId:e.uuid(),grooveEnvironmentId:e.uuid(),grooveCustomerId:e.uuid(),groovePaymentSetupId:e.uuid()}),setDefaultPaymentMethod:e.boolean(),expiresAt:e.iso.datetime({offset:!0})}),Ie=e.strictObject({id:e.uuid(),provider:e.literal("stripe"),status:e.enum(["prepared","complete","expired"]),currency:c,makeDefault:e.boolean(),url:e.url().nullable(),createdAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0}),completedAt:e.iso.datetime({offset:!0}).nullable(),execution:an.nullable()});var Yt=e.union([e.string(),e.number(),e.boolean(),e.null()]),ei=e.strictObject({customerId:e.uuid()}),ti=e.strictObject({customerId:e.uuid(),provider:e.literal("stripe"),checkedAt:e.iso.datetime({offset:!0}),status:e.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:e.number().int().nonnegative(),differences:e.array(e.strictObject({subscriptionId:e.string().startsWith("sub_"),itemId:e.string().nullable(),field:e.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Yt,actual:Yt})).max(1e4)});var H=e.iso.datetime({offset:!0}),X=e.strictObject({createdAt:H,id:e.uuid()}),J=e.strictObject({customerId:e.uuid().optional(),entityId:e.uuid().optional(),productId:e.string().min(1).max(256).optional(),provider:e.enum(["stripe","apple","google","merchant","free"]).optional(),status:e.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:X.optional(),limit:e.number().int().min(1).max(100).optional()}),ve={id:e.uuid(),customerId:e.uuid(),entityId:e.uuid().nullable(),productId:e.string().min(1).max(256),productVersionId:e.uuid(),name:e.string().min(1).max(120),provider:e.enum(["stripe","apple","google","merchant","free"]),createdAt:H},sn=e.strictObject({...ve,status:e.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:e.boolean(),billingSubscriptionId:e.uuid().nullable()}),on=e.strictObject({...ve,status:e.enum(["active","ended","refunded"]),orderId:e.uuid().nullable(),transactionId:e.uuid().nullable(),currency:c.nullable(),amountMinor:e.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),cn=e.strictObject({...ve,status:e.enum(["blocked","resolved"]),conflict:e.strictObject({detectedAt:H,blockingMembershipIds:e.array(e.uuid()).min(1).max(100),transactionId:e.uuid()}),resolvedAt:H.nullable()}),ii=J.extend({status:e.enum(["blocked","resolved"]).optional()}),ri=e.strictObject({customerId:e.uuid(),orderId:e.uuid()}),ni=e.strictObject({orderId:e.uuid(),status:e.enum(["blocked","resolved"])}),ai=e.strictObject({items:e.array(sn).max(100),nextCursor:X.nullable()}),si=e.strictObject({items:e.array(on).max(100),nextCursor:X.nullable()}),oi=e.strictObject({items:e.array(cn).max(100),nextCursor:X.nullable()});var ci=e.union([e.strictObject({intent:e.literal("read"),requestId:e.uuid(),purchaseIntentId:e.uuid()}),e.strictObject({requestId:e.uuid(),provider:e.literal("apple"),purchaseIntentId:e.uuid(),productId:e.string().min(1).max(255).optional(),signedTransaction:e.string().min(1).max(131072)}),e.strictObject({requestId:e.uuid(),provider:e.literal("google"),purchaseIntentId:e.uuid(),productId:e.string().min(1).max(255).optional(),purchaseToken:e.string().min(1).max(16384)})]),ui=e.strictObject({requestId:e.uuid(),orderId:e.uuid(),purchaseIntentId:e.uuid(),status:e.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:c,refunded:e.boolean(),completion:e.strictObject({transactionIds:e.array(e.string().min(1).max(255)).min(1).max(50).refine(t=>new Set(t).size===t.length),membership:e.boolean()}).nullable()});var un=e.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),pi=e.enum(["single_use","continuous_use"]),Oe=e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string())),di=e.string().min(1).max(64).refine(t=>!t.includes("::")),li={credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()},gi={credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(e.strictObject({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()}))},dn=e.union([e.strictObject({match:Oe,priority:e.number().int().optional(),...li}),e.strictObject({match:Oe,priority:e.number().int().optional(),...gi})]),mn=e.strictObject({match:Oe,factor:e.number().positive().optional(),add:e.number().optional()}).refine(t=>t.factor!==void 0||t.add!==void 0),mi={metered_feature_id:e.string(),feature_amount:e.number().optional(),dimensions:e.record(di,dn).optional(),multipliers:e.record(di,mn).optional()},Ae=e.union([e.strictObject({...mi,...li}),e.strictObject({...mi,...gi})]),ee=e.number().min(-100),hi=e.record(e.string(),e.strictObject({markup:ee})).nullish(),te=e.record(e.string().regex(/.+\/.+/),e.strictObject({markup:ee.optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish(),pn=e.strictObject({default_markup:ee.optional(),provider_markups:hi,model_markups:te}),Na=e.strictObject({schema:e.array(Ae).optional(),markups:pn.optional()}),ln=e.strictObject({filters:e.array(e.strictObject({property:e.string(),operator:e.string(),value:e.array(e.string())})),aggregate:e.strictObject({type:e.string(),property:e.string().nullable()}),usage_type:pi}),fi=e.strictObject({schema:e.array(Ae).min(1).refine(t=>new Set(t.map(n=>n.metered_feature_id)).size===t.length,"Credit rates must name each metered feature once"),invoice_credit:e.boolean().optional(),usage_type:pi.default("single_use").overwrite(()=>"single_use"),default_markup:ee.optional(),provider_markups:hi}),Pe=fi.safeExtend({schema:e.array(Ae).length(0)}),Y={id:un,name:e.string().min(1),display:e.strictObject({singular:e.string().optional(),plural:e.string().optional()}).nullish(),event_names:e.array(e.string()).default([]),model_markups:te,stripe_meter:e.strictObject({id:e.string(),event_name:e.string()}).nullish(),stripe_product_id:e.string().nullish()},je=t=>e.discriminatedUnion("type",[e.strictObject({...Y,...t,type:e.literal("boolean"),config:e.null()}),e.strictObject({...Y,...t,type:e.literal("metered"),config:ln}),e.strictObject({...Y,...t,type:e.literal("credit_system"),config:fi}),e.strictObject({...Y,...t,type:e.literal("ai_credit_system"),config:Pe})]),Va=je({}),gn=e.strictObject({id:e.boolean(),type:e.boolean(),usage_type:e.boolean()}),hn={internal_id:e.uuid(),org_id:e.uuid(),created_at:e.number(),env:e.enum(["sandbox","live"]),archived:e.boolean(),project_id:e.uuid(),environment_id:e.uuid(),revision:e.number().int().nonnegative(),update_rules:gn},bi=je(hn),Qa=e.strictObject({rows:e.array(bi).max(200),nextCursor:e.uuid().nullable()}),Za=e.strictObject({features:e.array(bi).max(500),limited:e.boolean()}),Ka=e.union([je({action:e.literal("save"),internal_id:e.uuid().nullable(),revision:e.number().int().nonnegative()}),e.strictObject({action:e.enum(["archive","restore","delete"]),internal_id:e.uuid(),revision:e.number().int().nonnegative()})]);var _e=e.uuid().refine(t=>t===t.toLowerCase(),"Product references require canonical lowercase UUIDs"),fn=e.record(e.string(),e.json()).refine(t=>Array.from(JSON.stringify(t)).length<=4e3,"Offering metadata exceeds 4000 characters"),bn=3,z=20,xn=bn*z,Ce=e.strictObject({type:e.literal("product"),productId:_e}),xi={type:e.literal("group"),key:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:e.string().trim().min(1).max(80)},Sn=e.discriminatedUnion("type",[Ce,e.strictObject({...xi,items:e.array(Ce).max(z)})]),yn=e.discriminatedUnion("type",[Ce,e.strictObject({...xi,items:e.array(Sn).max(z)})]),In=e.array(yn).max(z).superRefine((t,n)=>{let a=new Set,o=new Set,m=0;function Qe(Vr){for(let S of Vr){m++;let Ze=S.type==="product"?a:o,Ke=S.type==="product"?S.productId:S.key;Ze.has(Ke)&&n.addIssue({code:"custom",message:S.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),Ze.add(Ke),S.type==="group"&&Qe(S.items)}}Qe(t),(a.size>z||m>xn)&&n.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Re(t){return t.items.flatMap(n=>n.type==="product"?[n.productId]:Re(n))}var C=e.strictObject({lookupKey:e.string().trim().min(1).max(200),displayName:e.string().trim().min(1).max(1500),items:In,metadata:fn}),vn=e.strictObject({product:e.record(e.string(),e.json()),prices:e.array(e.record(e.string(),e.json())),entitlements:e.array(e.record(e.string(),e.json())),freeTrials:e.array(e.record(e.string(),e.json())),licenses:e.array(e.record(e.string(),e.json()))}),Si=C.extend({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),state:e.enum(["active","archived"]),isCurrent:e.boolean(),revision:e.number().int().nonnegative(),publishedVersionId:e.uuid().nullable(),createdAt:e.iso.datetime({offset:!0})}).superRefine((t,n)=>{t.isCurrent&&(t.state!=="active"||!t.publishedVersionId)&&n.addIssue({code:"custom",message:"Current Offering must be active and published"})}),yi=e.strictObject({id:e.uuid(),offeringId:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),version:e.number().int().positive(),document:C,productEvidence:e.record(_e,vn),createdAt:e.iso.datetime({offset:!0})}).superRefine((t,n)=>{let a=Re(t.document);(!a.length||Pn(t.document).length>0||Object.keys(t.productEvidence).length!==a.length||a.some(o=>!Object.hasOwn(t.productEvidence,o)))&&n.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),On=e.strictObject({rows:e.array(Si).max(200),versions:e.array(yi).max(500)}),Xa=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),document:C}),e.strictObject({action:e.literal("save"),id:e.uuid(),revision:e.number().int().nonnegative(),document:C}),e.strictObject({action:e.enum(["publish","set_current","archive","restore"]),id:e.uuid(),revision:e.number().int().nonnegative()})]),Ja=e.strictObject({record:Si,version:yi.nullable()}),Ii=e.discriminatedUnion("type",[e.strictObject({type:e.literal("current")}),e.strictObject({type:e.literal("id"),id:e.uuid()}),e.strictObject({type:e.literal("lookup_key"),lookupKey:e.string().min(1).max(200)}),e.strictObject({type:e.literal("version"),versionId:e.uuid()})]),An=e.strictObject({internalId:_e,id:e.string(),name:e.string().nullable(),version:e.number().int().positive(),archived:e.boolean()}),Ya=On.extend({products:e.array(An).max(500),pagination:e.strictObject({rows:e.string().nullable(),versions:e.string().nullable(),products:e.string().nullable()}).optional()});function Pn(t){let n=[];Re(t).length||n.push("Select at least one Product before publishing");function a(o){for(let m of o)m.type==="group"&&(m.items.length||n.push("Every published group requires a Product"),a(m.items))}return a(t.items),n}var vi=e.strictObject({id:e.uuid(),offeringId:e.uuid(),version:e.number().int().positive(),document:C});var Oi={requestId:e.uuid(),sourceId:e.uuid(),expectedAvailable:j},Ai=e.discriminatedUnion("action",[e.strictObject({...Oi,action:e.enum(["add","subtract","set_remaining"]),amount:s}),e.strictObject({...Oi,action:e.literal("edit"),granted:s,expiresAt:e.iso.datetime({offset:!0}).nullable(),nextResetAt:e.iso.datetime({offset:!0}).nullable(),expectedRevision:e.number().int().nonnegative()})]),we=e.strictObject({sourceId:e.uuid(),available:j,held:j,spent:j,adjustmentGrantId:e.uuid().nullable()}),Pi=we.extend({granted:j,expiresAt:e.iso.datetime({offset:!0}).nullable(),nextResetAt:e.iso.datetime({offset:!0}).nullable(),revision:e.number().int().nonnegative()});var ji=e.discriminatedUnion("action",[e.object({action:e.literal("upsert"),externalId:e.string().min(1).max(128),name:e.string().trim().min(1).max(80)}).strict(),e.object({action:e.literal("archive"),entityId:e.uuid()}).strict()]),Ci=e.object({id:e.uuid(),externalId:e.string().min(1).max(128),name:e.string().min(1).max(80),archived:e.boolean()}).strict();var _i=e.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Ri=e.number().int().min(1).max(1e3),ie=e.object({cap:s.refine(t=>/[1-9]/.test(t)).nullable(),capPercentage:e.number().positive().max(1e4).nullable(),cycles:e.number().int().min(1).max(1200).nullable()}).strict().refine(t=>t.cap===null||t.capPercentage===null,"Choose a fixed or percentage cap");var v=e.iso.datetime({offset:!0}),wi=s.refine(t=>/[1-9]/.test(t)),Bi=e.strictObject({interval:_i.exclude(["lifetime"]),count:Ri}),jn=e.strictObject({action:e.literal("create"),requestId:e.uuid(),internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),amount:wi.nullable(),expiresAt:v.nullable(),reset:Bi.nullable(),rollover:ie.nullable(),nextResetAt:v.nullable()}).refine(t=>t.amount!==null||t.reset===null&&t.rollover===null,"Unlimited grants cannot reset or roll over").refine(t=>!t.rollover||t.reset!==null,"Rollover requires a recurring grant").refine(t=>t.nextResetAt===null||t.reset!==null&&(t.expiresAt===null||Date.parse(t.nextResetAt)<Date.parse(t.expiresAt)),"The first reset needs a reset interval and must precede expiry"),qi=e.discriminatedUnion("action",[jn,e.strictObject({action:e.literal("update"),requestId:e.uuid(),grantId:e.uuid(),revision:e.number().int().nonnegative(),amount:wi.nullable(),expiresAt:v.nullable(),rollover:ie.nullable(),nextResetAt:v.nullable()}),e.strictObject({action:e.enum(["add","subtract","set_remaining"]),requestId:e.uuid(),grantId:e.uuid(),revision:e.number().int().nonnegative(),amount:s}),e.strictObject({action:e.literal("revoke"),requestId:e.uuid(),grantId:e.uuid(),revision:e.number().int().nonnegative()})]),Be=e.strictObject({id:e.uuid(),internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),amount:s.nullable(),reset:Bi.nullable(),rollover:ie.nullable(),nextResetAt:v.nullable(),startsAt:v,expiresAt:v.nullable(),revision:e.number().int().nonnegative(),revoked:e.boolean(),available:p,held:p,spent:p}),Ti=e.strictObject({customerId:e.uuid(),after:e.uuid().nullable(),limit:e.number().int().min(1).max(100)}),ki=e.strictObject({rows:e.array(Be).max(100),nextCursor:e.uuid().nullable()});var O=e.iso.datetime({offset:!0}),x=e.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Cn=e.discriminatedUnion("kind",[e.object({kind:e.literal("absolute"),from:O,to:O}).strict(),e.object({kind:e.literal("last_days"),days:e.union([e.literal(1),e.literal(7),e.literal(30),e.literal(90)])}).strict(),e.object({kind:e.literal("billing_cycles"),membershipId:e.uuid(),count:e.number().int().min(1).max(12),includeCurrent:e.boolean()}).strict()]),zi=e.string().max(100).refine(t=>{if(t!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(t))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:t}),!0}catch{return!1}},"Use an IANA timezone"),_n=e.object({key:e.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:e.array(e.string().max(120)).min(1).max(20).refine(t=>new Set(t).size===t.length)}).strict(),A=e.object({range:Cn,timezone:zi,filterBy:e.array(_n).max(5).refine(t=>new Set(t.map(n=>n.key)).size===t.length),interval:e.enum(["hour","day","week","month"]),internal_feature_id:e.uuid().nullable(),entityId:e.uuid().nullable(),topN:e.number().int().min(1).max(50).nullable(),groupBy:e.union([e.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),e.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:e.object({bucket:O,group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid(),resourceId:e.uuid()}).strict().nullable(),limit:e.number().int().min(1).max(100)}).strict().superRefine((t,n)=>{if(t.range.kind!=="absolute"){t.interval==="hour"&&t.range.kind==="last_days"&&t.range.days>31&&n.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let a=Date.parse(t.range.to)-Date.parse(t.range.from);(a<=0||a>366*864e5||t.interval==="hour"&&a>31*864e5)&&n.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),Ui=e.object({from:O,to:O,interval:e.enum(["hour","day","week","month"]),timezone:zi,rows:e.array(e.object({bucket:O,group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid(),resourceId:e.uuid(),consumedUnits:x,refundedUnits:x,reservedUnits:x,charged:x,refunded:x,reserved:x,netUnits:x,netCharged:x}).strict()).max(100),nextCursor:e.object({bucket:O,group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid(),resourceId:e.uuid()}).strict().nullable()}).strict();var _=e.string().regex(/^(0|[1-9]\d{0,29})$/),Mi=e.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),qe=e.strictObject({bucket:e.iso.datetime({offset:!0}),group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid()}),Ei=e.strictObject({...A.shape,groupBy:e.union([e.enum(["customer","entity","entitlement"]),e.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:qe.nullable()}).superRefine((t,n)=>{let a=A.safeParse({...t,after:null});if(!a.success)for(let o of a.error.issues)n.addIssue({code:"custom",path:o.path,message:o.message})}),Gi=e.strictObject({from:e.iso.datetime({offset:!0}),to:e.iso.datetime({offset:!0}),interval:A.shape.interval,timezone:A.shape.timezone,rows:e.array(e.strictObject({...qe.shape,eventCount:_,units:Mi,tokenEventCount:_,tokens:e.strictObject(Object.fromEntries(zt.map(t=>[t,_]))),totalTokens:_,providerCostEventCount:_,providerCostUsd:Mi,invalidTelemetryEventCount:_})).max(100),nextCursor:qe.nullable()});var Di=e.object({requestId:e.uuid(),items:e.array(e.object({customerId:e.uuid(),command:B.options[1]}).strict()).min(1).max(1e3)}).strict().refine(t=>new Set(t.items.map(n=>n.customerId+":"+n.command.idempotencyKey)).size===t.items.length,"Each logical event must appear once in a batch"),$i=e.object({batchId:e.uuid(),after:e.number().int().min(-1).max(999),limit:e.number().int().min(1).max(100)}).strict(),Li=e.object({batchId:e.uuid(),status:e.enum(["queued","complete"]),total:e.number().int().min(1).max(1e3),processed:e.number().int().min(0).max(1e3),items:e.array(e.object({position:e.number().int().min(0).max(999),customerId:e.uuid(),idempotencyKey:e.string().min(1).max(120),status:e.enum(["queued","accepted","rejected","failed"]),receipt:q.nullable(),errorCode:e.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(t=>t.status==="queued"?t.receipt===null&&t.errorCode===null:t.status==="failed"?t.receipt===null&&t.errorCode!==null:t.receipt!==null&&t.errorCode===null&&t.receipt.accepted===(t.status==="accepted"))).max(100),nextAfter:e.number().int().min(0).max(999).nullable()}).strict();var Rn=e.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Fi=e.enum(["draft","active","paused","archived"]),Ni=e.string().min(1).max(256),Vi=e.array(Ni).max(50).refine(t=>new Set(t).size===t.length,"Duplicate products"),wn=e.strictObject({duration:e.enum(["day","week","month","year"]),length:e.number().int().min(1).max(3660)}),Bn=e.strictObject({internal_feature_id:e.uuid(),allowance:e.number().nonnegative().max(1e15).nullable(),expiry:wn.nullable()}),qn=e.discriminatedUnion("type",[e.strictObject({type:e.literal("feature_grant"),grants:e.array(Bn).min(1).max(100).refine(t=>new Set(t.map(n=>n.internal_feature_id)).size===t.length,"Duplicate entitlement grants")}),e.strictObject({type:e.literal("free_product"),productId:Ni,duration:y}),e.strictObject({type:e.literal("invoice_credits"),amount:e.number().positive().max(1e8),duration:y,rollover:e.boolean(),productIds:Vi})]),Tn=e.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),Qi=e.object({key:Tn,name:e.string().trim().min(1).max(80),configuration:qn}).strict(),Zi=e.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Te=e.object({code:Zi,maxUses:e.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:e.boolean()}).strict(),Ki=e.object({key:e.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:e.string().trim().min(1).max(80),rewardId:e.uuid(),redeemOn:e.enum(["customer_creation","checkout"]),receivedBy:e.enum(["referrer","all"]),maxRedemptions:e.number().int().min(1).max(1e6).nullable(),productIds:Vi,excludeTrial:e.boolean()}).strict().refine(t=>t.redeemOn==="checkout"||t.productIds.length===0&&!t.excludeTrial,"Purchase restrictions require checkout trigger"),Wi={id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),revision:e.number().int().nonnegative(),status:Fi,createdAt:e.iso.datetime({offset:!0}),updatedAt:e.iso.datetime({offset:!0})},kn=Qi.extend(Wi).strict(),zn=Ki.safeExtend(Wi).strict(),Rs=e.strictObject({id:e.uuid(),key:e.string(),name:e.string(),type:Rn,status:Fi,ended:e.boolean()}),ws=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),input:Qi}).strict(),e.object({action:e.enum(["activate","pause","resume","archive","delete"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Bs=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),input:Ki}).strict(),e.object({action:e.enum(["activate","pause","resume","archive","delete"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Hi=e.object({id:e.uuid(),rewardId:e.uuid(),programId:e.uuid().nullable(),customerId:e.uuid(),referrerId:e.uuid().nullable(),status:e.enum(["pending","applied","unavailable"]),result:e.record(e.string(),e.unknown()).nullable(),createdAt:e.iso.datetime({offset:!0})}).strict(),Xi=e.object({code:Zi,requestId:e.uuid()}).strict(),Ji=e.strictObject({redemptionId:e.uuid(),currency:c,requestId:e.uuid(),accepted:e.literal(!0)}),Un=e.strictObject({type:e.literal("checkout"),orderId:e.uuid(),productVersionId:e.uuid(),currency:c,duration:y,renewalAmountMinor:e.number().int().positive().max(1e8),status:e.enum(["created","pending","trialing","paid","cancelled","failed"]),url:e.url().nullable()}),Yi=e.discriminatedUnion("type",[Un,e.strictObject({type:e.literal("subscription"),operationId:e.uuid(),membershipId:e.uuid(),productVersionId:e.uuid(),currency:c,duration:y,renewalAmountMinor:e.number().int().positive().max(1e8),status:e.enum(["pending","running","applied","failed"])})]),er=e.object({programId:e.uuid(),requestId:e.uuid()}).strict(),tr=e.object({id:e.uuid(),programId:e.uuid(),code:Te.shape.code,createdAt:e.iso.datetime({offset:!0})}).strict(),qs=e.object({rows:e.array(kn).max(100),nextCursor:e.uuid().nullable()}).strict(),Ts=e.object({rows:e.array(zn).max(100),nextCursor:e.uuid().nullable()}).strict(),Mn=Te.extend({id:e.uuid(),redemptions:e.number().int().nonnegative()}).strict(),En=e.strictObject({id:e.uuid(),programId:e.uuid().nullable(),customerId:e.uuid().nullable(),referrerId:e.uuid().nullable(),code:e.string().nullable(),status:e.enum(["pending","triggered","applied"]),createdAt:e.iso.datetime({offset:!0})}),ks=e.object({codes:e.array(Mn).max(100),redemptions:e.array(En).max(100),customers:e.record(e.uuid(),e.string()),codesCursor:e.uuid().nullable(),redemptionsCursor:e.uuid().nullable()}).strict(),zs=e.discriminatedUnion("action",[e.object({action:e.literal("create"),rewardId:e.uuid(),revision:e.number().int().nonnegative(),input:Te}).strict(),e.object({action:e.literal("remove"),rewardId:e.uuid(),revision:e.number().int().nonnegative(),codeId:e.uuid()}).strict()]);var rr=e.object({customerId:e.uuid()}).strict(),nr=e.discriminatedUnion("action",[e.object({customerId:e.uuid(),requestId:e.uuid(),action:e.literal("assign"),poolId:e.uuid(),memberCustomerId:e.uuid()}).strict(),e.strictObject({customerId:e.uuid(),requestId:e.uuid(),action:e.literal("assign_entity"),poolId:e.uuid(),entityId:e.uuid()}),e.object({customerId:e.uuid(),requestId:e.uuid(),action:e.literal("release"),poolId:e.uuid(),slotId:e.uuid()}).strict()]),U=e.number().int().nonnegative(),ke=e.iso.datetime({offset:!0}),ze=e.strictObject({internalId:e.uuid(),id:e.string(),name:e.string().nullable(),version:e.number().int().positive()}),ir=e.enum(["active","past_due"]),Ue=e.strictObject({customerId:e.uuid(),licenses:e.array(e.strictObject({id:e.uuid(),linkId:e.uuid(),parent:e.strictObject({customerProductId:e.uuid(),status:ir,product:ze}),product:ze,planLicense:e.strictObject({id:e.uuid(),prepaidOnly:e.boolean(),isCustom:e.boolean()}).nullable(),granted:U,included:U,paidQuantity:U,usage:U,remaining:U,createdAt:ke}).refine(t=>t.granted===t.included+t.paidQuantity&&t.granted===t.usage+t.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:e.array(e.strictObject({id:e.uuid(),linkId:e.uuid(),status:ir,product:ze,entity:e.strictObject({internalId:e.uuid(),id:e.string().nullable(),name:e.string().nullable()}).nullable(),beneficiary:e.strictObject({internalId:e.uuid(),id:e.string().nullable(),name:e.string().nullable()}).nullable(),startedAt:ke.nullable(),endedAt:ke.nullable()}).refine(t=>t.entity!==null||t.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:e.boolean()});var ur=e.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Me=e.string().regex(/^(0|[1-9]\d{0,14})$/),R=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Gn=e.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),M=Gn,b=s.refine(t=>/[1-9]/.test(t)),u=e.iso.datetime({offset:!0}),re=t=>{let[n,a=""]=t.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*1000000n+BigInt(a.padEnd(6,"0"))},Dn=e.array(e.object({upTo:b.nullable(),unitAmountMinor:ur,flatAmountMinor:e.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(t=>{try{return t.at(-1)?.upTo===null&&t.slice(0,-1).every((n,a)=>{let o=t[a-1]?.upTo;return n.upTo!==null&&(a===0||o!=null&&re(n.upTo)>re(o))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),$n=e.discriminatedUnion("kind",[e.object({kind:e.literal("flat"),units:b,unitAmountMinor:ur}).strict(),e.object({kind:e.enum(["graduated","volume"]),units:b,tiers:Dn}).strict()]).refine(t=>t.kind==="flat"||!t.tiers.some(n=>(n.flatAmountMinor??0)>0)||t.kind==="volume"&&t.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),Ln=e.strictObject({interval:e.enum(["month","year"]),count:e.number().int().min(1).max(12),anchor:e.enum(["membership","calendar"])}),E=e.object({currency:c,pricing:$n,billingCycle:Ln.optional()}).strict().refine(t=>t.pricing.kind!=="volume"||t.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var ar={requestId:e.uuid(),productVersionId:e.uuid(),internal_feature_id:e.uuid(),currency:c},dr=e.strictObject({interval:e.enum(["hour","day","week","month"]),intervalCount:e.number().int().min(1).max(12),limit:e.number().int().min(1).max(1e6)}),mr=e.discriminatedUnion("kind",[e.object({...ar,kind:e.literal("auto_topup"),threshold:oe,quantity:b.refine(t=>Number(t)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:dr.optional()}).strict(),e.object({...ar,kind:e.literal("postpaid"),maxAmountMinorPerPeriod:M,maxOutstandingMinor:M}).strict()]),sr={productVersionId:e.uuid(),internal_feature_id:e.uuid(),currency:c},pr=e.discriminatedUnion("kind",[e.object({...sr,kind:e.literal("auto_topup"),threshold:oe,quantity:b.refine(t=>Number(t)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:dr.optional(),purchaseAmountMinor:M,purchaseUnits:b}).strict(),e.object({...sr,kind:e.literal("postpaid"),maxAmountMinorPerPeriod:M,maxOutstandingMinor:M,cashPrice:E}).strict().refine(t=>t.cashPrice.currency===t.currency,"Currency must match")]),ne=e.object({id:e.uuid(),terms:pr,status:e.enum(["prepared","active","revoked","blocked"]),createdAt:u,acceptedAt:u.nullable(),effectiveAt:u.nullable(),revokedAt:u.nullable()}).strict().refine(t=>(t.status==="prepared"?t.acceptedAt===null:!0)&&(t.status==="active"?t.acceptedAt!==null&&t.effectiveAt!==null:!0)&&(t.status==="revoked"?t.revokedAt!==null:t.revokedAt===null),"Authorization consent and revocation must be explicit"),lr=e.object({authorizationId:e.uuid(),terms:pr,setupUrl:e.url().nullable()}).strict(),gr=e.object({authorizationId:e.uuid(),accepted:e.literal(!0)}).strict(),hr=e.object({authorizationId:e.uuid(),requestId:e.uuid()}).strict(),fr=e.object({internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),interval:e.enum(["day","week","month","year"]),anchor:e.enum(["billing_cycle","utc"]).optional(),basis:e.enum(["usage","credits"]),filter:h.optional(),limit:s.nullable(),thresholds:e.array(e.number().positive().max(1)).max(8),includedThresholds:e.array(e.number().positive().max(1)).max(8).optional(),absoluteThresholds:e.array(b).max(8).optional()}).strict().refine(t=>t.thresholds.every((n,a)=>{let o=t.thresholds[a-1];return a===0||o!==void 0&&n>o})&&(t.includedThresholds??[]).every((n,a,o)=>{let m=o[a-1];return a===0||m!==void 0&&n>m})&&(t.absoluteThresholds??[]).every((n,a,o)=>{let m=o[a-1];return a===0||m!==void 0&&re(n)>re(m)}),"Notification thresholds must increase"),Fn=fr.safeExtend({requestId:e.uuid()}),or={control:e.literal("overage"),requestId:e.uuid(),internal_feature_id:e.uuid(),entityId:e.uuid().nullable()},Nn=e.discriminatedUnion("action",[e.strictObject({...or,action:e.literal("set"),allowed:e.boolean().nullable(),overageLimit:s.nullable(),skipOverageBilling:e.boolean()}),e.strictObject({...or,action:e.literal("remove")})]),br=e.union([Fn,Nn]),Vn=e.strictObject({internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),allowed:e.boolean().nullable(),overageLimit:s.nullable(),skipOverageBilling:e.boolean(),interval:e.enum(["day","week","month","year"]),startsAt:u,endsAt:u,used:e.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:e.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:e.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Qn=e.object({internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),interval:e.enum(["day","week","month","year"]),anchor:e.enum(["billing_cycle","utc"]).optional(),basis:e.enum(["usage","credits"]),filter:h.optional(),startsAt:u,endsAt:u,used:p,reserved:p,limit:s.nullable(),thresholds:e.array(e.number().positive().max(1)).max(8),notifiedThresholds:e.array(e.number().positive().max(1)).max(1024),includedThresholds:e.array(e.number().positive().max(1)).max(8).optional(),includedAllowance:e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:e.array(e.number().positive().max(1)).max(1024).optional(),absoluteThresholds:e.array(b).max(8).optional(),notifiedAbsoluteThresholds:e.array(b).max(1024).optional()}).strict().refine(t=>t.basis!=="usage"||s.safeParse(t.used).success&&s.safeParse(t.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Zn=e.object({authorizationId:e.uuid(),status:e.enum(["idle","pending","blocked"]),taskId:e.uuid().nullable(),invoiceId:e.uuid().nullable(),hostedInvoiceUrl:e.url().nullable(),purchaseCount:e.number().int().nonnegative(),purchaseWindowEndsAt:u.nullable(),attemptCount:e.number().int().nonnegative(),failedAttemptCount:e.number().int().nonnegative(),suspendedAt:u.nullable(),nextAttemptAt:u.nullable(),failureReason:e.string().min(1).max(240).nullable()}).strict(),xr=e.object({internal_feature_id:e.uuid().optional(),entityId:e.uuid().optional()}).strict(),Ee=e.object({authorizations:e.array(ne).max(100),limits:e.array(fr).max(100),overages:e.array(Vn).max(100).optional(),windows:e.array(Qn).max(200),autoTopups:e.array(Zn).max(100),limited:e.boolean()}).strict(),Kn=e.object({id:e.uuid(),internal_feature_id:e.uuid(),productVersionId:e.uuid(),authorizationId:e.uuid(),entityId:e.uuid().nullable(),units:s,amountMinor:R,cashPrice:E}).strict(),G=e.object({id:e.uuid(),sourceKind:e.enum(["product","usage","manual"]),providerInvoiceId:e.string().min(1).max(240).nullable(),status:e.enum(["accruing","open","pending","paid","failed","void"]),currency:c,startsAt:u.nullable(),endsAt:u.nullable(),amountMinor:e.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:e.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Me,paidAmountMinor:Me,refundedAmountMinor:Me,createdAt:u,hostedInvoiceUrl:e.url().nullable(),adjustment:e.object({originalInvoiceId:e.uuid(),amountMinor:e.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(t=>t!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(t)&&BigInt(t)>=-200000000n&&BigInt(t)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:u.nullable(),reason:e.string().min(1).max(500).optional()}).strict().nullable(),lines:e.array(Kn).max(100),linesLimited:e.boolean()}).strict(),Sr=e.object({invoiceId:e.uuid(),accepted:e.literal(!0)}).strict(),yr=e.strictObject({requestId:e.uuid(),originalInvoiceId:e.uuid(),amountMinor:e.string().regex(/^[1-9]\d{0,8}$/).refine(t=>/^[1-9]\d{0,8}$/.test(t)&&BigInt(t)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:e.string().trim().min(1).max(500)}),Ir=e.object({after:e.uuid().nullable(),limit:e.number().int().min(1).max(100)}).strict(),vr=e.object({rows:e.array(G).max(100),nextCursor:e.uuid().nullable()}).strict(),cr=e.strictObject({id:e.string(),coupon:e.string(),start:e.number().nonnegative(),end:e.number().nullable()}),Wn=e.strictObject({subscriptionId:e.string(),customerId:e.string(),accountId:e.string(),sourceItems:e.array(e.strictObject({id:e.string(),price_id:e.string(),quantity:e.number().int(),discounts:e.array(cr).optional()})).max(100),items:e.array(e.strictObject({id:e.string(),price:e.string(),quantity:e.number().int(),discounts:e.array(e.strictObject({coupon:e.string().optional(),terms:e.strictObject({id:e.string(),name:e.string().optional(),percent_off:e.number().optional(),amount_off:e.number().optional(),currency:e.string().optional(),duration:e.enum(["once","forever","repeating"]),duration_in_months:e.number().optional()}).optional(),discount:e.string().optional(),receipt:cr.optional()})).max(20)})).max(100)}),Or=e.strictObject({membershipId:e.uuid(),requestId:e.uuid(),grantIds:e.array(e.uuid()).max(20).refine(t=>new Set(t).size===t.length,"Duplicate Coupon grants")}),Ar=e.strictObject({membershipId:e.uuid(),operationId:e.uuid(),status:e.enum(["pending","effective"]),execution:Wn.nullable(),grants:e.array(e.strictObject({id:e.uuid(),couponId:e.uuid(),name:e.string(),discount:nt,duration:y,startedAt:u.nullable()})).max(20)});var l={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},D=t=>new Set(t).size===t.length,Ge=e.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),Hn=e.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(t=>!t.split("/").some(n=>n==="."||n==="..")),$=e.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(t=>!t.includes("..")&&!t.endsWith(".")&&!t.split("/").some(n=>!n||n.startsWith(".")||n.endsWith(".lock"))),Xn=e.string().min(1).max(512).refine(t=>!/[\\\u0000-\u001f\u007f]/.test(t)&&!t.startsWith("/")&&!t.split("/").some(n=>!n||n==="."||n==="..")),Pr=e.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(t=>!t.startsWith("/")&&!t.split("/").some(n=>!n||n==="."||n===".."));var jr=e.strictObject({id:e.uuid(),repo:Hn,platform:e.enum(["github","gitlab","bitbucket"]),branches:e.array($).min(1).max(4).refine(D),workflow:e.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:e.array(e.uuid()).min(1).max(4).refine(D),include:e.array(Pr).min(1).max(16),exclude:e.array(Pr).max(16),methods:e.array(e.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(D),maxAgeHours:e.number().int().min(1).max(720)}),Cr=jr.extend({revision:e.number().int().positive()}),Qs=e.strictObject({repository:jr,expectedRevision:e.number().int().min(0)}).refine(({repository:t})=>t.platform==="gitlab"||t.repo.split("/").length===2,{path:["repository","repo"]}),_r=e.strictObject({repositoryId:e.uuid(),branch:$}),Jn=e.array(Ge).max(l.keys).refine(D),Rr=e.strictObject({repository:Cr.omit({keyIds:!0}),branch:$,keys:Jn,keySetHash:e.string().regex(/^[a-f0-9]{64}$/)}),Yn=e.strictObject({filePath:Xn,startingLineNumber:e.number().int().min(1).max(1e7)}),De=e.strictObject({protocol:e.literal(1),repositoryId:e.uuid(),branch:$,workflow:e.string().max(200),configurationRevision:e.number().int().positive(),keySetHash:e.string().regex(/^[a-f0-9]{64}$/),commit:e.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:e.uuid(),runNumber:e.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:e.number().int().min(1).max(1e4),scannerVersion:e.literal("1"),scannedAt:e.iso.datetime({offset:!0}),coverage:e.strictObject({complete:e.literal(!0),files:e.number().int().min(0).max(l.files),sourceBytes:e.number().int().min(0).max(l.sourceBytes),unresolvedCalls:e.number().int().min(0).max(1e6),unsupportedFiles:e.number().int().min(0).max(l.files)}),features:e.array(e.strictObject({key:Ge,refs:e.array(Yn).max(l.referencesPerKey)})).max(l.keys)}).superRefine((t,n)=>{D(t.features.map(a=>a.key))||n.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),t.features.reduce((a,o)=>a+o.refs.length,0)>l.references&&n.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),$e=e.strictObject({scanId:e.uuid(),commit:e.string(),receivedAt:e.string(),references:e.number().int().nonnegative(),removedReferences:e.number().int().nonnegative()}),ea=$e.extend({repositoryId:e.uuid(),branch:$,workflow:e.string(),digest:e.string(),configurationRevision:e.number().int().positive(),runNumber:e.number().int().positive(),runAttempt:e.number().int().positive(),scannedAt:e.string(),keySetHash:e.string(),coverage:De.shape.coverage}),ta=e.strictObject({repositories:e.array(Cr).max(l.repositories),scans:e.array(ea).max(l.repositories*l.branches)}),ia=e.strictObject({key:Ge,references:e.number().int().nonnegative(),coveredTargets:e.number().int().nonnegative(),expiredTargets:e.number().int().nonnegative(),uncertainTargets:e.number().int().nonnegative()}),Zs=e.strictObject({available:e.boolean().default(!0),settings:ta,expectedTargets:e.number().int().min(0).max(80),features:e.array(ia).max(2001),truncated:e.boolean()});var g=e.iso.datetime({offset:!0}),wr=e.strictObject({invoiceId:e.uuid(),after:e.string().min(1).max(180).nullable(),limit:e.number().int().min(1).max(100)}),ra=e.strictObject({kind:e.literal("product"),key:e.string(),productVersionId:e.uuid(),productName:e.string(),itemKey:e.string(),entityId:e.uuid().nullable(),quantity:e.number().positive(),subtotalMinor:e.string().regex(/^-?\d+$/),discountMinor:e.string().regex(/^\d+$/),taxMinor:e.string().regex(/^-?\d+$/).nullable(),totalMinor:e.string().regex(/^-?\d+$/),startsAt:g.nullable(),endsAt:g.nullable(),providerLineId:e.string().nullable(),providerItemId:e.string()}),Br=e.strictObject({invoice:G,items:e.array(e.discriminatedUnion("kind",[ra,e.strictObject({kind:e.literal("invoice_credit"),key:e.string(),internal_feature_id:e.uuid(),internal_credit_feature_id:e.uuid(),name:e.string(),units:s,reserved:s,amountMinor:R,grossAmountMinor:R,creditsAppliedMinor:R,properties:h,cashPrice:E,providerItemId:e.string().nullable(),creditProviderItemId:e.string().nullable()}),e.strictObject({kind:e.literal("usage"),key:e.string(),internal_feature_id:e.uuid(),name:e.string(),units:s,reserved:s,amountMinor:R,cashPrice:E})])).max(100),nextCursor:e.string().min(1).max(180).nullable()}),na=e.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(t=>!/^\-0(?:\.0+)?$/.test(t)),Le=e.strictObject({from:g,to:g,entityId:e.uuid().optional(),snapshotAt:g.nullable(),after:e.strictObject({at:g,id:e.uuid(),position:e.number().int().nonnegative()}).nullable(),limit:e.number().int().min(1).max(100)}).refine(t=>Date.parse(t.from)<Date.parse(t.to)&&Date.parse(t.to)-Date.parse(t.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(t=>t.after===null||t.snapshotAt!==null,"A cursor requires the original snapshot time"),qr=e.strictObject({customerId:e.uuid(),entityId:e.uuid().nullable(),from:g,to:g,snapshotAt:g,totals:e.array(e.strictObject({internal_credit_feature_id:e.uuid(),name:e.string(),consumed:p,refunded:p,net:na})).max(1e3),rows:e.array(e.strictObject({operationId:e.uuid(),position:e.number().int().nonnegative(),kind:e.enum(["consume","confirm","refund"]),originalId:e.uuid().nullable(),occurredAt:g,internal_feature_id:e.uuid(),entitlementName:e.string(),sourceId:e.uuid(),internal_credit_feature_id:e.uuid(),creditName:e.string(),units:yt,amount:p,pricing:e.array(St).max(12),properties:h})).max(100),nextCursor:Le.shape.after});var d=e.string().min(1).max(200),ae=e.iso.datetime({offset:!0}),L=e.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Fe=e.number().int().min(0).max(1e12),zr=e.number().int().min(1).max(1e12),Tr={...f,type:e.literal("coupon.redeemed"),grantId:e.uuid()},kr={...f,type:e.literal("usage.observed"),merchantTransactionId:d,resource:d,unit:d,quantity:zr},aa=e.strictObject({...f,type:e.literal("fulfillment.updated"),operationId:e.uuid(),merchantFulfillmentId:d,status:e.enum(["pending","applied","failed"])}),sa=e.strictObject({...f,type:e.literal("benefit.claimed"),merchantBenefitId:d,resource:d,unit:d,quantity:zr,expiresAt:ae.nullable(),revision:L}),oa=e.strictObject({...f,type:e.literal("benefit.closed"),merchantBenefitId:d,status:e.enum(["failed","expired","canceled"]),revision:L}),ca=e.strictObject({...f,type:e.literal("benefit.updated"),merchantBenefitId:d,status:e.enum(["active","expired","revoked"]),remainingQuantity:Fe.nullable(),expiresAt:ae.nullable(),revision:L}),ua=e.strictObject({...f,type:e.literal("authorization.updated"),merchantAuthorizationId:d,kind:e.literal("auto_topup"),status:e.enum(["pending","effective","revoked","failed"]),termsReference:d.nullable(),revision:L}),da=e.strictObject({...f,type:e.literal("balance.observed"),resource:d,unit:d,availableQuantity:Fe,reservedQuantity:Fe,periodStartsAt:ae.nullable(),periodEndsAt:ae.nullable(),revision:L}),Ur=e.union([e.discriminatedUnion("type",[...He,aa,sa,oa,ca,ua,da]),e.strictObject({...Tr,productVersionId:e.uuid(),subscriptionId:e.string().trim().min(1).max(255)}),e.strictObject({...Tr,merchandiseId:e.uuid()}),e.strictObject({...kr,operation:e.literal("consume")}),e.strictObject({...kr,operation:e.literal("reverse"),reversalOf:d})]),Mr=e.strictObject({id:e.uuid(),eventId:e.string().min(1).max(200),source:e.literal("merchant"),providerVerified:e.literal(!1),outcome:e.string().min(1).max(100)});var Er=st,pa=Er.extend({invoice_id:Er.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),Ne=e.strictObject({name:e.string().trim().min(1).max(255),memo:e.string().max(1e4).nullable().optional(),footer:e.string().max(1e4).nullable().optional(),net_terms_days:e.number().int().positive().nullable().optional()}),la=Ne.extend({id:e.string().min(1).max(255),created_at:e.number().nullable()}),Gr=e.strictObject({items:e.array(la).max(50),nextCursor:e.uuid().nullable()}),so=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),requestId:e.uuid(),values:Ne}),e.strictObject({action:e.literal("update"),id:e.string().min(1).max(255),values:Ne}),e.strictObject({action:e.literal("delete"),id:e.string().min(1).max(255)})]),Dr=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),requestId:e.uuid(),params:P}),e.strictObject({action:e.enum(["finalize","send","pay","void"]),requestId:e.uuid(),invoiceId:e.uuid()}),e.strictObject({action:e.literal("reissue"),requestId:e.uuid(),invoiceId:e.uuid(),params:pa})]),Ve=e.strictObject({id:e.uuid(),customerId:e.uuid(),providerInvoiceId:e.string().nullable(),status:e.enum(["draft","open","paid","void","uncollectible"]),currency:e.string(),totalMinor:e.string().regex(/^-?\d+$/),paidMinor:e.string().regex(/^\d+$/),refundedMinor:e.string().regex(/^\d+$/),hostedInvoiceUrl:e.url().nullable(),createdAt:e.number(),collectionMethod:e.enum(["send_invoice","charge_automatically"]).nullable()}),$r=Ve.extend({lines:e.array(e.strictObject({id:e.uuid(),description:e.string(),amountMinor:e.string().regex(/^-?\d+$/),netAmountMinor:e.string().regex(/^-?\d+$/),quantity:e.number().nullable(),periodStart:e.number().nullable(),periodEnd:e.number().nullable()})).max(1e3)}),w=e.strictObject({taskId:e.uuid(),status:e.enum(["ready","running","done","dead"]),invoice:Ve.nullable(),errorCode:e.string().nullable()}),Lr=e.strictObject({items:e.array(Ve).max(50),nextCursor:e.uuid().nullable(),operations:e.array(w).max(50),operationsLimited:e.boolean()});var ga=e.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Fr={scope:se,permissions:e.array(ga),expiresAt:e.iso.datetime().nullable()},ec=e.discriminatedUnion("kind",[e.object({...Fr,kind:e.literal("server"),keyId:e.string().min(1)}),e.object({...Fr,kind:e.literal("customer"),customerId:e.string().min(1),identityKind:e.enum(["identified","guest"]),expiresAt:e.iso.datetime()})]),r=e.object({requestId:e.uuid(),scope:se}).strict(),ha=Ct.safeExtend({fingerprint:he.optional()}).strict(),fa=r.extend({customer:Q,created:e.boolean()});function Nr(){return r.extend({offer:ue.nullable(),reason:at.nullable()})}var i={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Nt,response:r.extend({message:e.object({messageId:e.uuid(),channel:T,acceptedAt:e.iso.datetime({offset:!0}),status:e.enum(["accepted","sending","completed","canceled"]),replayed:e.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:e.strictObject({messageId:e.uuid()}),response:r.extend({message:e.object({id:e.uuid(),channel:T,status:e.enum(["accepted","sending","completed","canceled"]),deliveries:e.array(e.object({id:e.uuid(),status:Qt,attempts:e.number().int().nonnegative(),receipts:e.array(e.object({kind:Zt,occurredAt:e.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Ut,response:r.extend({installation:Z})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Mt,response:r.extend({installation:Z})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:Et,response:r.extend({installation:Z})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:e.strictObject({channel:T}),response:r.extend({preference:fe})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Vt,response:r.extend({preference:fe})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:e.strictObject({cursor:e.uuid().optional()}),response:r.extend({templates:Gr})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:e.strictObject({customerId:e.uuid(),params:P}),response:r.extend({preview:de})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:e.strictObject({customerId:e.uuid(),requestId:e.uuid(),params:P}).refine(t=>t.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:r.extend({operation:w})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:e.strictObject({customerId:e.uuid(),command:Dr}).refine(t=>t.command.action!=="create"||t.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:r.extend({operation:w})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:e.strictObject({customerId:e.uuid(),taskId:e.uuid()}),response:r.extend({operation:w})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:e.strictObject({customerId:e.uuid(),cursor:e.uuid().optional()}),response:r.extend({invoices:Lr})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:e.strictObject({customerId:e.uuid(),invoiceId:e.uuid()}),response:r.extend({invoice:$r})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:_r,response:r.extend({config:Rr})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:De,response:r.extend({receipt:$e})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:e.strictObject({}),response:r.extend({payload:gt})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:ht,response:r.merge(ft)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:bt,response:r.merge(xt)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:e.strictObject({customerId:e.uuid(),sourceId:e.uuid()}),response:r.extend({balance:Pi})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:e.strictObject({customerId:e.uuid(),command:Ai}),response:r.extend({balance:we})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:e.strictObject({internal_feature_id:e.uuid(),customerId:e.uuid().optional(),entityId:e.uuid().optional()}).refine(t=>!t.entityId||!!t.customerId,"Entity pricing requires a customer"),response:r.extend({internal_feature_id:e.uuid(),config:Pe,model_markups:te})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:e.strictObject({customerId:e.uuid(),query:vt}),response:r.extend({usage:ge})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:e.strictObject({customerId:e.uuid(),command:Ot}),response:r.extend({usage:ge})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:e.strictObject({customerId:e.uuid(),command:qi}),response:r.extend({grant:Be})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Ti,response:r.extend({grants:ki})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:e.union(ci.options.map(t=>t.extend({customerId:e.uuid().optional(),customerToken:e.string().regex(We).optional()}))),response:r.extend({operation:ui})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Xt.extend({customerId:e.uuid().optional()}),response:r.extend({setup:Ie})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Jt.extend({customerId:e.uuid().optional()}),response:r.extend({setup:Ie})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Kt.safeExtend({customerId:e.uuid()}),response:r.extend({batch:k})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:K.extend({customerId:e.uuid()}),response:r.extend({batch:k})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:K.extend({customerId:e.uuid()}),response:r.extend({batch:k})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:K.extend({customerId:e.uuid()}),response:r.extend({batch:k})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:e.discriminatedUnion("action",[W.options[0].extend({customerId:e.uuid()}),W.options[1].extend({customerId:e.uuid()}),W.options[2].extend({customerId:e.uuid()})]),response:r.extend({trial:ye})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Wt.extend({customerId:e.uuid()}),response:r.extend({trial:ye})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:J,response:r.extend({subscriptions:ai})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:J,response:r.extend({purchases:si})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:ii,response:r.extend({conflicts:oi})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:ri,response:r.extend({resolution:ni})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:ei,response:r.extend({verification:ti})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:ot.safeExtend({...V,customerId:e.uuid().optional()}),response:r.extend({quote:ct})},recordMerchantEvent:{replay:"immutable_event",method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:Ur,response:r.extend({record:Mr})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:I.extend({customerId:e.uuid().optional(),intent:e.enum(["confirm","cancel"]).optional(),merchantConfirmation:N.optional()}),response:r.extend({operation:me})},readSubscriptionOperation:{replay:"read",method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:I.extend({customerId:e.uuid().optional()}),response:r.extend({operation:me})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:ut.safeExtend({customerId:e.uuid().optional()}),response:r.extend({quote:mt})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:I.extend({customerId:e.uuid().optional(),intent:e.enum(["confirm","cancel"]).optional(),merchantConfirmation:N.optional()}),response:r.extend({operation:pe})},readSubscriptionUpdate:{replay:"read",method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:I.extend({customerId:e.uuid().optional()}),response:r.extend({operation:pe})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:pt.safeExtend({customerId:e.uuid()}),response:r.extend({quote:lt})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:I.extend({customerId:e.uuid(),merchantConfirmation:N.optional()}),response:r.extend({operation:le})},readRefund:{replay:"read",method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:I.extend({customerId:e.uuid()}),response:r.extend({operation:le})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:xr,response:r.extend({controls:Ee})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:mr,response:r.extend({prepared:lr})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:gr,response:r.extend({authorization:ne})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Or,response:r.extend({coupons:Ar})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:hr,response:r.extend({authorization:ne})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Ir,response:r.extend({invoices:vr})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:yr.extend({customerId:e.uuid()}),response:r.extend({operation:w})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Sr,response:r.extend({invoice:G})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:e.object({customerId:e.uuid(),command:br}).strict(),response:r.extend({controls:Ee})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:e.object({customerId:e.uuid(),command:ji}).strict(),response:r.extend({entity:Ci})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:e.strictObject({customerId:e.uuid().nullable(),query:Ei}),response:r.extend({analytics:Gi})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:e.object({customerId:e.uuid().nullable(),query:A}).strict(),response:r.extend({analytics:Ui})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Di,response:r.extend({batchId:e.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:$i,response:r.extend({batch:Li})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Ye.extend({customerId:e.string().min(1).optional()}),response:r.extend({check:ce})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:e.strictObject({kind:tt,selector:e.discriminatedUnion("type",[e.strictObject({type:e.literal("resource"),id:e.uuid()}),e.strictObject({type:e.literal("version"),id:e.uuid()})]),customerId:e.string().min(1).optional()}),response:r.extend({content:it})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Tt,response:r.extend({paywall:kt})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:e.strictObject({processContext:rt.optional(),...V,selector:Ii,customerId:e.string().min(1).optional(),commerce:Xe,requirement:Je.optional()}),response:r.extend({offering:vi,candidates:e.array(et).max(20),availability:e.array(e.strictObject({productVersionId:e.uuid(),available:e.boolean(),reason:e.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:ce.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:e.object({customerId:e.uuid().optional(),entityId:e.uuid().optional()}).strict(),response:r.extend({holdings:At})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:e.object({customerId:e.uuid().optional(),query:Pt}).strict(),response:r.extend({ledger:jt})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:wr.extend({customerId:e.uuid().optional()}),response:r.extend({detail:Br})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Le.safeExtend({customerId:e.uuid().optional()}),response:r.extend({statement:qr})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:e.object({customerId:e.uuid().optional(),command:B.options[0]}).strict(),response:r.extend({quote:It})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:e.strictObject({customerId:e.uuid(),command:e.union([e.strictObject({eventName:e.string().min(1),quantity:s.optional(),properties:h.optional(),entityId:e.uuid().optional(),idempotencyKey:e.string().min(1).max(120)}),e.strictObject({internal_feature_id:e.uuid(),quantity:s.optional(),properties:h.optional(),entityId:e.uuid().optional(),idempotencyKey:e.string().min(1).max(120)})])}),response:r.extend({receipts:e.array(q).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:e.object({customerId:e.uuid(),command:B.refine(t=>t.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:r.extend({receipt:q})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Xi,response:r.extend({redemption:Hi})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:er,response:r.extend({referralCode:tr})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:Ji,response:r.extend({checkout:Yi})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:rr,response:r.extend({seats:Ue})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:nr,response:r.extend({seats:Ue})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:ha,response:fa},getCustomer:{replay:"read",method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Rt,response:r.extend({customer:Q})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Bt,response:r.extend(qt.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:wt,response:r.extend(_t.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:e.object({customerId:e.uuid()}).strict(),response:r.extend(F.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:e.strictObject({}),response:r.extend(F.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:e.strictObject({customerId:e.uuid(),sessionId:e.uuid().optional()}),response:r.extend({revoked:e.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:e.strictObject({guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:he.optional()}),response:r.extend({customerId:e.uuid(),guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:e.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:e.strictObject({guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:r.extend(F.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:e.strictObject({guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:e.string().trim().min(1).max(255).refine(t=>!t.startsWith("gg_guest_")),requestId:e.uuid()}),response:r.extend({customer:Q,switched:e.boolean(),replayed:e.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:e.strictObject({code:e.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:e.uuid()}),response:Nr()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:e.object({}).strict(),response:r.extend({offers:e.array(ue)})},grantModelBenefit:{method:"POST",path:"benefits/model-usage/grant",permission:"offers:grant",audience:"server",request:$t,response:r.extend({operation:xe})},readModelBenefit:{method:"POST",path:"benefits/model-usage/read",permission:"offers:grant",audience:"server",request:Lt,response:r.extend({operation:xe})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:e.object({customerId:e.string().min(1).max(255).optional(),couponId:e.uuid(),...V,requestId:e.uuid(),couponContentDigest:e.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Nr()}},tc={recordMerchantEvent:i.recordMerchantEvent,sendMessage:i.sendMessage,readMessage:i.readMessage,bindPushInstallation:i.bindPushInstallation,readPushInstallation:i.readPushInstallation,updatePushAddress:i.updatePushAddress,readMessagingPreference:i.readMessagingPreference,setMessagingPreference:i.setMessagingPreference,listInvoiceTemplates:i.listInvoiceTemplates,previewInvoice:i.previewInvoice,createInvoice:i.createInvoice,manageInvoice:i.manageInvoice,readInvoiceOperation:i.readInvoiceOperation,listInvoices:i.listInvoices,getInvoice:i.getInvoice,getCodeReferenceConfig:i.getCodeReferenceConfig,submitCodeReferences:i.submitCodeReferences,getFeatures:i.getFeatures,evaluateFeatures:i.evaluateFeatures,trackEvents:i.trackEvents,setupPayment:i.setupPayment,readPaymentSetup:i.readPaymentSetup,previewSubscriptionBatch:i.previewSubscriptionBatch,confirmSubscriptionBatch:i.confirmSubscriptionBatch,readSubscriptionBatch:i.readSubscriptionBatch,abandonSubscriptionBatch:i.abandonSubscriptionBatch,manageSubscriptionTrial:i.manageSubscriptionTrial,readSubscriptionTrial:i.readSubscriptionTrial,listSubscriptions:i.listSubscriptions,listPurchases:i.listPurchases,listSubscriptionConflicts:i.listSubscriptionConflicts,retrySubscriptionConflict:i.retrySubscriptionConflict,readAiPricing:i.readAiPricing,readUsage:i.readUsage,setUsage:i.setUsage,previewRefund:i.previewRefund,refund:i.refund,readRefund:i.readRefund,previewUpdate:i.previewUpdate,update:i.update,readSubscriptionUpdate:i.readSubscriptionUpdate,restoreNativePurchase:i.restoreNativePurchase,verifySubscriptions:i.verifySubscriptions,previewAttach:i.previewAttach,attach:i.attach,readSubscriptionOperation:i.readSubscriptionOperation,manageBalanceGrant:i.manageBalanceGrant,readBalanceSource:i.readBalanceSource,adjustBalance:i.adjustBalance,listBalanceGrants:i.listBalanceGrants,readBillingControls:i.readBillingControls,prepareBillingAuthorization:i.prepareBillingAuthorization,confirmBillingAuthorization:i.confirmBillingAuthorization,setBillingCoupons:i.setBillingCoupons,revokeBillingAuthorization:i.revokeBillingAuthorization,listBillingInvoices:i.listBillingInvoices,confirmBillingAdjustment:i.confirmBillingAdjustment,prepareBillingAdjustment:i.prepareBillingAdjustment,manageBillingLimits:i.manageBillingLimits,createCustomer:i.createCustomer,getCustomer:i.getCustomer,listCustomers:i.listCustomers,updateCustomer:i.updateCustomer,createSession:i.createSession,refreshSession:i.refreshSession,revokeSessions:i.revokeSessions,createGuestCustomer:i.createGuestCustomer,resumeGuestSession:i.resumeGuestSession,claimGuestCustomer:i.claimGuestCustomer,checkEntitlement:i.checkEntitlement,resolveOffering:i.resolveOffering,resolveContent:i.resolveContent,resolvePaywall:i.resolvePaywall,readHoldings:i.readHoldings,readLedger:i.readLedger,readBillingInvoice:i.readBillingInvoice,readCreditStatement:i.readCreditStatement,quoteBalance:i.quoteBalance,trackUsage:i.trackUsage,mutateBalance:i.mutateBalance,manageUsageEntity:i.manageUsageEntity,readUsageAnalytics:i.readUsageAnalytics,readCreditAnalytics:i.readCreditAnalytics,submitUsageBatch:i.submitUsageBatch,readUsageBatch:i.readUsageBatch,listOffers:i.listOffers,grantOffer:i.grantOffer,grantModelBenefit:i.grantModelBenefit,readModelBenefit:i.readModelBenefit,redeemCoupon:i.redeemCoupon,redeemReward:i.redeemReward,createReferralCode:i.createReferralCode,claimRewardProduct:i.claimRewardProduct,readSeats:i.readSeats,manageSeat:i.manageSeat};export{be as a,Dt as b,Gt as c,xa as d,i as e};