@curless/hotel-storefront 0.80.3 → 0.82.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 (106) hide show
  1. package/dist/account/addon-pages.d.ts +22 -0
  2. package/dist/account/addon-pages.d.ts.map +1 -0
  3. package/dist/account/addon-pages.js +282 -0
  4. package/dist/account/addon-pages.js.map +1 -0
  5. package/dist/account/index.d.ts +54 -0
  6. package/dist/account/index.d.ts.map +1 -1
  7. package/dist/account/index.js +719 -61
  8. package/dist/account/index.js.map +1 -1
  9. package/dist/account/ota-member.d.ts +15 -0
  10. package/dist/account/ota-member.d.ts.map +1 -1
  11. package/dist/account/ota-member.js +21 -5
  12. package/dist/account/ota-member.js.map +1 -1
  13. package/dist/account/pages.d.ts +39 -4
  14. package/dist/account/pages.d.ts.map +1 -1
  15. package/dist/account/pages.js +104 -42
  16. package/dist/account/pages.js.map +1 -1
  17. package/dist/account/requests.d.ts +11 -1
  18. package/dist/account/requests.d.ts.map +1 -1
  19. package/dist/account/requests.js +2 -1
  20. package/dist/account/requests.js.map +1 -1
  21. package/dist/account/wallet-pages.d.ts +84 -0
  22. package/dist/account/wallet-pages.d.ts.map +1 -0
  23. package/dist/account/wallet-pages.js +229 -0
  24. package/dist/account/wallet-pages.js.map +1 -0
  25. package/dist/account/wallet.d.ts +163 -0
  26. package/dist/account/wallet.d.ts.map +1 -0
  27. package/dist/account/wallet.js +365 -0
  28. package/dist/account/wallet.js.map +1 -0
  29. package/dist/backend.d.ts +25 -0
  30. package/dist/backend.d.ts.map +1 -1
  31. package/dist/backend.js.map +1 -1
  32. package/dist/card-v168.generated.d.ts +6 -0
  33. package/dist/card-v168.generated.d.ts.map +1 -0
  34. package/dist/card-v168.generated.js +10 -0
  35. package/dist/card-v168.generated.js.map +1 -0
  36. package/dist/card.generated.d.ts +1 -1
  37. package/dist/card.generated.js +2 -2
  38. package/dist/card.generated.js.map +1 -1
  39. package/dist/config.d.ts +51 -2
  40. package/dist/config.d.ts.map +1 -1
  41. package/dist/config.js +21 -1
  42. package/dist/config.js.map +1 -1
  43. package/dist/legal.d.ts.map +1 -1
  44. package/dist/legal.js +33 -4
  45. package/dist/legal.js.map +1 -1
  46. package/dist/otaless/addons-answers.d.ts +17 -0
  47. package/dist/otaless/addons-answers.d.ts.map +1 -0
  48. package/dist/otaless/addons-answers.js +170 -0
  49. package/dist/otaless/addons-answers.js.map +1 -0
  50. package/dist/otaless/addons.d.ts +218 -0
  51. package/dist/otaless/addons.d.ts.map +1 -0
  52. package/dist/otaless/addons.js +758 -0
  53. package/dist/otaless/addons.js.map +1 -0
  54. package/dist/otaless/booking.d.ts +64 -0
  55. package/dist/otaless/booking.d.ts.map +1 -1
  56. package/dist/otaless/booking.js +156 -0
  57. package/dist/otaless/booking.js.map +1 -1
  58. package/dist/otaless/client.d.ts +111 -0
  59. package/dist/otaless/client.d.ts.map +1 -1
  60. package/dist/otaless/client.js +44 -4
  61. package/dist/otaless/client.js.map +1 -1
  62. package/dist/otaless/fake.d.ts +114 -0
  63. package/dist/otaless/fake.d.ts.map +1 -1
  64. package/dist/otaless/fake.js +305 -7
  65. package/dist/otaless/fake.js.map +1 -1
  66. package/dist/otaless/make.d.ts +41 -1
  67. package/dist/otaless/make.d.ts.map +1 -1
  68. package/dist/otaless/make.js +165 -2
  69. package/dist/otaless/make.js.map +1 -1
  70. package/dist/otaless/shop-answers.d.ts +81 -0
  71. package/dist/otaless/shop-answers.d.ts.map +1 -0
  72. package/dist/otaless/shop-answers.js +378 -0
  73. package/dist/otaless/shop-answers.js.map +1 -0
  74. package/dist/otaless/shop-client.d.ts +133 -0
  75. package/dist/otaless/shop-client.d.ts.map +1 -0
  76. package/dist/otaless/shop-client.js +201 -0
  77. package/dist/otaless/shop-client.js.map +1 -0
  78. package/dist/otaless/shop-fake.d.ts +130 -0
  79. package/dist/otaless/shop-fake.d.ts.map +1 -0
  80. package/dist/otaless/shop-fake.js +335 -0
  81. package/dist/otaless/shop-fake.js.map +1 -0
  82. package/dist/otaless/shop-service.d.ts +111 -0
  83. package/dist/otaless/shop-service.d.ts.map +1 -0
  84. package/dist/otaless/shop-service.js +195 -0
  85. package/dist/otaless/shop-service.js.map +1 -0
  86. package/dist/otaless/shop.d.ts +169 -0
  87. package/dist/otaless/shop.d.ts.map +1 -0
  88. package/dist/otaless/shop.js +793 -0
  89. package/dist/otaless/shop.js.map +1 -0
  90. package/dist/otaless/wallet.d.ts +160 -0
  91. package/dist/otaless/wallet.d.ts.map +1 -0
  92. package/dist/otaless/wallet.js +650 -0
  93. package/dist/otaless/wallet.js.map +1 -0
  94. package/dist/server.d.ts +14 -3
  95. package/dist/server.d.ts.map +1 -1
  96. package/dist/server.js +89 -16
  97. package/dist/server.js.map +1 -1
  98. package/dist/surface.d.ts +7 -0
  99. package/dist/surface.d.ts.map +1 -1
  100. package/dist/surface.js +15 -1
  101. package/dist/surface.js.map +1 -1
  102. package/dist/tools.d.ts +223 -99
  103. package/dist/tools.d.ts.map +1 -1
  104. package/dist/tools.js +484 -75
  105. package/dist/tools.js.map +1 -1
  106. package/package.json +1 -1
