@tallyui/core 2.0.0 → 3.0.0-next.1

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-C4PWPOKO.js +18 -0
  2. package/dist/commands-BW4YYgRG.d.ts +306 -0
  3. package/dist/index.d.ts +247 -130
  4. package/dist/index.js +210 -22
  5. package/dist/rxdb/index.d.ts +5 -9
  6. package/dist/server/index.d.ts +213 -0
  7. package/dist/server/index.js +591 -0
  8. package/package.json +8 -2
  9. package/src/commands.ts +1 -1
  10. package/src/context/connector-context.tsx +30 -1
  11. package/src/index.ts +17 -5
  12. package/src/known-warnings.ts +77 -0
  13. package/src/replication/combine.ts +13 -7
  14. package/src/replication/reconcile-feed.ts +73 -20
  15. package/src/rxdb/read-fresh.ts +3 -7
  16. package/src/rxdb/watch-fresh.ts +2 -2
  17. package/src/rxdb-remote-version-mismatch.ts +30 -0
  18. package/src/server/__fixtures__/fingerprint-vectors.json +139 -0
  19. package/src/server/__fixtures__/order-create-v3.json +97 -0
  20. package/src/server/batch-outcome.ts +19 -0
  21. package/src/server/batch.ts +112 -0
  22. package/src/server/command-result.ts +138 -0
  23. package/src/server/fingerprint.ts +18 -0
  24. package/src/server/fiscal-figures.ts +84 -0
  25. package/src/server/index.ts +20 -0
  26. package/src/server/money.ts +34 -0
  27. package/src/server/order-payload-shape.ts +112 -0
  28. package/src/server/register-figures.ts +32 -0
  29. package/src/server/register-outcome.ts +12 -0
  30. package/src/server/register-payload-shape.ts +86 -0
  31. package/src/server/rejection-codes.ts +49 -0
  32. package/src/server/total-warnings.ts +10 -0
  33. package/src/server/versions.ts +9 -0
  34. package/src/sync-notice.ts +26 -0
  35. package/src/types/commands.ts +138 -9
  36. package/src/types/connector.ts +63 -1
  37. package/src/types/customers.ts +26 -0
  38. package/src/types/index.ts +9 -2
  39. package/src/types/reconcile.ts +40 -0
  40. package/src/types/replication.ts +6 -0
  41. package/src/types/store-settings.ts +6 -0
  42. package/src/types/traits/product.ts +7 -0
  43. package/src/unauthorized.ts +15 -0
package/dist/index.js CHANGED
@@ -1,7 +1,47 @@
1
+ import {
2
+ COMMANDS_PATH,
3
+ MAX_COMMANDS_PER_BATCH,
4
+ PROTOCOL_HEADER,
5
+ PROTOCOL_VERSION,
6
+ isCommandBatchResponse
7
+ } from "./chunk-C4PWPOKO.js";
8
+
1
9
  // src/types/connector.ts
2
10
  function resolveCapabilities(fresh, stored) {
3
11
  return fresh ?? stored;
4
12
  }
13
+ var GRANULARITIES = ["per_order", "per_line_items", "per_rate_group_items"];
14
+ var MODES = ["half_away_from_zero", "half_up"];
15
+ function parseTaxRounding(value, warn) {
16
+ if (value === void 0) return void 0;
17
+ const { granularity, mode } = value ?? {};
18
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
19
+ if (granularity === "custom") return { granularity };
20
+ if (GRANULARITIES.includes(granularity) && MODES.includes(mode)) {
21
+ return { granularity, mode };
22
+ }
23
+ }
24
+ warn?.(`ignoring a malformed taxRounding, so the default applies: ${JSON.stringify(value)}`);
25
+ return void 0;
26
+ }
27
+ var maxVersion = (list) => {
28
+ const valid = Array.isArray(list) ? list.filter((v) => typeof v === "number" && Number.isSafeInteger(v) && v > 0) : [];
29
+ return valid.length > 0 ? Math.max(...valid) : void 0;
30
+ };
31
+ function parseInfoCapabilities(body, warn) {
32
+ const { contracts, taxRounding } = body ?? {};
33
+ const register = maxVersion(contracts?.register);
34
+ const rounding = parseTaxRounding(taxRounding);
35
+ if (taxRounding !== void 0 && rounding === void 0) {
36
+ warn?.(`malformed taxRounding: rounding is unknown, so settings wait: ${JSON.stringify(taxRounding)}`);
37
+ return void 0;
38
+ }
39
+ return {
40
+ orderCreate: maxVersion(contracts?.["order.create"]) ?? 1,
41
+ ...register !== void 0 ? { register } : {},
42
+ ...rounding ? { taxRounding: rounding } : {}
43
+ };
44
+ }
5
45
 
