@tallyui/core 0.2.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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/dist/chunk-C4PWPOKO.js +18 -0
  3. package/dist/commands-BW4YYgRG.d.ts +306 -0
  4. package/dist/index.d.ts +636 -8
  5. package/dist/index.js +468 -4
  6. package/dist/rxdb/index.d.ts +37 -0
  7. package/dist/rxdb/index.js +26 -0
  8. package/dist/server/index.d.ts +213 -0
  9. package/dist/server/index.js +591 -0
  10. package/package.json +33 -3
  11. package/src/commands.ts +32 -0
  12. package/src/context/connector-context.tsx +78 -4
  13. package/src/index.ts +53 -0
  14. package/src/known-warnings.ts +77 -0
  15. package/src/money.ts +142 -0
  16. package/src/replication/combine.ts +77 -0
  17. package/src/replication/reconcile-feed.ts +116 -0
  18. package/src/rxdb/index.ts +4 -0
  19. package/src/rxdb/read-fresh.ts +32 -0
  20. package/src/rxdb/watch-fresh.ts +19 -0
  21. package/src/rxdb-remote-version-mismatch.ts +30 -0
  22. package/src/server/__fixtures__/fingerprint-vectors.json +139 -0
  23. package/src/server/__fixtures__/order-create-v3.json +97 -0
  24. package/src/server/batch-outcome.ts +19 -0
  25. package/src/server/batch.ts +112 -0
  26. package/src/server/command-result.ts +138 -0
  27. package/src/server/fingerprint.ts +18 -0
  28. package/src/server/fiscal-figures.ts +84 -0
  29. package/src/server/index.ts +20 -0
  30. package/src/server/money.ts +34 -0
  31. package/src/server/order-payload-shape.ts +112 -0
  32. package/src/server/register-figures.ts +32 -0
  33. package/src/server/register-outcome.ts +12 -0
  34. package/src/server/register-payload-shape.ts +86 -0
  35. package/src/server/rejection-codes.ts +49 -0
  36. package/src/server/total-warnings.ts +10 -0
  37. package/src/server/versions.ts +9 -0
  38. package/src/sign-in.ts +21 -0
  39. package/src/stock-overlay.ts +35 -0
  40. package/src/store-settings.ts +29 -0
  41. package/src/sync-notice.ts +26 -0
  42. package/src/types/commands.ts +236 -0
  43. package/src/types/connector.ts +127 -0
  44. package/src/types/customers.ts +26 -0
  45. package/src/types/index.ts +23 -1
  46. package/src/types/money.ts +33 -0
  47. package/src/types/reconcile.ts +73 -0
  48. package/src/types/replication.ts +12 -0
  49. package/src/types/stock.ts +18 -0
  50. package/src/types/store-settings.ts +27 -0
  51. package/src/types/traits/product.ts +62 -6
  52. package/src/unauthorized.ts +13 -0
  53. package/src/utils/compare-ids.ts +16 -0
  54. package/src/variants.ts +14 -0
  55. package/src/__tests__/connector-context.test.tsx +0 -100
  56. package/src/types/replication.test-d.ts +0 -20
