@qr-bill/invoice 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2593 @@
1
+ import { ADDRESS_MAX_LENGTH, LABELS, MAX_AMOUNT, isValidCurrency, layoutQRBill, validateBuildingNumber, validateCountry, validateName, validatePostalCode, validateQRBill, validateStreet, validateTown } from "@qr-bill/core";
2
+ import { POINTS_PER_MM, attachTo, registerFonts } from "@qr-bill/pdfkit";
3
+ import PDFDocument from "pdfkit";
4
+ /**
5
+ * Shortens a text with "…" until it fits a width. A text that fits already is returned as is.
6
+ *
7
+ * @param text - The text, on one line.
8
+ * @param width - The width available, in millimetres.
9
+ * @param measure - The width of a text.
10
+ * @returns The text, or its beginning followed by "…"; just "…" when nothing else fits.
11
+ * @example
12
+ * ```ts
13
+ * shorten('Seldwyla', 5, (text) => text.length); // 'Seld…'
14
+ * ```
15
+ */
16
+ function shorten(text, width, measure) {
17
+ if (measure(text) <= width) return text;
18
+ const characters = [...text];
19
+ for (let length = characters.length - 1; length > 0; length--) {
20
+ const candidate = `${characters.slice(0, length).join("").trimEnd()}…`;
21
+ if (measure(candidate) <= width) return candidate;
22
+ }
23
+ return "…";
24
+ }
25
+ /**
26
+ * Breaks a text into lines that fit a width: between words where possible, inside a word longer than the width
27
+ * otherwise. Line feeds start new lines. Beyond the maximum number of lines, the last one is shortened with "…".
28
+ *
29
+ * @param text - The text, which may contain line feeds.
30
+ * @param width - The width available, in millimetres.
31
+ * @param measure - The width of a text.
32
+ * @param maxLines - The maximum number of lines; unlimited by default.
33
+ * @returns The lines, each fitting the width.
34
+ * @example
35
+ * ```ts
36
+ * wrap('Max Muster & Söhne', 10, (text) => text.length); // ['Max Muster', '& Söhne']
37
+ * wrap('Max Muster & Söhne', 10, (text) => text.length, 1); // ['Max Muste…']
38
+ * ```
39
+ */
40
+ function wrap(text, width, measure, maxLines = Number.POSITIVE_INFINITY) {
41
+ const lines = [];
42
+ for (const paragraph of text.split("\n")) {
43
+ let line = "";
44
+ for (const word of paragraph.split(" ").filter((part) => part !== "")) {
45
+ const candidate = line === "" ? word : `${line} ${word}`;
46
+ if (measure(candidate) <= width) {
47
+ line = candidate;
48
+ continue;
49
+ }
50
+ if (line !== "") lines.push(line);
51
+ let rest = [...word];
52
+ while (rest.length > 1 && measure(rest.join("")) > width) {
53
+ let length = 1;
54
+ while (measure(rest.slice(0, length + 1).join("")) <= width) length++;
55
+ lines.push(rest.slice(0, length).join(""));
56
+ rest = rest.slice(length);
57
+ }
58
+ line = rest.join("");
59
+ }
60
+ lines.push(line);
61
+ }
62
+ if (lines.length <= maxLines) return lines;
63
+ const [last = ""] = lines.slice(maxLines - 1, maxLines);
64
+ return [...lines.slice(0, maxLines - 1), shorten(`${last}…`, width, measure)];
65
+ }
66
+ // src/details/date.ts
67
+ /**
68
+ * How dates are written on the invoice: as in Switzerland, in every language.
69
+ *
70
+ * @module
71
+ */
72
+ /**
73
+ * Writes a date as in Switzerland, whatever the language: day, month and year separated by points.
74
+ *
75
+ * @param date - A date written `YYYY-MM-DD`.
76
+ * @returns The date, e.g. `20.11.2026`.
77
+ * @example
78
+ * ```ts
79
+ * formatDate('2026-11-20'); // '20.11.2026'
80
+ * ```
81
+ */
82
+ function formatDate(date) {
83
+ const [year, month, day] = date.split("-");
84
+ return `${day}.${month}.${year}`;
85
+ }
86
+ // src/details/details.ts
87
+ /** The title: its baseline and size. */
88
+ const TITLE_BASELINE = 100;
89
+ const TITLE_SIZE = 16;
90
+ /** The grid of details: where it starts, columns, sizes, and the lines a value may take. */
91
+ const GRID_TOP = 102;
92
+ const GRID_COLUMNS = 5;
93
+ const GRID_COLUMN_WIDTH = 170 / GRID_COLUMNS;
94
+ const LABEL_SIZE = 7.5;
95
+ const VALUE_SIZE = 9;
96
+ const VALUE_LINE = 4;
97
+ const VALUE_MAX_LINES = 2;
98
+ /** The subject: size, line height and lines at most. */
99
+ const SUBJECT_SIZE = 10.5;
100
+ const SUBJECT_LINE = 4.8;
101
+ const SUBJECT_MAX_LINES = 3;
102
+ /** The introduction. */
103
+ const BODY_SIZE$1 = 9;
104
+ const BODY_LINE$1 = 4.2;
105
+ /** The details of the invoice, in the order they are printed. */
106
+ function details(context) {
107
+ const { invoice, labels } = context;
108
+ const optional = (label, value) => value === void 0 ? [] : [{
109
+ label,
110
+ value
111
+ }];
112
+ return [
113
+ ...optional(labels.number, invoice.number),
114
+ {
115
+ label: labels.date,
116
+ value: formatDate(invoice.date)
117
+ },
118
+ ...optional(labels.dueDate, invoice.dueDate === void 0 ? void 0 : formatDate(invoice.dueDate)),
119
+ ...optional(labels.servicePeriod, invoice.servicePeriod),
120
+ ...optional(labels.customerReference, invoice.customerReference),
121
+ ...invoice.extraFields
122
+ ];
123
+ }
124
+ /**
125
+ * Draws the title, the grid of details, the subject and the introduction, from the top of the body of the first
126
+ * page.
127
+ *
128
+ * @param context - The invoice being drawn.
129
+ * @param flow - Where the content goes; afterwards, under the introduction.
130
+ */
131
+ function drawDetails(context, flow) {
132
+ const { pen, invoice, labels, colors } = context;
133
+ pen.text(shorten(invoice.title, 170, pen.measurer(TITLE_SIZE, true)), 20, TITLE_BASELINE, {
134
+ size: TITLE_SIZE,
135
+ bold: true,
136
+ color: colors.title
137
+ });
138
+ const width = 32;
139
+ const labelMeasure = pen.measurer(LABEL_SIZE);
140
+ const valueMeasure = pen.measurer(VALUE_SIZE, true);
141
+ const all = details(context);
142
+ let top = GRID_TOP;
143
+ for (let start = 0; start < all.length; start += GRID_COLUMNS) {
144
+ const row = all.slice(start, start + GRID_COLUMNS).map((detail) => ({
145
+ label: shorten(detail.label, width, labelMeasure),
146
+ lines: wrap(detail.value, width, valueMeasure, VALUE_MAX_LINES)
147
+ }));
148
+ row.forEach((detail, column) => {
149
+ const x = 20 + column * GRID_COLUMN_WIDTH;
150
+ pen.text(detail.label, x, top + 3, {
151
+ size: LABEL_SIZE,
152
+ color: colors.muted
153
+ });
154
+ detail.lines.forEach((line, index) => {
155
+ pen.text(line, x, top + 7 + index * VALUE_LINE, {
156
+ size: VALUE_SIZE,
157
+ bold: true,
158
+ color: colors.text
159
+ });
160
+ });
161
+ });
162
+ top += 4 + Math.max(...row.map((detail) => detail.lines.length)) * VALUE_LINE + 1;
163
+ }
164
+ flow.y = top + 1;
165
+ if (invoice.subject !== void 0) {
166
+ const lines = wrap(`${labels.subject}${invoice.subject}`, 170, pen.measurer(SUBJECT_SIZE, true), SUBJECT_MAX_LINES);
167
+ flow.paragraph(lines, SUBJECT_LINE, (line, baseline) => {
168
+ pen.text(line, 20, baseline, {
169
+ size: SUBJECT_SIZE,
170
+ bold: true,
171
+ color: colors.text
172
+ });
173
+ });
174
+ flow.y += 2;
175
+ }
176
+ if (invoice.introduction !== void 0) {
177
+ const lines = wrap(invoice.introduction, 170, pen.measurer(BODY_SIZE$1));
178
+ flow.paragraph(lines, BODY_LINE$1, (line, baseline) => {
179
+ pen.text(line, 20, baseline, {
180
+ size: BODY_SIZE$1,
181
+ color: colors.text
182
+ });
183
+ });
184
+ flow.y += 2;
185
+ }
186
+ }
187
+ // src/drawing/pen.ts
188
+ /**
189
+ * Drawing on a PDFKit document in millimetres: texts at their baseline, in Liberation Sans without kerning nor
190
+ * ligatures (so that they take the width they were measured with), rectangles, lines and images.
191
+ *
192
+ * @module
193
+ */
194
+ /** Kerning and ligatures off: PDFKit applies them by default, and they change the width of a text. */
195
+ const NO_KERNING = { features: {
196
+ kern: false,
197
+ liga: false
198
+ } };
199
+ /** Draws on a PDFKit document, in millimetres from the top left corner of the page. */
200
+ var Pen = class {
201
+ /** The document. */
202
+ doc;
203
+ /** The names of the regular and bold fonts. */
204
+ fonts;
205
+ /**
206
+ * @param doc - The document.
207
+ * @param fonts - The names of the fonts, as registered by `registerFonts` of `@qr-bill/pdfkit`.
208
+ */
209
+ constructor(doc, fonts) {
210
+ this.doc = doc;
211
+ this.fonts = fonts;
212
+ }
213
+ /** Selects the font and its size. */
214
+ select(size, bold) {
215
+ this.doc.font(bold === true ? this.fonts.bold : this.fonts.regular);
216
+ this.doc.fontSize(size);
217
+ }
218
+ /**
219
+ * The width of a text.
220
+ *
221
+ * @param text - The text.
222
+ * @param size - Its size in points.
223
+ * @param bold - Whether it is bold.
224
+ * @returns The width in millimetres.
225
+ */
226
+ measure(text, size, bold) {
227
+ this.select(size, bold);
228
+ return this.doc.widthOfString(text, NO_KERNING) / POINTS_PER_MM;
229
+ }
230
+ /**
231
+ * The function measuring texts of a size and weight, for `wrap` and `shorten`.
232
+ *
233
+ * @param size - The size in points.
234
+ * @param bold - Whether bold.
235
+ * @returns The measure.
236
+ */
237
+ measurer(size, bold) {
238
+ return (text) => this.measure(text, size, bold);
239
+ }
240
+ /**
241
+ * Writes a text on one line.
242
+ *
243
+ * @param text - The text, which must fit where it goes.
244
+ * @param x - Where it starts, or ends when aligned right.
245
+ * @param y - Its baseline.
246
+ * @param style - Its size, weight, colour and alignment.
247
+ */
248
+ text(text, x, y, style) {
249
+ const start = style.align === "right" ? x - this.measure(text, style.size, style.bold) : x;
250
+ this.select(style.size, style.bold);
251
+ this.doc.fillColor(style.color);
252
+ this.doc.text(text, start * POINTS_PER_MM, y * POINTS_PER_MM, {
253
+ ...NO_KERNING,
254
+ baseline: "alphabetic",
255
+ lineBreak: false
256
+ });
257
+ }
258
+ /**
259
+ * Fills a rectangle.
260
+ *
261
+ * @param x - Left edge.
262
+ * @param y - Top edge.
263
+ * @param width - Width.
264
+ * @param height - Height.
265
+ * @param color - Colour, `#RRGGBB`.
266
+ */
267
+ rect(x, y, width, height, color) {
268
+ const k = POINTS_PER_MM;
269
+ this.doc.rect(x * k, y * k, width * k, height * k);
270
+ this.doc.fill(color);
271
+ }
272
+ /**
273
+ * Draws a horizontal line.
274
+ *
275
+ * @param x1 - Start.
276
+ * @param x2 - End.
277
+ * @param y - Height.
278
+ * @param width - Thickness in points.
279
+ * @param color - Colour, `#RRGGBB`.
280
+ */
281
+ line(x1, x2, y, width, color) {
282
+ const k = POINTS_PER_MM;
283
+ this.doc.moveTo(x1 * k, y * k);
284
+ this.doc.lineTo(x2 * k, y * k);
285
+ this.doc.lineWidth(width);
286
+ this.doc.stroke(color);
287
+ }
288
+ /**
289
+ * Draws an image fitted in a box, keeping its proportions, in the top left corner of the box.
290
+ *
291
+ * @param bytes - A PNG or JPEG file.
292
+ * @param x - Left edge of the box.
293
+ * @param y - Top edge of the box.
294
+ * @param width - Width of the box.
295
+ * @param height - Height of the box.
296
+ */
297
+ image(bytes, x, y, width, height) {
298
+ const k = POINTS_PER_MM;
299
+ const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
300
+ this.doc.image(buffer, x * k, y * k, { fit: [width * k, height * k] });
301
+ }
302
+ };
303
+ // src/parties/address.ts
304
+ /**
305
+ * The name of a country in a language, from the data of the JavaScript runtime (`Intl.DisplayNames`); the code
306
+ * itself when the runtime does not know it.
307
+ *
308
+ * @param code - A two-letter ISO 3166-1 code, in upper case.
309
+ * @param language - The language of the name.
310
+ * @returns The name of the country.
311
+ * @example
312
+ * ```ts
313
+ * countryName('DE', 'fr'); // 'Allemagne'
314
+ * countryName('CH', 'rm'); // 'Svizra'
315
+ * ```
316
+ */
317
+ function countryName(code, language) {
318
+ return String(new Intl.DisplayNames([language], {
319
+ type: "region",
320
+ fallback: "code"
321
+ }).of(code));
322
+ }
323
+ /**
324
+ * The line of the street and the building number, when there is one.
325
+ *
326
+ * @param address - An address.
327
+ * @returns `"Musterstrasse 123"`, or `undefined` without street nor number.
328
+ * @example
329
+ * ```ts
330
+ * streetLine({ name: 'A', street: 'Musterstrasse', buildingNumber: '123', postalCode: '8000', town: 'Seldwyla', country: 'CH' }); // 'Musterstrasse 123'
331
+ * ```
332
+ */
333
+ function streetLine(address) {
334
+ const line = [address.street, address.buildingNumber].filter((part) => part !== void 0).join(" ");
335
+ return line === "" ? void 0 : line;
336
+ }
337
+ /**
338
+ * The line of the postal code and the town.
339
+ *
340
+ * @param address - An address.
341
+ * @returns `"8000 Seldwyla"`.
342
+ */
343
+ function townLine(address) {
344
+ return `${address.postalCode} ${address.town}`;
345
+ }
346
+ // src/header/address-window.ts
347
+ /**
348
+ * The window: left edge and width of its texts on the left and on the right, top; the sender line, its rule and the
349
+ * address under it. On the right, the texts end at the right edge of the content.
350
+ */
351
+ const WINDOW_LEFT = {
352
+ x: 25,
353
+ width: 85
354
+ };
355
+ const WINDOW_RIGHT = {
356
+ x: 118,
357
+ width: 72
358
+ };
359
+ const SENDER_SIZE = 7;
360
+ const ADDRESS_SIZE = 10;
361
+ const ADDRESS_LINE = 4.4;
362
+ /**
363
+ * Draws the recipient in the window of the envelope: the sender on one line, a rule, then the address, its name in
364
+ * bold on two lines at most, its country when it is not the issuer's.
365
+ *
366
+ * @param context - The invoice being drawn.
367
+ */
368
+ function drawAddressWindow(context) {
369
+ const { pen, invoice, colors, foreign } = context;
370
+ const { issuer, recipient, language } = invoice;
371
+ const { x, width } = invoice.addressWindow === "right" ? WINDOW_RIGHT : WINDOW_LEFT;
372
+ const sender = [
373
+ issuer.name,
374
+ streetLine(issuer),
375
+ townLine(issuer),
376
+ foreign ? countryName(issuer.country, language) : void 0
377
+ ].filter((part) => part !== void 0).join(", ");
378
+ pen.text(shorten(sender, width, pen.measurer(SENDER_SIZE)), x, 49.5, {
379
+ size: SENDER_SIZE,
380
+ color: colors.muted
381
+ });
382
+ pen.line(x, x + width, 51, .3, colors.muted);
383
+ const measure = pen.measurer(ADDRESS_SIZE);
384
+ const plain = (text) => text === void 0 ? [] : [{
385
+ text: shorten(text, width, measure),
386
+ bold: false
387
+ }];
388
+ [
389
+ ...plain(recipient.salutation),
390
+ ...wrap(recipient.name, width, pen.measurer(ADDRESS_SIZE, true), 2).map((text) => ({
391
+ text,
392
+ bold: true
393
+ })),
394
+ ...recipient.extraLines.flatMap(plain),
395
+ ...plain(streetLine(recipient)),
396
+ ...plain(townLine(recipient)),
397
+ ...plain(foreign ? countryName(recipient.country, language) : void 0)
398
+ ].forEach((line, index) => {
399
+ pen.text(line.text, x, 58 + index * ADDRESS_LINE, {
400
+ size: ADDRESS_SIZE,
401
+ bold: line.bold,
402
+ color: colors.text
403
+ });
404
+ });
405
+ }
406
+ // src/header/continued-header.ts
407
+ /** Baseline and size of its texts. */
408
+ const CONTINUED_BASELINE = 18;
409
+ const CONTINUED_SIZE = 9;
410
+ /**
411
+ * Draws the short header of the pages after the first: the name of the issuer on the left, the title and number of
412
+ * the invoice on the right.
413
+ *
414
+ * @param context - The invoice being drawn.
415
+ */
416
+ function drawContinuedHeader(context) {
417
+ const { pen, invoice, colors } = context;
418
+ const half = 83;
419
+ const name = shorten(invoice.issuer.name, half, pen.measurer(CONTINUED_SIZE, true));
420
+ pen.text(name, 20, CONTINUED_BASELINE, {
421
+ size: CONTINUED_SIZE,
422
+ bold: true,
423
+ color: colors.text
424
+ });
425
+ const title = [invoice.title, invoice.number].filter((part) => part !== void 0).join(" ");
426
+ pen.text(shorten(title, half, pen.measurer(CONTINUED_SIZE)), 190, CONTINUED_BASELINE, {
427
+ size: CONTINUED_SIZE,
428
+ color: colors.muted,
429
+ align: "right"
430
+ });
431
+ }
432
+ // src/header/issuer.ts
433
+ /** The details of the issuer: width, first baseline in each layout, line height, sizes. */
434
+ const ISSUER_WIDTH = 72;
435
+ const ISSUER_TOP_RIGHT_COLUMN = 18;
436
+ const ISSUER_TOP_UNDER_LETTERHEAD = 40;
437
+ const ISSUER_LINE = 3.8;
438
+ const ISSUER_SIZE = 8.5;
439
+ const ISSUER_NAME_SIZE = 9;
440
+ /** The lines of the details of the issuer: its name when a logo stands for it, its address and its contacts. */
441
+ function issuerLines(context) {
442
+ const { pen, invoice, labels, foreign } = context;
443
+ const { issuer } = invoice;
444
+ const name = issuer.logo === void 0 ? [] : wrap(issuer.name, ISSUER_WIDTH, pen.measurer(ISSUER_NAME_SIZE, true), 2).map((text) => ({
445
+ text,
446
+ bold: true
447
+ }));
448
+ const uid = issuer.uid === void 0 ? [] : [issuer.vatRegistered ? `${issuer.uid} ${labels.vatNumberSuffix}` : issuer.uid];
449
+ const others = [
450
+ ...issuer.extraLines,
451
+ streetLine(issuer),
452
+ townLine(issuer),
453
+ foreign ? countryName(issuer.country, invoice.language) : void 0,
454
+ ...issuer.phones,
455
+ issuer.email,
456
+ issuer.contact,
457
+ ...uid
458
+ ].filter((text) => text !== void 0);
459
+ const measure = pen.measurer(ISSUER_SIZE);
460
+ return [...name, ...others.map((text) => ({
461
+ text: shorten(text, ISSUER_WIDTH, measure),
462
+ bold: false
463
+ }))];
464
+ }
465
+ /**
466
+ * Draws the details of the issuer: in the right column, aligned right, with the window on the left; under the
467
+ * letterhead with the window on the right.
468
+ *
469
+ * @param context - The invoice being drawn.
470
+ */
471
+ function drawIssuer(context) {
472
+ const { pen, invoice, colors } = context;
473
+ const left = invoice.addressWindow === "right";
474
+ const top = left ? ISSUER_TOP_UNDER_LETTERHEAD : ISSUER_TOP_RIGHT_COLUMN;
475
+ issuerLines(context).forEach((line, index) => {
476
+ const style = {
477
+ size: line.bold ? ISSUER_NAME_SIZE : ISSUER_SIZE,
478
+ bold: line.bold,
479
+ color: colors.text,
480
+ align: left ? "left" : "right"
481
+ };
482
+ pen.text(line.text, left ? 20 : 190, top + index * ISSUER_LINE, style);
483
+ });
484
+ }
485
+ // src/invoice/errors.ts
486
+ /**
487
+ * Thrown by {@link createInvoicePDF}. Lists every problem found, not just the first.
488
+ *
489
+ * @example
490
+ * ```ts
491
+ * try {
492
+ * await createInvoicePDF(input);
493
+ * } catch (error) {
494
+ * if (error instanceof InvoiceValidationError) {
495
+ * error.issues; // [{ code: 'invalid_uid', path: ['issuer', 'uid'], message: '…' }, …]
496
+ * }
497
+ * }
498
+ * ```
499
+ */
500
+ var InvoiceValidationError = class extends Error {
501
+ /** Always "InvoiceValidationError". */
502
+ name = "InvoiceValidationError";
503
+ /** Every problem found. */
504
+ issues;
505
+ /**
506
+ * @param issues - The problems found; the message of the error summarizes them.
507
+ */
508
+ constructor(issues) {
509
+ const summary = issues.map((issue) => issue.path.length > 0 ? `${issue.path.join(".")}: ${issue.message}` : issue.message).join("; ");
510
+ super(`Invalid invoice: ${summary}`);
511
+ this.issues = issues;
512
+ }
513
+ };
514
+ // src/header/letterhead.ts
515
+ /** The box of the logo, whose proportions are kept. */
516
+ const LOGO = {
517
+ x: 20,
518
+ y: 15,
519
+ width: 50,
520
+ height: 18
521
+ };
522
+ /**
523
+ * The name of the issuer, without a logo: the sizes tried until it fits on two lines, the smallest one, shortened
524
+ * when even it does not fit, and the width.
525
+ */
526
+ const LETTERHEAD_SIZES = [16, 14];
527
+ const LETTERHEAD_SMALLEST_SIZE = 12;
528
+ const LETTERHEAD_WIDTH = 95;
529
+ /**
530
+ * Draws the logo, or the name of the issuer in large type: on two lines at most, in a smaller size when needed,
531
+ * shortened with "…" as a last resort.
532
+ *
533
+ * @param context - The invoice being drawn.
534
+ * @throws {InvoiceValidationError} When the logo is not a PNG or JPEG file PDFKit can read.
535
+ */
536
+ function drawLetterhead(context) {
537
+ const { pen, invoice, colors } = context;
538
+ const { logo, name } = invoice.issuer;
539
+ if (logo !== void 0) {
540
+ try {
541
+ pen.image(logo.bytes, LOGO.x, LOGO.y, LOGO.width, LOGO.height);
542
+ } catch (error) {
543
+ throw new InvoiceValidationError([{
544
+ code: "unsupported_logo",
545
+ path: ["issuer", "logo"],
546
+ message: `The logo could not be read (${String(error)})`
547
+ }]);
548
+ }
549
+ return;
550
+ }
551
+ const size = LETTERHEAD_SIZES.find((candidate) => wrap(name, LETTERHEAD_WIDTH, pen.measurer(candidate, true)).length <= 2) ?? LETTERHEAD_SMALLEST_SIZE;
552
+ const lineHeight = size * .41;
553
+ wrap(name, LETTERHEAD_WIDTH, pen.measurer(size, true), 2).forEach((line, index) => {
554
+ pen.text(line, 20, LOGO.y + size * .32 + index * lineHeight, {
555
+ size,
556
+ bold: true,
557
+ color: colors.title
558
+ });
559
+ });
560
+ }
561
+ // src/amounts/money.ts
562
+ /**
563
+ * Reads a decimal number with at most a given number of decimals, as an integer in that unit: `"12.5"` with 2
564
+ * decimals is `1250n`. A string (`"-12.50"`, surrounding spaces ignored) or a number is accepted; a number only when
565
+ * its decimal form has at most that many decimals, so that `0.1 + 0.2` is refused.
566
+ *
567
+ * @param value - The number as given.
568
+ * @param decimals - The number of decimals allowed, which is also the scale of the result.
569
+ * @returns The scaled integer, or `undefined` when the value is not such a number.
570
+ * @example
571
+ * ```ts
572
+ * parseDecimal('-12.5', 2); // -1250n
573
+ * parseDecimal(0.1 + 0.2, 2); // undefined: 0.30000000000000004
574
+ * ```
575
+ */
576
+ function parseDecimal(value, decimals) {
577
+ let text;
578
+ if (typeof value === "string") text = value.trim();
579
+ else if (typeof value === "number" && Number.isFinite(value)) text = String(value);
580
+ else return void 0;
581
+ const match = /^(-?)(\d+)(?:\.(\d+))?$/.exec(text);
582
+ if (match === null) return void 0;
583
+ const [, sign, whole, fraction = ""] = match;
584
+ if (fraction.length > decimals) return void 0;
585
+ const units = BigInt(whole + fraction.padEnd(decimals, "0"));
586
+ return sign === "-" ? -units : units;
587
+ }
588
+ /**
589
+ * Divides two integers, rounding half away from zero (commercial rounding): 2.5 gives 3 and -2.5 gives -3.
590
+ *
591
+ * @param numerator - The dividend.
592
+ * @param denominator - The divisor, not zero.
593
+ * @returns The rounded quotient.
594
+ * @example
595
+ * ```ts
596
+ * roundDiv(5n, 2n); // 3n
597
+ * roundDiv(-5n, 2n); // -3n
598
+ * ```
599
+ */
600
+ function roundDiv(numerator, denominator) {
601
+ const quotient = numerator / denominator;
602
+ const remainder = numerator % denominator;
603
+ if (2n * (remainder < 0n ? -remainder : remainder) < (denominator < 0n ? -denominator : denominator)) return quotient;
604
+ return numerator < 0n === denominator < 0n ? quotient + 1n : quotient - 1n;
605
+ }
606
+ /**
607
+ * Writes a scaled integer as a decimal string with exactly that many decimals.
608
+ *
609
+ * @param units - The integer, e.g. cents.
610
+ * @param scale - The number of decimals.
611
+ * @returns The decimal string, with `-` for a negative number.
612
+ * @example
613
+ * ```ts
614
+ * toDecimal(-9000n, 2); // '-90.00'
615
+ * ```
616
+ */
617
+ function toDecimal(units, scale) {
618
+ const sign = units < 0n ? "-" : "";
619
+ const digits = (units < 0n ? -units : units).toString().padStart(scale + 1, "0");
620
+ return scale === 0 ? `${sign}${digits}` : `${sign}${digits.slice(0, -scale)}.${digits.slice(-scale)}`;
621
+ }
622
+ /**
623
+ * Writes a scaled integer as a decimal string without trailing zeros after the decimal point, at least
624
+ * `minDecimals` decimals being kept.
625
+ *
626
+ * @param units - The integer.
627
+ * @param scale - Its number of decimals.
628
+ * @param minDecimals - Decimals always kept; 0 by default.
629
+ * @returns The shortest decimal string.
630
+ * @example
631
+ * ```ts
632
+ * toShortDecimal(810n, 2); // '8.1'
633
+ * toShortDecimal(1250000n, 4, 2); // '125.00'
634
+ * ```
635
+ */
636
+ function toShortDecimal(units, scale, minDecimals = 0) {
637
+ const full = toDecimal(units, scale);
638
+ if (scale === 0) return full;
639
+ const [whole, fraction] = full.split(".");
640
+ const kept = fraction.replace(/0+$/, "").padEnd(minDecimals, "0");
641
+ return kept === "" ? whole : `${whole}.${kept}`;
642
+ }
643
+ /**
644
+ * Writes a decimal number as it is printed on the invoice: thousands separated by a space (as on the payment part)
645
+ * or by an apostrophe, the decimals kept as they are. Serves the amounts, the quantities and the unit prices.
646
+ *
647
+ * @param amount - A decimal string, e.g. `"-1234.50"` or `"1500"`.
648
+ * @param format - `space` or `apostrophe`.
649
+ * @returns The number as printed.
650
+ * @example
651
+ * ```ts
652
+ * formatMoney('-1234.50', 'space'); // '-1 234.50'
653
+ * formatMoney('1234567.00', 'apostrophe'); // "1'234'567.00"
654
+ * formatMoney('1500', 'space'); // '1 500'
655
+ * ```
656
+ */
657
+ function formatMoney(amount, format) {
658
+ const negative = amount.startsWith("-");
659
+ const [whole = "", ...fraction] = (negative ? amount.slice(1) : amount).split(".");
660
+ const separator = format === "space" ? " " : "'";
661
+ const grouped = whole.replace(/\B(?=(\d{3})+$)/g, separator);
662
+ return [`${negative ? "-" : ""}${grouped}`, ...fraction].join(".");
663
+ }
664
+ /** The largest amount, in centimes: the largest amount of a QR-bill, 999 999 999.99. */
665
+ const MAX_CENTIMES = 99999999999n;
666
+ /**
667
+ * The amount of a line in centimes: its own amount, or quantity × unit price; `undefined` for a line of text.
668
+ *
669
+ * @param line - The line, read.
670
+ * @returns The amount in centimes.
671
+ */
672
+ function lineAmount(line) {
673
+ if (line.amount !== void 0) return line.amount;
674
+ if (line.unitPrice === void 0) return void 0;
675
+ return roundDiv((line.quantity ?? 10n ** BigInt(3)) * line.unitPrice, 10n ** BigInt(5));
676
+ }
677
+ /**
678
+ * Computes the totals of lines already read. The result is in centimes; see {@link computeInvoiceTotals} for the
679
+ * rules.
680
+ *
681
+ * @param lines - The lines, read.
682
+ * @param options - Prices with or without VAT, rounding to 5 centimes.
683
+ * @returns The amount of each line, the subtotal, the VAT per rate, the rounding and the total.
684
+ */
685
+ function computeTotals(lines, options) {
686
+ const amounts = lines.map(lineAmount);
687
+ const bases = /* @__PURE__ */ new Map();
688
+ let subtotal = 0n;
689
+ lines.forEach((line, index) => {
690
+ const amount = amounts[index] ?? 0n;
691
+ subtotal += amount;
692
+ if (line.vatRate !== void 0) bases.set(line.vatRate, (bases.get(line.vatRate) ?? 0n) + amount);
693
+ });
694
+ const hundredPercent = 100n * 10n ** BigInt(2);
695
+ const vat = [...bases].sort(([a], [b]) => a < b ? 1 : -1).map(([rate, base]) => ({
696
+ rate,
697
+ base,
698
+ amount: roundDiv(base * rate, options.pricesIncludeVAT === true ? hundredPercent + rate : hundredPercent)
699
+ }));
700
+ const vatTotal = vat.reduce((total, { amount }) => total + amount, 0n);
701
+ const total = options.pricesIncludeVAT === true ? subtotal : subtotal + vatTotal;
702
+ if (options.roundTo5Centimes !== true) return {
703
+ lines: amounts,
704
+ subtotal,
705
+ vat,
706
+ total
707
+ };
708
+ const rounded = roundDiv(total, 5n) * 5n;
709
+ return {
710
+ lines: amounts,
711
+ subtotal,
712
+ vat,
713
+ rounding: rounded - total,
714
+ total: rounded
715
+ };
716
+ }
717
+ /**
718
+ * Writes totals in centimes as decimal strings.
719
+ *
720
+ * @param totals - The result of {@link computeTotals}.
721
+ * @returns The totals as printed in an {@link Invoice}.
722
+ */
723
+ function totalsToDecimals(totals) {
724
+ const vat = totals.vat.map(({ rate, base, amount }) => ({
725
+ rate: toShortDecimal(rate, 2),
726
+ base: toDecimal(base, 2),
727
+ amount: toDecimal(amount, 2)
728
+ }));
729
+ return {
730
+ lines: totals.lines.map((amount) => amount === void 0 ? void 0 : toDecimal(amount, 2)),
731
+ subtotal: toDecimal(totals.subtotal, 2),
732
+ vat,
733
+ ...totals.rounding !== void 0 && { rounding: toDecimal(totals.rounding, 2) },
734
+ total: toDecimal(totals.total, 2)
735
+ };
736
+ }
737
+ /** Reads one number of a line, or throws a RangeError naming it. */
738
+ function readNumber$1(value, decimals, name, index) {
739
+ if (value === void 0 || value === null || value === "") return void 0;
740
+ const parsed = parseDecimal(value, decimals);
741
+ if (parsed === void 0) throw new RangeError(`items[${index}].${name}: expected a number with at most ${decimals} decimals`);
742
+ return parsed;
743
+ }
744
+ /**
745
+ * Computes the amounts of an invoice from its lines, without the rest of the invoice: useful to show the totals
746
+ * while a form is being filled.
747
+ *
748
+ * - The amount of a line is its `amount`, or its `quantity` (1 when absent) × `unitPrice`, rounded to the centime;
749
+ * a line with neither is a line of text.
750
+ * - The VAT is computed per rate on the sum of the lines at that rate. Prices exclude VAT by default: it is added to
751
+ * the total. With `pricesIncludeVAT`, the VAT is the part of the gross amount that is VAT.
752
+ * - Roundings are commercial (half away from zero), to the centime; the total is rounded to 5 centimes with
753
+ * `roundTo5Centimes`.
754
+ *
755
+ * @param items - The lines of the invoice.
756
+ * @param options - Prices with or without VAT, rounding to 5 centimes.
757
+ * @returns The amount of each line, the subtotal, the VAT per rate (highest rate first), the rounding and the
758
+ * total, as decimal strings.
759
+ * @throws {RangeError} When a quantity, price, rate or amount is not a number with the decimals allowed.
760
+ * @example
761
+ * ```ts
762
+ * computeInvoiceTotals([{ description: 'Advice', quantity: 6, unitPrice: '150', vatRate: '8.1' }]).total; // '972.90'
763
+ * ```
764
+ */
765
+ function computeInvoiceTotals(items, options = {}) {
766
+ return totalsToDecimals(computeTotals(items.map((item, index) => ({
767
+ quantity: readNumber$1(item.quantity, 3, "quantity", index),
768
+ unitPrice: readNumber$1(item.unitPrice, 4, "unitPrice", index),
769
+ vatRate: readNumber$1(item.vatRate, 2, "vatRate", index),
770
+ amount: readNumber$1(item.amount, 2, "amount", index)
771
+ })), options));
772
+ }
773
+ // src/fields/fields.ts
774
+ /** The problems found so far, in the order of the fields. */
775
+ var IssueList = class {
776
+ /** The problems. */
777
+ list = [];
778
+ /**
779
+ * Reports a problem.
780
+ *
781
+ * @param code - What the problem is.
782
+ * @param path - Where it is.
783
+ * @param message - An explanation in English.
784
+ */
785
+ add(code, path, message) {
786
+ this.list.push({
787
+ code,
788
+ path,
789
+ message
790
+ });
791
+ }
792
+ };
793
+ /** Characters that never belong in a line: control characters and line separators. */
794
+ const CONTROL = /[\p{Cc}\u2028\u2029]/u;
795
+ /** The same, except the line feed, which separates the lines of a paragraph. */
796
+ const CONTROL_EXCEPT_NEWLINE = /(?!\n)[\p{Cc}\u2028\u2029]/u;
797
+ /**
798
+ * Whether a value is absent: `undefined` or `null`.
799
+ *
800
+ * @param value - Any value.
801
+ * @returns `true` when absent.
802
+ */
803
+ function isAbsent(value) {
804
+ return value === void 0 || value === null;
805
+ }
806
+ /**
807
+ * Whether a value is absent or a blank string: what a required field must not be.
808
+ *
809
+ * @param value - Any value.
810
+ * @returns `true` when absent or blank.
811
+ */
812
+ function isBlank(value) {
813
+ return isAbsent(value) || typeof value === "string" && value.trim() === "";
814
+ }
815
+ /**
816
+ * Whether a value is a plain object (not an array, nor the bytes of a file).
817
+ *
818
+ * @param value - Any value.
819
+ * @returns `true` for an object whose properties can be read.
820
+ */
821
+ function isRecord(value) {
822
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Uint8Array);
823
+ }
824
+ /**
825
+ * Reads an object that must be present.
826
+ *
827
+ * @param value - The value.
828
+ * @param path - Where it is.
829
+ * @param issues - Where problems are reported: `required` or `invalid_type`.
830
+ * @returns The object, or `undefined`.
831
+ */
832
+ function readRecord(value, path, issues) {
833
+ if (isRecord(value)) return value;
834
+ if (isAbsent(value)) issues.add("required", path, "Required");
835
+ else issues.add("invalid_type", path, "Expected an object");
836
+ }
837
+ /**
838
+ * Reads a string, normalized; blank counts as absent.
839
+ *
840
+ * @param value - The value.
841
+ * @param path - Where it is.
842
+ * @param issues - Where problems are reported: `invalid_type`.
843
+ * @returns The text, or `undefined` when absent, blank or not a string.
844
+ */
845
+ function readString(value, path, issues) {
846
+ if (isAbsent(value)) return void 0;
847
+ if (typeof value !== "string") {
848
+ issues.add("invalid_type", path, `Expected a string, received ${typeof value}`);
849
+ return;
850
+ }
851
+ const text = value.normalize("NFC").trim();
852
+ return text === "" ? void 0 : text;
853
+ }
854
+ /** Reports a text longer than its limit, counted in Unicode code points. */
855
+ function checkLength(text, path, max, issues) {
856
+ const length = [...text].length;
857
+ if (length <= max) return true;
858
+ issues.add("too_long", path, `At most ${max} characters, received ${length}`);
859
+ return false;
860
+ }
861
+ /**
862
+ * Reads a text on one line.
863
+ *
864
+ * @param value - The value.
865
+ * @param path - Where it is.
866
+ * @param max - Its maximum length.
867
+ * @param issues - Where problems are reported: `required`, `invalid_type`, `invalid_characters`, `too_long`.
868
+ * @param required - Whether a blank value is a problem.
869
+ * @returns The text, or `undefined`.
870
+ */
871
+ function readLine(value, path, max, issues, required = false) {
872
+ if (required && isBlank(value)) {
873
+ issues.add("required", path, "Required");
874
+ return;
875
+ }
876
+ const text = readString(value, path, issues);
877
+ if (text === void 0) return void 0;
878
+ if (CONTROL.test(text)) {
879
+ issues.add("invalid_characters", path, "Line breaks and control characters are not allowed in this field");
880
+ return;
881
+ }
882
+ return checkLength(text, path, max, issues) ? text : void 0;
883
+ }
884
+ /**
885
+ * Reads a text of several lines separated by line feeds; `\r\n` and `\r` become `\n`.
886
+ *
887
+ * @param value - The value.
888
+ * @param path - Where it is.
889
+ * @param max - Its maximum length, line feeds included.
890
+ * @param maxLines - Its maximum number of lines.
891
+ * @param issues - Where problems are reported: `required`, `invalid_type`, `invalid_characters`, `too_long`,
892
+ * `too_many_lines`.
893
+ * @param required - Whether a blank value is a problem.
894
+ * @returns The text, or `undefined`.
895
+ */
896
+ function readParagraph(value, path, max, maxLines, issues, required = false) {
897
+ if (required && isBlank(value)) {
898
+ issues.add("required", path, "Required");
899
+ return;
900
+ }
901
+ const raw = readString(value, path, issues);
902
+ if (raw === void 0) return void 0;
903
+ const text = raw.replace(/\r\n?/g, "\n");
904
+ if (CONTROL_EXCEPT_NEWLINE.test(text)) {
905
+ issues.add("invalid_characters", path, "Control characters are not allowed in this field");
906
+ return;
907
+ }
908
+ if (!checkLength(text, path, max, issues)) return void 0;
909
+ const lines = text.split("\n").length;
910
+ if (lines > maxLines) {
911
+ issues.add("too_many_lines", path, `At most ${maxLines} lines, received ${lines}`);
912
+ return;
913
+ }
914
+ return text;
915
+ }
916
+ /**
917
+ * Reads a list; absent counts as empty.
918
+ *
919
+ * @param value - The value.
920
+ * @param path - Where it is.
921
+ * @param max - Its maximum number of entries.
922
+ * @param issues - Where problems are reported: `invalid_type`, `too_many`.
923
+ * @returns The entries, unchecked; empty when the list is absent or invalid.
924
+ */
925
+ function readList(value, path, max, issues) {
926
+ if (isAbsent(value)) return [];
927
+ if (!Array.isArray(value)) {
928
+ issues.add("invalid_type", path, "Expected an array");
929
+ return [];
930
+ }
931
+ if (value.length > max) {
932
+ issues.add("too_many", path, `At most ${max} entries, received ${value.length}`);
933
+ return [];
934
+ }
935
+ return value;
936
+ }
937
+ /**
938
+ * Reads a list of texts on one line, blank entries being left out.
939
+ *
940
+ * @param value - The value.
941
+ * @param path - Where it is.
942
+ * @param maxLines - The maximum number of entries.
943
+ * @param max - The maximum length of an entry.
944
+ * @param issues - Where problems are reported.
945
+ * @returns The texts.
946
+ */
947
+ function readLines(value, path, maxLines, max, issues) {
948
+ return readList(value, path, maxLines, issues).flatMap((entry, index) => {
949
+ const line = readLine(entry, [...path, index], max, issues);
950
+ return line === void 0 ? [] : [line];
951
+ });
952
+ }
953
+ /**
954
+ * Reads a boolean.
955
+ *
956
+ * @param value - The value.
957
+ * @param path - Where it is.
958
+ * @param issues - Where problems are reported: `invalid_type`.
959
+ * @returns The boolean, or `undefined` when absent or invalid.
960
+ */
961
+ function readBoolean(value, path, issues) {
962
+ if (isAbsent(value)) return void 0;
963
+ if (typeof value === "boolean") return value;
964
+ issues.add("invalid_type", path, `Expected a boolean, received ${typeof value}`);
965
+ }
966
+ /**
967
+ * Reads one value among a few allowed.
968
+ *
969
+ * @param value - The value.
970
+ * @param path - Where it is.
971
+ * @param options - The values allowed.
972
+ * @param issues - Where problems are reported: `invalid_option`.
973
+ * @returns The value, or `undefined` when absent or not allowed.
974
+ */
975
+ function readOption(value, path, options, issues) {
976
+ if (isAbsent(value)) return void 0;
977
+ if (options.includes(value)) return value;
978
+ issues.add("invalid_option", path, `Expected one of ${options.map((option) => `"${option}"`).join(", ")}`);
979
+ }
980
+ /** Whether a year, a month (1 to 12) and a day exist in the calendar: not the 30 February. */
981
+ function isCalendarDate(year, month, day) {
982
+ const date = new Date(Date.UTC(year, month - 1, day));
983
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
984
+ }
985
+ /**
986
+ * Reads a calendar date written `YYYY-MM-DD`.
987
+ *
988
+ * @param value - The value.
989
+ * @param path - Where it is.
990
+ * @param required - Whether a blank value is a problem.
991
+ * @param issues - Where problems are reported: `required`, `invalid_type`, `invalid_date`.
992
+ * @returns The date as written, or `undefined`.
993
+ */
994
+ function readDate(value, path, required, issues) {
995
+ if (required && isBlank(value)) {
996
+ issues.add("required", path, "Required");
997
+ return;
998
+ }
999
+ const text = readString(value, path, issues);
1000
+ if (text === void 0) return void 0;
1001
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
1002
+ if (match === null || !isCalendarDate(Number(match[1]), Number(match[2]), Number(match[3]))) {
1003
+ issues.add("invalid_date", path, `Expected a date written YYYY-MM-DD, received ${JSON.stringify(text)}`);
1004
+ return;
1005
+ }
1006
+ return text;
1007
+ }
1008
+ /**
1009
+ * Reads a decimal number with at most a given number of decimals, within ±limit; blank counts as absent.
1010
+ *
1011
+ * @param value - The value, a string or a number.
1012
+ * @param path - Where it is.
1013
+ * @param decimals - The decimals allowed, which are also the unit of the result.
1014
+ * @param limit - The largest magnitude allowed, in that unit.
1015
+ * @param issues - Where problems are reported: `invalid_number`, `out_of_range`.
1016
+ * @returns The number as an integer of that unit, or `undefined`.
1017
+ */
1018
+ function readNumber(value, path, decimals, limit, issues) {
1019
+ if (isBlank(value)) return void 0;
1020
+ const parsed = parseDecimal(value, decimals);
1021
+ if (parsed === void 0) {
1022
+ issues.add("invalid_number", path, `Expected a number with at most ${decimals} decimals, e.g. "12.50"`);
1023
+ return;
1024
+ }
1025
+ if (parsed < -limit || parsed > limit) {
1026
+ issues.add("out_of_range", path, `Expected a number within ±${toShortDecimal(limit, decimals)}`);
1027
+ return;
1028
+ }
1029
+ return parsed;
1030
+ }
1031
+ /**
1032
+ * Freezes an object and everything in it, except the bytes of a logo, which cannot be frozen.
1033
+ *
1034
+ * @param value - The object.
1035
+ * @returns The same object, frozen.
1036
+ */
1037
+ function deepFreeze(value) {
1038
+ if (typeof value === "object" && value !== null && !(value instanceof Uint8Array)) {
1039
+ for (const nested of Object.values(value)) deepFreeze(nested);
1040
+ Object.freeze(value);
1041
+ }
1042
+ return value;
1043
+ }
1044
+ // src/invoice/limits.ts
1045
+ /**
1046
+ * Maximum lengths of the fields of an invoice. They are chosen so that each text fits in its place on the page:
1047
+ * a longer text wraps within its zone, and is shortened with "…" only as a last resort. The addresses keep the
1048
+ * limits of the QR-bill, since they are also printed on the payment part.
1049
+ *
1050
+ * @module
1051
+ */
1052
+ /**
1053
+ * The limits of each field, for the `maxlength` of a form. A longer value is reported by {@link validateInvoice}
1054
+ * as `too_long`, `too_many` or `too_many_lines`.
1055
+ *
1056
+ * @example
1057
+ * ```ts
1058
+ * INVOICE_LIMITS.issuer.phones; // 2
1059
+ * ```
1060
+ */
1061
+ const INVOICE_LIMITS = {
1062
+ title: 35,
1063
+ number: 35,
1064
+ servicePeriod: 50,
1065
+ customerReference: 35,
1066
+ extraFields: 3,
1067
+ extraFieldLabel: 25,
1068
+ extraFieldValue: 50,
1069
+ subject: 140,
1070
+ introduction: 1e3,
1071
+ introductionLines: 10,
1072
+ closing: 1e3,
1073
+ closingLines: 10,
1074
+ issuer: {
1075
+ name: ADDRESS_MAX_LENGTH.name,
1076
+ street: ADDRESS_MAX_LENGTH.street,
1077
+ buildingNumber: ADDRESS_MAX_LENGTH.buildingNumber,
1078
+ postalCode: ADDRESS_MAX_LENGTH.postalCode,
1079
+ town: ADDRESS_MAX_LENGTH.town,
1080
+ extraLines: 2,
1081
+ extraLine: 70,
1082
+ phones: 2,
1083
+ phone: 30,
1084
+ email: 70,
1085
+ contact: 70
1086
+ },
1087
+ recipient: {
1088
+ salutation: 35,
1089
+ name: ADDRESS_MAX_LENGTH.name,
1090
+ street: ADDRESS_MAX_LENGTH.street,
1091
+ buildingNumber: ADDRESS_MAX_LENGTH.buildingNumber,
1092
+ postalCode: ADDRESS_MAX_LENGTH.postalCode,
1093
+ town: ADDRESS_MAX_LENGTH.town,
1094
+ extraLines: 2,
1095
+ extraLine: 70
1096
+ },
1097
+ items: 1e3,
1098
+ description: 300,
1099
+ descriptionLines: 6,
1100
+ unit: 10,
1101
+ notes: 3,
1102
+ note: 300,
1103
+ noteLines: 4,
1104
+ logoBytes: 2e6
1105
+ };
1106
+ // src/items/items.validator.ts
1107
+ /**
1108
+ * Validation of the lines of an invoice: their texts, and their numbers read as exact integers.
1109
+ *
1110
+ * @module
1111
+ */
1112
+ /** The largest quantity and unit price: a billion, in their units. */
1113
+ const MAX_QUANTITY = 10n ** BigInt(12);
1114
+ const MAX_UNIT_PRICE = 10n ** BigInt(13);
1115
+ /** VAT rates go from 0 to 100 %, in hundredths of a percent. */
1116
+ const MAX_RATE = 100n * 10n ** BigInt(2);
1117
+ /**
1118
+ * Reads the lines of an invoice: from 1 to 1000, each with a description and optional numbers. A line with a
1119
+ * quantity needs a unit price or an amount.
1120
+ *
1121
+ * @param value - The lines, as given.
1122
+ * @param issues - Where problems are reported.
1123
+ * @returns The lines read, or `undefined` when one of them is invalid.
1124
+ */
1125
+ function readItems(value, issues) {
1126
+ const L = INVOICE_LIMITS;
1127
+ if (isAbsent(value) || Array.isArray(value) && value.length === 0) {
1128
+ issues.add("required", ["items"], "At least one line is required");
1129
+ return;
1130
+ }
1131
+ const entries = readList(value, ["items"], L.items, issues);
1132
+ if (entries.length === 0) return void 0;
1133
+ const parsed = [];
1134
+ const lines = [];
1135
+ let valid = true;
1136
+ for (const [index, entry] of entries.entries()) {
1137
+ const path = ["items", index];
1138
+ if (!isRecord(entry)) {
1139
+ issues.add("invalid_type", path, "Expected a line object");
1140
+ valid = false;
1141
+ continue;
1142
+ }
1143
+ const count = issues.list.length;
1144
+ const description = readParagraph(entry["description"], [...path, "description"], L.description, L.descriptionLines, issues, true);
1145
+ const unit = readLine(entry["unit"], [...path, "unit"], L.unit, issues);
1146
+ const line = {
1147
+ quantity: readNumber(entry["quantity"], [...path, "quantity"], 3, MAX_QUANTITY, issues),
1148
+ unitPrice: readNumber(entry["unitPrice"], [...path, "unitPrice"], 4, MAX_UNIT_PRICE, issues),
1149
+ vatRate: readRate(entry["vatRate"], [...path, "vatRate"], issues),
1150
+ amount: readNumber(entry["amount"], [...path, "amount"], 2, MAX_CENTIMES, issues)
1151
+ };
1152
+ if (line.quantity !== void 0 && line.unitPrice === void 0 && line.amount === void 0) issues.add("required", [...path, "unitPrice"], "A line with a quantity needs a unit price or an amount");
1153
+ const amount = lineAmount(line);
1154
+ if (amount !== void 0 && (amount < -99999999999n || amount > 99999999999n)) issues.add("out_of_range", [...path, "amount"], `The amount of the line must stay within ±${MAX_AMOUNT}`);
1155
+ if (issues.list.length > count || description === void 0) {
1156
+ valid = false;
1157
+ continue;
1158
+ }
1159
+ parsed.push(line);
1160
+ lines.push({
1161
+ description,
1162
+ ...line.quantity !== void 0 && { quantity: toShortDecimal(line.quantity, 3) },
1163
+ ...unit !== void 0 && { unit },
1164
+ ...line.unitPrice !== void 0 && { unitPrice: toShortDecimal(line.unitPrice, 4, 2) },
1165
+ ...line.vatRate !== void 0 && { vatRate: toShortDecimal(line.vatRate, 2) }
1166
+ });
1167
+ }
1168
+ return valid ? {
1169
+ parsed,
1170
+ lines
1171
+ } : void 0;
1172
+ }
1173
+ /**
1174
+ * Reads a VAT rate in percent, from 0 to 100, with at most 2 decimals.
1175
+ *
1176
+ * @param value - The rate, as given.
1177
+ * @param path - Where it is.
1178
+ * @param issues - Where problems are reported: `invalid_number`, `out_of_range`.
1179
+ * @returns The rate in hundredths of a percent, or `undefined`.
1180
+ */
1181
+ function readRate(value, path, issues) {
1182
+ const rate = readNumber(value, path, 2, MAX_RATE, issues);
1183
+ if (rate === void 0 || rate >= 0n) return rate;
1184
+ issues.add("out_of_range", path, "A VAT rate goes from 0 to 100 %");
1185
+ }
1186
+ // src/amounts/totals.validator.ts
1187
+ /** At most one VAT line per rate in use; 10 is plenty. */
1188
+ const MAX_PROVIDED_RATES = 10;
1189
+ /**
1190
+ * Reads totals given by the caller: a total, and optionally a subtotal and the VAT per rate.
1191
+ *
1192
+ * @param value - The totals, as given.
1193
+ * @param issues - Where problems are reported.
1194
+ * @returns The totals, or `undefined` when absent or invalid.
1195
+ */
1196
+ function readProvidedTotals(value, issues) {
1197
+ if (isAbsent(value)) return void 0;
1198
+ if (!isRecord(value)) {
1199
+ issues.add("invalid_type", ["totals"], "Expected an object with at least a total");
1200
+ return;
1201
+ }
1202
+ const amount = (field, path) => readNumber(field, path, 2, MAX_CENTIMES, issues);
1203
+ const count = issues.list.length;
1204
+ const subtotal = amount(value["subtotal"], ["totals", "subtotal"]);
1205
+ const total = amount(value["total"], ["totals", "total"]);
1206
+ if (isBlank(value["total"])) issues.add("required", ["totals", "total"], "Required");
1207
+ const vat = readList(value["vat"], ["totals", "vat"], MAX_PROVIDED_RATES, issues).flatMap((entry, index) => {
1208
+ const path = [
1209
+ "totals",
1210
+ "vat",
1211
+ index
1212
+ ];
1213
+ if (!isRecord(entry)) {
1214
+ issues.add("invalid_type", path, "Expected an object with a rate and an amount");
1215
+ return [];
1216
+ }
1217
+ const rate = readRate(entry["rate"], [...path, "rate"], issues);
1218
+ const base = amount(entry["base"], [...path, "base"]);
1219
+ const vatAmount = amount(entry["amount"], [...path, "amount"]);
1220
+ if (isBlank(entry["rate"])) issues.add("required", [...path, "rate"], "Required");
1221
+ if (isBlank(entry["amount"])) issues.add("required", [...path, "amount"], "Required");
1222
+ if (rate === void 0 || vatAmount === void 0) return [];
1223
+ return [{
1224
+ rate: toShortDecimal(rate, 2),
1225
+ ...base !== void 0 && { base: toDecimal(base, 2) },
1226
+ amount: toDecimal(vatAmount, 2)
1227
+ }];
1228
+ });
1229
+ if (issues.list.length > count || total === void 0) return void 0;
1230
+ return {
1231
+ totals: {
1232
+ ...subtotal !== void 0 && { subtotal: toDecimal(subtotal, 2) },
1233
+ vat,
1234
+ total: toDecimal(total, 2)
1235
+ },
1236
+ total
1237
+ };
1238
+ }
1239
+ // src/labels/labels.ts
1240
+ /** The texts of an invoice, by language. */
1241
+ const INVOICE_LABELS = {
1242
+ de: {
1243
+ invoice: "Rechnung",
1244
+ number: "Rechnungsnummer",
1245
+ date: "Datum",
1246
+ dueDate: "Fällig am",
1247
+ servicePeriod: "Leistungszeitraum",
1248
+ customerReference: "Ihre Referenz",
1249
+ subject: "Betreff: ",
1250
+ description: "Bezeichnung",
1251
+ quantity: "Menge",
1252
+ unit: "Einheit",
1253
+ unitPrice: "Preis",
1254
+ vat: "MWST",
1255
+ amount: "Betrag",
1256
+ subtotal: "Zwischensumme",
1257
+ vatOn: "MWST {rate} % auf {base}",
1258
+ vatIncluded: "Inkl. MWST {rate} % auf {base}",
1259
+ vatRate: "MWST {rate} %",
1260
+ rounding: "Rundung",
1261
+ total: "Total",
1262
+ page: "Seite {page}/{pages}",
1263
+ vatNumberSuffix: "MWST",
1264
+ notVatRegistered: "Nicht MWST-pflichtig.",
1265
+ vatExcluded: "Von der MWST ausgenommene Leistung.",
1266
+ paymentDays: "Zahlbar innert {days} Tagen.",
1267
+ thanks: "Vielen Dank für Ihr Vertrauen."
1268
+ },
1269
+ fr: {
1270
+ invoice: "Facture",
1271
+ number: "N° de facture",
1272
+ date: "Date",
1273
+ dueDate: "Échéance",
1274
+ servicePeriod: "Période",
1275
+ customerReference: "Votre référence",
1276
+ subject: "Objet : ",
1277
+ description: "Désignation",
1278
+ quantity: "Qté",
1279
+ unit: "Unité",
1280
+ unitPrice: "Prix unit.",
1281
+ vat: "TVA",
1282
+ amount: "Montant",
1283
+ subtotal: "Sous-total",
1284
+ vatOn: "TVA {rate} % sur {base}",
1285
+ vatIncluded: "Dont TVA {rate} % sur {base}",
1286
+ vatRate: "TVA {rate} %",
1287
+ rounding: "Arrondi",
1288
+ total: "Total",
1289
+ page: "Page {page}/{pages}",
1290
+ vatNumberSuffix: "TVA",
1291
+ notVatRegistered: "Non assujetti à la TVA.",
1292
+ vatExcluded: "Prestation exclue du champ de la TVA.",
1293
+ paymentDays: "Payable dans les {days} jours.",
1294
+ thanks: "Merci pour votre confiance."
1295
+ },
1296
+ it: {
1297
+ invoice: "Fattura",
1298
+ number: "N. fattura",
1299
+ date: "Data",
1300
+ dueDate: "Scadenza",
1301
+ servicePeriod: "Periodo",
1302
+ customerReference: "Vostro riferimento",
1303
+ subject: "Oggetto: ",
1304
+ description: "Descrizione",
1305
+ quantity: "Qtà",
1306
+ unit: "Unità",
1307
+ unitPrice: "Prezzo unit.",
1308
+ vat: "IVA",
1309
+ amount: "Importo",
1310
+ subtotal: "Subtotale",
1311
+ vatOn: "IVA {rate} % su {base}",
1312
+ vatIncluded: "Di cui IVA {rate} % su {base}",
1313
+ vatRate: "IVA {rate} %",
1314
+ rounding: "Arrotondamento",
1315
+ total: "Totale",
1316
+ page: "Pagina {page}/{pages}",
1317
+ vatNumberSuffix: "IVA",
1318
+ notVatRegistered: "Non assoggettato all'IVA.",
1319
+ vatExcluded: "Prestazione esclusa dall'IVA.",
1320
+ paymentDays: "Pagabile entro {days} giorni.",
1321
+ thanks: "Grazie per la vostra fiducia."
1322
+ },
1323
+ en: {
1324
+ invoice: "Invoice",
1325
+ number: "Invoice no.",
1326
+ date: "Date",
1327
+ dueDate: "Due date",
1328
+ servicePeriod: "Period",
1329
+ customerReference: "Your reference",
1330
+ subject: "Subject: ",
1331
+ description: "Description",
1332
+ quantity: "Qty",
1333
+ unit: "Unit",
1334
+ unitPrice: "Unit price",
1335
+ vat: "VAT",
1336
+ amount: "Amount",
1337
+ subtotal: "Subtotal",
1338
+ vatOn: "VAT {rate} % on {base}",
1339
+ vatIncluded: "Incl. VAT {rate} % on {base}",
1340
+ vatRate: "VAT {rate} %",
1341
+ rounding: "Rounding",
1342
+ total: "Total",
1343
+ page: "Page {page}/{pages}",
1344
+ vatNumberSuffix: "MWST",
1345
+ notVatRegistered: "Not registered for VAT.",
1346
+ vatExcluded: "Supply excluded from VAT.",
1347
+ paymentDays: "Payable within {days} days.",
1348
+ thanks: "Thank you for your trust."
1349
+ },
1350
+ rm: {
1351
+ invoice: "Quint",
1352
+ number: "Nr. dal quint",
1353
+ date: "Data",
1354
+ dueDate: "Termin da pajament",
1355
+ servicePeriod: "Perioda",
1356
+ customerReference: "Vossa referenza",
1357
+ subject: "Object: ",
1358
+ description: "Descripziun",
1359
+ quantity: "Quantitad",
1360
+ unit: "Unitad",
1361
+ unitPrice: "Pretsch unitar",
1362
+ vat: "TPV",
1363
+ amount: "Import",
1364
+ subtotal: "Subtotal",
1365
+ vatOn: "TPV {rate} % sin {base}",
1366
+ vatIncluded: "Incl. TPV {rate} % sin {base}",
1367
+ vatRate: "TPV {rate} %",
1368
+ rounding: "Arrundaziun",
1369
+ total: "Total",
1370
+ page: "Pagina {page}/{pages}",
1371
+ vatNumberSuffix: "MWST",
1372
+ notVatRegistered: "Betg suttamess a la TPV.",
1373
+ vatExcluded: "Prestaziun exclusa da la TPV.",
1374
+ paymentDays: "Da pajar entaifer {days} dis.",
1375
+ thanks: "Grazia fitg per Vossa fidanza."
1376
+ }
1377
+ };
1378
+ /**
1379
+ * Fills the placeholders of a template, written in braces.
1380
+ *
1381
+ * @param template - A text of {@link InvoiceLabels} such as `"VAT {rate} % on {base}"`.
1382
+ * @param values - The value of each placeholder.
1383
+ * @returns The text.
1384
+ * @example
1385
+ * ```ts
1386
+ * fill('Page {page}/{pages}', { page: 1, pages: 3 }); // 'Page 1/3'
1387
+ * ```
1388
+ */
1389
+ function fill(template, values) {
1390
+ return template.replace(/\{(\w+)\}/g, (placeholder, name) => String(values[name] ?? placeholder));
1391
+ }
1392
+ // src/uid/uid.ts
1393
+ /**
1394
+ * The Swiss business identification number (UID; IDE in French and Italian): the prefix `CHE`, eight digits and a
1395
+ * check digit, written `CHE-123.456.788`. A company registered for VAT uses it as its VAT number, followed by
1396
+ * `MWST`, `TVA` or `IVA`. The check digit is a modulo 11 with the weights 5, 4, 3, 2, 7, 6, 5, 4 (standard
1397
+ * eCH-0097).
1398
+ *
1399
+ * @module
1400
+ */
1401
+ const WEIGHTS = [
1402
+ 5,
1403
+ 4,
1404
+ 3,
1405
+ 2,
1406
+ 7,
1407
+ 6,
1408
+ 5,
1409
+ 4
1410
+ ];
1411
+ /**
1412
+ * The nine digits of a UID written in a usual way: separators, spaces, lower case and a VAT suffix are accepted.
1413
+ *
1414
+ * @param value - The UID, e.g. `"CHE-123.456.788 TVA"`.
1415
+ * @returns The nine digits, or `undefined` when the value does not have the shape of a UID.
1416
+ * @example
1417
+ * ```ts
1418
+ * uidDigits('che-123.456.788 TVA'); // '123456788'
1419
+ * ```
1420
+ */
1421
+ function uidDigits(value) {
1422
+ const compact = value.normalize("NFC").toUpperCase().replace(/[\s.-]/g, "").replace(/(MWST|TVA|IVA)$/, "");
1423
+ return /^CHE(\d{9})$/.exec(compact)?.[1];
1424
+ }
1425
+ /**
1426
+ * Whether the last of nine digits is the check digit of the eight others. A remainder giving 10 means that no UID
1427
+ * uses these eight digits.
1428
+ *
1429
+ * @param digits - Nine digits, as returned by {@link uidDigits}.
1430
+ * @returns `true` when the check digit is right.
1431
+ * @example
1432
+ * ```ts
1433
+ * hasValidCheckDigit('123456788'); // true
1434
+ * ```
1435
+ */
1436
+ function hasValidCheckDigit(digits) {
1437
+ const check = (11 - WEIGHTS.reduce((total, weight, index) => total + weight * Number(digits[index]), 0) % 11) % 11;
1438
+ return check !== 10 && check === Number(digits[8]);
1439
+ }
1440
+ /**
1441
+ * Writes a UID in its usual form, `CHE-123.456.788`.
1442
+ *
1443
+ * @param value - A UID that {@link validateUID} accepts.
1444
+ * @returns The UID with its separators, without VAT suffix.
1445
+ * @throws {RangeError} When the value is not a valid UID.
1446
+ * @example
1447
+ * ```ts
1448
+ * formatUID('che123456788'); // 'CHE-123.456.788'
1449
+ * ```
1450
+ */
1451
+ function formatUID(value) {
1452
+ const digits = uidDigits(value);
1453
+ if (digits === void 0 || !hasValidCheckDigit(digits)) throw new RangeError(`Invalid UID: ${JSON.stringify(value)}`);
1454
+ return `CHE-${digits.slice(0, 3)}.${digits.slice(3, 6)}.${digits.slice(6)}`;
1455
+ }
1456
+ // src/uid/uid.validator.ts
1457
+ /**
1458
+ * Validator of the Swiss business identification number (UID).
1459
+ *
1460
+ * @module
1461
+ */
1462
+ /**
1463
+ * Validates a Swiss business identification number (UID): its shape and its check digit. Separators, spaces, lower
1464
+ * case and a VAT suffix (`MWST`, `TVA`, `IVA`) are accepted. Blank counts as missing.
1465
+ *
1466
+ * @param value - The UID as typed.
1467
+ * @returns `'valid'`, `'required'` when blank, or `'invalid_uid'`.
1468
+ * @example
1469
+ * ```ts
1470
+ * validateUID('CHE-123.456.788'); // 'valid'
1471
+ * validateUID('che 123 456 788 tva'); // 'valid'
1472
+ * validateUID('CHE-123.456.789'); // 'invalid_uid': wrong check digit
1473
+ * validateUID(' '); // 'required'
1474
+ * ```
1475
+ */
1476
+ function validateUID(value) {
1477
+ const text = (value ?? "").trim();
1478
+ if (text === "") return "required";
1479
+ const digits = uidDigits(text);
1480
+ return digits !== void 0 && hasValidCheckDigit(digits) ? "valid" : "invalid_uid";
1481
+ }
1482
+ // src/parties/parties.validator.ts
1483
+ /**
1484
+ * Validation of the issuer and the recipient. Their names and structured addresses are checked with the validators
1485
+ * of the QR-bill, since they are also the creditor and the debtor of the payment part.
1486
+ *
1487
+ * @module
1488
+ */
1489
+ /** A field of an address, checked by the validator of the QR-bill. */
1490
+ function readAddressField(value, path, validate, max, issues) {
1491
+ if (!isAbsent(value) && typeof value !== "string") {
1492
+ issues.add("invalid_type", path, `Expected a string, received ${typeof value}`);
1493
+ return;
1494
+ }
1495
+ const text = (value ?? "").normalize("NFC").trim();
1496
+ const status = validate(text);
1497
+ if (status === "valid") return text === "" ? void 0 : text;
1498
+ const messages = {
1499
+ required: "Required",
1500
+ invalid_characters: "Characters not allowed on the payment part of a QR-bill",
1501
+ too_long: `At most ${max} characters, received ${[...text].length}`
1502
+ };
1503
+ issues.add(status, path, messages[status]);
1504
+ }
1505
+ /** The structured address of the issuer or the recipient, with the rules of the QR-bill. */
1506
+ function readAddress(value, path, issues) {
1507
+ const L = INVOICE_LIMITS.recipient;
1508
+ const name = readAddressField(value["name"], [...path, "name"], validateName, L.name, issues);
1509
+ const street = readAddressField(value["street"], [...path, "street"], validateStreet, L.street, issues);
1510
+ const buildingNumber = readAddressField(value["buildingNumber"], [...path, "buildingNumber"], validateBuildingNumber, L.buildingNumber, issues);
1511
+ const postalCode = readAddressField(value["postalCode"], [...path, "postalCode"], validatePostalCode, L.postalCode, issues);
1512
+ const town = readAddressField(value["town"], [...path, "town"], validateTown, L.town, issues);
1513
+ const country = readCountry(value["country"], [...path, "country"], issues);
1514
+ if (name === void 0 || postalCode === void 0 || town === void 0 || country === void 0) return void 0;
1515
+ return {
1516
+ name,
1517
+ ...street !== void 0 && { street },
1518
+ ...buildingNumber !== void 0 && { buildingNumber },
1519
+ postalCode,
1520
+ town,
1521
+ country
1522
+ };
1523
+ }
1524
+ function readCountry(value, path, issues) {
1525
+ if (!isAbsent(value) && typeof value !== "string") {
1526
+ issues.add("invalid_type", path, `Expected a string, received ${typeof value}`);
1527
+ return;
1528
+ }
1529
+ const text = value ?? "";
1530
+ const status = validateCountry(text);
1531
+ if (status === "valid") return text.trim().toUpperCase();
1532
+ issues.add(status, path, status === "required" ? "Required" : "Expected a two-letter ISO 3166-1 country code");
1533
+ }
1534
+ /**
1535
+ * Reads the issuer: its name and address with the rules of the QR-bill, its logo, its contacts and its UID.
1536
+ *
1537
+ * @param value - The issuer, as given.
1538
+ * @param issues - Where problems are reported.
1539
+ * @returns The issuer, normalized, or `undefined` when its name or address is invalid.
1540
+ */
1541
+ function readIssuer(value, issues) {
1542
+ const record = readRecord(value, ["issuer"], issues);
1543
+ if (record === void 0) return void 0;
1544
+ const L = INVOICE_LIMITS.issuer;
1545
+ const address = readAddress(record, ["issuer"], issues);
1546
+ const logo = readLogo(record["logo"], issues);
1547
+ const extraLines = readLines(record["extraLines"], ["issuer", "extraLines"], L.extraLines, L.extraLine, issues);
1548
+ const phones = readLines(record["phones"], ["issuer", "phones"], L.phones, L.phone, issues);
1549
+ const email = readEmail(record["email"], issues);
1550
+ const contact = readLine(record["contact"], ["issuer", "contact"], L.contact, issues);
1551
+ const uid = readUID(record["uid"], issues);
1552
+ const vatRegistered = readBoolean(record["vatRegistered"], ["issuer", "vatRegistered"], issues);
1553
+ if (address === void 0) return void 0;
1554
+ return {
1555
+ ...address,
1556
+ ...logo !== void 0 && { logo },
1557
+ extraLines,
1558
+ phones,
1559
+ ...email !== void 0 && { email },
1560
+ ...contact !== void 0 && { contact },
1561
+ ...uid !== void 0 && { uid },
1562
+ vatRegistered: vatRegistered ?? false
1563
+ };
1564
+ }
1565
+ /**
1566
+ * Reads the recipient: its name and address with the rules of the QR-bill, its salutation and its extra lines.
1567
+ *
1568
+ * @param value - The recipient, as given.
1569
+ * @param issues - Where problems are reported.
1570
+ * @returns The recipient, normalized, or `undefined` when its name or address is invalid.
1571
+ */
1572
+ function readRecipient(value, issues) {
1573
+ const record = readRecord(value, ["recipient"], issues);
1574
+ if (record === void 0) return void 0;
1575
+ const L = INVOICE_LIMITS.recipient;
1576
+ const salutation = readLine(record["salutation"], ["recipient", "salutation"], L.salutation, issues);
1577
+ const address = readAddress(record, ["recipient"], issues);
1578
+ const extraLines = readLines(record["extraLines"], ["recipient", "extraLines"], L.extraLines, L.extraLine, issues);
1579
+ if (address === void 0) return void 0;
1580
+ return {
1581
+ ...salutation !== void 0 && { salutation },
1582
+ ...address,
1583
+ extraLines
1584
+ };
1585
+ }
1586
+ /** The first bytes of a PNG file. */
1587
+ const PNG_SIGNATURE = [
1588
+ 137,
1589
+ 80,
1590
+ 78,
1591
+ 71,
1592
+ 13,
1593
+ 10,
1594
+ 26,
1595
+ 10
1596
+ ];
1597
+ /** The first bytes of a JPEG file. */
1598
+ const JPEG_SIGNATURE = [
1599
+ 255,
1600
+ 216,
1601
+ 255
1602
+ ];
1603
+ /** A logo: the bytes of a PNG or JPEG file, recognized from their first bytes. */
1604
+ function readLogo(value, issues) {
1605
+ if (isAbsent(value)) return void 0;
1606
+ const path = ["issuer", "logo"];
1607
+ if (!(value instanceof Uint8Array)) {
1608
+ issues.add("invalid_type", path, "Expected the bytes of a PNG or JPEG file (a Uint8Array or a Buffer)");
1609
+ return;
1610
+ }
1611
+ if (value.length > INVOICE_LIMITS.logoBytes) {
1612
+ issues.add("logo_too_large", path, `At most ${INVOICE_LIMITS.logoBytes} bytes, received ${value.length}`);
1613
+ return;
1614
+ }
1615
+ const starts = (signature) => signature.every((byte, index) => value[index] === byte);
1616
+ const format = starts(PNG_SIGNATURE) ? "png" : starts(JPEG_SIGNATURE) ? "jpeg" : void 0;
1617
+ if (format === void 0) {
1618
+ issues.add("unsupported_logo", path, "Expected a PNG or JPEG file");
1619
+ return;
1620
+ }
1621
+ return {
1622
+ format,
1623
+ bytes: value
1624
+ };
1625
+ }
1626
+ function readEmail(value, issues) {
1627
+ const path = ["issuer", "email"];
1628
+ const email = readLine(value, path, INVOICE_LIMITS.issuer.email, issues);
1629
+ if (email === void 0 || /^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(email)) return email;
1630
+ issues.add("invalid_email", path, `Expected an e-mail address, received ${JSON.stringify(email)}`);
1631
+ }
1632
+ function readUID(value, issues) {
1633
+ const path = ["issuer", "uid"];
1634
+ const text = readString(value, path, issues);
1635
+ if (text === void 0) return void 0;
1636
+ if (validateUID(text) === "valid") return formatUID(text);
1637
+ issues.add("invalid_uid", path, `Expected a UID such as "CHE-123.456.788" with its check digit`);
1638
+ }
1639
+ // src/themes/business.ts
1640
+ /** The `business` theme. */
1641
+ const BUSINESS_THEME = {
1642
+ name: "business",
1643
+ accent: "#1F3A5F",
1644
+ accentTitle: true,
1645
+ tableHeader: "band",
1646
+ stripedRows: false,
1647
+ topBar: false,
1648
+ accentTotal: true
1649
+ };
1650
+ /**
1651
+ * The red, green and blue of a colour.
1652
+ *
1653
+ * @param color - A colour written `#RRGGBB`.
1654
+ * @returns The three channels, from 0 to 255.
1655
+ */
1656
+ function channels(color) {
1657
+ return [
1658
+ 1,
1659
+ 3,
1660
+ 5
1661
+ ].map((start) => parseInt(color.slice(start, start + 2), 16));
1662
+ }
1663
+ /**
1664
+ * Writes three channels as `#RRGGBB`, in upper case.
1665
+ *
1666
+ * @param values - Red, green and blue, rounded and kept within 0 to 255.
1667
+ * @returns The colour.
1668
+ */
1669
+ function toHex(values) {
1670
+ return `#${values.map((value) => Math.min(255, Math.max(0, Math.round(value))).toString(16).padStart(2, "0")).join("")}`.toUpperCase();
1671
+ }
1672
+ /**
1673
+ * Mixes a colour with another one: with a share of 1 the result is the colour, with 0 the other one.
1674
+ *
1675
+ * @param color - The colour, `#RRGGBB`.
1676
+ * @param background - The colour it is mixed with, usually white.
1677
+ * @param share - The share of the colour, from 0 to 1.
1678
+ * @returns The mixed colour.
1679
+ * @example
1680
+ * ```ts
1681
+ * mix('#1F3A5F', '#FFFFFF', 0.5); // '#8F9DAF'
1682
+ * ```
1683
+ */
1684
+ function mix(color, background, share) {
1685
+ const [red, green, blue] = channels(color);
1686
+ const [baseRed, baseGreen, baseBlue] = channels(background);
1687
+ return toHex([
1688
+ baseRed + (red - baseRed) * share,
1689
+ baseGreen + (green - baseGreen) * share,
1690
+ baseBlue + (blue - baseBlue) * share
1691
+ ]);
1692
+ }
1693
+ /**
1694
+ * The relative luminance of a colour, from 0 (black) to 1 (white), as WCAG 2 defines it.
1695
+ *
1696
+ * @param color - The colour, `#RRGGBB`.
1697
+ * @returns The luminance.
1698
+ */
1699
+ function luminance(color) {
1700
+ const [red, green, blue] = channels(color).map((value) => {
1701
+ const share = value / 255;
1702
+ return share <= .04045 ? share / 12.92 : ((share + .055) / 1.055) ** 2.4;
1703
+ });
1704
+ return .2126 * red + .7152 * green + .0722 * blue;
1705
+ }
1706
+ /**
1707
+ * The contrast between two colours, from 1 (the same luminance) to 21 (black on white), as WCAG 2 defines it.
1708
+ *
1709
+ * @param first - A colour, `#RRGGBB`.
1710
+ * @param second - Another colour.
1711
+ * @returns The contrast ratio.
1712
+ * @example
1713
+ * ```ts
1714
+ * contrastRatio('#000000', '#FFFFFF'); // 21
1715
+ * ```
1716
+ */
1717
+ function contrastRatio(first, second) {
1718
+ const [lighter, darker] = [luminance(first), luminance(second)].sort((a, b) => b - a);
1719
+ return (lighter + .05) / (darker + .05);
1720
+ }
1721
+ /**
1722
+ * Darkens a colour by steps of 5 % until it is readable on a light background, where black always is.
1723
+ *
1724
+ * @param color - The colour of the text, `#RRGGBB`.
1725
+ * @param background - A light background, e.g. white or a tint.
1726
+ * @returns The colour itself when it is readable already, otherwise the first darker step that is.
1727
+ * @example
1728
+ * ```ts
1729
+ * readableOn('#1F3A5F', '#FFFFFF'); // '#1F3A5F': dark enough already
1730
+ * readableOn('#F59E0B', '#FFFFFF'); // '#9F6707': amber, darkened to a contrast of 4.75
1731
+ * ```
1732
+ */
1733
+ function readableOn(color, background) {
1734
+ let darker = color;
1735
+ for (let step = 1; contrastRatio(darker, background) < 4.5 && step <= 20; step++) darker = mix(color, "#000000", 1 - step * .05);
1736
+ return darker;
1737
+ }
1738
+ // src/themes/modern.ts
1739
+ /** The `modern` theme. */
1740
+ const MODERN_THEME = {
1741
+ name: "modern",
1742
+ accent: "#0F766E",
1743
+ accentTitle: true,
1744
+ tableHeader: "tint",
1745
+ stripedRows: true,
1746
+ topBar: true,
1747
+ accentTotal: true
1748
+ };
1749
+ // src/themes/standard.ts
1750
+ /** The `standard` theme. */
1751
+ const STANDARD_THEME = {
1752
+ name: "standard",
1753
+ accent: "#555555",
1754
+ accentTitle: false,
1755
+ tableHeader: "rule",
1756
+ stripedRows: false,
1757
+ topBar: false,
1758
+ accentTotal: false
1759
+ };
1760
+ // src/themes/themes.ts
1761
+ /**
1762
+ * The themes of the invoice and the colours computed from them. A theme changes only the look of the invoice (the
1763
+ * title, the table header, the rows of the table, the total, a bar along the top of the pages), never its layout:
1764
+ * positions, limits and the payment part stay the same. The payment part is always black on white, as the style
1765
+ * guide of the QR-bill requires.
1766
+ *
1767
+ * @module
1768
+ */
1769
+ /**
1770
+ * The names of the themes, for a selector: `standard` (black and grey, the default), `business` (a filled band of
1771
+ * colour), `modern` (light tints).
1772
+ *
1773
+ * @example
1774
+ * ```ts
1775
+ * INVOICE_THEMES.length; // 3
1776
+ * ```
1777
+ */
1778
+ const INVOICE_THEMES = [
1779
+ "standard",
1780
+ "business",
1781
+ "modern"
1782
+ ];
1783
+ /** Each theme by its name. */
1784
+ const THEMES = {
1785
+ standard: STANDARD_THEME,
1786
+ business: BUSINESS_THEME,
1787
+ modern: MODERN_THEME
1788
+ };
1789
+ const BLACK = "#000000";
1790
+ const WHITE = "#FFFFFF";
1791
+ /** Share of the accent in the tint of a table header, and in the tint of a striped row. */
1792
+ const HEADER_TINT = .14;
1793
+ const STRIPE_TINT = .05;
1794
+ /**
1795
+ * Computes the colours of an invoice from its theme and accent. Every text stays readable, with a contrast of at
1796
+ * least 4.5:1 on its background: a text written in the accent colour is darkened if needed, and the text of a band
1797
+ * filled with the accent is white, or black when the accent is too light for white.
1798
+ *
1799
+ * @param theme - The theme of the invoice and its accent, if one was given.
1800
+ * @returns The colours of each part of the invoice.
1801
+ * @example
1802
+ * ```ts
1803
+ * resolveTheme({ name: 'business' }).tableHeaderBackground; // '#1F3A5F'
1804
+ * resolveTheme({ name: 'business', accent: '#FDE047' }).tableHeaderText; // '#000000': yellow is too light for white
1805
+ * ```
1806
+ */
1807
+ function resolveTheme(theme) {
1808
+ const definition = THEMES[theme.name];
1809
+ const accent = theme.accent ?? definition.accent;
1810
+ const readableAccent = readableOn(accent, WHITE);
1811
+ let header;
1812
+ if (definition.tableHeader === "band") header = {
1813
+ tableHeaderBackground: accent,
1814
+ tableHeaderText: contrastRatio(WHITE, accent) >= 4.5 ? WHITE : BLACK
1815
+ };
1816
+ else if (definition.tableHeader === "tint") {
1817
+ const tint = mix(accent, WHITE, HEADER_TINT);
1818
+ header = {
1819
+ tableHeaderBackground: tint,
1820
+ tableHeaderText: readableOn(accent, tint)
1821
+ };
1822
+ } else header = {
1823
+ tableHeaderRule: accent,
1824
+ tableHeaderText: BLACK
1825
+ };
1826
+ return {
1827
+ text: BLACK,
1828
+ muted: "#595959",
1829
+ line: "#DDDDDD",
1830
+ title: definition.accentTitle ? readableAccent : BLACK,
1831
+ ...header,
1832
+ ...definition.stripedRows && { stripe: mix(accent, WHITE, STRIPE_TINT) },
1833
+ total: definition.accentTotal ? readableAccent : BLACK,
1834
+ totalRule: accent,
1835
+ ...definition.topBar && { topBar: accent }
1836
+ };
1837
+ }
1838
+ // src/themes/themes.validator.ts
1839
+ /**
1840
+ * Validation of the theme of an invoice: its name, and its accent colour written `#RRGGBB`.
1841
+ *
1842
+ * @module
1843
+ */
1844
+ /**
1845
+ * Reads the theme: the name of a theme, or an object with a name and an accent colour.
1846
+ *
1847
+ * @param value - The theme, as given.
1848
+ * @param issues - Where problems are reported: `invalid_type`, `invalid_option`, `invalid_color`.
1849
+ * @returns The theme; `standard` when absent or invalid.
1850
+ */
1851
+ function readTheme(value, issues) {
1852
+ if (isAbsent(value)) return { name: "standard" };
1853
+ const record = typeof value === "string" ? { name: value } : value;
1854
+ if (!isRecord(record)) {
1855
+ issues.add("invalid_type", ["theme"], "Expected the name of a theme or an object with a name and an accent");
1856
+ return { name: "standard" };
1857
+ }
1858
+ const path = typeof value === "string" ? ["theme"] : ["theme", "name"];
1859
+ const name = readOption(record["name"], path, INVOICE_THEMES, issues) ?? "standard";
1860
+ const accent = record["accent"];
1861
+ if (isAbsent(accent)) return { name };
1862
+ if (typeof accent === "string" && /^#[0-9a-f]{6}$/iu.test(accent.trim())) return {
1863
+ name,
1864
+ accent: accent.trim().toUpperCase()
1865
+ };
1866
+ issues.add("invalid_color", ["theme", "accent"], "Expected a colour written #RRGGBB, e.g. \"#1F3A5F\"");
1867
+ return { name };
1868
+ }
1869
+ // src/invoice/invoice.validator.ts
1870
+ /**
1871
+ * Validation of an invoice. Only the form is checked: types, lengths, numbers, dates, UID, e-mail, and the QR-bill
1872
+ * of the payment part, which must be valid. What the invoice says is the issuer's business: no legal mention is
1873
+ * required. Every problem is reported at once, with a stable code and the path of the field.
1874
+ *
1875
+ * @module
1876
+ */
1877
+ /**
1878
+ * Validates and normalizes an invoice without throwing.
1879
+ *
1880
+ * Accepts `unknown`, so that a request body can be passed as is. The issuer and the recipient are checked with the
1881
+ * validators of the QR-bill, since they are also the creditor and the debtor of the payment part; the payment part
1882
+ * is checked by `validateQRBill` of `@qr-bill/core`, with the total of the invoice as its amount. Its codes are
1883
+ * reused for these fields.
1884
+ *
1885
+ * @param input - The invoice to check, normally an {@link InvoiceInput}.
1886
+ * @returns Either `{ success: true, data }`, where `data` is the normalized, frozen {@link Invoice} with its totals
1887
+ * and its QR-bill, or `{ success: false, issues }` listing every problem found.
1888
+ * @example
1889
+ * ```ts
1890
+ * const result = validateInvoice(requestBody);
1891
+ * if (!result.success) {
1892
+ * result.issues; // [{ code: 'invalid_uid', path: ['issuer', 'uid'], message: '…' }, …]
1893
+ * }
1894
+ * ```
1895
+ */
1896
+ function validateInvoice(input) {
1897
+ if (!isRecord(input)) return {
1898
+ success: false,
1899
+ issues: [{
1900
+ code: "invalid_type",
1901
+ path: [],
1902
+ message: "Expected an invoice object"
1903
+ }]
1904
+ };
1905
+ const issues = new IssueList();
1906
+ const L = INVOICE_LIMITS;
1907
+ const language = readLanguage(input["language"], issues);
1908
+ const currency = readCurrency(input["currency"], issues);
1909
+ const title = readLine(input["title"], ["title"], L.title, issues);
1910
+ const number = readLine(input["number"], ["number"], L.number, issues);
1911
+ const date = readDate(input["date"], ["date"], true, issues);
1912
+ const dueDate = readDate(input["dueDate"], ["dueDate"], false, issues);
1913
+ const servicePeriod = readLine(input["servicePeriod"], ["servicePeriod"], L.servicePeriod, issues);
1914
+ const customerReference = readLine(input["customerReference"], ["customerReference"], L.customerReference, issues);
1915
+ const extraFields = readExtraFields(input["extraFields"], issues);
1916
+ const subject = readLine(input["subject"], ["subject"], L.subject, issues);
1917
+ const introduction = readParagraph(input["introduction"], ["introduction"], L.introduction, L.introductionLines, issues);
1918
+ const closing = readParagraph(input["closing"], ["closing"], L.closing, L.closingLines, issues);
1919
+ const issuer = readIssuer(input["issuer"], issues);
1920
+ const recipient = readRecipient(input["recipient"], issues);
1921
+ const items = readItems(input["items"], issues);
1922
+ const pricesIncludeVAT = readBoolean(input["pricesIncludeVAT"], ["pricesIncludeVAT"], issues);
1923
+ const roundTo5Centimes = readBoolean(input["roundTo5Centimes"], ["roundTo5Centimes"], issues);
1924
+ const providedTotals = readProvidedTotals(input["totals"], issues);
1925
+ const mentions = readMentions(input["mentions"], issues);
1926
+ const notes = readNotes(input["notes"], issues);
1927
+ const amountFormat = readOption(input["amountFormat"], ["amountFormat"], ["space", "apostrophe"], issues);
1928
+ const addressWindow = readOption(input["addressWindow"], ["addressWindow"], ["left", "right"], issues);
1929
+ const theme = readTheme(input["theme"], issues);
1930
+ let totals;
1931
+ let total;
1932
+ if (items !== void 0) {
1933
+ const computed = computeTotals(items.parsed, {
1934
+ pricesIncludeVAT,
1935
+ roundTo5Centimes
1936
+ });
1937
+ if (providedTotals === void 0) {
1938
+ totals = totalsToDecimals(computed);
1939
+ total = computed.total;
1940
+ } else {
1941
+ totals = {
1942
+ lines: totalsToDecimals(computed).lines,
1943
+ ...providedTotals.totals
1944
+ };
1945
+ total = providedTotals.total;
1946
+ }
1947
+ if (total < -99999999999n || total > 99999999999n) issues.add("out_of_range", ["items"], `The total must stay within ±${MAX_AMOUNT}`);
1948
+ }
1949
+ const bill = readPayment(input, {
1950
+ language,
1951
+ currency,
1952
+ title,
1953
+ number,
1954
+ total
1955
+ }, issues);
1956
+ if (issues.list.length > 0 || language === void 0 || date === void 0 || issuer === void 0 || recipient === void 0 || items === void 0 || totals === void 0) return {
1957
+ success: false,
1958
+ issues: issues.list
1959
+ };
1960
+ return {
1961
+ success: true,
1962
+ data: deepFreeze({
1963
+ language,
1964
+ currency: currency ?? "CHF",
1965
+ title: title ?? INVOICE_LABELS[language].invoice,
1966
+ ...number !== void 0 && { number },
1967
+ date,
1968
+ ...dueDate !== void 0 && { dueDate },
1969
+ ...servicePeriod !== void 0 && { servicePeriod },
1970
+ ...customerReference !== void 0 && { customerReference },
1971
+ extraFields,
1972
+ ...subject !== void 0 && { subject },
1973
+ ...introduction !== void 0 && { introduction },
1974
+ ...closing !== void 0 && { closing },
1975
+ issuer,
1976
+ recipient,
1977
+ lines: items.lines,
1978
+ pricesIncludeVAT: pricesIncludeVAT ?? false,
1979
+ totals,
1980
+ totalsProvided: providedTotals !== void 0,
1981
+ mentions,
1982
+ notes,
1983
+ amountFormat: amountFormat ?? "space",
1984
+ addressWindow: addressWindow ?? "left",
1985
+ theme,
1986
+ ...bill !== void 0 && { bill }
1987
+ })
1988
+ };
1989
+ }
1990
+ function readLanguage(value, issues) {
1991
+ if (typeof value === "string" && Object.hasOwn(LABELS, value)) return value;
1992
+ issues.add("invalid_language", ["language"], "Expected \"de\", \"fr\", \"it\", \"rm\" or \"en\"");
1993
+ }
1994
+ function readCurrency(value, issues) {
1995
+ if (isAbsent(value)) return void 0;
1996
+ if (isValidCurrency(value)) return value;
1997
+ issues.add("invalid_currency", ["currency"], "Currency must be \"CHF\" or \"EUR\"");
1998
+ }
1999
+ function readExtraFields(value, issues) {
2000
+ const L = INVOICE_LIMITS;
2001
+ return readList(value, ["extraFields"], L.extraFields, issues).flatMap((entry, index) => {
2002
+ const path = ["extraFields", index];
2003
+ if (!isRecord(entry)) {
2004
+ issues.add("invalid_type", path, "Expected an object with a label and a value");
2005
+ return [];
2006
+ }
2007
+ const label = readLine(entry["label"], [...path, "label"], L.extraFieldLabel, issues, true);
2008
+ const fieldValue = readLine(entry["value"], [...path, "value"], L.extraFieldValue, issues, true);
2009
+ return label === void 0 || fieldValue === void 0 ? [] : [{
2010
+ label,
2011
+ value: fieldValue
2012
+ }];
2013
+ });
2014
+ }
2015
+ function readMentions(value, issues) {
2016
+ if (isAbsent(value)) return {};
2017
+ if (!isRecord(value)) {
2018
+ issues.add("invalid_type", ["mentions"], "Expected an object");
2019
+ return {};
2020
+ }
2021
+ const notVatRegistered = readBoolean(value["notVatRegistered"], ["mentions", "notVatRegistered"], issues);
2022
+ const vatExcluded = readBoolean(value["vatExcluded"], ["mentions", "vatExcluded"], issues);
2023
+ const thanks = readBoolean(value["thanks"], ["mentions", "thanks"], issues);
2024
+ const days = value["paymentDays"];
2025
+ let paymentDays;
2026
+ if (!isAbsent(days)) {
2027
+ if (typeof days === "number" && Number.isInteger(days) && days >= 1 && days <= 365) paymentDays = days;
2028
+ else issues.add("invalid_number", ["mentions", "paymentDays"], "Expected a whole number of days from 1 to 365");
2029
+ }
2030
+ return {
2031
+ ...notVatRegistered !== void 0 && { notVatRegistered },
2032
+ ...vatExcluded !== void 0 && { vatExcluded },
2033
+ ...paymentDays !== void 0 && { paymentDays },
2034
+ ...thanks !== void 0 && { thanks }
2035
+ };
2036
+ }
2037
+ /** The free remarks, blank ones being left out. */
2038
+ function readNotes(value, issues) {
2039
+ const path = ["notes"];
2040
+ const L = INVOICE_LIMITS;
2041
+ return readList(value, path, L.notes, issues).flatMap((entry, index) => {
2042
+ const note = readParagraph(entry, [...path, index], L.note, L.noteLines, issues);
2043
+ return note === void 0 ? [] : [note];
2044
+ });
2045
+ }
2046
+ /**
2047
+ * Checks the payment part with `validateQRBill`, the issuer and the recipient being the creditor and the debtor,
2048
+ * and the total the amount. A total of 0.00 is a notification (chapter 4.4): its message becomes "DO NOT USE FOR
2049
+ * PAYMENT" in the language of the invoice. A negative total (a credit note) has no payment part.
2050
+ */
2051
+ function readPayment(input, context, issues) {
2052
+ const value = input["payment"];
2053
+ if (isAbsent(value)) return void 0;
2054
+ if (!isRecord(value)) {
2055
+ issues.add("invalid_type", ["payment"], "Expected an object with at least an account");
2056
+ return;
2057
+ }
2058
+ const issuer = isRecord(input["issuer"]) ? input["issuer"] : {};
2059
+ const recipient = isRecord(input["recipient"]) ? input["recipient"] : void 0;
2060
+ const { language, total } = context;
2061
+ const notification = total === 0n && language !== void 0;
2062
+ const payable = total !== void 0 && total > 0n && total <= 99999999999n;
2063
+ const defaultMessage = context.number === void 0 ? void 0 : `${context.title ?? INVOICE_LABELS[language ?? "en"].invoice} ${context.number}`;
2064
+ const qrInput = {
2065
+ currency: context.currency ?? "CHF",
2066
+ creditor: {
2067
+ ...addressFields(issuer),
2068
+ account: value["account"]
2069
+ },
2070
+ debtor: recipient === void 0 ? void 0 : addressFields(recipient),
2071
+ amount: total !== void 0 && (payable || notification) ? toDecimal(total, 2) : void 0,
2072
+ reference: value["reference"],
2073
+ message: notification ? LABELS[language].doNotUseForPayment : value["message"] ?? defaultMessage,
2074
+ billingInformation: value["billingInformation"],
2075
+ alternativeProcedures: void 0
2076
+ };
2077
+ const result = validateQRBill(qrInput);
2078
+ if (result.success) return total !== void 0 && total < 0n ? void 0 : result.data;
2079
+ for (const issue of result.issues) {
2080
+ const path = paymentPath(issue.path);
2081
+ if (path !== void 0) issues.add(issue.code, path, issue.message);
2082
+ }
2083
+ }
2084
+ /** The fields of an address, as given, for the QR-bill. */
2085
+ function addressFields(record) {
2086
+ return {
2087
+ name: record["name"],
2088
+ street: record["street"],
2089
+ buildingNumber: record["buildingNumber"],
2090
+ postalCode: record["postalCode"],
2091
+ town: record["town"],
2092
+ country: record["country"]
2093
+ };
2094
+ }
2095
+ /** Where a problem of the QR-bill is in the invoice; `undefined` for the addresses, reported elsewhere. */
2096
+ function paymentPath(path) {
2097
+ const [first, second] = path;
2098
+ if (first === "creditor") return second === "account" ? ["payment", "account"] : void 0;
2099
+ if (first === "debtor") return void 0;
2100
+ if (first === "currency") return ["currency"];
2101
+ return ["payment", ...path];
2102
+ }
2103
+ // src/page/decorations.ts
2104
+ /**
2105
+ * What every page carries once the whole invoice is drawn and the number of pages known: the bar of colour along
2106
+ * the top (theme `modern`), and the number of the page when there are several.
2107
+ *
2108
+ * @module
2109
+ */
2110
+ /** The height of the bar along the top of each page. */
2111
+ const TOP_BAR_HEIGHT = 3;
2112
+ /** The number of the page: baseline and size. */
2113
+ const PAGE_NUMBER_BASELINE = 10;
2114
+ const PAGE_NUMBER_SIZE = 7.5;
2115
+ /**
2116
+ * Draws the bar of colour and the number of each page, going back to every page of the document.
2117
+ *
2118
+ * @param context - The invoice drawn, whose document keeps its pages in memory (`bufferPages`).
2119
+ */
2120
+ function drawPageDecorations(context) {
2121
+ const { pen, colors, labels } = context;
2122
+ const { doc } = pen;
2123
+ const { count } = doc.bufferedPageRange();
2124
+ for (let page = 0; page < count; page++) {
2125
+ doc.switchToPage(page);
2126
+ if (colors.topBar !== void 0) pen.rect(0, 0, doc.page.width / POINTS_PER_MM, TOP_BAR_HEIGHT, colors.topBar);
2127
+ if (count > 1) {
2128
+ const number = fill(labels.page, {
2129
+ page: page + 1,
2130
+ pages: count
2131
+ });
2132
+ pen.text(number, 190, PAGE_NUMBER_BASELINE, {
2133
+ size: PAGE_NUMBER_SIZE,
2134
+ color: colors.muted,
2135
+ align: "right"
2136
+ });
2137
+ }
2138
+ }
2139
+ }
2140
+ // src/page/flow.ts
2141
+ /** Where the baseline of a line sits under its top, as a share of the line height. */
2142
+ const BASELINE_SHARE$1 = .76;
2143
+ /**
2144
+ * Where the next content goes: the current page and the height on it. A block that does not fit above
2145
+ * {@link CONTENT_BOTTOM} goes to a new page, which gets the short header of the following pages.
2146
+ */
2147
+ var Flow = class {
2148
+ /** The top of the next content on the current page. */
2149
+ y;
2150
+ /** The document. */
2151
+ doc;
2152
+ /** Draws the header of a new page. */
2153
+ header;
2154
+ /**
2155
+ * @param doc - The document.
2156
+ * @param y - Where the content starts on the first page.
2157
+ * @param header - Draws the short header of the following pages.
2158
+ */
2159
+ constructor(doc, y, header) {
2160
+ this.doc = doc;
2161
+ this.y = y;
2162
+ this.header = header;
2163
+ }
2164
+ /**
2165
+ * Makes room for a block: a new page when it does not fit under the current position.
2166
+ *
2167
+ * @param height - The height of the block.
2168
+ * @param bottom - The lowest point the block may reach; {@link CONTENT_BOTTOM} by default.
2169
+ * @returns Whether a page was added.
2170
+ */
2171
+ ensure(height, bottom = 282) {
2172
+ if (this.y + height <= bottom) return false;
2173
+ const { page } = this.doc;
2174
+ this.doc.addPage({
2175
+ size: [page.width, page.height],
2176
+ margins: page.margins
2177
+ });
2178
+ this.header();
2179
+ this.y = 28;
2180
+ return true;
2181
+ }
2182
+ /**
2183
+ * Draws lines one under the other from the current position, each going to a new page when it does not fit.
2184
+ * Afterwards the position is under the last line.
2185
+ *
2186
+ * @param lines - The lines, each fitting the width already.
2187
+ * @param lineHeight - The height of a line, in millimetres.
2188
+ * @param draw - Writes a line at its baseline.
2189
+ */
2190
+ paragraph(lines, lineHeight, draw) {
2191
+ for (const line of lines) {
2192
+ this.ensure(lineHeight);
2193
+ draw(line, this.y + lineHeight * BASELINE_SHARE$1);
2194
+ this.y += lineHeight;
2195
+ }
2196
+ }
2197
+ };
2198
+ // src/summary/mentions.ts
2199
+ /**
2200
+ * The ready-made mentions chosen, in the language of the invoice, then the free remarks, each a paragraph.
2201
+ *
2202
+ * @param context - The invoice being drawn.
2203
+ * @returns The paragraphs, in the order they are printed.
2204
+ */
2205
+ function mentionTexts(context) {
2206
+ const { invoice, labels } = context;
2207
+ const { mentions } = invoice;
2208
+ return [
2209
+ ...mentions.notVatRegistered === true ? [labels.notVatRegistered] : [],
2210
+ ...mentions.vatExcluded === true ? [labels.vatExcluded] : [],
2211
+ ...mentions.paymentDays === void 0 ? [] : [fill(labels.paymentDays, { days: mentions.paymentDays })],
2212
+ ...mentions.thanks === true ? [labels.thanks] : [],
2213
+ ...invoice.notes
2214
+ ];
2215
+ }
2216
+ // src/summary/total-rows.ts
2217
+ /**
2218
+ * The rows of the totals, as printed: labels in the language of the invoice, amounts in its format.
2219
+ *
2220
+ * @module
2221
+ */
2222
+ /**
2223
+ * The rows of the totals: the subtotal when something lies between it and the total, the VAT of each rate (before
2224
+ * the total when it is added, after it when the prices include it), the rounding when it changed the total, and the
2225
+ * total.
2226
+ *
2227
+ * @param context - The invoice being drawn.
2228
+ * @returns The rows, as printed.
2229
+ */
2230
+ function totalRows(context) {
2231
+ const { invoice, labels } = context;
2232
+ const { totals, amountFormat, pricesIncludeVAT } = invoice;
2233
+ const money = (value) => formatMoney(value, amountFormat);
2234
+ const vat = totals.vat.map((entry) => {
2235
+ const values = {
2236
+ rate: entry.rate,
2237
+ ...entry.base !== void 0 && { base: money(entry.base) }
2238
+ };
2239
+ return {
2240
+ label: fill(entry.base === void 0 ? labels.vatRate : pricesIncludeVAT ? labels.vatIncluded : labels.vatOn, values),
2241
+ value: money(entry.amount)
2242
+ };
2243
+ });
2244
+ const subtotal = totals.subtotal === void 0 || totals.subtotal === totals.total ? [] : [{
2245
+ label: labels.subtotal,
2246
+ value: money(totals.subtotal)
2247
+ }];
2248
+ const rounding = totals.rounding === void 0 || totals.rounding === "0.00" ? [] : [{
2249
+ label: labels.rounding,
2250
+ value: money(totals.rounding)
2251
+ }];
2252
+ return {
2253
+ before: [
2254
+ ...subtotal,
2255
+ ...pricesIncludeVAT ? [] : vat,
2256
+ ...rounding
2257
+ ],
2258
+ total: {
2259
+ label: `${labels.total} ${invoice.currency}`,
2260
+ value: money(totals.total)
2261
+ },
2262
+ after: pricesIncludeVAT ? vat : []
2263
+ };
2264
+ }
2265
+ // src/summary/summary.ts
2266
+ /** Space between the table and the totals, and between the totals and the closing text. */
2267
+ const SPACE_BEFORE = 3;
2268
+ const SPACE_AFTER = 5;
2269
+ /**
2270
+ * The totals: left edge, sizes, line heights, where the baseline sits in a line, gap between labels and amounts,
2271
+ * thickness of the rule.
2272
+ */
2273
+ const TOTALS_LEFT = 110;
2274
+ const TOTALS_SIZE = 9;
2275
+ const TOTALS_LINE = 4.4;
2276
+ const TOTAL_SIZE = 10.5;
2277
+ const TOTAL_LINE = 6;
2278
+ const BASELINE_SHARE = .72;
2279
+ const TOTALS_GAP = 3;
2280
+ const TOTAL_RULE = .6;
2281
+ /** The mentions and remarks: width, size, line height, space between them. */
2282
+ const NOTES_WIDTH = 84;
2283
+ const NOTES_SIZE = 8.5;
2284
+ const NOTES_LINE = 3.8;
2285
+ const NOTES_SPACE = 1.5;
2286
+ /** The closing text. */
2287
+ const BODY_SIZE = 9;
2288
+ const BODY_LINE = 4.2;
2289
+ /**
2290
+ * Draws the totals with the mentions and remarks beside them, on the same page, then the closing text.
2291
+ *
2292
+ * @param context - The invoice being drawn.
2293
+ * @param flow - Where the content goes; afterwards, under the closing text.
2294
+ */
2295
+ function drawSummary(context, flow) {
2296
+ const { pen, invoice, colors } = context;
2297
+ const rows = totalRows(context);
2298
+ const labelWidth = 190 - Math.max(pen.measure(rows.total.value, TOTAL_SIZE, true), ...[...rows.before, ...rows.after].map((row) => pen.measure(row.value, TOTALS_SIZE))) - TOTALS_GAP - TOTALS_LEFT;
2299
+ const totalsHeight = (rows.before.length + rows.after.length) * TOTALS_LINE + TOTAL_LINE + 1;
2300
+ const noteMeasure = pen.measurer(NOTES_SIZE);
2301
+ const paragraphs = mentionTexts(context).map((note) => wrap(note, NOTES_WIDTH, noteMeasure));
2302
+ const notesHeight = paragraphs.reduce((height, lines) => height + lines.length * NOTES_LINE + NOTES_SPACE, 0);
2303
+ flow.y += SPACE_BEFORE;
2304
+ flow.ensure(Math.max(totalsHeight, notesHeight));
2305
+ const top = flow.y;
2306
+ let y = top;
2307
+ const row = (entry, size, bold, color, height) => {
2308
+ const label = shorten(entry.label, labelWidth, pen.measurer(size, bold));
2309
+ const baseline = y + height * BASELINE_SHARE;
2310
+ pen.text(label, TOTALS_LEFT, baseline, {
2311
+ size,
2312
+ bold,
2313
+ color
2314
+ });
2315
+ pen.text(entry.value, 190, baseline, {
2316
+ size,
2317
+ bold,
2318
+ color,
2319
+ align: "right"
2320
+ });
2321
+ y += height;
2322
+ };
2323
+ for (const entry of rows.before) row(entry, TOTALS_SIZE, false, colors.text, TOTALS_LINE);
2324
+ pen.line(TOTALS_LEFT, 190, y + .5, TOTAL_RULE, colors.totalRule);
2325
+ y += 1;
2326
+ row(rows.total, TOTAL_SIZE, true, colors.total, TOTAL_LINE);
2327
+ for (const entry of rows.after) row(entry, TOTALS_SIZE, false, colors.muted, TOTALS_LINE);
2328
+ let noteY = top;
2329
+ for (const lines of paragraphs) {
2330
+ lines.forEach((line, index) => {
2331
+ const baseline = noteY + TOTALS_LINE * BASELINE_SHARE + index * NOTES_LINE;
2332
+ pen.text(line, 20, baseline, {
2333
+ size: NOTES_SIZE,
2334
+ color: colors.muted
2335
+ });
2336
+ });
2337
+ noteY += lines.length * NOTES_LINE + NOTES_SPACE;
2338
+ }
2339
+ flow.y = Math.max(y, noteY);
2340
+ if (invoice.closing !== void 0) {
2341
+ flow.y += SPACE_AFTER;
2342
+ const lines = wrap(invoice.closing, 170, pen.measurer(BODY_SIZE));
2343
+ flow.paragraph(lines, BODY_LINE, (line, baseline) => {
2344
+ pen.text(line, 20, baseline, {
2345
+ size: BODY_SIZE,
2346
+ color: colors.text
2347
+ });
2348
+ });
2349
+ }
2350
+ }
2351
+ // src/table/dimensions.ts
2352
+ /**
2353
+ * The dimensions of the table of the lines, in millimetres, sizes in points.
2354
+ *
2355
+ * @module
2356
+ */
2357
+ /** Height of the header. */
2358
+ const HEADER_HEIGHT = 6.5;
2359
+ /** Baseline of the labels of the header, under its top. */
2360
+ const HEADER_BASELINE = 4.5;
2361
+ /** Size of the labels of the header. */
2362
+ const HEADER_SIZE = 8.5;
2363
+ /** Thickness of the rule under the header, in points. */
2364
+ const HEADER_RULE = .6;
2365
+ /** Height of a line of text in a row. */
2366
+ const ROW_LINE = 4.2;
2367
+ /** Space added to the lines of a row, above and below. */
2368
+ const ROW_PADDING = 1.8;
2369
+ /** Thickness of the rules between rows, in points. */
2370
+ const ROW_RULE = .2;
2371
+ // src/table/columns.ts
2372
+ /**
2373
+ * The columns of the table: those at least one line uses, each as wide as its widest text, so that no number is ever
2374
+ * cut; the descriptions take the room left.
2375
+ *
2376
+ * @module
2377
+ */
2378
+ /**
2379
+ * The columns of numbers and units that at least one line uses, in their order: quantity, unit, unit price, VAT
2380
+ * rate, amount.
2381
+ *
2382
+ * @param context - The invoice being drawn.
2383
+ * @returns The columns, with the text of each line.
2384
+ */
2385
+ function tableColumns(context) {
2386
+ const { invoice, labels } = context;
2387
+ const { lines, totals, amountFormat, currency } = invoice;
2388
+ const number = (value) => value === void 0 ? void 0 : formatMoney(value, amountFormat);
2389
+ return [
2390
+ {
2391
+ label: labels.quantity,
2392
+ cells: lines.map((line) => number(line.quantity)),
2393
+ align: "right"
2394
+ },
2395
+ {
2396
+ label: labels.unit,
2397
+ cells: lines.map((line) => line.unit),
2398
+ align: "left"
2399
+ },
2400
+ {
2401
+ label: labels.unitPrice,
2402
+ cells: lines.map((line) => number(line.unitPrice)),
2403
+ align: "right"
2404
+ },
2405
+ {
2406
+ label: labels.vat,
2407
+ cells: lines.map((line) => line.vatRate === void 0 ? void 0 : `${line.vatRate} %`),
2408
+ align: "right"
2409
+ },
2410
+ {
2411
+ label: `${labels.amount} ${currency}`,
2412
+ cells: totals.lines.map(number),
2413
+ align: "right"
2414
+ }
2415
+ ].filter((column) => column.cells.some((cell) => cell !== void 0));
2416
+ }
2417
+ /**
2418
+ * Places the columns from the right edge, each as wide as its widest text, label included; the descriptions take
2419
+ * the rest.
2420
+ *
2421
+ * @param context - The invoice being drawn.
2422
+ * @param columns - The columns, in their order.
2423
+ * @returns The columns placed, and the width left for the descriptions.
2424
+ */
2425
+ function placeColumns(context, columns) {
2426
+ const { pen } = context;
2427
+ let right = 190;
2428
+ const placed = [];
2429
+ for (const column of [...columns].reverse()) {
2430
+ const width = Math.max(pen.measure(column.label, HEADER_SIZE, true), ...column.cells.map((cell) => cell === void 0 ? 0 : pen.measure(cell, 9)));
2431
+ placed.unshift({
2432
+ ...column,
2433
+ left: right - width,
2434
+ right
2435
+ });
2436
+ right -= width + 3;
2437
+ }
2438
+ return {
2439
+ columns: placed,
2440
+ description: right - 20
2441
+ };
2442
+ }
2443
+ // src/table/table.ts
2444
+ /**
2445
+ * Draws the table of the lines from the current position, over as many pages as needed.
2446
+ *
2447
+ * @param context - The invoice being drawn.
2448
+ * @param flow - Where the content goes; afterwards, under the table.
2449
+ */
2450
+ function drawTable(context, flow) {
2451
+ const { pen, invoice, labels, colors } = context;
2452
+ const { columns: placed, description } = placeColumns(context, tableColumns(context));
2453
+ const measure = pen.measurer(9);
2454
+ const rows = invoice.lines.map((line) => wrap(line.description, description, measure));
2455
+ const rowHeight = (lines) => lines.length * ROW_LINE + ROW_PADDING;
2456
+ const header = () => {
2457
+ const top = flow.y;
2458
+ const band = 174;
2459
+ if (colors.tableHeaderBackground !== void 0) pen.rect(18, top, band, HEADER_HEIGHT, colors.tableHeaderBackground);
2460
+ const style = {
2461
+ size: HEADER_SIZE,
2462
+ bold: true,
2463
+ color: colors.tableHeaderText
2464
+ };
2465
+ pen.text(labels.description, 20, top + HEADER_BASELINE, style);
2466
+ for (const column of placed) {
2467
+ const x = column.align === "right" ? column.right : column.left;
2468
+ pen.text(column.label, x, top + HEADER_BASELINE, {
2469
+ ...style,
2470
+ align: column.align
2471
+ });
2472
+ }
2473
+ if (colors.tableHeaderRule !== void 0) pen.line(20, 190, top + HEADER_HEIGHT, HEADER_RULE, colors.tableHeaderRule);
2474
+ flow.y += HEADER_HEIGHT;
2475
+ };
2476
+ const [first = []] = rows;
2477
+ flow.ensure(HEADER_HEIGHT + rowHeight(first));
2478
+ header();
2479
+ rows.forEach((lines, index) => {
2480
+ const height = rowHeight(lines);
2481
+ if (flow.ensure(height)) header();
2482
+ const top = flow.y;
2483
+ if (colors.stripe !== void 0 && index % 2 === 1) pen.rect(18, top, 174, height, colors.stripe);
2484
+ const style = {
2485
+ size: 9,
2486
+ color: colors.text
2487
+ };
2488
+ lines.forEach((line, row) => {
2489
+ pen.text(line, 20, top + ROW_LINE + row * ROW_LINE, style);
2490
+ });
2491
+ for (const column of placed) {
2492
+ const cell = column.cells[index];
2493
+ if (cell !== void 0) {
2494
+ const x = column.align === "right" ? column.right : column.left;
2495
+ pen.text(cell, x, top + ROW_LINE, {
2496
+ ...style,
2497
+ align: column.align
2498
+ });
2499
+ }
2500
+ }
2501
+ if (colors.stripe === void 0) pen.line(20, 190, top + height, ROW_RULE, colors.line);
2502
+ flow.y += height;
2503
+ });
2504
+ }
2505
+ // src/pdf/pdf.ts
2506
+ /**
2507
+ * The invoice as a PDF: an A4 document drawn with PDFKit in Liberation Sans, the payment slip at the bottom of the
2508
+ * last page.
2509
+ *
2510
+ * @module
2511
+ */
2512
+ /**
2513
+ * Draws a valid invoice in a document, page after page, then its payment slip.
2514
+ *
2515
+ * @param doc - A PDFKit document of A4 pages without margins, keeping its pages in memory (`bufferPages`).
2516
+ * @param invoice - The invoice.
2517
+ */
2518
+ function drawInvoice(doc, invoice) {
2519
+ const context = {
2520
+ invoice,
2521
+ labels: INVOICE_LABELS[invoice.language],
2522
+ colors: resolveTheme(invoice.theme),
2523
+ pen: new Pen(doc, registerFonts(doc)),
2524
+ foreign: invoice.issuer.country !== invoice.recipient.country
2525
+ };
2526
+ drawLetterhead(context);
2527
+ drawIssuer(context);
2528
+ drawAddressWindow(context);
2529
+ const flow = new Flow(doc, 0, () => {
2530
+ drawContinuedHeader(context);
2531
+ });
2532
+ drawDetails(context, flow);
2533
+ drawTable(context, flow);
2534
+ drawSummary(context, flow);
2535
+ if (invoice.bill !== void 0) {
2536
+ const options = { language: invoice.language };
2537
+ const slip = layoutQRBill(invoice.bill, options);
2538
+ flow.ensure(slip.height - slip.bounds.y, doc.page.height / POINTS_PER_MM);
2539
+ doc.y = flow.y * POINTS_PER_MM;
2540
+ attachTo(doc, invoice.bill, options);
2541
+ }
2542
+ drawPageDecorations(context);
2543
+ }
2544
+ /**
2545
+ * Creates the PDF of an invoice: an A4 document with the letterhead of the issuer, the recipient in the window of
2546
+ * the envelope, the details, the lines over as many pages as needed, the totals, the mentions, and the payment slip
2547
+ * at the bottom of the last page, or on a page of its own when there is no room left. Without `payment`, or with a
2548
+ * negative total (a credit note), the invoice has no payment slip.
2549
+ *
2550
+ * Nothing overflows: every text is wrapped or shortened within its zone, whatever its length within
2551
+ * {@link INVOICE_LIMITS}. The fonts are Liberation Sans, embedded with only the characters used.
2552
+ *
2553
+ * @param input - The data of the invoice, checked by {@link validateInvoice}.
2554
+ * @returns The bytes of the PDF file.
2555
+ * @throws {InvoiceValidationError} When the data is not valid, with every problem found.
2556
+ * @example
2557
+ * ```ts
2558
+ * const pdf = await createInvoicePDF({
2559
+ * language: 'fr',
2560
+ * date: '2026-11-20',
2561
+ * issuer: { name: 'Max Muster & Söhne', street: 'Musterstrasse', buildingNumber: '123', postalCode: '8000', town: 'Seldwyla', country: 'CH' },
2562
+ * recipient: { name: 'Simon Muster', postalCode: '8000', town: 'Seldwyla', country: 'CH' },
2563
+ * items: [{ description: 'Conseil', quantity: 6, unit: 'h', unitPrice: '150', vatRate: '8.1' }],
2564
+ * payment: { account: 'CH44 3199 9123 0008 8901 2', reference: '210000000003139471430009017' },
2565
+ * });
2566
+ * await writeFile('facture.pdf', pdf);
2567
+ * ```
2568
+ */
2569
+ async function createInvoicePDF(input) {
2570
+ const result = validateInvoice(input);
2571
+ if (!result.success) throw new InvoiceValidationError(result.issues);
2572
+ const invoice = result.data;
2573
+ const doc = new PDFDocument({
2574
+ size: "A4",
2575
+ margin: 0,
2576
+ bufferPages: true,
2577
+ lang: invoice.language,
2578
+ info: {
2579
+ Title: [invoice.title, invoice.number].filter((part) => part !== void 0).join(" "),
2580
+ Author: invoice.issuer.name
2581
+ }
2582
+ });
2583
+ const chunks = [];
2584
+ doc.on("data", (chunk) => chunks.push(chunk));
2585
+ const ended = new Promise((resolve) => doc.on("end", resolve));
2586
+ drawInvoice(doc, invoice);
2587
+ doc.end();
2588
+ await ended;
2589
+ return new Uint8Array(Buffer.concat(chunks));
2590
+ }
2591
+ export { INVOICE_LIMITS, INVOICE_THEMES, InvoiceValidationError, computeInvoiceTotals, createInvoicePDF, validateInvoice, validateUID };
2592
+
2593
+ //# sourceMappingURL=index.js.map