6
46
  // src/sign-in.ts
7
47
  var SignInError = class extends Error {
@@ -15,6 +55,43 @@ var SignInError = class extends Error {
15
55
  }
16
56
  };
17
57
 
58
+ // src/unauthorized.ts
59
+ var ConnectorUnauthorizedError = class extends Error {
60
+ code;
61
+ fixedBy;
62
+ /** Set by meaning, not copied from the HTTP answer: a backend that answers both with the same code decides first (Vendure's session probe). */
63
+ status;
64
+ constructor(message, status) {
65
+ super(message);
66
+ this.name = "ConnectorUnauthorizedError";
67
+ this.status = status;
68
+ this.code = status === 401 ? "unauthorized" : "forbidden";
69
+ this.fixedBy = status === 401 ? "till" : "store";
70
+ }
71
+ };
72
+
73
+ // src/rxdb-remote-version-mismatch.ts
74
+ var REMOTE_CREATE_PREFIX = "could not create instance ";
75
+ function isRxdbRemoteVersionMismatch(error) {
76
+ const { code, rxdb, message } = typeof error === "object" && error !== null ? error : {};
77
+ if (code === "RM1" && (rxdb ?? true) === true) return true;
78
+ const text = typeof error === "string" ? error : message;
79
+ if (typeof text !== "string" || !text.startsWith(REMOTE_CREATE_PREFIX)) return false;
80
+ try {
81
+ const wrapped = JSON.parse(text.slice(REMOTE_CREATE_PREFIX.length));
82
+ return wrapped?.rxdb === true && wrapped.code === "RM1";
83
+ } catch {
84
+ return false;
85
+ }
86
+ }
87
+
88
+ // src/sync-notice.ts
89
+ function errorKind(error) {
90
+ if (typeof error !== "object" || error === null) return "transient";
91
+ const { fixedBy, code } = error;
92
+ return (fixedBy === "till" || fixedBy === "store") && typeof code === "string" ? fixedBy : "transient";
93
+ }
94
+
18
95
  // src/store-settings.ts
19
96
  var StoreSettingsError = class extends Error {
20
97
  code;
@@ -27,16 +104,21 @@ var StoreSettingsError = class extends Error {
27
104
  }
28
105
  };
29
106
 
