@folijs/docx 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +21 -0
  3. package/README.md +141 -2
  4. package/dist/export/content.d.ts +17 -0
  5. package/dist/export/content.d.ts.map +1 -0
  6. package/dist/export/content.js +165 -0
  7. package/dist/export/content.js.map +1 -0
  8. package/dist/export/index.d.ts +14 -0
  9. package/dist/export/index.d.ts.map +1 -0
  10. package/dist/export/index.js +352 -0
  11. package/dist/export/index.js.map +1 -0
  12. package/dist/export/parts.d.ts +24 -0
  13. package/dist/export/parts.d.ts.map +1 -0
  14. package/dist/export/parts.js +413 -0
  15. package/dist/export/parts.js.map +1 -0
  16. package/dist/export/properties.d.ts +39 -0
  17. package/dist/export/properties.d.ts.map +1 -0
  18. package/dist/export/properties.js +506 -0
  19. package/dist/export/properties.js.map +1 -0
  20. package/dist/export/xmlout.d.ts +63 -0
  21. package/dist/export/xmlout.d.ts.map +1 -0
  22. package/dist/export/xmlout.js +194 -0
  23. package/dist/export/xmlout.js.map +1 -0
  24. package/dist/import/content.d.ts +35 -0
  25. package/dist/import/content.d.ts.map +1 -0
  26. package/dist/import/content.js +370 -0
  27. package/dist/import/content.js.map +1 -0
  28. package/dist/import/index.d.ts +26 -0
  29. package/dist/import/index.d.ts.map +1 -0
  30. package/dist/import/index.js +96 -0
  31. package/dist/import/index.js.map +1 -0
  32. package/dist/import/ooxml.d.ts +38 -0
  33. package/dist/import/ooxml.d.ts.map +1 -0
  34. package/dist/import/ooxml.js +70 -0
  35. package/dist/import/ooxml.js.map +1 -0
  36. package/dist/import/parts.d.ts +35 -0
  37. package/dist/import/parts.d.ts.map +1 -0
  38. package/dist/import/parts.js +365 -0
  39. package/dist/import/parts.js.map +1 -0
  40. package/dist/import/properties.d.ts +50 -0
  41. package/dist/import/properties.d.ts.map +1 -0
  42. package/dist/import/properties.js +403 -0
  43. package/dist/import/properties.js.map +1 -0
  44. package/dist/import/report.d.ts +28 -0
  45. package/dist/import/report.d.ts.map +1 -0
  46. package/dist/import/report.js +42 -0
  47. package/dist/import/report.js.map +1 -0
  48. package/dist/index.d.ts +6 -0
  49. package/dist/index.d.ts.map +1 -0
  50. package/dist/index.js +6 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/package.d.ts +70 -0
  53. package/dist/package.d.ts.map +1 -0
  54. package/dist/package.js +259 -0
  55. package/dist/package.js.map +1 -0
  56. package/dist/xml.d.ts +79 -0
  57. package/dist/xml.d.ts.map +1 -0
  58. package/dist/xml.js +384 -0
  59. package/dist/xml.js.map +1 -0
  60. package/dist/zip.d.ts +66 -0
  61. package/dist/zip.d.ts.map +1 -0
  62. package/dist/zip.js +356 -0
  63. package/dist/zip.js.map +1 -0
  64. package/package.json +36 -3
  65. package/src/export/content.ts +229 -0
  66. package/src/export/index.ts +445 -0
  67. package/src/export/parts.ts +545 -0
  68. package/src/export/properties.ts +608 -0
  69. package/src/export/xmlout.ts +225 -0
  70. package/src/import/content.ts +413 -0
  71. package/src/import/index.ts +126 -0
  72. package/src/import/ooxml.ts +77 -0
  73. package/src/import/parts.ts +423 -0
  74. package/src/import/properties.ts +504 -0
  75. package/src/import/report.ts +64 -0
  76. package/src/index.ts +24 -0
  77. package/src/package.ts +328 -0
  78. package/src/xml.ts +443 -0
  79. package/src/zip.ts +401 -0
