@tallyui/core 3.9.1 → 3.10.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.
@@ -0,0 +1,185 @@
1
+ // src/commands.ts
2
+ var COMMANDS_PATH = "/tally/v1/commands";
3
+ var PROTOCOL_HEADER = "X-Tally-Protocol";
4
+ var PROTOCOL_VERSION = 1;
5
+ var MAX_COMMANDS_PER_BATCH = 50;
6
+ function isCommandBatchResponse(value) {
7
+ return typeof value === "object" && value !== null && "results" in value && Array.isArray(value.results) && value.results.every(
8
+ (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")
9
+ );
10
+ }
11
+
12
+ // src/server/command-result.ts
13
+ var CommandResultError = class extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = "CommandResultError";
17
+ }
18
+ };
19
+ function parseCommandResult(value) {
20
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
21
+ throw new CommandResultError("Invalid result: expected object");
22
+ }
23
+ const input = value;
24
+ if (typeof input.id !== "string" || input.id.length === 0) {
25
+ throw new CommandResultError("Invalid id");
26
+ }
27
+ if (input.status !== "applied" && input.status !== "duplicate" && input.status !== "rejected") {
28
+ throw new CommandResultError("Invalid status");
29
+ }
30
+ const result = { id: input.id, status: input.status };
31
+ const object = (value2) => typeof value2 === "object" && value2 !== null && (Object.getPrototypeOf(value2) === Object.prototype || Object.getPrototypeOf(value2) === null);
32
+ if (input.serverRefs !== void 0) {
33
+ if (typeof input.serverRefs !== "object" || input.serverRefs === null || Array.isArray(input.serverRefs)) {
34
+ throw new CommandResultError("Invalid serverRefs");
35
+ }
36
+ const refs = input.serverRefs;
37
+ if (typeof refs.orderId !== "string" || refs.orderId.length === 0) {
38
+ throw new CommandResultError("Invalid serverRefs.orderId");
39
+ }
40
+ if (refs.displayId !== void 0 && typeof refs.displayId !== "string") {
41
+ throw new CommandResultError("Invalid serverRefs.displayId");
42
+ }
43
+ if (!Number.isSafeInteger(refs.totalMinor)) {
44
+ throw new CommandResultError("Invalid serverRefs.totalMinor");
45
+ }
46
+ result.serverRefs = { orderId: refs.orderId, totalMinor: refs.totalMinor };
47
+ if (refs.displayId !== void 0) result.serverRefs.displayId = refs.displayId;
48
+ }
49
+ if (input.register !== void 0) {
50
+ if (!object(input.register)) throw new CommandResultError("Invalid register");
51
+ result.register = input.register;
52
+ }
53
+ if (input.refund !== void 0) {
54
+ if (!object(input.refund)) throw new CommandResultError("Invalid refund");
55
+ const refund = input.refund;
56
+ if (!Number.isSafeInteger(refund.totalMinor) || refund.totalMinor < 0) throw new CommandResultError("Invalid refund.totalMinor");
57
+ if (!object(refund.byMethod)) throw new CommandResultError("Invalid refund.byMethod");
58
+ const byMethod = Object.fromEntries(Object.entries(refund.byMethod).map(([key, amount]) => {
59
+ if (!key.length) throw new CommandResultError("Invalid refund.byMethod");
60
+ if (!Number.isSafeInteger(amount) || amount < 0) throw new CommandResultError(`Invalid refund.byMethod.${key}`);
61
+ return [key, amount];
62
+ }));
63
+ if (Object.values(byMethod).reduce((sum, amount) => sum + amount, 0) !== refund.totalMinor) throw new CommandResultError("Invalid refund.byMethod");
64
+ if (!Array.isArray(refund.refunds) || refund.refunds.length === 0) throw new CommandResultError("Invalid refund.refunds");
65
+ const refunds = refund.refunds.map((value2, index) => {
66
+ const field = `refund.refunds[${index}]`;
67
+ if (!object(value2)) throw new CommandResultError(`Invalid ${field}`);
68
+ const entry = value2;
69
+ for (const key of ["id", "paymentId"]) {
70
+ if (typeof entry[key] !== "string" || entry[key].length === 0) throw new CommandResultError(`Invalid ${field}.${key}`);
71
+ }
72
+ if (!Number.isSafeInteger(entry.totalMinor) || entry.totalMinor < 0) throw new CommandResultError(`Invalid ${field}.totalMinor`);
73
+ if (typeof entry.state !== "string" || entry.state.length === 0) throw new CommandResultError(`Invalid ${field}.state`);
74
+ return { id: entry.id, paymentId: entry.paymentId, totalMinor: entry.totalMinor, state: entry.state };
75
+ });
76
+ if (refunds.reduce((sum, entry) => sum + entry.totalMinor, 0) !== refund.totalMinor) throw new CommandResultError("Invalid refund.refunds");
77
+ result.refund = { totalMinor: refund.totalMinor, byMethod, refunds };
78
+ }
79
+ if (result.status === "applied" && result.serverRefs === void 0 && result.register === void 0 && result.refund === void 0) {
80
+ throw new CommandResultError("Invalid serverRefs: required for applied");
81
+ }
82
+ if (input.warnings !== void 0) {
83
+ if (!Array.isArray(input.warnings)) {
84
+ throw new CommandResultError("Invalid warnings");
85
+ }
86
+ result.warnings = input.warnings.map((warning, index) => {
87
+ const field = `warnings[${index}]`;
88
+ if (typeof warning !== "object" || warning === null || Array.isArray(warning)) {
89
+ throw new CommandResultError(`Invalid ${field}`);
90
+ }
91
+ const item = warning;
92
+ if (item.code === "total_mismatch") {
93
+ for (const key of ["expectedMinor", "serverMinor"]) {
94
+ if (!Number.isInteger(item[key])) {
95
+ throw new CommandResultError(`Invalid ${field}.${key}`);
96
+ }
97
+ }
98
+ if (item.bridgeMinor != null && !Number.isSafeInteger(item.bridgeMinor)) {
99
+ throw new CommandResultError(`Invalid ${field}.bridgeMinor`);
100
+ }
101
+ 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 };
102
+ }
103
+ if (item.code === "insufficient_stock") {
104
+ if (typeof item.variantId !== "string" || item.variantId.length === 0) {
105
+ throw new CommandResultError(`Invalid ${field}.variantId`);
106
+ }
107
+ if (!Number.isInteger(item.quantity) || item.quantity < 1) {
108
+ throw new CommandResultError(`Invalid ${field}.quantity`);
109
+ }
110
+ return { code: item.code, variantId: item.variantId, quantity: item.quantity };
111
+ }
112
+ if (item.code === "tax_rate_mismatch") {
113
+ if (!Number.isSafeInteger(item.ratePpm) || item.ratePpm < 0) {
114
+ throw new CommandResultError(`Invalid ${field}.ratePpm`);
115
+ }
116
+ for (const key of ["expectedMinor", "serverMinor"]) {
117
+ if (!Number.isSafeInteger(item[key])) {
118
+ throw new CommandResultError(`Invalid ${field}.${key}`);
119
+ }
120
+ }
121
+ return { code: item.code, ratePpm: item.ratePpm, expectedMinor: item.expectedMinor, serverMinor: item.serverMinor };
122
+ }
123
+ if (item.code === "customer_ignored") {
124
+ if (typeof item.customerId !== "string" || item.customerId.length === 0 || item.customerId.length > 64) {
125
+ throw new CommandResultError(`Invalid ${field}.customerId`);
126
+ }
127
+ return { code: item.code, customerId: item.customerId };
128
+ }
129
+ if (item.code === "register_session_unknown") {
130
+ if (typeof item.sessionId !== "string" || item.sessionId.length === 0 || item.sessionId.length > 64) {
131
+ throw new CommandResultError(`Invalid ${field}.sessionId`);
132
+ }
133
+ return { code: item.code, sessionId: item.sessionId };
134
+ }
135
+ if (item.code === "figures_mismatch") {
136
+ if (!Array.isArray(item.fields) || item.fields.length === 0) throw new CommandResultError(`Invalid ${field}.fields`);
137
+ const seen = [];
138
+ return { code: item.code, fields: item.fields.map((value2, i) => {
139
+ const path = `${field}.fields[${i}]`;
140
+ if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) throw new CommandResultError(`Invalid ${path}`);
141
+ const entry = value2;
142
+ if (!["subtotalMinor", "taxMinor", "discountMinor"].includes(entry.field) || seen.includes(entry.field)) {
143
+ throw new CommandResultError(`Invalid ${path}.field`);
144
+ }
145
+ seen.push(entry.field);
146
+ if (!Number.isSafeInteger(entry.tillMinor)) throw new CommandResultError(`Invalid ${path}.tillMinor`);
147
+ if (!Number.isSafeInteger(entry.serverMinor) || entry.serverMinor === entry.tillMinor) throw new CommandResultError(`Invalid ${path}.serverMinor`);
148
+ return { field: entry.field, tillMinor: entry.tillMinor, serverMinor: entry.serverMinor };
149
+ }) };
150
+ }
151
+ throw new CommandResultError(`Invalid ${field}.code`);
152
+ });
153
+ }
154
+ if (input.error !== void 0) {
155
+ if (typeof input.error !== "object" || input.error === null || Array.isArray(input.error)) {
156
+ throw new CommandResultError("Invalid error");
157
+ }
158
+ const error = input.error;
159
+ if (typeof error.code !== "string" || error.code.length === 0) {
160
+ throw new CommandResultError("Invalid error.code");
161
+ }
162
+ if (typeof error.message !== "string") {
163
+ throw new CommandResultError("Invalid error.message");
164
+ }
165
+ result.error = { code: error.code, message: error.message };
166
+ if (error.data !== void 0) {
167
+ if (!object(error.data)) throw new CommandResultError("Invalid error.data");
168
+ result.error.data = error.data;
169
+ }
170
+ }
171
+ if (result.status === "rejected" && result.error === void 0) {
172
+ throw new CommandResultError("Invalid error: required for rejected");
173
+ }
174
+ return result;
175
+ }
176
+
177
+ export {
178
+ COMMANDS_PATH,
179
+ PROTOCOL_HEADER,
180
+ PROTOCOL_VERSION,
181
+ MAX_COMMANDS_PER_BATCH,
182
+ isCommandBatchResponse,
183
+ CommandResultError,
184
+ parseCommandResult
185
+ };
@@ -7,7 +7,7 @@ interface CommandEnvelope<P = unknown> {
7
7
  /** 3 when the order carries ADR-065's `display` and `taxByRate` (the store accepts 3), else 2 when discounted, else 1;
8
8
  * 4 is 3 with every `discountMinor` tax-exclusive, built only when capped at 4 or more (#286).
9
9
  * 5 is 4 plus fees, shipping and custom lines (ADR-075), sent only for an order that has one. */
10
- version: 1 | 2 | 3 | 4 | 5;
10
+ version: 1 | 2 | 3 | 4 | 5 | 6;
11
11
  payload: P;
12
12
  createdAt: string;
13
13
  deviceId: string;
@@ -86,7 +86,7 @@ interface OrderRefundNoOpenSessionData {
86
86
  /** An order.create envelope: 5 is 4 plus fees, shipping and custom lines (ADR-075), sent only for an order that has one. */
87
87
  type OrderCreateEnvelope = CommandEnvelope<OrderCreatePayload> & {
88
88
  type: 'order.create';
89
- version: 1 | 2 | 3 | 4 | 5;
89
+ version: 1 | 2 | 3 | 4 | 5 | 6;
90
90
  };
91
91
  /** Outcome of processing a command. */
92
92
  type CommandStatus = 'applied' | 'duplicate' | 'rejected';
@@ -169,6 +169,24 @@ interface CommandError {
169
169
  /** A refusal's details, e.g. the server's supported version. */
170
170
  data?: Record<string, unknown>;
171
171
  }
172
+ /** `coupon_invalid` (order.create v6, ADR-077 d4): the store would not apply one of the order's coupons. */
173
+ interface OrderCreateCouponInvalidData {
174
+ /** The payload coupon's code, when the store can tell which one. */
175
+ couponCode?: string;
176
+ /** The store's own error code, e.g. WooCommerce's, for the log; never shown as the cashier's message. */
177
+ storeCode?: string;
178
+ }
179
+ /**
180
+ * `total_mismatch` as a refusal (order.create v6, ADR-077 R4): the store would accept the order but computes a
181
+ * different total from the envelope, so it made no order. The store's own figures, as `figures_mismatch` names them.
182
+ */
183
+ interface OrderCreateTotalMismatchData {
184
+ fields: Array<{
185
+ field: 'subtotalMinor' | 'taxMinor' | 'discountMinor' | 'totalMinor' | (string & {});
186
+ tillMinor: number;
187
+ serverMinor: number;
188
+ }>;
189
+ }
172
190
  /** Server result for a single command. */
173
191
  interface CommandResult {
174
192
  id: string;
@@ -316,6 +334,10 @@ interface OrderCreateLine {
316
334
  title?: string;
317
335
  quantity: number;
318
336
  unitPriceMinor: number;
337
+ /** Version 6 recorded figure: the product's regular (not sale) unit price, in the line's tax mode and integer minor units, when the till knew it. */
338
+ regularUnitPriceMinor?: number;
339
+ /** Version 6 recorded: the variant's attribute names and values (#495), each at most 255 characters. */
340
+ attributes?: Record<string, string>;
319
341
  /**
320
342
  * This line's own tax mode, when it differs from the order's `pricesIncludeTax`
321
343
  * (a price that carries its own flag, D2c). Absent means the order's flag, so
@@ -330,6 +352,17 @@ interface OrderCreateLine {
330
352
  */
331
353
  discountMinor?: number;
332
354
  }
355
+ /** Version 6 (ADR-077): a coupon the till applied. Recorded figures, in integer minor units of the order's currency. */
356
+ interface OrderCreateCoupon {
357
+ /** The coupon code as the store knows it, 1–255 characters. */
358
+ code: string;
359
+ /** The store's id for the coupon, 1–64 characters. */
360
+ couponId: string;
361
+ /** The discount it gave, tax-exclusive, integer >= 0. */
362
+ discountMinor: number;
363
+ /** The tax on that discount, integer >= 0. */
364
+ discountTaxMinor: number;
365
+ }
333
366
  /** Version 5: a fee, never discounted (ADR-075). */
334
367
  interface OrderCreateFee {
335
368
  /** Identity: UUID, stable for the order's life, at most 36 characters. */
@@ -396,6 +429,11 @@ interface OrderCreateDisplay {
396
429
  /** Recorded integer minor units, equal to the payload shipping amount. */
397
430
  amountMinor: number;
398
431
  }>;
432
+ /** Version 6 recorded figures: one row per payload coupon, its discount in the display tax mode. */
433
+ coupons?: Array<{
434
+ code: string;
435
+ amountMinor: number;
436
+ }>;
399
437
  }
400
438
  /** Version 3 (ADR-065): one tax rate's net, tax and gross, as the receipt's tax summary splits them. */
401
439
  interface OrderCreateTaxRate {
@@ -416,10 +454,15 @@ interface OrderCreatePayload {
416
454
  fees?: OrderCreateFee[];
417
455
  /** Version 5 instructions: shipping in the order's tax mode; omitted when none. */
418
456
  shipping?: OrderCreateShipping[];
457
+ /** Version 6 (ADR-077): the coupons the till applied, in the order it applied them; omitted when none.
458
+ * The store re-applies them by `code` and refuses the order with `coupon_invalid` if one no longer applies. */
459
+ coupons?: OrderCreateCoupon[];
460
+ /** Version 6: net of the coupons' `discountMinor`, as `taxMinor` is of their `discountTaxMinor`; coupons are not part of `discountMinor`. */
419
461
  subtotalMinor: number;
420
462
  /**
421
463
  * Version 2 (ADR-062): the order's total discount, equal to Σ `lines[].discountMinor`. Present only when above 0.
422
464
  * Version 4+ (#286) means every `discountMinor`, this and each line's, is tax-exclusive, so the sum still holds.
465
+ * Version 6: coupons are not included; their amounts are in `coupons[].discountMinor`.
423
466
  */
424
467
  discountMinor?: number;
425
468
  taxMinor: number;
@@ -470,4 +513,13 @@ declare const MAX_COMMANDS_PER_BATCH = 50;
470
513
  */
471
514
  declare function isCommandBatchResponse(value: unknown): value is CommandBatchResponse;
472
515
 
473
- export { type AnyCommandEnvelope as A, type BatchTooLargeBody as B, type CommandWarning as C, type RegisterCommandResult as D, type RegisterCommandType as E, type RegisterMovementRecordPayload as F, type RegisterMovementVoidPayload as G, type RegisterSessionAlreadyOpenData as H, type RegisterSessionOpenPayload as I, type RegisterSessionSupersededData as J, type RegisterSessionTransitionPayload as K, isCommandBatchResponse as L, MAX_COMMANDS_PER_BATCH as M, type OrderCreateDisplay as O, PROTOCOL_HEADER as P, type RegisterClosureSubmitPayload as R, COMMANDS_PATH as a, type CommandBatchRequest as b, type CommandBatchResponse as c, type CommandEnvelope as d, type CommandError as e, type CommandResult as f, type CommandServerRefs as g, type CommandStatus as h, type CommandType as i, type OrderCreateEnvelope as j, type OrderCreateLine as k, type OrderCreatePayload as l, type OrderCreatePayment as m, type OrderCreateTaxRate as n, type OrderRefundAmountMismatchData as o, type OrderRefundEnvelope as p, type OrderRefundLine as q, type OrderRefundNoOpenSessionData as r, type OrderRefundOrderStateData as s, type OrderRefundPayload as t, type OrderRefundQuantityExceedsData as u, type OrderRefundRejectionCode as v, type OrderRefundResult as w, PROTOCOL_VERSION as x, type PaymentMethodKind as y, type RegisterCommandEnvelope as z };
516
+ /** parseCommandResult's refusal; its message names the first bad field. A plugin maps it
517
+ * to its own invalid-data error (e.g. Medusa's MedusaError INVALID_DATA). */
518
+ declare class CommandResultError extends Error {
519
+ constructor(message: string);
520
+ }
521
+ /** Validates a CommandResult (e.g. one read back from the ledger). Throws
522
+ * CommandResultError naming the first bad field. */
523
+ declare function parseCommandResult(value: unknown): CommandResult;
524
+
525
+ export { type AnyCommandEnvelope as A, type BatchTooLargeBody as B, type CommandWarning as C, type OrderRefundResult as D, PROTOCOL_VERSION as E, type PaymentMethodKind as F, type RegisterCommandEnvelope as G, type RegisterCommandResult as H, type RegisterCommandType as I, type RegisterMovementRecordPayload as J, type RegisterMovementVoidPayload as K, type RegisterSessionAlreadyOpenData as L, MAX_COMMANDS_PER_BATCH as M, type RegisterSessionOpenPayload as N, type OrderCreateCoupon as O, PROTOCOL_HEADER as P, type RegisterSessionSupersededData as Q, type RegisterClosureSubmitPayload as R, type RegisterSessionTransitionPayload as S, isCommandBatchResponse as T, parseCommandResult as U, COMMANDS_PATH as a, type CommandBatchRequest as b, type CommandBatchResponse as c, type CommandEnvelope as d, type CommandError as e, type CommandResult as f, CommandResultError as g, type CommandServerRefs as h, type CommandStatus as i, type CommandType as j, type OrderCreateCouponInvalidData as k, type OrderCreateDisplay as l, type OrderCreateEnvelope as m, type OrderCreateLine as n, type OrderCreatePayload as o, type OrderCreatePayment as p, type OrderCreateTaxRate as q, type OrderCreateTotalMismatchData as r, type OrderRefundAmountMismatchData as s, type OrderRefundEnvelope as t, type OrderRefundLine as u, type OrderRefundNoOpenSessionData as v, type OrderRefundOrderStateData as w, type OrderRefundPayload as x, type OrderRefundQuantityExceedsData as y, type OrderRefundRejectionCode as z };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { RxReplicationPullStreamItem, RxReplicationWriteToMasterRow, RxJsonSchema } from 'rxdb';
2
2
  import { Observable } from 'rxjs';
3
- import { C as CommandWarning } from './commands-BPNfbeF9.js';
4
- export { A as AnyCommandEnvelope, B as BatchTooLargeBody, a as COMMANDS_PATH, b as CommandBatchRequest, c as CommandBatchResponse, d as CommandEnvelope, e as CommandError, f as CommandResult, g as CommandServerRefs, h as CommandStatus, i as CommandType, M as MAX_COMMANDS_PER_BATCH, O as OrderCreateDisplay, j as OrderCreateEnvelope, k as OrderCreateLine, l as OrderCreatePayload, m as OrderCreatePayment, n as OrderCreateTaxRate, o as OrderRefundAmountMismatchData, p as OrderRefundEnvelope, q as OrderRefundLine, r as OrderRefundNoOpenSessionData, s as OrderRefundOrderStateData, t as OrderRefundPayload, u as OrderRefundQuantityExceedsData, v as OrderRefundRejectionCode, w as OrderRefundResult, P as PROTOCOL_HEADER, x as PROTOCOL_VERSION, y as PaymentMethodKind, R as RegisterClosureSubmitPayload, z as RegisterCommandEnvelope, D as RegisterCommandResult, E as RegisterCommandType, F as RegisterMovementRecordPayload, G as RegisterMovementVoidPayload, H as RegisterSessionAlreadyOpenData, I as RegisterSessionOpenPayload, J as RegisterSessionSupersededData, K as RegisterSessionTransitionPayload, L as isCommandBatchResponse } from './commands-BPNfbeF9.js';
3
+ import { C as CommandWarning } from './command-result-DmHIPt6Z.js';
4
+ export { A as AnyCommandEnvelope, B as BatchTooLargeBody, a as COMMANDS_PATH, b as CommandBatchRequest, c as CommandBatchResponse, d as CommandEnvelope, e as CommandError, f as CommandResult, g as CommandResultError, h as CommandServerRefs, i as CommandStatus, j as CommandType, M as MAX_COMMANDS_PER_BATCH, O as OrderCreateCoupon, k as OrderCreateCouponInvalidData, l as OrderCreateDisplay, m as OrderCreateEnvelope, n as OrderCreateLine, o as OrderCreatePayload, p as OrderCreatePayment, q as OrderCreateTaxRate, r as OrderCreateTotalMismatchData, s as OrderRefundAmountMismatchData, t as OrderRefundEnvelope, u as OrderRefundLine, v as OrderRefundNoOpenSessionData, w as OrderRefundOrderStateData, x as OrderRefundPayload, y as OrderRefundQuantityExceedsData, z as OrderRefundRejectionCode, D as OrderRefundResult, P as PROTOCOL_HEADER, E as PROTOCOL_VERSION, F as PaymentMethodKind, R as RegisterClosureSubmitPayload, G as RegisterCommandEnvelope, H as RegisterCommandResult, I as RegisterCommandType, J as RegisterMovementRecordPayload, K as RegisterMovementVoidPayload, L as RegisterSessionAlreadyOpenData, N as RegisterSessionOpenPayload, Q as RegisterSessionSupersededData, S as RegisterSessionTransitionPayload, T as isCommandBatchResponse, U as parseCommandResult } from './command-result-DmHIPt6Z.js';
5
5
  import * as react_jsx_runtime from 'react/jsx-runtime';
6
6
  import { ReactNode } from 'react';
7
7
 
@@ -341,12 +341,14 @@ interface CatalogueReconcileAdapter<Doc = any, Cursor = unknown> {
341
341
  /**
342
342
  * Hand documents to the collection's pull (the reconcile feed). An entry's `key` is the local primary key when
343
343
  * there is a local copy, and otherwise the listing's key.
344
+ * A `refreshOnly` entry asks the feed to fetch the document again and is never tombstoned when the fetch omits it.
344
345
  */
345
346
  enqueue(entries: Array<{
346
347
  key: string;
347
348
  local?: Doc;
348
349
  remote?: unknown;
349
350
  tombstone?: boolean;
351
+ refreshOnly?: boolean;
350
352
  }>): void;
351
353
  /** Ids per `fetchByIds` request of the feed this adapter enqueues into: a page's `n` refetches take `ceil(n / refetchBatchSize)` budget slots (1 when unset). */
352
354
  refetchBatchSize?: number;
package/dist/index.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import {
2
2
  COMMANDS_PATH,
3
+ CommandResultError,
3
4
  MAX_COMMANDS_PER_BATCH,
4
5
  PROTOCOL_HEADER,
5
6
  PROTOCOL_VERSION,
6
- isCommandBatchResponse
7
- } from "./chunk-C4PWPOKO.js";
7
+ isCommandBatchResponse,
8
+ parseCommandResult
9
+ } from "./chunk-UFWXJAMF.js";
8
10
  import {
9
11
  __export
10
12
  } from "./chunk-MLKGABMK.js";
@@ -1750,6 +1752,7 @@ function toCouponConfigs(codes, coupons) {
1750
1752
  }
1751
1753
  export {
1752
1754
  COMMANDS_PATH,
1755
+ CommandResultError,
1753
1756
  ConnectorProvider,
1754
1757
  ConnectorUnauthorizedError,
1755
1758
  CustomerServiceError,
@@ -1775,6 +1778,7 @@ export {
1775
1778
  moneyFromDecimalString,
1776
1779
  moneyFromMajor,
1777
1780
  moneyToMajor,
1781
+ parseCommandResult,
1778
1782
  parseInfoCapabilities,
1779
1783
  parseLineTax,
1780
1784
  parseTaxRounding,
@@ -1,5 +1,5 @@
1
- import { e as CommandError, l as OrderCreatePayload, d as CommandEnvelope, z as RegisterCommandEnvelope, A as AnyCommandEnvelope, f as CommandResult, B as BatchTooLargeBody, c as CommandBatchResponse, C as CommandWarning, D as RegisterCommandResult, v as OrderRefundRejectionCode } from '../commands-BPNfbeF9.js';
2
- export { M as MAX_COMMANDS_PER_BATCH, O as OrderCreateDisplay, n as OrderCreateTaxRate } from '../commands-BPNfbeF9.js';
1
+ import { e as CommandError, o as OrderCreatePayload, d as CommandEnvelope, G as RegisterCommandEnvelope, A as AnyCommandEnvelope, f as CommandResult, B as BatchTooLargeBody, c as CommandBatchResponse, C as CommandWarning, H as RegisterCommandResult, z as OrderRefundRejectionCode } from '../command-result-DmHIPt6Z.js';
2
+ export { g as CommandResultError, M as MAX_COMMANDS_PER_BATCH, l as OrderCreateDisplay, q as OrderCreateTaxRate, U as parseCommandResult } from '../command-result-DmHIPt6Z.js';
3
3
 
4
4
  /** ISO 4217 minor-unit exponent as resolved by Intl (which rejects malformed codes); depends on the runtime's ICU data. */
5
5
  declare function currencyDecimals(currency: string): number;
@@ -128,15 +128,6 @@ type Rejection = {
128
128
  };
129
129
  declare function totalWarnings(expectedMinor: number, serverMinor: number): CommandWarning[];
130
130
 
131
- /** parseCommandResult's refusal; its message names the first bad field. A plugin maps it
132
- * to its own invalid-data error (e.g. Medusa's MedusaError INVALID_DATA). */
133
- declare class CommandResultError extends Error {
134
- constructor(message: string);
135
- }
136
- /** Validates a CommandResult (e.g. one read back from the ledger). Throws
137
- * CommandResultError naming the first bad field. */
138
- declare function parseCommandResult(value: unknown): CommandResult;
139
-
140
131
  /** Shape errors before a register command claims a ledger row. Unknown top-level keys are allowed. */
141
132
  declare function registerPayloadErrors(type: string, payload: unknown): string[];
142
133
 
@@ -189,7 +180,7 @@ type RegisterOutcome = {
189
180
 
190
181
  /** Every error.code a plugin may put on a rejected result (ADR-038 and its amendments, ADR-068),
191
182
  * except `register_approval_required`, which arrives with registers c2c. */
192
- type CommandRejectionCode = 'invalid_payload' | 'unsupported_version' | 'idempotency_mismatch' | 'store_configuration' | 'platform_error' | 'insufficient_stock' | 'unsupported_tax_mode' | 'internal_error' | OrderRejectionCode | RegisterConflictCode | OrderRefundRejectionCode;
183
+ type CommandRejectionCode = 'invalid_payload' | 'unsupported_version' | 'idempotency_mismatch' | 'store_configuration' | 'platform_error' | 'insufficient_stock' | 'unsupported_tax_mode' | 'internal_error' | 'coupon_invalid' | 'total_mismatch' | OrderRejectionCode | RegisterConflictCode | OrderRefundRejectionCode;
193
184
  /**
194
185
  * The rejected result for a platform-native error the plugin has judged permanent (a replay would fail
195
186
  * the same way, e.g. a Vendure ErrorResult code) and the contract has no code for. `platform_error` is
@@ -224,4 +215,4 @@ declare function platformErrorResult(id: string, platformCode: string, platformM
224
215
  */
225
216
  declare function internalErrorResult(id: string, correlationId: string): CommandResult;
226
217
 
227
- export { type BatchOutcome, BatchTooLargeBody, type CommandErrorWithData, type CommandRejectionCode, CommandResultError, type OrderCreatePayloadV3, type OrderRejectionCode, type RegisterConflictCode, type RegisterOutcome, type Rejection, SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_ORDER_REFUND_VERSIONS, SUPPORTED_REGISTER_VERSIONS, type ValidatedCommandEnvelope, canonicalJson, commandFingerprint, currencyDecimals, deriveSessionFigures, deriveVariance, fiscalFiguresErrors, inProgressOutcome, internalErrorResult, majorToMinor, minorToMajor, parseCommandResult, payloadBoundErrors, payloadShapeErrors, platformErrorResult, precheckCommand, refundPayloadErrors, registerPayloadErrors, totalWarnings, transientOutcome, validateBatch };
218
+ export { type BatchOutcome, BatchTooLargeBody, type CommandErrorWithData, type CommandRejectionCode, type OrderCreatePayloadV3, type OrderRejectionCode, type RegisterConflictCode, type RegisterOutcome, type Rejection, SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_ORDER_REFUND_VERSIONS, SUPPORTED_REGISTER_VERSIONS, type ValidatedCommandEnvelope, canonicalJson, commandFingerprint, currencyDecimals, deriveSessionFigures, deriveVariance, fiscalFiguresErrors, inProgressOutcome, internalErrorResult, majorToMinor, minorToMajor, payloadBoundErrors, payloadShapeErrors, platformErrorResult, precheckCommand, refundPayloadErrors, registerPayloadErrors, totalWarnings, transientOutcome, validateBatch };
@@ -1,6 +1,8 @@
1
1
  import {
2
- MAX_COMMANDS_PER_BATCH
3
- } from "../chunk-C4PWPOKO.js";
2
+ CommandResultError,
3
+ MAX_COMMANDS_PER_BATCH,
4
+ parseCommandResult
5
+ } from "../chunk-UFWXJAMF.js";
4
6
  import "../chunk-MLKGABMK.js";
5
7
 
6
8
  // src/server/money.ts
@@ -146,6 +148,36 @@ function payloadShapeErrors(payload) {
146
148
  }
147
149
  });
148
150
  }
151
+ for (const prefix of ["", "display."]) {
152
+ const parent = prefix ? payload.display : payload;
153
+ const items = object(parent) ? parent.coupons : void 0;
154
+ if (items === void 0) continue;
155
+ check(Array.isArray(items), `${prefix}coupons`, "an array");
156
+ if (!Array.isArray(items)) continue;
157
+ const keys = prefix ? ["code", "amountMinor"] : ["code", "couponId", "discountMinor", "discountTaxMinor"];
158
+ const seen = /* @__PURE__ */ new Set();
159
+ items.forEach((item, index) => {
160
+ const path = `${prefix}coupons[${index}]`;
161
+ check(object(item), path, "an object");
162
+ if (!object(item)) return;
163
+ for (const key of Object.keys(item)) check(keys.includes(key), `${path}.${key}`, "no unknown key");
164
+ for (const key of prefix ? ["code"] : ["code", "couponId"]) check(typeof item[key] === "string" && item[key].length > 0, `${path}.${key}`, "a non-empty string");
165
+ for (const key of prefix ? ["amountMinor"] : ["discountMinor", "discountTaxMinor"]) check(Number.isSafeInteger(item[key]) && item[key] >= 0, `${path}.${key}`, "a safe integer >= 0");
166
+ if (!prefix) {
167
+ check(!seen.has(item.code), `${path}.code`, "no duplicate code");
168
+ seen.add(item.code);
169
+ }
170
+ });
171
+ }
172
+ if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
173
+ if (!object(line)) return;
174
+ const path = `lines[${index}]`;
175
+ if (line.regularUnitPriceMinor !== void 0) check(Number.isSafeInteger(line.regularUnitPriceMinor) && line.regularUnitPriceMinor >= 0, `${path}.regularUnitPriceMinor`, "a safe integer >= 0");
176
+ if (line.attributes !== void 0) {
177
+ check(object(line.attributes), `${path}.attributes`, "an object");
178
+ if (object(line.attributes)) for (const [key, value] of Object.entries(line.attributes)) check(typeof value === "string", `${path}.attributes.${key}`, "a string");
179
+ }
180
+ });
149
181
  for (const [value, path] of payloadStrings(payload)) check(!value.includes("\0"), path, "no NUL character");
150
182
  return errors;
151
183
  }
@@ -179,6 +211,18 @@ function payloadStrings(payload) {
179
211
  }
180
212
  });
