@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.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { RxReplicationPullStreamItem, RxReplicationWriteToMasterRow, RxJsonSchema } from 'rxdb';
2
2
  import { Observable } from 'rxjs';
3
+ import { C as CommandWarning } from './commands-BW4YYgRG.js';
4
+ export { A as AnyCommandEnvelope, B as BatchTooLargeBody, a as COMMANDS_PATH, b as CommandBatchRequest, c as CommandBatchResponse, d as CommandEnvelope, e as CommandError, f as CommandResult, g as CommandServerRefs, h as CommandStatus, i as CommandType, M as MAX_COMMANDS_PER_BATCH, O as OrderCreateDisplay, j as OrderCreateEnvelope, k as OrderCreateLine, l as OrderCreatePayload, m as OrderCreatePayment, n as OrderCreateTaxRate, P as PROTOCOL_HEADER, o as PROTOCOL_VERSION, p as PaymentMethodKind, R as RegisterClosureSubmitPayload, q as RegisterCommandEnvelope, r as RegisterCommandResult, s as RegisterCommandType, t as RegisterMovementRecordPayload, u as RegisterMovementVoidPayload, v as RegisterSessionOpenPayload, w as RegisterSessionTransitionPayload, x as isCommandBatchResponse } from './commands-BW4YYgRG.js';
3
5
  import * as react_jsx_runtime from 'react/jsx-runtime';
4
6
  import { ReactNode } from 'react';
5
7
 
@@ -107,6 +109,12 @@ interface ProductTraits<Doc = any> {
107
109
  getStock: (doc: Doc) => StockLevel;
108
110
  /** All purchasable variants, in id order (connectors store variants sorted by id). Optional: connectors without variant support omit it. */
109
111
  getVariants?: (doc: Doc, context?: TraitContext) => VariantSummary[];
112
+ /**
113
+ * The backend's tax class id for the variant `variantId`, or for the product (its default variant) when omitted.
114
+ * The id is a key of `StoreSettings.taxRatesPpm`; undefined means the default class. Optional: without it, every
115
+ * line is taxed at the default rate.
116
+ */
117
+ getTaxClass?: (doc: Doc, variantId?: string) => string | undefined;
110
118
  /** @deprecated Use `getPrices` with `resolvePrice`. */
111
119
  getPrice: (doc: Doc) => string | undefined;
112
120
  /** Regular (non-sale) price. @deprecated Use `getPrices` with `resolvePrice`. */
@@ -180,6 +188,11 @@ interface ReplicationAdapter<RxDocType, CheckpointType = any> {
180
188
  }>;
181
189
  checkpoint: CheckpointType;
182
190
  }>;
191
+ /**
192
+ * Documents per pull page, passed to handler as batchSize. RxDB treats a
193
+ * shorter page as the end of the cycle. Defaults to RxDB's 100.
194
+ */
195
+ batchSize?: number;
183
196
  /**
184
197
  * Fresh install only: the checkpoint this feed starts from instead of a full first pass,
185
198
  * read before any feed runs (combinePullAdapters). Absent: a full first pass, as today.
@@ -237,6 +250,8 @@ interface IdReconcileAdapter<Doc = any> {
237
250
  id: string;
238
251
  local: Doc;
239
252
  }>): void;
253
+ /** Ids per `fetchByIds` request; see `CatalogueReconcileAdapter.refetchBatchSize`. */
254
+ refetchBatchSize?: number;
240
255
  }
241
256
  /** Re-delivers products whose remote fingerprint differs from the local one (ADR-060). */
242
257
  interface FingerprintReconcileAdapter<Doc = any> {
@@ -254,6 +269,44 @@ interface FingerprintReconcileAdapter<Doc = any> {
254
269
  local: Doc;
255
270
  refreshOnly?: boolean;
256
271
  }>): void;
