@bendyline/squisq-formats 1.4.0 → 1.4.2

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 (83) hide show
  1. package/README.md +180 -43
  2. package/dist/{chunk-CRTC6DEX.js → chunk-46FMDOWZ.js} +2 -2
  3. package/dist/{chunk-ON232HJR.js → chunk-5LSSWZPU.js} +2 -2
  4. package/dist/{chunk-APSIAEXL.js → chunk-D7IFPWNZ.js} +87 -43
  5. package/dist/chunk-D7IFPWNZ.js.map +1 -0
  6. package/dist/chunk-DQAZR57U.js +33 -0
  7. package/dist/chunk-DQAZR57U.js.map +1 -0
  8. package/dist/chunk-EHLGMSTE.js +273 -0
  9. package/dist/chunk-EHLGMSTE.js.map +1 -0
  10. package/dist/{chunk-A3FHLTY5.js → chunk-MJGRI6XR.js} +6 -19
  11. package/dist/chunk-MJGRI6XR.js.map +1 -0
  12. package/dist/{chunk-JBNVE2GV.js → chunk-RFAPOKHJ.js} +9 -2
  13. package/dist/chunk-RFAPOKHJ.js.map +1 -0
  14. package/dist/chunk-RTS5XBZ7.js +526 -0
  15. package/dist/chunk-RTS5XBZ7.js.map +1 -0
  16. package/dist/{chunk-FMOIGA5T.js → chunk-SHLPSADL.js} +178 -5
  17. package/dist/chunk-SHLPSADL.js.map +1 -0
  18. package/dist/chunk-SSUPBUF5.js +15 -0
  19. package/dist/chunk-SSUPBUF5.js.map +1 -0
  20. package/dist/{chunk-BJQIJ4S4.js → chunk-WWBIKRNP.js} +17 -41
  21. package/dist/chunk-WWBIKRNP.js.map +1 -0
  22. package/dist/{chunk-I2GFTEOV.js → chunk-YESS7VY3.js} +77 -15
  23. package/dist/{chunk-I2GFTEOV.js.map → chunk-YESS7VY3.js.map} +1 -1
  24. package/dist/csv/index.d.ts +14 -1
  25. package/dist/csv/index.js +1 -1
  26. package/dist/docx/index.js +4 -3
  27. package/dist/epub/index.js +3 -2
  28. package/dist/html/index.d.ts +3 -0
  29. package/dist/html/index.js +3 -2
  30. package/dist/index.d.ts +1 -0
  31. package/dist/index.js +26 -11
  32. package/dist/ooxml/index.d.ts +5 -1
  33. package/dist/ooxml/index.js +16 -12
  34. package/dist/pdf/index.js +2 -1
  35. package/dist/pptx/index.d.ts +18 -3
  36. package/dist/pptx/index.js +7 -4
  37. package/dist/registry/index.d.ts +167 -0
  38. package/dist/registry/index.js +17 -0
  39. package/dist/registry/index.js.map +1 -0
  40. package/dist/xlsx/index.d.ts +44 -14
  41. package/dist/xlsx/index.js +4 -2
  42. package/package.json +7 -2
  43. package/src/__tests__/convert.test.ts +186 -0
  44. package/src/__tests__/csvImport.test.ts +34 -1
  45. package/src/__tests__/formatRegistry.test.ts +174 -0
  46. package/src/__tests__/lossyWarnings.test.ts +105 -0
  47. package/src/__tests__/pdfImport.test.ts +95 -1
  48. package/src/__tests__/pptxImport.test.ts +46 -1
  49. package/src/__tests__/roundTripAssets.test.ts +50 -0
  50. package/src/__tests__/roundTripMatrix.test.ts +10 -4
  51. package/src/__tests__/sharedContainer.test.ts +41 -0
  52. package/src/__tests__/sharedImages.test.ts +61 -0
  53. package/src/__tests__/xlsxExport.test.ts +164 -0
  54. package/src/csv/index.ts +25 -2
  55. package/src/docx/import.ts +6 -37
  56. package/src/html/imageUtils.ts +5 -19
  57. package/src/index.ts +29 -5
  58. package/src/ooxml/index.ts +3 -0
  59. package/src/ooxml/namespaces.ts +10 -0
  60. package/src/pdf/import.ts +145 -50
  61. package/src/pptx/import.ts +127 -10
  62. package/src/pptx/index.ts +1 -1
  63. package/src/registry/convert.ts +318 -0
  64. package/src/registry/defaultFormats.ts +323 -0
  65. package/src/registry/errors.ts +46 -0
  66. package/src/registry/index.ts +38 -0
  67. package/src/registry/registry.ts +48 -0
  68. package/src/registry/types.ts +107 -0
  69. package/src/shared/container.ts +28 -0
  70. package/src/shared/images.ts +44 -0
  71. package/src/xlsx/export.ts +253 -0
  72. package/src/xlsx/index.ts +10 -36
  73. package/dist/chunk-A3FHLTY5.js.map +0 -1
  74. package/dist/chunk-APSIAEXL.js.map +0 -1
  75. package/dist/chunk-BJQIJ4S4.js.map +0 -1
  76. package/dist/chunk-FMOIGA5T.js.map +0 -1
  77. package/dist/chunk-JBNVE2GV.js.map +0 -1
  78. package/dist/chunk-L53YIGYS.js +0 -141
  79. package/dist/chunk-L53YIGYS.js.map +0 -1
  80. package/dist/chunk-QSE7EWE7.js +0 -181
  81. package/dist/chunk-QSE7EWE7.js.map +0 -1
  82. /package/dist/{chunk-CRTC6DEX.js.map → chunk-46FMDOWZ.js.map} +0 -0
  83. /package/dist/{chunk-ON232HJR.js.map → chunk-5LSSWZPU.js.map} +0 -0