181
213
  }
214
+ for (const prefix of ["", "display."]) {
215
+ const parent = prefix ? payload.display : payload;
216
+ const items = object(parent) ? parent.coupons : void 0;
217
+ if (Array.isArray(items)) items.forEach((item, index) => {
218
+ if (object(item)) for (const key of prefix ? ["code"] : ["code", "couponId"]) found.push([item[key], `${prefix}coupons[${index}].${key}`, key === "code" ? 255 : 64]);
219
+ });
220
+ }
221
+ if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
222
+ if (object(line) && object(line.attributes)) for (const [key, value] of Object.entries(line.attributes)) {
223
+ found.push([key, `lines[${index}].attributes`, 255], [value, `lines[${index}].attributes.${key}`, 255]);
224
+ }
225
+ });
182
226
  if (object(payload.customer)) found.push([payload.customer.email, "customer.email", 254], [payload.customer.customerId, "customer.customerId", void 0]);
183
227
  found.push([payload.sessionId, "sessionId", void 0]);
184
228
  return found.filter((entry) => typeof entry[0] === "string");
@@ -200,7 +244,7 @@ function fiscalFiguresErrors(payload) {
200
244
  for (const key of keys) check(Number.isSafeInteger(value[key]), `${path}.${key}`, "a safe integer");
201
245
  };