272
+ /** Ids per `fetchByIds` request; see `CatalogueReconcileAdapter.refetchBatchSize`. */
273
+ refetchBatchSize?: number;
274
+ }
275
+ /** One product in the catalogue listing. `key` is the local primary key value; `remote` is whatever the connector needs to refetch it (a numeric backend id, say). */
276
+ interface CatalogueReconcileEntry {
277
+ key: string;
278
+ fingerprint: string;
279
+ remote?: unknown;
280
+ }
281
+ /**
282
+ * The daily catalogue check (#248): one walk that refetches what differs and
283
+ * deletes only with proof. Nothing is written locally: `enqueue` hands
284
+ * documents to the collection's pull (the reconcile feed). `Cursor` must be
285
+ * JSON-serialisable, since the runner persists it to resume a stopped pass.
286
+ */
287
+ interface CatalogueReconcileAdapter<Doc = any, Cursor = unknown> {
288
+ /** Remote listing, one backend request per page, from `from` (a cursor this adapter yielded earlier) or the start. */
289
+ fetchPages(context: SyncContext, from?: Cursor): AsyncIterable<{
290
+ entries: CatalogueReconcileEntry[];
291
+ cursor: Cursor;
292
+ }>;
293
+ /** Pure: the same fingerprint from a local document. */
294
+ fingerprint(doc: Doc): string;
295
+ /**
296
+ * Deletion proof, required: of these local documents (the ones the listing did not name), the keys
297
+ * the backend confirms gone (absent, or no longer sellable). One or more requests. Only confirmed
298
+ * keys are tombstoned; an adapter that never deletes returns none.
299
+ */
300
+ confirmGone(locals: Doc[], context: SyncContext): Promise<string[]>;
301
+ /** Hand documents to the collection's pull (the reconcile feed). */
302
+ enqueue(entries: Array<{
303
+ key: string;
304
+ local?: Doc;
305
+ remote?: unknown;
306
+ tombstone?: boolean;
307
+ }>): void;
308
+ /** Ids per `fetchByIds` request of the feed this adapter enqueues into: a page's `n` refetches take `ceil(n / refetchBatchSize)` budget slots (1 when unset). */
309
+ refetchBatchSize?: number;
257
310
  }
258
311
 
259
312
  /** What the POS needs from the store's own settings (TV4). Read once after sign-in; the app feeds all three consumers from it. */
@@ -269,6 +322,8 @@ interface StoreSettings {
269
322
  };
270
323
  /** Connector-specific and opaque to the app: what the connector needs to price documents. The app passes it back to the connector unchanged, and never logs it. */
271
324
  pricingContext?: Record<string, string>;
325
+ /** Derived, never read by `storeSettings`: the store's `ServerCapabilities.taxRounding`, which `useStoreSettings` fills in (#324). */
326
+ taxRounding?: TaxRounding;
272
327
  }
273
328
  /**
274
329
  * Picks among several regions, countries or sales channels when the store has more than one.
@@ -282,6 +337,33 @@ interface StoreSettingsChoice {
282
337
  channel?: string;
283
338
  }
284
339
 
340
+ /** A store customer, as the till shows and picks it (programme item 14). Platform-neutral. */
341
+ interface Customer {
342
+ /** The platform's id: order.create v3 sends it as `customer.customerId`. */
343
+ id: string;
344
+ /** Display name: first + last, else company, else email, else id. Never empty. */
345
+ name: string;
346
+ firstName?: string;
347
+ lastName?: string;
348
+ email?: string;
349
+ phone?: string;
350
+ company?: string;
351
+ }
352
+ /** What the till collects to create a customer. v1 requires an email. */
353
+ interface CustomerInput {
354
+ email: string;
355
+ firstName?: string;
356
+ lastName?: string;
357
+ phone?: string;
358
+ company?: string;
359
+ }
360
+ declare const customerTraits: CustomerTraits<Customer>;
361
+ /** A customer call that failed for a reason other than credentials (credentials throw ConnectorUnauthorizedError). */
362
+ declare class CustomerServiceError extends Error {
363
+ readonly code: 'network' | 'server' | 'invalid';
364
+ constructor(code: 'network' | 'server' | 'invalid', message: string);
365
+ }
366
+
285
367
  /**
286
368
  * Authentication configuration for a connector.
287
369
  * Each API has wildly different auth — JWT, API keys, OAuth, etc.
@@ -318,7 +400,18 @@ interface SignInResult {
318
400
  /** The highest `order.create` contract version a store's server currently accepts (ADR-062). */
