@pretextbook/import 0.9.0 → 0.11.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 (45) hide show
  1. package/dist/convert-worker.cjs +1 -1
  2. package/dist/convert-worker.js +1 -1
  3. package/dist/{import-mode-DuPFMu97.cjs → import-mode-CV7gCDzF.cjs} +1 -1
  4. package/dist/{import-mode-BaaBvzcy.js → import-mode-DQ8g5P8P.js} +1 -1
  5. package/dist/import.css +1 -1
  6. package/dist/index.cjs +5 -3
  7. package/dist/index.d.ts +10 -5
  8. package/dist/index.js +562 -219
  9. package/dist/lib/assets/images.d.ts +49 -0
  10. package/dist/lib/detect-snippet-format.d.ts +32 -0
  11. package/dist/lib/insert/dedupe-ids.d.ts +36 -0
  12. package/dist/lib/insert/destination.d.ts +21 -0
  13. package/dist/lib/insert/index.d.ts +4 -0
  14. package/dist/lib/insert/prepare.d.ts +44 -0
  15. package/dist/lib/insert/retarget.d.ts +35 -0
  16. package/dist/lib/layout/xml-scan.d.ts +28 -0
  17. package/dist/lib/pandoc/formats.d.ts +40 -0
  18. package/dist/lib/pandoc/index.d.ts +3 -0
  19. package/dist/lib/pandoc/pandoc-engine.d.ts +24 -0
  20. package/dist/lib/pandoc/remote-pandoc.d.ts +74 -0
  21. package/dist/lib/paste/place-markup.d.ts +41 -0
  22. package/dist/lib/pool/division-pool.d.ts +5 -0
  23. package/dist/lib/pool/index.d.ts +5 -1
  24. package/dist/lib/pool/place-divisions.d.ts +25 -0
  25. package/dist/lib/pool/placeholders.d.ts +4 -0
  26. package/dist/lib/pool/refs.d.ts +8 -0
  27. package/dist/lib/pool/serialize-destination.d.ts +24 -0
  28. package/dist/lib/pool/serialize-files.d.ts +1 -2
  29. package/dist/lib/pool/serialize-insert-records.d.ts +22 -0
  30. package/dist/lib/pool/serialize-insert.d.ts +44 -0
  31. package/dist/lib/pool/serialize-plus.d.ts +4 -4
  32. package/dist/lib/pool/serialize-records.d.ts +11 -0
  33. package/dist/lib/pretext-divisions.d.ts +25 -0
  34. package/dist/lib/select/divisions.d.ts +44 -0
  35. package/dist/lib/types.d.ts +82 -2
  36. package/dist/lib/upload.d.ts +56 -4
  37. package/dist/react/import-wizard.d.ts +30 -1
  38. package/dist/react/index.d.ts +1 -1
  39. package/dist/react.cjs +2 -2
  40. package/dist/react.js +658 -511
  41. package/dist/upload-BnRj1gU1.cjs +135 -0
  42. package/dist/upload-H_OCZBBn.js +7648 -0
  43. package/package.json +5 -5
  44. package/dist/upload-BmErkg8I.js +0 -7140
  45. package/dist/upload-BtS22hIH.cjs +0 -135