202
246
  const { display, taxByRate } = payload;
203
- if (object(display, "display", ["currency", "exponent", "taxInclusive", "subtotalMinor", "discountMinor", "taxMinor", "totalMinor", "orderDiscountMinor", "lines", "fees", "shipping"])) {
247
+ if (object(display, "display", ["currency", "exponent", "taxInclusive", "subtotalMinor", "discountMinor", "taxMinor", "totalMinor", "orderDiscountMinor", "lines", "fees", "shipping", "coupons"])) {
204
248
  check(typeof display.currency === "string", "display.currency", "a string");
205
249
  check(Number.isInteger(display.exponent) && display.exponent >= 0, "display.exponent", "an integer >= 0");
206
250
  check(typeof display.taxInclusive === "boolean", "display.taxInclusive", "a boolean");
@@ -229,19 +273,27 @@ function fiscalFiguresErrors(payload) {
229
273
  ]));
230
274
  const rows = display[field];
231
275
  if (rows !== void 0) check(Array.isArray(rows), `display.${field}`, "an array");
232
- const seen2 = /* @__PURE__ */ new Set();
276
+ const seen3 = /* @__PURE__ */ new Set();
233
277
  if (Array.isArray(rows)) rows.forEach((row, index) => {
234
278
  const path = `display.${field}[${index}]`;
235
279
  if (!object(row, path, [id, "amountMinor"])) return;
236
280
  check(typeof row[id] === "string" && row[id].length > 0, `${path}.${id}`, "a non-empty string");
237
281
  money(row, path, ["amountMinor"]);
238
282
  check(amounts.has(row[id]), `${path}.${id}`, `a payload.${field}[].${id}`);
239
- check(!seen2.has(row[id]), `${path}.${id}`, `no duplicate ${id}`);
240
- seen2.add(row[id]);
283
+ check(!seen3.has(row[id]), `${path}.${id}`, `no duplicate ${id}`);
284
+ seen3.add(row[id]);
241
285
  if (amounts.has(row[id])) check(row.amountMinor === amounts.get(row[id]), `${path}.amountMinor`, `the payload.${field} amountMinor`);
242
286
  });