319
401
  interface ServerCapabilities {
320
402
  orderCreate: number;
321
- }
403
+ /** The highest `register` contract version; absent or 0 means no register sync. */
404
+ register?: number;
405
+ /** How the store rounds tax (#287). Absent: an older server, per_order + half_away_from_zero. */
406
+ taxRounding?: TaxRounding;
407
+ }
408
+ /** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
409
+ type TaxRounding = {
410
+ granularity: 'per_order' | 'per_line_items' | 'per_rate_group_items';
411
+ mode: 'half_away_from_zero' | 'half_up';
412
+ } | {
413
+ granularity: 'custom';
414
+ };
322
415
  /**
323
416
  * Resolves the capabilities to act on: a definitive fresh read always wins,
324
417
  * even a downgrade to 1; an inconclusive fresh read (`undefined`) keeps the
@@ -328,6 +421,18 @@ interface ServerCapabilities {
328
421
  * only happens when the value has never been read (ADR-062).
329
422
  */
330
423
  declare function resolveCapabilities(fresh: ServerCapabilities | undefined, stored: ServerCapabilities | undefined): ServerCapabilities | undefined;
424
+ /**
425
+ * Reads the `taxRounding` of `GET /tally/v1/info` (#287): a valid value comes back without
426
+ * extra keys, and `custom` drops any `mode`. Absent gives `undefined`, the default. Core has
427
+ * no logger, so a malformed value gives `undefined` and one reason to `warn` for the caller to log.
428
+ */
429
+ declare function parseTaxRounding(value: unknown, warn?: (reason: string) => void): TaxRounding | undefined;
430
+ /**
431
+ * Reads a 2xx body of `GET /tally/v1/info` (ADR-062): `orderCreate` is the max of
432
+ * `contracts["order.create"]`, or 1 when it's missing or malformed; `register` is the max of
433
+ * `contracts.register` when valid; `taxRounding` is the top-level sibling of `contracts` (#287).
434
+ */
435
+ declare function parseInfoCapabilities(body: unknown, warn?: (reason: string) => void): ServerCapabilities;
331
436
  interface AuthField {
332
437
  key: string;
333
438
  label: string;
@@ -434,6 +539,8 @@ interface TallyConnector {
434
539
  prices?: FingerprintReconcileAdapter;
435
540
  /** Prices the backend calculates for the sales context (price lists, sale dates), which change without a timestamp bump. */
436
541
  calculatedPrices?: FingerprintReconcileAdapter;
542
+ /** The daily catalogue check (#248): refetches what differs, deletes only with proof. */
543
+ catalogue?: CatalogueReconcileAdapter;
437
544
  };
438
545
  /**
439
546
  * Reads the store's own settings (TV4): currency, tax inclusivity, tax
@@ -450,110 +557,14 @@ interface TallyConnector {
450
557
  * see `resolveCapabilities`.
451
558
  */
452
559
  capabilities?: (context: SyncContext) => Promise<ServerCapabilities | undefined>;
453
- }
454
-
455
- /** Supported command operation. */
456
- type CommandType = 'order.create';
457
- /** Client command with a stable idempotency key and typed payload. */
458
- interface CommandEnvelope<P = unknown> {
459
- id: string;
460
- type: CommandType;
461
- /** 2 only when an `order.create` carries a discount (ADR-062); a discount-free payload stays 1, byte-identical. */
462
- version: 1 | 2;
463
- payload: P;
464
- createdAt: string;
465
- deviceId: string;
466
- attempt: number;
467
- }
468
- /** Outcome of processing a command. */
469
- type CommandStatus = 'applied' | 'duplicate' | 'rejected';
470
- /** Server order identifiers and authoritative total. */
471
- interface CommandServerRefs {
472
- orderId: string;
473
- displayId?: string;
474
- totalMinor: number;
475
- }
476
- /** Non-fatal discrepancies reported while processing a command. */
477
- type CommandWarning = {
478
- code: 'total_mismatch';
479
- expectedMinor: number;
480
- serverMinor: number;
481
- } | {
482
- code: 'insufficient_stock';
483
- variantId: string;
484
- quantity: number;
485
- };
486
- /** Error reported when a command is rejected. */
487
- interface CommandError {
488
- code: string;
489
- message: string;
490
- }
491
- /** Server result for a single command. */
492
- interface CommandResult {
493
- id: string;
494
- status: CommandStatus;
495
- serverRefs?: CommandServerRefs;
496
- warnings?: CommandWarning[];
497
- error?: CommandError;
498
- }
499
- /** Order line with client identity and price in minor units. */
500
- interface OrderCreateLine {
501
- clientLineId: string;
502
- variantId: string;
503
- title?: string;
504
- quantity: number;
505
- unitPriceMinor: number;
506
- /**
507
- * This line's own tax mode, when it differs from the order's `pricesIncludeTax`
508
- * (a price that carries its own flag, D2c). Absent means the order's flag, so
509
- * older clients and single-mode orders are unchanged.
510
- */
511
- taxInclusive?: boolean;
512
- /**
513
- * Version 2 (ADR-062): this line's total discount, its own line discounts plus its allocated share of
514
- * the order discount, in the line's own tax mode and integer minor units. The line is taxed on
515
- * `unitPriceMinor × quantity − discountMinor`. Present only when above 0.
516
- */
517
- discountMinor?: number;
518
- }
519
- /** Supported order payment method. */
520
- type PaymentMethodKind = 'cash' | 'external';
521
- /** Order payment with client identity and amounts in minor units. */
522
- interface OrderCreatePayment {
523
- clientPaymentId: string;
524
- method: PaymentMethodKind;
525
- amountMinor: number;
526
- tenderedMinor?: number;
527
- changeMinor?: number;
528
- reference?: string;
529
- }
530
- /** Client order data submitted by an order.create command. */
531
- interface OrderCreatePayload {
532
- clientOrderId: string;
533
- createdAt: string;
534
- currency: string;
535
- pricesIncludeTax: boolean;
536
- lines: OrderCreateLine[];
537
- subtotalMinor: number;
538
- /** Version 2 (ADR-062): the order's total discount, equal to Σ `lines[].discountMinor`. Present only when above 0. */
539
- discountMinor?: number;
540
- taxMinor: number;
541
- totalMinor: number;
542
- payments: OrderCreatePayment[];
543
- customer?: {
544
- email?: string;
545
- } | null;
546
- registerId?: string;
547
- cashierRef?: string;
548
- locationId?: string;
549
- }
550
- /** Batch of commands submitted to the server. */
551
- interface CommandBatchRequest {
552
- commands: CommandEnvelope[];
553
- }
554
- /** Results returned by the server for a command batch. */
555
- interface CommandBatchResponse {
556
- results: CommandResult[];
560
+ /** Customer search: online only; `undefined` when the connector has no customer support. */
561
+ searchCustomers?: (context: SyncContext, query: string, options?: {
562
+ limit?: number;
563
+ }) => Promise<Customer[]>;
564
+ /** Customer creation: online only; `undefined` when the connector has no customer support. */
565
+ createCustomer?: (context: SyncContext, input: CustomerInput) => Promise<Customer>;
566
+ /** Customer lookup: online only; `undefined` when the connector has no customer support. */
567
+ getCustomer?: (context: SyncContext, id: string) => Promise<Customer | null>;
557
568
  }
