@wix/himalaya-cli 0.1660.0 → 0.1661.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.
@@ -140,8 +140,8 @@ export interface IapVerticalOrderAdapter extends IapAdapterBase {
140
140
  /** Opens, or reuses the vertical's own open, order for the signed-in member. */
141
141
  /** Repeatable adapters call beforeCreate immediately before their first inventory write,
142
142
  * after read-only checks, and abort without writing if it returns false. They call afterCreate
143
- * with the ids of each inventory write as soon as it answers, so a later failure can be undone. */
144
- openOrder(item: IapOrderItem, bridge: SessionBoundBridge, beforeCreate?: (guard: OpeningGuard) => boolean, afterCreate?: (guard: OpeningGuard) => void): Promise<OrderAttempt>;
143
+ * with the ids of each inventory write as soon as it answers; on false they answer `unavailable`. */
144
+ openOrder(item: IapOrderItem, bridge: SessionBoundBridge, beforeCreate?: (guard: OpeningGuard) => boolean, afterCreate?: (guard: OpeningGuard) => boolean): Promise<OrderAttempt>;
145
145
  /** Settles an earlier attempt's guard before a new sale of the same item. `settled`: the attempt
146
146
  * that wrote it has had time to finish, so what it created may be undone; before then it may be
147
147
  * another screen's sale still in flight. `claim` must answer true immediately before anything
@@ -168,7 +168,7 @@ export interface IapItemPaymentAdapter extends IapAdapterBase {
168
168
  /** The catalog item to order, for an item `eligibility` accepted. A vertical that must read or
169
169
  * make something first (a plan's pricing variant, the member's booking) does it here, through
170
170
  * the session-bound bridge, before anything is ordered. */
171
- itemPayment(item: IapOrderItem, bridge: SessionBoundBridge, beforeCreate?: (guard: OpeningGuard) => boolean, afterCreate?: (guard: OpeningGuard) => void): ItemPayment | ItemPaymentRefusal | Promise<ItemPayment | ItemPaymentRefusal>;
171
+ itemPayment(item: IapOrderItem, bridge: SessionBoundBridge, beforeCreate?: (guard: OpeningGuard) => boolean, afterCreate?: (guard: OpeningGuard) => boolean): ItemPayment | ItemPaymentRefusal | Promise<ItemPayment | ItemPaymentRefusal>;
172
172
  openOrder?: never;
173
173
  reopenOrder?: never;
174
174
  /** Each sale is its own attempt (a ticket, a booking): the item carries an `attemptId`. */
@@ -213,13 +213,22 @@ export interface OrderRef {
213
213
  appAccountToken?: string;
214
214
  /** For `openingOrder`: when anything its write created has been released by Wix. */
215
215
  releaseAt?: number;
216
+ /** For `openingOrder`: the attempt that owns the guard. Ownership is checked by it, never by
217
+ * `updatedAt`, which two workers can write in the same millisecond. Absent on guards stored before it. */
218
+ guardToken?: string;
216
219
  updatedAt: number;
217
220
  }
221
+ /** `replaced`: the key no longer holds the expected guard, so nothing was written. */
222
+ export type GuardWrite = "written" | "replaced" | "unavailable";
218
223
  export interface OrderRefPartition {
219
224
  refs(): readonly OrderRef[];
220
225
  /** False when the write could not be verified as durable; the caller must not proceed. */
221
226
  put(ref: OrderRef): boolean;
222
227
  remove(key: string): boolean;
228
+ /** Writes `next` only while the key still holds `expected`'s creation guard (the same token). */
229
+ replaceGuard(expected: OrderRef, next: OrderRef): GuardWrite;
230
+ /** Removes the key only while it still holds `expected`'s creation guard. */
231
+ removeGuard(expected: OrderRef): GuardWrite;
223
232
  }
224
233
  export interface OrderRefStore {
225
234
  /** Null when this partition cannot be stored durably: no storage bridge, unreadable or
@@ -13,17 +13,21 @@ export declare const ITEM_START_HOLD_MS = 3600000;
13
13
  /** Drops every hold older than its stage's hold time, whatever its key (an item, or a `payment:`
14
14
  * with no local order), so holds never accumulate and lock the member out. A held proof still
15
15
  * unfinished renews its hold on every retry, so only one Apple no longer delivers expires. A
16
- * creation guard goes at its own `releaseAt`. Returns the keys it removed. */
16
+ * creation guard goes at its own `releaseAt`, and only while it is still the guard that expired,
17
+ * never a fresh one another worker stored under the key since. Returns the keys it removed. */
17
18
  export declare function pruneExpiredHolds(partition: OrderRefPartition, now: number): string[];
18
19
  /** How long (5 minutes) a creation guard may belong to a sale still running in another screen's
19
20
  * worker, which shares these references but not that sale's coordinator: longer than any one
20
21
  * openOrder takes. Until then nothing it may have created is undone. A literal, as above. */
21
22
  export declare const OPENING_SETTLE_MS = 300000;
22
23
  /** Asks the guard's adapter to settle it. Before undoing anything the adapter claims the guard
23
- * (restamps it), so the sale that wrote it, should it still be running, is no longer charged. It
24
- * is dropped only while it is still the stored guard: a slow answer never removes what another
25
- * worker wrote under the key since. A guard changed meanwhile is judged again as it now is. */
24
+ * (gives it a new token), so the sale that wrote it, should it still be running, is no longer
25
+ * charged. It is dropped only while it is still the stored guard: a slow answer never removes what
26
+ * another worker wrote under the key since. A guard changed meanwhile is judged again as it now is. */
26
27
  export declare function settleOpening(partition: OrderRefPartition, adapter: IapOrderAdapter, guard: OrderRef, item: IapOrderItem | undefined, bridge: SessionBoundBridge, now: number): Promise<OpeningResolution | "storageUnavailable">;
28
+ export declare function isStoredGuard(partition: OrderRefPartition, guard: OrderRef): boolean;
29
+ /** Unique per creation attempt, across the workers sharing these references. */
30
+ export declare function newGuardToken(): string;
27
31
  /** References one member keeps at once. When full, the oldest reference from before Apple's sheet
28
32
  * is evicted; a partition full of handed-over payments refuses new sales instead. */
29
33
  export declare const MAX_ORDER_REFS = 16;
@@ -1818,7 +1818,8 @@ var NEEDS_SUPPORT_HOLD_MS = 6048e5;
1818
1818
  var ITEM_START_HOLD_MS = 36e5;
1819
1819
  function pruneExpiredHolds(partition, now) {
1820
1820
  const expired = partition.refs().filter((ref) => now - ref.updatedAt >= (HOLD_MS[ref.stage] ?? Infinity) || released(ref, now));
1821
- return expired.filter((ref) => partition.remove(ref.key)).map((ref) => ref.key);
1821
+ const removed = (ref) => ref.stage === "openingOrder" ? partition.removeGuard(ref) === "written" : partition.remove(ref.key);
1822
+ return expired.filter(removed).map((ref) => ref.key);
1822
1823
  }
1823
1824
  var OPENING_SETTLE_MS = 3e5;
1824
1825
  async function settleOpening(partition, adapter, guard, item, bridge, now) {
@@ -1826,23 +1827,36 @@ async function settleOpening(partition, adapter, guard, item, bridge, now) {
1826
1827
  if (!resolve) return "held";
1827
1828
  let current = guard;
1828
1829
  const claim = () => {
1829
- const next = { ...current, updatedAt: now };
1830
- if (!isStoredGuard(partition, current) || !partition.put(next)) return false;
1830
+ const next = { ...current, guardToken: newGuardToken(), updatedAt: now };
1831
+ if (partition.replaceGuard(current, next) !== "written") return false;
1831
1832
  current = next;
1832
1833
  return true;
1833
1834
  };
1834
1835
  const resolution = await resolve(guard, item, bridge, { settled: now - guard.updatedAt >= OPENING_SETTLE_MS, claim });
1835
- if (isStoredGuard(partition, current)) {
1836
- if (resolution !== "released") return resolution;
1837
- return partition.remove(guard.key) ? "released" : "storageUnavailable";
1836
+ if (resolution === "released") {
1837
+ const removed = partition.removeGuard(current);
1838
+ if (removed !== "replaced") return removed === "written" ? "released" : "storageUnavailable";
1839
+ } else if (isStoredGuard(partition, current)) {
1840
+ return resolution;
1838
1841
  }
1839
1842
  const stored = partition.refs().find((ref) => ref.key === guard.key);
1840
1843
  if (!stored) return "released";
1841
1844
  return stored.stage === "openingOrder" ? resolve(stored, item, bridge, { settled: false, claim: () => false }) : "held";
1842
1845
  }
1843
1846
  function isStoredGuard(partition, guard) {
1844
- const stored = partition.refs().find((ref) => ref.key === guard.key);
1845
- return stored?.stage === "openingOrder" && stored.updatedAt === guard.updatedAt;
1847
+ return holdsGuard(partition.refs(), guard);
1848
+ }
1849
+ function holdsGuard(refs, expected) {
1850
+ const stored = refs.find((ref) => ref.key === expected.key);
1851
+ if (stored?.stage !== "openingOrder") return false;
1852
+ return expected.guardToken === void 0 ? stored.guardToken === void 0 && stored.updatedAt === expected.updatedAt : stored.guardToken === expected.guardToken;
1853
+ }
1854
+ var guardTokens = 0;
1855
+ function newGuardToken() {
1856
+ const crypto = globalThis.crypto;
1857
+ if (typeof crypto?.randomUUID === "function") return crypto.randomUUID();
1858
+ const random = () => Math.random().toString(36).slice(2, 12);
1859
+ return `${Date.now().toString(36)}-${(guardTokens++).toString(36)}-${random()}${random()}`;
1846
1860
  }
1847
1861
  var MAX_ORDER_REFS = 16;
1848
1862
  function createWorkerOrderRefStore(storage) {
@@ -1854,19 +1868,34 @@ function createWorkerOrderRefStore(storage) {
1854
1868
  return {
1855
1869
  refs: () => readRefs(kv(), location) ?? [],
1856
1870
  put: (ref) => writeWith(location, key, (refs) => upsert(refs, ref)),
1857
- remove: (refKey) => writeWith(location, key, (refs) => refs.filter((stored) => stored.key !== refKey))
1871
+ remove: (refKey) => writeWith(location, key, (refs) => refs.filter((stored) => stored.key !== refKey)),
1872
+ replaceGuard: (expected, next) => guardedWrite(location, key, expected, (refs) => upsert(refs, next)),
1873
+ removeGuard: (expected) => guardedWrite(location, key, expected, (refs) => refs.filter((stored) => stored.key !== expected.key))
1858
1874
  };
1859
1875
  }
1876
+ function guardedWrite(location, key, expected, change) {
1877
+ let replaced = false;
1878
+ const written = writeWith(location, key, (refs) => {
1879
+ replaced = !holdsGuard(refs, expected);
1880
+ return replaced ? null : change(refs);
1881
+ });
1882
+ return written ? "written" : replaced ? "replaced" : "unavailable";
1883
+ }
1860
1884
  function writeWith(location, key, change) {
1861
1885
  const store = kv();
1862
1886
  if (!store) return false;
1863
- const current = readRefs(store, location);
1864
- const next = current && change(current);
1865
- if (!next) return false;
1866
- if (next.length > 0 && !updateIndex(store, key, true)) return false;
1867
- if (!writeVerified(store, location, serialize({ v: VERSION, refs: next }))) return false;
1868
- if (next.length === 0) updateIndex(store, key, false);
1869
- return true;
1887
+ for (let attempt3 = 0; attempt3 < WRITE_ATTEMPTS; attempt3++) {
1888
+ const raw = safely(() => store.getItem(location));
1889
+ const current = parseRefs(raw);
1890
+ const next = current && change(current);
1891
+ if (!next) return false;
1892
+ if (next.length > 0 && !updateIndex(store, key, true)) return false;
1893
+ if (safely(() => store.getItem(location)) !== raw) continue;
1894
+ if (!writeVerified(store, location, serialize({ v: VERSION, refs: next }))) return false;
1895
+ if (next.length === 0) updateIndex(store, key, false);
1896
+ return true;
1897
+ }
1898
+ return false;
1870
1899
  }
1871
1900
  function hasRefs(app) {
1872
1901
  if (!isUUID3(app.purchasesAppId) || !isUUID3(app.siteId)) return null;
@@ -1891,7 +1920,10 @@ function updateIndex(store, key, holdsRefs) {
1891
1920
  return next.length === members.length && next.every((m, i) => m === members[i]) || writeVerified(store, location, serialize({ v: VERSION, members: next }));
1892
1921
  }
1893
1922
  function readRefs(store, location) {
1894
- const parsed = readVersioned(store, location);
1923
+ return store ? parseRefs(safely(() => store.getItem(location))) : null;
1924
+ }
1925
+ function parseRefs(raw) {
1926
+ const parsed = parseVersioned(raw);
1895
1927
  if (parsed === "empty") return [];
1896
1928
  if (!parsed || !Array.isArray(parsed.refs) || !parsed.refs.every(isOrderRef)) return null;
1897
1929
  return parsed.refs;
@@ -1903,8 +1935,9 @@ function readIndex(store, location) {
1903
1935
  return parsed.members;
1904
1936
  }
1905
1937
  function readVersioned(store, location) {
1906
- if (!store) return null;
1907
- const raw = safely(() => store.getItem(location));
1938
+ return store ? parseVersioned(safely(() => store.getItem(location))) : null;
1939
+ }
1940
+ function parseVersioned(raw) {
1908
1941
  if (raw === void 0) return null;
1909
1942
  if (raw === null || raw === "") return "empty";
1910
1943
  const parsed = safely(() => JSON.parse(raw));
@@ -1921,7 +1954,7 @@ function isOrderRef(value) {
1921
1954
  if (!isObject6(value) || typeof value.key !== "string" || !STAGES.has(value.stage)) return false;
1922
1955
  if (typeof value.updatedAt !== "number") return false;
1923
1956
  if (value.releaseAt !== void 0 && typeof value.releaseAt !== "number") return false;
1924
- const optional = ["kind", "cashierOrderId", "wixTransactionId", "paymentId", "storeProductId", "appProductId", "appleTransactionId", "appAccountToken"];
1957
+ const optional = ["kind", "cashierOrderId", "wixTransactionId", "paymentId", "storeProductId", "appProductId", "appleTransactionId", "appAccountToken", "guardToken"];
1925
1958
  if (!optional.every((field) => value[field] === void 0 || typeof value[field] === "string")) return false;
1926
1959
  return value.verticalRef === void 0 || isStringMap(value.verticalRef);
1927
1960
  }
@@ -1977,6 +2010,7 @@ function isUUID3(value) {
1977
2010
  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);
1978
2011
  }
1979
2012
  var VERSION = 1;
2013
+ var WRITE_ATTEMPTS = 3;
1980
2014
  var PREFIX = "himi.iap.wix-checkout.v1";
1981
2015
  var STAGES = /* @__PURE__ */ new Set(["startingItem", "openingOrder", "ordered", "charged", "started", "submitted", "fulfilled", "held", "needsSupport"]);
1982
2016
  var HOLD_MS = { held: NEEDS_SUPPORT_HOLD_MS, needsSupport: NEEDS_SUPPORT_HOLD_MS, startingItem: ITEM_START_HOLD_MS };
@@ -2075,15 +2109,16 @@ function createWixOrderBackend(deps) {
2075
2109
  const { state, beforeCreate, afterCreate } = creationGuards(sale, void 0);
2076
2110
  const prepared = await adapter.itemPayment(sale.item, sale.bridge, beforeCreate, afterCreate);
2077
2111
  if (state.prevented) return contextResult(catalogRef, state.prevented);
2112
+ if (state.orphan) return contextResult(catalogRef, await releaseOrphan(sale, state.orphan));
2078
2113
  if (!sale.bridge.isCurrent()) return contextResult(catalogRef, STALE2);
2079
2114
  if ("status" in prepared) return contextResult(catalogRef, preparationStop(sale, prepared, state.guarded));
2080
- if (state.guarded !== void 0 && !stillGuarded(sale, state.guarded)) return contextResult(catalogRef, retry("unavailable"));
2115
+ if (state.guarded && !isStoredGuard(sale.partition, state.guarded)) return contextResult(catalogRef, retry("unavailable"));
2081
2116
  const stillBlocked = state.guarded === void 0 ? saleBlocked(sale) : null;
2082
2117
  if (stillBlocked) return contextResult(catalogRef, stillBlocked);
2083
- return startItemFor(sale, prepared, country);
2118
+ return startItemFor(sale, prepared, country, state.guarded);
2084
2119
  }
2085
2120
  function preparationStop(sale, refusal, guarded) {
2086
- if (refusal.noOrderCreated && guarded !== void 0 && stillGuarded(sale, guarded) && !sale.partition.remove(sale.catalogRef)) {
2121
+ if (refusal.noOrderCreated && guarded && sale.partition.removeGuard(guarded) === "unavailable") {
2087
2122
  return stopWith("rejected", "storageUnavailable");
2088
2123
  }
2089
2124
  if (refusal.status === "refused") return stopWith("rejected", refusal.reason);
@@ -2159,19 +2194,21 @@ function createWixOrderBackend(deps) {
2159
2194
  state.prevented = blocked;
2160
2195
  return false;
2161
2196
  }
2162
- const opening = persist(sale, { ...guard, key: sale.catalogRef, kind: sale.adapter.kind, stage: "openingOrder", updatedAt: now() });
2197
+ const opening = persist(sale, { ...guard, key: sale.catalogRef, kind: sale.adapter.kind, stage: "openingOrder", guardToken: newGuardToken(), updatedAt: now() });
2163
2198
  if (isStop(opening)) {
2164
2199
  state.prevented = opening;
2165
2200
  return false;
2166
2201
  }
2167
- state.guarded = opening.updatedAt;
2202
+ state.guarded = opening;
2168
2203
  return true;
2169
2204
  };
2170
2205
  const afterCreate = (guard) => {
2171
- const opening = refAt(sale.partition, sale.catalogRef);
2172
- if (opening?.stage !== "openingOrder" || opening.updatedAt !== state.guarded) return;
2173
- const recorded = persist(sale, { ...opening, ...guard, verticalRef: { ...opening.verticalRef, ...guard.verticalRef }, updatedAt: now() });
2174
- if (!isStop(recorded)) state.guarded = recorded.updatedAt;
2206
+ if (!state.guarded || !sale.bridge.isCurrent()) return true;
2207
+ const recorded = { ...state.guarded, ...guard, verticalRef: { ...state.guarded.verticalRef, ...guard.verticalRef }, updatedAt: now() };
2208
+ const written = sale.partition.replaceGuard(state.guarded, recorded);
2209
+ if (written === "written") state.guarded = recorded;
2210
+ if (written === "replaced") state.orphan = recorded;
2211
+ return written !== "replaced";
2175
2212
  };
2176
2213
  return { state, beforeCreate, afterCreate };
2177
2214
  }
@@ -2180,28 +2217,24 @@ function createWixOrderBackend(deps) {
2180
2217
  const { state, beforeCreate, afterCreate } = creationGuards(sale, existing);
2181
2218
  const attempt3 = existing?.cashierOrderId && existing.verticalRef ? await reopenOrOpen(sale, { cashierOrderId: existing.cashierOrderId, verticalRef: existing.verticalRef }) : await sale.adapter.openOrder(sale.item, sale.bridge, beforeCreate, afterCreate);
2182
2219
  if (state.prevented) return state.prevented;
2183
- if (state.guarded !== void 0 && attempt3.status === "open" && !stillGuarded(sale, state.guarded)) return retry("unavailable");
2220
+ if (state.orphan) return releaseOrphan(sale, state.orphan);
2184
2221
  const ref = recordOrder(sale, existing, attempt3, state.guarded);
2185
2222
  return isStop(ref) ? ref : { ref, placed: isPlaced(attempt3) };
2186
2223
  }
2187
- function stillGuarded(sale, guarded) {
2188
- const stored = refAt(sale.partition, sale.catalogRef);
2189
- return stored?.stage === "openingOrder" && stored.updatedAt === guarded;
2190
- }
2191
2224
  async function reopenOrOpen(sale, order) {
2192
2225
  const reopened = await sale.adapter.reopenOrder(order, sale.bridge);
2193
2226
  const closed = reopened.status === "refused" && reopened.reason === "orderClosed";
2194
2227
  return closed && !sale.adapter.repeatable ? sale.adapter.openOrder(sale.item, sale.bridge) : reopened;
2195
2228
  }
2196
2229
  function recordOrder(sale, existing, attempt3, guarded) {
2197
- if (attempt3.noOrderCreated && guarded !== void 0 && stillGuarded(sale, guarded) && !sale.partition.remove(sale.catalogRef)) {
2230
+ if (attempt3.noOrderCreated && guarded && sale.partition.removeGuard(guarded) === "unavailable") {
2198
2231
  return stopWith("rejected", "storageUnavailable");
2199
2232
  }
2200
2233
  if (attempt3.status === "granted") return alreadyOwned(sale);
2201
2234
  if (attempt3.status === "refused") return stopWith("rejected", attempt3.reason);
2202
2235
  if (attempt3.status !== "open") return attempt3.status === "sessionChanged" ? STALE2 : retry("unavailable");
2203
2236
  const kept = existing && existing.cashierOrderId === attempt3.cashierOrderId ? existing : { key: sale.catalogRef, updatedAt: 0 };
2204
- return persist(sale, {
2237
+ const ordered = {
2205
2238
  ...kept,
2206
2239
  key: sale.catalogRef,
2207
2240
  stage: "ordered",
@@ -2209,7 +2242,18 @@ function createWixOrderBackend(deps) {
2209
2242
  verticalRef: attempt3.verticalRef,
2210
2243
  cashierOrderId: attempt3.cashierOrderId,
2211
2244
  updatedAt: now()
2212
- });
2245
+ };
2246
+ return guarded ? persistGuarded(sale, guarded, ordered) : persist(sale, ordered);
2247
+ }
2248
+ async function releaseOrphan(sale, made) {
2249
+ const released2 = await sale.adapter.resolveOpening?.(made, sale.item, sale.bridge, { settled: true, claim: () => true });
2250
+ return released2 === "sessionChanged" || !sale.bridge.isCurrent() ? STALE2 : retry("unavailable");
2251
+ }
2252
+ function persistGuarded(sale, guarded, ref) {
2253
+ if (!sale.bridge.isCurrent()) return STALE2;
2254
+ const written = sale.partition.replaceGuard(guarded, ref);
2255
+ if (written === "replaced") return retry("unavailable");
2256
+ return written === "written" ? ref : stopWith("rejected", "storageUnavailable");
2213
2257
  }
2214
2258
  async function chargeFor(sale, ref, options) {
2215
2259
  const charge = await (options.placed ? chargePlacedOrder : ensureAppleIapCharge)(sale.bridge, deps.cashier, ref.cashierOrderId ?? "");
@@ -2265,10 +2309,10 @@ function createWixOrderBackend(deps) {
2265
2309
  if (isStop(recorded)) return contextResult(sale.catalogRef, recorded);
2266
2310
  return { status: "ok", context: { productId: started.storeProductId, appAccountToken: started.appAccountToken, scopeKey: sale.member.scopeKey } };
2267
2311
  }
2268
- async function startItemFor(sale, itemPayment4, country) {
2312
+ async function startItemFor(sale, itemPayment4, country, owned) {
2269
2313
  const made = refAt(sale.partition, sale.catalogRef);
2270
2314
  const guarded = made?.stage === "openingOrder" ? { verticalRef: made.verticalRef, releaseAt: made.releaseAt } : {};
2271
- const attempt3 = persist(sale, {
2315
+ const next = {
2272
2316
  key: sale.catalogRef,
2273
2317
  stage: "startingItem",
2274
2318
  kind: sale.adapter.kind,
@@ -2276,7 +2320,8 @@ function createWixOrderBackend(deps) {
2276
2320
  ...guarded.verticalRef ? { verticalRef: guarded.verticalRef } : {},
2277
2321
  ...guarded.releaseAt !== void 0 ? { releaseAt: guarded.releaseAt } : {},
2278
2322
  updatedAt: now()
2279
- });
2323
+ };
2324
+ const attempt3 = owned ? persistGuarded(sale, owned, next) : persist(sale, next);
2280
2325
  if (isStop(attempt3)) return contextResult(sale.catalogRef, attempt3);
2281
2326
  const started = await deps.wixIap.startItemPayment({ item: itemPayment4.catalogItem, ...country ? { storeCountryCode: country } : {} });
2282
2327
  if (started.status === "outcomeUnknown") return contextResult(sale.catalogRef, sale.bridge.isCurrent() ? OUTCOME_UNKNOWN : STALE2);
@@ -2325,6 +2370,7 @@ function createWixOrderBackend(deps) {
2325
2370
  key: attempt3.key,
2326
2371
  kind: adapter.kind,
2327
2372
  stage: "openingOrder",
2373
+ guardToken: newGuardToken(),
2328
2374
  verticalRef: attempt3.verticalRef,
2329
2375
  ...attempt3.releaseAt !== void 0 ? { releaseAt: attempt3.releaseAt } : {},
2330
2376
  updatedAt: now() - OPENING_SETTLE_MS
@@ -3694,7 +3740,7 @@ async function bookingPayment(item, bridge, beforeCreate, afterCreate) {
3694
3740
  if (isRefusal(created)) return creationRefused(created);
3695
3741
  const bookingId = bodyObject(created, "booking")?.id;
3696
3742
  if (!isNonEmpty3(bookingId)) return ORDER_REFUSED;
3697
- afterCreate?.({ verticalRef: { bookingId } });
3743
+ if (afterCreate?.({ verticalRef: { bookingId } }) === false) return { status: "unavailable" };
3698
3744
  const serviceId = item.reference.id;
3699
3745
  return {
3700
3746
  catalogItem: { catalogItemId: serviceId, catalogAppId: WIX_BOOKINGS_APP, options: { bookingId } },
@@ -3850,7 +3896,7 @@ async function openBooking(item, bridge, beforeCreate, afterCreate) {
3850
3896
  if (isRefusal(created)) return creationRefused2(created);
3851
3897
  const bookingId = bodyObject(created, "booking")?.id;
3852
3898
  if (!isNonEmpty3(bookingId)) return ORDER_REFUSED;
3853
- afterCreate?.({ verticalRef: { bookingId } });
3899
+ if (afterCreate?.({ verticalRef: { bookingId } }) === false) return { status: "unavailable" };
3854
3900
  return bookingCheckout(item, bookingId, bridge);
3855
3901
  }
3856
3902
  function slotGuard2(slot) {
@@ -3943,7 +3989,7 @@ async function reserveTicket(item, bridge, now, afterCreate) {
3943
3989
  if (isRefusal(held)) return creationRefused2(held);
3944
3990
  const reservation = held.body;
3945
3991
  if (!isObject7(reservation) || !isNonEmpty3(reservation.id) || !future(reservation.expires, now)) return ORDER_CLOSED;
3946
- afterCreate?.({ verticalRef: { reservationId: reservation.id }, releaseAt: Date.parse(reservation.expires) + RELEASE_MARGIN_MS2 });
3992
+ if (afterCreate?.({ verticalRef: { reservationId: reservation.id }, releaseAt: Date.parse(reservation.expires) + RELEASE_MARGIN_MS2 }) === false) return { status: "unavailable" };
3947
3993
  if (!heldAsSelected(reservation, item)) return CHANGED2;
3948
3994
  const placed = await bridge.call("POST", "/events/v1/checkout", { eventId: selected.eventId, reservationId: reservation.id, buyer: selected.buyer, ...selected.guests ? { guests: selected.guests } : {}, ...selected.buyerSubmission ? { buyerSubmission: selected.buyerSubmission } : {}, ...selected.guestSubmissions ? { guestSubmissions: selected.guestSubmissions } : {}, options: { silent: false, payInPerson: false, ignoreFormValidation: false, markAsPaid: false } });
3949
3995
  if (isRefusal(placed)) return attemptRefused(placed);
@@ -3482,7 +3482,8 @@ var NEEDS_SUPPORT_HOLD_MS = 6048e5;
3482
3482
  var ITEM_START_HOLD_MS = 36e5;
3483
3483
  function pruneExpiredHolds(partition, now) {
3484
3484
  const expired = partition.refs().filter((ref) => now - ref.updatedAt >= (HOLD_MS[ref.stage] ?? Infinity) || released(ref, now));
3485
- return expired.filter((ref) => partition.remove(ref.key)).map((ref) => ref.key);
3485
+ const removed = (ref) => ref.stage === "openingOrder" ? partition.removeGuard(ref) === "written" : partition.remove(ref.key);
3486
+ return expired.filter(removed).map((ref) => ref.key);
3486
3487
  }
3487
3488
  var OPENING_SETTLE_MS = 3e5;
3488
3489
  async function settleOpening(partition, adapter, guard, item, bridge, now) {
@@ -3490,23 +3491,36 @@ async function settleOpening(partition, adapter, guard, item, bridge, now) {
3490
3491
  if (!resolve) return "held";
3491
3492
  let current = guard;
3492
3493
  const claim = () => {
3493
- const next = { ...current, updatedAt: now };
3494
- if (!isStoredGuard(partition, current) || !partition.put(next)) return false;
3494
+ const next = { ...current, guardToken: newGuardToken(), updatedAt: now };
3495
+ if (partition.replaceGuard(current, next) !== "written") return false;
3495
3496
  current = next;
3496
3497
  return true;
3497
3498
  };
3498
3499
  const resolution = await resolve(guard, item, bridge, { settled: now - guard.updatedAt >= OPENING_SETTLE_MS, claim });
3499
- if (isStoredGuard(partition, current)) {
3500
- if (resolution !== "released") return resolution;
3501
- return partition.remove(guard.key) ? "released" : "storageUnavailable";
3500
+ if (resolution === "released") {
3501
+ const removed = partition.removeGuard(current);
3502
+ if (removed !== "replaced") return removed === "written" ? "released" : "storageUnavailable";
3503
+ } else if (isStoredGuard(partition, current)) {
3504
+ return resolution;
3502
3505
  }
3503
3506
  const stored = partition.refs().find((ref) => ref.key === guard.key);
3504
3507
  if (!stored) return "released";
3505
3508
  return stored.stage === "openingOrder" ? resolve(stored, item, bridge, { settled: false, claim: () => false }) : "held";
3506
3509
  }
3507
3510
  function isStoredGuard(partition, guard) {
3508
- const stored = partition.refs().find((ref) => ref.key === guard.key);
3509
- return stored?.stage === "openingOrder" && stored.updatedAt === guard.updatedAt;
3511
+ return holdsGuard(partition.refs(), guard);
3512
+ }
3513
+ function holdsGuard(refs, expected) {
3514
+ const stored = refs.find((ref) => ref.key === expected.key);
3515
+ if (stored?.stage !== "openingOrder") return false;
3516
+ return expected.guardToken === void 0 ? stored.guardToken === void 0 && stored.updatedAt === expected.updatedAt : stored.guardToken === expected.guardToken;
3517
+ }
3518
+ var guardTokens = 0;
3519
+ function newGuardToken() {
3520
+ const crypto = globalThis.crypto;
3521
+ if (typeof crypto?.randomUUID === "function") return crypto.randomUUID();
3522
+ const random = () => Math.random().toString(36).slice(2, 12);
3523
+ return `${Date.now().toString(36)}-${(guardTokens++).toString(36)}-${random()}${random()}`;
3510
3524
  }
3511
3525
  var MAX_ORDER_REFS = 16;
3512
3526
  function createWorkerOrderRefStore(storage) {
@@ -3518,19 +3532,34 @@ function createWorkerOrderRefStore(storage) {
3518
3532
  return {
3519
3533
  refs: () => readRefs(kv(), location) ?? [],
3520
3534
  put: (ref) => writeWith(location, key, (refs) => upsert(refs, ref)),
3521
- remove: (refKey) => writeWith(location, key, (refs) => refs.filter((stored) => stored.key !== refKey))
3535
+ remove: (refKey) => writeWith(location, key, (refs) => refs.filter((stored) => stored.key !== refKey)),
3536
+ replaceGuard: (expected, next) => guardedWrite(location, key, expected, (refs) => upsert(refs, next)),
3537
+ removeGuard: (expected) => guardedWrite(location, key, expected, (refs) => refs.filter((stored) => stored.key !== expected.key))
3522
3538
  };
3523
3539
  }
3540
+ function guardedWrite(location, key, expected, change) {
3541
+ let replaced = false;
3542
+ const written = writeWith(location, key, (refs) => {
3543
+ replaced = !holdsGuard(refs, expected);
3544
+ return replaced ? null : change(refs);
3545
+ });
3546
+ return written ? "written" : replaced ? "replaced" : "unavailable";
3547
+ }
3524
3548
  function writeWith(location, key, change) {
3525
3549
  const store = kv();
3526
3550
  if (!store) return false;
3527
- const current = readRefs(store, location);
3528
- const next = current && change(current);
3529
- if (!next) return false;
3530
- if (next.length > 0 && !updateIndex(store, key, true)) return false;
3531
- if (!writeVerified(store, location, serialize({ v: VERSION, refs: next }))) return false;
3532
- if (next.length === 0) updateIndex(store, key, false);
3533
- return true;
3551
+ for (let attempt4 = 0; attempt4 < WRITE_ATTEMPTS; attempt4++) {
3552
+ const raw = safely(() => store.getItem(location));
3553
+ const current = parseRefs(raw);
3554
+ const next = current && change(current);
3555
+ if (!next) return false;
3556
+ if (next.length > 0 && !updateIndex(store, key, true)) return false;
3557
+ if (safely(() => store.getItem(location)) !== raw) continue;
3558
+ if (!writeVerified(store, location, serialize({ v: VERSION, refs: next }))) return false;
3559
+ if (next.length === 0) updateIndex(store, key, false);
3560
+ return true;
3561
+ }
3562
+ return false;
3534
3563
  }
3535
3564
  function hasRefs(app) {
3536
3565
  if (!isUUID3(app.purchasesAppId) || !isUUID3(app.siteId)) return null;
@@ -3555,7 +3584,10 @@ function updateIndex(store, key, holdsRefs) {
3555
3584
  return next.length === members.length && next.every((m, i) => m === members[i]) || writeVerified(store, location, serialize({ v: VERSION, members: next }));
3556
3585
  }
3557
3586
  function readRefs(store, location) {
3558
- const parsed = readVersioned(store, location);
3587
+ return store ? parseRefs(safely(() => store.getItem(location))) : null;
3588
+ }
3589
+ function parseRefs(raw) {
3590
+ const parsed = parseVersioned(raw);
3559
3591
  if (parsed === "empty") return [];
3560
3592
  if (!parsed || !Array.isArray(parsed.refs) || !parsed.refs.every(isOrderRef)) return null;
3561
3593
  return parsed.refs;
@@ -3567,8 +3599,9 @@ function readIndex(store, location) {
3567
3599
  return parsed.members;
3568
3600
  }
3569
3601
  function readVersioned(store, location) {
3570
- if (!store) return null;
3571
- const raw = safely(() => store.getItem(location));
3602
+ return store ? parseVersioned(safely(() => store.getItem(location))) : null;
3603
+ }
3604
+ function parseVersioned(raw) {
3572
3605
  if (raw === void 0) return null;
3573
3606
  if (raw === null || raw === "") return "empty";
3574
3607
  const parsed = safely(() => JSON.parse(raw));
@@ -3585,7 +3618,7 @@ function isOrderRef(value) {
3585
3618
  if (!isObject6(value) || typeof value.key !== "string" || !STAGES.has(value.stage)) return false;
3586
3619
  if (typeof value.updatedAt !== "number") return false;
3587
3620
  if (value.releaseAt !== void 0 && typeof value.releaseAt !== "number") return false;
3588
- const optional = ["kind", "cashierOrderId", "wixTransactionId", "paymentId", "storeProductId", "appProductId", "appleTransactionId", "appAccountToken"];
3621
+ const optional = ["kind", "cashierOrderId", "wixTransactionId", "paymentId", "storeProductId", "appProductId", "appleTransactionId", "appAccountToken", "guardToken"];
3589
3622
  if (!optional.every((field) => value[field] === void 0 || typeof value[field] === "string")) return false;
3590
3623
  return value.verticalRef === void 0 || isStringMap(value.verticalRef);
3591
3624
  }
@@ -3641,6 +3674,7 @@ function isUUID3(value) {
3641
3674
  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);
3642
3675
  }
3643
3676
  var VERSION = 1;
3677
+ var WRITE_ATTEMPTS = 3;
3644
3678
  var PREFIX = "himi.iap.wix-checkout.v1";
3645
3679
  var STAGES = /* @__PURE__ */ new Set(["startingItem", "openingOrder", "ordered", "charged", "started", "submitted", "fulfilled", "held", "needsSupport"]);
3646
3680
  var HOLD_MS = { held: NEEDS_SUPPORT_HOLD_MS, needsSupport: NEEDS_SUPPORT_HOLD_MS, startingItem: ITEM_START_HOLD_MS };
@@ -3739,15 +3773,16 @@ function createWixOrderBackend(deps) {
3739
3773
  const { state, beforeCreate, afterCreate } = creationGuards(sale, void 0);
3740
3774
  const prepared = await adapter.itemPayment(sale.item, sale.bridge, beforeCreate, afterCreate);
3741
3775
  if (state.prevented) return contextResult(catalogRef, state.prevented);
3776
+ if (state.orphan) return contextResult(catalogRef, await releaseOrphan(sale, state.orphan));
3742
3777
  if (!sale.bridge.isCurrent()) return contextResult(catalogRef, STALE2);
3743
3778
  if ("status" in prepared) return contextResult(catalogRef, preparationStop(sale, prepared, state.guarded));
3744
- if (state.guarded !== void 0 && !stillGuarded(sale, state.guarded)) return contextResult(catalogRef, retry("unavailable"));
3779
+ if (state.guarded && !isStoredGuard(sale.partition, state.guarded)) return contextResult(catalogRef, retry("unavailable"));
3745
3780
  const stillBlocked = state.guarded === void 0 ? saleBlocked(sale) : null;
3746
3781
  if (stillBlocked) return contextResult(catalogRef, stillBlocked);
3747
- return startItemFor(sale, prepared, country);
3782
+ return startItemFor(sale, prepared, country, state.guarded);
3748
3783
  }
3749
3784
  function preparationStop(sale, refusal, guarded) {
3750
- if (refusal.noOrderCreated && guarded !== void 0 && stillGuarded(sale, guarded) && !sale.partition.remove(sale.catalogRef)) {
3785
+ if (refusal.noOrderCreated && guarded && sale.partition.removeGuard(guarded) === "unavailable") {
3751
3786
  return stopWith("rejected", "storageUnavailable");
3752
3787
  }
3753
3788
  if (refusal.status === "refused") return stopWith("rejected", refusal.reason);
@@ -3823,19 +3858,21 @@ function createWixOrderBackend(deps) {
3823
3858
  state.prevented = blocked;
3824
3859
  return false;
3825
3860
  }
3826
- const opening = persist(sale, { ...guard, key: sale.catalogRef, kind: sale.adapter.kind, stage: "openingOrder", updatedAt: now() });
3861
+ const opening = persist(sale, { ...guard, key: sale.catalogRef, kind: sale.adapter.kind, stage: "openingOrder", guardToken: newGuardToken(), updatedAt: now() });
3827
3862
  if (isStop(opening)) {
3828
3863
  state.prevented = opening;
3829
3864
  return false;
3830
3865
  }
3831
- state.guarded = opening.updatedAt;
3866
+ state.guarded = opening;
3832
3867
  return true;
3833
3868
  };
3834
3869
  const afterCreate = (guard) => {
3835
- const opening = refAt(sale.partition, sale.catalogRef);
3836
- if (opening?.stage !== "openingOrder" || opening.updatedAt !== state.guarded) return;
3837
- const recorded = persist(sale, { ...opening, ...guard, verticalRef: { ...opening.verticalRef, ...guard.verticalRef }, updatedAt: now() });
3838
- if (!isStop(recorded)) state.guarded = recorded.updatedAt;
3870
+ if (!state.guarded || !sale.bridge.isCurrent()) return true;
3871
+ const recorded = { ...state.guarded, ...guard, verticalRef: { ...state.guarded.verticalRef, ...guard.verticalRef }, updatedAt: now() };
3872
+ const written = sale.partition.replaceGuard(state.guarded, recorded);
3873
+ if (written === "written") state.guarded = recorded;
3874
+ if (written === "replaced") state.orphan = recorded;
3875
+ return written !== "replaced";
3839
3876
  };
3840
3877
  return { state, beforeCreate, afterCreate };
3841
3878
  }
@@ -3844,28 +3881,24 @@ function createWixOrderBackend(deps) {
3844
3881
  const { state, beforeCreate, afterCreate } = creationGuards(sale, existing);
3845
3882
  const attempt4 = existing?.cashierOrderId && existing.verticalRef ? await reopenOrOpen(sale, { cashierOrderId: existing.cashierOrderId, verticalRef: existing.verticalRef }) : await sale.adapter.openOrder(sale.item, sale.bridge, beforeCreate, afterCreate);
3846
3883
  if (state.prevented) return state.prevented;
3847
- if (state.guarded !== void 0 && attempt4.status === "open" && !stillGuarded(sale, state.guarded)) return retry("unavailable");
3884
+ if (state.orphan) return releaseOrphan(sale, state.orphan);
3848
3885
  const ref = recordOrder(sale, existing, attempt4, state.guarded);
3849
3886
  return isStop(ref) ? ref : { ref, placed: isPlaced(attempt4) };
3850
3887
  }
3851
- function stillGuarded(sale, guarded) {
3852
- const stored = refAt(sale.partition, sale.catalogRef);
3853
- return stored?.stage === "openingOrder" && stored.updatedAt === guarded;
3854
- }
3855
3888
  async function reopenOrOpen(sale, order) {
3856
3889
  const reopened = await sale.adapter.reopenOrder(order, sale.bridge);
3857
3890
  const closed = reopened.status === "refused" && reopened.reason === "orderClosed";
3858
3891
  return closed && !sale.adapter.repeatable ? sale.adapter.openOrder(sale.item, sale.bridge) : reopened;
3859
3892
  }
3860
3893
  function recordOrder(sale, existing, attempt4, guarded) {
3861
- if (attempt4.noOrderCreated && guarded !== void 0 && stillGuarded(sale, guarded) && !sale.partition.remove(sale.catalogRef)) {
3894
+ if (attempt4.noOrderCreated && guarded && sale.partition.removeGuard(guarded) === "unavailable") {
3862
3895
  return stopWith("rejected", "storageUnavailable");
3863
3896
  }
3864
3897
  if (attempt4.status === "granted") return alreadyOwned(sale);
3865
3898
  if (attempt4.status === "refused") return stopWith("rejected", attempt4.reason);
3866
3899
  if (attempt4.status !== "open") return attempt4.status === "sessionChanged" ? STALE2 : retry("unavailable");
3867
3900
  const kept = existing && existing.cashierOrderId === attempt4.cashierOrderId ? existing : { key: sale.catalogRef, updatedAt: 0 };
3868
- return persist(sale, {
3901
+ const ordered = {
3869
3902
  ...kept,
3870
3903
  key: sale.catalogRef,
3871
3904
  stage: "ordered",
@@ -3873,7 +3906,18 @@ function createWixOrderBackend(deps) {
3873
3906
  verticalRef: attempt4.verticalRef,
3874
3907
  cashierOrderId: attempt4.cashierOrderId,
3875
3908
  updatedAt: now()
3876
- });
3909
+ };
3910
+ return guarded ? persistGuarded(sale, guarded, ordered) : persist(sale, ordered);
3911
+ }
3912
+ async function releaseOrphan(sale, made) {
3913
+ const released2 = await sale.adapter.resolveOpening?.(made, sale.item, sale.bridge, { settled: true, claim: () => true });
3914
+ return released2 === "sessionChanged" || !sale.bridge.isCurrent() ? STALE2 : retry("unavailable");
3915
+ }
3916
+ function persistGuarded(sale, guarded, ref) {
3917
+ if (!sale.bridge.isCurrent()) return STALE2;
3918
+ const written = sale.partition.replaceGuard(guarded, ref);
3919
+ if (written === "replaced") return retry("unavailable");
3920
+ return written === "written" ? ref : stopWith("rejected", "storageUnavailable");
3877
3921
  }
3878
3922
  async function chargeFor(sale, ref, options) {
3879
3923
  const charge = await (options.placed ? chargePlacedOrder : ensureAppleIapCharge)(sale.bridge, deps.cashier, ref.cashierOrderId ?? "");
@@ -3929,10 +3973,10 @@ function createWixOrderBackend(deps) {
3929
3973
  if (isStop(recorded)) return contextResult(sale.catalogRef, recorded);
3930
3974
  return { status: "ok", context: { productId: started.storeProductId, appAccountToken: started.appAccountToken, scopeKey: sale.member.scopeKey } };
3931
3975
  }
3932
- async function startItemFor(sale, itemPayment2, country) {
3976
+ async function startItemFor(sale, itemPayment2, country, owned) {
3933
3977
  const made = refAt(sale.partition, sale.catalogRef);
3934
3978
  const guarded = made?.stage === "openingOrder" ? { verticalRef: made.verticalRef, releaseAt: made.releaseAt } : {};
3935
- const attempt4 = persist(sale, {
3979
+ const next = {
3936
3980
  key: sale.catalogRef,
3937
3981
  stage: "startingItem",
3938
3982
  kind: sale.adapter.kind,
@@ -3940,7 +3984,8 @@ function createWixOrderBackend(deps) {
3940
3984
  ...guarded.verticalRef ? { verticalRef: guarded.verticalRef } : {},
3941
3985
  ...guarded.releaseAt !== void 0 ? { releaseAt: guarded.releaseAt } : {},
3942
3986
  updatedAt: now()
3943
- });
3987
+ };
3988
+ const attempt4 = owned ? persistGuarded(sale, owned, next) : persist(sale, next);
3944
3989
  if (isStop(attempt4)) return contextResult(sale.catalogRef, attempt4);
3945
3990
  const started = await deps.wixIap.startItemPayment({ item: itemPayment2.catalogItem, ...country ? { storeCountryCode: country } : {} });
3946
3991
  if (started.status === "outcomeUnknown") return contextResult(sale.catalogRef, sale.bridge.isCurrent() ? OUTCOME_UNKNOWN : STALE2);
@@ -3989,6 +4034,7 @@ function createWixOrderBackend(deps) {
3989
4034
  key: attempt4.key,
3990
4035
  kind: adapter.kind,
3991
4036
  stage: "openingOrder",
4037
+ guardToken: newGuardToken(),
3992
4038
  verticalRef: attempt4.verticalRef,
3993
4039
  ...attempt4.releaseAt !== void 0 ? { releaseAt: attempt4.releaseAt } : {},
3994
4040
  updatedAt: now() - OPENING_SETTLE_MS
@@ -5196,7 +5242,7 @@ async function bookingPayment(item, bridge, beforeCreate, afterCreate) {
5196
5242
  if (isRefusal(created)) return creationRefused(created);
5197
5243
  const bookingId = bodyObject(created, "booking")?.id;
5198
5244
  if (!isNonEmpty3(bookingId)) return ORDER_REFUSED;
5199
- afterCreate?.({ verticalRef: { bookingId } });
5245
+ if (afterCreate?.({ verticalRef: { bookingId } }) === false) return { status: "unavailable" };
5200
5246
  const serviceId = item.reference.id;
5201
5247
  return {
5202
5248
  catalogItem: { catalogItemId: serviceId, catalogAppId: WIX_BOOKINGS_APP, options: { bookingId } },
@@ -5352,7 +5398,7 @@ async function openBooking(item, bridge, beforeCreate, afterCreate) {
5352
5398
  if (isRefusal(created)) return creationRefused2(created);
5353
5399
  const bookingId = bodyObject(created, "booking")?.id;
5354
5400
  if (!isNonEmpty3(bookingId)) return ORDER_REFUSED;
5355
- afterCreate?.({ verticalRef: { bookingId } });
5401
+ if (afterCreate?.({ verticalRef: { bookingId } }) === false) return { status: "unavailable" };
5356
5402
  return bookingCheckout(item, bookingId, bridge);
5357
5403
  }
5358
5404
  function slotGuard2(slot) {
@@ -5445,7 +5491,7 @@ async function reserveTicket(item, bridge, now, afterCreate) {
5445
5491
  if (isRefusal(held)) return creationRefused2(held);
5446
5492
  const reservation = held.body;
5447
5493
  if (!isObject7(reservation) || !isNonEmpty3(reservation.id) || !future(reservation.expires, now)) return ORDER_CLOSED;
5448
- afterCreate?.({ verticalRef: { reservationId: reservation.id }, releaseAt: Date.parse(reservation.expires) + RELEASE_MARGIN_MS2 });
5494
+ if (afterCreate?.({ verticalRef: { reservationId: reservation.id }, releaseAt: Date.parse(reservation.expires) + RELEASE_MARGIN_MS2 }) === false) return { status: "unavailable" };
5449
5495
  if (!heldAsSelected(reservation, item)) return CHANGED2;
5450
5496
  const placed = await bridge.call("POST", "/events/v1/checkout", { eventId: selected.eventId, reservationId: reservation.id, buyer: selected.buyer, ...selected.guests ? { guests: selected.guests } : {}, ...selected.buyerSubmission ? { buyerSubmission: selected.buyerSubmission } : {}, ...selected.guestSubmissions ? { guestSubmissions: selected.guestSubmissions } : {}, options: { silent: false, payInPerson: false, ignoreFormValidation: false, markAsPaid: false } });
5451
5497
  if (isRefusal(placed)) return attemptRefused(placed);
package/dist/cli.mjs CHANGED
@@ -440,8 +440,8 @@ var init_client = __esm({
440
440
  return this.request("control", "POST", "/v1/admin/dist/plan", { body, headers: this.ctrlHeaders() });
441
441
  }
442
442
  /** One job's record, refreshed from Job Service while it is still in flight. */
443
- /** `wixAuthorization` lets a status read finish a customer TestFlight upload: the control plane
444
- * uploads only after it re-verifies, from this Wix credential, that the caller owns the site. */
443
+ /** `wixAuthorization` lets a status read start a customer TestFlight upload: the control plane
444
+ * starts it only after it re-verifies, from this Wix credential, that the caller owns the site. */
445
445
  distStatus(jobId, options = {}) {
446
446
  if (options.wixAuthorization) this.assertWixAuthorizationTarget();
447
447
  return this.request("control", "GET", `/v1/admin/dist/${encodeURIComponent(jobId)}`, {
@@ -214461,8 +214461,18 @@ __export(site_oauth_client_exports, {
214461
214461
  sameNamedForeignTypes: () => sameNamedForeignTypes,
214462
214462
  toRow: () => toRow
214463
214463
  });
214464
- function noSiteCredential(seams = {}) {
214465
- return !process.env.WIX_TEST_TOKEN?.trim() && !siteApiKey() && !heldWixToken() && !(seams.wixCliOnPath ?? wixCliOnPath)();
214464
+ async function storedDeviceAnswer(msid, stored, seams = {}) {
214465
+ if (!stored || process.env.WIX_TEST_TOKEN?.trim() || siteApiKey() || heldWixToken()) return {};
214466
+ if (!(seams.wixCliOnPath ?? wixCliOnPath)()) return { stored };
214467
+ try {
214468
+ await requireSiteCredential(msid, seams);
214469
+ return {};
214470
+ } catch (e2) {
214471
+ if (e2 instanceof WixTokenError && e2.code === "wix_cli_token_failed") {
214472
+ return { stored, warning: `\`wix token --site ${msid}\` failed, so this is the client the device login stored: ${e2.message}` };
214473
+ }
214474
+ throw e2;
214475
+ }
214466
214476
  }
214467
214477
  async function requireSiteCredential(msid, seams = {}) {
214468
214478
  if (process.env.WIX_TEST_TOKEN?.trim() || siteApiKey()) return;
@@ -214529,7 +214539,7 @@ async function runSiteClientList(opts = {}) {
214529
214539
  const msid = resolveSiteId(opts.siteFlag);
214530
214540
  const redirectUri = opts.redirectUri?.trim() || DEFAULT_REDIRECT_URI;
214531
214541
  const checks = !opts.call || opts.credential;
214532
- const stored = checks && noSiteCredential(opts.credential) ? opts.stored?.(msid) : void 0;
214542
+ const { stored, warning } = checks ? await storedDeviceAnswer(msid, opts.stored?.(msid), opts.credential) : {};
214533
214543
  if (stored) {
214534
214544
  const storedRedirect = stored.redirectUri ?? DEFAULT_REDIRECT_URI;
214535
214545
  return {
@@ -214539,6 +214549,7 @@ async function runSiteClientList(opts = {}) {
214539
214549
  clients: [toRow({ id: stored.clientId, name: DEFAULT_CLIENT_NAME, applicationType: MOBILE_APPLICATION_TYPE, allowedRedirectUris: [storedRedirect] }, redirectUri)],
214540
214550
  source: "device-login",
214541
214551
  note: DEVICE_LOGIN_NOTE,
214552
+ ...warning ? { warning } : {},
214542
214553
  dashboardUrl: `${DASHBOARD_BASE}/${msid}/oauth-apps-settings`
214543
214554
  };
214544
214555
  }
@@ -214583,8 +214594,10 @@ async function runSiteClientEnsure(opts = {}) {
214583
214594
  assertAbsoluteHttpUrl(opts.siteUrl.trim(), { exit: 2, usage: SITE_CLIENT_ENSURE_USAGE });
214584
214595
  }
214585
214596
  const checks = !opts.call || opts.credential;
214586
- const stored = checks && opts.new !== true && name === DEFAULT_CLIENT_NAME && noSiteCredential(opts.credential) ? opts.stored?.(msid) : void 0;
214587
- if (stored && (stored.redirectUri ?? DEFAULT_REDIRECT_URI) === redirectUri) {
214597
+ const candidate = checks && opts.new !== true && name === DEFAULT_CLIENT_NAME ? opts.stored?.(msid) : void 0;
214598
+ const eligible = candidate && (candidate.redirectUri ?? DEFAULT_REDIRECT_URI) === redirectUri ? candidate : void 0;
214599
+ const { stored, warning } = eligible ? await storedDeviceAnswer(msid, eligible, opts.credential) : {};
214600
+ if (stored) {
214588
214601
  const target = provisioningPath(opts);
214589
214602
  if (target && opts.yes !== true) {
214590
214603
  return {
@@ -214594,11 +214607,12 @@ async function runSiteClientEnsure(opts = {}) {
214594
214607
  action: "reused",
214595
214608
  clientId: stored.clientId,
214596
214609
  source: "device-login",
214610
+ ...warning ? { warning } : {},
214597
214611
  planned: { action: "reused", clientId: stored.clientId, name, redirectUri, provisioning: target },
214598
214612
  nextSteps: [`client ${stored.clientId} (from the device login) carries ${redirectUri}, but --write-provisioning would rewrite ${target}. Re-run with --yes to bind it.`]
214599
214613
  };
214600
214614
  }
214601
- return finish({ ok: true, ...base, action: "reused", clientId: stored.clientId, redirectUris: [redirectUri], source: "device-login" }, opts, msid);
214615
+ return finish({ ok: true, ...base, action: "reused", clientId: stored.clientId, redirectUris: [redirectUri], source: "device-login", ...warning ? { warning } : {} }, opts, msid);
214602
214616
  }
214603
214617
  if (checks) await requireSiteCredential(msid, opts.credential);
214604
214618
  const call = opts.call ?? ownerTransport(msid);
@@ -217106,8 +217120,9 @@ var USAGE = `himi \u2014 the Himalaya authoring CLI (remote dev loop)
217106
217120
  package on the Mac pool and asks Apple to validate it.
217107
217121
  Push is optional and follows the App Store profile.
217108
217122
  The Mac pool validates the package and does not upload.
217109
- The control plane uploads it to TestFlight on the next
217110
- status read when HIMI_DIST_CUSTOMER_APP_STORE_UPLOAD=1.
217123
+ The control plane starts its TestFlight upload on the
217124
+ next status read (read again to see it end) when
217125
+ HIMI_DIST_CUSTOMER_APP_STORE_UPLOAD=1.
217111
217126
  It does not go through Wix Mobile Release.
217112
217127
  For a Containers app (bound to a Wix site),
217113
217128
  --destination testflight --version <x.y.z> with no
@@ -223029,6 +223044,10 @@ function customerUploadWaiting(record3) {
223029
223044
  const pending2 = record3?.customerAppStore;
223030
223045
  return pending2?.status === "READY_FOR_UPLOAD" || pending2?.status === "UPLOADING";
223031
223046
  }
223047
+ function customerUploadUnsettled(record3, readAfterBuildEnded) {
223048
+ const status = record3?.customerAppStore?.status;
223049
+ return status === "UPLOADING" || status === "READY_FOR_UPLOAD" && !readAfterBuildEnded;
223050
+ }
223032
223051
  async function distCommand(ctx) {
223033
223052
  const { io: io2, pos, flags, print, targetName, client: client2, serveBase } = ctx;
223034
223053
  const sub = pos[1];
@@ -223456,6 +223475,7 @@ ${label3}`);
223456
223475
  for (const j2 of jobs) (flags.json === true ? io2.error : io2.log)(` ${j2.platform} dispatched as ${j2.jobId}`);
223457
223476
  const MAX_POLL_ERRORS = 3;
223458
223477
  const pollErrors = /* @__PURE__ */ new Map();
223478
+ const uploadReadAfterBuildEnded = /* @__PURE__ */ new Set();
223459
223479
  while (pending2.size > 0) {
223460
223480
  if (Date.now() >= deadline) {
223461
223481
  await printDistQrsForJobs(done);
@@ -223497,6 +223517,10 @@ ${label3}`);
223497
223517
  pollErrors.delete(jobId);
223498
223518
  const rec = s2.json ?? {};
223499
223519
  if (!TERMINAL_DIST_STATUSES.has(String(rec.status))) continue;
223520
+ if (customerUploadUnsettled(rec, uploadReadAfterBuildEnded.has(jobId))) {
223521
+ uploadReadAfterBuildEnded.add(jobId);
223522
+ continue;
223523
+ }
223500
223524
  pending2.delete(jobId);
223501
223525
  done.push(rec);
223502
223526
  if (!flags.json) {
@@ -60,7 +60,7 @@ CLI: run the login again or use `fallbackUrl`.
60
60
 
61
61
  ## `himi site client list|ensure` codes
62
62
 
63
- These commands need a site-scoped Wix credential. They take, in order: `WIX_API_KEY`; the owner's Wix **account** token in `WIX_TOKEN`, exchanged for a 900-second token on that site (OAuth2-NG token exchange, `POST https://www.wixapis.com/oauth2/token`); or a logged-in `wix` CLI (`wix token --site <msid>`). With `WIX_TOKEN` set, no `wix` CLI is needed. The exchanged token is kept in memory for that run only, re-exchanged a minute before it expires or on a `401`, and never written, logged or printed. A himi login alone is not a site credential: `--device` holds no Wix token, and a token piped to `--wix-token-stdin` is not kept after the login. With no site credential, a client id kept by `himi login --device --site` answers instead (`source: "device-login"`; `ensure` only for the default name and the stored redirect, and never with `--new`). The credential is checked before anything is sent to the site. A failed check prints `{ ok: false, code, error, fix, dashboardUrl, usage }` on stderr, exit 1. `fix` is one line to act on; `dashboardUrl` is the site's OAuth-apps page, where the owner can copy a client id by hand; `usage` is the usage of the subcommand that ran. None of these codes is retried. A network failure or a `5xx` from the exchange is retried like any other Wix call, and is never given one of these codes.
63
+ These commands need a site-scoped Wix credential. They take, in order: `WIX_API_KEY`; the owner's Wix **account** token in `WIX_TOKEN`, exchanged for a 900-second token on that site (OAuth2-NG token exchange, `POST https://www.wixapis.com/oauth2/token`); or a logged-in `wix` CLI (`wix token --site <msid>`). With `WIX_TOKEN` set, no `wix` CLI is needed. The exchanged token is kept in memory for that run only, re-exchanged a minute before it expires or on a `401`, and never written, logged or printed. A himi login alone is not a site credential: `--device` holds no Wix token, and a token piped to `--wix-token-stdin` is not kept after the login. With no explicit site credential, a client id kept by `himi login --device --site` answers instead (`source: "device-login"`; `ensure` only for the default name and the stored redirect, and never with `--new`). A `wix` CLI on PATH is tried first; when its `wix token --site` fails (`wix_cli_token_failed`: not logged in, unsupported Node), the stored id still answers, with a `warning` naming the failure. A refused `WIX_API_KEY` or `WIX_TOKEN` is never replaced by the stored id. The credential is checked before anything is sent to the site. A failed check prints `{ ok: false, code, error, fix, dashboardUrl, usage }` on stderr, exit 1. `fix` is one line to act on; `dashboardUrl` is the site's OAuth-apps page, where the owner can copy a client id by hand; `usage` is the usage of the subcommand that ran. None of these codes is retried. A network failure or a `5xx` from the exchange is retried like any other Wix call, and is never given one of these codes.
64
64
 
65
65
  | Code | Meaning |
66
66
  | --- | --- |
@@ -14,7 +14,7 @@ install link or QR. These paths are distinct from the CI gates (`test:*`,
14
14
  > `himi dist` request returns an installable QA artifact and install link. A customer
15
15
  > iOS request may instead use `--signing byo --destination testflight --site <id>
16
16
  > --version <x.y.z>`; the build validates the App Store IPA, and an authorized
17
- > `himi dist status <jobId>` read uploads it to the customer's App Store Connect account.
17
+ > `himi dist status <jobId>` read starts its upload to the customer's App Store Connect account.
18
18
  > The customer path is not Himi Player's Wix Mobile Release route and does not use MRE.
19
19
 
20
20
  > **Customer request gate.** Do not dispatch `himi dist` merely because a draft preview is ready.
@@ -56,8 +56,10 @@ himi dist status <jobId> --target wix
56
56
  ```
57
57
 
58
58
  The pool records `READY_FOR_UPLOAD` after validating the IPA. The status read proves site
59
- ownership with the Wix credential, then claims and uploads the IPA once; repeat reads are
60
- safe. Without that authorization, status reports the waiting state and does not upload.
59
+ ownership with the Wix credential, then starts the upload in the background (claimed once) and
60
+ answers without waiting for it, so it shows `READY_FOR_UPLOAD` or `UPLOADING`: read again until
61
+ `UPLOADED` or `FAILED`. Without `--no-wait`, `himi dist` reads on until then. Repeat reads are
62
+ safe. Without that authorization, status reports the waiting state and starts nothing.
61
63
  The upload also requires customer App Store upload to be enabled on the Himi backend
62
64
  (`HIMI_DIST_CUSTOMER_APP_STORE_UPLOAD=1`); where that switch is off, the job stays at `READY_FOR_UPLOAD` with a validated IPA that is
63
65
  never uploaded.
@@ -1313,7 +1315,8 @@ himi dist --app <app> --platform android --aab --wait --target bo
1313
1315
  their hashes. The upload starts on its own once the pool reports the validated IPA: the pool's
1314
1316
  callback starts it in the background, and so does every list read of the app's builds (the owner
1315
1317
  card's poll) while it can be claimed, which also picks up one a stopped serve pod left. A status
1316
- read still uploads too; any read the caller may make of the app moves it on, since the owner was
1318
+ read starts it the same way and answers without waiting for it (it never waits on Apple, so a
1319
+ read answers in seconds); any read the caller may make of the app moves it on, since the owner was
1317
1320
  proven when the build started (the Containers server's reads carry a project token, not the
1318
1321
  owner's Wix login). A caller reads the job until `customerAppStore.status` is `UPLOADED` or
1319
1322
  `FAILED` to learn how it ended; it no longer has to read for the upload to happen. An attempt that
@@ -3567,14 +3567,14 @@
3567
3567
  "name": "IapVerticalOrderAdapter",
3568
3568
  "kind": "interface",
3569
3569
  "jsdoc": "/** A vertical whose order the device opens; it is charged through cashier and paid with StartPayment. */",
3570
- "decl": "export interface IapVerticalOrderAdapter extends IapAdapterBase {\n readonly repeatable?: boolean;\n /** Opens, or reuses the vertical's own open, order for the signed-in member. */\n /** Repeatable adapters call beforeCreate immediately before their first inventory write,\n * after read-only checks, and abort without writing if it returns false. They call afterCreate\n * with the ids of each inventory write as soon as it answers, so a later failure can be undone. */\n openOrder(item: IapOrderItem, bridge: SessionBoundBridge, beforeCreate?: (guard: OpeningGuard) => boolean, afterCreate?: (guard: OpeningGuard) => void): Promise<OrderAttempt>;\n /** Settles an earlier attempt's guard before a new sale of the same item. `settled`: the attempt\n * that wrote it has had time to finish, so what it created may be undone; before then it may be\n * another screen's sale still in flight. `claim` must answer true immediately before anything\n * is undone: it takes the guard from that sale, which is then never charged. With no item (on\n * entry, not a sale) only `released` matters. Without it, a guard holds its item until its `releaseAt`. */\n resolveOpening?(guard: OpeningGuard, item: IapOrderItem | undefined, bridge: SessionBoundBridge, options: { settled: boolean; claim(): boolean }): Promise<OpeningResolution>;\n /** Re-reads an order opened earlier; `open` only while it can still be paid. */\n reopenOrder(order: { cashierOrderId: string; verticalRef: VerticalRef }, bridge: SessionBoundBridge): Promise<OrderAttempt>;\n itemPayment?: never;\n}",
3570
+ "decl": "export interface IapVerticalOrderAdapter extends IapAdapterBase {\n readonly repeatable?: boolean;\n /** Opens, or reuses the vertical's own open, order for the signed-in member. */\n /** Repeatable adapters call beforeCreate immediately before their first inventory write,\n * after read-only checks, and abort without writing if it returns false. They call afterCreate\n * with the ids of each inventory write as soon as it answers; on false they answer `unavailable`. */\n openOrder(item: IapOrderItem, bridge: SessionBoundBridge, beforeCreate?: (guard: OpeningGuard) => boolean, afterCreate?: (guard: OpeningGuard) => boolean): Promise<OrderAttempt>;\n /** Settles an earlier attempt's guard before a new sale of the same item. `settled`: the attempt\n * that wrote it has had time to finish, so what it created may be undone; before then it may be\n * another screen's sale still in flight. `claim` must answer true immediately before anything\n * is undone: it takes the guard from that sale, which is then never charged. With no item (on\n * entry, not a sale) only `released` matters. Without it, a guard holds its item until its `releaseAt`. */\n resolveOpening?(guard: OpeningGuard, item: IapOrderItem | undefined, bridge: SessionBoundBridge, options: { settled: boolean; claim(): boolean }): Promise<OpeningResolution>;\n /** Re-reads an order opened earlier; `open` only while it can still be paid. */\n reopenOrder(order: { cashierOrderId: string; verticalRef: VerticalRef }, bridge: SessionBoundBridge): Promise<OrderAttempt>;\n itemPayment?: never;\n}",
3571
3571
  "verificationChecked": true
3572
3572
  },
3573
3573
  {
3574
3574
  "name": "IapItemPaymentAdapter",
3575
3575
  "kind": "interface",
3576
3576
  "jsdoc": "",
3577
- "decl": "export interface IapItemPaymentAdapter extends IapAdapterBase {\n /** The catalog item to order, for an item `eligibility` accepted. A vertical that must read or\n * make something first (a plan's pricing variant, the member's booking) does it here, through\n * the session-bound bridge, before anything is ordered. */\n itemPayment(item: IapOrderItem, bridge: SessionBoundBridge, beforeCreate?: (guard: OpeningGuard) => boolean, afterCreate?: (guard: OpeningGuard) => void):\n ItemPayment | ItemPaymentRefusal | Promise<ItemPayment | ItemPaymentRefusal>;\n openOrder?: never;\n reopenOrder?: never;\n /** Each sale is its own attempt (a ticket, a booking): the item carries an `attemptId`. */\n repeatable?: boolean;\n /** A repeatable adapter whose `itemPayment` makes something first (the member's booking) guards it\n * as an order adapter does: `beforeCreate` before that write, `afterCreate` with what it made, and\n * `resolveOpening` settles one a later attempt finds unpaid. */\n resolveOpening?: IapVerticalOrderAdapter[\"resolveOpening\"];\n /** StartItemPayment answers a re-tap with the same pending Payment (Online Programs), so a closed\n * sheet's CancelPayment could cancel the sale being paid: none is sent. */\n reusesPayment?: boolean;\n}",
3577
+ "decl": "export interface IapItemPaymentAdapter extends IapAdapterBase {\n /** The catalog item to order, for an item `eligibility` accepted. A vertical that must read or\n * make something first (a plan's pricing variant, the member's booking) does it here, through\n * the session-bound bridge, before anything is ordered. */\n itemPayment(item: IapOrderItem, bridge: SessionBoundBridge, beforeCreate?: (guard: OpeningGuard) => boolean, afterCreate?: (guard: OpeningGuard) => boolean):\n ItemPayment | ItemPaymentRefusal | Promise<ItemPayment | ItemPaymentRefusal>;\n openOrder?: never;\n reopenOrder?: never;\n /** Each sale is its own attempt (a ticket, a booking): the item carries an `attemptId`. */\n repeatable?: boolean;\n /** A repeatable adapter whose `itemPayment` makes something first (the member's booking) guards it\n * as an order adapter does: `beforeCreate` before that write, `afterCreate` with what it made, and\n * `resolveOpening` settles one a later attempt finds unpaid. */\n resolveOpening?: IapVerticalOrderAdapter[\"resolveOpening\"];\n /** StartItemPayment answers a re-tap with the same pending Payment (Online Programs), so a closed\n * sheet's CancelPayment could cancel the sale being paid: none is sent. */\n reusesPayment?: boolean;\n}",
3578
3578
  "verificationChecked": true
3579
3579
  },
3580
3580
  {
@@ -3602,14 +3602,14 @@
3602
3602
  "name": "OrderRef",
3603
3603
  "kind": "interface",
3604
3604
  "jsdoc": "",
3605
- "decl": "export interface OrderRef {\n /** `<kind>:<id>` of the item, or `payment:<paymentId>` for a payment with no local order. */\n key: string;\n stage: OrderRefStage;\n kind?: string;\n verticalRef?: VerticalRef;\n cashierOrderId?: string;\n wixTransactionId?: string;\n paymentId?: string;\n storeProductId?: string;\n appProductId?: string;\n appleTransactionId?: string;\n /** The StoreKit token StartPayment minted for this payment (D61): recovery finds the order by it. */\n appAccountToken?: string;\n /** For `openingOrder`: when anything its write created has been released by Wix. */\n releaseAt?: number;\n updatedAt: number;\n}",
3605
+ "decl": "export interface OrderRef {\n /** `<kind>:<id>` of the item, or `payment:<paymentId>` for a payment with no local order. */\n key: string;\n stage: OrderRefStage;\n kind?: string;\n verticalRef?: VerticalRef;\n cashierOrderId?: string;\n wixTransactionId?: string;\n paymentId?: string;\n storeProductId?: string;\n appProductId?: string;\n appleTransactionId?: string;\n /** The StoreKit token StartPayment minted for this payment (D61): recovery finds the order by it. */\n appAccountToken?: string;\n /** For `openingOrder`: when anything its write created has been released by Wix. */\n releaseAt?: number;\n /** For `openingOrder`: the attempt that owns the guard. Ownership is checked by it, never by\n * `updatedAt`, which two workers can write in the same millisecond. Absent on guards stored before it. */\n guardToken?: string;\n updatedAt: number;\n}",
3606
3606
  "verificationChecked": true
3607
3607
  },
3608
3608
  {
3609
3609
  "name": "OrderRefPartition",
3610
3610
  "kind": "interface",
3611
3611
  "jsdoc": "",
3612
- "decl": "export interface OrderRefPartition {\n refs(): readonly OrderRef[];\n /** False when the write could not be verified as durable; the caller must not proceed. */\n put(ref: OrderRef): boolean;\n remove(key: string): boolean;\n}",
3612
+ "decl": "export interface OrderRefPartition {\n refs(): readonly OrderRef[];\n /** False when the write could not be verified as durable; the caller must not proceed. */\n put(ref: OrderRef): boolean;\n remove(key: string): boolean;\n /** Writes `next` only while the key still holds `expected`'s creation guard (the same token). */\n replaceGuard(expected: OrderRef, next: OrderRef): GuardWrite;\n /** Removes the key only while it still holds `expected`'s creation guard. */\n removeGuard(expected: OrderRef): GuardWrite;\n}",
3613
3613
  "verificationChecked": true
3614
3614
  },
3615
3615
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wix/himalaya-cli",
3
- "version": "0.1660.0",
3
+ "version": "0.1661.0",
4
4
  "type": "module",
5
5
  "description": "himi — the Himalaya authoring CLI. Build a Tier-5 content package on your own machine, push it to the production serve as a draft, preview it on web + Himi Player, and read worker logs back — the remote dev loop. Wraps @himalaya/serve-cli for transport.",
6
6
  "keywords": [
@@ -72,5 +72,5 @@
72
72
  "artifactId": "himalaya-cli"
73
73
  }
74
74
  },
75
- "falconPackageHash": "e2336ceb2590a9a8d43c93035c296a1a7cca6730797e90393ba7d957"
75
+ "falconPackageHash": "545eb57867cfae3959c869789a561c017b67c8a66d6a9c5f69cdee90"
76
76
  }