@tallyui/core 3.20.0 → 4.0.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 (43) hide show
  1. package/dist/chunk-XF3RD6GX.js +515 -0
  2. package/dist/index.d.ts +41 -47
  3. package/dist/index.js +119 -101
  4. package/dist/server/index.cjs +1923 -0
  5. package/dist/server/index.d.cts +1039 -0
  6. package/dist/server/index.d.ts +46 -48
  7. package/dist/server/index.js +516 -206
  8. package/dist/{command-result-E_nH57WD.d.ts → tax-rate-DCJhfJbZ.d.ts} +442 -26
  9. package/package.json +10 -5
  10. package/src/commands.ts +12 -0
  11. package/src/context/money-format-context.tsx +50 -0
  12. package/src/coupons/woocommerce/to-coupon-configs.ts +5 -8
  13. package/src/fnv1a32.ts +14 -0
  14. package/src/index.ts +18 -5
  15. package/src/known-warnings.ts +23 -0
  16. package/src/money.ts +85 -2
  17. package/src/server/batch.ts +63 -27
  18. package/src/server/command-result.ts +28 -1
  19. package/src/server/display-signalling/contract.ts +203 -78
  20. package/src/server/display-signalling/memory-server.ts +71 -23
  21. package/src/server/fiscal-figures.ts +1 -1
  22. package/src/server/index.ts +5 -1
  23. package/src/server/money.ts +4 -1
  24. package/src/server/order-payload-shape.ts +96 -5
  25. package/src/server/refund-payload-shape.ts +5 -11
  26. package/src/server/register-payload-shape.ts +6 -12
  27. package/src/server/rejection-codes.ts +4 -4
  28. package/src/server/reopen-payload-shape.ts +25 -0
  29. package/src/server/shape-errors.ts +17 -0
  30. package/src/server/tax-rate.ts +13 -0
  31. package/src/server/update-payload-shape.ts +51 -0
  32. package/src/server/versions.ts +9 -2
  33. package/src/types/closures.ts +34 -0
  34. package/src/types/commands.ts +93 -8
  35. package/src/types/connector.ts +37 -4
  36. package/src/types/display-signalling.ts +30 -14
  37. package/src/types/index.ts +6 -3
  38. package/src/types/orders.ts +25 -3
  39. package/src/types/payment-methods.ts +17 -0
  40. package/src/types/stock.ts +2 -0
  41. package/src/types/store-settings.ts +7 -0
  42. package/src/types/traits/product.ts +19 -0
  43. package/dist/chunk-27L7XLTT.js +0 -235