558
569
 
559
570
  /**
@@ -571,6 +582,51 @@ declare class SignInError extends Error {
571
582
  constructor(code: SignInErrorCode, message: string, status?: number);
572
583
  }
573
584
 
585
+ /** A backend refused the stored credentials (expired, revoked or insufficient); the app should sign in again. */
586
+ declare class ConnectorUnauthorizedError extends Error {
587
+ readonly code: "unauthorized";
588
+ /** Only signing in on this till fixes it, so the pull stops until `resume()` (`errorKind`). */
589
+ readonly fixedBy: "till";
590
+ readonly status?: number;
591
+ constructor(message: string, status?: number);
592
+ }
593
+
594
+ /**
595
+ * True for RxDB's RM1: the remote storage worker was built on another RxDB
596
+ * version than the main thread, e.g. a stale worker the browser cached from
597
+ * before an upgrade. Reloading loads the matching worker.
598
+ *
599
+ * Matched by structure, never by substring. An `RxError` (rxdb 17.5.0
600
+ * src/rx-error.ts) has own `code`, `message`, `url`, `parameters` and
601
+ * `rxdb: true`; its `name` is a getter. So RM1 is either an object whose own
602
+ * `code` is `'RM1'` (with `rxdb === true` when `rxdb` is present), or an
603
+ * error, `{ message }` copy or string whose message is the remote storage's
604
+ * `could not create instance ` followed by JSON with `rxdb: true` and
605
+ * `code: 'RM1'`. Needs no rxdb import.
606
+ */
607
+ declare function isRxdbRemoteVersionMismatch(error: unknown): boolean;
608
+
609
+ /**
610
+ * A pull that stopped until someone acts; `SyncStatus` owns the words for each `code`.
611
+ * `fixedBy` says who can fix it: the till (sign in again) or the store owner.
612
+ * `software` / `minVersion` / `fix` are copied from the error when it names them.
613
+ */
614
+ type SyncNotice = {
615
+ code: string;
616
+ since: number;
617
+ fixedBy: 'till' | 'store';
618
+ software?: string;
619
+ minVersion?: string;
620
+ fix?: string;
621
+ };
622
+ /** Who can fix a pull error: the till, the store owner, or nobody (it passes, so it is retried). */
623
+ type ErrorKind = 'till' | 'store' | 'transient';
624
+ /**
625
+ * 'till' or 'store' for an error whose class sets `fixedBy` to that value and a
626
+ * string `code`; 'transient' for anything else.
627
+ */
628
+ declare function errorKind(error: unknown): ErrorKind;
629
+
574
630
  /**
575
631
  * Why `TallyConnector.storeSettings` failed:
576
632
  * - `choice_required`: the store has more than one region, country or
@@ -599,21 +655,6 @@ declare class StoreSettingsError extends Error {
599
655
  constructor(code: StoreSettingsErrorCode, message: string, choices?: StoreSettingsChoices);
600
656
  }
601
657
 
602
- /** Path of the command endpoint, relative to the backend's base URL. */
603
- declare const COMMANDS_PATH = "/tally/v1/commands";
604
- /** Header carrying the protocol version. */
605
- declare const PROTOCOL_HEADER = "X-Tally-Protocol";
606
- /** Current protocol version. */
607
- declare const PROTOCOL_VERSION = 1;
608
- /** Maximum commands per batch request. */
609
- declare const MAX_COMMANDS_PER_BATCH = 50;
610
- /**
611
- * True if `value` has the shape of a CommandBatchResponse: an object with a
612
- * `results` array whose every entry has a string `id` and a `status` of
613
- * 'applied' | 'duplicate' | 'rejected'. Optional fields are not deep-checked.
614
- */
615
- declare function isCommandBatchResponse(value: unknown): value is CommandBatchResponse;
616
-
617
658
  /** Number of minor-unit digits for an ISO 4217 code (2 for EUR, 0 for JPY). */
