@curless/hotel-storefront 0.80.3 → 0.81.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 (82) hide show
  1. package/dist/account/index.d.ts +14 -0
  2. package/dist/account/index.d.ts.map +1 -1
  3. package/dist/account/index.js +427 -43
  4. package/dist/account/index.js.map +1 -1
  5. package/dist/account/pages.d.ts +15 -2
  6. package/dist/account/pages.d.ts.map +1 -1
  7. package/dist/account/pages.js +13 -10
  8. package/dist/account/pages.js.map +1 -1
  9. package/dist/account/wallet-pages.d.ts +84 -0
  10. package/dist/account/wallet-pages.d.ts.map +1 -0
  11. package/dist/account/wallet-pages.js +229 -0
  12. package/dist/account/wallet-pages.js.map +1 -0
  13. package/dist/account/wallet.d.ts +163 -0
  14. package/dist/account/wallet.d.ts.map +1 -0
  15. package/dist/account/wallet.js +365 -0
  16. package/dist/account/wallet.js.map +1 -0
  17. package/dist/backend.d.ts +18 -0
  18. package/dist/backend.d.ts.map +1 -1
  19. package/dist/backend.js.map +1 -1
  20. package/dist/card-v168.generated.d.ts +6 -0
  21. package/dist/card-v168.generated.d.ts.map +1 -0
  22. package/dist/card-v168.generated.js +10 -0
  23. package/dist/card-v168.generated.js.map +1 -0
  24. package/dist/card.generated.d.ts +1 -1
  25. package/dist/card.generated.js +2 -2
  26. package/dist/card.generated.js.map +1 -1
  27. package/dist/config.d.ts +48 -2
  28. package/dist/config.d.ts.map +1 -1
  29. package/dist/config.js +14 -1
  30. package/dist/config.js.map +1 -1
  31. package/dist/legal.d.ts.map +1 -1
  32. package/dist/legal.js +26 -4
  33. package/dist/legal.js.map +1 -1
  34. package/dist/otaless/client.d.ts +109 -0
  35. package/dist/otaless/client.d.ts.map +1 -1
  36. package/dist/otaless/client.js +44 -4
  37. package/dist/otaless/client.js.map +1 -1
  38. package/dist/otaless/fake.d.ts +92 -0
  39. package/dist/otaless/fake.d.ts.map +1 -1
  40. package/dist/otaless/fake.js +265 -0
  41. package/dist/otaless/fake.js.map +1 -1
  42. package/dist/otaless/make.d.ts +40 -1
  43. package/dist/otaless/make.d.ts.map +1 -1
  44. package/dist/otaless/make.js +150 -2
  45. package/dist/otaless/make.js.map +1 -1
  46. package/dist/otaless/shop-answers.d.ts +72 -0
  47. package/dist/otaless/shop-answers.d.ts.map +1 -0
  48. package/dist/otaless/shop-answers.js +344 -0
  49. package/dist/otaless/shop-answers.js.map +1 -0
  50. package/dist/otaless/shop-client.d.ts +133 -0
  51. package/dist/otaless/shop-client.d.ts.map +1 -0
  52. package/dist/otaless/shop-client.js +201 -0
  53. package/dist/otaless/shop-client.js.map +1 -0
  54. package/dist/otaless/shop-fake.d.ts +100 -0
  55. package/dist/otaless/shop-fake.d.ts.map +1 -0
  56. package/dist/otaless/shop-fake.js +259 -0
  57. package/dist/otaless/shop-fake.js.map +1 -0
  58. package/dist/otaless/shop-service.d.ts +105 -0
  59. package/dist/otaless/shop-service.d.ts.map +1 -0
  60. package/dist/otaless/shop-service.js +187 -0
  61. package/dist/otaless/shop-service.js.map +1 -0
  62. package/dist/otaless/shop.d.ts +160 -0
  63. package/dist/otaless/shop.d.ts.map +1 -0
  64. package/dist/otaless/shop.js +715 -0
  65. package/dist/otaless/shop.js.map +1 -0
  66. package/dist/otaless/wallet.d.ts +160 -0
  67. package/dist/otaless/wallet.d.ts.map +1 -0
  68. package/dist/otaless/wallet.js +650 -0
  69. package/dist/otaless/wallet.js.map +1 -0
  70. package/dist/server.d.ts +14 -3
  71. package/dist/server.d.ts.map +1 -1
  72. package/dist/server.js +41 -12
  73. package/dist/server.js.map +1 -1
  74. package/dist/surface.d.ts +7 -0
  75. package/dist/surface.d.ts.map +1 -1
  76. package/dist/surface.js +14 -0
  77. package/dist/surface.js.map +1 -1
  78. package/dist/tools.d.ts +98 -93
  79. package/dist/tools.d.ts.map +1 -1
  80. package/dist/tools.js +239 -1
  81. package/dist/tools.js.map +1 -1
  82. package/package.json +1 -1