@@ -0,0 +1,793 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { checkoutEntryOf, pathSegments } from './booking.js';
3
+ import { NOT_SIGNED_IN, OtalessBusy, OtalessError, imageOf } from './client.js';
4
+ import { ADDON_CODES, ShopSignInRequired, isUnknown, } from './shop-client.js';
5
+ // --- small parsers ------------------------------------------------------------------------
6
+ /**
7
+ * Cents from a backend number or numeric string: whole cents only, finite, not negative. ⚠️ A third
8
+ * decimal is not rounded away - 75.655 is not a price we can compare, it is not taken (an amount
9
+ * half a cent over would otherwise pass as equal).
10
+ */
11
+ export const centsOf = (v) => {
12
+ const n = typeof v === 'number'
13
+ ? v
14
+ : typeof v === 'string' && /^\d+(\.\d+)?$/.test(v.trim())
15
+ ? Number(v)
16
+ : Number.NaN;
17
+ if (!Number.isFinite(n) || n < 0 || n > 1e9)
18
+ return undefined;
19
+ const c = Math.round(n * 100);
20
+ return Math.abs(n * 100 - c) < 1e-6 ? c : undefined;
21
+ };
22
+ const CURRENCY = /^[A-Z]{3}$/;
23
+ const currencyOf = (v) => {
24
+ const c = typeof v === 'string' ? v.trim().toUpperCase() : '';
25
+ return CURRENCY.test(c) ? c : undefined;
26
+ };
27
+ const CONTROLS =
28
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: removing them is the point
29
+ /[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u2028-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g;
30
+ /** A backend's text for a guest's eyes: one line, no controls or direction marks, cut short. */
31
+ const textOf = (v, max) => {
32
+ if (typeof v !== 'string')
33
+ return undefined;
34
+ const s = v.replace(CONTROLS, ' ').replace(/\s+/g, ' ').trim().slice(0, max).trim();
35
+ return s || undefined;
36
+ };
37
+ /** Everything in CONTROLS but the line break (a description keeps those). */
38
+ const CONTROLS_NOT_NEWLINE =
39
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: removing them is the point
40
+ /[\u0000-\u0009\u000B-\u001F\u007F-\u009F\u200B-\u200F\u2028-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g;
41
+ /** A description keeps its paragraphs - but nothing else odd. */
42
+ const paragraphsOf = (v, max) => {
43
+ if (typeof v !== 'string')
44
+ return undefined;
45
+ const s = v
46
+ .replace(/\r\n?/g, '\n')
47
+ .replace(CONTROLS_NOT_NEWLINE, ' ')
48
+ .replace(/[ \t]+/g, ' ')
49
+ .replace(/\n{3,}/g, '\n\n')
50
+ .trim()
51
+ .slice(0, max)
52
+ .trim();
53
+ return s || undefined;
54
+ };
55
+ /** An id the backend made - or a product's: plain, short, nothing a path or a log line could be bent by. */
56
+ const ID = /^[A-Za-z0-9_.:/-]{1,200}$/;
57
+ const idOf = (v) => {
58
+ const s = typeof v === 'string' ? v.trim() : '';
59
+ return ID.test(s) ? s : undefined;
60
+ };
61
+ const STATUS = {
62
+ PENDING: 'awaiting-payment',
63
+ PAID: 'paid',
64
+ CONFIRMED: 'confirmed',
65
+ COMPLETED: 'completed',
66
+ CANCELLED: 'cancelled',
67
+ REFUNDED: 'refunded',
68
+ REFUND_REQUESTED: 'refund-requested',
69
+ FAILED: 'failed',
70
+ };
71
+ export const orderStatusOf = (v) => (typeof v === 'string' ? STATUS[v.trim().toUpperCase()] : undefined) ?? 'unknown';
72
+ /** An order the guest has paid for - whoever took the money. */
73
+ const PAID_STATES = new Set(['paid', 'confirmed', 'completed']);
74
+ const lower = (s) => s.replace(/\s+/g, ' ').trim().toLowerCase();
75
+ /** A status word for the log - the backend's own enum, at most 32 plain characters; never a sentence. */
76
+ const statusSaid = (v) => typeof v === 'string' && v.trim()
77
+ ? v
78
+ .trim()
79
+ .replace(/[^A-Za-z0-9_ -]/g, '?')
80
+ .slice(0, 32)
81
+ : '(none)';
82
+ /** Keys `buy.params` may not carry: they are ours, or they are the very thing we promise not to send. */
83
+ const RESERVED_PARAMS = new Set([
84
+ 'providerCode',
85
+ 'productId',
86
+ 'productName',
87
+ 'unitPrice',
88
+ 'quantity',
89
+ 'vccId',
90
+ 'confirmationCode',
91
+ 'specSelections',
92
+ 'sessionToken',
93
+ 'extraParams',
94
+ 'lang',
95
+ 'customerName',
96
+ 'customerPhone',
97
+ 'customerEmail',
98
+ ]);
99
+ const hashOf = (token) => createHash('sha256').update(token).digest('base64url').slice(0, 16);
100
+ const HOLD_MS = 10 * 60_000;
101
+ export const createOtalessShop = (o) => {
102
+ const { client } = o;
103
+ const log = o.log ?? ((line) => console.error(line));
104
+ const now = o.now ?? Date.now;
105
+ const providers = new Set(o.providers.map((p) => p.trim().toLowerCase()).filter(Boolean));
106
+ const imageHosts = o.imageHosts.map((h) => h.toLowerCase());
107
+ const entries = o.checkoutHosts
108
+ .map((h) => checkoutEntryOf(h))
109
+ .filter((e) => e.order === undefined && !e.tokenPage && e.under.length > 0 && !e.under.includes('\u0000'));
110
+ // ⚠️ `buy` present = open, with or without extra parameters (0.82.0).
111
+ const params = o.buy ? { ...(o.buy.params ?? {}) } : undefined;
112
+ if (params) {
113
+ for (const [k, v] of Object.entries(params)) {
114
+ if (RESERVED_PARAMS.has(k))
115
+ throw new Error(`otaless shop: buy.params may not carry "${k}"`);
116
+ if (typeof v !== 'string' && typeof v !== 'boolean')
117
+ throw new Error(`otaless shop: buy.params "${k}" must be a string or a boolean`);
118
+ }
119
+ }
120
+ const providerOf = (p) => {
121
+ const c = typeof p === 'string' ? p.trim().toLowerCase() : '';
122
+ return providers.has(c) ? c : undefined;
123
+ };
124
+ const langOf = (l) => (l === 'zh' ? 'zh' : 'en');
125
+ /** What an error means to the caller. */
126
+ const whyOf = (err) => {
127
+ if (err instanceof OtalessBusy)
128
+ return 'busy';
129
+ if (err instanceof ShopSignInRequired)
130
+ return 'shop-sign-in';
131
+ if (err instanceof OtalessError) {
132
+ if (err.backendCode === NOT_SIGNED_IN)
133
+ return 'not-signed-in';
134
+ if (err.backendCode === ADDON_CODES.channelSessionExpired)
135
+ return 'session-expired';
136
+ }
137
+ return 'failed';
138
+ };
139
+ // --- links ------------------------------------------------------------------------------
140
+ /**
141
+ * A checkout page as it may be handed to a guest - or nothing. https, no user, no port, no
142
+ * fragment; the host exactly an entry's, the path under that entry's by whole segments (put the
143
+ * way a server reads it: no `..`, `%2e` or `//` slips past) with at least one segment more - the
144
+ * checkout's own token, plain characters only.
145
+ *
146
+ * ⚠️ WHAT IS HANDED ON IS REBUILT: `https://<host>/<path>`, and the QUERY IS DROPPED but for one
147
+ * `lang` of `zh` or `en` (0.82.0: the Curless pay page's own language). We cannot
148
+ * prove a Shopify checkout needs one (the document's own example, `/checkouts/cn/<token>`, has
149
+ * none; the newer checkouts carry their key in the path), and a query is where tracking
150
+ * parameters and redirects ride. If a live checkout turns out to need one, that is a decision
151
+ * for the main thread - an allowlist of parameter NAMES, not a pass-through.
152
+ */
153
+ const checkoutLinkOf = (raw) => {
154
+ if (typeof raw !== 'string' || !raw || raw.length > 2_048)
155
+ return undefined;
156
+ let u;
157
+ try {
158
+ u = new URL(raw);
159
+ }
160
+ catch {
161
+ return undefined;
162
+ }
163
+ if (u.protocol !== 'https:' || u.username || u.password || u.port || u.hash)
164
+ return undefined;
165
+ const segs = pathSegments(u.pathname);
166
+ if (!segs)
167
+ return undefined;
168
+ const host = u.hostname.toLowerCase();
169
+ for (const e of entries) {
170
+ if (e.host !== host || !e.under.every((seg, i) => segs[i] === seg))
171
+ continue;
172
+ const token = segs.slice(e.under.length);
173
+ if (token.length < 1 || token.length > 4)
174
+ continue;
175
+ if (!token.every((s) => /^[A-Za-z0-9_.~=-]{1,200}$/.test(s) && s !== '.' && s !== '..'))
176
+ continue;
177
+ // The page's own language, kept (live walkthrough 11-23: agent.curless.ai/pay/shopify/<token>
178
+ // ?lang=zh) - only `zh` or `en`, as the wallet's link; every other parameter is dropped.
179
+ const l = u.searchParams.getAll('lang');
180
+ const keep = l.length === 1 && (l[0] === 'zh' || l[0] === 'en') ? `?lang=${l[0]}` : '';
181
+ return `https://${host}/${segs.join('/')}${keep}`;
182
+ }
183
+ return undefined;
184
+ };
185
+ // --- parsing ----------------------------------------------------------------------------
186
+ const itemOf = (raw) => {
187
+ if (!raw || typeof raw !== 'object')
188
+ return undefined;
189
+ const id = idOf(raw.productId);
190
+ const name = textOf(raw.name, 200);
191
+ const priceCents = centsOf(raw.price);
192
+ const currency = currencyOf(raw.currency);
193
+ if (!id || !name || priceCents === undefined || !currency)
194
+ return undefined;
195
+ const options = [
196
+ ...new Set((Array.isArray(raw.options) ? raw.options : [])
197
+ .map((x) => textOf(x, 100))
198
+ .filter((x) => !!x)),
199
+ ].slice(0, 50);
200
+ const picture = typeof raw.imageUrl === 'string' && raw.imageUrl.trim().startsWith('https://')
201
+ ? imageOf(raw.imageUrl, imageHosts)
202
+ : undefined;
203
+ const description = paragraphsOf(raw.description, 1_000);
204
+ const category = textOf(raw.category, 60);
205
+ const unit = textOf(raw.unit, 30);
206
+ return {
207
+ id,
208
+ name,
209
+ ...(description ? { description } : {}),
210
+ ...(category ? { category } : {}),
211
+ priceCents,
212
+ currency,
213
+ ...(unit ? { unit } : {}),
214
+ options,
215
+ // Only a plain `true` is stock: "false", 0, null and a missing field are not.
216
+ available: raw.available === true,
217
+ ...(picture ? { imageUrl: picture } : {}),
218
+ };
219
+ };
220
+ const unknownSeen = new Set();
221
+ const rowOf = (raw) => {
222
+ if (!raw || typeof raw !== 'object')
223
+ return undefined;
224
+ const id = idOf(raw.orderId);
225
+ const totalCents = centsOf(raw.totalAmount);
226
+ const currency = currencyOf(raw.currency);
227
+ if (!id || totalCents === undefined || !currency)
228
+ return undefined;
229
+ const status = orderStatusOf(raw.status);
230
+ // A status the document does not list (live walkthrough 11-23: a refunded order read one): its
231
+ // word logged once per process, for a person to map - shown to the guest as "not known".
232
+ if (status === 'unknown') {
233
+ const w = statusSaid(raw.status);
234
+ if (!unknownSeen.has(w) && unknownSeen.size < 20) {
235
+ unknownSeen.add(w);
236
+ log(`[otaless-shop] an order status not in the document: ${w}`);
237
+ }
238
+ }
239
+ const link = status === 'awaiting-payment' ? checkoutLinkOf(raw.checkoutUrl) : undefined;
240
+ // ⚠️ `refundUrl` is not read at all (questions #115).
241
+ return {
242
+ id,
243
+ name: textOf(raw.itemName, 200) ?? '',
244
+ totalCents,
245
+ currency,
246
+ status,
247
+ ...(link ? { checkoutUrl: link } : {}),
248
+ ...(typeof raw.checkoutUrl === 'string' ? { checkoutRaw: raw.checkoutUrl } : {}),
249
+ };
250
+ };
251
+ const publicRow = ({ checkoutRaw: _raw, ...r }) => r;
252
+ /** The member's orders as the backend lists them now - and every id in the answer, parsed or not. */
253
+ const readOrders = async (token, provider, lang) => {
254
+ const raw = await client.orders({ providerCode: provider, limit: 100, lang }, token);
255
+ const ids = new Set();
256
+ const rows = [];
257
+ for (const r of raw) {
258
+ const id = typeof r?.orderId === 'string' ? r.orderId : undefined;
259
+ if (id)
260
+ ids.add(id);
261
+ const row = rowOf(r);
262
+ if (row)
263
+ rows.push(row);
264
+ else
265
+ log('[otaless-shop] an order row was not taken (no id, amount or currency)');
266
+ }
267
+ return { rows, ids };
268
+ };
269
+ // --- in-flight and held ----------------------------------------------------------------------
270
+ /** Writes under way: a second one for the same thing is refused, not queued (no idempotency key). */
271
+ const running = new Set();
272
+ /** Writes whose answer is not known, or that were made a moment ago: not asked again for a while. */
273
+ const held = new Map();
274
+ const holding = (key) => {
275
+ const at = held.get(key);
276
+ if (at === undefined)
277
+ return false;
278
+ if (now() - at < HOLD_MS)
279
+ return true;
280
+ held.delete(key);
281
+ return false;
282
+ };
283
+ /** One write at a time per key - false if one is under way or held. */
284
+ const guarded = async (key, inFlight, checking, work, keepHeld) => {
285
+ if (running.has(key))
286
+ return inFlight();
287
+ if (holding(key))
288
+ return checking();
289
+ running.add(key);
290
+ try {
291
+ const r = await work();
292
+ if (keepHeld(r))
293
+ held.set(key, now());
294
+ return r;
295
+ }
296
+ finally {
297
+ running.delete(key);
298
+ }
299
+ };
300
+ // --- reads ------------------------------------------------------------------------------
301
+ const item = async (provider, id, lang) => {
302
+ const p = providerOf(provider);
303
+ if (!p)
304
+ return { ok: false, why: 'not-enabled' };
305
+ const want = idOf(id);
306
+ if (!want)
307
+ return { ok: false, why: 'not-found' };
308
+ try {
309
+ const raw = await client.productDetail({
310
+ providerCode: p,
311
+ productId: want,
312
+ lang: langOf(lang),
313
+ });
314
+ const it = itemOf(raw);
315
+ // ⚠️ THE ITEM ASKED FOR: a detail answered with another product's id is not this item.
316
+ return it && it.id === want ? { ok: true, item: it } : { ok: false, why: 'not-found' };
317
+ }
318
+ catch (err) {
319
+ log(`[otaless-shop] item read failed: ${err instanceof Error ? err.message : 'error'}`);
320
+ return { ok: false, why: whyOf(err) };
321
+ }
322
+ };
323
+ const items = async (provider, q) => {
324
+ const p = providerOf(provider);
325
+ if (!p)
326
+ return { ok: false, why: 'not-enabled' };
327
+ const limit = Math.min(50, Math.max(1, Math.trunc(Number.isFinite(q.limit) ? q.limit : 20)));
328
+ const keyword = textOf(q.keyword, 100);
329
+ const category = textOf(q.category, 60);
330
+ const max = typeof q.maxPrice === 'number' && Number.isFinite(q.maxPrice) && q.maxPrice >= 0
331
+ ? q.maxPrice
332
+ : undefined;
333
+ try {
334
+ const raw = await client.products({
335
+ providerCode: p,
336
+ ...(keyword ? { keyword } : {}),
337
+ ...(category ? { category } : {}),
338
+ ...(max !== undefined ? { maxPrice: max } : {}),
339
+ limit,
340
+ lang: langOf(q.lang),
341
+ });
342
+ const seen = new Set();
343
+ const out = [];
344
+ for (const r of raw) {
345
+ const it = itemOf(r);
346
+ if (!it || seen.has(it.id))
347
+ continue;
348
+ // The backend's filter is not trusted: a dearer item than asked is not listed.
349
+ if (max !== undefined && it.priceCents > Math.round(max * 100))
350
+ continue;
351
+ seen.add(it.id);
352
+ out.push(it);
353
+ if (out.length >= limit)
354
+ break;
355
+ }
356
+ return { ok: true, items: out };
357
+ }
358
+ catch (err) {
359
+ log(`[otaless-shop] items read failed: ${err instanceof Error ? err.message : 'error'}`);
360
+ return { ok: false, why: whyOf(err) };
361
+ }
362
+ };
363
+ const orders = async (token, provider, opts) => {
364
+ const p = providerOf(provider);
365
+ if (!p)
366
+ return { ok: false, why: 'not-enabled' };
367
+ const lang = langOf(opts?.lang);
368
+ try {
369
+ const { rows } = await readOrders(token, p, lang);
370
+ if (opts?.refresh !== false) {
371
+ // The payment state of an awaiting order, once each (`once: true` is the client's, always).
372
+ let asked = 0;
373
+ for (const r of rows) {
374
+ if (r.status !== 'awaiting-payment' || asked >= 5)
375
+ continue;
376
+ asked += 1;
377
+ try {
378
+ const s = await client.paymentStatus({ providerCode: p, unifiedOrderId: r.id, lang }, token);
379
+ const said = typeof s.status === 'string' ? s.status.toLowerCase() : '';
380
+ if (said === 'paid') {
381
+ r.status = 'paid';
382
+ r.checkoutUrl = undefined;
383
+ }
384
+ else if (said === 'cancelled' || said === 'expired') {
385
+ r.status = 'cancelled';
386
+ r.checkoutUrl = undefined;
387
+ }
388
+ }
389
+ catch {
390
+ // The list stands as it was.
391
+ }
392
+ }
393
+ }
394
+ return {
395
+ ok: true,
396
+ orders: rows
397
+ .map(publicRow)
398
+ .map((r) => (r.checkoutUrl === undefined ? stripUndefined(r) : r)),
399
+ };
400
+ }
401
+ catch (err) {
402
+ log(`[otaless-shop] orders read failed: ${err instanceof Error ? err.message : 'error'}`);
403
+ return { ok: false, why: whyOf(err) };
404
+ }
405
+ };
406
+ const stripUndefined = (r) => {
407
+ const { checkoutUrl: _u, ...rest } = r;
408
+ return rest;
409
+ };
410
+ // --- cancel -----------------------------------------------------------------------------
411
+ /** One `/cancel`, sent once. `cancelled` only on the backend saying so. */
412
+ const sendCancel = async (token, provider, orderId, lang) => {
413
+ try {
414
+ const r = await client.cancel({ providerCode: provider, unifiedOrderId: orderId, reason: 'cancelled by the guest', lang }, token);
415
+ // ⚠️ ONLY A PLAIN NO IS "NOT CANCELLED" (live walkthrough 11-23, the refund beside it): an
416
+ // answer that is neither `success: false` nor cancelled - another status, none - is not known.
417
+ const said = typeof r.status === 'string' ? r.status.toLowerCase() : 'cancelled';
418
+ if (r.success === true && said === 'cancelled')
419
+ return 'cancelled';
420
+ if (r.success === false) {
421
+ log(`[otaless-shop] cancel of ${orderId}: the shop said no (status ${statusSaid(r.status)})`);
422
+ return 'refused';
423
+ }
424
+ log(`[otaless-shop] cancel of ${orderId} answered status ${statusSaid(r.status)} - not known, not sent again`);
425
+ return 'unknown';
426
+ }
427
+ catch (err) {
428
+ if (isUnknown(err))
429
+ return 'unknown';
430
+ log(`[otaless-shop] cancel of ${orderId} refused by the shop (code ${err instanceof OtalessError ? String(err.backendCode ?? '-') : '-'})`);
431
+ return 'refused';
432
+ }
433
+ };
434
+ const cancel = async (token, provider, orderId) => {
435
+ const p = providerOf(provider);
436
+ if (!p)
437
+ return { outcome: 'refused', why: 'not-enabled' };
438
+ const id = idOf(orderId);
439
+ if (!id)
440
+ return { outcome: 'refused', why: 'not-found' };
441
+ return guarded(`${p}:${id}`, () => ({ outcome: 'refused', why: 'in-progress' }), () => ({ outcome: 'refused', why: 'checking' }), async () => {
442
+ // ⚠️ THE ORDERS READ NOW, NOT A LIST FROM BEFORE: the id must be one of THIS member's rows
443
+ // (the backend scopes `/orders` to the signed-in member), still awaiting payment.
444
+ let row;
445
+ try {
446
+ row = (await readOrders(token, p, 'en')).rows.find((r) => r.id === id);
447
+ }
448
+ catch (err) {
449
+ return { outcome: 'refused', why: whyOf(err) };
450
+ }
451
+ if (!row)
452
+ return { outcome: 'refused', why: 'not-found' };
453
+ if (row.status !== 'awaiting-payment')
454
+ return { outcome: 'refused', why: 'not-awaiting' };
455
+ // A guest may have paid a moment ago, and `/orders` not know yet: ask the payment's state once.
456
+ try {
457
+ const s = await client.paymentStatus({ providerCode: p, unifiedOrderId: id, lang: 'en' }, token);
458
+ if (typeof s.status === 'string' && s.status.toLowerCase() === 'paid')
459
+ return { outcome: 'refused', why: 'paid' };
460
+ }
461
+ catch {
462
+ // Not known: the backend's own rule (it cancels what is not paid) stands.
463
+ }
464
+ const r = await sendCancel(token, p, id, 'en');
465
+ if (r === 'cancelled')
466
+ return { outcome: 'cancelled' };
467
+ if (r === 'unknown') {
468
+ log(`[otaless-shop] cancel of ${id} not known - not sent again`);
469
+ return { outcome: 'unknown' };
470
+ }
471
+ return { outcome: 'refused', why: 'failed' };
472
+ }, (r) => r.outcome === 'unknown' || r.outcome === 'cancelled');
473
+ };
474
+ // --- refund -----------------------------------------------------------------------------
475
+ const refund = async (token, provider, orderId) => {
476
+ const p = providerOf(provider);
477
+ if (!p)
478
+ return { outcome: 'refused', why: 'not-enabled' };
479
+ const id = idOf(orderId);
480
+ if (!id)
481
+ return { outcome: 'refused', why: 'not-found' };
482
+ return guarded(`${p}:${id}`, () => ({ outcome: 'refused', why: 'in-progress' }), () => ({ outcome: 'refused', why: 'checking' }), async () => {
483
+ let row;
484
+ try {
485
+ row = (await readOrders(token, p, 'en')).rows.find((r) => r.id === id);
486
+ }
487
+ catch (err) {
488
+ return { outcome: 'refused', why: whyOf(err) };
489
+ }
490
+ if (!row)
491
+ return { outcome: 'refused', why: 'not-found' };
492
+ if (!PAID_STATES.has(row.status))
493
+ return { outcome: 'refused', why: 'not-refundable' };
494
+ try {
495
+ const r = await client.refund({
496
+ providerCode: p,
497
+ unifiedOrderId: id,
498
+ // ⚠️ THE FULL TOTAL, WRITTEN OUT: an empty `amount` is "all" by the document, and
499
+ // what the backend takes to be all is not for us to leave to it.
500
+ amount: row.totalCents / 100,
501
+ reason: 'refund requested by the guest',
502
+ lang: 'en',
503
+ }, token);
504
+ // ⚠️ ONLY A PLAIN NO IS "NOT REFUNDED" (live walkthrough 11-23): the dev backend took a
505
+ // refund and answered neither `success: false` nor `refunded` - the order then read a
506
+ // status not in the document - and we said "the shop did not take it; nothing was
507
+ // changed". A refund the shop may have taken is NOT KNOWN: never sent again, a person
508
+ // looks, the orders say.
509
+ const said = typeof r.status === 'string' ? r.status.toLowerCase() : 'refunded';
510
+ if (r.success === false) {
511
+ log(`[otaless-shop] refund of ${id}: the shop said no (status ${statusSaid(r.status)})`);
512
+ return { outcome: 'refused', why: 'failed' };
513
+ }
514
+ // `refund_requested` (live walkthrough 11-23 - the Curless pay page read it of the order):
515
+ // the shop took the request, the money is not back yet. Said as that, never "refunded".
516
+ if (said === 'refund_requested') {
517
+ log(`[otaless-shop] refund of ${id}: requested - the shop pays it back later`);
518
+ const cents = centsOf(r.refundAmount);
519
+ return { outcome: 'requested', ...(cents !== undefined ? { refundCents: cents } : {}) };
520
+ }
521
+ if (r.success !== true || said !== 'refunded') {
522
+ log(`[otaless-shop] NEEDS A PERSON: refund of ${id} answered success ${String(r.success)}, status ${statusSaid(r.status)} - taken as not known, not sent again; the orders will say`);
523
+ return { outcome: 'unknown' };
524
+ }
525
+ const refundCents = centsOf(r.refundAmount);
526
+ if (refundCents !== undefined && refundCents > row.totalCents)
527
+ log(`[otaless-shop] NEEDS A PERSON: refund of ${id} said ${row.currency} ${(refundCents / 100).toFixed(2)}, more than the ${(row.totalCents / 100).toFixed(2)} asked`);
528
+ return { outcome: 'refunded', ...(refundCents !== undefined ? { refundCents } : {}) };
529
+ }
530
+ catch (err) {
531
+ if (isUnknown(err)) {
532
+ log(`[otaless-shop] refund of ${id} not known - not sent again; the orders will say`);
533
+ return { outcome: 'unknown' };
534
+ }
535
+ const code = err instanceof OtalessError ? err.backendCode : undefined;
536
+ log(`[otaless-shop] refund of ${id} refused by the shop (code ${String(code ?? '-')})`);
537
+ if (code === ADDON_CODES.cannotRefund || code === ADDON_CODES.orderNotFound)
538
+ return {
539
+ outcome: 'refused',
540
+ why: code === ADDON_CODES.orderNotFound ? 'not-found' : 'not-refundable',
541
+ };
542
+ return { outcome: 'refused', why: whyOf(err) };
543
+ }
544
+ },
545
+ // A refund made, or not known, is not asked again for ten minutes: `/orders` may lag, and
546
+ // a second one is a second payout.
547
+ (r) => r.outcome === 'unknown' || r.outcome === 'refunded' || r.outcome === 'requested');
548
+ };
549
+ const madeFromAnswer = (a) => {
550
+ const status = orderStatusOf(a.status);
551
+ const id = idOf(a.unifiedOrderId);
552
+ const totalCents = centsOf(a.totalAmount);
553
+ const currency = currencyOf(a.currency);
554
+ return {
555
+ ...(id ? { id } : {}),
556
+ status,
557
+ charged: a.isVccPaid === true || PAID_STATES.has(status),
558
+ failed: a.success === false || status === 'failed',
559
+ ...(totalCents !== undefined ? { totalCents } : {}),
560
+ ...(currency ? { currency } : {}),
561
+ checkoutRaw: a.checkoutUrl,
562
+ };
563
+ };
564
+ const madeFromRow = (r) => ({
565
+ id: r.id,
566
+ status: r.status,
567
+ charged: PAID_STATES.has(r.status),
568
+ failed: r.status === 'failed',
569
+ totalCents: r.totalCents,
570
+ currency: r.currency,
571
+ checkoutRaw: r.checkoutRaw,
572
+ });
573
+ const buy = async (token, provider, req, shown) => {
574
+ // ⚠️ SHUT UNLESS THE DEPLOYMENT OPENED IT (`shopBuy`): not one request is sent.
575
+ if (!params)
576
+ return { outcome: 'off' };
577
+ const p = providerOf(provider);
578
+ if (!p)
579
+ return { outcome: 'off' };
580
+ const qty = req.quantity;
581
+ if (!Number.isInteger(qty) || qty < 1 || qty > 10)
582
+ return { outcome: 'refused', why: 'quantity' };
583
+ const code = typeof req.confirmationCode === 'string' ? req.confirmationCode.trim() : '';
584
+ if (!code || code.length > 64)
585
+ return { outcome: 'refused', why: 'confirmation-code' };
586
+ const shownCurrency = currencyOf(shown?.currency);
587
+ if (!shownCurrency || !Number.isInteger(shown.unitCents) || shown.unitCents <= 0)
588
+ return { outcome: 'refused', why: 'shown' };
589
+ const lang = langOf(req.lang);
590
+ const itemId = idOf(req.itemId);
591
+ if (!itemId)
592
+ return { outcome: 'refused', why: 'not-found' };
593
+ const key = `buy:${hashOf(token)}:${p}:${itemId}`;
594
+ return guarded(key, () => ({ outcome: 'refused', why: 'in-progress' }), () => ({ outcome: 'refused', why: 'checking' }), async () => {
595
+ // 1. The item as it is now: there, in stock, the option one of its own, the price the guest saw.
596
+ const fresh = await item(p, itemId, lang);
597
+ if (!fresh.ok) {
598
+ if (fresh.why === 'not-found')
599
+ return { outcome: 'refused', why: 'not-found' };
600
+ return fresh.why === 'busy' ||
601
+ fresh.why === 'not-signed-in' ||
602
+ fresh.why === 'shop-sign-in' ||
603
+ fresh.why === 'session-expired'
604
+ ? { outcome: fresh.why }
605
+ : // Not read (no answer, an answer not understood): nothing was sent - "not just now",
606
+ // never "the shop refused" (live walkthrough 11-23: a timeout was said as declined).
607
+ { outcome: 'refused', why: 'unavailable' };
608
+ }
609
+ const it = fresh.item;
610
+ if (!it.available)
611
+ return { outcome: 'refused', why: 'unavailable' };
612
+ const option = typeof req.option === 'string' ? req.option.trim() : '';
613
+ if (it.options.length > 0 ? !it.options.includes(option) : option !== '')
614
+ return { outcome: 'refused', why: 'option' };
615
+ if (it.priceCents !== shown.unitCents || it.currency !== shownCurrency)
616
+ return {
617
+ outcome: 'price-changed',
618
+ now: { unitCents: it.priceCents, currency: it.currency },
619
+ };
620
+ // 2. The orders as they stand: what is new after the request is the request's.
621
+ let before;
622
+ try {
623
+ before = (await readOrders(token, p, lang)).ids;
624
+ }
625
+ catch (err) {
626
+ const why = whyOf(err);
627
+ return why === 'busy' ||
628
+ why === 'not-signed-in' ||
629
+ why === 'shop-sign-in' ||
630
+ why === 'session-expired'
631
+ ? { outcome: why }
632
+ : { outcome: 'refused', why: 'unavailable' };
633
+ }
634
+ // 3. The request: ONCE. No `vccId`; the checkout-only parameters first, ours over them.
635
+ const guest = req.guest ?? {};
636
+ const name = textOf(guest.name, 100);
637
+ const email = textOf(guest.email, 200);
638
+ const phone = textOf(guest.phone, 40);
639
+ const body = {
640
+ ...params,
641
+ providerCode: p,
642
+ productId: it.id,
643
+ productName: it.name,
644
+ unitPrice: it.priceCents / 100,
645
+ quantity: qty,
646
+ confirmationCode: code,
647
+ ...(option ? { specSelections: { option } } : {}),
648
+ ...(name ? { customerName: name } : {}),
649
+ ...(email ? { customerEmail: email } : {}),
650
+ ...(phone ? { customerPhone: phone } : {}),
651
+ lang,
652
+ };
653
+ let made;
654
+ try {
655
+ made = madeFromAnswer(await client.buy(body, token));
656
+ }
657
+ catch (err) {
658
+ if (err instanceof OtalessBusy)
659
+ return { outcome: 'busy' };
660
+ if (err instanceof ShopSignInRequired)
661
+ return { outcome: 'shop-sign-in' };
662
+ const codeSaid = err instanceof OtalessError ? err.backendCode : undefined;
663
+ if (codeSaid === NOT_SIGNED_IN)
664
+ return { outcome: 'not-signed-in' };
665
+ if (codeSaid === ADDON_CODES.channelSessionExpired)
666
+ return { outcome: 'session-expired' };
667
+ if (!isUnknown(err)) {
668
+ if (codeSaid === ADDON_CODES.vccFailed)
669
+ log('[otaless-shop] buy: the backend tried a card on the account and it was refused (4020)');
670
+ return { outcome: 'refused', why: 'backend' };
671
+ }
672
+ // 4. ⚠️ NOT KNOWN WHETHER IT WAS MADE: never sent again. Read the orders once.
673
+ log('[otaless-shop] buy answer not known - not sent again; reading the orders once');
674
+ try {
675
+ const after = await readOrders(token, p, lang);
676
+ // ⚠️ ADOPTED ONLY WHEN IT CAN BE NO OTHER (总线程 11-23): new since the request, the
677
+ // same item name (whole, not one inside the other), the same amount and currency the
678
+ // guest was shown - and EXACTLY ONE such row. None or several: not known, a person
679
+ // looks, no link. A name alone could take another order for this one.
680
+ const mine = after.rows.filter((r) => !before.has(r.id) &&
681
+ sameName(r.name, it.name) &&
682
+ r.totalCents === shown.unitCents * qty &&
683
+ r.currency === shownCurrency);
684
+ if (mine.length !== 1 || !mine[0]) {
685
+ log(`[otaless-shop] NEEDS A PERSON: buy answer not known and ${mine.length === 0 ? 'no' : 'more than one'} new order matches it (name, amount, currency) - none taken, no link`);
686
+ return { outcome: 'unknown', needsPerson: true };
687
+ }
688
+ made = madeFromRow(mine[0]);
689
+ }
690
+ catch {
691
+ log('[otaless-shop] NEEDS A PERSON: buy answer not known and the orders could not be read - no link');
692
+ return { outcome: 'unknown', needsPerson: true };
693
+ }
694
+ }
695
+ return settle(token, p, lang, it, qty, shown, made);
696
+ },
697
+ // An answer not known keeps the same buy shut for ten minutes: the orders say what happened.
698
+ (r) => r.outcome === 'unknown');
699
+ };
700
+ const sameName = (a, b) => {
701
+ const x = lower(a);
702
+ const y = lower(b);
703
+ return !!x && x === y;
704
+ };
705
+ /** What was made, checked against what the guest was shown - and acted on. */
706
+ const settle = async (token, provider, lang, it, qty, shown, made) => {
707
+ const asOrder = (status, link) => ({
708
+ id: made.id ?? '',
709
+ name: it.name,
710
+ totalCents: made.totalCents ?? 0,
711
+ currency: made.currency ?? shown.currency,
712
+ status,
713
+ ...(link ? { checkoutUrl: link } : {}),
714
+ });
715
+ const allowed = shown.unitCents * qty;
716
+ // ⚠️ CHARGED - by the card the guest agreed to on the confirm screen (0.82.0). The order is
717
+ // kept whatever the amount: cancelling or refunding is money moving once more (decision D).
718
+ // A total above what was confirmed, another currency, or none said is `needsPerson` - said as
719
+ // it is.
720
+ if (made.charged) {
721
+ const over = made.totalCents !== undefined && made.totalCents > allowed;
722
+ const odd = made.totalCents === undefined || over || made.currency !== shown.currency;
723
+ if (odd)
724
+ log(`[otaless-shop] NEEDS A PERSON: shop order ${made.id ?? '(no id)'} was charged${made.totalCents !== undefined ? ` ${made.currency ?? '?'} ${(made.totalCents / 100).toFixed(2)}` : ' (no amount said)'} against ${shown.currency} ${(allowed / 100).toFixed(2)} confirmed`);
725
+ return {
726
+ outcome: 'paid',
727
+ order: asOrder(made.status === 'awaiting-payment' ? 'paid' : made.status),
728
+ ...(made.totalCents !== undefined ? { totalCents: made.totalCents } : {}),
729
+ ...(made.currency ? { currency: made.currency } : {}),
730
+ overShown: over,
731
+ ...(odd ? { needsPerson: true } : {}),
732
+ };
733
+ }
734
+ if (made.failed || made.status === 'cancelled' || made.status === 'refunded')
735
+ return { outcome: 'refused', why: 'backend' };
736
+ // A state we do not know, with or without an order behind it: not guessed at.
737
+ if (made.status !== 'awaiting-payment') {
738
+ log('[otaless-shop] buy answered a state not known - the orders will say');
739
+ return { outcome: 'unknown' };
740
+ }
741
+ const wrongAmount = made.totalCents === undefined ||
742
+ made.totalCents <= 0 ||
743
+ made.totalCents > allowed ||
744
+ made.currency !== shown.currency;
745
+ const link = checkoutLinkOf(made.checkoutRaw);
746
+ const bad = wrongAmount
747
+ ? 'wrong-amount'
748
+ : link
749
+ ? undefined
750
+ : 'bad-link';
751
+ if (bad) {
752
+ // ⚠️ CANCELLED AT ONCE, AND NO LINK EITHER WAY. If the cancel does not work out, the order is
753
+ // still there, awaiting payment: a person looks (the log has its id).
754
+ let cancelled = false;
755
+ if (made.id)
756
+ cancelled = (await sendCancel(token, provider, made.id, lang)) === 'cancelled';
757
+ // Which page it was, to tell what to allow (live walkthrough 11-23): the scheme, host and path
758
+ // with every long segment as <token>, and the query's parameter NAMES - never a value.
759
+ if (bad === 'bad-link' && typeof made.checkoutRaw === 'string') {
760
+ let where = '(not a URL)';
761
+ try {
762
+ const u = new URL(made.checkoutRaw);
763
+ const names = [...new Set([...u.searchParams.keys()])]
764
+ .map((k) => k.replace(/[^A-Za-z0-9_.-]/g, '?').slice(0, 32))
765
+ .slice(0, 8);
766
+ where = `${u.protocol}//${u.host}${u.pathname.replace(/[A-Za-z0-9_-]{12,}/g, '<token>')}${names.length ? ` query names: ${names.join(',')}` : ''}`;
767
+ }
768
+ catch {
769
+ // left as not a URL
770
+ }
771
+ log(`[otaless-shop] the checkout page refused was ${where}`);
772
+ }
773
+ log(cancelled
774
+ ? `[otaless-shop] buy of order ${made.id}: ${bad === 'wrong-amount' ? 'amount or currency did not match' : 'checkout page not allowed'} - cancelled`
775
+ : `[otaless-shop] NEEDS A PERSON: shop order ${made.id ?? '(no id)'} has ${bad === 'wrong-amount' ? 'an amount or currency that does not match' : 'a checkout page that is not allowed'} and could not be cancelled`);
776
+ return {
777
+ outcome: bad,
778
+ cancelled,
779
+ needsPerson: !cancelled,
780
+ ...(made.id ? { orderId: made.id } : {}),
781
+ };
782
+ }
783
+ if (!made.id)
784
+ return { outcome: 'unknown' };
785
+ return {
786
+ outcome: 'awaiting-payment',
787
+ order: asOrder('awaiting-payment', link),
788
+ checkoutUrl: link,
789
+ };
790
+ };
791
+ return { items, item, orders, cancel, refund, buy };
792
+ };
793
+ //# sourceMappingURL=shop.js.map