618
659
  declare function minorUnitDigits(currency: string): number;
619
660
  /** The currency's symbol for a plain-English label ('€' for EUR, '$' for USD), not a full amount. */
@@ -658,6 +699,18 @@ declare function resolvePriceRange(variants: Array<{
658
699
  */
659
700
  declare function findVariantByCode(variants: VariantSummary[], code: string): VariantSummary | undefined;
660
701
 
702
+ /**
703
+ * The till's single reader of stored warnings. `[]` for anything that isn't a warnings array.
704
+ * A `total_mismatch`'s `bridgeMinor` is dropped (the rest of the warning is kept) when it's
705
+ * absent, `null`, not a safe integer, zero, or not equal to `expectedMinor - serverMinor`.
706
+ * A `tax_rate_mismatch` with a negative `ratePpm` is dropped entirely; zero stays valid.
707
+ * A `customer_ignored` is dropped unless its `customerId` is a string of 1 to 64 characters.
708
+ * A `figures_mismatch` is dropped entirely unless `fields` is non-empty and each entry names a
709
+ * different figure with two differing safe integers; each entry is rebuilt from its known keys.
710
+ * A figure name it doesn't know (any non-empty string) is kept, since a newer store may send one.
711
+ */
712
+ declare function knownWarnings(warnings: unknown): CommandWarning[];
713
+
661
714
  /** Orders backend ids: numerically when both are integer strings (Vendure '9' < '10', compared with BigInt so long ids stay exact), with ties in numeric value (e.g. '01' vs '1') broken by plain string order; an integer id always sorts before a non-integer one; otherwise (neither is an integer string) by plain string order (not `localeCompare`, which is locale-dependent). This is a total order, so sorting is consistent regardless of input order. */
662
715
  declare function compareIds(a: string | number, b: string | number): number;
663
716
 
@@ -690,41 +743,75 @@ declare function getProductStock<Doc>(doc: Doc, traits: ProductTraits<Doc>, adap
690
743
  * checkpoint with none of the keys becomes that key's checkpoint. With no stored
691
744
  * checkpoint at all, each sub-adapter with `pull.seedCheckpoint` starts from its seed.
692
745
  *
746
+ * `options.batchSize` sets the combined pull page size; sub-adapters' own
747
+ * `pull.batchSize` is ignored.
693
748
  * Pull only: a sub-adapter with `push` or `pull.stream$` throws here.
694
749
  */
695
750
  declare function combinePullAdapters<Doc>(adapters: Record<string, ReplicationAdapter<Doc, any>>, options?: {
696
751
  legacyKey?: string;
752
+ batchSize?: number;
697
753
  }): ReplicationAdapter<Doc, Record<string, any>>;
698
754
 
699
- interface ReconcileFeedEntry<Doc = any> {
755
+ /**
756
+ * One queued correction, keyed by the local primary key: `key`, or `id`, its
757
+ * older name. `local` is the till's copy, if it has one; `remote` is whatever
758
+ * the connector needs to refetch it.
759
+ */
760
+ type ReconcileFeedEntry<Doc = any> = ({
761
+ key: string;
762
+ id?: undefined;
763
+ } | {
700
764
  id: string;
701
- local: Doc;
765
+ key?: undefined;
766
+ }) & {
767
+ local?: Doc;
768
+ remote?: unknown;
702
769
  /**
703
770
  * Re-deliver if the product still exists; never tombstone if missing (the
704
771
  * fingerprint path, ADR-060). Only the id reconcile, with its mass-delete
705
772
  * brake, enqueues deletable entries.
706
773
  */
707
774
  refreshOnly?: boolean;
775
+ /** Proven gone (the catalogue reconcile, #248): written as deleted from `local`, without a fetch. */
776
+ tombstone?: boolean;
777
+ };
778
+ /** What a keyed feed's `fetchByIds` receives for each entry. */
779
+ interface ReconcileFetchEntry<Doc = any> {
780
+ key: string;
781
+ local?: Doc;
782
+ remote?: unknown;
708
783
  }
709
784
  interface CreateReconcileFeedOptions<Doc = any> {
710
- /** The current projected documents for the ids that still exist. */
785
+ /** The current projected documents for the ids that still exist, matched back by `doc.id`. */
711
786
  fetchByIds(ids: string[], context: SyncContext): Promise<Doc[]>;
712
787
  }
788
+ /** A feed keyed by the primary key where that is not `doc.id` (WooCommerce's uuid, #248). */
789
+ interface KeyedReconcileFeedOptions<Doc = any> {
790
+ /** The local primary key of a fetched document; fetched documents are matched to entries by it. */
791
+ key(doc: Doc): string;
792
+ /** The current documents for the entries that still exist. A document may carry `_deleted: true` (an unpublished product). */
793
+ fetchByIds(entries: Array<ReconcileFetchEntry<Doc>>, context: SyncContext): Promise<Doc[]>;
794
+ }
713
795
  interface ReconcileFeed<Doc = any> {
714
796
  /** Pull-only; meant as the last key of `combinePullAdapters` so its fetch wins duplicates. */
715
797
  adapter: ReplicationAdapter<Doc, {
716
798
  n: number;
717
799
  }>;
718
800
  /**
719
- * Add entries to the in-memory queue, de-duplicated by id, last entry's
720
- * `local` wins. `refreshOnly` is merged separately: it is true only when
721
- * every merged entry for that id was `refreshOnly`, so a deletable entry
722
- * (the id reconcile's) is never downgraded by a later refresh-only one.
801
+ * Add entries to the in-memory queue, de-duplicated by key, last entry wins.
802
+ * `refreshOnly` is merged separately: it is true only when every merged
803
+ * entry for that key was `refreshOnly`, so a deletable entry (the id
804
+ * reconcile's) is never downgraded by a later refresh-only one.
723
805
  */
724
806
  enqueue(entries: Array<ReconcileFeedEntry<Doc>>): void;
725
807
  }
726
- /** Turns queued corrections into a pull adapter's documents; nothing here writes locally (ADR-060). */
727
- declare function createReconcileFeed<Doc = any>({ fetchByIds }: CreateReconcileFeedOptions<Doc>): ReconcileFeed<Doc>;
808
+ /**
809
+ * Turns queued corrections into a pull adapter's documents; nothing here writes locally (ADR-060).
810
+ * Two overloads: with `key`, `fetchByIds` receives the entries and fetched documents are matched by
811
+ * `key(doc)`; without it, `fetchByIds` receives bare ids and documents are matched by `doc.id`.
812
+ */
813
+ declare function createReconcileFeed<Doc = any>(options: KeyedReconcileFeedOptions<Doc>): ReconcileFeed<Doc>;
814
+ declare function createReconcileFeed<Doc = any>(options: CreateReconcileFeedOptions<Doc>): ReconcileFeed<Doc>;
728
815
 
729
816
  interface ConnectorProviderProps {
730
817
  connector: TallyConnector;
@@ -760,10 +847,19 @@ declare function useTraitContext(): TraitContext;
760
847
  declare function useProductStock(doc: any): StockLevel & {
761
848
  asOf?: string;
762
849
  };
850
+ /**
851
+ * The products with the nearest ConnectorProvider's reconciled stock overlay merged in (copies only; the
852
+ * documents are never changed), for components that derive stock from documents themselves. Returns
853
+ * `products` itself, unchanged, when there is no provider, no overlay, or the connector has no stock
854
+ * reconcile adapter, and the same array while its inputs are unchanged.
855
+ */
856
+ declare function useStockOverlaid<Doc>(products: readonly Doc[]): readonly Doc[];
857
+ /** The reconciled stock overlay's confirmed-as-of time from the nearest ConnectorProvider, or undefined without one or when its connector has no `reconcile.stock` (the same gate `useProductStock` uses). */
858
+ declare function useStockOverlayAsOf(): string | undefined;
763
859
  /**
764
860
  * Convenience hook: grab just the customer traits from the active connector.
765
861
  * Returns undefined if the connector doesn't implement customer traits.
766
862
  */
767
863
  declare function useCustomerTraits(): CustomerTraits<any> | undefined;
768
864
 
769
- export { type AuthField, COMMANDS_PATH, type CollectionSync, type CommandBatchRequest, type CommandBatchResponse, type CommandEnvelope, type CommandError, type CommandResult, type CommandServerRefs, type CommandStatus, type CommandType, type CommandWarning, type ConnectorAuth, ConnectorProvider, type ConnectorProviderProps, type ConnectorSchemas, type ConnectorTraits, type CustomerTraits, type FingerprintReconcileAdapter, type IdReconcileAdapter, MAX_COMMANDS_PER_BATCH, type Money, type OrderCreateLine, type OrderCreatePayload, type OrderCreatePayment, PROTOCOL_HEADER, PROTOCOL_VERSION, type PaymentMethodKind, type ProductPrice, type ProductTraits, type ReconcileFeed, type ReconcileFeedEntry, type RemoteIdEntry, type ReplicationAdapter, type ResolvedPrice, STOCK_LEVELS_LAST_PASS, type ServerCapabilities, SignInError, type SignInErrorCode, type SignInResult, type StockLevel, type StockReconcileAdapter, type StockStatus, type StoreSettings, type StoreSettingsChoice, type StoreSettingsChoices, StoreSettingsError, type StoreSettingsErrorCode, type SyncContext, type TallyConnector, type TraitContext, type VariantSummary, combinePullAdapters, compareIds, createReconcileFeed, currencySymbol, findVariantByCode, formatMoney, getProductStock, isCommandBatchResponse, minorUnitDigits, moneyFromDecimalString, moneyFromMajor, moneyToMajor, resolveCapabilities, resolvePrice, resolvePriceRange, useConnector, useCustomerTraits, useProductStock, useProductTraits, useTraitContext, withStockOverlay };
865
+ export { type AuthField, type CatalogueReconcileAdapter, type CatalogueReconcileEntry, type CollectionSync, CommandWarning, type ConnectorAuth, ConnectorProvider, type ConnectorProviderProps, type ConnectorSchemas, type ConnectorTraits, ConnectorUnauthorizedError, type Customer, type CustomerInput, CustomerServiceError, type CustomerTraits, type ErrorKind, type FingerprintReconcileAdapter, type IdReconcileAdapter, type KeyedReconcileFeedOptions, type Money, type ProductPrice, type ProductTraits, type ReconcileFeed, type ReconcileFeedEntry, type ReconcileFetchEntry, type RemoteIdEntry, type ReplicationAdapter, type ResolvedPrice, STOCK_LEVELS_LAST_PASS, type ServerCapabilities, SignInError, type SignInErrorCode, type SignInResult, type StockLevel, type StockReconcileAdapter, type StockStatus, type StoreSettings, type StoreSettingsChoice, type StoreSettingsChoices, StoreSettingsError, type StoreSettingsErrorCode, type SyncContext, type SyncNotice, type TallyConnector, type TaxRounding, type TraitContext, type VariantSummary, combinePullAdapters, compareIds, createReconcileFeed, currencySymbol, customerTraits, errorKind, findVariantByCode, formatMoney, getProductStock, isRxdbRemoteVersionMismatch, knownWarnings, minorUnitDigits, moneyFromDecimalString, moneyFromMajor, moneyToMajor, parseInfoCapabilities, parseTaxRounding, resolveCapabilities, resolvePrice, resolvePriceRange, useConnector, useCustomerTraits, useProductStock, useProductTraits, useStockOverlaid, useStockOverlayAsOf, useTraitContext, withStockOverlay };