@tallyui/pos 3.12.0 → 3.13.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 (79) hide show
  1. package/dist/index.d.ts +1545 -300
  2. package/dist/index.js +4259 -2218
  3. package/package.json +12 -6
  4. package/src/app-settings/app-settings.ts +93 -0
  5. package/src/app-settings/index.ts +8 -0
  6. package/src/app-settings/use-app-settings.ts +23 -0
  7. package/src/cashier/can.ts +12 -0
  8. package/src/cashier/index.ts +2 -0
  9. package/src/cashier/use-cashier.ts +81 -0
  10. package/src/csv/csv.ts +33 -0
  11. package/src/csv/index.ts +2 -0
  12. package/src/customer-display/display-state.ts +30 -0
  13. package/src/customer-display/index.ts +8 -0
  14. package/src/customer-display/protocol.ts +87 -0
  15. package/src/customer-display/snapshot.ts +65 -0
  16. package/src/index.ts +67 -10
  17. package/src/order/order-builder.ts +11 -1
  18. package/src/order/order-drafts.ts +16 -0
  19. package/src/order/types.ts +6 -3
  20. package/src/outbox/index.ts +5 -1
  21. package/src/outbox/outbox-health.ts +40 -0
  22. package/src/outbox/register-outbox.ts +59 -6
  23. package/src/outbox/safe-error.ts +11 -0
  24. package/src/outbox/types.ts +3 -1
  25. package/src/outbox/use-outbox-health.ts +22 -0
  26. package/src/outbox/use-register-outbox.ts +6 -0
  27. package/src/payment-driver/index.ts +8 -0
  28. package/src/payment-driver/registry.ts +39 -0
  29. package/src/payment-driver/simulated-driver.ts +104 -0
  30. package/src/payment-driver/types.ts +73 -0
  31. package/src/pos-order/__fixtures__/order-create-v7.json +97 -0
  32. package/src/pos-order/command.ts +36 -16
  33. package/src/pos-order/finalize.ts +7 -3
  34. package/src/pos-order/index.ts +1 -0
  35. package/src/pos-order/note-delivery.ts +13 -0
  36. package/src/pos-order/reopen.ts +3 -2
  37. package/src/pos-order/schema.ts +5 -4
  38. package/src/pos-order/types.ts +3 -2
  39. package/src/print/index.ts +10 -0
  40. package/src/print/print-queue.ts +67 -0
  41. package/src/print/printer-profiles.ts +71 -0
  42. package/src/print/system-transport.ts +101 -0
  43. package/src/print/types.ts +40 -0
  44. package/src/receipt/reprint.ts +2 -1
  45. package/src/receipt/types.ts +2 -0
  46. package/src/receipt-template/default-templates.ts +78 -0
  47. package/src/receipt-template/index.ts +15 -0
  48. package/src/receipt-template/parse-xml.ts +175 -0
  49. package/src/receipt-template/render-html.ts +152 -0
  50. package/src/receipt-template/render-receipt.ts +19 -0
  51. package/src/receipt-template/render-template.ts +35 -0
  52. package/src/receipt-template/sanitize-html.ts +146 -0
  53. package/src/receipt-template/template-data.ts +97 -0
  54. package/src/receipt-template/types.ts +49 -0
  55. package/src/refund/index.ts +2 -0
  56. package/src/refund/refundable-lines.ts +91 -0
  57. package/src/register/export-csv.ts +24 -35
  58. package/src/register/float-suggestion.ts +22 -0
  59. package/src/register/index.ts +8 -3
  60. package/src/register/register-adoption.ts +71 -2
  61. package/src/register/register-commands.ts +7 -4
  62. package/src/register/register-count.helpers.ts +4 -0
  63. package/src/register/session-store.ts +4 -1
  64. package/src/register/use-register-session.ts +112 -28
  65. package/src/reports/adapters.ts +67 -0
  66. package/src/reports/index.ts +5 -0
  67. package/src/reports/presets.ts +27 -0
  68. package/src/reports/sales-figures.ts +173 -0
  69. package/src/reports/types.ts +63 -0
  70. package/src/sale/index.ts +3 -1
  71. package/src/sale/open-sales.ts +40 -0
  72. package/src/sale/use-sale.ts +72 -8
  73. package/src/scanner/index.ts +6 -0
  74. package/src/scanner/scan-session.ts +84 -0
  75. package/src/scanner/use-barcode-scanner.ts +61 -0
  76. package/src/scanner/wedge-detector.ts +137 -0
  77. package/src/tender/cash-rounding.ts +74 -0
  78. package/src/tender/index.ts +4 -0
  79. package/src/tender/payment-legs.ts +48 -0