243
- for (const key of amounts.keys()) check(seen2.has(key), `display.${field}`, `a row for ${id} ${key}`);
287
+ for (const key of amounts.keys()) check(seen3.has(key), `display.${field}`, `a row for ${id} ${key}`);
244
288
  }
289
+ const codes = new Set((payload.coupons ?? []).map((coupon) => coupon.code));
290
+ const seen2 = /* @__PURE__ */ new Set();
291
+ if (Array.isArray(display.coupons)) display.coupons.forEach((row, index) => {
292
+ const path = `display.coupons[${index}]`;
293
+ check(codes.has(row.code), `${path}.code`, "a payload.coupons[].code");
294
+ check(!seen2.has(row.code), `${path}.code`, "no duplicate code");
295
+ seen2.add(row.code);
296
+ });
245
297
  }
246
298
  check(Array.isArray(taxByRate), "taxByRate", "an array");
247
299
  if (Array.isArray(taxByRate)) taxByRate.forEach((rate, index) => {
@@ -365,7 +417,14 @@ function precheckCommand(envelope, supported) {
365
417
  if (line?.custom !== void 0) v5Fields.push(`lines[${index}].custom`);
366
418
  });
367
419
  for (const field of ["fees", "shipping"]) if (display?.[field] !== void 0) v5Fields.push(`display.${field}`);
368
- let versionError = command.version < 5 && v5Fields.length ? v5Fields.map((field) => `${field} requires version 5`).join("; ") : command.version === 2 && discountMinor === void 0 ? "version 2 requires discountMinor" : command.version === 1 && discounted ? "discountMinor requires version 2" : !v3 && (display !== void 0 || taxByRate !== void 0) ? "display and taxByRate require version 3" : !v3 && sessionId !== void 0 ? "sessionId requires version 3" : !v3 && payload.customer?.customerId !== void 0 ? "customerId requires version 3" : v3 && display !== void 0 !== (taxByRate !== void 0) ? "display and taxByRate must both be present or both absent" : void 0;
420
+ const v6Fields = payload.coupons !== void 0 ? ["coupons"] : [];
421
+ if (display?.coupons !== void 0) v6Fields.push("display.coupons");
422
+ if (Array.isArray(lines)) lines.forEach((line, index) => {
423
+ for (const field of ["regularUnitPriceMinor", "attributes"]) {
424
+ if (line?.[field] !== void 0) v6Fields.push(`lines[${index}].${field}`);
425
+ }
426
+ });
427
+ let versionError = command.version < 5 && v5Fields.length ? v5Fields.map((field) => `${field} requires version 5`).join("; ") : command.version < 6 && v6Fields.length ? v6Fields.map((field) => `${field} requires version 6`).join("; ") : command.version === 2 && discountMinor === void 0 ? "version 2 requires discountMinor" : command.version === 1 && discounted ? "discountMinor requires version 2" : !v3 && (display !== void 0 || taxByRate !== void 0) ? "display and taxByRate require version 3" : !v3 && sessionId !== void 0 ? "sessionId requires version 3" : !v3 && payload.customer?.customerId !== void 0 ? "customerId requires version 3" : v3 && display !== void 0 !== (taxByRate !== void 0) ? "display and taxByRate must both be present or both absent" : void 0;
369
428
  if (!versionError && Array.isArray(lines)) for (const [index, line] of lines.entries()) {
370
429
  if (line?.custom === void 0 && (typeof line?.variantId !== "string" || !line.variantId.length)) {
371
430
  versionError = `lines[${index}].variantId is required`;
@@ -402,171 +461,6 @@ function totalWarnings(expectedMinor, serverMinor) {
402
461
  return serverMinor === expectedMinor ? [] : [{ code: "total_mismatch", expectedMinor, serverMinor }];
403
462
  }
404
463
 
405
- // src/server/command-result.ts
406
- var CommandResultError = class extends Error {
407
- constructor(message) {
408
- super(message);
409
- this.name = "CommandResultError";
410
- }
411
- };
412
- function parseCommandResult(value) {
413
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
414
- throw new CommandResultError("Invalid result: expected object");
415
- }
416
- const input = value;
417
- if (typeof input.id !== "string" || input.id.length === 0) {
418
- throw new CommandResultError("Invalid id");
419
- }
420
- if (input.status !== "applied" && input.status !== "duplicate" && input.status !== "rejected") {
421
- throw new CommandResultError("Invalid status");
422
- }
423
- const result = { id: input.id, status: input.status };
424
- const object = (value2) => typeof value2 === "object" && value2 !== null && (Object.getPrototypeOf(value2) === Object.prototype || Object.getPrototypeOf(value2) === null);
425
- if (input.serverRefs !== void 0) {
426
- if (typeof input.serverRefs !== "object" || input.serverRefs === null || Array.isArray(input.serverRefs)) {
427
- throw new CommandResultError("Invalid serverRefs");
428
- }
429
- const refs = input.serverRefs;
430
- if (typeof refs.orderId !== "string" || refs.orderId.length === 0) {
431
- throw new CommandResultError("Invalid serverRefs.orderId");
432
- }
433
- if (refs.displayId !== void 0 && typeof refs.displayId !== "string") {
434
- throw new CommandResultError("Invalid serverRefs.displayId");
435
- }
436
- if (!Number.isSafeInteger(refs.totalMinor)) {
437
- throw new CommandResultError("Invalid serverRefs.totalMinor");
438
- }
439
- result.serverRefs = { orderId: refs.orderId, totalMinor: refs.totalMinor };
440
- if (refs.displayId !== void 0) result.serverRefs.displayId = refs.displayId;
441
- }
442
- if (input.register !== void 0) {
443
- if (!object(input.register)) throw new CommandResultError("Invalid register");
444
- result.register = input.register;
445
- }
446
- if (input.refund !== void 0) {
447
- if (!object(input.refund)) throw new CommandResultError("Invalid refund");
448
- const refund = input.refund;
449
- if (!Number.isSafeInteger(refund.totalMinor) || refund.totalMinor < 0) throw new CommandResultError("Invalid refund.totalMinor");
450
- if (!object(refund.byMethod)) throw new CommandResultError("Invalid refund.byMethod");
451
- const byMethod = Object.fromEntries(Object.entries(refund.byMethod).map(([key, amount]) => {
452
- if (!key.length) throw new CommandResultError("Invalid refund.byMethod");
453
- if (!Number.isSafeInteger(amount) || amount < 0) throw new CommandResultError(`Invalid refund.byMethod.${key}`);
454
- return [key, amount];
455
- }));
456
- if (Object.values(byMethod).reduce((sum, amount) => sum + amount, 0) !== refund.totalMinor) throw new CommandResultError("Invalid refund.byMethod");
457
- if (!Array.isArray(refund.refunds) || refund.refunds.length === 0) throw new CommandResultError("Invalid refund.refunds");
458
- const refunds = refund.refunds.map((value2, index) => {
459
- const field = `refund.refunds[${index}]`;
460
- if (!object(value2)) throw new CommandResultError(`Invalid ${field}`);
461
- const entry = value2;
462
- for (const key of ["id", "paymentId"]) {
463
- if (typeof entry[key] !== "string" || entry[key].length === 0) throw new CommandResultError(`Invalid ${field}.${key}`);
464
- }
465
- if (!Number.isSafeInteger(entry.totalMinor) || entry.totalMinor < 0) throw new CommandResultError(`Invalid ${field}.totalMinor`);
466
- if (typeof entry.state !== "string" || entry.state.length === 0) throw new CommandResultError(`Invalid ${field}.state`);
467
- return { id: entry.id, paymentId: entry.paymentId, totalMinor: entry.totalMinor, state: entry.state };
468
- });
469
- if (refunds.reduce((sum, entry) => sum + entry.totalMinor, 0) !== refund.totalMinor) throw new CommandResultError("Invalid refund.refunds");
470
- result.refund = { totalMinor: refund.totalMinor, byMethod, refunds };
471
- }
472
- if (result.status === "applied" && result.serverRefs === void 0 && result.register === void 0 && result.refund === void 0) {
473
- throw new CommandResultError("Invalid serverRefs: required for applied");
474
- }
475
- if (input.warnings !== void 0) {
476
- if (!Array.isArray(input.warnings)) {
477
- throw new CommandResultError("Invalid warnings");
478
- }
479
- result.warnings = input.warnings.map((warning, index) => {
480
- const field = `warnings[${index}]`;
481
- if (typeof warning !== "object" || warning === null || Array.isArray(warning)) {
482
- throw new CommandResultError(`Invalid ${field}`);
483
- }
484
- const item = warning;
485
- if (item.code === "total_mismatch") {
486
- for (const key of ["expectedMinor", "serverMinor"]) {
487
- if (!Number.isInteger(item[key])) {
488
- throw new CommandResultError(`Invalid ${field}.${key}`);
489
- }
490
- }
491
- if (item.bridgeMinor != null && !Number.isSafeInteger(item.bridgeMinor)) {
492
- throw new CommandResultError(`Invalid ${field}.bridgeMinor`);
493
- }
494
- 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 };
495
- }
496
- if (item.code === "insufficient_stock") {
497
- if (typeof item.variantId !== "string" || item.variantId.length === 0) {
498
- throw new CommandResultError(`Invalid ${field}.variantId`);
499
- }
500
- if (!Number.isInteger(item.quantity) || item.quantity < 1) {
501
- throw new CommandResultError(`Invalid ${field}.quantity`);
502
- }
503
- return { code: item.code, variantId: item.variantId, quantity: item.quantity };
504
- }
505
- if (item.code === "tax_rate_mismatch") {
506
- if (!Number.isSafeInteger(item.ratePpm) || item.ratePpm < 0) {
507
- throw new CommandResultError(`Invalid ${field}.ratePpm`);
508
- }
509
- for (const key of ["expectedMinor", "serverMinor"]) {
510
- if (!Number.isSafeInteger(item[key])) {
511
- throw new CommandResultError(`Invalid ${field}.${key}`);
512
- }
513
- }
514
- return { code: item.code, ratePpm: item.ratePpm, expectedMinor: item.expectedMinor, serverMinor: item.serverMinor };
515
- }
516
- if (item.code === "customer_ignored") {
517
- if (typeof item.customerId !== "string" || item.customerId.length === 0 || item.customerId.length > 64) {
518
- throw new CommandResultError(`Invalid ${field}.customerId`);
519
- }
520
- return { code: item.code, customerId: item.customerId };
521
- }
522
- if (item.code === "register_session_unknown") {
523
- if (typeof item.sessionId !== "string" || item.sessionId.length === 0 || item.sessionId.length > 64) {
524
- throw new CommandResultError(`Invalid ${field}.sessionId`);
525
- }
526
- return { code: item.code, sessionId: item.sessionId };
527
- }
528
- if (item.code === "figures_mismatch") {
529
- if (!Array.isArray(item.fields) || item.fields.length === 0) throw new CommandResultError(`Invalid ${field}.fields`);
530
- const seen = [];
531
- return { code: item.code, fields: item.fields.map((value2, i) => {
532
- const path = `${field}.fields[${i}]`;
533
- if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) throw new CommandResultError(`Invalid ${path}`);
534
- const entry = value2;
535
- if (!["subtotalMinor", "taxMinor", "discountMinor"].includes(entry.field) || seen.includes(entry.field)) {
536
- throw new CommandResultError(`Invalid ${path}.field`);
537
- }
538
- seen.push(entry.field);
539
- if (!Number.isSafeInteger(entry.tillMinor)) throw new CommandResultError(`Invalid ${path}.tillMinor`);
540
- if (!Number.isSafeInteger(entry.serverMinor) || entry.serverMinor === entry.tillMinor) throw new CommandResultError(`Invalid ${path}.serverMinor`);
541
- return { field: entry.field, tillMinor: entry.tillMinor, serverMinor: entry.serverMinor };
542
- }) };
543
- }
544
- throw new CommandResultError(`Invalid ${field}.code`);
545
- });
546
- }
547
- if (input.error !== void 0) {
548
- if (typeof input.error !== "object" || input.error === null || Array.isArray(input.error)) {
549
- throw new CommandResultError("Invalid error");
550
- }
551
- const error = input.error;
552
- if (typeof error.code !== "string" || error.code.length === 0) {
553
- throw new CommandResultError("Invalid error.code");
554
- }
555
- if (typeof error.message !== "string") {
556
- throw new CommandResultError("Invalid error.message");
557
- }
558
- result.error = { code: error.code, message: error.message };
559
- if (error.data !== void 0) {
560
- if (!object(error.data)) throw new CommandResultError("Invalid error.data");
561
- result.error.data = error.data;
562
- }
563
- }
564
- if (result.status === "rejected" && result.error === void 0) {
565
- throw new CommandResultError("Invalid error: required for rejected");
566
- }
567
- return result;
568
- }
569
-
570
464
  // src/server/register-payload-shape.ts