30
- // src/commands.ts
31
- var COMMANDS_PATH = "/tally/v1/commands";
32
- var PROTOCOL_HEADER = "X-Tally-Protocol";
33
- var PROTOCOL_VERSION = 1;
34
- var MAX_COMMANDS_PER_BATCH = 50;
35
- function isCommandBatchResponse(value) {
36
- return typeof value === "object" && value !== null && "results" in value && Array.isArray(value.results) && value.results.every(
37
- (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")
38
- );
39
- }
107
+ // src/types/customers.ts
108
+ var customerTraits = {
109
+ getId: (customer) => customer.id,
110
+ getName: (customer) => customer.name,
111
+ getEmail: (customer) => customer.email,
112
+ getPhone: (customer) => customer.phone,
113
+ getAddressSummary: () => void 0
114
+ };
115
+ var CustomerServiceError = class extends Error {
116
+ constructor(code, message) {
117
+ super(message);
118
+ this.code = code;
119
+ this.name = "CustomerServiceError";
120
+ }
121
+ };
40
122
 
41
123
  // src/money.ts
42
124
  var digitsCache = /* @__PURE__ */ new Map();
@@ -142,6 +224,66 @@ function findVariantByCode(variants, code) {
142
224
  return variants.find((variant) => variant.barcode?.trim().toLowerCase() === normalized) ?? variants.find((variant) => variant.sku?.trim().toLowerCase() === normalized);
143
225
  }
144
226
 
227
+ // src/known-warnings.ts
228
+ function isSafeInt(value) {
229
+ return typeof value === "number" && Number.isSafeInteger(value);
230
+ }
231
+ function figuresMismatchFields(fields) {
232
+ if (!Array.isArray(fields) || fields.length === 0) return null;
233
+ const rebuilt = [];
234
+ for (const entry of fields) {
235
+ if (typeof entry !== "object" || entry === null) return null;
236
+ const { field, tillMinor, serverMinor } = entry;
237
+ if (typeof field !== "string" || field === "" || rebuilt.some((kept) => kept.field === field)) return null;
238
+ if (!isSafeInt(tillMinor) || !isSafeInt(serverMinor) || tillMinor === serverMinor) return null;
239
+ rebuilt.push({ field, tillMinor, serverMinor });
240
+ }
241
+ return rebuilt;
242
+ }
243
+ function knownWarnings(warnings) {
244
+ if (!Array.isArray(warnings)) return [];
245
+ const kept = [];
246
+ for (const item of warnings) {
247
+ if (typeof item !== "object" || item === null || Array.isArray(item)) continue;
248
+ const warning = item;
249
+ switch (warning.code) {
250
+ case "total_mismatch": {
251
+ if (!isSafeInt(warning.expectedMinor) || !isSafeInt(warning.serverMinor)) continue;
252
+ const { bridgeMinor } = warning;
253
+ const validBridge = isSafeInt(bridgeMinor) && bridgeMinor !== 0 && bridgeMinor === warning.expectedMinor - warning.serverMinor;
254
+ kept.push(validBridge ? { code: "total_mismatch", expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor, bridgeMinor } : { code: "total_mismatch", expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor });
255
+ break;
256
+ }
257
+ case "insufficient_stock": {
258
+ if (typeof warning.variantId !== "string" || warning.variantId === "") continue;
259
+ if (!isSafeInt(warning.quantity) || warning.quantity < 1) continue;
260
+ kept.push({ code: "insufficient_stock", variantId: warning.variantId, quantity: warning.quantity });
261
+ break;
262
+ }
263
+ case "tax_rate_mismatch": {
264
+ if (!isSafeInt(warning.ratePpm) || warning.ratePpm < 0) continue;
265
+ if (!isSafeInt(warning.expectedMinor) || !isSafeInt(warning.serverMinor)) continue;
266
+ kept.push({ code: "tax_rate_mismatch", ratePpm: warning.ratePpm, expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor });
267
+ break;
268
+ }
269
+ case "customer_ignored": {
270
+ const { customerId } = warning;
271
+ if (typeof customerId !== "string" || customerId === "" || customerId.length > 64) continue;
272
+ kept.push({ code: "customer_ignored", customerId });
273
+ break;
274
+ }
275
+ case "figures_mismatch": {
276
+ const fields = figuresMismatchFields(warning.fields);
277
+ if (fields !== null) kept.push({ code: "figures_mismatch", fields });
278
+ break;
279
+ }
280
+ default:
281
+ continue;
282
+ }
283
+ }
284
+ return kept;
285
+ }
286
+
145
287
  // src/utils/compare-ids.ts
146
288
  var INTEGER_STRING = /^\d+$/;
147
289
  function compareIds(a, b) {
@@ -179,6 +321,7 @@ function combinePullAdapters(adapters, options = {}) {
179
321
  }
180
322
  return {
181
323
  pull: {
324
+ batchSize: options.batchSize,
182
325
  async handler(lastCheckpoint, batchSize, context) {
183
326
  let previous = lastCheckpoint;
184
327
  if (options.legacyKey && previous && typeof previous === "object" && Object.keys(previous).length && !keys.some((key) => key in previous)) {
@@ -192,14 +335,15 @@ function combinePullAdapters(adapters, options = {}) {
192
335
  }
193
336
  previous = seeded;
194
337
  }
195
- const byId = /* @__PURE__ */ new Map();
338
+ const keyOf2 = options.key ?? ((doc) => doc.id);
339
+ const byKey = /* @__PURE__ */ new Map();
196
340
  const checkpoint = {};
197
341
  for (const key of keys) {
198
342
  const result = await adapters[key].pull.handler(previous?.[key], batchSize, context);
199
- for (const doc of result.documents) byId.set(doc.id, doc);
343
+ for (const doc of result.documents) byKey.set(keyOf2(doc), doc);
200
344
  checkpoint[key] = { ...previous?.[key], ...result.checkpoint };
201
345
  }
202
- return { documents: [...byId.values()], checkpoint };
346
+ return { documents: [...byKey.values()], checkpoint };
203
347
  }
204
348
  }
205
349
  };
@@ -207,11 +351,14 @@ function combinePullAdapters(adapters, options = {}) {
207
351
 
208
352
  // src/replication/reconcile-feed.ts
209
353
  var MAX_CHUNK = 1e3;
210
- function createReconcileFeed({ fetchByIds }) {
354
+ function createReconcileFeed(options) {
355
+ const keyed = "key" in options && typeof options.key === "function" ? options : void 0;
356
+ const docKey = keyed ? keyed.key : (doc) => doc.id;
357
+ const fetch = (chunk, context) => keyed ? keyed.fetchByIds(chunk.map((e) => ({ key: keyOf(e), local: e.local, remote: e.remote })), context) : options.fetchByIds(chunk.map(keyOf), context);
211
358
  let queue = /* @__PURE__ */ new Map();
212
359
  const merge = (prior, e) => ({ ...e, refreshOnly: Boolean(e.refreshOnly) && (prior?.refreshOnly ?? true) });
213
360
  const enqueue = (entries) => {
214
- for (const e of entries) queue.set(e.id, merge(queue.get(e.id), e));
361
+ for (const e of entries) queue.set(keyOf(e), merge(queue.get(keyOf(e)), e));
215
362
  };
216
363
  const adapter = {
217
364
  pull: {
@@ -223,18 +370,26 @@ function createReconcileFeed({ fetchByIds }) {
223
370
  const documents = [];
224
371
  for (let i = 0; i < entries.length; i += MAX_CHUNK) {
225
372
  const chunk = entries.slice(i, i + MAX_CHUNK);
226
- const fetched = await fetchByIds(chunk.map((e) => e.id), context);
227
- const byId = new Map(fetched.map((doc) => [doc.id, doc]));
373
+ const toFetch = chunk.filter((e) => !e.tombstone);
374
+ const fetched = toFetch.length ? await fetch(toFetch, context) : [];
375
+ const byKey = new Map(fetched.map((doc) => [docKey(doc), doc]));
376
+ const byRemote = keyed?.remote && new Map(fetched.map((doc) => [keyed.remote(doc), doc]));
377
+ const pushed = /* @__PURE__ */ new Set();
228
378
  for (const entry of chunk) {
229
- const doc = byId.get(entry.id);
230
- if (doc) documents.push({ ...doc, _deleted: false });
231
- else if (!entry.refreshOnly) documents.push({ ...entry.local, _deleted: true });
379
+ const doc = entry.tombstone ? void 0 : byKey.get(keyOf(entry)) ?? (entry.local === void 0 && entry.remote !== void 0 && byRemote ? byRemote.get(entry.remote) : void 0);
380
+ const moved = !entry.tombstone && !doc && entry.local !== void 0 && entry.remote !== void 0 && byRemote ? byRemote.get(entry.remote) : void 0;
381
+ const fetchedDoc = doc ?? moved;
382
+ if (fetchedDoc && !pushed.has(fetchedDoc)) {
383
+ documents.push({ ...fetchedDoc, _deleted: fetchedDoc._deleted ?? false });
384
+ pushed.add(fetchedDoc);
385
+ }
386
+ if (!doc && !entry.refreshOnly && entry.local) documents.push({ ...entry.local, _deleted: true });
232
387
  }
233
388
  }
234
389
  return { documents, checkpoint: { n: (lastCheckpoint?.n ?? 0) + 1 } };
235
390
  } catch (error) {
236
- const restored = new Map(entries.map((e) => [e.id, e]));
237
- for (const [id, e] of queue) restored.set(id, merge(restored.get(id), e));
391
+ const restored = new Map(entries.map((e) => [keyOf(e), e]));
392
+ for (const [key, e] of queue) restored.set(key, merge(restored.get(key), e));
238
393
  queue = restored;
239
394
  throw error;
240
395
  }
@@ -243,6 +398,9 @@ function createReconcileFeed({ fetchByIds }) {
243
398
  };
244
399
  return { adapter, enqueue };
245
400
  }
401
+ function keyOf(entry) {
402
+ return entry.key ?? entry.id;
403
+ }
246
404
 
247
405
  // src/context/connector-context.tsx
248
406
  import { createContext, useContext, useMemo } from "react";
@@ -283,6 +441,26 @@ function useProductStock(doc) {
283
441
  const stock = getProductStock(doc, connector.traits.product, adapter, overlay);
284
442
  return adapter && asOf ? { ...stock, asOf } : stock;
285
443
  }
444
+ function useStockOverlaid(products) {
445
+ const connector = useContext(ConnectorContext);
446
+ const { overlay } = useContext(StockOverlayContext);
447
+ const adapter = connector?.reconcile?.stock;
448
+ return useMemo(() => {
449
+ if (!adapter || !overlay) return products;
450
+ let changed = false;
451
+ const mapped = products.map((doc) => {
452
+ const next = withStockOverlay(doc, adapter, overlay);
453
+ if (next !== doc) changed = true;
454
+ return next;
455
+ });
456
+ return changed ? mapped : products;
457
+ }, [products, overlay, adapter]);
458
+ }
459
+ function useStockOverlayAsOf() {
460
+ const connector = useContext(ConnectorContext);
461
+ const { asOf } = useContext(StockOverlayContext);
462
+ return connector?.reconcile?.stock ? asOf : void 0;
463
+ }
286
464
  function useCustomerTraits() {
287
465
  const connector = useConnector();
288
466
  return connector.traits.customer;
@@ -290,6 +468,8 @@ function useCustomerTraits() {
290
468
  export {
291
469
  COMMANDS_PATH,
292
470
  ConnectorProvider,
471
+ ConnectorUnauthorizedError,
472
+ CustomerServiceError,
293
473
  MAX_COMMANDS_PER_BATCH,
294
474
  PROTOCOL_HEADER,
295
475
  PROTOCOL_VERSION,
@@ -300,14 +480,20 @@ export {
300
480
  compareIds,
301
481
  createReconcileFeed,
302
482
  currencySymbol,
483
+ customerTraits,
484
+ errorKind,
303
485
  findVariantByCode,
304
486
  formatMoney,
305
487
  getProductStock,
306
488
  isCommandBatchResponse,
489
+ isRxdbRemoteVersionMismatch,
490
+ knownWarnings,
307
491
  minorUnitDigits,
308
492
  moneyFromDecimalString,
309
493
  moneyFromMajor,
310
494
  moneyToMajor,
495
+ parseInfoCapabilities,
496
+ parseTaxRounding,
311
497
  resolveCapabilities,
312
498
  resolvePrice,
313
499
  resolvePriceRange,
@@ -315,6 +501,8 @@ export {
315
501
  useCustomerTraits,
316
502
  useProductStock,
317
503
  useProductTraits,
504
+ useStockOverlaid,
505
+ useStockOverlayAsOf,
318
506
  useTraitContext,
319
507
  withStockOverlay
320
508
  };
@@ -4,13 +4,9 @@ import { Observable } from 'rxjs';
4
4
  /**
5
5
  * Reads straight from the collection's storage, past RxDB's cached query result.
6
6
  *
7
- * Why: in RxDB 16.21.1, a document written while a query's storage read is in flight (about one
8
- * to three microtasks after it starts) is counted as seen but is missing from the result. RxDB
9
- * caches that `RxQuery` per query string, so every later `find(sameQuery).exec()` or
10
- * `count(sameQuery).exec()` returns the stale result, and a later matching write doesn't heal it.
11
- * No subscription is needed. This is "bug 4" in TallyUI's local RxDB repro (the query-cache-stale
12
- * script beside the migration checkpoint repro). For the order outbox it left a sale unsent until
13
- * the app restarted.
7
+ * Originally bypassed RxDB 16.21.1's bug 4, fixed in RxDB 17 (rxdb#7067) by snapshotting the
8
+ * change counter before a read and rerunning when it moves. `readFresh`, `countFresh` and
9
+ * `watchFresh` remain correct public API; retiring them is a separate decision.
14
10
  *
15
11
  * The prepared query is RxDB's own (`find(query).getPreparedQuery()`), so it already carries the
16
12
  * `_deleted: false` filter, the query's sort and its limit. The read goes through the same wrapped
@@ -28,8 +24,8 @@ declare function readFresh<T>(collection: RxCollection<T>, query: MangoQuery<T>)
28
24
  declare function countFresh<T>(collection: RxCollection<T>, selector: MangoQuerySelector<T>): Promise<number>;
29
25
 
30
26
  /**
31
- * A live list a cached `RxQuery` can't leave stale (bug 4 in the local RxDB 16.21.1 repro,
32
- * `readFresh`'s doc comment): a write during a query's storage read never reaches it, for good.
27
+ * RxDB 17 fixed RxDB 16.21.1's bug 4 (rxdb#7067); `readFresh`, `countFresh` and `watchFresh`
28
+ * remain correct public API. Retiring them is a separate decision.
33
29
  * `collection.eventBulks$` fires on every write and never touches that cache, so re-reading with
34
30
  * `readFresh` on subscribe and again on every event bulk can't miss one; `switchMap` drops a read
35
31
  * still in flight when a newer one starts. It is one event per storage change bulk, not per
@@ -0,0 +1,213 @@
1
+ import { e as CommandError, l as OrderCreatePayload, d as CommandEnvelope, q as RegisterCommandEnvelope, A as AnyCommandEnvelope, f as CommandResult, B as BatchTooLargeBody, c as CommandBatchResponse, C as CommandWarning, r as RegisterCommandResult } from '../commands-BW4YYgRG.js';
2
+ export { M as MAX_COMMANDS_PER_BATCH, O as OrderCreateDisplay, n as OrderCreateTaxRate } from '../commands-BW4YYgRG.js';
3
+
4
+ /** ISO 4217 minor-unit exponent as resolved by Intl (which rejects malformed codes); depends on the runtime's ICU data. */
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
+ /** JSON with recursively sorted object keys; arrays keep their order. */
12
+ declare function canonicalJson(value: unknown): string;
13
+ /** Lower-case hex SHA-256 of the canonical command content. */
14
+ declare function commandFingerprint(envelope: {
15
+ type: string;
16
+ version: number;
17
+ payload: unknown;
18
+ }): string;
19
+
20
+ /** Shape errors of an order.create payload, e.g. ['lines: expected a non-empty array',
21
+ * 'payments[0].method: expected a string']; [] when the shape is valid, at most ten. Checks
22
+ * presence, types, the `customerId` (64) and `sessionId` (36) bounds, and U+0000 in any string;
23
+ * numbers are finite numbers, and value ranges are the planner's job. A plugin runs it before its
24
+ * replay lookup; every other length bound is payloadBoundErrors', after that lookup. The NUL check
25
+ * runs last, so the earlier checks' errors keep their order. */
26
+ declare function payloadShapeErrors(payload: unknown): string[];
27
+ /** Length-bound errors of an order.create payload, e.g. ['lines[0].title: expected at most 255
28
+ * characters']; [] when every string is within its bound, at most ten. Bounds in UTF-16 code units:
29
+ * `customer.email` 254, every other string 255 (`customerId` and `sessionId` keep theirs in
30
+ * payloadShapeErrors); only strings are checked. A plugin calls it through precheckCommand, after
31
+ * its replay lookup, so a bound tightened later never turns an applied command's resend into
32
+ * `invalid_payload`. */
33
+ declare function payloadBoundErrors(payload: unknown): string[];
34
+
35
+ /** @deprecated Use `CommandError` from `@tallyui/core`; kept for plugins migrating from local copies. */
36
+ type CommandErrorWithData = CommandError;
37
+ /** @deprecated Use `OrderCreatePayload` from `@tallyui/core`; kept for plugins migrating from local copies. */
38
+ type OrderCreatePayloadV3 = OrderCreatePayload;
39
+ declare function fiscalFiguresErrors(payload: OrderCreatePayloadV3): string[];
40
+
41
+ /**
42
+ * The till's capability: the order.create versions `toOrderCreateEnvelope` can produce. It is not what a server
43
+ * supports (#297). A server passes its own lists to `precheckCommand`, and its /info advertises them, gated by its
44
+ * own check (Front desk, 2026-09-30): 4 (#286) is 3 with every discountMinor tax-exclusive, and a plugin
45
+ * advertises it only once it handles it.
46
+ */
47
+ declare const SUPPORTED_ORDER_CREATE_VERSIONS: readonly number[];
48
+ /** The till's capability for the contract versions shared by all five register commands; a server passes its own. */
49
+ declare const SUPPORTED_REGISTER_VERSIONS: readonly number[];
50
+
51
+ /** An envelope validateBatch accepted: every field's shape is checked, and its version is any positive
52
+ * safe integer (precheckCommand decides which versions this server supports). */
53
+ type ValidatedCommandEnvelope = (Omit<CommandEnvelope<Record<string, unknown>>, 'version'> & {
54
+ type: 'order.create';
55
+ version: number;
56
+ }) | RegisterCommandEnvelope<Record<string, unknown>>;
57
+ /** Validates every envelope before any command is claimed. */
58
+ declare function validateBatch(body: unknown): {
59
+ ok: true;
60
+ commands: ValidatedCommandEnvelope[];
61
+ } | {
62
+ ok: false;
63
+ status: 400;
64
+ message: string;
65
+ } | {
66
+ ok: false;
67
+ status: 413;
68
+ message: string;
69
+ body: BatchTooLargeBody;
70
+ };
71
+ /**
72
+ * The rejection a batch returns for this command before any executor runs, or undefined
73
+ * when the command goes on to the plugin's executor. A plugin's batch handler calls
74
+ * validateBatch once, then, for each command in order: the shape check (payloadShapeErrors:
75
+ * types and NUL) first, before any database access, because a NUL in clientOrderId would make
76
+ * the lookup itself fail; then the plugin's own replay and collision lookups; then
77
+ * precheckCommand (versions, string lengths via payloadBoundErrors, fiscal figures); then the
78
+ * claim, in the executor (order.create; register commands follow ADR-068). It pushes any result
79
+ * one of those steps returns and moves on.
80
+ *
81
+ * The replay lookup goes before precheckCommand so an already-applied command always replays
82
+ * as `duplicate`, even once a later @tallyui/core tightens what precheckCommand accepts.
83
+ *
84
+ * `supported` is the SERVER's own list (what its /info advertises), never core's constants, which are the
85
+ * till's capability (#297). The version check, the `unsupported_version` message and its `data` all use it:
86
+ * `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1] })`.
87
+ */
88
+ declare function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCommandEnvelope, 'id' | 'type' | 'version' | 'payload'>, supported: {
89
+ orderCreate: readonly number[];
90
+ register: readonly number[];
91
+ }): CommandResult | undefined;
92
+
93
+ /**
94
+ * A plugin's batch handler stops at the first in-progress or transient command and returns that
95
+ * outcome for the whole batch; otherwise it returns 200 with every result in order.
96
+ */
97
+ type BatchOutcome = {
98
+ status: 200;
99
+ body: CommandBatchResponse;
100
+ } | {
101
+ status: 409;
102
+ body: {
103
+ code: 'in_progress';
104
+ id: string;
105
+ };
106
+ } | {
107
+ status: 503;
108
+ body: {
109
+ code: 'transient';
110
+ id: string;
111
+ message: 'Temporary failure, retry later.';
112
+ };
113
+ };
114
+ declare function inProgressOutcome(id: string): BatchOutcome;
115
+ /** The message is fixed so a server never leaks its internal error (log that separately). */
116
+ declare function transientOutcome(id: string): BatchOutcome;
117
+
118
+ type OrderRejectionCode = 'unknown_variant' | 'invalid_quantity' | 'underpaid' | 'unsupported_currency';
119
+ type Rejection = {
120
+ code: OrderRejectionCode;
121
+ message: string;
122
+ };
123
+ declare function totalWarnings(expectedMinor: number, serverMinor: number): CommandWarning[];
124
+
125
+ /** parseCommandResult's refusal; its message names the first bad field. A plugin maps it
126
+ * to its own invalid-data error (e.g. Medusa's MedusaError INVALID_DATA). */
127
+ declare class CommandResultError extends Error {
128
+ constructor(message: string);
129
+ }
130
+ /** Validates a CommandResult (e.g. one read back from the ledger). Throws
131
+ * CommandResultError naming the first bad field. */
132
+ declare function parseCommandResult(value: unknown): CommandResult;
133
+
134
+ /** Shape errors before a register command claims a ledger row. Unknown top-level keys are allowed. */
135
+ declare function registerPayloadErrors(type: string, payload: unknown): string[];
136
+
137
+ /**
138
+ * A session's expected figures per method: the counted float in cash, plus each order's payments, plus paid_in
139
+ * and minus paid_out movements that are not voided. The plugin chooses which orders count (for Medusa: completed,
140
+ * archived and cancelled POS orders, so a received sale stays counted after an admin archives or cancels it) and
141
+ * passes each order's recorded POS payments; this function only sums.
142
+ */
143
+ declare function deriveSessionFigures(input: {
144
+ countedFloatMinor: number;
145
+ orders: {
146
+ payments: {
147
+ method: string;
148
+ amountMinor: number;
149
+ }[];
150
+ }[];
151
+ movements: {
152
+ id: string;
153
+ type: 'paid_in' | 'paid_out' | 'no_sale' | 'void';
154
+ amountMinor: number;
155
+ voids: string | null;
156
+ }[];
157
+ }): {
158
+ expected: Record<string, number>;
159
+ salesCount: number;
160
+ };
161
+ declare function deriveVariance(counted: Record<string, number>, expected: Record<string, number>): Record<string, number>;
162
+
163
+ type RegisterConflictCode = 'register_session_already_open' | 'register_session_closed' | 'register_closure_exists' | 'register_closure_number_invalid';
164
+ type RegisterOutcome = {
165
+ kind: 'ok';
166
+ register: RegisterCommandResult;
167
+ } | {
168
+ kind: 'conflict';
169
+ code: RegisterConflictCode;
170
+ data?: Record<string, unknown>;
171
+ } | {
172
+ kind: 'invalid';
173
+ message: string;
174
+ };
175
+
176
+ /** Every error.code a plugin may put on a rejected result (ADR-038 and its amendments, ADR-068),
177
+ * except `register_approval_required`, which arrives with registers c2c. */
178
+ type CommandRejectionCode = 'invalid_payload' | 'unsupported_version' | 'idempotency_mismatch' | 'store_configuration' | 'platform_error' | 'insufficient_stock' | 'unsupported_tax_mode' | 'internal_error' | OrderRejectionCode | RegisterConflictCode;
179
+ /**
180
+ * The rejected result for a platform-native error the plugin has judged permanent (a replay would fail
181
+ * the same way, e.g. a Vendure ErrorResult code) and the contract has no code for. `platform_error` is
182
+ * for `order.create` only, for now: a rejected register command halts that register's queue until c2c,
183
+ * so register refusals use the ADR-068 codes.
184
+ *
185
+ * Return it only when the platform made no durable change for this command: the plugin threw so its
186
+ * transaction rolled back, or it compensated. Otherwise the plugin applies the command (with a warning
187
+ * where one fits), or compensates the partial write and then stays transient (ADR-039). The till offers
188
+ * Retry for `platform_error` and requeue resends under a new command id, and a transient result resends
189
+ * the same id after the ledger claim is released, so either would duplicate a partly written sale.
190
+ *
191
+ * It is stored in the ledger and replayed as recorded; the order shows under "Needs attention" with
192
+ * Retry. An error the plugin can't classify stays transient (503, retried), never platform_error.
193
+ */
194
+ declare function platformErrorResult(id: string, platformCode: string, platformMessage: string): CommandResult;
195
+ /**
196
+ * The rejected result for an exception from the plugin's own code (a programming error, not the
197
+ * database, the network, or an unknown SQLSTATE), raised after a complete rollback or a complete
198
+ * compensation, so that nothing of the sale remains, in the database or outside it. "The plugin's own
199
+ * code" excludes an error thrown from inside the platform SDK, the database client or the HTTP client.
200
+ *
201
+ * It is stored in the ledger and replayed as recorded, because it fails the same way on every retry
202
+ * and a retry loop would hide the bug. The message is generic so no internal detail reaches the till;
203
+ * the correlation id links it to the plugin's log.
204
+ *
205
+ * Database, network, unknown-SQLSTATE and any other unclassifiable errors stay transient (503), never
206
+ * `internal_error`. `order.create` only, as for `platform_error`.
207
+ *
208
+ * See ADR-038's `internal_error` amendment (needs-admin on a failed compensation; on Vendure only
209
+ * before the first write).
210
+ */
211
+ declare function internalErrorResult(id: string, correlationId: string): CommandResult;
212
+
213
+ export { type BatchOutcome, BatchTooLargeBody, type CommandErrorWithData, type CommandRejectionCode, CommandResultError, type OrderCreatePayloadV3, type OrderRejectionCode, type RegisterConflictCode, type RegisterOutcome, type Rejection, SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_REGISTER_VERSIONS, type ValidatedCommandEnvelope, canonicalJson, commandFingerprint, currencyDecimals, deriveSessionFigures, deriveVariance, fiscalFiguresErrors, inProgressOutcome, internalErrorResult, majorToMinor, minorToMajor, parseCommandResult, payloadBoundErrors, payloadShapeErrors, platformErrorResult, precheckCommand, registerPayloadErrors, totalWarnings, transientOutcome, validateBatch };