@@ -58,6 +58,8 @@ export interface ReceiptData {
58
58
  changeDueMinor: number;
59
59
  footer: {
60
60
  note?: string;
61
+ /** ADR-083 condition 2: set only on a reprint of a till order whose note was not sent to the store. */
62
+ noteNotSent?: true;
61
63
  barcode?: string;
62
64
  };
63
65
  currency: string;
@@ -0,0 +1,78 @@
1
+ export type ReceiptPaper = '58mm' | '80mm';
2
+ /** Characters per line (v2 encode-receipt.ts:18). */
3
+ export const PAPER_COLUMNS: Record<ReceiptPaper, number> = { '58mm': 32, '80mm': 48 };
4
+ export const DEFAULT_RECEIPT_TEMPLATES: Record<ReceiptPaper, string> = {
5
+ '58mm': receiptTemplate(32, 10, 12),
6
+ '80mm': receiptTemplate(48, 12, 14),
7
+ };
8
+
9
+ function receiptTemplate(columns: number, labelWidth: number, amountWidth: number): string {
10
+ return `<receipt paper-width="${columns}">
11
+ <align mode="center">
12
+ <bold><text>{{store.name}}</text></bold>
13
+ {{#store.addressLines}}
14
+ <text>{{line}}</text>
15
+ {{/store.addressLines}}
16
+ </align>
17
+ <line />
18
+ <align mode="center"><bold><text>{{document.title}}</text></bold></align>
19
+ {{#document.isReprint}}
20
+ <align mode="center"><text>Copy {{document.reprintCount}}</text></align>
21
+ {{/document.isReprint}}
22
+ <row><col width="${labelWidth}">Order</col><col width="*" align="right">{{order.number}}</col></row>
23
+ <row><col width="${labelWidth}">Date</col><col width="*" align="right">{{order.date}}</col></row>
24
+ {{#cashier}}
25
+ <row><col width="${labelWidth}">Cashier</col><col width="*" align="right">{{cashier}}</col></row>
26
+ {{/cashier}}
27
+ {{#register}}
28
+ <row><col width="${labelWidth}">Register</col><col width="*" align="right">{{register}}</col></row>
29
+ {{/register}}
30
+ {{#customer}}
31
+ <row><col width="${labelWidth}">Customer</col><col width="*" align="right">{{customer}}</col></row>
32
+ {{/customer}}
33
+ <line style="dashed" />
34
+ {{#lines}}
35
+ <text>{{name}}</text>
36
+ {{#options}}
37
+ <text> {{text}}</text>
38
+ {{/options}}
39
+ <row><col width="*"> {{detail}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
40
+ {{#discounts}}
41
+ <row><col width="*"> {{label}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
42
+ {{/discounts}}
43
+ {{/lines}}
44
+ <line style="dashed" />
45
+ <row><col width="*">Subtotal</col><col width="${amountWidth}" align="right">{{subtotal}}</col></row>
46
+ {{#lineDiscount}}
47
+ <row><col width="*">Line discounts</col><col width="${amountWidth}" align="right">{{lineDiscount}}</col></row>
48
+ {{/lineDiscount}}
49
+ {{#orderDiscount}}
50
+ <row><col width="*">Order discount</col><col width="${amountWidth}" align="right">{{orderDiscount}}</col></row>
51
+ {{/orderDiscount}}
52
+ {{#charges}}
53
+ <row><col width="*">{{label}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
54
+ {{/charges}}
55
+ {{#taxes}}
56
+ <row><col width="*">{{label}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
57
+ {{/taxes}}
58
+ <bold><row><col width="*">Total</col><col width="${amountWidth}" align="right">{{total}}</col></row></bold>
59
+ <line />
60
+ {{#payments}}
61
+ <row><col width="*">{{method}}{{#reference}} {{reference}}{{/reference}}</col><col width="${amountWidth}" align="right">{{amount}}</col></row>
62
+ {{/payments}}
63
+ {{#change}}
64
+ <row><col width="*">Change</col><col width="${amountWidth}" align="right">{{change}}</col></row>
65
+ {{/change}}
66
+ {{#note}}
67
+ <feed lines="1" />
68
+ <text>{{note}}</text>
69
+ {{/note}}
70
+ <feed lines="1" />
71
+ <align mode="center"><text>Thank you</text></align>
72
+ {{#qrPayload}}
73
+ <align mode="center"><qrcode size="4">{{qrPayload}}</qrcode></align>
74
+ {{/qrPayload}}
75
+ <feed lines="3" />
76
+ <cut />
77
+ </receipt>`;
78
+ }
@@ -0,0 +1,15 @@
1
+ export { parseXml } from './parse-xml';
2
+ export { renderHtml } from './render-html';
3
+ export { sanitizeHtml } from './sanitize-html';
4
+ export { renderReceiptTemplate, renderLogiclessTemplate, renderThermalPreview } from './render-template';
5
+ export { receiptTemplateData } from './template-data';
6
+ export { DEFAULT_RECEIPT_TEMPLATES, PAPER_COLUMNS } from './default-templates';
7
+ export { renderReceiptHtml } from './render-receipt';
8
+ export type { ThermalNode, ReceiptNode } from './types';
9
+ export type { SanitizeHtmlOptions } from './sanitize-html';
10
+ export type { RenderSanitizeOptions } from './render-template';
11
+ export type {
12
+ ReceiptTemplateRow, ReceiptTemplateLine, ReceiptTemplateData, ReceiptTemplateOptions,
13
+ } from './template-data';
14
+ export type { ReceiptPaper } from './default-templates';
15
+ export type { RenderReceiptOptions } from './render-receipt';
@@ -0,0 +1,175 @@
1
+ // Ported from WCPOS v2 packages/receipt-renderer/src/parse-xml.ts (monorepo main 5ac185b0, MIT).
2
+ // Native DOMParser, else @xmldom/xmldom (React Native).
3
+ import { DOMParser as XmlDOMParser } from '@xmldom/xmldom';
4
+ import type { ColNode, DrawerConnector, ReceiptNode, RowNode, ThermalNode } from './types';
5
+
6
+ /** Parse a thermal XML template string into an AST using the native DOMParser or xmldom. */
7
+ export function parseXml(xml: string): ReceiptNode {
8
+ const doc = parseXmlDocument(xml);
9
+ const errorNode = doc.getElementsByTagName('parsererror')[0];
10
+ if (errorNode) throw new Error(`XML parse error: ${errorNode.textContent}`);
11
+ const root = doc.documentElement;
12
+ if (root.tagName !== 'receipt') {
13
+ throw new Error(`Expected <receipt> root element, got <${root.tagName}>`);
14
+ }
15
+ return { type: 'receipt', paperWidth: intAttr(root, 'paper-width', 48), children: parseChildren(root) };
16
+ }
17
+
18
+ function parseChildren(parent: Element): ThermalNode[] {
19
+ const nodes: ThermalNode[] = [];
20
+ for (const child of Array.from(parent.childNodes)) {
21
+ if (child.nodeType === 3 /* TEXT_NODE */) {
22
+ const text = child.textContent ?? '';
23
+ // Skip indentation, but preserve non-empty text so spaces around inline elements survive.
24
+ if (/\S/.test(text)) nodes.push({ type: 'raw-text', value: text });
25
+ continue;
26
+ }
27
+ if (child.nodeType !== 1 /* ELEMENT_NODE */) continue;
28
+ const el = child as Element;
29
+ const tag = el.tagName.toLowerCase();
30
+ switch (tag) {
31
+ case 'text':
32
+ nodes.push({ type: 'text', children: parseChildren(el) });
33
+ break;
34
+ case 'bold':
35
+ nodes.push({ type: 'bold', children: parseChildren(el) });
36
+ break;
37
+ case 'underline':
38
+ nodes.push({ type: 'underline', children: parseChildren(el) });
39
+ break;
40
+ case 'invert':
41
+ nodes.push({ type: 'invert', children: parseChildren(el) });
42
+ break;
43
+ case 'size': {
44
+ const w = intAttr(el, 'width', 1);
45
+ nodes.push({ type: 'size', width: w, height: intAttr(el, 'height', w), children: parseChildren(el) });
46
+ break;
47
+ }
48
+ case 'align': {
49
+ const modeAttr = el.getAttribute('mode');
50
+ const validModes = ['left', 'center', 'right'] as const;
51
+ const mode = validModes.includes(modeAttr as (typeof validModes)[number])
52
+ ? (modeAttr as 'left' | 'center' | 'right') : 'left';
53
+ nodes.push({ type: 'align', mode, children: parseChildren(el) });
54
+ break;
55
+ }
56
+ case 'row':
57
+ nodes.push({ type: 'row', children: parseRowChildren(el) } as RowNode);
58
+ break;
59
+ case 'col':
60
+ break;
61
+ case 'line': {
62
+ const styleAttr = el.getAttribute('style');
63
+ const validStyles = ['single', 'double', 'dashed', 'dotted'] as const;
64
+ nodes.push({
65
+ type: 'line',
66
+ style: validStyles.includes(styleAttr as (typeof validStyles)[number])
67
+ ? (styleAttr as (typeof validStyles)[number]) : 'single',
68
+ });
69
+ break;
70
+ }
71
+ case 'barcode':
72
+ if (isQrBarcodeType(el.getAttribute('type') ?? 'code128')) {
73
+ nodes.push({
74
+ type: 'qrcode', size: heightToQrSize(intAttr(el, 'height', 40)), value: (el.textContent ?? '').trim(),
75
+ });
76
+ } else {
77
+ nodes.push({
78
+ type: 'barcode', barcodeType: el.getAttribute('type') ?? 'code128',
79
+ height: intAttr(el, 'height', 40), value: (el.textContent ?? '').trim(),
80
+ });
81
+ }
82
+ break;
83
+ case 'qrcode':
84
+ nodes.push({ type: 'qrcode', size: intAttr(el, 'size', 4), value: (el.textContent ?? '').trim() });
85
+ break;
86
+ case 'image':
87
+ nodes.push({ type: 'image', src: el.getAttribute('src') ?? '', width: intAttr(el, 'width', 200) });
88
+ break;
89
+ case 'cut': {
90
+ const cutAttr = el.getAttribute('type');
91
+ const validCuts = ['full', 'partial'] as const;
92
+ nodes.push({
93
+ type: 'cut',
94
+ cutType: validCuts.includes(cutAttr as (typeof validCuts)[number])
95
+ ? (cutAttr as 'full' | 'partial') : 'partial',
96
+ });
97
+ break;
98
+ }
99
+ case 'feed':
100
+ nodes.push({ type: 'feed', lines: intAttr(el, 'lines', 1) });
101
+ break;
102
+ case 'drawer':
103
+ nodes.push({ type: 'drawer', ...(drawerConnectorAttr(el) ? { connector: drawerConnectorAttr(el) } : {}) });
104
+ break;
105
+ default:
106
+ nodes.push(...parseChildren(el));
107
+ }
108
+ }
109
+ return nodes;
110
+ }
111
+
112
+ function drawerConnectorAttr(el: Element): DrawerConnector | undefined {
113
+ const connector = el.getAttribute('connector')?.trim();
114
+ return connector === 'pin2' || connector === 'pin5' ? connector : undefined;
115
+ }
116
+
117
+ function isQrBarcodeType(type: string): boolean {
118
+ return type.trim().toLowerCase() === 'qrcode' || type.trim().toLowerCase() === 'qr';
119
+ }
120
+
121
+ function heightToQrSize(height: number): number {
122
+ return Number.isFinite(height) && height > 0 ? Math.max(2, Math.min(10, Math.round(height / 10))) : 4;
123
+ }
124
+
125
+ function parseRowChildren(row: Element): ColNode[] {
126
+ const cols: ColNode[] = [];
127
+ for (const child of Array.from(row.childNodes)) {
128
+ if (child.nodeType !== 1 /* ELEMENT_NODE */) continue;
129
+ const el = child as Element;
130
+ if (el.tagName.toLowerCase() === 'col') {
131
+ const rawWidth = el.getAttribute('width');
132
+ const width: number | '*' = rawWidth === '*' ? '*' : intAttr(el, 'width', 12);
133
+ cols.push({
134
+ type: 'col', width,
135
+ align: (['left', 'right'] as const).includes(el.getAttribute('align') as 'left' | 'right')
136
+ ? (el.getAttribute('align') as 'left' | 'right') : 'left',
137
+ children: parseChildren(el),
138
+ });
139
+ }
140
+ }
141
+ return cols;
142
+ }
143
+
144
+ function parseXmlDocument(xml: string): Document {
145
+ if (typeof DOMParser !== 'undefined') {
146
+ return new DOMParser().parseFromString(xml, 'text/xml');
147
+ }
148
+
149
+ const errors: string[] = [];
150
+ let doc: Document | undefined;
151
+ try {
152
+ doc = new XmlDOMParser({
153
+ onError: (_level: string, message: unknown) => errors.push(String(message)),
154
+ } as unknown as ConstructorParameters<typeof XmlDOMParser>[0]).parseFromString(
155
+ xml,
156
+ 'text/xml'
157
+ ) as unknown as Document;
158
+ } catch (error) {
159
+ errors.push(error instanceof Error ? error.message : String(error));
160
+ }
161
+
162
+ if (errors.length > 0 || !doc) {
163
+ throw new Error(`XML parse error: ${errors.join('; ') || 'invalid document'}`);
164
+ }
165
+
166
+ return doc;
167
+ }
168
+
169
+ function intAttr(el: Element, name: string, fallback: number): number {
170
+ const raw = el.getAttribute(name)?.trim();
171
+ if (raw == null) return fallback;
172
+ if (!/^[1-9]\d*$/.test(raw)) return fallback;
173
+ const n = Number(raw);
174
+ return Number.isSafeInteger(n) ? n : fallback;
175
+ }
@@ -0,0 +1,152 @@
1
+ // Ported from WCPOS v2 packages/receipt-renderer/src/render-html.ts (monorepo main 5ac185b0, MIT).
2
+ // Barcode SVG generation and options omitted; codes render pending placeholders.
3
+ import type { ColNode, ReceiptNode, RowNode, ThermalNode } from './types';
4
+
5
+ // 80mm paper at 203 DPI prints ~576 dots wide; 58mm prints ~384 dots.
6
+ // The AST gives character width: anything >= 40 chars is treated as 80mm.
7
+ const DOT_BUDGET_WIDE = 576;
8
+ const DOT_BUDGET_NARROW = 384;
9
+ const NARROW_PAPER_THRESHOLD_CHARS = 40;
10
+
11
+ export function renderHtml(ast: ReceiptNode): string {
12
+ const widthChars = safeInteger(ast.paperWidth, 48, 16, 120);
13
+ const inner = renderNodes(ast.children, widthChars);
14
+ return `<div style="width: ${widthChars}ch; font-family: 'Courier New', Courier, monospace; font-size: 13px; ` +
15
+ 'line-height: 1.4; background: #fff; color: #000; padding: 16px 12px; overflow: hidden; ' +
16
+ `white-space: pre-wrap; overflow-wrap: anywhere;">${inner}</div>`;
17
+ }
18
+
19
+ function renderNodes(nodes: ThermalNode[], widthChars: number): string {
20
+ return nodes.map((node) => renderNode(node, widthChars)).join('');
21
+ }
22
+
23
+ function renderNode(node: ThermalNode, widthChars: number): string {
24
+ switch (node.type) {
25
+ case 'raw-text':
26
+ return escapeHtml(node.value);
27
+ case 'text':
28
+ return `<div>${renderNodes(node.children, widthChars)}</div>`;
29
+ case 'bold':
30
+ return `<strong>${renderNodes(node.children, widthChars)}</strong>`;
31
+ case 'underline':
32
+ return `<span style="text-decoration: underline">${renderNodes(node.children, widthChars)}</span>`;
33
+ case 'invert':
34
+ // Inline-block keeps block <text> children from collapsing the reversed background to zero width.
35
+ return '<span style="display: inline-block; background: #000; color: #fff; padding: 0 4px">' +
36
+ `${renderNodes(node.children, widthChars)}</span>`;
37
+ case 'size':
38
+ return `<span style="font-size: ${safeFloat(node.width, 1, 0.5, 8)}em; line-height: 1.2">` +
39
+ `${renderNodes(node.children, widthChars)}</span>`;
40
+ case 'align':
41
+ return `<div style="text-align: ${safeAlign(node.mode)}">${renderNodes(node.children, widthChars)}</div>`;
42
+ case 'row':
43
+ return renderRow(node, widthChars);
44
+ case 'col':
45
+ return renderCol(node, widthChars);
46
+ case 'line':
47
+ if (node.style === 'double') return '<hr style="border: none; border-top: 3px double #000; margin: 4px 0" />';
48
+ if (node.style === 'dashed') return '<hr style="border: none; border-top: 1px dashed #000; margin: 4px 0" />';
49
+ if (node.style === 'dotted') return '<hr style="border: none; border-top: 1px dotted #000; margin: 4px 0" />';
50
+ return '<hr style="border: none; border-top: 1px solid #000; margin: 4px 0" />';
51
+ case 'barcode':
52
+ return pendingCode(isQrBarcodeType(node.barcodeType) ? 'qrcode' : 'barcode', node.value);
53
+ case 'qrcode':
54
+ return pendingCode('qrcode', node.value);
55
+ case 'image': {
56
+ const safeSrc = safeImageSrc(node.src);
57
+ if (!safeSrc) return '';
58
+ const widthDots = safeInteger(node.width, 200, 1, 2000);
59
+ const widthCh = dotsToCh(widthDots, widthChars);
60
+ return `<div style="text-align: center; padding: 8px 0"><img src="${safeSrc}" ` +
61
+ `style="width: min(100%, ${widthCh.toFixed(2)}ch); height: auto" /></div>`;
62
+ }
63
+ case 'cut':
64
+ return '<div style="border-top: 1px dashed #ccc; margin: 12px 0; position: relative">' +
65
+ '<span style="position: absolute; top: -8px; left: -4px; font-size: 14px">&#9986;</span></div>';
66
+ case 'feed':
67
+ return `<div style="height: ${(safeInteger(node.lines, 1, 1, 50) * 1.4).toFixed(1)}em"></div>`;
68
+ case 'drawer':
69
+ return '';
70
+ case 'receipt':
71
+ return renderNodes(node.children, widthChars);
72
+ default:
73
+ return '';
74
+ }
75
+ }
76
+
77
+ function pendingCode(kind: 'barcode' | 'qrcode', value: string): string {
78
+ const text = value.trim();
79
+ if (!text) return '';
80
+ const safeKind = kind === 'qrcode' ? 'qrcode' : 'barcode';
81
+ return `<div data-barcode-kind="${safeKind}" data-barcode-value="${escapeHtml(text)}" ` +
82
+ 'data-barcode-pending="true" style="text-align: center; padding: 8px 0">' +
83
+ `<code>${escapeHtml(text)}</code></div>`;
84
+ }
85
+
86
+ function renderRow(node: RowNode, widthChars: number): string {
87
+ const cols = node.children.map((col) => renderCol(col, widthChars)).join('');
88
+ return `<div style="display: flex">${cols}</div>`;
89
+ }
90
+
91
+ function renderCol(node: ColNode, widthChars: number): string {
92
+ const flex = node.width === '*' ? 'flex: 1' : `flex: 0 0 ${safeInteger(node.width, 12, 1, 120)}ch`;
93
+ return `<span style="${flex}; text-align: ${safeAlign(node.align)}; overflow: hidden">` +
94
+ `${renderNodes(node.children, widthChars)}</span>`;
95
+ }
96
+
97
+ function safeInteger(value: unknown, fallback: number, min: number, max: number): number {
98
+ const n = Math.trunc(Number(value));
99
+ return Number.isFinite(n) && n >= min && n <= max ? n : fallback;
100
+ }
101
+
102
+ function safeFloat(value: unknown, fallback: number, min: number, max: number): number {
103
+ const n = Number(value);
104
+ return Number.isFinite(n) && n >= min && n <= max ? n : fallback;
105
+ }
106
+
107
+ function safeAlign(value: unknown): 'left' | 'center' | 'right' {
108
+ return value === 'left' || value === 'center' || value === 'right' ? value : 'left';
109
+ }
110
+
111
+ function isQrBarcodeType(type: string): boolean {
112
+ const normalized = type.trim().toLowerCase();
113
+ return normalized === 'qrcode' || normalized === 'qr';
114
+ }
115
+
116
+ /** Convert printer dots to ch units relative to the receipt's character width. */
117
+ function dotsToCh(dots: number, paperWidthChars: number): number {
118
+ const dotBudget = paperWidthChars >= NARROW_PAPER_THRESHOLD_CHARS ? DOT_BUDGET_WIDE : DOT_BUDGET_NARROW;
119
+ return (dots * paperWidthChars) / dotBudget;
120
+ }
121
+
122
+ function safeImageSrc(src: unknown): string {
123
+ if (typeof src !== 'string') return '';
124
+ const value = src.trim();
125
+ const isHttpUrl = /^https?:\/\//i.test(value);
126
+ const isSafeDataUri = /^data:image\/(?:png|jpe?g|gif);base64,[A-Za-z0-9+/=]+$/i.test(value);
127
+ const isSafeRootRelative = isSafeRootRelativeImageSrc(value);
128
+ return isHttpUrl || isSafeDataUri || isSafeRootRelative ? escapeHtml(value) : '';
129
+ }
130
+
131
+ function isSafeRootRelativeImageSrc(value: string): boolean {
132
+ if (value.startsWith('//')) return false;
133
+ if (value.includes('\\')) return false;
134
+ const path = value.split(/[?#]/, 1)[0];
135
+ const suffix = value.slice(path.length);
136
+ let decodedPath: string;
137
+ try {
138
+ decodedPath = decodeURIComponent(path);
139
+ } catch {
140
+ return false;
141
+ }
142
+ if (decodedPath.includes('\\')) return false;
143
+ const segments = decodedPath.split('/');
144
+ if (segments.includes('..') || segments.includes('.')) return false;
145
+ return /^\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]+$/.test(path) &&
146
+ (suffix === '' || /^[?#][A-Za-z0-9._~!$&'()*+,;=:@%/?#-]+$/.test(suffix));
147
+ }
148
+
149
+ function escapeHtml(str: string): string {
150
+ return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
151
+ .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
152
+ }
@@ -0,0 +1,19 @@
1
+ import type { ReceiptData } from '../receipt/types';
2
+ import { DEFAULT_RECEIPT_TEMPLATES } from './default-templates';
3
+ import type { ReceiptPaper } from './default-templates';
4
+ import { renderThermalPreview } from './render-template';
5
+ import { receiptTemplateData } from './template-data';
6
+ import type { ReceiptTemplateOptions } from './template-data';
7
+
8
+ export interface RenderReceiptOptions extends ReceiptTemplateOptions {
9
+ /** Default '80mm'. Picks DEFAULT_RECEIPT_TEMPLATES[paper] when no template is given. */
10
+ paper?: ReceiptPaper;
11
+ /** A thermal-XML Mustache template over ReceiptTemplateData. */
12
+ template?: string;
13
+ }
14
+
15
+ /** receiptTemplateData, then renderThermalPreview (sanitized). Needs a global DOMParser (browsers, jsdom). */
16
+ export function renderReceiptHtml(receipt: ReceiptData, options: RenderReceiptOptions = {}): string {
17
+ const template = options.template ?? DEFAULT_RECEIPT_TEMPLATES[options.paper ?? '80mm'];
18
+ return renderThermalPreview(template, receiptTemplateData(receipt, options));
19
+ }
@@ -0,0 +1,35 @@
1
+ // Ported from WCPOS v2 packages/receipt-renderer/src/render-template.ts (monorepo main 5ac185b0, MIT).
2
+ // Uses object data; barcode resolution and SVG sanitization options omitted.
3
+ import Mustache from 'mustache';
4
+ import { parseXml } from './parse-xml';
5
+ import { renderHtml } from './render-html';
6
+ import { sanitizeHtml } from './sanitize-html';
7
+ import type { SanitizeHtmlOptions } from './sanitize-html';
8
+
9
+ export interface RenderSanitizeOptions extends SanitizeHtmlOptions {
10
+ /** Disable sanitization only for trusted test/debug output. Defaults to true. */
11
+ sanitize?: boolean;
12
+ }
13
+
14
+ /** Mustache only. */
15
+ export function renderReceiptTemplate(template: string, data: object): string {
16
+ return Mustache.render(template, data);
17
+ }
18
+
19
+ /** Mustache HTML template, then sanitize (unless sanitize === false). No <barcode>/<qrcode> resolution. */
20
+ export function renderLogiclessTemplate(
21
+ template: string, data: object, options: RenderSanitizeOptions = {},
22
+ ): string {
23
+ const html = Mustache.render(template, data);
24
+ return options.sanitize === false ? html : sanitizeHtml(html, options);
25
+ }
26
+
27
+ /** Mustache, then parseXml, then renderHtml, then sanitize (unless sanitize === false). */
28
+ export function renderThermalPreview(
29
+ template: string, data: object, options: RenderSanitizeOptions = {},
30
+ ): string {
31
+ const resolved = Mustache.render(template, data);
32
+ const ast = parseXml(resolved);
33
+ const html = renderHtml(ast);
34
+ return options.sanitize === false ? html : sanitizeHtml(html, options);
35
+ }
@@ -0,0 +1,146 @@
1
+ // Ported from WCPOS v2 packages/receipt-renderer/src/sanitize-html.ts (monorepo main 5ac185b0, MIT).
2
+ // All three runtime paths ported: DOMPurify, DOM walk, xmldom.
3
+ import { DOMParser as XmlDOMParser, XMLSerializer as XmlSerializer } from '@xmldom/xmldom';
4
+ import createDOMPurify from 'dompurify';
5
+
6
+ export interface SanitizeHtmlOptions {
7
+ /** Additional tag names to allow beyond DOMPurify's default HTML profile. */
8
+ addTags?: string[];
9
+ /** Additional attribute names to allow beyond DOMPurify's default HTML profile. */
10
+ addAttributes?: string[];
11
+ }
12
+
13
+ /**
14
+ * Sanitize rendered receipt HTML before it is inserted into an admin/browser DOM
15
+ * (or a native WebView via `srcDoc`).
16
+ *
17
+ * The default profile deliberately excludes SVG/MathML and strips scripts,
18
+ * event handlers, and unsafe URL protocols while preserving normal receipt HTML.
19
+ *
20
+ * Three execution paths, in priority order:
21
+ * 1. Browser/DOM with `window.document` → DOMPurify (the strongest profile).
22
+ * 2. A runtime that exposes a global `DOMParser` (e.g. jsdom/SSR) → DOM walk.
23
+ * 3. React Native, which has neither → parse via `@xmldom/xmldom` and walk.
24
+ *
25
+ * The xmldom fallback mirrors `parse-xml.ts`, which already uses xmldom on
26
+ * native. Without it, native runtimes hit the escaped-text last resort and the
27
+ * receipt preview renders raw HTML markup as visible text instead of HTML.
28
+ */
29
+ export function sanitizeHtml(html: string, options: SanitizeHtmlOptions = {}): string {
30
+ const win = globalThis.window;
31
+
32
+ if (win?.document) {
33
+ const purify = createDOMPurify(win);
34
+ return purify.sanitize(html, {
35
+ USE_PROFILES: { html: true },
36
+ ADD_TAGS: options.addTags,
37
+ ADD_ATTR: options.addAttributes,
38
+ });
39
+ }
40
+
41
+ const parsed = parseHtmlForSanitize(html);
42
+ if (!parsed) {
43
+ // Last-resort non-DOM fallback for SSR/build tooling: return escaped text instead of unsafe markup.
44
+ return escapeHtml(html);
45
+ }
46
+
47
+ sanitizeParsedBody(parsed.body, options);
48
+ return parsed.serialize();
49
+ }
50
+
51
+ const URL_BEARING_ATTRIBUTES = new Set(['href', 'src', 'action', 'formaction', 'xlink:href']);
52
+
53
+ /** Executable, document-control, remote-fetch and SVG/MathML tags stripped unless explicitly allow-listed. */
54
+ const DANGEROUS_TAGS = new Set([
55
+ 'script', 'iframe', 'object', 'embed', 'style', 'link', 'meta', 'base', 'svg', 'math',
56
+ ]);
57
+
58
+ const XHTML_NAMESPACE_ATTR = / xmlns="http:\/\/www\.w3\.org\/1999\/xhtml"/g;
59
+
60
+ function hasUnsafeProtocol(raw: string): boolean {
61
+ // eslint-disable-next-line no-control-regex -- Strip control characters before checking URL protocols, as in v2.
62
+ const normalized = raw.replace(/[\u0000-\u001F\u007F\s]+/g, '').toLowerCase();
63
+ return normalized.startsWith('javascript:') || normalized.startsWith('vbscript:') || normalized.startsWith('data:');
64
+ }
65
+
66
+ interface ParsedHtml {
67
+ body: Element;
68
+ serialize: () => string;
69
+ }
70
+
71
+ /**
72
+ * Parse `html` into a DOM `<body>` and return a serializer for its inner HTML.
73
+ * Uses the native `DOMParser` when present, and falls back to `@xmldom/xmldom`
74
+ * for React Native runtimes that do not provide browser DOM globals. Returns
75
+ * `null` when no parser can produce a document (callers escape as a last resort).
76
+ */
77
+ function parseHtmlForSanitize(html: string): ParsedHtml | null {
78
+ const source = `<!doctype html><html><body>${html}</body></html>`;
79
+
80
+ if (typeof DOMParser !== 'undefined') {
81
+ const doc = new DOMParser().parseFromString(source, 'text/html');
82
+ const body = doc.body ?? doc.getElementsByTagName('body')[0];
83
+ if (!body) return null;
84
+ return { body, serialize: () => body.innerHTML };
85
+ }
86
+
87
+ try {
88
+ const errors: string[] = [];
89
+ const doc = new XmlDOMParser({
90
+ onError: (_level: string, message: unknown) => errors.push(String(message)),
91
+ } as unknown as ConstructorParameters<typeof XmlDOMParser>[0]).parseFromString(
92
+ source,
93
+ 'text/html'
94
+ ) as unknown as Document;
95
+
96
+ const body = doc.getElementsByTagName('body')[0] as unknown as Element | undefined;
97
+ if (!body) return null;
98
+
99
+ const serializer = new XmlSerializer();
100
+ return {
101
+ body,
102
+ serialize: () => {
103
+ let inner = '';
104
+ for (const child of Array.from(body.childNodes)) {
105
+ inner += serializer.serializeToString(
106
+ child as unknown as Parameters<typeof serializer.serializeToString>[0]
107
+ );
108
+ }
109
+ // xmldom annotates serialized HTML nodes with the XHTML namespace; the
110
+ // attribute is inert in a WebView but noisy, so drop it.
111
+ // codeql[js/unsafe-html] Safe because sanitizeParsedBody() removes dangerous
112
+ // elements, event handlers, and unsafe URL protocols before serialize() runs.
113
+ return inner.replace(XHTML_NAMESPACE_ATTR, '');
114
+ },
115
+ };
116
+ } catch {
117
+ return null;
118
+ }
119
+ }
120
+
121
+ /** Remove dangerous elements, event-handler attributes, and unsafe-protocol URLs from the parsed body. */
122
+ function sanitizeParsedBody(body: Element, options: SanitizeHtmlOptions): void {
123
+ const allowedExtraTags = new Set((options.addTags ?? []).map((tag) => tag.toLowerCase()));
124
+ const allowedExtraAttrs = new Set((options.addAttributes ?? []).map((attr) => attr.toLowerCase()));
125
+ for (const el of Array.from(body.getElementsByTagName('*'))) {
126
+ const tag = el.tagName.toLowerCase();
127
+ if (DANGEROUS_TAGS.has(tag) && !allowedExtraTags.has(tag)) el.parentNode?.removeChild(el);
128
+ }
129
+ for (const el of Array.from(body.getElementsByTagName('*'))) {
130
+ if (!el.attributes) continue;
131
+ for (const attr of Array.from(el.attributes)) {
132
+ const name = attr.name.toLowerCase();
133
+ const value = (attr.value ?? '').trim();
134
+ if (name.startsWith('on') && !allowedExtraAttrs.has(name)) {
135
+ el.removeAttribute(attr.name);
136
+ continue;
137
+ }
138
+ if (URL_BEARING_ATTRIBUTES.has(name) && hasUnsafeProtocol(value)) el.removeAttribute(attr.name);
139
+ }
140
+ }
141
+ }
142
+
143
+ function escapeHtml(str: string): string {
144
+ return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
145
+ .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
146
+ }