571
465
  function registerPayloadErrors(type, payload) {
572
466
  const errors = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/core",
3
- "version": "3.9.1",
3
+ "version": "3.10.0",
4
4
  "type": "module",
5
5
  "description": "Core interfaces, traits, and context providers for Tally UI",
6
6
  "main": "./dist/index.js",
package/src/index.ts CHANGED
@@ -46,6 +46,7 @@ export type {
46
46
  CommandWarning, CommandError, CommandResult, OrderCreateLine,
47
47
  PaymentMethodKind, OrderCreatePayment, OrderCreatePayload, OrderCreateEnvelope,
48
48
  OrderCreateDisplay, OrderCreateTaxRate,
49
+ OrderCreateCoupon, OrderCreateCouponInvalidData, OrderCreateTotalMismatchData,
49
50
  CommandBatchRequest, CommandBatchResponse, BatchTooLargeBody,
50
51
  RegisterCommandResult, RegisterSessionOpenPayload, RegisterSessionAlreadyOpenData, RegisterSessionSupersededData,
51
52
  RegisterSessionTransitionPayload,
@@ -81,3 +82,7 @@ export {
81
82
  export type { ConnectorProviderProps } from './context/connector-context';
82
83
  export * as woocommerceTax from './tax/woocommerce';
83
84
  export * as woocommerceCoupons from './coupons/woocommerce';
85
+
86
+ // Browser-safe: command-result.ts imports only types. @tallyui/core/server re-exports these too, but
87
+ // its barrel reaches node:crypto (fingerprint.ts), so browser packages import them from here.
88
+ export { parseCommandResult, CommandResultError } from './server/command-result';
@@ -105,7 +105,15 @@ export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCom
105
105
  if (line?.custom !== undefined) v5Fields.push(`lines[${index}].custom`)
106
106
  })
107
107
  for (const field of ['fees', 'shipping'] as const) if (display?.[field] !== undefined) v5Fields.push(`display.${field}`)
108
+ const v6Fields = payload.coupons !== undefined ? ['coupons'] : []
109
+ if (display?.coupons !== undefined) v6Fields.push('display.coupons')
110
+ if (Array.isArray(lines)) lines.forEach((line, index) => {
111
+ for (const field of ['regularUnitPriceMinor', 'attributes'] as const) {
112
+ if (line?.[field] !== undefined) v6Fields.push(`lines[${index}].${field}`)
113
+ }
114
+ })
108
115
  let versionError = command.version < 5 && v5Fields.length ? v5Fields.map(field => `${field} requires version 5`).join('; ')
116
+ : command.version < 6 && v6Fields.length ? v6Fields.map(field => `${field} requires version 6`).join('; ')
109
117
  : command.version === 2 && discountMinor === undefined ? 'version 2 requires discountMinor'
110
118
  : command.version === 1 && discounted ? 'discountMinor requires version 2'
111
119
  : !v3 && (display !== undefined || taxByRate !== undefined) ? 'display and taxByRate require version 3'
@@ -22,7 +22,7 @@ export function fiscalFiguresErrors(payload: OrderCreatePayloadV3): string[] {
22
22
  for (const key of keys) check(Number.isSafeInteger(value[key]), `${path}.${key}`, 'a safe integer')
23
23
  }
24
24
  const { display, taxByRate } = payload
25
- if (object(display, 'display', ['currency', 'exponent', 'taxInclusive', 'subtotalMinor', 'discountMinor', 'taxMinor', 'totalMinor', 'orderDiscountMinor', 'lines', 'fees', 'shipping'])) {
25
+ if (object(display, 'display', ['currency', 'exponent', 'taxInclusive', 'subtotalMinor', 'discountMinor', 'taxMinor', 'totalMinor', 'orderDiscountMinor', 'lines', 'fees', 'shipping', 'coupons'])) {
26
26
  check(typeof display.currency === 'string', 'display.currency', 'a string')
27
27
  check(Number.isInteger(display.exponent) && display.exponent >= 0, 'display.exponent', 'an integer >= 0')
28
28
  check(typeof display.taxInclusive === 'boolean', 'display.taxInclusive', 'a boolean')
@@ -63,6 +63,14 @@ export function fiscalFiguresErrors(payload: OrderCreatePayloadV3): string[] {
63
63
  })
64
64
  for (const key of amounts.keys()) check(seen.has(key), `display.${field}`, `a row for ${id} ${key}`)
65
65
  }
66
+ const codes = new Set((payload.coupons ?? []).map(coupon => coupon.code))
67
+ const seen = new Set<string>()
68
+ if (Array.isArray(display.coupons)) display.coupons.forEach((row, index) => {
69
+ const path = `display.coupons[${index}]`
70
+ check(codes.has(row.code), `${path}.code`, 'a payload.coupons[].code')
71
+ check(!seen.has(row.code), `${path}.code`, 'no duplicate code')
72
+ seen.add(row.code)
73
+ })
66
74
  }
