@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.
- package/dist/chunk-C4PWPOKO.js +18 -0
- package/dist/commands-BW4YYgRG.d.ts +306 -0
- package/dist/index.d.ts +226 -130
- package/dist/index.js +193 -19
- package/dist/rxdb/index.d.ts +5 -9
- package/dist/server/index.d.ts +213 -0
- package/dist/server/index.js +591 -0
- package/package.json +8 -2
- package/src/commands.ts +1 -1
- package/src/context/connector-context.tsx +30 -1
- package/src/index.ts +17 -5
- package/src/known-warnings.ts +77 -0
- package/src/replication/combine.ts +7 -3
- package/src/replication/reconcile-feed.ts +57 -20
- package/src/rxdb/read-fresh.ts +3 -7
- package/src/rxdb/watch-fresh.ts +2 -2
- package/src/rxdb-remote-version-mismatch.ts +30 -0
- package/src/server/__fixtures__/fingerprint-vectors.json +139 -0
- package/src/server/__fixtures__/order-create-v3.json +97 -0
- package/src/server/batch-outcome.ts +19 -0
- package/src/server/batch.ts +112 -0
- package/src/server/command-result.ts +138 -0
- package/src/server/fingerprint.ts +18 -0
- package/src/server/fiscal-figures.ts +84 -0
- package/src/server/index.ts +20 -0
- package/src/server/money.ts +34 -0
- package/src/server/order-payload-shape.ts +112 -0
- package/src/server/register-figures.ts +32 -0
- package/src/server/register-outcome.ts +12 -0
- package/src/server/register-payload-shape.ts +86 -0
- package/src/server/rejection-codes.ts +49 -0
- package/src/server/total-warnings.ts +10 -0
- package/src/server/versions.ts +9 -0
- package/src/sync-notice.ts +26 -0
- package/src/types/commands.ts +138 -9
- package/src/types/connector.ts +58 -1
- package/src/types/customers.ts +26 -0
- package/src/types/index.ts +9 -2
- package/src/types/reconcile.ts +30 -0
- package/src/types/replication.ts +6 -0
- package/src/types/store-settings.ts +4 -0
- package/src/types/traits/product.ts +7 -0
- package/src/unauthorized.ts +13 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createContext, useContext, useMemo, type ReactNode } from 'react';
|
|
2
2
|
|
|
3
|
-
import { getProductStock } from '../stock-overlay';
|
|
3
|
+
import { getProductStock, withStockOverlay } from '../stock-overlay';
|
|
4
4
|
import type { StockLevel, TallyConnector, TraitContext } from '../types';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -89,6 +89,35 @@ export function useProductStock(doc: any): StockLevel & { asOf?: string } {
|
|
|
89
89
|
return adapter && asOf ? { ...stock, asOf } : stock;
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
+
/**
|
|
93
|
+
* The products with the nearest ConnectorProvider's reconciled stock overlay merged in (copies only; the
|
|
94
|
+
* documents are never changed), for components that derive stock from documents themselves. Returns
|
|
95
|
+
* `products` itself, unchanged, when there is no provider, no overlay, or the connector has no stock
|
|
96
|
+
* reconcile adapter, and the same array while its inputs are unchanged.
|
|
97
|
+
*/
|
|
98
|
+
export function useStockOverlaid<Doc>(products: readonly Doc[]): readonly Doc[] {
|
|
99
|
+
const connector = useContext(ConnectorContext);
|
|
100
|
+
const { overlay } = useContext(StockOverlayContext);
|
|
101
|
+
const adapter = connector?.reconcile?.stock;
|
|
102
|
+
return useMemo(() => {
|
|
103
|
+
if (!adapter || !overlay) return products;
|
|
104
|
+
let changed = false;
|
|
105
|
+
const mapped = products.map((doc) => {
|
|
106
|
+
const next = withStockOverlay(doc, adapter, overlay as Map<string, unknown>);
|
|
107
|
+
if (next !== doc) changed = true;
|
|
108
|
+
return next;
|
|
109
|
+
});
|
|
110
|
+
return changed ? mapped : products;
|
|
111
|
+
}, [products, overlay, adapter]);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 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). */
|
|
115
|
+
export function useStockOverlayAsOf(): string | undefined {
|
|
116
|
+
const connector = useContext(ConnectorContext);
|
|
117
|
+
const { asOf } = useContext(StockOverlayContext);
|
|
118
|
+
return connector?.reconcile?.stock ? asOf : undefined;
|
|
119
|
+
}
|
|
120
|
+
|
|
92
121
|
/**
|
|
93
122
|
* Convenience hook: grab just the customer traits from the active connector.
|
|
94
123
|
* Returns undefined if the connector doesn't implement customer traits.
|
package/src/index.ts
CHANGED
|
@@ -24,18 +24,27 @@ export type {
|
|
|
24
24
|
StoreSettings,
|
|
25
25
|
StoreSettingsChoice,
|
|
26
26
|
} from './types';
|
|
27
|
-
export type { SignInResult, ServerCapabilities } from './types/connector';
|
|
28
|
-
export {
|
|
27
|
+
export type { SignInResult, ServerCapabilities, TaxRounding } from './types/connector';
|
|
28
|
+
export type { CatalogueReconcileAdapter, CatalogueReconcileEntry } from './types/reconcile';
|
|
29
|
+
export { parseInfoCapabilities, parseTaxRounding, resolveCapabilities } from './types/connector';
|
|
29
30
|
export { SignInError } from './sign-in';
|
|
31
|
+
export { ConnectorUnauthorizedError } from './unauthorized';
|
|
32
|
+
export { isRxdbRemoteVersionMismatch } from './rxdb-remote-version-mismatch';
|
|
33
|
+
export { errorKind, type ErrorKind, type SyncNotice } from './sync-notice';
|
|
30
34
|
export type { SignInErrorCode } from './sign-in';
|
|
31
35
|
export { StoreSettingsError } from './store-settings';
|
|
36
|
+
export { customerTraits, CustomerServiceError, type Customer, type CustomerInput } from './types/customers';
|
|
32
37
|
export type { StoreSettingsErrorCode, StoreSettingsChoices } from './store-settings';
|
|
33
38
|
|
|
34
39
|
export type {
|
|
35
40
|
CommandType, CommandEnvelope, CommandStatus, CommandServerRefs,
|
|
41
|
+
RegisterCommandType, RegisterCommandEnvelope, AnyCommandEnvelope,
|
|
36
42
|
CommandWarning, CommandError, CommandResult, OrderCreateLine,
|
|
37
|
-
PaymentMethodKind, OrderCreatePayment, OrderCreatePayload,
|
|
38
|
-
|
|
43
|
+
PaymentMethodKind, OrderCreatePayment, OrderCreatePayload, OrderCreateEnvelope,
|
|
44
|
+
OrderCreateDisplay, OrderCreateTaxRate,
|
|
45
|
+
CommandBatchRequest, CommandBatchResponse, BatchTooLargeBody,
|
|
46
|
+
RegisterCommandResult, RegisterSessionOpenPayload, RegisterSessionTransitionPayload,
|
|
47
|
+
RegisterMovementRecordPayload, RegisterMovementVoidPayload, RegisterClosureSubmitPayload,
|
|
39
48
|
} from './types';
|
|
40
49
|
|
|
41
50
|
export {
|
|
@@ -46,11 +55,12 @@ export {
|
|
|
46
55
|
// Money helpers
|
|
47
56
|
export { currencySymbol, formatMoney, minorUnitDigits, moneyFromDecimalString, moneyFromMajor, moneyToMajor, resolvePrice, resolvePriceRange } from './money';
|
|
48
57
|
export { findVariantByCode } from './variants';
|
|
58
|
+
export { knownWarnings } from './known-warnings';
|
|
49
59
|
export { compareIds } from './utils/compare-ids';
|
|
50
60
|
export { STOCK_LEVELS_LAST_PASS, withStockOverlay, getProductStock } from './stock-overlay';
|
|
51
61
|
export { combinePullAdapters } from './replication/combine';
|
|
52
62
|
export { createReconcileFeed } from './replication/reconcile-feed';
|
|
53
|
-
export type { ReconcileFeed, ReconcileFeedEntry } from './replication/reconcile-feed';
|
|
63
|
+
export type { ReconcileFeed, ReconcileFeedEntry, ReconcileFetchEntry, KeyedReconcileFeedOptions } from './replication/reconcile-feed';
|
|
54
64
|
|
|
55
65
|
// Context & hooks
|
|
56
66
|
export {
|
|
@@ -60,5 +70,7 @@ export {
|
|
|
60
70
|
useCustomerTraits,
|
|
61
71
|
useTraitContext,
|
|
62
72
|
useProductStock,
|
|
73
|
+
useStockOverlaid,
|
|
74
|
+
useStockOverlayAsOf,
|
|
63
75
|
} from './context/connector-context';
|
|
64
76
|
export type { ConnectorProviderProps } from './context/connector-context';
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { CommandWarning } from './types/commands';
|
|
2
|
+
|
|
3
|
+
function isSafeInt(value: unknown): value is number {
|
|
4
|
+
return typeof value === 'number' && Number.isSafeInteger(value);
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
type FiguresMismatchField = Extract<CommandWarning, { code: 'figures_mismatch' }>['fields'][number];
|
|
8
|
+
|
|
9
|
+
function figuresMismatchFields(fields: unknown): FiguresMismatchField[] | null {
|
|
10
|
+
if (!Array.isArray(fields) || fields.length === 0) return null;
|
|
11
|
+
const rebuilt: FiguresMismatchField[] = [];
|
|
12
|
+
for (const entry of fields) {
|
|
13
|
+
if (typeof entry !== 'object' || entry === null) return null;
|
|
14
|
+
const { field, tillMinor, serverMinor } = entry as Record<string, unknown>;
|
|
15
|
+
if (typeof field !== 'string' || field === '' || rebuilt.some((kept) => kept.field === field)) return null;
|
|
16
|
+
if (!isSafeInt(tillMinor) || !isSafeInt(serverMinor) || tillMinor === serverMinor) return null;
|
|
17
|
+
rebuilt.push({ field, tillMinor, serverMinor });
|
|
18
|
+
}
|
|
19
|
+
return rebuilt;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The till's single reader of stored warnings. `[]` for anything that isn't a warnings array.
|
|
24
|
+
* A `total_mismatch`'s `bridgeMinor` is dropped (the rest of the warning is kept) when it's
|
|
25
|
+
* absent, `null`, not a safe integer, zero, or not equal to `expectedMinor - serverMinor`.
|
|
26
|
+
* A `tax_rate_mismatch` with a negative `ratePpm` is dropped entirely; zero stays valid.
|
|
27
|
+
* A `customer_ignored` is dropped unless its `customerId` is a string of 1 to 64 characters.
|
|
28
|
+
* A `figures_mismatch` is dropped entirely unless `fields` is non-empty and each entry names a
|
|
29
|
+
* different figure with two differing safe integers; each entry is rebuilt from its known keys.
|
|
30
|
+
* A figure name it doesn't know (any non-empty string) is kept, since a newer store may send one.
|
|
31
|
+
*/
|
|
32
|
+
export function knownWarnings(warnings: unknown): CommandWarning[] {
|
|
33
|
+
if (!Array.isArray(warnings)) return [];
|
|
34
|
+
const kept: CommandWarning[] = [];
|
|
35
|
+
for (const item of warnings) {
|
|
36
|
+
if (typeof item !== 'object' || item === null || Array.isArray(item)) continue;
|
|
37
|
+
const warning = item as Record<string, unknown>;
|
|
38
|
+
switch (warning.code) {
|
|
39
|
+
case 'total_mismatch': {
|
|
40
|
+
if (!isSafeInt(warning.expectedMinor) || !isSafeInt(warning.serverMinor)) continue;
|
|
41
|
+
const { bridgeMinor } = warning;
|
|
42
|
+
const validBridge = isSafeInt(bridgeMinor) && bridgeMinor !== 0
|
|
43
|
+
&& bridgeMinor === warning.expectedMinor - warning.serverMinor;
|
|
44
|
+
kept.push(validBridge
|
|
45
|
+
? { code: 'total_mismatch', expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor, bridgeMinor }
|
|
46
|
+
: { code: 'total_mismatch', expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor });
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
case 'insufficient_stock': {
|
|
50
|
+
if (typeof warning.variantId !== 'string' || warning.variantId === '') continue;
|
|
51
|
+
if (!isSafeInt(warning.quantity) || warning.quantity < 1) continue;
|
|
52
|
+
kept.push({ code: 'insufficient_stock', variantId: warning.variantId, quantity: warning.quantity });
|
|
53
|
+
break;
|
|
54
|
+
}
|
|
55
|
+
case 'tax_rate_mismatch': {
|
|
56
|
+
if (!isSafeInt(warning.ratePpm) || warning.ratePpm < 0) continue;
|
|
57
|
+
if (!isSafeInt(warning.expectedMinor) || !isSafeInt(warning.serverMinor)) continue;
|
|
58
|
+
kept.push({ code: 'tax_rate_mismatch', ratePpm: warning.ratePpm, expectedMinor: warning.expectedMinor, serverMinor: warning.serverMinor });
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
case 'customer_ignored': {
|
|
62
|
+
const { customerId } = warning;
|
|
63
|
+
if (typeof customerId !== 'string' || customerId === '' || customerId.length > 64) continue;
|
|
64
|
+
kept.push({ code: 'customer_ignored', customerId });
|
|
65
|
+
break;
|
|
66
|
+
}
|
|
67
|
+
case 'figures_mismatch': {
|
|
68
|
+
const fields = figuresMismatchFields(warning.fields);
|
|
69
|
+
if (fields !== null) kept.push({ code: 'figures_mismatch', fields });
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
default:
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return kept;
|
|
77
|
+
}
|
|
@@ -12,11 +12,13 @@ import type { ReplicationAdapter } from '../types';
|
|
|
12
12
|
* checkpoint with none of the keys becomes that key's checkpoint. With no stored
|
|
13
13
|
* checkpoint at all, each sub-adapter with `pull.seedCheckpoint` starts from its seed.
|
|
14
14
|
*
|
|
15
|
+
* `options.batchSize` sets the combined pull page size; sub-adapters' own
|
|
16
|
+
* `pull.batchSize` is ignored.
|
|
15
17
|
* Pull only: a sub-adapter with `push` or `pull.stream$` throws here.
|
|
16
18
|
*/
|
|
17
19
|
export function combinePullAdapters<Doc>(
|
|
18
20
|
adapters: Record<string, ReplicationAdapter<Doc, any>>,
|
|
19
|
-
options: { legacyKey?: string } = {},
|
|
21
|
+
options: { legacyKey?: string; batchSize?: number } = {},
|
|
20
22
|
): ReplicationAdapter<Doc, Record<string, any>> {
|
|
21
23
|
const keys = Object.keys(adapters);
|
|
22
24
|
for (const key of keys) {
|
|
@@ -26,6 +28,7 @@ export function combinePullAdapters<Doc>(
|
|
|
26
28
|
}
|
|
27
29
|
return {
|
|
28
30
|
pull: {
|
|
31
|
+
batchSize: options.batchSize,
|
|
29
32
|
async handler(lastCheckpoint, batchSize, context) {
|
|
30
33
|
let previous = lastCheckpoint;
|
|
31
34
|
if (options.legacyKey && previous && typeof previous === 'object'
|
|
@@ -52,8 +55,9 @@ export function combinePullAdapters<Doc>(
|
|
|
52
55
|
// Call sub-adapters strictly one after another, in key order: a
|
|
53
56
|
// correctness rule, not politeness. Each feed writes whole documents.
|
|
54
57
|
// Sequential calls with the last duplicate winning mean every document
|
|
55
|
-
// comes from the latest fetch of this call
|
|
56
|
-
// call
|
|
58
|
+
// comes from the latest fetch of this call. RxDB 16.21.1 can fetch the next
|
|
59
|
+
// call before these writes finish, but its persistence queue keeps fetch
|
|
60
|
+
// order (pending duplicates keep the latest). Concurrent feeds could let a
|
|
57
61
|
// fetch made before another feed's newer write land after it and revert
|
|
58
62
|
// it, with neither checkpoint ever revisiting the document.
|
|
59
63
|
for (const key of keys) {
|
|
@@ -4,41 +4,70 @@ import type { ReplicationAdapter } from '../types/replication';
|
|
|
4
4
|
/** At most this many ids per `fetchByIds` call (ADR-060). */
|
|
5
5
|
const MAX_CHUNK = 1000;
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
7
|
+
/**
|
|
8
|
+
* One queued correction, keyed by the local primary key: `key`, or `id`, its
|
|
9
|
+
* older name. `local` is the till's copy, if it has one; `remote` is whatever
|
|
10
|
+
* the connector needs to refetch it.
|
|
11
|
+
*/
|
|
12
|
+
export type ReconcileFeedEntry<Doc = any> = ({ key: string; id?: undefined } | { id: string; key?: undefined }) & {
|
|
13
|
+
local?: Doc;
|
|
14
|
+
remote?: unknown;
|
|
10
15
|
/**
|
|
11
16
|
* Re-deliver if the product still exists; never tombstone if missing (the
|
|
12
17
|
* fingerprint path, ADR-060). Only the id reconcile, with its mass-delete
|
|
13
18
|
* brake, enqueues deletable entries.
|
|
14
19
|
*/
|
|
15
20
|
refreshOnly?: boolean;
|
|
16
|
-
|
|
21
|
+
/** Proven gone (the catalogue reconcile, #248): written as deleted from `local`, without a fetch. */
|
|
22
|
+
tombstone?: boolean;
|
|
23
|
+
};
|
|
24
|
+
/** What a keyed feed's `fetchByIds` receives for each entry. */
|
|
25
|
+
export interface ReconcileFetchEntry<Doc = any> { key: string; local?: Doc; remote?: unknown }
|
|
17
26
|
export interface CreateReconcileFeedOptions<Doc = any> {
|
|
18
|
-
/** The current projected documents for the ids that still exist. */
|
|
27
|
+
/** The current projected documents for the ids that still exist, matched back by `doc.id`. */
|
|
19
28
|
fetchByIds(ids: string[], context: SyncContext): Promise<Doc[]>;
|
|
20
29
|
}
|
|
30
|
+
/** A feed keyed by the primary key where that is not `doc.id` (WooCommerce's uuid, #248). */
|
|
31
|
+
export interface KeyedReconcileFeedOptions<Doc = any> {
|
|
32
|
+
/** The local primary key of a fetched document; fetched documents are matched to entries by it. */
|
|
33
|
+
key(doc: Doc): string;
|
|
34
|
+
/** The current documents for the entries that still exist. A document may carry `_deleted: true` (an unpublished product). */
|
|
35
|
+
fetchByIds(entries: Array<ReconcileFetchEntry<Doc>>, context: SyncContext): Promise<Doc[]>;
|
|
36
|
+
}
|
|
21
37
|
export interface ReconcileFeed<Doc = any> {
|
|
22
38
|
/** Pull-only; meant as the last key of `combinePullAdapters` so its fetch wins duplicates. */
|
|
23
39
|
adapter: ReplicationAdapter<Doc, { n: number }>;
|
|
24
40
|
/**
|
|
25
|
-
* Add entries to the in-memory queue, de-duplicated by
|
|
26
|
-
* `
|
|
27
|
-
*
|
|
28
|
-
*
|
|
41
|
+
* Add entries to the in-memory queue, de-duplicated by key, last entry wins.
|
|
42
|
+
* `refreshOnly` is merged separately: it is true only when every merged
|
|
43
|
+
* entry for that key was `refreshOnly`, so a deletable entry (the id
|
|
44
|
+
* reconcile's) is never downgraded by a later refresh-only one.
|
|
29
45
|
*/
|
|
30
46
|
enqueue(entries: Array<ReconcileFeedEntry<Doc>>): void;
|
|
31
47
|
}
|
|
32
48
|
|
|
33
|
-
/**
|
|
34
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Turns queued corrections into a pull adapter's documents; nothing here writes locally (ADR-060).
|
|
51
|
+
* Two overloads: with `key`, `fetchByIds` receives the entries and fetched documents are matched by
|
|
52
|
+
* `key(doc)`; without it, `fetchByIds` receives bare ids and documents are matched by `doc.id`.
|
|
53
|
+
*/
|
|
54
|
+
export function createReconcileFeed<Doc = any>(options: KeyedReconcileFeedOptions<Doc>): ReconcileFeed<Doc>;
|
|
55
|
+
export function createReconcileFeed<Doc = any>(options: CreateReconcileFeedOptions<Doc>): ReconcileFeed<Doc>;
|
|
56
|
+
export function createReconcileFeed<Doc = any>(
|
|
57
|
+
options: KeyedReconcileFeedOptions<Doc> | CreateReconcileFeedOptions<Doc>,
|
|
58
|
+
): ReconcileFeed<Doc> {
|
|
59
|
+
const keyed = 'key' in options && typeof options.key === 'function' ? options : undefined;
|
|
60
|
+
const docKey = keyed ? keyed.key : (doc: Doc) => (doc as { id?: unknown }).id;
|
|
61
|
+
const fetch = (chunk: Array<ReconcileFeedEntry<Doc>>, context: SyncContext): Promise<Doc[]> => keyed
|
|
62
|
+
? keyed.fetchByIds(chunk.map((e) => ({ key: keyOf(e), local: e.local, remote: e.remote })), context)
|
|
63
|
+
: (options as CreateReconcileFeedOptions<Doc>).fetchByIds(chunk.map(keyOf), context);
|
|
35
64
|
let queue = new Map<string, ReconcileFeedEntry<Doc>>();
|
|
36
65
|
// refreshOnly is true only if both the prior and the incoming entry were
|
|
37
66
|
// refreshOnly: a deletable entry is never downgraded by a later refresh-only one.
|
|
38
67
|
const merge = (prior: ReconcileFeedEntry<Doc> | undefined, e: ReconcileFeedEntry<Doc>): ReconcileFeedEntry<Doc> =>
|
|
39
68
|
({ ...e, refreshOnly: Boolean(e.refreshOnly) && (prior?.refreshOnly ?? true) });
|
|
40
69
|
const enqueue = (entries: Array<ReconcileFeedEntry<Doc>>) => {
|
|
41
|
-
for (const e of entries) queue.set(e
|
|
70
|
+
for (const e of entries) queue.set(keyOf(e), merge(queue.get(keyOf(e)), e));
|
|
42
71
|
};
|
|
43
72
|
|
|
44
73
|
const adapter: ReplicationAdapter<Doc, { n: number }> = {
|
|
@@ -50,25 +79,28 @@ export function createReconcileFeed<Doc = any>({ fetchByIds }: CreateReconcileFe
|
|
|
50
79
|
queue = new Map();
|
|
51
80
|
try {
|
|
52
81
|
const documents: Array<Doc & { _deleted: boolean }> = [];
|
|
53
|
-
// Fetch in chunks of at most MAX_CHUNK
|
|
82
|
+
// Fetch in chunks of at most MAX_CHUNK entries per call; a tombstone is never fetched.
|
|
54
83
|
for (let i = 0; i < entries.length; i += MAX_CHUNK) {
|
|
55
84
|
const chunk = entries.slice(i, i + MAX_CHUNK);
|
|
56
|
-
const
|
|
57
|
-
const
|
|
85
|
+
const toFetch = chunk.filter((e) => !e.tombstone);
|
|
86
|
+
const fetched = toFetch.length ? await fetch(toFetch, context) : [];
|
|
87
|
+
const byKey = new Map(fetched.map((doc) => [docKey(doc), doc]));
|
|
58
88
|
for (const entry of chunk) {
|
|
59
|
-
const doc =
|
|
60
|
-
|
|
89
|
+
const doc = entry.tombstone ? undefined : byKey.get(keyOf(entry));
|
|
90
|
+
// A fetched document keeps a `_deleted` the connector set (an unpublished product, #248).
|
|
91
|
+
if (doc) documents.push({ ...doc, _deleted: (doc as { _deleted?: boolean })._deleted ?? false });
|
|
61
92
|
// A refreshOnly entry (the fingerprint path) is skipped, not tombstoned, when the
|
|
62
93
|
// product is missing: only the id reconcile's braked entries may delete (ADR-060).
|
|
63
|
-
|
|
94
|
+
// An entry with no local copy has nothing to delete.
|
|
95
|
+
else if (!entry.refreshOnly && entry.local) documents.push({ ...entry.local, _deleted: true });
|
|
64
96
|
}
|
|
65
97
|
}
|
|
66
98
|
return { documents, checkpoint: { n: (lastCheckpoint?.n ?? 0) + 1 } };
|
|
67
99
|
} catch (error) {
|
|
68
100
|
// Put entries back at the front; anything queued mid-fetch wins, merged
|
|
69
101
|
// by the same rule, so a failed fetch never downgrades a deletable entry. RxDB retries.
|
|
70
|
-
const restored = new Map(entries.map((e) => [e
|
|
71
|
-
for (const [
|
|
102
|
+
const restored = new Map(entries.map((e) => [keyOf(e), e]));
|
|
103
|
+
for (const [key, e] of queue) restored.set(key, merge(restored.get(key), e));
|
|
72
104
|
queue = restored;
|
|
73
105
|
throw error;
|
|
74
106
|
}
|
|
@@ -77,3 +109,8 @@ export function createReconcileFeed<Doc = any>({ fetchByIds }: CreateReconcileFe
|
|
|
77
109
|
};
|
|
78
110
|
return { adapter, enqueue };
|
|
79
111
|
}
|
|
112
|
+
|
|
113
|
+
/** An entry's local primary key: `key`, or `id`, its older name. */
|
|
114
|
+
function keyOf(entry: ReconcileFeedEntry): string {
|
|
115
|
+
return (entry.key ?? entry.id) as string;
|
|
116
|
+
}
|
package/src/rxdb/read-fresh.ts
CHANGED
|
@@ -3,13 +3,9 @@ import { clone, type MangoQuery, type MangoQuerySelector, type RxCollection } fr
|
|
|
3
3
|
/**
|
|
4
4
|
* Reads straight from the collection's storage, past RxDB's cached query result.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* `count(sameQuery).exec()` returns the stale result, and a later matching write doesn't heal it.
|
|
10
|
-
* No subscription is needed. This is "bug 4" in TallyUI's local RxDB repro (the query-cache-stale
|
|
11
|
-
* script beside the migration checkpoint repro). For the order outbox it left a sale unsent until
|
|
12
|
-
* the app restarted.
|
|
6
|
+
* Originally bypassed RxDB 16.21.1's bug 4, fixed in RxDB 17 (rxdb#7067) by snapshotting the
|
|
7
|
+
* change counter before a read and rerunning when it moves. `readFresh`, `countFresh` and
|
|
8
|
+
* `watchFresh` remain correct public API; retiring them is a separate decision.
|
|
13
9
|
*
|
|
14
10
|
* The prepared query is RxDB's own (`find(query).getPreparedQuery()`), so it already carries the
|
|
15
11
|
* `_deleted: false` filter, the query's sort and its limit. The read goes through the same wrapped
|
package/src/rxdb/watch-fresh.ts
CHANGED
|
@@ -3,8 +3,8 @@ import type { MangoQuery, RxCollection } from 'rxdb';
|
|
|
3
3
|
import { readFresh } from './read-fresh';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
6
|
+
* RxDB 17 fixed RxDB 16.21.1's bug 4 (rxdb#7067); `readFresh`, `countFresh` and `watchFresh`
|
|
7
|
+
* remain correct public API. Retiring them is a separate decision.
|
|
8
8
|
* `collection.eventBulks$` fires on every write and never touches that cache, so re-reading with
|
|
9
9
|
* `readFresh` on subscribe and again on every event bulk can't miss one; `switchMap` drops a read
|
|
10
10
|
* still in flight when a newer one starts. It is one event per storage change bulk, not per
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// How RxDB's remote storage re-throws a worker's rejected createStorageInstance on the main thread
|
|
2
|
+
// (rxdb 17.5.0 src/plugins/storage-remote/rx-storage-remote.ts:100):
|
|
3
|
+
// `new Error('could not create instance ' + JSON.stringify(error))`.
|
|
4
|
+
const REMOTE_CREATE_PREFIX = 'could not create instance ';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* True for RxDB's RM1: the remote storage worker was built on another RxDB
|
|
8
|
+
* version than the main thread, e.g. a stale worker the browser cached from
|
|
9
|
+
* before an upgrade. Reloading loads the matching worker.
|
|
10
|
+
*
|
|
11
|
+
* Matched by structure, never by substring. An `RxError` (rxdb 17.5.0
|
|
12
|
+
* src/rx-error.ts) has own `code`, `message`, `url`, `parameters` and
|
|
13
|
+
* `rxdb: true`; its `name` is a getter. So RM1 is either an object whose own
|
|
14
|
+
* `code` is `'RM1'` (with `rxdb === true` when `rxdb` is present), or an
|
|
15
|
+
* error, `{ message }` copy or string whose message is the remote storage's
|
|
16
|
+
* `could not create instance ` followed by JSON with `rxdb: true` and
|
|
17
|
+
* `code: 'RM1'`. Needs no rxdb import.
|
|
18
|
+
*/
|
|
19
|
+
export function isRxdbRemoteVersionMismatch(error: unknown): boolean {
|
|
20
|
+
const { code, rxdb, message } = (typeof error === 'object' && error !== null ? error : {}) as Record<string, unknown>;
|
|
21
|
+
if (code === 'RM1' && (rxdb ?? true) === true) return true;
|
|
22
|
+
const text = typeof error === 'string' ? error : message;
|
|
23
|
+
if (typeof text !== 'string' || !text.startsWith(REMOTE_CREATE_PREFIX)) return false;
|
|
24
|
+
try {
|
|
25
|
+
const wrapped = JSON.parse(text.slice(REMOTE_CREATE_PREFIX.length)) as Record<string, unknown> | null;
|
|
26
|
+
return wrapped?.rxdb === true && wrapped.code === 'RM1';
|
|
27
|
+
} catch {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"name": "order-create-v3 golden fixture",
|
|
4
|
+
"envelope": {
|
|
5
|
+
"type": "order.create",
|
|
6
|
+
"version": 3,
|
|
7
|
+
"payload": {
|
|
8
|
+
"clientOrderId": "019f6d2e-7800-7000-8000-000000000002",
|
|
9
|
+
"createdAt": "2026-09-28T10:00:00.000Z",
|
|
10
|
+
"currency": "EUR",
|
|
11
|
+
"pricesIncludeTax": true,
|
|
12
|
+
"lines": [
|
|
13
|
+
{
|
|
14
|
+
"clientLineId": "line_inclusive",
|
|
15
|
+
"variantId": "variant_inclusive",
|
|
16
|
+
"title": "Inclusive item",
|
|
17
|
+
"quantity": 2,
|
|
18
|
+
"unitPriceMinor": 1200,
|
|
19
|
+
"discountMinor": 203
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"clientLineId": "line_exclusive",
|
|
23
|
+
"variantId": "variant_exclusive",
|
|
24
|
+
"title": "Exclusive item",
|
|
25
|
+
"quantity": 1,
|
|
26
|
+
"unitPriceMinor": 1000,
|
|
27
|
+
"taxInclusive": false,
|
|
28
|
+
"discountMinor": 37
|
|
29
|
+
}
|
|
30
|
+
],
|
|
31
|
+
"payments": [
|
|
32
|
+
{
|
|
33
|
+
"clientPaymentId": "payment_cash",
|
|
34
|
+
"method": "cash",
|
|
35
|
+
"amountMinor": 3256,
|
|
36
|
+
"tenderedMinor": 4000,
|
|
37
|
+
"changeMinor": 744,
|
|
38
|
+
"reference": "cash_receipt_1"
|
|
39
|
+
}
|
|
40
|
+
],
|
|
41
|
+
"subtotalMinor": 2794,
|
|
42
|
+
"discountMinor": 240,
|
|
43
|
+
"taxMinor": 462,
|
|
44
|
+
"totalMinor": 3256,
|
|
45
|
+
"display": {
|
|
46
|
+
"currency": "EUR",
|
|
47
|
+
"exponent": 2,
|
|
48
|
+
"taxInclusive": true,
|
|
49
|
+
"subtotalMinor": 3500,
|
|
50
|
+
"discountMinor": 244,
|
|
51
|
+
"taxMinor": 462,
|
|
52
|
+
"totalMinor": 3256,
|
|
53
|
+
"lines": [
|
|
54
|
+
{
|
|
55
|
+
"clientLineId": "line_inclusive",
|
|
56
|
+
"amountMinor": 2400,
|
|
57
|
+
"discounts": [
|
|
58
|
+
{
|
|
59
|
+
"discountId": "discount_line",
|
|
60
|
+
"label": "Line discount",
|
|
61
|
+
"amountMinor": 120
|
|
62
|
+
}
|
|
63
|
+
]
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
"clientLineId": "line_exclusive",
|
|
67
|
+
"amountMinor": 1100,
|
|
68
|
+
"discounts": []
|
|
69
|
+
}
|
|
70
|
+
],
|
|
71
|
+
"orderDiscountMinor": 124
|
|
72
|
+
},
|
|
73
|
+
"taxByRate": [
|
|
74
|
+
{
|
|
75
|
+
"ratePpm": 200000,
|
|
76
|
+
"code": "VAT20",
|
|
77
|
+
"netMinor": 1831,
|
|
78
|
+
"taxMinor": 366,
|
|
79
|
+
"grossMinor": 2197
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
"ratePpm": 100000,
|
|
83
|
+
"netMinor": 963,
|
|
84
|
+
"taxMinor": 96,
|
|
85
|
+
"grossMinor": 1059
|
|
86
|
+
}
|
|
87
|
+
],
|
|
88
|
+
"customer": {
|
|
89
|
+
"email": "buyer@example.com",
|
|
90
|
+
"customerId": "cus_golden_v3"
|
|
91
|
+
},
|
|
92
|
+
"registerId": "register_golden",
|
|
93
|
+
"cashierRef": "cashier_golden",
|
|
94
|
+
"sessionId": "019f6d2e-7800-7000-8000-000000000003"
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
"canonical": "{\"payload\":{\"cashierRef\":\"cashier_golden\",\"clientOrderId\":\"019f6d2e-7800-7000-8000-000000000002\",\"createdAt\":\"2026-09-28T10:00:00.000Z\",\"currency\":\"EUR\",\"customer\":{\"customerId\":\"cus_golden_v3\",\"email\":\"buyer@example.com\"},\"discountMinor\":240,\"display\":{\"currency\":\"EUR\",\"discountMinor\":244,\"exponent\":2,\"lines\":[{\"amountMinor\":2400,\"clientLineId\":\"line_inclusive\",\"discounts\":[{\"amountMinor\":120,\"discountId\":\"discount_line\",\"label\":\"Line discount\"}]},{\"amountMinor\":1100,\"clientLineId\":\"line_exclusive\",\"discounts\":[]}],\"orderDiscountMinor\":124,\"subtotalMinor\":3500,\"taxInclusive\":true,\"taxMinor\":462,\"totalMinor\":3256},\"lines\":[{\"clientLineId\":\"line_inclusive\",\"discountMinor\":203,\"quantity\":2,\"title\":\"Inclusive item\",\"unitPriceMinor\":1200,\"variantId\":\"variant_inclusive\"},{\"clientLineId\":\"line_exclusive\",\"discountMinor\":37,\"quantity\":1,\"taxInclusive\":false,\"title\":\"Exclusive item\",\"unitPriceMinor\":1000,\"variantId\":\"variant_exclusive\"}],\"payments\":[{\"amountMinor\":3256,\"changeMinor\":744,\"clientPaymentId\":\"payment_cash\",\"method\":\"cash\",\"reference\":\"cash_receipt_1\",\"tenderedMinor\":4000}],\"pricesIncludeTax\":true,\"registerId\":\"register_golden\",\"sessionId\":\"019f6d2e-7800-7000-8000-000000000003\",\"subtotalMinor\":2794,\"taxByRate\":[{\"code\":\"VAT20\",\"grossMinor\":2197,\"netMinor\":1831,\"ratePpm\":200000,\"taxMinor\":366},{\"grossMinor\":1059,\"netMinor\":963,\"ratePpm\":100000,\"taxMinor\":96}],\"taxMinor\":462,\"totalMinor\":3256},\"type\":\"order.create\",\"version\":3}",
|
|
98
|
+
"fingerprint": "aea62fe9f460bbdfd93771cbe08b3bb98e5761f172b974b62d72dfe30f6bc436"
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
"name": "key order, nested objects, undefined field dropped",
|
|
102
|
+
"envelope": {
|
|
103
|
+
"type": "order.create",
|
|
104
|
+
"version": 1,
|
|
105
|
+
"payload": {
|
|
106
|
+
"z": 1,
|
|
107
|
+
"a": {
|
|
108
|
+
"d": [
|
|
109
|
+
3,
|
|
110
|
+
1,
|
|
111
|
+
2
|
|
112
|
+
],
|
|
113
|
+
"c": "x"
|
|
114
|
+
},
|
|
115
|
+
"m": null
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
"canonical": "{\"payload\":{\"a\":{\"c\":\"x\",\"d\":[3,1,2]},\"m\":null,\"z\":1},\"type\":\"order.create\",\"version\":1}",
|
|
119
|
+
"fingerprint": "cecf2c94e7da1867b95b66d5e46e686bf274f780e312efb2d8387841cc00d483"
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
"name": "undefined array item becomes null; unicode and negative numbers",
|
|
123
|
+
"envelope": {
|
|
124
|
+
"type": "register.movement.record",
|
|
125
|
+
"version": 1,
|
|
126
|
+
"payload": {
|
|
127
|
+
"items": [
|
|
128
|
+
1,
|
|
129
|
+
null,
|
|
130
|
+
"é",
|
|
131
|
+
-0.5
|
|
132
|
+
],
|
|
133
|
+
"reason": "café \"quoted\""
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
"canonical": "{\"payload\":{\"items\":[1,null,\"é\",-0.5],\"reason\":\"café \\\"quoted\\\"\"},\"type\":\"register.movement.record\",\"version\":1}",
|
|
137
|
+
"fingerprint": "95316177d791a50f25937d646cae922766e33dc77e3287b3dbec791f9c410948"
|
|
138
|
+
}
|
|
139
|
+
]
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "019f6d2e-7800-7000-8000-000000000001",
|
|
3
|
+
"type": "order.create",
|
|
4
|
+
"version": 3,
|
|
5
|
+
"createdAt": "2026-09-28T10:00:00.000Z",
|
|
6
|
+
"deviceId": "device_golden",
|
|
7
|
+
"attempt": 1,
|
|
8
|
+
"payload": {
|
|
9
|
+
"clientOrderId": "019f6d2e-7800-7000-8000-000000000002",
|
|
10
|
+
"createdAt": "2026-09-28T10:00:00.000Z",
|
|
11
|
+
"currency": "EUR",
|
|
12
|
+
"pricesIncludeTax": true,
|
|
13
|
+
"lines": [
|
|
14
|
+
{
|
|
15
|
+
"clientLineId": "line_inclusive",
|
|
16
|
+
"variantId": "variant_inclusive",
|
|
17
|
+
"title": "Inclusive item",
|
|
18
|
+
"quantity": 2,
|
|
19
|
+
"unitPriceMinor": 1200,
|
|
20
|
+
"discountMinor": 203
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
"clientLineId": "line_exclusive",
|
|
24
|
+
"variantId": "variant_exclusive",
|
|
25
|
+
"title": "Exclusive item",
|
|
26
|
+
"quantity": 1,
|
|
27
|
+
"unitPriceMinor": 1000,
|
|
28
|
+
"taxInclusive": false,
|
|
29
|
+
"discountMinor": 37
|
|
30
|
+
}
|
|
31
|
+
],
|
|
32
|
+
"payments": [
|
|
33
|
+
{
|
|
34
|
+
"clientPaymentId": "payment_cash",
|
|
35
|
+
"method": "cash",
|
|
36
|
+
"amountMinor": 3256,
|
|
37
|
+
"tenderedMinor": 4000,
|
|
38
|
+
"changeMinor": 744,
|
|
39
|
+
"reference": "cash_receipt_1"
|
|
40
|
+
}
|
|
41
|
+
],
|
|
42
|
+
"subtotalMinor": 2794,
|
|
43
|
+
"discountMinor": 240,
|
|
44
|
+
"taxMinor": 462,
|
|
45
|
+
"totalMinor": 3256,
|
|
46
|
+
"display": {
|
|
47
|
+
"currency": "EUR",
|
|
48
|
+
"exponent": 2,
|
|
49
|
+
"taxInclusive": true,
|
|
50
|
+
"subtotalMinor": 3500,
|
|
51
|
+
"discountMinor": 244,
|
|
52
|
+
"taxMinor": 462,
|
|
53
|
+
"totalMinor": 3256,
|
|
54
|
+
"lines": [
|
|
55
|
+
{
|
|
56
|
+
"clientLineId": "line_inclusive",
|
|
57
|
+
"amountMinor": 2400,
|
|
58
|
+
"discounts": [
|
|
59
|
+
{
|
|
60
|
+
"discountId": "discount_line",
|
|
61
|
+
"label": "Line discount",
|
|
62
|
+
"amountMinor": 120
|
|
63
|
+
}
|
|
64
|
+
]
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
"clientLineId": "line_exclusive",
|
|
68
|
+
"amountMinor": 1100,
|
|
69
|
+
"discounts": []
|
|
70
|
+
}
|
|
71
|
+
],
|
|
72
|
+
"orderDiscountMinor": 124
|
|
73
|
+
},
|
|
74
|
+
"taxByRate": [
|
|
75
|
+
{
|
|
76
|
+
"ratePpm": 200000,
|
|
77
|
+
"code": "VAT20",
|
|
78
|
+
"netMinor": 1831,
|
|
79
|
+
"taxMinor": 366,
|
|
80
|
+
"grossMinor": 2197
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
"ratePpm": 100000,
|
|
84
|
+
"netMinor": 963,
|
|
85
|
+
"taxMinor": 96,
|
|
86
|
+
"grossMinor": 1059
|
|
87
|
+
}
|
|
88
|
+
],
|
|
89
|
+
"customer": {
|
|
90
|
+
"email": "buyer@example.com",
|
|
91
|
+
"customerId": "cus_golden_v3"
|
|
92
|
+
},
|
|
93
|
+
"registerId": "register_golden",
|
|
94
|
+
"cashierRef": "cashier_golden",
|
|
95
|
+
"sessionId": "019f6d2e-7800-7000-8000-000000000003"
|
|
96
|
+
}
|
|
97
|
+
}
|