@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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/book/index.ts","../src/document/ids.ts","../src/document/articleMeta.ts","../src/document/citations.ts","../src/ast/commands/index.ts","../src/ast/arabic_ast.ts","../src/shared/math-document/mathObject.ts","../src/document/labels.ts","../src/document/inlineIdentity.ts","../src/document/inlineScanner.ts","../src/document/importJson.ts","../src/editor/atomicCommandsOperators.ts","../src/editor/characterFonts.ts","../src/editor/display/delimiter.ts","../src/editor/display/boxed.ts","../src/editor/display/frac.ts","../src/editor/display/sqrt.ts","../src/editor/display/overset.ts","../src/editor/display/underset.ts","../src/editor/display/accent.ts","../src/editor/display/env.ts","../src/diwani-font.ts","../src/editor/display/atomicCommand.ts","../src/editor/display/atomicCommandsOperators.ts","../src/editor/display/standardCommand.ts","../src/editor/styles.ts","../src/shared/math-document/normalizeCharImport.ts","../src/shared/math-document/mathEditorAdapter.ts","../src/document/keys.ts","../src/document/diff.ts","../src/document/introspection.ts","../src/book/utils.ts","../src/book/validation.ts","../src/book/jsonCommands.ts","../src/book/introspection.ts"],"sourcesContent":["export type * from './contracts.js';\nexport { BookContractError, normalizeBookSnapshot } from './validation.js';\nexport { applyBookCommand, parseBookCommand } from './jsonCommands.js';\nexport type { BookCommand } from './jsonCommands.js';\nexport {\n bookContextForUnit,\n bookOutline,\n getBookReferenceIndex,\n resolveBookSnapshot,\n validateBookSnapshot,\n} from './introspection.js';\nexport type {\n BookIssue, BookOutlineEntry, BookResolution, BookTarget,\n} from './introspection.js';\n","let nextId = 1;\nconst instanceId = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n\nexport function documentId(prefix: string): string {\n const id = `${prefix}_${instanceId}_${String(nextId)}`;\n nextId += 1;\n return id;\n}\n","import { formatDigits } from '../editor/digits.js';\nimport type { DigitFormId } from '../editor/types.js';\nimport type { ButexUiLocale } from '../uiLocale.js';\nimport type { DocumentHijriDate, DocumentMeta, HijriMonthId } from './types.js';\n\nexport const BUTEX_BASMALA_LINE1 = 'بِسْمِ ٱللَّٰهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ';\n\nexport const BUTEX_BASMALA_LINE2 = 'وَٱلصَّلَاةُ وَٱلسَّلَامُ عَلَىٰ رَسُولِ ٱللَّٰهِ';\n\nexport const BUTEX_BASMALA_SALAWAT = 'صَلَّى ٱللَّهُ عَلَيْهِ وَسَلَّمَ';\n\n/** Three-line basmala joined for UI / plain-text matchers. */\nexport const BUTEX_BASMALA = `${BUTEX_BASMALA_LINE1}\\n${BUTEX_BASMALA_LINE2}\\n${BUTEX_BASMALA_SALAWAT}`;\n\nexport const BUTEX_CLOSING_HAMDALA = 'الْحَمْدُ لِلَّهِ نَفَعَنَا بِعِلْمِهِ';\n\nfunction escapeButexTextArg(text: string): string {\n return text.replace(/\\\\/g, '\\\\textbackslash{}').replace(/[{}]/g, '\\\\$&');\n}\n\nfunction butexFontDisplayTex(macro: '\\\\butexdiwani' | '\\\\butexmaghribi', text: string): string {\n return `${macro}{${escapeButexTextArg(text)}}`;\n}\n\n/** Display-math body using BuTeX Diwani (for MathJax preview islands). */\nexport function butexDiwaniDisplayTex(text: string): string {\n return butexFontDisplayTex('\\\\butexdiwani', text);\n}\n\n/** Full display equation for XeLaTeX export. */\nexport function butexDiwaniDisplayLatex(text: string): string {\n return `\\\\[\\n${butexDiwaniDisplayTex(text)}\\n\\\\]`;\n}\n\n/** Display-math body using BuTeX Maghribi (for document chrome). */\nexport function butexMaghribiDisplayTex(text: string): string {\n return butexFontDisplayTex('\\\\butexmaghribi', text);\n}\n\n/** Full display equation using BuTeX Maghribi for XeLaTeX export. */\nexport function butexMaghribiDisplayLatex(text: string): string {\n return `\\\\[\\n${butexMaghribiDisplayTex(text)}\\n\\\\]`;\n}\n\nconst BASMALA_LINES = [BUTEX_BASMALA_LINE1, BUTEX_BASMALA_LINE2, BUTEX_BASMALA_SALAWAT] as const;\n\n/** Three-line Maghribi body for MathJax basmala islands. */\nexport function butexBasmalaDisplayTex(): string {\n return BASMALA_LINES.map((line) => butexMaghribiDisplayTex(line)).join(' \\\\\\\\ ');\n}\n\n/** Standalone display equation when there is no \\\\maketitle (title-less docs). */\nexport function butexBasmalaDisplayLatex(): string {\n return `\\\\[\\n\\\\begin{gathered}\\n${BASMALA_LINES.map((line) => butexMaghribiDisplayTex(line)).join(' \\\\\\\\\\n')}\\n\\\\end{gathered}\\n\\\\]`;\n}\n\n/**\n * Keep \\\\maketitle inside the current column when twocolumn is on.\n * Standard article otherwise does \\\\twocolumn[\\\\@maketitle] and spans both columns.\n * Call after titling so \\\\@maketitle still includes \\\\pretitle hooks.\n */\nexport function butexInColumnMaketitleHook(): string {\n return String.raw`\\makeatletter\n\\renewcommand{\\maketitle}{%\n \\par\n \\begingroup\n \\renewcommand\\thefootnote{\\@fnsymbol\\c@footnote}%\n \\def\\@makefnmark{\\rlap{\\@textsuperscript{\\normalfont\\@thefnmark}}}%\n \\long\\def\\@makefntext##1{\\parindent 1em\\noindent\n \\hb@xt@1.8em{\\hss\\@textsuperscript{\\normalfont\\@thefnmark}}##1}%\n \\@maketitle\n \\thispagestyle{plain}\\@thanks\n \\endgroup\n \\setcounter{footnote}{0}%\n \\global\\let\\thanks\\relax\n \\global\\let\\maketitle\\relax\n \\global\\let\\@maketitle\\relax\n \\global\\let\\@thanks\\@empty\n \\global\\let\\@author\\@empty\n \\global\\let\\@date\\@empty\n \\global\\let\\@title\\@empty\n \\global\\let\\title\\relax\n \\global\\let\\author\\relax\n \\global\\let\\date\\relax\n \\global\\let\\and\\relax\n}\n\\makeatother`;\n}\n\n/** Titling hooks so the basmala stays attached to the visible title. */\nexport function butexBasmalaTitlingPreamble(options: { twocolumn?: boolean } = {}): string {\n const lines = [\n '\\\\usepackage{titling}',\n '\\\\pretitle{%',\n ' \\\\begin{center}',\n ...BASMALA_LINES.map((line, index) => {\n const suffix = index < BASMALA_LINES.length - 1 ? '\\\\\\\\' : '';\n return ` ${butexMaghribiDisplayTex(line)}${suffix}`;\n }),\n ' \\\\par\\\\vspace{1.5em}',\n ' \\\\LARGE',\n '}',\n '\\\\posttitle{\\\\par\\\\end{center}}',\n ];\n if (options.twocolumn) {\n lines.push(butexInColumnMaketitleHook());\n }\n return lines.join('\\n');\n}\nexport const HIJRI_YEAR_MIN = 1400;\nexport const HIJRI_YEAR_MAX = 1500;\n\nexport const HIJRI_MONTH_IDS: HijriMonthId[] = [\n 'محرم',\n 'صفر',\n 'ربيع الأول',\n 'ربيع الآخر',\n 'جمادى الأولى',\n 'جمادى الآخرة',\n 'رجب',\n 'شعبان',\n 'رمضان',\n 'شوال',\n 'ذو القعدة',\n 'ذو الحجة',\n];\n\nconst HIJRI_MONTH_LABELS_EN: Record<HijriMonthId, string> = {\n محرم: 'Muharram',\n صفر: 'Safar',\n 'ربيع الأول': 'Rabiʻ I',\n 'ربيع الآخر': 'Rabiʻ II',\n 'جمادى الأولى': 'Jumada I',\n 'جمادى الآخرة': 'Jumada II',\n رجب: 'Rajab',\n شعبان: 'Shaʻban',\n رمضان: 'Ramadan',\n شوال: 'Shawwal',\n 'ذو القعدة': 'Dhul Qaʻdah',\n 'ذو الحجة': 'Dhul Hijjah',\n};\n\n/** Legacy Latin month ids from earlier drafts — accepted on import only. */\nconst LEGACY_LATIN_MONTH: Record<string, HijriMonthId> = {\n muharram: 'محرم',\n safar: 'صفر',\n rabiAwwal: 'ربيع الأول',\n rabiThani: 'ربيع الآخر',\n jumadaAwwal: 'جمادى الأولى',\n jumadaThani: 'جمادى الآخرة',\n rajab: 'رجب',\n shaban: 'شعبان',\n ramadan: 'رمضان',\n shawwal: 'شوال',\n dhulQadah: 'ذو القعدة',\n dhulHijjah: 'ذو الحجة',\n};\n\nexport const DEFAULT_HIJRI_DATE: DocumentHijriDate = {\n day: 1,\n month: 'محرم',\n year: 1448,\n};\n\nexport function hijriMonthLabel(month: HijriMonthId, locale: ButexUiLocale = 'ar'): string {\n return locale === 'en' ? HIJRI_MONTH_LABELS_EN[month] : month;\n}\n\nexport function emptyDocumentMeta(): DocumentMeta {\n return {\n title: '',\n authors: '',\n date: { ...DEFAULT_HIJRI_DATE },\n abstract: '',\n };\n}\n\nfunction clampInt(value: number, min: number, max: number): number {\n if (!Number.isFinite(value)) {\n return min;\n }\n return Math.min(max, Math.max(min, Math.trunc(value)));\n}\n\nfunction isHijriMonthId(value: unknown): value is HijriMonthId {\n return typeof value === 'string' && (HIJRI_MONTH_IDS as string[]).includes(value);\n}\n\nfunction resolveHijriMonthId(value: unknown): HijriMonthId {\n if (isHijriMonthId(value)) {\n return value;\n }\n if (typeof value === 'string' && value in LEGACY_LATIN_MONTH) {\n return LEGACY_LATIN_MONTH[value]!;\n }\n return DEFAULT_HIJRI_DATE.month;\n}\n\nexport function normalizeDocumentHijriDate(value: unknown): DocumentHijriDate {\n if (typeof value !== 'object' || value === null) {\n return { ...DEFAULT_HIJRI_DATE };\n }\n const raw = value as Record<string, unknown>;\n const day = clampInt(typeof raw.day === 'number' ? raw.day : Number(raw.day), 1, 30);\n const year = clampInt(typeof raw.year === 'number' ? raw.year : Number(raw.year), HIJRI_YEAR_MIN, HIJRI_YEAR_MAX);\n const month = resolveHijriMonthId(raw.month);\n return { day, month, year };\n}\n\nexport function normalizeDocumentMeta(value: unknown): DocumentMeta {\n if (typeof value !== 'object' || value === null) {\n return emptyDocumentMeta();\n }\n const raw = value as Record<string, unknown>;\n return {\n title: typeof raw.title === 'string' ? raw.title : '',\n authors: typeof raw.authors === 'string' ? raw.authors : '',\n date: normalizeDocumentHijriDate(raw.date),\n abstract: typeof raw.abstract === 'string' ? raw.abstract : '',\n };\n}\n\nexport type DocumentMetaProp = Partial<Omit<DocumentMeta, 'date'>> & {\n date?: Partial<DocumentHijriDate>;\n};\n\n/** Prop fills gaps; JSON wins only when the key is present on the JSON object. */\nexport function mergeDocumentMeta(fromJson: unknown, fromProp?: DocumentMetaProp): DocumentMeta {\n const fromPropMeta: DocumentMeta = {\n title: typeof fromProp?.title === 'string' ? fromProp.title : '',\n authors: typeof fromProp?.authors === 'string' ? fromProp.authors : '',\n abstract: typeof fromProp?.abstract === 'string' ? fromProp.abstract : '',\n date: fromProp?.date\n ? normalizeDocumentHijriDate({ ...DEFAULT_HIJRI_DATE, ...fromProp.date })\n : { ...DEFAULT_HIJRI_DATE },\n };\n if (typeof fromJson !== 'object' || fromJson === null) {\n return fromPropMeta;\n }\n const json = fromJson as Record<string, unknown>;\n return {\n title: 'title' in json && typeof json.title === 'string' ? json.title : fromPropMeta.title,\n authors: 'authors' in json && typeof json.authors === 'string' ? json.authors : fromPropMeta.authors,\n abstract: 'abstract' in json && typeof json.abstract === 'string' ? json.abstract : fromPropMeta.abstract,\n date: 'date' in json ? normalizeDocumentHijriDate(json.date) : fromPropMeta.date,\n };\n}\n\n/** For live DocumentNode meta: prop fills empty title/authors/abstract; date patch merges. */\nexport function fillDocumentMetaGaps(current: DocumentMeta, fromProp?: DocumentMetaProp): DocumentMeta {\n if (!fromProp) {\n return cloneDocumentMeta(current);\n }\n return {\n title: current.title.trim().length > 0 ? current.title : typeof fromProp.title === 'string' ? fromProp.title : current.title,\n authors:\n current.authors.trim().length > 0\n ? current.authors\n : typeof fromProp.authors === 'string'\n ? fromProp.authors\n : current.authors,\n abstract:\n current.abstract.trim().length > 0\n ? current.abstract\n : typeof fromProp.abstract === 'string'\n ? fromProp.abstract\n : current.abstract,\n date: fromProp.date\n ? normalizeDocumentHijriDate({ ...current.date, ...fromProp.date })\n : { ...current.date },\n };\n}\n\nexport function documentHasMaketitle(meta: DocumentMeta): boolean {\n return meta.title.trim().length > 0 || meta.authors.trim().length > 0;\n}\n\nexport function documentHasAbstract(meta: DocumentMeta): boolean {\n return meta.abstract.trim().length > 0;\n}\n\nexport function documentHasTitleStack(meta: DocumentMeta): boolean {\n return documentHasMaketitle(meta) || documentHasAbstract(meta);\n}\n\nexport type FormatHijriDateOptions = {\n locale?: ButexUiLocale;\n digitForm?: DigitFormId;\n};\n\nexport function formatHijriDate(date: DocumentHijriDate, options: FormatHijriDateOptions | ButexUiLocale = 'ar'): string {\n const opts: FormatHijriDateOptions = typeof options === 'string' ? { locale: options } : options;\n const locale = opts.locale ?? 'ar';\n const digitForm: DigitFormId =\n opts.digitForm ?? (locale === 'en' ? 'western' : 'arabicIndic');\n const month = hijriMonthLabel(date.month, locale);\n const day = formatDigits(String(date.day), digitForm);\n const year = formatDigits(String(date.year), digitForm);\n if (locale === 'en') {\n return `${day} ${month} ${year} AH`;\n }\n return `${day} ${month} ${year}هـ`;\n}\n\nexport function cloneDocumentMeta(meta: DocumentMeta): DocumentMeta {\n return {\n title: meta.title,\n authors: meta.authors,\n date: { ...meta.date },\n abstract: meta.abstract,\n };\n}\n","import { formatDigits } from '../editor/digits.js';\nimport type { DigitFormId } from '../editor/types.js';\nimport type { FormatCiteLabelOptions, Reference2, Reference2Json, ReferenceFieldSeparator } from './types.js';\nimport { documentId } from './ids.js';\n\nexport const DEFAULT_REFERENCE_FIELD_SEPARATOR: ReferenceFieldSeparator = '،';\n\nexport function normalizeReferenceFieldSeparator(value: unknown): ReferenceFieldSeparator {\n return value === ',' ? ',' : DEFAULT_REFERENCE_FIELD_SEPARATOR;\n}\n\nexport function referenceNumberMap(references: Array<Pick<Reference2, 'key'>>): Map<string, number> {\n const map = new Map<string, number>();\n references.forEach((reference, index) => {\n if (!map.has(reference.key)) {\n map.set(reference.key, index + 1);\n }\n });\n return map;\n}\n\nexport function resolveCiteNumbers(keys: string[], references: Array<Pick<Reference2, 'key'>>): Array<number | null> {\n const map = referenceNumberMap(references);\n return keys.map((key) => map.get(key) ?? null);\n}\n\nexport function formatCiteLabel(\n keys: string[],\n references: Array<Pick<Reference2, 'key'>>,\n options: FormatCiteLabelOptions = {},\n): string {\n const documentDirection = options.documentDirection ?? 'rtl';\n const digitForm: DigitFormId = options.digitForm ?? (documentDirection === 'rtl' ? 'arabicIndic' : 'western');\n const numbers = resolveCiteNumbers(keys, references).map((value) => (value === null ? '?' : String(value)));\n const display = documentDirection === 'rtl' ? [...numbers].reverse() : numbers;\n const separator = documentDirection === 'rtl' ? '،' : ', ';\n const body = display.map((part) => formatDigits(part, digitForm)).join(separator);\n return `[${body}]`;\n}\n\nexport function formatBibliographyNumber(index: number, options: FormatCiteLabelOptions = {}): string {\n const documentDirection = options.documentDirection ?? 'rtl';\n const digitForm: DigitFormId = options.digitForm ?? (documentDirection === 'rtl' ? 'arabicIndic' : 'western');\n return formatDigits(String(index), digitForm);\n}\n\nexport function parseCiteKeys(source: string): string[] {\n const match = /^\\\\cite\\{([^}]*)\\}$/.exec(source.trim());\n if (!match) {\n return [];\n }\n return (match[1] ?? '')\n .split(',')\n .map((key) => key.trim())\n .filter((key) => key.length > 0);\n}\n\nexport function citeTokenLatex(keys: string[]): string {\n return `\\\\cite{${keys.join(',')}}`;\n}\n\nexport function referenceFromJson(json: Reference2Json): Reference2 {\n return {\n id: documentId('ref'),\n key: json.key,\n authors: typeof json.authors === 'string' ? json.authors : '',\n title: typeof json.title === 'string' ? json.title : '',\n year: typeof json.year === 'string' ? json.year : '',\n url: typeof json.url === 'string' ? json.url : '',\n venue: typeof json.venue === 'string' ? json.venue : '',\n fieldSeparator: normalizeReferenceFieldSeparator(json.field_separator),\n };\n}\n\nexport function createEmptyReference(partial: Partial<Reference2Json> = {}): Reference2 {\n return referenceFromJson({\n key: partial.key ?? `ref${String(Date.now()).slice(-4)}`,\n authors: partial.authors,\n title: partial.title,\n year: partial.year,\n url: partial.url,\n venue: partial.venue,\n field_separator: partial.field_separator,\n });\n}\n\n/** Joined authors/title/venue/year for preview and export (no \\\\bibitem wrapper). */\nexport function bibliographyEntryBody(\n reference: Pick<Reference2, 'authors' | 'title' | 'venue' | 'year' | 'fieldSeparator'>,\n separator: ReferenceFieldSeparator = reference.fieldSeparator,\n options: { digitForm?: DigitFormId } = {},\n): string {\n const year =\n options.digitForm !== undefined ? formatDigits(reference.year, options.digitForm) : reference.year;\n const parts = [reference.authors, reference.title, reference.venue, year].filter((part) => part.trim().length > 0);\n return parts.join(`${separator} `);\n}\n\nexport function bibliographyEntryLatex(reference: Reference2): string {\n const body = bibliographyEntryBody(reference);\n const url = reference.url.trim().length > 0 ? ` \\\\url{${reference.url}}` : '';\n return `\\\\bibitem{${reference.key}} ${body}${url}`.trim();\n}\n\n/**\n * Build an href for a bibliography URL. Values without a scheme become https://…\n * so the browser does not resolve them against the editor origin (e.g. localhost).\n * Leaves http(s)/mailto/ftp and other schemed URLs unchanged. Empty → ''.\n */\nexport function absoluteHttpHref(url: string): string {\n const trimmed = url.trim();\n if (trimmed.length === 0) {\n return '';\n }\n if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {\n return trimmed;\n }\n if (trimmed.startsWith('//')) {\n return `https:${trimmed}`;\n }\n return `https://${trimmed}`;\n}\n","import type { ChainNode } from '../arabic_ast.js';\n\ntype CommandRenderContext = {\n name: string;\n optionalArgs: ChainNode[];\n mandatoryArgs: ChainNode[];\n renderChain: (chain: ChainNode) => string;\n};\n\nexport function renderCommandCore(context: CommandRenderContext): string {\n const optional = context.optionalArgs.map((arg) => `[${context.renderChain(arg)}]`).join('');\n const mandatory = context.mandatoryArgs.map((arg) => `{${context.renderChain(arg)}}`).join('');\n return context.name + optional + mandatory;\n}\n","import { renderCommandCore } from './commands/index.js';\n\nexport type ArabicNodeJson = {\n node_type: string;\n expr?: string;\n name?: string;\n superscript?: ChainJson | null;\n subscript?: ChainJson | null;\n left_delim_expr?: string;\n right_delim_expr?: string;\n inner_expr?: ChainJson;\n optional_args?: ChainJson[];\n mandatory_args?: ChainJson[];\n opening?: string;\n closing?: string;\n lines?: ChainJson[];\n source_latex?: string;\n};\n\nexport type ChainJson = {\n node_type: 'ChainClass';\n chain: ArabicNodeJson[];\n};\n\nexport class State {\n // Empty for now, like the Python State placeholder used by BaseNode.\n}\n\nexport class BaseAstNode {\n state: State;\n superscript: ChainNode | null;\n subscript: ChainNode | null;\n nodeType: string;\n sourceLatex: string | null;\n\n constructor(state: State | null = null) {\n if (state === null) {\n state = new State();\n }\n\n this.state = state;\n this.superscript = null;\n this.subscript = null;\n this.nodeType = this.constructor.name;\n this.sourceLatex = null;\n }\n\n latex(): string {\n throw new Error('NotImplementedError');\n }\n\n arabicLatex(): string {\n throw new Error('NotImplementedError');\n }\n\n toArabicLatex(): string {\n return this.arabicLatex();\n }\n\n /** Latin-style scripts: `^{...}` and `_{...}` for english_json rendering. */\n latexScripts(): string {\n let s = '';\n\n if (this.superscript !== null) {\n s += '^{' + this.superscript.latex() + '}';\n }\n\n if (this.subscript !== null) {\n s += '_{' + this.subscript.latex() + '}';\n }\n\n return s;\n }\n\n /**\n * Arabic scripts use \\\\prescript{sup}{sub}{content} (matches reference Python output).\n * Call with rendered strings for sup/sub chains (may be empty strings).\n */\n arabicLatexScripts(sup: string, sub: string, content: string): string {\n if (sup !== '' || sub !== '') {\n return '\\\\prescript{' + sup + '}{' + sub + '}{' + content + '}';\n }\n return content;\n }\n}\n\nexport class ChainNode {\n chain: BaseAstNode[];\n\n constructor(chain: BaseAstNode[] = []) {\n this.chain = chain;\n }\n\n latex(): string {\n return this.chain.map((node) => node.latex()).join(' ');\n }\n toEnglishLatex(): string {\n return this.chain.map((node) => node.latex()).join(' ');\n }\n /** RTL: reverse order relative to Latin chain (see test/ref_tests.txt). */\n arabicLatex(): string {\n const reversed = this.chain.slice().reverse();\n return reversed.map((node) => node.arabicLatex()).join(' ');\n }\n\n toArabicLatex(): string {\n return this.arabicLatex();\n }\n}\n\nexport class NumberNode extends BaseAstNode {\n expr: string;\n\n constructor(expr: string, state: State | null = null) {\n super(state);\n this.nodeType = 'NumberObject';\n this.expr = expr;\n }\n\n latex(): string {\n return this.expr + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n return this.arabicLatexScripts(sup, sub, this.expr);\n }\n}\n\nexport class CharNode extends BaseAstNode {\n expr: string;\n\n constructor(expr: string, state: State | null = null) {\n super(state);\n this.nodeType = 'CharObject';\n this.expr = expr;\n }\n\n latex(): string {\n return this.expr + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n return this.arabicLatexScripts(sup, sub, this.expr);\n }\n}\n\n/**\n * Operator leaf: value comes from JSON as-is (English or Arabic side already chosen by the service).\n * Scripts are not appended (Python parity).\n */\nexport class OperatorNode extends BaseAstNode {\n expr: string;\n\n constructor(expr: string, state: State | null = null) {\n super(state);\n this.nodeType = 'OperatorObject';\n this.expr = expr;\n }\n\n latex(): string {\n return this.expr;\n }\n\n arabicLatex(): string {\n return this.expr;\n }\n}\n\nexport class DelimiterNode extends BaseAstNode {\n leftDelimExpr: string;\n innerExpr: ChainNode;\n rightDelimExpr: string;\n\n constructor(leftDelimExpr: string, innerExpr: ChainNode, rightDelimExpr: string, state: State | null = null) {\n super(state);\n this.nodeType = 'DelimiterObject';\n this.leftDelimExpr = leftDelimExpr;\n this.innerExpr = innerExpr;\n this.rightDelimExpr = rightDelimExpr;\n }\n\n latex(): string {\n return this.leftDelimExpr + ' ' + this.innerExpr.latex() + this.rightDelimExpr + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n const content = this.leftDelimExpr + this.innerExpr.arabicLatex() + this.rightDelimExpr;\n return this.arabicLatexScripts(sup, sub, content);\n }\n}\n\nexport class CommandNode extends BaseAstNode {\n name: string;\n optionalArgs: ChainNode[];\n mandatoryArgs: ChainNode[];\n\n constructor(\n name: string,\n optionalArgs: ChainNode[] = [],\n mandatoryArgs: ChainNode[] = [],\n state: State | null = null\n ) {\n super(state);\n this.nodeType = 'CommandObject';\n this.name = name;\n this.optionalArgs = optionalArgs;\n this.mandatoryArgs = mandatoryArgs;\n }\n\n latex(): string {\n const content = renderCommandCore({\n name: this.name,\n optionalArgs: this.optionalArgs,\n mandatoryArgs: this.mandatoryArgs,\n renderChain: (chain) => chain.latex(),\n });\n return content + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n const arabicName =\n this.name === '\\\\sqrt' || this.name === '\\\\arabsqrt' ? '\\\\arsqrt' : this.name;\n const content = renderCommandCore({\n name: arabicName,\n optionalArgs: this.optionalArgs,\n mandatoryArgs: this.mandatoryArgs,\n renderChain: (chain) => chain.arabicLatex(),\n });\n return this.arabicLatexScripts(sup, sub, content);\n }\n}\n\nexport class EnvNode extends BaseAstNode {\n opening: string;\n lines: ChainNode[];\n closing: string;\n\n constructor(opening: string, lines: ChainNode[] = [], closing: string, state: State | null = null) {\n super(state);\n this.nodeType = 'EnvObject';\n this.opening = opening;\n this.lines = lines;\n this.closing = closing;\n }\n\n latex(): string {\n if (this.lines.length === 0) {\n return this.opening + this.closing + this.latexScripts();\n }\n\n const formattedLines = this.lines.map((line) => ` ${line.latex()}`);\n const content = formattedLines.join(' \\\\\\\\' + '\\n');\n return `${this.opening}\\n${content}\\n${this.closing}` + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n\n if (this.lines.length === 0) {\n return this.arabicLatexScripts(sup, sub, this.opening + this.closing);\n }\n\n const formattedLines = this.lines.map((line) => ` ${line.arabicLatex()}`);\n const content = formattedLines.join(' \\\\\\\\' + '\\n');\n // Only the Arabic presentation differs: stored EnvObject stays canonical cases.\n const fullContent = this.opening === '\\\\begin{cases}' && this.closing === '\\\\end{cases}'\n ? `\\\\left.\\\\begin{array}{rl}\\n${content}\\n\\\\end{array}\\\\right\\\\}`\n : `${this.opening}\\n${content}\\n${this.closing}`;\n return this.arabicLatexScripts(sup, sub, fullContent);\n }\n}\n\ntype ParseMode = 'english' | 'arabic';\n\nfunction parseScripts(node: BaseAstNode, json: ArabicNodeJson, mode: ParseMode): void {\n node.sourceLatex = typeof json.source_latex === 'string' && json.source_latex.length > 0\n ? json.source_latex\n : null;\n if (json.superscript) {\n node.superscript = parseChain(json.superscript, mode);\n }\n\n if (json.subscript) {\n node.subscript = parseChain(json.subscript, mode);\n }\n}\n\nfunction parseNode(json: ArabicNodeJson, mode: ParseMode): BaseAstNode {\n if (json.node_type === 'DelimiterObject') {\n const node = parseDelimiter(json, mode);\n parseScripts(node, json, mode);\n return node;\n }\n\n if (json.node_type === 'OperatorObject') {\n if (typeof json.expr !== 'string') {\n throw new Error('OperatorObject requires string expr');\n }\n const node = new OperatorNode(json.expr);\n parseScripts(node, json, mode);\n return node;\n }\n\n if (json.node_type === 'CommandObject') {\n const node = parseCommand(json, mode);\n parseScripts(node, json, mode);\n return node;\n }\n\n if (json.node_type === 'EnvObject') {\n const node = parseEnv(json, mode);\n parseScripts(node, json, mode);\n return node;\n }\n\n if (typeof json.expr !== 'string') {\n throw new Error(`${json.node_type} requires string expr`);\n }\n\n let node: BaseAstNode;\n\n if (json.node_type === 'NumberObject') {\n node = new NumberNode(json.expr);\n } else if (json.node_type === 'CharObject') {\n node = new CharNode(json.expr);\n } else {\n throw new Error(`Unsupported node_type: ${json.node_type}`);\n }\n\n parseScripts(node, json, mode);\n return node;\n}\n\nfunction parseDelimiter(json: ArabicNodeJson, mode: ParseMode): DelimiterNode {\n if (typeof json.left_delim_expr !== 'string') {\n throw new Error('DelimiterObject requires string left_delim_expr');\n }\n\n if (!json.inner_expr || json.inner_expr.node_type !== 'ChainClass') {\n throw new Error('DelimiterObject requires ChainClass inner_expr');\n }\n\n if (typeof json.right_delim_expr !== 'string') {\n throw new Error('DelimiterObject requires string right_delim_expr');\n }\n\n const innerExpr = parseChain(json.inner_expr, mode);\n return new DelimiterNode(json.left_delim_expr, innerExpr, json.right_delim_expr);\n}\n\nfunction parseCommand(json: ArabicNodeJson, mode: ParseMode): CommandNode {\n if (typeof json.name !== 'string') {\n throw new Error('CommandObject requires string name');\n }\n\n const optionalJson = Array.isArray(json.optional_args) ? json.optional_args : [];\n const mandatoryJson = Array.isArray(json.mandatory_args) ? json.mandatory_args : [];\n const optionalArgs = optionalJson.map((arg) => parseChain(arg, mode));\n const mandatoryArgs = mandatoryJson.map((arg) => parseChain(arg, mode));\n\n return new CommandNode(json.name, optionalArgs, mandatoryArgs);\n}\n\nfunction parseEnv(json: ArabicNodeJson, mode: ParseMode): EnvNode {\n if (typeof json.opening !== 'string') {\n throw new Error('EnvObject requires string opening');\n }\n\n if (typeof json.closing !== 'string') {\n throw new Error('EnvObject requires string closing');\n }\n\n if (!Array.isArray(json.lines)) {\n throw new Error('EnvObject requires lines array');\n }\n\n const lines = json.lines.map((line) => parseChain(line, mode));\n return new EnvNode(json.opening, lines, json.closing);\n}\n\nfunction parseChain(json: ChainJson, mode: ParseMode): ChainNode {\n if (json.node_type !== 'ChainClass') {\n throw new Error(`Expected ChainClass, got: ${json.node_type}`);\n }\n\n const nodes = json.chain.map((childJson) => parseNode(childJson, mode));\n return new ChainNode(nodes);\n}\n\n/** Import AST from Python english_dict JSON (Latin expr fields). */\nexport function fromEnglishJson(json: ChainJson | ArabicNodeJson): ChainNode | BaseAstNode {\n if (json.node_type === 'ChainClass') {\n return parseChain(json as ChainJson, 'english');\n }\n return parseNode(json, 'english');\n}\n\n/** Import AST from Python arabic_dict JSON (Arabic expr fields). Same shape as English; values differ. */\nexport function fromArabicJson(json: ChainJson | ArabicNodeJson): ChainNode | BaseAstNode {\n if (json.node_type === 'ChainClass') {\n return parseChain(json as ChainJson, 'arabic');\n }\n return parseNode(json, 'arabic');\n}\n","import {\n BaseAstNode,\n ChainNode,\n CharNode,\n CommandNode,\n DelimiterNode,\n EnvNode,\n NumberNode,\n OperatorNode,\n fromArabicJson,\n fromEnglishJson,\n type ArabicNodeJson,\n type ChainJson,\n} from '../../ast/arabic_ast.js';\nimport type { DocumentParseMode, MathNode, MathObjectJson } from './types.js';\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isMathObjectJson(value: unknown): value is MathObjectJson {\n return isObject(value) && value.node_type === 'MathObject';\n}\n\nfunction assertChainNode(value: unknown): ChainNode {\n if (!(value instanceof ChainNode)) {\n throw new Error('MathObject lines must parse to ChainNode');\n }\n return value;\n}\n\nexport function fromMathObjectJson(json: unknown, mode: DocumentParseMode = 'english'): MathNode {\n if (!isMathObjectJson(json)) {\n throw new Error('MathObject requires node_type \"MathObject\"');\n }\n\n if (typeof json.math_mode !== 'string') {\n throw new Error('MathObject requires string math_mode');\n }\n\n if (typeof json.closing !== 'string') {\n throw new Error('MathObject requires string closing');\n }\n\n if (!Array.isArray(json.lines) || json.lines.length === 0) {\n throw new Error('MathObject requires non-empty lines array');\n }\n\n const parseChain = mode === 'arabic' ? fromArabicJson : fromEnglishJson;\n const lines = json.lines.map((line) => assertChainNode(parseChain(line)));\n\n return {\n nodeType: 'MathObject',\n mathMode: json.math_mode,\n lines,\n closing: json.closing,\n };\n}\n\nfunction scriptsToJson(\n node: BaseAstNode,\n path: string,\n): Pick<ArabicNodeJson, 'superscript' | 'subscript' | 'source_latex'> {\n return {\n ...(node.superscript ? { superscript: chainToJson(node.superscript, `${path}.superscript`) } : {}),\n ...(node.subscript ? { subscript: chainToJson(node.subscript, `${path}.subscript`) } : {}),\n ...(node.sourceLatex ? { source_latex: node.sourceLatex } : {}),\n };\n}\n\nfunction nodeToJson(node: BaseAstNode, path: string): ArabicNodeJson {\n const scripts = scriptsToJson(node, path);\n if (node instanceof CharNode || node instanceof NumberNode || node instanceof OperatorNode) {\n return { node_type: node.nodeType, expr: node.expr, ...scripts };\n }\n if (node instanceof DelimiterNode) {\n return {\n node_type: 'DelimiterObject',\n left_delim_expr: node.leftDelimExpr,\n inner_expr: chainToJson(node.innerExpr, `${path}.inner_expr`),\n right_delim_expr: node.rightDelimExpr,\n ...scripts,\n };\n }\n if (node instanceof CommandNode) {\n return {\n node_type: 'CommandObject',\n name: node.name,\n optional_args: node.optionalArgs.map((arg, index) => chainToJson(arg, `${path}.optional_args[${String(index)}]`)),\n mandatory_args: node.mandatoryArgs.map((arg, index) => chainToJson(arg, `${path}.mandatory_args[${String(index)}]`)),\n ...scripts,\n };\n }\n if (node instanceof EnvNode) {\n return {\n node_type: 'EnvObject',\n opening: node.opening,\n lines: node.lines.map((line, index) => chainToJson(line, `${path}.lines[${String(index)}]`)),\n closing: node.closing,\n ...scripts,\n };\n }\n throw new Error(`Unsupported runtime math node at ${path}: ${node.nodeType}`);\n}\n\nfunction chainToJson(chain: ChainNode, path: string): ChainJson {\n if (!(chain instanceof ChainNode)) {\n throw new Error(`Expected live ChainNode at ${path}`);\n }\n return {\n node_type: 'ChainClass',\n chain: chain.chain.map((node, index) => nodeToJson(node, `${path}.chain[${String(index)}]`)),\n };\n}\n\nexport function toMathObjectJson(math: MathNode): MathObjectJson {\n if (math.nodeType !== 'MathObject' || !Array.isArray(math.lines) || math.lines.length === 0) {\n throw new Error('Cannot serialize invalid runtime MathObject');\n }\n return {\n node_type: 'MathObject',\n math_mode: math.mathMode,\n lines: math.lines.map((line, index) => chainToJson(line, `$.lines[${String(index)}]`)),\n closing: math.closing,\n };\n}\n\nexport function renderMathNodeLatex(math: MathNode): string {\n const lines = math.lines.map((line) => line.arabicLatex());\n\n if (math.mathMode === '$' || math.mathMode === '\\\\(') {\n return math.mathMode + lines.join(' ') + math.closing;\n }\n\n if (math.mathMode === '$$' || math.mathMode === '\\\\[') {\n if (lines.length === 1) {\n return math.mathMode + '\\n' + lines[0] + '\\n' + math.closing;\n }\n return math.mathMode + '\\n' + lines.map((line) => ` ${line}`).join(' \\\\\\\\\\n') + '\\n' + math.closing;\n }\n\n if (lines.length === 1) {\n return `${math.mathMode}\\n ${lines[0]}\\n${math.closing}`;\n }\n\n return `${math.mathMode}\\n${lines.map((line) => ` ${line}`).join(' \\\\\\\\\\n')}\\n${math.closing}`;\n}\n\nexport function isDisplayMathNode(math: MathNode): boolean {\n return math.mathMode === '$$' || math.mathMode === '\\\\[' || math.mathMode.startsWith('\\\\begin{');\n}\n","import { formatDigits } from '../editor/digits.js';\nimport type { DigitFormId } from '../editor/types.js';\nimport type { ButexUiLocale } from '../uiLocale.js';\nimport { formatBibliographyNumber } from './citations.js';\nimport { documentId } from './ids.js';\nimport type {\n DocumentBlock,\n DocumentDirection,\n DocumentNode,\n FormatCiteLabelOptions,\n ImageBlock2,\n InlineField2,\n MathToken2,\n TableBlock2,\n} from './types.js';\n\nexport type DocumentLabelKind = 'fig' | 'tab' | 'eq';\n\nexport type DocumentLabelEntry = {\n key: string;\n kind: DocumentLabelKind;\n caption: string;\n /** Block id for fig/tab, or math token id for eq. */\n ownerId: string;\n number: number;\n};\n\nexport type FloatMetaPatch = {\n centered?: boolean;\n captionEnabled?: boolean;\n caption?: string;\n labelEnabled?: boolean;\n label?: string;\n};\n\nexport function defaultFloatMeta(): {\n centered: true;\n captionEnabled: false;\n caption: string;\n captionField: InlineField2;\n labelEnabled: false;\n label: string;\n} {\n return {\n centered: true,\n captionEnabled: false,\n caption: '',\n captionField: {\n id: documentId('field'),\n tokens: [{ id: documentId('text'), kind: 'text', text: '' }],\n },\n labelEnabled: false,\n label: '',\n };\n}\n\nexport function parseFloatMetaFromJson(json: {\n caption?: string;\n label?: string;\n caption_enabled?: boolean;\n label_enabled?: boolean;\n centered?: boolean;\n}): {\n centered: boolean;\n captionEnabled: boolean;\n caption: string;\n labelEnabled: boolean;\n label: string;\n} {\n const caption = typeof json.caption === 'string' ? json.caption : '';\n const label = typeof json.label === 'string' ? json.label : '';\n return {\n centered: json.centered !== false,\n captionEnabled: json.caption_enabled === true || (typeof json.caption_enabled !== 'boolean' && caption.length > 0),\n caption,\n labelEnabled: json.label_enabled === true || (typeof json.label_enabled !== 'boolean' && label.trim().length > 0),\n label,\n };\n}\n\nexport function parseRefKeys(source: string): { keys: string[]; refCommand: 'ref' | 'eqref' } {\n const eqref = /^\\\\eqref\\{([^}]*)\\}$/.exec(source.trim());\n if (eqref) {\n return {\n refCommand: 'eqref',\n keys: (eqref[1] ?? '')\n .split(',')\n .map((key) => key.trim())\n .filter((key) => key.length > 0),\n };\n }\n const ref = /^\\\\ref\\{([^}]*)\\}$/.exec(source.trim());\n if (ref) {\n return {\n refCommand: 'ref',\n keys: (ref[1] ?? '')\n .split(',')\n .map((key) => key.trim())\n .filter((key) => key.length > 0),\n };\n }\n return { keys: [], refCommand: 'ref' };\n}\n\nexport function refTokenLatex(keys: string[], refCommand: 'ref' | 'eqref'): string {\n const command = refCommand === 'eqref' ? '\\\\eqref' : '\\\\ref';\n return `${command}{${keys.join(',')}}`;\n}\n\n/** Deterministic, reversible, TeX-safe reference key from a persisted target ID. */\nfunction implicitObjectKey(kind: string, ownerId: string, unitId?: string): string {\n const hex = (value: string): string =>\n Array.from(new TextEncoder().encode(value), (byte) => byte.toString(16).padStart(2, '0')).join('');\n const scope = unitId === undefined ? 'a' : 'u' + hex(unitId);\n return kind + ':butex-auto-' + scope + '-' + hex(ownerId);\n}\n\nexport function implicitReferenceKey(kind: DocumentLabelKind, ownerId: string, unitId?: string): string {\n return implicitObjectKey(kind, ownerId, unitId);\n}\n\nexport function implicitHeadingReferenceKey(kind: 'section' | 'subsection' | 'subsubsection', ownerId: string, unitId: string): string {\n return implicitObjectKey(kind, ownerId, unitId);\n}\n\n/** Single-number display forms supported by the article reference model. */\nexport function supportsSingleEquationNumbering(token: MathToken2): boolean {\n return token.display && (\n token.opening === '\\\\[' || token.opening === String.fromCharCode(36, 36) ||\n token.opening === '\\\\begin{equation}' || token.opening === '\\\\begin{equation*}'\n );\n}\n\n/** Explicit numbering wins; legacy labeled/equation-environment math stays numbered. */\nexport function isNumberedEquation(token: MathToken2): boolean {\n if (!supportsSingleEquationNumbering(token)) return false;\n if (typeof token.numbered === 'boolean') return token.numbered;\n return token.opening === '\\\\begin{equation}' ||\n (Boolean(token.labelEnabled) && Boolean(token.label?.trim()));\n}\n\nexport function isNumberedFloat(block: ImageBlock2 | TableBlock2): boolean {\n return (block.captionEnabled && block.caption.trim().length > 0) ||\n (block.labelEnabled && block.label.trim().length > 0);\n}\n\nexport type DocumentReferenceTarget = {\n key: string;\n kind: DocumentLabelKind;\n caption: string;\n ownerId: string;\n /** null means a displayed equation that has not been numbered. */\n number: number | null;\n manualKey?: string;\n};\n\n/** Projection of object identities and ordinals; never mutates document state. */\nexport function collectDocumentReferenceTargets(document: DocumentNode): DocumentReferenceTarget[] {\n const targets: DocumentReferenceTarget[] = [];\n const counters: Record<DocumentLabelKind, number> = { fig: 0, tab: 0, eq: 0 };\n function append(kind: DocumentLabelKind, ownerId: string, caption: string, numbered: boolean, manualKey = ''): void {\n if (numbered) counters[kind] += 1;\n targets.push({\n key: implicitReferenceKey(kind, ownerId),\n kind, ownerId, caption,\n number: numbered ? counters[kind] : null,\n ...(manualKey.trim() ? { manualKey: manualKey.trim() } : {}),\n });\n }\n function visitField(field: InlineField2): void {\n for (const token of field.tokens) {\n if (token.kind === 'math' && supportsSingleEquationNumbering(token)) {\n append('eq', token.id, '', isNumberedEquation(token), token.labelEnabled ? token.label ?? '' : '');\n }\n }\n }\n function walk(blocks: DocumentBlock[]): void {\n for (const block of blocks) {\n if (block.kind === 'image' || block.kind === 'table') {\n append(\n block.kind === 'image' ? 'fig' : 'tab',\n block.id, block.captionEnabled ? block.caption : '',\n isNumberedFloat(block), block.labelEnabled ? block.label : '',\n );\n if (block.captionEnabled) visitField(block.captionField);\n if (block.kind === 'table') {\n for (const row of block.rows) for (const cell of row) visitField(cell);\n }\n } else if (block.kind === 'textBlock') {\n visitField(block.field);\n } else if (block.kind === 'list') {\n for (const item of block.items) {\n visitField(item.field);\n walk(item.blocks);\n }\n }\n }\n }\n walk(document.blocks);\n return targets;\n}\n\n/** Author-managed manual labels only; auto keys are not editable author metadata. */\nexport function collectDocumentLabels(document: DocumentNode): DocumentLabelEntry[] {\n return collectDocumentReferenceTargets(document)\n .filter((target): target is DocumentReferenceTarget & { number: number; manualKey: string } =>\n target.number !== null && Boolean(target.manualKey))\n .map(({ manualKey, kind, caption, ownerId, number }) => ({ key: manualKey, kind, caption, ownerId, number }));\n}\n\n/** Key collision checks include generated aliases without adding persistence fields. */\nexport function collectDocumentKeyLabels(document: DocumentNode): Array<Pick<DocumentLabelEntry, 'key' | 'ownerId'>> {\n return collectDocumentReferenceTargets(document).filter((target) => target.number !== null)\n .flatMap((target) => [\n { key: target.key, ownerId: target.ownerId },\n ...(target.manualKey && target.manualKey !== target.key\n ? [{ key: target.manualKey, ownerId: target.ownerId }]\n : []),\n ]);\n}\n\nexport function labelNumberMap(document: DocumentNode): Map<string, { kind: DocumentLabelKind; number: number }> {\n const map = new Map<string, { kind: DocumentLabelKind; number: number }>();\n for (const target of collectDocumentReferenceTargets(document)) {\n if (target.number === null) continue;\n for (const key of [target.key, target.manualKey]) {\n if (key && !map.has(key)) map.set(key, { kind: target.kind, number: target.number });\n }\n }\n return map;\n}\n\nexport type FormatFloatCaptionTitleOptions = {\n uiLocale?: ButexUiLocale;\n documentDirection?: DocumentDirection;\n digitForm?: DigitFormId;\n};\n\nfunction labelKindWord(kind: DocumentLabelKind, uiLocale: ButexUiLocale): string {\n if (kind === 'fig') {\n return uiLocale === 'ar' ? 'الشكل' : 'Figure';\n }\n if (kind === 'tab') {\n return uiLocale === 'ar' ? 'الجدول' : 'Table';\n }\n return uiLocale === 'ar' ? 'المعادلة' : 'Equation';\n}\n\n/** Localized numbered float/equation title: الشكل ١ / Figure 1 / المعادلة ١. */\nexport function formatFloatCaptionTitle(\n kind: DocumentLabelKind,\n number: number,\n options: FormatFloatCaptionTitleOptions = {},\n): string {\n const locale = options.uiLocale ?? 'ar';\n const digits = formatBibliographyNumber(number, {\n documentDirection: options.documentDirection ?? (locale === 'ar' ? 'rtl' : 'ltr'),\n digitForm: options.digitForm ?? (locale === 'ar' ? 'arabicIndic' : 'western'),\n });\n return `${labelKindWord(kind, locale)} ${digits}`;\n}\n\n/** Caption line as shown in document preview: الشكل ١: نص / Figure 1. text. */\nexport function formatFloatCaptionPreview(\n title: string,\n caption: string | undefined,\n uiLocale: ButexUiLocale = 'ar',\n): string {\n const trimmed = caption?.trim() ?? '';\n if (trimmed.length === 0) {\n return title;\n }\n const separator = uiLocale === 'ar' ? ': ' : '. ';\n return `${title}${separator}${trimmed}`;\n}\n\nexport function formatRefLabel(\n keys: string[],\n document: DocumentNode,\n refCommand: 'ref' | 'eqref',\n options: FormatCiteLabelOptions = {},\n): string {\n const documentDirection: DocumentDirection = options.documentDirection ?? 'rtl';\n const digitForm: DigitFormId = options.digitForm ?? (documentDirection === 'rtl' ? 'arabicIndic' : 'western');\n const uiLocale: ButexUiLocale = documentDirection === 'rtl' ? 'ar' : 'en';\n const map = labelNumberMap(document);\n const parts = keys.map((key) => {\n const hit = map.get(key);\n if (!hit) {\n return refCommand === 'eqref' ? '(?)' : '?';\n }\n const digits = formatDigits(String(hit.number), digitForm);\n const numberLabel = refCommand === 'eqref' ? `(${digits})` : digits;\n return `${labelKindWord(hit.kind, uiLocale)} ${numberLabel}`;\n });\n return parts.join(documentDirection === 'rtl' ? '،' : ', ');\n}\n\nexport function stripDisplayMathDelimiters(source: string): string {\n const trimmed = source.trim();\n if (trimmed.startsWith('\\\\[') && trimmed.endsWith('\\\\]')) {\n return trimmed.slice(2, -2).trim();\n }\n if (trimmed.startsWith('$$') && trimmed.endsWith('$$')) {\n return trimmed.slice(2, -2).trim();\n }\n for (const environment of ['equation', 'equation*']) {\n const opening = `\\\\begin{${environment}}`;\n const closing = `\\\\end{${environment}}`;\n if (trimmed.startsWith(opening) && trimmed.endsWith(closing)) {\n return trimmed.slice(opening.length, -closing.length).trim();\n }\n }\n return trimmed;\n}\n\nexport function applyFloatMetaPatch<T extends ImageBlock2 | TableBlock2>(block: T, patch: FloatMetaPatch): void {\n if (typeof patch.centered === 'boolean') {\n block.centered = patch.centered;\n }\n if (typeof patch.captionEnabled === 'boolean') {\n block.captionEnabled = patch.captionEnabled;\n }\n if (typeof patch.caption === 'string') {\n block.caption = patch.caption;\n const existingText = block.captionField.tokens.find((token) => token.kind === 'text');\n block.captionField.tokens = [\n {\n id: existingText?.id ?? documentId('text'),\n kind: 'text',\n text: patch.caption,\n },\n ];\n }\n if (typeof patch.labelEnabled === 'boolean') {\n block.labelEnabled = patch.labelEnabled;\n }\n if (typeof patch.label === 'string') {\n block.label = patch.label;\n }\n}\n","import { citeTokenLatex } from './citations.js';\nimport { documentId } from './ids.js';\nimport { refTokenLatex } from './labels.js';\nimport type {\n DocumentInlineIdsJson,\n DocumentInlineTokenIdJson,\n InlineField2,\n InlineToken2,\n} from './types.js';\n\nexport type DocumentIdentityState = {\n blockIds: Set<string>;\n itemIds: Set<string>;\n fieldIds: Set<string>;\n tokenIds: Set<string>;\n};\n\nexport function createDocumentIdentityState(): DocumentIdentityState {\n return {\n blockIds: new Set<string>(),\n itemIds: new Set<string>(),\n fieldIds: new Set<string>(),\n tokenIds: new Set<string>(),\n };\n}\n\nexport function importedOrGeneratedId(value: unknown, prefix: string, used: Set<string>): string {\n const imported = typeof value === 'string' ? value.trim() : '';\n if (imported.length > 0 && !used.has(imported)) {\n used.add(imported);\n return imported;\n }\n\n let generated = documentId(prefix);\n while (used.has(generated)) {\n generated = documentId(prefix);\n }\n used.add(generated);\n return generated;\n}\n\nexport function inlineTokenSource(token: InlineToken2): string {\n if (token.kind === 'text') {\n return token.text;\n }\n if (token.kind === 'math') {\n return token.source;\n }\n if (token.kind === 'cite') {\n return citeTokenLatex(token.keys);\n }\n return refTokenLatex(token.keys, token.refCommand);\n}\n\nexport function inlineIdsFromField(field: InlineField2): DocumentInlineIdsJson {\n let offset = 0;\n const tokens = field.tokens.map((token): DocumentInlineTokenIdJson => {\n const start = offset;\n offset += inlineTokenSource(token).length;\n return { id: token.id, kind: token.kind, start, end: offset };\n });\n return { field_id: field.id, tokens };\n}\n\nfunction isAlignedSidecar(value: unknown, field: InlineField2): value is DocumentInlineIdsJson {\n if (typeof value !== 'object' || value === null || !Array.isArray((value as DocumentInlineIdsJson).tokens)) {\n return false;\n }\n const tokens = (value as DocumentInlineIdsJson).tokens;\n const expected = inlineIdsFromField(field).tokens;\n if (tokens.length !== expected.length) {\n return false;\n }\n return tokens.every((token, index) => {\n const expectedToken = expected[index];\n return (\n typeof token === 'object' &&\n token !== null &&\n expectedToken !== undefined &&\n token.kind === expectedToken.kind &&\n token.start === expectedToken.start &&\n token.end === expectedToken.end\n );\n });\n}\n\nexport function applyImportedInlineIds(\n field: InlineField2,\n sidecar: unknown,\n state: DocumentIdentityState,\n): InlineField2 {\n field.id = importedOrGeneratedId(\n typeof sidecar === 'object' && sidecar !== null ? (sidecar as { field_id?: unknown }).field_id : undefined,\n 'field',\n state.fieldIds,\n );\n\n const aligned = isAlignedSidecar(sidecar, field);\n field.tokens.forEach((token, index) => {\n token.id = importedOrGeneratedId(aligned ? sidecar.tokens[index]?.id : undefined, token.kind, state.tokenIds);\n });\n return field;\n}\n","import type { DetectedInlineSpan2, DetectedMathSpan2 } from './types.js';\nimport { parseCiteKeys } from './citations.js';\nimport { parseRefKeys } from './labels.js';\n\nconst MATH_ENVIRONMENTS = new Set([\n 'equation',\n 'equation*',\n 'align',\n 'align*',\n 'aligned',\n 'gather',\n 'gather*',\n 'multline',\n 'multline*',\n]);\n\nfunction isEscaped(value: string, index: number): boolean {\n let slashCount = 0;\n let i = index - 1;\n while (i >= 0 && value[i] === '\\\\') {\n slashCount += 1;\n i -= 1;\n }\n return slashCount % 2 === 1;\n}\n\nfunction findClosingDollar(value: string, start: number): number {\n let i = start;\n while (i < value.length) {\n if (value[i] === '$' && !isEscaped(value, i)) {\n return i;\n }\n i += 1;\n }\n return -1;\n}\n\nfunction environmentSpan(value: string, start: number): DetectedMathSpan2 | null {\n const match = /^\\\\begin\\{([A-Za-z*]+)\\}/.exec(value.slice(start));\n if (!match) {\n return null;\n }\n\n const envName = match[1] ?? '';\n if (!MATH_ENVIRONMENTS.has(envName)) {\n return null;\n }\n\n const opening = match[0] ?? '';\n const closing = `\\\\end{${envName}}`;\n const closingStart = value.indexOf(closing, start + opening.length);\n if (closingStart < 0) {\n return null;\n }\n\n const end = closingStart + closing.length;\n return { start, end, source: value.slice(start, end), opening, closing, display: true };\n}\n\nfunction citeSpan(value: string, start: number): DetectedInlineSpan2 | null {\n if (!value.startsWith('\\\\cite{', start) || isEscaped(value, start)) {\n return null;\n }\n const openBrace = start + '\\\\cite'.length;\n if (value[openBrace] !== '{') {\n return null;\n }\n let depth = 0;\n for (let i = openBrace; i < value.length; i += 1) {\n const char = value[i];\n if (char === '{' && !isEscaped(value, i)) {\n depth += 1;\n continue;\n }\n if (char === '}' && !isEscaped(value, i)) {\n depth -= 1;\n if (depth === 0) {\n const end = i + 1;\n const source = value.slice(start, end);\n return { kind: 'cite', start, end, source, keys: parseCiteKeys(source) };\n }\n }\n }\n return null;\n}\n\nfunction refSpan(value: string, start: number): DetectedInlineSpan2 | null {\n const eqrefPrefix = '\\\\eqref{';\n const refPrefix = '\\\\ref{';\n const isEqref = value.startsWith(eqrefPrefix, start) && !isEscaped(value, start);\n const isRef = value.startsWith(refPrefix, start) && !isEscaped(value, start);\n if (!isEqref && !isRef) {\n return null;\n }\n const refCommand: 'ref' | 'eqref' = isEqref ? 'eqref' : 'ref';\n const prefix = isEqref ? eqrefPrefix : refPrefix;\n\n const openBrace = start + prefix.length - 1;\n if (value[openBrace] !== '{') {\n return null;\n }\n let depth = 0;\n for (let i = openBrace; i < value.length; i += 1) {\n const char = value[i];\n if (char === '{' && !isEscaped(value, i)) {\n depth += 1;\n continue;\n }\n if (char === '}' && !isEscaped(value, i)) {\n depth -= 1;\n if (depth === 0) {\n const end = i + 1;\n const source = value.slice(start, end);\n const parsed = parseRefKeys(source);\n return { kind: 'ref', start, end, source, keys: parsed.keys, refCommand };\n }\n }\n }\n return null;\n}\n\nfunction mathSpanAt(value: string, i: number): DetectedMathSpan2 | null {\n if (value.startsWith('\\\\begin{', i)) {\n return environmentSpan(value, i);\n }\n\n if (value.startsWith('\\\\(', i)) {\n const close = value.indexOf('\\\\)', i + 2);\n if (close >= 0) {\n const end = close + 2;\n return { start: i, end, source: value.slice(i, end), opening: '\\\\(', closing: '\\\\)', display: false };\n }\n }\n\n if (value.startsWith('\\\\[', i)) {\n const close = value.indexOf('\\\\]', i + 2);\n if (close >= 0) {\n const end = close + 2;\n return { start: i, end, source: value.slice(i, end), opening: '\\\\[', closing: '\\\\]', display: true };\n }\n }\n\n if (value.startsWith('$$', i) && !isEscaped(value, i)) {\n const close = value.indexOf('$$', i + 2);\n if (close >= 0) {\n const end = close + 2;\n return { start: i, end, source: value.slice(i, end), opening: '$$', closing: '$$', display: true };\n }\n }\n\n if (value[i] === '$' && !isEscaped(value, i)) {\n const close = findClosingDollar(value, i + 1);\n if (close >= 0) {\n const end = close + 1;\n return { start: i, end, source: value.slice(i, end), opening: '$', closing: '$', display: false };\n }\n }\n\n return null;\n}\n\n/** Math-only spans (used for math_objects alignment counts). */\nexport function detectMathSpans(value: string): DetectedMathSpan2[] {\n return detectInlineSpans(value)\n .filter((span): span is DetectedInlineSpan2 & { kind: 'math' } => span.kind === 'math')\n .map((span) => ({\n start: span.start,\n end: span.end,\n source: span.source,\n opening: span.opening,\n closing: span.closing,\n display: span.display,\n }));\n}\n\n/** Left-to-right math + \\\\cite + \\\\ref/\\\\eqref spans without overlap. */\nexport function detectInlineSpans(value: string): DetectedInlineSpan2[] {\n const spans: DetectedInlineSpan2[] = [];\n let i = 0;\n\n while (i < value.length) {\n const cite = citeSpan(value, i);\n if (cite) {\n spans.push(cite);\n i = cite.end;\n continue;\n }\n\n const ref = refSpan(value, i);\n if (ref) {\n spans.push(ref);\n i = ref.end;\n continue;\n }\n\n const math = mathSpanAt(value, i);\n if (math) {\n spans.push({ kind: 'math', ...math });\n i = math.end;\n continue;\n }\n\n i += 1;\n }\n\n return spans;\n}\n","import { fromMathObjectJson } from '../shared/math-document/mathObject.js';\nimport { normalizeDocumentMeta, emptyDocumentMeta } from './articleMeta.js';\nimport { referenceFromJson } from './citations.js';\nimport { documentId } from './ids.js';\nimport {\n applyImportedInlineIds,\n createDocumentIdentityState,\n importedOrGeneratedId,\n type DocumentIdentityState,\n} from './inlineIdentity.js';\nimport { detectInlineSpans, detectMathSpans } from './inlineScanner.js';\nimport { parseFloatMetaFromJson } from './labels.js';\nimport type {\n BibliographyBlock2,\n DocumentBlock,\n DocumentBlockMetadata,\n DocumentBlockJson,\n DocumentDiagnostic,\n DocumentMathObjectJson,\n DocumentListItemJson,\n DocumentNode,\n DocumentParseMode,\n ImageBlock2,\n ImportDocumentOptions,\n InlineField2,\n InlineToken2,\n ListBlock2,\n ListItem2,\n RawBlock2,\n Reference2,\n Reference2Json,\n TableBlock2,\n TextFormatSpan2Json,\n TextStyle2,\n TextBlock2,\n} from './types.js';\n\nconst TEXT_COMMANDS = new Set(['\\\\section', '\\\\subsection', '\\\\subsubsection', '\\\\paragraph']);\nconst LIST_COMMANDS = new Set(['\\\\begin{itemize}', '\\\\begin{enumerate}']);\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction requireString(value: unknown, message: string): string {\n if (typeof value !== 'string') {\n throw new Error(message);\n }\n return value;\n}\n\nfunction isRecordOfStrings(value: unknown): value is Record<string, string> {\n return isObject(value) && Object.values(value).every((entry) => typeof entry === 'string');\n}\n\nfunction asBlockJson(value: unknown): DocumentBlockJson {\n if (!isObject(value)) {\n throw new Error('Document block must be an object');\n }\n if (typeof value.command !== 'string') {\n throw new Error('Document block requires string command');\n }\n return value as DocumentBlockJson;\n}\n\nfunction blockIdFromJson(json: DocumentBlockJson, state: DocumentIdentityState): string {\n return importedOrGeneratedId(json.id, 'block', state.blockIds);\n}\n\nfunction metadataFromJson(value: unknown): { metadata?: DocumentBlockMetadata } {\n if (!isObject(value) || (value.source !== 'agent' && value.source !== 'user')) {\n return {};\n }\n return { metadata: { source: value.source } };\n}\n\nfunction pushDiagnostic(diagnostics: DocumentDiagnostic[], options: ImportDocumentOptions, path: string, message: string): void {\n if (options.strict) {\n throw new Error(message);\n }\n diagnostics.push({ code: 'math_alignment', message, path });\n}\n\nfunction parseReferences(json: unknown): Reference2[] {\n if (!Array.isArray(json)) {\n return [];\n }\n const references: Reference2[] = [];\n for (const entry of json) {\n if (!isObject(entry) || typeof entry.key !== 'string' || entry.key.trim().length === 0) {\n continue;\n }\n references.push(\n referenceFromJson({\n key: entry.key.trim(),\n authors: typeof entry.authors === 'string' ? entry.authors : undefined,\n title: typeof entry.title === 'string' ? entry.title : undefined,\n year: typeof entry.year === 'string' ? entry.year : undefined,\n url: typeof entry.url === 'string' ? entry.url : undefined,\n venue: typeof entry.venue === 'string' ? entry.venue : undefined,\n field_separator:\n entry.field_separator === ',' || entry.field_separator === '،'\n ? entry.field_separator\n : undefined,\n } satisfies Reference2Json),\n );\n }\n return references;\n}\n\nexport function createInlineField(\n value = '',\n mathObjects: Array<DocumentMathObjectJson | null> = [],\n options: ImportDocumentOptions = {},\n path = '$',\n diagnostics: DocumentDiagnostic[] = [],\n formats: TextFormatSpan2Json[] = [],\n): InlineField2 {\n const mode: DocumentParseMode = options.mode ?? 'english';\n const spans = detectInlineSpans(value);\n const mathSpans = spans.filter((span) => span.kind === 'math');\n const tokens: InlineToken2[] = [];\n let index = 0;\n let mathObjectIndex = 0;\n\n if (mathObjects.length > 0 && mathObjects.length !== mathSpans.length) {\n pushDiagnostic(diagnostics, options, path, `math_objects count mismatch: detected ${String(mathSpans.length)}, got ${String(mathObjects.length)}`);\n }\n\n for (const span of spans) {\n if (span.start > index) {\n pushFormattedTextTokens(tokens, value.slice(index, span.start), index, formats);\n }\n\n if (span.kind === 'cite') {\n tokens.push({\n id: documentId('cite'),\n kind: 'cite',\n keys: span.keys.length > 0 ? span.keys : [],\n });\n index = span.end;\n continue;\n }\n\n if (span.kind === 'ref') {\n tokens.push({\n id: documentId('ref'),\n kind: 'ref',\n keys: span.keys.length > 0 ? span.keys : [],\n refCommand: span.refCommand,\n });\n index = span.end;\n continue;\n }\n\n const mathJson = mathObjects[mathObjectIndex];\n mathObjectIndex += 1;\n const structuredMathJson = mathJson?.node_type === 'MathObject' ? mathJson : null;\n if (structuredMathJson && (structuredMathJson.math_mode !== span.opening || structuredMathJson.closing !== span.closing)) {\n pushDiagnostic(diagnostics, options, path, 'math_objects order mismatch');\n }\n\n if (structuredMathJson && structuredMathJson.math_mode === span.opening && structuredMathJson.closing === span.closing) {\n tokens.push({\n id: documentId('math'),\n kind: 'math',\n display: span.display,\n opening: span.opening,\n closing: span.closing,\n source: span.source,\n sourceSide:\n structuredMathJson.source_side === 'arabic' || structuredMathJson.source_side === 'english'\n ? structuredMathJson.source_side\n : mode,\n math: fromMathObjectJson(structuredMathJson, mode),\n editable: true,\n sourceOwner: structuredMathJson.source_owner === 'editor' ? 'editor' : 'imported-structured',\n ...(typeof structuredMathJson.label_enabled === 'boolean' ? { labelEnabled: structuredMathJson.label_enabled } : {}),\n ...(typeof structuredMathJson.label === 'string' ? { label: structuredMathJson.label } : {}),\n ...(typeof structuredMathJson.numbered === 'boolean' ? { numbered: structuredMathJson.numbered } : {}),\n });\n } else {\n tokens.push({\n id: documentId('math'),\n kind: 'math',\n display: span.display,\n opening: span.opening,\n closing: span.closing,\n source: span.source,\n math: null,\n editable: false,\n reason: 'هذه المعادلة محفوظة كنص خام فقط حاليا',\n sourceOwner: 'raw',\n ...(mathJson?.node_type === 'RawMathObject' && typeof mathJson.label_enabled === 'boolean'\n ? { labelEnabled: mathJson.label_enabled }\n : {}),\n ...(mathJson?.node_type === 'RawMathObject' && typeof mathJson.label === 'string'\n ? { label: mathJson.label }\n : {}),\n ...(mathJson?.node_type === 'RawMathObject' && typeof mathJson.numbered === 'boolean'\n ? { numbered: mathJson.numbered }\n : {}),\n });\n }\n\n index = span.end;\n }\n\n if (index < value.length || tokens.length === 0) {\n pushFormattedTextTokens(tokens, value.slice(index), index, formats);\n }\n\n return { id: documentId('field'), tokens: compactTextTokens(tokens) };\n}\n\nfunction styleFromFormat(format: TextFormatSpan2Json): TextStyle2 | null {\n const style: TextStyle2 = {};\n if (format.bold === true) {\n style.bold = true;\n }\n if (format.italic === true) {\n style.italic = true;\n }\n if (format.underline === true) {\n style.underline = true;\n }\n return style.bold || style.italic || style.underline ? style : null;\n}\n\nfunction mergeTextStyle(base: TextStyle2 | undefined, added: TextStyle2): TextStyle2 {\n return {\n ...(base?.bold ? { bold: true as const } : {}),\n ...(base?.italic ? { italic: true as const } : {}),\n ...(base?.underline ? { underline: true as const } : {}),\n ...(added.bold ? { bold: true as const } : {}),\n ...(added.italic ? { italic: true as const } : {}),\n ...(added.underline ? { underline: true as const } : {}),\n };\n}\n\nfunction textStylesEqual(a: TextStyle2 | undefined, b: TextStyle2 | undefined): boolean {\n return Boolean(a?.bold) === Boolean(b?.bold) && Boolean(a?.italic) === Boolean(b?.italic) && Boolean(a?.underline) === Boolean(b?.underline);\n}\n\nfunction compactTextTokens(tokens: InlineToken2[]): InlineToken2[] {\n const compacted: InlineToken2[] = [];\n for (const token of tokens) {\n const previous = compacted[compacted.length - 1];\n if (previous?.kind === 'text' && token.kind === 'text' && textStylesEqual(previous.style, token.style)) {\n previous.text += token.text;\n } else {\n compacted.push(token);\n }\n }\n return compacted;\n}\n\nfunction styleKey(style: TextStyle2 | undefined): string {\n return `${style?.bold ? 'b' : ''}${style?.italic ? 'i' : ''}${style?.underline ? 'u' : ''}`;\n}\n\nfunction pushFormattedTextTokens(tokens: InlineToken2[], text: string, sourceStart: number, formats: TextFormatSpan2Json[]): void {\n if (text.length === 0) {\n tokens.push({ id: documentId('text'), kind: 'text', text });\n return;\n }\n const styles: Array<TextStyle2 | undefined> = Array.from({ length: text.length });\n for (const format of formats) {\n const style = styleFromFormat(format);\n if (!style || !Number.isFinite(format.start) || !Number.isFinite(format.end)) {\n continue;\n }\n const start = Math.max(0, Math.min(text.length, Math.trunc(format.start) - sourceStart));\n const end = Math.max(0, Math.min(text.length, Math.trunc(format.end) - sourceStart));\n if (end <= start) {\n continue;\n }\n for (let index = start; index < end; index += 1) {\n styles[index] = mergeTextStyle(styles[index], style);\n }\n }\n\n let chunkStart = 0;\n for (let index = 1; index <= text.length; index += 1) {\n if (index < text.length && styleKey(styles[index]) === styleKey(styles[chunkStart])) {\n continue;\n }\n const chunk = text.slice(chunkStart, index);\n const style = styles[chunkStart];\n tokens.push({ id: documentId('text'), kind: 'text', text: chunk, ...(style ? { style } : {}) });\n chunkStart = index;\n }\n}\n\nfunction closingForList(command: '\\\\begin{itemize}' | '\\\\begin{enumerate}'): '\\\\end{itemize}' | '\\\\end{enumerate}' {\n return command === '\\\\begin{itemize}' ? '\\\\end{itemize}' : '\\\\end{enumerate}';\n}\n\nfunction parseTextBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): TextBlock2 {\n const value = requireString(json.value, `${json.command} requires string value`);\n return {\n id: blockIdFromJson(json, identities),\n kind: 'textBlock',\n command: json.command as TextBlock2['command'],\n field: applyImportedInlineIds(\n createInlineField(value, json.math_objects ?? [], options, `${path}.value`, diagnostics, json.command === '\\\\paragraph' ? json.formats ?? [] : []),\n json.inline_ids,\n identities,\n ),\n ...metadataFromJson(json.metadata),\n ...(typeof json.label === 'string' && json.command !== '\\\\paragraph' ? { label: json.label } : {}),\n ...(json.centered === true ? { centered: true } : {}),\n };\n}\n\nfunction parseListItem(\n json: DocumentListItemJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): ListItem2 {\n const value = requireString(json.value, 'Document list item requires string value');\n const blocksJson = Array.isArray(json.blocks) ? json.blocks : [];\n return {\n id: importedOrGeneratedId(json.id, 'item', identities.itemIds),\n field: applyImportedInlineIds(\n createInlineField(value, json.math_objects ?? [], options, `${path}.value`, diagnostics, json.formats ?? []),\n json.inline_ids,\n identities,\n ),\n blocks: blocksJson.map((block, index) =>\n parseBlock(asBlockJson(block), options, `${path}.blocks[${String(index)}]`, diagnostics, identities),\n ),\n };\n}\n\nfunction parseListBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): ListBlock2 {\n if (!Array.isArray(json.items)) {\n throw new Error(`${json.command} requires items array`);\n }\n const command = json.command as ListBlock2['command'];\n const closing = closingForList(command);\n return {\n id: blockIdFromJson(json, identities),\n kind: 'list',\n command,\n closing,\n items: json.items.map((item, index) =>\n parseListItem(item, options, `${path}.items[${String(index)}]`, diagnostics, identities),\n ),\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction captionFieldFromJson(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): InlineField2 {\n const caption = typeof json.caption === 'string' ? json.caption : '';\n return applyImportedInlineIds(\n createInlineField(\n caption,\n json.caption_math_objects ?? [],\n options,\n `${path}.caption`,\n diagnostics,\n json.caption_formats ?? [],\n ),\n json.caption_inline_ids,\n identities,\n );\n}\n\nfunction parseTableBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): TableBlock2 {\n if (!Array.isArray(json.rows)) {\n throw new Error('\\\\begin{tabular} requires rows array');\n }\n\n const mathObjects = json.math_objects ?? [];\n let mathObjectIndex = 0;\n const rows = json.rows.map((row, rowIndex) => {\n if (!Array.isArray(row)) {\n throw new Error('\\\\begin{tabular} rows must be arrays');\n }\n return row.map((cell, columnIndex) => {\n const value = requireString(cell, '\\\\begin{tabular} cells must be strings');\n const spanCount = detectMathSpans(value).length;\n const cellMathObjects = mathObjects.slice(mathObjectIndex, mathObjectIndex + spanCount);\n mathObjectIndex += spanCount;\n const cellFormats = json.cell_formats?.[rowIndex]?.[columnIndex] ?? [];\n return applyImportedInlineIds(\n createInlineField(value, cellMathObjects, options, `${path}.rows[${String(rowIndex)}][${String(columnIndex)}]`, diagnostics, cellFormats),\n json.cell_inline_ids?.[rowIndex]?.[columnIndex],\n identities,\n );\n });\n });\n\n if (mathObjects.length > 0 && mathObjects.length !== mathObjectIndex) {\n pushDiagnostic(diagnostics, options, path, `math_objects count mismatch: detected ${String(mathObjectIndex)}, got ${String(mathObjects.length)}`);\n }\n\n const floatMeta = parseFloatMetaFromJson(json);\n return {\n id: blockIdFromJson(json, identities),\n kind: 'table',\n command: '\\\\begin{tabular}',\n closing: '\\\\end{tabular}',\n columns: typeof json.columns === 'string' ? json.columns : '',\n rows,\n ...floatMeta,\n captionField: captionFieldFromJson(json, options, path, diagnostics, identities),\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction parseImageBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): ImageBlock2 {\n const assetId = typeof json.asset_id === 'string' && json.asset_id.length > 0 ? json.asset_id : undefined;\n const value =\n assetId !== undefined\n ? typeof json.value === 'string'\n ? json.value\n : ''\n : requireString(json.value, '\\\\includegraphics requires string value');\n const floatMeta = parseFloatMetaFromJson(json);\n return {\n id: blockIdFromJson(json, identities),\n kind: 'image',\n command: '\\\\includegraphics',\n value,\n ...(assetId !== undefined ? { assetId } : {}),\n options: isRecordOfStrings(json.options) ? json.options : {},\n ...floatMeta,\n captionField: captionFieldFromJson(json, options, path, diagnostics, identities),\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction parseRawBlock(json: DocumentBlockJson, identities: DocumentIdentityState): RawBlock2 {\n return {\n id: blockIdFromJson(json, identities),\n kind: 'raw',\n command: '\\\\raw',\n value: typeof json.value === 'string' ? json.value : '',\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction parseBibliographyBlock(json: DocumentBlockJson, identities: DocumentIdentityState): BibliographyBlock2 {\n return {\n id: blockIdFromJson(json, identities),\n kind: 'bibliography',\n command: '\\\\begin{thebibliography}',\n closing: '\\\\end{thebibliography}',\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction parseBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): DocumentBlock {\n if (TEXT_COMMANDS.has(json.command)) {\n return parseTextBlock(json, options, path, diagnostics, identities);\n }\n if (LIST_COMMANDS.has(json.command)) {\n return parseListBlock(json, options, path, diagnostics, identities);\n }\n if (json.command === '\\\\begin{tabular}') {\n return parseTableBlock(json, options, path, diagnostics, identities);\n }\n if (json.command === '\\\\includegraphics') {\n return parseImageBlock(json, options, path, diagnostics, identities);\n }\n if (json.command === '\\\\begin{thebibliography}' || json.command === '\\\\bibliography') {\n return parseBibliographyBlock(json, identities);\n }\n if (json.command === '\\\\raw') {\n return parseRawBlock(json, identities);\n }\n return {\n id: blockIdFromJson(json, identities),\n kind: 'raw',\n command: '\\\\raw',\n value: typeof json.value === 'string' ? json.value : json.command,\n ...metadataFromJson(json.metadata),\n };\n}\n\nexport function fromDocumentJson(json: unknown, options: ImportDocumentOptions = {}): DocumentNode {\n if (!isObject(json) || json.node_type !== 'DocumentObject') {\n throw new Error('DocumentObject requires node_type \"DocumentObject\"');\n }\n if (!Array.isArray(json.blocks)) {\n throw new Error('DocumentObject requires blocks array');\n }\n\n const diagnostics: DocumentDiagnostic[] = [];\n const identities = createDocumentIdentityState();\n return {\n nodeType: 'DocumentObject',\n meta: normalizeDocumentMeta(json.meta),\n references: parseReferences(json.references),\n blocks: json.blocks.map((block, index) =>\n parseBlock(asBlockJson(block), options, `$.blocks[${String(index)}]`, diagnostics, identities),\n ),\n diagnostics,\n };\n}\n\nexport function createEmptyDocument(): DocumentNode {\n return {\n nodeType: 'DocumentObject',\n meta: emptyDocumentMeta(),\n references: [],\n blocks: [],\n diagnostics: [],\n };\n}\n","export const ATOMIC_OPERATOR_COMMANDS = {\n inf: {\n id: 'inf',\n category: 'operators1',\n Tex: '\\\\infty',\n mirror: true,\n Label: '∞',\n title: 'اللانهاية',\n svg_path: null,\n },\n top: {\n id: 'top',\n category: 'operators1',\n Tex: '\\\\top',\n mirror: false,\n Label: '⊤',\n title: 'المنقول',\n svg_path: null,\n },\n times: {\n id: 'times',\n category: 'operators1',\n Tex: '\\\\times',\n mirror: false,\n Label: '×',\n title: 'ضرب',\n svg_path: null,\n },\n div: {\n id: 'div',\n category: 'operators1',\n Tex: '\\\\div',\n mirror: false,\n Label: '÷',\n title: 'قسمة',\n svg_path: null,\n },\n pm: {\n id: 'pm',\n category: 'operators1',\n Tex: '\\\\pm',\n mirror: false,\n Label: '±',\n title: 'زائد أو ناقص',\n svg_path: null,\n },\n mp: {\n id: 'mp',\n category: 'operators1',\n Tex: '\\\\mp',\n mirror: false,\n Label: '∓',\n title: 'ناقص أو زائد',\n svg_path: null,\n },\n neq: {\n id: 'neq',\n category: 'operators1',\n Tex: '\\\\neq',\n mirror: true,\n compileMirror: true,\n Label: '≠',\n title: 'لا يساوي',\n svg_path: null,\n },\n approx: {\n id: 'approx',\n category: 'operators1',\n Tex: '\\\\approx',\n mirror: false,\n displayMirror: true,\n Label: '≈',\n title: 'تقريبا يساوي',\n svg_path: null,\n },\n sim: {\n id: 'sim',\n category: 'operators1',\n Tex: '\\\\sim',\n mirror: false,\n displayMirror: true,\n Label: '∼',\n title: 'مشابه',\n svg_path: null,\n },\n mid: {\n id: 'mid',\n category: 'operators1',\n Tex: '\\\\mid',\n mirror: false,\n Label: '∣',\n title: 'يقسم',\n svg_path: null,\n },\n leq: {\n id: 'leq',\n category: 'operators1',\n Tex: '\\\\leq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '≤',\n title: 'أصغر من أو يساوي',\n svg_path: null,\n },\n geq: {\n id: 'geq',\n category: 'operators1',\n Tex: '\\\\geq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '≥',\n title: 'أكبر من أو يساوي',\n svg_path: null,\n },\n coloneqq: {\n id: 'coloneqq',\n category: 'operators1',\n Tex: '\\\\coloneqq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '≔',\n title: 'يعرف بأنه يساوي',\n svg_path: null,\n },\n eqqcolon: {\n id: 'eqqcolon',\n category: 'operators1',\n Tex: '\\\\eqqcolon',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '≕',\n title: 'يساوي بالتعريف',\n svg_path: null,\n },\n\n ///// Operators 2\n propto: {\n id: 'propto',\n category: 'operators2',\n Tex: '\\\\propto',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∝',\n title: 'يتناسب مع',\n svg_path: null,\n },\n in: {\n id: 'in',\n category: 'operators2',\n Tex: '\\\\in',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∈',\n title: 'ينتمي إلى',\n svg_path: null,\n },\n notin: {\n id: 'notin',\n category: 'operators2',\n Tex: '\\\\notin',\n mirror: false,\n displayMirror: true,\n Label: '∉',\n title: 'لا ينتمي إلى',\n svg_path: null,\n },\n subset: {\n id: 'subset',\n category: 'operators2',\n Tex: '\\\\subset',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊂',\n title: 'مجموعة جزئية من',\n svg_path: null,\n },\n supset: {\n id: 'supset',\n category: 'operators2',\n Tex: '\\\\supset',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊃',\n title: 'مجموعة شاملة لـ',\n svg_path: null,\n },\n subseteq: {\n id: 'subseteq',\n category: 'operators2',\n Tex: '\\\\subseteq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊆',\n title: 'مجموعة جزئية أو تساوي',\n svg_path: null,\n },\n supseteq: {\n id: 'supseteq',\n category: 'operators2',\n Tex: '\\\\supseteq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊇',\n title: 'مجموعة شاملة أو تساوي',\n svg_path: null,\n },\n cap: {\n id: 'cap',\n category: 'operators2',\n Tex: '\\\\cap',\n mirror: false,\n displayMirror: true,\n Label: '∩',\n title: 'تقاطع',\n svg_path: null,\n },\n cup: {\n id: 'cup',\n category: 'operators2',\n Tex: '\\\\cup',\n mirror: false,\n displayMirror: true,\n Label: '∪',\n title: 'اتحاد',\n svg_path: null,\n },\n emptyset: {\n id: 'emptyset',\n category: 'operators2',\n Tex: '\\\\emptyset',\n mirror: false,\n displayMirror: true,\n Label: '∅',\n title: 'المجموعة الخالية',\n svg_path: null,\n },\n nsubseteq: {\n id: 'nsubseteq',\n category: 'operators2',\n Tex: '\\\\nsubseteq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊈',\n title: 'ليست مجموعة جزئية أو تساوي',\n svg_path: null,\n },\n nsupseteq: {\n id: 'nsupseteq',\n category: 'operators2',\n Tex: '\\\\nsupseteq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊉',\n title: 'ليست مجموعة شاملة أو تساوي',\n svg_path: null,\n },\n\n ///// Dots\n ldots: {\n id: 'ldots',\n category: 'dots',\n Tex: '\\\\ldots',\n mirror: false,\n Label: '…',\n title: 'نقاط أفقية',\n svg_path: null,\n },\n cdot: {\n id: 'cdot',\n category: 'dots',\n Tex: '\\\\cdot',\n mirror: false,\n Label: '·',\n title: 'نقطة ضرب',\n svg_path: null,\n },\n cdots: {\n id: 'cdots',\n category: 'dots',\n Tex: '\\\\cdots',\n mirror: false,\n Label: '⋯',\n title: 'نقاط وسطية أفقية',\n svg_path: null,\n },\n vdots: {\n id: 'vdots',\n category: 'dots',\n Tex: '\\\\vdots',\n mirror: false,\n Label: '⋮',\n title: 'نقاط عمودية',\n svg_path: null,\n },\n ddots: {\n id: 'ddots',\n category: 'dots',\n Tex: '\\\\ddots',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⋱',\n title: 'نقاط قطرية',\n svg_path: null,\n },\n\n /// Operators 3\n leftrightarrowDouble: {\n id: 'leftrightarrowDouble',\n category: 'operators3',\n Tex: '\\\\Leftrightarrow',\n mirror: false,\n Label: '⇔',\n title: 'يكافئ',\n svg_path: null,\n },\n implies: {\n id: 'implies',\n category: 'operators3',\n Tex: '\\\\implies',\n mirror: true,\n compileMirror: true,\n Label: '⇒',\n title: 'يستلزم',\n svg_path: null,\n },\n impliedby: {\n id: 'impliedby',\n category: 'operators3',\n Tex: '\\\\impliedby',\n mirror: true,\n compileMirror: true,\n Label: '⇐',\n title: 'مستلزم من',\n svg_path: null,\n },\n iff: {\n id: 'iff',\n category: 'operators3',\n Tex: '\\\\iff',\n mirror: false,\n Label: '⇔',\n title: 'إذا وفقط إذا',\n svg_path: null,\n },\n Longrightarrow: {\n id: 'Longrightarrow',\n category: 'operators3',\n Tex: '\\\\Longrightarrow',\n mirror: true,\n compileMirror: true,\n Label: '⟹',\n title: 'سهم مزدوج طويل إلى اليمين',\n svg_path: null,\n },\n Longleftarrow: {\n id: 'Longleftarrow',\n category: 'operators3',\n Tex: '\\\\Longleftarrow',\n mirror: true,\n compileMirror: true,\n Label: '⟸',\n title: 'سهم مزدوج طويل إلى اليسار',\n svg_path: null,\n },\n to: {\n id: 'to',\n category: 'operators3',\n Tex: '\\\\to',\n mirror: true,\n compileMirror: true,\n Label: '→',\n title: 'يؤول إلى',\n svg_path: null,\n },\n rightleftharpoons: {\n id: 'rightleftharpoons',\n category: 'operators3',\n Tex: '\\\\rightleftharpoons',\n mirror: true,\n compileMirror: true,\n Label: '⇌',\n title: 'اتزان',\n svg_path: null,\n },\n leftarrow: {\n id: 'leftarrow',\n category: 'operators3',\n Tex: '\\\\leftarrow',\n mirror: true,\n compileMirror: true,\n Label: '←',\n title: 'سهم إلى اليسار',\n svg_path: null,\n },\n rightarrow: {\n id: 'rightarrow',\n category: 'operators3',\n Tex: '\\\\rightarrow',\n mirror: true,\n compileMirror: true,\n Label: '→',\n title: 'سهم إلى اليمين',\n svg_path: null,\n },\n leftarrowDouble: {\n id: 'leftarrowDouble',\n category: 'operators3',\n Tex: '\\\\Leftarrow',\n mirror: true,\n compileMirror: true,\n Label: '⇐',\n title: 'سهم مزدوج إلى اليسار',\n svg_path: null,\n },\n rightarrowDouble: {\n id: 'rightarrowDouble',\n category: 'operators3',\n Tex: '\\\\Rightarrow',\n mirror: true,\n compileMirror: true,\n Label: '⇒',\n title: 'سهم مزدوج إلى اليمين',\n svg_path: null,\n },\n leftharpoonup: {\n id: 'leftharpoonup',\n category: 'operators3',\n Tex: '\\\\leftharpoonup',\n mirror: true,\n compileMirror: true,\n Label: '↼',\n title: 'سهم خطافي علوي إلى اليسار',\n svg_path: null,\n },\n rightharpoonup: {\n id: 'rightharpoonup',\n category: 'operators3',\n Tex: '\\\\rightharpoonup',\n mirror: true,\n compileMirror: true,\n Label: '⇀',\n title: 'سهم خطافي علوي إلى اليمين',\n svg_path: null,\n },\n leftharpoondown: {\n id: 'leftharpoondown',\n category: 'operators3',\n Tex: '\\\\leftharpoondown',\n mirror: true,\n compileMirror: true,\n Label: '↽',\n title: 'سهم خطافي سفلي إلى اليسار',\n svg_path: null,\n },\n rightharpoondown: {\n id: 'rightharpoondown',\n category: 'operators3',\n Tex: '\\\\rightharpoondown',\n mirror: true,\n compileMirror: true,\n Label: '⇁',\n title: 'سهم خطافي سفلي إلى اليمين',\n svg_path: null,\n },\n\n // Integrals\n int: {\n id: 'int',\n category: 'integrals',\n Tex: '\\\\int',\n mirror: true,\n compileMirror: true,\n Label: '∫',\n title: 'تكامل',\n svg_path: null,\n },\n iint: {\n id: 'iint',\n category: 'integrals',\n Tex: '\\\\iint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∬',\n title: 'تكامل مزدوج',\n svg_path: null,\n },\n iiint: {\n id: 'iiint',\n category: 'integrals',\n Tex: '\\\\iiint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∭',\n title: 'تكامل ثلاثي',\n svg_path: null,\n },\n iiiint: {\n id: 'iiiint',\n category: 'integrals',\n Tex: '\\\\iiiint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⨌',\n title: 'تكامل رباعي',\n svg_path: null,\n },\n oint: {\n id: 'oint',\n category: 'integrals',\n Tex: '\\\\oint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∮',\n title: 'تكامل مغلق',\n svg_path: null,\n },\n oiint: {\n id: 'oiint',\n category: 'integrals',\n Tex: '\\\\oiint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∯',\n title: 'تكامل سطحي مغلق',\n svg_path: null,\n },\n oiiint: {\n id: 'oiiint',\n category: 'integrals',\n Tex: '\\\\oiiint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∰',\n title: 'تكامل حجمي مغلق',\n svg_path: null,\n },\n} as const;\n\nexport type AtomicOperatorCommandId = keyof typeof ATOMIC_OPERATOR_COMMANDS;\n\nexport type AtomicOperatorCommandCategory =\n | 'operators1'\n | 'operators2'\n | 'operators3'\n | 'dots'\n | 'integrals';\n\nexport type AtomicOperatorCommandSpec =\n (typeof ATOMIC_OPERATOR_COMMANDS)[AtomicOperatorCommandId] & {\n displayMirror?: boolean;\n compileMirror?: boolean;\n };\n\nexport function shouldMirrorOperatorDisplay(\n command: AtomicOperatorCommandSpec | null | undefined,\n): boolean {\n return command?.displayMirror ?? command?.mirror ?? false;\n}\n\nconst MIRRORED_OPERATOR_TEX = Object.values(ATOMIC_OPERATOR_COMMANDS)\n .filter((command) => command.mirror)\n .map((command) => command.Tex)\n .sort((a, b) => b.length - a.length) as string[];\n\nconst COMPILE_MIRRORED_OPERATOR_TEX = Object.values(ATOMIC_OPERATOR_COMMANDS)\n .filter((command) => 'compileMirror' in command && command.compileMirror)\n .map((command) => command.Tex)\n .sort((a, b) => b.length - a.length) as string[];\n\nfunction matchingMirroredOperatorFrom(tex: string, index: number, operatorTexList: string[]): string | null {\n for (const operatorTex of operatorTexList) {\n if (!tex.startsWith(operatorTex, index)) {\n continue;\n }\n const next = tex[index + operatorTex.length];\n if (next != null && /[A-Za-z]/.test(next)) {\n continue;\n }\n return operatorTex;\n }\n return null;\n}\n\nfunction findMatchingBrace(tex: string, openIndex: number): number {\n let depth = 0;\n for (let index = openIndex; index < tex.length; index += 1) {\n const char = tex[index];\n if (char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === '{') {\n depth += 1;\n } else if (char === '}') {\n depth -= 1;\n if (depth === 0) {\n return index;\n }\n }\n }\n return -1;\n}\n\nexport function mirrorBuTeXOperatorsInTex(tex: string, options: { target?: 'preview' | 'compile' } = {}): string {\n const mirroredOperatorTex = options.target === 'compile'\n ? COMPILE_MIRRORED_OPERATOR_TEX\n : MIRRORED_OPERATOR_TEX;\n let result = '';\n let index = 0;\n\n while (index < tex.length) {\n if (tex.startsWith('\\\\butexmirror{', index)) {\n const end = findMatchingBrace(tex, index + '\\\\butexmirror'.length);\n if (end !== -1) {\n const bodyStart = index + '\\\\butexmirror{'.length;\n const body = tex.slice(bodyStart, end);\n if (\n options.target === 'compile' &&\n MIRRORED_OPERATOR_TEX.includes(body) &&\n !mirroredOperatorTex.includes(body)\n ) {\n result += body;\n } else {\n result += tex.slice(index, end + 1);\n }\n index = end + 1;\n continue;\n }\n }\n\n const operatorTex = matchingMirroredOperatorFrom(tex, index, mirroredOperatorTex);\n if (operatorTex) {\n result += `\\\\butexmirror{${operatorTex}}`;\n index += operatorTex.length;\n continue;\n }\n\n result += tex[index];\n index += 1;\n }\n\n return result;\n}\n\nexport function atomicOperatorCommandsByCategory(\n category: AtomicOperatorCommandCategory,\n): AtomicOperatorCommandSpec[] {\n return Object.values(ATOMIC_OPERATOR_COMMANDS).filter(\n (command) => command.category === category,\n );\n}\n\nexport function atomicOperatorCommandSpec(\n id: string,\n): AtomicOperatorCommandSpec | null {\n return Object.prototype.hasOwnProperty.call(ATOMIC_OPERATOR_COMMANDS, id)\n ? ATOMIC_OPERATOR_COMMANDS[id as AtomicOperatorCommandId]\n : null;\n}\n","import type { CharacterFontId } from './types.js';\n\nexport type CharacterFontSpec = {\n id: CharacterFontId;\n label: string;\n titleKey:\n | 'defaultFont'\n | 'takweenFont'\n | 'diwaniFont'\n | 'diwaniOutlineFont'\n | 'maghribiFont';\n cssClass?: string;\n mathJaxClass?: string;\n macro?: string;\n latexFontCommand?: string;\n latexFontFamily?: string;\n browserFontStack?: string;\n importAliases?: string[];\n svgLayoutKey?: string;\n};\n\nexport const CHARACTER_FONT_SPECS: CharacterFontSpec[] = [\n {\n id: 'default',\n label: 'س',\n titleKey: 'defaultFont',\n },\n {\n id: 'takween',\n label: 'تك',\n titleKey: 'takweenFont',\n cssClass: 'node-value--takween',\n mathJaxClass: 'butex-takween-text',\n macro: '\\\\butextakween',\n latexFontCommand: '\\\\takween',\n latexFontFamily: 'Takween',\n browserFontStack: '\"BuTeX Takween\", Amiri, \"Segoe UI\", Tahoma, sans-serif',\n importAliases: ['\\\\takween'],\n svgLayoutKey: 'takween',\n },\n {\n id: 'diwani',\n label: 'ديو',\n titleKey: 'diwaniFont',\n cssClass: 'node-value--diwani',\n mathJaxClass: 'butex-diwani-text',\n macro: '\\\\butexdiwani',\n latexFontCommand: '\\\\diwani',\n latexFontFamily: 'Diwani Letter',\n browserFontStack: '\"Diwani Letter\", Amiri, \"Segoe UI\", Tahoma, sans-serif',\n importAliases: ['\\\\diwani'],\n svgLayoutKey: 'diwani',\n },\n {\n id: 'diwaniOutline',\n label: 'ظل',\n titleKey: 'diwaniOutlineFont',\n cssClass: 'node-value--diwani-outline',\n mathJaxClass: 'butex-diwani-outline-text',\n macro: '\\\\butexdiwanioutline',\n latexFontCommand: '\\\\diwanioutlineshaded',\n latexFontFamily: 'Diwani Outline Shaded',\n browserFontStack: '\"BuTeX Diwani Outline\", \"Diwani Letter\", Amiri, \"Segoe UI\", Tahoma, sans-serif',\n importAliases: ['\\\\diwanioutlineshaded'],\n svgLayoutKey: 'diwani-outline',\n },\n {\n id: 'maghribi',\n label: 'مغ',\n titleKey: 'maghribiFont',\n cssClass: 'node-value--maghribi',\n mathJaxClass: 'butex-maghribi-text',\n macro: '\\\\butexmaghribi',\n latexFontCommand: '\\\\maghribi',\n latexFontFamily: 'Almaghribi Warsh Quran',\n browserFontStack: '\"Almaghribi Warsh Quran\", Amiri, \"Segoe UI\", Tahoma, sans-serif',\n importAliases: ['\\\\maghribi'],\n svgLayoutKey: 'maghribi',\n },\n];\n\nexport const CHARACTER_FONT_OPTIONS = CHARACTER_FONT_SPECS.map(({ id, label }) => ({ id, label }));\n\nexport const NON_DEFAULT_CHARACTER_FONT_SPECS = CHARACTER_FONT_SPECS.filter(\n (font): font is CharacterFontSpec & { macro: string } => font.id !== 'default' && typeof font.macro === 'string',\n);\n\nexport function characterFontSpec(fontId: CharacterFontId): CharacterFontSpec {\n return CHARACTER_FONT_SPECS.find((font) => font.id === fontId) ?? CHARACTER_FONT_SPECS[0];\n}\n\nexport function characterFontSpecByMacro(macro: string): CharacterFontSpec | null {\n return NON_DEFAULT_CHARACTER_FONT_SPECS.find(\n (font) => font.macro === macro || font.importAliases?.includes(macro),\n ) ?? null;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const DELIMITER_CSS = `\n.delim-pair {\n display: inline-flex;\n align-items: stretch;\n min-height: 1.85em;\n}\n\n.delim-inner {\n display: inline-flex;\n align-items: center;\n}\n\n.delim {\n display: inline-flex;\n align-self: stretch;\n align-items: center;\n justify-content: center;\n color: var(--butex-delim-color, #475569);\n padding: 0 1px;\n min-height: 100%;\n}\n\n.delim-glyph {\n display: inline-flex;\n align-items: center;\n line-height: 1;\n font-size: clamp(20px, 1.08em + 0.8vh, 36px);\n transform: translateY(-20%) scaleY(var(--butex-delim-scale, 1));\n transform-origin: center;\n}\n`.trim();\n\nfunction escapeDelimiterExpr(value: string): string {\n return value.replace(/[.*+?^$()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction buildDelimiterExpr(prefixes: string[], delimiters: string[]): RegExp {\n const prefixExpr = prefixes.map(escapeDelimiterExpr).join('|');\n const delimiterExpr = delimiters.map(escapeDelimiterExpr).join('|');\n return new RegExp(`^(?:(?:${prefixExpr}))?(?:${delimiterExpr})$`);\n}\n\nexport const leftDelimExpr = buildDelimiterExpr(\n ['\\\\left', '\\\\bigl', '\\\\Bigl', '\\\\biggl', '\\\\Biggl'],\n ['(', '[', '\\\\{', '\\\\lfloor', '\\\\lceil', '\\\\langle', '`', '|', '\\\\|', '\\\\lvert', '\\\\vert', '\\\\lVert', '\\\\Vert'],\n);\nexport const rightDelimExpr = buildDelimiterExpr(\n ['\\\\right', '\\\\bigr', '\\\\Bigr', '\\\\biggr', '\\\\Biggr'],\n [')', ']', '\\\\}', '\\\\rfloor', '\\\\rceil', '\\\\rangle', '`', '|', '\\\\|', '\\\\rvert', '\\\\vert', '\\\\rVert', '\\\\Vert'],\n);\n\nconst DELIMITER_BASE_HEIGHT_PX = 18;\nconst DELIMITER_MAX_SCALE = 4.8;\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction applyDelimiterScale(pair: HTMLElement, inner: HTMLElement): void {\n const innerHeight = Math.max(inner.getBoundingClientRect().height, DELIMITER_BASE_HEIGHT_PX);\n const scale = clamp((innerHeight / DELIMITER_BASE_HEIGHT_PX) * 1.18, 1.18, DELIMITER_MAX_SCALE);\n pair.style.setProperty('--butex-delim-scale', scale.toFixed(3));\n}\n\nfunction visibleDelimiter(expr: string): string {\n return expr\n .replace(/\\\\(?:left|right|bigl|Bigl|biggl|Biggl|bigr|Bigr|biggr|Biggr)/, '')\n .replace('\\\\{', '{')\n .replace('\\\\}', '}')\n .replace(/\\\\(?:lvert|rvert|vert)/, '|')\n .replace(/\\\\(?:lVert|rVert|Vert)/, '‖')\n .replace('\\\\|', '‖');\n}\n\nexport function buildDelimiterNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const pair = document.createElement('span');\n pair.className = 'delim-pair';\n\n const left = document.createElement('span');\n left.className = 'delim delim--left';\n const leftGlyph = document.createElement('span');\n leftGlyph.className = 'delim-glyph';\n leftGlyph.textContent = visibleDelimiter(node.leftDelimExpr);\n left.appendChild(leftGlyph);\n pair.appendChild(left);\n\n const inner = document.createElement('span');\n inner.className = 'delim-inner';\n if (node.innerExpr) {\n inner.appendChild(buildChain(node.innerExpr));\n }\n pair.appendChild(inner);\n\n const right = document.createElement('span');\n right.className = 'delim delim--right';\n const rightGlyph = document.createElement('span');\n rightGlyph.className = 'delim-glyph';\n rightGlyph.textContent = visibleDelimiter(node.rightDelimExpr);\n right.appendChild(rightGlyph);\n pair.appendChild(right);\n\n applyDelimiterScale(pair, inner);\n requestAnimationFrame(() => applyDelimiterScale(pair, inner));\n\n return pair;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const BOXED_CSS = `\n.boxed-command {\n display: inline-flex;\n align-items: center;\n border: 1.5px solid currentColor;\n padding: 0.12em 0.22em;\n min-height: 1.25em;\n}\n\n.boxed-command > .chain {\n min-height: auto;\n}\n`.trim();\n\nexport function buildBoxedNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const box = document.createElement('span');\n box.className = 'boxed-command';\n if (node.innerExpr) {\n box.appendChild(buildChain(node.innerExpr));\n }\n return box;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const FRAC_CSS = `\n.frac {\n display: inline-flex;\n flex-direction: column;\n align-items: stretch;\n justify-content: center;\n vertical-align: middle;\n margin: 0 3px;\n min-width: 1.5em;\n}\n\n.frac-num,\n.frac-den {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 1.1em;\n padding: 0 4px;\n}\n\n.frac-bar {\n align-self: stretch;\n height: 1px;\n background: var(--butex-frac-bar, currentColor);\n opacity: 0.88;\n}\n`.trim();\n\nexport function buildFracNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = 'frac';\n\n const num = document.createElement('span');\n num.className = 'frac-num';\n if (node.numerator) {\n num.appendChild(buildChain(node.numerator));\n }\n\n const bar = document.createElement('span');\n bar.className = 'frac-bar';\n bar.setAttribute('aria-hidden', 'true');\n\n const den = document.createElement('span');\n den.className = 'frac-den';\n if (node.denominator) {\n den.appendChild(buildChain(node.denominator));\n }\n\n wrap.appendChild(num);\n wrap.appendChild(bar);\n wrap.appendChild(den);\n\n return wrap;\n}\n","import type { EditorChain, EditorNode, EditorSide } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const SQRT_CSS = `\n.sqrt {\n display: inline-flex;\n align-items: stretch;\n position: relative;\n vertical-align: middle;\n margin: 0 2px;\n min-height: 2.1em;\n direction: ltr;\n --butex-sqrt-scale: 1;\n}\n\n.sqrt.sqrt--english .sqrt-root {\n order: 1;\n}\n\n.sqrt.sqrt--english .sqrt-sign {\n order: 2;\n}\n\n.sqrt.sqrt--english .sqrt-radicand {\n order: 3;\n}\n\n.sqrt.sqrt--arabic .sqrt-radicand {\n order: 1;\n}\n\n.sqrt.sqrt--arabic .sqrt-sign {\n order: 2;\n}\n\n.sqrt.sqrt--arabic .sqrt-root {\n order: 3;\n}\n\n.sqrt.sqrt--arabic .sqrt-root,\n.sqrt.sqrt--arabic .sqrt-radicand {\n direction: rtl;\n}\n\n.sqrt-root {\n align-self: flex-start;\n min-width: 0.9em;\n min-height: 1em;\n margin-inline-end: -0.18em;\n transform: translate(0.16em, 0.02em);\n font-size: 0.64em;\n line-height: 1;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n position: relative;\n z-index: 1;\n}\n\n.sqrt.sqrt--arabic .sqrt-root {\n margin-inline-start: -0.22em;\n margin-inline-end: 0;\n transform: translate(-0.16em, 0.02em);\n}\n\n.sqrt-root .chain {\n min-height: auto;\n}\n\n.sqrt-sign {\n display: inline-flex;\n align-items: flex-end;\n justify-content: center;\n align-self: stretch;\n line-height: 0.78;\n font-size: 2em;\n color: var(--butex-sqrt-color, currentColor);\n transform: scaleY(var(--butex-sqrt-scale));\n transform-origin: center bottom;\n margin-inline-end: -0.24em;\n min-height: 100%;\n position: relative;\n z-index: 1;\n}\n\n.sqrt.sqrt--arabic .sqrt-sign {\n transform: scaleX(-1) scaleY(var(--butex-sqrt-scale));\n margin-inline-start: -0.24em;\n margin-inline-end: 0;\n}\n\n.sqrt-radicand {\n display: inline-flex;\n align-items: center;\n min-width: 1.35em;\n min-height: 1.35em;\n padding: 0.06em 0.24em 0;\n border-top: 2px solid var(--butex-sqrt-bar, currentColor);\n transform: translateY(-0.08em);\n position: relative;\n}\n\n.sqrt-radicand .chain {\n min-height: auto;\n}\n`.trim();\n\nconst SQRT_BASE_HEIGHT_PX = 32;\nconst SQRT_MAX_SCALE = 3.8;\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction applySqrtScale(wrap: HTMLElement, radicand: HTMLElement): void {\n const radicandHeight = Math.max(radicand.getBoundingClientRect().height, SQRT_BASE_HEIGHT_PX);\n const scale = clamp(radicandHeight / SQRT_BASE_HEIGHT_PX, 1, SQRT_MAX_SCALE);\n wrap.style.setProperty('--butex-sqrt-scale', scale.toFixed(3));\n}\n\nexport function buildSqrtNodeBody(node: EditorNode, buildChain: BuildChain, side: EditorSide): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = `sqrt sqrt--${side}`;\n\n const root = document.createElement('span');\n root.className = 'sqrt-root';\n if (node.rootIndex) {\n root.appendChild(buildChain(node.rootIndex));\n }\n\n const sign = document.createElement('span');\n sign.className = 'sqrt-sign';\n sign.setAttribute('aria-hidden', 'true');\n sign.textContent = '\\u221a';\n\n const radicand = document.createElement('span');\n radicand.className = 'sqrt-radicand';\n if (node.radicand) {\n radicand.appendChild(buildChain(node.radicand));\n }\n\n wrap.appendChild(root);\n wrap.appendChild(sign);\n wrap.appendChild(radicand);\n\n applySqrtScale(wrap, radicand);\n requestAnimationFrame(() => applySqrtScale(wrap, radicand));\n\n return wrap;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const OVERSET_CSS = `\n.overset {\n display: inline-flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n vertical-align: middle;\n margin: 0 2px;\n min-width: 1.2em;\n}\n\n.overset-over {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 0.85em;\n padding: 0 2px;\n font-size: 0.72em;\n line-height: 1.1;\n}\n\n.overset-base {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 1.05em;\n padding: 0 2px;\n}\n`.trim();\n\nexport function buildOversetNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = 'overset';\n\n const over = document.createElement('span');\n over.className = 'overset-over';\n if (node.overExpr) {\n over.appendChild(buildChain(node.overExpr));\n }\n\n const base = document.createElement('span');\n base.className = 'overset-base';\n if (node.baseExpr) {\n base.appendChild(buildChain(node.baseExpr));\n }\n\n wrap.appendChild(over);\n wrap.appendChild(base);\n return wrap;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const UNDERSET_CSS = `\n.underset {\n display: inline-flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n vertical-align: middle;\n margin: 0 2px;\n min-width: 1.2em;\n}\n\n.underset-base {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 1.05em;\n padding: 0 2px;\n}\n\n.underset-under {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 0.85em;\n padding: 0 2px;\n font-size: 0.72em;\n line-height: 1.1;\n}\n`.trim();\n\nexport function buildUndersetNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = 'underset';\n\n const base = document.createElement('span');\n base.className = 'underset-base';\n if (node.baseExpr) {\n base.appendChild(buildChain(node.baseExpr));\n }\n\n const under = document.createElement('span');\n under.className = 'underset-under';\n if (node.underExpr) {\n under.appendChild(buildChain(node.underExpr));\n }\n\n wrap.appendChild(base);\n wrap.appendChild(under);\n return wrap;\n}\n","import { accentCommandSpec } from '../accentCommands.js';\nimport type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const ACCENT_CSS = `\n.math-accent {\n display: inline-flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n vertical-align: middle;\n margin: 0 2px;\n min-width: 1.1em;\n}\n\n.math-accent-chrome {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 0.7em;\n padding: 0 2px;\n font-size: 0.85em;\n line-height: 1;\n color: var(--butex-script-color, #475569);\n user-select: none;\n}\n\n.math-accent-base {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 1.05em;\n padding: 0 2px;\n}\n\n.math-accent--under .math-accent-chrome {\n min-height: 0.45em;\n border-top: 1.5px solid currentColor;\n width: 100%;\n font-size: 0;\n color: var(--butex-surface-fg, #0f172a);\n}\n`.trim();\n\nexport function buildAccentNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const wrap = document.createElement('span');\n const spec = accentCommandSpec(node.expr);\n const placement = spec?.placement ?? 'over';\n wrap.className = placement === 'under' ? 'math-accent math-accent--under' : 'math-accent math-accent--over';\n\n const chrome = document.createElement('span');\n chrome.className = 'math-accent-chrome';\n chrome.setAttribute('aria-hidden', 'true');\n if (placement === 'over') {\n chrome.textContent = spec?.label ?? 'ˆ';\n }\n\n const base = document.createElement('span');\n base.className = 'math-accent-base';\n if (node.baseExpr) {\n base.appendChild(buildChain(node.baseExpr));\n }\n\n if (placement === 'under') {\n wrap.appendChild(base);\n wrap.appendChild(chrome);\n } else {\n wrap.appendChild(chrome);\n wrap.appendChild(base);\n }\n return wrap;\n}\n","import type { EditorChain, EditorNode, EditorSide, MatrixEnvStyle } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nconst WRAPPERS: Record<MatrixEnvStyle, { left: string; right: string }> = {\n matrix: { left: '', right: '' },\n pmatrix: { left: '(', right: ')' },\n bmatrix: { left: '[', right: ']' },\n Bmatrix: { left: '{', right: '}' },\n vmatrix: { left: '|', right: '|' },\n Vmatrix: { left: '||', right: '||' },\n};\n\nexport const MATRIX_ENV_CSS = `\n.matrix-env {\n display: inline-flex;\n align-items: stretch;\n vertical-align: middle;\n margin: 0 3px;\n --butex-matrix-delim-scale: 1.25;\n}\n\n.matrix-env__wrapper {\n display: inline-flex;\n align-self: stretch;\n align-items: center;\n justify-content: center;\n min-width: 0.42em;\n padding: 0 2px;\n color: var(--butex-delim-color, currentColor);\n font-family: ui-serif, \"Cambria Math\", \"Times New Roman\", serif;\n font-size: clamp(22px, 1.35em + 0.8vh, 42px);\n line-height: 1;\n transform: scaleY(var(--butex-matrix-delim-scale));\n transform-origin: center;\n}\n\n.matrix-env--cases .matrix-env__wrapper:empty {\n min-width: 0;\n padding: 0;\n}\n\n.matrix-env__grid {\n display: inline-grid;\n direction: ltr;\n gap: 2px 5px;\n align-items: center;\n justify-items: center;\n padding: 2px 3px;\n}\n\n.matrix-env__cell {\n min-width: 1.35em;\n min-height: 1.45em;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n border-radius: 5px;\n border: 1px dashed rgba(148, 163, 184, 0.48);\n padding: 1px 3px;\n}\n\n.matrix-env__cell .chain {\n min-height: auto;\n}\n\n.matrix-env--arabic .matrix-env__cell {\n direction: rtl;\n}\n\n.matrix-env--english .matrix-env__cell {\n direction: ltr;\n}\n`.trim();\n\nconst MATRIX_DELIMITER_BASE_HEIGHT_PX = 20;\nconst MATRIX_DELIMITER_MAX_SCALE = 5.2;\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction applyMatrixDelimiterScale(wrap: HTMLElement, grid: HTMLElement): void {\n const gridHeight = Math.max(grid.getBoundingClientRect().height, MATRIX_DELIMITER_BASE_HEIGHT_PX);\n const scale = clamp((gridHeight / MATRIX_DELIMITER_BASE_HEIGHT_PX) * 1.22, 1.25, MATRIX_DELIMITER_MAX_SCALE);\n wrap.style.setProperty('--butex-matrix-delim-scale', scale.toFixed(3));\n}\n\nexport function buildMatrixEnvNodeBody(node: EditorNode, buildChain: BuildChain, side: EditorSide): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = `matrix-env matrix-env--${side}${node.envName === 'cases' ? ' matrix-env--cases' : ''}`;\n if (node.envName === 'cases') wrap.dir = 'ltr';\n\n const style = node.envName ?? node.matrixStyle ?? 'matrix';\n const glyphs = style === 'cases'\n ? (side === 'arabic' ? { left: '', right: '}' } : { left: '{', right: '' })\n : style === 'array' || style === 'aligned' ? undefined : WRAPPERS[style];\n\n const left = document.createElement('span');\n left.className = 'matrix-env__wrapper matrix-env__wrapper--left';\n left.textContent = glyphs?.left ?? '';\n\n const grid = document.createElement('span');\n grid.className = 'matrix-env__grid';\n\n const rows = node.matrixRows ?? [];\n const columnCount = Math.max(1, ...rows.map((row) => row.length));\n grid.style.gridTemplateColumns = `repeat(${String(columnCount)}, minmax(1.35em, auto))`;\n\n const displayRows = side === 'arabic' ? rows.map((row) => row.slice().reverse()) : rows;\n for (const row of displayRows) {\n for (const cellChain of row) {\n const cell = document.createElement('span');\n cell.className = 'matrix-env__cell';\n cell.dir = side === 'arabic' ? 'rtl' : 'ltr';\n cell.appendChild(buildChain(cellChain));\n grid.appendChild(cell);\n }\n }\n\n const right = document.createElement('span');\n right.className = 'matrix-env__wrapper matrix-env__wrapper--right';\n right.textContent = glyphs?.right ?? '';\n\n wrap.appendChild(left);\n wrap.appendChild(grid);\n wrap.appendChild(right);\n\n applyMatrixDelimiterScale(wrap, grid);\n requestAnimationFrame(() => applyMatrixDelimiterScale(wrap, grid));\n\n return wrap;\n}\n","import diwaniLetterUrl from './fonts/Diwani Letter Regular.ttf';\nimport diwaniOutlineUrl from './fonts/DWNOUTSH.TTF';\nimport maghribiUrl from './fonts/Almaghribi-Warsh-Quran.otf';\nimport takweenUrl from './fonts/Takween.otf';\n\n\nexport const BUTEX_DIWANI_FONT_FAMILY = 'Diwani Letter';\nexport const BUTEX_DIWANI_OUTLINE_FONT_FAMILY = 'BuTeX Diwani Outline';\nexport const BUTEX_MAGHRIBI_FONT_FAMILY = 'Almaghribi Warsh Quran';\nexport const BUTEX_TAKWEEN_FONT_FAMILY = 'BuTeX Takween';\n\nexport const BUTEX_DIWANI_FONT_STACK = `\"${BUTEX_DIWANI_FONT_FAMILY}\", Amiri, \"Segoe UI\", Tahoma, sans-serif`;\nexport const BUTEX_DIWANI_OUTLINE_FONT_STACK = `\"${BUTEX_DIWANI_OUTLINE_FONT_FAMILY}\", \"${BUTEX_DIWANI_FONT_FAMILY}\", Amiri, \"Segoe UI\", Tahoma, sans-serif`;\nexport const BUTEX_MAGHRIBI_FONT_STACK = `\"${BUTEX_MAGHRIBI_FONT_FAMILY}\", Amiri, \"Segoe UI\", Tahoma, sans-serif`;\nexport const BUTEX_TAKWEEN_FONT_STACK = `\"${BUTEX_TAKWEEN_FONT_FAMILY}\", Amiri, \"Segoe UI\", Tahoma, sans-serif`;\n\nexport const BUTEX_DIWANI_FONT_FACE_CSS = `\n@font-face {\n font-family: \"${BUTEX_DIWANI_FONT_FAMILY}\";\n src: url(\"${diwaniLetterUrl}\") format(\"truetype\");\n font-weight: 400;\n font-style: normal;\n font-display: swap;\n}\n`.trim();\n\nexport const BUTEX_TAKWEEN_FONT_FACE_CSS = `\n@font-face {\n font-family: \"${BUTEX_TAKWEEN_FONT_FAMILY}\";\n src: url(\"${takweenUrl}\") format(\"opentype\");\n font-weight: 400;\n font-style: normal;\n font-display: swap;\n}\n`.trim();\n\nexport const BUTEX_DIWANI_OUTLINE_FONT_FACE_CSS = `\n@font-face {\n font-family: \"${BUTEX_DIWANI_OUTLINE_FONT_FAMILY}\";\n src: url(\"${diwaniOutlineUrl}\") format(\"truetype\");\n font-weight: 400;\n font-style: normal;\n font-display: swap;\n}\n`.trim();\n\nexport const BUTEX_MAGHRIBI_FONT_FACE_CSS = `\n@font-face {\n font-family: \"${BUTEX_MAGHRIBI_FONT_FAMILY}\";\n src: url(\"${maghribiUrl}\") format(\"opentype\");\n font-weight: 400;\n font-style: normal;\n font-display: swap;\n}\n`.trim();\n\nexport const BUTEX_FONT_FACE_CSS = `\n${BUTEX_DIWANI_FONT_FACE_CSS}\n\n${BUTEX_DIWANI_OUTLINE_FONT_FACE_CSS}\n\n${BUTEX_TAKWEEN_FONT_FACE_CSS}\n\n${BUTEX_MAGHRIBI_FONT_FACE_CSS}\n`.trim();\n","import { atomicCommandSpec, isSpacingCommandSpec, type AtomicCommandSpec, type SpacingCommandSpec } from '../atomicCommands.js';\nimport { BUTEX_DIWANI_FONT_STACK, BUTEX_DIWANI_OUTLINE_FONT_STACK } from '../../diwani-font.js';\nimport type { EditorNode, EditorSide } from '../types.js';\nimport type { ButexUiLocale } from '../../uiLocale.js';\nimport { atomicCommandTitle } from '../uiLocale.js';\n\nexport const ATOMIC_COMMAND_CSS = `\n/* Shared atomic-command display */\n.atomic-command {\n display: inline-flex;\n align-items: center;\n font-weight: 600;\n line-height: 1;\n}\n\n/* Function-style commands: sin/cos/tan families. */\n.atomic-command--arabic {\n font-family: ${BUTEX_DIWANI_FONT_STACK};\n font-size: 1.15em;\n direction: rtl;\n}\n\n.atomic-command--diwani-outline {\n font-family: ${BUTEX_DIWANI_OUTLINE_FONT_STACK};\n}\n\n.atomic-command--english {\n font-family: \"Cambria Math\", \"Times New Roman\", serif;\n font-size: 0.96em;\n}\n\n.atomic-command-label-with-sub {\n position: relative;\n display: inline-block;\n padding-inline-end: 0.45em;\n padding-block-end: 0.22em;\n line-height: 1;\n}\n\n.atomic-command-label-with-sub__sub {\n position: absolute;\n inset-inline-end: 0;\n inset-block-end: 0;\n font-size: 0.62em;\n line-height: 1;\n}\n\n/* Spacing commands: tiny selectable marker, real spacing remains in LaTeX preview. */\n.atomic-spacing {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 3px;\n min-width: 3px;\n height: 1em;\n color: var(--butex-accent, currentColor);\n opacity: 0.62;\n}\n\n.atomic-spacing__marker {\n display: inline-block;\n width: 3px;\n height: 0.85em;\n border-radius: 999px;\n background: currentColor;\n}\n\n.atomic-spacing--negative {\n color: var(--butex-danger, #dc2626);\n}\n`.trim();\n\nfunction spacingArrowForSide(spec: SpacingCommandSpec, side: EditorSide): string {\n const pointsWithFlow = spec.spacing.direction === 'positive';\n if (pointsWithFlow) {\n return side === 'arabic' ? '\\u2190' : '\\u2192';\n }\n return side === 'arabic' ? '\\u2192' : '\\u2190';\n}\n\nexport function spacingTooltipForSide(spec: SpacingCommandSpec, side: EditorSide, uiLocale: ButexUiLocale = 'ar'): string {\n return `${atomicCommandTitle(spec, uiLocale)} ${spacingArrowForSide(spec, side).repeat(spec.spacing.level)}`;\n}\n\nfunction buildFunctionAtomicCommandBody(node: EditorNode, side: EditorSide, spec: AtomicCommandSpec | null): HTMLElement {\n const value = document.createElement('span');\n value.className = `atomic-command atomic-command--${side}`;\n if (side === 'arabic' && spec?.category === 'groups') {\n value.classList.add('atomic-command--diwani-outline');\n }\n if (side === 'arabic' && node.expr === 'ln') {\n const label = document.createElement('span');\n label.className = 'atomic-command-label-with-sub';\n const base = document.createElement('span');\n base.className = 'atomic-command-label-with-sub__base';\n base.textContent = spec?.arabicLabel ?? node.expr;\n const sub = document.createElement('span');\n sub.className = 'atomic-command-label-with-sub__sub';\n sub.textContent = 'هـ';\n label.append(base, sub);\n value.appendChild(label);\n return value;\n }\n value.textContent = side === 'arabic'\n ? spec?.arabicLabel ?? node.expr\n : spec?.englishLabel ?? spec?.englishTex.replace(/^\\\\/, '') ?? node.expr;\n return value;\n}\n\nfunction buildSpacingAtomicCommandBody(spec: SpacingCommandSpec, side: EditorSide, uiLocale: ButexUiLocale): HTMLElement {\n const value = document.createElement('span');\n value.className = `atomic-spacing atomic-spacing--${spec.spacing.direction} atomic-spacing--level-${String(spec.spacing.level)}`;\n value.title = spacingTooltipForSide(spec, side, uiLocale);\n const marker = document.createElement('span');\n marker.className = 'atomic-spacing__marker';\n value.appendChild(marker);\n return value;\n}\n\nexport function buildAtomicCommandNodeBody(node: EditorNode, side: EditorSide, uiLocale: ButexUiLocale = 'ar'): HTMLElement {\n const spec = atomicCommandSpec(node.expr);\n if (isSpacingCommandSpec(spec)) {\n return buildSpacingAtomicCommandBody(spec, side, uiLocale);\n }\n return buildFunctionAtomicCommandBody(node, side, spec);\n}\n","import { atomicOperatorCommandSpec, shouldMirrorOperatorDisplay, type AtomicOperatorCommandSpec } from '../atomicCommandsOperators.js';\nimport type { EditorNode, EditorSide } from '../types.js';\nimport type { ButexUiLocale } from '../../uiLocale.js';\nimport { atomicOperatorCommandTitle } from '../uiLocale.js';\n\nexport const ATOMIC_OPERATOR_COMMAND_CSS = `\n.atomic-operator-command {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 0.9em;\n font-family: \"Cambria Math\", \"Times New Roman\", serif;\n font-size: 1.05em;\n font-weight: 600;\n line-height: 1;\n}\n\n.atomic-operator-command--mirrored {\n transform: scaleX(-1);\n}\n\n.atomic-operator-command__svg {\n width: 1em;\n height: 1em;\n background: currentColor;\n}\n`.trim();\n\nfunction buildOperatorLabel(spec: AtomicOperatorCommandSpec): HTMLElement {\n const value = document.createElement('span');\n value.className = 'atomic-operator-command__label';\n value.textContent = spec.Label;\n return value;\n}\n\nexport function buildAtomicOperatorCommandNodeBody(node: EditorNode, side: EditorSide, uiLocale: ButexUiLocale = 'ar'): HTMLElement {\n const spec = atomicOperatorCommandSpec(node.expr);\n const value = document.createElement('span');\n value.className = 'atomic-operator-command';\n value.title = spec ? atomicOperatorCommandTitle(spec, uiLocale) : node.expr;\n if (side === 'arabic' && shouldMirrorOperatorDisplay(spec)) {\n value.classList.add('atomic-operator-command--mirrored');\n }\n\n if (spec?.svg_path) {\n const icon = document.createElement('span');\n icon.className = 'atomic-operator-command__svg';\n icon.style.mask = `url(\"${spec.svg_path}\") center / contain no-repeat`;\n icon.style.webkitMask = `url(\"${spec.svg_path}\") center / contain no-repeat`;\n value.appendChild(icon);\n return value;\n }\n\n if (spec) {\n value.appendChild(buildOperatorLabel(spec));\n } else {\n const label = document.createElement('span');\n label.className = 'atomic-operator-command__label';\n label.textContent = node.expr;\n value.appendChild(label);\n }\n return value;\n}\n","import { standardCommandSpec } from '../standardCommands.js';\nimport type { EditorNode } from '../types.js';\n\nexport const STANDARD_COMMAND_CSS = `\n.standard-command {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 0.9em;\n font-family: \"Cambria Math\", \"Times New Roman\", serif;\n font-size: 1.05em;\n line-height: 1;\n}\n`.trim();\n\nexport function buildStandardCommandNodeBody(node: EditorNode): HTMLElement {\n const spec = standardCommandSpec(node.expr);\n const value = document.createElement('span');\n value.className = 'standard-command';\n value.title = spec?.title ?? node.expr;\n value.textContent = spec?.label ?? node.expr;\n return value;\n}\n","import { DELIMITER_CSS } from './display/delimiter.js';\nimport { BOXED_CSS } from './display/boxed.js';\nimport { FRAC_CSS } from './display/frac.js';\nimport { SQRT_CSS } from './display/sqrt.js';\nimport { OVERSET_CSS } from './display/overset.js';\nimport { UNDERSET_CSS } from './display/underset.js';\nimport { ACCENT_CSS } from './display/accent.js';\nimport { MATRIX_ENV_CSS } from './display/env.js';\nimport { ATOMIC_COMMAND_CSS } from './display/atomicCommand.js';\nimport { ATOMIC_OPERATOR_COMMAND_CSS } from './display/atomicCommandsOperators.js';\nimport { STANDARD_COMMAND_CSS } from './display/standardCommand.js';\nimport { BUTEX_FONT_FACE_CSS } from '../diwani-font.js';\nimport { NON_DEFAULT_CHARACTER_FONT_SPECS } from './characterFonts.js';\n\nconst CHARACTER_FONT_CSS = NON_DEFAULT_CHARACTER_FONT_SPECS\n .filter((font) => font.cssClass && font.browserFontStack)\n .map((font) => `.${font.cssClass} {\\n font-family: ${font.browserFontStack};\\n}`)\n .join('\\n\\n');\n\nexport const BUTEX_EDITOR_CSS = `\n${BUTEX_FONT_FACE_CSS}\n\n.surface {\n background: var(--butex-surface-bg, linear-gradient(180deg, #ffffff 0%, #fafbfc 100%));\n border: 1px solid var(--butex-border, #e2e8f0);\n border-radius: 12px;\n color: var(--butex-surface-fg, #0f172a);\n cursor: text;\n max-width: 100%;\n min-height: 100px;\n min-width: 0;\n outline: none;\n overflow-x: auto;\n overflow-y: hidden;\n overscroll-behavior-inline: contain;\n padding: 8px 10px;\n touch-action: pan-x pan-y;\n transition: box-shadow 0.15s ease, border-color 0.15s ease;\n}\n\n.surface:focus,\n.surface.surface--typing-focus {\n border-color: var(--butex-focus-border, rgba(13, 148, 136, 0.45));\n box-shadow: 0 0 0 3px var(--butex-focus-shadow, rgba(13, 148, 136, 0.12));\n}\n\n.surface.surface--arabic {\n direction: rtl;\n}\n\n.surface.surface--english {\n direction: ltr;\n}\n\n${CHARACTER_FONT_CSS}\n\n.node-value--bold {\n font-family: var(--font-display-ar, Amiri), \"Noto Serif Arabic\", serif;\n font-weight: 700;\n}\n\n.node-value--unit {\n font-style: normal;\n text-decoration-line: underline;\n text-decoration-style: dotted;\n text-underline-offset: 0.2em;\n}\n\n.chain {\n display: inline-flex;\n align-items: center;\n gap: 0;\n min-height: 28px;\n flex-wrap: wrap;\n row-gap: 2px;\n}\n\n.slot {\n width: 5px;\n min-height: 28px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n border-radius: 3px;\n}\n\n.slot:hover {\n background: var(--butex-slot-hover, rgba(13, 148, 136, 0.08));\n}\n\n.slot.range-highlight {\n background: var(--butex-selection-bg, rgba(13, 148, 136, 0.34));\n width: 11px;\n min-height: 42px;\n border: 2px solid var(--butex-selection-border, rgba(15, 118, 110, 0.9));\n position: relative;\n z-index: 1;\n}\n\n.caret {\n display: inline-block;\n width: 2px;\n height: 20px;\n background: var(--butex-caret, #0f172a);\n border-radius: 1px;\n animation: butex-editor-blink 1s step-end infinite;\n}\n\n@keyframes butex-editor-blink {\n 50% { opacity: 0; }\n}\n\n@media (prefers-reduced-motion: reduce) {\n .surface {\n scroll-behavior: auto;\n transition: none;\n }\n\n .caret {\n animation: none;\n }\n}\n\n.node {\n display: inline-flex;\n align-items: stretch;\n gap: 3px;\n border-radius: 8px;\n padding: 2px 4px;\n cursor: pointer;\n border: 1px solid transparent;\n user-select: none;\n}\n\n.node.node--atomic-spacing {\n padding-inline: 0;\n margin-inline: -2px;\n border-color: transparent;\n}\n\n.node:hover {\n border-color: var(--butex-border, #e2e8f0);\n background: var(--butex-node-hover, rgba(148, 163, 184, 0.08));\n}\n\n.node.selected {\n background: var(--butex-node-selected-bg, rgba(13, 148, 136, 0.14));\n border-color: var(--butex-node-selected-border, rgba(13, 148, 136, 0.45));\n}\n\n.node.range-highlight {\n background: var(--butex-selection-bg, rgba(13, 148, 136, 0.34));\n border-color: var(--butex-selection-border, rgba(15, 118, 110, 0.9));\n box-shadow: inset 0 0 0 3px var(--butex-selection-border, rgba(15, 118, 110, 0.9)),\n 0 0 0 1px var(--butex-selection-border, rgba(15, 118, 110, 0.9));\n position: relative;\n z-index: 2;\n}\n\n.chain .slot.range-highlight + .node.range-highlight,\n.chain .node.range-highlight + .slot.range-highlight {\n margin-inline: -1px;\n}\n\n.node-body {\n display: inline-flex;\n align-items: stretch;\n gap: 0;\n min-height: 1.6em;\n}\n\n.node-value {\n font-size: 16px;\n font-weight: 500;\n line-height: 1.25;\n display: inline-flex;\n align-items: center;\n}\n\n.scripts {\n display: flex;\n flex-direction: column;\n flex-shrink: 0;\n justify-content: space-between;\n align-items: center;\n padding: 1px 0;\n min-width: 0.75em;\n}\n\n.scripts.scripts--sup-only {\n justify-content: flex-start;\n padding-bottom: 2px;\n}\n\n.scripts.scripts--sub-only {\n justify-content: flex-end;\n padding-top: 2px;\n}\n\n.script-box {\n min-height: 12px;\n min-width: 10px;\n border-radius: 4px;\n border: 1px dashed var(--butex-script-border, #cbd5e1);\n padding: 0 2px;\n font-size: 0.68em;\n line-height: 1.15;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n background: var(--butex-script-bg, rgba(248, 250, 252, 0.95));\n color: var(--butex-script-color, #475569);\n}\n\n.script-box .chain {\n min-height: auto;\n}\n\n${DELIMITER_CSS}\n\n${BOXED_CSS}\n\n${FRAC_CSS}\n\n${SQRT_CSS}\n\n${OVERSET_CSS}\n\n${UNDERSET_CSS}\n\n${ACCENT_CSS}\n\n${MATRIX_ENV_CSS}\n\n${ATOMIC_COMMAND_CSS}\n\n${ATOMIC_OPERATOR_COMMAND_CSS}\n\n${STANDARD_COMMAND_CSS}\n`.trim();\n\n/**\n * Injects BuTeX editor surface styles into `document.head` if not already present.\n * Browser-only; no-op if `document` is undefined (Node).\n */\nexport function injectBuTeXEditorStyles(doc?: Document): void {\n const d = doc ?? (typeof document !== 'undefined' ? document : undefined);\n if (!d) {\n return;\n }\n const id = 'butex-editor-styles';\n const existing = d.getElementById(id);\n if (existing) {\n existing.textContent = BUTEX_EDITOR_CSS;\n return;\n }\n const style = d.createElement('style');\n style.id = id;\n style.textContent = BUTEX_EDITOR_CSS;\n d.head.appendChild(style);\n}\n","import type { CharacterFontId } from '../../editor/types.js';\nimport { NON_DEFAULT_CHARACTER_FONT_SPECS } from '../../editor/characterFonts.js';\n\nexport type NormalizedCharImport = {\n expr: string;\n characterFont: CharacterFontId;\n};\n\ntype WrapperSpec = {\n prefix: string;\n font?: CharacterFontId;\n};\n\nconst WRAPPER_SPECS: WrapperSpec[] = [\n ...NON_DEFAULT_CHARACTER_FONT_SPECS.flatMap((font) => [\n { prefix: font.macro, font: font.id },\n ...(font.importAliases ?? []).map((alias) => ({ prefix: alias, font: font.id })),\n ]),\n { prefix: '\\\\text' },\n];\n\nfunction readBracedArg(source: string, openBraceIndex: number): { inner: string; end: number } | null {\n if (source[openBraceIndex] !== '{') {\n return null;\n }\n\n let depth = 0;\n for (let index = openBraceIndex; index < source.length; index += 1) {\n const char = source[index];\n if (char === '{') {\n depth += 1;\n } else if (char === '}') {\n depth -= 1;\n if (depth === 0) {\n return { inner: source.slice(openBraceIndex + 1, index), end: index + 1 };\n }\n }\n }\n\n return null;\n}\n\nfunction peelWrapper(source: string): { inner: string; font?: CharacterFontId } | null {\n for (const wrapper of WRAPPER_SPECS) {\n if (!source.startsWith(wrapper.prefix)) {\n continue;\n }\n\n const braced = readBracedArg(source, wrapper.prefix.length);\n if (!braced || braced.end !== source.length) {\n continue;\n }\n\n return { inner: braced.inner, font: wrapper.font };\n }\n\n return null;\n}\n\nexport function normalizeCharImportExpr(expr: string): NormalizedCharImport {\n const original = expr;\n let current = expr;\n let characterFont: CharacterFontId = 'default';\n let changed = false;\n\n while (true) {\n const peeled = peelWrapper(current);\n if (!peeled) {\n break;\n }\n\n current = peeled.inner;\n if (peeled.font) {\n characterFont = peeled.font;\n }\n changed = true;\n }\n\n if (!changed) {\n return { expr: original, characterFont: 'default' };\n }\n\n if (current.includes('\\\\')) {\n return { expr: original, characterFont: 'default' };\n }\n\n return { expr: current, characterFont };\n}\n","import {\n BaseAstNode,\n ChainNode,\n CharNode,\n CommandNode,\n DelimiterNode,\n EnvNode,\n NumberNode,\n OperatorNode,\n} from '../../ast/arabic_ast.js';\nimport {\n accentCommandIdFromTex,\n accentCommandSpec,\n} from '../../editor/accentCommands.js';\nimport {\n ATOMIC_COMMANDS,\n atomicCommandSpec,\n type AtomicCommandId,\n} from '../../editor/atomicCommands.js';\nimport {\n ATOMIC_OPERATOR_COMMANDS,\n atomicOperatorCommandSpec,\n type AtomicOperatorCommandId,\n} from '../../editor/atomicCommandsOperators.js';\nimport { isStandardCommandTex } from '../../editor/standardCommands.js';\nimport {\n buildInitialSyncMap,\n cloneEditorSession,\n createAccentNode,\n createDelimiterNode,\n createBoxedNode,\n createEditorChain,\n createEditorNode,\n createEditorSession,\n createFracNode,\n createGridEnvNode,\n createSqrtNode,\n createOversetNode,\n createUndersetNode,\n renderArabicLatexFromSession,\n} from '../../editor/index.js';\nimport { NON_DEFAULT_CHARACTER_FONT_SPECS } from '../../editor/characterFonts.js';\nimport type {\n CharacterFontId,\n EditorChain,\n EditorNode,\n EditorSession,\n EnvColumnAlignment,\n GridEnvName,\n MatrixEnvStyle,\n} from '../../editor/index.js';\nimport { normalizeCharImportExpr } from './normalizeCharImport.js';\nimport { isValidIndexSequence } from '../../editor/indexSequence.js';\nimport type { MathNode } from './types.js';\n\ntype CommandFontPolicy = CharacterFontId | 'infer';\n\nconst COMMAND_FONT_MAP: Record<string, CommandFontPolicy> = Object.fromEntries([\n ['\\\\text', 'infer'],\n ...NON_DEFAULT_CHARACTER_FONT_SPECS.flatMap((font) => [\n [font.macro, font.id],\n ...(font.importAliases ?? []).map((alias) => [alias, font.id]),\n ]),\n]) as Record<string, CommandFontPolicy>;\n\nconst CHAR_FONT_EXPORT_TEX: Record<Exclude<CharacterFontId, 'default'>, string> = Object.fromEntries(\n NON_DEFAULT_CHARACTER_FONT_SPECS.map((font) => [font.id, font.macro]),\n) as Record<Exclude<CharacterFontId, 'default'>, string>;\n\nfunction hasBareBoldCharSource(node: EditorNode): boolean {\n return node.kind === 'char'\n && (node.wrapperCommand === '\\\\boldarabic' || node.wrapperCommand === '\\\\mathbf')\n && typeof node.sourceLatex === 'string'\n && node.sourceLatex.length > 0\n && !node.sourceLatex.startsWith('\\\\mathbf{');\n}\n\nfunction charEditorNodeToAstNode(node: EditorNode): BaseAstNode {\n const font = node.characterFont ?? 'default';\n const charNode = new CharNode(node.expr);\n if (node.wrapperCommand) {\n const wrapper = node.wrapperCommand === '\\\\boldarabic' ? '\\\\mathbf' : node.wrapperCommand;\n // Burhan's nested boldarabic{text{س}} supplies 'x' as source identity\n // for the inner character. Keep it on that character, not the enclosing\n // \\\\mathbf command: reverse conversion would otherwise replace the entire\n // styled command with an unstyled x.\n if (hasBareBoldCharSource(node)) {\n charNode.sourceLatex = node.sourceLatex!;\n }\n return new CommandNode(wrapper, [], [new ChainNode([charNode])]);\n }\n if (font === 'default') {\n return charNode;\n }\n return new CommandNode(CHAR_FONT_EXPORT_TEX[font], [], [new ChainNode([charNode])]);\n}\n\nexport type MathEditorAdapterResult =\n | { editable: true; session: EditorSession }\n | { editable: false; reason: string };\n\ntype NodeAdapterResult =\n | { editable: true; node: EditorNode }\n | { editable: false; reason: string };\n\ntype UnsupportedAdapterResult = { editable: false; reason: string };\n\nexport type MathNodeFromEditorResult =\n | { ok: true; math: MathNode }\n | { ok: false; reason: string };\n\nfunction commandIdForTex(tex: string): AtomicCommandId | null {\n for (const spec of Object.values(ATOMIC_COMMANDS)) {\n const renderTex = (spec as { arabicRenderTex?: string }).arabicRenderTex;\n if (spec.englishTex === tex || spec.arabicTex === tex || renderTex === tex) {\n return spec.id as AtomicCommandId;\n }\n }\n return null;\n}\n\nfunction operatorCommandIdForTex(tex: string): AtomicOperatorCommandId | null {\n const normalized = tex === '\\\\le' ? '\\\\leq' : tex === '\\\\ge' ? '\\\\geq' : tex;\n for (const spec of Object.values(ATOMIC_OPERATOR_COMMANDS)) {\n if (spec.Tex === normalized) {\n return spec.id as AtomicOperatorCommandId;\n }\n }\n return null;\n}\n\nfunction cloneChainWithFreshIds(chain: EditorChain): EditorChain {\n return structuredClone(chain);\n}\n\nfunction attachScripts(astNode: BaseAstNode, editorNode: EditorNode): UnsupportedAdapterResult | null {\n if (astNode.sourceLatex) {\n editorNode.sourceLatex = astNode.sourceLatex;\n }\n if (astNode.superscript) {\n const sup = chainToEditorChain(astNode.superscript, true);\n if (!sup.editable) {\n return sup;\n }\n editorNode.superscript = sup.chain;\n }\n if (astNode.subscript) {\n const sub = chainToEditorChain(astNode.subscript, true);\n if (!sub.editable) {\n return sub;\n }\n editorNode.subscript = sub.chain;\n }\n return null;\n}\n\ntype ChainAdapterResult =\n | { editable: true; chain: EditorChain }\n | { editable: false; reason: string };\n\nconst MATRIX_ENV_NAMES = new Set<GridEnvName>(['matrix', 'pmatrix', 'bmatrix', 'Bmatrix', 'vmatrix', 'Vmatrix']);\n\nfunction isGridEnvName(value: string): value is GridEnvName {\n return MATRIX_ENV_NAMES.has(value as GridEnvName) || value === 'array' || value === 'aligned' || value === 'cases';\n}\n\nfunction isMatrixEnvName(value: GridEnvName): value is MatrixEnvStyle {\n return MATRIX_ENV_NAMES.has(value);\n}\n\nfunction parseEnvOpening(opening: string): { envName: GridEnvName; alignments?: EnvColumnAlignment[] } | null {\n const match = /^\\\\begin\\{([^}]+)\\}(?:\\{([lcr]+)\\})?$/.exec(opening);\n if (!match) {\n return null;\n }\n\n const envName = match[1] ?? '';\n if (!isGridEnvName(envName)) {\n return null;\n }\n\n if (envName === 'array') {\n const spec = match[2] ?? 'c';\n return {\n envName,\n alignments: spec.split('').map((alignment) => alignment as EnvColumnAlignment),\n };\n }\n\n return { envName };\n}\n\nfunction splitEnvLine(line: ChainNode): ChainNode[] {\n const cells: ChainNode[] = [];\n let current: BaseAstNode[] = [];\n for (const node of line.chain) {\n if (node instanceof OperatorNode && node.expr === '&') {\n cells.push(new ChainNode(current));\n current = [];\n } else {\n current.push(node);\n }\n }\n cells.push(new ChainNode(current));\n return cells;\n}\n\nfunction envToEditorNode(node: EnvNode): NodeAdapterResult {\n const parsed = parseEnvOpening(node.opening);\n if (!parsed) {\n return { editable: false, reason: `بيئة رياضية غير مدعومة حاليا: ${node.opening}` };\n }\n\n const expectedClosing = `\\\\end{${parsed.envName}}`;\n if (node.closing !== expectedClosing) {\n return { editable: false, reason: `إغلاق بيئة رياضية غير مدعوم حاليا: ${node.closing}` };\n }\n\n const rowCells = node.lines.map(splitEnvLine);\n if (parsed.envName === 'cases' && (rowCells.length === 0 || rowCells.length > 12 || rowCells.some((row) => row.length !== 2))) {\n return { editable: false, reason: 'بيئة cases تتطلب تعبيرا وشرطا في كل صف (عمودان)' };\n }\n const rows = Math.max(1, rowCells.length);\n const columns = Math.max(1, ...rowCells.map((row) => row.length));\n const env = createGridEnvNode(parsed.envName, rows, columns, parsed.alignments);\n\n for (let rowIndex = 0; rowIndex < rows; rowIndex += 1) {\n const row = rowCells[rowIndex] ?? [];\n for (let columnIndex = 0; columnIndex < columns; columnIndex += 1) {\n const cell = chainToEditorChain(row[columnIndex] ?? new ChainNode());\n if (!cell.editable) {\n return cell;\n }\n env.matrixRows![rowIndex]![columnIndex] = cell.chain;\n }\n }\n\n if (parsed.envName === 'array') {\n env.columnAlignments = Array.from(\n { length: columns },\n (_, index) => parsed.alignments?.[index] ?? 'c',\n );\n }\n if (isMatrixEnvName(parsed.envName)) {\n env.matrixStyle = parsed.envName;\n }\n\n const scripts = attachScripts(node, env);\n return scripts ?? { editable: true, node: env };\n}\n\nfunction charFromTextLikeCommand(node: CommandNode): NodeAdapterResult | null {\n const commandFont = COMMAND_FONT_MAP[node.name];\n if (commandFont === undefined) {\n return null;\n }\n if (node.optionalArgs.length > 0 || node.mandatoryArgs.length !== 1) {\n return null;\n }\n\n const arg = node.mandatoryArgs[0]!;\n if (arg.chain.length !== 1) {\n return null;\n }\n\n const child = arg.chain[0]!;\n if (child instanceof CommandNode) {\n const nested = charFromTextLikeCommand(child);\n if (!nested?.editable) {\n return null;\n }\n if (commandFont !== 'infer') {\n nested.node.characterFont = commandFont;\n }\n const scripts = attachScripts(node, nested.node);\n return scripts ?? nested;\n }\n\n if (!(child instanceof CharNode)) {\n return null;\n }\n\n const normalized = normalizeCharImportExpr(child.expr);\n const characterFont = commandFont === 'infer' ? normalized.characterFont : commandFont;\n const editorNode = createEditorNode('char', normalized.expr);\n if (characterFont !== 'default') {\n editorNode.characterFont = characterFont;\n }\n const scripts = attachScripts(node, editorNode);\n return scripts ?? { editable: true, node: editorNode };\n}\n\nfunction singleCommandChar(node: CommandNode): CharNode | null {\n if (node.optionalArgs.length > 0 || node.mandatoryArgs.length !== 1) {\n return null;\n }\n const arg = node.mandatoryArgs[0]!;\n if (arg.chain.length !== 1 || !(arg.chain[0] instanceof CharNode)) {\n return null;\n }\n return arg.chain[0];\n}\n\nfunction wrappedAtomicCommandId(node: CommandNode): AtomicCommandId | null {\n if (node.name !== '\\\\mathbb' && node.name !== '\\\\mathrm') {\n return null;\n }\n const child = singleCommandChar(node);\n if (!child) {\n return null;\n }\n return commandIdForTex(`${node.name}{${child.expr}}`);\n}\n\nfunction editableWrapperCommand(node: CommandNode): NodeAdapterResult | null {\n if (\n node.name !== '\\\\mathtt' &&\n node.name !== '\\\\operatorname' &&\n node.name !== '\\\\text' &&\n node.name !== '\\\\mathsf' &&\n node.name !== '\\\\unit' &&\n node.name !== '\\\\mathbf' &&\n node.name !== '\\\\boldarabic'\n ) {\n return null;\n }\n // A mapped legacy variable may be represented as \\text{س}, sourced from x.\n // Only a canonical \\text invocation (or edited literal) is a text wrapper.\n if (node.name === '\\\\text' && node.sourceLatex && !node.sourceLatex.startsWith('\\\\text{')) {\n return null;\n }\n const child = singleCommandChar(node);\n if (node.name === '\\\\text' && child?.sourceLatex && !node.sourceLatex) return null;\n let editorNode: EditorNode;\n if (child) {\n const normalized = normalizeCharImportExpr(child.expr);\n editorNode = createEditorNode('char', normalized.expr);\n // Keep source identity when reopening an editor-exported wrapped CharObject.\n // Without it, reopening \\mathbf{س} loses the original English x.\n if (child.sourceLatex) editorNode.sourceLatex = child.sourceLatex;\n if (normalized.characterFont !== 'default') {\n editorNode.characterFont = normalized.characterFont;\n }\n } else {\n // Burhan represents mapped mathbf characters as boldarabic{text{Arabic}}\n // with source_latex on the inner text node, not as a single CharObject.\n // Import that existing supported character without discarding its identity.\n if (node.optionalArgs.length || node.mandatoryArgs.length !== 1) return null;\n const nodes = node.mandatoryArgs[0]?.chain;\n if (!nodes || nodes.length !== 1 || !(nodes[0] instanceof CommandNode)) return null;\n const nested = charFromTextLikeCommand(nodes[0]);\n if (!nested?.editable) return null;\n editorNode = nested.node;\n }\n\n editorNode.wrapperCommand = node.name === '\\\\mathsf' ? '\\\\unit'\n : node.name as NonNullable<EditorNode['wrapperCommand']>;\n\n const scripts = attachScripts(node, editorNode);\n if (scripts) {\n return scripts;\n }\n if (!editorNode.sourceLatex && node.name === '\\\\mathsf' && child) {\n editorNode.sourceLatex = `\\\\mathsf{${child.expr}}`;\n }\n return { editable: true, node: editorNode };\n}\n\nfunction commandToEditorNode(node: CommandNode): NodeAdapterResult {\n if (node.name === '\\\\frac' && node.mandatoryArgs.length >= 2) {\n const frac = createFracNode();\n const numerator = chainToEditorChain(node.mandatoryArgs[0]!);\n const denominator = chainToEditorChain(node.mandatoryArgs[1]!);\n if (!numerator.editable) {\n return numerator;\n }\n if (!denominator.editable) {\n return denominator;\n }\n frac.numerator = numerator.chain;\n frac.denominator = denominator.chain;\n const scripts = attachScripts(node, frac);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: frac };\n }\n\n if (\n (node.name === '\\\\sqrt' || node.name === '\\\\arabsqrt' || node.name === '\\\\arsqrt') &&\n node.mandatoryArgs.length >= 1\n ) {\n const sqrt = createSqrtNode();\n const radicand = chainToEditorChain(node.mandatoryArgs[0]!);\n if (!radicand.editable) {\n return radicand;\n }\n sqrt.radicand = radicand.chain;\n if (node.optionalArgs[0]) {\n const rootIndex = chainToEditorChain(node.optionalArgs[0]);\n if (!rootIndex.editable) {\n return rootIndex;\n }\n sqrt.rootIndex = rootIndex.chain;\n }\n const scripts = attachScripts(node, sqrt);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: sqrt };\n }\n\n if (node.name === '\\\\boxed' && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 1) {\n const boxed = createBoxedNode();\n const inner = chainToEditorChain(node.mandatoryArgs[0]!);\n if (!inner.editable) {\n return inner;\n }\n boxed.innerExpr = inner.chain;\n const scripts = attachScripts(node, boxed);\n return scripts ?? { editable: true, node: boxed };\n }\n\n if (node.name === '\\\\overset' && node.mandatoryArgs.length >= 2) {\n const overset = createOversetNode();\n const overExpr = chainToEditorChain(node.mandatoryArgs[0]!);\n const baseExpr = chainToEditorChain(node.mandatoryArgs[1]!);\n if (!overExpr.editable) {\n return overExpr;\n }\n if (!baseExpr.editable) {\n return baseExpr;\n }\n overset.overExpr = overExpr.chain;\n overset.baseExpr = baseExpr.chain;\n const scripts = attachScripts(node, overset);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: overset };\n }\n\n if (node.name === '\\\\underset' && node.mandatoryArgs.length >= 2) {\n const underset = createUndersetNode();\n const underExpr = chainToEditorChain(node.mandatoryArgs[0]!);\n const baseExpr = chainToEditorChain(node.mandatoryArgs[1]!);\n if (!underExpr.editable) {\n return underExpr;\n }\n if (!baseExpr.editable) {\n return baseExpr;\n }\n underset.underExpr = underExpr.chain;\n underset.baseExpr = baseExpr.chain;\n const scripts = attachScripts(node, underset);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: underset };\n }\n\n const accentId = accentCommandIdFromTex(node.name);\n if (accentId && node.mandatoryArgs.length >= 1) {\n const accent = createAccentNode(accentId);\n const baseExpr = chainToEditorChain(node.mandatoryArgs[0]!);\n if (!baseExpr.editable) {\n return baseExpr;\n }\n accent.baseExpr = baseExpr.chain;\n const scripts = attachScripts(node, accent);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: accent };\n }\n\n const wrappedAtomicId = wrappedAtomicCommandId(node);\n if (wrappedAtomicId) {\n const atomic = createEditorNode('atomicCommand', wrappedAtomicId);\n const scripts = attachScripts(node, atomic);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: atomic };\n }\n\n const wrapper = editableWrapperCommand(node);\n if (wrapper) {\n return wrapper;\n }\n\n const atomicId = commandIdForTex(node.name);\n if (atomicId && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 0) {\n const atomic = createEditorNode('atomicCommand', atomicId);\n const scripts = attachScripts(node, atomic);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: atomic };\n }\n\n const operatorId = operatorCommandIdForTex(node.name);\n if (operatorId && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 0) {\n const atomicOperator = createEditorNode('atomicOperatorCommand', operatorId);\n if (node.name === '\\\\le' || node.name === '\\\\ge') atomicOperator.sourceLatex = node.name;\n const scripts = attachScripts(node, atomicOperator);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: atomicOperator };\n }\n\n if (isStandardCommandTex(node.name) && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 0) {\n const standard = createEditorNode('standardCommand', node.name);\n const scripts = attachScripts(node, standard);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: standard };\n }\n\n const textLike = charFromTextLikeCommand(node);\n if (textLike) {\n return textLike;\n }\n\n return { editable: false, reason: `أمر رياضي غير مدعوم حاليا: ${node.name}` };\n}\n\nfunction astNodeToEditorNode(node: ChainNode['chain'][number]): NodeAdapterResult {\n if (node instanceof CharNode) {\n const normalized = normalizeCharImportExpr(node.expr);\n const editorNode = createEditorNode('char', normalized.expr);\n if (normalized.characterFont !== 'default') {\n editorNode.characterFont = normalized.characterFont;\n }\n const scripts = attachScripts(node, editorNode);\n return scripts ?? { editable: true, node: editorNode };\n }\n if (node instanceof NumberNode) {\n const editorNode = createEditorNode('number', node.expr);\n const scripts = attachScripts(node, editorNode);\n return scripts ?? { editable: true, node: editorNode };\n }\n if (node instanceof OperatorNode) {\n return { editable: true, node: createEditorNode('operator', node.expr) };\n }\n if (node instanceof DelimiterNode) {\n const editorNode = createDelimiterNode(node.leftDelimExpr, node.rightDelimExpr);\n const inner = chainToEditorChain(node.innerExpr);\n if (!inner.editable) {\n return inner;\n }\n editorNode.innerExpr = inner.chain;\n const scripts = attachScripts(node, editorNode);\n return scripts ?? { editable: true, node: editorNode };\n }\n if (node instanceof CommandNode) {\n return commandToEditorNode(node);\n }\n if (node instanceof EnvNode) {\n return envToEditorNode(node);\n }\n return { editable: false, reason: `عقدة رياضية غير مدعومة حاليا: ${node.nodeType}` };\n}\n\nconst VERTICAL_DELIMITER_COMMAND_PAIRS: Readonly<Record<string, string>> = {\n '\\\\vert': '\\\\vert',\n '\\\\lvert': '\\\\rvert',\n '\\\\Vert': '\\\\Vert',\n '\\\\lVert': '\\\\rVert',\n '\\\\|': '\\\\|',\n};\n\nfunction isBareCommand(node: BaseAstNode, name: string): node is CommandNode {\n return node instanceof CommandNode &&\n node.name === name &&\n node.optionalArgs.length === 0 &&\n node.mandatoryArgs.length === 0;\n}\n\nfunction normalizeVerticalDelimiterCommands(chain: ChainNode): ChainNode {\n const normalized: BaseAstNode[] = [];\n\n for (let index = 0; index < chain.chain.length; index += 1) {\n const left = chain.chain[index]!;\n if (!(left instanceof CommandNode) || left.superscript || left.subscript) {\n normalized.push(left);\n continue;\n }\n\n const rightName = VERTICAL_DELIMITER_COMMAND_PAIRS[left.name];\n if (!rightName || left.optionalArgs.length > 0 || left.mandatoryArgs.length > 0) {\n normalized.push(left);\n continue;\n }\n\n let rightIndex = -1;\n for (let candidate = index + 1; candidate < chain.chain.length; candidate += 1) {\n if (isBareCommand(chain.chain[candidate]!, rightName)) {\n rightIndex = candidate;\n break;\n }\n }\n\n if (rightIndex < 0) {\n normalized.push(left);\n continue;\n }\n\n const right = chain.chain[rightIndex]! as CommandNode;\n const delimiter = new DelimiterNode(\n left.name,\n new ChainNode(chain.chain.slice(index + 1, rightIndex)),\n right.name,\n );\n delimiter.superscript = right.superscript;\n delimiter.subscript = right.subscript;\n normalized.push(delimiter);\n index = rightIndex;\n }\n\n return new ChainNode(normalized);\n}\n\nfunction chainToEditorChain(chain: ChainNode, script = false): ChainAdapterResult {\n // Only a complete script wrapper is semantic; ordinary \\mathnormal font use\n // elsewhere is not silently reinterpreted as ordered indices.\n if (script && chain.chain.length === 1) {\n const wrapper = chain.chain[0]!;\n if (wrapper instanceof CommandNode && wrapper.name === '\\\\mathnormal') {\n if (wrapper.optionalArgs.length || wrapper.mandatoryArgs.length !== 1) {\n return { editable: false, reason: 'صيغة مجموعة الفهارس غير مدعومة' };\n }\n const imported = chainToEditorChain(wrapper.mandatoryArgs[0]!);\n if (!imported.editable) return imported;\n // Be compatible with older Burhan versions that stored \"23\" as one NumberObject.\n const atoms: EditorNode[] = [];\n for (const node of imported.chain.nodes) {\n if (node.kind === 'number' && /^[0-9]{2,}$/.test(node.expr)) {\n atoms.push(...node.expr.split('').map((digit) => createEditorNode('number', digit)));\n } else if (node.kind === 'char' && !node.sourceLatex && /^[A-Za-z]{2,}$/.test(node.expr)) {\n atoms.push(...node.expr.split('').map((letter) => createEditorNode('char', letter)));\n } else {\n atoms.push(node);\n }\n }\n imported.chain.nodes = atoms;\n if (!isValidIndexSequence(imported.chain)) {\n return { editable: false, reason: 'محتوى مجموعة الفهارس غير مدعوم' };\n }\n imported.chain.indexSequence = true;\n return imported;\n }\n }\n const nodes: EditorNode[] = [];\n for (const astNode of normalizeVerticalDelimiterCommands(chain).chain) {\n const converted = astNodeToEditorNode(astNode);\n if (!converted.editable) {\n return converted;\n }\n nodes.push(converted.node);\n }\n return { editable: true, chain: createEditorChain(nodes) };\n}\n\nexport function mathObjectToEditorSession(math: MathNode): MathEditorAdapterResult {\n if (math.lines.length !== 1) {\n return { editable: false, reason: 'تحرير المعادلات متعددة الأسطر داخل المستند غير مدعوم بعد' };\n }\n\n const english = chainToEditorChain(math.lines[0]!);\n if (!english.editable) {\n return english;\n }\n\n const arabic = cloneChainWithFreshIds(english.chain);\n const session = createEditorSession(english.chain, arabic, 'english');\n session.sync = buildInitialSyncMap(session.englishTree, session.arabicTree);\n return { editable: true, session: cloneEditorSession(session) };\n}\n\ntype AstNodeResult =\n | { ok: true; node: BaseAstNode }\n | { ok: false; reason: string };\n\ntype AstChainResult =\n | { ok: true; chain: ChainNode }\n | { ok: false; reason: string };\n\nfunction attachAstScripts(editorNode: EditorNode, astNode: BaseAstNode): AstNodeResult | null {\n if (editorNode.superscript) {\n const sup = editorChainToAstChain(editorNode.superscript);\n if (!sup.ok) {\n return sup;\n }\n astNode.superscript = sup.chain;\n }\n if (editorNode.subscript) {\n const sub = editorChainToAstChain(editorNode.subscript);\n if (!sub.ok) {\n return sub;\n }\n astNode.subscript = sub.chain;\n }\n return null;\n}\n\nfunction editorEnvOpening(node: EditorNode): { opening: string; closing: string } | null {\n const envName = node.envName ?? node.matrixStyle;\n if (!envName) {\n return null;\n }\n if (envName === 'array') {\n const spec = (node.columnAlignments ?? []).slice(0, node.matrixRows?.[0]?.length ?? 0).join('') || 'c';\n return { opening: `\\\\begin{array}{${spec}}`, closing: '\\\\end{array}' };\n }\n return { opening: `\\\\begin{${envName}}`, closing: `\\\\end{${envName}}` };\n}\n\nfunction editorEnvToAstNode(node: EditorNode): AstNodeResult {\n const wrapper = editorEnvOpening(node);\n if (!wrapper || !node.matrixRows) {\n return { ok: false, reason: 'بيئة رياضية غير مدعومة حاليا' };\n }\n const lines: ChainNode[] = [];\n for (const row of node.matrixRows) {\n const lineNodes: BaseAstNode[] = [];\n for (let columnIndex = 0; columnIndex < row.length; columnIndex += 1) {\n if (columnIndex > 0) {\n lineNodes.push(new OperatorNode('&'));\n }\n const cell = editorChainToAstChain(row[columnIndex]!);\n if (!cell.ok) {\n return cell;\n }\n lineNodes.push(...cell.chain.chain);\n }\n lines.push(new ChainNode(lineNodes));\n }\n const env = new EnvNode(wrapper.opening, lines, wrapper.closing);\n const scripts = attachAstScripts(node, env);\n return scripts ?? { ok: true, node: env };\n}\n\nfunction accentChainForExport(accent: EditorChain | null): AstChainResult {\n if (!accent) {\n return { ok: true, chain: new ChainNode([]) };\n }\n return editorChainToAstChain(accent);\n}\n\nfunction nodeFromAccentBase(\n command: '\\\\overset' | '\\\\underset',\n accent: ChainNode,\n base: ChainNode,\n): BaseAstNode {\n if (accent.chain.length > 0) {\n return new CommandNode(command, [], [accent, base]);\n }\n if (base.chain.length === 1) {\n return base.chain[0]!;\n }\n return new DelimiterNode('', base, '');\n}\n\nfunction editorNodeToAstNode(node: EditorNode): AstNodeResult {\n let astNode: BaseAstNode;\n\n if (node.kind === 'char') {\n astNode = charEditorNodeToAstNode(node);\n } else if (node.kind === 'number') {\n astNode = new NumberNode(node.expr);\n } else if (node.kind === 'operator') {\n astNode = new OperatorNode(node.expr);\n } else if (node.kind === 'delimiter' && node.innerExpr) {\n const inner = editorChainToAstChain(node.innerExpr);\n if (!inner.ok) {\n return inner;\n }\n astNode = new DelimiterNode(node.leftDelimExpr, inner.chain, node.rightDelimExpr);\n } else if (node.kind === 'boxed' && node.innerExpr) {\n const inner = editorChainToAstChain(node.innerExpr);\n if (!inner.ok) {\n return inner;\n }\n astNode = new CommandNode('\\\\boxed', [], [inner.chain]);\n } else if (node.kind === 'frac' && node.numerator && node.denominator) {\n const numerator = editorChainToAstChain(node.numerator);\n const denominator = editorChainToAstChain(node.denominator);\n if (!numerator.ok) {\n return numerator;\n }\n if (!denominator.ok) {\n return denominator;\n }\n astNode = new CommandNode('\\\\frac', [], [numerator.chain, denominator.chain]);\n } else if (node.kind === 'sqrt' && node.radicand) {\n const radicand = editorChainToAstChain(node.radicand);\n if (!radicand.ok) {\n return radicand;\n }\n const optionalArgs: ChainNode[] = [];\n if (node.rootIndex && node.rootIndex.nodes.length > 0) {\n const rootIndex = editorChainToAstChain(node.rootIndex);\n if (!rootIndex.ok) {\n return rootIndex;\n }\n optionalArgs.push(rootIndex.chain);\n }\n astNode = new CommandNode('\\\\sqrt', optionalArgs, [radicand.chain]);\n } else if (node.kind === 'overset' && node.baseExpr) {\n const accent = accentChainForExport(node.overExpr);\n if (!accent.ok) {\n return accent;\n }\n const baseExpr = editorChainToAstChain(node.baseExpr);\n if (!baseExpr.ok) {\n return baseExpr;\n }\n astNode = nodeFromAccentBase('\\\\overset', accent.chain, baseExpr.chain);\n } else if (node.kind === 'underset' && node.baseExpr) {\n const accent = accentChainForExport(node.underExpr);\n if (!accent.ok) {\n return accent;\n }\n const baseExpr = editorChainToAstChain(node.baseExpr);\n if (!baseExpr.ok) {\n return baseExpr;\n }\n astNode = nodeFromAccentBase('\\\\underset', accent.chain, baseExpr.chain);\n } else if (node.kind === 'accent' && node.baseExpr) {\n const tex = accentCommandSpec(node.expr)?.englishTex;\n if (!tex) {\n return { ok: false, reason: `لكنة رياضية غير مدعومة حاليا: ${node.expr}` };\n }\n const baseExpr = editorChainToAstChain(node.baseExpr);\n if (!baseExpr.ok) {\n return baseExpr;\n }\n astNode = new CommandNode(tex, [], [baseExpr.chain]);\n } else if (node.kind === 'atomicCommand') {\n const tex = atomicCommandSpec(node.expr)?.englishTex;\n if (!tex) {\n return { ok: false, reason: `أمر رياضي غير مدعوم حاليا: ${node.expr}` };\n }\n if (node.expr === 'ad') {\n astNode = new CommandNode('\\\\mathrm', [], [new ChainNode([new CharNode('d')])]);\n } else if (['N', 'Z', 'Q', 'R', 'C', 'H'].includes(node.expr)) {\n astNode = new CommandNode('\\\\mathbb', [], [new ChainNode([new CharNode(node.expr)])]);\n } else {\n astNode = new CommandNode(tex);\n }\n } else if (node.kind === 'atomicOperatorCommand') {\n const tex = atomicOperatorCommandSpec(node.expr)?.Tex;\n if (!tex) {\n return { ok: false, reason: `رمز رياضي غير مدعوم حاليا: ${node.expr}` };\n }\n astNode = new CommandNode(node.sourceLatex === '\\\\le' || node.sourceLatex === '\\\\ge' ? node.sourceLatex : tex);\n } else if (node.kind === 'standardCommand') {\n if (!isStandardCommandTex(node.expr)) {\n return { ok: false, reason: `أمر رياضي قياسي غير مدعوم حاليا: ${node.expr}` };\n }\n astNode = new CommandNode(node.expr);\n } else if (node.kind === 'env') {\n return editorEnvToAstNode(node);\n } else {\n return { ok: false, reason: `عقدة رياضية غير مدعومة حاليا: ${node.kind}` };\n }\n\n if (node.sourceLatex && !hasBareBoldCharSource(node)) {\n astNode.sourceLatex = node.sourceLatex;\n }\n const scripts = attachAstScripts(node, astNode);\n return scripts ?? { ok: true, node: astNode };\n}\n\nfunction editorChainToAstChain(chain: EditorChain): AstChainResult {\n const nodes: BaseAstNode[] = [];\n for (const editorNode of chain.nodes) {\n const converted = editorNodeToAstNode(editorNode);\n if (!converted.ok) {\n return converted;\n }\n nodes.push(converted.node);\n }\n const content = new ChainNode(nodes);\n if (chain.indexSequence && isValidIndexSequence(chain)) {\n return { ok: true, chain: new ChainNode([new CommandNode('\\\\mathnormal', [], [content])]) };\n }\n return { ok: true, chain: content };\n}\n\nexport function mathNodeFromEditorSession(\n session: EditorSession,\n mathMode = '$',\n closing = '$',\n): MathNodeFromEditorResult {\n const converted = editorChainToAstChain(session.englishTree);\n if (!converted.ok) {\n return converted;\n }\n return {\n ok: true,\n math: {\n nodeType: 'MathObject',\n mathMode,\n lines: [converted.chain],\n closing,\n },\n };\n}\n\nexport function mathSourceFromEditorSession(\n session: EditorSession,\n mathMode = '$',\n closing = '$',\n): string {\n const inner = renderArabicLatexFromSession(session);\n if (mathMode === '$' || mathMode === '\\\\(') {\n return mathMode + inner + closing;\n }\n if (mathMode === '$$' || mathMode === '\\\\[') {\n if (!inner.includes('\\n')) {\n return `${mathMode}\\n${inner}\\n${closing}`;\n }\n return `${mathMode}\\n${inner.split('\\n').map((line) => ` ${line}`).join(' \\\\\\\\\\n')}\\n${closing}`;\n }\n return `${mathMode}\\n ${inner}\\n${closing}`;\n}\n\nexport function mathSourceWithReplacement(source: string, replacementInnerLatex: string): string {\n if (source.startsWith('$$') && source.endsWith('$$')) {\n return `$$${replacementInnerLatex}$$`;\n }\n if (source.startsWith('$') && source.endsWith('$')) {\n return `$${replacementInnerLatex}$`;\n }\n if (source.startsWith('\\\\(') && source.endsWith('\\\\)')) {\n return `\\\\(${replacementInnerLatex}\\\\)`;\n }\n if (source.startsWith('\\\\[') && source.endsWith('\\\\]')) {\n return `\\\\[${replacementInnerLatex}\\\\]`;\n }\n const begin = /^\\\\begin\\{([A-Za-z*]+)\\}/.exec(source);\n if (begin) {\n const opening = begin[0] ?? '';\n const closing = `\\\\end{${begin[1] ?? ''}}`;\n if (source.endsWith(closing)) {\n return `${opening}${replacementInnerLatex}${closing}`;\n }\n }\n return replacementInnerLatex;\n}\n","import type { DocumentLabelEntry } from './labels.js';\nimport type { Reference2 } from './types.js';\n\nexport type DocumentKeyError = 'empty' | 'invalid' | 'duplicate';\n\nconst DOCUMENT_KEY_PATTERN = /^[\\p{L}\\p{M}\\p{Nd}:._-]+$/u;\n\n/** NFC-normalize and trim a document key (label or bibliography). */\nexport function normalizeDocumentKey(key: string): string {\n return key.normalize('NFC').trim();\n}\n\n/** True when key matches Unicode letters/marks, decimal digits, and :._- with no spaces. */\nexport function isValidDocumentKey(key: string): boolean {\n const normalized = normalizeDocumentKey(key);\n return normalized.length > 0 && DOCUMENT_KEY_PATTERN.test(normalized);\n}\n\nexport type DocumentKeyNamespace = {\n references?: Array<Pick<Reference2, 'id' | 'key'>>;\n labels?: Array<Pick<DocumentLabelEntry, 'ownerId' | 'key'>>;\n /** Skip this reference id when checking (editing that entry). */\n excludeReferenceId?: string;\n /** Skip this label owner id when checking (editing that float/eq). */\n excludeOwnerId?: string;\n};\n\n/** Returns true if another reference or label already uses this key (NFC match). */\nexport function isDuplicateDocumentKey(key: string, namespace: DocumentKeyNamespace): boolean {\n const normalized = normalizeDocumentKey(key);\n if (normalized.length === 0) {\n return false;\n }\n for (const reference of namespace.references ?? []) {\n if (namespace.excludeReferenceId && reference.id === namespace.excludeReferenceId) {\n continue;\n }\n if (normalizeDocumentKey(reference.key) === normalized) {\n return true;\n }\n }\n for (const label of namespace.labels ?? []) {\n if (namespace.excludeOwnerId && label.ownerId === namespace.excludeOwnerId) {\n continue;\n }\n if (normalizeDocumentKey(label.key) === normalized) {\n return true;\n }\n }\n return false;\n}\n\n/** Classify a key for UI messaging: empty, invalid charset, or duplicate. */\nexport function documentKeyError(key: string, namespace: DocumentKeyNamespace = {}): DocumentKeyError | null {\n const normalized = normalizeDocumentKey(key);\n if (normalized.length === 0) {\n return 'empty';\n }\n if (!DOCUMENT_KEY_PATTERN.test(normalized)) {\n return 'invalid';\n }\n if (isDuplicateDocumentKey(normalized, namespace)) {\n return 'duplicate';\n }\n return null;\n}\n","import { diffJson } from 'diff';\nimport { fromDocumentJson } from './importJson.js';\nimport { toDocumentJson } from './exportJson.js';\nimport type { DocumentJson } from './types.js';\n\nexport type DocumentDiffChunkKind = 'added' | 'removed' | 'context';\n\nexport type DocumentDiffChunk = {\n kind: DocumentDiffChunkKind;\n text: string;\n};\n\nexport type DocumentDiff = {\n version: 1;\n changed: boolean;\n truncated: boolean;\n chunks: DocumentDiffChunk[];\n};\n\ntype JsonDiffPart = {\n value: string;\n added?: boolean;\n removed?: boolean;\n};\n\nconst MAX_TOTAL_TEXT_CHARS = 16_000;\nconst MAX_CHANGED_CHUNK_CHARS = 4_000;\nconst MAX_CONTEXT_CHUNK_CHARS = 600;\nconst TRUNCATION_MARKER = '\\n…\\n';\nconst IDENTITY_KEYS = new Set(['id', 'inline_ids', 'caption_inline_ids', 'cell_inline_ids']);\n\ntype SliceMode = 'head' | 'tail' | 'both';\n\nfunction comparisonValue(value: unknown, key?: string): unknown {\n if (key && IDENTITY_KEYS.has(key)) {\n return undefined;\n }\n if (Array.isArray(value)) {\n return value.map((entry) => comparisonValue(entry));\n }\n if (value && typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const childKey of Object.keys(value as Record<string, unknown>).sort()) {\n const child = comparisonValue((value as Record<string, unknown>)[childKey], childKey);\n if (child !== undefined) {\n result[childKey] = child;\n }\n }\n return result;\n }\n return value;\n}\n\nfunction normalizedComparisonDocument(document: DocumentJson): Record<string, unknown> {\n return comparisonValue(toDocumentJson(fromDocumentJson(document))) as Record<string, unknown>;\n}\n\nfunction withoutFinalNewline(value: string): string {\n return value.endsWith('\\n') ? value.slice(0, -1) : value;\n}\n\nfunction shorten(text: string, limit: number, mode: SliceMode): { text: string; truncated: boolean } {\n if (text.length <= limit) {\n return { text, truncated: false };\n }\n if (limit <= TRUNCATION_MARKER.length) {\n return { text: text.slice(0, Math.max(0, limit)), truncated: true };\n }\n const available = limit - TRUNCATION_MARKER.length;\n if (mode === 'head') {\n return { text: `${text.slice(0, available)}${TRUNCATION_MARKER}`, truncated: true };\n }\n if (mode === 'tail') {\n return { text: `${TRUNCATION_MARKER}${text.slice(text.length - available)}`, truncated: true };\n }\n const head = Math.ceil(available / 2);\n const tail = available - head;\n return {\n text: `${text.slice(0, head)}${TRUNCATION_MARKER}${text.slice(text.length - tail)}`,\n truncated: true,\n };\n}\n\n/**\n * Compare two persisted Document documents using canonical Document import/export\n * semantics and jsdiff's maintained JSON diff implementation.\n *\n * Generated editor identity sidecars are intentionally excluded so equivalent\n * legacy documents do not differ merely because normalization assigned new IDs.\n */\nexport function diffDocument(before: DocumentJson, after: DocumentJson): DocumentDiff {\n const beforeComparable = normalizedComparisonDocument(before);\n const afterComparable = normalizedComparisonDocument(after);\n const parts = diffJson(beforeComparable, afterComparable) as JsonDiffPart[];\n const changed = parts.some((part) => part.added === true || part.removed === true);\n\n if (!changed) {\n return { version: 1, changed: false, truncated: false, chunks: [] };\n }\n\n const chunks: DocumentDiffChunk[] = [];\n let truncated = false;\n let totalTextChars = 0;\n\n const append = (kind: DocumentDiffChunkKind, rawText: string, limit: number, mode: SliceMode): void => {\n const cleaned = withoutFinalNewline(rawText);\n if (cleaned.length === 0) return;\n\n const perChunk = shorten(cleaned, limit, mode);\n truncated ||= perChunk.truncated;\n const remaining = MAX_TOTAL_TEXT_CHARS - totalTextChars;\n if (remaining <= 0) {\n truncated = true;\n return;\n }\n\n const withinBudget = shorten(perChunk.text, remaining, mode);\n truncated ||= withinBudget.truncated;\n if (withinBudget.text.length === 0) return;\n chunks.push({ kind, text: withinBudget.text });\n totalTextChars += withinBudget.text.length;\n };\n\n parts.forEach((part, index) => {\n if (part.added) {\n append('added', part.value, MAX_CHANGED_CHUNK_CHARS, 'both');\n return;\n }\n if (part.removed) {\n append('removed', part.value, MAX_CHANGED_CHUNK_CHARS, 'both');\n return;\n }\n\n const previousChanged = index > 0 && (parts[index - 1]?.added === true || parts[index - 1]?.removed === true);\n const nextChanged = index + 1 < parts.length && (parts[index + 1]?.added === true || parts[index + 1]?.removed === true);\n if (!previousChanged && !nextChanged) return;\n\n const mode: SliceMode = previousChanged && nextChanged ? 'both' : previousChanged ? 'head' : 'tail';\n append('context', part.value, MAX_CONTEXT_CHUNK_CHARS, mode);\n });\n\n return { version: 1, changed: true, truncated, chunks };\n}\n","import { collectDocumentLabels, collectDocumentReferenceTargets, labelNumberMap, type DocumentLabelKind } from './labels.js';\nimport type {\n DocumentBlock,\n DocumentNode,\n InlineField2,\n Reference2Json,\n} from './types.js';\n\nexport type DocumentCitationIndexEntry = {\n kind: 'cite';\n block_id: string;\n field_id: string;\n token_id: string;\n keys: string[];\n unresolved_keys: string[];\n};\n\nexport type DocumentCrossReferenceIndexEntry = {\n kind: 'ref';\n ref_command: 'ref' | 'eqref';\n block_id: string;\n field_id: string;\n token_id: string;\n keys: string[];\n unresolved_keys: string[];\n};\n\nexport type DocumentIndexedLabel = {\n key: string;\n kind: DocumentLabelKind;\n caption: string;\n number: number;\n block_id?: string;\n field_id?: string;\n token_id?: string;\n};\n\nexport type DocumentReferenceIndex = {\n citations: DocumentCitationIndexEntry[];\n cross_references: DocumentCrossReferenceIndexEntry[];\n labels: DocumentIndexedLabel[];\n reference_targets: Array<Omit<DocumentIndexedLabel, 'number'> & { number: number | null; manual_key?: string }>;\n unresolved: {\n citation_keys: string[];\n cross_reference_keys: string[];\n };\n};\n\ntype TokenLocation = {\n block_id: string;\n field_id: string;\n};\n\nfunction appendUnique(target: string[], seen: Set<string>, values: string[]): void {\n for (const value of values) {\n if (!seen.has(value)) {\n seen.add(value);\n target.push(value);\n }\n }\n}\n\n/** Return a detached, read-only view of the registered bibliography catalog. */\nexport function getDocumentReferences(document: DocumentNode): Reference2Json[] {\n return document.references.map((reference) => ({\n key: reference.key,\n authors: reference.authors,\n title: reference.title,\n year: reference.year,\n venue: reference.venue,\n url: reference.url,\n field_separator: reference.fieldSeparator,\n }));\n}\n\n/**\n * Return semantic citation, cross-reference, and label relationships without\n * changing the document. Entries follow document/token order and preserve the\n * stable IDs already present in the live Document node.\n */\nexport function getDocumentReferenceIndex(document: DocumentNode): DocumentReferenceIndex {\n const referenceKeys = new Set(document.references.map((reference) => reference.key));\n const labelEntries = collectDocumentLabels(document);\n const labelKeys = new Set(labelNumberMap(document).keys());\n const citations: DocumentCitationIndexEntry[] = [];\n const crossReferences: DocumentCrossReferenceIndexEntry[] = [];\n const tokenLocations = new Map<string, TokenLocation>();\n const unresolvedCitationKeys: string[] = [];\n const unresolvedCrossReferenceKeys: string[] = [];\n const seenCitationKeys = new Set<string>();\n const seenCrossReferenceKeys = new Set<string>();\n\n function visitField(blockId: string, field: InlineField2): void {\n for (const token of field.tokens) {\n tokenLocations.set(token.id, { block_id: blockId, field_id: field.id });\n if (token.kind === 'cite') {\n const unresolvedKeys = token.keys.filter((key) => !referenceKeys.has(key));\n citations.push({\n kind: 'cite',\n block_id: blockId,\n field_id: field.id,\n token_id: token.id,\n keys: [...token.keys],\n unresolved_keys: unresolvedKeys,\n });\n appendUnique(unresolvedCitationKeys, seenCitationKeys, unresolvedKeys);\n } else if (token.kind === 'ref') {\n const unresolvedKeys = token.keys.filter((key) => !labelKeys.has(key));\n crossReferences.push({\n kind: 'ref',\n ref_command: token.refCommand,\n block_id: blockId,\n field_id: field.id,\n token_id: token.id,\n keys: [...token.keys],\n unresolved_keys: unresolvedKeys,\n });\n appendUnique(unresolvedCrossReferenceKeys, seenCrossReferenceKeys, unresolvedKeys);\n }\n }\n }\n\n function visitBlocks(blocks: DocumentBlock[]): void {\n for (const block of blocks) {\n if (block.kind === 'textBlock') {\n visitField(block.id, block.field);\n } else if (block.kind === 'table') {\n visitField(block.id, block.captionField);\n for (const row of block.rows) {\n for (const cell of row) {\n visitField(block.id, cell);\n }\n }\n } else if (block.kind === 'image') {\n visitField(block.id, block.captionField);\n } else if (block.kind === 'list') {\n for (const item of block.items) {\n visitField(block.id, item.field);\n visitBlocks(item.blocks);\n }\n }\n }\n }\n\n visitBlocks(document.blocks);\n\n const labels: DocumentIndexedLabel[] = labelEntries.map((entry) => {\n if (entry.kind !== 'eq') {\n return {\n key: entry.key,\n kind: entry.kind,\n caption: entry.caption,\n number: entry.number,\n block_id: entry.ownerId,\n };\n }\n const location = tokenLocations.get(entry.ownerId);\n return {\n key: entry.key,\n kind: entry.kind,\n caption: entry.caption,\n number: entry.number,\n ...(location ? { block_id: location.block_id, field_id: location.field_id } : {}),\n token_id: entry.ownerId,\n };\n });\n\n return {\n citations,\n cross_references: crossReferences,\n labels,\n reference_targets: collectDocumentReferenceTargets(document).map((target) => ({\n key: target.key,\n kind: target.kind,\n caption: target.caption,\n number: target.number,\n ...(target.kind === 'eq' ? { token_id: target.ownerId } : { block_id: target.ownerId }),\n ...(target.manualKey ? { manual_key: target.manualKey } : {}),\n })),\n unresolved: {\n citation_keys: unresolvedCitationKeys,\n cross_reference_keys: unresolvedCrossReferenceKeys,\n },\n };\n}\n","/** Pure JSON and stable-identity helpers shared by book adapters. */\nconst ID = /^[A-Za-z0-9_-]{1,128}$/;\nexport function safeId(id: string): boolean {\n return ID.test(id) && !['__proto__', 'prototype', 'constructor'].includes(id);\n}\n\nexport function object(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\nexport function copy<T>(value: T): T { return JSON.parse(JSON.stringify(value)) as T; }\n","import { isValidDocumentKey } from '../document/index.js';\nimport type { BookSnapshotJson } from './contracts.js';\nimport { copy, object, safeId } from './utils.js';\n\nexport class BookContractError extends Error {\n readonly code = 'invalid_book';\n constructor(message: string) { super(message); this.name = 'BookContractError'; }\n}\n\nconst KEYS = new Set(['title-page', 'table-of-contents', 'list-of-figures', 'list-of-tables', 'bibliography']);\nconst UNIT_TYPES = new Set(['abstract', 'dedication', 'acknowledgements', 'preface', 'abbreviations', 'chapter', 'appendix', 'backmatter']);\n\n/** Structural validation is deterministic and preserves every authored title and key. */\nexport function normalizeBookSnapshot(value: unknown): BookSnapshotJson {\n if (!object(value) || !object(value.manifest) || !object(value.references) || !object(value.documents)) {\n throw new BookContractError('Book snapshot requires manifest, references and documents');\n }\n const manifest = value.manifest;\n const meta = manifest.meta;\n if (manifest.node_type !== 'BookManifest' || manifest.schema_version !== 1 ||\n typeof manifest.id !== 'string' || !safeId(manifest.id) ||\n manifest.references_path !== 'references.json' || !Array.isArray(manifest.entries) ||\n !object(meta) || typeof meta.title !== 'string' || !Array.isArray(meta.authors) ||\n !meta.authors.every(x => typeof x === 'string') || meta.language !== 'ar' || meta.direction !== 'rtl' ||\n (meta.numbering !== undefined && (!object(meta.numbering) ||\n (meta.numbering.digit_form !== undefined && !['arabicIndic', 'western'].includes(String(meta.numbering.digit_form))) ||\n (meta.numbering.chapter_heading !== undefined && !['ordinal-words', 'digits'].includes(String(meta.numbering.chapter_heading))) ||\n (meta.numbering.appendix_heading !== undefined && !['letters', 'digits'].includes(String(meta.numbering.appendix_heading)))))) {\n throw new BookContractError('Invalid BookManifest v1');\n }\n if (value.references.node_type !== 'BookReferences' || value.references.schema_version !== 1 ||\n !Array.isArray(value.references.references)) {\n throw new BookContractError('Invalid BookReferences v1');\n }\n const ids = new Set<string>();\n const generated = new Set<string>();\n const unitIds = new Set<string>();\n for (const entry of manifest.entries as unknown[]) {\n if (!object(entry) || typeof entry.id !== 'string' || !safeId(entry.id) || ids.has(entry.id)) {\n throw new BookContractError('Duplicate or unsafe book entry ID');\n }\n ids.add(entry.id);\n if (entry.kind === 'generated') {\n if (typeof entry.generated !== 'string' || !KEYS.has(entry.generated) || generated.has(entry.generated)) {\n throw new BookContractError('Invalid or repeated generated entry');\n }\n generated.add(entry.generated);\n } else if (entry.kind === 'document') {\n if (typeof entry.type !== 'string' || !UNIT_TYPES.has(entry.type) ||\n typeof entry.title !== 'string' || typeof entry.numbered !== 'boolean' ||\n typeof entry.include_in_toc !== 'boolean' ||\n entry.document_path !== 'content/units/' + entry.id + '/document.json') {\n throw new BookContractError('Invalid or unsafe unit entry');\n }\n unitIds.add(entry.id);\n } else {\n throw new BookContractError('Unknown book entry kind');\n }\n }\n const documents = value.documents;\n if (Object.keys(documents).length !== unitIds.size || Object.keys(documents).some(id => !unitIds.has(id))) {\n throw new BookContractError('Unit documents must exactly match manifest');\n }\n for (const id of unitIds) {\n const doc = documents[id];\n if (!object(doc) || doc.node_type !== 'DocumentObject' || !Array.isArray(doc.blocks)) {\n throw new BookContractError('Invalid unit DocumentJson for ' + id);\n }\n }\n for (const ref of value.references.references) {\n if (!object(ref) || typeof ref.key !== 'string' || !isValidDocumentKey(ref.key)) {\n throw new BookContractError('Invalid shared bibliography entry');\n }\n }\n return copy(value as BookSnapshotJson);\n}\n","import type { DocumentJson, Reference2Json } from '../document/index.js';\nimport type { BookEntry, BookMetaJson, BookSnapshotJson } from './contracts.js';\nimport { copy, object, safeId } from './utils.js';\nimport { BookContractError, normalizeBookSnapshot } from './validation.js';\n\nexport type BookCommand =\n | { op: 'reorder_entries'; entry_ids: string[] }\n | { op: 'update_entry'; entry_id: string; title?: string; numbered?: boolean; include_in_toc?: boolean; label?: string | null }\n | { op: 'set_meta'; meta: BookMetaJson }\n | { op: 'set_references'; references: Reference2Json[] }\n | { op: 'insert_entry'; entry: BookEntry; document?: DocumentJson; index: number }\n | { op: 'remove_entry'; entry_id: string };\n\n/** Validate untrusted book-command JSON before it reaches the typed reducer. */\nexport function parseBookCommand(value: unknown): BookCommand {\n if (!object(value) || typeof value.op !== 'string') {\n throw new BookContractError('Book command requires an operation');\n }\n const rules: Record<string, string[]> = {\n reorder_entries: ['entry_ids'],\n update_entry: ['entry_id', 'title', 'numbered', 'include_in_toc', 'label'],\n set_meta: ['meta'],\n set_references: ['references'],\n insert_entry: ['entry', 'document', 'index'],\n remove_entry: ['entry_id'],\n };\n const allowed = rules[value.op];\n if (!allowed || Object.keys(value).some(key => key !== 'op' && !allowed.includes(key))) {\n throw new BookContractError('Unsupported book command fields');\n }\n if (value.op === 'reorder_entries' &&\n (!Array.isArray(value.entry_ids) || !value.entry_ids.every(id => typeof id === 'string'))) {\n throw new BookContractError('Reorder requires entry ID list');\n }\n if (value.op === 'update_entry' &&\n (typeof value.entry_id !== 'string' || !safeId(value.entry_id) ||\n !['title', 'numbered', 'include_in_toc', 'label'].some(key => key in value) ||\n (value.title !== undefined && typeof value.title !== 'string') ||\n (value.numbered !== undefined && typeof value.numbered !== 'boolean') ||\n (value.include_in_toc !== undefined && typeof value.include_in_toc !== 'boolean') ||\n (value.label !== undefined && value.label !== null && typeof value.label !== 'string'))) {\n throw new BookContractError('Invalid book entry patch');\n }\n if (value.op === 'set_meta' && !object(value.meta)) {\n throw new BookContractError('Book metadata must be an object');\n }\n if (value.op === 'set_references' &&\n (!Array.isArray(value.references) || !value.references.every(entry => object(entry)))) {\n throw new BookContractError('Shared bibliography must be an array of entries');\n }\n if (value.op === 'insert_entry' &&\n (!object(value.entry) || !Number.isInteger(value.index) ||\n ((value.entry.kind !== 'document') && (value.entry.kind !== 'generated')) ||\n (value.entry.kind === 'document' && !object(value.document)) ||\n (value.entry.kind === 'generated' && value.document !== undefined))) {\n throw new BookContractError('Invalid book insertion command');\n }\n if (value.op === 'remove_entry' && (typeof value.entry_id !== 'string' || !safeId(value.entry_id))) {\n throw new BookContractError('Removal requires stable entry ID');\n }\n return value as BookCommand;\n}\n\n/** Commands only edit a manifest/catalog; individual Document commands remain on /v1/document. */\nexport function applyBookCommand(raw: unknown, command: BookCommand): BookSnapshotJson {\n const snapshot = normalizeBookSnapshot(raw);\n command = parseBookCommand(command);\n if (command.op === 'reorder_entries') {\n const actual = snapshot.manifest.entries.map(e => e.id);\n if (command.entry_ids.length !== actual.length ||\n new Set(command.entry_ids).size !== actual.length ||\n actual.some(id => !command.entry_ids.includes(id))) {\n throw new BookContractError('Reorder must contain every existing entry exactly once');\n }\n const byId = new Map(snapshot.manifest.entries.map(e => [e.id, e]));\n snapshot.manifest.entries = command.entry_ids.map(id => byId.get(id)!);\n } else if (command.op === 'update_entry') {\n const entry = snapshot.manifest.entries.find(e => e.id === command.entry_id);\n if (!entry || entry.kind !== 'document') throw new BookContractError('Unknown document unit');\n if (command.title !== undefined) entry.title = command.title;\n if (command.numbered !== undefined) entry.numbered = command.numbered;\n if (command.include_in_toc !== undefined) entry.include_in_toc = command.include_in_toc;\n if (command.label !== undefined) {\n if (command.label === null) delete entry.label;\n else entry.label = command.label;\n }\n } else if (command.op === 'set_meta') {\n snapshot.manifest.meta = copy(command.meta);\n } else if (command.op === 'set_references') {\n snapshot.references.references = copy(command.references);\n } else if (command.op === 'insert_entry') {\n if (!Number.isInteger(command.index) || command.index < 0 || command.index > snapshot.manifest.entries.length) {\n throw new BookContractError('Invalid insertion index');\n }\n snapshot.manifest.entries.splice(command.index, 0, copy(command.entry));\n if (command.entry.kind === 'document') {\n if (!command.document) throw new BookContractError('New document unit needs a separate DocumentJson');\n snapshot.documents[command.entry.id] = copy(command.document);\n }\n } else if (command.op === 'remove_entry') {\n const at = snapshot.manifest.entries.findIndex(e => e.id === command.entry_id);\n if (at < 0) throw new BookContractError('Unknown book entry');\n const [removed] = snapshot.manifest.entries.splice(at, 1);\n if (removed?.kind === 'document') delete snapshot.documents[removed.id];\n } else {\n throw new BookContractError('Unknown book structure operation');\n }\n return normalizeBookSnapshot(snapshot);\n}\n","import {\n collectDocumentReferenceTargets,\n fromDocumentJson,\n getDocumentReferenceIndex,\n implicitHeadingReferenceKey,\n implicitReferenceKey,\n isValidDocumentKey,\n} from '../document/index.js';\nimport type { DocumentBlockJson, DocumentBookContext, DocumentBookTarget } from '../document/index.js';\nimport type { BookSnapshotJson } from './contracts.js';\nimport { copy } from './utils.js';\nimport { BookContractError, normalizeBookSnapshot } from './validation.js';\n\nexport type BookIssue = {\n code: 'invalid_snapshot' | 'invalid_entry' | 'missing_document' | 'duplicate_entry' |\n 'duplicate_generated' | 'local_bibliography' | 'unstable_block_id' |\n 'duplicate_key' | 'invalid_key' | 'missing_citation' | 'missing_reference' |\n 'invalid_reference_kind';\n path: string;\n severity: 'error' | 'warning';\n unit_id?: string;\n block_id?: string;\n token_id?: string;\n key?: string;\n};\n\nexport type BookOutlineEntry = {\n id: string;\n kind: 'chapter' | 'appendix' | 'unit' | 'generated' | 'section' | 'subsection' | 'subsubsection';\n title: string;\n display_label: string;\n level: number;\n unit_id?: string;\n parent_unit_id?: string;\n numbered: boolean;\n include_in_toc: boolean;\n};\n\nexport type BookTarget = DocumentBookTarget & {\n numbered: boolean;\n ordinal?: string;\n};\n\nexport type BookResolution = {\n manifest_id: string;\n outline: BookOutlineEntry[];\n targets: BookTarget[];\n citations: Array<{ key: string; number: number; display_label: string }>;\n issues: BookIssue[];\n};\n\nconst LETTERS = ['أ', 'ب', 'ج', 'د', 'هـ', 'و', 'ز', 'ح', 'ط', 'ي', 'ك', 'ل', 'م', 'ن', 'س', 'ع', 'ف', 'ص', 'ق', 'ر', 'ش', 'ت', 'ث', 'خ', 'ذ', 'ض', 'ظ', 'غ'];\nconst ORDINALS = ['الأول', 'الثاني', 'الثالث', 'الرابع', 'الخامس', 'السادس', 'السابع', 'الثامن', 'التاسع', 'العاشر',\n 'الحادي عشر', 'الثاني عشر', 'الثالث عشر', 'الرابع عشر', 'الخامس عشر', 'السادس عشر', 'السابع عشر', 'الثامن عشر', 'التاسع عشر', 'العشرون'];\n\nfunction digits(value: number | string, form: 'arabicIndic' | 'western'): string {\n return form === 'western' ? String(value) : String(value).replace(/[0-9]/g, ch => '٠١٢٣٤٥٦٧٨٩'[Number(ch)]!);\n}\nfunction ordinal(number: number, form: 'arabicIndic' | 'western', style: 'ordinal-words' | 'digits'): string {\n return style === 'digits' ? digits(number, form) : ORDINALS[number - 1] ?? digits(number, form);\n}\nfunction appendix(number: number, form: 'arabicIndic' | 'western', style: 'letters' | 'digits'): string {\n return style === 'digits' ? digits(number, form) : LETTERS[number - 1] ?? digits(number, form);\n}\nfunction unitAlias(kind: 'chapter' | 'appendix', unitId: string): string {\n const hex = Array.from(new TextEncoder().encode(unitId), byte => byte.toString(16).padStart(2, '0')).join('');\n return kind + ':butex-auto-u' + hex + '-' + hex;\n}\nfunction issue(code: BookIssue['code'], path: string, extra: Partial<BookIssue> = {}): BookIssue {\n return { code, path, severity: code === 'missing_citation' || code === 'missing_reference' ? 'warning' : 'error', ...extra };\n}\n\nfunction headingKind(block: DocumentBlockJson): 'section' | 'subsection' | 'subsubsection' | null {\n if (block.command === '\\\\section') return 'section';\n if (block.command === '\\\\subsection') return 'subsection';\n if (block.command === '\\\\subsubsection') return 'subsubsection';\n return null;\n}\nfunction headingLevel(kind: 'section' | 'subsection' | 'subsubsection'): number {\n return kind === 'section' ? 1 : kind === 'subsection' ? 2 : 3;\n}\n\n/** One global, read-only catalog; no ordinals or shared bibliography are written into chapter JSON. */\nexport function resolveBookSnapshot(raw: unknown): BookResolution {\n const snapshot = normalizeBookSnapshot(raw);\n const { manifest, references, documents } = snapshot;\n const digitForm = manifest.meta.numbering?.digit_form ?? 'arabicIndic';\n const chapterStyle = manifest.meta.numbering?.chapter_heading ?? 'ordinal-words';\n const appendixStyle = manifest.meta.numbering?.appendix_heading ?? 'letters';\n const outline: BookOutlineEntry[] = [];\n const targets: BookTarget[] = [];\n const issues: BookIssue[] = [];\n const aliasOwners = new Map<string, { unitId?: string; ownerId?: string }>();\n const citationKeys = new Set<string>();\n const unnumbered = { fig: 0, tab: 0, eq: 0 };\n let chapterCount = 0;\n let appendixCount = 0;\n\n function register(key: string | undefined, unitId?: string, ownerId?: string): void {\n if (!key) return;\n if (!isValidDocumentKey(key)) {\n issues.push(issue('invalid_key', '$.references', { unit_id: unitId, block_id: ownerId, key }));\n }\n if (aliasOwners.has(key)) {\n issues.push(issue('duplicate_key', '$.references', { unit_id: unitId, block_id: ownerId, key }));\n } else {\n aliasOwners.set(key, { unitId, ownerId });\n }\n }\n for (let n = 0; n < references.references.length; n++) {\n const ref = references.references[n]!;\n citationKeys.add(ref.key);\n register(ref.key);\n }\n const citations = references.references.map((ref, i) => ({\n key: ref.key, number: i + 1, display_label: '[' + digits(i + 1, digitForm) + ']',\n }));\n\n for (const entry of manifest.entries) {\n if (entry.kind === 'generated') {\n outline.push({ id: entry.id, kind: 'generated', title: entry.generated,\n display_label: entry.generated, level: 0, numbered: false, include_in_toc: false });\n continue;\n }\n const unitId = entry.id;\n const isChapter = entry.type === 'chapter';\n const isAppendix = entry.type === 'appendix';\n if (isChapter && entry.numbered) chapterCount++;\n if (isAppendix && entry.numbered) appendixCount++;\n const chapterNumber = isChapter && entry.numbered ? chapterCount : null;\n const appendixNumber = isAppendix && entry.numbered ? appendixCount : null;\n const prefix = chapterNumber !== null ? digits(chapterNumber, digitForm)\n : appendixNumber !== null ? appendix(appendixNumber, digitForm, appendixStyle) : '';\n const generatedTitle = chapterNumber !== null ? 'الفصل ' + ordinal(chapterNumber, digitForm, chapterStyle)\n : appendixNumber !== null ? 'الملحق ' + prefix : '';\n const displayTitle = generatedTitle ? generatedTitle + ': ' + entry.title : entry.title;\n outline.push({\n id: unitId, unit_id: unitId, kind: isChapter ? 'chapter' : isAppendix ? 'appendix' : 'unit',\n title: entry.title, display_label: displayTitle, level: 0, numbered: entry.numbered,\n include_in_toc: entry.include_in_toc,\n });\n if (isChapter || isAppendix) {\n const kind = isChapter ? 'chapter' : 'appendix';\n const key = unitAlias(kind, unitId);\n targets.push({ unitId, ownerId: unitId, key, kind, caption: entry.title,\n displayLabel: generatedTitle || entry.title, numbered: entry.numbered,\n ...(prefix ? { ordinal: prefix } : {}), ...(entry.label ? { manualKey: entry.label } : {}) });\n register(key, unitId, unitId);\n register(entry.label, unitId, unitId);\n } else {\n register(entry.label, unitId, unitId);\n }\n\n const doc = documents[unitId]!;\n const seenBlocks = new Set<string>();\n const headingNumbers = { section: 0, subsection: 0, subsubsection: 0 };\n for (let b = 0; b < doc.blocks.length; b++) {\n const block = doc.blocks[b]!;\n if (!block.id || seenBlocks.has(block.id)) {\n issues.push(issue('unstable_block_id', '$.documents.' + unitId + '.blocks[' + b + ']',\n { unit_id: unitId, block_id: block.id }));\n } else seenBlocks.add(block.id);\n if (block.command === '\\\\begin{thebibliography}' || block.command === '\\\\bibliography') {\n issues.push(issue('local_bibliography', '$.documents.' + unitId + '.blocks[' + b + ']',\n { unit_id: unitId, block_id: block.id }));\n }\n const kind = headingKind(block);\n if (kind && block.id) {\n // Chapter-aware heading numbers are a projection; never persist them\n // in a unit's canonical DocumentJson or overwrite authored titles.\n if (kind === 'section') {\n headingNumbers.section++;\n headingNumbers.subsection = 0;\n headingNumbers.subsubsection = 0;\n } else if (kind === 'subsection') {\n headingNumbers.subsection++;\n headingNumbers.subsubsection = 0;\n } else {\n headingNumbers.subsubsection++;\n }\n const levels = kind === 'section' ? [headingNumbers.section]\n : kind === 'subsection' ? [headingNumbers.section, headingNumbers.subsection]\n : [headingNumbers.section, headingNumbers.subsection, headingNumbers.subsubsection];\n const ordinalLabel = [...(prefix ? [prefix] : []),\n ...levels.map(number => digits(number, digitForm))].join('.');\n const visible = 'القسم ' + ordinalLabel;\n const key = implicitHeadingReferenceKey(kind, block.id, unitId);\n const label = block.value ?? '';\n outline.push({ id: block.id, parent_unit_id: unitId, unit_id: unitId, kind,\n title: label, display_label: visible + ': ' + label, level: headingLevel(kind), numbered: true,\n include_in_toc: entry.include_in_toc });\n targets.push({ unitId, ownerId: block.id, key, kind, caption: label,\n displayLabel: visible, ordinal: ordinalLabel, numbered: true,\n ...(block.label ? { manualKey: block.label } : {}) });\n register(key, unitId, block.id);\n register(block.label, unitId, block.id);\n }\n }\n const resolved = fromDocumentJson(doc);\n const localCounts = { fig: 0, tab: 0, eq: 0 };\n for (const target of collectDocumentReferenceTargets(resolved)) {\n const key = implicitReferenceKey(target.kind, target.ownerId, unitId);\n const numbered = target.number !== null;\n if (numbered) {\n if (prefix) localCounts[target.kind]++;\n else unnumbered[target.kind]++;\n }\n const index = prefix ? localCounts[target.kind] : unnumbered[target.kind];\n const displayOrdinal = numbered ? (prefix ? prefix + '.' : '') + digits(index, digitForm) : '';\n const name = target.kind === 'fig' ? 'الشكل' : target.kind === 'tab' ? 'الجدول' : 'المعادلة';\n const displayLabel = numbered ? (target.kind === 'eq' ? name + ' (' + displayOrdinal + ')' : name + ' ' + displayOrdinal) : '';\n targets.push({ unitId, ownerId: target.ownerId, key, kind: target.kind,\n caption: target.caption, numbered, ...(displayOrdinal ? { ordinal: displayOrdinal, displayLabel } : {}),\n ...(target.manualKey ? { manualKey: target.manualKey } : {}) });\n if (numbered) {\n register(key, unitId, target.ownerId);\n register(target.manualKey, unitId, target.ownerId);\n }\n }\n }\n // Validate relationships only after seeing all units: references may point forward.\n for (const entry of manifest.entries) {\n if (entry.kind !== 'document') continue;\n const doc = fromDocumentJson(documents[entry.id]!);\n const refs = getDocumentReferenceIndex(doc);\n for (const citation of refs.citations) {\n for (const key of citation.keys) {\n if (!citationKeys.has(key)) {\n issues.push(issue('missing_citation', '$.documents.' + entry.id + '.citations', {\n unit_id: entry.id, block_id: citation.block_id, token_id: citation.token_id, key,\n }));\n }\n }\n }\n for (const reference of refs.cross_references) {\n for (const key of reference.keys) {\n const hit = targets.find(t => t.key === key || t.manualKey === key);\n if (!hit || (!hit.numbered && (hit.kind === 'fig' || hit.kind === 'tab' || hit.kind === 'eq'))) {\n issues.push(issue('missing_reference', '$.documents.' + entry.id + '.references', {\n unit_id: entry.id, block_id: reference.block_id, token_id: reference.token_id, key,\n }));\n } else if (reference.ref_command === 'eqref' && hit.kind !== 'eq') {\n issues.push(issue('invalid_reference_kind', '$.documents.' + entry.id + '.references', {\n unit_id: entry.id, block_id: reference.block_id, token_id: reference.token_id, key,\n }));\n }\n }\n }\n }\n return { manifest_id: manifest.id, outline, targets, citations, issues };\n}\n\nexport function bookContextForUnit(snapshot: BookSnapshotJson, unitId: string): DocumentBookContext {\n if (!Object.prototype.hasOwnProperty.call(snapshot.documents, unitId)) {\n throw new BookContractError('Unknown book unit: ' + unitId);\n }\n const projection = resolveBookSnapshot(snapshot);\n return { unitId, references: copy(snapshot.references.references), targets: projection.targets.map(t => ({\n unitId: t.unitId, ownerId: t.ownerId, key: t.key, kind: t.kind,\n ...(t.caption !== undefined ? { caption: t.caption } : {}),\n ...(t.displayLabel !== undefined ? { displayLabel: t.displayLabel } : {}),\n ...(t.manualKey !== undefined ? { manualKey: t.manualKey } : {}),\n })) };\n}\n\nexport function bookOutline(snapshot: unknown): BookOutlineEntry[] {\n return resolveBookSnapshot(snapshot).outline;\n}\nexport function getBookReferenceIndex(snapshot: unknown): BookResolution {\n return resolveBookSnapshot(snapshot);\n}\nexport function validateBookSnapshot(snapshot: unknown): { valid: boolean; issues: BookIssue[] } {\n const resolution = resolveBookSnapshot(snapshot);\n return { valid: resolution.issues.every(x => x.severity !== 'error'), issues: resolution.issues };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAI,SAAS;AACb,IAAM,aAAa,GAAG,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE,CAAC;AAEjF,SAAS,WAAW,QAAwB;AACjD,QAAM,KAAK,GAAG,MAAM,IAAI,UAAU,IAAI,OAAO,MAAM,CAAC;AACpD,YAAU;AACV,SAAO;AACT;;;ACFO,IAAM,sBAAsB;AAE5B,IAAM,sBAAsB;AAE5B,IAAM,wBAAwB;AAG9B,IAAM,gBAAgB,GAAG,mBAAmB;AAAA,EAAK,mBAAmB;AAAA,EAAK,qBAAqB;AAiG9F,IAAM,iBAAiB;AACvB,IAAM,iBAAiB;AAEvB,IAAM,kBAAkC;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAkBA,IAAM,qBAAmD;AAAA,EACvD,UAAU;AAAA,EACV,OAAO;AAAA,EACP,WAAW;AAAA,EACX,WAAW;AAAA,EACX,aAAa;AAAA,EACb,aAAa;AAAA,EACb,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,SAAS;AAAA,EACT,WAAW;AAAA,EACX,YAAY;AACd;AAEO,IAAM,qBAAwC;AAAA,EACnD,KAAK;AAAA,EACL,OAAO;AAAA,EACP,MAAM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