@@ -0,0 +1,650 @@
1
+ import { CHANNEL_SESSION_EXPIRED, NOT_SIGNED_IN, OtalessBusy, OtalessError, REPEAT_SUBMIT, WALLET_CARD_ID, forTheLog, } from './client.js';
2
+ export const LEDGER_KINDS = [
3
+ 'authorize',
4
+ 'hold',
5
+ 'capture',
6
+ 'release',
7
+ 'refund',
8
+ 'expire',
9
+ 'renew',
10
+ ];
11
+ /** One authorization is at most US$2,000 (the document, 17.3). */
12
+ export const AUTHORIZE_MAX_CENTS = 200_000;
13
+ /** A limit is held to the same top. */
14
+ export const LIMIT_MAX_CENTS = 200_000;
15
+ /** What a caller's idempotency key may look like. */
16
+ export const IDEMPOTENCY_KEY = /^[A-Za-z0-9_-]{8,80}$/;
17
+ /** What the backend's `sid` in a link may look like. */
18
+ const SID = /^[A-Za-z0-9_-]{1,128}$/;
19
+ /** 15 minutes (17.1) - only where the backend gives no end. */
20
+ const LINK_MS = 15 * 60 * 1000;
21
+ const BOOKING_REF = /^[A-Za-z0-9_.:-]{1,100}$/;
22
+ export const HOST = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;
23
+ const SEGMENT = /^[A-Za-z0-9._~-]+$/;
24
+ /**
25
+ * `host/path/{sid}` -> its parts, or undefined for any other shape: a host name with a dot, plain
26
+ * path segments (no `.`, `..`, `%`, `\`), the LITERAL `{sid}` last, no query, no fragment.
27
+ */
28
+ export const parseLinkEntry = (entry) => {
29
+ if (typeof entry !== 'string')
30
+ return undefined;
31
+ const e = entry.trim();
32
+ const slash = e.indexOf('/');
33
+ if (slash < 0)
34
+ return undefined;
35
+ const host = e.slice(0, slash).toLowerCase();
36
+ const segs = e.slice(slash + 1).split('/');
37
+ if (!HOST.test(host) || segs.length < 1 || segs.at(-1) !== '{sid}')
38
+ return undefined;
39
+ const dir = segs.slice(0, -1);
40
+ if (dir.some((s) => !SEGMENT.test(s) || /^\.+$/.test(s)))
41
+ return undefined;
42
+ return { host, prefix: `/${dir.map((s) => `${s}/`).join('')}` };
43
+ };
44
+ /**
45
+ * ⚠️ THE ONLY WAY A BINDING LINK IS HANDED ON (§15.3's rule, as for a payment page): the
46
+ * backend's string is read for a host and a `sid`, and the address given out is REBUILT from the
47
+ * entry that matched and that `sid` - its own string never goes further. https only, the host
48
+ * exact, the path exactly the entry's, no port, user info, query or fragment. undefined: refused.
49
+ */
50
+ export const bindLinkOf = (raw, entries) => {
51
+ if (typeof raw !== 'string' || raw.length > 2048)
52
+ return undefined;
53
+ // ⚠️ ONE QUERY PARAMETER IS TAKEN, AND ONLY ITS TWO VALUES (live walkthrough 11-23: the dev
54
+ // backend's 17.1 answered `…/wallet/link/<sid>?lang=zh` - the `lang` we sent): `?lang=zh` or
55
+ // `?lang=en`, alone. Anything else in a query still refuses the link; the link handed on is
56
+ // rebuilt with that same `lang`, never the backend's string.
57
+ const q = /^([^?]*)\?lang=(zh|en)$/.exec(raw);
58
+ const base = q ? q[1] : raw;
59
+ const lang = q ? q[2] : undefined;
60
+ // The pattern itself leaves out `:`, `@`, `?`, `#`, `%` and `\`: no port, user info, other query, fragment or escape.
61
+ const m = /^https:\/\/([A-Za-z0-9.-]+)(\/[A-Za-z0-9_./-]*)$/.exec(base);
62
+ if (!m)
63
+ return undefined;
64
+ const host = m[1].toLowerCase();
65
+ const path = m[2];
66
+ for (const e of entries) {
67
+ if (e.host !== host || !path.startsWith(e.prefix))
68
+ continue;
69
+ const sid = path.slice(e.prefix.length);
70
+ if (SID.test(sid))
71
+ return `https://${e.host}${e.prefix}${sid}${lang ? `?lang=${lang}` : ''}`;
72
+ }
73
+ return undefined;
74
+ };
75
+ /** An answer that cannot be read as money or as a wallet. */
76
+ class Unreadable extends Error {
77
+ }
78
+ /** Whole cents from a JSON number or numeric string; `undefined` for none; anything else is unreadable. */
79
+ const centsOf = (v) => {
80
+ if (v === undefined || v === null)
81
+ return undefined;
82
+ let n;
83
+ if (typeof v === 'number')
84
+ n = v;
85
+ else if (typeof v === 'string' && /^\d{1,12}(?:\.\d+)?$/.test(v.trim()))
86
+ n = Number(v.trim());
87
+ else
88
+ throw new Unreadable('amount');
89
+ if (!Number.isFinite(n) || n < 0)
90
+ throw new Unreadable('amount');
91
+ const cents = Math.round(n * 100);
92
+ // ⚠️ A FRACTION OF A CENT IS NOT MONEY WE KNOW HOW TO SAY: read as nothing, not as a rounding.
93
+ if (!Number.isSafeInteger(cents) || Math.abs(n * 100 - cents) > 1e-6)
94
+ throw new Unreadable('amount');
95
+ return cents;
96
+ };
97
+ const usdOf = (cents) => Number((cents / 100).toFixed(2));
98
+ /** Words a wallet answer may carry that say a state, not who or what (shown whole by `shapeOf`). */
99
+ const SHAPE_WORDS = new Set([
100
+ 'statusTag',
101
+ 'status',
102
+ 'currency',
103
+ 'brand',
104
+ 'kind',
105
+ 'cardTag',
106
+ 'actor',
107
+ 'merchant',
108
+ 'message',
109
+ 'msg',
110
+ ]);
111
+ /** A value's shape for the log (see `debug`): never a free string, never an id. */
112
+ export const shapeOf = (v, key = '', depth = 0) => {
113
+ if (depth > 5)
114
+ return '…';
115
+ if (v === null || typeof v === 'number' || typeof v === 'boolean')
116
+ return v;
117
+ if (typeof v === 'string')
118
+ return SHAPE_WORDS.has(key) ? v.slice(0, 60) : `str(${v.length})`;
119
+ if (Array.isArray(v))
120
+ return v.length ? [shapeOf(v[0], key, depth + 1), `×${v.length}`] : [];
121
+ if (typeof v === 'object')
122
+ return Object.fromEntries(Object.entries(v)
123
+ .slice(0, 40)
124
+ .map(([k, x]) => [k, shapeOf(x, k, depth + 1)]));
125
+ return typeof v;
126
+ };
127
+ export const createOtalessWallet = (opts) => {
128
+ const now = opts.now ?? Date.now;
129
+ const log = opts.log ?? ((line) => console.error(line));
130
+ const client = opts.debug
131
+ ? Object.fromEntries(Object.entries(opts.client).map(([name, fn]) => [
132
+ name,
133
+ async (...a) => {
134
+ const sent = await fn(...a);
135
+ log(`[otaless-wallet] debug ${name} answer shape ${JSON.stringify(shapeOf(sent?.data))}`);
136
+ return sent;
137
+ },
138
+ ]))
139
+ : opts.client;
140
+ const groups = [...opts.groups];
141
+ const entries = opts.linkHosts.map((h) => {
142
+ const e = parseLinkEntry(h);
143
+ if (!e)
144
+ throw new Error(`not a wallet link host entry: ${JSON.stringify(h)}`);
145
+ return e;
146
+ });
147
+ const said = { unknownKinds: new Set(), simulated: false };
148
+ const offers = (group) => groups.includes(group);
149
+ /** Why a request failed - nothing about the guest in it. */
150
+ const why = (err) => {
151
+ if (err instanceof OtalessBusy)
152
+ return 'busy';
153
+ if (err instanceof OtalessError) {
154
+ if (err.backendCode === NOT_SIGNED_IN)
155
+ return 'signed-out';
156
+ // The member's link to this group is over (questions #106): the caller offers linking it.
157
+ if (err.backendCode === CHANNEL_SESSION_EXPIRED)
158
+ return 'session-expired';
159
+ }
160
+ return 'unavailable';
161
+ };
162
+ const creditOf = (c) => {
163
+ const w = c ?? {};
164
+ if (typeof w !== 'object')
165
+ throw new Unreadable('credit');
166
+ if (w.currency !== undefined && w.currency !== null && w.currency !== 'USD')
167
+ throw new Unreadable('currency');
168
+ const authorized = centsOf(w.authorizedUsd);
169
+ const captured = centsOf(w.capturedUsd);
170
+ const held = centsOf(w.heldUsd);
171
+ const stated = centsOf(w.availableUsd);
172
+ // ⚠️ THE LESSER OF WHAT IT SAYS AND WHAT ITS OWN NUMBERS GIVE: `available = max(0,
173
+ // authorized - captured - held)` (the document, 1.5) - a figure above it is never shown.
174
+ const formula = authorized !== undefined
175
+ ? Math.max(0, authorized - (captured ?? 0) - (held ?? 0))
176
+ : undefined;
177
+ const available = stated !== undefined && formula !== undefined
178
+ ? Math.min(stated, formula)
179
+ : (stated ?? formula ?? 0);
180
+ const expiresAt = typeof w.expiresAt === 'string' && w.expiresAt.trim() ? w.expiresAt.trim() : undefined;
181
+ const expired = typeof w.expired === 'boolean'
182
+ ? w.expired
183
+ : expiresAt !== undefined && Date.parse(expiresAt) <= now();
184
+ return {
185
+ availableCents: expired ? 0 : available,
186
+ authorizedCents: authorized ?? 0,
187
+ capturedCents: captured ?? 0,
188
+ heldCents: held ?? 0,
189
+ ...(expiresAt ? { expiresAt } : {}),
190
+ expired,
191
+ };
192
+ };
193
+ /** `simulated` is the backend's, never the guest's to read (docs §17.3): one line on the log. */
194
+ const noteSimulated = (group) => {
195
+ if (said.simulated)
196
+ return;
197
+ said.simulated = true;
198
+ log(`[otaless-wallet] ${group} says its authorization is simulated (not shown to guests)`);
199
+ };
200
+ const limitsOf = (l) => {
201
+ if (l !== undefined && l !== null && typeof l !== 'object')
202
+ throw new Unreadable('limits');
203
+ return {
204
+ perTxnCents: centsOf(l?.perTxnUsd) ?? null,
205
+ perDayCents: centsOf(l?.perDayUsd) ?? null,
206
+ };
207
+ };
208
+ const entriesOf = (rows) => {
209
+ if (rows === undefined || rows === null)
210
+ return [];
211
+ if (!Array.isArray(rows))
212
+ throw new Unreadable('transactions');
213
+ const out = [];
214
+ for (const raw of rows) {
215
+ if (!raw || typeof raw !== 'object')
216
+ continue;
217
+ const kind = typeof raw.kind === 'string' ? raw.kind.trim().toLowerCase() : '';
218
+ if (!LEDGER_KINDS.includes(kind)) {
219
+ if (!said.unknownKinds.has(kind)) {
220
+ said.unknownKinds.add(kind);
221
+ log(`[otaless-wallet] a ledger entry of a kind not known is left out: "${forTheLog(kind).slice(0, 30)}"`);
222
+ }
223
+ continue;
224
+ }
225
+ const amount = centsOf(raw.amountUsd);
226
+ if (amount === undefined || typeof raw.at !== 'string' || !raw.at.trim())
227
+ throw new Unreadable('entry');
228
+ const ref = typeof raw.ref === 'string' ? raw.ref : '';
229
+ const booking = /^booking:(.+)$/.exec(ref)?.[1];
230
+ const card = /^auth:(.+)$/.exec(ref)?.[1];
231
+ out.push({
232
+ kind: kind,
233
+ amountCents: amount,
234
+ at: raw.at.trim(),
235
+ ...(booking && BOOKING_REF.test(booking) ? { bookingId: booking } : {}),
236
+ ...(card && WALLET_CARD_ID.test(card) ? { cardId: card } : {}),
237
+ });
238
+ }
239
+ return out;
240
+ };
241
+ const viewOf = (w, group) => {
242
+ if (!w || typeof w !== 'object')
243
+ throw new Unreadable('status');
244
+ const credit = creditOf(w.credit);
245
+ if (w.simulated !== undefined)
246
+ noteSimulated(group);
247
+ if (w.cards !== undefined && w.cards !== null && !Array.isArray(w.cards))
248
+ throw new Unreadable('cards');
249
+ const cards = [];
250
+ for (const c of w.cards ?? []) {
251
+ if (!c || typeof c !== 'object')
252
+ continue;
253
+ const status = typeof c.status === 'string' ? c.status.trim().toLowerCase() : 'active';
254
+ if (status !== 'active')
255
+ continue;
256
+ if (typeof c.id !== 'string' ||
257
+ !WALLET_CARD_ID.test(c.id) ||
258
+ typeof c.last4 !== 'string' ||
259
+ !/^\d{4}$/.test(c.last4) ||
260
+ typeof c.exp !== 'string' ||
261
+ !/^\d{2}\/\d{2}$/.test(c.exp))
262
+ continue;
263
+ cards.push({
264
+ id: c.id,
265
+ brand: typeof c.brand === 'string' ? c.brand.trim().slice(0, 30) : '',
266
+ last4: c.last4,
267
+ exp: c.exp,
268
+ });
269
+ }
270
+ const tag = typeof w.statusTag === 'string' ? w.statusTag.trim().toLowerCase() : '';
271
+ // ⚠️ THE NUMBERS OVER THE TAG: an expired credit is expired, and "Ready" with nothing to
272
+ // spend is "no credit" - never the more hopeful of the two.
273
+ const status = credit.expired
274
+ ? 'expired'
275
+ : credit.availableCents > 0
276
+ ? tag === 'no credit'
277
+ ? 'no-credit'
278
+ : 'ready'
279
+ : 'no-credit';
280
+ return {
281
+ group,
282
+ status,
283
+ credit,
284
+ cards,
285
+ // ⚠️ null/absent = not given = unknown (see `WalletView.limits`), never "no limit".
286
+ ...(w.limits === null || w.limits === undefined ? {} : { limits: limitsOf(w.limits) }),
287
+ recent: entriesOf(w.recentTransactions),
288
+ };
289
+ };
290
+ /** 17.2, read fresh and parsed - or why not. */
291
+ const balance = async (cred, group, who) => {
292
+ let sent;
293
+ try {
294
+ sent = await client.walletBalance({ providerCode: group }, cred, who);
295
+ }
296
+ catch (err) {
297
+ const reason = why(err);
298
+ log(`[otaless-wallet] balance at ${group} not read: ${reason}`);
299
+ return { ok: false, reason };
300
+ }
301
+ try {
302
+ if (sent.data?.ok === false)
303
+ throw new Unreadable('not ok');
304
+ return { ok: true, value: viewOf(sent.data, group) };
305
+ }
306
+ catch (err) {
307
+ if (!(err instanceof Unreadable))
308
+ throw err;
309
+ log(`[otaless-wallet] balance at ${group} could not be read (${err.message})`);
310
+ return { ok: false, reason: 'unreadable' };
311
+ }
312
+ };
313
+ /**
314
+ * One write's end, from what went wrong: nothing sent or the backend said no is `refused`;
315
+ * a request that may have been applied is `unknown`. ⚠️ Only a 200 carrying a backend `code` is a
316
+ * refusal - an HTTP error, a lost answer and a 10014 are not known to have changed nothing.
317
+ */
318
+ const ended = (err, what, group, extra = '') => {
319
+ if (err instanceof OtalessBusy)
320
+ return { status: 'refused', reason: 'busy' };
321
+ if (err instanceof OtalessError) {
322
+ if (err.backendCode === NOT_SIGNED_IN)
323
+ return { status: 'refused', reason: 'signed-out' };
324
+ if (err.backendCode === CHANNEL_SESSION_EXPIRED)
325
+ return { status: 'refused', reason: 'session-expired' };
326
+ if (err.backendCode === REPEAT_SUBMIT) {
327
+ log(`[otaless-wallet] NEEDS A PERSON? ${what} at ${group}${extra} was refused as a repeat: not known whether it was applied - not sent again`);
328
+ return { status: 'unknown', why: 'repeat' };
329
+ }
330
+ // ⚠️ A SERVER ERROR IN A 200 IS NOT A NO (总线程-style review, 0.81.0): the backend's
331
+ // `code: 500` ("Internal Server Error", seen on 8 - questions #96) may come after the
332
+ // write was applied downstream, so it is not known to have changed nothing.
333
+ // (500-599 only: the backend's own business codes - 4012, 10014… - are numbers above 500.)
334
+ if (err.status === 200 &&
335
+ typeof err.backendCode === 'number' &&
336
+ err.backendCode >= 500 &&
337
+ err.backendCode < 600) {
338
+ log(`[otaless-wallet] NEEDS A PERSON? ${what} at ${group}${extra} answered code=${err.backendCode}: not known whether it was applied - not sent again`);
339
+ return { status: 'unknown', why: 'http' };
340
+ }
341
+ if (err.status === 200 && typeof err.backendCode === 'number') {
342
+ const words = err.answer?.msg ? ` "${forTheLog(err.answer.msg)}"` : '';
343
+ log(`[otaless-wallet] ${what} at ${group}${extra} refused by the backend: code=${err.backendCode}${words}`);
344
+ return { status: 'refused', reason: 'declined' };
345
+ }
346
+ const how = err.status === undefined ? 'timeout' : 'http';
347
+ log(`[otaless-wallet] NEEDS A PERSON? ${what} at ${group}${extra}: no answer to read (${how}) - not known whether it was applied, not sent again`);
348
+ return { status: 'unknown', why: how };
349
+ }
350
+ log(`[otaless-wallet] NEEDS A PERSON? ${what} at ${group}${extra}: failed before an answer`);
351
+ return { status: 'unknown', why: 'timeout' };
352
+ };
353
+ const unreadableWrite = (what, group, extra = '') => {
354
+ log(`[otaless-wallet] NEEDS A PERSON? ${what} at ${group}${extra} was answered but the answer could not be read - not sent again`);
355
+ return { status: 'unknown', why: 'unreadable' };
356
+ };
357
+ const wholeCents = (v, max) => typeof v === 'number' && Number.isInteger(v) && v >= 1 && v <= max;
358
+ return {
359
+ groups,
360
+ offers,
361
+ view: async (cred, group, who, o = {}) => {
362
+ if (!offers(group))
363
+ return { ok: false, reason: 'not-offered' };
364
+ const b = await balance(cred, group, who);
365
+ if (!b.ok)
366
+ return b;
367
+ const n = o.transactions;
368
+ if (n === undefined || n <= 0)
369
+ return b;
370
+ try {
371
+ const t = await client.walletTransactions({ providerCode: group, limit: Math.min(50, Math.max(1, Math.floor(n))) }, cred, who);
372
+ const rows = Array.isArray(t.data) ? t.data : t.data?.transactions;
373
+ return { ok: true, value: { ...b.value, recent: entriesOf(rows).slice(0, n) } };
374
+ }
375
+ catch (err) {
376
+ if (err instanceof Unreadable) {
377
+ log(`[otaless-wallet] transactions at ${group} could not be read: the latest of the balance are shown`);
378
+ return b;
379
+ }
380
+ const reason = why(err);
381
+ // A guest signed out, a group link over or a limit reached say so; any other failure of the
382
+ // second read leaves the first one's latest entries.
383
+ if (reason !== 'unavailable')
384
+ return { ok: false, reason };
385
+ log(`[otaless-wallet] transactions at ${group} not read: the latest of the balance are shown`);
386
+ return b;
387
+ }
388
+ },
389
+ bindLink: async (cred, group, lang, who) => {
390
+ if (!offers(group))
391
+ return { ok: false, reason: 'not-offered' };
392
+ // ⚠️ READ FIRST, AS EVERY WRITE (总线程 11-23): a binding session is only asked for an
393
+ // account whose wallet answers now.
394
+ const fresh = await balance(cred, group, who);
395
+ if (!fresh.ok)
396
+ return {
397
+ ok: false,
398
+ reason: fresh.reason === 'bad-link' ? 'unavailable' : fresh.reason,
399
+ };
400
+ let sent;
401
+ try {
402
+ sent = await client.walletLinkSession({ providerCode: group, lang: lang === 'zh' ? 'zh' : 'en' }, cred, who);
403
+ }
404
+ catch (err) {
405
+ const reason = why(err);
406
+ log(`[otaless-wallet] no binding page at ${group}: ${reason}`);
407
+ return { ok: false, reason };
408
+ }
409
+ const d = sent.data;
410
+ if (!d || typeof d !== 'object' || d.ok === false) {
411
+ log(`[otaless-wallet] no binding page at ${group}: the backend did not give one`);
412
+ return { ok: false, reason: 'unavailable' };
413
+ }
414
+ const url = bindLinkOf(d.linkUrl, entries);
415
+ if (!url) {
416
+ // ⚠️ HOST AND PATH ONLY, NEVER THE QUERY - and never the sid, which is the page.
417
+ let where = '?';
418
+ try {
419
+ const u = new URL(String(d.linkUrl));
420
+ // The query's parameter NAMES only (never a value - a value may be a token), and
421
+ // whether a fragment, a port or a user part is there (live walkthrough 11-23: the
422
+ // host and path matched and nothing else said why it was refused).
423
+ const names = [...new Set([...u.searchParams.keys()])]
424
+ .map((k) => k.replace(/[^A-Za-z0-9_.-]/g, '?').slice(0, 32))
425
+ .slice(0, 8);
426
+ where = `${u.protocol}//${u.host}${u.pathname.replace(/[A-Za-z0-9_-]{8,}$/, '<sid>')}${names.length ? ` query names: ${names.join(',')}` : ''}${u.hash ? ' fragment' : ''}${u.username || u.password ? ' userinfo' : ''}`;
427
+ }
428
+ catch {
429
+ // not a URL at all
430
+ }
431
+ log(`[otaless-wallet] binding page at ${group} refused: not an allowed address (${where})`);
432
+ return { ok: false, reason: 'bad-link' };
433
+ }
434
+ if (typeof d.cardsBefore !== 'number' ||
435
+ !Number.isInteger(d.cardsBefore) ||
436
+ d.cardsBefore < 0) {
437
+ log(`[otaless-wallet] binding page at ${group} refused: no count of cards before`);
438
+ return { ok: false, reason: 'unreadable' };
439
+ }
440
+ const ends = typeof d.expiresAt === 'string' ? Date.parse(d.expiresAt) : Number.NaN;
441
+ return {
442
+ ok: true,
443
+ value: {
444
+ url,
445
+ expiresAt: Number.isFinite(ends)
446
+ ? d.expiresAt
447
+ : new Date(now() + LINK_MS).toISOString(),
448
+ cardsBefore: d.cardsBefore,
449
+ },
450
+ };
451
+ },
452
+ authorize: async (cred, group, a, who) => {
453
+ if (!offers(group))
454
+ return { status: 'refused', reason: 'not-offered' };
455
+ if (!a ||
456
+ !wholeCents(a.amountCents, AUTHORIZE_MAX_CENTS) ||
457
+ typeof a.cardId !== 'string' ||
458
+ !WALLET_CARD_ID.test(a.cardId) ||
459
+ typeof a.key !== 'string' ||
460
+ !IDEMPOTENCY_KEY.test(a.key))
461
+ return { status: 'refused', reason: 'bad-input' };
462
+ // ⚠️ A FRESH READ FIRST (docs §17.3): the card is one the account holds NOW. And the card is
463
+ // always sent - never the backend's "first card" when none is given.
464
+ const fresh = await balance(cred, group, who);
465
+ if (!fresh.ok)
466
+ return {
467
+ status: 'refused',
468
+ reason: fresh.reason === 'unreadable' || fresh.reason === 'bad-link'
469
+ ? 'unavailable'
470
+ : fresh.reason,
471
+ };
472
+ if (!fresh.value.cards.some((c) => c.id === a.cardId))
473
+ return { status: 'refused', reason: 'no-such-card' };
474
+ const amount = ` of US$${(a.amountCents / 100).toFixed(2)}`;
475
+ try {
476
+ const sent = await client.walletAuthorize({
477
+ providerCode: group,
478
+ // Two decimals at most: whole cents / 100, never a float sum.
479
+ amountUsd: usdOf(a.amountCents),
480
+ cardId: a.cardId,
481
+ idempotencyKey: a.key,
482
+ }, cred, who);
483
+ const d = sent.data;
484
+ if (d && typeof d === 'object' && d.ok === false) {
485
+ log(`[otaless-wallet] authorize${amount} at ${group} refused: the answer says not ok`);
486
+ return { status: 'refused', reason: 'declined' };
487
+ }
488
+ if (d && d.simulated !== undefined)
489
+ noteSimulated(group);
490
+ try {
491
+ if (!d || typeof d !== 'object' || !d.credit)
492
+ throw new Unreadable('credit');
493
+ return { status: 'done', credit: creditOf(d.credit) };
494
+ }
495
+ catch (err) {
496
+ if (!(err instanceof Unreadable))
497
+ throw err;
498
+ return unreadableWrite('authorize', group, amount);
499
+ }
500
+ }
501
+ catch (err) {
502
+ return ended(err, 'authorize', group, amount);
503
+ }
504
+ },
505
+ setLimits: async (cred, group, l, who) => {
506
+ if (!offers(group))
507
+ return { status: 'refused', reason: 'not-offered' };
508
+ const okLimit = (v) => v === null || wholeCents(v, LIMIT_MAX_CENTS);
509
+ if (!l || !okLimit(l.perTxnCents) || !okLimit(l.perDayCents))
510
+ return { status: 'refused', reason: 'bad-input' };
511
+ // ⚠️ READ FIRST, AS EVERY WRITE (总线程 11-23).
512
+ const fresh = await balance(cred, group, who);
513
+ if (!fresh.ok)
514
+ return {
515
+ status: 'refused',
516
+ reason: fresh.reason === 'unreadable' || fresh.reason === 'bad-link'
517
+ ? 'unavailable'
518
+ : fresh.reason,
519
+ };
520
+ try {
521
+ const sent = await client.walletLimits({
522
+ providerCode: group,
523
+ // ⚠️ BOTH, ALWAYS, `null` WHERE CLEARED: the document says "absent keeps, null
524
+ // clears", but the Java side may not tell them apart (questions #108) - a limit
525
+ // left out could be wiped, or kept when it was meant to go.
526
+ perTransactionUsd: l.perTxnCents === null ? null : usdOf(l.perTxnCents),
527
+ perDayUsd: l.perDayCents === null ? null : usdOf(l.perDayCents),
528
+ }, cred, who);
529
+ const d = sent.data;
530
+ if (d && typeof d === 'object' && d.ok === false) {
531
+ log(`[otaless-wallet] limits at ${group} refused: the answer says not ok`);
532
+ return { status: 'refused', reason: 'declined' };
533
+ }
534
+ try {
535
+ if (!d || typeof d !== 'object' || !d.limits)
536
+ throw new Unreadable('limits');
537
+ const said = limitsOf(d.limits);
538
+ // ⚠️ DONE ONLY WHEN THE ANSWER SAYS WHAT WAS ASKED (live walkthrough 11-23: 17.4 answered
539
+ // ok and 17.2 still showed no limit): limits the answer does not carry as asked are not
540
+ // known to be set - never "done".
541
+ if (said.perTxnCents !== l.perTxnCents || said.perDayCents !== l.perDayCents)
542
+ throw new Unreadable('the limits answered are not the ones asked');
543
+ return { status: 'done', limits: said };
544
+ }
545
+ catch (err) {
546
+ if (!(err instanceof Unreadable))
547
+ throw err;
548
+ return unreadableWrite('limits', group);
549
+ }
550
+ }
551
+ catch (err) {
552
+ return ended(err, 'limits', group);
553
+ }
554
+ },
555
+ renew: async (cred, group, r, who) => {
556
+ if (!offers(group))
557
+ return { status: 'refused', reason: 'not-offered' };
558
+ if (!r || typeof r.cardId !== 'string' || !WALLET_CARD_ID.test(r.cardId))
559
+ return { status: 'refused', reason: 'bad-input' };
560
+ // ⚠️ READ FIRST, AS EVERY WRITE (总线程 11-23): a renewal keeps a hold on the guest's own card
561
+ // a week longer - the card must be one the account holds now.
562
+ const fresh = await balance(cred, group, who);
563
+ if (!fresh.ok)
564
+ return {
565
+ status: 'refused',
566
+ reason: fresh.reason === 'unreadable' || fresh.reason === 'bad-link'
567
+ ? 'unavailable'
568
+ : fresh.reason,
569
+ };
570
+ if (!fresh.value.cards.some((c) => c.id === r.cardId))
571
+ return { status: 'refused', reason: 'no-such-card' };
572
+ try {
573
+ const sent = await client.walletRenew({ providerCode: group, cardId: r.cardId }, cred, who);
574
+ const d = sent.data;
575
+ if (d && typeof d === 'object' && d.ok === false) {
576
+ log(`[otaless-wallet] renew at ${group} refused: the answer says not ok`);
577
+ return {
578
+ status: 'refused',
579
+ reason: /nothing_to_renew/i.test(String(d.message ?? ''))
580
+ ? 'nothing-to-renew'
581
+ : 'declined',
582
+ };
583
+ }
584
+ try {
585
+ if (!d || typeof d !== 'object' || !d.credit)
586
+ throw new Unreadable('credit');
587
+ return { status: 'done', credit: creditOf(d.credit) };
588
+ }
589
+ catch (err) {
590
+ if (!(err instanceof Unreadable))
591
+ throw err;
592
+ return unreadableWrite('renew', group);
593
+ }
594
+ }
595
+ catch (err) {
596
+ return ended(err, 'renew', group);
597
+ }
598
+ },
599
+ unbind: async (cred, group, cardId, who) => {
600
+ if (!offers(group))
601
+ return { status: 'refused', reason: 'not-offered' };
602
+ if (typeof cardId !== 'string' || !WALLET_CARD_ID.test(cardId))
603
+ return { status: 'refused', reason: 'bad-input' };
604
+ const fresh = await balance(cred, group, who);
605
+ if (!fresh.ok)
606
+ return {
607
+ status: 'refused',
608
+ reason: fresh.reason === 'unreadable' || fresh.reason === 'bad-link'
609
+ ? 'unavailable'
610
+ : fresh.reason,
611
+ };
612
+ if (!fresh.value.cards.some((c) => c.id === cardId))
613
+ return { status: 'refused', reason: 'no-such-card' };
614
+ const heldCents = fresh.value.credit.heldCents;
615
+ try {
616
+ const sent = await client.walletUnbind(cardId, group, cred, who);
617
+ const d = sent.data;
618
+ if (d && typeof d === 'object' && (d.ok === false || d.unlinked === false)) {
619
+ log(`[otaless-wallet] unbind at ${group} refused: the answer says not unlinked`);
620
+ return { status: 'refused', reason: 'declined' };
621
+ }
622
+ try {
623
+ if (!d || typeof d !== 'object')
624
+ throw new Unreadable('unbind');
625
+ // ⚠️ DONE ON THE BACKEND'S SAY-SO, AMOUNT OR NOT (live walkthrough 11-23: `unlinked: true`
626
+ // with `releasedUsd: null`, and the card WAS gone): an amount absent is left out, never
627
+ // guessed. Neither `unlinked` nor the card id echoed = unreadable.
628
+ const unlinked = d.unlinked === true || (d.ok === true && d.cardId === cardId);
629
+ if (!unlinked)
630
+ throw new Unreadable('unbind');
631
+ const released = centsOf(d.releasedUsd);
632
+ return {
633
+ status: 'done',
634
+ ...(released === undefined ? {} : { releasedCents: released }),
635
+ heldCents,
636
+ };
637
+ }
638
+ catch (err) {
639
+ if (!(err instanceof Unreadable))
640
+ throw err;
641
+ return unreadableWrite('unbind', group);
642
+ }
643
+ }
644
+ catch (err) {
645
+ return ended(err, 'unbind', group);
646
+ }
647
+ },
648
+ };
649
+ };
650
+ //# sourceMappingURL=wallet.js.map