@tallyui/core 2.0.0 → 3.0.0-next.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-C4PWPOKO.js +18 -0
  2. package/dist/commands-BW4YYgRG.d.ts +306 -0
  3. package/dist/index.d.ts +226 -130
  4. package/dist/index.js +193 -19
  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 +7 -3
  14. package/src/replication/reconcile-feed.ts +57 -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 +58 -1
  37. package/src/types/customers.ts +26 -0
  38. package/src/types/index.ts +9 -2
  39. package/src/types/reconcile.ts +30 -0
  40. package/src/types/replication.ts +6 -0
  41. package/src/types/store-settings.ts +4 -0
  42. package/src/types/traits/product.ts +7 -0
  43. package/src/unauthorized.ts +13 -0
package/dist/index.js CHANGED
@@ -1,7 +1,43 @@
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, warn);
35
+ return {
36
+ orderCreate: maxVersion(contracts?.["order.create"]) ?? 1,
37
+ ...register !== void 0 ? { register } : {},
38
+ ...rounding ? { taxRounding: rounding } : {}
39
+ };
40
+ }
5
41
 
6
42
  // src/sign-in.ts
7
43
  var SignInError = class extends Error {
@@ -15,6 +51,41 @@ var SignInError = class extends Error {
15
51
  }
16
52
  };
17
53
 
54
+ // src/unauthorized.ts
55
+ var ConnectorUnauthorizedError = class extends Error {
56
+ code = "unauthorized";
57
+ /** Only signing in on this till fixes it, so the pull stops until `resume()` (`errorKind`). */
58
+ fixedBy = "till";
59
+ status;
60
+ constructor(message, status) {
61
+ super(message);
62
+ this.name = "ConnectorUnauthorizedError";
63
+ this.status = status;
64
+ }
65
+ };
66
+
67
+ // src/rxdb-remote-version-mismatch.ts
68
+ var REMOTE_CREATE_PREFIX = "could not create instance ";
69
+ function isRxdbRemoteVersionMismatch(error) {
70
+ const { code, rxdb, message } = typeof error === "object" && error !== null ? error : {};
71
+ if (code === "RM1" && (rxdb ?? true) === true) return true;
72
+ const text = typeof error === "string" ? error : message;
73
+ if (typeof text !== "string" || !text.startsWith(REMOTE_CREATE_PREFIX)) return false;
74
+ try {
75
+ const wrapped = JSON.parse(text.slice(REMOTE_CREATE_PREFIX.length));
76
+ return wrapped?.rxdb === true && wrapped.code === "RM1";
77
+ } catch {
78
+ return false;
79
+ }
80
+ }
81
+
82
+ // src/sync-notice.ts
83
+ function errorKind(error) {
84
+ if (typeof error !== "object" || error === null) return "transient";
85
+ const { fixedBy, code } = error;
86
+ return (fixedBy === "till" || fixedBy === "store") && typeof code === "string" ? fixedBy : "transient";
87
+ }
88
+
18
89
  // src/store-settings.ts
19
90
  var StoreSettingsError = class extends Error {
20
91
  code;
@@ -27,16 +98,21 @@ var StoreSettingsError = class extends Error {
27
98
  }
28
99
  };
29
100
 
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
- }
101
+ // src/types/customers.ts
102
+ var customerTraits = {
103
+ getId: (customer) => customer.id,
104
+ getName: (customer) => customer.name,
105
+ getEmail: (customer) => customer.email,
106
+ getPhone: (customer) => customer.phone,
107
+ getAddressSummary: () => void 0
108
+ };
109
+ var CustomerServiceError = class extends Error {
110
+ constructor(code, message) {
111
+ super(message);
112
+ this.code = code;
113
+ this.name = "CustomerServiceError";
114
+ }
115
+ };
40
116
 
41
117
  // src/money.ts
42
118
  var digitsCache = /* @__PURE__ */ new Map();
@@ -142,6 +218,66 @@ function findVariantByCode(variants, code) {
142
218
  return variants.find((variant) => variant.barcode?.trim().toLowerCase() === normalized) ?? variants.find((variant) => variant.sku?.trim().toLowerCase() === normalized);
143
219
  }
144
220
 
