POS Business Logic
Tax calculations, currency formatting, order management, receipts, and logging for point-of-sale apps
The @tallyui/pos package handles the business logic layer of a point-of-sale application. It sits between the UI components and the data layer, providing tax math, currency formatting, order building, receipt generation, and structured logging.
Everything here is framework-agnostic at its core -- plain functions and observables -- with thin React providers where components need shared config.
Installation
pnpm add @tallyui/posThe package has peer dependencies on react, rxjs, and rxdb.
Tax System
Tax calculations need to handle two common retail scenarios: prices that already include tax (common in Europe, Australia) and prices where tax gets added at checkout (common in the US).
Tax Provider
Wrap your app with TaxProvider to make tax configuration available to the order system and any component that needs it:
import { TaxProvider } from '@tallyui/pos';
import type { ComponentType } from 'react';
declare const PosInterface: ComponentType;
function App() {
return (
<TaxProvider
ratesPpm={{ default: 100000, reduced: 50000 }}
pricesIncludeTax={true}
>
<PosInterface />
</TaxProvider>
);
}The ratesPpm object maps tax class names to integer parts per million (10% = 100000). The default key supplies the fallback when no tax class is specified.
useTax Hook
Inside the provider, useTax() gives you the tax context:
import { useTax } from '@tallyui/pos';
function PriceDisplay({ price, taxClass }: { price: number; taxClass?: string }) {
const { getTaxRatePpm, pricesIncludeTax } = useTax();
const ratePpm = getTaxRatePpm(taxClass);
// ratePpm is 100000 for default, 50000 for 'reduced', etc.
}Direct Calculation
For standalone tax math outside of React, use the calculation functions directly:
import { createTaxContext, ratePpmFromPercent, computeOrderTax, taxMicros, roundMicrosToMinor } from '@tallyui/pos';
const taxContext = createTaxContext({
ratesPpm: { default: ratePpmFromPercent(10) },
pricesIncludeTax: false,
});
const ratePpm = taxContext.getTaxRatePpm();
// $10 exclusive of tax, expressed in integer cents
const result = computeOrderTax(
[{ unitPriceMinor: 1000, quantity: 1, ratePpm }], taxContext.pricesIncludeTax,
);
// subtotalMinor: 1000, taxMinor: 100, totalMinor: 1100
// Extract the tax from $11 inclusive of tax, then round to cents
roundMicrosToMinor(taxMicros(1100, ratePpm, true)); // 100Before you split a sale's tax by rate with taxLinesByRate, pass its lines and its fees and shipping through taxedLinesFor. It marks each with the tax mode its tax was rounded in: a fee or shipping charge keeps its own amountIncludesTax, or the store's mode if it has none, unless the store rounds as WooCommerce does.
Currency Formatting
Currency formatting uses Intl.NumberFormat under the hood, with a caching layer so formatters are only created once per currency/locale pair.
Standalone Function
Use formatMoney from @tallyui/core with integer minor units and a currency code:
import { formatMoney } from '@tallyui/core';
formatMoney({ amount: 2999, currency: 'USD' }, 'en-US'); // "$29.99"
formatMoney({ amount: 2999, currency: 'EUR' }, 'de-DE'); // "29,99 €"
formatMoney({ amount: 1500, currency: 'JPY' }, 'ja-JP'); // "¥1,500"Currency Provider
For components that format prices throughout the app, the provider shares locale and formatting settings. The formatter takes a Money object with integer minor units and its currency code:
import { CurrencyProvider, useCurrencyFormatter } from '@tallyui/pos';
import type { Money } from '@tallyui/core';
import type { ComponentType } from 'react';
declare const PosInterface: ComponentType;
function App() {
return (
<CurrencyProvider currencyCode="USD" locale="en-US">
<PosInterface />
</CurrencyProvider>
);
}
function TotalDisplay({ money }: { money: Money }) {
const format = useCurrencyFormatter();
return <span>{format(money)}</span>; // "$29.99" for { amount: 2999, currency: 'USD' }
}Order Management
The order system has two layers: OrderBuilder handles a single order's state, and OrderManager coordinates multiple orders (parking, resuming, creating new ones).
Building an Order
createOrderBuilder returns a reactive order object. Every mutation emits the recalculated order through order$:
import { createOrderBuilder } from '@tallyui/pos';
import type { ProductTraits } from '@tallyui/core';
declare const productDoc: unknown, productTraits: ProductTraits;
const builder = createOrderBuilder({
currency: 'USD',
taxContext: { getTaxRatePpm: () => 100000, pricesIncludeTax: false },
});
// Subscribe to order changes
builder.order$.subscribe((order) => {
console.log('Total (cents):', order.totalMinor);
console.log('Tax (cents):', order.taxMinor);
console.log('Balance due (cents):', order.balanceDueMinor);
});
// Add products using connector traits
const lineId = builder.addProduct(productDoc, productTraits, { quantity: 2 });
// Adjust quantities
builder.updateQuantity(lineId, 3);
// Apply a 10% line discount
builder.applyLineDiscount(lineId, {
type: 'percentage',
value: 10,
label: 'Staff discount',
});
// Apply a $5 order-level discount
builder.applyOrderDiscount({
type: 'fixed',
value: 500,
label: 'Loyalty reward',
});
// Record a $25.50 payment in cents
builder.addPayment({ method: 'card', amountMinor: 2550 });
// Attach a customer
builder.setCustomer({ id: '42', name: 'Jane Doe', email: 'jane@example.com' });The builder automatically recalculates subtotals, discounts, tax, and balance due on every change. It handles both tax-inclusive and tax-exclusive pricing based on the taxContext you provide.
When the same product is added twice, the builder increments the existing line item's quantity rather than adding a duplicate.
Managing Multiple Orders
createOrderManager wraps the builder with persistence. It requires an RxDB collection to store parked order drafts:
import { createOrderManager } from '@tallyui/pos';
import type { TallyDatabase } from '@tallyui/database';
declare const db: TallyDatabase;
const manager = createOrderManager({
currency: 'USD',
taxContext: { getTaxRatePpm: () => 100000, pricesIncludeTax: false },
draftsCollection: db.order_drafts,
});
// The active order builder
manager.activeOrder$.subscribe((builder) => {
// Use builder.order$ for the current order state
});
// Park the current order (saves to RxDB, starts a fresh one)
const parkedId = await manager.parkCurrentOrder();
// See all parked orders
manager.parkedOrders$.subscribe((parked) => {
// [{ id, customerName, itemCount, totalMinor, parkedAt, source }]
});
// Resume a parked order (restores all line items, discounts, payments)
const builder = await manager.resumeOrder(parkedId);
// Delete a parked order without resuming
await manager.deleteParkedOrder(parkedId);
// Start a fresh order manually
manager.newOrder();Selling with useSale
useSale is the React hook the platform apps sell with: one sale's cart, tender and completion on top of createOrderBuilder. Call it under a TaxProvider; Cart, Tender and ParkedSales take its result as sale. The first argument is settings: Pick<StoreSettings, 'currency' | 'calcDiscountsSequentially'>; the second is the options below (? marks optional options).
| Option | Type | Description |
|---|---|---|
registerId | string | Register identifier passed to order finalization. |
cashierRef | string | Cashier reference passed to order finalization. |
capabilities? | ServerCapabilities | Server capabilities used by finalization and exposed to sale components. |
discountCodes? | SaleDiscountCodes<any> | Platform discount codes; without them, applyCoupon refuses with COUPONS_UNSUPPORTED. |
tenderGate? | (attempt: { method: 'cash' | 'external' }) => Promise<string | null> | Awaited after checkout checks: return a refusal or null to start tender; rejection gives TENDER_GATE_FAILED. If a customer or address change re-taxes the sale while the gate runs, tender does not start and the sale shows TENDER_SALE_CHANGED. |
defaultCustomer? | CustomerSummary | null | Customer for each new sale, never a resumed one; changes apply to an idle cart or the next new sale, and a refused customer is skipped. |
drafts? | RxCollection | Collection created with orderDraftSchema where park() keeps carts. |
currentPrice? | (variantId: string) => number | undefined | Current variant price in integer minor units, or unknown; resume() re-prices unless asked to keep parked prices. |
session? | { id: string; sessions: RegisterSessionCollection } | Session pinned at tender start for completion; a refused stamp uses lateSessionId and records a late-sale fact without stopping the sale. |
onSaleCompleted? | (posOrder: PosOrder) => Promise<void> | void | Receives the finalized order; must accept the same order again when completion is retried. |
isStored? | (posOrder: PosOrder) => Promise<boolean> | Confirms storage after a failed or hung save, including a refused mid-save newSale(); only true enables Continue, otherwise Retry is offered. |
taxContextFor? | (customer: CustomerSummary | null) => SaleTaxContext | Memoized customer tax context, e.g. saleTaxContexts(settings); customer changes re-tax the cart, while tender and receipt keep their rates. Defaults to useTax(). |
| Group | Returned member | Description |
|---|---|---|
| State | order | Current order snapshot. |
| State | stage | SaleStage: cart, tender with a cash or external method, or receipt with order and posOrder. |
| State | error | Current error or refusal message, or null. |
| State | idle | In the cart stage with no product lines, fees or shipping. |
| State | taxLocation | Customer's matched tax address; undefined without taxContextFor. |
| State | capabilities | Passed-through capabilities; components offer fees, shipping and custom lines at orderCreate >= 5, and tax controls as lineTax allows. |
| State | saving | Completion is pending; the sale is locked and the UI offers Retry. |
| State | canContinue | The pending order is confirmed stored, so the UI can offer Continue. |
| State | couponsRepricing | Coupons are being priced again; tender refuses with COUPONS_REPRICING. |
| Cart | add(entry, traits) | Adds a line or increments its quantity; returns { lineId } or a refusal also shown in error. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion; on the receipt it starts the next sale first. |
| Cart | setQuantity(lineId, quantity) | Updates a line's quantity. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | remove(lineId) | Removes a line. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | splitLine(lineId) | Splits quantity N into N lines of one; returns a refusal or null. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | setUnitPrice(lineId, amountMinor) | Sets price in minor units of the line's tax mode and recalculates discounts and tax; returns a refusal or null. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | applyDiscount(lineId, discount) | Applies a line discount, or an order discount for null; returns a refusal (including DISCOUNTS_UNSUPPORTED) or null. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | removeDiscount(id) | Removes a discount. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | applyCoupon(code) | Looks up, checks and applies a platform discount code; resolves to a refusal or null. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | removeCoupon(code) | Removes an applied coupon; returns a refusal or null. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | repriceCoupons() | Retries coupon pricing; resolves to a refusal or error, or null. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt; stale coupons are not priced again automatically while a payment is live either. |
| Cart | setNote(note) | Sets the note kept with parked carts and sent as the order note; a new sale clears it. |
| Cart | setCustomer(customer) | Picks a customer or null for guest; refuses invalid customer data or a tax change once rates are fixed. |
| Cart | addFee(input) | Adds a fee from ChargeInput; returns { id } or a refusal. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | updateFee(id, patch) | Updates a fee; returns a refusal or null. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | removeFee(id) | Removes a fee; returns a refusal or null. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | addShipping(input) | Adds shipping from ChargeInput with optional methodId; returns { id } or a refusal. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | updateShipping(id, patch) | Updates shipping; returns a refusal or null. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | removeShipping(id) | Removes shipping; returns a refusal or null. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | addCustomLine(input) | Adds a distinct custom line with name, priceMinor and optional quantity, taxClass, taxStatus, sku; returns { id } or a refusal. Refuses with SALE_HAS_PAYMENT while a payment is taken or in motion and with SALE_FINISHED on the receipt. |
| Cart | park() | Stores the cart in drafts and starts a new sale; resolves to a refusal or null. |
| Cart | resume(draftId, options?) | Restores a draft into an empty cart, rechecks coupons and optionally keeps parked prices with keepParkedPrices; resolves to a refusal or null. |
| Cart | switchSale(draftId) | Parks the current cart and opens a draft, or a new sale for null; refuses while saving, partly paid, payment in motion or in tender. |
| Cart | closeSale() | Discards the current sale and starts an empty one; refuses while saving, with money on an unfinished sale or in tender (SALE_PARTLY_PAID, SALE_IN_TENDER). |
| Cart | holdsStoreOrder(orderId) | Resolves whether the live sale or a readable parked draft holds this store order. |
| Cart | openStoreOrder(order) | Loads a reopened store order into an empty sale; returns a refusal or null. |
| Tender | startTender(method, options?) | Starts cash or external tender and pins options.session or the hook's session; repeated calls keep the first pin. |
| Tender | setTender(tender) | Replaces unlocked payments with one tender, or clears them for null. |
| Tender | addTender(tender) | Adds a cash or external payment, recording takenAt at once unless it enters pending or authorized; external amounts are capped at the balance less payments in motion, and only cash gives change. A cash payment for picked units may carry tenderedMinor (an integer at least its amountMinor; amountMinor must be at most the balance less payments in motion), and it stores changeMinor. |
| Tender | setTenderStatus(paymentId, status) | Sets authorized, captured or failed; records takenAt on a move to captured; returns whether the status changed. |
| Tender | voidTender(paymentId) | Voids an eligible payment, keeping its record but counting nothing; returns whether it was voided. Refuses with SALE_FINISHED on the receipt. |
| Tender | removeTender(paymentId) | Removes an unlocked payment and its dropped-reference warning. Refuses with SALE_FINISHED on the receipt. |
| Tender | cancelTender() | Clears unlocked payments and returns to the cart. |
| Completion | complete() | Finalizes, saves and shows the receipt, recording takenAt on a new payment that has none (the pre-filled tender); refuses payments in motion with PAYMENT_IN_MOTION. Retry reuses the same pending order. |
| Completion | newSale() | Starts an empty sale; a pending save must be confirmed stored before it can be abandoned, and its stored record is kept. |
| Completion | continueSale() | Starts a new sale only for a confirmed stored pending completion, without redelivering it or showing its receipt. |
For an Undo on the "removed from cart" toast, take sale.removal('line', id) (or 'fee', 'shipping') before the remove (remove, removeFee, removeShipping), then pass it to sale.restore(removal). The item goes back at its old index, or at the end when the list is now shorter, with its own price, quantity, discounts and meta. When the customer's tax rates changed in between, the cart is re-taxed as a customer change does, so the restored item ends up as the items that stayed, never on the old customer's rates. restore() returns the cart's refusals (SALE_HAS_PAYMENT, SALE_FINISHED, SALE_SAVING), RESTORE_STALE outside the cart, once the sale was reset, parked, resumed or completed, or when the item is already back, or null.
complete() finalizes the order, stamps the session if given, and hands it to onSaleCompleted, where the app stores it for the outbox (for example, with useOrderOutbox's record), then shows the receipt. While completion is pending, saving is true and every sale change refuses with SALE_SAVING; after a save failure, Retry calls complete() with the same pending order. isStored decides whether canContinue offers Continue: only confirmed storage enables it, and without isStored a failed save offers Retry only.
import { useSale, type CatalogueEntry, type PosOrder, type RegisterSessionCollection } from '@tallyui/pos';
import type { ProductTraits, ServerCapabilities, StoreSettings } from '@tallyui/core';
import { VStack, Button, Text } from '@tallyui/components';
declare const settings: Pick<StoreSettings, 'currency' | 'calcDiscountsSequentially'>;
declare const registerId: string, cashierRef: string;
declare const capabilities: ServerCapabilities;
declare const session: { id: string; sessions: RegisterSessionCollection };
declare const onSaleCompleted: (posOrder: PosOrder) => Promise<void>;
declare const isStored: (posOrder: PosOrder) => Promise<boolean>;
declare const entry: CatalogueEntry<unknown>, traits: ProductTraits<unknown>;
// Render under a TaxProvider.
function Sale() {
const sale = useSale(settings, { registerId, cashierRef, capabilities, session, onSaleCompleted, isStored });
return (
<VStack>
<Button onPress={() => sale.add(entry, traits)}><Text>Add item</Text></Button>
{sale.error ? <Text className="text-destructive">{sale.error}</Text> : null}
</VStack>
);
}Store orders in a range
useStoreOrdersInRange(connector, context, query) reads every store order matching query from connector.listOrders, one page of 100 after another, and returns orders, progress, unreadable, error and complete. While pages are still being fetched, progress is WCPOS v2's { downloaded, total }, with total the store's count or null when it gives none; it is null when idle, finished or failed. Nothing is stored or cached, so opening the screen again re-reads: a row pushed past a page boundary mid-read is missed until then, and a repeated row is dropped.
import { useMemo } from 'react';
import { useStoreOrdersInRange } from '@tallyui/pos';
import type { SyncContext, TallyConnector } from '@tallyui/core';
import { Text } from '@tallyui/components';
declare const connector: TallyConnector, context: SyncContext;
declare const todayStart: string, tomorrowStart: string; // the store's today, as UTC ISO instants
function OrdersToday() {
const query = useMemo(() => ({ dateRange: { after: todayStart, before: tomorrowStart } }), []);
const { progress } = useStoreOrdersInRange(connector, context, query);
if (!progress) return null;
const { downloaded, total } = progress;
return <Text>Downloading orders — {total === null ? downloaded : `${downloaded} of ${total}`}</Text>;
}Keep connector and context the same objects across renders, from state, a ref or useMemo: a new object restarts the read. A page that says there is more but adds no new order and no unreadable one ends the read with an error, so a store that keeps repeating a page stops, unless that page reports unreadable orders.
Repositories
createRepository wraps an RxDB collection with a clean read/write API that returns plain JSON objects instead of RxDB documents:
import { createRepository } from '@tallyui/pos';
import type { TallyDatabase } from '@tallyui/database';
declare const db: TallyDatabase;
const productRepo = createRepository(db.products);
// Reactive queries (return Observables)
productRepo.findById$('prod-123').subscribe((product) => { /* ... */ });
productRepo.findAll$({ selector: { status: 'active' } }).subscribe((products) => { /* ... */ });
productRepo.search$('espresso', ['name', 'sku']).subscribe((results) => { /* ... */ });
productRepo.count$().subscribe((count) => { /* ... */ });
// Mutations (return Promises)
await productRepo.create({ id: 'prod-new', name: 'Flat White', price: '4.50' });
await productRepo.update('prod-new', { price: '5.00' });
await productRepo.remove('prod-new');
// Bulk operations
await productRepo.bulkCreate([
{ id: 'prod-1', name: 'Espresso', price: '3.00' },
{ id: 'prod-2', name: 'Latte', price: '4.50' },
{ id: 'prod-3', name: 'Mocha', price: '5.00' },
]);
await productRepo.bulkRemove(['id-1', 'id-2']);The reactive queries (findAll$, search$, etc.) stay live -- they re-emit whenever the underlying collection changes, which ties directly into RxDB's replication system.
Receipt Builder
buildReceiptData takes a completed order and a store config, and returns a structured receipt object ready for rendering or printing:
import { buildReceiptData, type Order } from '@tallyui/pos';
declare const order: Order;
const receipt = buildReceiptData(order, {
storeName: 'Blue Bottle Coffee',
storeAddress: '123 Main St, San Francisco, CA',
cashier: 'Alex',
register: 'POS-1',
taxLabels: { 100000: 'GST 10%', 50000: 'Reduced GST 5%' },
});
// receipt.header — store name, address, order number, date, cashier, register
// receipt.lineItems — name, sku, quantity, unitPriceMinor, lineTotalMinor
// receipt.discounts — label, amountMinor
// receipt.totals — taxInclusive, subtotalMinor (before discounts), discountMinor, taxLines[], taxMinor, totalMinor: the display figures (ADR-063)
// receipt.payments — method, amountMinor, reference
// receipt.changeDueMinor — change owed to customer in minor units
// receipt.footer — note, barcode
// receipt.currency — currency codeThe taxLabels config maps tax rates in ppm (100000 = 10%) to human-readable labels. If a rate doesn't have a label, it falls back to "Tax X%" formatting.
Receipt printers
createWebUsbSink and createWebBluetoothSink are ESC/POS sinks for createEscPosTransport, for a printer attached to the browser.
The device comes from the app. The app gets it from navigator.usb.requestDevice or navigator.bluetooth.requestDevice, called from a user gesture such as a click handler; navigator.usb.getDevices can return a USB device already granted. For Bluetooth, the app lists BLUETOOTH_PRINT_SERVICES in optionalServices. The sinks never call navigator.usb or navigator.bluetooth themselves.
The app owns the device. The USB sink opens, configures and claims the device when it needs to, and never closes it. The Bluetooth sink connects GATT when the link is down, and never disconnects. The app keeps the device between jobs and releases it.
Which USB interface. The USB sink writes to the first printer-class interface that has a bulk OUT endpoint. Otherwise it writes to the first interface with a bulk OUT endpoint.
Bluetooth pacing. By default the Bluetooth sink writes 20-byte chunks (the chunkSize option changes the size), 20 ms apart, the last with response, then waits 300 ms before the write resolves. An empty write sends nothing and skips the wait. A characteristic without writeWithoutResponse gets every chunk with response.
No timeout on a write. Neither sink sets a timeout, so a job waits as long as the browser's USB transfer or GATT write does.
Errors. A device the sink cannot print to is a PrintError.
import {
createEscPosTransport,
createWebBluetoothSink,
createWebUsbSink,
type PrinterProfile,
type WebBluetoothDevice,
type WebUsbDevice,
} from '@tallyui/pos';
// From navigator.usb.requestDevice in a click handler, or navigator.usb.getDevices.
declare const usbDevice: WebUsbDevice;
// From navigator.bluetooth.requestDevice in a click handler, with BLUETOOTH_PRINT_SERVICES in optionalServices.
declare const bluetoothDevice: WebBluetoothDevice;
const usbPrinter: PrinterProfile = { id: 'usb-1', name: 'Front counter', connectionType: 'usb', columns: 48 };
const bluetoothPrinter: PrinterProfile = { id: 'ble-1', name: 'Mobile', connectionType: 'bluetooth', columns: 32 };
const usbTransport = createEscPosTransport({ sink: createWebUsbSink({ device: usbDevice }), profile: usbPrinter });
const bluetoothTransport = createEscPosTransport({
sink: createWebBluetoothSink({ device: bluetoothDevice }),
profile: bluetoothPrinter,
});Logging
createLogger provides structured logging with scopes and pluggable sinks. Each sink controls which log levels and scopes it listens to.
import { createLogger, consoleSink, callbackSink } from '@tallyui/pos';
const logger = createLogger('pos');
// Add a console sink that logs warnings and errors
logger.addSink(consoleSink({
levels: ['warn', 'error'],
}));
// Add a callback sink for sending logs to a remote service
logger.addSink(callbackSink({
id: 'remote',
levels: ['error'],
callback: (entry) => {
fetch('/api/logs', {
method: 'POST',
body: JSON.stringify(entry),
});
},
}));
// Log messages
logger.info('Order completed', { orderId: '123', total: 42.50 });
logger.error('Payment failed', { method: 'card', error: 'declined' });
// Create scoped child loggers (share parent's sinks)
const replicationLogger = logger.createScope('replication');
replicationLogger.info('Sync started');
// Console output: [replication] Sync startedScoped loggers inherit all sinks from the parent. You can filter sinks by scope if you only want certain loggers to write to certain destinations:
import { consoleSink, type Logger } from '@tallyui/pos';
declare const logger: Logger;
logger.addSink(consoleSink({
levels: ['debug', 'info', 'warn', 'error'],
scopes: ['replication'], // only logs from the 'replication' scope
}));Log entries include a timestamp, level, scope, message, and optional data object -- enough structure for filtering and search without over-engineering it.