@tallyui/core 3.20.1 → 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,1039 @@
1
+ /**
2
+ * ISO 4217 minor-unit exponent as resolved by Intl (which rejects malformed codes); depends on the runtime's ICU data.
3
+ * @deprecated Use `minorUnitDigits` (exported here and from `@tallyui/core`). It returns 2 for a code Intl rejects, where this throws.
4
+ */
5
+ declare function currencyDecimals(currency: string): number;
6
+ /** Converts a safe integer minor amount to an exact major-unit decimal string. */
7
+ declare function minorToMajor(minor: number, decimals: number): string;
8
+ /** Rounds a major-unit decimal to minor units, half away from zero, without float scaling. */
9
+ declare function majorToMinor(value: string | number, decimals: number): number;
10
+
11
+ /** Number of minor-unit digits for an ISO 4217 code (2 for EUR, 0 for JPY). */
12
+ declare function minorUnitDigits(currency: string): number;
13
+
14
+ /** Converts a plain decimal percentage with at most four fractional digits to safe integer ppm. */
15
+ declare function ratePpmFromPercent(percent: number | string): number;
16
+
17
+ /** JSON with recursively sorted object keys; arrays keep their order. */
18
+ declare function canonicalJson(value: unknown): string;
19
+ /** Lower-case hex SHA-256 of the canonical command content. */
20
+ declare function commandFingerprint(envelope: {
21
+ type: string;
22
+ version: number;
23
+ payload: unknown;
24
+ }): string;
25
+
26
+ /** Shape errors of an order.create payload, e.g. ['lines: expected a non-empty array',
27
+ * 'payments[0].method: expected a string']; [] when the shape is valid, at most ten. Checks
28
+ * presence, types, the `customerId` (64) and `sessionId` (36) bounds, and U+0000 in any string;
29
+ * numbers are finite numbers, and value ranges are the planner's job. A plugin runs it before its
30
+ * replay lookup; every other length bound is payloadBoundErrors', after that lookup. The NUL check
31
+ * runs last, so the earlier checks' errors keep their order. */
32
+ declare function payloadShapeErrors(payload: unknown): string[];
33
+ /** Length-bound errors of an order.create payload, e.g. ['lines[0].title: expected at most 255
34
+ * characters']; [] when every bound holds, at most ten. Bounds in UTF-16 code units:
35
+ * `note` ORDER_NOTE_MAX (1000), `customer.email` 254, v8 address fields 255, v5 ids 36 and class/sku/method 64, other strings 255 (`customerId` and `sessionId` keep theirs in
36
+ * payloadShapeErrors); v12 (ADR-092) tax id type 32, value 64 and country 2, a line's `sku` 100, meta key 255 and value ORDER_NOTE_MAX.
37
+ * Each coupon's lines array is also capped at payload.lines.length, `customer.taxIds` at 10 entries and `meta` at 50. A plugin calls it through precheckCommand, after
38
+ * its replay lookup, so a bound tightened later never turns an applied command's resend into
39
+ * `invalid_payload`. */
40
+ declare function payloadBoundErrors(payload: unknown): string[];
41
+
42
+ /** Supported command operation. */
43
+ type CommandType = 'order.create';
44
+ /** Client command with a stable idempotency key and typed payload. */
45
+ interface CommandEnvelope<P = unknown> {
46
+ id: string;
47
+ type: CommandType;
48
+ /** 3 when the order carries ADR-065's `display` and `taxByRate` (the store accepts 3), else 2 when discounted, else 1;
49
+ * 4 is 3 with every `discountMinor` tax-exclusive, built only when capped at 4 or more (#286).
50
+ * 5 is 4 plus fees, shipping and custom lines (ADR-075), sent only for an order that has one.
51
+ * 6 is 5 plus coupons, regular prices, line attributes and Any picks (ADR-077, #495), sent only for an order that has one.
52
+ * 7 is 6 plus the sale's `note` (ADR-083), sent only for an order that has one.
53
+ * 8 is 7 plus `taxAddress` and the customer's addresses (#722), sent only for a sale taxed on the customer's address.
54
+ * 9 is 8 plus each coupon's per-line amounts (`coupons[].lines`, #790), sent only when every coupon carries them; it needs no `taxAddress`.
55
+ * 11 is 10 plus the customer's addresses on a sale with no taxAddress, as informational fields (ADR-086 d2 amended).
56
+ * 12 is 11 plus the customer's tax ids, a catalogue line's edited SKU and order meta, as informational fields (ADR-092). */
57
+ version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
58
+ payload: P;
59
+ createdAt: string;
60
+ deviceId: string;
61
+ attempt: number;
62
+ }
63
+ /** The register commands (ADR-068); each versions on its own, from 1. */
64
+ type RegisterCommandType = 'register.session.open' | 'register.session.transition' | 'register.movement.record' | 'register.movement.void' | 'register.closure.submit';
65
+ /** A register command's envelope: the same fields as CommandEnvelope, with its own type and a numeric version. */
66
+ type RegisterCommandEnvelope<P = Record<string, unknown>> = Omit<CommandEnvelope<P>, 'type' | 'version'> & {
67
+ type: RegisterCommandType;
68
+ version: number;
69
+ };
70
+ /** Any command a transport can carry. */
71
+ type AnyCommandEnvelope = CommandEnvelope<unknown> | RegisterCommandEnvelope<unknown> | OrderRefundEnvelope<unknown> | OrderReopenEnvelope<unknown> | OrderUpdateEnvelope<unknown>;
72
+ /** A line's refunded quantity and restock choice (ADR-080). */
73
+ interface OrderRefundLine {
74
+ orderLineId: string;
75
+ quantity: number;
76
+ restock: boolean;
77
+ }
78
+ /** An online refund against an order, attributed to the refunding session (ADR-080). */
79
+ interface OrderRefundPayload {
80
+ clientRefundId: string;
81
+ orderId: string;
82
+ clientOrderId?: string;
83
+ lines: OrderRefundLine[];
84
+ shippingMinor: number;
85
+ adjustmentMinor: number;
86
+ totalMinor: number;
87
+ destination: 'original_method' | 'cash';
88
+ reason: string;
89
+ registerId: string;
90
+ sessionId: string;
91
+ cashierRef?: string;
92
+ createdAt: string;
93
+ }
94
+ /** An order.refund v1 command with the shared idempotency envelope (ADR-080). */
95
+ type OrderRefundEnvelope<P = OrderRefundPayload> = Omit<CommandEnvelope<P>, 'type' | 'version'> & {
96
+ type: 'order.refund';
97
+ version: 1;
98
+ };
99
+ /** The server's refund total, tender attribution and platform refunds (ADR-080). */
100
+ interface OrderRefundResult {
101
+ totalMinor: number;
102
+ byMethod: Record<string, number>;
103
+ refunds: Array<{
104
+ id: string;
105
+ paymentId: string;
106
+ totalMinor: number;
107
+ state: string;
108
+ }>;
109
+ }
110
+ /** Per-command refund refusals (ADR-080 decision 5). */
111
+ type OrderRefundRejectionCode = 'nothing_to_refund' | 'quantity_exceeds' | 'amount_mismatch' | 'order_state' | 'not_till_order' | 'forbidden' | 'no_open_session';
112
+ /** An online reopen against a store order, attributed to the cashier and register (ADR-090). */
113
+ interface OrderReopenPayload {
114
+ orderId: string;
115
+ clientOrderId?: string;
116
+ baseRevision?: string;
117
+ cashierRef: string;
118
+ registerId: string;
119
+ storeId?: string;
120
+ createdAt: string;
121
+ }
122
+ /** An order.reopen v1 command with the shared idempotency envelope (ADR-090). */
123
+ type OrderReopenEnvelope<P = OrderReopenPayload> = Omit<CommandEnvelope<P>, 'type' | 'version'> & {
124
+ type: 'order.reopen';
125
+ version: 1;
126
+ };
127
+ /** The reopened order's server identity, status and revision (ADR-090). */
128
+ interface OrderReopenResult {
129
+ orderId: string;
130
+ status: string;
131
+ revision?: string;
132
+ }
133
+ /** Per-command reopen refusals (ADR-090). */
134
+ type OrderReopenRejectionCode = 'payment_in_motion' | 'order_state' | 'revision_conflict' | 'forbidden';
135
+ /** A kept line's store order-item id, absent on a new line (ADR-090). */
136
+ type OrderUpdateLine = OrderCreateLine & {
137
+ storeLineId?: string;
138
+ };
139
+ /** A kept fee's store order-item id, absent on a new fee (ADR-090). */
140
+ type OrderUpdateFee = OrderCreateFee & {
141
+ storeLineId?: string;
142
+ };
143
+ /** A kept shipping charge's store order-item id, absent on a new charge (ADR-090). */
144
+ type OrderUpdateShipping = OrderCreateShipping & {
145
+ storeLineId?: string;
146
+ };
147
+ /** A payment already on the order carries its store id and is never re-taken (ADR-090). */
148
+ type OrderUpdatePayment = OrderCreatePayment & {
149
+ paymentId?: string;
150
+ };
151
+ /** The reopened sale's whole new state, checked by its named order.create version (ADR-090). */
152
+ interface OrderUpdatePayload extends Omit<OrderCreatePayload, 'lines' | 'payments' | 'fees' | 'shipping'> {
153
+ orderId: string;
154
+ baseRevision?: string;
155
+ createVersion: OrderCreateEnvelope['version'];
156
+ lines: OrderUpdateLine[];
157
+ payments: OrderUpdatePayment[];
158
+ fees?: OrderUpdateFee[];
159
+ shipping?: OrderUpdateShipping[];
160
+ }
161
+ /** An order.update v1 command with the shared idempotency envelope (ADR-090). */
162
+ type OrderUpdateEnvelope<P = OrderUpdatePayload> = Omit<CommandEnvelope<P>, 'type' | 'version'> & {
163
+ type: 'order.update';
164
+ version: 1;
165
+ };
166
+ /** Per-command update refusals; payment_in_motion reuses OrderReopenPaymentInMotionData (ADR-090). */
167
+ type OrderUpdateRejectionCode = 'payment_in_motion' | 'reopen_required' | 'revision_conflict';
168
+ /** An order.create envelope: 5 is 4 plus fees, shipping and custom lines (ADR-075), sent only for an order that has one.
169
+ * 6 is 5 plus coupons, regular prices, line attributes and Any picks (ADR-077, #495).
170
+ * 7 is 6 plus the sale's note (ADR-083). 8 is 7 plus `taxAddress` and the customer's addresses (#722).
171
+ * 9 is 8 plus each coupon's per-line amounts (`coupons[].lines`, #790), sent only when every coupon carries them; it needs no `taxAddress`.
172
+ * 11 is 10 plus the customer's addresses on a sale with no taxAddress, as informational fields (ADR-086 d2 amended).
173
+ * 12 is 11 plus the customer's tax ids, a catalogue line's edited SKU and order meta, as informational fields (ADR-092). */
174
+ type OrderCreateEnvelope = CommandEnvelope<OrderCreatePayload> & {
175
+ type: 'order.create';
176
+ version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
177
+ };
178
+ /** Outcome of processing a command. */
179
+ type CommandStatus = 'applied' | 'duplicate' | 'rejected';
180
+ /** Server order identifiers and authoritative total. */
181
+ interface CommandServerRefs {
182
+ orderId: string;
183
+ displayId?: string;
184
+ totalMinor: number;
185
+ }
186
+ /**
187
+ * Non-fatal discrepancies reported while processing a command. A server may send codes not
188
+ * listed here (a newer contract); readers go through `knownWarnings`, which drops them, and a
189
+ * warning never rejects a sale.
190
+ */
191
+ type CommandWarning = {
192
+ code: 'total_mismatch';
193
+ expectedMinor: number;
194
+ serverMinor: number;
195
+ /**
196
+ * Present if and only if the server added an untaxed rounding surcharge so its total
197
+ * matches the till's; signed, in minor units, `expectedMinor - serverMinor`, where
198
+ * `serverMinor` is the platform's total before the bridge.
199
+ */
200
+ bridgeMinor?: number;
201
+ } | {
202
+ /**
203
+ * One per variant this sale took below zero stock. `quantity` is the units of this sale that
204
+ * stock did not cover (medusapos plugin 0.2.0 and later); older servers sent the variant's
205
+ * whole shortfall under the same field.
206
+ */
207
+ code: 'insufficient_stock';
208
+ variantId: string;
209
+ quantity: number;
210
+ } | {
211
+ /**
212
+ * One warning per tax rate whose tax differs by more than the server's rounding tolerance
213
+ * (order.create v3 only); `expectedMinor` is the till's `taxByRate[].taxMinor` for that
214
+ * rate and `serverMinor` the platform's tax for it.
215
+ */
216
+ code: 'tax_rate_mismatch';
217
+ ratePpm: number;
218
+ expectedMinor: number;
219
+ serverMinor: number;
220
+ }
221
+ /**
222
+ * The sale's `customerId` (1 to 64 characters) was unknown, deleted or in another channel, so
223
+ * the sale was kept as a guest sale rather than held (ADR-070).
224
+ */
225
+ | {
226
+ code: 'customer_ignored';
227
+ customerId: string;
228
+ }
229
+ /**
230
+ * The order named a session the store did not hold when it applied the order (register v2).
231
+ * The store keeps the id on the order, and an open or alias that arrives later counts it.
232
+ * It does not mean the session was abandoned.
233
+ */
234
+ | {
235
+ code: 'register_session_unknown';
236
+ sessionId: string;
237
+ }
238
+ /**
239
+ * One warning per sale, never a refusal: each of the till's figures that differs from the
240
+ * server's own computation, once, with both values (#257). `total_mismatch` stays separate.
241
+ * `parseCommandResult` refuses a `field` it doesn't know; `knownWarnings` keeps it (a newer
242
+ * store's figure), so the type admits any non-empty string besides the three names.
243
+ */
244
+ | {
245
+ code: 'figures_mismatch';
246
+ fields: Array<{
247
+ field: 'subtotalMinor' | 'taxMinor' | 'discountMinor' | (string & {});
248
+ tillMinor: number;
249
+ serverMinor: number;
250
+ }>;
251
+ }
252
+ /**
253
+ * One warning per sale, never a refusal: each line figure that differs from the server's own computation,
254
+ * once per (line, figure), with both values. `lineId` is the line's order.create `clientLineId`.
255
+ * `figures_mismatch` stays the order-level one. `parseCommandResult` refuses a `field` it doesn't know;
256
+ * `knownWarnings` keeps it (a newer store's figure).
257
+ */
258
+ | {
259
+ code: 'line_figures_mismatch';
260
+ lines: Array<{
261
+ lineId: string;
262
+ field: 'subtotalMinor' | 'taxMinor' | 'discountMinor' | 'totalMinor' | (string & {});
263
+ tillMinor: number;
264
+ serverMinor: number;
265
+ }>;
266
+ };
267
+ /** Error reported when a command is rejected. */
268
+ interface CommandError {
269
+ code: string;
270
+ message: string;
271
+ /** A refusal's details, e.g. the server's supported version. */
272
+ data?: Record<string, unknown>;
273
+ }
274
+ /** Server result for a single command. */
275
+ interface CommandResult {
276
+ id: string;
277
+ status: CommandStatus;
278
+ serverRefs?: CommandServerRefs;
279
+ warnings?: CommandWarning[];
280
+ error?: CommandError;
281
+ register?: RegisterCommandResult;
282
+ refund?: OrderRefundResult;
283
+ reopen?: OrderReopenResult;
284
+ }
285
+ /** A register command's server figures (registers c2b applies them). */
286
+ interface RegisterCommandResult {
287
+ /** The session's server state after this command. `expected` is absent when the server redacts it (blind). */
288
+ session?: {
289
+ id: string;
290
+ status: 'open' | 'counting' | 'closed' | 'superseded';
291
+ expected?: Record<string, number>;
292
+ salesCount?: number;
293
+ /** Sent on a resume (register v2): the store session's opening time. */
294
+ openedAt?: string;
295
+ /** Sent on a resume (register v2): the store session's counted opening float. */
296
+ openingFloatMinor?: number;
297
+ };
298
+ /** The open was this device's own live session (register v2); the store keeps fromSessionId as a permanent alias of session.id. */
299
+ resumed?: {
300
+ fromSessionId: string;
301
+ };
302
+ /** The session this open took over (register v2). */
303
+ superseded?: {
304
+ sessionId: string;
305
+ openedAt?: string;
306
+ deviceId?: string;
307
+ deviceName?: string;
308
+ };
309
+ /** The register's counters: a floor for the till's own, never lowered. */
310
+ counters?: {
311
+ lastClosureNumber: number;
312
+ perpetualSalesTotalMinor: number;
313
+ perpetualRefundsTotalMinor: number;
314
+ };
315
+ /** `register.closure.submit` only. */
316
+ closure?: {
317
+ serverClosureId: string;
318
+ number: number;
319
+ expected?: Record<string, number>;
320
+ variance?: Record<string, number>;
321
+ };
322
+ }
323
+ /** Order line with client identity and price in minor units. */
324
+ interface OrderCreateLine {
325
+ clientLineId: string;
326
+ /** Required unless `custom` is set (version 5). */
327
+ variantId?: string;
328
+ /** Version 5 instruction: a non-catalogue line, without variantId; takes line and order discounts. */
329
+ custom?: {
330
+ /** Recorded title, 1–255 characters. */
331
+ name: string;
332
+ /** Recorded SKU, at most 64 characters when present. */
333
+ sku?: string;
334
+ /** Instruction, at most 64 characters; absent means the standard class. */
335
+ taxClass?: string;
336
+ /** Instruction: `none` means no tax on this line. */
337
+ taxStatus: 'taxable' | 'none';
338
+ };
339
+ title?: string;
340
+ /** Version 12 (ADR-092): a catalogue line's SKU as the cashier edited it, 1–100 characters; a custom line uses `custom.sku`. */
341
+ sku?: string;
342
+ quantity: number;
343
+ unitPriceMinor: number;
344
+ /** 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. */
345
+ regularUnitPriceMinor?: number;
346
+ /** Version 6 recorded: the variant's attribute names and values (#495), each at most 255 characters. */
347
+ attributes?: Record<string, string>;
348
+ /** Version 6: the names in attributes the cashier picked for the variant's "Any" option groups (#495 c/d). */
349
+ anyAttributes?: string[];
350
+ /**
351
+ * This line's own tax mode, when it differs from the order's `pricesIncludeTax`
352
+ * (a price that carries its own flag, D2c). Absent means the order's flag, so
353
+ * older clients and single-mode orders are unchanged.
354
+ */
355
+ taxInclusive?: boolean;
356
+ /**
357
+ * Version 2 (ADR-062): this line's total discount, its own line discounts plus its allocated share of
358
+ * the order discount, in the line's own tax mode and integer minor units. The line is taxed on
359
+ * `unitPriceMinor × quantity − discountMinor`. Present only when above 0.
360
+ * Version 4+ (#286): tax-exclusive (net) in every mode; an inclusive line's is `net(A) − net(A − D)`.
361
+ */
362
+ discountMinor?: number;
363
+ }
364
+ /** Version 6 (ADR-077): a coupon the till applied. Recorded figures, in integer minor units of the order's currency. */
365
+ interface OrderCreateCoupon {
366
+ /** The coupon code as the store knows it, 1–255 characters. */
367
+ code: string;
368
+ /** The store's id for the coupon, 1–64 characters. */
369
+ couponId: string;
370
+ /** The discount it gave, tax-exclusive, integer >= 0. */
371
+ discountMinor: number;
372
+ /** The tax on that discount, integer >= 0. */
373
+ discountTaxMinor: number;
374
+ /** Version 9 (#790): this coupon's share of each line it reduced; present on every coupon at 9, never below. */
375
+ lines?: OrderCreateCouponLine[];
376
+ }
377
+ /** Version 9 (#790): one coupon's share of one line, in integer minor units; see docs/contract/order-create-v9.md. */
378
+ interface OrderCreateCouponLine {
379
+ /** A `payload.lines[].clientLineId`. */
380
+ clientLineId: string;
381
+ /** This coupon's discount on that line, tax-exclusive, integer >= 0. */
382
+ discountMinor: number;
383
+ /** The tax on it, integer >= 0. */
384
+ discountTaxMinor: number;
385
+ }
386
+ /** Version 5: a fee, never discounted (ADR-075). */
387
+ interface OrderCreateFee {
388
+ /** Identity: UUID, stable for the order's life, at most 36 characters. */
389
+ clientFeeId: string;
390
+ /** Recorded fee title, 1–255 characters. */
391
+ name: string;
392
+ /** Instruction: integer >= 0, gross when pricesIncludeTax, net otherwise; never discounted. */
393
+ amountMinor: number;
394
+ /** Instruction: `none` means no tax on this fee. */
395
+ taxStatus: 'taxable' | 'none';
396
+ /** Instruction, at most 64 characters; absent means the standard class. */
397
+ taxClass?: string;
398
+ /** Informational till tax, integer >= 0; a server difference is total_mismatch, not a refusal. */
399
+ taxMinor: number;
400
+ }
401
+ /** Version 5: the same instructions and recorded/informational fields as a fee, never discounted. */
402
+ interface OrderCreateShipping extends Omit<OrderCreateFee, 'clientFeeId'> {
403
+ /** Identity: UUID, stable for the order's life, at most 36 characters. */
404
+ clientShippingId: string;
405
+ /** Recorded shipping method id, at most 64 characters; absent means a POS-entered charge. */
406
+ methodId?: string;
407
+ }
408
+ /** Supported order payment method. */
409
+ type PaymentMethodKind = 'cash' | 'external';
410
+ /** Order payment with client identity and amounts in minor units. */
411
+ interface OrderCreatePayment {
412
+ clientPaymentId: string;
413
+ method: PaymentMethodKind;
414
+ amountMinor: number;
415
+ tenderedMinor?: number;
416
+ changeMinor?: number;
417
+ reference?: string;
418
+ /** Version 10: the payment method's own id on the platform (a Woo gateway id, a Medusa provider id, a Vendure PaymentMethod code), 1–64 characters, no NUL. Informational: `method` still decides cash; core refuses no value by meaning. */
419
+ methodId?: string;
420
+ }
421
+ /** Version 3 (ADR-065): the receipt's display figures, integer minor units of `currency` at `exponent`. */
422
+ interface OrderCreateDisplay {
423
+ currency: string;
424
+ exponent: number;
425
+ taxInclusive: boolean;
426
+ subtotalMinor: number;
427
+ discountMinor: number;
428
+ taxMinor: number;
429
+ totalMinor: number;
430
+ orderDiscountMinor: number;
431
+ lines: Array<{
432
+ clientLineId: string;
433
+ amountMinor: number;
434
+ discounts: Array<{
435
+ discountId: string;
436
+ label?: string;
437
+ amountMinor: number;
438
+ }>;
439
+ }>;
440
+ /** Version 5 recorded figures: one row per payload fee, in the display tax mode. */
441
+ fees?: Array<{
442
+ /** Identity: the payload fee's clientFeeId. */
443
+ clientFeeId: string;
444
+ /** Recorded integer minor units, equal to the payload fee amount. */
445
+ amountMinor: number;
446
+ }>;
447
+ /** Version 5 recorded figures: one row per payload shipping charge, in the display tax mode. */
448
+ shipping?: Array<{
449
+ /** Identity: the payload shipping charge's clientShippingId. */
450
+ clientShippingId: string;
451
+ /** Recorded integer minor units, equal to the payload shipping amount. */
452
+ amountMinor: number;
453
+ }>;
454
+ /** Version 6 recorded figures: one row per payload coupon, its discount in the display tax mode. */
455
+ coupons?: Array<{
456
+ code: string;
457
+ amountMinor: number;
458
+ }>;
459
+ }
460
+ /** Version 3 (ADR-065): one tax rate's net, tax and gross, as the receipt's tax summary splits them. */
461
+ interface OrderCreateTaxRate {
462
+ ratePpm: number;
463
+ code?: string;
464
+ netMinor: number;
465
+ taxMinor: number;
466
+ grossMinor: number;
467
+ }
468
+ /** Client order data submitted by an order.create command. */
469
+ interface OrderCreatePayload {
470
+ clientOrderId: string;
471
+ createdAt: string;
472
+ currency: string;
473
+ pricesIncludeTax: boolean;
474
+ lines: OrderCreateLine[];
475
+ /** Version 5 instructions: fees in the order's tax mode; omitted when none. */
476
+ fees?: OrderCreateFee[];
477
+ /** Version 5 instructions: shipping in the order's tax mode; omitted when none. */
478
+ shipping?: OrderCreateShipping[];
479
+ /** Version 6 (ADR-077): the coupons the till applied, in the order it applied them; omitted when none.
480
+ * The store re-applies them by `code` and refuses the order with `coupon_invalid` if one no longer applies. */
481
+ coupons?: OrderCreateCoupon[];
482
+ /** Version 6: net of the coupons' `discountMinor`, as `taxMinor` is of their `discountTaxMinor`; coupons are not part of `discountMinor`. */
483
+ subtotalMinor: number;
484
+ /**
485
+ * Version 2 (ADR-062): the order's total discount, equal to Σ `lines[].discountMinor`. Present only when above 0.
486
+ * Version 4+ (#286) means every `discountMinor`, this and each line's, is tax-exclusive, so the sum still holds.
487
+ * Version 6: coupons are not included; their amounts are in `coupons[].discountMinor`.
488
+ */
489
+ discountMinor?: number;
490
+ taxMinor: number;
491
+ totalMinor: number;
492
+ payments: OrderCreatePayment[];
493
+ /** Version 3+; both or neither. */
494
+ display?: OrderCreateDisplay;
495
+ /** Version 3+; both or neither. */
496
+ taxByRate?: OrderCreateTaxRate[];
497
+ customer?: {
498
+ email?: string;
499
+ /** Version 3+: the platform's id for the customer picked at the till, a soft reference of at most 64 characters. Absent for a guest sale, or when no customer was picked. */
500
+ customerId?: string;
501
+ /** Version 8 (#722): the customer's billing address, sent at 8+ with `taxAddress` and at 11 without it. */
502
+ billing?: OrderAddress;
503
+ /** Version 8 (#722): the customer's shipping address, sent at 8+ with `taxAddress` and at 11 without it. */
504
+ shipping?: OrderAddress;
505
+ /** Version 12 (ADR-092): the customer's tax ids on this sale, at most ORDER_TAX_IDS_MAX (10). */
506
+ taxIds?: OrderCreateTaxId[];
507
+ } | null;
508
+ /** Version 8 (#722): the customer address the till taxed the sale on; always present at 8; optional at 9, and that address has a
509
+ * non-empty `country`. Absent: the store's base address. */
510
+ taxAddress?: 'billing' | 'shipping';
511
+ registerId?: string;
512
+ cashierRef?: string;
513
+ locationId?: string;
514
+ /** Version 3+: the register session the sale was taken for, stamped or late (ADR-032). A late sale names the session that refused its stamp; the server tells the two apart by the session's closure `orderIds`. Absent when the sale had no session. */
515
+ sessionId?: string;
516
+ /** Version 7 (ADR-083): the sale's note, 1 to ORDER_NOTE_MAX UTF-16 units; omitted when the sale has none. */
517
+ note?: string;
518
+ /** Version 12 (ADR-092): the order's custom fields, at most ORDER_META_MAX (50), keys unique; omitted when none. */
519
+ meta?: OrderCreateMeta[];
520
+ }
521
+ /** A customer tax id on order.create 12 (ADR-092): `type` 1–32 UTF-16 units (the connector's scheme id), `value` 1–64,
522
+ * `country` an ISO 3166-1 alpha-2 code. */
523
+ interface OrderCreateTaxId {
524
+ type: string;
525
+ value: string;
526
+ country?: string;
527
+ }
528
+ /** An order custom field on order.create 12 (ADR-092): `key` 1–255 UTF-16 units, not starting with `_`; `value` 0–ORDER_NOTE_MAX. */
529
+ interface OrderCreateMeta {
530
+ key: string;
531
+ value: string;
532
+ }
533
+ /** A customer's address on order.create v8 (#722): each field a string of at most 255 UTF-16 units; no email, which
534
+ * `customer.email` carries. */
535
+ interface OrderAddress {
536
+ firstName?: string;
537
+ lastName?: string;
538
+ company?: string;
539
+ address1?: string;
540
+ address2?: string;
541
+ city?: string;
542
+ state?: string;
543
+ postcode?: string;
544
+ country?: string;
545
+ phone?: string;
546
+ }
547
+ /** Results returned by the server for a command batch. */
548
+ interface CommandBatchResponse {
549
+ results: CommandResult[];
550
+ }
551
+ /** The `413` body for a batch over the limit (ADR-038; Front desk ruling 18). */
552
+ type BatchTooLargeBody = {
553
+ code: 'batch_too_large';
554
+ maxCommands: number;
555
+ message: string;
556
+ };
557
+
558
+ /** One ICE server, in the shape `RTCPeerConnection` takes (ADR-085 d7). */
559
+ interface IceServer {
560
+ urls: string | string[];
561
+ username?: string;
562
+ credential?: string;
563
+ }
564
+ /** The store's display advertisement from `GET /tally/v1/info` (`customerDisplay`, ADR-085 d7, d8). */
565
+ interface DisplayAdvertisement {
566
+ /** The ICE servers both peers use; `[]` is LAN-only. */
567
+ iceServers: IceServer[];
568
+ /** Whether the till posts the snapshot fallback while a display's data channel is not open. */
569
+ snapshot: boolean;
570
+ }
571
+ /** The display side's context: a display has no login, only the store's address. */
572
+ interface DisplaySignallingContext {
573
+ baseUrl: string;
574
+ fetch?: typeof globalThis.fetch;
575
+ }
576
+ /** A claim waiting for the minting till's cashier. */
577
+ interface PendingPairing {
578
+ claimId: string;
579
+ displayName: string;
580
+ /** 4 digits, shown on the display and on the till, so the cashier can see which display asks (#705). */
581
+ checkCode: string;
582
+ /** ISO 8601: the code's expiry, when an unconfirmed claim is deleted. */
583
+ expiresAt: string;
584
+ }
585
+ /** A paired display in the server's registry (ADR-085 d6). */
586
+ interface DisplayRecord {
587
+ displayId: string;
588
+ name: string;
589
+ /** The cashier who confirmed the pairing. */
590
+ cashierId: string;
591
+ /** ISO 8601 of the last successful display-side token call, or `null` when never seen. */
592
+ lastSeenAt: string | null;
593
+ /** Whether the display was seen recently (the reference server: within the last 30 s). */
594
+ connected: boolean;
595
+ }
596
+ /** The till's credential on every till-side call: its device id and the key `registerDevice` issued for it. Core treats `deviceKey` as opaque. */
597
+ interface TillDevice {
598
+ deviceId: string;
599
+ deviceKey: string;
600
+ }
601
+ /** One WebRTC signalling message; `payload` is opaque to the server. */
602
+ interface SignalMessage {
603
+ type: 'offer' | 'answer' | 'ice';
604
+ payload: string;
605
+ }
606
+ /**
607
+ * The platform-neutral signalling seam for a second-device customer display (ADR-085 d2). Each backend's plugin
608
+ * implements the routes its own way; every implementation meets this floor (d4–d6, d8, #705), which
609
+ * `displaySignallingContract` in `@tallyui/core/server` tests. A plugin may be stricter.
610
+ * Till side: every call takes a cashier session and the till's `TillDevice`; the refusal order is `forbidden` (a
611
+ * session without `customer_display.pair`), then `device_refused` (the device key), then `not_found` (an id this device
612
+ * does not own), and a refused call has no effect. Display side: no login; calls are gated by the display's token
613
+ * (`token_refused`), and each successful token call updates `lastSeenAt`. Every refusal is a `DisplaySignallingError`.
614
+ * The device key is the till's credential (TallyUI#754). An implementation compares key hashes in constant time, never
615
+ * logs the key, never puts it in an error or a response body, and never returns it after issue. The device id is an
616
+ * identifier, not a credential, anywhere, including the device id in order data (`order.create`).
617
+ */
618
+ interface DisplaySignalling {
619
+ /**
620
+ * Issues the device key for `deviceId`, needing `customer_display.pair`: 128 bits, base64url, stored only as SHA-256
621
+ * hex, and returned once, by this call only. An id that already holds a key gives `device_refused`. A pre-migration id
622
+ * (rows from before device keys, no key hash) adopts them once, logged with the cashier id. An admin reset deletes the
623
+ * device record with every display, code and pending pairing it owns, so the id registers as new; a reset never returns
624
+ * an id to the keyless pre-migration state.
625
+ */
626
+ registerDevice(ctx: SyncContext, deviceId: string): Promise<{
627
+ deviceKey: string;
628
+ }>;
629
+ /** A pairing code: 6+ digits from `crypto.getRandomValues`, single use, live at most 10 minutes; a 6th unspent code per device gives `limit`. */
630
+ mint(ctx: SyncContext, device: TillDevice): Promise<{
631
+ code: string;
632
+ expiresAt: string;
633
+ }>;
634
+ /** The live claims on codes this device minted, each with its check code. */
635
+ pending(ctx: SyncContext, device: TillDevice): Promise<PendingPairing[]>;
636
+ /**
637
+ * Confirms a claim on a code this device minted, recording the display as owned by this device and cashier. The
638
+ * display then collects its token: 128 bits, base64url, stored only as SHA-256 hex. A claim that carried a valid
639
+ * token moves that display: its old row, token and snapshot go in the same step, and this device owns the same id.
640
+ */
641
+ confirm(ctx: SyncContext, device: TillDevice, claimId: string): Promise<void>;
642
+ /** Declines a claim on a code this device minted: the pending pairing is deleted, and nothing is issued. */
643
+ decline(ctx: SyncContext, device: TillDevice, claimId: string): Promise<void>;
644
+ /** The displays this device owns. A display unseen for 30 days is pruned with its token and snapshot. */
645
+ list(ctx: SyncContext, device: TillDevice): Promise<DisplayRecord[]>;
646
+ /** Deletes the display's row, token hash and snapshot at once; the token is refused on its next call. */
647
+ forget(ctx: SyncContext, device: TillDevice, displayId: string): Promise<void>;
648
+ /** Queues a message in an owned display's inbox. */
649
+ sendSignal(ctx: SyncContext, device: TillDevice, displayId: string, message: SignalMessage): Promise<void>;
650
+ /** Drains this device's inbox: each message once, in send order, only from displays it owns. */
651
+ receiveSignals(ctx: SyncContext, device: TillDevice): Promise<Array<SignalMessage & {
652
+ displayId: string;
653
+ }>>;
654
+ /** Keeps `body` as the display's only snapshot for at most 60 s; over 204 800 UTF-8 bytes of JSON gives `too_large` and keeps the old one. */
655
+ postSnapshot(ctx: SyncContext, device: TillDevice, displayId: string, body: unknown): Promise<void>;
656
+ /**
657
+ * Claims a live code: the first claim spends it and records a pending pairing with `displayName` and a fresh 4-digit
658
+ * check code, unique among that till's live pending pairings, and returns a claim secret (128 bits, base64url, stored only as a
659
+ * hash); no token. `token` is the display's current token, if any, so a confirm moves it. A claim naming no live code
660
+ * fails and spends nothing. Failed claims are limited per source (10 a minute, IPv6 by /64 via `rateLimitSource`) and
661
+ * store-wide (100 per 10 minutes); over either, every claim is refused and spends nothing. Every refusal is `claim_refused`.
662
+ */
663
+ claim(dctx: DisplaySignallingContext, request: {
664
+ code: string;
665
+ displayName: string;
666
+ token?: string;
667
+ }): Promise<{
668
+ claimSecret: string;
669
+ checkCode: string;
670
+ }>;
671
+ /** Pending: `pending` with the check code. After the confirm the first collect gives `paired` with the token; later, declined, expired or unknown gives `collect_refused`. */
672
+ collect(dctx: DisplaySignallingContext, claimSecret: string): Promise<{
673
+ status: 'pending';
674
+ checkCode: string;
675
+ } | {
676
+ status: 'paired';
677
+ displayId: string;
678
+ token: string;
679
+ }>;
680
+ /** Queues a message in the owning till's inbox. */
681
+ displaySendSignal(dctx: DisplaySignallingContext, token: string, message: SignalMessage): Promise<void>;
682
+ /** Drains this display's own inbox: each message once, in send order. */
683
+ displayReceiveSignals(dctx: DisplaySignallingContext, token: string): Promise<SignalMessage[]>;
684
+ /** The display's latest snapshot, or `null` when none is held. */
685
+ readSnapshot(dctx: DisplaySignallingContext, token: string): Promise<unknown | null>;
686
+ }
687
+
688
+ /** The highest `order.create` contract version a store's server currently accepts (ADR-062). */
689
+ interface ServerCapabilities {
690
+ orderCreate: number;
691
+ /** The highest `register` contract version; absent or 0 means no register sync. */
692
+ register?: number;
693
+ /** The highest `order.refund` version; absent or 0 means the store takes no refunds and the app hides the action (ADR-080). */
694
+ orderRefund?: number;
695
+ /** The highest `order.reopen` version; absent or 0 means the store cannot reopen orders and the app hides the action (ADR-090). */
696
+ orderReopen?: number;
697
+ /** The highest `order.update` version; a store that lists `order.reopen` lists it (ADR-090). */
698
+ orderUpdate?: number;
699
+ /** How the store rounds tax (#287). Absent: an older server, per_order + half_away_from_zero. */
700
+ taxRounding?: TaxRounding;
701
+ /** Whether one order may carry several payments. Absent means it may: order.create's `payments` has always been a
702
+ * list. A WooCommerce store says false until its plugin records the list (`order_payments_list`). The app offers
703
+ * split tender only when this is not false. */
704
+ multiplePayments?: boolean;
705
+ /**
706
+ * What the store accepts for a fee's, a shipping charge's or a custom line's tax (order.create 5, ADR-075):
707
+ * `none` is `taxStatus: 'none'`, `classes` is a `taxClass`. Absent means neither; the UI hides what is false.
708
+ */
709
+ lineTax?: {
710
+ none: boolean;
711
+ classes: boolean;
712
+ };
713
+ /**
714
+ * Whether the store accepts an order's coupons (ADR-077). Absent means it does not: the till refuses to apply a
715
+ * coupon. WooCommerce: true only when the woocommerce-pos plugin reports 1.9.0 or later. Other platforms report it as
716
+ * `/tally/v1/info`'s `coupons: true` (#709).
717
+ */
718
+ coupons?: boolean;
719
+ /**
720
+ * The store's register approval threshold (ADR-082 d3), from the top level of `/tally/v1/info`. With
721
+ * `register >= 3`, a close whose absolute cash variance is over `thresholdMinor` needs the store's approval.
722
+ * Absent means the store sets none, and the app's own threshold applies.
723
+ */
724
+ registerApproval?: {
725
+ thresholdMinor: number;
726
+ };
727
+ /**
728
+ * A store whose plugin signals second-device customer displays (ADR-085), from `/tally/v1/info`'s top-level
729
+ * `customerDisplay`. Absent means no second-device display.
730
+ */
731
+ customerDisplay?: DisplayAdvertisement;
732
+ /** The receipt-email version a store's `/tally/v1/info` advertises as `receiptEmail: { v: n }` (vendurepos gap 12.1b).
733
+ * Absent means the store does not email receipts. */
734
+ receiptEmail?: number;
735
+ /** The platform plugin's own contract version, from `/tally/v1/info`'s top-level `pluginContract` (#1114). Absent when not sent or malformed; each connector says what a version adds. */
736
+ pluginContract?: number;
737
+ }
738
+ /** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
739
+ type TaxRounding = {
740
+ granularity: 'per_order' | 'per_line_items' | 'per_rate_group_items';
741
+ mode: 'half_away_from_zero' | 'half_up';
742
+ } | {
743
+ granularity: 'woocommerce';
744
+ roundAtSubtotal: boolean;
745
+ } | {
746
+ granularity: 'custom';
747
+ };
748
+ interface SyncContext {
749
+ /** Unique connector identifier (used as replication namespace) */
750
+ connectorId: string;
751
+ /** Base URL for the API */
752
+ baseUrl: string;
753
+ /** Authenticated headers */
754
+ headers: Record<string, string>;
755
+ /** Optional abort signal */
756
+ signal?: AbortSignal;
757
+ /** From `storeSettings().pricingContext`; opaque to the app; the connector prices documents with it. Never logged. */
758
+ pricingContext?: Record<string, string>;
759
+ /** The store's contract capabilities (ADR-062), copied from the sign-in result. */
760
+ capabilities?: ServerCapabilities;
761
+ /** The fetch the connector sends its requests with; defaults to globalThis.fetch. A host passes a wrapper
762
+ * here, for example @tallyui/database meteredFetch, to count requests. Resolved per request. */
763
+ fetch?: typeof globalThis.fetch;
764
+ }
765
+
766
+ /** @deprecated Use `CommandError` from `@tallyui/core`; kept for plugins migrating from local copies. */
767
+ type CommandErrorWithData = CommandError;
768
+ /** @deprecated Use `OrderCreatePayload` from `@tallyui/core`; kept for plugins migrating from local copies. */
769
+ type OrderCreatePayloadV3 = OrderCreatePayload;
770
+ declare function fiscalFiguresErrors(payload: OrderCreatePayload): string[];
771
+
772
+ /**
773
+ * The till's capability: the order.create versions `toOrderCreateEnvelope` can produce. It is not what a server
774
+ * supports (#297). A server passes its own lists to `precheckCommand`, and its /info advertises them, gated by its
775
+ * own check (Front desk, 2026-09-30): 4 (#286) is 3 with every discountMinor tax-exclusive, and a plugin
776
+ * advertises it only once it handles it.
777
+ * 5 (ADR-075) adds fees, shipping and custom lines; 6 (ADR-077) adds coupons, regular prices, line
778
+ * attributes and Any picks (#495); a plugin advertises each only once it handles it.
779
+ * 7 (ADR-083) adds the sale note; 8 (#722) adds `taxAddress` and the customer's addresses; 9 (#790) adds each coupon's per-line amounts.
780
+ * 10 adds each payment's methodId (ruling A, 2026-11-18).
781
+ * 11 is 10 plus the customer's billing and shipping on a sale not taxed by address (ADR-086 d2 as amended 2026-11-19).
782
+ * 12 is 11 plus the customer's tax ids, a catalogue line's edited SKU and order meta, as informational fields (ADR-092).
783
+ */
784
+ declare const SUPPORTED_ORDER_CREATE_VERSIONS: readonly number[];
785
+ /** The till's capability for the contract versions shared by all five register commands; a server passes its own. */
786
+ declare const SUPPORTED_REGISTER_VERSIONS: readonly number[];
787
+ /** The till's capability for order.refund versions (ADR-080); a server passes its own. */
788
+ declare const SUPPORTED_ORDER_REFUND_VERSIONS: readonly number[];
789
+ /** The till's capability for order.reopen versions (ADR-090); a server passes its own. */
790
+ declare const SUPPORTED_ORDER_REOPEN_VERSIONS: readonly number[];
791
+ /** The till's capability for order.update versions (ADR-090); a server passes its own. */
792
+ declare const SUPPORTED_ORDER_UPDATE_VERSIONS: readonly number[];
793
+
794
+ /** The ADR-038 batch limit; a server answers more with 413 and a BatchTooLargeBody. */
795
+ declare const MAX_COMMANDS_PER_BATCH = 50;
796
+ /** The longest order.create `note` (version 7, ADR-083), in UTF-16 code units. WCPOS v2's order note has no cap; this bounds the wire. */
797
+ declare const ORDER_NOTE_MAX = 1000;
798
+
799
+ /** An envelope validateBatch accepted: every field's shape is checked, and its version is any positive
800
+ * safe integer (precheckCommand decides which versions this server supports). */
801
+ type ValidatedCommandEnvelope = (Omit<CommandEnvelope<Record<string, unknown>>, 'version'> & {
802
+ type: 'order.create';
803
+ version: number;
804
+ }) | RegisterCommandEnvelope<Record<string, unknown>> | (Omit<CommandEnvelope<Record<string, unknown>>, 'type' | 'version'> & {
805
+ type: 'order.refund';
806
+ version: number;
807
+ }) | (Omit<CommandEnvelope<Record<string, unknown>>, 'type' | 'version'> & {
808
+ type: 'order.reopen';
809
+ version: number;
810
+ }) | (Omit<CommandEnvelope<Record<string, unknown>>, 'type' | 'version'> & {
811
+ type: 'order.update';
812
+ version: number;
813
+ });
814
+ /** Validates every envelope before any command is claimed. */
815
+ declare function validateBatch(body: unknown): {
816
+ ok: true;
817
+ commands: ValidatedCommandEnvelope[];
818
+ } | {
819
+ ok: false;
820
+ status: 400;
821
+ message: string;
822
+ } | {
823
+ ok: false;
824
+ status: 413;
825
+ message: string;
826
+ body: BatchTooLargeBody;
827
+ };
828
+ /**
829
+ * The rejection a batch returns for this command before any executor runs, or undefined
830
+ * when the command goes on to the plugin's executor. A plugin's batch handler calls
831
+ * validateBatch once, then, for each command in order: the shape check (payloadShapeErrors:
832
+ * types and NUL) first, before any database access, because a NUL in clientOrderId would make
833
+ * the lookup itself fail; then the plugin's own replay and collision lookups; then
834
+ * precheckCommand (versions, string lengths via payloadBoundErrors, fiscal figures); then the
835
+ * claim, in the executor (order.create; register commands follow ADR-068). It pushes any result
836
+ * one of those steps returns and moves on.
837
+ *
838
+ * For order.update the shape check is updatePayloadErrors (ADR-090): it adds the update's store ids, and below
839
+ * createVersion 5 precheckCommand does not repeat it.
840
+ *
841
+ * The replay lookup goes before precheckCommand so an already-applied command always replays
842
+ * as `duplicate`, even once a later @tallyui/core tightens what precheckCommand accepts.
843
+ *
844
+ * `supported` is the SERVER's own list (what its /info advertises), never core's constants, which are the
845
+ * till's capability (#297). The version check, the `unsupported_version` message and its `data` all use it:
846
+ * `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1], orderRefund: [1], orderReopen: [1], orderUpdate: [1] })` (`orderRefund`, `orderReopen` and `orderUpdate` are optional).
847
+ */
848
+ declare function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCommandEnvelope, 'id' | 'type' | 'version' | 'payload'>, supported: {
849
+ orderCreate: readonly number[];
850
+ register: readonly number[];
851
+ orderRefund?: readonly number[];
852
+ orderReopen?: readonly number[];
853
+ orderUpdate?: readonly number[];
854
+ }): CommandResult | undefined;
855
+
856
+ /**
857
+ * A plugin's batch handler stops at the first in-progress or transient command and returns that
858
+ * outcome for the whole batch; otherwise it returns 200 with every result in order.
859
+ */
860
+ type BatchOutcome = {
861
+ status: 200;
862
+ body: CommandBatchResponse;
863
+ } | {
864
+ status: 409;
865
+ body: {
866
+ code: 'in_progress';
867
+ id: string;
868
+ };
869
+ } | {
870
+ status: 503;
871
+ body: {
872
+ code: 'transient';
873
+ id: string;
874
+ message: 'Temporary failure, retry later.';
875
+ };
876
+ };
877
+ declare function inProgressOutcome(id: string): BatchOutcome;
878
+ /** The message is fixed so a server never leaks its internal error (log that separately). */
879
+ declare function transientOutcome(id: string): BatchOutcome;
880
+
881
+ type OrderRejectionCode = 'unknown_variant' | 'invalid_quantity' | 'underpaid' | 'unsupported_currency';
882
+ type Rejection = {
883
+ code: OrderRejectionCode;
884
+ message: string;
885
+ };
886
+ declare function totalWarnings(expectedMinor: number, serverMinor: number): CommandWarning[];
887
+
888
+ /** parseCommandResult's refusal; its message names the first bad field. A plugin maps it
889
+ * to its own invalid-data error (e.g. Medusa's MedusaError INVALID_DATA). */
890
+ declare class CommandResultError extends Error {
891
+ constructor(message: string);
892
+ }
893
+ /** Validates a CommandResult (e.g. one read back from the ledger). Throws
894
+ * CommandResultError naming the first bad field. */
895
+ declare function parseCommandResult(value: unknown): CommandResult;
896
+
897
+ /** Shape errors before a register command claims a ledger row. Unknown top-level keys are allowed. */
898
+ declare function registerPayloadErrors(type: string, payload: unknown): string[];
899
+
900
+ /** Strict shape errors per ADR-070 and ADR-080 for order.refund v1; plugins run this before any lookup. */
901
+ declare function refundPayloadErrors(payload: unknown): string[];
902
+
903
+ /** Strict shape errors per ADR-070 and ADR-090 for order.reopen v1; plugins run this before any lookup. */
904
+ declare function reopenPayloadErrors(payload: unknown): string[];
905
+
906
+ /** Strict update identity and order.create body shape errors, at most ten (ADR-090). */
907
+ declare function updatePayloadErrors(payload: unknown): string[];
908
+
909
+ /**
910
+ * A session's expected figures per method: the counted float in cash, plus each order's payments, plus paid_in
911
+ * and minus paid_out movements that are not voided. The plugin chooses which orders count (for Medusa: completed,
912
+ * archived and cancelled POS orders, so a received sale stays counted after an admin archives or cancels it) and
913
+ * passes each order's recorded POS payments; this function only sums. Refunds made in the session (by the refund's
914
+ * own sessionId, ADR-080) lower expected per method.
915
+ */
916
+ declare function deriveSessionFigures(input: {
917
+ countedFloatMinor: number;
918
+ orders: {
919
+ payments: {
920
+ method: string;
921
+ amountMinor: number;
922
+ }[];
923
+ }[];
924
+ movements: {
925
+ id: string;
926
+ type: 'paid_in' | 'paid_out' | 'no_sale' | 'void';
927
+ amountMinor: number;
928
+ voids: string | null;
929
+ }[];
930
+ refunds?: {
931
+ byMethod: Record<string, number>;
932
+ }[];
933
+ }): {
934
+ expected: Record<string, number>;
935
+ salesCount: number;
936
+ refundsTotalMinor?: number;
937
+ };
938
+ declare function deriveVariance(counted: Record<string, number>, expected: Record<string, number>): Record<string, number>;
939
+
940
+ type RegisterConflictCode = 'register_session_already_open' | 'register_session_superseded' | 'register_supersede_forbidden' | 'register_session_closed' | 'register_closure_exists' | 'register_closure_number_invalid' | 'register_approval_required' | 'register_approval_invalid';
941
+ type RegisterOutcome = {
942
+ kind: 'ok';
943
+ register: RegisterCommandResult;
944
+ } | {
945
+ kind: 'conflict';
946
+ code: RegisterConflictCode;
947
+ data?: Record<string, unknown>;
948
+ } | {
949
+ kind: 'invalid';
950
+ message: string;
951
+ };
952
+
953
+ /** Every error.code a plugin may put on a rejected result (ADR-038 and its amendments, ADR-068, ADR-082). */
954
+ 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 | OrderReopenRejectionCode | OrderUpdateRejectionCode;
955
+ /**
956
+ * The rejected result for a platform-native error the plugin has judged permanent (a replay would fail
957
+ * the same way, e.g. a Vendure ErrorResult code) and the contract has no code for. `platform_error` is
958
+ * for `order.create` and `order.refund` (ADR-080) and `order.reopen` and `order.update` (ADR-090): a rejected register command halts that register's queue until c2c,
959
+ * so register refusals use the ADR-068 codes.
960
+ *
961
+ * Return it only when the platform made no durable change for this command: the plugin threw so its
962
+ * transaction rolled back, or it compensated. Otherwise the plugin applies the command (with a warning
963
+ * where one fits), or compensates the partial write and then stays transient (ADR-039). The till offers
964
+ * Retry for `platform_error` and requeue resends under a new command id, and a transient result resends
965
+ * the same id after the ledger claim is released, so either would duplicate a partly written sale.
966
+ *
967
+ * It is stored in the ledger and replayed as recorded; the order shows under "Needs attention" with
968
+ * Retry. An error the plugin can't classify stays transient (503, retried), never platform_error.
969
+ */
970
+ declare function platformErrorResult(id: string, platformCode: string, platformMessage: string): CommandResult;
971
+ /**
972
+ * The rejected result for an exception from the plugin's own code (a programming error, not the
973
+ * database, the network, or an unknown SQLSTATE), raised after a complete rollback or a complete
974
+ * compensation, so that nothing of the sale remains, in the database or outside it. "The plugin's own
975
+ * code" excludes an error thrown from inside the platform SDK, the database client or the HTTP client.
976
+ *
977
+ * It is stored in the ledger and replayed as recorded, because it fails the same way on every retry
978
+ * and a retry loop would hide the bug. The message is generic so no internal detail reaches the till;
979
+ * the correlation id links it to the plugin's log.
980
+ *
981
+ * Database, network, unknown-SQLSTATE and any other unclassifiable errors stay transient (503), never
982
+ * `internal_error`. `order.create` and `order.refund` (ADR-080) and `order.reopen` and `order.update` (ADR-090), as for `platform_error`.
983
+ *
984
+ * See ADR-038's `internal_error` amendment (needs-admin on a failed compensation; on Vendure only
985
+ * before the first write).
986
+ */
987
+ declare function internalErrorResult(id: string, correlationId: string): CommandResult;
988
+
989
+ /** What the contract suite drives; each plugin's U7 implements it for its own routes. */
990
+ interface DisplaySignallingHarness {
991
+ signalling: DisplaySignalling;
992
+ /** A cashier session on the server, with or without `customer_display.pair`. */
993
+ till(cashier: {
994
+ cashierId: string;
995
+ canPair: boolean;
996
+ }): SyncContext | Promise<SyncContext>;
997
+ /** A display-side context whose requests come from `source`, an IPv4 or IPv6 address. */
998
+ display(source: string): DisplaySignallingContext;
999
+ /** Moves the server's clock. */
1000
+ advance(ms: number): Promise<void>;
1001
+ /** Everything the server persists, serialised. */
1002
+ storedText(): Promise<string>;
1003
+ storedCounts(): Promise<{
1004
+ codes: number;
1005
+ pending: number;
1006
+ displays: number;
1007
+ snapshots: number;
1008
+ devices: number;
1009
+ }>;
1010
+ /** Writes a pre-migration till: a device with no key, owning one paired display with a token. */
1011
+ seedLegacyDevice(deviceId: string): Promise<{
1012
+ displayId: string;
1013
+ token: string;
1014
+ }>;
1015
+ /** Every adoption of a pre-migration device id by `registerDevice`, in order. */
1016
+ adoptionLog(): Promise<Array<{
1017
+ deviceId: string;
1018
+ cashierId: string;
1019
+ }>>;
1020
+ }
1021
+ /** The ADR-085 U2 reference server: every rule of the seam, in memory, with lazy pruning on every call. */
1022
+ declare function createMemoryDisplaySignalling(options?: {
1023
+ now?: () => number;
1024
+ }): {
1025
+ signalling: DisplaySignalling;
1026
+ harness: DisplaySignallingHarness;
1027
+ };
1028
+
1029
+ /**
1030
+ * The security floor of ADR-085 d4–d6 and d8, and #705, as runner-agnostic cases: each builds a fresh harness and
1031
+ * throws on failure. Each plugin's connector runs it against its own routes:
1032
+ * `for (const c of displaySignallingContract(make)) it(c.name, c.run);`
1033
+ */
1034
+ declare function displaySignallingContract(makeHarness: () => Promise<DisplaySignallingHarness>): Array<{
1035
+ name: string;
1036
+ run: () => Promise<void>;
1037
+ }>;
1038
+
1039
+ export { type BatchOutcome, type BatchTooLargeBody, type CommandErrorWithData, type CommandRejectionCode, CommandResultError, type DisplaySignallingHarness, MAX_COMMANDS_PER_BATCH, ORDER_NOTE_MAX, type OrderCreateDisplay, type OrderCreatePayloadV3, type OrderCreateTaxRate, type OrderRejectionCode, type RegisterConflictCode, type RegisterOutcome, type Rejection, SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_ORDER_REFUND_VERSIONS, SUPPORTED_ORDER_REOPEN_VERSIONS, SUPPORTED_ORDER_UPDATE_VERSIONS, SUPPORTED_REGISTER_VERSIONS, type ValidatedCommandEnvelope, canonicalJson, commandFingerprint, createMemoryDisplaySignalling, currencyDecimals, deriveSessionFigures, deriveVariance, displaySignallingContract, fiscalFiguresErrors, inProgressOutcome, internalErrorResult, majorToMinor, minorToMajor, minorUnitDigits, parseCommandResult, payloadBoundErrors, payloadShapeErrors, platformErrorResult, precheckCommand, ratePpmFromPercent, refundPayloadErrors, registerPayloadErrors, reopenPayloadErrors, totalWarnings, transientOutcome, updatePayloadErrors, validateBatch };