package/dist/index.js CHANGED
@@ -1,7 +1,65 @@
1
- import { d as I, r as _, a as w, f as T, b, w as x, s as v, e as C, c as k, p as y, g as E, h as A } from "./upload-BmErkg8I.js";
2
- import { C as q, L as V, i as Y, M as J, j as Q, P as Z, k as ee, l as te, m as se, n as ae, o as ne, q as oe, t as re, u as ie, v as ce, x as le, y as ue, z as pe, A as fe, B as me, D as de, E as ge, F as Pe, G as he, H as xe, I as Ee, J as Te, K as be, N as ve, O as Se, Q as Le, R as Fe, S as Ie, T as _e, U as we, V as Ce, W as ke, X as ye, Y as Ae, Z as Me, _ as Re, $ as je, a0 as De, a1 as $e, a2 as Ne, a3 as Oe, a4 as Be, a5 as We } from "./upload-BmErkg8I.js";
3
- import { D as Ke, a as ze, d as Ue, b as Ge, c as He, f as qe, e as Ve, g as Ye, h as Je, p as Qe, r as Ze } from "./import-mode-BaaBvzcy.js";
4
- const M = {
1
+ import { i as W, P as H, d as U, r as G, a as V, f as C, b as R, w as v, s as k, e as q, c as Z, p as Y, g as $, h as J, j as Q } from "./upload-H_OCZBBn.js";
2
+ import { C as Xe, D as ze, L as Be, k as Ke, l as We, M as He, m as Ue, n as Ge, o as Ve, q as qe, t as Ze, u as Ye, v as Je, x as Qe, y as et, z as tt, A as nt, B as rt, E as ot, F as st, G as at, H as it, I as ct, J as lt, K as ut, N as pt, O as dt, Q as mt, R as ft, S as ht, T as gt, U as wt, V as Tt, W as xt, X as Pt, Y as Et, Z as vt, _ as St, $ as bt, a0 as It, a1 as _t, a2 as $t, a3 as At, a4 as Ft, a5 as Lt, a6 as yt, a7 as Ct, a8 as Rt, a9 as kt, aa as Dt, ab as Mt, ac as Ot, ad as Nt, ae as jt, af as Xt, ag as zt, ah as Bt, ai as Kt, aj as Wt, ak as Ht, al as Ut, am as Gt } from "./upload-H_OCZBBn.js";
3
+ import { D as qt, a as Zt, d as Yt, b as Jt, c as Qt, f as en, e as tn, g as nn, h as rn, p as on, r as sn } from "./import-mode-DQ8g5P8P.js";
4
+ const ee = /\$(?![\s$])([^$\n]{1,200})\$/;
5
+ function te(e) {
6
+ const t = ee.exec(e);
7
+ if (!t)
8
+ return !1;
9
+ const n = t[1];
10
+ return /[\\^_{}]/.test(n) || /^[A-Za-z]'?$/.test(n.trim());
11
+ }
12
+ const ne = [
13
+ // \begin{...} / \end{...} — unambiguous.
14
+ { pattern: /\\(?:begin|end)\{[a-zA-Z*]+\}/, weight: 3 },
15
+ // Display math, either delimiter style.
16
+ { pattern: /\\\[[\s\S]*?\\\]|\$\$[\s\S]*?\$\$/, weight: 3 },
17
+ // A command taking an argument: \emph{...}, \frac{...}{...}.
18
+ { pattern: /\\[a-zA-Z]+\s*\{/, weight: 2 },
19
+ // Inline math delimiters \( ... \).
20
+ { pattern: /\\\([\s\S]*?\\\)/, weight: 2 },
21
+ // A bare command: \alpha, \ldots, \\.
22
+ { pattern: /\\[a-zA-Z]+\b/, weight: 1 },
23
+ // Label/ref machinery is a strong hint even without braces nearby.
24
+ { pattern: /\\(?:label|ref|eqref|cite)\b/, weight: 2 }
25
+ ], re = [
26
+ // ATX heading.
27
+ { pattern: /^#{1,6}\s+\S/m, weight: 3 },
28
+ // Fenced code block.
29
+ { pattern: /^\s*```/m, weight: 3 },
30
+ // Bullet list.
31
+ { pattern: /^\s*[-*+]\s+\S/m, weight: 2 },
32
+ // Ordered list.
33
+ { pattern: /^\s*\d+[.)]\s+\S/m, weight: 2 },
34
+ // Strong emphasis.
35
+ { pattern: /\*\*[^\s*][^*]*\*\*/, weight: 2 },
36
+ // Inline link.
37
+ { pattern: /\[[^\]\n]+\]\([^)\s]+\)/, weight: 2 },
38
+ // Blockquote.
39
+ { pattern: /^\s*>\s+\S/m, weight: 2 },
40
+ // Underscore emphasis, bounded so snake_case_names do not count.
41
+ { pattern: /(?:^|\s)_[^_\s][^_\n]*_(?:\s|[.,;:!?]|$)/, weight: 1 },
42
+ // Inline code span.
43
+ { pattern: /`[^`\n]+`/, weight: 1 }
44
+ ], oe = 2;
45
+ function A(e, t) {
46
+ return t.reduce(
47
+ (n, { pattern: r, weight: o }) => n + (r.test(e) ? o : 0),
48
+ 0
49
+ );
50
+ }
51
+ function se(e) {
52
+ return { latex: A(e, ne) + (te(e) ? 2 : 0), markdown: A(e, re) };
53
+ }
54
+ function Fe(e) {
55
+ const t = e.trim();
56
+ if (!t || t.startsWith("<"))
57
+ return;
58
+ const { latex: n, markdown: r } = se(t);
59
+ if (!(Math.max(n, r) < oe))
60
+ return n >= r ? "latex" : "markdown";
61
+ }
62
+ const ae = {
5
63
  png: "image/png",
6
64
  jpg: "image/jpeg",
7
65
  jpeg: "image/jpeg",
@@ -15,20 +73,45 @@ const M = {
15
73
  webp: "image/webp",
16
74
  ico: "image/vnd.microsoft.icon"
17
75
  };
18
- function R(e) {
19
- const s = e.split(".").pop()?.toLowerCase() ?? "";
20
- return M[s] ?? "application/octet-stream";
76
+ function ie(e) {
77
+ const t = e.split(".").pop()?.toLowerCase() ?? "";
78
+ return ae[t] ?? "application/octet-stream";
21
79
  }
22
80
  const P = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
23
- function j(e) {
24
- const s = e.length, o = [];
25
- for (let t = 0; t < s; t += 3) {
26
- const a = e[t], c = t + 1 < s, r = t + 2 < s, l = c ? e[t + 1] : 0, i = r ? e[t + 2] : 0;
27
- o.push(P[a >> 2]), o.push(P[(a & 3) << 4 | l >> 4]), o.push(c ? P[(l & 15) << 2 | i >> 6] : "="), o.push(r ? P[i & 63] : "=");
81
+ function ce(e) {
82
+ const t = e.length, n = [];
83
+ for (let r = 0; r < t; r += 3) {
84
+ const o = e[r], a = r + 1 < t, s = r + 2 < t, i = a ? e[r + 1] : 0, c = s ? e[r + 2] : 0;
85
+ n.push(P[o >> 2]), n.push(P[(o & 3) << 4 | i >> 4]), n.push(a ? P[(i & 15) << 2 | c >> 6] : "="), n.push(s ? P[c & 63] : "=");
28
86
  }
29
- return o.join("");
87
+ return n.join("");
30
88
  }
31
89
  function D(e) {
90
+ return {
91
+ ref: e.ref,
92
+ fileName: e.fileName,
93
+ contentType: ie(e.fileName),
94
+ data: ce(e.data)
95
+ };
96
+ }
97
+ function M(e) {
98
+ return {
99
+ ref: e.xmlId,
100
+ source: e.content,
101
+ sourceFormat: e.sourceFormat,
102
+ isRoot: e.isRoot
103
+ };
104
+ }
105
+ function le(e) {
106
+ return {
107
+ title: e.title,
108
+ docinfo: e.docinfo,
109
+ documentKind: e.documentKind,
110
+ divisions: e.divisions.map(M),
111
+ assets: e.assets.map(D)
112
+ };
113
+ }
114
+ function ue(e) {
32
115
  return {
33
116
  ref: e.ref,
34
117
  kind: "file",
@@ -36,82 +119,129 @@ function D(e) {
36
119
  short_description: e.fileName,
37
120
  file: {
38
121
  filename: e.fileName,
39
- content_type: R(e.fileName),
40
- data: j(e.data)
122
+ content_type: e.contentType,
123
+ data: e.data
41
124
  }
42
125
  };
43
126
  }
44
- function K(e) {
127
+ function pe(e) {
45
128
  return {
46
129
  title: e.title,
47
130
  docinfo: e.docinfo,
48
131
  document_type: e.documentKind,
49
- divisions_attributes: e.divisions.map((s) => ({
50
- ref: s.xmlId,
51
- source: s.content,
52
- source_format: s.sourceFormat,
53
- is_root: s.isRoot
132
+ divisions_attributes: e.divisions.map((t) => ({
133
+ ref: t.ref,
134
+ source: t.source,
135
+ source_format: t.sourceFormat,
136
+ is_root: t.isRoot
54
137
  })),
55
- assets_attributes: e.assets.map(D)
138
+ assets_attributes: e.assets.map(ue)
139
+ };
140
+ }
141
+ function Le(e) {
142
+ return pe(le(e));
143
+ }
144
+ function ye(e, t) {
145
+ const { root: n, entries: r } = W(e, t), o = new Set(r.map((s) => s.xmlId)), a = e.divisions.filter(
146
+ (s) => !o.has(s.xmlId) && !(t.unwrapRoot && s.xmlId === n.xmlId)
147
+ );
148
+ return {
149
+ divisions: [...r, ...a].map(M),
150
+ assets: e.assets.map(D),
151
+ placeholders: r.map(
152
+ (s) => `<plus:${s.type} ref="${s.xmlId}"/>`
153
+ )
56
154
  };
57
155
  }
58
- const h = {
156
+ const F = /<(\/?)p(?=[\s>/])/g;
157
+ function Ce(e) {
158
+ let t = 0;
159
+ F.lastIndex = 0;
160
+ let n;
161
+ for (; (n = F.exec(e)) !== null; )
162
+ t += n[1] ? -1 : 1;
163
+ return t > 0;
164
+ }
165
+ const de = new RegExp(
166
+ `<(${H.join("|")})(?=[\\s>/])`
167
+ );
168
+ function me(e) {
169
+ return de.exec(e)?.[1];
170
+ }
171
+ function fe(e, t, n) {
172
+ return e.split(`
173
+ `).map(
174
+ (r, o) => o === 0 && n ? r : r && t + r
175
+ ).join(`
176
+ `);
177
+ }
178
+ function Re(e, t) {
179
+ let n = e.trim(), r;
180
+ if (t.inline) {
181
+ const o = n.replace(/^<p>\s*([\s\S]*?)\s*<\/p>$/, "$1");
182
+ n = o !== n ? o : n.replace(/^<p>/, "");
183
+ const a = me(n);
184
+ a && (r = `Pasted content produced a <${a}>, which cannot sit inside a <p>. It was inserted as-is — move it out of the paragraph to make the document valid.`);
185
+ }
186
+ return t.baseIndent && (n = fe(n, t.baseIndent, t.midLine)), { markup: n, warning: r };
187
+ }
188
+ const E = {
59
189
  mainSourcePath: "source/main.ptx",
60
190
  publicationPath: "publication/publication.ptx",
61
191
  projectFilePath: "project.ptx",
62
192
  docinfoPath: "source/docinfo.ptx"
63
193
  };
64
- function S(e) {
65
- return T(e, "pretext") ? e : `<pretext>
194
+ function O(e) {
195
+ return C(e, "pretext") ? e : `<pretext>
66
196
  ${e}
67
197
  </pretext>`;
68
198
  }
69
- function L(e, s, o) {
70
- const t = /* @__PURE__ */ new Map(), a = [], c = `${s}-`;
71
- return e.forEach((r, l) => {
72
- const i = r.attributes["xml:id"];
73
- let u;
74
- if (i) {
75
- const m = k(i);
76
- u = m.startsWith(c) ? m : `${c}${m}`;
199
+ function N(e, t, n) {
200
+ const r = /* @__PURE__ */ new Map(), o = [], a = `${t}-`;
201
+ return e.forEach((s, i) => {
202
+ const c = s.attributes["xml:id"];
203
+ let l;
204
+ if (c) {
205
+ const m = Z(c);
206
+ l = m.startsWith(a) ? m : `${a}${m}`;
77
207
  } else
78
- u = `${c}${y(l + 1, e.length)}`, o.push({
208
+ l = `${a}${Y(i + 1, e.length)}`, n.push({
79
209
  action: "anomaly",
80
210
  severity: "info",
81
211
  kind: "structure",
82
212
  category: "missing_xml_id",
83
- macro: r.name,
213
+ macro: s.name,
84
214
  occurrences: 1,
85
- message: `<${r.name}> at position ${l + 1} has no xml:id; using \`${u}\` as filename.`
215
+ message: `<${s.name}> at position ${i + 1} has no xml:id; using \`${l}\` as filename.`
86
216
  });
87
- const p = t.get(u) ?? 0;
88
- t.set(u, p + 1);
89
- const n = p === 0 ? u : `${u}-${p + 1}`;
90
- a.push({
91
- span: r,
92
- slug: n,
93
- filename: `${n}.ptx`
217
+ const p = r.get(l) ?? 0;
218
+ r.set(l, p + 1);
219
+ const u = p === 0 ? l : `${l}-${p + 1}`;
220
+ o.push({
221
+ span: s,
222
+ slug: u,
223
+ filename: `${u}.ptx`
94
224
  });
95
- }), a;
225
+ }), o;
96
226
  }
97
- function $(e, s, o, t) {
98
- const a = b(e, "section");
99
- if (a.length === 0)
227
+ function he(e, t, n, r) {
228
+ const o = R(e, "section");
229
+ if (o.length === 0)
100
230
  return e;
101
- const r = L(a, "sec", t).map((l) => {
102
- const i = `source/${s}/${l.filename}`;
103
- return o[i] = x(l.span.outer), {
104
- start: l.span.start,
105
- end: l.span.end,
106
- replacement: `<xi:include href="${s}/${l.filename}"/>`
231
+ const s = N(o, "sec", r).map((i) => {
232
+ const c = `source/${t}/${i.filename}`;
233
+ return n[c] = v(i.span.outer), {
234
+ start: i.span.start,
235
+ end: i.span.end,
236
+ replacement: `<xi:include href="${t}/${i.filename}"/>`
107
237
  };
108
238
  });
109
- return v(e, r);
239
+ return k(e, s);
110
240
  }
111
- function N(e, s, o) {
112
- const t = T(e, "book");
113
- if (!t)
114
- return o.push({
241
+ function ge(e, t, n) {
242
+ const r = C(e, "book");
243
+ if (!r)
244
+ return n.push({
115
245
  action: "anomaly",
116
246
  severity: "warning",
117
247
  kind: "structure",
@@ -119,203 +249,416 @@ function N(e, s, o) {
119
249
  macro: "book",
120
250
  occurrences: 1,
121
251
  message: "Document was treated as a book but no <book> element found; emitting as a single file."
122
- }), F(e, s);
123
- const a = {}, c = b(t.inner, "chapter");
124
- let r = t.inner;
125
- if (s.splitChapters && c.length > 0) {
126
- const p = L(c, "ch", o).map((n) => {
127
- let m = n.span.outer;
128
- if (s.splitSections) {
129
- const f = n.span.inner, d = $(
130
- f,
131
- n.slug,
132
- a,
133
- o
252
+ }), j(e, t);
253
+ const o = {}, a = R(r.inner, "chapter");
254
+ let s = r.inner;
255
+ if (t.splitChapters && a.length > 0) {
256
+ const p = N(a, "ch", n).map((u) => {
257
+ let m = u.span.outer;
258
+ if (t.splitSections) {
259
+ const d = u.span.inner, f = he(
260
+ d,
261
+ u.slug,
262
+ o,
263
+ n
134
264
  );
135
- m = n.span.outer.slice(0, n.span.startTagEnd - n.span.start) + d + n.span.outer.slice(n.span.contentEnd - n.span.start);
265
+ m = u.span.outer.slice(0, u.span.startTagEnd - u.span.start) + f + u.span.outer.slice(u.span.contentEnd - u.span.start);
136
266
  }
137
- const g = `source/${n.filename}`;
138
- return a[g] = x(m), {
139
- start: n.span.start,
140
- end: n.span.end,
141
- replacement: `<xi:include href="${n.filename}"/>`
267
+ const h = `source/${u.filename}`;
268
+ return o[h] = v(m), {
269
+ start: u.span.start,
270
+ end: u.span.end,
271
+ replacement: `<xi:include href="${u.filename}"/>`
142
272
  };
143
273
  });
144
- r = v(t.inner, p);
274
+ s = k(r.inner, p);
145
275
  }
146
- const l = e.slice(t.start, t.startTagEnd) + r + e.slice(t.contentEnd, t.end), i = e.slice(0, t.start) + l + e.slice(t.end);
147
- return a[s.mainSourcePath] = x(
148
- C(S(i.trim()))
149
- ), a;
150
- }
151
- function F(e, s, o) {
152
- const t = {};
153
- return t[s.mainSourcePath] = x(
154
- S(e.trim())
155
- ), t;
156
- }
157
- function z(e, s = {}) {
158
- const o = [], t = s.documentKind ?? I(e), a = {
159
- splitChapters: s.splitChapters ?? t === "book",
160
- splitSections: s.splitSections ?? !1,
161
- mainSourcePath: s.mainSourcePath ?? h.mainSourcePath,
162
- publicationPath: s.publicationPath ?? h.publicationPath,
163
- projectFilePath: s.projectFilePath ?? h.projectFilePath,
164
- docinfoPath: s.docinfoPath ?? h.docinfoPath
165
- }, c = t === "book" ? N(e, a, o) : F(e, a);
166
- return c[a.projectFilePath] = _({
167
- mainSource: a.mainSourcePath,
168
- publication: a.publicationPath
169
- }), c[a.publicationPath] = w(), { files: c, documentKind: t, warnings: o };
170
- }
171
- class O extends Error {
276
+ const i = e.slice(r.start, r.startTagEnd) + s + e.slice(r.contentEnd, r.end), c = e.slice(0, r.start) + i + e.slice(r.end);
277
+ return o[t.mainSourcePath] = v(
278
+ q(O(c.trim()))
279
+ ), o;
280
+ }
281
+ function j(e, t, n) {
282
+ const r = {};
283
+ return r[t.mainSourcePath] = v(
284
+ O(e.trim())
285
+ ), r;
286
+ }
287
+ function ke(e, t = {}) {
288
+ const n = [], r = t.documentKind ?? U(e), o = {
289
+ splitChapters: t.splitChapters ?? r === "book",
290
+ splitSections: t.splitSections ?? !1,
291
+ mainSourcePath: t.mainSourcePath ?? E.mainSourcePath,
292
+ publicationPath: t.publicationPath ?? E.publicationPath,
293
+ projectFilePath: t.projectFilePath ?? E.projectFilePath,
294
+ docinfoPath: t.docinfoPath ?? E.docinfoPath
295
+ }, a = r === "book" ? ge(e, o, n) : j(e, o);
296
+ return a[o.projectFilePath] = G({
297
+ mainSource: o.mainSourcePath,
298
+ publication: o.publicationPath
299
+ }), a[o.publicationPath] = V(), { files: a, documentKind: r, warnings: n };
300
+ }
301
+ class we extends Error {
172
302
  constructor() {
173
303
  super("Import cancelled."), this.name = "ConversionCancelledError";
174
304
  }
175
305
  }
176
- let B = 0;
177
- function W(e, s, o = {}) {
178
- const t = `convert-${B++}`, a = e(), { assets: c = {}, ...r } = o;
179
- let l;
180
- const i = new Promise((p, n) => {
306
+ let Te = 0;
307
+ function xe(e, t, n = {}) {
308
+ const r = `convert-${Te++}`, o = e(), { assets: a = {}, ...s } = n;
309
+ let i;
310
+ const c = new Promise((p, u) => {
181
311
  let m = !1;
182
- const g = (f) => {
183
- m || (m = !0, a.terminate(), f());
312
+ const h = (d) => {
313
+ m || (m = !0, o.terminate(), d());
184
314
  };
185
- l = () => g(() => n(new O())), a.addEventListener("message", (f) => {
186
- const d = f.data;
187
- if (!(!d || d.requestId !== t)) {
188
- if (d.type === "result") {
189
- g(() => p(d.result));
315
+ i = () => h(() => u(new we())), o.addEventListener("message", (d) => {
316
+ const f = d.data;
317
+ if (!(!f || f.requestId !== r)) {
318
+ if (f.type === "result") {
319
+ h(() => p(f.result));
190
320
  return;
191
321
  }
192
- g(() => n(new Error(d.message)));
322
+ h(() => u(new Error(f.message)));
193
323
  }
194
- }), a.addEventListener("error", (f) => {
195
- const d = typeof f == "object" && f && "message" in f ? String(f.message) : "The import worker failed to start.";
196
- g(() => n(new Error(d)));
324
+ }), o.addEventListener("error", (d) => {
325
+ const f = typeof d == "object" && d && "message" in d ? String(d.message) : "The import worker failed to start.";
326
+ h(() => u(new Error(f)));
197
327
  });
198
- }), u = [
328
+ }), l = [
199
329
  ...new Set(
200
- Object.values(c).map((p) => p.buffer).filter(
330
+ Object.values(a).map((p) => p.buffer).filter(
201
331
  (p) => p instanceof ArrayBuffer
202
332
  )
203
333
  )
204
334
  ];
205
- return a.postMessage(
206
- { type: "convert", requestId: t, files: s, assets: c, options: r },
207
- u
208
- ), { result: i, cancel: () => l?.() };
335
+ return o.postMessage(
336
+ { type: "convert", requestId: r, files: t, assets: a, options: s },
337
+ l
338
+ ), { result: c, cancel: () => i?.() };
209
339
  }
210
- function U(e) {
340
+ function De(e) {
211
341
  const {
212
- createWorker: s,
213
- id: o = "worker",
214
- label: t = "Built-in converter",
215
- description: a = "Create a new project starting with LaTeX, Markdown, or PreTeXt files.",
216
- acceptExtensions: c
342
+ createWorker: t,
343
+ id: n = "worker",
344
+ label: r = "Built-in converter",
345
+ description: o = "Create a new project starting with LaTeX, Markdown, or PreTeXt files.",
346
+ acceptExtensions: a
217
347
  } = e;
218
- let r = null;
219
- const l = async (i, u) => {
220
- r?.cancel(), r = W(s, i, u);
348
+ let s = null;
349
+ const i = async (c, l) => {
350
+ s?.cancel(), s = xe(t, c, l);
221
351
  try {
222
- return await r.result;
352
+ return await s.result;
223
353
  } finally {
224
- r = null;
354
+ s = null;
225
355
  }
226
356
  };
227
357
  return {
228
- id: o,
229
- label: t,
230
- description: a,
231
- acceptExtensions: c,
232
- prepare: async (i) => {
233
- const { files: u, assets: p } = await E(i);
358
+ id: n,
359
+ label: r,
360
+ description: o,
361
+ acceptExtensions: a,
362
+ prepare: async (c) => {
363
+ const { files: l, assets: p } = await $(c);
234
364
  return {
235
- fileName: i.name,
236
- files: u,
365
+ fileName: c.name,
366
+ files: l,
237
367
  assets: p,
238
- analysis: A(u)
368
+ analysis: J(l)
239
369
  };
240
370
  },
241
- convertPrepared: (i, u) => l(i.files, { ...u, assets: i.assets }),
242
- convertFile: async (i, u) => {
243
- const { files: p, assets: n } = await E(i);
244
- return l(p, { ...u, assets: n });
371
+ convertPrepared: (c, l) => i(c.files, { ...l, assets: c.assets }),
372
+ convertFile: async (c, l) => {
373
+ const { files: p, assets: u } = await $(c);
374
+ return i(p, { ...l, assets: u });
245
375
  },
246
376
  cancel: () => {
247
- r?.cancel(), r = null;
377
+ s?.cancel(), s = null;
378
+ }
379
+ };
380
+ }
381
+ const Pe = {
382
+ ".docx": "docx",
383
+ ".odt": "odt",
384
+ ".epub": "epub",
385
+ ".tex": "latex",
386
+ ".ltx": "latex",
387
+ ".md": "markdown",
388
+ ".markdown": "markdown",
389
+ ".html": "html",
390
+ ".htm": "html",
391
+ ".rst": "rst",
392
+ ".org": "org",
393
+ ".ipynb": "ipynb",
394
+ ".typ": "typst",
395
+ ".xml": "docbook",
396
+ ".textile": "textile"
397
+ }, Me = /* @__PURE__ */ new Set(["docx", "odt", "epub"]), X = [
398
+ ".docx",
399
+ ".odt",
400
+ ".epub",
401
+ ".html",
402
+ ".htm",
403
+ ".rst",
404
+ ".org",
405
+ ".ipynb",
406
+ ".typ",
407
+ ".textile",
408
+ ".tex",
409
+ ".ltx",
410
+ ".md",
411
+ ".markdown"
412
+ ];
413
+ function z(e) {
414
+ const t = e.lastIndexOf(".");
415
+ return t <= 0 ? "" : e.slice(t).toLowerCase();
416
+ }
417
+ function Ee(e) {
418
+ return Pe[z(e)];
419
+ }
420
+ function ve(e) {
421
+ const {
422
+ convertToPretext: t,
423
+ id: n = "pandoc",
424
+ label: r = "Pandoc",
425
+ description: o = "Convert Word, OpenOffice, EPUB, HTML, reStructuredText, and more.",
426
+ acceptExtensions: a = X
427
+ } = e;
428
+ return {
429
+ id: n,
430
+ label: r,
431
+ description: o,
432
+ acceptExtensions: a,
433
+ convertFile: async (s, i) => {
434
+ const c = await t(s, i);
435
+ if (!c.trim())
436
+ throw new Error(
437
+ `Pandoc produced no output for ${s.name}. The file may be empty or in an unexpected format.`
438
+ );
439
+ const l = Q(
440
+ { "source.ptx": c },
441
+ {
442
+ documentKind: i.documentKind,
443
+ splitChapters: i.splitChapters,
444
+ splitSections: i.splitSections,
445
+ splitLevel: i.splitLevel
446
+ }
447
+ );
448
+ return "pretextError" in l || (l.sourceName = s.name, l.sourcePath = s.name), l;
248
449
  }
249
450
  };
250
451
  }
452
+ const Se = 3e4;
453
+ function be(e) {
454
+ const t = /<pre>([\s\S]*?)<\/pre>/i.exec(e);
455
+ return (t ? t[1] : e).replace(/<[^>]+>/g, "").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&").trim();
456
+ }
457
+ function Ie(e, t, n) {
458
+ const r = _e(be(t)), o = r ? ` (${y(r)})` : "";
459
+ switch (e) {
460
+ case 400:
461
+ return `The pandoc server will not convert ${n}${o}.${T(n)}`;
462
+ case 401:
463
+ case 403:
464
+ return `The pandoc server rejected this site's credentials, so ${n} was never converted. Nothing is wrong with your file — this is a configuration problem with the service, and worth reporting.${T(n)}`;
465
+ case 404:
466
+ return `The pandoc conversion service could not be found at the address this site is configured to use. Nothing is wrong with your file — this is a configuration problem worth reporting.${T(n)}`;
467
+ case 413:
468
+ return `${n} is too large for the pandoc server to accept. Splitting it into chapters and importing them one at a time should get through.`;
469
+ case 422:
470
+ return `Pandoc could not read ${n}${o}. The file may be damaged, or may use features pandoc does not support.`;
471
+ case 503:
472
+ return `The pandoc server is running without its PreTeXt writer, so it cannot convert anything right now. Nothing is wrong with your file — this is a problem with the service, and worth reporting.${T(n)}`;
473
+ case 504:
474
+ return `Converting ${n} took longer than the pandoc server allows. Splitting it into chapters and importing them one at a time usually works.`;
475
+ default: {
476
+ const a = r ? `(HTTP ${e}: ${y(r)})` : `(HTTP ${e})`;
477
+ return `The pandoc server could not convert ${n} ${a}.${T(n)}`;
478
+ }
479
+ }
480
+ }
481
+ const L = 300;
482
+ function _e(e) {
483
+ return e.replace(/\s+/g, " ").trim();
484
+ }
485
+ function y(e) {
486
+ return e.length <= L ? e : `${e.slice(0, L).trimEnd()}…`;
487
+ }
488
+ const $e = /* @__PURE__ */ new Set([
489
+ ".tex",
490
+ ".ltx",
491
+ ".md",
492
+ ".markdown"
493
+ ]);
494
+ function T(e) {
495
+ return $e.has(z(e)) ? " You can import this file with the built-in converter instead." : "";
496
+ }
497
+ function Oe(e) {
498
+ const {
499
+ url: t,
500
+ token: n,
501
+ headers: r,
502
+ credentials: o,
503
+ standalone: a = !0,
504
+ from: s,
505
+ timeoutMs: i = Se,
506
+ fetchImpl: c,
507
+ id: l = "pandoc-remote",
508
+ label: p = "Pandoc (server)",
509
+ description: u = "Convert Word, OpenOffice, EPUB, HTML, reStructuredText, and more — no local install needed.",
510
+ acceptExtensions: m = X
511
+ } = e;
512
+ return ve({
513
+ convertToPretext: async (d, f) => {
514
+ const S = c ?? globalThis.fetch;
515
+ if (typeof S != "function")
516
+ throw new Error(
517
+ "This environment has no fetch; pass fetchImpl to createRemotePandocEngine."
518
+ );
519
+ const b = s ?? Ee(d.name);
520
+ if (!b)
521
+ throw new Error(
522
+ `Pandoc cannot determine a format for ${d.name}. Supported extensions: ${m.join(", ")}.`
523
+ );
524
+ const g = new FormData();
525
+ n && g.set("token", n), g.set("file", d, d.name), g.set("from", b), a && g.set("standalone", "yes");
526
+ const I = new AbortController(), B = setTimeout(() => I.abort(), i);
527
+ let x;
528
+ try {
529
+ x = await S(t, {
530
+ method: "POST",
531
+ body: g,
532
+ headers: r,
533
+ credentials: o,
534
+ signal: I.signal
535
+ });
536
+ } catch (w) {
537
+ if (w instanceof Error && w.name === "AbortError")
538
+ throw new Error(
539
+ `Pandoc conversion of ${d.name} timed out after ${Math.round(i / 1e3)}s.`
540
+ );
541
+ const K = w instanceof Error ? w.message : String(w);
542
+ throw new Error(`Could not reach the pandoc server: ${K}`);
543
+ } finally {
544
+ clearTimeout(B);
545
+ }
546
+ const _ = await x.text();
547
+ if (!x.ok)
548
+ throw new Error(
549
+ Ie(x.status, _, d.name)
550
+ );
551
+ return _;
552
+ },
553
+ id: l,
554
+ label: p,
555
+ description: u,
556
+ acceptExtensions: m
557
+ });
558
+ }
251
559
  export {
252
- q as CLEAN_RULES,
253
- O as ConversionCancelledError,
254
- Ke as DEFAULT_IMPORT_MODE,
255
- V as LATEX_DIVISION_COMMANDS,
256
- Y as LATEX_FORMAT_MARKERS,
257
- J as MARKDOWN_FORMAT_MARKERS,
258
- Q as MAX_SUGGESTED_SPLIT_LEVEL,
259
- Z as PRETEXT_DIVISION_TAGS,
260
- ee as PRETEXT_ROOT_TAGS,
261
- A as analyzeImportSources,
262
- te as applyLatexFixes,
263
- ze as assetsForImportMode,
264
- se as attachLatexRoots,
265
- ae as attachMarkdownRoots,
266
- ne as buildDivisionPool,
267
- oe as buildNativeDivisionPool,
268
- z as buildPretextProjectFiles,
269
- re as carryOverProjectFiles,
270
- ie as cleanLatex,
271
- ce as cleanLatexInChunks,
272
- le as cleanLatexText,
273
- ue as convertLatexToPretext,
274
- pe as convertMarkdownToPretext,
275
- fe as convertSourceToPretext,
276
- U as createWorkerEngine,
277
- me as defaultAttachLevel,
278
- de as defaultManifestTarget,
279
- I as detectDocumentKind,
280
- ge as detectSourceFormat,
281
- Ue as diffHunks,
282
- Ge as diffLines,
283
- He as diffStats,
284
- Pe as divisionChildRefs,
285
- he as divisionsAtLevel,
286
- xe as expandPretextIncludes,
287
- E as extractUpload,
288
- qe as fileChangesForImport,
289
- Ee as filePrefixForDivision,
290
- Ve as filesForImportMode,
291
- Te as findLatexFixes,
292
- be as findLatexHeaders,
293
- ve as findProjectManifest,
294
- Se as fixesToWarnings,
295
- Ye as formatWarningLine,
296
- Le as getConversionErrorMessage,
297
- Fe as getLatexCleanDiagnostics,
298
- Ie as handleImportUploadFile,
299
- Je as hasNativeImportMode,
300
- _e as importProjectFromFiles,
301
- we as isDivisionTag,
302
- Ce as latexDivisionHierarchy,
303
- ke as latexFixesToCodeActions,
304
- ye as mergeChunksAtLevel,
305
- Ae as normalizePretextSource,
306
- Me as parseLatexDivisions,
307
- Re as parseProjectManifest,
308
- Qe as projectForImportMode,
309
- je as relayoutImport,
310
- _ as renderProjectPtx,
311
- De as renderProjectPtxFromManifest,
312
- w as renderPublicationPtx,
313
- Ze as resolveImportMode,
314
- $e as resolveImportSplitLevel,
315
- Ne as resolveSplitLevel,
316
- W as runConversionInWorker,
317
- Oe as sanitizeRef,
318
- Be as serializeProjectToFiles,
319
- K as serializeProjectToPlusPayload,
320
- We as suggestSplitLevel
560
+ Xe as CLEAN_RULES,
561
+ we as ConversionCancelledError,
562
+ qt as DEFAULT_IMPORT_MODE,
563
+ Se as DEFAULT_REMOTE_PANDOC_TIMEOUT_MS,
564
+ ze as DIVISION_LADDER,
565
+ Be as LADDER_OVERFLOW_TAG,
566
+ Ke as LATEX_DIVISION_COMMANDS,
567
+ We as LATEX_FORMAT_MARKERS,
568
+ He as MARKDOWN_FORMAT_MARKERS,
569
+ Ue as MAX_SUGGESTED_SPLIT_LEVEL,
570
+ X as PANDOC_ACCEPT_EXTENSIONS,
571
+ Me as PANDOC_BINARY_FORMATS,
572
+ Pe as PANDOC_EXTENSION_FORMATS,
573
+ H as PRETEXT_DIVISION_TAGS,
574
+ Ge as PRETEXT_ROOT_TAGS,
575
+ Ve as PROJECT_DESTINATION,
576
+ J as analyzeImportSources,
577
+ qe as applyLatexFixes,
578
+ Zt as assetsForImportMode,
579
+ Ze as attachLatexRoots,
580
+ Ye as attachMarkdownRoots,
581
+ Je as buildDivisionPool,
582
+ Qe as buildNativeDivisionPool,
583
+ ke as buildPretextProjectFiles,
584
+ et as carryOverProjectFiles,
585
+ tt as cleanLatex,
586
+ nt as cleanLatexInChunks,
587
+ rt as cleanLatexText,
588
+ ot as convertLatexToPretext,
589
+ st as convertMarkdownToPretext,
590
+ at as convertSourceToPretext,
591
+ ve as createPandocEngine,
592
+ Oe as createRemotePandocEngine,
593
+ De as createWorkerEngine,
594
+ it as dedupeXmlIds,
595
+ ct as defaultAttachLevel,
596
+ lt as defaultManifestTarget,
597
+ Ie as describeRemotePandocFailure,
598
+ U as detectDocumentKind,
599
+ Fe as detectSnippetFormat,
600
+ ut as detectSourceFormat,
601
+ Yt as diffHunks,
602
+ Jt as diffLines,
603
+ Qt as diffStats,
604
+ pt as divisionChildRefs,
605
+ dt as divisionsAtLevel,
606
+ mt as expandPretextIncludes,
607
+ be as extractPandocErrorDetail,
608
+ $ as extractUpload,
609
+ en as fileChangesForImport,
610
+ z as fileExtension,
611
+ ft as filePrefixForDivision,
612
+ tn as filesForImportMode,
613
+ ht as findLatexFixes,
614
+ gt as findLatexHeaders,
615
+ wt as findProjectManifest,
616
+ me as firstDivisionTag,
617
+ Tt as fixesToWarnings,
618
+ nn as formatWarningLine,
619
+ xt as getConversionErrorMessage,
620
+ Pt as getLatexCleanDiagnostics,
621
+ Et as handleImportUploadFile,
622
+ rn as hasNativeImportMode,
623
+ Q as importProjectFromFiles,
624
+ vt as isDivisionTag,
625
+ Ce as isInlineContext,
626
+ St as ladderDepth,
627
+ bt as latexDivisionHierarchy,
628
+ It as latexFixesToCodeActions,
629
+ _t as mergeChunksAtLevel,
630
+ $t as normalizePretextSource,
631
+ At as outlineDivisions,
632
+ Ee as pandocFormatForFileName,
633
+ Ft as parseLatexDivisions,
634
+ Lt as parseProjectManifest,
635
+ Re as placeConvertedMarkup,
636
+ yt as prepareInsertSource,
637
+ on as projectForImportMode,
638
+ Ct as pruneDivisions,
639
+ Rt as rebuildImport,
640
+ pe as recordsToPlusPayload,
641
+ fe as reindentForContext,
642
+ kt as relayoutImport,
643
+ G as renderProjectPtx,
644
+ Dt as renderProjectPtxFromManifest,
645
+ V as renderPublicationPtx,
646
+ Mt as reselectImport,
647
+ sn as resolveImportMode,
648
+ Ot as resolveImportSplitLevel,
649
+ Nt as resolveSplitLevel,
650
+ jt as retargetFragment,
651
+ Xt as retargetFragmentToDepth,
652
+ zt as retargetImport,
653
+ xe as runConversionInWorker,
654
+ Bt as sanitizeRef,
655
+ se as scoreSnippetFormats,
656
+ Kt as serializeForDestination,
657
+ Wt as serializeInsertFiles,
658
+ ye as serializeInsertToRecords,
659
+ Ht as serializeProjectToFiles,
660
+ Le as serializeProjectToPlusPayload,
661
+ le as serializeProjectToRecords,
662
+ Ut as shiftLadderTag,
663
+ Gt as suggestSplitLevel
321
664
  };