67
75
  check(Array.isArray(taxByRate), 'taxByRate', 'an array')
68
76
  if (Array.isArray(taxByRate)) taxByRate.forEach((rate, index) => {
@@ -104,6 +104,36 @@ export function payloadShapeErrors(payload: unknown): string[] {
104
104
  }
105
105
  })
106
106
  }
107
+ for (const prefix of ['', 'display.']) {
108
+ const parent = prefix ? payload.display : payload
109
+ const items = object(parent) ? parent.coupons : undefined
110
+ if (items === undefined) continue
111
+ check(Array.isArray(items), `${prefix}coupons`, 'an array')
112
+ if (!Array.isArray(items)) continue
113
+ const keys = prefix ? ['code', 'amountMinor'] : ['code', 'couponId', 'discountMinor', 'discountTaxMinor']
114
+ const seen = new Set<unknown>()
115
+ items.forEach((item, index) => {
116
+ const path = `${prefix}coupons[${index}]`
117
+ check(object(item), path, 'an object')
118
+ if (!object(item)) return
119
+ for (const key of Object.keys(item)) check(keys.includes(key), `${path}.${key}`, 'no unknown key')
120
+ for (const key of prefix ? ['code'] : ['code', 'couponId']) check(typeof item[key] === 'string' && item[key].length > 0, `${path}.${key}`, 'a non-empty string')
121
+ for (const key of prefix ? ['amountMinor'] : ['discountMinor', 'discountTaxMinor']) check(Number.isSafeInteger(item[key]) && (item[key] as number) >= 0, `${path}.${key}`, 'a safe integer >= 0')
122
+ if (!prefix) {
123
+ check(!seen.has(item.code), `${path}.code`, 'no duplicate code')
124
+ seen.add(item.code)
125
+ }
126
+ })
127
+ }
128
+ if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
129
+ if (!object(line)) return
130
+ const path = `lines[${index}]`
131
+ if (line.regularUnitPriceMinor !== undefined) check(Number.isSafeInteger(line.regularUnitPriceMinor) && (line.regularUnitPriceMinor as number) >= 0, `${path}.regularUnitPriceMinor`, 'a safe integer >= 0')
132
+ if (line.attributes !== undefined) {
133
+ check(object(line.attributes), `${path}.attributes`, 'an object')
134
+ if (object(line.attributes)) for (const [key, value] of Object.entries(line.attributes)) check(typeof value === 'string', `${path}.attributes.${key}`, 'a string')
135
+ }
136
+ })
107
137
  // NUL, only on strings (the checks above name any other type): Postgres text can't hold it, and the lookup keys must be clean.
