@tinkerlandai/longplay-sdk 0.10.65 → 0.10.66

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 (92) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +10 -0
  3. package/README.zh-CN.md +1 -1
  4. package/dist/check-response-WOTPYNDN.js +1 -0
  5. package/dist/{chunk-EB7MIZ4T.js → chunk-3Q3DZEP3.js} +1 -1
  6. package/dist/{chunk-R4CYPCBI.js → chunk-45MWDZ42.js} +1 -1
  7. package/dist/{chunk-TK3WOD2O.js → chunk-46USIMCJ.js} +1 -1
  8. package/dist/{chunk-ZCJEXNJD.js → chunk-47FCHF3Y.js} +1 -1
  9. package/dist/{chunk-ZRGL2CAP.js → chunk-56YCOGQZ.js} +1 -1
  10. package/dist/{chunk-S5RM3VO6.js → chunk-5WFI36LF.js} +1 -1
  11. package/dist/{chunk-77O2O552.js → chunk-74T76RE4.js} +1 -1
  12. package/dist/{chunk-4LQX4K5Q.js → chunk-7D5462NE.js} +1 -1
  13. package/dist/{chunk-HUYKZH3H.js → chunk-7EENIOSJ.js} +1 -1
  14. package/dist/chunk-7NKBMAOB.js +1 -0
  15. package/dist/{chunk-FQMZY5VP.js → chunk-7OJIW75D.js} +1 -1
  16. package/dist/{chunk-QXDLOPZK.js → chunk-A22QPPNY.js} +1 -1
  17. package/dist/{chunk-EKUDMQXT.js → chunk-AD35L6BX.js} +1 -1
  18. package/dist/{chunk-AHRBQWCA.js → chunk-C5FSL4XH.js} +2 -2
  19. package/dist/{chunk-PGLBFTRK.js → chunk-DCMA7W7N.js} +1 -1
  20. package/dist/{chunk-C3HZCZVJ.js → chunk-E3FUZSTM.js} +1 -1
  21. package/dist/{chunk-7PY3ACZY.js → chunk-EYTP23EK.js} +1 -1
  22. package/dist/{chunk-32AEJKJW.js → chunk-FUP5JVDE.js} +1 -1
  23. package/dist/{chunk-EE6QNOCL.js → chunk-G2OLUFYT.js} +1 -1
  24. package/dist/{chunk-PJHTN5NJ.js → chunk-GE6RSO2C.js} +1 -1
  25. package/dist/{chunk-YFOIOYTZ.js → chunk-HT5SLWWG.js} +1 -1
  26. package/dist/{chunk-7STWC4L4.js → chunk-IGE2UMXG.js} +1 -1
  27. package/dist/{chunk-5LNX7MHO.js → chunk-JBN6ADWQ.js} +1 -1
  28. package/dist/{chunk-IM5OXTEH.js → chunk-K675GO7R.js} +1 -1
  29. package/dist/{chunk-NDNHTG5B.js → chunk-KVLOMX2G.js} +1 -1
  30. package/dist/{chunk-OMJSBFMI.js → chunk-M6MXJHJ5.js} +1 -1
  31. package/dist/{chunk-DBYRJ4QV.js → chunk-MNICOIQ6.js} +1 -1
  32. package/dist/chunk-MUCDKWMP.js +1 -0
  33. package/dist/{chunk-US4MQ4ZG.js → chunk-MUP7FNNY.js} +1 -1
  34. package/dist/{chunk-JBSJ3JU2.js → chunk-N5HX3K5J.js} +1 -1
  35. package/dist/{chunk-KTWKDR5L.js → chunk-O5YYORDW.js} +1 -1
  36. package/dist/{chunk-VW2K4TZI.js → chunk-OFG3SGEX.js} +1 -1
  37. package/dist/{chunk-XCFAKO23.js → chunk-OKPWZZZW.js} +1 -1
  38. package/dist/{chunk-W7ATFFBO.js → chunk-OT55LG4U.js} +1 -1
  39. package/dist/{chunk-JEDRJAJ5.js → chunk-PNX7Y2K3.js} +1 -1
  40. package/dist/{chunk-2KM537QH.js → chunk-PQ4ISW55.js} +1 -1
  41. package/dist/{chunk-VXDVMAS6.js → chunk-Q523TPZM.js} +1 -1
  42. package/dist/{chunk-NAFHQVSX.js → chunk-QPVA644N.js} +1 -1
  43. package/dist/{chunk-G2CBJZEI.js → chunk-RHILCVPZ.js} +1 -1
  44. package/dist/{chunk-2RFI2DEV.js → chunk-RNCUAYLQ.js} +1 -1
  45. package/dist/{chunk-4SI4SQ3C.js → chunk-SAPICYY3.js} +1 -1
  46. package/dist/{chunk-BJW4AXFL.js → chunk-TXVLJFZG.js} +1 -1
  47. package/dist/{chunk-RIEWU4MN.js → chunk-XIBJF5E6.js} +1 -1
  48. package/dist/{chunk-KPILWKMK.js → chunk-YA5YKHDE.js} +1 -1
  49. package/dist/{chunk-VNYUL3PV.js → chunk-YUL23NAW.js} +1 -1
  50. package/dist/chunk-ZLSZBGJG.js +1 -0
  51. package/dist/{chunk-4OODZM64.js → chunk-ZWNWVMCH.js} +1 -1
  52. package/dist/{content-7HVO5QRZ.js → content-WWME7E27.js} +1 -1
  53. package/dist/funnel-host-purchase-XIGJ7P7M.js +1 -0
  54. package/dist/{funnel-host-recovery-paywall-D3VA3OIW.js → funnel-host-recovery-paywall-POMEY6I2.js} +1 -1
  55. package/dist/{funnel-paywall-copies-U3JIYQJ5.js → funnel-paywall-copies-DUZ3YX67.js} +1 -1
  56. package/dist/funnel-paywall-prerender-5NU457SR.js +1 -0
  57. package/dist/funnel-route-prediction-EW3HVH46.js +1 -0
  58. package/dist/funnel-route-source-YVFAFCVG.js +1 -0
  59. package/dist/funnel-runtime-host-J2HWW5IN.js +1 -0
  60. package/dist/index.d.ts +12 -6
  61. package/dist/index.js +1 -1
  62. package/dist/merchant-bridge-contracts-PNRVNTCN.js +1 -0
  63. package/dist/native-shell.js +1 -1
  64. package/dist/openrouter.js +1 -1
  65. package/dist/operation-contracts-6ORJSGYH.js +1 -0
  66. package/dist/page.js +1 -1
  67. package/dist/paywall-YRB7LQUS.js +1 -0
  68. package/dist/paywall-content-QLJIOFR3.js +1 -0
  69. package/dist/paywall-session-Q6ZYXUOU.js +1 -0
  70. package/dist/popup.js +1 -1
  71. package/dist/react-native.js +1 -1
  72. package/dist/screen-renderer-P6U5UBFX.js +1 -0
  73. package/dist/server.js +1 -1
  74. package/dist/visual.js +1 -1
  75. package/package.json +1 -1
  76. package/dist/check-response-K56UEZ6E.js +0 -1
  77. package/dist/chunk-6GIWQMRH.js +0 -1
  78. package/dist/chunk-75537OEL.js +0 -1
  79. package/dist/chunk-N7WQEC3L.js +0 -1
  80. package/dist/funnel-host-purchase-WNJ77ZPW.js +0 -1
  81. package/dist/funnel-paywall-prerender-AHG6D2TY.js +0 -1
  82. package/dist/funnel-route-prediction-XYWNKGQZ.js +0 -1
  83. package/dist/funnel-route-source-4ZVBFNYV.js +0 -1
  84. package/dist/funnel-runtime-host-KD2MR2MG.js +0 -1
  85. package/dist/merchant-bridge-contracts-IZ7ARRRO.js +0 -1
  86. package/dist/operation-contracts-6RQ33K66.js +0 -1
  87. package/dist/paywall-I3UXNTKB.js +0 -1
  88. package/dist/paywall-content-KYHTDMWU.js +0 -1
  89. package/dist/paywall-session-TNFSCXH6.js +0 -1
  90. package/dist/screen-renderer-3YO6EUWD.js +0 -1
  91. /package/dist/{chunk-AHRBQWCA.js.LEGAL.txt → chunk-C5FSL4XH.js.LEGAL.txt} +0 -0
  92. /package/dist/{chunk-PZTWDJHN.js → chunk-YLH3AYCK.js} +0 -0