@@ -0,0 +1,515 @@
1
+ // src/types/display-signalling.ts
2
+ var DISPLAY_PAIR_CAPABILITY = "customer_display.pair";
3
+ var DisplaySignallingError = class extends Error {
4
+ code;
5
+ constructor(code, message = code) {
6
+ super(message);
7
+ this.name = "DisplaySignallingError";
8
+ this.code = code;
9
+ }
10
+ };
11
+
12
+ // src/customer-display/rate-limit-source.ts
13
+ var IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
14
+ var HEXTET = /^[0-9a-f]{1,4}$/;
15
+ function expandIpv6(address) {
16
+ let text = address.toLowerCase();
17
+ const last = text.slice(text.lastIndexOf(":") + 1);
18
+ if (IPV4.test(last)) {
19
+ const [a, b, c, d] = last.split(".").map(Number);
20
+ text = `${text.slice(0, text.length - last.length)}${(a << 8 | b).toString(16)}:${(c << 8 | d).toString(16)}`;
21
+ }
22
+ const halves = text.split("::");
23
+ if (halves.length > 2) return void 0;
24
+ const head = halves[0] ? halves[0].split(":") : [];
25
+ const tail = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
26
+ const missing = 8 - head.length - tail.length;
27
+ if (halves.length === 2 ? missing < 1 : missing !== 0) return void 0;
28
+ const groups = [...head, ...Array(missing).fill("0"), ...tail];
29
+ if (!groups.every((group) => HEXTET.test(group))) return void 0;
30
+ return groups.map((group) => group.padStart(4, "0"));
31
+ }
32
+ function rateLimitSource(address) {
33
+ const input = address.trim();
34
+ if (IPV4.test(input)) return input;
35
+ const zone = input.indexOf("%");
36
+ const hextets = expandIpv6(zone >= 0 ? input.slice(0, zone) : input);
37
+ if (!hextets) return input;
38
+ if (hextets.slice(0, 5).every((group) => group === "0000") && hextets[5] === "ffff") {
39
+ const high = parseInt(hextets[6], 16);
40
+ const low = parseInt(hextets[7], 16);
41
+ return [high >> 8, high & 255, low >> 8, low & 255].join(".");
42
+ }
43
+ return `${hextets.slice(0, 4).join(":")}::/64`;
44
+ }
45
+
46
+ // src/commands.ts
47
+ var COMMANDS_PATH = "/tally/v1/commands";
48
+ var PROTOCOL_HEADER = "X-Tally-Protocol";
49
+ var PROTOCOL_VERSION = 1;
50
+ var MAX_COMMANDS_PER_BATCH = 50;
51
+ var ORDER_NOTE_MAX = 1e3;
52
+ var ORDER_TAX_IDS_MAX = 10;
53
+ var ORDER_TAX_ID_TYPE_MAX = 32;
54
+ var ORDER_TAX_ID_VALUE_MAX = 64;
55
+ var ORDER_META_MAX = 50;
56
+ var ORDER_META_KEY_MAX = 255;
57
+ var ORDER_LINE_SKU_MAX = 100;
58
+ function isCommandBatchResponse(value) {
59
+ return typeof value === "object" && value !== null && "results" in value && Array.isArray(value.results) && value.results.every(
60
+ (result) => typeof result === "object" && result !== null && "id" in result && typeof result.id === "string" && "status" in result && (result.status === "applied" || result.status === "duplicate" || result.status === "rejected")
61
+ );
62
+ }
63
+
64
+ // src/money.ts
65
+ var digitsCache = /* @__PURE__ */ new Map();
66
+ function minorUnitDigits(currency) {
67
+ const code = currency.toUpperCase();
68
+ let digits = digitsCache.get(code);
69
+ if (digits === void 0) {
70
+ try {
71
+ digits = new Intl.NumberFormat("en", { style: "currency", currency: code }).resolvedOptions().maximumFractionDigits ?? 2;
72
+ } catch {
73
+ digits = 2;
74
+ }
75
+ digitsCache.set(code, digits);
76
+ }
77
+ return digits;
78
+ }
79
+ var symbolCache = /* @__PURE__ */ new Map();
80
+ function currencySymbol(currency, locale) {
81
+ const code = currency.toUpperCase();
82
+ const key = `${code}:${locale ?? ""}`;
83
+ let symbol = symbolCache.get(key);
84
+ if (symbol === void 0) {
85
+ try {
86
+ const part = new Intl.NumberFormat(locale, { style: "currency", currency: code }).formatToParts(0).find((p) => p.type === "currency");
87
+ symbol = part?.value ?? code;
88
+ } catch {
89
+ symbol = code;
90
+ }
91
+ symbolCache.set(key, symbol);
92
+ }
93
+ return symbol;
94
+ }
95
+ function moneyFromMajor(value, currency) {
96
+ if (value === null || value === void 0 || value === "") return void 0;
97
+ const major = typeof value === "number" ? value : Number(value);
98
+ if (!Number.isFinite(major)) return void 0;
99
+ const code = currency.toUpperCase();
100
+ return { amount: Math.round(major * 10 ** minorUnitDigits(code)), currency: code };
101
+ }
102
+ function moneyFromDecimalString(text, currency) {
103
+ const trimmed = text.trim();
104
+ if (!/^\d+(\.\d+)?$/.test(trimmed)) return void 0;
105
+ const code = currency.toUpperCase();
106
+ const digits = minorUnitDigits(code);
107
+ const [whole, fraction = ""] = trimmed.split(".");
108
+ if (fraction.length > digits) return void 0;
109
+ const amount = Number(whole) * 10 ** digits + Number(fraction.padEnd(digits, "0"));
110
+ return Number.isSafeInteger(amount) ? { amount, currency: code } : void 0;
111
+ }
112
+ function moneyToMajor(money) {
113
+ return money.amount / 10 ** minorUnitDigits(money.currency);
114
+ }
115
+ var formatters = /* @__PURE__ */ new Map();
116
+ function formatMoney(money, locale, format) {
117
+ if (format !== void 0) return formatMoneyWith(money, format, locale);
118
+ if (money.currency === "XXX") return void 0;
119
+ const key = `${money.currency}:${locale ?? ""}`;
120
+ let formatter = formatters.get(key);
121
+ if (!formatter) {
122
+ try {
123
+ formatter = new Intl.NumberFormat(locale, { style: "currency", currency: money.currency });
124
+ } catch {
125
+ return void 0;
126
+ }
127
+ formatters.set(key, formatter);
128
+ }
129
+ return formatter.format(moneyToMajor(money));
130
+ }
131
+ var POSITIONS = ["left", "right", "left_space", "right_space"];
132
+ function formatMoneyWith(money, format, locale) {
133
+ if (money.currency === "XXX") return void 0;
134
+ const minor = minorUnitDigits(money.currency);
135
+ const decimals = format.decimals ?? minor;
136
+ const abs = Math.abs(money.amount);
137
+ const major = decimals >= minor ? abs / 10 ** minor : Math.round(abs / 10 ** (minor - decimals)) / 10 ** decimals;
138
+ let parts;
139
+ try {
140
+ parts = new Intl.NumberFormat(locale, {
141
+ style: "currency",
142
+ currency: money.currency,
143
+ minimumFractionDigits: decimals,
144
+ maximumFractionDigits: decimals,
145
+ numberingSystem: "latn"
146
+ }).formatToParts(major);
147
+ } catch {
148
+ return void 0;
149
+ }
150
+ const text = (...types) => parts.filter((p) => types.includes(p.type)).map((p) => p.value).join("");
151
+ const { thousandSeparator, decimalSeparator } = format;
152
+ const position = format.position !== void 0 && POSITIONS.includes(format.position) ? format.position : void 0;
153
+ const integer = thousandSeparator === void 0 ? text("integer", "group") : text("integer").replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
154
+ const number = integer + (decimals > 0 ? (decimalSeparator ?? text("decimal")) + text("fraction") : "");
155
+ const symbol = format.symbol ?? text("currency");
156
+ const left = position ? position.startsWith("left") : parts.findIndex((p) => p.type === "currency") < parts.findIndex((p) => p.type === "integer");
157
+ const gap = position ? position.endsWith("_space") ? " " : "" : text("literal");
158
+ return (money.amount < 0 && major > 0 ? "-" : "") + (left ? symbol + gap + number : number + gap + symbol);
159
+ }
160
+ function normalizeMoneyText(text, format) {
161
+ if (format === void 0 || !format.decimalSeparator && !format.thousandSeparator) return text;
162
+ const decimal = format.decimalSeparator || ".";
163
+ const thousands = format.thousandSeparator === decimal ? "" : format.thousandSeparator || "";
164
+ const trimmed = text.trim();
165
+ if ([".", ","].some((sep) => sep !== decimal && sep !== thousands && trimmed.includes(sep))) return text;
166
+ const [whole = "", fraction, ...more] = trimmed.split(decimal);
167
+ if (more.length > 0 || fraction !== void 0 && /\D/.test(fraction)) return text;
168
+ let integer = whole;
169
+ if (thousands && whole.includes(thousands)) {
170
+ const groups = whole.split(thousands);
171
+ if (/^-?[1-9]\d{0,2}$/.test(groups[0] ?? "") && groups.slice(1).every((g) => /^\d{3}$/.test(g))) integer = groups.join("");
172
+ else if (fraction === void 0 && groups.length === 2 && (thousands === "." || thousands === ",") && !/^\d{3}$/.test(groups[1] ?? "")) integer = groups.join(".");
173
+ else return text;
174
+ }
175
+ const t = fraction === void 0 ? integer : `${integer}.${fraction}`;
176
+ if (!/^-?(\d+(?:\.\d*)?|\.\d+)$/.test(t)) return text;
177
+ return t.replace(/^(-?)\./, (_, sign) => `${sign}0.`).replace(/\.$/, "");
178
+ }
179
+ function resolvePrice(prices, currency) {
180
+ const code = (currency ?? prices[0]?.currency)?.toUpperCase();
181
+ const inCurrency = prices.filter((p) => p.currency === code);
182
+ const base = inCurrency.find((p) => p.kind === "base");
183
+ const sale = inCurrency.find((p) => p.kind === "sale");
184
+ const strip = (p) => ({
185
+ amount: p.amount,
186
+ currency: p.currency,
187
+ ...p.taxInclusive !== void 0 ? { taxInclusive: p.taxInclusive } : {}
188
+ });
189
+ if (sale && (!base || sale.amount < base.amount)) {
190
+ return { current: strip(sale), was: base ? strip(base) : void 0 };
191
+ }
192
+ return base ? { current: strip(base) } : void 0;
193
+ }
194
+ function resolvePriceRange(variants, currency) {
195
+ let range;
196
+ for (const variant of variants) {
197
+ const resolved = resolvePrice(variant.prices, currency);
198
+ if (!resolved) continue;
199
+ const money = resolved.current;
200
+ if (!range) {
201
+ range = { min: money, max: money };
202
+ } else if (money.currency === range.min.currency) {
203
+ if (money.amount < range.min.amount) range.min = money;
204
+ if (money.amount > range.max.amount) range.max = money;
205
+ }
206
+ }
207
+ return range;
208
+ }
209
+
210
+ // src/server/money.ts
211
+ function currencyDecimals(currency) {
212
+ return new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits;
213
+ }
214
+ function minorToMajor(minor, decimals) {
215
+ if (!Number.isSafeInteger(minor)) throw new RangeError("minor must be a safe integer");
216
+ const sign = minor < 0 ? "-" : "";
217
+ const digits = Math.abs(minor).toString().padStart(decimals + 1, "0");
218
+ return sign + (decimals === 0 ? digits : `${digits.slice(0, -decimals)}.${digits.slice(-decimals)}`);
219
+ }
220
+ function majorToMinor(value, decimals) {
221
+ const match = /^([+-]?)(\d+(?:\.\d*)?|\.\d+)(?:e([+-]?\d+))?$/i.exec(String(value));
222
+ if (!match) throw new RangeError("value must be a finite decimal");
223
+ const [, sign, mantissa, exponent = "0"] = match;
224
+ const [whole, fraction = ""] = mantissa.split(".");
225
+ const coefficient = BigInt(whole + fraction);
226
+ const shift = BigInt(decimals) + BigInt(exponent) - BigInt(fraction.length);
227
+ let rounded;
228
+ if (shift >= 0n) {
229
+ rounded = coefficient * 10n ** shift;
230
+ } else {
231
+ const divisor = 10n ** -shift;
232
+ rounded = coefficient / divisor + (coefficient % divisor * 2n >= divisor ? 1n : 0n);
233
+ }
234
+ const minor = Number(sign === "-" ? -rounded : rounded);
235
+ if (!Number.isSafeInteger(minor)) throw new RangeError("minor amount exceeds safe integer range");
236
+ return minor;
237
+ }
238
+
239
+ // src/server/command-result.ts
240
+ var CommandResultError = class extends Error {
241
+ constructor(message) {
242
+ super(message);
243
+ this.name = "CommandResultError";
244
+ }
245
+ };
246
+ function parseCommandResult(value) {
247
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
248
+ throw new CommandResultError("Invalid result: expected object");
249
+ }
250
+ const input = value;
251
+ if (typeof input.id !== "string" || input.id.length === 0) {
252
+ throw new CommandResultError("Invalid id");
253
+ }
254
+ if (input.status !== "applied" && input.status !== "duplicate" && input.status !== "rejected") {
255
+ throw new CommandResultError("Invalid status");
256
+ }
257
+ const result = { id: input.id, status: input.status };
258
+ const object = (value2) => typeof value2 === "object" && value2 !== null && (Object.getPrototypeOf(value2) === Object.prototype || Object.getPrototypeOf(value2) === null);
259
+ if (input.serverRefs !== void 0) {
260
+ if (typeof input.serverRefs !== "object" || input.serverRefs === null || Array.isArray(input.serverRefs)) {
261
+ throw new CommandResultError("Invalid serverRefs");
262
+ }
263
+ const refs = input.serverRefs;
264
+ if (typeof refs.orderId !== "string" || refs.orderId.length === 0) {
265
+ throw new CommandResultError("Invalid serverRefs.orderId");
266
+ }
267
+ if (refs.displayId !== void 0 && typeof refs.displayId !== "string") {
268
+ throw new CommandResultError("Invalid serverRefs.displayId");
269
+ }
270
+ if (!Number.isSafeInteger(refs.totalMinor)) {
271
+ throw new CommandResultError("Invalid serverRefs.totalMinor");
272
+ }
273
+ result.serverRefs = { orderId: refs.orderId, totalMinor: refs.totalMinor };
274
+ if (refs.displayId !== void 0) result.serverRefs.displayId = refs.displayId;
275
+ }
276
+ if (input.register !== void 0) {
277
+ if (!object(input.register)) throw new CommandResultError("Invalid register");
278
+ result.register = input.register;
279
+ }
280
+ if (input.refund !== void 0) {
281
+ if (!object(input.refund)) throw new CommandResultError("Invalid refund");
282
+ const refund = input.refund;
283
+ if (!Number.isSafeInteger(refund.totalMinor) || refund.totalMinor < 0) throw new CommandResultError("Invalid refund.totalMinor");
284
+ if (!object(refund.byMethod)) throw new CommandResultError("Invalid refund.byMethod");
285
+ const byMethod = Object.fromEntries(Object.entries(refund.byMethod).map(([key, amount]) => {
286
+ if (!key.length) throw new CommandResultError("Invalid refund.byMethod");
287
+ if (!Number.isSafeInteger(amount) || amount < 0) throw new CommandResultError(`Invalid refund.byMethod.${key}`);
288
+ return [key, amount];
289
+ }));
290
+ if (Object.values(byMethod).reduce((sum, amount) => sum + amount, 0) !== refund.totalMinor) throw new CommandResultError("Invalid refund.byMethod");
291
+ if (!Array.isArray(refund.refunds) || refund.refunds.length === 0) throw new CommandResultError("Invalid refund.refunds");
292
+ const refunds = refund.refunds.map((value2, index) => {
293
+ const field = `refund.refunds[${index}]`;
294
+ if (!object(value2)) throw new CommandResultError(`Invalid ${field}`);
295
+ const entry = value2;
296
+ for (const key of ["id", "paymentId"]) {
297
+ if (typeof entry[key] !== "string" || entry[key].length === 0) throw new CommandResultError(`Invalid ${field}.${key}`);
298
+ }
299
+ if (!Number.isSafeInteger(entry.totalMinor) || entry.totalMinor < 0) throw new CommandResultError(`Invalid ${field}.totalMinor`);
300
+ if (typeof entry.state !== "string" || entry.state.length === 0) throw new CommandResultError(`Invalid ${field}.state`);
301
+ return { id: entry.id, paymentId: entry.paymentId, totalMinor: entry.totalMinor, state: entry.state };
302
+ });
303
+ if (refunds.reduce((sum, entry) => sum + entry.totalMinor, 0) !== refund.totalMinor) throw new CommandResultError("Invalid refund.refunds");
304
+ result.refund = { totalMinor: refund.totalMinor, byMethod, refunds };
305
+ }
306
+ if (input.reopen !== void 0) {
307
+ if (!object(input.reopen)) throw new CommandResultError("Invalid reopen");
308
+ const reopen = input.reopen;
309
+ if (typeof reopen.orderId !== "string" || reopen.orderId.length === 0) throw new CommandResultError("Invalid reopen.orderId");
310
+ if (typeof reopen.status !== "string" || reopen.status.length === 0) throw new CommandResultError("Invalid reopen.status");
311
+ if (reopen.revision !== void 0 && (typeof reopen.revision !== "string" || reopen.revision.length === 0)) throw new CommandResultError("Invalid reopen.revision");
312
+ result.reopen = { orderId: reopen.orderId, status: reopen.status };
313
+ if (reopen.revision !== void 0) result.reopen.revision = reopen.revision;
314
+ }
315
+ if (result.status === "applied" && result.serverRefs === void 0 && result.register === void 0 && result.refund === void 0 && result.reopen === void 0) {
316
+ throw new CommandResultError("Invalid serverRefs: required for applied");
317
+ }
318
+ if (input.warnings !== void 0) {
319
+ if (!Array.isArray(input.warnings)) {
320
+ throw new CommandResultError("Invalid warnings");
321
+ }
322
+ result.warnings = input.warnings.map((warning, index) => {
323
+ const field = `warnings[${index}]`;
324
+ if (typeof warning !== "object" || warning === null || Array.isArray(warning)) {
325
+ throw new CommandResultError(`Invalid ${field}`);
326
+ }
327
+ const item = warning;
328
+ if (item.code === "total_mismatch") {
329
+ for (const key of ["expectedMinor", "serverMinor"]) {
330
+ if (!Number.isInteger(item[key])) {
331
+ throw new CommandResultError(`Invalid ${field}.${key}`);
332
+ }
333
+ }
334
+ if (item.bridgeMinor != null && !Number.isSafeInteger(item.bridgeMinor)) {
335
+ throw new CommandResultError(`Invalid ${field}.bridgeMinor`);
336
+ }
337
+ return item.bridgeMinor != null ? { code: item.code, expectedMinor: item.expectedMinor, serverMinor: item.serverMinor, bridgeMinor: item.bridgeMinor } : { code: item.code, expectedMinor: item.expectedMinor, serverMinor: item.serverMinor };
338
+ }
339
+ if (item.code === "insufficient_stock") {
340
+ if (typeof item.variantId !== "string" || item.variantId.length === 0) {
341
+ throw new CommandResultError(`Invalid ${field}.variantId`);
342
+ }
343
+ if (!Number.isInteger(item.quantity) || item.quantity < 1) {
344
+ throw new CommandResultError(`Invalid ${field}.quantity`);
345
+ }
346
+ return { code: item.code, variantId: item.variantId, quantity: item.quantity };
347
+ }
348
+ if (item.code === "tax_rate_mismatch") {
349
+ if (!Number.isSafeInteger(item.ratePpm) || item.ratePpm < 0) {
350
+ throw new CommandResultError(`Invalid ${field}.ratePpm`);
351
+ }
352
+ for (const key of ["expectedMinor", "serverMinor"]) {
353
+ if (!Number.isSafeInteger(item[key])) {
354
+ throw new CommandResultError(`Invalid ${field}.${key}`);
355
+ }
356
+ }
357
+ return { code: item.code, ratePpm: item.ratePpm, expectedMinor: item.expectedMinor, serverMinor: item.serverMinor };
358
+ }
359
+ if (item.code === "customer_ignored") {
360
+ if (typeof item.customerId !== "string" || item.customerId.length === 0 || item.customerId.length > 64) {
361
+ throw new CommandResultError(`Invalid ${field}.customerId`);
362
+ }
363
+ return { code: item.code, customerId: item.customerId };
364
+ }
365
+ if (item.code === "register_session_unknown") {
366
+ if (typeof item.sessionId !== "string" || item.sessionId.length === 0 || item.sessionId.length > 64) {
367
+ throw new CommandResultError(`Invalid ${field}.sessionId`);
368
+ }
369
+ return { code: item.code, sessionId: item.sessionId };
370
+ }
371
+ if (item.code === "figures_mismatch") {
372
+ if (!Array.isArray(item.fields) || item.fields.length === 0) throw new CommandResultError(`Invalid ${field}.fields`);
373
+ const seen = [];
374
+ return { code: item.code, fields: item.fields.map((value2, i) => {
375
+ const path = `${field}.fields[${i}]`;
376
+ if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) throw new CommandResultError(`Invalid ${path}`);
377
+ const entry = value2;
378
+ if (!["subtotalMinor", "taxMinor", "discountMinor"].includes(entry.field) || seen.includes(entry.field)) {
379
+ throw new CommandResultError(`Invalid ${path}.field`);
380
+ }
381
+ seen.push(entry.field);
382
+ if (!Number.isSafeInteger(entry.tillMinor)) throw new CommandResultError(`Invalid ${path}.tillMinor`);
383
+ if (!Number.isSafeInteger(entry.serverMinor) || entry.serverMinor === entry.tillMinor) throw new CommandResultError(`Invalid ${path}.serverMinor`);
384
+ return { field: entry.field, tillMinor: entry.tillMinor, serverMinor: entry.serverMinor };
385
+ }) };
386
+ }
387
+ if (item.code === "line_figures_mismatch") {
388
+ if (!Array.isArray(item.lines) || item.lines.length === 0) throw new CommandResultError(`Invalid ${field}.lines`);
389
+ const seen = [];
390
+ return { code: item.code, lines: item.lines.map((value2, i) => {
391
+ const path = `${field}.lines[${i}]`;
392
+ if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) throw new CommandResultError(`Invalid ${path}`);
393
+ const entry = value2;
394
+ if (typeof entry.lineId !== "string" || entry.lineId.length === 0 || entry.lineId.length > 64) throw new CommandResultError(`Invalid ${path}.lineId`);
395
+ const key = JSON.stringify([entry.lineId, entry.field]);
396
+ if (!["subtotalMinor", "taxMinor", "discountMinor", "totalMinor"].includes(entry.field) || seen.includes(key)) {
397
+ throw new CommandResultError(`Invalid ${path}.field`);
398
+ }
399
+ seen.push(key);
400
+ if (!Number.isSafeInteger(entry.tillMinor)) throw new CommandResultError(`Invalid ${path}.tillMinor`);
401
+ if (!Number.isSafeInteger(entry.serverMinor) || entry.serverMinor === entry.tillMinor) throw new CommandResultError(`Invalid ${path}.serverMinor`);
402
+ return { lineId: entry.lineId, field: entry.field, tillMinor: entry.tillMinor, serverMinor: entry.serverMinor };
403
+ }) };
404
+ }
405
+ throw new CommandResultError(`Invalid ${field}.code`);
406
+ });
407
+ }
408
+ if (input.error !== void 0) {
409
+ if (typeof input.error !== "object" || input.error === null || Array.isArray(input.error)) {
410
+ throw new CommandResultError("Invalid error");
411
+ }
412
+ const error = input.error;
413
+ if (typeof error.code !== "string" || error.code.length === 0) {
414
+ throw new CommandResultError("Invalid error.code");
415
+ }
416
+ if (typeof error.message !== "string") {
417
+ throw new CommandResultError("Invalid error.message");
418
+ }
419
+ result.error = { code: error.code, message: error.message };
420
+ if (error.data !== void 0) {
421
+ if (!object(error.data)) throw new CommandResultError("Invalid error.data");
422
+ result.error.data = error.data;
423
+ }
424
+ }
425
+ if (result.status === "rejected" && result.error === void 0) {
426
+ throw new CommandResultError("Invalid error: required for rejected");
427
+ }
428
+ return result;
429
+ }
430
+
431
+ // src/server/register-figures.ts
432
+ function deriveSessionFigures(input) {
433
+ const expected = Object.assign(/* @__PURE__ */ Object.create(null), { cash: input.countedFloatMinor });
434
+ for (const order of input.orders) {
435
+ if (!Array.isArray(order.payments)) continue;
436
+ for (const payment of order.payments) {
437
+ if (typeof payment?.method !== "string" || !payment.method.length || !Number.isSafeInteger(payment.amountMinor)) continue;
438
+ expected[payment.method] = (expected[payment.method] ?? 0) + payment.amountMinor;
439
+ }
440
+ }
441
+ const voided = new Set(input.movements.filter((row) => row.type === "void").map((row) => row.voids));
442
+ for (const row of input.movements) {
443
+ if (row.type === "void" || voided.has(row.id)) continue;
444
+ if (row.type === "paid_in") expected.cash += row.amountMinor;
445
+ if (row.type === "paid_out") expected.cash -= row.amountMinor;
446
+ }
447
+ let refundsTotalMinor = 0;
448
+ for (const refund of input.refunds ?? []) {
449
+ if (typeof refund !== "object" || refund === null) continue;
450
+ const byMethod = refund.byMethod;
451
+ if (typeof byMethod !== "object" || byMethod === null || Object.getPrototypeOf(byMethod) !== Object.prototype && Object.getPrototypeOf(byMethod) !== null) continue;
452
+ for (const [method, amount] of Object.entries(byMethod)) {
453
+ if (!method.length || !Number.isSafeInteger(amount) || amount < 0) continue;
454
+ expected[method] = (expected[method] ?? 0) - amount;
455
+ refundsTotalMinor += amount;
456
+ }
457
+ }
458
+ return {
459
+ expected: { ...expected },
460
+ salesCount: input.orders.length,
461
+ ...input.refunds !== void 0 ? { refundsTotalMinor } : {}
462
+ };
463
+ }
464
+ function deriveVariance(counted, expected) {
465
+ return Object.fromEntries(Object.entries(counted).map(([key, value]) => [key, value - (expected[key] ?? 0)]));
466
+ }
467
+
468
+ // src/server/tax-rate.ts
469
+ function ratePpmFromPercent(percent) {
470
+ const value = String(percent);
471
+ const match = /^(\d+)(?:\.(\d{1,4}))?$/.exec(value);
472
+ if (!match || match[0] !== value) {
473
+ throw new RangeError("Percent must be a plain decimal with at most four fractional digits");
474
+ }
475
+ const ratePpm = BigInt(match[1]) * 10000n + BigInt((match[2] ?? "").padEnd(4, "0"));
476
+ if (ratePpm > BigInt(Number.MAX_SAFE_INTEGER)) {
477
+ throw new RangeError("Rate must be a safe integer");
478
+ }
479
+ return Number(ratePpm);
480
+ }
481
+
482
+ export {
483
+ DISPLAY_PAIR_CAPABILITY,
484
+ DisplaySignallingError,
485
+ rateLimitSource,
486
+ COMMANDS_PATH,
487
+ PROTOCOL_HEADER,
488
+ PROTOCOL_VERSION,
489
+ MAX_COMMANDS_PER_BATCH,
490
+ ORDER_NOTE_MAX,
491
+ ORDER_TAX_IDS_MAX,
492
+ ORDER_TAX_ID_TYPE_MAX,
493
+ ORDER_TAX_ID_VALUE_MAX,
494
+ ORDER_META_MAX,
495
+ ORDER_META_KEY_MAX,
496
+ ORDER_LINE_SKU_MAX,
497
+ isCommandBatchResponse,
498
+ minorUnitDigits,
499
+ currencySymbol,
500
+ moneyFromMajor,
501
+ moneyFromDecimalString,
502
+ moneyToMajor,
503
+ formatMoney,
504
+ normalizeMoneyText,
505
+ resolvePrice,
506
+ resolvePriceRange,
507
+ currencyDecimals,
508
+ minorToMajor,
509
+ majorToMinor,
510
+ CommandResultError,
511
+ parseCommandResult,
512
+ deriveSessionFigures,
513
+ deriveVariance,
514
+ ratePpmFromPercent
515
+ };