@@ -0,0 +1,318 @@
1
+ /**
2
+ * Programmatic `convert()` — the format-registry front door.
3
+ *
4
+ * Normalizes any {@link ConvertSource} into a {@link NormalizedInput} (always
5
+ * yielding a `Doc`, keeping the `MarkdownDocument` when the source was
6
+ * markdown-shaped, and always carrying a `ContentContainer` for media), applies
7
+ * an optional transform, then hands off to the target format's exporter.
8
+ */
9
+
10
+ import type { MarkdownDocument } from '@bendyline/squisq/markdown';
11
+ import type { ContentContainer } from '@bendyline/squisq/storage';
12
+ import { ConversionError } from './errors.js';
13
+ import { defaultRegistry } from './registry.js';
14
+ import type {
15
+ ConversionResult,
16
+ ConvertOptions,
17
+ ConvertSource,
18
+ FormatDefinition,
19
+ FormatId,
20
+ FormatRegistry,
21
+ NormalizedInput,
22
+ } from './types.js';
23
+
24
+ // ── Byte sniffing ───────────────────────────────────────────────────
25
+
26
+ function hasPrefix(bytes: Uint8Array, prefix: number[]): boolean {
27
+ if (bytes.length < prefix.length) return false;
28
+ for (let i = 0; i < prefix.length; i++) {
29
+ if (bytes[i] !== prefix[i]) return false;
30
+ }
31
+ return true;
32
+ }
33
+
34
+ const ZIP_MAGIC = [0x50, 0x4b, 0x03, 0x04]; // "PK\x03\x04"
35
+ const PDF_MAGIC = [0x25, 0x50, 0x44, 0x46]; // "%PDF"
36
+
37
+ /**
38
+ * Disambiguate a ZIP-based file. OOXML formats (docx/pptx/xlsx) all carry a
39
+ * `[Content_Types].xml` whose content-type strings name the flavor; a squisq
40
+ * container (.dbk) is a plain ZIP with no such part, so absence of the OOXML
41
+ * marker means `dbk`.
42
+ */
43
+ async function sniffZip(bytes: Uint8Array): Promise<FormatId> {
44
+ const JSZip = (await import('jszip')).default;
45
+ const zip = await JSZip.loadAsync(bytes).catch(() => {
46
+ throw new ConversionError('invalid-input', 'Input is not a readable ZIP archive.');
47
+ });
48
+ const contentTypes = zip.file('[Content_Types].xml');
49
+ if (!contentTypes) return 'dbk';
50
+ const xml = await contentTypes.async('string');
51
+ if (xml.includes('wordprocessingml')) return 'docx';
52
+ if (xml.includes('presentationml')) return 'pptx';
53
+ if (xml.includes('spreadsheetml')) return 'xlsx';
54
+ return 'dbk';
55
+ }
56
+
57
+ /** Determine the source format for raw bytes. */
58
+ async function detectByteFormat(
59
+ bytes: Uint8Array,
60
+ filename: string | undefined,
61
+ options: ConvertOptions,
62
+ registry: FormatRegistry,
63
+ ): Promise<FormatId> {
64
+ if (options.from) return options.from;
65
+
66
+ const ext = filename ? extractExt(filename) : undefined;
67
+ if (ext) {
68
+ const byExt = registry.byExtension(ext);
69
+ if (byExt) return byExt.id;
70
+ }
71
+
72
+ if (hasPrefix(bytes, PDF_MAGIC)) return 'pdf';
73
+ if (hasPrefix(bytes, ZIP_MAGIC)) return sniffZip(bytes);
74
+
75
+ // No magic and no recognized extension → assume UTF-8 markdown.
76
+ return 'md';
77
+ }
78
+
79
+ // ── Filename helpers ────────────────────────────────────────────────
80
+
81
+ /** Lowercased extension without the leading dot (`report.DocX` → `docx`). */
82
+ function extractExt(filename: string): string {
83
+ const base = filename.split('/').pop() ?? filename;
84
+ const dot = base.lastIndexOf('.');
85
+ if (dot <= 0) return '';
86
+ return base.slice(dot + 1).toLowerCase();
87
+ }
88
+
89
+ /** Basename without its final extension (`a/b/report.docx` → `report`). */
90
+ function baseNameOf(filename: string): string {
91
+ const base = filename.split('/').pop() ?? filename;
92
+ const dot = base.lastIndexOf('.');
93
+ return dot > 0 ? base.slice(0, dot) : base;
94
+ }
95
+
96
+ // ── Normalization ───────────────────────────────────────────────────
97
+
98
+ interface Normalized {
99
+ input: NormalizedInput;
100
+ warnings: string[];
101
+ }
102
+
103
+ async function normalizeBytes(
104
+ source: Extract<ConvertSource, { kind: 'bytes' }>,
105
+ options: ConvertOptions,
106
+ registry: FormatRegistry,
107
+ ): Promise<Normalized> {
108
+ const bytes = source.data instanceof Uint8Array ? source.data : new Uint8Array(source.data);
109
+ const buffer = bytes.buffer.slice(
110
+ bytes.byteOffset,
111
+ bytes.byteOffset + bytes.byteLength,
112
+ ) as ArrayBuffer;
113
+
114
+ const fromId = await detectByteFormat(bytes, source.filename, options, registry);
115
+ const fromDef = registry.get(fromId);
116
+ if (!fromDef) {
117
+ throw new ConversionError('unknown-format', `Unknown source format "${fromId}".`, {
118
+ format: fromId,
119
+ });
120
+ }
121
+ if (!fromDef.importContainer && !fromDef.importDoc) {
122
+ throw new ConversionError(
123
+ 'unsupported-input',
124
+ `Format "${fromDef.label}" cannot be used as a conversion source.`,
125
+ {
126
+ format: fromId,
127
+ hint: 'This format is export-only.',
128
+ },
129
+ );
130
+ }
131
+
132
+ const { markdownToDoc } = await import('@bendyline/squisq/doc');
133
+ const { parseMarkdown, stringifyMarkdown } = await import('@bendyline/squisq/markdown');
134
+
135
+ const warnings: string[] = [];
136
+ let markdownDoc: MarkdownDocument;
137
+ let container: ContentContainer;
138
+
139
+ if (fromDef.importContainer) {
140
+ container = await fromDef.importContainer(buffer, options);
141
+ // PDF embedded-image extraction needs a browser canvas; under Node it's
142
+ // skipped inside pdfToContainer. importContainer has no warnings channel of
143
+ // its own, so surface that degraded path here where warnings are collected.
144
+ if (fromDef.id === 'pdf' && typeof document === 'undefined') {
145
+ warnings.push(
146
+ 'PDF embedded images were skipped — image decoding requires a browser canvas (running under Node).',
147
+ );
148
+ }
149
+ const text = await container.readDocument();
150
+ markdownDoc = text ? parseMarkdown(text) : { type: 'document', children: [] };
151
+ } else {
152
+ // importDoc is guaranteed present by the guard above.
153
+ markdownDoc = await fromDef.importDoc!(buffer, options);
154
+ const { MemoryContentContainer } = await import('@bendyline/squisq/storage');
155
+ const mem = new MemoryContentContainer();
156
+ await mem.writeDocument(stringifyMarkdown(markdownDoc));
157
+ container = mem;
158
+ }
159
+
160
+ const doc = markdownToDoc(markdownDoc, { autoTemplates: options.autoTemplates });
161
+ const baseName = source.filename ? baseNameOf(source.filename) : 'document';
162
+
163
+ return {
164
+ input: { doc, markdownDoc, container, baseName },
165
+ warnings,
166
+ };
167
+ }
168
+
169
+ async function normalizeMarkdown(
170
+ source: Extract<ConvertSource, { kind: 'markdown' }>,
171
+ options: ConvertOptions,
172
+ ): Promise<Normalized> {
173
+ const { markdownToDoc } = await import('@bendyline/squisq/doc');
174
+ const { parseMarkdown } = await import('@bendyline/squisq/markdown');
175
+
176
+ const { stringifyMarkdown } = await import('@bendyline/squisq/markdown');
177
+
178
+ const markdownDoc =
179
+ typeof source.markdown === 'string' ? parseMarkdown(source.markdown) : source.markdown;
180
+
181
+ let container = source.container;
182
+ if (!container) {
183
+ // Seed a fresh container with the document so container-backed exports
184
+ // (dbk) and media resolution have the markdown to serialize.
185
+ const { MemoryContentContainer } = await import('@bendyline/squisq/storage');
186
+ const mem = new MemoryContentContainer();
187
+ await mem.writeDocument(stringifyMarkdown(markdownDoc));
188
+ container = mem;
189
+ }
190
+
191
+ const doc = markdownToDoc(markdownDoc, { autoTemplates: options.autoTemplates });
192
+ const baseName = source.baseName ?? 'document';
193
+
194
+ return { input: { doc, markdownDoc, container, baseName }, warnings: [] };
195
+ }
196
+
197
+ async function normalizeDoc(source: Extract<ConvertSource, { kind: 'doc' }>): Promise<Normalized> {
198
+ let container = source.container;
199
+ if (!container) {
200
+ const { MemoryContentContainer } = await import('@bendyline/squisq/storage');
201
+ const { docToMarkdown } = await import('@bendyline/squisq/doc');
202
+ const { stringifyMarkdown } = await import('@bendyline/squisq/markdown');
203
+ const mem = new MemoryContentContainer();
204
+ await mem.writeDocument(stringifyMarkdown(docToMarkdown(source.doc)));
205
+ container = mem;
206
+ }
207
+ const baseName = source.baseName ?? 'document';
208
+ // markdownDoc is intentionally omitted — exporters derive it lazily via docToMarkdown.
209
+ return { input: { doc: source.doc, container, baseName }, warnings: [] };
210
+ }
211
+
212
+ async function normalize(
213
+ source: ConvertSource,
214
+ options: ConvertOptions,
215
+ registry: FormatRegistry,
216
+ ): Promise<Normalized> {
217
+ switch (source.kind) {
218
+ case 'bytes':
219
+ return normalizeBytes(source, options, registry);
220
+ case 'markdown':
221
+ return normalizeMarkdown(source, options);
222
+ case 'doc':
223
+ return normalizeDoc(source);
224
+ }
225
+ }
226
+
227
+ // ── Transform ───────────────────────────────────────────────────────
228
+
229
+ async function applyTransformStyle(
230
+ input: NormalizedInput,
231
+ transformStyle: string,
232
+ themeId?: string,
233
+ ): Promise<string[]> {
234
+ const { applyTransform, extractDocImages } = await import('@bendyline/squisq/transform');
235
+ const { docToMarkdown, markdownToDoc } = await import('@bendyline/squisq/doc');
236
+ const images = extractDocImages(input.doc.blocks);
237
+ const result = applyTransform(input.doc, transformStyle, { themeId, images });
238
+ input.doc = result.doc;
239
+ const markdownDoc = docToMarkdown(result.doc);
240
+ input.markdownDoc = markdownDoc;
241
+
242
+ // Lossy-path detection: transforms can emit template blocks whose data lives
243
+ // in template inputs rather than in round-trippable markdown `contents`, so
244
+ // `docToMarkdown` silently drops them. Re-parse with auto-templating off (so
245
+ // the comparison stays ~1:1 and isn't confused by content-aware promotion)
246
+ // and compare block counts. Best-effort — most blocks carry `contents` and
247
+ // round-trip fine, so this only fires on a genuine collapse.
248
+ const roundTripped = markdownToDoc(markdownDoc, { autoTemplates: false });
249
+ if (roundTripped.blocks.length < result.doc.blocks.length) {
250
+ return [
251
+ 'Transform produced blocks that don’t round-trip to markdown; export may be incomplete.',
252
+ ];
253
+ }
254
+ return [];
255
+ }
256
+
257
+ // ── convert() ───────────────────────────────────────────────────────
258
+
259
+ /**
260
+ * Convert a source document to a target format.
261
+ *
262
+ * @param source - A bytes / markdown / doc source.
263
+ * @param to - The target format id (must be registered and support export).
264
+ * @param options - Conversion options (registry, theme, transform, …).
265
+ * @throws {@link ConversionError} on any failure, with a stable `code`.
266
+ */
267
+ export async function convert(
268
+ source: ConvertSource,
269
+ to: FormatId,
270
+ options: ConvertOptions = {},
271
+ ): Promise<ConversionResult> {
272
+ const registry = options.registry ?? defaultRegistry();
273
+
274
+ const target: FormatDefinition | undefined = registry.get(to);
275
+ if (!target) {
276
+ throw new ConversionError('unknown-format', `Unknown target format "${to}".`, { format: to });
277
+ }
278
+ if (!target.exportDoc) {
279
+ throw new ConversionError(
280
+ 'unsupported-output',
281
+ `Format "${target.label}" does not support export.`,
282
+ { format: to, hint: 'This format is import-only.' },
283
+ );
284
+ }
285
+
286
+ const { input, warnings } = await normalize(source, options, registry);
287
+
288
+ // Respect an existing doc theme; only fill it in from options when absent.
289
+ if (options.themeId && !input.doc.themeId) {
290
+ input.doc.themeId = options.themeId;
291
+ }
292
+
293
+ if (options.transformStyle) {
294
+ warnings.push(
295
+ ...(await applyTransformStyle(
296
+ input,
297
+ options.transformStyle,
298
+ options.themeId ?? input.doc.themeId,
299
+ )),
300
+ );
301
+ }
302
+
303
+ let result: ConversionResult;
304
+ try {
305
+ result = await target.exportDoc(input, options);
306
+ } catch (err: unknown) {
307
+ if (err instanceof ConversionError) throw err;
308
+ const message = err instanceof Error ? err.message : String(err);
309
+ throw new ConversionError('conversion-failed', message, { format: to, cause: err });
310
+ }
311
+
312
+ const ext = target.extensions[0]?.replace(/^\.+/, '') ?? to;
313
+ return {
314
+ ...result,
315
+ suggestedFilename: `${input.baseName}.${ext}`,
316
+ warnings: [...warnings, ...result.warnings],
317
+ };
318
+ }
@@ -0,0 +1,323 @@
1
+ /**
2
+ * Built-in format definitions.
3
+ *
4
+ * Each definition loads its converter module lazily via `import()` inside the
5
+ * method body, so importing the registry never eagerly bundles a heavy
6
+ * converter (pdf-lib, jszip, the OOXML writers, …). The capability of each
7
+ * format — which of import/export it supports — is expressed purely by which
8
+ * methods are present.
9
+ */
10
+
11
+ import type { ContentContainer } from '@bendyline/squisq/storage';
12
+ import type { MarkdownDocument } from '@bendyline/squisq/markdown';
13
+ import { ConversionError } from './errors.js';
14
+ import type {
15
+ ConversionResult,
16
+ ConvertOptions,
17
+ FormatDefinition,
18
+ NormalizedInput,
19
+ } from './types.js';
20
+
21
+ // ── MIME constants ──────────────────────────────────────────────────
22
+
23
+ const MIME = {
24
+ md: 'text/markdown',
25
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
26
+ pdf: 'application/pdf',
27
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
28
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
29
+ csv: 'text/csv',
30
+ html: 'text/html',
31
+ zip: 'application/zip',
32
+ epub: 'application/epub+zip',
33
+ } as const;
34
+
35
+ // ── Small shared helpers ────────────────────────────────────────────
36
+
37
+ /** Normalize any binary export return shape to Uint8Array. */
38
+ async function toBytes(data: ArrayBuffer | Uint8Array | Blob): Promise<Uint8Array> {
39
+ if (data instanceof Uint8Array) return data;
40
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
41
+ // Blob. Prefer the modern arrayBuffer() method; fall back to FileReader for
42
+ // environments (e.g. some jsdom builds) whose Blob lacks it.
43
+ if (typeof data.arrayBuffer === 'function') {
44
+ return new Uint8Array(await data.arrayBuffer());
45
+ }
46
+ const buffer = await new Promise<ArrayBuffer>((resolve, reject) => {
47
+ const reader = new FileReader();
48
+ reader.onload = () => resolve(reader.result as ArrayBuffer);
49
+ reader.onerror = () => reject(reader.error);
50
+ reader.readAsArrayBuffer(data);
51
+ });
52
+ return new Uint8Array(buffer);
53
+ }
54
+
55
+ /** The theme to apply: explicit option wins, then the doc's own theme. */
56
+ function resolveThemeId(input: NormalizedInput, options: ConvertOptions): string | undefined {
57
+ return options.themeId ?? input.doc.themeId;
58
+ }
59
+
60
+ /** The markdown shape an exporter needs — reuse the source's, else derive it. */
61
+ async function markdownOf(input: NormalizedInput): Promise<MarkdownDocument> {
62
+ if (input.markdownDoc) return input.markdownDoc;
63
+ const { docToMarkdown } = await import('@bendyline/squisq/doc');
64
+ return docToMarkdown(input.doc);
65
+ }
66
+
67
+ /**
68
+ * Collect image files from a container, keyed by both their container path and
69
+ * their bare filename. Exporters that resolve by url (PPTX) and the standalone
70
+ * player (HTML) both match against one of those two keys.
71
+ */
72
+ async function collectContainerImages(
73
+ container: ContentContainer,
74
+ ): Promise<Map<string, ArrayBuffer>> {
75
+ const images = new Map<string, ArrayBuffer>();
76
+ const files = await container.listFiles();
77
+ for (const file of files) {
78
+ if (!/\.(jpg|jpeg|png|gif|webp|svg|bmp|avif)$/i.test(file.path)) continue;
79
+ const data = await container.readFile(file.path);
80
+ if (!data) continue;
81
+ images.set(file.path, data);
82
+ const slash = file.path.lastIndexOf('/');
83
+ if (slash !== -1) images.set(file.path.slice(slash + 1), data);
84
+ }
85
+ return images;
86
+ }
87
+
88
+ /** Resolve the player IIFE bundle or throw a helpful missing-dependency error. */
89
+ async function requirePlayerScript(options: ConvertOptions, format: string): Promise<string> {
90
+ const script = await options.resolvePlayerScript?.();
91
+ if (!script) {
92
+ throw new ConversionError('missing-dependency', 'HTML export needs a player script.', {
93
+ format,
94
+ hint: "pass resolvePlayerScript, e.g. () => import('@bendyline/squisq-react/standalone-source').then(m => m.PLAYER_BUNDLE)",
95
+ });
96
+ }
97
+ return script;
98
+ }
99
+
100
+ function ok(bytes: Uint8Array, mimeType: string, warnings: string[] = []): ConversionResult {
101
+ // suggestedFilename is filled in by convert() once the baseName is known.
102
+ return { bytes, mimeType, suggestedFilename: '', warnings };
103
+ }
104
+
105
+ // ── Definitions ─────────────────────────────────────────────────────
106
+
107
+ export function defaultFormats(): FormatDefinition[] {
108
+ const md: FormatDefinition = {
109
+ id: 'md',
110
+ label: 'Markdown',
111
+ mimeType: MIME.md,
112
+ extensions: ['.md', '.markdown'],
113
+ async importDoc(data): Promise<MarkdownDocument> {
114
+ const { parseMarkdown } = await import('@bendyline/squisq/markdown');
115
+ return parseMarkdown(new TextDecoder().decode(data));
116
+ },
117
+ async exportDoc(input): Promise<ConversionResult> {
118
+ const { stringifyMarkdown } = await import('@bendyline/squisq/markdown');
119
+ const text = stringifyMarkdown(await markdownOf(input));
120
+ return ok(new TextEncoder().encode(text), MIME.md);
121
+ },
122
+ };
123
+
124
+ const docx: FormatDefinition = {
125
+ id: 'docx',
126
+ label: 'Word (DOCX)',
127
+ mimeType: MIME.docx,
128
+ extensions: ['.docx'],
129
+ async importContainer(data): Promise<ContentContainer> {
130
+ const { docxToContainer } = await import('../docx/index.js');
131
+ return docxToContainer(data);
132
+ },
133
+ async importDoc(data): Promise<MarkdownDocument> {
134
+ const { docxToMarkdownDoc } = await import('../docx/index.js');
135
+ return docxToMarkdownDoc(data);
136
+ },
137
+ async exportDoc(input, options): Promise<ConversionResult> {
138
+ const { markdownDocToDocx } = await import('../docx/index.js');
139
+ const buf = await markdownDocToDocx(await markdownOf(input), {
140
+ themeId: resolveThemeId(input, options),
141
+ });
142
+ return ok(await toBytes(buf), MIME.docx);
143
+ },
144
+ };
145
+
146
+ const pdf: FormatDefinition = {
147
+ id: 'pdf',
148
+ label: 'PDF',
149
+ mimeType: MIME.pdf,
150
+ extensions: ['.pdf'],
151
+ async importContainer(data): Promise<ContentContainer> {
152
+ const { pdfToContainer } = await import('../pdf/index.js');
153
+ return pdfToContainer(data);
154
+ },
155
+ async importDoc(data): Promise<MarkdownDocument> {
156
+ const { pdfToMarkdownDoc } = await import('../pdf/index.js');
157
+ return pdfToMarkdownDoc(data);
158
+ },
159
+ async exportDoc(input, options): Promise<ConversionResult> {
160
+ const { markdownDocToPdf } = await import('../pdf/index.js');
161
+ const buf = await markdownDocToPdf(await markdownOf(input), {
162
+ themeId: resolveThemeId(input, options),
163
+ });
164
+ return ok(await toBytes(buf), MIME.pdf);
165
+ },
166
+ };
167
+
168
+ const pptx: FormatDefinition = {
169
+ id: 'pptx',
170
+ label: 'PowerPoint (PPTX)',
171
+ mimeType: MIME.pptx,
172
+ extensions: ['.pptx'],
173
+ async importContainer(data): Promise<ContentContainer> {
174
+ const { pptxToContainer } = await import('../pptx/index.js');
175
+ return pptxToContainer(data);
176
+ },
177
+ async importDoc(data): Promise<MarkdownDocument> {
178
+ const { pptxToMarkdownDoc } = await import('../pptx/index.js');
179
+ return pptxToMarkdownDoc(data);
180
+ },
181
+ async exportDoc(input, options): Promise<ConversionResult> {
182
+ const { markdownDocToPptx } = await import('../pptx/index.js');
183
+ const images = await collectContainerImages(input.container);
184
+ const buf = await markdownDocToPptx(await markdownOf(input), {
185
+ themeId: resolveThemeId(input, options),
186
+ images,
187
+ });
188
+ return ok(await toBytes(buf), MIME.pptx);
189
+ },
190
+ };
191
+
192
+ const xlsx: FormatDefinition = {
193
+ id: 'xlsx',
194
+ label: 'Excel (XLSX)',
195
+ mimeType: MIME.xlsx,
196
+ extensions: ['.xlsx'],
197
+ async importDoc(data): Promise<MarkdownDocument> {
198
+ const { xlsxToMarkdownDoc } = await import('../xlsx/index.js');
199
+ return xlsxToMarkdownDoc(data);
200
+ },
201
+ async exportDoc(input): Promise<ConversionResult> {
202
+ const { markdownDocToXlsx } = await import('../xlsx/index.js');
203
+ const markdownDoc = await markdownOf(input);
204
+ // XLSX fidelity is tables-only: `table` nodes become worksheets and
205
+ // headings name them, but every other top-level block (prose, lists,
206
+ // images, code, …) is dropped. Count those and warn honestly.
207
+ const omitted = markdownDoc.children.filter(
208
+ (n) => n.type !== 'table' && n.type !== 'heading',
209
+ ).length;
210
+ const warnings =
211
+ omitted > 0
212
+ ? [`XLSX export is tables-only; ${omitted} non-table block(s) were omitted.`]
213
+ : [];
214
+ const blob = await markdownDocToXlsx(markdownDoc);
215
+ return ok(await toBytes(blob), MIME.xlsx, warnings);
216
+ },
217
+ };
218
+
219
+ const csv: FormatDefinition = {
220
+ id: 'csv',
221
+ label: 'CSV',
222
+ mimeType: MIME.csv,
223
+ extensions: ['.csv'],
224
+ async importDoc(data): Promise<MarkdownDocument> {
225
+ const { csvToMarkdownDoc } = await import('../csv/index.js');
226
+ return csvToMarkdownDoc(data);
227
+ },
228
+ async exportDoc(input): Promise<ConversionResult> {
229
+ const { markdownDocToCsv } = await import('../csv/index.js');
230
+ const markdownDoc = await markdownOf(input);
231
+ const tableCount = markdownDoc.children.filter((n) => n.type === 'table').length;
232
+ const warnings: string[] = [];
233
+ if (tableCount > 1) {
234
+ warnings.push(
235
+ `Document has ${tableCount} tables; CSV export emitted only the first. Use the csv converter's tableIndex option to select another.`,
236
+ );
237
+ }
238
+ const text = markdownDocToCsv(markdownDoc);
239
+ return ok(new TextEncoder().encode(text), MIME.csv, warnings);
240
+ },
241
+ };
242
+
243
+ const html: FormatDefinition = {
244
+ id: 'html',
245
+ label: 'HTML (single file)',
246
+ mimeType: MIME.html,
247
+ extensions: ['.html', '.htm'],
248
+ async importDoc(data): Promise<MarkdownDocument> {
249
+ const { htmlToMarkdownDoc } = await import('../html/index.js');
250
+ return htmlToMarkdownDoc(data);
251
+ },
252
+ // importContainer omitted: HTML import already inlines images as data URIs,
253
+ // so there is nothing to extract into a container this wave.
254
+ async exportDoc(input, options): Promise<ConversionResult> {
255
+ const playerScript = await requirePlayerScript(options, 'html');
256
+ const { docToHtml } = await import('../html/index.js');
257
+ const images = await collectContainerImages(input.container);
258
+ const htmlText = docToHtml(input.doc, {
259
+ playerScript,
260
+ images,
261
+ title: options.title ?? input.baseName,
262
+ mode: 'static',
263
+ themeId: resolveThemeId(input, options),
264
+ });
265
+ return ok(new TextEncoder().encode(htmlText), MIME.html);
266
+ },
267
+ };
268
+
269
+ const htmlzip: FormatDefinition = {
270
+ id: 'htmlzip',
271
+ label: 'HTML (ZIP archive)',
272
+ mimeType: MIME.zip,
273
+ extensions: ['.html.zip'],
274
+ async exportDoc(input, options): Promise<ConversionResult> {
275
+ const playerScript = await requirePlayerScript(options, 'htmlzip');
276
+ const { docToHtmlZip } = await import('../html/index.js');
277
+ const images = await collectContainerImages(input.container);
278
+ const blob = await docToHtmlZip(input.doc, {
279
+ playerScript,
280
+ images,
281
+ title: options.title ?? input.baseName,
282
+ mode: 'static',
283
+ themeId: resolveThemeId(input, options),
284
+ });
285
+ return ok(await toBytes(blob), MIME.zip);
286
+ },
287
+ };
288
+
289
+ const epub: FormatDefinition = {
290
+ id: 'epub',
291
+ label: 'EPUB',
292
+ mimeType: MIME.epub,
293
+ extensions: ['.epub'],
294
+ async exportDoc(input, options): Promise<ConversionResult> {
295
+ const { markdownDocToEpub } = await import('../epub/index.js');
296
+ const images = await collectContainerImages(input.container);
297
+ const buf = await markdownDocToEpub(await markdownOf(input), {
298
+ title: options.title ?? input.baseName,
299
+ themeId: resolveThemeId(input, options),
300
+ images,
301
+ });
302
+ return ok(await toBytes(buf), MIME.epub);
303
+ },
304
+ };
305
+
306
+ const dbk: FormatDefinition = {
307
+ id: 'dbk',
308
+ label: 'Squisq container (DBK)',
309
+ mimeType: MIME.zip,
310
+ extensions: ['.dbk', '.zip'],
311
+ async importContainer(data): Promise<ContentContainer> {
312
+ const { zipToContainer } = await import('../container/index.js');
313
+ return zipToContainer(data);
314
+ },
315
+ async exportDoc(input): Promise<ConversionResult> {
316
+ const { containerToZip } = await import('../container/index.js');
317
+ const blob = await containerToZip(input.container);
318
+ return ok(await toBytes(blob), MIME.zip);
319
+ },
320
+ };
321
+
322
+ return [md, docx, pdf, pptx, xlsx, csv, html, htmlzip, epub, dbk];
323
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Structured error for the format registry / `convert()` pipeline.
3
+ *
4
+ * Every failure path in the registry throws a `ConversionError` with a stable
5
+ * machine-readable `code`, so callers can branch on the failure kind rather
6
+ * than string-matching messages.
7
+ */
8
+
9
+ import type { FormatId } from './types.js';
10
+
11
+ /** Machine-readable failure kinds surfaced by the registry / `convert()`. */
12
+ export type ConversionErrorCode =
13
+ | 'unknown-format'
14
+ | 'unsupported-input'
15
+ | 'unsupported-output'
16
+ | 'invalid-input'
17
+ | 'missing-dependency'
18
+ | 'conversion-failed';
19
+
20
+ /** Options for constructing a {@link ConversionError}. */
21
+ export interface ConversionErrorOptions {
22
+ /** The format id the error relates to, if any. */
23
+ format?: FormatId;
24
+ /** A human-oriented remediation hint. */
25
+ hint?: string;
26
+ /** The underlying error, preserved on `error.cause`. */
27
+ cause?: unknown;
28
+ }
29
+
30
+ /** An error raised by the format registry or `convert()`. */
31
+ export class ConversionError extends Error {
32
+ readonly code: ConversionErrorCode;
33
+ readonly format?: FormatId;
34
+ readonly hint?: string;
35
+
36
+ constructor(code: ConversionErrorCode, message: string, opts: ConversionErrorOptions = {}) {
37
+ super(message);
38
+ this.name = 'ConversionError';
39
+ this.code = code;
40
+ this.format = opts.format;
41
+ this.hint = opts.hint;
42
+ if (opts.cause !== undefined) {
43
+ (this as Error & { cause?: unknown }).cause = opts.cause;
44
+ }
45
+ }
46
+ }