@@ -1 +1 @@
1
- import{J as se,d as O,f as ie}from"./chunk-EKUDMQXT.js";import{a as F}from"./chunk-4OODZM64.js";import{b as te,f as ne,g as re,h as oe}from"./chunk-EB7MIZ4T.js";import{e as ee,k as ae}from"./chunk-DBYRJ4QV.js";import{s as ce}from"./chunk-VXDVMAS6.js";import{C as Y,e as J,j as Z,l as W,p as R,s as X,t as H,v as w,w as P,x as Q,z as k}from"./chunk-ZRGL2CAP.js";import{a as T,f as K}from"./chunk-KTWKDR5L.js";import{a as I,b as S,d as h,e as D,f as C,g as A}from"./chunk-FQMZY5VP.js";import{h as j}from"./chunk-RIEWU4MN.js";import{b as e}from"./chunk-PZTWDJHN.js";import{a as L,b as U}from"./chunk-CILM5XMH.js";var V=e.strictObject({eventsEnabled:e.boolean(),experimentViewsEnabled:e.boolean(),featureUsageEnabled:e.boolean()}),Ze=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function We(t,r){return r==="experiment_exposure"?t.experimentViewsEnabled:r==="feature_usage"?t.featureUsageEnabled:t.eventsEnabled}var z=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,r])=>t<=r),Se=e.strictObject({attribute:e.string().optional(),seed:e.string(),hashVersion:e.literal(2),ranges:e.array(z).max(100)}),we=e.strictObject({id:e.string().min(1).max(255),condition:C,gate:e.boolean().optional()}),Oe=e.strictObject({key:e.string().optional(),name:e.string().optional(),passthrough:e.boolean().optional()}),ue={condition:C.optional(),parentConditions:e.array(we).max(100).optional(),weights:e.array(e.number().min(0).max(1)).max(20).optional(),coverage:e.number().min(0).max(1).optional(),hashAttribute:e.string().optional(),fallbackAttribute:e.string().optional(),hashVersion:e.literal(2).optional(),disableStickyBucketing:e.boolean().optional(),bucketVersion:e.number().int().nonnegative().optional(),minBucketVersion:e.number().int().nonnegative().optional(),filters:e.array(Se).max(100).optional(),ranges:e.array(z).max(20).optional(),meta:e.array(Oe).max(20).optional(),seed:e.string().optional(),name:e.string().optional(),phase:e.string().optional()},pe=e.strictObject({...ue,key:e.string().min(1).max(255),variations:e.tuple([h,h]).rest(h).refine(t=>t.length<=20),urlPatterns:e.array(e.strictObject({include:e.boolean(),type:e.enum(["regex","simple"]),pattern:e.string()})).max(100).optional(),force:e.number().int().nonnegative().optional(),active:e.boolean().optional(),persistQueryString:e.boolean().optional()}),G=e.strictObject({value:h,variationId:e.number().int(),key:e.string(),name:e.string().optional(),bucket:e.number().optional(),passthrough:e.boolean().optional(),inExperiment:e.boolean(),hashUsed:e.boolean().optional(),hashAttribute:e.string(),hashValue:e.string(),featureId:e.string().nullable(),stickyBucketUsed:e.boolean().optional()}),je=e.strictObject({...ue,id:e.string().max(255).optional(),force:h.optional(),variations:e.array(h).min(2).max(20).optional(),key:e.string().optional(),range:z.optional(),tracks:e.array(e.strictObject({experiment:pe,result:G})).max(100).optional()}),Ie=e.strictObject({defaultValue:h.optional(),rules:e.array(je).max(500).optional()}),Pe=e.record(e.string(),e.union([e.strictObject({type:e.literal("hashed"),attributeKey:e.string(),values:e.array(e.string().regex(/^[a-f0-9]{64}$/))}),e.strictObject({type:e.literal("list"),attributeKey:e.string(),values:e.array(e.union([e.string(),e.number()]))}),e.strictObject({type:e.literal("condition"),condition:C})])),v=e.strictObject({scope:j,generation:e.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0}).nullable(),features:e.record(e.string(),Ie),savedGroups:Pe,experiments:e.record(e.uuid(),pe)});var ke=v.extend({analyticsConfig:V,remoteFeatures:e.array(e.string().min(1).max(255)).max(500)}),it=ke.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((t,r)=>{for(let a of t.remoteFeatures)Object.hasOwn(t.features,a)&&r.addIssue({code:"custom",path:["features",a],message:"Remote Feature definitions cannot be public"});for(let[a,o]of Object.entries(t.savedGroups))o.type==="list"&&r.addIssue({code:"custom",path:["savedGroups",a],message:"Raw Saved Group lists cannot be public"})}),at=e.strictObject({attributes:D,features:e.array(e.string().min(1).max(255)).max(500).optional(),customerId:e.uuid().optional()}),me=e.strictObject({value:h,source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:e.boolean(),off:e.boolean(),ruleId:e.string(),experimentResult:G.optional()}),st=e.strictObject({generation:v.shape.generation,evaluatedAt:v.shape.evaluatedAt,expiresAt:v.shape.expiresAt,features:e.record(e.string(),me),merchandiseContext:e.strictObject({merchandiseId:e.uuid(),merchandise:D}).optional()}),de={eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}),merchandise:te.optional(),deviceId:e.string().min(1).max(255).optional(),sessionId:e.string().min(1).max(255).optional()},le={...de,generation:v.shape.generation},Ce=e.discriminatedUnion("kind",[e.strictObject({...de,kind:e.literal("custom"),name:e.string().min(1).max(255),properties:e.record(e.string(),h).default({})}),e.strictObject({...le,kind:e.literal("experiment_exposure"),experimentId:e.string().min(1).max(255),variationId:e.string().min(1).max(255)}),e.strictObject({...le,kind:e.literal("feature_usage"),feature:e.string().min(1).max(255),value:h,source:me.shape.source,ruleId:e.string().max(255),variationId:e.string().min(1).max(255).optional()})]),ct=e.strictObject({customerId:e.uuid().optional(),events:e.array(Ce).min(1).max(100)}),Ae=e.strictObject({eventUuid:e.uuid(),reason:e.enum(["invalid_event","invalid_merchandise","not_delivered","reserved_name"])}),ut=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),rejected:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejections:e.array(Ae).max(100),analyticsConfig:V});function fe(t,r){let a=new Set,o=new Set,c=new Set,p=[],g=new Map,f=new Map,d=new Map;function m(s){for(let n of A(s))i(n)}function i(s){if(c.has(s)||!Object.hasOwn(r.savedGroups,s))return;let n=r.savedGroups[s];n&&(c.add(s),d.set(s,n),p.push(()=>{!Array.isArray(n)&&n.type==="condition"&&m(n.condition)}))}function u(s){for(let n of["hashAttribute","fallbackAttribute"])if(s[n]!==void 0&&ae(s[n]))throw new Error(`Funnel GB ${n} uses a reserved flow namespace`);m(s.condition);for(let n of s.parentConditions??[])l(n.id),m(n.condition)}function l(s,n=!1){let b=Object.hasOwn(r.features,s)?r.features[s]:void 0;if(!b){if(n)throw new Error("Required GB Feature is unavailable");return}a.has(s)||(a.add(s),g.set(s,b),p.push(()=>{for(let x of b.rules??[]){u(x);for(let ve of x.tracks??[])u(ve.experiment)}}))}function y(s){let n=Object.hasOwn(r.experiments,s)?r.experiments[s]:void 0;if(!n)throw new Error("Required GB Experiment is unavailable");o.has(s)||(o.add(s),f.set(s,n),p.push(()=>u(n)))}for(let s of t.graph.nodes){s.type==="feature"&&l(s.featureKey,!0),s.type==="split"&&y(s.experimentId),s.type==="condition"&&s.cases.forEach(b=>m(b.condition)),s.type==="offering"&&s.configuration.source==="feature"&&l(s.configuration.featureKey,!0);let n=s.type==="output"?s.value:s.type==="end"?s.output:null;n?.type==="feature"&&l(n.featureKey,!0)}for(let s of p)s();return{...r,features:Object.fromEntries(g),experiments:Object.fromEntries(f),savedGroups:Object.fromEntries(d)}}var ge=e.object({defaultLocale:R,locales:e.record(R,e.object({name:e.string().max(80),description:e.string().max(500)}).strict())}).strict().superRefine((t,r)=>{let a=Object.keys(t.locales);(!a.length||a.length>20||!t.locales[t.defaultLocale])&&r.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(t)).length>5e4&&r.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var M=e.discriminatedUnion("type",[e.strictObject({type:e.literal("event"),event:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),e.strictObject({type:e.literal("open_url"),url:e.url().refine(t=>new URL(t).protocol==="https:")})]),Fe=P,Ee=e.discriminatedUnion("type",[e.object({type:e.literal("checkout"),product:I}).strict(),e.object({type:e.literal("close")}).strict(),e.object({type:e.literal("action"),action:M}).strict()]),E=e.object({schemaVersion:e.literal(3),kind:e.literal("paywall"),name:e.string().trim().min(1).max(80),presentation:S,requirement:K.optional(),products:F,offeringVersionId:e.uuid().nullable(),offeringId:e.uuid(),screen:Fe,buttons:e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ee)}).strict(),Pt=E.superRefine((t,r)=>{(t.screen.surface!=="paywall"||t.screen.actions.some(o=>!["event","navigate"].includes(o.type)||o.close))&&r.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let o of Re(t))r.addIssue({code:"custom",message:o});for(let o of _e(t))r.addIssue({code:"custom",message:o});for(let o of t.screen.actions){let c=o.properties.closeControl;c!==void 0&&(c!=="content"||t.buttons[o.id]?.type!=="close")&&r.addIssue({code:"custom",path:["screen","actions",o.id],message:'Only a close button can carry closeControl, and its value is "content"'})}for(let o of t.screen.actions){let c=o.properties.couponBinding;c!==void 0&&(typeof c!="string"||!X.safeParse(c).success||t.buttons[o.id]?.type!=="checkout"||Y(t.screen,c)?.type!=="text")&&r.addIssue({code:"custom",path:["screen","actions",o.id],message:"Choose a Coupon text binding for this checkout action"})}k(t.screen).some(o=>!o.complete)&&r.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(t.buttons).length!==t.screen.actions.filter(o=>o.type!=="navigate").length||t.screen.actions.some(o=>o.type!=="navigate"&&!Object.hasOwn(t.buttons,o.id)))&&r.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(t.buttons).some(o=>o.type==="checkout")||r.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function _e(t){let r=t.products.items.map(p=>p.productVersionId),a=Z(t.screen),o=new Set,c=[];(!r.length||!t.products.defaultProductVersionId||!r.includes(t.products.defaultProductVersionId))&&c.push("products"),t.offeringVersionId||c.push("offering"),t.products.grouping&&(!W(t.products.grouping,r)||t.products.grouping.tiers.some(p=>!t.products.grouping.assignments.some(g=>g.tierId===p.id)))&&c.push("grouping");for(let p of Object.values(t.buttons))if(p.type==="checkout"){let g=p.product;if(g.type==="fixed")o.add(g.productVersionId);else{g.allowedProductVersionIds.forEach(m=>o.add(m));let f=!1,d=a[g.pickerId];d&&(f=!0,(g.allowedProductVersionIds.some(m=>!d.ids.includes(m))||d.ids.some(m=>!g.allowedProductVersionIds.includes(m)))&&c.push("picker")),w(t.screen,m=>{if(m.id!==g.pickerId||m.type!=="plan_picker")return;f=!0,(JSON.stringify(m.planIds)!==JSON.stringify(r)||JSON.stringify(g.allowedProductVersionIds)!==JSON.stringify(r)||m.defaultPlan!==t.products.defaultProductVersionId)&&c.push("picker");let i=m.grouping?{tiers:m.grouping.tiers,assignments:m.grouping.assignments}:void 0;JSON.stringify(i)!==JSON.stringify(t.products.grouping)&&c.push("grouping")}),f||c.push("picker")}}return(!o.size||[...o].some(p=>!r.includes(p)))&&c.push("purchase"),w(t.screen,p=>{p.type==="stack"&&p.productSlot&&!p.bind?.plan&&c.push(`productBinding:${p.id}`),(p.type==="stack"||p.type==="button")&&p.bind?.plan&&!r.includes(p.bind.plan)&&c.push("binding"),p.type==="plan_picker"&&(!p.planIds?.length||p.planIds.some(g=>!r.includes(g)))&&c.push("binding")}),[...new Set(c)]}function Re(t){let r=[],a=t.screen.pages.at(-1),o=new Map;for(let f of t.screen.pages)o.set(f.id,[]),Q(f.root,d=>{let m=d.type==="button"?d.action:d.type==="stack"?d.purchaseAction:void 0;if(m){let i=t.screen.actions.find(l=>l.id===m);i?.type==="navigate"&&o.get(f.id).push(i.pageId);let u=t.buttons[m];f.id!==a.id&&u&&u.type!=="close"&&r.push(`purchaseScreen:${d.id}`)}f.id!==a.id&&(d.type==="plan_picker"||d.type==="stack"&&d.productSlot)&&r.push(`packageScreen:${d.id}`)});let c=new Set;function p(f){if(!c.has(f)){c.add(f);for(let d of o.get(f)??[])p(d)}}let g=t.screen.initialPageId??t.screen.pages[0]?.id;g?p(g):r.push("initialPage");for(let f of t.screen.pages)c.has(f.id)||r.push(`unreachableScreen:${f.id}`);return[...new Set(r)]}var ye=e.object({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),revision:e.number().int().nonnegative(),state:e.enum(["active","archived"]),publishedVersionId:e.uuid().nullable(),updatedAt:e.iso.datetime({offset:!0}),draft:E}).strict(),kt=e.object({rows:e.array(ye).max(200),nextCursor:e.uuid().nullable()}).strict(),Ct=ye.omit({draft:!0}).extend({name:e.string(),productCount:e.number().int().nonnegative()}).strict(),At=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),document:E}).strict(),e.object({action:e.enum(["publish","archive"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Ft=e.object({paywalls:e.array(e.object({id:e.uuid(),paywallId:e.uuid(),version:e.number().int().positive(),name:e.string().min(1).max(80),presentation:S,buttons:E.shape.buttons}).strict()).max(500),limited:e.boolean()}).strict();var De=["customer_data","coupon_code"],be=e.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Ve=e.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),_=(t,r)=>new Set(t.map(r)).size===t.length,ze=e.strictObject({currency:T,amountMinor:e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Ge=e.strictObject({featureId:e.uuid(),name:e.string().trim().min(1).max(120),allowance:e.string().max(40).nullable(),access:e.boolean()}),Me=e.strictObject({stripe:e.strictObject({prices:e.array(ze).min(1).max(50)}).optional(),apple:e.strictObject({productIds:e.array(be).min(1).max(10)}).optional(),google:e.strictObject({products:e.array(e.strictObject({productId:be,basePlanId:Ve.nullable()})).min(1).max(10)}).optional()}).superRefine((t,r)=>{(t.stripe&&!_(t.stripe.prices,a=>a.currency)||t.apple&&!_(t.apple.productIds,a=>a)||t.google&&!_(t.google.products,a=>`${a.productId}:${a.basePlanId}`))&&r.addIssue({code:"custom",message:"Duplicate channel entry"})}),qe=e.strictObject({name:e.string().trim().min(1).max(80),interval:e.enum(["free","week","month","year","one_time"]),intervalCount:e.number().int().min(1).max(100),trial:e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}).nullable(),benefits:e.array(Ge).max(50).refine(t=>_(t,r=>r.featureId),"Duplicate benefit"),channels:Me,prepaid:e.array(J).max(100).optional()}),Be=e.strictObject({digest:O,content:e.strictObject({discount:ne,duration:re,appliesTo:oe,displayCopy:ge.nullable(),firstPurchaseOnly:e.boolean(),qualificationRequired:e.boolean(),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),grantWindowHours:e.number().int().positive(),perCustomerLimit:e.number().int().positive()})}),Ne=e.discriminatedUnion("type",[e.strictObject({type:e.literal("checkout"),product:I}),e.strictObject({type:e.literal("close")}),e.strictObject({type:e.literal("action"),action:M})]),Lt=e.strictObject({kind:e.literal("paywall"),formatVersion:e.literal(1),name:e.string().trim().min(1).max(80),offeringVersionId:e.uuid(),presentation:S,screen:P,products:F,catalog:e.record(e.uuid(),qe),buttons:e.record(H,Ne),coupons:e.record(e.uuid(),Be)}).superRefine((t,r)=>{let a=n=>r.addIssue({code:"custom",message:n}),{screen:o}=t;ce(o,t.catalog).forEach(a),o.surface!=="paywall"&&a("Screen must be a Paywall"),ie(o,De).forEach(a),k(o).some(n=>!n.complete)&&a("Every published locale must be complete");let c=new Set,p=new Set,g=new Set;w(o,n=>{let b="bind"in n?n.bind:void 0;b?.promotionCode&&a("Promotion codes must not be published"),b?.plan&&c.add(b.plan),b?.coupon&&p.add(b.coupon),n.type==="plan_picker"&&(n.planIds?.forEach(x=>c.add(x)),n.defaultPlan&&c.add(n.defaultPlan)),n.type==="text"&&n.feature&&g.add(n.feature.id)});let f=t.products.items.map(n=>n.productVersionId),d=Object.keys(t.catalog);(f.length!==d.length||f.some(n=>!Object.hasOwn(t.catalog,n)))&&a("Catalog must contain exactly the displayed Products");let m=new Set(f);t.products.defaultProductVersionId!==null&&!m.has(t.products.defaultProductVersionId)&&a("Default Product must be displayed");for(let n of c)m.has(n)||a("Screen references a Product that is not displayed");for(let n of Object.values(t.catalog))!n.channels.stripe&&!n.channels.apple&&!n.channels.google&&a("A displayed Product needs at least one sales channel");let i=new Set(Object.values(t.catalog).flatMap(n=>n.benefits.map(b=>b.featureId)));for(let n of g)i.has(n)||a("Feature text must read a displayed benefit");let u=o.actions.filter(n=>n.type!=="navigate");o.actions.some(n=>n.type!=="event"&&n.type!=="navigate")&&a("Paywall actions are events or navigation"),(Object.keys(t.buttons).length!==u.length||u.some(n=>!Object.hasOwn(t.buttons,n.id)))&&a("Buttons must match the screen's actions");let y=!1;for(let n of Object.values(t.buttons)){if(n.type!=="checkout")continue;y=!0,(n.product.type==="fixed"?[n.product.productVersionId]:n.product.allowedProductVersionIds).some(x=>!m.has(x))&&a("Checkout may only sell displayed Products")}y||a("A Paywall needs a checkout button");let s=Object.keys(t.coupons);(s.length!==p.size||s.some(n=>!p.has(n)))&&a("Coupons must be exactly the bound Coupons")}),he=e.strictObject({state:e.enum(["published","archived"]),controlRevision:e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:e.uuid(),versions:e.record(e.uuid(),e.strictObject({version:e.number().int().positive(),artifact:e.string().min(1),sourceDigest:e.string().regex(/^[a-f0-9]{64}$/)}))}).refine(t=>Object.keys(t.versions).length>0,"Reviewed Paywall Versions are required");var $e={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},q=e.string().regex(/^[a-f0-9]{64}$/),B=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Le=j.extend({environmentId:e.uuid()}),xe=e.strictObject({features:e.array(e.string()).max(500),experiments:e.record(e.uuid(),e.array(e.string()).max(20)),savedGroups:e.array(e.string()).max(1e3)}),Ue=e.strictObject({kind:e.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:e.number().int().positive(),url:e.string().min(1).max(2048),sha256:q,byteLength:e.number().int().positive().max($e.maxArtifactBytes),generation:q.optional()}),Te=e.strictObject({state:e.enum(["active","paused","archived"]),controlRevision:B,evaluationMode:e.enum(["local","remote"]),evaluationRevision:B,currentVersionId:e.uuid(),versions:e.record(e.uuid(),e.strictObject({artifact:e.string(),dependencies:xe,definitionDigest:O.optional(),couponDigests:e.record(e.uuid(),O).optional()}))}),en=e.strictObject({kind:e.literal("sdk_configuration"),schemaVersion:e.literal(1),scope:Le,revision:B,generation:q,policy:e.strictObject({refreshIntervalSeconds:e.number().positive().max(15),maxControlAgeSeconds:e.number().positive().max(60)}),gb:e.strictObject({features:e.string().nullable(),pageExperiments:e.string().nullable()}),artifacts:e.record(e.string(),Ue),funnels:e.record(e.uuid(),Te),paywalls:e.record(e.uuid(),he).optional()}).superRefine((t,r)=>{let a=(o,c)=>{o!==null&&t.artifacts[o]?.kind!==c&&r.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};a(t.gb.features,"gb_features"),a(t.gb.pageExperiments,"gb_page_experiments");for(let o of Object.values(t.paywalls??{}))for(let c of Object.values(o.versions))a(c.artifact,"paywall");for(let o of Object.values(t.funnels)){o.evaluationMode==="remote"&&Object.keys(o.versions).length&&r.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),o.evaluationMode==="local"&&!o.versions[o.currentVersionId]&&r.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let c of Object.values(o.versions))a(c.artifact,"funnel")}});function N(t){if(Array.isArray(t))return`[${t.map(N).join(",")}]`;if(t!==null&&typeof t=="object")return`{${Object.entries(t).sort(([a],[o])=>a<o?-1:a>o?1:0).map(([a,o])=>`${JSON.stringify(a)}:${N(o)}`).join(",")}}`;let r=JSON.stringify(t);if(r===void 0)throw new Error("Configuration must contain JSON values");return r}function Je(t){return L(U(typeof t=="string"?new TextEncoder().encode(t):t))}function tn(t){return Je(N(t))}var $=class extends Error{constructor(a,o){super(a);this.dependency=o}dependency};function nn(t,r){let a=i=>i.type==="feature"?i.featureKey:i.type==="end"&&i.output?.type==="feature"?i.output.featureKey:i.type==="output"&&i.value.type==="feature"?i.value.featureKey:void 0,o=(i,u)=>t.graph.nodes.find(l=>i==="experiment"?l.type==="split"&&l.experimentId===u:i==="feature"&&a(l)===u)?.name,c=(i,u,l=o(u.type,u.resource))=>new $(i,{...u,...l?{step:l}:{}});for(let i of Object.values(t.references)){let u=i.type==="flag"?!Object.hasOwn(r.features,i.key)||r.remoteFeatures.includes(i.key)?{type:"feature",resource:i.key}:null:i.type==="experiment"?Object.hasOwn(r.experiments,i.id)?null:{type:"experiment",resource:i.id}:i.type==="saved_group"&&!Object.hasOwn(r.savedGroups,i.id)?{type:"saved_group",resource:i.id}:null;if(u)throw c("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...u})}let p=fe(t,{...r,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),g=new Set(r.remoteFeatures);for(let i of t.graph.nodes){let u=a(i);if(!u)continue;let l=p.features[u],y=i.type==="feature"?t.variables[i.writes.value]:t.outputSchema,s={type:"feature",resource:u};if(!l||!y)throw c("Required public Feature declaration is unavailable",{reason:"unavailable",...s},i.name);if([l.defaultValue,...(l.rules??[]).flatMap(b=>[...Object.hasOwn(b,"force")?[b.force]:[],...b.variations??[],...(b.tracks??[]).flatMap(x=>x.experiment.variations)])].some(b=>b===void 0||!ee(y,b)))throw c("GB Feature values violate the Funnel type contract",{reason:"value_type",...s},i.name)}let f=new Set,d=(i,u)=>{for(let l of A(i)){if(f.has(l))continue;let y=r.savedGroups[l];if(!y)throw c("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:l},u);f.add(l),!Array.isArray(y)&&y.type==="condition"&&d(y.condition,u)}},m=(i,u)=>{if(g.has(i)||!r.features[i])throw c("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:i},u)};for(let i of t.graph.nodes)if(i.type==="condition")for(let u of i.cases)d(u.condition,i.name);for(let[i,u]of Object.entries(p.features)){let l=o("feature",i);for(let y of u.rules??[]){d(y.condition,l);for(let s of[...y.parentConditions??[],...(y.tracks??[]).flatMap(n=>n.experiment.parentConditions??[])])m(s.id,l),d(s.condition,l);for(let s of y.tracks??[])d(s.experiment.condition,l)}}for(let[i,u]of Object.entries(p.experiments)){let l=o("experiment",i);d(u.condition,l);for(let y of u.parentConditions??[])m(y.id,l),d(y.condition,l)}for(let i of t.graph.nodes)if(i.type==="split"){let u=p.experiments[i.experimentId],l={type:"experiment",resource:i.experimentId};if(!u)throw c("Local Funnel requires a public Experiment",{reason:"unavailable",...l},i.name);for(let y of u.variations)if(typeof y!="string"||!Object.hasOwn(i.routes,y))throw c("Experiment variation has no declared Funnel route",{reason:"variation_route",...l},i.name)}return xe.parse({features:Object.keys(p.features).sort(),experiments:Object.fromEntries(Object.entries(p.experiments).map(([i,u])=>[i,u.variations.map(String)])),savedGroups:[...f].sort()})}function rn(t){return se.parse(t)}export{E as a,We as b,pe as c,Pe as d,v as e,ke as f,it as g,at as h,st as i,ct as j,ut as k,fe as l,Lt as m,$e as n,Le as o,Ue as p,en as q,N as r,Je as s,tn as t,nn as u,rn as v};
1
+ import{J as se,d as O,f as ie}from"./chunk-AD35L6BX.js";import{a as F}from"./chunk-ZWNWVMCH.js";import{b as te,f as ne,g as re,h as oe}from"./chunk-3Q3DZEP3.js";import{e as ee,k as ae}from"./chunk-MNICOIQ6.js";import{s as ce}from"./chunk-Q523TPZM.js";import{C as Y,e as J,j as Z,l as W,p as R,s as X,t as H,v as w,w as P,x as Q,z as k}from"./chunk-56YCOGQZ.js";import{a as T,f as K}from"./chunk-O5YYORDW.js";import{a as I,b as S,d as h,e as D,f as C,g as A}from"./chunk-7OJIW75D.js";import{h as j}from"./chunk-XIBJF5E6.js";import{b as e}from"./chunk-YLH3AYCK.js";import{a as L,b as U}from"./chunk-CILM5XMH.js";var V=e.strictObject({eventsEnabled:e.boolean(),experimentViewsEnabled:e.boolean(),featureUsageEnabled:e.boolean()}),Ze=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function We(t,r){return r==="experiment_exposure"?t.experimentViewsEnabled:r==="feature_usage"?t.featureUsageEnabled:t.eventsEnabled}var z=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,r])=>t<=r),Se=e.strictObject({attribute:e.string().optional(),seed:e.string(),hashVersion:e.literal(2),ranges:e.array(z).max(100)}),we=e.strictObject({id:e.string().min(1).max(255),condition:C,gate:e.boolean().optional()}),Oe=e.strictObject({key:e.string().optional(),name:e.string().optional(),passthrough:e.boolean().optional()}),ue={condition:C.optional(),parentConditions:e.array(we).max(100).optional(),weights:e.array(e.number().min(0).max(1)).max(20).optional(),coverage:e.number().min(0).max(1).optional(),hashAttribute:e.string().optional(),fallbackAttribute:e.string().optional(),hashVersion:e.literal(2).optional(),disableStickyBucketing:e.boolean().optional(),bucketVersion:e.number().int().nonnegative().optional(),minBucketVersion:e.number().int().nonnegative().optional(),filters:e.array(Se).max(100).optional(),ranges:e.array(z).max(20).optional(),meta:e.array(Oe).max(20).optional(),seed:e.string().optional(),name:e.string().optional(),phase:e.string().optional()},pe=e.strictObject({...ue,key:e.string().min(1).max(255),variations:e.tuple([h,h]).rest(h).refine(t=>t.length<=20),urlPatterns:e.array(e.strictObject({include:e.boolean(),type:e.enum(["regex","simple"]),pattern:e.string()})).max(100).optional(),force:e.number().int().nonnegative().optional(),active:e.boolean().optional(),persistQueryString:e.boolean().optional()}),G=e.strictObject({value:h,variationId:e.number().int(),key:e.string(),name:e.string().optional(),bucket:e.number().optional(),passthrough:e.boolean().optional(),inExperiment:e.boolean(),hashUsed:e.boolean().optional(),hashAttribute:e.string(),hashValue:e.string(),featureId:e.string().nullable(),stickyBucketUsed:e.boolean().optional()}),je=e.strictObject({...ue,id:e.string().max(255).optional(),force:h.optional(),variations:e.array(h).min(2).max(20).optional(),key:e.string().optional(),range:z.optional(),tracks:e.array(e.strictObject({experiment:pe,result:G})).max(100).optional()}),Ie=e.strictObject({defaultValue:h.optional(),rules:e.array(je).max(500).optional()}),Pe=e.record(e.string(),e.union([e.strictObject({type:e.literal("hashed"),attributeKey:e.string(),values:e.array(e.string().regex(/^[a-f0-9]{64}$/))}),e.strictObject({type:e.literal("list"),attributeKey:e.string(),values:e.array(e.union([e.string(),e.number()]))}),e.strictObject({type:e.literal("condition"),condition:C})])),v=e.strictObject({scope:j,generation:e.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0}).nullable(),features:e.record(e.string(),Ie),savedGroups:Pe,experiments:e.record(e.uuid(),pe)});var ke=v.extend({analyticsConfig:V,remoteFeatures:e.array(e.string().min(1).max(255)).max(500)}),it=ke.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((t,r)=>{for(let a of t.remoteFeatures)Object.hasOwn(t.features,a)&&r.addIssue({code:"custom",path:["features",a],message:"Remote Feature definitions cannot be public"});for(let[a,o]of Object.entries(t.savedGroups))o.type==="list"&&r.addIssue({code:"custom",path:["savedGroups",a],message:"Raw Saved Group lists cannot be public"})}),at=e.strictObject({attributes:D,features:e.array(e.string().min(1).max(255)).max(500).optional(),customerId:e.uuid().optional()}),me=e.strictObject({value:h,source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:e.boolean(),off:e.boolean(),ruleId:e.string(),experimentResult:G.optional()}),st=e.strictObject({generation:v.shape.generation,evaluatedAt:v.shape.evaluatedAt,expiresAt:v.shape.expiresAt,features:e.record(e.string(),me),merchandiseContext:e.strictObject({merchandiseId:e.uuid(),merchandise:D}).optional()}),de={eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}),merchandise:te.optional(),deviceId:e.string().min(1).max(255).optional(),sessionId:e.string().min(1).max(255).optional()},le={...de,generation:v.shape.generation},Ce=e.discriminatedUnion("kind",[e.strictObject({...de,kind:e.literal("custom"),name:e.string().min(1).max(255),properties:e.record(e.string(),h).default({})}),e.strictObject({...le,kind:e.literal("experiment_exposure"),experimentId:e.string().min(1).max(255),variationId:e.string().min(1).max(255)}),e.strictObject({...le,kind:e.literal("feature_usage"),feature:e.string().min(1).max(255),value:h,source:me.shape.source,ruleId:e.string().max(255),variationId:e.string().min(1).max(255).optional()})]),ct=e.strictObject({customerId:e.uuid().optional(),events:e.array(Ce).min(1).max(100)}),Ae=e.strictObject({eventUuid:e.uuid(),reason:e.enum(["invalid_event","invalid_merchandise","not_delivered","reserved_name"])}),ut=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),rejected:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejections:e.array(Ae).max(100),analyticsConfig:V});function fe(t,r){let a=new Set,o=new Set,c=new Set,p=[],g=new Map,f=new Map,d=new Map;function m(s){for(let n of A(s))i(n)}function i(s){if(c.has(s)||!Object.hasOwn(r.savedGroups,s))return;let n=r.savedGroups[s];n&&(c.add(s),d.set(s,n),p.push(()=>{!Array.isArray(n)&&n.type==="condition"&&m(n.condition)}))}function u(s){for(let n of["hashAttribute","fallbackAttribute"])if(s[n]!==void 0&&ae(s[n]))throw new Error(`Funnel GB ${n} uses a reserved flow namespace`);m(s.condition);for(let n of s.parentConditions??[])l(n.id),m(n.condition)}function l(s,n=!1){let b=Object.hasOwn(r.features,s)?r.features[s]:void 0;if(!b){if(n)throw new Error("Required GB Feature is unavailable");return}a.has(s)||(a.add(s),g.set(s,b),p.push(()=>{for(let x of b.rules??[]){u(x);for(let ve of x.tracks??[])u(ve.experiment)}}))}function y(s){let n=Object.hasOwn(r.experiments,s)?r.experiments[s]:void 0;if(!n)throw new Error("Required GB Experiment is unavailable");o.has(s)||(o.add(s),f.set(s,n),p.push(()=>u(n)))}for(let s of t.graph.nodes){s.type==="feature"&&l(s.featureKey,!0),s.type==="split"&&y(s.experimentId),s.type==="condition"&&s.cases.forEach(b=>m(b.condition)),s.type==="offering"&&s.configuration.source==="feature"&&l(s.configuration.featureKey,!0);let n=s.type==="output"?s.value:s.type==="end"?s.output:null;n?.type==="feature"&&l(n.featureKey,!0)}for(let s of p)s();return{...r,features:Object.fromEntries(g),experiments:Object.fromEntries(f),savedGroups:Object.fromEntries(d)}}var ge=e.object({defaultLocale:R,locales:e.record(R,e.object({name:e.string().max(80),description:e.string().max(500)}).strict())}).strict().superRefine((t,r)=>{let a=Object.keys(t.locales);(!a.length||a.length>20||!t.locales[t.defaultLocale])&&r.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(t)).length>5e4&&r.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var M=e.discriminatedUnion("type",[e.strictObject({type:e.literal("event"),event:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),e.strictObject({type:e.literal("open_url"),url:e.url().refine(t=>new URL(t).protocol==="https:")})]),Fe=P,Ee=e.discriminatedUnion("type",[e.object({type:e.literal("checkout"),product:I}).strict(),e.object({type:e.literal("close")}).strict(),e.object({type:e.literal("action"),action:M}).strict()]),E=e.object({schemaVersion:e.literal(3),kind:e.literal("paywall"),name:e.string().trim().min(1).max(80),presentation:S,requirement:K.optional(),products:F,offeringVersionId:e.uuid().nullable(),offeringId:e.uuid(),screen:Fe,buttons:e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ee)}).strict(),Pt=E.superRefine((t,r)=>{(t.screen.surface!=="paywall"||t.screen.actions.some(o=>!["event","navigate"].includes(o.type)||o.close))&&r.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let o of Re(t))r.addIssue({code:"custom",message:o});for(let o of _e(t))r.addIssue({code:"custom",message:o});for(let o of t.screen.actions){let c=o.properties.closeControl;c!==void 0&&(c!=="content"||t.buttons[o.id]?.type!=="close")&&r.addIssue({code:"custom",path:["screen","actions",o.id],message:'Only a close button can carry closeControl, and its value is "content"'})}for(let o of t.screen.actions){let c=o.properties.couponBinding;c!==void 0&&(typeof c!="string"||!X.safeParse(c).success||t.buttons[o.id]?.type!=="checkout"||Y(t.screen,c)?.type!=="text")&&r.addIssue({code:"custom",path:["screen","actions",o.id],message:"Choose a Coupon text binding for this checkout action"})}k(t.screen).some(o=>!o.complete)&&r.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(t.buttons).length!==t.screen.actions.filter(o=>o.type!=="navigate").length||t.screen.actions.some(o=>o.type!=="navigate"&&!Object.hasOwn(t.buttons,o.id)))&&r.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(t.buttons).some(o=>o.type==="checkout")||r.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function _e(t){let r=t.products.items.map(p=>p.productVersionId),a=Z(t.screen),o=new Set,c=[];(!r.length||!t.products.defaultProductVersionId||!r.includes(t.products.defaultProductVersionId))&&c.push("products"),t.offeringVersionId||c.push("offering"),t.products.grouping&&(!W(t.products.grouping,r)||t.products.grouping.tiers.some(p=>!t.products.grouping.assignments.some(g=>g.tierId===p.id)))&&c.push("grouping");for(let p of Object.values(t.buttons))if(p.type==="checkout"){let g=p.product;if(g.type==="fixed")o.add(g.productVersionId);else{g.allowedProductVersionIds.forEach(m=>o.add(m));let f=!1,d=a[g.pickerId];d&&(f=!0,(g.allowedProductVersionIds.some(m=>!d.ids.includes(m))||d.ids.some(m=>!g.allowedProductVersionIds.includes(m)))&&c.push("picker")),w(t.screen,m=>{if(m.id!==g.pickerId||m.type!=="plan_picker")return;f=!0,(JSON.stringify(m.planIds)!==JSON.stringify(r)||JSON.stringify(g.allowedProductVersionIds)!==JSON.stringify(r)||m.defaultPlan!==t.products.defaultProductVersionId)&&c.push("picker");let i=m.grouping?{tiers:m.grouping.tiers,assignments:m.grouping.assignments}:void 0;JSON.stringify(i)!==JSON.stringify(t.products.grouping)&&c.push("grouping")}),f||c.push("picker")}}return(!o.size||[...o].some(p=>!r.includes(p)))&&c.push("purchase"),w(t.screen,p=>{p.type==="stack"&&p.productSlot&&!p.bind?.plan&&c.push(`productBinding:${p.id}`),(p.type==="stack"||p.type==="button")&&p.bind?.plan&&!r.includes(p.bind.plan)&&c.push("binding"),p.type==="plan_picker"&&(!p.planIds?.length||p.planIds.some(g=>!r.includes(g)))&&c.push("binding")}),[...new Set(c)]}function Re(t){let r=[],a=t.screen.pages.at(-1),o=new Map;for(let f of t.screen.pages)o.set(f.id,[]),Q(f.root,d=>{let m=d.type==="button"?d.action:d.type==="stack"?d.purchaseAction:void 0;if(m){let i=t.screen.actions.find(l=>l.id===m);i?.type==="navigate"&&o.get(f.id).push(i.pageId);let u=t.buttons[m];f.id!==a.id&&u&&u.type!=="close"&&r.push(`purchaseScreen:${d.id}`)}f.id!==a.id&&(d.type==="plan_picker"||d.type==="stack"&&d.productSlot)&&r.push(`packageScreen:${d.id}`)});let c=new Set;function p(f){if(!c.has(f)){c.add(f);for(let d of o.get(f)??[])p(d)}}let g=t.screen.initialPageId??t.screen.pages[0]?.id;g?p(g):r.push("initialPage");for(let f of t.screen.pages)c.has(f.id)||r.push(`unreachableScreen:${f.id}`);return[...new Set(r)]}var ye=e.object({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),revision:e.number().int().nonnegative(),state:e.enum(["active","archived"]),publishedVersionId:e.uuid().nullable(),updatedAt:e.iso.datetime({offset:!0}),draft:E}).strict(),kt=e.object({rows:e.array(ye).max(200),nextCursor:e.uuid().nullable()}).strict(),Ct=ye.omit({draft:!0}).extend({name:e.string(),productCount:e.number().int().nonnegative()}).strict(),At=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),document:E}).strict(),e.object({action:e.enum(["publish","archive"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Ft=e.object({paywalls:e.array(e.object({id:e.uuid(),paywallId:e.uuid(),version:e.number().int().positive(),name:e.string().min(1).max(80),presentation:S,buttons:E.shape.buttons}).strict()).max(500),limited:e.boolean()}).strict();var De=["customer_data","coupon_code"],be=e.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Ve=e.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),_=(t,r)=>new Set(t.map(r)).size===t.length,ze=e.strictObject({currency:T,amountMinor:e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Ge=e.strictObject({featureId:e.uuid(),name:e.string().trim().min(1).max(120),allowance:e.string().max(40).nullable(),access:e.boolean()}),Me=e.strictObject({stripe:e.strictObject({prices:e.array(ze).min(1).max(50)}).optional(),apple:e.strictObject({productIds:e.array(be).min(1).max(10)}).optional(),google:e.strictObject({products:e.array(e.strictObject({productId:be,basePlanId:Ve.nullable()})).min(1).max(10)}).optional()}).superRefine((t,r)=>{(t.stripe&&!_(t.stripe.prices,a=>a.currency)||t.apple&&!_(t.apple.productIds,a=>a)||t.google&&!_(t.google.products,a=>`${a.productId}:${a.basePlanId}`))&&r.addIssue({code:"custom",message:"Duplicate channel entry"})}),qe=e.strictObject({name:e.string().trim().min(1).max(80),interval:e.enum(["free","week","month","year","one_time"]),intervalCount:e.number().int().min(1).max(100),trial:e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}).nullable(),benefits:e.array(Ge).max(50).refine(t=>_(t,r=>r.featureId),"Duplicate benefit"),channels:Me,prepaid:e.array(J).max(100).optional()}),Be=e.strictObject({digest:O,content:e.strictObject({discount:ne,duration:re,appliesTo:oe,displayCopy:ge.nullable(),firstPurchaseOnly:e.boolean(),qualificationRequired:e.boolean(),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),grantWindowHours:e.number().int().positive(),perCustomerLimit:e.number().int().positive()})}),Ne=e.discriminatedUnion("type",[e.strictObject({type:e.literal("checkout"),product:I}),e.strictObject({type:e.literal("close")}),e.strictObject({type:e.literal("action"),action:M})]),Lt=e.strictObject({kind:e.literal("paywall"),formatVersion:e.literal(1),name:e.string().trim().min(1).max(80),offeringVersionId:e.uuid(),presentation:S,screen:P,products:F,catalog:e.record(e.uuid(),qe),buttons:e.record(H,Ne),coupons:e.record(e.uuid(),Be)}).superRefine((t,r)=>{let a=n=>r.addIssue({code:"custom",message:n}),{screen:o}=t;ce(o,t.catalog).forEach(a),o.surface!=="paywall"&&a("Screen must be a Paywall"),ie(o,De).forEach(a),k(o).some(n=>!n.complete)&&a("Every published locale must be complete");let c=new Set,p=new Set,g=new Set;w(o,n=>{let b="bind"in n?n.bind:void 0;b?.promotionCode&&a("Promotion codes must not be published"),b?.plan&&c.add(b.plan),b?.coupon&&p.add(b.coupon),n.type==="plan_picker"&&(n.planIds?.forEach(x=>c.add(x)),n.defaultPlan&&c.add(n.defaultPlan)),n.type==="text"&&n.feature&&g.add(n.feature.id)});let f=t.products.items.map(n=>n.productVersionId),d=Object.keys(t.catalog);(f.length!==d.length||f.some(n=>!Object.hasOwn(t.catalog,n)))&&a("Catalog must contain exactly the displayed Products");let m=new Set(f);t.products.defaultProductVersionId!==null&&!m.has(t.products.defaultProductVersionId)&&a("Default Product must be displayed");for(let n of c)m.has(n)||a("Screen references a Product that is not displayed");for(let n of Object.values(t.catalog))!n.channels.stripe&&!n.channels.apple&&!n.channels.google&&a("A displayed Product needs at least one sales channel");let i=new Set(Object.values(t.catalog).flatMap(n=>n.benefits.map(b=>b.featureId)));for(let n of g)i.has(n)||a("Feature text must read a displayed benefit");let u=o.actions.filter(n=>n.type!=="navigate");o.actions.some(n=>n.type!=="event"&&n.type!=="navigate")&&a("Paywall actions are events or navigation"),(Object.keys(t.buttons).length!==u.length||u.some(n=>!Object.hasOwn(t.buttons,n.id)))&&a("Buttons must match the screen's actions");let y=!1;for(let n of Object.values(t.buttons)){if(n.type!=="checkout")continue;y=!0,(n.product.type==="fixed"?[n.product.productVersionId]:n.product.allowedProductVersionIds).some(x=>!m.has(x))&&a("Checkout may only sell displayed Products")}y||a("A Paywall needs a checkout button");let s=Object.keys(t.coupons);(s.length!==p.size||s.some(n=>!p.has(n)))&&a("Coupons must be exactly the bound Coupons")}),he=e.strictObject({state:e.enum(["published","archived"]),controlRevision:e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:e.uuid(),versions:e.record(e.uuid(),e.strictObject({version:e.number().int().positive(),artifact:e.string().min(1),sourceDigest:e.string().regex(/^[a-f0-9]{64}$/)}))}).refine(t=>Object.keys(t.versions).length>0,"Reviewed Paywall Versions are required");var $e={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},q=e.string().regex(/^[a-f0-9]{64}$/),B=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Le=j.extend({environmentId:e.uuid()}),xe=e.strictObject({features:e.array(e.string()).max(500),experiments:e.record(e.uuid(),e.array(e.string()).max(20)),savedGroups:e.array(e.string()).max(1e3)}),Ue=e.strictObject({kind:e.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:e.number().int().positive(),url:e.string().min(1).max(2048),sha256:q,byteLength:e.number().int().positive().max($e.maxArtifactBytes),generation:q.optional()}),Te=e.strictObject({state:e.enum(["active","paused","archived"]),controlRevision:B,evaluationMode:e.enum(["local","remote"]),evaluationRevision:B,currentVersionId:e.uuid(),versions:e.record(e.uuid(),e.strictObject({artifact:e.string(),dependencies:xe,definitionDigest:O.optional(),couponDigests:e.record(e.uuid(),O).optional()}))}),en=e.strictObject({kind:e.literal("sdk_configuration"),schemaVersion:e.literal(1),scope:Le,revision:B,generation:q,policy:e.strictObject({refreshIntervalSeconds:e.number().positive().max(15),maxControlAgeSeconds:e.number().positive().max(60)}),gb:e.strictObject({features:e.string().nullable(),pageExperiments:e.string().nullable()}),artifacts:e.record(e.string(),Ue),funnels:e.record(e.uuid(),Te),paywalls:e.record(e.uuid(),he).optional()}).superRefine((t,r)=>{let a=(o,c)=>{o!==null&&t.artifacts[o]?.kind!==c&&r.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};a(t.gb.features,"gb_features"),a(t.gb.pageExperiments,"gb_page_experiments");for(let o of Object.values(t.paywalls??{}))for(let c of Object.values(o.versions))a(c.artifact,"paywall");for(let o of Object.values(t.funnels)){o.evaluationMode==="remote"&&Object.keys(o.versions).length&&r.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),o.evaluationMode==="local"&&!o.versions[o.currentVersionId]&&r.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let c of Object.values(o.versions))a(c.artifact,"funnel")}});function N(t){if(Array.isArray(t))return`[${t.map(N).join(",")}]`;if(t!==null&&typeof t=="object")return`{${Object.entries(t).sort(([a],[o])=>a<o?-1:a>o?1:0).map(([a,o])=>`${JSON.stringify(a)}:${N(o)}`).join(",")}}`;let r=JSON.stringify(t);if(r===void 0)throw new Error("Configuration must contain JSON values");return r}function Je(t){return L(U(typeof t=="string"?new TextEncoder().encode(t):t))}function tn(t){return Je(N(t))}var $=class extends Error{constructor(a,o){super(a);this.dependency=o}dependency};function nn(t,r){let a=i=>i.type==="feature"?i.featureKey:i.type==="end"&&i.output?.type==="feature"?i.output.featureKey:i.type==="output"&&i.value.type==="feature"?i.value.featureKey:void 0,o=(i,u)=>t.graph.nodes.find(l=>i==="experiment"?l.type==="split"&&l.experimentId===u:i==="feature"&&a(l)===u)?.name,c=(i,u,l=o(u.type,u.resource))=>new $(i,{...u,...l?{step:l}:{}});for(let i of Object.values(t.references)){let u=i.type==="flag"?!Object.hasOwn(r.features,i.key)||r.remoteFeatures.includes(i.key)?{type:"feature",resource:i.key}:null:i.type==="experiment"?Object.hasOwn(r.experiments,i.id)?null:{type:"experiment",resource:i.id}:i.type==="saved_group"&&!Object.hasOwn(r.savedGroups,i.id)?{type:"saved_group",resource:i.id}:null;if(u)throw c("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...u})}let p=fe(t,{...r,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),g=new Set(r.remoteFeatures);for(let i of t.graph.nodes){let u=a(i);if(!u)continue;let l=p.features[u],y=i.type==="feature"?t.variables[i.writes.value]:t.outputSchema,s={type:"feature",resource:u};if(!l||!y)throw c("Required public Feature declaration is unavailable",{reason:"unavailable",...s},i.name);if([l.defaultValue,...(l.rules??[]).flatMap(b=>[...Object.hasOwn(b,"force")?[b.force]:[],...b.variations??[],...(b.tracks??[]).flatMap(x=>x.experiment.variations)])].some(b=>b===void 0||!ee(y,b)))throw c("GB Feature values violate the Funnel type contract",{reason:"value_type",...s},i.name)}let f=new Set,d=(i,u)=>{for(let l of A(i)){if(f.has(l))continue;let y=r.savedGroups[l];if(!y)throw c("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:l},u);f.add(l),!Array.isArray(y)&&y.type==="condition"&&d(y.condition,u)}},m=(i,u)=>{if(g.has(i)||!r.features[i])throw c("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:i},u)};for(let i of t.graph.nodes)if(i.type==="condition")for(let u of i.cases)d(u.condition,i.name);for(let[i,u]of Object.entries(p.features)){let l=o("feature",i);for(let y of u.rules??[]){d(y.condition,l);for(let s of[...y.parentConditions??[],...(y.tracks??[]).flatMap(n=>n.experiment.parentConditions??[])])m(s.id,l),d(s.condition,l);for(let s of y.tracks??[])d(s.experiment.condition,l)}}for(let[i,u]of Object.entries(p.experiments)){let l=o("experiment",i);d(u.condition,l);for(let y of u.parentConditions??[])m(y.id,l),d(y.condition,l)}for(let i of t.graph.nodes)if(i.type==="split"){let u=p.experiments[i.experimentId],l={type:"experiment",resource:i.experimentId};if(!u)throw c("Local Funnel requires a public Experiment",{reason:"unavailable",...l},i.name);for(let y of u.variations)if(typeof y!="string"||!Object.hasOwn(i.routes,y))throw c("Experiment variation has no declared Funnel route",{reason:"variation_route",...l},i.name)}return xe.parse({features:Object.keys(p.features).sort(),experiments:Object.fromEntries(Object.entries(p.experiments).map(([i,u])=>[i,u.variations.map(String)])),savedGroups:[...f].sort()})}function rn(t){return se.parse(t)}export{E as a,We as b,pe as c,Pe as d,v as e,ke as f,it as g,at as h,st as i,ct as j,ut as k,fe as l,Lt as m,$e as n,Le as o,Ue as p,en as q,N as r,Je as s,tn as t,nn as u,rn as v};
@@ -1 +1 @@
1
- import{b as p,c as d}from"./chunk-EKUDMQXT.js";import{t as a,w as u,z as m}from"./chunk-ZRGL2CAP.js";import{b as e}from"./chunk-PZTWDJHN.js";var s=e.enum(["page","popup","banner"]),y=3e5,f=e.strictObject({type:e.enum(["string","number","boolean","strings","json"]),nullable:e.boolean()}),h=e.strictObject({inputs:e.record(a,f.extend({required:e.boolean()})).refine(t=>Object.keys(t).length<=40,"Too many content inputs"),outputs:e.record(a,f).refine(t=>Object.keys(t).length<=40,"Too many content outputs")}),g=e.strictObject({kind:s,schemaVersion:e.literal(1),name:e.string().trim().min(1).max(80),screen:u,contract:h}),c=g.superRefine((t,r)=>{let n=(o,b)=>r.addIssue({code:"custom",message:o,path:b});t.screen.surface!==t.kind&&n("Content surface must match its domain",["screen","surface"]),t.screen.name!==t.name&&n("Content has one editable name",["screen","name"]),t.kind==="banner"&&t.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),t.kind!=="banner"&&t.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),t.screen.actions.some(o=>o.type!=="event"&&o.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let i=new Set(t.screen.actions.filter(o=>o.type==="event").map(o=>o.id));(Object.keys(t.contract.outputs).some(o=>!i.has(o))||[...i].some(o=>!Object.hasOwn(t.contract.outputs,o)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),d(t)>y&&n("Content document exceeds its byte budget",[])});function S(t,r){if(t===null)return r.nullable;switch(r.type){case"json":return!0;case"string":return typeof t=="string";case"number":return typeof t=="number"&&Number.isFinite(t);case"boolean":return typeof t=="boolean";case"strings":return Array.isArray(t)&&t.every(n=>typeof n=="string")}}var x=c.superRefine((t,r)=>{for(let n of p(t.screen))Object.keys(t.contract.inputs).some(i=>n===i||n.startsWith(i+"."))||r.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of t.screen.actions){if(n.type!=="event")continue;let i=t.contract.outputs[n.id],o=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;i&&!S(o,i)&&r.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}m(t.screen).some(n=>!n.complete)&&r.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),l=e.strictObject({id:e.uuid(),kind:s,projectId:e.uuid(),environmentId:e.uuid(),name:e.string(),revision:e.number().int().nonnegative(),status:e.enum(["draft","published","archived"]),publishedVersionId:e.uuid().nullable(),createdAt:e.iso.datetime({offset:!0}),updatedAt:e.iso.datetime({offset:!0})}),D=l.extend({draft:c}),I=e.strictObject({rows:e.array(l).max(200),nextCursor:e.uuid().nullable()}),v=e.strictObject({id:e.uuid(),kind:s,resourceId:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),version:e.number().int().positive(),sourceRevision:e.number().int().nonnegative(),document:x,createdAt:e.iso.datetime({offset:!0})}),z=v.omit({document:!0}),V=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),kind:s,id:e.uuid(),document:c}),e.strictObject({action:e.literal("save"),kind:s,id:e.uuid(),revision:e.number().int().nonnegative(),document:c}),e.strictObject({action:e.enum(["publish","archive"]),kind:s,id:e.uuid(),revision:e.number().int().nonnegative()})]).superRefine((t,r)=>{"document"in t&&t.document.kind!==t.kind&&r.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});export{s as a,v as b};
1
+ import{b as p,c as d}from"./chunk-AD35L6BX.js";import{t as a,w as u,z as m}from"./chunk-56YCOGQZ.js";import{b as e}from"./chunk-YLH3AYCK.js";var s=e.enum(["page","popup","banner"]),y=3e5,f=e.strictObject({type:e.enum(["string","number","boolean","strings","json"]),nullable:e.boolean()}),h=e.strictObject({inputs:e.record(a,f.extend({required:e.boolean()})).refine(t=>Object.keys(t).length<=40,"Too many content inputs"),outputs:e.record(a,f).refine(t=>Object.keys(t).length<=40,"Too many content outputs")}),g=e.strictObject({kind:s,schemaVersion:e.literal(1),name:e.string().trim().min(1).max(80),screen:u,contract:h}),c=g.superRefine((t,r)=>{let n=(o,b)=>r.addIssue({code:"custom",message:o,path:b});t.screen.surface!==t.kind&&n("Content surface must match its domain",["screen","surface"]),t.screen.name!==t.name&&n("Content has one editable name",["screen","name"]),t.kind==="banner"&&t.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),t.kind!=="banner"&&t.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),t.screen.actions.some(o=>o.type!=="event"&&o.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let i=new Set(t.screen.actions.filter(o=>o.type==="event").map(o=>o.id));(Object.keys(t.contract.outputs).some(o=>!i.has(o))||[...i].some(o=>!Object.hasOwn(t.contract.outputs,o)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),d(t)>y&&n("Content document exceeds its byte budget",[])});function S(t,r){if(t===null)return r.nullable;switch(r.type){case"json":return!0;case"string":return typeof t=="string";case"number":return typeof t=="number"&&Number.isFinite(t);case"boolean":return typeof t=="boolean";case"strings":return Array.isArray(t)&&t.every(n=>typeof n=="string")}}var x=c.superRefine((t,r)=>{for(let n of p(t.screen))Object.keys(t.contract.inputs).some(i=>n===i||n.startsWith(i+"."))||r.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of t.screen.actions){if(n.type!=="event")continue;let i=t.contract.outputs[n.id],o=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;i&&!S(o,i)&&r.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}m(t.screen).some(n=>!n.complete)&&r.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),l=e.strictObject({id:e.uuid(),kind:s,projectId:e.uuid(),environmentId:e.uuid(),name:e.string(),revision:e.number().int().nonnegative(),status:e.enum(["draft","published","archived"]),publishedVersionId:e.uuid().nullable(),createdAt:e.iso.datetime({offset:!0}),updatedAt:e.iso.datetime({offset:!0})}),D=l.extend({draft:c}),I=e.strictObject({rows:e.array(l).max(200),nextCursor:e.uuid().nullable()}),v=e.strictObject({id:e.uuid(),kind:s,resourceId:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),version:e.number().int().positive(),sourceRevision:e.number().int().nonnegative(),document:x,createdAt:e.iso.datetime({offset:!0})}),z=v.omit({document:!0}),V=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),kind:s,id:e.uuid(),document:c}),e.strictObject({action:e.literal("save"),kind:s,id:e.uuid(),revision:e.number().int().nonnegative(),document:c}),e.strictObject({action:e.enum(["publish","archive"]),kind:s,id:e.uuid(),revision:e.number().int().nonnegative()})]).superRefine((t,r)=>{"document"in t&&t.document.kind!==t.kind&&r.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});export{s as a,v as b};
@@ -1 +1 @@
1
- import{a as n}from"./chunk-TK3WOD2O.js";function o(r,e){try{return r.parse(e)}catch{throw new n("INVALID_RESPONSE","Invalid gateway response")}}export{o as a};
1
+ import{a as n}from"./chunk-46USIMCJ.js";function o(r,e){try{return r.parse(e)}catch{throw new n("INVALID_RESPONSE","Invalid gateway response")}}export{o as a};
@@ -1 +1 @@
1
- import{e as w,f as b}from"./chunk-BJW4AXFL.js";import{n as h,s as u}from"./chunk-32AEJKJW.js";import{a as y}from"./chunk-4LQX4K5Q.js";import{a as n}from"./chunk-TK3WOD2O.js";import{a as g}from"./chunk-3VUPVXAV.js";import{a as f}from"./chunk-5MRSFLQA.js";function p(r,s){let a=typeof r=="string"?new TextEncoder().encode(r):r;return a.byteLength===s.byteLength&&u(a)===s.sha256}async function _(r,s){let a=w.parse(s),{artifact:i,environmentId:P}=a.content,m=new y(r.baseUrl??f).origin,e=new y(i.url,m);if(e.origin!==m||e.username||e.password||e.search||e.hash||e.pathname!==`/api/v1/configuration/${P}/artifacts/${i.sha256}`)throw new n("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,d,I=new Promise((t,l)=>{d=setTimeout(()=>{let c=new n("TIMEOUT","Public Paywall read timed out");o.abort(c),l(c)},h.initializationMs)}),E=(async()=>{let t=await(r.fetch??globalThis.fetch)(e,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(t.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!t.ok||!t.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(t.headers.get("content-length"))>i.byteLength)throw t.body?.cancel().catch(()=>{}),new n("INVALID_RESPONSE","Public Paywall is unavailable");let l=await g(t,i.byteLength,{signal:o.signal,error:c=>new n("INVALID_RESPONSE",c==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!p(l,i))throw new n("INVALID_RESPONSE","Public Paywall digest or size changed");return b(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([E,I])}finally{clearTimeout(d)}}export{p as a,_ as b};
1
+ import{e as w,f as b}from"./chunk-TXVLJFZG.js";import{n as h,s as u}from"./chunk-FUP5JVDE.js";import{a as y}from"./chunk-7D5462NE.js";import{a as n}from"./chunk-46USIMCJ.js";import{a as g}from"./chunk-3VUPVXAV.js";import{a as f}from"./chunk-5MRSFLQA.js";function p(r,s){let a=typeof r=="string"?new TextEncoder().encode(r):r;return a.byteLength===s.byteLength&&u(a)===s.sha256}async function _(r,s){let a=w.parse(s),{artifact:i,environmentId:P}=a.content,m=new y(r.baseUrl??f).origin,e=new y(i.url,m);if(e.origin!==m||e.username||e.password||e.search||e.hash||e.pathname!==`/api/v1/configuration/${P}/artifacts/${i.sha256}`)throw new n("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,d,I=new Promise((t,l)=>{d=setTimeout(()=>{let c=new n("TIMEOUT","Public Paywall read timed out");o.abort(c),l(c)},h.initializationMs)}),E=(async()=>{let t=await(r.fetch??globalThis.fetch)(e,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(t.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!t.ok||!t.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(t.headers.get("content-length"))>i.byteLength)throw t.body?.cancel().catch(()=>{}),new n("INVALID_RESPONSE","Public Paywall is unavailable");let l=await g(t,i.byteLength,{signal:o.signal,error:c=>new n("INVALID_RESPONSE",c==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!p(l,i))throw new n("INVALID_RESPONSE","Public Paywall digest or size changed");return b(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([E,I])}finally{clearTimeout(d)}}export{p as a,_ as b};
@@ -1 +1 @@
1
- import{a as E,b as M,c as j,d as O,e as T}from"./chunk-2RFI2DEV.js";import{a as u}from"./chunk-TK3WOD2O.js";import{j as w}from"./chunk-RIEWU4MN.js";import{b as t}from"./chunk-PZTWDJHN.js";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Z(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Z as d};
1
+ import{a as E,b as M,c as j,d as O,e as T}from"./chunk-RNCUAYLQ.js";import{a as u}from"./chunk-46USIMCJ.js";import{j as w}from"./chunk-XIBJF5E6.js";import{b as t}from"./chunk-YLH3AYCK.js";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Z(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Z as d};
@@ -1 +1 @@
1
- import{B as p,C as u,D as d,E as f}from"./chunk-EB7MIZ4T.js";import{v as y}from"./chunk-ZRGL2CAP.js";import{a as s}from"./chunk-TK3WOD2O.js";function Q(e,t,r=new Set){let i={...t};return y(e.document.screen,n=>{if(n.hidden)return!1;if(n.type!=="quantity_picker"||r.has(n.id))return;let a=e.capabilities.quantities?.[n.id],o=a?.available?a.value:i[n.id]??n.defaultQuantity;if(a?.available&&(typeof o!="number"||!Number.isSafeInteger(o)||o<Math.max(n.minimumQuantity,a.minimum)||o>Math.min(n.maximumQuantity,a.maximum)||(o-n.minimumQuantity)%n.step!==0))throw new s("INVALID_RESPONSE","The current subscription quantity is outside this control's bounds");typeof o=="number"&&(i[n.id]=o)}),i}function V(e){let t=Object.create(null);for(let r of e.document.screen.actions){let i=r.properties.couponBinding,n=e.document.buttons[r.id];if(typeof i!="string"||n?.type!=="checkout")continue;let a=Object.hasOwn(e.capabilities.nodes,i)?e.capabilities.nodes[i]:void 0,{product:o}=n,b=o.type==="fixed"?[o.productVersionId]:o.allowedProductVersionIds,I=a?[a.base,...Object.values(a.byPlan??{})]:[],w=Object.fromEntries(I.flatMap(l=>l.planVersionId&&l.couponId&&l.text&&b.includes(l.planVersionId)?[[l.planVersionId,l]]:[]));t[r.id]={products:w,...o.type==="picker"?{picker:o.pickerId}:{}}}return Object.keys(t).length?{...e.capabilities,checkoutCoupons:t}:e.capabilities}function E(e,t){let r=structuredClone(e);for(let[i,n]of Object.entries(r.plans)){let a=t.plans[i];!a||a.versionId!==n.versionId||(a.amountMinor!==void 0&&(n.amountMinor=a.amountMinor),a.interval!==void 0&&(n.interval=a.interval),a.intervalCount!==void 0&&(n.intervalCount=a.intervalCount),a.prepaid!==void 0&&(n.prepaid=structuredClone(a.prepaid)))}return r}var h=class extends s{constructor(r="Plans were updated. Choose again.",i="套餐已更新,请重新选择。"){super("CONFLICT",r);this.zhMessage=i}zhMessage;customerMessage(r){return r?this.zhMessage:this.message}};function N(e,t){let r=i=>"document"in i?i.offering.id:i.content.offeringVersionId;return e.id===t.id&&r(e)===r(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function D(e,t,r){if(e.operationId!==t.operationId||t.currency!==void 0&&"currency"in e&&e.currency!==t.currency||t.membershipId!==void 0&&(t.membershipId===null?u(e):!u(e)||e.membershipId!==t.membershipId)||t.featureQuantities!==void 0&&(!u(e)||!c(e.featureQuantities,t.featureQuantities)))throw new s("INVALID_RESPONSE",r)}function c(e,t){return Object.keys(e??{}).length===Object.keys(t??{}).length&&Object.entries(t??{}).every(([r,i])=>e?.[r]===i)}function P(e,t,r){if(p(e)){if(!t.subscriptionChange||e.membershipId!==t.subscriptionChange.membershipId||e.timing!==t.subscriptionChange.timing||e.productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||!c(e.featureQuantities,t.featureQuantities))throw new s("INVALID_RESPONSE",r);if(e.execution.provider==="merchant"){let n=e.execution.change,a=e.merchantTerms?.request;if(e.execution.membershipId!==e.membershipId||e.execution.timing!==e.timing||n.type!=="plan"||n.productVersionId!==e.productVersionId||!c(n.featureQuantities,e.featureQuantities)||a&&(a.action!=="subscription_change"||a.timing!==e.timing||a.change.type!=="plan"||a.change.productVersionId!==e.productVersionId||!c(a.change.featureQuantities,e.featureQuantities)))throw new s("INVALID_RESPONSE",r)}return}if(t.subscriptionChange)throw new s("INVALID_RESPONSE",r);let i=Object.fromEntries((e.lines[0]?.prepaid??[]).map(n=>[n.internal_feature_id,n.quantity]));if(t.featureQuantities&&(Object.keys(i).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([n,a])=>i[n]!==a)))throw new s("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new s("INVALID_RESPONSE",r)}function m(e,t){if(e.operationId===t.operationId){if(p(e))P(t,{productVersionId:e.productVersionId,currency:e.currency,subscriptionChange:{membershipId:e.membershipId,timing:e.timing},featureQuantities:e.featureQuantities??{}},"The original membership change selection changed");else if(p(t))throw new s("INVALID_RESPONSE","The commercial operation kind changed")}}function C(e,t,r=!1){if(t&&u(t)&&t.quote&&!c(t.featureQuantities,t.quote.featureQuantities))throw new s("INVALID_RESPONSE","The original membership change quantities changed");if(t&&u(t)&&t.quote&&m(t.quote,t.quote),!e||e.operationId!==t?.operationId)return t;if(e.quote&&t.quote&&m(e.quote,t.quote),u(e)&&u(t)&&!c(e.featureQuantities,t.featureQuantities))throw new s("INVALID_RESPONSE","The original membership change quantities changed");let i=e.merchantExecution,n=t.merchantExecution;if(i&&(!n||Date.parse(n.updatedAt)<Date.parse(i.updatedAt)))return e;if(u(e)!==u(t))throw new s("INVALID_RESPONSE","The commercial operation kind changed");if(d(e)&&!d(t))return e;let a=t.status===e.status&&i?.recordingStatus!=="accepted"&&n?.recordingStatus==="accepted";return!f(e)&&(f(t)||r&&!d(t)&&!a)?e:t}function R(e){return e.screen.actions.some(t=>t.properties.closeControl==="content"&&e.buttons[t.id]?.type==="close")}export{Q as a,V as b,E as c,h as d,N as e,D as f,P as g,m as h,C as i,R as j};
1
+ import{B as p,C as u,D as d,E as f}from"./chunk-3Q3DZEP3.js";import{v as y}from"./chunk-56YCOGQZ.js";import{a as s}from"./chunk-46USIMCJ.js";function Q(e,t,r=new Set){let i={...t};return y(e.document.screen,n=>{if(n.hidden)return!1;if(n.type!=="quantity_picker"||r.has(n.id))return;let a=e.capabilities.quantities?.[n.id],o=a?.available?a.value:i[n.id]??n.defaultQuantity;if(a?.available&&(typeof o!="number"||!Number.isSafeInteger(o)||o<Math.max(n.minimumQuantity,a.minimum)||o>Math.min(n.maximumQuantity,a.maximum)||(o-n.minimumQuantity)%n.step!==0))throw new s("INVALID_RESPONSE","The current subscription quantity is outside this control's bounds");typeof o=="number"&&(i[n.id]=o)}),i}function V(e){let t=Object.create(null);for(let r of e.document.screen.actions){let i=r.properties.couponBinding,n=e.document.buttons[r.id];if(typeof i!="string"||n?.type!=="checkout")continue;let a=Object.hasOwn(e.capabilities.nodes,i)?e.capabilities.nodes[i]:void 0,{product:o}=n,b=o.type==="fixed"?[o.productVersionId]:o.allowedProductVersionIds,I=a?[a.base,...Object.values(a.byPlan??{})]:[],w=Object.fromEntries(I.flatMap(l=>l.planVersionId&&l.couponId&&l.text&&b.includes(l.planVersionId)?[[l.planVersionId,l]]:[]));t[r.id]={products:w,...o.type==="picker"?{picker:o.pickerId}:{}}}return Object.keys(t).length?{...e.capabilities,checkoutCoupons:t}:e.capabilities}function E(e,t){let r=structuredClone(e);for(let[i,n]of Object.entries(r.plans)){let a=t.plans[i];!a||a.versionId!==n.versionId||(a.amountMinor!==void 0&&(n.amountMinor=a.amountMinor),a.interval!==void 0&&(n.interval=a.interval),a.intervalCount!==void 0&&(n.intervalCount=a.intervalCount),a.prepaid!==void 0&&(n.prepaid=structuredClone(a.prepaid)))}return r}var h=class extends s{constructor(r="Plans were updated. Choose again.",i="套餐已更新,请重新选择。"){super("CONFLICT",r);this.zhMessage=i}zhMessage;customerMessage(r){return r?this.zhMessage:this.message}};function N(e,t){let r=i=>"document"in i?i.offering.id:i.content.offeringVersionId;return e.id===t.id&&r(e)===r(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function D(e,t,r){if(e.operationId!==t.operationId||t.currency!==void 0&&"currency"in e&&e.currency!==t.currency||t.membershipId!==void 0&&(t.membershipId===null?u(e):!u(e)||e.membershipId!==t.membershipId)||t.featureQuantities!==void 0&&(!u(e)||!c(e.featureQuantities,t.featureQuantities)))throw new s("INVALID_RESPONSE",r)}function c(e,t){return Object.keys(e??{}).length===Object.keys(t??{}).length&&Object.entries(t??{}).every(([r,i])=>e?.[r]===i)}function P(e,t,r){if(p(e)){if(!t.subscriptionChange||e.membershipId!==t.subscriptionChange.membershipId||e.timing!==t.subscriptionChange.timing||e.productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||!c(e.featureQuantities,t.featureQuantities))throw new s("INVALID_RESPONSE",r);if(e.execution.provider==="merchant"){let n=e.execution.change,a=e.merchantTerms?.request;if(e.execution.membershipId!==e.membershipId||e.execution.timing!==e.timing||n.type!=="plan"||n.productVersionId!==e.productVersionId||!c(n.featureQuantities,e.featureQuantities)||a&&(a.action!=="subscription_change"||a.timing!==e.timing||a.change.type!=="plan"||a.change.productVersionId!==e.productVersionId||!c(a.change.featureQuantities,e.featureQuantities)))throw new s("INVALID_RESPONSE",r)}return}if(t.subscriptionChange)throw new s("INVALID_RESPONSE",r);let i=Object.fromEntries((e.lines[0]?.prepaid??[]).map(n=>[n.internal_feature_id,n.quantity]));if(t.featureQuantities&&(Object.keys(i).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([n,a])=>i[n]!==a)))throw new s("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new s("INVALID_RESPONSE",r)}function m(e,t){if(e.operationId===t.operationId){if(p(e))P(t,{productVersionId:e.productVersionId,currency:e.currency,subscriptionChange:{membershipId:e.membershipId,timing:e.timing},featureQuantities:e.featureQuantities??{}},"The original membership change selection changed");else if(p(t))throw new s("INVALID_RESPONSE","The commercial operation kind changed")}}function C(e,t,r=!1){if(t&&u(t)&&t.quote&&!c(t.featureQuantities,t.quote.featureQuantities))throw new s("INVALID_RESPONSE","The original membership change quantities changed");if(t&&u(t)&&t.quote&&m(t.quote,t.quote),!e||e.operationId!==t?.operationId)return t;if(e.quote&&t.quote&&m(e.quote,t.quote),u(e)&&u(t)&&!c(e.featureQuantities,t.featureQuantities))throw new s("INVALID_RESPONSE","The original membership change quantities changed");let i=e.merchantExecution,n=t.merchantExecution;if(i&&(!n||Date.parse(n.updatedAt)<Date.parse(i.updatedAt)))return e;if(u(e)!==u(t))throw new s("INVALID_RESPONSE","The commercial operation kind changed");if(d(e)&&!d(t))return e;let a=t.status===e.status&&i?.recordingStatus!=="accepted"&&n?.recordingStatus==="accepted";return!f(e)&&(f(t)||r&&!d(t)&&!a)?e:t}function R(e){return e.screen.actions.some(t=>t.properties.closeControl==="content"&&e.buttons[t.id]?.type==="close")}export{Q as a,V as b,E as c,h as d,N as e,D as f,P as g,m as h,C as i,R as j};
@@ -1 +1 @@
1
- import{c as $}from"./chunk-FQMZY5VP.js";import{a as z}from"./chunk-DSPLGTQI.js";var G={sm:420,md:640,lg:900},F=767;function Pe(e,t,r=()=>!0,a="Close"){let n=e.ownerDocument.defaultView,o=e.ownerDocument.createElement("button");o.type="button",o.setAttribute("aria-label",a),o.style.cssText="position:absolute;inset:0 48px auto;z-index:2;height:24px;border:0;padding:0;background:transparent;touch-action:none;cursor:grab";let d=e.ownerDocument.createElement("span");d.style.cssText="display:block;width:36px;height:4px;border-radius:4px;margin:8px auto 12px;background:currentColor;opacity:.22;pointer-events:none",o.append(d),e.prepend(o);let l,c=0,s=!1,p=()=>{o.hidden=e.dataset.presentation!=="sheet",o.setAttribute("aria-disabled",String(!r()))},b=i=>{p(),!(o.hidden||!r()||i.button!==0)&&(l={y:i.clientY,time:Date.now(),id:i.pointerId},c=0,s=!1,o.setPointerCapture?.(i.pointerId))},x=i=>{!l||i.pointerId!==l.id||(c=Math.max(0,i.clientY-l.y),e.style.transform=`translateY(${c}px)`)},v=i=>{if(!l||i.pointerId!==l.id)return;let g=Math.max(1,Date.now()-l.time),P=i.type!=="pointercancel"&&r()&&(c>120||c>40&&c/g>.5);s=c>6,l=void 0,o.releasePointerCapture?.(i.pointerId),e.style.transform="",P?t():c&&typeof e.animate=="function"&&!n?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&e.animate([{transform:`translateY(${c}px)`},{transform:"none"}],{duration:200,easing:"cubic-bezier(.2,.8,.2,1)"}),c=0},m=()=>{if(s){s=!1;return}!l&&c===0&&r()&&t()};o.addEventListener("pointerdown",b),o.addEventListener("pointermove",x),o.addEventListener("pointerup",v),o.addEventListener("pointercancel",v),o.addEventListener("click",m);let L=typeof MutationObserver=="function"?new MutationObserver(p):void 0;return L?.observe(e,{attributes:!0,attributeFilter:["data-presentation"]}),n?.addEventListener("resize",p),p(),()=>{L?.disconnect(),n?.removeEventListener("resize",p),o.remove(),e.style.transform=""}}function q(e,t,r=!1){return(e.type==="modal"||e.type==="sheet")&&e.mobile&&r&&t<=F?e.mobile:e.type}function j(e,t,r){let a=e.ownerDocument.defaultView,n=t.presentation,o;if((n.type==="modal"||n.type==="sheet")&&n.backdrop){let i=`lp-backdrop-${crypto.randomUUID()}`,g={none:"transparent",scrim:"#f2f2f2cc",dim:"#0006","strong-dim":"#000000bf",blur:"#0006"};e.dataset.indianaBackdrop=i,o=e.ownerDocument.createElement("style"),o.textContent=`dialog[data-indiana-backdrop="${i}"]::backdrop{background:${g[n.backdrop]};backdrop-filter:${n.backdrop==="blur"?"blur(16px)":"none"}}`,e.append(o)}let d=t.pages?.[0]?.root.style?.shape,l=d?.type==="pill"?"9999px":d?.type==="rect"?typeof d.radius=="number"?`${d.radius}px`:[d.radius.topLeft,d.radius.topRight,d.radius.bottomRight,d.radius.bottomLeft].map(i=>`${i}px`).join(" "):void 0,c=(n.type==="modal"||n.type==="sheet")&&(n.desktopWidth!==void 0||n.mobile!==void 0||n.type==="modal"&&n.position!==void 0),s=n.type,p,b,x=!1,v=i=>{x||!Number.isFinite(i)||i<0||(b=i,s!=="fullscreen"&&s!=="inline"&&(e.style.height=`min(${Math.max(i,40)}px, calc(100dvh - ${s==="sheet"?0:32}px))`))},m=()=>{if(!x&&(s=p??q(n,a?.innerWidth??1024,a?.matchMedia?.("(pointer: coarse)").matches===!0),e.dataset.presentation=s,!(!c||n.type!=="modal"&&n.type!=="sheet"))){if(e.style.boxSizing="border-box",e.style.padding="0",e.style.border="0",e.style.overflow="hidden",e.style.outline="none",e.tabIndex=-1,e.style.background=t.theme.background,e.style.color=t.theme.text,s==="fullscreen")e.style.width="100vw",e.style.height="100dvh",e.style.maxWidth="100vw",e.style.maxHeight="100dvh",e.style.margin="0",e.style.borderRadius="0";else{let i=n.mobile==="sheet"&&s==="sheet",g=n.desktopWidth,P=a?.innerWidth??1024;e.style.width=i?`${P}px`:g?`${Math.min(g.max,Math.max(P*g.viewport/100,g.min))}px`:`${$[n.size]}px`,e.style.maxWidth=`${Math.max(0,P-(s==="sheet"?0:32))}px`,e.style.maxHeight=s==="sheet"?"100dvh":"calc(100dvh - 32px)",e.style.margin=s==="sheet"?"auto auto 0":n.type==="modal"&&n.position==="top"?"16px auto auto":n.type==="modal"&&n.position==="bottom"?"auto auto 16px":"auto",e.style.borderRadius=l??(s==="sheet"?"16px 16px 0 0":"24px"),e.style.height="",b!==void 0&&v(b)}r?.(s)}},L=c?[a?.matchMedia?.(`(max-width: ${F}px)`),a?.matchMedia?.("(pointer: coarse)")].filter(i=>i!==void 0):[];if(c){a?.addEventListener("resize",m);for(let i of L)i.addEventListener?i.addEventListener("change",m):i.addListener?.(m)}return m(),{responsive:c,get type(){return s},latch(){x||p!==void 0||(m(),p=s)},setContentHeight:v,destroy(){if(!x){x=!0,o?.remove(),delete e.dataset.indianaBackdrop,a?.removeEventListener("resize",m);for(let i of L)i.removeEventListener?i.removeEventListener("change",m):i.removeListener?.(m)}}}}function Se(e,t,r){let{presentation:a}=t,n="size"in a?`${G[a.size]}px`:"100vw";return e.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${n}`,j(e,t,r)}function Le(e,t,r=!1){let a=e.ownerDocument.defaultView;if(typeof e.animate!="function"||a?.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;let n=r?{duration:300,easing:"cubic-bezier(0.23, 1, 0.32, 1)"}:{duration:240,easing:"cubic-bezier(0.2, 0.8, 0.2, 1)"};e.animate(t==="sheet"?[{transform:"translateY(100%)"},{transform:"none"}]:t==="modal"?[{opacity:0,transform:r?"translateY(12px) scale(0.96)":"translateY(8px) scale(0.98)"},{opacity:1,transform:"none"}]:[{opacity:0},{opacity:1}],n);try{e.animate([{opacity:0},{opacity:1}],{...n,pseudoElement:"::backdrop"})}catch{}}function V(e,t){e.style.cssText=["position:absolute","z-index:1","top:calc(4px + env(safe-area-inset-top, 0px))","inset-inline-end:calc(4px + env(safe-area-inset-right, 0px))","width:44px","height:44px","padding:0","border:0","border-radius:50%","font:400 20px/1 system-ui,sans-serif","cursor:pointer","touch-action:manipulation"].join(";"),e.style.background=`radial-gradient(circle, ${t.background} 0 15px, color-mix(in srgb, ${t.text} 22%, ${t.background}) 15px 16px, transparent 16.5px)`,e.style.color=t.text}function De(e){let t=e.closest("dialog");if(!t?.open||!t.isConnected)return;let r=["style","tabindex","aria-label","data-presentation","data-indiana-backdrop"].map(a=>[a,t.getAttribute(a)]);return{dialog:t,content:e,release(){for(let[a,n]of r)n===null?t.removeAttribute(a):t.setAttribute(a,n)}}}var O=new WeakMap;function ke(e,t){return O.set(e,t),()=>O.delete(e)}function B(e){let t=e.defaultView?.HTMLElement,r=e.activeElement;for(let n=0;n<16&&r?.shadowRoot?.activeElement;n++)r=r.shadowRoot.activeElement;let a=r?O.get(r)?.():void 0;return()=>{!r?.isConnected||!t||!(r instanceof t)||(r.focus({preventScroll:!0}),a?.())}}var Ie=15e3;function Ae(e,t,r,a,n){let o=e.ownerDocument,d=new AbortController,l=!1,c=!1,s,p,b,x,v,m;function L(){clearTimeout(m),m=void 0,b?.(),b=void 0,s?.tagName==="DIALOG"&&s.close?.(),s?.remove(),s=void 0,p=void 0,v=void 0}function i(u,w){c||(c=!0,L(),(u==="dismissed"||u==="error")&&d.abort(w??new DOMException("Presentation cancelled","AbortError")),!(!l&&u!=="ready")&&z(t.onPresentationState,u==="error"?{surface:r,state:u,error:w}:{surface:r,state:u}))}let g=a,P=()=>{c||g()};return{setDismissHandler(u){g=u},get active(){return l&&!c},get cancelled(){return d.signal.aborted},retainPurchaseDialog(){return p?.()},setPurchaseRecovery(u,w){x={message:u,retry:w},v?.()},start(u,w,y){if(l||c)return;l=!0;let C=()=>{if(!c&&t.loading!=="host"){let k=(w??o.documentElement.lang)||"en",M=u&&y?.presentation?.type!=="inline",D=y!==void 0,h=o.createElement(M?"dialog":"div");s=h,h.dataset.longplayLoading=r;let R=k.startsWith("zh"),W=D?R?"正在加载套餐":"Loading plans":R?"正在加载":"Loading",N=y?.screen.theme??{background:"Canvas",text:"CanvasText"};h.setAttribute("aria-label",W);let S=o.createElement("div");S.setAttribute("role","status");let H=o.createElement("div");H.setAttribute("aria-hidden","true"),D?(S.style.cssText="padding:calc(24px + env(safe-area-inset-top, 0px)) 24px 16px;padding-inline-end:68px;font:650 20px/1.3 system-ui,sans-serif;letter-spacing:-.015em",y||(S.style.paddingBlockEnd="24px")):S.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)",S.textContent=W;let T=o.createElement("button");T.type="button",T.textContent=R?"重试":"Retry",T.style.cssText="margin:0 24px 20px;padding:8px 16px",T.onclick=()=>x?.retry?.(),v=()=>{x&&(S.textContent=x.message,x.retry?S.after(T):T.remove())};let E=o.createElement("button");E.type="button",E.textContent="×",E.setAttribute("aria-label",R?"取消加载":"Cancel loading"),V(E,N),D&&(E.style.borderRadius="50%",E.style.top="calc(15px + env(safe-area-inset-top, 0px))",E.style.insetInlineEnd="calc(15px + env(safe-area-inset-right, 0px))"),E.addEventListener("click",P);let _=f=>{f.preventDefault(),P()};h.addEventListener("cancel",_);let I=o.createElement("style");I.textContent="[data-longplay-loading] > button:focus-visible{outline:2px solid currentColor;outline-offset:-2px}",h.append(S,H,E,I),v(),e.append(h);let A=()=>{if(!c&&M){let f=h,Y=B(o);f.showModal?f.showModal():f.open=!0,E.focus({preventScroll:!0}),p=()=>{if(!f.open||!f.isConnected)return;let U=b;return b=void 0,s=void 0,p=void 0,delete f.dataset.longplayLoading,f.removeAttribute("aria-label"),f.style.padding="0",f.removeEventListener("cancel",_),S.remove(),H.remove(),E.remove(),I.remove(),T.remove(),v=void 0,{dialog:f,release(){U?.(),f.close?.(),f.remove(),Y()}}}}};y&&n?(b=n(h,H,y),A()):D?(h.style.cssText=M?"padding:0;border:0;border-radius:24px;background:Canvas;color:CanvasText;width:min(420px,calc(100vw - 32px))":"position:relative;background:Canvas;color:CanvasText;width:100%",A()):(X(h,H,M,r),A())}};y!==void 0&&t.loading!=="host"?m=setTimeout(C,120):C(),z(t.onPresentationState,{surface:r,state:"loading",dismiss:P})},present(u){if(c)return;let w=!!s;L(),u(w),i("ready")},dismiss:P,finish:i,async wait(u,w){let y=d.signal,C,k,M=new Promise((D,h)=>{k=()=>h(y.reason),y.aborted?k():y.addEventListener("abort",k,{once:!0}),w!==void 0&&(C=setTimeout(()=>h(new Error("Presentation data timed out")),w))});try{let D=await Promise.race([M,u]);return y.throwIfAborted(),D}finally{y.removeEventListener("abort",k),clearTimeout(C)}}}}function X(e,t,r,a){e.style.cssText="position:relative;box-sizing:border-box;background:Canvas;color:CanvasText;padding:24px 48px 24px 24px;"+(r?"position:fixed;width:min(480px,calc(100% - 32px));border:0;border-radius:16px;max-height:calc(100dvh - 32px)":"width:100%"),t.style.cssText="display:grid;gap:12px";let n=a==="banner"?[["72%",12],["44%",10]]:[["46%",20],["84%",12],["65%",12],["100%",64]];for(let[o,d]of n){let l=e.ownerDocument.createElement("div");l.style.cssText=`width:${o};height:${d}px;background:currentColor;opacity:.11;border-radius:6px`,t.append(l)}}function J(e){let t={display:"block",position:"fixed",top:"0",left:"0",opacity:"0",pointerEvents:"none",zIndex:"-1"},r=Object.keys(t).map(o=>{let d=o,l=e.style[d];return e.style[d]=t[d],[d,l]}),a=e.inert??!1,n=e.getAttribute("aria-hidden");return e.inert=!0,e.setAttribute("aria-hidden","true"),()=>{for(let[o,d]of r)e.style[o]=d;e.inert=a,n===null?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",n)}}function ze(e,t){let r=e.style.width;e.style.width=`${t.getBoundingClientRect().width||t.ownerDocument.defaultView?.innerWidth||800}px`;let a=J(e);return()=>{a(),e.style.width=r}}export{Pe as a,q as b,j as c,Se as d,Le as e,V as f,De as g,ke as h,B as i,Ie as j,Ae as k,J as l,ze as m};
1
+ import{c as $}from"./chunk-7OJIW75D.js";import{a as z}from"./chunk-DSPLGTQI.js";var G={sm:420,md:640,lg:900},F=767;function Pe(e,t,r=()=>!0,a="Close"){let n=e.ownerDocument.defaultView,o=e.ownerDocument.createElement("button");o.type="button",o.setAttribute("aria-label",a),o.style.cssText="position:absolute;inset:0 48px auto;z-index:2;height:24px;border:0;padding:0;background:transparent;touch-action:none;cursor:grab";let d=e.ownerDocument.createElement("span");d.style.cssText="display:block;width:36px;height:4px;border-radius:4px;margin:8px auto 12px;background:currentColor;opacity:.22;pointer-events:none",o.append(d),e.prepend(o);let l,c=0,s=!1,p=()=>{o.hidden=e.dataset.presentation!=="sheet",o.setAttribute("aria-disabled",String(!r()))},b=i=>{p(),!(o.hidden||!r()||i.button!==0)&&(l={y:i.clientY,time:Date.now(),id:i.pointerId},c=0,s=!1,o.setPointerCapture?.(i.pointerId))},x=i=>{!l||i.pointerId!==l.id||(c=Math.max(0,i.clientY-l.y),e.style.transform=`translateY(${c}px)`)},v=i=>{if(!l||i.pointerId!==l.id)return;let g=Math.max(1,Date.now()-l.time),P=i.type!=="pointercancel"&&r()&&(c>120||c>40&&c/g>.5);s=c>6,l=void 0,o.releasePointerCapture?.(i.pointerId),e.style.transform="",P?t():c&&typeof e.animate=="function"&&!n?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&e.animate([{transform:`translateY(${c}px)`},{transform:"none"}],{duration:200,easing:"cubic-bezier(.2,.8,.2,1)"}),c=0},m=()=>{if(s){s=!1;return}!l&&c===0&&r()&&t()};o.addEventListener("pointerdown",b),o.addEventListener("pointermove",x),o.addEventListener("pointerup",v),o.addEventListener("pointercancel",v),o.addEventListener("click",m);let L=typeof MutationObserver=="function"?new MutationObserver(p):void 0;return L?.observe(e,{attributes:!0,attributeFilter:["data-presentation"]}),n?.addEventListener("resize",p),p(),()=>{L?.disconnect(),n?.removeEventListener("resize",p),o.remove(),e.style.transform=""}}function q(e,t,r=!1){return(e.type==="modal"||e.type==="sheet")&&e.mobile&&r&&t<=F?e.mobile:e.type}function j(e,t,r){let a=e.ownerDocument.defaultView,n=t.presentation,o;if((n.type==="modal"||n.type==="sheet")&&n.backdrop){let i=`lp-backdrop-${crypto.randomUUID()}`,g={none:"transparent",scrim:"#f2f2f2cc",dim:"#0006","strong-dim":"#000000bf",blur:"#0006"};e.dataset.indianaBackdrop=i,o=e.ownerDocument.createElement("style"),o.textContent=`dialog[data-indiana-backdrop="${i}"]::backdrop{background:${g[n.backdrop]};backdrop-filter:${n.backdrop==="blur"?"blur(16px)":"none"}}`,e.append(o)}let d=t.pages?.[0]?.root.style?.shape,l=d?.type==="pill"?"9999px":d?.type==="rect"?typeof d.radius=="number"?`${d.radius}px`:[d.radius.topLeft,d.radius.topRight,d.radius.bottomRight,d.radius.bottomLeft].map(i=>`${i}px`).join(" "):void 0,c=(n.type==="modal"||n.type==="sheet")&&(n.desktopWidth!==void 0||n.mobile!==void 0||n.type==="modal"&&n.position!==void 0),s=n.type,p,b,x=!1,v=i=>{x||!Number.isFinite(i)||i<0||(b=i,s!=="fullscreen"&&s!=="inline"&&(e.style.height=`min(${Math.max(i,40)}px, calc(100dvh - ${s==="sheet"?0:32}px))`))},m=()=>{if(!x&&(s=p??q(n,a?.innerWidth??1024,a?.matchMedia?.("(pointer: coarse)").matches===!0),e.dataset.presentation=s,!(!c||n.type!=="modal"&&n.type!=="sheet"))){if(e.style.boxSizing="border-box",e.style.padding="0",e.style.border="0",e.style.overflow="hidden",e.style.outline="none",e.tabIndex=-1,e.style.background=t.theme.background,e.style.color=t.theme.text,s==="fullscreen")e.style.width="100vw",e.style.height="100dvh",e.style.maxWidth="100vw",e.style.maxHeight="100dvh",e.style.margin="0",e.style.borderRadius="0";else{let i=n.mobile==="sheet"&&s==="sheet",g=n.desktopWidth,P=a?.innerWidth??1024;e.style.width=i?`${P}px`:g?`${Math.min(g.max,Math.max(P*g.viewport/100,g.min))}px`:`${$[n.size]}px`,e.style.maxWidth=`${Math.max(0,P-(s==="sheet"?0:32))}px`,e.style.maxHeight=s==="sheet"?"100dvh":"calc(100dvh - 32px)",e.style.margin=s==="sheet"?"auto auto 0":n.type==="modal"&&n.position==="top"?"16px auto auto":n.type==="modal"&&n.position==="bottom"?"auto auto 16px":"auto",e.style.borderRadius=l??(s==="sheet"?"16px 16px 0 0":"24px"),e.style.height="",b!==void 0&&v(b)}r?.(s)}},L=c?[a?.matchMedia?.(`(max-width: ${F}px)`),a?.matchMedia?.("(pointer: coarse)")].filter(i=>i!==void 0):[];if(c){a?.addEventListener("resize",m);for(let i of L)i.addEventListener?i.addEventListener("change",m):i.addListener?.(m)}return m(),{responsive:c,get type(){return s},latch(){x||p!==void 0||(m(),p=s)},setContentHeight:v,destroy(){if(!x){x=!0,o?.remove(),delete e.dataset.indianaBackdrop,a?.removeEventListener("resize",m);for(let i of L)i.removeEventListener?i.removeEventListener("change",m):i.removeListener?.(m)}}}}function Se(e,t,r){let{presentation:a}=t,n="size"in a?`${G[a.size]}px`:"100vw";return e.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${n}`,j(e,t,r)}function Le(e,t,r=!1){let a=e.ownerDocument.defaultView;if(typeof e.animate!="function"||a?.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;let n=r?{duration:300,easing:"cubic-bezier(0.23, 1, 0.32, 1)"}:{duration:240,easing:"cubic-bezier(0.2, 0.8, 0.2, 1)"};e.animate(t==="sheet"?[{transform:"translateY(100%)"},{transform:"none"}]:t==="modal"?[{opacity:0,transform:r?"translateY(12px) scale(0.96)":"translateY(8px) scale(0.98)"},{opacity:1,transform:"none"}]:[{opacity:0},{opacity:1}],n);try{e.animate([{opacity:0},{opacity:1}],{...n,pseudoElement:"::backdrop"})}catch{}}function V(e,t){e.style.cssText=["position:absolute","z-index:1","top:calc(4px + env(safe-area-inset-top, 0px))","inset-inline-end:calc(4px + env(safe-area-inset-right, 0px))","width:44px","height:44px","padding:0","border:0","border-radius:50%","font:400 20px/1 system-ui,sans-serif","cursor:pointer","touch-action:manipulation"].join(";"),e.style.background=`radial-gradient(circle, ${t.background} 0 15px, color-mix(in srgb, ${t.text} 22%, ${t.background}) 15px 16px, transparent 16.5px)`,e.style.color=t.text}function De(e){let t=e.closest("dialog");if(!t?.open||!t.isConnected)return;let r=["style","tabindex","aria-label","data-presentation","data-indiana-backdrop"].map(a=>[a,t.getAttribute(a)]);return{dialog:t,content:e,release(){for(let[a,n]of r)n===null?t.removeAttribute(a):t.setAttribute(a,n)}}}var O=new WeakMap;function ke(e,t){return O.set(e,t),()=>O.delete(e)}function B(e){let t=e.defaultView?.HTMLElement,r=e.activeElement;for(let n=0;n<16&&r?.shadowRoot?.activeElement;n++)r=r.shadowRoot.activeElement;let a=r?O.get(r)?.():void 0;return()=>{!r?.isConnected||!t||!(r instanceof t)||(r.focus({preventScroll:!0}),a?.())}}var Ie=15e3;function Ae(e,t,r,a,n){let o=e.ownerDocument,d=new AbortController,l=!1,c=!1,s,p,b,x,v,m;function L(){clearTimeout(m),m=void 0,b?.(),b=void 0,s?.tagName==="DIALOG"&&s.close?.(),s?.remove(),s=void 0,p=void 0,v=void 0}function i(u,w){c||(c=!0,L(),(u==="dismissed"||u==="error")&&d.abort(w??new DOMException("Presentation cancelled","AbortError")),!(!l&&u!=="ready")&&z(t.onPresentationState,u==="error"?{surface:r,state:u,error:w}:{surface:r,state:u}))}let g=a,P=()=>{c||g()};return{setDismissHandler(u){g=u},get active(){return l&&!c},get cancelled(){return d.signal.aborted},retainPurchaseDialog(){return p?.()},setPurchaseRecovery(u,w){x={message:u,retry:w},v?.()},start(u,w,y){if(l||c)return;l=!0;let C=()=>{if(!c&&t.loading!=="host"){let k=(w??o.documentElement.lang)||"en",M=u&&y?.presentation?.type!=="inline",D=y!==void 0,h=o.createElement(M?"dialog":"div");s=h,h.dataset.longplayLoading=r;let R=k.startsWith("zh"),W=D?R?"正在加载套餐":"Loading plans":R?"正在加载":"Loading",N=y?.screen.theme??{background:"Canvas",text:"CanvasText"};h.setAttribute("aria-label",W);let S=o.createElement("div");S.setAttribute("role","status");let H=o.createElement("div");H.setAttribute("aria-hidden","true"),D?(S.style.cssText="padding:calc(24px + env(safe-area-inset-top, 0px)) 24px 16px;padding-inline-end:68px;font:650 20px/1.3 system-ui,sans-serif;letter-spacing:-.015em",y||(S.style.paddingBlockEnd="24px")):S.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)",S.textContent=W;let T=o.createElement("button");T.type="button",T.textContent=R?"重试":"Retry",T.style.cssText="margin:0 24px 20px;padding:8px 16px",T.onclick=()=>x?.retry?.(),v=()=>{x&&(S.textContent=x.message,x.retry?S.after(T):T.remove())};let E=o.createElement("button");E.type="button",E.textContent="×",E.setAttribute("aria-label",R?"取消加载":"Cancel loading"),V(E,N),D&&(E.style.borderRadius="50%",E.style.top="calc(15px + env(safe-area-inset-top, 0px))",E.style.insetInlineEnd="calc(15px + env(safe-area-inset-right, 0px))"),E.addEventListener("click",P);let _=f=>{f.preventDefault(),P()};h.addEventListener("cancel",_);let I=o.createElement("style");I.textContent="[data-longplay-loading] > button:focus-visible{outline:2px solid currentColor;outline-offset:-2px}",h.append(S,H,E,I),v(),e.append(h);let A=()=>{if(!c&&M){let f=h,Y=B(o);f.showModal?f.showModal():f.open=!0,E.focus({preventScroll:!0}),p=()=>{if(!f.open||!f.isConnected)return;let U=b;return b=void 0,s=void 0,p=void 0,delete f.dataset.longplayLoading,f.removeAttribute("aria-label"),f.style.padding="0",f.removeEventListener("cancel",_),S.remove(),H.remove(),E.remove(),I.remove(),T.remove(),v=void 0,{dialog:f,release(){U?.(),f.close?.(),f.remove(),Y()}}}}};y&&n?(b=n(h,H,y),A()):D?(h.style.cssText=M?"padding:0;border:0;border-radius:24px;background:Canvas;color:CanvasText;width:min(420px,calc(100vw - 32px))":"position:relative;background:Canvas;color:CanvasText;width:100%",A()):(X(h,H,M,r),A())}};y!==void 0&&t.loading!=="host"?m=setTimeout(C,120):C(),z(t.onPresentationState,{surface:r,state:"loading",dismiss:P})},present(u){if(c)return;let w=!!s;L(),u(w),i("ready")},dismiss:P,finish:i,async wait(u,w){let y=d.signal,C,k,M=new Promise((D,h)=>{k=()=>h(y.reason),y.aborted?k():y.addEventListener("abort",k,{once:!0}),w!==void 0&&(C=setTimeout(()=>h(new Error("Presentation data timed out")),w))});try{let D=await Promise.race([M,u]);return y.throwIfAborted(),D}finally{y.removeEventListener("abort",k),clearTimeout(C)}}}}function X(e,t,r,a){e.style.cssText="position:relative;box-sizing:border-box;background:Canvas;color:CanvasText;padding:24px 48px 24px 24px;"+(r?"position:fixed;width:min(480px,calc(100% - 32px));border:0;border-radius:16px;max-height:calc(100dvh - 32px)":"width:100%"),t.style.cssText="display:grid;gap:12px";let n=a==="banner"?[["72%",12],["44%",10]]:[["46%",20],["84%",12],["65%",12],["100%",64]];for(let[o,d]of n){let l=e.ownerDocument.createElement("div");l.style.cssText=`width:${o};height:${d}px;background:currentColor;opacity:.11;border-radius:6px`,t.append(l)}}function J(e){let t={display:"block",position:"fixed",top:"0",left:"0",opacity:"0",pointerEvents:"none",zIndex:"-1"},r=Object.keys(t).map(o=>{let d=o,l=e.style[d];return e.style[d]=t[d],[d,l]}),a=e.inert??!1,n=e.getAttribute("aria-hidden");return e.inert=!0,e.setAttribute("aria-hidden","true"),()=>{for(let[o,d]of r)e.style[o]=d;e.inert=a,n===null?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",n)}}function ze(e,t){let r=e.style.width;e.style.width=`${t.getBoundingClientRect().width||t.ownerDocument.defaultView?.innerWidth||800}px`;let a=J(e);return()=>{a(),e.style.width=r}}export{Pe as a,q as b,j as c,Se as d,Le as e,V as f,De as g,ke as h,B as i,Ie as j,Ae as k,J as l,ze as m};
@@ -1 +1 @@
1
- import{C as d,D as u}from"./chunk-EB7MIZ4T.js";function f(r){let{quote:o,operation:e,requestId:s}=r,a={type:"recover",operationId:e?.operationId??o?.operationId??null,requestId:s};if(r.destroyed||r.pending)return a;if(!e)return o?{type:"cancel",operationId:o.operationId}:a;let t=e.merchantExecution;if(d(e)){if(t&&t.type!=="subscription_change")return a;if(t?.type==="subscription_change"){if(["applied","scheduled"].includes(t.status))return!["applied","not_applicable"].includes(t.fulfillmentStatus)||e.problem?.phase==="fulfillment"||t.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:t.recordingStatus==="accepted"&&u(e)&&!e.problem&&!t.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&!e.problem&&!t.problem&&t.nextAction?.type==="redirect"&&(!e.checkoutUrl||t.nextAction.url===e.checkoutUrl)&&Date.parse(t.nextAction.expiresAt)>Date.now()&&t.status==="pending")return{type:"checkout",operationId:e.operationId,checkoutUrl:t.nextAction.url}}if(!e.problem&&!t?.problem&&u(e)&&e.executor!=="merchant")return{type:"complete",operationId:e.operationId};if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&(!o||Date.parse(o.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let n=p=>!p||p.phase==="execution"&&p.reason==="STATE_CHANGED";return r.canReselect===!0&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&n(e.problem)&&n(t?.problem)&&(!t||t.status==="failed"&&t.recordingStatus==="accepted"&&t.fulfillmentStatus==="not_applicable")?{type:"native",operationId:e.operationId}:["prepared","quoted"].includes(e.status)&&!e.confirmedAt&&!t&&!e.checkoutUrl&&!e.problem?{type:"cancel",operationId:e.operationId}:a}if(t?.type==="purchase"){if(["succeeded","not_required"].includes(t.paymentStatus))return!["applied","not_applicable"].includes(t.fulfillmentStatus)||e.problem?.phase==="fulfillment"||t.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:t.recordingStatus==="accepted"&&e.status==="complete"&&!e.problem&&!t.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&e.checkoutUrl&&!e.problem&&!t.problem&&t.checkoutUrl===e.checkoutUrl&&t.checkoutExpiresAt&&Date.parse(t.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(t.paymentStatus))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl}}if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&!e.nativePurchase&&(!o||Date.parse(o.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let c=[e.problem,t?.problem],i=c.every(n=>!n||n.phase==="execution"&&n.reason!=="RESULT_UNKNOWN"),y=e.status==="cancelled"&&!c.some(Boolean)&&t?.type==="purchase"&&["pending","not_started","expired"].includes(t.paymentStatus)&&["not_started","not_applicable"].includes(t.fulfillmentStatus);return r.canReselect===!0&&i&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"||!t||t.type==="purchase"&&!["succeeded","not_required"].includes(t.paymentStatus)&&(y||t.recordingStatus==="accepted"&&t.fulfillmentStatus==="not_applicable"))?{type:"native",operationId:e.operationId}:!c.some(Boolean)&&e.status==="complete"&&e.executor!=="merchant"?{type:"complete",operationId:e.operationId}:i&&r.canReselect!==!1&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"?!e.confirmedAt&&(e.status==="cancelled"||!e.quoteFinalized):!t&&!e.quoteFinalized||t?.type==="purchase"&&["failed","expired"].includes(t.paymentStatus)&&t.fulfillmentStatus==="not_applicable"&&t.recordingStatus==="accepted")?{type:"native",operationId:e.operationId}:e.status==="pending"&&i&&!e.quoteFinalized&&!t&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase?{type:"cancel",operationId:e.operationId}:a}function h(r,o=!0){if(!r)return!1;let e=f({quote:r.quote??null,operation:r,requestId:null,pending:!1,destroyed:!1,canReselect:o});return e.type==="complete"||e.type==="native"}function l(r){return r.recovery??{type:"recover",operationId:r.operation?.operationId??r.quote?.operationId??null,requestId:null}}function b(r){return!!(r?.operationId&&(r.type==="checkout"||r.type==="recover"||r.type==="fulfillment"||r.type==="recording"))}async function g(r){let o=l(r);if(o.type==="recover"&&r.quote)try{await r.read(),o=l(r)}catch{return o}if(o.type!=="cancel"&&!(o.type==="recover"&&r.pendingCancellation))return o;try{await r.cancel();let e=l(r);return e.type==="cancel"?{type:"recover",operationId:o.operationId,requestId:null}:e}catch{let e=l(r);return e.type==="recover"?e:{type:"recover",operationId:o.operationId,requestId:null}}}export{f as a,h as b,l as c,b as d,g as e};
1
+ import{C as d,D as u}from"./chunk-3Q3DZEP3.js";function f(r){let{quote:o,operation:e,requestId:s}=r,a={type:"recover",operationId:e?.operationId??o?.operationId??null,requestId:s};if(r.destroyed||r.pending)return a;if(!e)return o?{type:"cancel",operationId:o.operationId}:a;let t=e.merchantExecution;if(d(e)){if(t&&t.type!=="subscription_change")return a;if(t?.type==="subscription_change"){if(["applied","scheduled"].includes(t.status))return!["applied","not_applicable"].includes(t.fulfillmentStatus)||e.problem?.phase==="fulfillment"||t.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:t.recordingStatus==="accepted"&&u(e)&&!e.problem&&!t.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&!e.problem&&!t.problem&&t.nextAction?.type==="redirect"&&(!e.checkoutUrl||t.nextAction.url===e.checkoutUrl)&&Date.parse(t.nextAction.expiresAt)>Date.now()&&t.status==="pending")return{type:"checkout",operationId:e.operationId,checkoutUrl:t.nextAction.url}}if(!e.problem&&!t?.problem&&u(e)&&e.executor!=="merchant")return{type:"complete",operationId:e.operationId};if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&(!o||Date.parse(o.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let n=p=>!p||p.phase==="execution"&&p.reason==="STATE_CHANGED";return r.canReselect===!0&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&n(e.problem)&&n(t?.problem)&&(!t||t.status==="failed"&&t.recordingStatus==="accepted"&&t.fulfillmentStatus==="not_applicable")?{type:"native",operationId:e.operationId}:["prepared","quoted"].includes(e.status)&&!e.confirmedAt&&!t&&!e.checkoutUrl&&!e.problem?{type:"cancel",operationId:e.operationId}:a}if(t?.type==="purchase"){if(["succeeded","not_required"].includes(t.paymentStatus))return!["applied","not_applicable"].includes(t.fulfillmentStatus)||e.problem?.phase==="fulfillment"||t.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:t.recordingStatus==="accepted"&&e.status==="complete"&&!e.problem&&!t.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&e.checkoutUrl&&!e.problem&&!t.problem&&t.checkoutUrl===e.checkoutUrl&&t.checkoutExpiresAt&&Date.parse(t.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(t.paymentStatus))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl}}if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&!e.nativePurchase&&(!o||Date.parse(o.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let c=[e.problem,t?.problem],i=c.every(n=>!n||n.phase==="execution"&&n.reason!=="RESULT_UNKNOWN"),y=e.status==="cancelled"&&!c.some(Boolean)&&t?.type==="purchase"&&["pending","not_started","expired"].includes(t.paymentStatus)&&["not_started","not_applicable"].includes(t.fulfillmentStatus);return r.canReselect===!0&&i&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"||!t||t.type==="purchase"&&!["succeeded","not_required"].includes(t.paymentStatus)&&(y||t.recordingStatus==="accepted"&&t.fulfillmentStatus==="not_applicable"))?{type:"native",operationId:e.operationId}:!c.some(Boolean)&&e.status==="complete"&&e.executor!=="merchant"?{type:"complete",operationId:e.operationId}:i&&r.canReselect!==!1&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"?!e.confirmedAt&&(e.status==="cancelled"||!e.quoteFinalized):!t&&!e.quoteFinalized||t?.type==="purchase"&&["failed","expired"].includes(t.paymentStatus)&&t.fulfillmentStatus==="not_applicable"&&t.recordingStatus==="accepted")?{type:"native",operationId:e.operationId}:e.status==="pending"&&i&&!e.quoteFinalized&&!t&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase?{type:"cancel",operationId:e.operationId}:a}function h(r,o=!0){if(!r)return!1;let e=f({quote:r.quote??null,operation:r,requestId:null,pending:!1,destroyed:!1,canReselect:o});return e.type==="complete"||e.type==="native"}function l(r){return r.recovery??{type:"recover",operationId:r.operation?.operationId??r.quote?.operationId??null,requestId:null}}function b(r){return!!(r?.operationId&&(r.type==="checkout"||r.type==="recover"||r.type==="fulfillment"||r.type==="recording"))}async function g(r){let o=l(r);if(o.type==="recover"&&r.quote)try{await r.read(),o=l(r)}catch{return o}if(o.type!=="cancel"&&!(o.type==="recover"&&r.pendingCancellation))return o;try{await r.cancel();let e=l(r);return e.type==="cancel"?{type:"recover",operationId:o.operationId,requestId:null}:e}catch{let e=l(r);return e.type==="recover"?e:{type:"recover",operationId:o.operationId,requestId:null}}}export{f as a,h as b,l as c,b as d,g as e};
@@ -1 +1 @@
1
- import{A as me,E as rt,b as qe,c as $e,d as Se,h as He,i as Ke,j as Ye,n as We,q as Xe,z as nt}from"./chunk-G2CBJZEI.js";import{a as tt}from"./chunk-YFOIOYTZ.js";import{c as Ne,d as Te,e as _e,f as Le,g as De,i as Ue,m as ke,n as M,o as Ge,q as be,r as _,s as je,t as ze,u as Be,v as Je}from"./chunk-32AEJKJW.js";import{K as U,e as Ve,q as ve,r as Me}from"./chunk-EKUDMQXT.js";import{a as fe,b as Ze}from"./chunk-4LQX4K5Q.js";import{a as le}from"./chunk-HUYKZH3H.js";import{e as de}from"./chunk-FQMZY5VP.js";import{a as D}from"./chunk-TK3WOD2O.js";import{h as ie}from"./chunk-RIEWU4MN.js";import{b as et}from"./chunk-3VUPVXAV.js";import{a as Qe}from"./chunk-5MRSFLQA.js";import{b as e}from"./chunk-PZTWDJHN.js";import{c as Fe,f as Pe}from"./chunk-VPT5MFDG.js";var j=e.literal(Ve),ht=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ot=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:xe}),e.strictObject({type:e.literal("customer"),customer:ve,customerData:Me.optional()})]),Ee=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),yt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:Ee.omit({runId:!0,requestId:!0}).nullable()}),wt=e.union([qe,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),It=$e.omit({authenticated:!0}).extend({identity:yt,instruction:wt.nullable()}),vt=e.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),pe={contract:j,customerToken:e.string().regex(le)},it={contract:j,requestId:e.uuid(),runToken:ht,externalUserId:ve.options[1].shape.value},at=e.discriminatedUnion("operation",[e.strictObject({contract:j,operation:e.literal("describe")}),e.strictObject({contract:j,operation:e.literal("start"),source:ot,funnelId:U.options[0].shape.funnelId,requestId:e.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),He.omit({operation:!0}).extend({contract:j,operation:e.literal("entry_start"),source:ot}),e.strictObject({...it,operation:e.literal("bind_customer"),guestToken:xe,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...it,operation:e.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("review")}),Ye.omit({customerToken:!0}).extend(pe),e.strictObject({...pe,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:vt})]),bt=Se.omit({run:!0}).extend({contract:j,run:It,settlement:Se.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Dt=Ke.extend({contract:j}),Ut=e.discriminatedUnion("operation",[at.options[1].omit({contract:!0,source:!0,requestId:!0}),at.options[2].omit({contract:!0,source:!0,requestId:!0})]),Vt=bt.extend({binding:Ee,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Mt=e.discriminatedUnion("state",[e.strictObject({contract:j,scope:ie,state:e.literal("not_accepted")}),e.strictObject({contract:j,scope:ie,state:e.literal("conflict")}),e.strictObject({contract:j,scope:ie,state:e.literal("bound"),binding:Ee})]),kt=e.strictObject({contract:j,scope:ie,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var st=e.string().regex(/^[a-f0-9]{64}$/),St=Ne.omit({variations:!0,active:!0}).extend({changeId:st,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),ut=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:st,experiments:e.array(St).max(100),savedGroups:Te}),xt=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),Bt=e.strictObject({events:e.array(xt).min(1).max(20)}),Jt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Wt(r){let a=null,g=null,O=0,v=0,C=new Set,l=null,w=null,m=new Set,b=()=>{for(let s of m)try{s()}catch{}},d={attributes:de.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,I)=>{!C.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(I),structuredClone(d.attributes),a.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,I)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(I),structuredClone(d.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,I=new Set){return C.has(s)?!l||!l.features[s]||["unknownFeature","cyclicPrerequisite"].includes(l.features[s].source):I.has(s)?!1:(I.add(s),(a?.features[s]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(P=>P.experiment.parentConditions??[])].some(P=>h(P.id,I))))}let x=s=>{if(r.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return l?.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(l=null,d.features=a.features),C.has(s)?!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()?S():structuredClone(l.features[s]??S()):r.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!l||h(s)?S():structuredClone(Pe(s,d))};async function V(){if(!a||!C.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=v;if(w?.revision===s)return w.loading;let I=O,F=a,P=[...C],E=(async()=>{let y=Ue.parse(await r.evaluateRemote({attributes:structuredClone(d.attributes),features:P}));if(!(I!==O||s!==v||F!==a)){if(r.assertUsable?.(F.generation),y.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(P.some(T=>!Object.hasOwn(y.features,T))||Object.keys(y.features).some(T=>!C.has(T)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!y.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=de.parse({...d.attributes,...y.merchandiseContext})}l=structuredClone(y),d.features={...F.features,...Object.fromEntries(Object.entries(l.features).map(([T,J])=>[T,{defaultValue:J.value}]))},b()}})();w={revision:s,loading:E};try{await E}finally{w?.loading===E&&(w=null)}}function L(){V().catch(s=>{try{r.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=O,I=(async()=>{let F=await r.load(),P="remoteFeatures"in F?Le.parse(F):null,E=P??_e.parse(F);if(E.scope.projectId!==r.scope.projectId||E.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==O)throw new Error("Feature client was reset");if(r.assertUsable&&a?.generation===E.generation){let{evaluatedAt:T,expiresAt:J,...ae}=a,{evaluatedAt:Z,expiresAt:ge,...z}=E;if(_(ae)!==_(z))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=E.evaluatedAt,a.expiresAt=E.expiresAt,b(),(!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())&&L(),structuredClone(a)}let y=new Set(P?.remoteFeatures??[]);if([...y].some(T=>Object.hasOwn(E.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in E&&!a.analyticsConfig.experimentViewsEnabled&&P?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),a=structuredClone(E),C=y,l=null,w=null,v++,d.features=a.features,d.savedGroups=Fe(a.savedGroups),d.trackedFeatureUsage={},b(),L(),structuredClone(a)})();g=I;try{return await I}finally{g===I&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let I=de.parse(s);(d.attributes?.merchandise||d.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=I,v++,l=null,w=null,d.features=a?.features??{},d.trackedFeatureUsage={},b(),L()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,I){let F=x(s).value;return structuredClone(F===null?I:F)},reset(){O++,v++,g=null,w=null,a=null,l=null,C.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),b()}}}var Et=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),Q=2*1048576,Ct=100;function Rt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ct(r,a){let g=a===void 0?Rt():a,O=new Map,v=0,C=!1,l=!1,w,m;async function b(S){if(!g)return null;let h;try{let x=await Promise.race([Promise.resolve().then(()=>g.getItem(S)),new Promise(V=>{h=setTimeout(()=>V(null),Ct)})]);return typeof x=="string"&&x.length<=Q&&new TextEncoder().encode(x).byteLength<=Q?x:null}catch{return null}finally{clearTimeout(h)}}function d(){if(m)return m;let S=(async()=>{try{let h=await b(`${r}:artifacts`);if(h)return Et.parse(JSON.parse(h))}catch{}return{}})();return m=S,S.finally(()=>{m===S&&(m=void 0)}),S}return{async readManifest(){return b(r)},writeManifest(S){!g||S.length>Q||new TextEncoder().encode(S).byteLength>Q||(w=S,!l&&(l=!0,Promise.resolve().then(async()=>{try{for(;w!==void 0;){let h=w;try{await g.setItem(r,h)}catch{}w===h&&(w=void 0)}}finally{l=!1}})))},async readArtifact(S){let h=(await d())[S],x=Date.now();return h&&x>=h.at&&x-h.at<=M.retentionMs?h.text:void 0},writeArtifact(S,h){if(!g||h.length>Q)return;let x=O.get(S);if(x?.text===h||!x&&O.size>=128)return;let V=new TextEncoder().encode(h).byteLength;v-(x?.byteLength??0)+V>Q||(O.set(S,{text:h,byteLength:V}),v+=V-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;O.size;){let L=new Map(O);try{let k={...await d()},s=Date.now();for(let[E,y]of L)k[E]={at:s,text:y.text};let I={},F=2,P=0;for(let[E,y]of Object.entries(k).sort(([,T],[,J])=>J.at-T.at)){if(y.at>s||s-y.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[E]:y})).byteLength;F+T>Q||P>=128||(I[E]=y,F+=T,P++)}await g.setItem(`${r}:artifacts`,JSON.stringify(I))}catch{}finally{for(let[k,s]of L)O.get(k)===s&&(O.delete(k),v-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,a)=>new D(r,a),B=()=>performance.now(),lt=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function pn(r){let a=Ge.parse(r.scope),g=new fe(r.origin??Qe);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let O=new Set([g.origin,...(r.assetOrigins??[]).map(t=>{let n=new fe(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return n.origin})]),v=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${a.environmentId}`,l=`indiana:configuration:1:${g.origin}:${_(a)}`,w=ct(l,r.storage),m,b=0,d=0,S=!1,h=!1,x=0,V=0,L,k,s,I,F=0,P=new Set,E=new Set,y=new Map,T=new Map,J=0,ae=!1;function Z(){for(let t of P)try{t()}catch{}}function ge(t){try{r.onError?.(t)}catch{}}let z=()=>!h&&!S&&!!m&&B()<b&&Date.now()<d;function re(){if(!z())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(t,n,i){if(!y.has(t)){for(;y.size&&(y.size>=128||J+i>M.maxCacheBytes);){let o=y.entries().next().value;J-=o[1].byteLength,y.delete(o[0])}y.set(t,{text:n,byteLength:i}),J+=i}}function he(t,n,i){return et(t,n,{signal:i,error:o=>u("INVALID_RESPONSE",o==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function ye(t){let n=new fe(t,g);if(!O.has(n.origin)||n.username||n.password||n.hash||n.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return n.href}async function we(t,n,i=!1){let o=await v(ye(t),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:n,headers:{}});if(o.status===429){let f=o.headers.get("retry-after")??"";F=/^\d+$/.test(f)?Number(f)*1e3:Math.max(0,Date.parse(f)-Date.now())||15e3}if(!o.ok&&o.status!==304)throw u(`CONFIGURATION_HTTP_${o.status}`,"Configuration synchronization failed");return o}function ft(t,n,i){let o=Date.parse(t.headers.get("x-indiana-config-validated-at")??""),f=Date.parse(t.headers.get("x-indiana-config-valid-until")??""),p=Date.parse(t.headers.get("date")??""),c=t.headers.get("age"),R=c!==null&&/^\d+(\.\d+)?$/.test(c)?Number(c)*1e3:NaN;if(![o,f,p,R].every(Number.isFinite)||f<=o||f-o>M.maxControlAgeMs||o>p+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let A=Math.min(f-o,i.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(R,p-o,0)-(B()-n);if(A<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return B()+A}function se(){if(clearTimeout(s),clearTimeout(I),h||!P.size||(z()&&(I=setTimeout(()=>{z()?se():Z()},Math.max(1,b-B())),lt(I)),typeof document<"u"&&document.visibilityState==="hidden"))return;let t=V?Math.min(15e3,1e3*2**Math.min(V-1,4)):Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{X().catch(ge)},Math.max(F,t*(.8+Math.random()*.2))),lt(s)}async function X(){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let t=x,n=new AbortController;k=n;let i=(async()=>{if(!ae){ae=!0;try{let ce=await w.readManifest();if(ce&&!m){let $=be.parse(JSON.parse(ce));_($.scope)===_(a)&&(m=$)}}catch{}}n.signal.throwIfAborted();let c=m,R=B(),N=await we(C,n.signal);N.status===304&&(!c||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await we(C,n.signal));let A=N.status===304?c:be.parse(JSON.parse(await he(N,M.maxManifestBytes,n.signal))),{generation:G,...ne}=A,q=N.headers.get("etag");if(_(A.scope)!==_(a)||ze(ne)!==G||q!==`"${G}"`&&q!==`W/"${G}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(c&&(A.revision<c.revision||A.revision===c.revision&&A.generation!==c.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ce,$]of Object.entries(c?.funnels??{})){let W=A.funnels[ce];if(W&&(W.controlRevision<$.controlRevision||W.evaluationRevision<$.evaluationRevision||W.controlRevision===$.controlRevision&&W.state!==$.state||W.evaluationRevision===$.evaluationRevision&&W.evaluationMode!==$.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=ft(N,R,A.policy);if(n.signal.throwIfAborted(),t!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return m=A,b=Y,d=Date.now()+Math.max(0,Y-B()),S=!1,V=0,F=0,w.writeManifest(_(A)),Z(),structuredClone(A)})(),o=setTimeout(()=>n.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),f=new Promise((c,R)=>n.signal.addEventListener("abort",()=>R(n.signal.reason),{once:!0})),p=Promise.race([i,f]).catch(c=>{throw V++,(c instanceof e.ZodError||c instanceof SyntaxError||c instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(c.code))&&(b=0,S=!0,Z()),c}).finally(()=>{clearTimeout(o),L===p&&(L=void 0),se()});return L=p,p}async function ue(t){let n=t.sha256,i=ne=>tt(ne,t);ye(t.url);let o=y.get(n);if(o){if(o.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return y.delete(n),y.set(n,o),o.text}let f=T.get(n);if(f){if(f.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return f.promise}let p=new AbortController;E.add(p);let c=x,R=(async()=>{try{let Y=await w.readArtifact(n);if(Y&&i(Y)){if(p.signal.throwIfAborted(),h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,Y,t.byteLength),Y}}catch{}p.signal.throwIfAborted();let ne=await we(t.url,p.signal,!0),q=await he(ne,t.byteLength,p.signal);if(!i(q))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,q,t.byteLength),w.writeArtifact(n,q),q})(),N=setTimeout(()=>p.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),A=new Promise((ne,q)=>p.signal.addEventListener("abort",()=>q(p.signal.reason),{once:!0})),G=Promise.race([R,A]).finally(()=>{clearTimeout(N),E.delete(p),T.delete(n)});return T.set(n,{promise:G,byteLength:t.byteLength}),G}async function ee(){return z()||await X(),re(),m}async function K(t){let n,i=new Promise((o,f)=>{n=setTimeout(()=>f(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([t(),i])}finally{clearTimeout(n)}}function H(t,n){if(re(),m?.generation!==t.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(n&&m.funnels[n]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Re(t){let n=t.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let o=De.parse(JSON.parse(await ue(i)));if(_(o.scope)!==_({projectId:a.projectId,environment:a.environment})||o.generation!==i.generation||o.remoteFeatures.some(f=>Object.hasOwn(o.features,f)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return H(t),{...o,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,b-B())).toISOString()}}async function Oe(t,n){let i=await ee(),o=i.funnels[t];n&&(!o||o.evaluationMode==="local"&&!o.versions[n])&&(L&&await L,i=await X()),H(i,t);let f=i.funnels[t];if(f.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let p=n??f.currentVersionId,c=f.versions[p];if(!c)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[c.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[R,N]=await Promise.all([ue(i.artifacts[c.artifact]).then(A=>Je(JSON.parse(A))),f.evaluationMode==="local"?Re(i):void 0]);if(N&&_(Be(R,N))!==_(c.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return H(i,t),{document:R,growth:N,versionId:p,control:structuredClone(f),manifest:structuredClone(i)}}async function Ie(t,n){try{return await Oe(t,n)}catch(i){if(!(i instanceof D)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&z()))throw i;let o=m?.generation;if(L&&await L,await X(),i.code!=="CONFIGURATION_CHANGED"&&m?.generation===o)throw i;return Oe(t,n)}}let oe=new Map;async function mt(t,n){let{FUNNEL_ROUTE_LIMITS:i,funnelRouteSchema:o}=await import("./funnel-route-source-4ZVBFNYV.js"),f=new AbortController;E.add(f);let p=setTimeout(()=>f.abort(u("CONFIGURATION_UNAVAILABLE","Funnel route read timed out")),M.initializationMs);try{let c=await v(ye(`${C}/funnels/${t}/versions/${n}/route`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:f.signal,headers:{}});if(c.status===404)throw u("ROUTE_UNAVAILABLE","This Funnel Version publishes no route");if(!c.ok)throw u(`CONFIGURATION_HTTP_${c.status}`,"Funnel route read failed");let R=await he(c,i.maxBytes,f.signal),N=je(R),A=c.headers.get("etag");if(A!==`"${N}"`&&A!==`W/"${N}"`)throw u("INVALID_RESPONSE","Funnel route identity changed");let G=o.safeParse(JSON.parse(R));if(!G.success||G.data.funnelId!==t||G.data.versionId!==n)throw u("INVALID_RESPONSE","Funnel route does not describe this Version");return G.data}finally{clearTimeout(p),E.delete(f)}}async function pt(t){let n=await ee();H(n,t);let i=n.funnels[t],o=i.currentVersionId,f;if(i.evaluationMode==="local"){let{projectFunnelRoute:p}=await import("./funnel-route-source-4ZVBFNYV.js"),c=await Ie(t,o),R=Object.entries(c.manifest.paywalls??{});f=p({funnelId:t,versionId:o,document:c.document,experiments:c.growth?.experiments??{},paywallOf:N=>R.find(([,A])=>Object.hasOwn(A.versions,N))?.[0]})}else{let p=`${t}:${o}`,c=oe.get(p);if(!c||B()-c.readAt>=M.maxControlAgeMs){let R={promise:mt(t,o),readAt:B()};oe.set(p,R),R.promise.catch(()=>{oe.get(p)===R&&oe.delete(p)}),c=R}f=await c.promise}return H(n,t),{route:structuredClone(f),control:structuredClone(i),generation:n.generation}}function te(){if(z()||Z(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}X().catch(ge)}function gt(t){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(t),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("focus",te),document.addEventListener("visibilitychange",te)),se()),()=>{P.delete(t),P.size||(clearTimeout(s),clearTimeout(I),Ae())}}function Ae(){typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",te))}return{scope:Object.freeze({...a}),refresh:X,subscribe:gt,assertFresh:re,assertFeatures(t){re();let n=m.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(t!==void 0&&m.artifacts[n].generation!==t)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return z()?Math.max(0,b-B()):0},async features(){return K(async()=>Re(await ee()))},pageExperiments:()=>K(async()=>{let t=await ee(),n=t.gb.pageExperiments;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let o=ut.parse(JSON.parse(await ue(i)));if(o.environmentId!==a.environmentId||o.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return H(t),o}),funnel:(t,n)=>K(()=>Ie(t,n)),funnelControl:t=>K(async()=>{let n=await ee();return H(n,t),structuredClone(n.funnels[t])}),funnelRoute:t=>K(()=>pt(t)),paywall:(t,n)=>K(async()=>{let i=await ee(),o=i.paywalls?.[t];if(!o||!n&&o.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let f=n??o.currentVersionId,p=o.versions[f],c=p&&i.artifacts[p.artifact];if(!c||c.kind!=="paywall"||c.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let R=ke.parse(JSON.parse(await ue(c)));return H(i),{document:R,versionId:f,version:p.version,control:structuredClone(o),manifest:structuredClone(i)}}),async localFunnel(t,n){let i=await K(()=>Ie(t,n));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:o,remoteFeatures:f,...p}=i.growth;return We({scope:{projectId:a.projectId,environment:a.environment},funnelId:t,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:p})},assertFunnel(t,n,i){re();let o=m.funnels[t];if(!o||o.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(o.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(n!==void 0&&o.controlRevision!==n)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!o.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,x++,b=0,k?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(I),Ae(),Z(),P.clear();for(let t of E)t.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));y.clear(),oe.clear(),J=0}}}}function dt(r){let a=le.test(r.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!me.test(r.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let O=U.safeParse({...g,operation:"start"});if(!O.success||O.data.operation!=="start"||(a?O.data.customer!==void 0:O.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let v=O.data,C=Ze({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let l=Xe(r,await C.request("funnels",v));if(!l.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(l.run.source.id!==v.funnelId||l.run.locale!==(v.locale??"en")||!nt(l.run.parameters,v.parameters??{})||(v.customer?!l.customerId||v.customer.type==="id"&&l.customerId!==v.customer.value:l.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...l,runToken:l.runToken}}finally{C.dispose()}}}}async function An(r){r={...r};let a=r.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(r.scope&&_(g)!==_(r.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(r.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let v=me.test(r.credential);if(v?!r.customerId:r.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=dt({...r,scope:g,apiKey:r.credential}),l=(w,m)=>{let b=rt({...r,scope:g,runToken:w,initialResponse:m,...v?{serverKey:r.credential}:{}});return v||b.identify(r.credential),b};return{async start(w){let m=await C.start({...w,funnelId:r.funnelId,...v?{customer:{type:"id",value:r.customerId}}:{}}),b=l(m.runToken,m),d=await b.get();return{...m,...d,controller:b}},async restore(w){let m=l(w),b=await m.get();if(b.run.source.id!==r.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...b,runToken:w,controller:m}}}}export{at as a,bt as b,Dt as c,Ut as d,Vt as e,Mt as f,kt as g,Wt as h,pn as i,dt as j,An as k};
1
+ import{A as me,E as rt,b as qe,c as $e,d as Se,h as He,i as Ke,j as Ye,n as We,q as Xe,z as nt}from"./chunk-RHILCVPZ.js";import{a as tt}from"./chunk-HT5SLWWG.js";import{c as Ne,d as Te,e as _e,f as Le,g as De,i as Ue,m as ke,n as M,o as Ge,q as be,r as _,s as je,t as ze,u as Be,v as Je}from"./chunk-FUP5JVDE.js";import{K as U,e as Ve,q as ve,r as Me}from"./chunk-AD35L6BX.js";import{a as fe,b as Ze}from"./chunk-7D5462NE.js";import{a as le}from"./chunk-7EENIOSJ.js";import{e as de}from"./chunk-7OJIW75D.js";import{a as D}from"./chunk-46USIMCJ.js";import{h as ie}from"./chunk-XIBJF5E6.js";import{b as et}from"./chunk-3VUPVXAV.js";import{a as Qe}from"./chunk-5MRSFLQA.js";import{b as e}from"./chunk-YLH3AYCK.js";import{c as Fe,f as Pe}from"./chunk-VPT5MFDG.js";var j=e.literal(Ve),ht=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ot=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:xe}),e.strictObject({type:e.literal("customer"),customer:ve,customerData:Me.optional()})]),Ee=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),yt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:Ee.omit({runId:!0,requestId:!0}).nullable()}),wt=e.union([qe,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),It=$e.omit({authenticated:!0}).extend({identity:yt,instruction:wt.nullable()}),vt=e.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),pe={contract:j,customerToken:e.string().regex(le)},it={contract:j,requestId:e.uuid(),runToken:ht,externalUserId:ve.options[1].shape.value},at=e.discriminatedUnion("operation",[e.strictObject({contract:j,operation:e.literal("describe")}),e.strictObject({contract:j,operation:e.literal("start"),source:ot,funnelId:U.options[0].shape.funnelId,requestId:e.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),He.omit({operation:!0}).extend({contract:j,operation:e.literal("entry_start"),source:ot}),e.strictObject({...it,operation:e.literal("bind_customer"),guestToken:xe,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...it,operation:e.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("review")}),Ye.omit({customerToken:!0}).extend(pe),e.strictObject({...pe,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:vt})]),bt=Se.omit({run:!0}).extend({contract:j,run:It,settlement:Se.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Dt=Ke.extend({contract:j}),Ut=e.discriminatedUnion("operation",[at.options[1].omit({contract:!0,source:!0,requestId:!0}),at.options[2].omit({contract:!0,source:!0,requestId:!0})]),Vt=bt.extend({binding:Ee,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Mt=e.discriminatedUnion("state",[e.strictObject({contract:j,scope:ie,state:e.literal("not_accepted")}),e.strictObject({contract:j,scope:ie,state:e.literal("conflict")}),e.strictObject({contract:j,scope:ie,state:e.literal("bound"),binding:Ee})]),kt=e.strictObject({contract:j,scope:ie,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var st=e.string().regex(/^[a-f0-9]{64}$/),St=Ne.omit({variations:!0,active:!0}).extend({changeId:st,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),ut=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:st,experiments:e.array(St).max(100),savedGroups:Te}),xt=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),Bt=e.strictObject({events:e.array(xt).min(1).max(20)}),Jt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Wt(r){let a=null,g=null,O=0,v=0,C=new Set,l=null,w=null,m=new Set,b=()=>{for(let s of m)try{s()}catch{}},d={attributes:de.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,I)=>{!C.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(I),structuredClone(d.attributes),a.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,I)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(I),structuredClone(d.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,I=new Set){return C.has(s)?!l||!l.features[s]||["unknownFeature","cyclicPrerequisite"].includes(l.features[s].source):I.has(s)?!1:(I.add(s),(a?.features[s]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(P=>P.experiment.parentConditions??[])].some(P=>h(P.id,I))))}let x=s=>{if(r.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return l?.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(l=null,d.features=a.features),C.has(s)?!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()?S():structuredClone(l.features[s]??S()):r.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!l||h(s)?S():structuredClone(Pe(s,d))};async function V(){if(!a||!C.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=v;if(w?.revision===s)return w.loading;let I=O,F=a,P=[...C],E=(async()=>{let y=Ue.parse(await r.evaluateRemote({attributes:structuredClone(d.attributes),features:P}));if(!(I!==O||s!==v||F!==a)){if(r.assertUsable?.(F.generation),y.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(P.some(T=>!Object.hasOwn(y.features,T))||Object.keys(y.features).some(T=>!C.has(T)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!y.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=de.parse({...d.attributes,...y.merchandiseContext})}l=structuredClone(y),d.features={...F.features,...Object.fromEntries(Object.entries(l.features).map(([T,J])=>[T,{defaultValue:J.value}]))},b()}})();w={revision:s,loading:E};try{await E}finally{w?.loading===E&&(w=null)}}function L(){V().catch(s=>{try{r.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=O,I=(async()=>{let F=await r.load(),P="remoteFeatures"in F?Le.parse(F):null,E=P??_e.parse(F);if(E.scope.projectId!==r.scope.projectId||E.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==O)throw new Error("Feature client was reset");if(r.assertUsable&&a?.generation===E.generation){let{evaluatedAt:T,expiresAt:J,...ae}=a,{evaluatedAt:Z,expiresAt:ge,...z}=E;if(_(ae)!==_(z))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=E.evaluatedAt,a.expiresAt=E.expiresAt,b(),(!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())&&L(),structuredClone(a)}let y=new Set(P?.remoteFeatures??[]);if([...y].some(T=>Object.hasOwn(E.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in E&&!a.analyticsConfig.experimentViewsEnabled&&P?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),a=structuredClone(E),C=y,l=null,w=null,v++,d.features=a.features,d.savedGroups=Fe(a.savedGroups),d.trackedFeatureUsage={},b(),L(),structuredClone(a)})();g=I;try{return await I}finally{g===I&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let I=de.parse(s);(d.attributes?.merchandise||d.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=I,v++,l=null,w=null,d.features=a?.features??{},d.trackedFeatureUsage={},b(),L()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,I){let F=x(s).value;return structuredClone(F===null?I:F)},reset(){O++,v++,g=null,w=null,a=null,l=null,C.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),b()}}}var Et=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),Q=2*1048576,Ct=100;function Rt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ct(r,a){let g=a===void 0?Rt():a,O=new Map,v=0,C=!1,l=!1,w,m;async function b(S){if(!g)return null;let h;try{let x=await Promise.race([Promise.resolve().then(()=>g.getItem(S)),new Promise(V=>{h=setTimeout(()=>V(null),Ct)})]);return typeof x=="string"&&x.length<=Q&&new TextEncoder().encode(x).byteLength<=Q?x:null}catch{return null}finally{clearTimeout(h)}}function d(){if(m)return m;let S=(async()=>{try{let h=await b(`${r}:artifacts`);if(h)return Et.parse(JSON.parse(h))}catch{}return{}})();return m=S,S.finally(()=>{m===S&&(m=void 0)}),S}return{async readManifest(){return b(r)},writeManifest(S){!g||S.length>Q||new TextEncoder().encode(S).byteLength>Q||(w=S,!l&&(l=!0,Promise.resolve().then(async()=>{try{for(;w!==void 0;){let h=w;try{await g.setItem(r,h)}catch{}w===h&&(w=void 0)}}finally{l=!1}})))},async readArtifact(S){let h=(await d())[S],x=Date.now();return h&&x>=h.at&&x-h.at<=M.retentionMs?h.text:void 0},writeArtifact(S,h){if(!g||h.length>Q)return;let x=O.get(S);if(x?.text===h||!x&&O.size>=128)return;let V=new TextEncoder().encode(h).byteLength;v-(x?.byteLength??0)+V>Q||(O.set(S,{text:h,byteLength:V}),v+=V-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;O.size;){let L=new Map(O);try{let k={...await d()},s=Date.now();for(let[E,y]of L)k[E]={at:s,text:y.text};let I={},F=2,P=0;for(let[E,y]of Object.entries(k).sort(([,T],[,J])=>J.at-T.at)){if(y.at>s||s-y.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[E]:y})).byteLength;F+T>Q||P>=128||(I[E]=y,F+=T,P++)}await g.setItem(`${r}:artifacts`,JSON.stringify(I))}catch{}finally{for(let[k,s]of L)O.get(k)===s&&(O.delete(k),v-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,a)=>new D(r,a),B=()=>performance.now(),lt=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function pn(r){let a=Ge.parse(r.scope),g=new fe(r.origin??Qe);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let O=new Set([g.origin,...(r.assetOrigins??[]).map(t=>{let n=new fe(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return n.origin})]),v=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${a.environmentId}`,l=`indiana:configuration:1:${g.origin}:${_(a)}`,w=ct(l,r.storage),m,b=0,d=0,S=!1,h=!1,x=0,V=0,L,k,s,I,F=0,P=new Set,E=new Set,y=new Map,T=new Map,J=0,ae=!1;function Z(){for(let t of P)try{t()}catch{}}function ge(t){try{r.onError?.(t)}catch{}}let z=()=>!h&&!S&&!!m&&B()<b&&Date.now()<d;function re(){if(!z())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(t,n,i){if(!y.has(t)){for(;y.size&&(y.size>=128||J+i>M.maxCacheBytes);){let o=y.entries().next().value;J-=o[1].byteLength,y.delete(o[0])}y.set(t,{text:n,byteLength:i}),J+=i}}function he(t,n,i){return et(t,n,{signal:i,error:o=>u("INVALID_RESPONSE",o==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function ye(t){let n=new fe(t,g);if(!O.has(n.origin)||n.username||n.password||n.hash||n.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return n.href}async function we(t,n,i=!1){let o=await v(ye(t),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:n,headers:{}});if(o.status===429){let f=o.headers.get("retry-after")??"";F=/^\d+$/.test(f)?Number(f)*1e3:Math.max(0,Date.parse(f)-Date.now())||15e3}if(!o.ok&&o.status!==304)throw u(`CONFIGURATION_HTTP_${o.status}`,"Configuration synchronization failed");return o}function ft(t,n,i){let o=Date.parse(t.headers.get("x-indiana-config-validated-at")??""),f=Date.parse(t.headers.get("x-indiana-config-valid-until")??""),p=Date.parse(t.headers.get("date")??""),c=t.headers.get("age"),R=c!==null&&/^\d+(\.\d+)?$/.test(c)?Number(c)*1e3:NaN;if(![o,f,p,R].every(Number.isFinite)||f<=o||f-o>M.maxControlAgeMs||o>p+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let A=Math.min(f-o,i.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(R,p-o,0)-(B()-n);if(A<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return B()+A}function se(){if(clearTimeout(s),clearTimeout(I),h||!P.size||(z()&&(I=setTimeout(()=>{z()?se():Z()},Math.max(1,b-B())),lt(I)),typeof document<"u"&&document.visibilityState==="hidden"))return;let t=V?Math.min(15e3,1e3*2**Math.min(V-1,4)):Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{X().catch(ge)},Math.max(F,t*(.8+Math.random()*.2))),lt(s)}async function X(){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let t=x,n=new AbortController;k=n;let i=(async()=>{if(!ae){ae=!0;try{let ce=await w.readManifest();if(ce&&!m){let $=be.parse(JSON.parse(ce));_($.scope)===_(a)&&(m=$)}}catch{}}n.signal.throwIfAborted();let c=m,R=B(),N=await we(C,n.signal);N.status===304&&(!c||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await we(C,n.signal));let A=N.status===304?c:be.parse(JSON.parse(await he(N,M.maxManifestBytes,n.signal))),{generation:G,...ne}=A,q=N.headers.get("etag");if(_(A.scope)!==_(a)||ze(ne)!==G||q!==`"${G}"`&&q!==`W/"${G}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(c&&(A.revision<c.revision||A.revision===c.revision&&A.generation!==c.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ce,$]of Object.entries(c?.funnels??{})){let W=A.funnels[ce];if(W&&(W.controlRevision<$.controlRevision||W.evaluationRevision<$.evaluationRevision||W.controlRevision===$.controlRevision&&W.state!==$.state||W.evaluationRevision===$.evaluationRevision&&W.evaluationMode!==$.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=ft(N,R,A.policy);if(n.signal.throwIfAborted(),t!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return m=A,b=Y,d=Date.now()+Math.max(0,Y-B()),S=!1,V=0,F=0,w.writeManifest(_(A)),Z(),structuredClone(A)})(),o=setTimeout(()=>n.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),f=new Promise((c,R)=>n.signal.addEventListener("abort",()=>R(n.signal.reason),{once:!0})),p=Promise.race([i,f]).catch(c=>{throw V++,(c instanceof e.ZodError||c instanceof SyntaxError||c instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(c.code))&&(b=0,S=!0,Z()),c}).finally(()=>{clearTimeout(o),L===p&&(L=void 0),se()});return L=p,p}async function ue(t){let n=t.sha256,i=ne=>tt(ne,t);ye(t.url);let o=y.get(n);if(o){if(o.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return y.delete(n),y.set(n,o),o.text}let f=T.get(n);if(f){if(f.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return f.promise}let p=new AbortController;E.add(p);let c=x,R=(async()=>{try{let Y=await w.readArtifact(n);if(Y&&i(Y)){if(p.signal.throwIfAborted(),h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,Y,t.byteLength),Y}}catch{}p.signal.throwIfAborted();let ne=await we(t.url,p.signal,!0),q=await he(ne,t.byteLength,p.signal);if(!i(q))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,q,t.byteLength),w.writeArtifact(n,q),q})(),N=setTimeout(()=>p.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),A=new Promise((ne,q)=>p.signal.addEventListener("abort",()=>q(p.signal.reason),{once:!0})),G=Promise.race([R,A]).finally(()=>{clearTimeout(N),E.delete(p),T.delete(n)});return T.set(n,{promise:G,byteLength:t.byteLength}),G}async function ee(){return z()||await X(),re(),m}async function K(t){let n,i=new Promise((o,f)=>{n=setTimeout(()=>f(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([t(),i])}finally{clearTimeout(n)}}function H(t,n){if(re(),m?.generation!==t.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(n&&m.funnels[n]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Re(t){let n=t.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let o=De.parse(JSON.parse(await ue(i)));if(_(o.scope)!==_({projectId:a.projectId,environment:a.environment})||o.generation!==i.generation||o.remoteFeatures.some(f=>Object.hasOwn(o.features,f)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return H(t),{...o,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,b-B())).toISOString()}}async function Oe(t,n){let i=await ee(),o=i.funnels[t];n&&(!o||o.evaluationMode==="local"&&!o.versions[n])&&(L&&await L,i=await X()),H(i,t);let f=i.funnels[t];if(f.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let p=n??f.currentVersionId,c=f.versions[p];if(!c)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[c.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[R,N]=await Promise.all([ue(i.artifacts[c.artifact]).then(A=>Je(JSON.parse(A))),f.evaluationMode==="local"?Re(i):void 0]);if(N&&_(Be(R,N))!==_(c.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return H(i,t),{document:R,growth:N,versionId:p,control:structuredClone(f),manifest:structuredClone(i)}}async function Ie(t,n){try{return await Oe(t,n)}catch(i){if(!(i instanceof D)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&z()))throw i;let o=m?.generation;if(L&&await L,await X(),i.code!=="CONFIGURATION_CHANGED"&&m?.generation===o)throw i;return Oe(t,n)}}let oe=new Map;async function mt(t,n){let{FUNNEL_ROUTE_LIMITS:i,funnelRouteSchema:o}=await import("./funnel-route-source-YVFAFCVG.js"),f=new AbortController;E.add(f);let p=setTimeout(()=>f.abort(u("CONFIGURATION_UNAVAILABLE","Funnel route read timed out")),M.initializationMs);try{let c=await v(ye(`${C}/funnels/${t}/versions/${n}/route`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:f.signal,headers:{}});if(c.status===404)throw u("ROUTE_UNAVAILABLE","This Funnel Version publishes no route");if(!c.ok)throw u(`CONFIGURATION_HTTP_${c.status}`,"Funnel route read failed");let R=await he(c,i.maxBytes,f.signal),N=je(R),A=c.headers.get("etag");if(A!==`"${N}"`&&A!==`W/"${N}"`)throw u("INVALID_RESPONSE","Funnel route identity changed");let G=o.safeParse(JSON.parse(R));if(!G.success||G.data.funnelId!==t||G.data.versionId!==n)throw u("INVALID_RESPONSE","Funnel route does not describe this Version");return G.data}finally{clearTimeout(p),E.delete(f)}}async function pt(t){let n=await ee();H(n,t);let i=n.funnels[t],o=i.currentVersionId,f;if(i.evaluationMode==="local"){let{projectFunnelRoute:p}=await import("./funnel-route-source-YVFAFCVG.js"),c=await Ie(t,o),R=Object.entries(c.manifest.paywalls??{});f=p({funnelId:t,versionId:o,document:c.document,experiments:c.growth?.experiments??{},paywallOf:N=>R.find(([,A])=>Object.hasOwn(A.versions,N))?.[0]})}else{let p=`${t}:${o}`,c=oe.get(p);if(!c||B()-c.readAt>=M.maxControlAgeMs){let R={promise:mt(t,o),readAt:B()};oe.set(p,R),R.promise.catch(()=>{oe.get(p)===R&&oe.delete(p)}),c=R}f=await c.promise}return H(n,t),{route:structuredClone(f),control:structuredClone(i),generation:n.generation}}function te(){if(z()||Z(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}X().catch(ge)}function gt(t){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(t),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("focus",te),document.addEventListener("visibilitychange",te)),se()),()=>{P.delete(t),P.size||(clearTimeout(s),clearTimeout(I),Ae())}}function Ae(){typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",te))}return{scope:Object.freeze({...a}),refresh:X,subscribe:gt,assertFresh:re,assertFeatures(t){re();let n=m.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(t!==void 0&&m.artifacts[n].generation!==t)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return z()?Math.max(0,b-B()):0},async features(){return K(async()=>Re(await ee()))},pageExperiments:()=>K(async()=>{let t=await ee(),n=t.gb.pageExperiments;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let o=ut.parse(JSON.parse(await ue(i)));if(o.environmentId!==a.environmentId||o.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return H(t),o}),funnel:(t,n)=>K(()=>Ie(t,n)),funnelControl:t=>K(async()=>{let n=await ee();return H(n,t),structuredClone(n.funnels[t])}),funnelRoute:t=>K(()=>pt(t)),paywall:(t,n)=>K(async()=>{let i=await ee(),o=i.paywalls?.[t];if(!o||!n&&o.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let f=n??o.currentVersionId,p=o.versions[f],c=p&&i.artifacts[p.artifact];if(!c||c.kind!=="paywall"||c.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let R=ke.parse(JSON.parse(await ue(c)));return H(i),{document:R,versionId:f,version:p.version,control:structuredClone(o),manifest:structuredClone(i)}}),async localFunnel(t,n){let i=await K(()=>Ie(t,n));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:o,remoteFeatures:f,...p}=i.growth;return We({scope:{projectId:a.projectId,environment:a.environment},funnelId:t,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:p})},assertFunnel(t,n,i){re();let o=m.funnels[t];if(!o||o.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(o.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(n!==void 0&&o.controlRevision!==n)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!o.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,x++,b=0,k?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(I),Ae(),Z(),P.clear();for(let t of E)t.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));y.clear(),oe.clear(),J=0}}}}function dt(r){let a=le.test(r.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!me.test(r.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let O=U.safeParse({...g,operation:"start"});if(!O.success||O.data.operation!=="start"||(a?O.data.customer!==void 0:O.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let v=O.data,C=Ze({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let l=Xe(r,await C.request("funnels",v));if(!l.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(l.run.source.id!==v.funnelId||l.run.locale!==(v.locale??"en")||!nt(l.run.parameters,v.parameters??{})||(v.customer?!l.customerId||v.customer.type==="id"&&l.customerId!==v.customer.value:l.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...l,runToken:l.runToken}}finally{C.dispose()}}}}async function An(r){r={...r};let a=r.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(r.scope&&_(g)!==_(r.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(r.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let v=me.test(r.credential);if(v?!r.customerId:r.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=dt({...r,scope:g,apiKey:r.credential}),l=(w,m)=>{let b=rt({...r,scope:g,runToken:w,initialResponse:m,...v?{serverKey:r.credential}:{}});return v||b.identify(r.credential),b};return{async start(w){let m=await C.start({...w,funnelId:r.funnelId,...v?{customer:{type:"id",value:r.customerId}}:{}}),b=l(m.runToken,m),d=await b.get();return{...m,...d,controller:b}},async restore(w){let m=l(w),b=await m.get();if(b.run.source.id!==r.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...b,runToken:w,controller:m}}}}export{at as a,bt as b,Dt as c,Ut as d,Vt as e,Mt as f,kt as g,Wt as h,pn as i,dt as j,An as k};
@@ -1 +1 @@
1
- import{d as b}from"./chunk-FQMZY5VP.js";import{b as r}from"./chunk-PZTWDJHN.js";var f=r.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),y=r.strictObject({type:r.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:r.boolean(),enum:r.array(r.string().max(255)).min(1).max(100).optional()}),g=y.extend({type:r.enum([...y.shape.type.options,"array"]),items:y.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),h=g.safeExtend({source:r.discriminatedUnion("type",[r.strictObject({type:r.literal("input")}),r.strictObject({type:r.literal("node")}),r.strictObject({type:r.enum(["parameter","attribute"]),key:f})])}),O=r.record(f,h),R=r.record(f,f).refine(e=>Object.keys(e).length<=20);function m(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>m(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&r.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function w(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&w(e.items,t.items)}function d(e,t){let n={};for(let[s,a]of Object.entries(e)){let i=a.source,l=i.type==="input"?t.answers:i.type==="node"?t.results??{}:i.type==="parameter"?t.parameters:t.attributes,c=i.type==="parameter"||i.type==="attribute"?i.key:s,u=Object.hasOwn(l,c),o=l[c];if(i.type==="attribute"&&c.includes(".")&&(!u||c.startsWith("merchandise."))){o=l,u=!0;for(let p of c.split(".")){if(!o||typeof o!="object"||!Object.hasOwn(o,p)||Array.isArray(o)&&(!/^(0|[1-9]\d*)$/.test(p)||Number(p)>=o.length)){u=!1;break}o=o[p]}}if(!(!u||o===void 0)){if(!m(a,o))throw new Error(`Invalid variable value: ${s}`);n[s]=o}}return n}function J(e,t){let n={};for(let[s,a]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,s))throw new Error(`Node output is missing: ${s}`);if(Object.hasOwn(n,a))throw new Error("Node outputs cannot overwrite one another");n[a]=t[s]}return n}function A(e,t,n){let s=new Set(Object.values(t.writes??{}));for(let[a,i]of Object.entries(n))if(!s.has(a)||e[a]?.source.type!=="node"||!m(e[a],i))throw new Error(`Invalid node variable write: ${a}`);if(s.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var k=b,V=["parameters","answers","results","variables"];function j(e){return V.some(t=>e===t||e.startsWith(t+"."))}function z(e){let t={};for(let[s,a]of Object.entries(d(e.declarations,e))){let i=s.split(".");if(i.some(u=>["__proto__","constructor","prototype"].includes(u)))throw new Error("Reserved result path");let l=t;for(let u of i.slice(0,-1)){Object.hasOwn(l,u)||(l[u]={});let o=l[u];if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Ambiguous result path");l=o}let c=i.at(-1);if(c===void 0)throw new Error("Empty result path");l[c]=a}return{...Object.fromEntries(Object.entries(e.attributes).filter(([s])=>!j(s))),variables:t}}var N=r.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);export{f as a,g as b,h as c,R as d,m as e,w as f,d as g,J as h,A as i,k as j,j as k,z as l,N as m};
1
+ import{d as b}from"./chunk-7OJIW75D.js";import{b as r}from"./chunk-YLH3AYCK.js";var f=r.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),y=r.strictObject({type:r.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:r.boolean(),enum:r.array(r.string().max(255)).min(1).max(100).optional()}),g=y.extend({type:r.enum([...y.shape.type.options,"array"]),items:y.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),h=g.safeExtend({source:r.discriminatedUnion("type",[r.strictObject({type:r.literal("input")}),r.strictObject({type:r.literal("node")}),r.strictObject({type:r.enum(["parameter","attribute"]),key:f})])}),O=r.record(f,h),R=r.record(f,f).refine(e=>Object.keys(e).length<=20);function m(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>m(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&r.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function w(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&w(e.items,t.items)}function d(e,t){let n={};for(let[s,a]of Object.entries(e)){let i=a.source,l=i.type==="input"?t.answers:i.type==="node"?t.results??{}:i.type==="parameter"?t.parameters:t.attributes,c=i.type==="parameter"||i.type==="attribute"?i.key:s,u=Object.hasOwn(l,c),o=l[c];if(i.type==="attribute"&&c.includes(".")&&(!u||c.startsWith("merchandise."))){o=l,u=!0;for(let p of c.split(".")){if(!o||typeof o!="object"||!Object.hasOwn(o,p)||Array.isArray(o)&&(!/^(0|[1-9]\d*)$/.test(p)||Number(p)>=o.length)){u=!1;break}o=o[p]}}if(!(!u||o===void 0)){if(!m(a,o))throw new Error(`Invalid variable value: ${s}`);n[s]=o}}return n}function J(e,t){let n={};for(let[s,a]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,s))throw new Error(`Node output is missing: ${s}`);if(Object.hasOwn(n,a))throw new Error("Node outputs cannot overwrite one another");n[a]=t[s]}return n}function A(e,t,n){let s=new Set(Object.values(t.writes??{}));for(let[a,i]of Object.entries(n))if(!s.has(a)||e[a]?.source.type!=="node"||!m(e[a],i))throw new Error(`Invalid node variable write: ${a}`);if(s.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var k=b,V=["parameters","answers","results","variables"];function j(e){return V.some(t=>e===t||e.startsWith(t+"."))}function z(e){let t={};for(let[s,a]of Object.entries(d(e.declarations,e))){let i=s.split(".");if(i.some(u=>["__proto__","constructor","prototype"].includes(u)))throw new Error("Reserved result path");let l=t;for(let u of i.slice(0,-1)){Object.hasOwn(l,u)||(l[u]={});let o=l[u];if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Ambiguous result path");l=o}let c=i.at(-1);if(c===void 0)throw new Error("Empty result path");l[c]=a}return{...Object.fromEntries(Object.entries(e.attributes).filter(([s])=>!j(s))),variables:t}}var N=r.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);export{f as a,g as b,h as c,R as d,m as e,w as f,d as g,J as h,A as i,k as j,j as k,z as l,N as m};
@@ -0,0 +1 @@
1
+ import{o as n,r as t}from"./chunk-RHILCVPZ.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};