@wix/himalaya-cli 0.1280.0 → 0.1282.0

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 (24) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/sdk/iap/src/catalog-pricing-contract.d.ts +9 -0
  2. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/sdk/iap/src/delivery-contract.d.ts +10 -3
  3. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/apple-iap-contract.d.ts +178 -0
  4. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/apple-iap-core.d.ts +4 -0
  5. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/apple-iap.d.ts +12 -0
  6. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/cashier-charges.d.ts +23 -0
  7. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/checkout-source.d.ts +1 -0
  8. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/iap-finish-policy.d.ts +8 -0
  9. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/iap-order-backend.d.ts +29 -0
  10. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/iap-verticals/index.d.ts +3 -0
  11. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/iap-verticals/online-programs.d.ts +2 -0
  12. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/iap-verticals/pricing-plans.d.ts +2 -0
  13. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/iap-verticals/shared.d.ts +19 -0
  14. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/iap-verticals/stores.d.ts +9 -0
  15. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/index.d.ts +4 -0
  16. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/order-refs.d.ts +17 -0
  17. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/stdlib/flows/iap-checkout/src/wix-bridge.d.ts +8 -0
  18. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/iap-checkout.mjs +1709 -0
  19. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/iap.mjs +34 -18
  20. package/dist/authoring-runtime/node_modules/@wix/himalaya/package.json +4 -0
  21. package/dist/cli.mjs +4 -4
  22. package/guides/iap-pricing.md +9 -0
  23. package/guides/sdk-reference.json +12 -6
  24. package/package.json +2 -2