package/dist/index.js CHANGED
@@ -1,9 +1,407 @@
1
+ import {
2
+ COMMANDS_PATH,
3
+ MAX_COMMANDS_PER_BATCH,
4
+ PROTOCOL_HEADER,
5
+ PROTOCOL_VERSION,
6
+ isCommandBatchResponse
7
+ } from "./chunk-C4PWPOKO.js";
8
+
9
+ // src/types/connector.ts
10
+ function resolveCapabilities(fresh, stored) {
11
+ return fresh ?? stored;
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
+ }
41
+
42
+ // src/sign-in.ts
43
+ var SignInError = class extends Error {
44
+ code;
45
+ status;
46
+ constructor(code, message, status) {
47
+ super(message);
48
+ this.name = "SignInError";
49
+ this.code = code;
50
+ this.status = status;
51
+ }
52
+ };
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
+
89
+ // src/store-settings.ts
90
+ var StoreSettingsError = class extends Error {
91
+ code;
92
+ choices;
93
+ constructor(code, message, choices) {
94
+ super(message);
95
+ this.name = "StoreSettingsError";
96
+ this.code = code;
97
+ this.choices = choices;
98
+ }
99
+ };
100
+
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
+ };
116
+
117
+ // src/money.ts
118
+ var digitsCache = /* @__PURE__ */ new Map();
119
+ function minorUnitDigits(currency) {
120
+ const code = currency.toUpperCase();
121
+ let digits = digitsCache.get(code);
122
+ if (digits === void 0) {
123
+ try {
124
+ digits = new Intl.NumberFormat("en", { style: "currency", currency: code }).resolvedOptions().maximumFractionDigits ?? 2;
125
+ } catch {
126
+ digits = 2;
127
+ }
128
+ digitsCache.set(code, digits);
129
+ }
130
+ return digits;
131
+ }
132
+ var symbolCache = /* @__PURE__ */ new Map();
133
+ function currencySymbol(currency, locale) {
134
+ const code = currency.toUpperCase();
135
+ const key = `${code}:${locale ?? ""}`;
136
+ let symbol = symbolCache.get(key);
137
+ if (symbol === void 0) {
138
+ try {
139
+ const part = new Intl.NumberFormat(locale, { style: "currency", currency: code }).formatToParts(0).find((p) => p.type === "currency");
140
+ symbol = part?.value ?? code;
141
+ } catch {
142
+ symbol = code;
143
+ }
144
+ symbolCache.set(key, symbol);
145
+ }
146
+ return symbol;
147
+ }
148
+ function moneyFromMajor(value, currency) {
149
+ if (value === null || value === void 0 || value === "") return void 0;
150
+ const major = typeof value === "number" ? value : Number(value);
151
+ if (!Number.isFinite(major)) return void 0;
152
+ const code = currency.toUpperCase();
153
+ return { amount: Math.round(major * 10 ** minorUnitDigits(code)), currency: code };
154
+ }
155
+ function moneyFromDecimalString(text, currency) {
156
+ const trimmed = text.trim();
157
+ if (!/^\d+(\.\d+)?$/.test(trimmed)) return void 0;
158
+ const code = currency.toUpperCase();
159
+ const digits = minorUnitDigits(code);
160
+ const [whole, fraction = ""] = trimmed.split(".");
161
+ if (fraction.length > digits) return void 0;
162
+ const amount = Number(whole) * 10 ** digits + Number(fraction.padEnd(digits, "0"));
163
+ return Number.isSafeInteger(amount) ? { amount, currency: code } : void 0;
164
+ }
165
+ function moneyToMajor(money) {
166
+ return money.amount / 10 ** minorUnitDigits(money.currency);
167
+ }
168
+ var formatters = /* @__PURE__ */ new Map();
169
+ function formatMoney(money, locale) {
170
+ if (money.currency === "XXX") return void 0;
171
+ const key = `${money.currency}:${locale ?? ""}`;
172
+ let formatter = formatters.get(key);
173
+ if (!formatter) {
174
+ try {
175
+ formatter = new Intl.NumberFormat(locale, { style: "currency", currency: money.currency });
176
+ } catch {
177
+ return void 0;
178
+ }
179
+ formatters.set(key, formatter);
180
+ }
181
+ return formatter.format(moneyToMajor(money));
182
+ }
183
+ function resolvePrice(prices, currency) {
184
+ const code = (currency ?? prices[0]?.currency)?.toUpperCase();
185
+ const inCurrency = prices.filter((p) => p.currency === code);
186
+ const base = inCurrency.find((p) => p.kind === "base");
187
+ const sale = inCurrency.find((p) => p.kind === "sale");
188
+ const strip = (p) => ({
189
+ amount: p.amount,
190
+ currency: p.currency,
191
+ ...p.taxInclusive !== void 0 ? { taxInclusive: p.taxInclusive } : {}
192
+ });
193
+ if (sale && (!base || sale.amount < base.amount)) {
194
+ return { current: strip(sale), was: base ? strip(base) : void 0 };
195
+ }
196
+ return base ? { current: strip(base) } : void 0;
197
+ }
198
+ function resolvePriceRange(variants, currency) {
199
+ let range;
200
+ for (const variant of variants) {
201
+ const resolved = resolvePrice(variant.prices, currency);
202
+ if (!resolved) continue;
203
+ const money = resolved.current;
204
+ if (!range) {
205
+ range = { min: money, max: money };
206
+ } else if (money.currency === range.min.currency) {
207
+ if (money.amount < range.min.amount) range.min = money;
208
+ if (money.amount > range.max.amount) range.max = money;
209
+ }
210
+ }
211
+ return range;
212
+ }
213
+
214
+ // src/variants.ts
215
+ function findVariantByCode(variants, code) {
216
+ const normalized = code.trim().toLowerCase();
217
+ if (!normalized) return void 0;
218
+ return variants.find((variant) => variant.barcode?.trim().toLowerCase() === normalized) ?? variants.find((variant) => variant.sku?.trim().toLowerCase() === normalized);
219
+ }
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
+
281
+ // src/utils/compare-ids.ts
282
+ var INTEGER_STRING = /^\d+$/;
283
+ function compareIds(a, b) {
284
+ const sa = String(a);
285
+ const sb = String(b);
286
+ const aNum = INTEGER_STRING.test(sa);
287
+ const bNum = INTEGER_STRING.test(sb);
288
+ if (aNum && bNum) {
289
+ const diff = BigInt(sa) - BigInt(sb);
290
+ if (diff !== 0n) return diff < 0n ? -1 : 1;
291
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
292
+ }
293
+ if (aNum !== bNum) return aNum ? -1 : 1;
294
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
295
+ }
296
+
297
+ // src/stock-overlay.ts
298
+ var STOCK_LEVELS_LAST_PASS = "last-pass";
299
+ function withStockOverlay(doc, adapter, overlay) {
300
+ if (!adapter || !overlay) return doc;
301
+ const fields = adapter.overlay(doc, overlay);
302
+ return fields ? { ...doc, ...fields } : doc;
303
+ }
304
+ function getProductStock(doc, traits, adapter, overlay) {
305
+ return traits.getStock(withStockOverlay(doc, adapter, overlay));
306
+ }
307
+
308
+ // src/replication/combine.ts
309
+ function combinePullAdapters(adapters, options = {}) {
310
+ const keys = Object.keys(adapters);
311
+ for (const key of keys) {
312
+ if (adapters[key].push || adapters[key].pull.stream$) {
313
+ throw new Error(`combinePullAdapters: sub-adapter "${key}" has push or pull.stream$; only pull handlers can be combined.`);
314
+ }
315
+ }
316
+ return {
317
+ pull: {
318
+ batchSize: options.batchSize,
319
+ async handler(lastCheckpoint, batchSize, context) {
320
+ let previous = lastCheckpoint;
321
+ if (options.legacyKey && previous && typeof previous === "object" && Object.keys(previous).length && !keys.some((key) => key in previous)) {
322
+ previous = { [options.legacyKey]: previous };
323
+ }
324
+ if (!previous || !Object.keys(previous).length) {
325
+ const seeded = {};
326
+ for (const key of keys) {
327
+ const { pull } = adapters[key];
328
+ if (pull.seedCheckpoint) seeded[key] = await pull.seedCheckpoint(context);
329
+ }
330
+ previous = seeded;
331
+ }
332
+ const byId = /* @__PURE__ */ new Map();
333
+ const checkpoint = {};
334
+ for (const key of keys) {
335
+ const result = await adapters[key].pull.handler(previous?.[key], batchSize, context);
336
+ for (const doc of result.documents) byId.set(doc.id, doc);
337
+ checkpoint[key] = { ...previous?.[key], ...result.checkpoint };
338
+ }
339
+ return { documents: [...byId.values()], checkpoint };
340
+ }
341
+ }
342
+ };
343
+ }
344
+
345
+ // src/replication/reconcile-feed.ts
346
+ var MAX_CHUNK = 1e3;
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);
351
+ let queue = /* @__PURE__ */ new Map();
352
+ const merge = (prior, e) => ({ ...e, refreshOnly: Boolean(e.refreshOnly) && (prior?.refreshOnly ?? true) });
353
+ const enqueue = (entries) => {
354
+ for (const e of entries) queue.set(keyOf(e), merge(queue.get(keyOf(e)), e));
355
+ };
356
+ const adapter = {
357
+ pull: {
358
+ async handler(lastCheckpoint, _batchSize, context) {
359
+ if (queue.size === 0) return { documents: [], checkpoint: lastCheckpoint ?? { n: 0 } };
360
+ const entries = [...queue.values()];
361
+ queue = /* @__PURE__ */ new Map();
362
+ try {
363
+ const documents = [];
364
+ for (let i = 0; i < entries.length; i += MAX_CHUNK) {
365
+ const chunk = entries.slice(i, i + MAX_CHUNK);
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]));
369
+ for (const entry of chunk) {
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 });
373
+ }
374
+ }
375
+ return { documents, checkpoint: { n: (lastCheckpoint?.n ?? 0) + 1 } };
376
+ } catch (error) {
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));
379
+ queue = restored;
380
+ throw error;
381
+ }
382
+ }
383
+ }
384
+ };
385
+ return { adapter, enqueue };
386
+ }
387
+ function keyOf(entry) {
388
+ return entry.key ?? entry.id;
389
+ }
390
+
1
391
  // src/context/connector-context.tsx