package/dist/zip.js ADDED
@@ -0,0 +1,356 @@
1
+ /**
2
+ * The zip container of a `.docx`, on the platform's `DecompressionStream`/`CompressionStream`
3
+ * ("deflate-raw": browsers, workers, Node 20.12+); no dependency.
4
+ *
5
+ * Reading keeps every entry's compressed bytes as they are in the file, so writing copies an
6
+ * untouched entry verbatim: its data is the original byte for byte, never recompressed. Only
7
+ * replaced entries are compressed again.
8
+ */
9
+ /** A file that is not a zip Foli can read, or is damaged. */
10
+ export class ZipError extends Error {
11
+ name = "ZipError";
12
+ }
13
+ const LOCAL = 0x04034b50;
14
+ const CENTRAL = 0x02014b50;
15
+ const END = 0x06054b50;
16
+ const DESCRIPTOR = 0x08074b50;
17
+ const UTF8_NAME = 0x0800;
18
+ const textDecoder = new TextDecoder();
19
+ /**
20
+ * Lists the entries of a zip from its central directory, in the directory's order. Nothing is
21
+ * decompressed: see {@link inflateEntry}. Every entry is checked against its local header, and
22
+ * entries may not overlap: Foli reads what any other zip reader would.
23
+ */
24
+ export function readZip(bytes, limits = {}) {
25
+ const maxEntries = limits.maxEntries ?? 10_000;
26
+ const maxSize = limits.maxSize ?? 512 * 1024 * 1024;
27
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
28
+ const end = findEnd(view);
29
+ if (view.getUint16(end + 4, true) !== 0 || view.getUint16(end + 6, true) !== 0) {
30
+ throw new ZipError("Multi-disk zip archives are not supported");
31
+ }
32
+ const count = view.getUint16(end + 10, true);
33
+ const dirSize = view.getUint32(end + 12, true);
34
+ const dirOffset = view.getUint32(end + 16, true);
35
+ // shortcut: no ZIP64 (Word writes it only past 4 GiB or 65 535 entries); add if a real file needs it.
36
+ if (count === 0xffff || dirSize === 0xffffffff || dirOffset === 0xffffffff) {
37
+ throw new ZipError("ZIP64 archives are not supported");
38
+ }
39
+ if (count > maxEntries)
40
+ throw new ZipError(`Too many entries: ${count} (limit ${maxEntries})`);
41
+ const entries = [];
42
+ const spans = [];
43
+ const seen = new Set();
44
+ let total = 0;
45
+ let at = dirOffset;
46
+ for (let i = 0; i < count; i++) {
47
+ if (at + 46 > end || view.getUint32(at, true) !== CENTRAL) {
48
+ throw new ZipError("Damaged zip: bad central directory record");
49
+ }
50
+ const flags = view.getUint16(at + 8, true);
51
+ const method = view.getUint16(at + 10, true);
52
+ const time = view.getUint16(at + 12, true);
53
+ const date = view.getUint16(at + 14, true);
54
+ const crc32 = view.getUint32(at + 16, true);
55
+ const compressedSize = view.getUint32(at + 20, true);
56
+ const size = view.getUint32(at + 24, true);
57
+ const nameLength = view.getUint16(at + 28, true);
58
+ const recordLength = 46 + nameLength + view.getUint16(at + 30, true) + view.getUint16(at + 32, true);
59
+ const local = view.getUint32(at + 42, true);
60
+ if (at + recordLength > end)
61
+ throw new ZipError("Damaged zip: bad central directory record");
62
+ const central = bytes.subarray(at, at + recordLength);
63
+ const nameBytes = bytes.subarray(at + 46, at + 46 + nameLength);
64
+ // shortcut: names without the UTF-8 flag (CP437) are read as UTF-8, right for ASCII, which
65
+ // part names are; the bytes are written back unchanged either way.
66
+ const name = textDecoder.decode(nameBytes);
67
+ at += recordLength;
68
+ if (flags & 0x41)
69
+ throw new ZipError(`Encrypted entry: ${name}`);
70
+ if (compressedSize === 0xffffffff || size === 0xffffffff || local === 0xffffffff) {
71
+ throw new ZipError("ZIP64 archives are not supported");
72
+ }
73
+ if (method !== 0 && method !== 8) {
74
+ throw new ZipError(`Unsupported compression method ${method}: ${name}`);
75
+ }
76
+ // Deflate expands at most 1032 times: a larger declared size is a lie meant to make the
77
+ // reader allocate it.
78
+ if (method === 0 ? size !== compressedSize : size > compressedSize * 1032 + 1024) {
79
+ throw new ZipError(`Damaged zip: impossible size for ${name}`);
80
+ }
81
+ const key = name.toLowerCase();
82
+ if (seen.has(key))
83
+ throw new ZipError(`Duplicate entry: ${name}`);
84
+ seen.add(key);
85
+ total += size;
86
+ if (total > maxSize)
87
+ throw new ZipError(`Too large once uncompressed (limit ${maxSize} bytes)`);
88
+ if (local + 30 > dirOffset || view.getUint32(local, true) !== LOCAL) {
89
+ throw new ZipError(`Damaged zip: no local header for ${name}`);
90
+ }
91
+ const localNameLength = view.getUint16(local + 26, true);
92
+ // The data follows the local header, whose extra field may differ from the central record's.
93
+ const data = local + 30 + localNameLength + view.getUint16(local + 28, true);
94
+ if (data + compressedSize > dirOffset) {
95
+ throw new ZipError(`Damaged zip: data out of range for ${name}`);
96
+ }
97
+ const mismatch = () => new ZipError(`Damaged zip: local header does not match the directory for ${name}`);
98
+ if (view.getUint16(local + 8, true) !== method ||
99
+ !equalBytes(bytes.subarray(local + 30, local + 30 + localNameLength), nameBytes)) {
100
+ throw mismatch();
101
+ }
102
+ // A data descriptor (flag 3) follows the data with the CRC and sizes, with or without a
103
+ // signature; the local header then may hold zeros. Either way they must agree.
104
+ let descriptorLength = 0;
105
+ let check = local + 14;
106
+ if (flags & 0x08) {
107
+ const after = data + compressedSize;
108
+ const signed = after + 4 <= dirOffset && view.getUint32(after, true) === DESCRIPTOR;
109
+ descriptorLength = signed ? 16 : 12;
110
+ if (after + descriptorLength > dirOffset) {
111
+ throw new ZipError(`Damaged zip: no data descriptor for ${name}`);
112
+ }
113
+ check = signed ? after + 4 : after;
114
+ }
115
+ if (view.getUint32(check, true) !== crc32 ||
116
+ view.getUint32(check + 4, true) !== compressedSize ||
117
+ view.getUint32(check + 8, true) !== size) {
118
+ throw mismatch();
119
+ }
120
+ const stop = data + compressedSize + descriptorLength;
121
+ spans.push({ start: local, end: stop, name });
122
+ entries.push({
123
+ name,
124
+ nameBytes,
125
+ method,
126
+ flags,
127
+ time,
128
+ date,
129
+ crc32,
130
+ size,
131
+ raw: bytes.subarray(data, data + compressedSize),
132
+ stored: {
133
+ local: bytes.subarray(local, data),
134
+ descriptor: bytes.subarray(data + compressedSize, stop),
135
+ central,
136
+ },
137
+ });
138
+ }
139
+ if (at !== dirOffset + dirSize) {
140
+ throw new ZipError("Damaged zip: central directory size mismatch");
141
+ }
142
+ // Overlapping entries share data: another reader could see other content, and a small file
143
+ // could expand without limit.
144
+ spans.sort((a, b) => a.start - b.start);
145
+ for (let i = 1; i < spans.length; i++) {
146
+ const span = spans[i];
147
+ if (span.start < spans[i - 1].end) {
148
+ throw new ZipError(`Damaged zip: ${span.name} overlaps another entry`);
149
+ }
150
+ }
151
+ return entries;
152
+ }
153
+ function equalBytes(a, b) {
154
+ if (a.length !== b.length)
155
+ return false;
156
+ for (let i = 0; i < a.length; i++)
157
+ if (a[i] !== b[i])
158
+ return false;
159
+ return true;
160
+ }
161
+ /** The end record: the last one whose central directory is where it says (not one in a comment). */
162
+ function findEnd(view) {
163
+ // The end record is 22 bytes plus a comment of at most 65 535.
164
+ const last = view.byteLength - 22;
165
+ for (let at = last; at >= 0 && at >= last - 0xffff; at--) {
166
+ if (view.getUint32(at, true) !== END)
167
+ continue;
168
+ if (at + 22 + view.getUint16(at + 20, true) > view.byteLength)
169
+ continue;
170
+ const count = view.getUint16(at + 10, true);
171
+ const dirSize = view.getUint32(at + 12, true);
172
+ const dirOffset = view.getUint32(at + 16, true);
173
+ // ZIP64 and multi-disk archives: accepted here to be refused by name.
174
+ const special = count === 0xffff ||
175
+ dirOffset === 0xffffffff ||
176
+ view.getUint16(at + 4, true) !== 0 ||
177
+ view.getUint16(at + 6, true) !== 0;
178
+ // The directory ends where the end record starts (no ZIP64 records in between).
179
+ const directory = dirOffset + dirSize === at && (count === 0 || view.getUint32(dirOffset, true) === CENTRAL);
180
+ if (special || directory)
181
+ return at;
182
+ }
183
+ const head = view.byteLength >= 4 ? view.getUint32(0, false) : 0;
184
+ // Compound File Binary: an encrypted .docx, or a .doc.
185
+ if (head === 0xd0cf11e0) {
186
+ throw new ZipError("Not a zip: an encrypted document or a legacy .doc (Compound File)");
187
+ }
188
+ throw new ZipError("Not a zip archive");
189
+ }
190
+ /** The entry's data, decompressed, checked against its size and CRC-32. */
191
+ export async function inflateEntry(entry) {
192
+ const data = entry.method === 0
193
+ ? new Uint8Array(entry.raw)
194
+ : await inflateRaw(entry.raw, entry.size, entry.name);
195
+ if (data.length !== entry.size)
196
+ throw new ZipError(`Damaged zip: wrong size for ${entry.name}`);
197
+ if (crc32(data) !== entry.crc32)
198
+ throw new ZipError(`Damaged zip: CRC mismatch for ${entry.name}`);
199
+ return data;
200
+ }
201
+ async function inflateRaw(raw, size, name) {
202
+ // Collected as it comes, not allocated from the declared size.
203
+ const chunks = [];
204
+ let length = 0;
205
+ const reader = streamOf(raw).pipeThrough(new DecompressionStream("deflate-raw")).getReader();
206
+ try {
207
+ for (;;) {
208
+ const { done, value } = await reader.read();
209
+ if (done)
210
+ break;
211
+ // Never past the declared size: a zip bomb stops here.
212
+ if (length + value.length > size)
213
+ throw new ZipError(`Damaged zip: wrong size for ${name}`);
214
+ chunks.push(value);
215
+ length += value.length;
216
+ }
217
+ }
218
+ catch (error) {
219
+ await reader.cancel().catch(() => { });
220
+ if (error instanceof ZipError)
221
+ throw error;
222
+ throw new ZipError(`Damaged zip: cannot decompress ${name}`);
223
+ }
224
+ if (length !== size)
225
+ throw new ZipError(`Damaged zip: wrong size for ${name}`);
226
+ return concat(chunks);
227
+ }
228
+ /**
229
+ * A new deflated entry holding `data`. With `like` (the entry it replaces) it keeps that entry's
230
+ * name bytes, name encoding flag, time and date.
231
+ */
232
+ export async function deflateEntry(name, data, like) {
233
+ const chunks = [];
234
+ const reader = streamOf(data).pipeThrough(new CompressionStream("deflate-raw")).getReader();
235
+ for (;;) {
236
+ const { done, value } = await reader.read();
237
+ if (done)
238
+ break;
239
+ chunks.push(value);
240
+ }
241
+ return {
242
+ name,
243
+ nameBytes: like?.nameBytes ?? new TextEncoder().encode(name),
244
+ method: 8,
245
+ flags: like ? like.flags & UTF8_NAME : UTF8_NAME,
246
+ time: like?.time ?? 0,
247
+ // 1980-01-01, the earliest DOS date, when there is no entry to take it from.
248
+ date: like?.date ?? 0x21,
249
+ crc32: crc32(data),
250
+ size: data.length,
251
+ raw: concat(chunks),
252
+ };
253
+ }
254
+ /**
255
+ * The zip of `entries`, in order; each entry's data written as it is in `raw`. An entry read
256
+ * from a zip keeps its headers byte for byte (only its offset in the directory changes), so a
257
+ * zip written back with its entries unchanged is the same file, short of a trailing comment.
258
+ */
259
+ export function writeZip(entries) {
260
+ const parts = [];
261
+ const directory = [];
262
+ let offset = 0;
263
+ for (const entry of entries) {
264
+ if (entry.stored) {
265
+ const { local, descriptor } = entry.stored;
266
+ // A copy (a Node Buffer's `slice` is a view: the offset would be written into the input).
267
+ const central = new Uint8Array(entry.stored.central);
268
+ new DataView(central.buffer).setUint32(42, offset, true);
269
+ parts.push(local, entry.raw, descriptor);
270
+ directory.push(central);
271
+ offset += local.length + entry.raw.length + descriptor.length;
272
+ continue;
273
+ }
274
+ const flags = entry.flags & UTF8_NAME;
275
+ const local = new Uint8Array(30 + entry.nameBytes.length);
276
+ const l = new DataView(local.buffer);
277
+ l.setUint32(0, LOCAL, true);
278
+ l.setUint16(4, 20, true);
279
+ l.setUint16(6, flags, true);
280
+ l.setUint16(8, entry.method, true);
281
+ l.setUint16(10, entry.time, true);
282
+ l.setUint16(12, entry.date, true);
283
+ l.setUint32(14, entry.crc32, true);
284
+ l.setUint32(18, entry.raw.length, true);
285
+ l.setUint32(22, entry.size, true);
286
+ l.setUint16(26, entry.nameBytes.length, true);
287
+ local.set(entry.nameBytes, 30);
288
+ const central = new Uint8Array(46 + entry.nameBytes.length);
289
+ const c = new DataView(central.buffer);
290
+ c.setUint32(0, CENTRAL, true);
291
+ c.setUint16(4, 20, true);
292
+ c.setUint16(6, 20, true);
293
+ c.setUint16(8, flags, true);
294
+ c.setUint16(10, entry.method, true);
295
+ c.setUint16(12, entry.time, true);
296
+ c.setUint16(14, entry.date, true);
297
+ c.setUint32(16, entry.crc32, true);
298
+ c.setUint32(20, entry.raw.length, true);
299
+ c.setUint32(24, entry.size, true);
300
+ c.setUint16(28, entry.nameBytes.length, true);
301
+ c.setUint32(42, offset, true);
302
+ central.set(entry.nameBytes, 46);
303
+ parts.push(local, entry.raw);
304
+ directory.push(central);
305
+ offset += local.length + entry.raw.length;
306
+ }
307
+ if (entries.length > 0xfffe || offset > 0xfffffffe) {
308
+ throw new ZipError("Too large for a zip without ZIP64");
309
+ }
310
+ const dirSize = directory.reduce((sum, record) => sum + record.length, 0);
311
+ const end = new Uint8Array(22);
312
+ const e = new DataView(end.buffer);
313
+ e.setUint32(0, END, true);
314
+ e.setUint16(8, entries.length, true);
315
+ e.setUint16(10, entries.length, true);
316
+ e.setUint32(12, dirSize, true);
317
+ e.setUint32(16, offset, true);
318
+ return concat([...parts, ...directory, end]);
319
+ }
320
+ function streamOf(data) {
321
+ return new ReadableStream({
322
+ start(controller) {
323
+ // Never a SharedArrayBuffer here: the bytes come from slices and encoders.
324
+ controller.enqueue(data);
325
+ controller.close();
326
+ },
327
+ });
328
+ }
329
+ function concat(chunks) {
330
+ const out = new Uint8Array(chunks.reduce((sum, chunk) => sum + chunk.length, 0));
331
+ let at = 0;
332
+ for (const chunk of chunks) {
333
+ out.set(chunk, at);
334
+ at += chunk.length;
335
+ }
336
+ return out;
337
+ }
338
+ let table;
339
+ /** CRC-32 (IEEE), as zip stores it. */
340
+ export function crc32(data) {
341
+ if (!table) {
342
+ table = new Uint32Array(256);
343
+ for (let n = 0; n < 256; n++) {
344
+ let c = n;
345
+ for (let k = 0; k < 8; k++)
346
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
347
+ table[n] = c >>> 0;
348
+ }
349
+ }
350
+ let crc = 0xffffffff;
351
+ for (let i = 0; i < data.length; i++) {
352
+ crc = table[(crc ^ data[i]) & 0xff] ^ (crc >>> 8);
353
+ }
354
+ return (crc ^ 0xffffffff) >>> 0;
355
+ }
356
+ //# sourceMappingURL=zip.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zip.js","sourceRoot":"","sources":["../src/zip.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAoCH,6DAA6D;AAC7D,MAAM,OAAO,QAAS,SAAQ,KAAK;IACxB,IAAI,GAAG,UAAU,CAAC;CAC5B;AAED,MAAM,KAAK,GAAG,UAAU,CAAC;AACzB,MAAM,OAAO,GAAG,UAAU,CAAC;AAC3B,MAAM,GAAG,GAAG,UAAU,CAAC;AACvB,MAAM,UAAU,GAAG,UAAU,CAAC;AAC9B,MAAM,SAAS,GAAG,MAAM,CAAC;AACzB,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC;;;;GAIG;AACH,MAAM,UAAU,OAAO,CAAC,KAAiB,EAAE,MAAM,GAAc,EAAE;IAC/D,MAAM,UA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C,GAAG,GAAI,KAAK,CAAC,CAAC,GAAG,GAAI,IAAI,CAAC,CAAC,CAAY,CAAC,GAAG,IAAI,CAAY,GAAG,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC;IAC5E,CAAC;IACD,OAAO,CAAC,GAAG,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;AAClC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@folijs/docx",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "DOCX for the Foli document engine: import to Foli's Word model (schema v3) and lossless export, the package (zip, parts, relationships) and an XML reader that keeps the exact source text. No DOM.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/josep-audenis/foli.git",
9
+ "directory": "packages/docx"
10
+ },
11
+ "homepage": "https://github.com/josep-audenis/foli#readme",
12
+ "bugs": "https://github.com/josep-audenis/foli/issues",
13
+ "type": "module",
14
+ "sideEffects": false,
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "CHANGELOG.md",
24
+ "src",
25
+ "!src/**/*.test.*",
26
+ "!src/testing"
27
+ ],
28
+ "dependencies": {
29
+ "@folijs/core": "^0.3.0"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^20.19.43",
33
+ "fast-check": "^4.10.2"
34
+ },
35
+ "scripts": {
36
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
37
+ "typecheck": "tsc -p tsconfig.json --noEmit"
38
+ }
6
39
  }
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Schema v3 content back to WordprocessingML: paragraphs, runs grouped by their properties,
3
+ * hyperlinks and tracked changes around them, markers between them, opaque content verbatim.
4
+ */
5
+
6
+ import type { MarkJSON, NodeJSON } from "@folijs/core";
7
+ import { paragraphPropertiesXml, runPropertiesXml, same } from "./properties.js";
8
+ import { bagXml, el, escapeText, fragment, type Namespaces } from "./xmlout.js";
9
+
10
+ export interface WriteContext {
11
+ readonly namespaces: Namespaces;
12
+ /**
13
+ * The relationship id for an external hyperlink target: the link's own when the package
14
+ * still has it with that target, otherwise a new one.
15
+ */
16
+ readonly hyperlink: (href: string, id: string | undefined) => string;
17
+ }
18
+
19
+ type Json = Record<string, unknown>;
20
+
21
+ /** Opaque XML as kept, once checked to be one element that fits the part (DocxError otherwise). */
22
+ function verbatim(xml: unknown, context: WriteContext): string {
23
+ const text = typeof xml === "string" ? xml : "";
24
+ fragment(text, context.namespaces);
25
+ return text;
26
+ }
27
+
28
+ export function blocksXml(blocks: readonly NodeJSON[], context: WriteContext): string {
29
+ let out = "";
30
+ for (const block of blocks) {
31
+ if (block.type === "paragraph") out += paragraphXml(block, context);
32
+ else if (block.type === "opaqueBlock") out += verbatim(block.attrs?.xml, context);
33
+ }
34
+ return out;
35
+ }
36
+
37
+ export function paragraphXml(p: NodeJSON, context: WriteContext): string {
38
+ const attrs = (p.attrs ?? {}) as Json;
39
+ const own = bagXml(attrs.attributes, context.namespaces);
40
+ return `<w:p${own}>${paragraphPropertiesXml(attrs, context.namespaces)}${inlinesXml(p.content ?? [], context)}</w:p>`;
41
+ }
42
+
43
+ const markOf = (node: NodeJSON, type: string) => node.marks?.find((m) => m.type === type);
44
+
45
+ /** Consecutive nodes with the same `key`, each run of them given to `write`. */
46
+ function grouped(
47
+ nodes: readonly NodeJSON[],
48
+ key: (n: NodeJSON) => unknown,
49
+ write: (group: readonly NodeJSON[], k: unknown) => string,
50
+ ): string {
51
+ let out = "";
52
+ for (let i = 0; i < nodes.length; ) {
53
+ const k = key(nodes[i] as NodeJSON);
54
+ let j = i + 1;
55
+ while (j < nodes.length && same(key(nodes[j] as NodeJSON), k)) j++;
56
+ out += write(nodes.slice(i, j), k);
57
+ i = j;
58
+ }
59
+ return out;
60
+ }
61
+
62
+ /** Hyperlinks outermost, then insertions (or move destinations), then deletions (or move sources). */
63
+ function inlinesXml(nodes: readonly NodeJSON[], context: WriteContext): string {
64
+ return grouped(
65
+ nodes,
66
+ (n) => markOf(n, "link"),
67
+ (group, link) => {
68
+ const inner = grouped(
69
+ group,
70
+ (n) => markOf(n, "insertion"),
71
+ (g, ins) =>
72
+ wrapChange(
73
+ ins as MarkJSON | undefined,
74
+ "ins",
75
+ "moveTo",
76
+ grouped(
77
+ g,
78
+ (n) => markOf(n, "deletion"),
79
+ (g2, del) =>
80
+ wrapChange(
81
+ del as MarkJSON | undefined,
82
+ "del",
83
+ "moveFrom",
84
+ runsXml(g2, !!del, context),
85
+ context,
86
+ ),
87
+ ),
88
+ context,
89
+ ),
90
+ );
91
+ return link ? hyperlinkXml(link as MarkJSON, inner, context) : inner;
92
+ },
93
+ );
94
+ }
95
+
96
+ const CHANGE_ATTRIBUTES = ["w:id", "w:author", "w:date"];
97
+
98
+ function wrapChange(
99
+ mark: MarkJSON | undefined,
100
+ local: string,
101
+ moveLocal: string,
102
+ inner: string,
103
+ context: WriteContext,
104
+ ): string {
105
+ if (!mark) return inner;
106
+ const a = (mark.attrs ?? {}) as Json;
107
+ const name = a.move ? `w:${moveLocal}` : `w:${local}`;
108
+ const open = el(name, {
109
+ "w:id": String(a.id),
110
+ "w:author": String(a.author ?? ""),
111
+ "w:date": a.date as string | undefined,
112
+ }).slice(0, -2);
113
+ return `${open}${bagXml(a.attributes, context.namespaces, CHANGE_ATTRIBUTES)}>${inner}</${name}>`;
114
+ }
115
+
116
+ function hyperlinkXml(link: MarkJSON, inner: string, context: WriteContext): string {
117
+ const a = (link.attrs ?? {}) as Json;
118
+ const attributes = { ...((a.attributes as Record<string, string>) ?? {}) };
119
+ const original = attributes["r:id"];
120
+ delete attributes["r:id"];
121
+ // A target: its relationship. None (a relationship the package does not have, read as no
122
+ // target): the original reference as it was.
123
+ const id = typeof a.href === "string" ? context.hyperlink(a.href, original) : original;
124
+ const open = el("w:hyperlink", {
125
+ "r:id": id,
126
+ "w:anchor": a.anchor as string | undefined,
127
+ "w:tooltip": a.tooltip as string | undefined,
128
+ }).slice(0, -2);
129
+ return `${open}${bagXml(attributes, context.namespaces, ["r:id", "w:anchor", "w:tooltip"])}>${inner}</w:hyperlink>`;
130
+ }
131
+
132
+ /** Inline nodes that are a run's content (the rest stands between runs). */
133
+ function inRun(node: NodeJSON): boolean {
134
+ if (node.type === "opaqueInline") return node.attrs?.run === true;
135
+ return ["text", "tab", "hardBreak", "pageBreak", "columnBreak", "commentReference"].includes(
136
+ node.type,
137
+ );
138
+ }
139
+
140
+ const STRUCTURE = new Set(["link", "insertion", "deletion"]);
141
+
142
+ /** A run's own properties: its marks without the hyperlink and tracked changes around it. */
143
+ function runMarks(node: NodeJSON): MarkJSON[] {
144
+ return (node.marks ?? []).filter((m) => !STRUCTURE.has(m.type));
145
+ }
146
+
147
+ function runsXml(nodes: readonly NodeJSON[], deleted: boolean, context: WriteContext): string {
148
+ return grouped(
149
+ nodes,
150
+ (n) => (inRun(n) ? runMarks(n) : n),
151
+ (group) => {
152
+ const first = group[0] as NodeJSON;
153
+ if (!inRun(first)) return group.map((n) => markerXml(n, context)).join("");
154
+ const marks = runMarks(first);
155
+ const ext = marks.find((m) => m.type === "runExt")?.attrs?.xml as string | undefined;
156
+ const rPr = runPropertiesXml(
157
+ marks.filter((m) => m.type !== "runExt"),
158
+ ext,
159
+ context.namespaces,
160
+ );
161
+ return `<w:r>${rPr}${group.map((n) => runContentXml(n, deleted, context)).join("")}</w:r>`;
162
+ },
163
+ );
164
+ }
165
+
166
+ function markerXml(node: NodeJSON, context: WriteContext): string {
167
+ const a = (node.attrs ?? {}) as Json;
168
+ const tag = (name: string, attrs: Record<string, string | undefined>) =>
169
+ `${el(name, attrs).slice(0, -2)}${bagXml(a.attributes, context.namespaces, Object.keys(attrs))}/>`;
170
+ switch (node.type) {
171
+ case "bookmarkStart":
172
+ return tag("w:bookmarkStart", { "w:id": String(a.id), "w:name": String(a.name ?? "") });
173
+ case "bookmarkEnd":
174
+ return tag("w:bookmarkEnd", { "w:id": String(a.id) });
175
+ case "commentStart":
176
+ return tag("w:commentRangeStart", { "w:id": String(a.id) });
177
+ case "commentEnd":
178
+ return tag("w:commentRangeEnd", { "w:id": String(a.id) });
179
+ case "opaqueInline":
180
+ return verbatim(a.xml, context);
181
+ default:
182
+ return "";
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Text as `w:t` (or `w:delText`), with tabs and Word's special hyphens as their elements, and
188
+ * line ends and vertical tabs (Office's line break in pasted text) as breaks.
189
+ */
190
+ function textXml(text: string, deleted: boolean): string {
191
+ const name = deleted ? "w:delText" : "w:t";
192
+ let out = "";
193
+ // A vertical tab (U+000B) is a line break, as Office pastes it.
194
+ const lines = text.split(String.fromCharCode(11)).join("\n");
195
+ for (const piece of lines.split(/(\r\n|[\t‑­\n\r])/)) {
196
+ if (piece === "") continue;
197
+ if (piece === "\t") out += "<w:tab/>";
198
+ else if (piece === "‑") out += "<w:noBreakHyphen/>";
199
+ else if (piece === "­") out += "<w:softHyphen/>";
200
+ else if (piece === "\n" || piece === "\r" || piece === "\r\n") out += "<w:br/>";
201
+ else {
202
+ const preserve = /^\s|\s$/.test(piece) ? ' xml:space="preserve"' : "";
203
+ out += `<${name}${preserve}>${escapeText(piece)}</${name}>`;
204
+ }
205
+ }
206
+ return out;
207
+ }
208
+
209
+ function runContentXml(node: NodeJSON, deleted: boolean, context: WriteContext): string {
210
+ const a = (node.attrs ?? {}) as Json;
211
+ switch (node.type) {
212
+ case "text":
213
+ return textXml(node.text ?? "", deleted);
214
+ case "tab":
215
+ return "<w:tab/>";
216
+ case "hardBreak":
217
+ return el("w:br", { "w:clear": a.clear as string | undefined });
218
+ case "pageBreak":
219
+ return el("w:br", { "w:type": "page" });
220
+ case "columnBreak":
221
+ return el("w:br", { "w:type": "column" });
222
+ case "commentReference":
223
+ return `${el("w:commentReference", { "w:id": String(a.id) }).slice(0, -2)}${bagXml(a.attributes, context.namespaces, ["w:id"])}/>`;
224
+ case "opaqueInline":
225
+ return verbatim(a.xml, context);
226
+ default:
227
+ return "";
228
+ }
229
+ }