221
+ // src/known-warnings.ts
222
+ function isSafeInt(value) {
223
+ return typeof value === "number" && Number.isSafeInteger(value);
224
+ }
225
+ function figuresMismatchFields(fields) {
226
+ if (!Array.isArray(fields) || fields.length === 0) return null;
227
+ const rebuilt = [];
228
+ for (const entry of fields) {
229
+ if (typeof entry !== "object" || entry === null) return null;
230
+ const { field, tillMinor, serverMinor } = entry;
231
+ if (typeof field !== "string" || field === "" || rebuilt.some((kept) => kept.field === field)) return null;
232
+ if (!isSafeInt(tillMinor) || !isSafeInt(serverMinor) || tillMinor === serverMinor) return null;
233
+ rebuilt.push({ field, tillMinor, serverMinor });
234
+ }
235
+ return rebuilt;
236
+ }
237
+ function knownWarnings(warnings) {
238
+ if (!Array.isArray(warnings)) return [];
239
+ const kept = [];
240
+ for (const item of warnings) {
241
+ if (typeof item !== "object" || item === null || Array.isArray(item)) continue;
242
+ const warning = item;
243
+ switch (warning.code) {
244
+ case "total_mismatch": {
245
+ if (!isSafeInt(warning.expectedMinor) || !isSafeInt(warning.serverMinor)) continue;
246
+ const { bridgeMinor } = warning;
247
+ const validBridge = isSafeInt(bridgeMinor) && bridgeMinor !== 0 && bridgeMinor === warning.expectedMinor - warning.serverMinor;
248
+ kept.push(validBridge ? { code: "total_mismatch", expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor, bridgeMinor } : { code: "total_mismatch", expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor });
249
+ break;
250
+ }
251
+ case "insufficient_stock": {
252
+ if (typeof warning.variantId !== "string" || warning.variantId === "") continue;
253
+ if (!isSafeInt(warning.quantity) || warning.quantity < 1) continue;
254
+ kept.push({ code: "insufficient_stock", variantId: warning.variantId, quantity: warning.quantity });
255
+ break;
256
+ }
257
+ case "tax_rate_mismatch": {
258
+ if (!isSafeInt(warning.ratePpm) || warning.ratePpm < 0) continue;
259
+ if (!isSafeInt(warning.expectedMinor) || !isSafeInt(warning.serverMinor)) continue;
260
+ kept.push({ code: "tax_rate_mismatch", ratePpm: warning.ratePpm, expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor });
261
+ break;
262
+ }
263
+ case "customer_ignored": {
264
+ const { customerId } = warning;
265
+ if (typeof customerId !== "string" || customerId === "" || customerId.length > 64) continue;
266
+ kept.push({ code: "customer_ignored", customerId });
267
+ break;
268
+ }
269
+ case "figures_mismatch": {
270
+ const fields = figuresMismatchFields(warning.fields);
271
+ if (fields !== null) kept.push({ code: "figures_mismatch", fields });
272
+ break;
273
+ }
274
+ default:
275
+ continue;
276
+ }
277
+ }
278
+ return kept;
279
+ }
280
+
145
281
  // src/utils/compare-ids.ts
146
282
  var INTEGER_STRING = /^\d+$/;
147
283
  function compareIds(a, b) {
@@ -179,6 +315,7 @@ function combinePullAdapters(adapters, options = {}) {
179
315
  }
180
316
  return {
181
317
  pull: {
318
+ batchSize: options.batchSize,
182
319
  async handler(lastCheckpoint, batchSize, context) {
183
320
  let previous = lastCheckpoint;
184
321
  if (options.legacyKey && previous && typeof previous === "object" && Object.keys(previous).length && !keys.some((key) => key in previous)) {
@@ -207,11 +344,14 @@ function combinePullAdapters(adapters, options = {}) {
207
344
 
208
345
  // src/replication/reconcile-feed.ts
209
346
  var MAX_CHUNK = 1e3;
210
- function createReconcileFeed({ fetchByIds }) {
347
+ function createReconcileFeed(options) {
348
+ const keyed = "key" in options && typeof options.key === "function" ? options : void 0;
349
+ const docKey = keyed ? keyed.key : (doc) => doc.id;
350
+ 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
351
  let queue = /* @__PURE__ */ new Map();
212
352
  const merge = (prior, e) => ({ ...e, refreshOnly: Boolean(e.refreshOnly) && (prior?.refreshOnly ?? true) });
213
353
  const enqueue = (entries) => {
214
- for (const e of entries) queue.set(e.id, merge(queue.get(e.id), e));
354
+ for (const e of entries) queue.set(keyOf(e), merge(queue.get(keyOf(e)), e));
215
355
  };
216
356
  const adapter = {
217
357
  pull: {
@@ -223,18 +363,19 @@ function createReconcileFeed({ fetchByIds }) {
223
363
  const documents = [];
224
364
  for (let i = 0; i < entries.length; i += MAX_CHUNK) {
225
365
  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]));
366
+ const toFetch = chunk.filter((e) => !e.tombstone);
367
+ const fetched = toFetch.length ? await fetch(toFetch, context) : [];
368
+ const byKey = new Map(fetched.map((doc) => [docKey(doc), doc]));
228
369
  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 });
370
+ const doc = entry.tombstone ? void 0 : byKey.get(keyOf(entry));
371
+ if (doc) documents.push({ ...doc, _deleted: doc._deleted ?? false });
372
+ else if (!entry.refreshOnly && entry.local) documents.push({ ...entry.local, _deleted: true });
232
373
  }
233
374
  }
234
375
  return { documents, checkpoint: { n: (lastCheckpoint?.n ?? 0) + 1 } };
235
376
  } 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));
377
+ const restored = new Map(entries.map((e) => [keyOf(e), e]));
378
+ for (const [key, e] of queue) restored.set(key, merge(restored.get(key), e));
238
379
  queue = restored;
239
380
  throw error;
240
381
  }
@@ -243,6 +384,9 @@ function createReconcileFeed({ fetchByIds }) {
243
384
  };
244
385
  return { adapter, enqueue };
245
386
  }