2
- import { createContext, useContext } from "react";
392
+ import { createContext, useContext, useMemo } from "react";
3
393
  import { jsx } from "react/jsx-runtime";
4
394
  var ConnectorContext = createContext(null);
5
- function ConnectorProvider({ connector, children }) {
6
- return /* @__PURE__ */ jsx(ConnectorContext.Provider, { value: connector, children });
395
+ var EMPTY_TRAIT_CONTEXT = {};
396
+ var TraitContextContext = createContext(EMPTY_TRAIT_CONTEXT);
397
+ var EMPTY_STOCK_OVERLAY = {};
398
+ var StockOverlayContext = createContext(EMPTY_STOCK_OVERLAY);
399
+ function ConnectorProvider({ connector, traitContext, stockOverlay, stockOverlayAsOf, children }) {
400
+ const overlay = useMemo(
401
+ () => stockOverlay || stockOverlayAsOf ? { overlay: stockOverlay, asOf: stockOverlayAsOf } : EMPTY_STOCK_OVERLAY,
402
+ [stockOverlay, stockOverlayAsOf]
403
+ );
404
+ return /* @__PURE__ */ jsx(ConnectorContext.Provider, { value: connector, children: /* @__PURE__ */ jsx(TraitContextContext.Provider, { value: traitContext ?? EMPTY_TRAIT_CONTEXT, children: /* @__PURE__ */ jsx(StockOverlayContext.Provider, { value: overlay, children }) }) });
7
405
  }
8
406
  function useConnector() {
9
407
  const connector = useContext(ConnectorContext);
@@ -18,13 +416,79 @@ function useProductTraits() {
18
416
  const connector = useConnector();
19
417
  return connector.traits.product;
20
418
  }
419
+ function useTraitContext() {
420
+ return useContext(TraitContextContext);
421
+ }
422
+ function useProductStock(doc) {
423
+ const connector = useConnector();
424
+ const { overlay, asOf } = useContext(StockOverlayContext);
425
+ const adapter = connector.reconcile?.stock;
426
+ if (!overlay) return connector.traits.product.getStock(doc);
427
+ const stock = getProductStock(doc, connector.traits.product, adapter, overlay);
428
+ return adapter && asOf ? { ...stock, asOf } : stock;
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
+ }
21
450
  function useCustomerTraits() {
22
451
  const connector = useConnector();
23
452
  return connector.traits.customer;
24
453
  }
25
454
  export {
455
+ COMMANDS_PATH,
26
456
  ConnectorProvider,
457
+ ConnectorUnauthorizedError,
458
+ CustomerServiceError,
459
+ MAX_COMMANDS_PER_BATCH,
460
+ PROTOCOL_HEADER,
461
+ PROTOCOL_VERSION,
462
+ STOCK_LEVELS_LAST_PASS,
463
+ SignInError,
464
+ StoreSettingsError,
465
+ combinePullAdapters,
466
+ compareIds,
467
+ createReconcileFeed,
468
+ currencySymbol,
469
+ customerTraits,
470
+ errorKind,
471
+ findVariantByCode,
472
+ formatMoney,
473
+ getProductStock,
474
+ isCommandBatchResponse,
475
+ isRxdbRemoteVersionMismatch,
476
+ knownWarnings,
477
+ minorUnitDigits,
478
+ moneyFromDecimalString,
479
+ moneyFromMajor,
480
+ moneyToMajor,
481
+ parseInfoCapabilities,
482
+ parseTaxRounding,
483
+ resolveCapabilities,
484
+ resolvePrice,
485
+ resolvePriceRange,
27
486
  useConnector,
28
487
  useCustomerTraits,
29
- useProductTraits
488
+ useProductStock,
489
+ useProductTraits,
490
+ useStockOverlaid,
491
+ useStockOverlayAsOf,
492
+ useTraitContext,
493
+ withStockOverlay
30
494
  };
@@ -0,0 +1,37 @@
1
+ import { RxCollection, MangoQuerySelector, MangoQuery } from 'rxdb';
2
+ import { Observable } from 'rxjs';
3
+
4
+ /**
5
+ * Reads straight from the collection's storage, past RxDB's cached query result.
6
+ *
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.
10
+ *
11
+ * The prepared query is RxDB's own (`find(query).getPreparedQuery()`), so it already carries the
12
+ * `_deleted: false` filter, the query's sort and its limit. The read goes through the same wrapped
13
+ * storage instance an `RxQuery` uses, but skips `RxQuery` and `RxDocument`, so it is untested with
14
+ * key compression and field encryption; no TallyUI collection uses either.
15
+ *
16
+ * Returns plain, deep-cloned document data without RxDB's metadata. Use `findOne(id)` for an
17
+ * `RxDocument` to write through; its `incrementalModify` modifier sees the stored state.
18
+ */
19
+ declare function readFresh<T>(collection: RxCollection<T>, query: MangoQuery<T>): Promise<T[]>;
20
+ /**
21
+ * Counts straight from the collection's storage, past RxDB's cached count (see `readFresh`).
22
+ * Unlike `count().exec()`, it doesn't refuse a storage that reports a slow count.
23
+ */
24
+ declare function countFresh<T>(collection: RxCollection<T>, selector: MangoQuerySelector<T>): Promise<number>;
25
+
26
+ /**
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.
29
+ * `collection.eventBulks$` fires on every write and never touches that cache, so re-reading with
30
+ * `readFresh` on subscribe and again on every event bulk can't miss one; `switchMap` drops a read
31
+ * still in flight when a newer one starts. It is one event per storage change bulk, not per
32
+ * document (`collection.$`), so a `bulkInsert` of 100 documents costs one re-read, not 100. Still
33
+ * one storage read per write, so it's for a list a cashier would act on going stale, not every list.
34
+ */
35
+ declare function watchFresh<T>(collection: RxCollection<T>, query: MangoQuery<T>): Observable<T[]>;
36
+
37
+ export { countFresh, readFresh, watchFresh };
@@ -0,0 +1,26 @@
1
+ // src/rxdb/read-fresh.ts
2
+ import { clone } from "rxdb";
3
+ async function readFresh(collection, query) {
4
+ const { documents } = await collection.storageInstance.query(collection.find(query).getPreparedQuery());
5
+ return documents.map((document) => {
6
+ const { _meta, _rev, _attachments, _deleted, ...data } = clone(document);
7
+ return data;
8
+ });
9
+ }
10
+ async function countFresh(collection, selector) {
11
+ return (await collection.storageInstance.count(collection.count({ selector }).getPreparedQuery())).count;
12
+ }
13
+
14
+ // src/rxdb/watch-fresh.ts
15
+ import { startWith, switchMap } from "rxjs";
16
+ function watchFresh(collection, query) {
17
+ return collection.eventBulks$.pipe(
18
+ startWith(null),
19
+ switchMap(() => readFresh(collection, query))
20
+ );
21
+ }
22
+ export {
23
+ countFresh,
24
+ readFresh,
25
+ watchFresh
26
+ };