108
138
  for (const [value, path] of payloadStrings(payload)) check(!value.includes('\u0000'), path, 'no NUL character')
109
139
  return errors
@@ -152,6 +182,18 @@ function payloadStrings(payload: Record<string, unknown>): Array<[string, string
152
182
  }
153
183
  })
154
184
  }
185
+ for (const prefix of ['', 'display.']) {
186
+ const parent = prefix ? payload.display : payload
187
+ const items = object(parent) ? parent.coupons : undefined
188
+ if (Array.isArray(items)) items.forEach((item, index) => {
189
+ if (object(item)) for (const key of prefix ? ['code'] : ['code', 'couponId']) found.push([item[key], `${prefix}coupons[${index}].${key}`, key === 'code' ? 255 : 64])
190
+ })
191
+ }
192
+ if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
193
+ if (object(line) && object(line.attributes)) for (const [key, value] of Object.entries(line.attributes)) {
194
+ found.push([key, `lines[${index}].attributes`, 255], [value, `lines[${index}].attributes.${key}`, 255])
195
+ }
196
+ })
155
197
  if (object(payload.customer)) found.push([payload.customer.email, 'customer.email', 254], [payload.customer.customerId, 'customer.customerId', undefined])
156
198
  found.push([payload.sessionId, 'sessionId', undefined])
157
199
  return found.filter((entry): entry is [string, string, number | undefined] => typeof entry[0] === 'string')
@@ -7,6 +7,8 @@ import type { RegisterConflictCode } from './register-outcome'
7
7
  export type CommandRejectionCode =
8
8
  | 'invalid_payload' | 'unsupported_version' | 'idempotency_mismatch' | 'store_configuration' | 'platform_error'
9
9
  | 'insufficient_stock' | 'unsupported_tax_mode' | 'internal_error'
10
+ // Both are order.create v6 refusals (ADR-077 d4).
11
+ | 'coupon_invalid' | 'total_mismatch'
10
12
  | OrderRejectionCode | RegisterConflictCode | OrderRefundRejectionCode
