rtf-codec 0.0.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +208 -0
  3. package/dist/base64.cjs +66 -0
  4. package/dist/base64.d.cts +7 -0
  5. package/dist/base64.d.ts +7 -0
  6. package/dist/base64.js +62 -0
  7. package/dist/bytes.cjs +25 -0
  8. package/dist/bytes.d.cts +6 -0
  9. package/dist/bytes.d.ts +6 -0
  10. package/dist/bytes.js +22 -0
  11. package/dist/codec.cjs +29 -0
  12. package/dist/codec.d.cts +2308 -0
  13. package/dist/codec.d.ts +2308 -0
  14. package/dist/codec.js +26 -0
  15. package/dist/codepage.cjs +98 -0
  16. package/dist/codepage.d.cts +10 -0
  17. package/dist/codepage.d.ts +10 -0
  18. package/dist/codepage.js +92 -0
  19. package/dist/diagnostics-DdDFJLNO.d.cts +51 -0
  20. package/dist/diagnostics-DdDFJLNO.d.ts +51 -0
  21. package/dist/diagnostics.cjs +75 -0
  22. package/dist/diagnostics.d.cts +2 -0
  23. package/dist/diagnostics.d.ts +2 -0
  24. package/dist/diagnostics.js +67 -0
  25. package/dist/group.cjs +40 -0
  26. package/dist/group.d.cts +11 -0
  27. package/dist/group.d.ts +11 -0
  28. package/dist/group.js +38 -0
  29. package/dist/header.cjs +378 -0
  30. package/dist/header.d.cts +43 -0
  31. package/dist/header.d.ts +43 -0
  32. package/dist/header.js +376 -0
  33. package/dist/index.cjs +28 -0
  34. package/dist/index.d.cts +8 -0
  35. package/dist/index.d.ts +8 -0
  36. package/dist/index.js +8 -0
  37. package/dist/list-id.cjs +30 -0
  38. package/dist/list-id.d.cts +16 -0
  39. package/dist/list-id.d.ts +16 -0
  40. package/dist/list-id.js +27 -0
  41. package/dist/options.cjs +7 -0
  42. package/dist/options.d.cts +18 -0
  43. package/dist/options.d.ts +18 -0
  44. package/dist/options.js +5 -0
  45. package/dist/read.cjs +854 -0
  46. package/dist/read.d.cts +16 -0
  47. package/dist/read.d.ts +16 -0
  48. package/dist/read.js +852 -0
  49. package/dist/tokenize.cjs +155 -0
  50. package/dist/tokenize.d.cts +25 -0
  51. package/dist/tokenize.d.ts +25 -0
  52. package/dist/tokenize.js +154 -0
  53. package/dist/units.cjs +43 -0
  54. package/dist/units.d.cts +17 -0
  55. package/dist/units.d.ts +17 -0
  56. package/dist/units.js +29 -0
  57. package/dist/write.cjs +364 -0
  58. package/dist/write.d.cts +7 -0
  59. package/dist/write.d.ts +7 -0
  60. package/dist/write.js +362 -0
  61. package/package.json +95 -2
