@drghaliasri/butex 8.1.0 → 8.1.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.
@@ -754,11 +754,17 @@ function refTokenLatex(keys, refCommand) {
754
754
  const command = refCommand === "eqref" ? "\\eqref" : "\\ref";
755
755
  return `${command}{${keys.join(",")}}`;
756
756
  }
757
- function implicitReferenceKey(kind, ownerId, unitId) {
757
+ function implicitObjectKey(kind, ownerId, unitId) {
758
758
  const hex = (value) => Array.from(new TextEncoder().encode(value), (byte) => byte.toString(16).padStart(2, "0")).join("");
759
759
  const scope = unitId === void 0 ? "a" : "u" + hex(unitId);
760
760
  return kind + ":butex-auto-" + scope + "-" + hex(ownerId);
761
761
  }
762
+ function implicitReferenceKey(kind, ownerId, unitId) {
763
+ return implicitObjectKey(kind, ownerId, unitId);
764
+ }
765
+ function implicitHeadingReferenceKey(kind, ownerId, unitId) {
766
+ return implicitObjectKey(kind, ownerId, unitId);
767
+ }
762
768
  function supportsSingleEquationNumbering(token) {
763
769
  return token.display && (token.opening === "\\[" || token.opening === String.fromCharCode(36, 36) || token.opening === "\\begin{equation}" || token.opening === "\\begin{equation*}");
764
770
  }
@@ -1357,6 +1363,7 @@ function parseTextBlock(json, options, path, diagnostics, identities) {
1357
1363
  identities
1358
1364
  ),
1359
1365
  ...metadataFromJson(json.metadata),
1366
+ ...typeof json.label === "string" && json.command !== "\\paragraph" ? { label: json.label } : {},
1360
1367
  ...json.centered === true ? { centered: true } : {}
1361
1368
  };
1362
1369
  }
@@ -6138,6 +6145,7 @@ function blockJson(block) {
6138
6145
  id: block.id,
6139
6146
  command: block.command,
6140
6147
  ...fieldJson(block.field),
6148
+ ...block.command !== "\\paragraph" && block.label ? { label: block.label } : {},
6141
6149
  ...block.metadata ? { metadata: { ...block.metadata } } : {},
6142
6150
  ...block.command === "\\paragraph" ? { centered: block.centered === true } : {}
6143
6151
  };
@@ -6266,6 +6274,13 @@ function parseBasicCommand(value) {
6266
6274
  text: requireString2(value.text, "text")
6267
6275
  };
6268
6276
  }
6277
+ if (value.op === "set_heading_label") {
6278
+ return {
6279
+ op: value.op,
6280
+ block_id: requireString2(value.block_id, "block_id", false).trim(),
6281
+ label: value.label === null ? null : requireString2(value.label, "label")
6282
+ };
6283
+ }
6269
6284
  if (value.op === "remove_block") {
6270
6285
  return { op: value.op, block_id: requireString2(value.block_id, "block_id", false).trim() };
6271
6286
  }