11
13
 
12
14
  /**
@@ -8,7 +8,7 @@ export interface CommandEnvelope<P = unknown> {
8
8
  /** 3 when the order carries ADR-065's `display` and `taxByRate` (the store accepts 3), else 2 when discounted, else 1;
9
9
  * 4 is 3 with every `discountMinor` tax-exclusive, built only when capped at 4 or more (#286).
10
10
  * 5 is 4 plus fees, shipping and custom lines (ADR-075), sent only for an order that has one. */
11
- version: 1 | 2 | 3 | 4 | 5;
11
+ version: 1 | 2 | 3 | 4 | 5 | 6;
12
12
  payload: P;
13
13
  createdAt: string; // ISO 8601, client clock
14
14
  deviceId: string;
@@ -55,7 +55,7 @@ export interface OrderRefundOrderStateData { state: string }
55
55
  export interface OrderRefundNoOpenSessionData { sessionId: string }
56
56
 
57
57
  /** An order.create envelope: 5 is 4 plus fees, shipping and custom lines (ADR-075), sent only for an order that has one. */
58
- export type OrderCreateEnvelope = CommandEnvelope<OrderCreatePayload> & { type: 'order.create'; version: 1 | 2 | 3 | 4 | 5 };
58
+ export type OrderCreateEnvelope = CommandEnvelope<OrderCreatePayload> & { type: 'order.create'; version: 1 | 2 | 3 | 4 | 5 | 6 };
59
59
 
60
60
  /** Outcome of processing a command. */
61
61
  export type CommandStatus = 'applied' | 'duplicate' | 'rejected';
@@ -128,6 +128,21 @@ export interface CommandError {
128
128
  data?: Record<string, unknown>;
129
129
  }
130
130
 
131
+ /** `coupon_invalid` (order.create v6, ADR-077 d4): the store would not apply one of the order's coupons. */
132
+ export interface OrderCreateCouponInvalidData {
133
+ /** The payload coupon's code, when the store can tell which one. */
134
+ couponCode?: string;
135
+ /** The store's own error code, e.g. WooCommerce's, for the log; never shown as the cashier's message. */
136
+ storeCode?: string;
137
+ }
138
+ /**
139
+ * `total_mismatch` as a refusal (order.create v6, ADR-077 R4): the store would accept the order but computes a
140
+ * different total from the envelope, so it made no order. The store's own figures, as `figures_mismatch` names them.
141
+ */
142
+ export interface OrderCreateTotalMismatchData {
143
+ fields: Array<{ field: 'subtotalMinor' | 'taxMinor' | 'discountMinor' | 'totalMinor' | (string & {}); tillMinor: number; serverMinor: number }>;
144
+ }
145
+
131
146
  /** Server result for a single command. */
132
147
  export interface CommandResult {
133
148
  id: string;
@@ -217,6 +232,10 @@ export interface OrderCreateLine {
217
232
  title?: string;
218
233
  quantity: number;
219
234
  unitPriceMinor: number;
235
+ /** Version 6 recorded figure: the product's regular (not sale) unit price, in the line's tax mode and integer minor units, when the till knew it. */
236
+ regularUnitPriceMinor?: number;
237
+ /** Version 6 recorded: the variant's attribute names and values (#495), each at most 255 characters. */
238
+ attributes?: Record<string, string>;
220
239
  /**
221
240
  * This line's own tax mode, when it differs from the order's `pricesIncludeTax`
222
241
  * (a price that carries its own flag, D2c). Absent means the order's flag, so
@@ -232,6 +251,18 @@ export interface OrderCreateLine {
232
251
  discountMinor?: number;
233
252
  }
234
253
 
254
+ /** Version 6 (ADR-077): a coupon the till applied. Recorded figures, in integer minor units of the order's currency. */
255
+ export interface OrderCreateCoupon {
256
+ /** The coupon code as the store knows it, 1–255 characters. */
257
+ code: string;
258
+ /** The store's id for the coupon, 1–64 characters. */
259
+ couponId: string;
260
+ /** The discount it gave, tax-exclusive, integer >= 0. */
261
+ discountMinor: number;
262
+ /** The tax on that discount, integer >= 0. */
263
+ discountTaxMinor: number;
264
+ }
265
+
235
266
  /** Version 5: a fee, never discounted (ADR-075). */
236
267
  export interface OrderCreateFee {
237
268
  /** Identity: UUID, stable for the order's life, at most 36 characters. */
@@ -298,6 +329,8 @@ export interface OrderCreateDisplay {
298
329
  /** Recorded integer minor units, equal to the payload shipping amount. */
299
330
  amountMinor: number;
300
331
  }>;
332
+ /** Version 6 recorded figures: one row per payload coupon, its discount in the display tax mode. */
333
+ coupons?: Array<{ code: string; amountMinor: number }>;
301
334
  }
302
335
 
303
336
  /** Version 3 (ADR-065): one tax rate's net, tax and gross, as the receipt's tax summary splits them. */
@@ -320,10 +353,15 @@ export interface OrderCreatePayload {
320
353
  fees?: OrderCreateFee[];
321
354
  /** Version 5 instructions: shipping in the order's tax mode; omitted when none. */
322
355
  shipping?: OrderCreateShipping[];
356
+ /** Version 6 (ADR-077): the coupons the till applied, in the order it applied them; omitted when none.
357
+ * The store re-applies them by `code` and refuses the order with `coupon_invalid` if one no longer applies. */
358
+ coupons?: OrderCreateCoupon[];
359
+ /** Version 6: net of the coupons' `discountMinor`, as `taxMinor` is of their `discountTaxMinor`; coupons are not part of `discountMinor`. */
323
360
  subtotalMinor: number;
324
361
  /**
325
362
  * Version 2 (ADR-062): the order's total discount, equal to Σ `lines[].discountMinor`. Present only when above 0.
326
363
  * Version 4+ (#286) means every `discountMinor`, this and each line's, is tax-exclusive, so the sum still holds.
364
+ * Version 6: coupons are not included; their amounts are in `coupons[].discountMinor`.
327
365
  */
328
366
  discountMinor?: number;
329
367
  taxMinor: number;
@@ -34,6 +34,7 @@ export type {
34
34
  CommandWarning, CommandError, CommandResult, OrderCreateLine,
35
35
  PaymentMethodKind, OrderCreatePayment, OrderCreatePayload, OrderCreateEnvelope,
36
36
  OrderCreateDisplay, OrderCreateTaxRate,
37
+ OrderCreateCoupon, OrderCreateCouponInvalidData, OrderCreateTotalMismatchData,
37
38
  CommandBatchRequest, CommandBatchResponse, BatchTooLargeBody,
38
39
  RegisterCommandResult, RegisterSessionOpenPayload, RegisterSessionAlreadyOpenData, RegisterSessionSupersededData,
39
40
  RegisterSessionTransitionPayload,
@@ -76,8 +76,9 @@ export interface CatalogueReconcileAdapter<Doc = any, Cursor = unknown> {
76
76
  /**
77
77
  * Hand documents to the collection's pull (the reconcile feed). An entry's `key` is the local primary key when
78
78
  * there is a local copy, and otherwise the listing's key.
79
+ * A `refreshOnly` entry asks the feed to fetch the document again and is never tombstoned when the fetch omits it.
79
80
  */
80
- enqueue(entries: Array<{ key: string; local?: Doc; remote?: unknown; tombstone?: boolean }>): void;
81
+ enqueue(entries: Array<{ key: string; local?: Doc; remote?: unknown; tombstone?: boolean; refreshOnly?: boolean }>): void;
81
82
  /** Ids per `fetchByIds` request of the feed this adapter enqueues into: a page's `n` refetches take `ceil(n / refetchBatchSize)` budget slots (1 when unset). */
82
83
  refetchBatchSize?: number;
83
84
  }
@@ -1,18 +0,0 @@
1
- // src/commands.ts
2
- var COMMANDS_PATH = "/tally/v1/commands";
3
- var PROTOCOL_HEADER = "X-Tally-Protocol";
4
- var PROTOCOL_VERSION = 1;
5
- var MAX_COMMANDS_PER_BATCH = 50;
6
- function isCommandBatchResponse(value) {
7
- return typeof value === "object" && value !== null && "results" in value && Array.isArray(value.results) && value.results.every(
8
- (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")
9
- );
10
- }
11
-
12
- export {
13
- COMMANDS_PATH,
14
- PROTOCOL_HEADER,
15
- PROTOCOL_VERSION,
16
- MAX_COMMANDS_PER_BATCH,
17
- isCommandBatchResponse
18
- };