package/dist/read.cjs ADDED
@@ -0,0 +1,854 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_base64 = require("./base64.cjs");
3
+ const require_diagnostics = require("./diagnostics.cjs");
4
+ const require_bytes = require("./bytes.cjs");
5
+ const require_codepage = require("./codepage.cjs");
6
+ const require_group = require("./group.cjs");
7
+ const require_units = require("./units.cjs");
8
+ const require_header = require("./header.cjs");
9
+ const require_list_id = require("./list-id.cjs");
10
+ require("./options.cjs");
11
+ const require_tokenize = require("./tokenize.cjs");
12
+ let document_schema_js = require("document-schema.js");
13
+ //#region src/read.ts
14
+ const DESTINATION_KINDS = /* @__PURE__ */ new Map([
15
+ ["fldrslt", "body"],
16
+ ["ud", "body"],
17
+ ["shppict", "body"],
18
+ ["field", "body"],
19
+ ["pict", "picture"],
20
+ ["fldinst", "fieldInstruction"],
21
+ ["listtext", "listText"],
22
+ ["pntext", "listText"],
23
+ ["upr", "unicodeWrapper"],
24
+ ["footnote", "skip"],
25
+ ["header", "skip"],
26
+ ["headerl", "skip"],
27
+ ["headerr", "skip"],
28
+ ["headerf", "skip"],
29
+ ["footer", "skip"],
30
+ ["footerl", "skip"],
31
+ ["footerr", "skip"],
32
+ ["footerf", "skip"],
33
+ ["ftnsep", "skip"],
34
+ ["ftnsepc", "skip"],
35
+ ["ftncn", "skip"],
36
+ ["aftnsep", "skip"],
37
+ ["aftnsepc", "skip"],
38
+ ["aftncn", "skip"],
39
+ ["annotation", "skip"],
40
+ ["atnid", "skip"],
41
+ ["atnauthor", "skip"],
42
+ ["atnref", "skip"],
43
+ ["atndate", "skip"],
44
+ ["atnparent", "skip"],
45
+ ["atnicn", "skip"],
46
+ ["bkmkstart", "skip"],
47
+ ["bkmkend", "skip"],
48
+ ["object", "skip"],
49
+ ["objdata", "skip"],
50
+ ["objclass", "skip"],
51
+ ["objname", "skip"],
52
+ ["do", "skip"],
53
+ ["shp", "skip"],
54
+ ["shptxt", "skip"],
55
+ ["shpinst", "skip"],
56
+ ["nonshppict", "skip"],
57
+ ["xe", "skip"],
58
+ ["tc", "skip"],
59
+ ["tcn", "skip"],
60
+ ["pn", "skip"],
61
+ ["pnseclvl", "skip"],
62
+ ["template", "skip"],
63
+ ["comment", "skip"],
64
+ ["falt", "skip"],
65
+ ["panose", "skip"],
66
+ ["fname", "skip"]
67
+ ]);
68
+ const SILENT_SKIP_DESTINATIONS = /* @__PURE__ */ new Set([
69
+ "pn",
70
+ "pnseclvl",
71
+ "nonshppict",
72
+ "falt",
73
+ "panose",
74
+ "fname",
75
+ "atnid",
76
+ "atnauthor",
77
+ "atnref",
78
+ "atndate",
79
+ "atnparent",
80
+ "atnicn",
81
+ "objclass",
82
+ "objname",
83
+ "objdata",
84
+ "shpinst",
85
+ "shptxt",
86
+ "ftnsep",
87
+ "ftnsepc",
88
+ "ftncn",
89
+ "aftnsep",
90
+ "aftnsepc",
91
+ "aftncn",
92
+ "template",
93
+ "comment",
94
+ "xe",
95
+ "tc",
96
+ "tcn"
97
+ ]);
98
+ const SPECIAL_CHARACTER_TEXT = /* @__PURE__ */ new Map([
99
+ ["tab", " "],
100
+ ["line", "\n"],
101
+ ["softline", "\n"],
102
+ ["emdash", "—"],
103
+ ["endash", "–"],
104
+ ["bullet", "•"],
105
+ ["lquote", "‘"],
106
+ ["rquote", "’"],
107
+ ["ldblquote", "“"],
108
+ ["rdblquote", "”"],
109
+ ["emspace", " "],
110
+ ["enspace", " "],
111
+ ["qmspace", " "],
112
+ ["zwj", "‍"],
113
+ ["zwnj", "‌"],
114
+ ["ltrmark", "‎"],
115
+ ["rtlmark", "‏"]
116
+ ]);
117
+ const SPECIAL_SYMBOL_TEXT = /* @__PURE__ */ new Map([
118
+ ["~", "\xA0"],
119
+ ["-", "­"],
120
+ ["_", "‑"],
121
+ ["\\", "\\"],
122
+ ["{", "{"],
123
+ ["}", "}"]
124
+ ]);
125
+ const ALIGNMENTS = /* @__PURE__ */ new Map([
126
+ ["ql", "left"],
127
+ ["qc", "center"],
128
+ ["qr", "right"],
129
+ ["qj", "justify"]
130
+ ]);
131
+ const PICTURE_FORMATS = /* @__PURE__ */ new Map([["pngblip", "png"], ["jpegblip", "jpeg"]]);
132
+ function defaultCharacterState() {
133
+ return {
134
+ bold: false,
135
+ italic: false,
136
+ underline: false,
137
+ strike: false,
138
+ hidden: false,
139
+ fontIndex: void 0,
140
+ sizeHalfPoints: 24,
141
+ colorIndex: void 0
142
+ };
143
+ }
144
+ function defaultParagraphState() {
145
+ return {
146
+ alignment: void 0,
147
+ indentLeftTwips: 0,
148
+ indentFirstLineTwips: 0,
149
+ spaceBeforeTwips: 0,
150
+ spaceAfterTwips: 0,
151
+ lineSpacingTwips: void 0,
152
+ lineSpacingIsMultiple: false,
153
+ styleIndex: void 0,
154
+ outlineLevel: void 0,
155
+ listOverrideIndex: void 0,
156
+ listLevel: 0,
157
+ inTable: false,
158
+ pageBreakBefore: false
159
+ };
160
+ }
161
+ function cloneGroupState(state) {
162
+ return {
163
+ destination: state.destination,
164
+ uc: state.uc,
165
+ char: { ...state.char },
166
+ para: { ...state.para },
167
+ field: state.field,
168
+ picture: state.picture,
169
+ inUnicodeWrapper: state.inUnicodeWrapper
170
+ };
171
+ }
172
+ function runKey(char, fontName, color, hyperlink) {
173
+ return [
174
+ char.bold ? "b" : "",
175
+ char.italic ? "i" : "",
176
+ char.underline ? "u" : "",
177
+ char.strike ? "s" : "",
178
+ fontName ?? "",
179
+ String(char.sizeHalfPoints),
180
+ color === void 0 ? "" : `${String(color.r)},${String(color.g)},${String(color.b)}`,
181
+ hyperlink ?? ""
182
+ ].join("|");
183
+ }
184
+ const HYPERLINK_TARGET = /HYPERLINK\s+"([^"]*)"/i;
185
+ const HYPERLINK_BARE_TARGET = /HYPERLINK\s+([^\s"\\]\S*)/i;
186
+ const HYPERLINK_ANCHOR = /\\l\s+"([^"]*)"/i;
187
+ function hyperlinkFromInstruction(instruction) {
188
+ const quoted = HYPERLINK_TARGET.exec(instruction);
189
+ const anchor = HYPERLINK_ANCHOR.exec(instruction);
190
+ const target = quoted?.[1] ?? HYPERLINK_BARE_TARGET.exec(instruction)?.[1];
191
+ if (target === void 0) return anchor?.[1] === void 0 ? void 0 : `#${anchor[1]}`;
192
+ return anchor?.[1] === void 0 ? target : `${target}#${anchor[1]}`;
193
+ }
194
+ function skipUnicodeFallback(tokens, from, count) {
195
+ let { index, textOffset } = from;
196
+ let remaining = count;
197
+ while (remaining > 0 && index < tokens.length) {
198
+ const token = tokens[index];
199
+ if (token === void 0) break;
200
+ if (token.kind === "groupStart" || token.kind === "groupEnd") break;
201
+ if (token.kind === "text") {
202
+ const available = token.bytes.length - textOffset;
203
+ const consumed = Math.min(available, remaining);
204
+ remaining -= consumed;
205
+ textOffset += consumed;
206
+ if (textOffset >= token.bytes.length) {
207
+ index += 1;
208
+ textOffset = 0;
209
+ }
210
+ continue;
211
+ }
212
+ remaining -= 1;
213
+ index += 1;
214
+ textOffset = 0;
215
+ }
216
+ return {
217
+ index,
218
+ textOffset
219
+ };
220
+ }
221
+ var ContentBuilder = class {
222
+ header;
223
+ sink;
224
+ sections = [];
225
+ blocks = [];
226
+ runs = [];
227
+ pendingRunKey;
228
+ pendingRunText = "";
229
+ pendingRunFields = {};
230
+ tableRows = [];
231
+ tableColumnRights = [];
232
+ rowCells = [];
233
+ cellBlocks = [];
234
+ pendingCellRights = [];
235
+ rowLeftTwips = 0;
236
+ constructor(header, sink) {
237
+ this.header = header;
238
+ this.sink = sink;
239
+ }
240
+ appendText(text, char, hyperlink) {
241
+ if (text.length === 0 || char.hidden) return;
242
+ const fontName = char.fontIndex === void 0 ? void 0 : this.header.fonts.get(char.fontIndex)?.name;
243
+ const color = char.colorIndex === void 0 ? void 0 : this.header.colors[char.colorIndex];
244
+ const key = runKey(char, fontName, color, hyperlink);
245
+ if (this.pendingRunKey !== key) {
246
+ this.flushRun();
247
+ this.pendingRunKey = key;
248
+ this.pendingRunFields = buildRunFields(char, fontName, color, hyperlink);
249
+ }
250
+ this.pendingRunText += text;
251
+ }
252
+ flushRun() {
253
+ if (this.pendingRunText.length > 0) this.runs.push({
254
+ ...this.pendingRunFields,
255
+ text: this.pendingRunText
256
+ });
257
+ this.pendingRunText = "";
258
+ this.pendingRunKey = void 0;
259
+ this.pendingRunFields = {};
260
+ }
261
+ endParagraph(para, force) {
262
+ this.flushRun();
263
+ if (!force && this.runs.length === 0) return;
264
+ const target = para.inTable ? this.cellBlocks : this.blocks;
265
+ if (!para.inTable) this.closeTable();
266
+ target.push(this.buildParagraph(para));
267
+ this.runs = [];
268
+ }
269
+ buildParagraph(para) {
270
+ const style = para.styleIndex === void 0 ? void 0 : this.header.styles.get(para.styleIndex);
271
+ const headingLevel = para.outlineLevel === void 0 ? style?.headingLevel : para.outlineLevel + 1;
272
+ const paragraph = {
273
+ kind: "paragraph",
274
+ runs: this.runs
275
+ };
276
+ const withStyle = style?.name === void 0 || style.name.length === 0 ? paragraph : {
277
+ ...paragraph,
278
+ styleId: style.name
279
+ };
280
+ return {
281
+ ...headingLevel === void 0 ? withStyle : {
282
+ ...withStyle,
283
+ headingLevel
284
+ },
285
+ ...para.alignment === void 0 ? {} : { alignment: para.alignment },
286
+ ...para.indentLeftTwips === 0 ? {} : { indentLeftPt: require_units.twipsToPoints(para.indentLeftTwips) },
287
+ ...para.indentFirstLineTwips === 0 ? {} : { indentFirstLinePt: require_units.twipsToPoints(para.indentFirstLineTwips) },
288
+ ...para.spaceBeforeTwips === 0 ? {} : { spacingBeforePt: require_units.twipsToPoints(para.spaceBeforeTwips) },
289
+ ...para.spaceAfterTwips === 0 ? {} : { spacingAfterPt: require_units.twipsToPoints(para.spaceAfterTwips) },
290
+ ...this.lineSpacingFields(para),
291
+ ...para.pageBreakBefore ? { pageBreakBefore: true } : {},
292
+ ...this.listFields(para)
293
+ };
294
+ }
295
+ lineSpacingFields(para) {
296
+ const value = para.lineSpacingTwips;
297
+ if (value === void 0 || value === 0 || !para.lineSpacingIsMultiple) return {};
298
+ const multiple = Math.abs(value) / 240;
299
+ return multiple > 0 ? { lineSpacing: multiple } : {};
300
+ }
301
+ listFields(para) {
302
+ const overrideIndex = para.listOverrideIndex;
303
+ if (overrideIndex === void 0 || overrideIndex === 0) return {};
304
+ const list = this.header.lists.get(overrideIndex);
305
+ const level = list?.levels[para.listLevel] ?? list?.levels[0];
306
+ const type = level?.numberFormat === 23 ? "bullet" : "ordered";
307
+ return { list: {
308
+ numId: require_list_id.mintRtfListNumId({
309
+ listOverrideIndex: overrideIndex,
310
+ type,
311
+ ...level?.startAt === void 0 ? {} : { start: level.startAt }
312
+ }),
313
+ level: para.listLevel
314
+ } };
315
+ }
316
+ startRowDefinition() {
317
+ this.pendingCellRights = [];
318
+ this.rowLeftTwips = 0;
319
+ }
320
+ setRowLeft(twips) {
321
+ this.rowLeftTwips = twips;
322
+ }
323
+ addCellBoundary(rightTwips) {
324
+ this.pendingCellRights.push(rightTwips);
325
+ }
326
+ endCell(para) {
327
+ this.endParagraph(para, false);
328
+ this.rowCells.push({ blocks: this.cellBlocks });
329
+ this.cellBlocks = [];
330
+ }
331
+ endRow(para) {
332
+ if (this.cellBlocks.length > 0 || this.pendingRunText.length > 0) this.endCell(para);
333
+ if (this.rowCells.length === 0) {
334
+ this.sink({
335
+ code: require_diagnostics.RtfDiagnosticCodes.TABLE_ROW_WITHOUT_DEFINITION,
336
+ severity: "warning",
337
+ message: "a \\row closed a table row that contained no \\cell marks"
338
+ });
339
+ return;
340
+ }
341
+ this.tableRows.push({ cells: this.rowCells });
342
+ if (this.tableColumnRights.length === 0) this.tableColumnRights = [...this.pendingCellRights];
343
+ this.rowCells = [];
344
+ }
345
+ closeTable() {
346
+ if (this.tableRows.length === 0) return;
347
+ const columnCount = Math.max(...this.tableRows.map((row) => row.cells.length));
348
+ this.blocks.push({
349
+ kind: "table",
350
+ rows: this.tableRows,
351
+ columnWidthsPt: this.columnWidths(columnCount)
352
+ });
353
+ this.tableRows = [];
354
+ this.tableColumnRights = [];
355
+ }
356
+ columnWidths(columnCount) {
357
+ const rights = this.tableColumnRights;
358
+ const widths = [];
359
+ let previous = this.rowLeftTwips;
360
+ for (const right of rights.slice(0, columnCount)) {
361
+ widths.push(require_units.twipsToPoints(right - previous));
362
+ previous = right;
363
+ }
364
+ const usable = require_units.twipsToPoints(this.header.page.paperWidthTwips - this.header.page.marginLeftTwips - this.header.page.marginRightTwips);
365
+ if (widths.length !== columnCount || widths.some((width) => width <= 0)) {
366
+ this.sink({
367
+ code: require_diagnostics.RtfDiagnosticCodes.TABLE_COLUMN_WIDTH_INVALID,
368
+ severity: "warning",
369
+ message: "the row's \\cellxN boundaries do not describe increasing column widths for every column; falling back to an even split of the page's text width"
370
+ });
371
+ return Array.from({ length: columnCount }, () => usable / columnCount);
372
+ }
373
+ return widths;
374
+ }
375
+ addBlock(block) {
376
+ this.flushRun();
377
+ this.blocks.push(block);
378
+ }
379
+ endSection(pageSize, margins, para) {
380
+ this.endParagraph(para, false);
381
+ this.closeTable();
382
+ if (this.blocks.length === 0 && this.sections.length > 0) return;
383
+ this.sections.push({
384
+ pageSize,
385
+ margins,
386
+ blocks: this.blocks
387
+ });
388
+ this.blocks = [];
389
+ }
390
+ finish(metadata, pageSize, margins, para) {
391
+ this.endSection(pageSize, margins, para);
392
+ if (this.sections.length === 0) this.sections.push({
393
+ pageSize,
394
+ margins,
395
+ blocks: []
396
+ });
397
+ return {
398
+ kind: "wordprocessing",
399
+ metadata,
400
+ sections: this.sections
401
+ };
402
+ }
403
+ };
404
+ function buildRunFields(char, fontName, color, hyperlink) {
405
+ return {
406
+ ...char.bold ? { bold: true } : {},
407
+ ...char.italic ? { italic: true } : {},
408
+ ...char.underline ? { underline: true } : {},
409
+ ...char.strike ? { strike: true } : {},
410
+ ...fontName === void 0 || fontName.length === 0 ? {} : { fontFamily: fontName },
411
+ sizePt: require_units.halfPointsToPoints(char.sizeHalfPoints),
412
+ ...color === void 0 ? {} : { color },
413
+ ...hyperlink === void 0 ? {} : { hyperlink }
414
+ };
415
+ }
416
+ function buildPicture(picture, sink) {
417
+ if (picture.format === void 0) {
418
+ sink({
419
+ code: require_diagnostics.RtfDiagnosticCodes.UNSUPPORTED_PICTURE_FORMAT,
420
+ severity: "warning",
421
+ message: `a \\pict destination declared ${picture.unsupportedFormat ?? "no"} picture format; ContentImageBlock carries PNG and JPEG only, so this picture is dropped`
422
+ });
423
+ return;
424
+ }
425
+ const bytes = picture.binary.length > 0 ? Uint8Array.from(picture.binary) : require_base64.hexToBytes(picture.hex);
426
+ if (bytes.length === 0) {
427
+ sink({
428
+ code: require_diagnostics.RtfDiagnosticCodes.UNSUPPORTED_PICTURE_FORMAT,
429
+ severity: "warning",
430
+ message: "a \\pict destination carried no picture payload"
431
+ });
432
+ return;
433
+ }
434
+ const scaleX = picture.scaleXPercent / 100;
435
+ const scaleY = picture.scaleYPercent / 100;
436
+ const widthPt = picture.widthGoalTwips === void 0 ? picture.widthPixels === void 0 ? void 0 : require_units.pixelsToPoints(picture.widthPixels) : require_units.twipsToPoints(picture.widthGoalTwips);
437
+ const heightPt = picture.heightGoalTwips === void 0 ? picture.heightPixels === void 0 ? void 0 : require_units.pixelsToPoints(picture.heightPixels) : require_units.twipsToPoints(picture.heightGoalTwips);
438
+ if (widthPt === void 0 || heightPt === void 0) {
439
+ sink({
440
+ code: require_diagnostics.RtfDiagnosticCodes.PICTURE_SIZE_UNSTATED,
441
+ severity: "warning",
442
+ message: "a \\pict destination stated neither \\picwgoalN/\\pichgoalN nor \\picwN/\\pichN, so its rendered size is unknown and the picture is dropped; decoding the payload's own intrinsic size would need an image decoder this package deliberately does not carry"
443
+ });
444
+ return;
445
+ }
446
+ const scaledWidth = widthPt * scaleX;
447
+ const scaledHeight = heightPt * scaleY;
448
+ if (scaledWidth <= 0 || scaledHeight <= 0) {
449
+ sink({
450
+ code: require_diagnostics.RtfDiagnosticCodes.PICTURE_SIZE_UNSTATED,
451
+ severity: "warning",
452
+ message: "a \\pict destination's stated size scaled to zero or less, which ContentImageBlock cannot express"
453
+ });
454
+ return;
455
+ }
456
+ return {
457
+ kind: "image",
458
+ format: picture.format,
459
+ base64: require_base64.bytesToBase64(bytes),
460
+ widthPt: scaledWidth,
461
+ heightPt: scaledHeight
462
+ };
463
+ }
464
+ function defaultPictureState() {
465
+ return {
466
+ format: void 0,
467
+ unsupportedFormat: void 0,
468
+ widthGoalTwips: void 0,
469
+ heightGoalTwips: void 0,
470
+ widthPixels: void 0,
471
+ heightPixels: void 0,
472
+ scaleXPercent: 100,
473
+ scaleYPercent: 100,
474
+ hex: "",
475
+ binary: []
476
+ };
477
+ }
478
+ function toggleValue(param) {
479
+ return param === void 0 || param !== 0;
480
+ }
481
+ function readRtfDetail(input, options) {
482
+ options.signal?.throwIfAborted();
483
+ const maxInputBytes = options.maxInputBytes ?? 67108864;
484
+ if (input.length > maxInputBytes) throw new require_diagnostics.RtfInputTooLargeError(input.length, maxInputBytes);
485
+ const maxGroupDepth = options.maxGroupDepth ?? 256;
486
+ const diagnostics = [];
487
+ const callerSink = options.sink;
488
+ const sink = (diagnostic) => {
489
+ diagnostics.push(diagnostic);
490
+ callerSink?.(diagnostic);
491
+ };
492
+ const tokens = require_tokenize.tokenizeRtf(input);
493
+ assertRtfHeaderPresent(tokens);
494
+ const header = require_header.readRtfHeader(tokens, sink);
495
+ const builder = new ContentBuilder(header, sink);
496
+ const pageSize = {
497
+ widthPt: require_units.twipsToPoints(header.page.paperWidthTwips),
498
+ heightPt: require_units.twipsToPoints(header.page.paperHeightTwips)
499
+ };
500
+ const margins = {
501
+ topPt: require_units.twipsToPoints(header.page.marginTopTwips),
502
+ rightPt: require_units.twipsToPoints(header.page.marginRightTwips),
503
+ bottomPt: require_units.twipsToPoints(header.page.marginBottomTwips),
504
+ leftPt: require_units.twipsToPoints(header.page.marginLeftTwips)
505
+ };
506
+ const root = {
507
+ destination: "body",
508
+ uc: 1,
509
+ char: defaultCharacterState(),
510
+ para: defaultParagraphState(),
511
+ field: void 0,
512
+ picture: void 0,
513
+ inUnicodeWrapper: false
514
+ };
515
+ const stack = [root];
516
+ let state = root;
517
+ let pendingBytes = [];
518
+ const activeCodepage = () => {
519
+ return (state.char.fontIndex === void 0 ? void 0 : header.fonts.get(state.char.fontIndex)?.codepage) ?? header.codepage;
520
+ };
521
+ const flushBytes = () => {
522
+ if (pendingBytes.length === 0) return;
523
+ const text = require_codepage.decodeCodepageBytes(Uint8Array.from(pendingBytes), activeCodepage(), sink);
524
+ pendingBytes = [];
525
+ emitText(text);
526
+ };
527
+ const emitText = (text) => {
528
+ if (state.destination === "body") {
529
+ const hyperlink = state.field === void 0 ? void 0 : hyperlinkFromInstruction(state.field.instruction);
530
+ builder.appendText(text, state.char, hyperlink);
531
+ return;
532
+ }
533
+ if (state.destination === "fieldInstruction" && state.field !== void 0) state.field.instruction += text;
534
+ };
535
+ let index = 0;
536
+ let textOffset = 0;
537
+ while (index < tokens.length) {
538
+ const token = tokens[index];
539
+ if (token === void 0) break;
540
+ if (token.kind === "groupStart") {
541
+ flushBytes();
542
+ const head = require_group.groupHead(tokens, index);
543
+ const known = head.destination === void 0 ? void 0 : DESTINATION_KINDS.get(head.destination);
544
+ const isHeaderTable = head.destination !== void 0 && require_header.HEADER_DESTINATIONS.has(head.destination);
545
+ const wrapperChild = state.inUnicodeWrapper;
546
+ const kind = isHeaderTable || wrapperChild && head.destination !== "ud" ? "skip" : known ?? (head.ignorable ? "skip" : state.destination);
547
+ if (head.destination !== void 0 && !isHeaderTable) {
548
+ if (head.ignorable && known === void 0) sink({
549
+ code: require_diagnostics.RtfDiagnosticCodes.UNKNOWN_DESTINATION_SKIPPED,
550
+ severity: "info",
551
+ message: `the ignorable destination \\${head.destination} is not recognised and its content is discarded, as the specification requires`
552
+ });
553
+ else if (known === "skip" && !SILENT_SKIP_DESTINATIONS.has(head.destination)) sink({
554
+ code: require_diagnostics.RtfDiagnosticCodes.CONTENT_DESTINATION_SKIPPED,
555
+ severity: "warning",
556
+ message: `the \\${head.destination} destination's content is discarded: no ContentDocument position carries it`
557
+ });
558
+ }
559
+ if (kind === "skip") {
560
+ index = require_group.matchingGroupEnd(tokens, index) + 1;
561
+ textOffset = 0;
562
+ continue;
563
+ }
564
+ if (stack.length >= maxGroupDepth) throw new require_diagnostics.RtfNestingLimitExceededError(maxGroupDepth);
565
+ const child = cloneGroupState(state);
566
+ child.inUnicodeWrapper = kind === "unicodeWrapper";
567
+ if (known !== void 0) {
568
+ child.destination = kind;
569
+ if (head.destination === "field") child.field = { instruction: "" };
570
+ if (kind === "picture") child.picture = defaultPictureState();
571
+ index = head.contentStart;
572
+ } else index += 1;
573
+ stack.push(child);
574
+ state = child;
575
+ textOffset = 0;
576
+ continue;
577
+ }
578
+ if (token.kind === "groupEnd") {
579
+ flushBytes();
580
+ if (state.destination === "picture" && state.picture !== void 0) {
581
+ const image = buildPicture(state.picture, sink);
582
+ if (image !== void 0) builder.addBlock(image);
583
+ }
584
+ if (stack.length > 1) {
585
+ stack.pop();
586
+ const parent = stack[stack.length - 1];
587
+ if (parent !== void 0) state = parent;
588
+ } else sink({
589
+ code: require_diagnostics.RtfDiagnosticCodes.UNBALANCED_GROUP,
590
+ severity: "warning",
591
+ message: "a closing brace appeared with no group open; the extra brace is ignored",
592
+ tokenIndex: index
593
+ });
594
+ index += 1;
595
+ textOffset = 0;
596
+ continue;
597
+ }
598
+ if (token.kind === "text") {
599
+ const slice = textOffset === 0 ? token.bytes : token.bytes.subarray(textOffset);
600
+ if (state.destination === "picture" && state.picture !== void 0) state.picture.hex += require_bytes.asciiStringFromBytes(slice);
601
+ else require_bytes.appendBytes(pendingBytes, slice);
602
+ index += 1;
603
+ textOffset = 0;
604
+ continue;
605
+ }
606
+ if (token.kind === "binary") {
607
+ if (state.destination === "picture" && state.picture !== void 0) require_bytes.appendBytes(state.picture.binary, token.bytes);
608
+ index += 1;
609
+ continue;
610
+ }
611
+ if (token.kind === "hex") {
612
+ if (state.destination === "picture" && state.picture !== void 0) state.picture.binary.push(token.byte);
613
+ else pendingBytes.push(token.byte);
614
+ index += 1;
615
+ continue;
616
+ }
617
+ if (token.kind === "controlSymbol") {
618
+ const text = SPECIAL_SYMBOL_TEXT.get(token.symbol);
619
+ if (text !== void 0) {
620
+ flushBytes();
621
+ emitText(text);
622
+ }
623
+ index += 1;
624
+ continue;
625
+ }
626
+ if (token.name === "u") {
627
+ flushBytes();
628
+ const code = token.param;
629
+ if (code !== void 0) emitText(String.fromCharCode(code < 0 ? code + 65536 : code));
630
+ const skipped = skipUnicodeFallback(tokens, {
631
+ index: index + 1,
632
+ textOffset: 0
633
+ }, state.uc);
634
+ index = skipped.index;
635
+ textOffset = skipped.textOffset;
636
+ continue;
637
+ }
638
+ const special = SPECIAL_CHARACTER_TEXT.get(token.name);
639
+ if (special !== void 0) {
640
+ flushBytes();
641
+ emitText(special);
642
+ index += 1;
643
+ continue;
644
+ }
645
+ flushBytes();
646
+ applyControlWord(token.name, token.param, state, builder, header, sink);
647
+ index += 1;
648
+ }
649
+ flushBytes();
650
+ if (stack.length > 1) sink({
651
+ code: require_diagnostics.RtfDiagnosticCodes.UNBALANCED_GROUP,
652
+ severity: "warning",
653
+ message: `${String(stack.length - 1)} group(s) were still open at the end of the input; each is treated as closing there`
654
+ });
655
+ return {
656
+ document: builder.finish(header.metadata, pageSize, margins, root.para),
657
+ diagnostics
658
+ };
659
+ }
660
+ function assertRtfHeaderPresent(tokens) {
661
+ const first = tokens[0];
662
+ const second = tokens[1];
663
+ if (first?.kind !== "groupStart" || second?.kind !== "controlWord" || second.name !== "rtf") throw new require_diagnostics.RtfNotAnRtfDocumentError();
664
+ }
665
+ function applyPictureControlWord(name, param, picture) {
666
+ const format = PICTURE_FORMATS.get(name);
667
+ if (format !== void 0) {
668
+ picture.format = format;
669
+ return;
670
+ }
671
+ switch (name) {
672
+ case "emfblip":
673
+ case "macpict":
674
+ case "wmetafile":
675
+ case "pmmetafile":
676
+ case "dibitmap":
677
+ case "wbitmap":
678
+ picture.unsupportedFormat = `\\${name}`;
679
+ return;
680
+ case "picwgoal":
681
+ picture.widthGoalTwips = param;
682
+ return;
683
+ case "pichgoal":
684
+ picture.heightGoalTwips = param;
685
+ return;
686
+ case "picw":
687
+ picture.widthPixels = param;
688
+ return;
689
+ case "pich":
690
+ picture.heightPixels = param;
691
+ return;
692
+ case "picscalex":
693
+ if (param !== void 0) picture.scaleXPercent = param;
694
+ return;
695
+ case "picscaley":
696
+ if (param !== void 0) picture.scaleYPercent = param;
697
+ return;
698
+ default: return;
699
+ }
700
+ }
701
+ function applyCharacterControlWord(name, param, state, header) {
702
+ switch (name) {
703
+ case "plain":
704
+ state.char = defaultCharacterState();
705
+ return true;
706
+ case "b":
707
+ state.char.bold = toggleValue(param);
708
+ return true;
709
+ case "i":
710
+ state.char.italic = toggleValue(param);
711
+ return true;
712
+ case "strike":
713
+ state.char.strike = toggleValue(param);
714
+ return true;
715
+ case "v":
716
+ state.char.hidden = toggleValue(param);
717
+ return true;
718
+ case "ulnone":
719
+ state.char.underline = false;
720
+ return true;
721
+ case "f":
722
+ state.char.fontIndex = param ?? header.defaultFontIndex;
723
+ return true;
724
+ case "fs":
725
+ state.char.sizeHalfPoints = param ?? 24;
726
+ return true;
727
+ case "cf":
728
+ state.char.colorIndex = param;
729
+ return true;
730
+ case "uc":
731
+ if (param !== void 0 && param >= 0) state.uc = param;
732
+ return true;
733
+ default:
734
+ if (name.startsWith("ul") && name !== "ulc") {
735
+ state.char.underline = toggleValue(param);
736
+ return true;
737
+ }
738
+ return false;
739
+ }
740
+ }
741
+ function applyParagraphControlWord(name, param, state) {
742
+ const alignment = ALIGNMENTS.get(name);
743
+ if (alignment !== void 0) {
744
+ state.para.alignment = alignment;
745
+ return true;
746
+ }
747
+ switch (name) {
748
+ case "pard":
749
+ state.para = defaultParagraphState();
750
+ return true;
751
+ case "s":
752
+ state.para.styleIndex = param;
753
+ return true;
754
+ case "outlinelevel":
755
+ state.para.outlineLevel = param === void 0 || param > 8 ? void 0 : param;
756
+ return true;
757
+ case "li":
758
+ case "lin":
759
+ state.para.indentLeftTwips = param ?? 0;
760
+ return true;
761
+ case "fi":
762
+ state.para.indentFirstLineTwips = param ?? 0;
763
+ return true;
764
+ case "sb":
765
+ state.para.spaceBeforeTwips = param ?? 0;
766
+ return true;
767
+ case "sa":
768
+ state.para.spaceAfterTwips = param ?? 0;
769
+ return true;
770
+ case "sl":
771
+ state.para.lineSpacingTwips = param;
772
+ return true;
773
+ case "slmult":
774
+ state.para.lineSpacingIsMultiple = toggleValue(param);
775
+ return true;
776
+ case "pagebb":
777
+ state.para.pageBreakBefore = true;
778
+ return true;
779
+ case "ls":
780
+ state.para.listOverrideIndex = param;
781
+ return true;
782
+ case "ilvl":
783
+ state.para.listLevel = param ?? 0;
784
+ return true;
785
+ case "intbl":
786
+ state.para.inTable = true;
787
+ return true;
788
+ default: return false;
789
+ }
790
+ }
791
+ function applyStructureControlWord(name, param, state, builder, sink) {
792
+ switch (name) {
793
+ case "par":
794
+ builder.endParagraph(state.para, true);
795
+ return true;
796
+ case "trowd":
797
+ state.para.inTable = true;
798
+ builder.startRowDefinition();
799
+ return true;
800
+ case "trleft":
801
+ builder.setRowLeft(param ?? 0);
802
+ return true;
803
+ case "cellx":
804
+ if (param !== void 0) builder.addCellBoundary(param);
805
+ return true;
806
+ case "cell":
807
+ builder.endCell(state.para);
808
+ return true;
809
+ case "row":
810
+ builder.endRow(state.para);
811
+ state.para.inTable = false;
812
+ return true;
813
+ case "nestcell":
814
+ case "nestrow":
815
+ sink({
816
+ code: require_diagnostics.RtfDiagnosticCodes.NESTED_TABLE_FLATTENED,
817
+ severity: "warning",
818
+ message: "a nested table's cell/row marks are read as ordinary cell content; the inner table's own structure is not reconstructed"
819
+ });
820
+ return true;
821
+ case "page":
822
+ builder.endParagraph(state.para, false);
823
+ builder.addBlock({ kind: "pageBreak" });
824
+ return true;
825
+ case "sect":
826
+ builder.endParagraph(state.para, true);
827
+ return true;
828
+ case "sectd": return true;
829
+ default: return false;
830
+ }
831
+ }
832
+ function applyControlWord(name, param, state, builder, header, sink) {
833
+ const picture = state.picture;
834
+ if (state.destination === "picture" && picture !== void 0) {
835
+ applyPictureControlWord(name, param, picture);
836
+ return;
837
+ }
838
+ if (applyCharacterControlWord(name, param, state, header)) return;
839
+ if (applyParagraphControlWord(name, param, state)) return;
840
+ applyStructureControlWord(name, param, state, builder, sink);
841
+ }
842
+ function readRtfContent(input, options = {}) {
843
+ return readRtfDetail(typeof input === "string" ? require_bytes.rtfBytesFromLatin1(input) : input, options);
844
+ }
845
+ function readRtf(input, options = {}) {
846
+ const { document, diagnostics } = readRtfContent(input, options);
847
+ return {
848
+ documentPackage: (0, document_schema_js.assembleTree)(document),
849
+ diagnostics
850
+ };
851
+ }
852
+ //#endregion
853
+ exports.readRtf = readRtf;
854
+ exports.readRtfContent = readRtfContent;