@btps/sdk 1.2.0-rc.2 → 1.2.0-rc.3.1

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.
@@ -0,0 +1,344 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+
8
+ import { CURRENCY_DECIMALS } from "../constants/currency.js";
9
+ import {
10
+ BtpBoundViewSchema
11
+ } from "./boundViewSchema.js";
12
+ import { boundValue } from "./boundViewBindings.js";
13
+ const MONTHS = [
14
+ "January",
15
+ "February",
16
+ "March",
17
+ "April",
18
+ "May",
19
+ "June",
20
+ "July",
21
+ "August",
22
+ "September",
23
+ "October",
24
+ "November",
25
+ "December"
26
+ ], grouped = (digits, separator) => digits.replace(/\B(?=(\d{3})+(?!\d))/g, separator), writeDate = (iso, pattern) => {
27
+ const date = new Date(iso), d = String(date.getUTCDate()), dd = d.padStart(2, "0"), MM = String(date.getUTCMonth() + 1).padStart(2, "0"), month = MONTHS[date.getUTCMonth()] ?? "", yyyy = String(date.getUTCFullYear());
28
+ return {
29
+ "d MMM yyyy": `${d} ${month.slice(0, 3)} ${yyyy}`,
30
+ "d MMMM yyyy": `${d} ${month} ${yyyy}`,
31
+ "MMM d, yyyy": `${month.slice(0, 3)} ${d}, ${yyyy}`,
32
+ "MMMM d, yyyy": `${month} ${d}, ${yyyy}`,
33
+ "dd/MM/yyyy": `${dd}/${MM}/${yyyy}`,
34
+ "MM/dd/yyyy": `${MM}/${dd}/${yyyy}`,
35
+ "dd.MM.yyyy": `${dd}.${MM}.${yyyy}`,
36
+ "dd-MM-yyyy": `${dd}-${MM}-${yyyy}`,
37
+ "yyyy-MM-dd": `${yyyy}-${MM}-${dd}`
38
+ }[pattern] ?? "";
39
+ }, writtenValue = (value, bind) => {
40
+ const format = bind.format;
41
+ if (value.kind === "money" && format && "money" in format) {
42
+ const { group, decimal, prefix = "", suffix = "" } = format.money, places = CURRENCY_DECIMALS[value.currency] ?? 2, digits = String(Math.abs(value.amount)).padStart(places + 1, "0"), whole = grouped(digits.slice(0, digits.length - places), group), number = places > 0 ? `${whole}${decimal}${digits.slice(-places)}` : whole;
43
+ return `${value.amount < 0 ? "-" : ""}${prefix}${number}${suffix}`;
44
+ }
45
+ if (value.kind === "date" && format && "date" in format) return writeDate(value.date, format.date);
46
+ if (value.kind === "percent" && format && "percent" in format) {
47
+ const { decimals, decimal } = format.percent;
48
+ return `${(value.basisPoints / 100).toFixed(decimals).replace(".", decimal)}%`;
49
+ }
50
+ if (value.kind !== "text") return "";
51
+ if (format && "groups" in format) {
52
+ const characters2 = [...value.text.replace(/ /g, "")], parts = [];
53
+ let at = 0;
54
+ for (const size of format.groups.sizes)
55
+ parts.push(characters2.slice(at, at + size).join("")), at += size;
56
+ return parts.join(format.groups.separator);
57
+ }
58
+ const characters = [...value.text];
59
+ return bind.range ? characters.slice(bind.range[0], bind.range[1]).join("") : value.text;
60
+ }, transformed = (text, transform) => [...text].map((char) => {
61
+ if (transform === void 0) return char;
62
+ const changed = transform === "uppercase" ? char.toUpperCase() : char.toLowerCase();
63
+ return [...changed].length === 1 ? changed : char;
64
+ }).join(""), measured = (text, font, size, letterSpacing) => {
65
+ const characters = [...text], scale = size / font.unitsPerEm;
66
+ let width = 0;
67
+ for (let i = 0; i < characters.length; i++) {
68
+ const glyph = font.glyphs?.[characters[i] ?? ""];
69
+ if (glyph === void 0) return;
70
+ const kerning = font.kerning?.[`${characters[i]}${characters[i + 1] ?? ""}`] ?? 0;
71
+ width += (glyph.advance + kerning) * scale + letterSpacing;
72
+ }
73
+ return width;
74
+ }, overlaps = (a, b) => a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom, textBox = (element, view) => {
75
+ const font = view.fonts?.[element.font], scale = font ? element.size / font.unitsPerEm : 0;
76
+ return {
77
+ left: element.x,
78
+ right: element.x + element.width,
79
+ top: element.y - (font?.ascent ?? 0) * scale,
80
+ bottom: element.y + (font?.descent ?? 0) * scale
81
+ };
82
+ }, polygons = (d) => {
83
+ const tokens = d.trim().split(/[\s,]+|(?=[A-Z])|(?<=[A-Z])/).filter(Boolean), outlines = [];
84
+ let current = [], at = [0, 0], start = [0, 0], i = 0;
85
+ const next = () => Number(tokens[i++]), close = () => {
86
+ current.length > 1 && outlines.push(current), current = [];
87
+ };
88
+ for (; i < tokens.length; ) {
89
+ const command = tokens[i++];
90
+ if (command === "M")
91
+ close(), at = [next(), next()], start = at, current.push(at);
92
+ else if (command === "L")
93
+ at = [next(), next()], current.push(at);
94
+ else if (command === "H")
95
+ at = [next(), at[1]], current.push(at);
96
+ else if (command === "V")
97
+ at = [at[0], next()], current.push(at);
98
+ else if (command === "Q" || command === "C") {
99
+ const controls = [];
100
+ for (let n = command === "Q" ? 1 : 2; n > 0; n--) controls.push([next(), next()]);
101
+ const end = [next(), next()], from = at;
102
+ for (let step = 1; step <= 16; step++) {
103
+ const t = step / 16, u = 1 - t, [c1, c2] = controls;
104
+ current.push(
105
+ c2 === void 0 ? [
106
+ u * u * from[0] + 2 * u * t * c1[0] + t * t * end[0],
107
+ u * u * from[1] + 2 * u * t * c1[1] + t * t * end[1]
108
+ ] : [
109
+ u * u * u * from[0] + 3 * u * u * t * c1[0] + 3 * u * t * t * c2[0] + t * t * t * end[0],
110
+ u * u * u * from[1] + 3 * u * u * t * c1[1] + 3 * u * t * t * c2[1] + t * t * t * end[1]
111
+ ]
112
+ );
113
+ }
114
+ at = end;
115
+ } else command === "Z" && (current.push(start), at = start, close(), current.push(at));
116
+ }
117
+ return close(), outlines;
118
+ }, boundsOf = (points) => points.reduce(
119
+ (box, [x, y]) => ({
120
+ left: Math.min(box.left, x),
121
+ right: Math.max(box.right, x),
122
+ top: Math.min(box.top, y),
123
+ bottom: Math.max(box.bottom, y)
124
+ }),
125
+ { left: 1 / 0, right: -1 / 0, top: 1 / 0, bottom: -1 / 0 }
126
+ ), edgesOf = (outlines) => outlines.flatMap(
127
+ (outline) => outline.map((a, i) => {
128
+ const b = outline[(i + 1) % outline.length];
129
+ return [a[0], a[1], b[0], b[1]];
130
+ })
131
+ ), rowOf = (edges, y) => {
132
+ const crossings = [], spans = [];
133
+ for (const [ax, ay, bx, by] of edges)
134
+ ay === y && by === y ? spans.push([Math.min(ax, bx), Math.max(ax, bx)]) : ay <= y != by <= y && crossings.push([ax + (y - ay) * (bx - ax) / (by - ay), by > ay ? 1 : -1]);
135
+ crossings.sort((a, b) => a[0] - b[0]);
136
+ const winding = new Array(crossings.length + 1).fill(0);
137
+ for (let i = crossings.length - 1; i >= 0; i--)
138
+ winding[i] = (winding[i + 1] ?? 0) + (crossings[i]?.[1] ?? 0);
139
+ return { xs: crossings.map(([x]) => x), winding, spans };
140
+ }, rowCovers = (row, rule, x) => {
141
+ if (row.spans.some(([from, to]) => x >= from && x <= to)) return !0;
142
+ let low = 0, high = row.xs.length;
143
+ for (; low < high; ) {
144
+ const middle = low + high >> 1;
145
+ (row.xs[middle] ?? 0) <= x ? low = middle + 1 : high = middle;
146
+ }
147
+ return low > 0 && row.xs[low - 1] === x ? !0 : rule === "evenodd" ? (row.xs.length - low) % 2 === 1 : row.winding[low] !== 0;
148
+ }, CONTRAST_WORK_LIMIT = 2e7, rectCovers = (rect, [x, y]) => {
149
+ const { x: left, y: top, width, height } = rect;
150
+ if (x < left || x > left + width || y < top || y > top + height) return !1;
151
+ const limit = Math.min(width, height) / 2, { radius = 0 } = rect, radii = (Array.isArray(radius) ? radius : [radius, radius, radius, radius]).map(
152
+ (r) => Math.min(r, limit)
153
+ );
154
+ return [
155
+ [left + (radii[0] ?? 0), top + (radii[0] ?? 0), radii[0] ?? 0],
156
+ [left + width - (radii[1] ?? 0), top + (radii[1] ?? 0), radii[1] ?? 0],
157
+ [left + width - (radii[2] ?? 0), top + height - (radii[2] ?? 0), radii[2] ?? 0],
158
+ [left + (radii[3] ?? 0), top + height - (radii[3] ?? 0), radii[3] ?? 0]
159
+ ].every(([cx, cy, r], corner) => {
160
+ const outsideX = corner === 0 || corner === 3 ? x < cx : x > cx, outsideY = corner === 0 || corner === 1 ? y < cy : y > cy;
161
+ return !(outsideX && outsideY) || (x - cx) ** 2 + (y - cy) ** 2 <= r * r;
162
+ });
163
+ }, parse = (colour) => [
164
+ parseInt(colour.slice(1, 3), 16),
165
+ parseInt(colour.slice(3, 5), 16),
166
+ parseInt(colour.slice(5, 7), 16),
167
+ colour.length === 9 ? parseInt(colour.slice(7, 9), 16) / 255 : 1
168
+ ], paintAt = (paint, [x, y]) => {
169
+ if (typeof paint == "string") return parse(paint);
170
+ let t, stops;
171
+ if ("linear" in paint) {
172
+ const { from, to } = paint.linear, dx = to[0] - from[0], dy = to[1] - from[1], length = dx * dx + dy * dy;
173
+ t = length === 0 ? 0 : ((x - from[0]) * dx + (y - from[1]) * dy) / length, stops = paint.linear.stops;
174
+ } else {
175
+ const { centre, radius } = paint.radial;
176
+ t = radius === 0 ? 1 : Math.hypot(x - centre[0], y - centre[1]) / radius, stops = paint.radial.stops;
177
+ }
178
+ const first = stops[0], last = stops[stops.length - 1];
179
+ if (t <= first[0]) return parse(first[1]);
180
+ if (t >= last[0]) return parse(last[1]);
181
+ for (let i = 1; i < stops.length; i++) {
182
+ const [o1, c1] = stops[i - 1], [o2, c2] = stops[i];
183
+ if (t <= o2) {
184
+ const f = o2 === o1 ? 1 : (t - o1) / (o2 - o1), a = parse(c1), b = parse(c2);
185
+ return [0, 1, 2, 3].map((k) => a[k] + (b[k] - a[k]) * f);
186
+ }
187
+ }
188
+ return parse(last[1]);
189
+ }, over = (below, [r, g, b, a]) => [
190
+ r * a + below[0] * (1 - a),
191
+ g * a + below[1] * (1 - a),
192
+ b * a + below[2] * (1 - a)
193
+ ], luminance = (rgb) => {
194
+ const [r, g, b] = rgb.map((value) => {
195
+ const c = value / 255;
196
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
197
+ });
198
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
199
+ }, contrast = (a, b) => {
200
+ const [light, dark] = [luminance(a), luminance(b)].sort((x, y) => y - x);
201
+ return (light + 0.05) / (dark + 0.05);
202
+ }, samples = (start, end) => {
203
+ const points = [];
204
+ for (let at = start + 0.5; at <= end; at++) points.push(at);
205
+ return points.length > 0 ? points : [(start + end) / 2];
206
+ }, keyFacts = (document) => {
207
+ const type = document.type, lines = () => {
208
+ const items = document.lineItems;
209
+ if (items === void 0) return [];
210
+ const roles = items.roles ?? {}, named = Object.keys(roles).filter((column) => roles[column] === "description" || roles[column] === "lineTotal"), columns = Object.keys(roles).length > 0 ? named : items.columns;
211
+ return items.rows.flatMap(
212
+ (row, index) => columns.filter((column) => row[column] !== void 0).map((column) => `lineItems.rows.${index}.${column}`)
213
+ );
214
+ }, listAmounts = (key) => Array.isArray(document[key]) ? document[key].map((_, index) => `${key}.${index}.amount`) : [], discount = document.discount, bill = [
215
+ "id",
216
+ "issuedAt",
217
+ "totalAmount",
218
+ "subtotalAmount",
219
+ "taxAmount",
220
+ ...discount === void 0 ? [] : [discount.amount !== void 0 ? "discount.amount" : "discount.percent"],
221
+ "issuer.name",
222
+ "recipient.name",
223
+ "description",
224
+ ...lines()
225
+ ], letter = ["issuedAt", "issuer.name", "recipient.name", "body.content", "signatory.name", "signatory.title"];
226
+ return ({
227
+ invoice: [...bill, "dueAt"],
228
+ receipt: [...bill, "payment.amount", "payment.paidAt"],
229
+ payslip: [
230
+ "id",
231
+ "issuedAt",
232
+ "issuer.name",
233
+ "employee.name",
234
+ "payPeriod.start",
235
+ "payPeriod.end",
236
+ "payDate",
237
+ "gross",
238
+ "taxWithheld",
239
+ "net",
240
+ ...listAmounts("earnings"),
241
+ ...listAmounts("deductions"),
242
+ ...listAmounts("contributions")
243
+ ],
244
+ letter,
245
+ agreement: [...letter, "acceptance.by"]
246
+ }[typeof type == "string" ? type : ""] ?? []).filter(
247
+ (field) => boundValue(document, field) !== void 0
248
+ );
249
+ }, requiredCharacters = (text, markdown) => [...text].map((char) => !/\s/u.test(char) && !(markdown && /[#*_`>-]/.test(char))), isMarkdown = (document, field) => {
250
+ const value = field === "body.content" ? document.body : field === "description" ? document.description : void 0;
251
+ return typeof value == "object" && value !== null && value.format === "markdown";
252
+ }, checkBoundView = (document, view) => {
253
+ const problems = [], texts = view.elements.map((element, index) => ({ element, index })).filter((entry) => entry.element.type === "text");
254
+ for (const field of keyFacts(document)) {
255
+ const binds = texts.filter(({ element }) => element.bind.field === field).map(({ element }) => element.bind), value = boundValue(document, field);
256
+ if (binds.length === 0)
257
+ problems.push({ check: "keyFacts", field, message: `${field} is a key fact and is not shown` });
258
+ else if (value?.kind === "text" && !binds.some((bind) => bind.range === void 0)) {
259
+ const shown = [...value.text].map(() => !1);
260
+ for (const { range } of binds)
261
+ for (let at = range?.[0] ?? 0; at < (range?.[1] ?? 0); at++) shown[at] = !0;
262
+ requiredCharacters(value.text, isMarkdown(document, field)).some((needed, at) => needed && !shown[at]) && problems.push({ check: "keyFacts", field, message: `every word of ${field} is shown` });
263
+ }
264
+ }
265
+ (document.signatory ?? {}).visualSignature !== void 0 && !view.elements.some(({ type }) => type === "signature") && problems.push({ check: "keyFacts", field: "signatory.visualSignature", message: "the signature is shown" });
266
+ for (const { element, index } of texts) {
267
+ const font = view.fonts?.[element.font], value = boundValue(document, element.bind.field);
268
+ if (font === void 0 || value === void 0) continue;
269
+ const text = transformed(writtenValue(value, element.bind), element.transform), spacing = element.letterSpacing ?? 0, smallest = Math.max(element.size * 0.75, 6), width = measured(text, font, Math.min(smallest, element.size), spacing);
270
+ width === void 0 ? problems.push({ check: "shownInFull", element: index, message: "a character has no glyph in its font" }) : width > element.width && problems.push({ check: "shownInFull", element: index, message: "the value does not fit its box" });
271
+ }
272
+ const boxOf = (element) => {
273
+ switch (element.type) {
274
+ case "text":
275
+ case "label":
276
+ return textBox(element, view);
277
+ case "line": {
278
+ const half = element.strokeWidth / 2;
279
+ return {
280
+ left: Math.min(element.from[0], element.to[0]) - half,
281
+ right: Math.max(element.from[0], element.to[0]) + half,
282
+ top: Math.min(element.from[1], element.to[1]) - half,
283
+ bottom: Math.max(element.from[1], element.to[1]) + half
284
+ };
285
+ }
286
+ case "path": {
287
+ const half = element.stroke === void 0 ? 0 : (element.strokeWidth ?? 0) / 2, bounds = boundsOf(polygons(element.d).flat());
288
+ return { left: bounds.left - half, right: bounds.right + half, top: bounds.top - half, bottom: bounds.bottom + half };
289
+ }
290
+ default: {
291
+ const half = element.type === "rect" && element.stroke !== void 0 ? (element.strokeWidth ?? 0) / 2 : 0;
292
+ return {
293
+ left: element.x - half,
294
+ top: element.y - half,
295
+ right: element.x + element.width + half,
296
+ bottom: element.y + element.height + half
297
+ };
298
+ }
299
+ }
300
+ }, boxes = view.elements.map(boxOf), edges = view.elements.map((element) => element.type === "path" ? edgesOf(polygons(element.d)) : []), page = parse(view.page.background ?? "#ffffff"), pageColour = over([255, 255, 255], page);
301
+ let work = 0;
302
+ return view.elements.forEach((element, index) => {
303
+ if (element.type !== "text" && element.type !== "signature") return;
304
+ const box = boxes[index], hidden = (message) => problems.push({ check: "notHidden", element: index, message });
305
+ (box.left < 0 || box.top < 0 || box.right > view.page.width || box.bottom > view.page.height) && hidden("it lies outside the page"), boxes.slice(index + 1).some((later) => overlaps(box, later)) && hidden("an element drawn after it covers it"), view.elements.slice(0, index).some((earlier, at) => earlier.type === "image" && overlaps(box, boxes[at])) && hidden("an image lies under it");
306
+ const ink = over(pageColour, parse(element.colour)), beneath = view.elements.slice(0, index).map((earlier, at) => ({ earlier, at })).filter(
307
+ ({ earlier, at }) => (earlier.type === "rect" || earlier.type === "path") && earlier.fill !== void 0 && overlaps(box, boxes[at])
308
+ ), xs = samples(box.left, box.right);
309
+ let readable = !0;
310
+ for (const y of samples(box.top, box.bottom)) {
311
+ if (work += xs.length * beneath.length, work > CONTRAST_WORK_LIMIT) break;
312
+ const rows = beneath.map(({ earlier, at }) => {
313
+ if (earlier.type === "path")
314
+ return work += edges[at].length, work > CONTRAST_WORK_LIMIT ? void 0 : rowOf(edges[at], y);
315
+ });
316
+ if (work > CONTRAST_WORK_LIMIT) break;
317
+ for (const x of xs) {
318
+ let colour = pageColour;
319
+ if (beneath.forEach(({ earlier }, n) => {
320
+ if (earlier.type !== "rect" && earlier.type !== "path" || earlier.fill === void 0) return;
321
+ const row = rows[n];
322
+ if (!(earlier.type === "rect" ? rectCovers(earlier, [x, y]) : row !== void 0 && rowCovers(row, earlier.fillRule ?? "nonzero", x))) return;
323
+ const [r, g, b, a] = paintAt(earlier.fill, [x, y]);
324
+ colour = over(colour, [r, g, b, a * (earlier.opacity ?? 1)]);
325
+ }), contrast(ink, colour) < 3) {
326
+ readable = !1;
327
+ break;
328
+ }
329
+ }
330
+ if (!readable) break;
331
+ }
332
+ work > CONTRAST_WORK_LIMIT ? hidden("it is too complex to check what lies beneath it") : readable || hidden("its colour has less than 3:1 contrast with what lies beneath it");
333
+ }), problems.length === 0 ? { show: !0 } : { show: !1, problems };
334
+ }, boundViewResultOf = (document) => {
335
+ if (typeof document != "object" || document === null || !("boundView" in document)) return;
336
+ const parsed = BtpBoundViewSchema.safeParse(document.boundView);
337
+ return parsed.success ? checkBoundView(document, parsed.data) : { show: !1, problems: [{ check: "wellFormed", message: "the BoundView is not well formed" }] };
338
+ };
339
+ export {
340
+ CONTRAST_WORK_LIMIT,
341
+ boundViewResultOf,
342
+ checkBoundView,
343
+ writtenValue
344
+ };