@@ -0,0 +1,1709 @@
1
+ // ../../stdlib/flows/iap-checkout/src/checkout-source.ts
2
+ function appleIapCheckoutEnabled() {
3
+ return false;
4
+ }
5
+
6
+ // ../../core/sdk/dispatch/src/index.ts
7
+ function dispatch(handlerId, params, _options) {
8
+ const himalaya = globalThis.himalaya;
9
+ if (!himalaya) {
10
+ return Promise.reject(
11
+ new Error("@himalaya/dispatch: called outside a Himalaya runtime. This bundle must run inside a JSWorker (Tier 5).")
12
+ );
13
+ }
14
+ const stringParams = {};
15
+ if (params) {
16
+ for (const [k, v] of Object.entries(params)) stringParams[k] = String(v);
17
+ }
18
+ return himalaya.dispatch(handlerId, stringParams);
19
+ }
20
+
21
+ // ../../core/sdk/iap/src/delivery.ts
22
+ var MAX_AUTOMATIC_ATTEMPTS = 5;
23
+ var MAX_RETRY_DELAY_MS = 6e4;
24
+ var BASE_RETRY_DELAY_MS = 1e3;
25
+ var UNAVAILABLE_CODES = /* @__PURE__ */ new Set(["unsupported", "unavailable", "notEnabled"]);
26
+ function createPurchaseCoordinator(deps) {
27
+ const items = /* @__PURE__ */ new Map();
28
+ const queue = createSerialQueue();
29
+ const store = guardStore(deps.store);
30
+ let outcome = "idle";
31
+ let purchasing = false;
32
+ let signInPrompt = false;
33
+ let unavailable = null;
34
+ let pendingApproval = null;
35
+ let errorCode = null;
36
+ let errorFromReconcile = false;
37
+ let unfinishedCount = null;
38
+ let generation = deps.session.current().generation;
39
+ let staleSignal = createSignal();
40
+ let started = false;
41
+ let disposed = false;
42
+ const unsubscribe = deps.session.subscribe(onSessionNotified);
43
+ function start() {
44
+ started = true;
45
+ return reconcile2();
46
+ }
47
+ function purchase(catalogRef) {
48
+ onSessionNotified();
49
+ const requestedBy = deps.session.current();
50
+ const name = `purchase:${requestedBy.generation}:${catalogRef}`;
51
+ return runJob(name, () => runPurchase(requestedBy, catalogRef), { joinRunning: true }).then(([dropped, state]) => dropped ? { ...state, errorCode: "sessionChanged" } : state);
52
+ }
53
+ function reconcile2() {
54
+ resetIfSessionChanged();
55
+ return enqueue("reconcile", runReconcile);
56
+ }
57
+ function retry2() {
58
+ resetIfSessionChanged();
59
+ return enqueue("retry", runRetry);
60
+ }
61
+ function tick() {
62
+ if (resetIfSessionChanged() && started) return reconcile2();
63
+ return enqueue("tick", runDue);
64
+ }
65
+ function getState() {
66
+ if (disposed || !sessionMatches()) return { phase: "idle", errorCode: null, items: [], unfinishedCount: null, nextWakeAt: null };
67
+ const snapshot = [...items.values()].map((item) => ({ ...item.state }));
68
+ const due = snapshot.map((item) => item.nextAttemptAt).filter((at) => at !== null);
69
+ return { phase: currentPhase(), errorCode: errorCode ?? unavailable?.code ?? null, items: snapshot, unfinishedCount, nextWakeAt: due.length > 0 ? Math.min(...due) : null };
70
+ }
71
+ function dispose() {
72
+ disposed = true;
73
+ unsubscribe();
74
+ staleSignal.fire();
75
+ }
76
+ async function runPurchase(session, catalogRef) {
77
+ if (!isCurrent(session)) return !disposed;
78
+ setError(null, false);
79
+ outcome = "idle";
80
+ pendingApproval = null;
81
+ unavailable = null;
82
+ releaseSignIn();
83
+ if (session.kind !== "member") {
84
+ requireSignIn();
85
+ return false;
86
+ }
87
+ const context = await purchaseContext(session, catalogRef);
88
+ if (!isCurrent(session)) return !disposed;
89
+ if (!context) return false;
90
+ purchasing = true;
91
+ publish();
92
+ const { productId, appAccountToken } = context;
93
+ const result = await store.purchaseForVerification({ productId, appAccountToken });
94
+ purchasing = false;
95
+ if (!isCurrent(session)) return !disposed;
96
+ if (result.status === "purchased") await deliverPurchase(session, result.transaction, context);
97
+ else if (result.status === "failed") failStore(result.code, false);
98
+ else if (result.status === "pending") {
99
+ if (!await awaitApproval(session, context)) return !disposed;
100
+ } else setOutcome("cancelled");
101
+ return false;
102
+ }
103
+ async function deliverPurchase(session, transaction, context) {
104
+ const item = upsert2(transaction, null);
105
+ applyDelivered(await deliver(session, [item], context));
106
+ await enumerate(session);
107
+ publish();
108
+ }
109
+ async function runReconcile() {
110
+ resetIfSessionChanged();
111
+ const session = deps.session.current();
112
+ const listing = await enumerate(session);
113
+ if (listing === "stale") return;
114
+ if (session.kind !== "member") return requireSignIn();
115
+ if (listing === "listed") clearReconcileProblem();
116
+ const now = deps.clock.now();
117
+ const eligible = itemsWhere((item) => isAwaitingDelivery(item) && (item.state.nextAttemptAt === null || item.state.nextAttemptAt <= now));
118
+ eligible.forEach(restartAttemptBudget);
119
+ await settleDelivery(session, await deliver(session, eligible));
120
+ }
121
+ async function settleDelivery(session, delivered) {
122
+ applyDelivered(delivered);
123
+ if (delivered.finished) await enumerate(session);
124
+ publish();
125
+ }
126
+ function applyDelivered(delivered) {
127
+ if (delivered.confirmedProducts.length === 0) return;
128
+ if (outcome === "cancelled") outcome = "idle";
129
+ if (!delivered.signInLost) releaseSignIn();
130
+ }
131
+ function releaseSignIn() {
132
+ if (!signInPrompt) return;
133
+ signInPrompt = false;
134
+ const now = deps.clock.now();
135
+ for (const item of items.values()) {
136
+ if (item.state.access === "signInRequired") Object.assign(item.state, { access: "waitingToRetry", attempts: 0, nextAttemptAt: now });
137
+ }
138
+ }
139
+ function clearReconcileProblem() {
140
+ if (unavailable?.from === "reconcile") unavailable = null;
141
+ if (errorFromReconcile) setError(null, false);
142
+ }
143
+ async function runRetry() {
144
+ releaseSignIn();
145
+ for (const item of items.values()) unblock(item);
146
+ await runReconcile();
147
+ }
148
+ async function runDue() {
149
+ if (resetIfSessionChanged()) return started ? runReconcile() : void 0;
150
+ const session = memberSession();
151
+ const now = deps.clock.now();
152
+ const due = itemsWhere((item) => item.state.nextAttemptAt !== null && item.state.nextAttemptAt <= now);
153
+ if (!session || due.length === 0) return;
154
+ await settleDelivery(session, await deliver(session, due));
155
+ }
156
+ async function deliver(session, batch, known) {
157
+ const needProof = batch.filter((item) => !item.finishAllowed);
158
+ const context = known ?? (needProof.length > 0 ? await memberContext(session, needProof) : void 0);
159
+ const delivered = noDelivery();
160
+ for (const item of batch) {
161
+ if (!isCurrent(session)) return noDelivery();
162
+ const wasAllowed = item.finishAllowed;
163
+ if (delivered.signInLost && !wasAllowed) {
164
+ blockWithoutSession(item, context);
165
+ continue;
166
+ }
167
+ if (await deliverItem(session, item, context)) delivered.finished = true;
168
+ if (!wasAllowed && item.finishAllowed) delivered.confirmedProducts.push(item.state.productId);
169
+ if (item.state.access === "signInRequired") delivered.signInLost = true;
170
+ }
171
+ return delivered;
172
+ }
173
+ function blockWithoutSession(item, context) {
174
+ const foreign = context !== void 0 && !sameAccount(item.transaction.appAccountToken, context.appAccountToken);
175
+ block(item.state, foreign ? "ownershipConflict" : "signInRequired", null);
176
+ }
177
+ async function deliverItem(session, item, context) {
178
+ if (!item.finishAllowed) {
179
+ if (!context || !await confirmAccess(session, item, context)) return false;
180
+ }
181
+ return complete(session, item);
182
+ }
183
+ async function confirmAccess(session, item, context) {
184
+ if (!sameAccount(item.transaction.appAccountToken, context.appAccountToken)) {
185
+ block(item.state, "ownershipConflict", null);
186
+ return false;
187
+ }
188
+ updateItem(item, { access: "confirming", nextAttemptAt: null });
189
+ const settled = await settle(session, () => deps.backend.submitProof(session, item.transaction));
190
+ if (settled.kind === "stale") return false;
191
+ if (settled.kind === "error") return recordFailedAttempt(item, void 0);
192
+ return applySubmission(item, settled.value, context.scopeKey);
193
+ }
194
+ function applySubmission(item, raw, scopeKey) {
195
+ if (!isObject(raw)) return block(item.state, "rejected", "invalidResponse");
196
+ switch (raw.status) {
197
+ case "processed":
198
+ case "alreadyProcessed":
199
+ case "accepted":
200
+ case "refusedFinal":
201
+ if (!acknowledges(raw.acknowledgement, item.transaction, scopeKey)) return block(item.state, "rejected", "invalidResponse");
202
+ item.finishAllowed = true;
203
+ Object.assign(item.state, { ...FINISH_ALLOWED_STATE[raw.status], nextAttemptAt: null });
204
+ return true;
205
+ case "retryable":
206
+ return recordFailedAttempt(item, retryAfter(raw.retryAfterMs));
207
+ case "authRequired":
208
+ signInPrompt = true;
209
+ return block(item.state, "signInRequired", null);
210
+ case "ownershipConflict":
211
+ return block(item.state, "ownershipConflict", null);
212
+ case "rejected":
213
+ return block(item.state, "rejected", "proofRejected");
214
+ default:
215
+ return block(item.state, "rejected", "invalidResponse");
216
+ }
217
+ }
218
+ async function complete(session, item) {
219
+ if (!isCurrent(session)) return false;
220
+ const result = await store.finishTransaction({ transactionId: item.transaction.transactionId });
221
+ if (!isCurrent(session)) return false;
222
+ if (result.status === "failed") {
223
+ item.state.completion = "retryRequired";
224
+ recordFailedAttempt(item, void 0);
225
+ return false;
226
+ }
227
+ Object.assign(item.state, { completion: result.status, held: false, nextAttemptAt: null });
228
+ return result.status === "finished";
229
+ }
230
+ function recordFailedAttempt(item, retryAfterMs) {
231
+ const state = item.state;
232
+ state.attempts += 1;
233
+ if (!item.finishAllowed) state.access = "waitingToRetry";
234
+ state.nextAttemptAt = state.attempts >= MAX_AUTOMATIC_ATTEMPTS ? null : deps.clock.now() + retryDelay(state.attempts, retryAfterMs);
235
+ return false;
236
+ }
237
+ function retryDelay(attempts, retryAfterMs) {
238
+ if (retryAfterMs !== void 0) return Math.min(retryAfterMs, MAX_RETRY_DELAY_MS);
239
+ const base = Math.min(BASE_RETRY_DELAY_MS * 2 ** (attempts - 1), MAX_RETRY_DELAY_MS);
240
+ return base + Math.max(0, deps.jitter?.(base) ?? 0);
241
+ }
242
+ async function purchaseContext(session, catalogRef) {
243
+ const settled = await settle(session, () => deps.backend.getPurchaseContext(session, catalogRef));
244
+ if (settled.kind === "stale") return null;
245
+ const decoded = decodeContext(settled, isPurchaseContext);
246
+ if (decoded.kind === "ok") return decoded.context;
247
+ if (decoded.kind === "signInRequired") requireSignIn();
248
+ else failContext(decoded.kind);
249
+ return null;
250
+ }
251
+ async function memberContext(session, waiting) {
252
+ const settled = await settle(session, () => deps.backend.getMemberContext(session));
253
+ if (settled.kind === "stale") return void 0;
254
+ const decoded = decodeContext(settled, isMemberContext);
255
+ if (decoded.kind === "ok") return decoded.context;
256
+ if (decoded.kind === "rejected") setError("contextRejected", true);
257
+ if (decoded.kind === "signInRequired") signInPrompt = true;
258
+ for (const item of waiting) {
259
+ if (decoded.kind === "unavailable") recordFailedAttempt(item, decoded.retryAfterMs);
260
+ else if (decoded.kind === "rejected") block(item.state, "waitingToRetry", "contextRejected");
261
+ else block(item.state, "signInRequired", null);
262
+ }
263
+ return void 0;
264
+ }
265
+ async function enumerate(session, { quiet = false } = {}) {
266
+ if (!isCurrent(session)) return "stale";
267
+ const result = await store.getUnfinishedTransactions();
268
+ if (!isCurrent(session)) return "stale";
269
+ if (result.status !== "ok") {
270
+ unfinishedCount = null;
271
+ if (!quiet) failStore(result.code, true);
272
+ return "failed";
273
+ }
274
+ const held = new Set(result.transactions.map((transaction) => upsert2(transaction, true)));
275
+ for (const item of items.values()) if (!held.has(item)) item.state.held = false;
276
+ unfinishedCount = result.transactions.length;
277
+ return "listed";
278
+ }
279
+ function upsert2(transaction, held) {
280
+ const key = identityOf(transaction);
281
+ const existing = items.get(key);
282
+ if (existing) {
283
+ existing.transaction = transaction;
284
+ if (held !== null) existing.state.held = held;
285
+ return existing;
286
+ }
287
+ if (pendingApproval?.productId === transaction.productId && !pendingApproval.known.has(key) && sameAccount(transaction.appAccountToken, pendingApproval.token)) {
288
+ pendingApproval = null;
289
+ if (outcome === "awaitingApproval") outcome = "idle";
290
+ }
291
+ const item = { transaction, state: newItemState(transaction, held), finishAllowed: false };
292
+ items.set(key, item);
293
+ return item;
294
+ }
295
+ function onSessionNotified() {
296
+ if (resetIfSessionChanged() && started) void reconcile2();
297
+ }
298
+ function resetIfSessionChanged() {
299
+ const next = deps.session.current().generation;
300
+ if (disposed || next === generation) return false;
301
+ generation = next;
302
+ staleSignal.fire();
303
+ staleSignal = createSignal();
304
+ items.clear();
305
+ outcome = "idle";
306
+ purchasing = false;
307
+ signInPrompt = false;
308
+ unavailable = null;
309
+ pendingApproval = null;
310
+ unfinishedCount = null;
311
+ setError(null, false);
312
+ publish();
313
+ return true;
314
+ }
315
+ function memberSession() {
316
+ const session = deps.session.current();
317
+ return session.kind === "member" ? session : null;
318
+ }
319
+ function sessionMatches() {
320
+ return deps.session.current().generation === generation;
321
+ }
322
+ function isCurrent(session) {
323
+ return !disposed && session.generation === generation && sessionMatches();
324
+ }
325
+ async function settle(session, call) {
326
+ const stale = staleSignal.waiter();
327
+ try {
328
+ const pending = Promise.resolve().then(() => {
329
+ if (!isCurrent(session)) throw ABANDONED;
330
+ return call();
331
+ });
332
+ const settled = await Promise.race([pending.then((value) => ({ kind: "value", value })), stale.fired.then(() => STALE)]);
333
+ return isCurrent(session) ? settled : STALE;
334
+ } catch {
335
+ return isCurrent(session) ? { kind: "error" } : STALE;
336
+ } finally {
337
+ stale.cancel();
338
+ }
339
+ }
340
+ function runJob(name, run, options = {}) {
341
+ return queue.run(name, () => disposed ? Promise.resolve(void 0) : run(), options).then((result) => [result, getState()]);
342
+ }
343
+ function enqueue(name, run) {
344
+ return runJob(name, run).then(([, state]) => state);
345
+ }
346
+ function itemsWhere(predicate) {
347
+ return [...items.values()].filter(predicate);
348
+ }
349
+ function updateItem(item, patch) {
350
+ Object.assign(item.state, patch);
351
+ publish();
352
+ }
353
+ function requireSignIn() {
354
+ for (const item of items.values()) {
355
+ if (isAwaitingDelivery(item) && !item.finishAllowed) block(item.state, "signInRequired", null);
356
+ }
357
+ signInPrompt = true;
358
+ publish();
359
+ }
360
+ function failContext(reason) {
361
+ setError(reason === "rejected" ? "contextRejected" : "contextUnavailable", false);
362
+ publish();
363
+ }
364
+ function failStore(code, fromReconcile) {
365
+ setError(code, fromReconcile);
366
+ if (UNAVAILABLE_CODES.has(code) && unavailable?.from !== "purchase") {
367
+ unavailable = { from: fromReconcile ? "reconcile" : "purchase", code };
368
+ }
369
+ publish();
370
+ }
371
+ async function awaitApproval(session, context) {
372
+ if (await enumerate(session, { quiet: true }) === "stale") return false;
373
+ const known = new Set([...items.keys()].filter((key) => items.get(key).state.productId === context.productId));
374
+ pendingApproval = { productId: context.productId, token: context.appAccountToken, known };
375
+ setOutcome("awaitingApproval");
376
+ return true;
377
+ }
378
+ function setOutcome(next) {
379
+ outcome = next;
380
+ publish();
381
+ }
382
+ function currentPhase() {
383
+ if (purchasing) return "purchasing";
384
+ if (unavailable?.from === "purchase") return "unavailable";
385
+ if (signInPrompt) return "signInRequired";
386
+ if (unavailable?.from === "reconcile") return "unavailable";
387
+ return outcome;
388
+ }
389
+ function setError(code, fromReconcile) {
390
+ errorCode = code;
391
+ errorFromReconcile = code !== null && fromReconcile;
392
+ }
393
+ function publish() {
394
+ if (!disposed && sessionMatches()) deps.onState?.(getState());
395
+ }
396
+ return { start, purchase, reconcile: reconcile2, retry: retry2, tick, getState, dispose };
397
+ }
398
+ var FINISH_ALLOWED_STATE = {
399
+ processed: { access: "confirmed", errorCode: null },
400
+ alreadyProcessed: { access: "confirmed", errorCode: null },
401
+ accepted: { access: "processing", errorCode: null },
402
+ refusedFinal: { access: "rejected", errorCode: "proofRejected" }
403
+ };
404
+ var noDelivery = () => ({ finished: false, confirmedProducts: [], signInLost: false });
405
+ var STALE = { kind: "stale" };
406
+ var ABANDONED = { abandoned: true };
407
+ async function storeCall(call) {
408
+ try {
409
+ return await call();
410
+ } catch {
411
+ return { status: "failed", code: "storeError" };
412
+ }
413
+ }
414
+ function guardStore(store) {
415
+ return {
416
+ purchaseForVerification: (input) => storeCall(() => store.purchaseForVerification(input)),
417
+ getUnfinishedTransactions: () => storeCall(() => store.getUnfinishedTransactions()),
418
+ finishTransaction: (input) => storeCall(() => store.finishTransaction(input))
419
+ };
420
+ }
421
+ function identityOf(transaction) {
422
+ return `${transaction.store}:${transaction.environment}:${transaction.transactionId}`;
423
+ }
424
+ function newItemState(transaction, held) {
425
+ return {
426
+ productId: transaction.productId,
427
+ environment: transaction.environment,
428
+ held,
429
+ access: "pending",
430
+ completion: "pending",
431
+ attempts: 0,
432
+ nextAttemptAt: null,
433
+ errorCode: null
434
+ };
435
+ }
436
+ function isAwaitingDelivery(item) {
437
+ const state = item.state;
438
+ if (item.finishAllowed) return state.completion === "pending" || state.completion === "retryRequired";
439
+ return state.access === "pending" || state.access === "waitingToRetry" || state.access === "signInRequired";
440
+ }
441
+ function restartAttemptBudget(item) {
442
+ item.state.attempts = 0;
443
+ }
444
+ function unblock(item) {
445
+ if (!item.finishAllowed) Object.assign(item.state, { access: "pending", errorCode: null });
446
+ Object.assign(item.state, { attempts: 0, nextAttemptAt: null });
447
+ }
448
+ function block(state, access, errorCode) {
449
+ Object.assign(state, { access, errorCode, nextAttemptAt: null });
450
+ return false;
451
+ }
452
+ function sameAccount(transactionToken, memberToken) {
453
+ return transactionToken !== null && transactionToken.toLowerCase() === memberToken.toLowerCase();
454
+ }
455
+ function acknowledges(acknowledgement, transaction, scopeKey) {
456
+ return isObject(acknowledgement) && acknowledgement.transactionId === transaction.transactionId && acknowledgement.productId === transaction.productId && acknowledgement.environment === transaction.environment && acknowledgement.scopeKey === scopeKey;
457
+ }
458
+ function decodeContext(settled, isContext) {
459
+ const raw = settled.kind === "value" ? settled.value : null;
460
+ if (!isObject(raw)) return { kind: "unavailable" };
461
+ if (raw.status === "ok" && isContext(raw.context)) return { kind: "ok", context: raw.context };
462
+ if (raw.status === "authRequired") return { kind: "signInRequired" };
463
+ if (raw.status === "rejected") return { kind: "rejected" };
464
+ return { kind: "unavailable", retryAfterMs: retryAfter(raw.retryAfterMs) };
465
+ }
466
+ function isPurchaseContext(value) {
467
+ return isMemberContext(value) && isObject(value) && isNonEmpty(value.productId);
468
+ }
469
+ function isMemberContext(value) {
470
+ return isObject(value) && isNonEmpty(value.appAccountToken) && isNonEmpty(value.scopeKey);
471
+ }
472
+ function retryAfter(value) {
473
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
474
+ }
475
+ function isNonEmpty(value) {
476
+ return typeof value === "string" && value.length > 0;
477
+ }
478
+ function isObject(value) {
479
+ return value !== null && typeof value === "object" && !Array.isArray(value);
480
+ }
481
+ function createSignal() {
482
+ const listeners = /* @__PURE__ */ new Set();
483
+ let hasFired = false;
484
+ return {
485
+ fire() {
486
+ hasFired = true;
487
+ for (const listener of listeners) listener();
488
+ listeners.clear();
489
+ },
490
+ waiter() {
491
+ let listener = () => {
492
+ };
493
+ const fired = new Promise((resolve) => {
494
+ listener = resolve;
495
+ });
496
+ if (hasFired) listener();
497
+ else listeners.add(listener);
498
+ return { fired, cancel: () => {
499
+ listeners.delete(listener);
500
+ } };
501
+ }
502
+ };
503
+ }
504
+ function createSerialQueue() {
505
+ let tail = Promise.resolve();
506
+ const waiting = /* @__PURE__ */ new Map();
507
+ const running = /* @__PURE__ */ new Map();
508
+ async function execute(name, self, job) {
509
+ waiting.delete(name);
510
+ running.set(name, self);
511
+ try {
512
+ return await job();
513
+ } catch {
514
+ return void 0;
515
+ } finally {
516
+ running.delete(name);
517
+ }
518
+ }
519
+ return {
520
+ /** Callers joined onto a shared job all receive that job's result. */
521
+ run(name, job, { joinRunning = false }) {
522
+ const shared = waiting.get(name) ?? (joinRunning ? running.get(name) : void 0);
523
+ if (shared) return shared;
524
+ const scheduled = tail.then(() => execute(name, scheduled, job));
525
+ waiting.set(name, scheduled);
526
+ tail = scheduled;
527
+ return scheduled;
528
+ }
529
+ };
530
+ }
531
+
532
+ // ../../core/sdk/iap/src/index.ts
533
+ async function purchaseForVerification(input) {
534
+ if (!nonempty(input?.productId) || !isUUID2(input?.appAccountToken)) return failure2("invalidArgument");
535
+ const result = await managedDispatch(() => dispatch("capability.iap.purchaseForVerification", input));
536
+ if (result?.status === "purchased" && isAppleTransaction(result.transaction)) {
537
+ return { status: "purchased", transaction: decodeTransaction(result.transaction) };
538
+ }
539
+ if (result?.status === "pending" || result?.status === "cancelled") return { status: result.status };
540
+ return decodeFailure(result);
541
+ }
542
+ async function getUnfinishedTransactions() {
543
+ const result = await managedDispatch(() => dispatch("capability.iap.getUnfinishedTransactions"));
544
+ if (result?.status === "ok" && Array.isArray(result.transactions) && result.transactions.every(isAppleTransaction)) {
545
+ return { status: "ok", transactions: result.transactions.map(decodeTransaction) };
546
+ }
547
+ return decodeFailure(result);
548
+ }
549
+ async function finishTransaction(input) {
550
+ if (!nonempty(input?.transactionId)) return failure2("invalidArgument");
551
+ const result = await managedDispatch(() => dispatch("capability.iap.finishTransaction", input));
552
+ if (result?.status === "finished" || result?.status === "notFound") return { status: result.status };
553
+ return decodeFailure(result);
554
+ }
555
+ var appleManagedStore = { purchaseForVerification, getUnfinishedTransactions, finishTransaction };
556
+ var transactionErrors = /* @__PURE__ */ new Set(["unsupported", "unavailable", "invalidArgument", "invalidResponse", "notEnabled", "unsupportedProductType", "unknownProduct", "verificationFailed", "persistenceFailed", "ownershipConflict", "storeError", "busy"]);
557
+ var failure2 = (code) => ({ status: "failed", code });
558
+ var nonempty = (value) => typeof value === "string" && value.trim().length > 0;
559
+ var isUUID2 = (value) => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value) && value.length === 36;
560
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
561
+ async function managedDispatch(invoke) {
562
+ try {
563
+ const value = await invoke();
564
+ return isObject2(value) ? value : null;
565
+ } catch {
566
+ return failure2("unavailable");
567
+ }
568
+ }
569
+ function decodeFailure(value) {
570
+ return value?.status === "failed" && transactionErrors.has(value.code) ? failure2(value.code) : failure2("invalidResponse");
571
+ }
572
+ function isAppleTransaction(value) {
573
+ if (!isObject2(value)) return false;
574
+ return value.store === "apple" && typeof value.signedTransaction === "string" && /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(value.signedTransaction) && nonempty(value.transactionId) && nonempty(value.originalTransactionId) && nonempty(value.productId) && (value.appAccountToken === null || isUUID2(value.appAccountToken)) && ["production", "sandbox", "xcode", "unknown"].includes(value.environment);
575
+ }
576
+ function decodeTransaction(value) {
577
+ const { store, signedTransaction, transactionId, originalTransactionId, productId, appAccountToken, environment } = value;
578
+ return { store, signedTransaction, transactionId, originalTransactionId, productId, appAccountToken, environment };
579
+ }
580
+
581
+ // ../../stdlib/flows/iap-checkout/src/cashier-charges.ts
582
+ async function ensureAppleIapCharge(bridge, route, orderId) {
583
+ if (!isRoutePrefix2(route.prefix)) return { status: "notConfigured" };
584
+ if (!orderId) return { status: "invalidResponse" };
585
+ const listed = await listOrderCharges(bridge, route, orderId);
586
+ if (listed.status !== "ok") return listed;
587
+ return decideFromCharges(listed.charges) ?? chargeThenReconcile(bridge, route, orderId);
588
+ }
589
+ async function listOrderCharges(bridge, route, orderId) {
590
+ const answer = await bridge.call("GET", chargesPath(route, orderId));
591
+ if (answer.status !== "ok") return failureOf(answer);
592
+ const charges = decodeCharges(answer.body);
593
+ return charges ? { status: "ok", charges } : { status: "invalidResponse" };
594
+ }
595
+ async function chargeThenReconcile(bridge, route, orderId) {
596
+ const answer = await bridge.call("POST", chargesPath(route, orderId), APPLE_IAP_PAYMENT);
597
+ if (answer.status === "ok") return chargedFrom(answer.body) ?? reconcile(bridge, route, orderId);
598
+ if (answer.status === "sessionChanged" || answer.status === "notEnabled") return { status: answer.status };
599
+ return reconcile(bridge, route, orderId);
600
+ }
601
+ async function reconcile(bridge, route, orderId) {
602
+ const listed = await listOrderCharges(bridge, route, orderId);
603
+ if (listed.status !== "ok") return listed;
604
+ const decided = decideFromCharges(listed.charges);
605
+ return decided && decided.status !== "closed" ? decided : { status: "invalidResponse" };
606
+ }
607
+ function decideFromCharges(charges) {
608
+ const live = charges.filter((charge) => !RETRYABLE_AFTER.has(charge.status));
609
+ if (live.length === 0) return void 0;
610
+ if (live.some((charge) => CLOSED.has(charge.status))) return { status: "closed" };
611
+ const apple = live.find((charge) => charge.paymentMethod === APPLE_IAP);
612
+ if (!apple) return { status: "inOtherPayment" };
613
+ if (apple.status === "APPROVED") return { status: "approved", transactionId: apple.transactionId };
614
+ return isAwaitingApple(apple) ? { status: "pending", transactionId: apple.transactionId } : { status: "invalidResponse" };
615
+ }
616
+ function chargedFrom(body) {
617
+ const charge = isObject3(body) ? decodeCharge(body.charge) : null;
618
+ return charge && isAwaitingApple(charge) ? { status: "pending", transactionId: charge.transactionId } : null;
619
+ }
620
+ function isAwaitingApple(charge) {
621
+ return charge.paymentMethod === APPLE_IAP && AWAITING_PAYMENT.has(charge.status);
622
+ }
623
+ function decodeCharges(body) {
624
+ if (!isObject3(body)) return null;
625
+ const raw = body.charges ?? [];
626
+ if (!Array.isArray(raw)) return null;
627
+ const charges = raw.map(decodeCharge);
628
+ return charges.every((charge) => charge !== null) ? charges : null;
629
+ }
630
+ function decodeCharge(raw) {
631
+ if (!isObject3(raw) || !isNonEmpty2(raw.chargeId) || !isNonEmpty2(raw.transactionId)) return null;
632
+ const state = isObject3(raw.state) && isObject3(raw.state.transactionStatus) ? raw.state.transactionStatus : {};
633
+ const method = isNonEmpty2(raw.paymentMethodId) ? raw.paymentMethodId : isNonEmpty2(raw.paymentMethod) ? raw.paymentMethod : "";
634
+ return { chargeId: raw.chargeId, transactionId: raw.transactionId, status: isNonEmpty2(state.status) ? state.status : "UNDEFINED", paymentMethod: method };
635
+ }
636
+ function failureOf(answer) {
637
+ return answer.status === "http" ? { status: "refused" } : { status: answer.status };
638
+ }
639
+ function chargesPath(route, orderId) {
640
+ return `${route.prefix}/orders/${encodeURIComponent(orderId)}/charges`;
641
+ }
642
+ function isRoutePrefix2(prefix) {
643
+ return /^\/[A-Za-z0-9._~\-/]*[A-Za-z0-9._~-]$/.test(prefix);
644
+ }
645
+ function isObject3(value) {
646
+ return value !== null && typeof value === "object" && !Array.isArray(value);
647
+ }
648
+ function isNonEmpty2(value) {
649
+ return typeof value === "string" && value.length > 0;
650
+ }
651
+ var APPLE_IAP = "appleIAP";
652
+ var APPLE_IAP_PAYMENT = { payment: { details: { paymentMethod: APPLE_IAP } } };
653
+ var AWAITING_PAYMENT = /* @__PURE__ */ new Set(["INITIALIZATION", "INITIALIZED", "IN_PROCESS", "PENDING_BUYER"]);
654
+ var RETRYABLE_AFTER = /* @__PURE__ */ new Set(["DECLINED", "FAILED"]);
655
+ var CLOSED = /* @__PURE__ */ new Set(["BUYER_CANCELED", "TIMEOUT", "VOIDED", "REFUND", "CHARGE_BACK", "OFFLINE"]);
656
+
657
+ // ../../stdlib/flows/iap-checkout/src/iap-finish-policy.ts
658
+ var COMPLETE_PAYMENT_REFUSALS = {
659
+ // After recordPurchase (PurchaseMatcher.refusalOf / orphan): the purchase is recorded.
660
+ NOT_PURCHASED: "refusedFinal",
661
+ PURCHASE_REVOKED: "refusedFinal",
662
+ ZERO_PRICE: "refusedFinal",
663
+ NO_MATCHING_PAYMENT: "refusedFinal",
664
+ // Before recordPurchase: nothing is recorded. Held pending owner confirmation.
665
+ INVALID_PURCHASE: "hold",
666
+ APP_NOT_CONFIGURED: "hold",
667
+ OWNED_BY_ANOTHER_CUSTOMER: "ownershipConflict"
668
+ };
669
+ function isFinalRefusal(status) {
670
+ return status === "canceling" || status === "canceled" || status === "refunding" || status === "refunded";
671
+ }
672
+
673
+ // ../../stdlib/flows/iap-checkout/src/order-refs.ts
674
+ var NEEDS_SUPPORT_HOLD_MS = 6048e5;
675
+ function pruneExpiredHolds(partition, now) {
676
+ const expired = partition.refs().filter((ref) => HOLDS.has(ref.stage) && now - ref.updatedAt >= NEEDS_SUPPORT_HOLD_MS);
677
+ return expired.filter((ref) => partition.remove(ref.key)).map((ref) => ref.key);
678
+ }
679
+ var MAX_ORDER_REFS = 16;
680
+ function createWorkerOrderRefStore(storage) {
681
+ const kv = () => storage ?? hostStorage();
682
+ function open(key) {
683
+ if (!isPartitionKey(key)) return null;
684
+ const location = partitionKey(key);
685
+ if (readRefs(kv(), location) === null) return null;
686
+ return {
687
+ refs: () => readRefs(kv(), location) ?? [],
688
+ put: (ref) => writeWith(location, key, (refs) => upsert(refs, ref)),
689
+ remove: (refKey) => writeWith(location, key, (refs) => refs.filter((stored) => stored.key !== refKey))
690
+ };
691
+ }
692
+ function writeWith(location, key, change) {
693
+ const store = kv();
694
+ if (!store) return false;
695
+ const current = readRefs(store, location);
696
+ const next = current && change(current);
697
+ if (!next) return false;
698
+ if (next.length > 0 && !updateIndex(store, key, true)) return false;
699
+ if (!writeVerified(store, location, serialize({ v: VERSION, refs: next }))) return false;
700
+ if (next.length === 0) updateIndex(store, key, false);
701
+ return true;
702
+ }
703
+ function hasRefs(app) {
704
+ if (!isUUID3(app.purchasesAppId) || !isUUID3(app.siteId)) return null;
705
+ const customers = readIndex(kv(), indexKey(app));
706
+ return customers && customers.length > 0;
707
+ }
708
+ return { open, hasRefs };
709
+ }
710
+ function upsert(refs, ref) {
711
+ const others = refs.filter((stored) => stored.key !== ref.key);
712
+ if (others.length < MAX_ORDER_REFS) return [...others, ref];
713
+ const evictable = others.filter((stored) => EVICTABLE.has(stored.stage)).sort((a, b) => a.updatedAt - b.updatedAt)[0];
714
+ return evictable ? [...others.filter((stored) => stored !== evictable), ref] : null;
715
+ }
716
+ function updateIndex(store, key, holdsRefs) {
717
+ const location = indexKey(key);
718
+ const customers = readIndex(store, location);
719
+ if (customers === null) return false;
720
+ const customer = customerKey(key.customerId);
721
+ const others = customers.filter((stored) => stored !== customer);
722
+ const next = holdsRefs ? [...others, customer] : others;
723
+ return next.length === customers.length && next.every((c, i) => c === customers[i]) || writeVerified(store, location, serialize({ v: VERSION, customers: next }));
724
+ }
725
+ function readRefs(store, location) {
726
+ const parsed = readVersioned(store, location);
727
+ if (parsed === "empty") return [];
728
+ if (!parsed || !Array.isArray(parsed.refs) || !parsed.refs.every(isOrderRef)) return null;
729
+ return parsed.refs;
730
+ }
731
+ function readIndex(store, location) {
732
+ const parsed = readVersioned(store, location);
733
+ if (parsed === "empty") return [];
734
+ if (!parsed || !Array.isArray(parsed.customers) || !parsed.customers.every(isCustomerKey)) return null;
735
+ return parsed.customers;
736
+ }
737
+ function readVersioned(store, location) {
738
+ if (!store) return null;
739
+ const raw = safely(() => store.getItem(location));
740
+ if (raw === void 0) return null;
741
+ if (raw === null || raw === "") return "empty";
742
+ const parsed = safely(() => JSON.parse(raw));
743
+ return isObject4(parsed) && parsed.v === VERSION ? parsed : null;
744
+ }
745
+ function writeVerified(store, location, value) {
746
+ if (!store) return false;
747
+ return safely(() => {
748
+ store.setItem(location, value);
749
+ return store.getItem(location) === value;
750
+ }) === true;
751
+ }
752
+ function isOrderRef(value) {
753
+ if (!isObject4(value) || typeof value.key !== "string" || !STAGES.has(value.stage)) return false;
754
+ if (typeof value.updatedAt !== "number") return false;
755
+ const optional = ["kind", "cashierOrderId", "wixTransactionId", "paymentId", "storeProductId", "appProductId", "appleTransactionId"];
756
+ if (!optional.every((field) => value[field] === void 0 || typeof value[field] === "string")) return false;
757
+ return value.verticalRef === void 0 || isStringMap(value.verticalRef);
758
+ }
759
+ function isPartitionKey(key) {
760
+ return isUUID3(key.purchasesAppId) && isUUID3(key.siteId) && isUUID3(key.customerId);
761
+ }
762
+ function partitionKey(key) {
763
+ return `${PREFIX}.${key.purchasesAppId}.${key.siteId}.${customerKey(key.customerId)}`;
764
+ }
765
+ function customerKey(customerId) {
766
+ const text = customerId.toLowerCase();
767
+ let h1 = 3735928559;
768
+ let h2 = 1103547991;
769
+ for (let i = 0; i < text.length; i++) {
770
+ const code = text.charCodeAt(i);
771
+ h1 = Math.imul(h1 ^ code, 2654435761);
772
+ h2 = Math.imul(h2 ^ code, 1597334677);
773
+ }
774
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
775
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
776
+ return `c${(4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, "0")}`;
777
+ }
778
+ function isCustomerKey(value) {
779
+ return typeof value === "string" && /^c[0-9a-f]{14}$/.test(value);
780
+ }
781
+ function indexKey(app) {
782
+ return `${PREFIX}.${app.purchasesAppId}.${app.siteId}.customers`;
783
+ }
784
+ function hostStorage() {
785
+ const storage = globalThis.himalaya?.storage;
786
+ return typeof storage?.getItem === "function" && typeof storage.setItem === "function" ? storage : void 0;
787
+ }
788
+ function safely(read) {
789
+ try {
790
+ return read();
791
+ } catch {
792
+ return void 0;
793
+ }
794
+ }
795
+ function serialize(value) {
796
+ return JSON.stringify(value);
797
+ }
798
+ function isStringMap(value) {
799
+ return isObject4(value) && Object.values(value).every((entry) => typeof entry === "string");
800
+ }
801
+ function isObject4(value) {
802
+ return value !== null && typeof value === "object" && !Array.isArray(value);
803
+ }
804
+ function isUUID3(value) {
805
+ return typeof value === "string" && /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(value);
806
+ }
807
+ var VERSION = 1;
808
+ var PREFIX = "himi.iap.wix-checkout.v1";
809
+ var STAGES = /* @__PURE__ */ new Set(["ordered", "charged", "started", "submitted", "held", "needsSupport"]);
810
+ var HOLDS = /* @__PURE__ */ new Set(["held", "needsSupport"]);
811
+ var EVICTABLE = /* @__PURE__ */ new Set(["ordered", "charged", "started"]);
812
+
813
+ // ../../stdlib/flows/iap-checkout/src/wix-bridge.ts
814
+ function bindBridge(session, provider, bridge) {
815
+ const isCurrent = () => session.kind === "member" && provider.current().generation === session.generation;
816
+ async function call(method, path, body) {
817
+ if (!isCurrent()) return SESSION_CHANGED;
818
+ const outcome = await attempt(bridge, method, path, body);
819
+ return isCurrent() ? outcome : SESSION_CHANGED;
820
+ }
821
+ return { call, isCurrent };
822
+ }
823
+ function hostBridge() {
824
+ const himalaya = globalThis.himalaya;
825
+ const bridge = himalaya ? himalaya.wixApi : void 0;
826
+ return typeof bridge?.call === "function" ? bridge : void 0;
827
+ }
828
+ var MISSING_BRIDGE = { call: () => Promise.reject(new Error("wixApi not enabled")) };
829
+ async function attempt(bridge, method, path, body) {
830
+ try {
831
+ return { status: "ok", body: await bridge.call(method, path, body) };
832
+ } catch (error) {
833
+ return refusalOf(error);
834
+ }
835
+ }
836
+ function refusalOf(error) {
837
+ const message = error?.message;
838
+ const text = typeof message === "string" ? message : "";
839
+ if (BRIDGE_REFUSAL.test(text)) return { status: "notEnabled" };
840
+ if (PRINCIPAL_CHANGED.test(text)) return SESSION_CHANGED;
841
+ const http = /^HTTP (\d{3})(?: \[([^\]]+)\])?:/.exec(text);
842
+ if (!http) return { status: "unavailable" };
843
+ return httpRefusal(Number(http[1]), http[2] ?? "");
844
+ }
845
+ function httpRefusal(httpStatus, code) {
846
+ if (code === "PRINCIPAL_CHANGED") return SESSION_CHANGED;
847
+ if (code === "UNAVAILABLE" || httpStatus === 408 || httpStatus === 429 || httpStatus >= 500) return { status: "unavailable" };
848
+ return { status: "http", httpStatus, code };
849
+ }
850
+ var SESSION_CHANGED = { status: "sessionChanged" };
851
+ var BRIDGE_REFUSAL = /^(wixApi not enabled|capability wix_api not allowed)\b|^NotInstalled\(\)$/;
852
+ var PRINCIPAL_CHANGED = /^PRINCIPAL_CHANGED\b/;
853
+
854
+ // ../../stdlib/flows/iap-checkout/src/iap-order-backend.ts
855
+ function createWixOrderBackend(deps) {
856
+ let cached = null;
857
+ const now = () => deps.clock.now();
858
+ const isCurrent = (session) => session.kind === "member" && deps.session.current().generation === session.generation;
859
+ const adapterFor = (kind) => deps.adapters.find((adapter) => adapter.kind === kind);
860
+ async function memberOf(session) {
861
+ if (cached?.generation === session.generation) return cached.member;
862
+ const binding = await readBinding(deps.binding);
863
+ if (!isCurrent(session)) return STALE2;
864
+ if (binding === void 0) return retry("unavailable");
865
+ if (!binding) return stopWith("rejected", "notConfigured");
866
+ const customer = await deps.wixIap.getCustomerId();
867
+ if (!isCurrent(session)) return STALE2;
868
+ if (customer.status !== "found") return failureStop(customer);
869
+ const member = memberFor(binding, customer.customerId);
870
+ cached = { generation: session.generation, member };
871
+ return member;
872
+ }
873
+ function memberFor(binding, customerId) {
874
+ const partition = deps.refs.open({ purchasesAppId: binding.purchasesAppId, siteId: binding.siteId, customerId });
875
+ return { customerId, scopeKey: `${binding.purchasesAppId}:${customerId}`, partition };
876
+ }
877
+ async function getPurchaseContext(session, catalogRef) {
878
+ const sale = await saleFor(session, catalogRef);
879
+ if (isStop(sale)) return contextResult(catalogRef, sale);
880
+ const ordered = await orderFor(sale);
881
+ if (isStop(ordered)) return contextResult(catalogRef, ordered);
882
+ const charged = await chargeFor(sale, ordered, { reordered: false });
883
+ if (isStop(charged)) return contextResult(catalogRef, charged);
884
+ return startFor(sale, charged);
885
+ }
886
+ async function saleFor(session, catalogRef) {
887
+ const sold = deps.itemFor(catalogRef);
888
+ const adapter = sold && adapterFor(sold.item.reference.kind);
889
+ if (!sold || !adapter) return stopWith("rejected", "unsupportedItem");
890
+ const eligibility = adapter.eligibility(sold.item);
891
+ if (!eligibility.eligible) return stopWith("rejected", eligibility.reason);
892
+ const member = await memberOf(session);
893
+ if (isStop(member)) return member;
894
+ if (!member.partition) return stopWith("rejected", "storageUnavailable");
895
+ if (!isCurrent(session)) return STALE2;
896
+ pruneExpiredHolds(member.partition, now());
897
+ return {
898
+ catalogRef,
899
+ item: sold.item,
900
+ appleProduct: sold.appleProduct,
901
+ adapter,
902
+ member,
903
+ partition: member.partition,
904
+ bridge: bindBridge(session, deps.session, deps.bridge)
905
+ };
906
+ }
907
+ async function orderFor(sale) {
908
+ const existing = refAt(sale.partition, sale.catalogRef);
909
+ if (existing?.stage === "submitted") return stopWith("rejected", "paymentInProgress");
910
+ if (existing?.stage === "held") return stopWith("rejected", "paymentHeld");
911
+ if (existing?.stage === "needsSupport") return stopWith("rejected", "needsSupport");
912
+ const attempt2 = existing?.cashierOrderId && existing.verticalRef ? await reopenOrOpen(sale, { cashierOrderId: existing.cashierOrderId, verticalRef: existing.verticalRef }) : await sale.adapter.openOrder(sale.item, sale.bridge);
913
+ return recordOrder(sale, existing, attempt2);
914
+ }
915
+ async function reopenOrOpen(sale, order) {
916
+ const reopened = await sale.adapter.reopenOrder(order, sale.bridge);
917
+ const closed = reopened.status === "refused" && reopened.reason === "orderClosed";
918
+ return closed ? sale.adapter.openOrder(sale.item, sale.bridge) : reopened;
919
+ }
920
+ function recordOrder(sale, existing, attempt2) {
921
+ if (attempt2.status === "granted") return alreadyOwned(sale);
922
+ if (attempt2.status === "refused") return stopWith("rejected", attempt2.reason);
923
+ if (attempt2.status !== "open") return attempt2.status === "sessionChanged" ? STALE2 : retry("unavailable");
924
+ const kept = existing && existing.cashierOrderId === attempt2.cashierOrderId ? existing : { key: sale.catalogRef, updatedAt: 0 };
925
+ return persist(sale, {
926
+ ...kept,
927
+ key: sale.catalogRef,
928
+ stage: "ordered",
929
+ kind: sale.adapter.kind,
930
+ verticalRef: attempt2.verticalRef,
931
+ cashierOrderId: attempt2.cashierOrderId,
932
+ updatedAt: now()
933
+ });
934
+ }
935
+ async function chargeFor(sale, ref, options) {
936
+ const charge = await ensureAppleIapCharge(sale.bridge, deps.cashier, ref.cashierOrderId ?? "");
937
+ switch (charge.status) {
938
+ case "pending":
939
+ return persist(sale, { ...ref, stage: "charged", wixTransactionId: charge.transactionId, updatedAt: now() });
940
+ case "approved":
941
+ return alreadyPaid(sale, ref);
942
+ case "closed":
943
+ return options.reordered ? stopWith("rejected", "orderClosed") : reorder(sale);
944
+ case "inOtherPayment":
945
+ return stopWith("rejected", "orderRefused");
946
+ case "refused":
947
+ return stopWith("rejected", "chargeFailed");
948
+ case "notConfigured":
949
+ case "notEnabled":
950
+ return stopWith("rejected", "notConfigured");
951
+ case "sessionChanged":
952
+ return STALE2;
953
+ default:
954
+ return retry("unavailable");
955
+ }
956
+ }
957
+ async function reorder(sale) {
958
+ if (!forget(sale, sale.catalogRef)) return stopWith("rejected", "storageUnavailable");
959
+ const recorded = recordOrder(sale, void 0, await sale.adapter.openOrder(sale.item, sale.bridge));
960
+ return isStop(recorded) ? recorded : chargeFor(sale, recorded, { reordered: true });
961
+ }
962
+ async function alreadyPaid(sale, ref) {
963
+ const access = await sale.adapter.readAccess(ref.verticalRef ?? {}, sale.bridge);
964
+ if (access === "granted") return alreadyOwned(sale);
965
+ if (access === "sessionChanged") return STALE2;
966
+ return access === "unavailable" ? retry("unavailable") : stopWith("rejected", "paymentInProgress");
967
+ }
968
+ async function startFor(sale, ref) {
969
+ if (!sale.bridge.isCurrent()) return contextResult(sale.catalogRef, STALE2);
970
+ const started = await deps.wixIap.startPayment({ wixTransactionId: ref.wixTransactionId ?? "" });
971
+ if (!sale.bridge.isCurrent()) return contextResult(sale.catalogRef, STALE2);
972
+ if (started.status !== "started") return contextResult(sale.catalogRef, await startRefusal(sale, ref, started));
973
+ const mismatch = startedMismatch(sale, started);
974
+ if (mismatch) return contextResult(sale.catalogRef, stopWith("rejected", mismatch));
975
+ const recorded = persist(sale, {
976
+ ...ref,
977
+ stage: "started",
978
+ paymentId: started.payment.paymentId,
979
+ storeProductId: started.storeProductId,
980
+ ...started.payment.appProductId ? { appProductId: started.payment.appProductId } : {},
981
+ updatedAt: now()
982
+ });
983
+ if (isStop(recorded)) return contextResult(sale.catalogRef, recorded);
984
+ return { status: "ok", context: { productId: started.storeProductId, appAccountToken: sale.member.customerId, scopeKey: sale.member.scopeKey } };
985
+ }
986
+ function startedMismatch(sale, started) {
987
+ if (!sameUUID(started.customerId, sale.member.customerId)) return "invalidAssociation";
988
+ return sale.appleProduct.productId === started.storeProductId ? null : "productChanged";
989
+ }
990
+ async function startRefusal(sale, ref, failure3) {
991
+ if (failure3.kind !== "application") return failureStop(failure3);
992
+ if (failure3.code === "ALREADY_OWNED") return alreadyPaid(sale, ref);
993
+ if (failure3.code === "NOT_PENDING" || failure3.code === "NOT_ORDER_BUYER") forget(sale, sale.catalogRef);
994
+ return stopWith("rejected", failure3.code === "NOT_PENDING" ? "orderClosed" : "paymentRefused");
995
+ }
996
+ function alreadyOwned(sale) {
997
+ forget(sale, sale.catalogRef);
998
+ return stopWith("rejected", "alreadyOwned");
999
+ }
1000
+ function persist(sale, ref) {
1001
+ if (!sale.bridge.isCurrent()) return STALE2;
1002
+ return sale.partition.put(ref) ? ref : stopWith("rejected", "storageUnavailable");
1003
+ }
1004
+ function forget(sale, key) {
1005
+ return sale.bridge.isCurrent() && sale.partition.remove(key);
1006
+ }
1007
+ function contextResult(catalogRef, stop) {
1008
+ if (stop.failure) deps.report({ key: catalogRef, failure: stop.failure });
1009
+ return { status: stop.result };
1010
+ }
1011
+ async function submitProof(session, transaction) {
1012
+ const member = await memberOf(session);
1013
+ if (isStop(member)) return { status: member.result };
1014
+ if (!isCurrent(session)) return RETRYABLE;
1015
+ const completed = await deps.wixIap.completePayment(transaction);
1016
+ if (!isCurrent(session)) return RETRYABLE;
1017
+ const proof = { session, transaction, member, acknowledgement: acknowledgementOf(transaction, member.scopeKey) };
1018
+ return completed.status === "matched" ? matchedProof(proof, completed.payment) : refusedProof(proof, completed);
1019
+ }
1020
+ async function matchedProof(proof, payment) {
1021
+ const refs = proof.member.partition?.refs() ?? [];
1022
+ const ref = refs.find((stored) => stored.paymentId === payment.paymentId) ?? refs.find((stored) => stored.wixTransactionId === payment.wixTransactionId);
1023
+ if (ref?.storeProductId && ref.storeProductId !== proof.transaction.productId) return holdAssociation(ref);
1024
+ reportOtherOrders(refs, ref, payment, proof.transaction);
1025
+ const tracking = trackingRef(ref, payment, proof.transaction, now());
1026
+ if (isFinalRefusal(payment.status)) return finalRefusal(proof, tracking);
1027
+ if (payment.status === "pending") return RETRYABLE;
1028
+ if (payment.status === "approved") {
1029
+ const granted = await accessGranted(proof, tracking);
1030
+ if (granted === "stale") return RETRYABLE;
1031
+ if (granted) return processed(proof, tracking);
1032
+ }
1033
+ return acceptTracking(proof, tracking, payment);
1034
+ }
1035
+ function holdAssociation(ref) {
1036
+ deps.report({ key: ref.key, failure: "invalidAssociation" });
1037
+ return { status: "rejected" };
1038
+ }
1039
+ function reportOtherOrders(refs, matched, payment, transaction) {
1040
+ for (const other of refs) {
1041
+ if (other.key === matched?.key || other.stage !== "started" || other.storeProductId !== transaction.productId) continue;
1042
+ if (other.paymentId !== payment.paymentId) deps.report({ key: other.key, failure: "matchedOtherOrder" });
1043
+ }
1044
+ }
1045
+ async function accessGranted(proof, ref) {
1046
+ const adapter = adapterFor(ref.kind);
1047
+ if (!adapter || !ref.verticalRef) return false;
1048
+ const bridge = bindBridge(proof.session, deps.session, deps.bridge);
1049
+ const access = await adapter.readAccess(ref.verticalRef, bridge);
1050
+ if (!bridge.isCurrent()) return "stale";
1051
+ return access === "granted";
1052
+ }
1053
+ function processed(proof, ref) {
1054
+ proof.member.partition?.remove(ref.key);
1055
+ deps.report({ key: ref.key, access: "granted" });
1056
+ return { status: "processed", acknowledgement: proof.acknowledgement };
1057
+ }
1058
+ function acceptTracking(proof, ref, payment) {
1059
+ const partition = proof.member.partition;
1060
+ if (!partition || !isCurrent(proof.session) || !partition.put(ref)) return RETRYABLE;
1061
+ deps.report({ key: ref.key, access: !ref.kind && payment.status === "approved" ? "accessUnknown" : "processing" });
1062
+ return { status: "accepted", acknowledgement: proof.acknowledgement };
1063
+ }
1064
+ function finalRefusal(proof, ref) {
1065
+ const hold = ref ?? unassociatedHold(proof.transaction, now());
1066
+ const partition = proof.member.partition;
1067
+ if (!partition || !isCurrent(proof.session) || !partition.put({ ...hold, stage: "needsSupport", updatedAt: now() })) return RETRYABLE;
1068
+ deps.report({ key: hold.key, access: "needsSupport" });
1069
+ return { status: "refusedFinal", acknowledgement: proof.acknowledgement };
1070
+ }
1071
+ function refusedProof(proof, failure3) {
1072
+ const refusal = failure3.kind === "application" ? COMPLETE_PAYMENT_REFUSALS[failure3.code] : failureStop(failure3).result;
1073
+ if (refusal === "refusedFinal") return finalRefusal(proof, startedRefFor(proof));
1074
+ if (refusal === "hold" || refusal === "rejected") return heldProof(proof, "rejected");
1075
+ return refusal === "ownershipConflict" ? heldProof(proof, "ownershipConflict") : { status: refusal };
1076
+ }
1077
+ function heldProof(proof, status) {
1078
+ const started = startedRefFor(proof);
1079
+ const hold = started && { ...started, stage: "held", appleTransactionId: proof.transaction.transactionId, updatedAt: now() };
1080
+ if (hold && !(isCurrent(proof.session) && proof.member.partition?.put(hold))) return RETRYABLE;
1081
+ deps.report({ key: started?.key ?? `payment:${proof.transaction.transactionId}`, failure: "paymentHeld" });
1082
+ return { status };
1083
+ }
1084
+ function startedRefFor(proof) {
1085
+ const refs = proof.member.partition?.refs() ?? [];
1086
+ return refs.find((ref) => (ref.stage === "started" || ref.stage === "held") && ref.storeProductId === proof.transaction.productId);
1087
+ }
1088
+ async function getMemberContext(session) {
1089
+ const member = await memberOf(session);
1090
+ if (isStop(member)) return { status: member.result };
1091
+ return { status: "ok", context: { appAccountToken: member.customerId, scopeKey: member.scopeKey } };
1092
+ }
1093
+ return { getPurchaseContext, getMemberContext, submitProof };
1094
+ }
1095
+ var RETRYABLE = { status: "retryable" };
1096
+ var STALE2 = { stop: true, result: "retryable" };
1097
+ function stopWith(result, failure3) {
1098
+ return { stop: true, result, failure: failure3 };
1099
+ }
1100
+ function retry(failure3) {
1101
+ return stopWith("retryable", failure3);
1102
+ }
1103
+ function isStop(value) {
1104
+ return typeof value === "object" && value !== null && value.stop === true;
1105
+ }
1106
+ function failureStop(failure3) {
1107
+ if (failure3.kind === "application") return stopWith("rejected", "notConfigured");
1108
+ return KIND_STOPS[failure3.kind];
1109
+ }
1110
+ var SIGN_IN = { stop: true, result: "authRequired", failure: "signInRequired" };
1111
+ var NOT_CONFIGURED = { stop: true, result: "rejected", failure: "notConfigured" };
1112
+ var UNAVAILABLE = { stop: true, result: "retryable", failure: "unavailable" };
1113
+ var KIND_STOPS = {
1114
+ authRequired: SIGN_IN,
1115
+ notPermitted: SIGN_IN,
1116
+ notEnabled: NOT_CONFIGURED,
1117
+ notProvisioned: NOT_CONFIGURED,
1118
+ environmentUnsupported: NOT_CONFIGURED,
1119
+ invalidArgument: NOT_CONFIGURED,
1120
+ sessionChanged: STALE2,
1121
+ unavailable: UNAVAILABLE,
1122
+ unrecognized: UNAVAILABLE,
1123
+ invalidResponse: UNAVAILABLE
1124
+ };
1125
+ function trackingRef(ref, payment, transaction, updatedAt) {
1126
+ const ids = { paymentId: payment.paymentId, wixTransactionId: payment.wixTransactionId, appleTransactionId: transaction.transactionId, updatedAt };
1127
+ if (ref) return { ...ref, ...ids, stage: "submitted" };
1128
+ return {
1129
+ key: `payment:${payment.paymentId}`,
1130
+ stage: "submitted",
1131
+ storeProductId: transaction.productId,
1132
+ ...payment.appProductId ? { appProductId: payment.appProductId } : {},
1133
+ ...ids
1134
+ };
1135
+ }
1136
+ function unassociatedHold(transaction, updatedAt) {
1137
+ return { key: `payment:${transaction.transactionId}`, stage: "needsSupport", storeProductId: transaction.productId, appleTransactionId: transaction.transactionId, updatedAt };
1138
+ }
1139
+ function acknowledgementOf(transaction, scopeKey) {
1140
+ return { transactionId: transaction.transactionId, productId: transaction.productId, environment: transaction.environment, scopeKey };
1141
+ }
1142
+ function refAt(partition, key) {
1143
+ return partition.refs().find((ref) => ref.key === key);
1144
+ }
1145
+ async function readBinding(source) {
1146
+ try {
1147
+ return await source.current();
1148
+ } catch {
1149
+ return void 0;
1150
+ }
1151
+ }
1152
+ function sameUUID(a, b) {
1153
+ return a.toLowerCase() === b.toLowerCase();
1154
+ }
1155
+
1156
+ // ../../stdlib/flows/iap-checkout/src/apple-iap-core.ts
1157
+ function createAppleIapCheckoutWith(deps) {
1158
+ return deps.enabled ? enabledCheckout(deps) : disabledCheckout();
1159
+ }
1160
+ function enabledCheckout(deps) {
1161
+ const refs = deps.refs ?? createWorkerOrderRefStore();
1162
+ const bridge = deps.bridge ?? hostBridge() ?? MISSING_BRIDGE;
1163
+ const sales = /* @__PURE__ */ new Map();
1164
+ const payments = /* @__PURE__ */ new Map();
1165
+ let current = { item: null, failure: null, buying: false };
1166
+ let generation = deps.session.current().generation;
1167
+ let disposed = false;
1168
+ let tracking = Promise.resolve();
1169
+ let trackedCustomer = null;
1170
+ let partitionRead = null;
1171
+ const backend = createWixOrderBackend({
1172
+ wixIap: deps.wixIap,
1173
+ binding: deps.binding,
1174
+ session: deps.session,
1175
+ clock: deps.clock,
1176
+ cashier: deps.cashier,
1177
+ adapters: deps.adapters,
1178
+ refs,
1179
+ bridge,
1180
+ itemFor: (key) => sales.get(key),
1181
+ report: onEvent
1182
+ });
1183
+ const coordinator = createPurchaseCoordinator({
1184
+ store: deps.store ?? appleManagedStore,
1185
+ backend,
1186
+ session: deps.session,
1187
+ clock: deps.clock,
1188
+ jitter: deps.jitter,
1189
+ onState: publish
1190
+ });
1191
+ async function start() {
1192
+ resetIfSessionChanged();
1193
+ await coordinator.start();
1194
+ await trackPayments({ dueOnly: false });
1195
+ return state();
1196
+ }
1197
+ async function buy(item) {
1198
+ resetIfSessionChanged();
1199
+ const key = itemKey(item);
1200
+ const appleProduct = settledAppleProduct(item);
1201
+ current = { item: key, failure: appleProduct ? null : "notAppleRoute", buying: false };
1202
+ if (!appleProduct) return publishAndReturn();
1203
+ sales.set(key, { item, appleProduct });
1204
+ current.buying = true;
1205
+ publish();
1206
+ await coordinator.purchase(key);
1207
+ if (current.item === key) current.buying = false;
1208
+ return publishAndReturn();
1209
+ }
1210
+ async function reconcile2() {
1211
+ resetIfSessionChanged();
1212
+ await coordinator.reconcile();
1213
+ await trackPayments({ dueOnly: false });
1214
+ return state();
1215
+ }
1216
+ async function retry2() {
1217
+ resetIfSessionChanged();
1218
+ await coordinator.retry();
1219
+ await trackPayments({ dueOnly: false });
1220
+ return state();
1221
+ }
1222
+ async function tick() {
1223
+ resetIfSessionChanged();
1224
+ await coordinator.tick();
1225
+ await trackPayments({ dueOnly: true });
1226
+ return state();
1227
+ }
1228
+ function state() {
1229
+ if (disposed || deps.session.current().generation !== generation) return blankState(true);
1230
+ const purchase = coordinator.getState();
1231
+ const progress = [...payments.values()].map(({ item, access, nextAttemptAt }) => ({ item, access, nextAttemptAt }));
1232
+ return {
1233
+ enabled: true,
1234
+ phase: phaseOf(purchase, progress),
1235
+ item: current.item,
1236
+ failure: current.failure,
1237
+ purchase,
1238
+ payments: progress,
1239
+ nextWakeAt: earliest([purchase.nextWakeAt, partitionRead?.nextAttemptAt ?? null, ...progress.map((payment) => payment.nextAttemptAt)])
1240
+ };
1241
+ }
1242
+ function dispose() {
1243
+ disposed = true;
1244
+ coordinator.dispose();
1245
+ }
1246
+ function settledAppleProduct(item) {
1247
+ return deps.pricing.view(item.reference).route === "appleIap" ? deps.pricing.appleProduct(item.reference) : null;
1248
+ }
1249
+ function onEvent(event) {
1250
+ resetIfSessionChanged();
1251
+ const owned = event.failure === "alreadyOwned";
1252
+ const access = owned ? "granted" : event.access;
1253
+ const failure3 = owned ? void 0 : event.failure;
1254
+ if (access) setPayment(event.key, access);
1255
+ if (labelOf(event.key) === current.item && (failure3 || access)) current.failure = failure3 ?? failureOfAccess(access);
1256
+ }
1257
+ function setPayment(key, access) {
1258
+ const due = access === "processing" ? deps.clock.now() + BASE_DELAY_MS : null;
1259
+ payments.set(key, { key, item: labelOf(key), access, attempts: 0, nextAttemptAt: due });
1260
+ }
1261
+ function phaseOf(purchase, progress) {
1262
+ const mine = progress.find((payment) => payment.item === current.item);
1263
+ if (mine?.access === "granted") return "accessReady";
1264
+ if (current.failure) return "refused";
1265
+ if (OVERLAY_PHASES.has(purchase.phase)) return purchase.phase;
1266
+ if (current.buying) return "preparing";
1267
+ if (mine?.access === "processing" || purchase.items.some(isProcessing)) return "processing";
1268
+ return "idle";
1269
+ }
1270
+ function resetIfSessionChanged() {
1271
+ const next = deps.session.current().generation;
1272
+ if (next === generation) return;
1273
+ generation = next;
1274
+ sales.clear();
1275
+ payments.clear();
1276
+ trackedCustomer = null;
1277
+ partitionRead = null;
1278
+ current = { item: null, failure: null, buying: false };
1279
+ }
1280
+ function publish() {
1281
+ if (!disposed && deps.session.current().generation === generation) deps.onState?.(state());
1282
+ }
1283
+ function publishAndReturn() {
1284
+ publish();
1285
+ return state();
1286
+ }
1287
+ function trackPayments(options) {
1288
+ const run = tracking.then(() => trackOnce(options));
1289
+ tracking = run.catch(() => void 0);
1290
+ return run;
1291
+ }
1292
+ async function trackOnce(options) {
1293
+ resetIfSessionChanged();
1294
+ const session = deps.session.current();
1295
+ if (session.kind !== "member" || options.dueOnly && !anyDue()) return;
1296
+ if (!options.dueOnly) partitionRead = null;
1297
+ const tracked = await trackedPartition(session);
1298
+ if (!isCurrent(session)) return;
1299
+ if (tracked === "none") return;
1300
+ if (!tracked) return backOffDue();
1301
+ partitionRead = null;
1302
+ for (const key of pruneExpiredHolds(tracked.partition, deps.clock.now())) payments.delete(key);
1303
+ for (const ref of tracked.partition.refs()) {
1304
+ if (!isCurrent(session)) return;
1305
+ if (ref.stage === "needsSupport") setPayment(ref.key, "needsSupport");
1306
+ if (ref.stage !== "submitted" || !ref.paymentId) continue;
1307
+ if (!options.dueOnly) restartBudget(ref.key);
1308
+ if (isDue(ref.key, options.dueOnly)) await trackOne(session, tracked.partition, ref);
1309
+ }
1310
+ publish();
1311
+ }
1312
+ async function trackedPartition(session) {
1313
+ const binding = await bindingOf(deps.binding);
1314
+ if (!binding || !isCurrent(session)) return binding === null ? "none" : null;
1315
+ const stored = refs.hasRefs(binding);
1316
+ if (stored !== true) return stored === false ? "none" : null;
1317
+ const customerId = await customerIdFor(session);
1318
+ if (!customerId || !isCurrent(session)) return null;
1319
+ const partition = refs.open({ purchasesAppId: binding.purchasesAppId, siteId: binding.siteId, customerId });
1320
+ return partition && { partition };
1321
+ }
1322
+ async function customerIdFor(session) {
1323
+ if (trackedCustomer?.generation === session.generation) return trackedCustomer.customerId;
1324
+ const customer = await deps.wixIap.getCustomerId();
1325
+ if (customer.status !== "found" || !isCurrent(session)) return null;
1326
+ trackedCustomer = { generation: session.generation, customerId: customer.customerId };
1327
+ return customer.customerId;
1328
+ }
1329
+ function backOffDue() {
1330
+ const attempts = (partitionRead?.attempts ?? 0) + 1;
1331
+ partitionRead = { attempts, nextAttemptAt: attempts >= MAX_AUTOMATIC_ATTEMPTS ? null : deps.clock.now() + backoffDelay(attempts, deps.jitter) };
1332
+ for (const payment of payments.values()) {
1333
+ if (payment.access !== "processing" || !isDue(payment.key, true)) continue;
1334
+ const attempts2 = payment.attempts + 1;
1335
+ const nextAttemptAt = attempts2 >= MAX_AUTOMATIC_ATTEMPTS ? null : deps.clock.now() + backoffDelay(attempts2, deps.jitter);
1336
+ Object.assign(payment, { attempts: attempts2, nextAttemptAt });
1337
+ }
1338
+ publish();
1339
+ }
1340
+ function anyDue() {
1341
+ const readDue = partitionRead?.nextAttemptAt != null && partitionRead.nextAttemptAt <= deps.clock.now();
1342
+ return readDue || [...payments.values()].some((payment) => payment.access === "processing" && isDue(payment.key, true));
1343
+ }
1344
+ async function trackOne(session, partition, ref) {
1345
+ const read = await deps.wixIap.getPayment({ paymentId: ref.paymentId ?? "" });
1346
+ if (!isCurrent(session)) return;
1347
+ if (read.status !== "found") return read.kind === "application" ? markNeedsSupport(partition, ref) : backOff(partition, ref, false);
1348
+ await settlePayment(session, partition, ref, read.payment);
1349
+ }
1350
+ async function settlePayment(session, partition, ref, payment) {
1351
+ if (isFinalRefusal(payment.status)) return markNeedsSupport(partition, ref);
1352
+ if (payment.status !== "approved") return backOff(partition, ref, false);
1353
+ if (!ref.kind) return settleUnassociated(partition, ref);
1354
+ const access = await accessOf3(session, ref);
1355
+ if (!isCurrent(session)) return;
1356
+ if (access === "granted") return grant(partition, ref);
1357
+ backOff(partition, ref, access === "none");
1358
+ }
1359
+ function grant(partition, ref) {
1360
+ partition.remove(ref.key);
1361
+ setPayment(ref.key, "granted");
1362
+ }
1363
+ function settleUnassociated(partition, ref) {
1364
+ partition.remove(ref.key);
1365
+ setPayment(ref.key, "accessUnknown");
1366
+ }
1367
+ async function accessOf3(session, ref) {
1368
+ const adapter = deps.adapters.find((candidate) => candidate.kind === ref.kind);
1369
+ if (!adapter || !ref.verticalRef) return "unavailable";
1370
+ return adapter.readAccess(ref.verticalRef, bindBridge(session, deps.session, bridge));
1371
+ }
1372
+ function markNeedsSupport(partition, ref) {
1373
+ partition.put({ ...ref, stage: "needsSupport", updatedAt: deps.clock.now() });
1374
+ setPayment(ref.key, "needsSupport");
1375
+ if (labelOf(ref.key) === current.item) current.failure = "needsSupport";
1376
+ }
1377
+ function backOff(partition, ref, approvedWithoutAccess) {
1378
+ const payment = payments.get(ref.key) ?? newTracked(ref.key);
1379
+ const attempts = payment.attempts + 1;
1380
+ const exhausted = attempts >= MAX_AUTOMATIC_ATTEMPTS;
1381
+ if (exhausted && approvedWithoutAccess) return markNeedsSupport(partition, ref);
1382
+ const nextAttemptAt = exhausted ? null : deps.clock.now() + backoffDelay(attempts, deps.jitter);
1383
+ payments.set(ref.key, { ...payment, access: "processing", attempts, nextAttemptAt });
1384
+ }
1385
+ function restartBudget(key) {
1386
+ const payment = payments.get(key);
1387
+ if (payment?.access === "processing") Object.assign(payment, { attempts: 0, nextAttemptAt: deps.clock.now() });
1388
+ }
1389
+ function isDue(key, dueOnly) {
1390
+ const nextAttemptAt = payments.get(key)?.nextAttemptAt;
1391
+ return !dueOnly || nextAttemptAt === void 0 || nextAttemptAt !== null && nextAttemptAt <= deps.clock.now();
1392
+ }
1393
+ function newTracked(key) {
1394
+ return { key, item: labelOf(key), access: "processing", attempts: 0, nextAttemptAt: null };
1395
+ }
1396
+ function isCurrent(session) {
1397
+ return !disposed && deps.session.current().generation === session.generation;
1398
+ }
1399
+ return { start, buy, reconcile: reconcile2, retry: retry2, tick, state, dispose };
1400
+ }
1401
+ function disabledCheckout() {
1402
+ const state = () => blankState(false);
1403
+ const resolved = () => Promise.resolve(state());
1404
+ return { start: resolved, buy: resolved, reconcile: resolved, retry: resolved, tick: resolved, state, dispose: () => {
1405
+ } };
1406
+ }
1407
+ function blankState(enabled) {
1408
+ return {
1409
+ enabled,
1410
+ phase: enabled ? "idle" : "notEnabled",
1411
+ item: null,
1412
+ failure: null,
1413
+ payments: [],
1414
+ nextWakeAt: null,
1415
+ purchase: { phase: "idle", errorCode: null, items: [], unfinishedCount: null, nextWakeAt: null }
1416
+ };
1417
+ }
1418
+ function isProcessing(item) {
1419
+ return item.access === "processing" || item.access === "confirming" || item.access === "pending" || item.access === "waitingToRetry";
1420
+ }
1421
+ function itemKey(item) {
1422
+ return `${item.reference.kind}:${item.reference.id}`;
1423
+ }
1424
+ function labelOf(key) {
1425
+ return key.startsWith("payment:") ? "payment" : key;
1426
+ }
1427
+ function backoffDelay(attempts, jitter) {
1428
+ const base = Math.min(BASE_DELAY_MS * 2 ** (attempts - 1), MAX_RETRY_DELAY_MS);
1429
+ return base + Math.max(0, jitter?.(base) ?? 0);
1430
+ }
1431
+ function earliest(times) {
1432
+ const due = times.filter((time) => time !== null);
1433
+ return due.length > 0 ? Math.min(...due) : null;
1434
+ }
1435
+ async function bindingOf(source) {
1436
+ try {
1437
+ return await source.current();
1438
+ } catch {
1439
+ return void 0;
1440
+ }
1441
+ }
1442
+ function failureOfAccess(access) {
1443
+ return access === "needsSupport" ? "needsSupport" : null;
1444
+ }
1445
+ var BASE_DELAY_MS = 1e3;
1446
+ var OVERLAY_PHASES = /* @__PURE__ */ new Set(["purchasing", "awaitingApproval", "cancelled", "signInRequired", "unavailable"]);
1447
+
1448
+ // ../../stdlib/flows/iap-checkout/src/apple-iap.ts
1449
+ function createAppleIapCheckout(deps) {
1450
+ return createAppleIapCheckoutWith({ ...deps, enabled: appleIapCheckoutEnabled() });
1451
+ }
1452
+
1453
+ // ../../stdlib/flows/iap-checkout/src/iap-verticals/shared.ts
1454
+ function singleUnitOf(kind, item) {
1455
+ const quantity = item.quantity ?? 1;
1456
+ if (item.reference.kind !== kind || !isNonEmpty3(item.reference.id) || quantity !== 1) return UNSUPPORTED;
1457
+ return { eligible: true };
1458
+ }
1459
+ function attemptRefused(refusal) {
1460
+ if (refusal.status === "sessionChanged" || refusal.status === "unavailable") return { status: refusal.status };
1461
+ if (refusal.status === "notEnabled") return { status: "refused", reason: "notConfigured" };
1462
+ return { status: "refused", reason: "orderRefused" };
1463
+ }
1464
+ function accessRefused(refusal) {
1465
+ if (refusal.status === "sessionChanged") return "sessionChanged";
1466
+ return refusal.status === "http" && refusal.httpStatus === 404 ? "none" : "unavailable";
1467
+ }
1468
+ function isRefusal(outcome) {
1469
+ return outcome.status !== "ok";
1470
+ }
1471
+ function isHttp(outcome, httpStatus) {
1472
+ return outcome.status === "http" && outcome.httpStatus === httpStatus;
1473
+ }
1474
+ function bodyObject(outcome, name) {
1475
+ const body = outcome.body;
1476
+ return isObject5(body) && isObject5(body[name]) ? body[name] : null;
1477
+ }
1478
+ function isObject5(value) {
1479
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1480
+ }
1481
+ function isNonEmpty3(value) {
1482
+ return typeof value === "string" && value.length > 0;
1483
+ }
1484
+ var UNSUPPORTED = { eligible: false, reason: "unsupportedItem" };
1485
+ var ORDER_REFUSED = { status: "refused", reason: "orderRefused" };
1486
+ var ORDER_CLOSED = { status: "refused", reason: "orderClosed" };
1487
+ var GRANTED = { status: "granted" };
1488
+
1489
+ // ../../stdlib/flows/iap-checkout/src/iap-verticals/online-programs.ts
1490
+ var KIND = "onlineProgram";
1491
+ var BASE = "/online-programs/participants/v3/join-applications";
1492
+ var onlineProgramOrders = {
1493
+ kind: KIND,
1494
+ eligibility: (item) => singleUnitOf(KIND, item),
1495
+ openOrder,
1496
+ reopenOrder,
1497
+ readAccess
1498
+ };
1499
+ async function openOrder(item, bridge) {
1500
+ const found = await currentApplication(item.reference.id, bridge);
1501
+ if ("attempt" in found) return found.attempt;
1502
+ const read = found.application ? { application: found.application } : await createdApplication(item.reference.id, bridge);
1503
+ if ("attempt" in read) return read.attempt;
1504
+ return orderOf(read.application, bridge, { mayPrepare: true });
1505
+ }
1506
+ async function reopenOrder(order, bridge) {
1507
+ const read = await applicationById(order.verticalRef.joinApplicationId, bridge);
1508
+ if ("attempt" in read) return read.attempt;
1509
+ const attempt2 = await orderOf(read.application, bridge, { mayPrepare: false });
1510
+ return attempt2.status === "open" && attempt2.cashierOrderId !== order.cashierOrderId ? ORDER_CLOSED : attempt2;
1511
+ }
1512
+ async function readAccess(verticalRef, bridge) {
1513
+ if (!isNonEmpty3(verticalRef.joinApplicationId)) return "unavailable";
1514
+ const answer = await bridge.call("GET", `${BASE}/${encodeURIComponent(verticalRef.joinApplicationId)}`);
1515
+ if (isRefusal(answer)) return accessRefused(answer);
1516
+ const application = bodyObject(answer, "joinApplication");
1517
+ return application ? accessOf(application) : "unavailable";
1518
+ }
1519
+ function accessOf(application) {
1520
+ const paid = application.paymentStatus === "PAYMENT_SUCCESSFUL" || application.paymentStatus === "NO_PAYMENT_REQUIRED";
1521
+ if (application.status === "APPROVED" && paid && isNonEmpty3(application.participantId)) return "granted";
1522
+ if (paid || PAYMENT_UNDER_WAY.has(String(application.paymentStatus))) return "pending";
1523
+ return NO_ACCESS_STATUS.has(String(application.status)) || NO_ACCESS_PAYMENT.has(String(application.paymentStatus)) ? "none" : "unavailable";
1524
+ }
1525
+ async function orderOf(application, bridge, options) {
1526
+ if (accessOf(application) === "granted") return GRANTED;
1527
+ if (application.status === "APPROVAL_PENDING" || application.status === "INVITED") return { status: "refused", reason: "approvalRequired" };
1528
+ if (application.status !== "APPROVED" && application.status !== "SUSPENDED") return ORDER_CLOSED;
1529
+ const payment = String(application.paymentStatus);
1530
+ if (payment === "NO_PAYMENT_REQUIRED" || payment === "PAYMENT_SUCCESSFUL") return { status: "refused", reason: "paymentInProgress" };
1531
+ if (payment === "PENDING_OWNER_APPROVAL") return { status: "refused", reason: "approvalRequired" };
1532
+ if (payment === "PAYMENT_IN_PROGRESS") return inProgressOrder(application);
1533
+ if (!PREPARABLE.has(payment) || !options.mayPrepare) return ORDER_CLOSED;
1534
+ return preparedOrder(application, bridge);
1535
+ }
1536
+ function inProgressOrder(application) {
1537
+ const info = application.paymentInfo;
1538
+ const orderId = info?.paymentOrderId;
1539
+ if (!isNonEmpty3(orderId) || !isNonEmpty3(application.id)) return ORDER_REFUSED;
1540
+ return { status: "open", cashierOrderId: orderId, verticalRef: { joinApplicationId: application.id, programId: String(application.programId ?? "") } };
1541
+ }
1542
+ async function preparedOrder(application, bridge) {
1543
+ const id = String(application.id ?? "");
1544
+ const answer = await bridge.call("POST", `${BASE}/${encodeURIComponent(id)}/prepare-payment`, { paymentType: "SINGLE_PAYMENT" });
1545
+ if (isHttp(answer, 428)) return reopenAfterRace(id, bridge);
1546
+ if (isRefusal(answer)) return attemptRefused(answer);
1547
+ const prepared = bodyObject(answer, "joinApplication");
1548
+ return prepared ? orderOf(prepared, bridge, { mayPrepare: false }) : ORDER_REFUSED;
1549
+ }
1550
+ async function reopenAfterRace(id, bridge) {
1551
+ const read = await applicationById(id, bridge);
1552
+ return "attempt" in read ? read.attempt : orderOf(read.application, bridge, { mayPrepare: false });
1553
+ }
1554
+ async function currentApplication(programId, bridge) {
1555
+ const answer = await bridge.call("GET", `${BASE}/current/${encodeURIComponent(programId)}`);
1556
+ if (isHttp(answer, 404)) return { application: null };
1557
+ if (isRefusal(answer)) return { attempt: attemptRefused(answer) };
1558
+ const application = bodyObject(answer, "joinApplication");
1559
+ return application ? { application } : { attempt: ORDER_REFUSED };
1560
+ }
1561
+ async function createdApplication(programId, bridge) {
1562
+ const answer = await bridge.call("POST", BASE, { joinApplication: { programId } });
1563
+ if (isHttp(answer, 409)) {
1564
+ const existing = await currentApplication(programId, bridge);
1565
+ if ("attempt" in existing) return existing;
1566
+ return existing.application ? { application: existing.application } : { attempt: ORDER_REFUSED };
1567
+ }
1568
+ if (isRefusal(answer)) return { attempt: attemptRefused(answer) };
1569
+ return applicationIn(answer);
1570
+ }
1571
+ async function applicationById(id, bridge) {
1572
+ if (!isNonEmpty3(id)) return { attempt: ORDER_CLOSED };
1573
+ const answer = await bridge.call("GET", `${BASE}/${encodeURIComponent(id)}`);
1574
+ if (isHttp(answer, 404)) return { attempt: ORDER_CLOSED };
1575
+ if (isRefusal(answer)) return { attempt: attemptRefused(answer) };
1576
+ return applicationIn(answer);
1577
+ }
1578
+ function applicationIn(answer) {
1579
+ const application = bodyObject(answer, "joinApplication");
1580
+ return application ? { application } : { attempt: ORDER_REFUSED };
1581
+ }
1582
+ var PREPARABLE = /* @__PURE__ */ new Set(["PAYMENT_PENDING", "PAYMENT_FAILED", "PAYMENT_CANCELED"]);
1583
+ var PAYMENT_UNDER_WAY = /* @__PURE__ */ new Set(["PAYMENT_PENDING", "PAYMENT_IN_PROGRESS", "PENDING_OWNER_APPROVAL"]);
1584
+ var NO_ACCESS_STATUS = /* @__PURE__ */ new Set(["CANCELLED", "DECLINED", "SUSPENDED", "INVITED", "APPROVAL_PENDING"]);
1585
+ var NO_ACCESS_PAYMENT = /* @__PURE__ */ new Set(["PAYMENT_FAILED", "PAYMENT_CANCELED"]);
1586
+
1587
+ // ../../stdlib/flows/iap-checkout/src/iap-verticals/pricing-plans.ts
1588
+ var KIND2 = "pricingPlan";
1589
+ var CHECKOUT = "/pricing-plans/v2/checkout/orders";
1590
+ var MEMBER_ORDERS = "/pricing-plans/v2/member/orders";
1591
+ var pricingPlanOrders = {
1592
+ kind: KIND2,
1593
+ eligibility: (item) => singleUnitOf(KIND2, item),
1594
+ openOrder: openOrder2,
1595
+ reopenOrder: reopenOrder2,
1596
+ readAccess: readAccess2
1597
+ };
1598
+ async function openOrder2(item, bridge) {
1599
+ const planId = item.reference.id;
1600
+ const preview = await bridge.call("POST", `${CHECKOUT}/preview-online`, { planId });
1601
+ if (isRefusal(preview)) return attemptRefused(preview);
1602
+ if (!isOneTimeUnlimited(bodyObject(preview, "order"))) return { status: "refused", reason: "unsupportedItem" };
1603
+ const created = await bridge.call("POST", `${CHECKOUT}/online`, { planId });
1604
+ if (isRefusal(created)) return attemptRefused(created);
1605
+ return orderOf2(bodyObject(created, "order"), planId);
1606
+ }
1607
+ async function reopenOrder2(order, bridge) {
1608
+ const read = await memberOrder(order.verticalRef.orderId, bridge);
1609
+ if ("attempt" in read) return read.attempt;
1610
+ const attempt2 = orderOf2(read.order, order.verticalRef.planId ?? "");
1611
+ return attempt2.status === "open" && attempt2.cashierOrderId !== order.cashierOrderId ? ORDER_CLOSED : attempt2;
1612
+ }
1613
+ async function readAccess2(verticalRef, bridge) {
1614
+ if (!isNonEmpty3(verticalRef.orderId)) return "unavailable";
1615
+ const answer = await bridge.call("GET", `${MEMBER_ORDERS}/${encodeURIComponent(verticalRef.orderId)}`);
1616
+ if (isRefusal(answer)) return accessRefused(answer);
1617
+ const order = bodyObject(answer, "order");
1618
+ return order ? accessOf2(order) : "unavailable";
1619
+ }
1620
+ function accessOf2(order) {
1621
+ if (order.status === "ACTIVE") return "granted";
1622
+ if (order.status === "PENDING") return order.lastPaymentStatus === "PAID" ? "granted" : "pending";
1623
+ if (order.status === "DRAFT") return "pending";
1624
+ return NO_ACCESS.has(String(order.status)) ? "none" : "unavailable";
1625
+ }
1626
+ var NO_ACCESS = /* @__PURE__ */ new Set(["CANCELED", "ENDED", "PAUSED"]);
1627
+ function orderOf2(order, planId) {
1628
+ if (!order || !isNonEmpty3(order.id)) return ORDER_REFUSED;
1629
+ if (accessOf2(order) === "granted") return GRANTED;
1630
+ if (order.status === "PENDING") return { status: "refused", reason: "paymentInProgress" };
1631
+ if (order.status !== "DRAFT") return ORDER_CLOSED;
1632
+ if (!isNonEmpty3(order.wixPayOrderId)) return ORDER_REFUSED;
1633
+ return { status: "open", cashierOrderId: order.wixPayOrderId, verticalRef: { orderId: order.id, planId } };
1634
+ }
1635
+ async function memberOrder(orderId, bridge) {
1636
+ if (!isNonEmpty3(orderId)) return { attempt: ORDER_CLOSED };
1637
+ const answer = await bridge.call("GET", `${MEMBER_ORDERS}/${encodeURIComponent(orderId)}`);
1638
+ if (isRefusal(answer)) return { attempt: answer.status === "http" && answer.httpStatus === 404 ? ORDER_CLOSED : attemptRefused(answer) };
1639
+ return { order: bodyObject(answer, "order") };
1640
+ }
1641
+ function isOneTimeUnlimited(order) {
1642
+ const pricing = order?.pricing;
1643
+ return pricing?.singlePaymentUnlimited === true;
1644
+ }
1645
+
1646
+ // ../../stdlib/flows/iap-checkout/src/iap-verticals/stores.ts
1647
+ var KIND3 = "storesProduct";
1648
+ var storesProductOrders = {
1649
+ kind: KIND3,
1650
+ eligibility: (item) => {
1651
+ const single = singleUnitOf(KIND3, item);
1652
+ if (!single.eligible) return single;
1653
+ const catalog = item.catalogReference;
1654
+ const variant = catalog?.options && Object.keys(catalog.options).length > 0;
1655
+ return catalog && !variant && isNonEmpty3(catalog.appId) && catalog.catalogItemId === item.reference.id ? single : UNSUPPORTED;
1656
+ },
1657
+ openOrder: openOrder3,
1658
+ reopenOrder: reopenOrder3,
1659
+ readAccess: readAccess3
1660
+ };
1661
+ function classifyCart(lines) {
1662
+ if (lines.length === 0 || lines.some((line) => line.route === "resolving" || line.route === "unavailable")) return "blocked";
1663
+ const apple = lines.filter((line) => line.route === "appleIap");
1664
+ if (apple.length === 0) return "regular";
1665
+ return lines.length === 1 && apple[0].quantity === 1 ? "appleIap" : "mixedRefused";
1666
+ }
1667
+ async function openOrder3(item, bridge) {
1668
+ const checkout = await bridge.call("POST", "/ecom/v1/checkouts", { lineItems: [{ quantity: 1, catalogReference: item.catalogReference }], channelType: "OTHER_PLATFORM" });
1669
+ if (isRefusal(checkout)) return attemptRefused(checkout);
1670
+ const checkoutId = bodyObject(checkout, "checkout")?.id;
1671
+ if (!isNonEmpty3(checkoutId)) return ORDER_REFUSED;
1672
+ const placed = await bridge.call("POST", `/ecom/v1/checkouts/${encodeURIComponent(checkoutId)}/create-order`, {});
1673
+ if (isRefusal(placed)) return attemptRefused(placed);
1674
+ return placedOrder(placed.body, bridge);
1675
+ }
1676
+ async function reopenOrder3(order, bridge) {
1677
+ const access = await readAccess3(order.verticalRef, bridge);
1678
+ if (access === "granted") return GRANTED;
1679
+ if (access === "pending") return { status: "open", cashierOrderId: order.cashierOrderId, verticalRef: order.verticalRef };
1680
+ return access === "sessionChanged" || access === "unavailable" ? { status: access } : ORDER_CLOSED;
1681
+ }
1682
+ async function readAccess3(verticalRef, bridge) {
1683
+ if (!isNonEmpty3(verticalRef.orderId)) return "unavailable";
1684
+ const answer = await bridge.call("GET", `/ecom/v1/orders/${encodeURIComponent(verticalRef.orderId)}`);
1685
+ if (isRefusal(answer)) return accessRefused(answer);
1686
+ const status = String(bodyObject(answer, "order")?.paymentStatus);
1687
+ if (status === "PAID") return "granted";
1688
+ if (PAYMENT_UNDER_WAY2.has(status)) return "pending";
1689
+ return NO_ACCESS2.has(status) ? "none" : "unavailable";
1690
+ }
1691
+ async function placedOrder(body, bridge) {
1692
+ if (!isObject5(body) || !isNonEmpty3(body.orderId)) return ORDER_REFUSED;
1693
+ const verticalRef = { orderId: body.orderId };
1694
+ if (isNonEmpty3(body.paymentGatewayOrderId)) return { status: "open", cashierOrderId: body.paymentGatewayOrderId, verticalRef };
1695
+ const access = await readAccess3(verticalRef, bridge);
1696
+ if (access === "granted") return GRANTED;
1697
+ return access === "sessionChanged" || access === "unavailable" ? { status: access } : ORDER_REFUSED;
1698
+ }
1699
+ var PAYMENT_UNDER_WAY2 = /* @__PURE__ */ new Set(["NOT_PAID", "PENDING", "PENDING_MERCHANT", "PARTIALLY_PAID"]);
1700
+ var NO_ACCESS2 = /* @__PURE__ */ new Set(["FULLY_REFUNDED", "PARTIALLY_REFUNDED", "CANCELED", "DECLINED", "VOIDED"]);
1701
+ export {
1702
+ classifyCart,
1703
+ createAppleIapCheckout,
1704
+ createWorkerOrderRefStore,
1705
+ onlineProgramOrders,
1706
+ pricingPlanOrders,
1707
+ storesProductOrders
1708
+ };
1709
+ //# sourceMappingURL=iap-checkout.mjs.map