387
+ function keyOf(entry) {
388
+ return entry.key ?? entry.id;
389
+ }
246
390
 
247
391
  // src/context/connector-context.tsx
248
392
  import { createContext, useContext, useMemo } from "react";
@@ -283,6 +427,26 @@ function useProductStock(doc) {
283
427
  const stock = getProductStock(doc, connector.traits.product, adapter, overlay);
284
428
  return adapter && asOf ? { ...stock, asOf } : stock;
285
429
  }
430
+ function useStockOverlaid(products) {
431
+ const connector = useContext(ConnectorContext);
432
+ const { overlay } = useContext(StockOverlayContext);
433
+ const adapter = connector?.reconcile?.stock;
434
+ return useMemo(() => {
435
+ if (!adapter || !overlay) return products;
436
+ let changed = false;
437
+ const mapped = products.map((doc) => {
438
+ const next = withStockOverlay(doc, adapter, overlay);
439
+ if (next !== doc) changed = true;
440
+ return next;
441
+ });
442
+ return changed ? mapped : products;
443
+ }, [products, overlay, adapter]);
444
+ }
445
+ function useStockOverlayAsOf() {
446
+ const connector = useContext(ConnectorContext);
447
+ const { asOf } = useContext(StockOverlayContext);
448
+ return connector?.reconcile?.stock ? asOf : void 0;
449
+ }
286
450
  function useCustomerTraits() {
287
451
  const connector = useConnector();
288
452
  return connector.traits.customer;
@@ -290,6 +454,8 @@ function useCustomerTraits() {
290
454
  export {
291
455
  COMMANDS_PATH,
292
456
  ConnectorProvider,
457
+ ConnectorUnauthorizedError,
458
+ CustomerServiceError,
293
459
  MAX_COMMANDS_PER_BATCH,
294
460
  PROTOCOL_HEADER,
295
461
  PROTOCOL_VERSION,
@@ -300,14 +466,20 @@ export {
300
466
  compareIds,
301
467
  createReconcileFeed,
302
468
  currencySymbol,
469
+ customerTraits,
470
+ errorKind,
303
471
  findVariantByCode,
304
472
  formatMoney,
305
473
  getProductStock,
306
474
  isCommandBatchResponse,
475
+ isRxdbRemoteVersionMismatch,
476
+ knownWarnings,
307
477
  minorUnitDigits,
308
478
  moneyFromDecimalString,
309
479
  moneyFromMajor,
310
480
  moneyToMajor,
481
+ parseInfoCapabilities,
482
+ parseTaxRounding,
311
483
  resolveCapabilities,
312
484
  resolvePrice,
313
485
  resolvePriceRange,
@@ -315,6 +487,8 @@ export {
315
487
  useCustomerTraits,
316
488
  useProductStock,
317
489
  useProductTraits,
490
+ useStockOverlaid,
491
+ useStockOverlayAsOf,
318
492
  useTraitContext,
319
493
  withStockOverlay
320
494
  };
@@ -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 };