@@ -6358,7 +6373,7 @@ function parseCommand2(value) {
6358
6373
  if (value.op === "update_document_meta" || value.op === "insert_reference" || value.op === "update_reference" || value.op === "remove_reference" || value.op === "move_reference") {
6359
6374
  return parseArticleCommand(value);
6360
6375
  }
6361
- if (value.op === "insert_text_block" || value.op === "replace_text_block" || value.op === "remove_block" || value.op === "move_block" || value.op === "insert_figure" || value.op === "update_figure" || value.op === "update_float_meta" || value.op === "insert_bibliography") {
6376
+ if (value.op === "insert_text_block" || value.op === "replace_text_block" || value.op === "set_heading_label" || value.op === "remove_block" || value.op === "move_block" || value.op === "insert_figure" || value.op === "update_figure" || value.op === "update_float_meta" || value.op === "insert_bibliography") {
6362
6377
  return parseBasicCommand(value);
6363
6378
  }
6364
6379
  throw new DocumentCommandError("invalid_command", "Unsupported document command");
@@ -6403,6 +6418,20 @@ function applyBasicCommand(document2, command) {
6403
6418
  replacePlainField(document2, block2.field, command.text);
6404
6419
  return;
6405
6420
  }
6421
+ if (command.op === "set_heading_label") {
6422
+ const block2 = document2.blocks.find((entry) => entry.id === command.block_id);
6423
+ if (!block2) throw new DocumentCommandError("block_not_found", "Heading was not found");
6424
+ if (block2.kind !== "textBlock" || block2.command === "\\paragraph") {
6425
+ throw new DocumentCommandError("block_kind_mismatch", "Target is not a heading");
6426
+ }
6427
+ const key = command.label?.trim() ?? "";
6428
+ if (key && documentKeyError(key, { references: document2.references, labels: collectDocumentKeyLabels(document2), excludeOwnerId: block2.id })) {
6429
+ throw new DocumentCommandError("invalid_command", "Heading label is invalid or duplicated");
6430
+ }
6431
+ if (key) block2.label = key;
6432
+ else delete block2.label;
6433
+ return;
6434
+ }
6406
6435
  if (command.op === "remove_block") {
6407
6436
  const index = document2.blocks.findIndex((block2) => block2.id === command.block_id);
6408
6437
  if (index < 0) {
@@ -7130,7 +7159,7 @@ function refTokenLatexForDocument(token, labelKinds, previousToken) {
7130
7159
  }
7131
7160
  return `${semanticRefPrefix(kind)}~${reference}`;
7132
7161
  }
7133
- function tokenLatex(token, labelKinds, previousToken) {
7162
+ function tokenLatex(token, labelKinds, previousToken, unitId) {
7134
7163
  if (token.kind === "text") {
7135
7164
  return styledTextLatex(token.text, token.style);
7136
7165
  }
@@ -7142,7 +7171,7 @@ function tokenLatex(token, labelKinds, previousToken) {
7142
7171
  }
7143
7172
  if (isNumberedEquation(token)) {
7144
7173
  const body = mathBodyLatex(token);
7145
- const autoKey = implicitReferenceKey("eq", token.id);
7174
+ const autoKey = implicitReferenceKey("eq", token.id, unitId);
7146
7175
  const aliases = [autoKey];
7147
7176
  if (token.labelEnabled && token.label?.trim() && token.label.trim() !== autoKey) aliases.push(token.label.trim());
7148
7177
  return "\\begin{equation}\n" + body + "\n" + aliases.map((key) => "\\label{" + key + "}").join("\n") + "\n\\end{equation}";
@@ -7158,13 +7187,18 @@ function tokenLatex(token, labelKinds, previousToken) {
7158
7187
  }
7159
7188
  return renderMathNodeLatex(token.math);
7160
7189
  }
7161
- function inlineFieldLatexWithLabelKinds(field, labelKinds) {
7162
- return field.tokens.map((token, index) => tokenLatex(token, labelKinds, field.tokens[index - 1])).join("");
7190
+ function inlineFieldLatexWithLabelKinds(field, labelKinds, unitId) {
7191
+ return field.tokens.map((token, index) => tokenLatex(token, labelKinds, field.tokens[index - 1], unitId)).join("");
7163
7192
  }
7164
- function textBlockLatex(block, labelKinds) {
7165
- const content = inlineFieldLatexWithLabelKinds(block.field, labelKinds);
7193
+ function textBlockLatex(block, labelKinds, unitId) {
7194
+ const content = inlineFieldLatexWithLabelKinds(block.field, labelKinds, unitId);
7166
7195
  const body = block.command === "\\paragraph" ? `\\par
7167
7196
  ${content}` : `${block.command}{${content}}`;
7197
+ if (block.command !== "\\paragraph") {
7198
+ const keys = unitId ? [implicitHeadingReferenceKey(block.command.slice(1), block.id, unitId)] : [];
7199
+ if (block.label?.trim() && !keys.includes(block.label.trim())) keys.push(block.label.trim());
7200
+ return [body, ...keys.map((key) => `\\label{${key}}`)].join("\n");
7201
+ }
7168
7202
  if (block.command === "\\paragraph" && block.centered) {
7169
7203
  return `\\begin{center}
7170
7204
  ${body}
@@ -7175,10 +7209,10 @@ ${body}
7175
7209
  function indent(value) {
7176
7210
  return value.split("\n").map((line) => ` ${line}`).join("\n");
7177
7211
  }
7178
- function listBlockLatex(block, references, labelKinds, fixedFloats) {
7212
+ function listBlockLatex(block, references, labelKinds, fixedFloats, unitId) {
7179
7213
  const items = block.items.map((item) => {
7180
- const nested = item.blocks.map((child) => "\n" + indent(blockLatex(child, references, labelKinds, fixedFloats))).join("");
7181
- return ` \\item ${inlineFieldLatexWithLabelKinds(item.field, labelKinds)}${nested}`;
7214
+ const nested = item.blocks.map((child) => "\n" + indent(blockLatex(child, references, labelKinds, fixedFloats, unitId))).join("");
7215
+ return ` \\item ${inlineFieldLatexWithLabelKinds(item.field, labelKinds, unitId)}${nested}`;
7182
7216
  }).join("\n");
7183
7217
  return `${block.command}
7184
7218
  ${items}
@@ -7192,9 +7226,9 @@ function defaultGridColumnSpec(block) {
7192
7226
  }
7193
7227
  return `|${compact.split("").join("|")}|`;
7194
7228
  }
7195
- function tabularInnerLatex(block, labelKinds) {
7229
+ function tabularInnerLatex(block, labelKinds, unitId) {
7196
7230
  const rows = block.rows.map(
7197
- (row) => ` ${row.map((cell) => inlineFieldLatexWithLabelKinds(cell, labelKinds)).join(" & ")}`
7231
+ (row) => ` ${row.map((cell) => inlineFieldLatexWithLabelKinds(cell, labelKinds, unitId)).join(" & ")}`
7198
7232
  );
7199
7233
  const gridColumns = defaultGridColumnSpec(block);
7200
7234
  if (gridColumns) {
@@ -7208,9 +7242,9 @@ ${block.closing}`;
7208
7242
  ${rows.join(" \\\\\n")}
7209
7243
  ${block.closing}`;
7210
7244
  }
7211
- function floatCaptionLabelLines(block, counter, labelKinds) {
7245
+ function floatCaptionLabelLines(block, counter, labelKinds, unitId) {
7212
7246
  const lines = [];
7213
- const caption = inlineFieldLatexWithLabelKinds(block.captionField, labelKinds).trim();
7247
+ const caption = inlineFieldLatexWithLabelKinds(block.captionField, labelKinds, unitId).trim();
7214
7248
  const hasCaption = block.captionEnabled && caption.length > 0;
7215
7249
  if (hasCaption) {
7216
7250
  lines.push(` \\caption{${caption}}`);
@@ -7218,20 +7252,20 @@ function floatCaptionLabelLines(block, counter, labelKinds) {
7218
7252
  const hasManualLabel = block.labelEnabled && block.label.trim().length > 0;
7219
7253
  if (hasCaption || hasManualLabel) {
7220
7254
  if (!hasCaption) lines.push(" \\refstepcounter{" + counter + "}");
7221
- const autoKey = implicitReferenceKey(counter === "figure" ? "fig" : "tab", block.id);
7255
+ const autoKey = implicitReferenceKey(counter === "figure" ? "fig" : "tab", block.id, unitId);
7222
7256
  lines.push(" \\label{" + autoKey + "}");
7223
7257
  if (hasManualLabel && block.label.trim() !== autoKey) lines.push(" \\label{" + block.label.trim() + "}");
7224
7258
  }
7225
7259
  return lines;
7226
7260
  }
7227
- function tableBlockLatex(block, labelKinds, fixedFloats) {
7261
+ function tableBlockLatex(block, labelKinds, fixedFloats, unitId) {
7228
7262
  const placement = fixedFloats ? "H" : "htbp";
7229
7263
  const lines = [`\\begin{table}[${placement}]`];
7230
7264
  if (block.centered) {
7231
7265
  lines.push(" \\centering");
7232
7266
  }
7233
- lines.push(...floatCaptionLabelLines(block, "table", labelKinds));
7234
- lines.push(indent(tabularInnerLatex(block, labelKinds)));
7267
+ lines.push(...floatCaptionLabelLines(block, "table", labelKinds, unitId));
7268
+ lines.push(indent(tabularInnerLatex(block, labelKinds, unitId)));
7235
7269
  lines.push("\\end{table}");
7236
7270
  return lines.join("\n");
7237
7271
  }
@@ -7250,29 +7284,29 @@ function imageOptionsLatex(block, constrainToColumn) {
7250
7284
  }
7251
7285
  return `[${entries.map(([key, value]) => `${key}=${value}`).join(",")}]`;
7252
7286
  }
7253
- function imageBlockLatex(block, labelKinds, fixedFloats) {
7287
+ function imageBlockLatex(block, labelKinds, fixedFloats, unitId) {
7254
7288
  const placement = fixedFloats ? "H" : "htbp";
7255
7289
  const lines = [`\\begin{figure}[${placement}]`];
7256
7290
  if (block.centered) {
7257
7291
  lines.push(" \\centering");
7258
7292
  }
7259
7293
  lines.push(` ${block.command}${imageOptionsLatex(block, true)}{${block.value}}`);
7260
- lines.push(...floatCaptionLabelLines(block, "figure", labelKinds));
7294
+ lines.push(...floatCaptionLabelLines(block, "figure", labelKinds, unitId));
7261
7295
  lines.push("\\end{figure}");
7262
7296
  return lines.join("\n");
7263
7297
  }
7264
- function blockLatex(block, references, labelKinds, fixedFloats) {
7298
+ function blockLatex(block, references, labelKinds, fixedFloats, unitId) {
7265
7299
  if (block.kind === "textBlock") {
7266
- return textBlockLatex(block, labelKinds);
7300
+ return textBlockLatex(block, labelKinds, unitId);
7267
7301
  }
7268
7302
  if (block.kind === "list") {
7269
- return listBlockLatex(block, references, labelKinds, fixedFloats);
7303
+ return listBlockLatex(block, references, labelKinds, fixedFloats, unitId);
7270
7304
  }
7271
7305
  if (block.kind === "table") {
7272
- return tableBlockLatex(block, labelKinds, fixedFloats);
7306
+ return tableBlockLatex(block, labelKinds, fixedFloats, unitId);
7273
7307
  }
7274
7308
  if (block.kind === "image") {
7275
- return imageBlockLatex(block, labelKinds, fixedFloats);
7309
+ return imageBlockLatex(block, labelKinds, fixedFloats, unitId);
7276
7310
  }
7277
7311
  if (block.kind === "bibliography") {
7278
7312
  const width = String(Math.max(references.length, 9));
@@ -7326,6 +7360,17 @@ function closingHamdalaLatex() {
7326
7360
  \\maghribi{${BUTEX_CLOSING_HAMDALA}}
7327
7361
  \\end{center}`;
7328
7362
  }
7363
+ function documentContentLatex(document2, context) {
7364
+ if (!context?.unitId?.trim()) throw new Error("book-content export requires a stable unitId");
7365
+ const labelKinds = documentLabelKindMap(document2);
7366
+ for (const target of context?.targets ?? []) {
7367
+ if (target.kind === "fig" || target.kind === "tab" || target.kind === "eq") {
7368
+ labelKinds.set(target.key, target.kind);
7369
+ if (target.manualKey) labelKinds.set(target.manualKey, target.kind);
7370
+ }
7371
+ }
7372
+ return document2.blocks.filter((block) => block.kind !== "bibliography").map((block) => blockLatex(block, document2.references, labelKinds, false, context?.unitId)).filter((part) => part.length > 0).join("\n\n");
7373
+ }
7329
7374
  function documentLatex(document2, options = {}) {
7330
7375
  const meta = document2.meta ?? emptyDocumentMeta();
7331
7376
  const twocolumn = options.twocolumn === true;
@@ -7440,6 +7485,13 @@ function validateInlineField(context, field, path, blockId) {
7440
7485
  function validateBlock(context, block, path) {
7441
7486
  if (block.kind === "textBlock") {
7442
7487
  validateInlineField(context, block.field, `${path}.field`, block.id);
7488
+ if (block.command !== "\\paragraph") {
7489
+ const kind = block.command.slice(1);
7490
+ if (block.label) registerKey(context, block.label, `${path}.label`, kind, block.id);
7491
+ if (context.bookMode && context.bookContext) {
7492
+ context.labelKinds.set(implicitHeadingReferenceKey(kind, block.id, context.bookContext.unitId), kind);
7493
+ }
7494
+ }
7443
7495
  return;
7444
7496
  }
7445
7497
  if (block.kind === "list") {
@@ -7489,6 +7541,10 @@ function validateBlock(context, block, path) {
7489
7541
  }
7490
7542
  return;
7491
7543
  }
7544
+ if (block.kind === "bibliography" && context.bookMode) {
7545
+ addIssue(context, "book_local_bibliography", path, block.id);
7546
+ return;
7547
+ }
7492
7548
  if (block.kind === "raw") {
7493
7549
  validateTextValue(context, block.value, `${path}.value`, block.id);
7494
7550
  }
@@ -7511,7 +7567,7 @@ function validateDuplicateKeys(context) {
7511
7567
  }
7512
7568
  function validatePendingReferences(context) {
7513
7569
  for (const pending of context.pendingCitations) {
7514
- if (pending.token.keys.some((key) => !isValidDocumentKey(normalizeDocumentKey(key)))) {
7570
+ if (pending.token.keys.some((key) => !isValidDocumentKey(normalizeDocumentKey(key)) || context.citationKeys !== void 0 && !context.citationKeys.has(normalizeDocumentKey(key)))) {
7515
7571
  addIssue(
7516
7572
  context,
7517
7573
  "missing_citation",
@@ -7593,7 +7649,7 @@ function resolveDocument(document2) {
7593
7649
  return null;
7594
7650
  }
7595
7651
  }
7596
- function validateDocument(document2) {
7652
+ function validateDocument(document2, options = {}) {
7597
7653
  const resolved = resolveDocument(document2);
7598
7654
  if (!resolved) {
7599
7655
  return {
@@ -7605,6 +7661,9 @@ function validateDocument(document2) {
7605
7661
  issues: [],
7606
7662
  keyOwners: [],
7607
7663
  labelKinds: /* @__PURE__ */ new Map(),
7664
+ bookMode: options.mode === "book-content",
7665
+ bookContext: options.bookContext,
7666
+ ...options.mode === "book-content" && options.bookContext?.references ? { citationKeys: new Set(options.bookContext.references.map((entry) => normalizeDocumentKey(entry.key))) } : {},
7608
7667
  pendingCitations: [],
7609
7668
  pendingReferences: []
7610
7669
  };
@@ -7624,10 +7683,11 @@ function validateDocument(document2) {
7624
7683
  validateBlock(context, block, `$.blocks[${String(index)}]`);
7625
7684
  });
7626
7685
  for (const target of collectDocumentReferenceTargets(resolved)) {
7627
- if (target.number !== null && target.manualKey !== target.key) {
7686
+ const autoKey = context.bookMode && context.bookContext ? implicitReferenceKey(target.kind, target.ownerId, context.bookContext.unitId) : target.key;
7687
+ if (target.number !== null && target.manualKey !== autoKey) {
7628
7688
  registerKey(
7629
7689
  context,
7630
- target.key,
7690
+ autoKey,
7631
7691
  "$.automatic_labels",
7632
7692
  target.kind,
7633
7693
  target.kind === "eq" ? void 0 : target.ownerId,
@@ -7635,6 +7695,15 @@ function validateDocument(document2) {
7635
7695
  );
7636
7696
  }
7637
7697
  }
7698
+ if (context.bookMode) {
7699
+ for (const target of context.bookContext?.targets ?? []) {
7700
+ context.labelKinds.set(normalizeDocumentKey(target.key), target.kind);
7701
+ if (target.manualKey) context.labelKinds.set(normalizeDocumentKey(target.manualKey), target.kind);
7702
+ }
7703
+ }
7704
+ if (context.bookMode && !context.bookContext?.unitId?.trim()) {
7705
+ addIssue(context, "book_context_required", "$.book_context");
7706
+ }
7638
7707
  for (const diagnostic of resolved.diagnostics) {
7639
7708
  addIssue(context, "parser_diagnostic", diagnostic.path);
7640
7709
  }
@@ -7662,6 +7731,11 @@ function documentLatex2(document2, options = {}) {
7662
7731
  }
7663
7732
  return documentLatex(document2, options);
7664
7733
  }
7734
+ function documentContentLatex2(document2, context) {
7735
+ const validation = validateDocument(document2, { mode: "book-content", bookContext: context });
7736
+ if (!validation.valid) throw new DocumentValidationError(validation.issues);
7737
+ return documentContentLatex(document2, context);
7738
+ }
7665
7739
 
7666
7740
  // src/document-cli/mathDiagnostic.ts
7667
7741
  function compactError(error) {
@@ -7704,6 +7778,480 @@ function diagnoseMathObject(mathObject) {
7704
7778
  };
7705
7779
  }
7706
7780
 
7781
+ // src/book/utils.ts
7782
+ var ID = /^[A-Za-z0-9_-]{1,128}$/;
7783
+ function safeId(id) {
7784
+ return ID.test(id) && !["__proto__", "prototype", "constructor"].includes(id);
7785
+ }
7786
+ function object(value) {
7787
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7788
+ }
7789
+ function copy(value) {
7790
+ return JSON.parse(JSON.stringify(value));
7791
+ }
7792
+
7793
+ // src/book/validation.ts
7794
+ var BookContractError = class extends Error {
7795
+ code = "invalid_book";
7796
+ constructor(message) {
7797
+ super(message);
7798
+ this.name = "BookContractError";
7799
+ }
7800
+ };
7801
+ var KEYS = /* @__PURE__ */ new Set(["title-page", "table-of-contents", "list-of-figures", "list-of-tables", "bibliography"]);
7802
+ var UNIT_TYPES = /* @__PURE__ */ new Set(["abstract", "dedication", "acknowledgements", "preface", "abbreviations", "chapter", "appendix", "backmatter"]);
7803
+ function normalizeBookSnapshot(value) {
7804
+ if (!object(value) || !object(value.manifest) || !object(value.references) || !object(value.documents)) {
7805
+ throw new BookContractError("Book snapshot requires manifest, references and documents");
7806
+ }
7807
+ const manifest = value.manifest;
7808
+ const meta = manifest.meta;
7809
+ if (manifest.node_type !== "BookManifest" || manifest.schema_version !== 1 || typeof manifest.id !== "string" || !safeId(manifest.id) || manifest.references_path !== "references.json" || !Array.isArray(manifest.entries) || !object(meta) || typeof meta.title !== "string" || !Array.isArray(meta.authors) || !meta.authors.every((x) => typeof x === "string") || meta.language !== "ar" || meta.direction !== "rtl" || meta.numbering !== void 0 && (!object(meta.numbering) || meta.numbering.digit_form !== void 0 && !["arabicIndic", "western"].includes(String(meta.numbering.digit_form)) || meta.numbering.chapter_heading !== void 0 && !["ordinal-words", "digits"].includes(String(meta.numbering.chapter_heading)) || meta.numbering.appendix_heading !== void 0 && !["letters", "digits"].includes(String(meta.numbering.appendix_heading)))) {
7810
+ throw new BookContractError("Invalid BookManifest v1");
7811
+ }
7812
+ if (value.references.node_type !== "BookReferences" || value.references.schema_version !== 1 || !Array.isArray(value.references.references)) {
7813
+ throw new BookContractError("Invalid BookReferences v1");
7814
+ }
7815
+ const ids = /* @__PURE__ */ new Set();
7816
+ const generated = /* @__PURE__ */ new Set();
7817
+ const unitIds = /* @__PURE__ */ new Set();
7818
+ for (const entry of manifest.entries) {
7819
+ if (!object(entry) || typeof entry.id !== "string" || !safeId(entry.id) || ids.has(entry.id)) {
7820
+ throw new BookContractError("Duplicate or unsafe book entry ID");
7821
+ }
7822
+ ids.add(entry.id);
7823
+ if (entry.kind === "generated") {
7824
+ if (typeof entry.generated !== "string" || !KEYS.has(entry.generated) || generated.has(entry.generated)) {
7825
+ throw new BookContractError("Invalid or repeated generated entry");
7826
+ }
7827
+ generated.add(entry.generated);
7828
+ } else if (entry.kind === "document") {
7829
+ if (typeof entry.type !== "string" || !UNIT_TYPES.has(entry.type) || typeof entry.title !== "string" || typeof entry.numbered !== "boolean" || typeof entry.include_in_toc !== "boolean" || entry.document_path !== "content/units/" + entry.id + "/document.json") {
7830
+ throw new BookContractError("Invalid or unsafe unit entry");
7831
+ }
7832
+ unitIds.add(entry.id);
7833
+ } else {
7834
+ throw new BookContractError("Unknown book entry kind");
7835
+ }
7836
+ }
7837
+ const documents = value.documents;
7838
+ if (Object.keys(documents).length !== unitIds.size || Object.keys(documents).some((id) => !unitIds.has(id))) {
7839
+ throw new BookContractError("Unit documents must exactly match manifest");
7840
+ }
7841
+ for (const id of unitIds) {
7842
+ const doc = documents[id];
7843
+ if (!object(doc) || doc.node_type !== "DocumentObject" || !Array.isArray(doc.blocks)) {
7844
+ throw new BookContractError("Invalid unit DocumentJson for " + id);
7845
+ }
7846
+ }
7847
+ for (const ref of value.references.references) {
7848
+ if (!object(ref) || typeof ref.key !== "string" || !isValidDocumentKey(ref.key)) {
7849
+ throw new BookContractError("Invalid shared bibliography entry");
7850
+ }
7851
+ }
7852
+ return copy(value);
7853
+ }
7854
+
7855
+ // src/book/jsonCommands.ts
7856
+ function parseBookCommand(value) {
7857
+ if (!object(value) || typeof value.op !== "string") {
7858
+ throw new BookContractError("Book command requires an operation");
7859
+ }
7860
+ const rules = {
7861
+ reorder_entries: ["entry_ids"],
7862
+ update_entry: ["entry_id", "title", "numbered", "include_in_toc", "label"],
7863
+ set_meta: ["meta"],
7864
+ set_references: ["references"],
7865
+ insert_entry: ["entry", "document", "index"],
7866
+ remove_entry: ["entry_id"]
7867
+ };
7868
+ const allowed = rules[value.op];
7869
+ if (!allowed || Object.keys(value).some((key) => key !== "op" && !allowed.includes(key))) {
7870
+ throw new BookContractError("Unsupported book command fields");
7871
+ }
7872
+ if (value.op === "reorder_entries" && (!Array.isArray(value.entry_ids) || !value.entry_ids.every((id) => typeof id === "string"))) {
7873
+ throw new BookContractError("Reorder requires entry ID list");
7874
+ }
7875
+ if (value.op === "update_entry" && (typeof value.entry_id !== "string" || !safeId(value.entry_id) || !["title", "numbered", "include_in_toc", "label"].some((key) => key in value) || value.title !== void 0 && typeof value.title !== "string" || value.numbered !== void 0 && typeof value.numbered !== "boolean" || value.include_in_toc !== void 0 && typeof value.include_in_toc !== "boolean" || value.label !== void 0 && value.label !== null && typeof value.label !== "string")) {
7876
+ throw new BookContractError("Invalid book entry patch");
7877
+ }
7878
+ if (value.op === "set_meta" && !object(value.meta)) {
7879
+ throw new BookContractError("Book metadata must be an object");
7880
+ }
7881
+ if (value.op === "set_references" && (!Array.isArray(value.references) || !value.references.every((entry) => object(entry)))) {
7882
+ throw new BookContractError("Shared bibliography must be an array of entries");
7883
+ }
7884
+ if (value.op === "insert_entry" && (!object(value.entry) || !Number.isInteger(value.index) || value.entry.kind !== "document" && value.entry.kind !== "generated" || value.entry.kind === "document" && !object(value.document) || value.entry.kind === "generated" && value.document !== void 0)) {
7885
+ throw new BookContractError("Invalid book insertion command");
7886
+ }
7887
+ if (value.op === "remove_entry" && (typeof value.entry_id !== "string" || !safeId(value.entry_id))) {
7888
+ throw new BookContractError("Removal requires stable entry ID");
7889
+ }
7890
+ return value;
7891
+ }
7892
+ function applyBookCommand(raw, command) {
7893
+ const snapshot = normalizeBookSnapshot(raw);
7894
+ command = parseBookCommand(command);
7895
+ if (command.op === "reorder_entries") {
7896
+ const actual = snapshot.manifest.entries.map((e) => e.id);
7897
+ if (command.entry_ids.length !== actual.length || new Set(command.entry_ids).size !== actual.length || actual.some((id) => !command.entry_ids.includes(id))) {
7898
+ throw new BookContractError("Reorder must contain every existing entry exactly once");
7899
+ }
7900
+ const byId = new Map(snapshot.manifest.entries.map((e) => [e.id, e]));
7901
+ snapshot.manifest.entries = command.entry_ids.map((id) => byId.get(id));
7902
+ } else if (command.op === "update_entry") {
7903
+ const entry = snapshot.manifest.entries.find((e) => e.id === command.entry_id);
7904
+ if (!entry || entry.kind !== "document") throw new BookContractError("Unknown document unit");
7905
+ if (command.title !== void 0) entry.title = command.title;
7906
+ if (command.numbered !== void 0) entry.numbered = command.numbered;
7907
+ if (command.include_in_toc !== void 0) entry.include_in_toc = command.include_in_toc;
7908
+ if (command.label !== void 0) {
7909
+ if (command.label === null) delete entry.label;
7910
+ else entry.label = command.label;
7911
+ }
7912
+ } else if (command.op === "set_meta") {
7913
+ snapshot.manifest.meta = copy(command.meta);
7914
+ } else if (command.op === "set_references") {
7915
+ snapshot.references.references = copy(command.references);
7916
+ } else if (command.op === "insert_entry") {
7917
+ if (!Number.isInteger(command.index) || command.index < 0 || command.index > snapshot.manifest.entries.length) {
7918
+ throw new BookContractError("Invalid insertion index");
7919
+ }
7920
+ snapshot.manifest.entries.splice(command.index, 0, copy(command.entry));
7921
+ if (command.entry.kind === "document") {
7922
+ if (!command.document) throw new BookContractError("New document unit needs a separate DocumentJson");
7923
+ snapshot.documents[command.entry.id] = copy(command.document);
7924
+ }
7925
+ } else if (command.op === "remove_entry") {
7926
+ const at = snapshot.manifest.entries.findIndex((e) => e.id === command.entry_id);
7927
+ if (at < 0) throw new BookContractError("Unknown book entry");
7928
+ const [removed] = snapshot.manifest.entries.splice(at, 1);
7929
+ if (removed?.kind === "document") delete snapshot.documents[removed.id];
7930
+ } else {
7931
+ throw new BookContractError("Unknown book structure operation");
7932
+ }
7933
+ return normalizeBookSnapshot(snapshot);
7934
+ }
7935
+
7936
+ // src/book/introspection.ts
7937
+ var LETTERS = ["\u0623", "\u0628", "\u062C", "\u062F", "\u0647\u0640", "\u0648", "\u0632", "\u062D", "\u0637", "\u064A", "\u0643", "\u0644", "\u0645", "\u0646", "\u0633", "\u0639", "\u0641", "\u0635", "\u0642", "\u0631", "\u0634", "\u062A", "\u062B", "\u062E", "\u0630", "\u0636", "\u0638", "\u063A"];
7938
+ var ORDINALS = [
7939
+ "\u0627\u0644\u0623\u0648\u0644",
7940
+ "\u0627\u0644\u062B\u0627\u0646\u064A",
7941
+ "\u0627\u0644\u062B\u0627\u0644\u062B",
7942
+ "\u0627\u0644\u0631\u0627\u0628\u0639",
7943
+ "\u0627\u0644\u062E\u0627\u0645\u0633",
7944
+ "\u0627\u0644\u0633\u0627\u062F\u0633",
7945
+ "\u0627\u0644\u0633\u0627\u0628\u0639",
7946
+ "\u0627\u0644\u062B\u0627\u0645\u0646",
7947
+ "\u0627\u0644\u062A\u0627\u0633\u0639",
7948
+ "\u0627\u0644\u0639\u0627\u0634\u0631",
7949
+ "\u0627\u0644\u062D\u0627\u062F\u064A \u0639\u0634\u0631",
7950
+ "\u0627\u0644\u062B\u0627\u0646\u064A \u0639\u0634\u0631",
7951
+ "\u0627\u0644\u062B\u0627\u0644\u062B \u0639\u0634\u0631",
7952
+ "\u0627\u0644\u0631\u0627\u0628\u0639 \u0639\u0634\u0631",
7953
+ "\u0627\u0644\u062E\u0627\u0645\u0633 \u0639\u0634\u0631",
7954
+ "\u0627\u0644\u0633\u0627\u062F\u0633 \u0639\u0634\u0631",
7955
+ "\u0627\u0644\u0633\u0627\u0628\u0639 \u0639\u0634\u0631",
7956
+ "\u0627\u0644\u062B\u0627\u0645\u0646 \u0639\u0634\u0631",
7957
+ "\u0627\u0644\u062A\u0627\u0633\u0639 \u0639\u0634\u0631",
7958
+ "\u0627\u0644\u0639\u0634\u0631\u0648\u0646"
7959
+ ];
7960
+ function digits(value, form) {
7961
+ return form === "western" ? String(value) : String(value).replace(/[0-9]/g, (ch) => "\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669"[Number(ch)]);
7962
+ }
7963
+ function ordinal(number, form, style) {
7964
+ return style === "digits" ? digits(number, form) : ORDINALS[number - 1] ?? digits(number, form);
7965
+ }
7966
+ function appendix(number, form, style) {
7967
+ return style === "digits" ? digits(number, form) : LETTERS[number - 1] ?? digits(number, form);
7968
+ }
7969
+ function unitAlias(kind, unitId) {
7970
+ const hex = Array.from(new TextEncoder().encode(unitId), (byte) => byte.toString(16).padStart(2, "0")).join("");
7971
+ return kind + ":butex-auto-u" + hex + "-" + hex;
7972
+ }
7973
+ function issue(code, path, extra = {}) {
7974
+ return { code, path, severity: code === "missing_citation" || code === "missing_reference" ? "warning" : "error", ...extra };
7975
+ }
7976
+ function headingKind(block) {
7977
+ if (block.command === "\\section") return "section";
7978
+ if (block.command === "\\subsection") return "subsection";
7979
+ if (block.command === "\\subsubsection") return "subsubsection";
7980
+ return null;
7981
+ }
7982
+ function headingLevel(kind) {
7983
+ return kind === "section" ? 1 : kind === "subsection" ? 2 : 3;
7984
+ }
7985
+ function resolveBookSnapshot(raw) {
7986
+ const snapshot = normalizeBookSnapshot(raw);
7987
+ const { manifest, references, documents } = snapshot;
7988
+ const digitForm = manifest.meta.numbering?.digit_form ?? "arabicIndic";
7989
+ const chapterStyle = manifest.meta.numbering?.chapter_heading ?? "ordinal-words";
7990
+ const appendixStyle = manifest.meta.numbering?.appendix_heading ?? "letters";
7991
+ const outline = [];
7992
+ const targets = [];
7993
+ const issues = [];
7994
+ const aliasOwners = /* @__PURE__ */ new Map();
7995
+ const citationKeys = /* @__PURE__ */ new Set();
7996
+ const unnumbered = { fig: 0, tab: 0, eq: 0 };
7997
+ let chapterCount = 0;
7998
+ let appendixCount = 0;
7999
+ function register(key, unitId, ownerId) {
8000
+ if (!key) return;
8001
+ if (!isValidDocumentKey(key)) {
8002
+ issues.push(issue("invalid_key", "$.references", { unit_id: unitId, block_id: ownerId, key }));
8003
+ }
8004
+ if (aliasOwners.has(key)) {
8005
+ issues.push(issue("duplicate_key", "$.references", { unit_id: unitId, block_id: ownerId, key }));
8006
+ } else {
8007
+ aliasOwners.set(key, { unitId, ownerId });
8008
+ }
8009
+ }
8010
+ for (let n = 0; n < references.references.length; n++) {
8011
+ const ref = references.references[n];
8012
+ citationKeys.add(ref.key);
8013
+ register(ref.key);
8014
+ }
8015
+ const citations = references.references.map((ref, i) => ({
8016
+ key: ref.key,
8017
+ number: i + 1,
8018
+ display_label: "[" + digits(i + 1, digitForm) + "]"
8019
+ }));
8020
+ for (const entry of manifest.entries) {
8021
+ if (entry.kind === "generated") {
8022
+ outline.push({
8023
+ id: entry.id,
8024
+ kind: "generated",
8025
+ title: entry.generated,
8026
+ display_label: entry.generated,
8027
+ level: 0,
8028
+ numbered: false,
8029
+ include_in_toc: false
8030
+ });
8031
+ continue;
8032
+ }
8033
+ const unitId = entry.id;
8034
+ const isChapter = entry.type === "chapter";
8035
+ const isAppendix = entry.type === "appendix";
8036
+ if (isChapter && entry.numbered) chapterCount++;
8037
+ if (isAppendix && entry.numbered) appendixCount++;
8038
+ const chapterNumber = isChapter && entry.numbered ? chapterCount : null;
8039
+ const appendixNumber = isAppendix && entry.numbered ? appendixCount : null;
8040
+ const prefix = chapterNumber !== null ? digits(chapterNumber, digitForm) : appendixNumber !== null ? appendix(appendixNumber, digitForm, appendixStyle) : "";
8041
+ const generatedTitle = chapterNumber !== null ? "\u0627\u0644\u0641\u0635\u0644 " + ordinal(chapterNumber, digitForm, chapterStyle) : appendixNumber !== null ? "\u0627\u0644\u0645\u0644\u062D\u0642 " + prefix : "";
8042
+ const displayTitle = generatedTitle ? generatedTitle + ": " + entry.title : entry.title;
8043
+ outline.push({
8044
+ id: unitId,
8045
+ unit_id: unitId,
8046
+ kind: isChapter ? "chapter" : isAppendix ? "appendix" : "unit",
8047
+ title: entry.title,
8048
+ display_label: displayTitle,
8049
+ level: 0,
8050
+ numbered: entry.numbered,
8051
+ include_in_toc: entry.include_in_toc
8052
+ });
8053
+ if (isChapter || isAppendix) {
8054
+ const kind = isChapter ? "chapter" : "appendix";
8055
+ const key = unitAlias(kind, unitId);
8056
+ targets.push({
8057
+ unitId,
8058
+ ownerId: unitId,
8059
+ key,
8060
+ kind,
8061
+ caption: entry.title,
8062
+ displayLabel: generatedTitle || entry.title,
8063
+ numbered: entry.numbered,
8064
+ ...prefix ? { ordinal: prefix } : {},
8065
+ ...entry.label ? { manualKey: entry.label } : {}
8066
+ });
8067
+ register(key, unitId, unitId);
8068
+ register(entry.label, unitId, unitId);
8069
+ } else {
8070
+ register(entry.label, unitId, unitId);
8071
+ }
8072
+ const doc = documents[unitId];
8073
+ const seenBlocks = /* @__PURE__ */ new Set();
8074
+ const headingNumbers = { section: 0, subsection: 0, subsubsection: 0 };
8075
+ for (let b = 0; b < doc.blocks.length; b++) {
8076
+ const block = doc.blocks[b];
8077
+ if (!block.id || seenBlocks.has(block.id)) {
8078
+ issues.push(issue(
8079
+ "unstable_block_id",
8080
+ "$.documents." + unitId + ".blocks[" + b + "]",
8081
+ { unit_id: unitId, block_id: block.id }
8082
+ ));
8083
+ } else seenBlocks.add(block.id);
8084
+ if (block.command === "\\begin{thebibliography}" || block.command === "\\bibliography") {
8085
+ issues.push(issue(
8086
+ "local_bibliography",
8087
+ "$.documents." + unitId + ".blocks[" + b + "]",
8088
+ { unit_id: unitId, block_id: block.id }
8089
+ ));
8090
+ }
8091
+ const kind = headingKind(block);
8092
+ if (kind && block.id) {
8093
+ if (kind === "section") {
8094
+ headingNumbers.section++;
8095
+ headingNumbers.subsection = 0;
8096
+ headingNumbers.subsubsection = 0;
8097
+ } else if (kind === "subsection") {
8098
+ headingNumbers.subsection++;
8099
+ headingNumbers.subsubsection = 0;
8100
+ } else {
8101
+ headingNumbers.subsubsection++;
8102
+ }
8103
+ const levels = kind === "section" ? [headingNumbers.section] : kind === "subsection" ? [headingNumbers.section, headingNumbers.subsection] : [headingNumbers.section, headingNumbers.subsection, headingNumbers.subsubsection];
8104
+ const ordinalLabel = [
8105
+ ...prefix ? [prefix] : [],
8106
+ ...levels.map((number) => digits(number, digitForm))
8107
+ ].join(".");
8108
+ const visible = "\u0627\u0644\u0642\u0633\u0645 " + ordinalLabel;
8109
+ const key = implicitHeadingReferenceKey(kind, block.id, unitId);
8110
+ const label = block.value ?? "";
8111
+ outline.push({
8112
+ id: block.id,
8113
+ parent_unit_id: unitId,
8114
+ unit_id: unitId,
8115
+ kind,
8116
+ title: label,
8117
+ display_label: visible + ": " + label,
8118
+ level: headingLevel(kind),
8119
+ numbered: true,
8120
+ include_in_toc: entry.include_in_toc
8121
+ });
8122
+ targets.push({
8123
+ unitId,
8124
+ ownerId: block.id,
8125
+ key,
8126
+ kind,
8127
+ caption: label,
8128
+ displayLabel: visible,
8129
+ ordinal: ordinalLabel,
8130
+ numbered: true,
8131
+ ...block.label ? { manualKey: block.label } : {}
8132
+ });
8133
+ register(key, unitId, block.id);
8134
+ register(block.label, unitId, block.id);
8135
+ }
8136
+ }
8137
+ const resolved = fromDocumentJson(doc);
8138
+ const localCounts = { fig: 0, tab: 0, eq: 0 };
8139
+ for (const target of collectDocumentReferenceTargets(resolved)) {
8140
+ const key = implicitReferenceKey(target.kind, target.ownerId, unitId);
8141
+ const numbered = target.number !== null;
8142
+ if (numbered) {
8143
+ if (prefix) localCounts[target.kind]++;
8144
+ else unnumbered[target.kind]++;
8145
+ }
8146
+ const index = prefix ? localCounts[target.kind] : unnumbered[target.kind];
8147
+ const displayOrdinal = numbered ? (prefix ? prefix + "." : "") + digits(index, digitForm) : "";
8148
+ const name = target.kind === "fig" ? "\u0627\u0644\u0634\u0643\u0644" : target.kind === "tab" ? "\u0627\u0644\u062C\u062F\u0648\u0644" : "\u0627\u0644\u0645\u0639\u0627\u062F\u0644\u0629";
8149
+ const displayLabel = numbered ? target.kind === "eq" ? name + " (" + displayOrdinal + ")" : name + " " + displayOrdinal : "";
8150
+ targets.push({
8151
+ unitId,
8152
+ ownerId: target.ownerId,
8153
+ key,
8154
+ kind: target.kind,
8155
+ caption: target.caption,
8156
+ numbered,
8157
+ ...displayOrdinal ? { ordinal: displayOrdinal, displayLabel } : {},
8158
+ ...target.manualKey ? { manualKey: target.manualKey } : {}
8159
+ });
8160
+ if (numbered) {
8161
+ register(key, unitId, target.ownerId);
8162
+ register(target.manualKey, unitId, target.ownerId);
8163
+ }
8164
+ }
8165
+ }
8166
+ for (const entry of manifest.entries) {
8167
+ if (entry.kind !== "document") continue;
8168
+ const doc = fromDocumentJson(documents[entry.id]);
8169
+ const refs = getDocumentReferenceIndex(doc);
8170
+ for (const citation of refs.citations) {
8171
+ for (const key of citation.keys) {
8172
+ if (!citationKeys.has(key)) {
8173
+ issues.push(issue("missing_citation", "$.documents." + entry.id + ".citations", {
8174
+ unit_id: entry.id,
8175
+ block_id: citation.block_id,
8176
+ token_id: citation.token_id,
8177
+ key
8178
+ }));
8179
+ }
8180
+ }
8181
+ }
8182
+ for (const reference of refs.cross_references) {
8183
+ for (const key of reference.keys) {
8184
+ const hit = targets.find((t) => t.key === key || t.manualKey === key);
8185
+ if (!hit || !hit.numbered && (hit.kind === "fig" || hit.kind === "tab" || hit.kind === "eq")) {
8186
+ issues.push(issue("missing_reference", "$.documents." + entry.id + ".references", {
8187
+ unit_id: entry.id,
8188
+ block_id: reference.block_id,
8189
+ token_id: reference.token_id,
8190
+ key
8191
+ }));
8192
+ } else if (reference.ref_command === "eqref" && hit.kind !== "eq") {
8193
+ issues.push(issue("invalid_reference_kind", "$.documents." + entry.id + ".references", {
8194
+ unit_id: entry.id,
8195
+ block_id: reference.block_id,
8196
+ token_id: reference.token_id,
8197
+ key
8198
+ }));
8199
+ }
8200
+ }
8201
+ }
8202
+ }
8203
+ return { manifest_id: manifest.id, outline, targets, citations, issues };
8204
+ }
8205
+ function validateBookSnapshot(snapshot) {
8206
+ const resolution = resolveBookSnapshot(snapshot);
8207
+ return { valid: resolution.issues.every((x) => x.severity !== "error"), issues: resolution.issues };
8208
+ }
8209
+
8210
+ // src/book-cli/execute.ts
8211
+ function executeBookWorkerRequest(request) {
8212
+ switch (request.action) {
8213
+ case "book_resolve":
8214
+ return { ok: true, book: resolveBookSnapshot(request.snapshot) };
8215
+ case "book_validate":
8216
+ return { ok: true, validation: validateBookSnapshot(request.snapshot) };
8217
+ case "book_commands":
8218
+ return { ok: true, snapshot: applyBookCommand(request.snapshot, request.command) };
8219
+ }
8220
+ }
8221
+
8222
+ // src/book-cli/protocol.ts
8223
+ var BOOK_WORKER_ROUTES = {
8224
+ book_resolve: "/v1/book/resolve",
8225
+ book_validate: "/v1/book/validate",
8226
+ book_commands: "/v1/book/commands"
8227
+ };
8228
+ function bookActionForPath(pathname) {
8229
+ for (const [action, path] of Object.entries(BOOK_WORKER_ROUTES)) {
8230
+ if (path === pathname) return action;
8231
+ }
8232
+ return null;
8233
+ }
8234
+ function isBookWorkerAction(action) {
8235
+ return Object.prototype.hasOwnProperty.call(BOOK_WORKER_ROUTES, action);
8236
+ }
8237
+ function isBookWorkerRequest(request) {
8238
+ return isBookWorkerAction(request.action);
8239
+ }
8240
+ function parseBookWorkerRequest(value) {
8241
+ const action = value.action;
8242
+ if (typeof action !== "string" || !isBookWorkerAction(action) || !("snapshot" in value)) {
8243
+ throw new BookContractError("Book worker request requires action and snapshot");
8244
+ }
8245
+ if (action === "book_commands") {
8246
+ const command = value.command;
8247
+ if (typeof command !== "object" || command === null || Array.isArray(command) || typeof command.op !== "string") {
8248
+ throw new BookContractError("Book structure command requires an operation");
8249
+ }
8250
+ return { action, snapshot: value.snapshot, command };
8251
+ }
8252
+ return { action, snapshot: value.snapshot };
8253
+ }
8254
+
7707
8255
  // src/document-cli/mathProjection.ts
7708
8256
  function sourceMode2(value) {
7709
8257
  if (typeof value === "object" && value !== null && !Array.isArray(value) && value.source_side === "arabic") {
@@ -7761,6 +8309,15 @@ function parseDocumentWorkerRequest(value) {
7761
8309
  if (!isObject4(value) || typeof value.action !== "string") {
7762
8310
  throw new DocumentWorkerProtocolError("invalid_request", "Worker request requires an action");
7763
8311
  }
8312
+ if (isBookWorkerAction(value.action)) {
8313
+ if (!("snapshot" in value)) {
8314
+ throw new DocumentWorkerProtocolError("invalid_request", "Book operation requires snapshot");
8315
+ }
8316
+ if (value.action === "book_commands" && (!isObject4(value.command) || typeof value.command.op !== "string")) {
8317
+ throw new DocumentWorkerProtocolError("invalid_request", "Book command requires op");
8318
+ }
8319
+ return parseBookWorkerRequest(value);
8320
+ }
7764
8321
  if (value.action === "diagnose_contract") {
7765
8322
  return { action: "diagnose_contract" };
7766
8323
  }
@@ -7779,9 +8336,28 @@ function parseDocumentWorkerRequest(value) {
7779
8336
  if (!("document" in value)) {
7780
8337
  throw new DocumentWorkerProtocolError("invalid_request", "Worker request requires a document");
7781
8338
  }
7782
- if (value.action === "normalize" || value.action === "outline" || value.action === "references" || value.action === "reference_index" || value.action === "export") {
8339
+ if (value.action === "normalize" || value.action === "outline" || value.action === "references" || value.action === "reference_index") {
7783
8340
  return { action: value.action, document: value.document };
7784
8341
  }
8342
+ if (value.action === "export") {
8343
+ if (value.mode !== void 0 && value.mode !== "article" && value.mode !== "book-content") {
8344
+ throw new DocumentWorkerProtocolError("invalid_request", "Unsupported export mode");
8345
+ }
8346
+ if (value.mode === "book-content" && value.book_context === void 0) {
8347
+ throw new DocumentWorkerProtocolError("invalid_request", "book-content export requires book_context with unitId");
8348
+ }
8349
+ if (value.book_context !== void 0) {
8350
+ const ctx = value.book_context;
8351
+ if (!isObject4(ctx) || typeof ctx.unitId !== "string" || !ctx.unitId.trim() || ctx.references !== void 0 && (!Array.isArray(ctx.references) || ctx.references.some((entry) => !isObject4(entry) || typeof entry.key !== "string")) || ctx.targets !== void 0 && (!Array.isArray(ctx.targets) || ctx.targets.some((entry) => !isObject4(entry) || typeof entry.key !== "string" || typeof entry.unitId !== "string" || typeof entry.ownerId !== "string" || typeof entry.kind !== "string"))) {
8352
+ throw new DocumentWorkerProtocolError("invalid_request", "Invalid book_context");
8353
+ }
8354
+ if (value.mode !== "book-content") {
8355
+ throw new DocumentWorkerProtocolError("invalid_request", "book_context requires book-content mode");
8356
+ }
8357
+ return { action: "export", document: value.document, mode: "book-content", book_context: ctx };
8358
+ }
8359
+ return { action: "export", document: value.document, ...value.mode ? { mode: value.mode } : {} };
8360
+ }
7785
8361
  if (value.action === "apply_command") {
7786
8362
  if (!("command" in value)) {
7787
8363
  throw new DocumentWorkerProtocolError("invalid_request", "apply_command requires command");
@@ -7791,14 +8367,20 @@ function parseDocumentWorkerRequest(value) {
7791
8367
  throw new DocumentWorkerProtocolError("invalid_request", `Unsupported worker action: ${value.action}`);
7792
8368
  }
7793
8369
  function boundedValidationIssues(issues) {
7794
- return issues.slice(0, 100).map((issue) => ({
7795
- code: issue.code,
7796
- path: issue.path.slice(0, 500),
7797
- ...issue.blockId ? { blockId: issue.blockId.slice(0, 500) } : {},
7798
- ...issue.tokenId ? { tokenId: issue.tokenId.slice(0, 500) } : {}
8370
+ return issues.slice(0, 100).map((issue2) => ({
8371
+ code: issue2.code,
8372
+ path: issue2.path.slice(0, 500),
8373
+ ...issue2.blockId ? { blockId: issue2.blockId.slice(0, 500) } : {},
8374
+ ...issue2.tokenId ? { tokenId: issue2.tokenId.slice(0, 500) } : {}
7799
8375
  }));
7800
8376
  }
7801
8377
  function workerFailure(error) {
8378
+ if (error instanceof BookContractError) {
8379
+ return {
8380
+ response: { ok: false, error: { code: "invalid_book", message: error.message.slice(0, 400) } },
8381
+ status: 422
8382
+ };
8383
+ }
7802
8384
  if (error instanceof DocumentValidationError) {
7803
8385
  return {
7804
8386
  response: {
@@ -7883,12 +8465,15 @@ function collectAssetIds(blocks) {
7883
8465
  }
7884
8466
  function executeDocumentWorkerRequest(input) {
7885
8467
  const request = parseDocumentWorkerRequest(input);
8468
+ if (isBookWorkerRequest(request)) {
8469
+ return executeBookWorkerRequest(request);
8470
+ }
7886
8471
  if (request.action === "diagnose_contract") {
7887
8472
  return {
7888
8473
  ok: true,
7889
8474
  contract: {
7890
8475
  service: "butex-document",
7891
- routes: { ...DOCUMENT_WORKER_ROUTES },
8476
+ routes: { ...DOCUMENT_WORKER_ROUTES, ...BOOK_WORKER_ROUTES },
7892
8477
  build_commit: process.env.BUTEX_BUILD_COMMIT_SHA ?? process.env.RAILWAY_GIT_COMMIT_SHA ?? null,
7893
8478
  package_version: process.env.npm_package_version ?? null,
7894
8479
  provenance: "runtime_environment_unverified"
@@ -7930,7 +8515,7 @@ function executeDocumentWorkerRequest(input) {
7930
8515
  const document2 = resolveDocument2(request.document);
7931
8516
  return {
7932
8517
  ok: true,
7933
- latex: documentLatex2(document2, { twocolumn: true }),
8518
+ latex: request.mode === "book-content" ? documentContentLatex2(document2, request.book_context) : documentLatex2(document2, { twocolumn: true }),
7934
8519
  asset_ids: collectAssetIds(document2.blocks)
7935
8520
  };
7936
8521
  }
@@ -8063,6 +8648,8 @@ function traceId(request) {
8063
8648
  return typeof value === "string" ? value.slice(0, 128) : void 0;
8064
8649
  }
8065
8650
  function actionForPath(pathname) {
8651
+ const bookAction = bookActionForPath(pathname);
8652
+ if (bookAction) return bookAction;
8066
8653
  if (pathname === DOCUMENT_WORKER_ROUTES.diagnose_contract) {
8067
8654
  return "diagnose_contract";
8068
8655
  }