@ex-grid/sheet-xlsx 0.0.0-stage → 0.2.0-beta.3

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,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/reader.ts", "../src/column-width-unit.ts", "../src/text-casing.ts", "../src/date-formats.ts", "../src/format-parts.ts", "../src/invariant.ts", "../src/iso-date.ts", "../src/must.ts", "../src/open-error.ts", "../src/open-report.ts", "../src/sheet-format-plan.ts", "../src/sheet-elements.ts", "../src/stored-formula.ts", "../src/style-reading.ts", "../src/number-formats.ts", "../src/writer.ts", "../src/save-error.ts", "../src/save-pacer.ts", "../src/style-table.ts", "../src/written-formula.ts"],
4
+ "sourcesContent": ["import {\n CellAddress, CellBorders, CellFill, CellFont, CellRange, Culture, Entry, FormulaSyntaxError, NumberFormat, Sheet, SheetDocument,\n SheetDocumentAxisFormat, SheetDocumentCell, SheetDocumentColumnWidth, Value, WorkbookDocument,\n} from '@ex-grid/sheet-engine';\nimport {\n openXlsx, parseCell, formatCell, XlsxError,\n type XlsxCell, type XlsxColumn, type XlsxDefinedName, type XlsxFormula, type XlsxReader, type XlsxReadOptions, type XlsxRow,\n type XlsxSheetReader,\n} from '@ex-grid/data-xlsx';\nimport { readWidth } from './column-width-unit';\nimport { showsDate } from './date-formats';\nimport { defaultFormat, FormatParts } from './format-parts';\nimport { parseDouble } from './invariant';\nimport { isoDateSerial } from './iso-date';\nimport { defined, elementAt, unreachable } from './must';\nimport { XlsxOpenError } from './open-error';\nimport { OpenReport, type NotCarried, type NotCarriedKind, type UnsupportedFunctionCell, type XlsxOpenResult } from './open-report';\nimport { partsOf } from './sheet-format-plan';\nimport { elementNotCarried } from './sheet-elements';\nimport { readStoredFormula, stripPrefixes } from './stored-formula';\nimport { StyleReading, type ReadFormat } from './style-reading';\nimport { equalsIgnoreCase, foldCase, startsWithIgnoreCase } from './text-casing';\n\n// Reads an .xlsx workbook into a Workbook Document and its Open Report (ADR-0330 \u00A73, \u00A74, \u00A75, \u00A77), as ExSheet.Xlsx's\n// XlsxWorkbookReader reads it. Every worksheet becomes a Sheet, in the file's order, and the worksheet shown is the Sheet\n// shown. Constants \u2014 numbers, text, booleans, Error Values \u2014 and Formulas are carried, never a Value the file stored: opening\n// the document computes every Value again. Anything that would change a Value is refused by name, naming the Sheet, the cell\n// and what it held, and nothing opens. What changes only how a Sheet looks, or what else the file held, is listed in the\n// Open Report. Cell Formats cross at the levels the file records them \u2014 cell, row and column \u2014 with the column widths, in\n// Excel's own unit (ADR-0071); a colour that names the theme is the RGB the file's theme gives it (ADR-0330 \u00A78).\n\n/**\n * Reads the workbook in `file` into a Workbook Document under `culture`, with its Open Report, or refuses it by name\n * (`XlsxOpenError`). The read goes a batch of cells at a time, reporting progress and yielding between slices as `options`\n * says, so a browser keeps painting while a large file is read.\n *\n * @param file - The file's bytes.\n * @param culture - The Workbook's culture, declared by the application as a CSV's encoding is (ADR-0330 \u00A77): how typing is\n * read and Values are shown from here on. No Value read from the file depends on it, and nothing in the file is taken for\n * it. A locale the engine holds no data for throws a `RangeError` before the file is read.\n * @param options - The file layer's limits, progress, pacing and cancellation (ADR-0330 \u00A79); its defaults when left out. An\n * aborted `signal` is looked at between slices, and a cancelled read opens nothing.\n * @returns The Workbook Document and its Open Report.\n * @throws XlsxOpenError - The workbook is refused, and nothing opens.\n */\nexport async function openXlsxWorkbook(file: Uint8Array | ArrayBuffer | Blob, culture: Culture | string, options?: XlsxReadOptions): Promise<XlsxOpenResult> {\n // Refused before the file is read: a document under a culture the engine cannot name could not be opened.\n const workbookCulture = typeof culture === 'string' ? Culture.of(culture) : culture;\n let reader: XlsxReader;\n try {\n reader = await openXlsx(file, options);\n } catch (e) {\n if (e instanceof XlsxError) throw XlsxOpenError.fromFile(e);\n throw e;\n }\n try {\n return await new Mapping(reader, workbookCulture, options?.signal).read();\n } catch (e) {\n if (e instanceof XlsxError) throw XlsxOpenError.fromFile(e);\n throw e;\n }\n}\n\n/** How many days the 1904 date system's serials lie below 1900's for the same day. */\nconst days1904 = 1462;\n\nconst filterDatabase = '_xlnm._FilterDatabase';\nconst printArea = '_xlnm.Print_Area';\nconst printTitles = '_xlnm.Print_Titles';\n\n/** A format not carried, by kind, with the first place it was met. */\ninterface FormatNotCarried {\n readonly kind: NotCarriedKind;\n readonly detail: string;\n}\n\n/**\n * The formats the columns record, by column, with the parts any of them records: a formatted row records those parts even\n * at their defaults, because in the file a row's format stands in place of its columns', where in a Sheet each part of a\n * row's level that records nothing takes the column's.\n */\ninterface ColumnLevels {\n readonly byColumn: ReadonlyMap<number, FormatParts>;\n readonly runs: readonly SheetDocumentAxisFormat[];\n readonly recorded: FormatParts;\n}\n\n/** A shared formula's master: its Entry where it stands, and what it names. */\ninterface SharedMaster {\n readonly entry: Entry;\n readonly row: number;\n readonly column: number;\n readonly unsupported: readonly string[];\n}\n\n/** One workbook's mapping, Sheet by Sheet. */\nclass Mapping {\n readonly #reader: XlsxReader;\n readonly #culture: Culture;\n readonly #signal: AbortSignal | undefined;\n readonly #notCarried: NotCarried[] = [];\n readonly #unsupported: UnsupportedFunctionCell[] = [];\n readonly #definedNames: ReadonlySet<string>;\n readonly #hasExcelTables: boolean;\n readonly #dateStyles = new Map<number, boolean>();\n readonly #styles: StyleReading;\n #namesTheme = false;\n\n constructor(reader: XlsxReader, culture: Culture, signal: AbortSignal | undefined) {\n this.#reader = reader;\n this.#culture = culture;\n this.#signal = signal;\n this.#definedNames = new Set(reader.definedNames.map(n => foldCase(n.name)));\n this.#hasExcelTables = reader.parts.some(p => startsWithIgnoreCase(p, 0, 'xl/tables/'));\n this.#styles = new StyleReading(reader.styles, reader.theme);\n }\n\n async read(): Promise<XlsxOpenResult> {\n const reader = this.#reader;\n const worksheets: number[] = [];\n const names = new Map<string, string>();\n for (let i = 0; i < reader.sheets.length; i++) {\n const info = elementAt(reader.sheets, i);\n if (info.kind !== 'worksheet' || info.part === null) {\n this.#notCarried.push({\n kind: 'chartSheet', sheet: info.name, detail: null,\n description: `The sheet '${info.name}' is not a worksheet (a chart sheet, or another that holds no cells), and is not opened.`,\n });\n continue;\n }\n const why = Sheet.whyNotAName(info.name);\n if (why !== undefined) throw new XlsxOpenError('sheets', `The worksheet's name is not one a Sheet can have: ${why}`, { sheet: info.name });\n const same = names.get(foldCase(info.name));\n if (same !== undefined) {\n throw new XlsxOpenError('sheets',\n `The worksheets '${same}' and '${info.name}' have names that differ only in case, which two Sheets of one Workbook cannot have.`, { sheet: info.name });\n }\n names.set(foldCase(info.name), info.name);\n worksheets.push(i);\n }\n if (worksheets.length === 0) throw new XlsxOpenError('sheets', 'The workbook holds no worksheet, so it holds no cells to open.');\n\n this.#workbookParts();\n for (const name of reader.definedNames) {\n // A name local to a worksheet is said with that Sheet's entries; one of the workbook's, or of a chart sheet, here.\n const local = name.localSheet;\n if (local !== null && worksheets.includes(local)) continue;\n const shown = builtInName(name);\n if (shown === undefined) continue;\n const sheet = local !== null && local >= 0 && local < reader.sheets.length ? elementAt(reader.sheets, local).name : null;\n this.#notCarried.push({ kind: 'definedName', sheet, detail: shown, description: describeName(name, shown, sheet) });\n }\n const workbookEntries = this.#notCarried.length;\n const sheets: SheetDocument[] = [];\n for (const index of worksheets) {\n const info = elementAt(reader.sheets, index);\n if (info.visibility !== 'visible') {\n this.#notCarried.push({ kind: 'hiddenSheet', sheet: info.name, detail: null, description: `The Sheet '${info.name}' is hidden in the file, and opens shown.` });\n }\n let printNames = false;\n for (const name of reader.definedNames) {\n if (name.localSheet !== index) continue;\n if (equalsIgnoreCase(name.name, printArea) || equalsIgnoreCase(name.name, printTitles)) {\n printNames = true;\n } else {\n const shown = builtInName(name);\n if (shown !== undefined) {\n this.#notCarried.push({ kind: 'definedName', sheet: info.name, detail: shown, description: describeName(name, shown, info.name) });\n }\n }\n }\n sheets.push(await this.#readSheet(index, printNames));\n }\n if (this.#namesTheme) {\n // Said of the whole workbook, with what else it holds, before each Sheet's entries.\n this.#notCarried.splice(workbookEntries, 0, {\n kind: 'themeColours', sheet: null, detail: null,\n description: 'Colours of the workbook name its theme: each is carried as the RGB value the file\\'s theme gives it, and the link to the theme is not, so another theme will not recolour them.',\n });\n }\n const shownIndex = worksheets.includes(reader.activeSheet) ? reader.activeSheet : elementAt(worksheets, 0);\n const document = WorkbookDocument.of(this.#culture, elementAt(reader.sheets, shownIndex).name, sheets);\n return { document, report: new OpenReport(this.#notCarried, this.#unsupported) };\n }\n\n /** What the workbook as a whole holds, beside its sheets, as its parts say. */\n #workbookParts(): void {\n const parts = this.#reader.parts;\n const has = (folder: string): boolean => parts.some(p => startsWithIgnoreCase(p, 0, folder));\n const add = (kind: NotCarriedKind, description: string): void => {\n this.#notCarried.push({ kind, sheet: null, detail: null, description });\n };\n if (has('xl/pivotTables/')) add('pivotTables', 'The workbook holds PivotTables: the cells they show are carried as constants, the PivotTables are not.');\n if (has('xl/externalLinks/')) add('externalLinks', 'The workbook holds links to other workbooks, which no Formula carried reads; they are not carried.');\n if (has('xl/connections.xml') || has('xl/queryTables/')) {\n add('dataConnections', 'The workbook holds connections to outside data, which are not carried; the cells they filled are carried as constants.');\n }\n if (has('xl/slicers/') || has('xl/slicerCaches/') || has('xl/timelines/') || has('xl/timelineCaches/')) {\n add('slicers', 'The workbook holds slicers or timelines, which are not carried.');\n }\n }\n\n async #readSheet(index: number, printNames: boolean): Promise<SheetDocument> {\n const sheet = await this.#reader.openSheet(index);\n try {\n const name = sheet.sheet.name;\n const cells: SheetDocumentCell[] = [];\n const shared = new Map<number, SharedMaster>();\n let spills: CellRange[] = [];\n let spillRow = -1;\n let richCells = 0;\n let firstRich: string | undefined;\n const formats: FormatNotCarried[] = [];\n let columns: ColumnLevels | undefined;\n const rowRuns: SheetDocumentAxisFormat[] = [];\n const rowLevels = new Map<number, FormatParts>();\n let lastRow: { readonly row: number; readonly level: FormatParts } | undefined;\n while (await sheet.read()) {\n this.#signal?.throwIfAborted();\n // The columns come before the cells, complete once the first batch is read.\n columns ??= this.#readColumns(name, sheet.columns, formats);\n // A row is begun in the batch of its first cell or an earlier one; only the last row begun can hold cells of a later batch.\n rowLevels.clear();\n if (lastRow !== undefined) rowLevels.set(lastRow.row, lastRow.level);\n for (const row of sheet.rows) {\n const level = this.#readRow(name, row, columns, formats);\n rowLevels.set(row.row, level);\n lastRow = { row: row.row, level };\n addRun(rowRuns, row.row, level);\n }\n for (const cell of sheet.cells) {\n const at = formatCell(cell.row, cell.column);\n if (cell.isRichText) {\n richCells++;\n firstRich ??= at;\n }\n if (cell.row !== spillRow) {\n // Cells come row by row: a Spill Range whose last row lies above this one is behind the reader for good.\n spillRow = cell.row;\n if (spills.length > 0) spills = spills.filter(s => s.last.row >= spillRow);\n }\n const address = new CellAddress(cell.row, cell.column);\n const entry = cell.formula !== null\n ? this.#formulaEntry(name, cell, at, cell.formula, shared, spills)\n : insideSpill(spills, address) ? undefined : this.#constant(name, cell, at);\n const rowLevel = rowLevels.get(cell.row);\n const own = this.#readCell(name, cell, at, columns, rowLevel === undefined ? FormatParts.empty : rowLevel, formats);\n if (entry !== undefined || !own.isEmpty) {\n cells.push(new SheetDocumentCell(address, entry, own.numberFormat, own.alignment, own.font, own.fill, own.borders));\n }\n }\n }\n columns ??= this.#readColumns(name, sheet.columns, formats);\n this.#sheetElements(name, sheet, richCells, firstRich, printNames, formats);\n return SheetDocument.of(this.#culture, name, cells, { columns: columns.runs, rows: rowRuns, columnWidths: widths(sheet.columns) });\n } finally {\n await sheet.close();\n }\n }\n\n /** The cell format at `style`, refusing the file where a level records a Number Format that cannot cross. */\n #format(sheet: string, style: number, place: string, formats: FormatNotCarried[]): ReadFormat {\n const format = this.#styles.at(style);\n if (format.refusal !== undefined) throw new XlsxOpenError('numberFormat', format.refusal, { sheet, cell: place, held: format.held });\n this.#namesTheme ||= format.namesTheme;\n for (const kind of format.notCarried) {\n if (!formats.some(f => f.kind === kind)) formats.push({ kind, detail: place });\n }\n return format;\n }\n\n #readColumns(sheet: string, columns: readonly XlsxColumn[], formats: FormatNotCarried[]): ColumnLevels {\n const byColumn = new Map<number, FormatParts>();\n const runs: SheetDocumentAxisFormat[] = [];\n for (const range of byFirst(columns)) {\n if (range.styleIndex === 0) continue;\n const place = `${CellAddress.columnName(range.first)}:${CellAddress.columnName(range.last)}`;\n const level = FormatParts.differing(this.#format(sheet, range.styleIndex, place, formats).format, defaultFormat);\n if (level.isEmpty) continue;\n for (let c = range.first; c <= range.last; c++) byColumn.set(c, level);\n const last = runs.at(-1);\n if (last !== undefined && last.last === range.first - 1 && partsOf(last).equals(level)) {\n runs[runs.length - 1] = axisFormat(last.first, range.last, level);\n } else {\n runs.push(axisFormat(range.first, range.last, level));\n }\n }\n const recorded = new FormatParts(\n runs.some(r => r.numberFormat !== undefined) ? NumberFormat.general : undefined,\n runs.some(r => r.alignment !== undefined) ? 'general' : undefined,\n runs.some(r => r.font !== undefined) ? CellFont.default : undefined,\n runs.some(r => r.fill !== undefined) ? CellFill.none : undefined,\n runs.some(r => r.borders !== undefined) ? CellBorders.none : undefined);\n return { byColumn, runs, recorded };\n }\n\n /**\n * A formatted row's level: each part that differs from the default, and each part a column records, so that the row\n * stands in place of its columns as in the file.\n */\n #readRow(sheet: string, row: XlsxRow, columns: ColumnLevels, formats: FormatNotCarried[]): FormatParts {\n const number = String(row.row + 1);\n const format = this.#format(sheet, row.styleIndex, `${number}:${number}`, formats).format;\n const differing = FormatParts.differing(format, defaultFormat);\n const recorded = columns.recorded;\n return new FormatParts(\n differing.numberFormat ?? (recorded.numberFormat === undefined ? undefined : format.numberFormat),\n differing.alignment ?? (recorded.alignment === undefined ? undefined : format.alignment),\n differing.font ?? (recorded.font === undefined ? undefined : format.font),\n differing.fill ?? (recorded.fill === undefined ? undefined : format.fill),\n differing.borders ?? (recorded.borders === undefined ? undefined : format.borders));\n }\n\n /** A cell's own level: the parts of its format that differ from what its row and column give it. In the file a cell's format stands alone. */\n #readCell(sheet: string, cell: XlsxCell, at: string, columns: ColumnLevels, row: FormatParts, formats: FormatNotCarried[]): FormatParts {\n const format = this.#format(sheet, cell.styleIndex, at, formats).format;\n const level = columns.byColumn.get(cell.column);\n const column = level === undefined ? FormatParts.empty : level;\n return FormatParts.differing(format, row.over(column.over(defaultFormat)));\n }\n\n #formulaEntry(sheet: string, cell: XlsxCell, at: string, formula: XlsxFormula, shared: Map<number, SharedMaster>, spills: CellRange[]): Entry {\n switch (formula.kind) {\n case 'dataTable':\n throw new XlsxOpenError('unreadableFormula', 'The cell is part of a What-If data table, which the engine does not compute.',\n { sheet, cell: at, held: held(formula.text) });\n case 'array':\n if (!formula.isDynamicArray) {\n throw new XlsxOpenError('legacyArrayFormula',\n 'The cell holds a legacy array formula (entered with Ctrl+Shift+Enter), which Excel computes as one over its cells and ExSheet would spill instead.',\n { sheet, cell: at, held: `{${held(formula.text)}}` });\n }\n break;\n case 'shared':\n if (formula.text.length === 0) {\n const master = formula.sharedIndex === null ? undefined : shared.get(formula.sharedIndex);\n if (master === undefined) {\n const index = formula.sharedIndex === null ? '' : String(formula.sharedIndex);\n throw new XlsxOpenError('unreadableFormula', `The cell takes the shared formula ${index}, whose first cell does not come before it.`, { sheet, cell: at });\n }\n const moved = master.entry.movedBy(cell.row - master.row, cell.column - master.column);\n this.#report(sheet, at, master.unsupported);\n return moved;\n }\n break;\n case 'normal':\n break;\n }\n const { entry, unsupported } = this.#readFormula(sheet, at, formula.text);\n this.#report(sheet, at, unsupported);\n if (formula.kind === 'shared' && formula.sharedIndex !== null) {\n shared.set(formula.sharedIndex, { entry, row: cell.row, column: cell.column, unsupported });\n }\n if (formula.kind === 'array' && formula.reference !== null) {\n const spill = rangeOf(formula.reference);\n if (spill !== undefined) spills.push(spill);\n }\n return entry;\n }\n\n /** Reads a Formula's stored text into its Entry, refusing what would read wrongly, with the functions it names that ExSheet does not support. */\n #readFormula(sheet: string, at: string, stored: string): { readonly entry: Entry; readonly unsupported: readonly string[] } {\n const { read: text, problem } = readStoredFormula(stored);\n const where = { sheet, cell: at, held: text };\n switch (problem) {\n case 'otherWorkbook':\n throw new XlsxOpenError('otherWorkbook', 'The Formula reads another workbook, which ExSheet cannot reach.', where);\n case 'excelTable':\n throw new XlsxOpenError('excelTable', 'The Formula reads an Excel Table, which ExSheet does not read.', where);\n case 'implicitIntersection':\n throw new XlsxOpenError('unreadableFormula', 'The Formula uses the implicit intersection operator (@), which the engine does not read.', where);\n case 'spillRange':\n throw new XlsxOpenError('unreadableFormula', 'The Formula reads a Spill Range in a form the engine does not read.', where);\n case 'none':\n break;\n }\n let entry: Entry;\n try {\n entry = defined(Entry.parse(text, Culture.invariant), 'the Entry of a Formula');\n } catch (e) {\n if (e instanceof FormulaSyntaxError) throw new XlsxOpenError('unreadableFormula', `The engine cannot read the Formula: ${e.message}`, where, { cause: e });\n throw e;\n }\n for (const name of entry.unboundNames) {\n if (this.#definedNames.has(foldCase(name))) {\n throw new XlsxOpenError('definedName', `The Formula reads the defined name '${name}', which ExSheet does not define.`, where);\n }\n if (this.#hasExcelTables) {\n throw new XlsxOpenError('excelTable',\n `The Formula reads the name '${name}', which the workbook does not define; it holds Excel Tables, which a name can read, and ExSheet does not read them.`,\n where);\n }\n }\n const functions = entry.undeclaredFunctions;\n const lambda = functions.find(f => this.#definedNames.has(foldCase(f)));\n if (lambda !== undefined) throw new XlsxOpenError('definedName', `The Formula calls the defined name '${lambda}', which ExSheet does not define.`, where);\n return { entry, unsupported: functions };\n }\n\n #report(sheet: string, cell: string, functions: readonly string[]): void {\n if (functions.length > 0) this.#unsupported.push({ sheet, cell, functions });\n }\n\n /** A constant's Entry, or `undefined` for a cell that holds none (a cell with a style only). */\n #constant(sheet: string, cell: XlsxCell, at: string): Entry | undefined {\n const value = cell.value;\n switch (cell.type) {\n case 'sharedString':\n case 'inlineString':\n // A string cell with no text is the empty text, as the file layer and ExSheet.Xlsx read it.\n return Entry.fromValue(Value.fromText(cell.text === null ? '' : cell.text));\n case 'formulaString':\n return value === null ? undefined : Entry.fromValue(Value.fromText(value));\n case 'number': {\n if (value === null) return undefined;\n let number = parseDouble(value);\n if (number === undefined || !Number.isFinite(number)) {\n throw new XlsxOpenError('unreadableConstant', 'The cell\\'s number cannot be read.', { sheet, cell: at, held: value });\n }\n if (this.#reader.date1904 && this.#showsDate(cell.styleIndex)) number += days1904;\n return Entry.fromValue(Value.fromNumber(number));\n }\n case 'boolean':\n switch (value) {\n case '1':\n case 'true':\n return Entry.fromValue(Value.fromBoolean(true));\n case '0':\n case 'false':\n return Entry.fromValue(Value.fromBoolean(false));\n case null:\n return undefined;\n default:\n throw new XlsxOpenError('unreadableConstant', 'The cell\\'s boolean cannot be read.', { sheet, cell: at, held: value });\n }\n case 'error': {\n if (value === null) return undefined;\n const error = Entry.fromErrorText(value);\n if (error !== undefined) return error;\n throw new XlsxOpenError('unreadableConstant', 'The cell holds an Error Value a cell of ExSheet cannot hold.', { sheet, cell: at, held: value });\n }\n case 'date': {\n if (value === null) return undefined;\n const serial = isoDateSerial(value);\n if (serial === undefined) {\n throw new XlsxOpenError('unreadableConstant',\n 'The cell\\'s date is not an ISO 8601 date or time, or lies outside the dates a serial counts.', { sheet, cell: at, held: value });\n }\n return Entry.fromValue(Value.fromNumber(serial));\n }\n default:\n return unreachable(cell.type);\n }\n }\n\n /** Whether the cell format at `style` shows a date (its serial moves from 1904's to 1900's). */\n #showsDate(style: number): boolean {\n const known = this.#dateStyles.get(style);\n if (known !== undefined) return known;\n const styles = this.#reader.styles;\n const id = elementAt(styles.cellFormats, style).numberFormatId;\n const shows = showsDate(id, styles.numberFormats.get(id));\n this.#dateStyles.set(style, shows);\n return shows;\n }\n\n /** What else a worksheet held, as the file layer reports it, said once per Sheet and kind. */\n #sheetElements(sheet: string, read: XlsxSheetReader, richCells: number, firstRich: string | undefined, printNames: boolean, formats: readonly FormatNotCarried[]): void {\n const kinds: { readonly kind: NotCarriedKind; readonly detail: string | undefined }[] = [];\n const add = (kind: NotCarriedKind, detail?: string): void => {\n if (!kinds.some(k => k.kind === kind && k.detail === detail)) kinds.push({ kind, detail });\n };\n if (read.customRowHeights) add('rowHeights');\n if (read.hiddenRows) add('hiddenRows');\n if (read.columns.some(c => c.hidden || (c.width !== null && c.width <= 0))) add('hiddenColumns');\n if (read.frozenPanes) add('frozenPanes');\n for (const element of read.otherElements) {\n for (const { kind, detail } of elementNotCarried(element)) add(kind, detail);\n }\n if (printNames) add('printSettings');\n if (richCells > 0) add('richText', firstRich);\n for (const { kind, detail } of formats) add(kind, detail);\n for (const { kind, detail } of kinds) {\n this.#notCarried.push({ kind, sheet, detail: detail === undefined ? null : detail, description: describe(kind, sheet, detail, richCells) });\n }\n }\n}\n\n/**\n * The name a defined name is listed under, or `undefined` when it is not listed: `_xlnm._FilterDatabase` is the range an\n * AutoFilter keeps, which the AutoFilter's own entry says. A print area or titles is a print setting of its Sheet's.\n */\nfunction builtInName(name: XlsxDefinedName): string | undefined {\n return equalsIgnoreCase(name.name, filterDatabase) ? undefined : name.name;\n}\n\nfunction describeName(name: XlsxDefinedName, shown: string, sheet: string | null): string {\n return sheet === null\n ? `The defined name '${shown}' (${name.text}) is not carried; no Formula carried reads it.`\n : `The defined name '${shown}' of the sheet '${sheet}' (${name.text}) is not carried; no Formula carried reads it.`;\n}\n\n/** The column ranges in the order of their first column, as LINQ's stable `OrderBy` gives them. */\nfunction byFirst(columns: readonly XlsxColumn[]): XlsxColumn[] {\n return columns.toSorted((a, b) => a.first - b.first);\n}\n\nfunction axisFormat(first: number, last: number, level: FormatParts): SheetDocumentAxisFormat {\n return new SheetDocumentAxisFormat(first, last, level.numberFormat, level.alignment, level.font, level.fill, level.borders);\n}\n\n/** Adds a formatted row to the runs, joining the run before it when it is the next row, formatted alike. */\nfunction addRun(runs: SheetDocumentAxisFormat[], row: number, level: FormatParts): void {\n if (level.isEmpty) return;\n const last = runs.at(-1);\n if (last !== undefined && last.last === row - 1 && partsOf(last).equals(level)) {\n runs[runs.length - 1] = axisFormat(last.first, row, level);\n } else {\n runs.push(axisFormat(row, row, level));\n }\n}\n\n/** The columns' widths in the engine's unit, a run wherever adjacent columns share one; a width fitted to an entry (`bestFit`) is one an entry widened. */\nfunction widths(columns: readonly XlsxColumn[]): SheetDocumentColumnWidth[] {\n const runs: SheetDocumentColumnWidth[] = [];\n for (const range of byFirst(columns)) {\n if (range.width === null) continue;\n const characters = readWidth(range.width);\n if (characters === undefined) continue;\n const kind = range.bestFit ? 'widenedByEntry' : 'setByUser';\n const last = runs.at(-1);\n if (last !== undefined && last.last === range.first - 1 && last.width === characters && last.kind === kind) {\n runs[runs.length - 1] = new SheetDocumentColumnWidth(last.first, range.last, characters, kind);\n } else {\n runs.push(new SheetDocumentColumnWidth(range.first, range.last, characters, kind));\n }\n }\n return runs;\n}\n\nfunction held(stored: string): string {\n return `=${stripPrefixes(stored)}`;\n}\n\n/**\n * Whether a cell lies in a dynamic array's Spill Range, whose cells hold the Values Excel stored, not constants. The list\n * holds only the ranges not yet behind the reader, pruned as each row begins.\n */\nfunction insideSpill(spills: readonly CellRange[], cell: CellAddress): boolean {\n return spills.some(s => s.contains(cell));\n}\n\n/** A range written `A1:B3` or `A1`, or `undefined` when it is not one. */\nfunction rangeOf(text: string): CellRange | undefined {\n const colon = text.indexOf(':');\n const first = parseCell(colon < 0 ? text : text.slice(0, colon));\n const last = parseCell(colon < 0 ? text : text.slice(colon + 1));\n if (first === undefined || last === undefined) return undefined;\n return new CellRange(new CellAddress(first.row, first.column), new CellAddress(last.row, last.column));\n}\n\nfunction describe(kind: NotCarriedKind, sheet: string, detail: string | undefined, richCells: number): string {\n const at = detail === undefined ? '' : detail;\n switch (kind) {\n case 'rowHeights': return `Rows of '${sheet}' have heights of their own, which are not carried.`;\n case 'hiddenRows': return `Rows of '${sheet}' are hidden in the file, and open shown.`;\n case 'hiddenColumns': return `Columns of '${sheet}' are hidden in the file, and open shown.`;\n case 'frozenPanes': return `'${sheet}' has frozen panes, which are not carried.`;\n case 'mergedCells': return `'${sheet}' has merged cells; each cell is carried on its own.`;\n case 'conditionalFormatting': return `'${sheet}' has conditional formatting, which is not carried.`;\n case 'dataValidation': return `'${sheet}' has data validation, which is not carried.`;\n case 'notesAndComments': return `'${sheet}' has notes or comments, which are not carried.`;\n case 'hyperlinks': return `'${sheet}' has hyperlinks; their cells' text is carried, the links are not.`;\n case 'picturesAndCharts': return `'${sheet}' has pictures, charts, shapes or controls, which are not carried.`;\n case 'protection': return `'${sheet}' is protected in the file; the protection is not carried.`;\n case 'printSettings':\n return `'${sheet}' has print settings beyond Excel's defaults (margins, a header or footer, page breaks, a print area, a scale or the like), which are not carried.`;\n case 'view':\n return `'${sheet}' has view settings (hidden gridlines, headings or zeros, Formulas shown, right to left, a zoom or a page layout), which are not carried.`;\n case 'autoFilter': return `'${sheet}' has an AutoFilter, which is not carried; every row opens shown.`;\n case 'excelTable': return `'${sheet}' has Excel Tables; their cells are carried, the Tables are not.`;\n case 'slicers': return `'${sheet}' has slicers or timelines, which are not carried.`;\n case 'sheetProperties': return `The tab colour of '${sheet}' is not carried.`;\n case 'richText':\n return `${String(richCells)} cell(s) of '${sheet}', the first ${at}, hold rich text: the text is carried, the runs' own formatting is not.`;\n case 'defaultColumnWidth':\n return `'${sheet}' has a default column width of its own, which is not carried; its columns without a width of their own open at the default width.`;\n case 'fontNamesAndSizes':\n return `Cells of '${sheet}', the first at ${at}, use a typeface or a size other than the workbook's own, which is not carried; they open in the Sheet's font.`;\n case 'verticalAlignment': return `Cells of '${sheet}', the first at ${at}, are aligned vertically, which is not carried.`;\n case 'textLayout': return `Cells of '${sheet}', the first at ${at}, wrap, indent, rotate or shrink their text, which is not carried.`;\n case 'horizontalAlignment':\n return `Cells of '${sheet}', the first at ${at}, are aligned to fill, justify, distribute or centre across the selection, which is not carried; they open aligned as General.`;\n case 'underline': return `Cells of '${sheet}', the first at ${at}, are underlined twice or for accounting; they open with a single underline.`;\n case 'patternFills':\n return `Cells of '${sheet}', the first at ${at}, have a pattern or gradient fill, or a solid fill of no colour, which is not carried; they open with no Fill.`;\n case 'diagonalBorders': return `Cells of '${sheet}', the first at ${at}, have diagonal borders, which are not carried; their four sides are.`;\n // Said of the workbook, never of a Sheet's elements; an element the file layer names is said by its name.\n case 'chartSheet':\n case 'dataConnections':\n case 'definedName':\n case 'externalLinks':\n case 'hiddenSheet':\n case 'other':\n case 'pivotTables':\n case 'themeColours':\n default:\n return `'${sheet}' holds <${at}>, which is not carried.`;\n }\n}\n", "import { Sheet } from '@ex-grid/sheet-engine';\n\n// A column's width between the engine's unit and the file's (ADR-0330 \u00A74, ADR-0047), as ExSheet.Xlsx's ColumnWidthUnit\n// counts it. The engine counts characters of the default font's digit, as Excel's Column Width box shows them (8.43 by\n// default). The file counts the same characters with the cell's padding added, five pixels at the default font's maximum\n// digit width of seven, truncated to 1/256 of a character, as ECMA-376 Part 1, \u00A718.3.1.13 gives it: 8.43 is `9.140625`.\n// Read back, a width is rounded to hundredths, as Excel shows it, so a width written from the engine reads back as it was to\n// the hundredth.\n\n/** The default font's maximum digit width in pixels: Calibri 11's at 96 DPI, which every width is counted in. */\nconst maxDigitWidth = 7;\n\n/** The cell's padding, in pixels: two on each side and one for the gridline. */\nconst padding = 5;\n\n/** The narrowest width the engine holds, in characters: a file's narrower width, above 0, opens at it. */\nconst narrowest = 0.01;\n\n/** The file's width for `characters`. */\nexport function widthToFile(characters: number): number {\n return Math.trunc((characters * maxDigitWidth + padding) / maxDigitWidth * 256) / 256;\n}\n\n/** The characters a file's `width` holds, to the hundredth; 0 or less for a width too narrow to hold one. */\nexport function widthFromFile(width: number): number {\n return Math.trunc((width * maxDigitWidth - padding) / maxDigitWidth * 100 + 0.5) / 100;\n}\n\n/**\n * The engine's width for a file's `width`, or `undefined` where it records none: a width of 0 or less (a column Excel shows\n * hidden, which the Open Report lists), or the default. A width too narrow to hold a hundredth of a character opens at the\n * narrowest the engine holds, and one wider than the engine holds at the widest.\n */\nexport function readWidth(width: number): number | undefined {\n if (width <= 0) return undefined;\n const characters = Math.min(Math.max(widthFromFile(width), narrowest), Sheet.maxColumnWidth);\n return characters === Sheet.defaultColumnWidth ? undefined : characters;\n}\n", "// Text compares as .NET's OrdinalIgnoreCase does (ADR-0023), as the Script Core's query/text-casing.ts says it;\n// the packages share no code, so each carries its own: character by character, each upper-cased by\n// the invariant simple mapping, never by the reader's culture, so the machine a Consumer runs on cannot\n// reorder a result. JavaScript's toUpperCase applies the full mapping instead, and .NET keeps two rules it\n// does not: a character whose full upper case is several characters takes its simple mapping, which is\n// itself (\u00DF, \u0149) except for the Greek letters with ypogegrammeni (\u1FB3 is \u1FBC), and a character outside ASCII\n// never folds into ASCII (the dotless \u0131 is not I, the long \u017F is not S), so ASCII text compares as ASCII\n// always has. Every code point was compared against .NET 10 when this was written.\n\n/** `text` upper-cased as OrdinalIgnoreCase compares it. */\nexport function foldCase(text: string): string {\n let folded = '';\n let changed = false;\n for (const character of text) {\n const upper = upperOf(character);\n if (upper !== character) changed = true;\n folded += upper;\n }\n return changed ? folded : text;\n}\n\nfunction upperOf(character: string): string {\n const code = character.charCodeAt(0);\n if (code < 0x80) return code >= 0x61 && code <= 0x7a ? String.fromCharCode(code - 0x20) : character;\n const upper = character.toUpperCase();\n // One code point to one code point, and never from outside ASCII into it.\n const point = upper.codePointAt(0);\n const single = point !== undefined && upper.length === (point > 0xffff ? 2 : 1);\n if (!single) return simpleUpperOf(code, character);\n if (upper === character || point < 0x80) return character;\n return upper;\n}\n\n/** The simple upper case of a character whose full upper case is several characters. Only the Greek\n * letters with ypogegrammeni have one that is not themselves: each takes the prosgegrammeni form. */\nfunction simpleUpperOf(code: number, character: string): string {\n const pairs = (code >= 0x1f80 && code <= 0x1f87) || (code >= 0x1f90 && code <= 0x1f97) || (code >= 0x1fa0 && code <= 0x1fa7);\n if (pairs) return String.fromCharCode(code + 8);\n if (code === 0x1fb3 || code === 0x1fc3 || code === 0x1ff3) return String.fromCharCode(code + 9);\n return character;\n}\n\n/** C#'s `string.Equals(a, b, StringComparison.OrdinalIgnoreCase)`. */\nexport function equalsIgnoreCase(a: string, b: string): boolean {\n return a.length === b.length && foldCase(a) === foldCase(b);\n}\n\n/** Whether `text` holds `part` at `at`, compared as OrdinalIgnoreCase compares: `string.Compare(text, at, part, 0,\n * part.Length, StringComparison.OrdinalIgnoreCase) == 0`. */\nexport function startsWithIgnoreCase(text: string, at: number, part: string): boolean {\n return at + part.length <= text.length && equalsIgnoreCase(text.slice(at, at + part.length), part);\n}\n\n/** `char.IsWhiteSpace`: U+0009 to U+000D, the space, U+0085, U+00A0, U+1680, U+2000 to U+200A, U+2028, U+2029, U+202F,\n * U+205F and U+3000. */\nconst whiteSpaceEnds = /^[\\t-\\r \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]+|[\\t-\\r \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]+$/g;\n\n/** C#'s `string.Trim()`: the white space `char.IsWhiteSpace` names taken off both ends, which is JavaScript's `trim` with\n * U+0085 and without U+FEFF. */\nexport function trimWhiteSpace(text: string): string {\n return text.replace(whiteSpaceEnds, '');\n}\n", "import { startsWithIgnoreCase } from './text-casing';\n\n// Whether a Number Format shows a date (ADR-0330 \u00A74), as ExSheet.Xlsx's DateFormats says it: the cells whose serials a\n// workbook on the 1904 date system moves to 1900's. A format that shows only a time of day, or a duration (`[h]:mm`), is\n// not one: its number is the same in both systems, and moving it would change an elapsed time.\n\n/** The built-in formats that show a date (ECMA-376 Part 1, \u00A718.8.30), East Asian ones included. */\nconst builtInDates: ReadonlySet<number> = new Set([14, 15, 16, 17, 22, 27, 28, 29, 30, 31, 34, 35, 36, 50, 51, 52, 53, 54, 55, 56, 57, 58]);\n\n/** Whether the format `id` shows a date; a custom one by its `code`. */\nexport function showsDate(id: number, code: string | undefined): boolean {\n return code === undefined ? builtInDates.has(id) : codeShowsDate(code);\n}\n\n/** `char.ToLowerInvariant` of one ASCII letter of a format code; any other character as it is. */\nfunction lower(c: string): string {\n return c >= 'A' && c <= 'Z' ? c.toLowerCase() : c;\n}\n\n/**\n * Whether a format code's first section shows a part of a date: a year (`y`, `e`), a day (`d`), or a month (`m` in a\n * section with no hour or second, where Excel reads it as minutes). An elapsed time in brackets (`[h]`, `[mm]`, `[ss]`)\n * makes the section a duration, so an `m` beside it is minutes. Text in quotes, an escaped character, what else stands in\n * brackets and `General` are not read as parts.\n */\nexport function codeShowsDate(code: string): boolean {\n let hasMonthOrMinute = false;\n let hasTime = false;\n for (let i = 0; i < code.length; i++) {\n const c = code.charAt(i);\n switch (c) {\n case ';':\n return !hasTime && hasMonthOrMinute;\n case '\"': {\n const end = code.indexOf('\"', i + 1);\n i = end >= 0 ? end : code.length;\n continue;\n }\n case '\\\\':\n case '_':\n case '*':\n i++;\n continue;\n case '[': {\n let close = code.indexOf(']', i + 1);\n if (close < 0) close = code.length;\n // [h], [mm], [ss]: an elapsed time, so the section is a duration, and an m beside it is minutes.\n if (isElapsed(code.slice(i + 1, close))) hasTime = true;\n i = close;\n continue;\n }\n default:\n break;\n }\n if (startsWithIgnoreCase(code, i, 'General')) {\n i += 6;\n continue;\n }\n if (startsWithIgnoreCase(code, i, 'AM/PM')) {\n hasTime = true;\n i += 4;\n continue;\n }\n if (startsWithIgnoreCase(code, i, 'A/P')) {\n hasTime = true;\n i += 2;\n continue;\n }\n switch (lower(c)) {\n case 'y':\n case 'd':\n return true;\n case 'e':\n if (i + 1 >= code.length || (code.charAt(i + 1) !== '+' && code.charAt(i + 1) !== '-')) return true;\n break;\n case 'm':\n hasMonthOrMinute = true;\n break;\n case 'h':\n case 's':\n hasTime = true;\n break;\n default:\n break;\n }\n }\n return !hasTime && hasMonthOrMinute;\n}\n\n/** Whether a bracket's content is an elapsed time: one letter of `h`, `m` or `s`, repeated. */\nfunction isElapsed(inside: string): boolean {\n if (inside.length === 0) return false;\n const letter = lower(inside.charAt(0));\n if (letter !== 'h' && letter !== 'm' && letter !== 's') return false;\n for (const c of inside) {\n if (lower(c) !== letter) return false;\n }\n return true;\n}\n", "import { CellBorders, CellFill, CellFont, CellFormat, NumberFormat, type HorizontalAlignment } from '@ex-grid/sheet-engine';\n\n// The parts of a Cell Format one level records \u2014 a cell, a row or a column (ADR-0047, ADR-0071) \u2014 each `undefined` where the\n// level takes it from the level beneath, as ExSheet.Xlsx's FormatParts holds them.\n\n/** The Cell Format a Sheet shows where no level records a part. */\nexport const defaultFormat = new CellFormat(NumberFormat.general, 'general', CellFont.default, CellFill.none, CellBorders.none);\n\nexport class FormatParts {\n static readonly empty = new FormatParts(undefined, undefined, undefined, undefined, undefined);\n\n readonly numberFormat: NumberFormat | undefined;\n readonly alignment: HorizontalAlignment | undefined;\n readonly font: CellFont | undefined;\n readonly fill: CellFill | undefined;\n readonly borders: CellBorders | undefined;\n\n constructor(\n numberFormat: NumberFormat | undefined,\n alignment: HorizontalAlignment | undefined,\n font: CellFont | undefined,\n fill: CellFill | undefined,\n borders: CellBorders | undefined,\n ) {\n this.numberFormat = numberFormat;\n this.alignment = alignment;\n this.font = font;\n this.fill = fill;\n this.borders = borders;\n }\n\n get isEmpty(): boolean {\n return this.numberFormat === undefined && this.alignment === undefined && this.font === undefined && this.fill === undefined && this.borders === undefined;\n }\n\n /** This level over `under`, part by part. */\n over(under: CellFormat): CellFormat {\n return new CellFormat(\n this.numberFormat === undefined ? under.numberFormat : this.numberFormat,\n this.alignment === undefined ? under.alignment : this.alignment,\n this.font === undefined ? under.font : this.font,\n this.fill === undefined ? under.fill : this.fill,\n this.borders === undefined ? under.borders : this.borders);\n }\n\n /** The parts of `format` that differ from `under`: what a level records so that it shows `format` over it. */\n static differing(format: CellFormat, under: CellFormat): FormatParts {\n return new FormatParts(\n format.numberFormat.equals(under.numberFormat) ? undefined : format.numberFormat,\n format.alignment === under.alignment ? undefined : format.alignment,\n format.font.equals(under.font) ? undefined : format.font,\n format.fill.equals(under.fill) ? undefined : format.fill,\n format.borders.equals(under.borders) ? undefined : format.borders);\n }\n\n /** Whether the two levels record the same parts alike, as the C# record compares. */\n equals(other: FormatParts): boolean {\n return same(this.numberFormat, other.numberFormat, (a, b) => a.equals(b))\n && this.alignment === other.alignment\n && same(this.font, other.font, (a, b) => a.equals(b))\n && same(this.fill, other.fill, (a, b) => a.equals(b))\n && same(this.borders, other.borders, (a, b) => a.equals(b));\n }\n\n\n /** The parts a level records, as a mask: Number Format, alignment, Font, Fill, borders. */\n get mask(): number {\n return (this.numberFormat === undefined ? 0 : 1) | (this.alignment === undefined ? 0 : 2) | (this.font === undefined ? 0 : 4)\n | (this.fill === undefined ? 0 : 8) | (this.borders === undefined ? 0 : 16);\n }\n}\n\nfunction same<T>(a: T | undefined, b: T | undefined, equal: (a: T, b: T) => boolean): boolean {\n return a === undefined || b === undefined ? a === b : equal(a, b);\n}\n", "// Numbers written as ExSheet.Xlsx writes them with the invariant culture, so that a written part and a refusal's\n// words read alike in both packages (ADR-0370, section 2). Each function names the .NET format it stands for.\n\n/** C#'s `ToString(\"N0\", CultureInfo.InvariantCulture)` of a whole number: its digits grouped by threes with commas. */\nexport function grouped(value: number): string {\n const digits = String(Math.abs(Math.trunc(value)));\n const groups: string[] = [];\n for (let end = digits.length; end > 0; end -= 3) groups.unshift(digits.slice(Math.max(0, end - 3), end));\n return (value < 0 ? '-' : '') + groups.join(',');\n}\n\n/**\n * C#'s `ToString(\"R\", CultureInfo.InvariantCulture)` of a double: the shortest digits that read back as the same\n * number, in exponent form (`1E-05`, `1.2345678901234568E+17`) where the point stands more than seventeen places\n * right of the first digit or more than three places left of it.\n */\nexport function roundTrip(value: number): string {\n if (Number.isNaN(value)) return 'NaN';\n if (!Number.isFinite(value)) return value > 0 ? 'Infinity' : '-Infinity';\n if (value === 0) return Object.is(value, -0) ? '-0' : '0';\n const match = /^(\\d)(?:\\.(\\d+))?e([+-]\\d+)$/.exec(Math.abs(value).toExponential());\n if (match === null) throw new Error(`Internal: ${String(value)} is not written in exponent form.`);\n const [, first = '', rest = '', exponent = ''] = match;\n const digits = first + rest;\n const point = Number(exponent) + 1;\n const sign = value < 0 ? '-' : '';\n if (point > 17 || point < -3) {\n const e = point - 1;\n const mantissa = digits.length > 1 ? `${digits.slice(0, 1)}.${digits.slice(1)}` : digits;\n return `${sign}${mantissa}E${e < 0 ? '-' : '+'}${String(Math.abs(e)).padStart(2, '0')}`;\n }\n if (point <= 0) return `${sign}0.${'0'.repeat(-point)}${digits}`;\n if (point >= digits.length) return sign + digits + '0'.repeat(point - digits.length);\n return `${sign}${digits.slice(0, point)}.${digits.slice(point)}`;\n}\n\n/**\n * C#'s `double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture)`: an optional sign, digits with an optional\n * point, an optional exponent, and white space (U+0009 to U+000D and U+0020) on either side; or the invariant culture's\n * `Infinity` and `NaN`, in any case, with a sign. `undefined` for anything else.\n */\nexport function parseDouble(text: string): number | undefined {\n const trimmed = text.replace(/^[\\t\\n\\v\\f\\r ]+|[\\t\\n\\v\\f\\r ]+$/g, '');\n if (/^[+-]?(?:[0-9]+\\.?[0-9]*|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/.test(trimmed)) return Number(trimmed);\n const lower = trimmed.toLowerCase();\n if (lower === 'infinity' || lower === '+infinity') return Number.POSITIVE_INFINITY;\n if (lower === '-infinity') return Number.NEGATIVE_INFINITY;\n if (lower === 'nan' || lower === '+nan' || lower === '-nan') return Number.NaN;\n return undefined;\n}\n", "import { serialFromDate } from '@ex-grid/sheet-engine';\n\n// A date cell's ISO 8601 text (`t=\"d\"`, ECMA-376 Part 1, \u00A718.18.11) as the 1900 date system's serial (ADR-0330 \u00A74), as\n// ExSheet.Xlsx's IsoDate reads it: invariantly, never by the reader's culture, its time zone or today's date. A date with a\n// time is its day's serial and the time's fraction of a day; a time alone is its fraction (a serial below 1, as Excel holds\n// a time of day). A cell of Excel's has no time zone, so a written offset (`Z`, `+09:00`) is the writer's own, and the clock\n// time written beside it is the one its reader saw: that clock time is carried, and the offset converts nothing.\n\n// [0-9], never \\d: ISO 8601 writes no other script's digits. A time follows a date after a T, and stands alone without one.\nconst shape = /^(?:(?<y>[0-9]{4})-(?<mo>[0-9]{2})-(?<d>[0-9]{2}))?(?<t>T)?(?:(?<h>[0-9]{2}):(?<mi>[0-9]{2})(?::(?<s>[0-9]{2})(?<f>\\.[0-9]+)?)?)?(?<z>Z|[+-][0-9]{2}(?::?[0-9]{2})?)?$/;\n\n/** The serial of `text`, or `undefined` when it is not an ISO 8601 date or time, or lies outside 1900 to 9999. */\nexport function isoDateSerial(text: string): number | undefined {\n const groups = shape.exec(text)?.groups;\n if (groups === undefined) return undefined;\n const { y, mo, d, t, h, mi, s, f } = groups;\n const hasDate = y !== undefined;\n const hasTime = h !== undefined;\n if (!hasDate && !hasTime) return undefined;\n // .NET's (?(y)T): a time after a date takes a T, and a time alone takes none.\n if ((t !== undefined) !== (hasDate && hasTime)) return undefined;\n\n let time = 0;\n if (hasTime) {\n const hours = Number(h);\n const minutes = Number(mi);\n const seconds = s === undefined ? 0 : Number(s);\n const fraction = f === undefined ? 0 : Number(`0${f}`);\n if (hours > 23 || minutes > 59 || seconds > 59) return undefined;\n time = (hours * 3600 + minutes * 60 + seconds + fraction) / 86400;\n }\n if (!hasDate) return time;\n\n // The engine's own count of the 1900 date system, its 29 February 1900 (60) included.\n const serial = serialFromDate(Number(y), Number(mo), Number(d));\n return serial === undefined ? undefined : serial + time;\n}\n", "// What the package knows is there, as core/src/must.ts says it for the Script Core: a miss is a defect in\n// the package, said by throwing where a `!` would read on with `undefined` (CONVENTIONS.md, \"No quiet\n// fallback\"). The packages share no code, so each carries its own.\n\n/** The element at `index`, which the caller knows is there. A miss throws: it is a defect, never an answer. */\nexport function elementAt<T extends object | string | number | boolean | bigint | null>(list: ArrayLike<T>, index: number): T {\n const value = list[index];\n if (value === undefined) {\n throw new Error(`Internal: index ${String(index)} is outside a list of ${String(list.length)}.`);\n }\n return value;\n}\n\n/** The value, which the caller knows is there. `undefined` throws, naming what was missing. */\nexport function defined<T>(value: T | undefined, what: string): T {\n if (value === undefined) {\n throw new Error(`Internal: ${what} is missing.`);\n }\n return value;\n}\n\n/** The end of a switch that has taken every member of a union; a value from outside it throws here. */\nexport function unreachable(value: never): never {\n throw new Error(`Internal: ${String(value)} is not a value this switch takes.`);\n}\n", "import { XlsxError, type XlsxRefusal } from '@ex-grid/data-xlsx';\n\n// A workbook refused by name, and nothing opened (ADR-0330 \u00A74), as ExSheet.Xlsx's XlsxOpenException refuses it: the\n// reason, the Sheet and the cell, and what the cell held, as far as the refusal is about one \u2014 `Sheet 'Trades', cell B7\n// (=Rate*A7): \u2026`, as the CSV reader names a row and a column.\n\n/**\n * Why a workbook was refused, and nothing opened (ADR-0330 \u00A74): what it held would change a Value, or the number a cell\n * shows, or it is not a file that can be read faithfully.\n */\nexport type XlsxOpenRefusal =\n /** The file layer refused the file: not a plain .xlsx, damaged, or past a limit. `XlsxOpenError.fileRefusal` says why. */\n | 'file'\n /** A Formula the engine cannot read: a syntax it does not implement (an array constant, the union operator, `@`), or a\n * What-If data table. */\n | 'unreadableFormula'\n /** A Formula reads a defined name, which ExSheet does not define, so it would show `#NAME?` where Excel shows a Value. */\n | 'definedName'\n /** A Formula reads another workbook, which ExSheet cannot reach. */\n | 'otherWorkbook'\n /** A Formula reads an Excel Table, which ExSheet does not read yet (ADR-0330 \u00A76). */\n | 'excelTable'\n /** A legacy array formula (Ctrl+Shift+Enter), whose cells Excel computes as one, and ExSheet would spill otherwise. */\n | 'legacyArrayFormula'\n /** A constant a cell cannot hold in ExSheet, such as an Error Value the engine does not read. */\n | 'unreadableConstant'\n /** A worksheet's name is not one a Sheet can have, or the workbook holds no worksheet at all. */\n | 'sheets'\n /**\n * A cell, a row or a column takes a Number Format the engine does not read, or a built-in one whose code follows the\n * computer's locale and that the file does not spell out: shown in General instead, a date would show as a serial, or a\n * currency lose its symbol (ADR-0330 \u00A74). `XlsxOpenError.held` is the format's code as the file spells it, or\n * `Number Format N`, naming its id, where the file spells none.\n */\n | 'numberFormat';\n\n/** Where an open's refusal met what it refuses, as far as it is about one Sheet and cell. */\nexport interface XlsxOpenPlace {\n /** The name of the Sheet it met. */\n readonly sheet?: string | undefined;\n /** The cell it met, as `B7`. */\n readonly cell?: string | undefined;\n /** What the cell held, as a Formula's text with its `=` or a constant's. */\n readonly held?: string | undefined;\n}\n\n/** A workbook refused by name, and nothing opened (ADR-0330 \u00A74). */\nexport class XlsxOpenError extends Error {\n /** Why the workbook was refused. */\n readonly reason: XlsxOpenRefusal;\n /** The name of the Sheet the refusal met, or `undefined` when it is not about one Sheet. */\n readonly sheet: string | undefined;\n /** The cell the refusal met, as `B7`, or `undefined` when it is not about one cell. */\n readonly cell: string | undefined;\n /** What the cell held \u2014 a Formula's text with its `=`, or a constant \u2014 or `undefined` when the refusal is not about one\n * cell. */\n readonly held: string | undefined;\n\n /**\n * A refusal naming what it met.\n * @param reason - Why the workbook is refused.\n * @param message - What was wrong, as a sentence that follows the Sheet and the cell.\n * @param where - The Sheet, the cell and what the cell held, as far as it is about one.\n * @param options - What caused it, when it was another error.\n */\n constructor(reason: XlsxOpenRefusal, message: string, where: XlsxOpenPlace = {}, options?: ErrorOptions) {\n super(formatted(where.sheet, where.cell, where.held, message), options);\n this.name = 'XlsxOpenError';\n this.reason = reason;\n this.sheet = where.sheet;\n this.cell = where.cell;\n this.held = where.held;\n }\n\n /** Why the file layer refused the file, when `reason` is `file`; otherwise `undefined`. */\n get fileRefusal(): XlsxRefusal | undefined {\n return this.reason === 'file' && this.cause instanceof XlsxError ? this.cause.reason : undefined;\n }\n\n /** The file layer's refusal, with its Sheet and cell. @internal */\n static fromFile(e: XlsxError): XlsxOpenError {\n const refusal = new XlsxOpenError('file', e.message, { sheet: e.sheet, cell: e.cell }, { cause: e });\n // The file layer has already written its Sheet and cell into its words.\n refusal.message = e.message;\n return refusal;\n }\n}\n\n/** The message with the Sheet, the cell and what it held before it, as ExSheet.Xlsx writes them. */\nexport function formatted(sheet: string | undefined, cell: string | undefined, held: string | undefined, message: string): string {\n const at = held === undefined ? cell : `${cell === undefined ? '' : cell} (${held})`;\n if (sheet === undefined) return message;\n return at === undefined ? `Sheet '${sheet}': ${message}` : `Sheet '${sheet}', cell ${at}: ${message}`;\n}\n", "import type { WorkbookDocument } from '@ex-grid/sheet-engine';\n\n// What reading an .xlsx returns beside the Workbook Document (CONTEXT.md, ADR-0330 \u00A75), as ExSheet.Xlsx's OpenReport says\n// it: what the file held that ExSheet did not carry, and the cells whose Formulas name a function ExSheet does not support,\n// each with its Sheet and place. The package shows nothing; the application decides how to tell the user.\n\n/** What kind of thing an `OpenReport` says was not carried (ADR-0330 \u00A74). */\nexport type NotCarriedKind =\n /** A worksheet that is hidden: it opens shown (ADR-0331 \u00A74). */\n | 'hiddenSheet'\n /** A sheet that is not a worksheet \u2014 a chart sheet, a dialog or macro sheet \u2014 which holds no cells. */\n | 'chartSheet'\n /** A defined name, which no Formula carried reads; `detail` is its name, and `sheet` the sheet it is local to, or `null`\n * for a name of the whole workbook. */\n | 'definedName'\n /** Rows given heights of their own. */\n | 'rowHeights'\n /** Rows that are hidden: they open shown. */\n | 'hiddenRows'\n /** Columns that are hidden: they open shown. */\n | 'hiddenColumns'\n /** Panes frozen in the Sheet's view. */\n | 'frozenPanes'\n /** Merged cells: each cell is carried on its own. */\n | 'mergedCells'\n /** Conditional formatting. */\n | 'conditionalFormatting'\n /** Data validation. */\n | 'dataValidation'\n /** Notes and comments. */\n | 'notesAndComments'\n /** Hyperlinks: the cells' text is carried. */\n | 'hyperlinks'\n /** Pictures, charts, shapes and controls drawn over the Sheet. */\n | 'picturesAndCharts'\n /** The Sheet's protection. */\n | 'protection'\n /** Print settings beyond Excel's defaults: margins, a page set-up of its own, headers and footers with text, page breaks,\n * printed gridlines or headings, a fit to pages, a print area or print titles. */\n | 'printSettings'\n /** An AutoFilter, and the sort state it keeps. */\n | 'autoFilter'\n /** The structure of an Excel Table that no Formula reads: its cells are carried. */\n | 'excelTable'\n /** The Sheet's tab colour. */\n | 'sheetProperties'\n /** Rich-text runs inside cells: the text is carried, the runs' own formatting is not. */\n | 'richText'\n /** A PivotTable: the cells it shows are carried as constants, the PivotTable is not. */\n | 'pivotTables'\n /** Links to other workbooks that no Formula carried reads. */\n | 'externalLinks'\n /** Connections to outside data, and the queries that read through them. */\n | 'dataConnections'\n /** Slicers and timelines. */\n | 'slicers'\n /** View settings that change how the Sheet looks: hidden gridlines, headings or zeros, Formulas shown, right to left, a\n * zoom, a page layout. */\n | 'view'\n /** Anything else a worksheet holds; `detail` names its element, as `customSheetViews`. */\n | 'other'\n /** Colours that name the workbook's theme: each is carried as the RGB value the file's theme gives it, and the link to the\n * theme is not, so another theme does not recolour them (ADR-0330 \u00A78). Said once, of the whole workbook. */\n | 'themeColours'\n /** A typeface or a size other than the workbook's own font's: the cells open in the Sheet's one font (ADR-0071). */\n | 'fontNamesAndSizes'\n /** Vertical alignment other than bottom. */\n | 'verticalAlignment'\n /** Wrapped, indented, rotated or shrunk text. */\n | 'textLayout'\n /** A horizontal alignment a Sheet does not have \u2014 fill, justify, distributed, centred across the selection: the cells open\n * aligned as General. */\n | 'horizontalAlignment'\n /** A double or accounting underline: the cells open with a single underline. */\n | 'underline'\n /** A pattern or gradient fill, or a solid one of no colour: the cells open with no Fill. */\n | 'patternFills'\n /** Diagonal borders: the cells keep their four sides. */\n | 'diagonalBorders'\n /** A default column width of the Sheet's own: its columns without a width of their own open at the default width. */\n | 'defaultColumnWidth';\n\n/** One thing the file held that was not carried (ADR-0330 \u00A74). */\nexport interface NotCarried {\n /** What it is. */\n readonly kind: NotCarriedKind;\n /** The Sheet it was on, or `null` for what the workbook as a whole held. */\n readonly sheet: string | null;\n /** What names it more closely, where something does: a defined name, the first cell of rich text or of a format not\n * carried (a cell as `B7`, columns as `B:C`, rows as `5:5`), an element's name; otherwise `null`. */\n readonly detail: string | null;\n /** One sentence an application can show as it stands. */\n readonly description: string;\n}\n\n/** A cell whose Formula names a function ExSheet does not support (ADR-0330 \u00A74, \u00A75): the Formula is carried, and shows\n * `#NAME?`. */\nexport interface UnsupportedFunctionCell {\n /** The Sheet's name. */\n readonly sheet: string;\n /** The cell, as `B7`. */\n readonly cell: string;\n /** The functions it names that are not supported, in the Formula's order. */\n readonly functions: readonly string[];\n}\n\n/** What reading an .xlsx returns beside the Workbook Document (ADR-0330 \u00A75). */\nexport class OpenReport {\n /**\n * What the file held that changes how a Sheet looks, or what else the file held, and that ExSheet did not carry\n * (ADR-0330 \u00A74's \"Not carried\"), in the workbook's order: what the workbook holds first, then each Sheet's in turn. Saving\n * the Workbook again will not keep any of it.\n */\n readonly notCarried: readonly NotCarried[];\n\n /**\n * The cells whose Formula names a function outside ExSheet's declared set (`DeclaredFunction`), in Sheet order and then\n * row by row: each is carried, and shows `#NAME?` (ADR-0047, ADR-0330 \u00A74).\n */\n readonly unsupportedFunctions: readonly UnsupportedFunctionCell[];\n\n /** @internal */\n constructor(notCarried: readonly NotCarried[], unsupportedFunctions: readonly UnsupportedFunctionCell[]) {\n this.notCarried = Object.freeze(notCarried.map(n => Object.freeze({ ...n })));\n this.unsupportedFunctions = Object.freeze(unsupportedFunctions.map(u => Object.freeze({ ...u, functions: Object.freeze([...u.functions]) })));\n Object.freeze(this);\n }\n\n /** Whether the file was carried whole: nothing left behind, and every function it names supported. */\n get isEmpty(): boolean {\n return this.notCarried.length === 0 && this.unsupportedFunctions.length === 0;\n }\n}\n\n/** A Workbook Document read from an .xlsx, and its Open Report (ADR-0330 \u00A75). */\nexport interface XlsxOpenResult {\n /** The Workbook Document: every worksheet a Sheet, in the file's order, the one shown shown. */\n readonly document: WorkbookDocument;\n /** What was not carried, and the cells naming functions ExSheet does not support. */\n readonly report: OpenReport;\n}\n", "import { Sheet, type CellAddress, type SheetDocument, type SheetDocumentAxisFormat, type SheetDocumentColumnWidth } from '@ex-grid/sheet-engine';\nimport type { XlsxColumnInput } from '@ex-grid/data-xlsx';\nimport { widthToFile } from './column-width-unit';\nimport { defaultFormat, FormatParts } from './format-parts';\nimport { elementAt } from './must';\nimport type { StyleTable } from './style-table';\n\n// What a worksheet writes for a Sheet's Cell Formats and column widths (ADR-0330 \u00A74, ADR-0046, ADR-0047, ADR-0071), as\n// ExSheet.Xlsx's SheetFormatPlan plans it: its columns' widths and formats, its rows' formats, and the format each cell\n// element is written with.\n//\n// A Sheet records a format part by part at three levels, cell over row over column; a file records one whole format at each,\n// and a cell element's format stands alone. So a column writes its own level over the default, a row its own level over the\n// default (in the file a row's format stands in place of its columns'), and every cell the Sheet records writes the format the\n// Sheet shows there (`style`). Where a formatted row crosses a formatted column that records a part the row leaves to it, what\n// the Sheet shows there is not the row's format, so a cell of no value is written there with the format it shows: a crossing.\n// A width is written in the file's unit, marked fitted (`bestFit`) where an entry widened it; a column that records a format\n// and no width is written at the default width, not marked as set.\n//\n// The crossings are what a Sheet formatted on many rows and many columns costs: rows \u00D7 columns cells. They are counted first,\n// from the runs alone (`crossings`), in time that grows with the runs and not with the cells, so that the writer refuses a\n// Sheet that would write more cells than a file is read with before a cell is written; only then are their formats found\n// (`build`).\n\n/** A column range where a formatted row crosses a formatted column and shows another format than the row's. */\nexport interface Crossing {\n readonly first: number;\n readonly last: number;\n /** The cell format index its cells are written with. */\n readonly style: number;\n}\n\n/** A run of formatted rows, as the file writes them: each row's format, and the column ranges it crosses. */\nexport interface RowRun {\n readonly first: number;\n readonly last: number;\n /** The cell format index each row is written with. */\n readonly style: number;\n /** The column ranges, in order, where a cell of no value is written in each row of the run. */\n readonly crossings: readonly Crossing[];\n}\n\nconst allParts = 0b11111;\n\ninterface ColumnRun { readonly first: number; readonly last: number; readonly level: FormatParts; readonly parts: number }\n\ninterface FormattedRows { readonly first: number; readonly last: number; readonly level: FormatParts; readonly open: number }\n\nexport class SheetFormatPlan {\n readonly #sheet: SheetDocument;\n readonly #columnLevels = new Map<number, FormatParts>();\n /** Each formatted column's parts other than the default's, as a mask. */\n readonly #columnParts = new Map<number, number>();\n /** The formatted column runs, in order, each with the parts it records other than the default's, as a mask. */\n readonly #columnRuns: ColumnRun[] = [];\n /** The formatted row runs, in order, each with the parts it leaves to its columns, as a mask. */\n readonly #rowRuns: FormattedRows[] = [];\n /** For each mask of parts a row leaves open, the column runs it crosses and how many columns they hold. */\n readonly #crossed = new Map<number, { readonly runs: readonly number[]; readonly columns: number }>();\n\n /** The column ranges, in order, each with its width and its format's index; set by `build`. */\n columns: readonly XlsxColumnInput[] = [];\n /** The runs of formatted rows, in order; set by `build`. */\n rows: readonly RowRun[] = [];\n\n /** The plan for `sheet`, its levels read; nothing is written to a styles part yet. */\n constructor(sheet: SheetDocument) {\n this.#sheet = sheet;\n for (const run of sheet.columns.toSorted((a, b) => a.first - b.first)) {\n const level = partsOf(run);\n const parts = FormatParts.differing(level.over(defaultFormat), defaultFormat).mask;\n for (let c = run.first; c <= run.last; c++) {\n this.#columnLevels.set(c, level);\n this.#columnParts.set(c, parts);\n }\n this.#columnRuns.push({ first: run.first, last: run.last, level, parts });\n }\n for (const run of sheet.rows.toSorted((a, b) => a.first - b.first)) {\n const level = partsOf(run);\n this.#rowRuns.push({ first: run.first, last: run.last, level, open: ~level.mask & allParts });\n }\n }\n\n /** The rows the row formats write, each a `<row>` element whether or not it holds a cell. */\n get formattedRows(): number {\n let rows = 0;\n for (const run of this.#rowRuns) rows += run.last - run.first + 1;\n return rows;\n }\n\n /**\n * How many cells of no value the crossings write: every place a formatted row crosses a formatted column that records a\n * part the row leaves open, less those of `recorded`, which are written as the Sheet's own cells. Counted from the runs,\n * never cell by cell.\n * @param recorded - The cells the Sheet writes of its own, each once.\n */\n crossings(recorded: Iterable<CellAddress>): number {\n let count = 0;\n for (const run of this.#rowRuns) count += (run.last - run.first + 1) * this.#crossedBy(run.open).columns;\n if (count === 0) return 0;\n for (const at of recorded) {\n const r = this.#rowRunAt(at.row);\n const parts = this.#columnParts.get(at.column);\n if (r !== undefined && parts !== undefined && (parts & elementAt(this.#rowRuns, r).open) !== 0) count--;\n }\n return count;\n }\n\n /** Finds every format the columns, the rows and the crossings write, adding each to `styles`. */\n build(styles: StyleTable): void {\n const rows: RowRun[] = [];\n for (const run of this.#rowRuns) {\n const crossings: Crossing[] = [];\n for (const index of this.#crossedBy(run.open).runs) {\n const column = elementAt(this.#columnRuns, index);\n const style = styles.index(run.level.over(column.level.over(defaultFormat)));\n const last = crossings.at(-1);\n if (last !== undefined && last.last === column.first - 1 && last.style === style) crossings[crossings.length - 1] = { ...last, last: column.last };\n else crossings.push({ first: column.first, last: column.last, style });\n }\n rows.push({ first: run.first, last: run.last, style: styles.index(run.level.over(defaultFormat)), crossings });\n }\n this.rows = rows;\n this.columns = this.#columnRanges(styles);\n }\n\n /** The index of the format a cell element at `at` is written with: what the Sheet shows there, its own level over its row's\n * and its column's. */\n style(styles: StyleTable, own: FormatParts, at: CellAddress): number {\n const column = this.#columnLevels.get(at.column);\n let under = column === undefined ? defaultFormat : column.over(defaultFormat);\n const r = this.#rowRunAt(at.row);\n if (r !== undefined) under = elementAt(this.#rowRuns, r).level.over(under);\n return styles.index(own.over(under));\n }\n\n /** The column runs a row that leaves `open` to its columns crosses: those that record one of those parts other than the\n * default's. */\n #crossedBy(open: number): { readonly runs: readonly number[]; readonly columns: number } {\n const known = this.#crossed.get(open);\n if (known !== undefined) return known;\n const runs: number[] = [];\n let columns = 0;\n this.#columnRuns.forEach((run, i) => {\n if ((run.parts & open) === 0) return;\n runs.push(i);\n columns += run.last - run.first + 1;\n });\n const crossed = { runs, columns };\n this.#crossed.set(open, crossed);\n return crossed;\n }\n\n /** The index of the formatted row run that holds `row`, or `undefined`. */\n #rowRunAt(row: number): number | undefined {\n let low = 0;\n let high = this.#rowRuns.length - 1;\n while (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const run = elementAt(this.#rowRuns, mid);\n if (row < run.first) high = mid - 1;\n else if (row > run.last) low = mid + 1;\n else return mid;\n }\n return undefined;\n }\n\n /** The columns' widths and formats as ranges: a range wherever both stay the same. */\n #columnRanges(styles: StyleTable): XlsxColumnInput[] {\n const widths = new Map<number, SheetDocumentColumnWidth>();\n for (const run of this.#sheet.columnWidths) {\n for (let c = run.first; c <= run.last; c++) widths.set(c, run);\n }\n const ranges: { first: number; last: number; width: number; styleIndex: number; bestFit: boolean; customWidth: boolean }[] = [];\n for (const column of [...new Set([...widths.keys(), ...this.#columnLevels.keys()])].toSorted((a, b) => a - b)) {\n // A column that records a format and no width of its own is written at the default width, not marked as set: a\n // <col> with no width is believed to be read by Excel as a width of 0, which hides the column.\n const w = widths.get(column);\n const width = widthToFile(w === undefined ? Sheet.defaultColumnWidth : w.width);\n const bestFit = w !== undefined && w.kind === 'widenedByEntry';\n const level = this.#columnLevels.get(column);\n const styleIndex = level === undefined ? 0 : styles.index(level.over(defaultFormat));\n const last = ranges.at(-1);\n if (last !== undefined && last.last === column - 1 && last.width === width && last.styleIndex === styleIndex\n && last.bestFit === bestFit && last.customWidth === (w !== undefined)) {\n last.last = column;\n } else {\n ranges.push({ first: column, last: column, width, styleIndex, bestFit, customWidth: w !== undefined });\n }\n }\n return ranges;\n }\n}\n\n/** The parts a Sheet Document's run records. */\nexport function partsOf(run: SheetDocumentAxisFormat): FormatParts {\n return new FormatParts(run.numberFormat, run.alignment, run.font, run.fill, run.borders);\n}\n", "import type { XlsxElement } from '@ex-grid/data-xlsx';\nimport { parseDouble } from './invariant';\nimport type { NotCarriedKind } from './open-report';\nimport { trimWhiteSpace } from './text-casing';\n\n// What a worksheet's element the file layer does not read holds that the Open Report says (ADR-0330 \u00A74), as ExSheet.Xlsx's\n// SheetElements says it: what changes how the Sheet looks or prints, or what else it held. Every file Excel writes carries\n// elements in a form that holds nothing of the kind \u2014 its margins at their defaults, its phonetic settings, the error marks\n// a user dismissed, its dimension \u2014 and those are not listed, so a plain file's report is empty and a listed entry means\n// something was left behind.\n\n/** Excel's default margins, in inches: left, right, top, bottom, header, footer. */\nconst defaultMargins: readonly (readonly [string, number])[] = [['left', 0.7], ['right', 0.7], ['top', 0.75], ['bottom', 0.75], ['header', 0.3], ['footer', 0.3]];\n\n/** One kind of thing not carried, with what names it more closely, where something does. */\nexport interface ElementNotCarried {\n readonly kind: NotCarriedKind;\n readonly detail: string | undefined;\n}\n\n/** What `element` holds that is not carried, each kind with a detail; nothing when it holds none. */\nexport function elementNotCarried(element: XlsxElement): ElementNotCarried[] {\n const kinds: ElementNotCarried[] = [];\n const add = (kind: NotCarriedKind, detail?: string): void => {\n kinds.push({ kind, detail });\n };\n const attribute = (name: string): string | undefined => element.attributes.get(name);\n switch (element.name) {\n // Nothing a Sheet shows or prints: the used range, the sheet's default row (judged below), phonetic settings,\n // dismissed error marks, calculation flags.\n case 'dimension':\n case 'phoneticPr':\n case 'ignoredErrors':\n case 'sheetCalcPr':\n break;\n case 'sheetFormatPr': {\n if (isTrue(attribute('zeroHeight'))) add('hiddenRows');\n if (isTrue(attribute('customHeight'))) add('rowHeights');\n // Excel's own base width is 8 characters, which the default 8.43 is; any other default is the Sheet's own.\n const base = attribute('baseColWidth');\n if (attribute('defaultColWidth') !== undefined || (base !== undefined && base !== '8')) add('defaultColumnWidth');\n break;\n }\n case 'sheetViews':\n if (element.children.some(viewSetsAnything)) add('view');\n break;\n case 'sheetPr':\n if (element.children.some(c => c.name === 'tabColor')) add('sheetProperties');\n if (element.children.some(c => c.name === 'pageSetUpPr' && isTrue(c.attributes.get('fitToPage')))) add('printSettings');\n break;\n case 'pageMargins':\n if (defaultMargins.some(([name, inches]) => {\n const value = attribute(name);\n return value !== undefined && marginInches(value) !== inches;\n })) {\n add('printSettings');\n }\n break;\n case 'printOptions':\n if (['horizontalCentered', 'verticalCentered', 'headings', 'gridLines'].some(a => isTrue(attribute(a)))) add('printSettings');\n break;\n case 'pageSetup':\n if (pageSetupSetsAnything(element)) add('printSettings');\n break;\n case 'headerFooter':\n if (element.children.some(c => c.text !== null && trimWhiteSpace(c.text) !== '')) add('printSettings');\n break;\n case 'rowBreaks':\n case 'colBreaks':\n if (element.children.some(c => c.name === 'brk') || element.childrenCut) add('printSettings');\n break;\n case 'extLst':\n // Each extension by what it holds: Excel 2010's conditional formatting, validation, sparklines, slicers.\n for (const extension of element.children.filter(e => e.name === 'ext')) {\n for (const held of extension.children) kinds.push(...elementNotCarried(held));\n }\n break;\n case 'mergeCells': add('mergedCells'); break;\n case 'conditionalFormatting':\n case 'conditionalFormattings': add('conditionalFormatting'); break;\n case 'dataValidations': add('dataValidation'); break;\n case 'legacyDrawing': add('notesAndComments'); break;\n case 'hyperlinks': add('hyperlinks'); break;\n case 'drawing':\n case 'picture':\n case 'oleObjects':\n case 'controls':\n case 'legacyDrawingHF':\n case 'sparklineGroups': add('picturesAndCharts'); break;\n case 'sheetProtection':\n case 'protectedRanges': add('protection'); break;\n case 'autoFilter':\n case 'sortState': add('autoFilter'); break;\n case 'tableParts': add('excelTable'); break;\n case 'slicerList':\n case 'timelineRefs': add('slicers'); break;\n default: add('other', element.name); break;\n }\n return kinds;\n}\n\n/**\n * Whether a `<sheetView>` changes how the Sheet looks beyond what is carried: gridlines, headings or zeros hidden, Formulas\n * shown, right to left, a zoom, a page layout. The selection and the scroll position change nothing; frozen panes are said on\n * their own (`frozenPanes`).\n */\nfunction viewSetsAnything(view: XlsxElement): boolean {\n if (view.name !== 'sheetView') return false;\n const a = (name: string): string | undefined => view.attributes.get(name);\n const zoom = a('zoomScale');\n const layout = a('view');\n return isFalse(a('showGridLines')) || isFalse(a('showRowColHeaders')) || isFalse(a('showZeros'))\n || isTrue(a('showFormulas')) || isTrue(a('rightToLeft'))\n || (zoom !== undefined && zoom !== '100')\n || (layout !== undefined && layout !== 'normal');\n}\n\n/**\n * Whether a `<pageSetup>` sets anything beyond Excel's defaults (ECMA-376 Part 1, \u00A718.3.1.63). Letter (1) and A4 (9), the\n * paper Excel writes by the machine's locale, are not counted; any other paper, or a size of its own, is. The printer's\n * resolution and its settings part are the printer's, and are not counted.\n */\nfunction pageSetupSetsAnything(element: XlsxElement): boolean {\n for (const [name, value] of element.attributes) {\n let sets: boolean;\n switch (name) {\n case 'horizontalDpi':\n case 'verticalDpi':\n case 'id':\n case 'usePrinterDefaults':\n sets = false;\n break;\n case 'paperSize': sets = value !== '1' && value !== '9'; break;\n case 'orientation': sets = value !== 'default' && value !== 'portrait'; break;\n case 'scale': sets = value !== '100'; break;\n case 'fitToWidth':\n case 'fitToHeight':\n case 'firstPageNumber':\n case 'copies': sets = value !== '1'; break;\n case 'pageOrder': sets = value !== 'downThenOver'; break;\n case 'cellComments': sets = value !== 'none'; break;\n case 'errors': sets = value !== 'displayed'; break;\n case 'blackAndWhite':\n case 'draft':\n case 'useFirstPageNumber': sets = isTrue(value); break;\n default: sets = true; break;\n }\n if (sets) return true;\n }\n return false;\n}\n\nfunction isTrue(value: string | undefined): boolean {\n return value === '1' || value === 'true';\n}\n\nfunction isFalse(value: string | undefined): boolean {\n return value === '0' || value === 'false';\n}\n\n/** A margin in inches; one that does not read as a number differs from every default. */\nfunction marginInches(value: string): number {\n const inches = parseDouble(value);\n return inches === undefined ? Number.NaN : inches;\n}\n", "import { startsWithIgnoreCase, trimWhiteSpace } from './text-casing';\n\n// A Formula's text as an .xlsx stores it, read into the text ExSheet's engine reads (ADR-0330 \u00A74), as ExSheet.Xlsx's\n// StoredFormula reads it: Excel's stored prefixes taken off \u2014 `_xlfn.` before a function newer than Excel 2007, `_xlws.`\n// before a worksheet-only one, and `_xlpm.` before a name a `LET` binds \u2014 and `_xlfn.ANCHORARRAY(A1)` written as the Spill\n// Range reference `A1#` it stands for (ADR-0125). What the engine cannot reach is refused here, by name, before it would read\n// as a plausible `#REF!` or `#NAME?`: another workbook, an Excel Table, and the implicit intersection operator. Text in\n// quotes, and a Sheet's name in quotes, are never touched.\n\n/** Why a Formula as the file stores it is refused before the engine reads it. */\nexport type StoredFormulaProblem =\n | 'none'\n /** A Reference into another workbook: `[1]Sheet1!A1`, `'[1]Sheet 1'!A1`, `[1]!Rate`. */\n | 'otherWorkbook'\n /** A structured reference into an Excel Table: `Table1[Amount]`, `Table1[[#This Row],[Amount]]`. */\n | 'excelTable'\n /** Excel's implicit intersection operator, `@`, stored as `_xlfn.SINGLE`. */\n | 'implicitIntersection'\n /** A Spill Range reference (`_xlfn.ANCHORARRAY`) whose argument is not one cell. */\n | 'spillRange';\n\nconst prefixes = ['_xlfn.', '_xlws.', '_xlpm.'];\n\n/** The Formula ExSheet reads, with its `=`, and the problem that refuses it, `none` when nothing does. */\nexport function readStoredFormula(stored: string): { readonly read: string; readonly problem: StoredFormulaProblem } {\n const refusal = refusalOf(stored);\n if (refusal !== 'none') return { read: `=${stored}`, problem: refusal };\n const anchored = anchorArrays(stripPrefixes(stored));\n return { read: `=${anchored.text}`, problem: anchored.read ? 'none' : 'spillRange' };\n}\n\n/** The text with every stored prefix taken off, outside quotes. */\nexport function stripPrefixes(stored: string): string {\n let text = '';\n let i = 0;\n while (i < stored.length) {\n const c = stored.charAt(i);\n if (c === '\"' || c === \"'\") {\n const end = skipQuoted(stored, i);\n text += stored.slice(i, end);\n i = end;\n continue;\n }\n if (c === '_' && (text.length === 0 || !isNameChar(text.charAt(text.length - 1)))) {\n const prefix = prefixes.find(p => startsWithIgnoreCase(stored, i, p));\n if (prefix !== undefined) {\n i += prefix.length;\n continue;\n }\n }\n text += c;\n i++;\n }\n return text;\n}\n\n/** Why the stored text is refused before it is read, outside quotes; `none` when it is not. */\nfunction refusalOf(stored: string): StoredFormulaProblem {\n for (let i = 0; i < stored.length; i++) {\n const c = stored.charAt(i);\n if (c === '\"') {\n i = skipQuoted(stored, i) - 1;\n continue;\n }\n if (c === \"'\") {\n // A Sheet's name cannot hold '[' (Excel's rule, and ExSheet's): one that starts with it names a workbook.\n if (i + 1 < stored.length && stored.charAt(i + 1) === '[') return 'otherWorkbook';\n i = skipQuoted(stored, i) - 1;\n continue;\n }\n if (c === '[') {\n const before = i > 0 ? stored.charAt(i - 1) : '\\0';\n if (isNameChar(before)) return 'excelTable';\n return /^\\[[0-9]+\\]/.test(stored.slice(i)) ? 'otherWorkbook' : 'excelTable';\n }\n if (c === '@') return 'implicitIntersection';\n if (c === '_' && (i === 0 || !isNameChar(stored.charAt(i - 1))) && startsWithIgnoreCase(stored, i, '_xlfn.SINGLE(')) return 'implicitIntersection';\n }\n return 'none';\n}\n\n/** One cell, as a Spill Range reference names its anchor: `A1`, `$B$2`, `Sheet2!A1`, `'My Sheet'!A1`. */\nconst cellPattern = /^(?:'(?:[^']|'')+'!|[A-Za-z0-9_.\\\\]+!)?\\$?[A-Za-z]{1,3}\\$?[0-9]+$/;\n\n/**\n * Each `ANCHORARRAY(ref)` written as `ref#`; `read` is false when one names anything but one cell, which the engine's\n * grammar does not spell.\n */\nfunction anchorArrays(text: string): { readonly text: string; readonly read: boolean } {\n const name = 'ANCHORARRAY(';\n let written = '';\n let anchored = false;\n let at = 0;\n for (let i = 0; i < text.length; i++) {\n const c = text.charAt(i);\n if (c === '\"' || c === \"'\") {\n i = skipQuoted(text, i) - 1;\n continue;\n }\n if ((c !== 'A' && c !== 'a') || (i > 0 && isNameChar(text.charAt(i - 1))) || !startsWithIgnoreCase(text, i, name)) continue;\n const open = i + name.length;\n let close = open;\n while (close < text.length && text.charAt(close) !== ')') {\n close = text.charAt(close) === '\"' || text.charAt(close) === \"'\" ? skipQuoted(text, close) : close + 1;\n }\n const inner = close < text.length ? trimWhiteSpace(text.slice(open, close)) : '';\n if (!cellPattern.test(inner)) return { text, read: false };\n written += text.slice(at, i) + inner + '#';\n anchored = true;\n at = close + 1;\n i = close;\n }\n return anchored ? { text: written + text.slice(at), read: true } : { text, read: true };\n}\n\n/** Where the quoted run that starts at `start` ends: past its closing quote, a doubled quote read as one. */\nfunction skipQuoted(text: string, start: number): number {\n const quote = text.charAt(start);\n let i = start + 1;\n while (i < text.length) {\n if (text.charAt(i) === quote) {\n if (i + 1 < text.length && text.charAt(i + 1) === quote) {\n i += 2;\n continue;\n }\n return i + 1;\n }\n i++;\n }\n return text.length;\n}\n\n/** `char.IsLetterOrDigit(c) || c is '_' or '.' or '\\\\' or '?'`, of one code unit. */\nexport function isNameChar(c: string): boolean {\n return /^[\\p{L}\\p{Nd}_.\\\\?]$/u.test(c);\n}\n", "import {\n BorderLine, CellBorders, CellColour, CellFill, CellFont, CellFormat, NumberFormat,\n type BorderLineStyle, type HorizontalAlignment,\n} from '@ex-grid/sheet-engine';\nimport {\n defaultAlignment,\n type XlsxBorderEdge, type XlsxBorderStyle, type XlsxCellFormat, type XlsxColor, type XlsxFont, type XlsxStyles, type XlsxTheme,\n} from '@ex-grid/data-xlsx';\nimport { elementAt } from './must';\nimport { readNumberFormat } from './number-formats';\nimport type { NotCarriedKind } from './open-report';\nimport { equalsIgnoreCase } from './text-casing';\n\n// Reads the styles part's cell formats into the engine's Cell Formats (ADR-0330 \u00A74, \u00A78, ADR-0071), each once, as\n// ExSheet.Xlsx's StyleReading reads them. Carried: the Number Format, horizontal alignment (General, left, centre, right),\n// the Font's colour, bold, italic, underline and strikethrough, a solid Fill, and the four sides' borders in Excel's thirteen\n// line styles. A colour is the RGB the file's theme or palette gives it; the default font's own colour, where it is black,\n// is Automatic, the Ink, as a plain Excel workbook shows its text. Not carried, and said: another typeface or size than the\n// workbook's own, vertical alignment, wrapping, indent, rotation and shrinking, the other horizontal alignments, double and\n// accounting underlines (a single one is carried), pattern and gradient fills, and diagonal borders.\n\n/** A cell format of the file read into the engine's Cell Format: what crosses, what cannot, and what is not carried. */\nexport interface ReadFormat {\n /** The Cell Format, every part the file's, or its default where the part cannot cross. */\n readonly format: CellFormat;\n /** Why its Number Format cannot cross, or `undefined`; a level that records it refuses the file. */\n readonly refusal: string | undefined;\n /** What the refusal names as held: the code, or the id. */\n readonly held: string | undefined;\n /** What it holds that is not carried, each kind once. */\n readonly notCarried: readonly NotCarriedKind[];\n /** Whether a colour it carries names a theme slot: carried as the theme's RGB, the link not. */\n readonly namesTheme: boolean;\n}\n\nexport class StyleReading {\n readonly #styles: XlsxStyles;\n readonly #theme: XlsxTheme;\n readonly #read = new Map<number, ReadFormat>();\n readonly #workbookFont: XlsxFont;\n\n constructor(styles: XlsxStyles, theme: XlsxTheme) {\n this.#styles = styles;\n this.#theme = theme;\n this.#workbookFont = elementAt(styles.fonts, 0);\n }\n\n /** The cell format at `index` of the styles' cell formats, read once. */\n at(index: number): ReadFormat {\n let format = this.#read.get(index);\n if (format === undefined) {\n format = this.#readFormat(elementAt(this.#styles.cellFormats, index));\n this.#read.set(index, format);\n }\n return format;\n }\n\n #readFormat(xf: XlsxCellFormat): ReadFormat {\n const styles = this.#styles;\n const notCarried: NotCarriedKind[] = [];\n let namesTheme = false;\n const note = (kind: NotCarriedKind): void => {\n if (!notCarried.includes(kind)) notCarried.push(kind);\n };\n const colour = (color: XlsxColor | null): CellColour => {\n if (color === null) return CellColour.automatic;\n const argb = this.#theme.resolve(color, styles.indexedColors);\n if (argb === undefined) return CellColour.automatic;\n namesTheme ||= color.kind === 'theme';\n return CellColour.fromRgb(argb & 0xFFFFFF);\n };\n\n let refusal: string | undefined;\n let held: string | undefined;\n let numberFormat = NumberFormat.general;\n const read = readNumberFormat(xf.numberFormatId, styles.numberFormats.get(xf.numberFormatId));\n if (read.format !== undefined) {\n numberFormat = read.format;\n } else {\n refusal = read.reason;\n held = read.held;\n }\n\n const a = xf.alignment === null ? defaultAlignment : xf.alignment;\n let alignment: HorizontalAlignment | undefined;\n switch (a.horizontal) {\n case 'general':\n case 'left':\n case 'center':\n case 'right':\n alignment = a.horizontal;\n break;\n case 'fill':\n case 'justify':\n case 'centerContinuous':\n case 'distributed':\n note('horizontalAlignment');\n break;\n default:\n return unreachableAlignment(a.horizontal);\n }\n if (a.vertical !== 'bottom') note('verticalAlignment');\n if (a.wrapText || a.indent !== 0 || a.textRotation !== 0 || a.shrinkToFit) note('textLayout');\n\n const f = elementAt(styles.fonts, xf.fontId);\n if (!sameFace(f, this.#workbookFont)) note('fontNamesAndSizes');\n if (f.underline !== 'none' && f.underline !== 'single') note('underline');\n const font = new CellFont({ colour: this.#fontColour(f.color, colour), bold: f.bold, italic: f.italic, underline: f.underline !== 'none', strikethrough: f.strike });\n\n let fill = CellFill.none;\n const x = elementAt(styles.fills, xf.fillId);\n if (x.isGradient || (x.pattern !== 'none' && x.pattern !== 'solid')) {\n note('patternFills');\n } else if (x.pattern === 'solid') {\n // A solid fill whose colour is automatic, or names no colour the palette holds, has no RGB to carry.\n const solid = colour(x.foreground);\n if (solid.isAutomatic) note('patternFills');\n else fill = CellFill.solid(solid);\n }\n\n const b = elementAt(styles.borders, xf.borderId);\n if ((b.diagonalUp || b.diagonalDown) && b.diagonal.style !== 'none') note('diagonalBorders');\n const line = (edge: XlsxBorderEdge): BorderLine => (edge.style === 'none' ? BorderLine.none : new BorderLine(lineStyle(edge.style), colour(edge.color)));\n const borders = new CellBorders({ top: line(b.top), bottom: line(b.bottom), left: line(b.left), right: line(b.right) });\n\n return {\n format: new CellFormat(numberFormat, alignment === undefined ? 'general' : alignment, font, fill, borders),\n refusal, held, notCarried, namesTheme,\n };\n }\n\n /**\n * A Font's colour: the workbook font's own colour, where it paints black, is Automatic, the Ink, as Excel's own default\n * text (Text 1 of the Office theme) is; any other is the RGB it resolves to.\n */\n #fontColour(color: XlsxColor | null, colour: (color: XlsxColor | null) => CellColour): CellColour {\n const own = this.#workbookFont.color;\n if (color !== null && own !== null && sameColor(color, own)) {\n const argb = this.#theme.resolve(color, this.#styles.indexedColors);\n if (argb === undefined || argb >>> 0 === 0xFF000000 || argb === 0) return CellColour.automatic;\n }\n return colour(color);\n }\n}\n\nfunction unreachableAlignment(value: never): never {\n throw new Error(`Internal: ${String(value)} is not a horizontal alignment.`);\n}\n\n/** Whether two colours are the same as the C# record compares them. */\nfunction sameColor(a: XlsxColor, b: XlsxColor): boolean {\n return a.kind === b.kind && a.value === b.value && a.tint === b.tint;\n}\n\n/** Whether a font has the workbook font's typeface and size; one that names none takes the workbook's. */\nfunction sameFace(font: XlsxFont, workbook: XlsxFont): boolean {\n return (font.name === null || (workbook.name !== null && equalsIgnoreCase(font.name, workbook.name)))\n && (font.size === null || font.size === workbook.size);\n}\n\nconst fromFile: ReadonlyMap<XlsxBorderStyle, BorderLineStyle> = new Map<XlsxBorderStyle, BorderLineStyle>([\n ['thin', 'thin'], ['medium', 'medium'], ['dashed', 'dashed'], ['dotted', 'dotted'], ['thick', 'thick'], ['double', 'double'],\n ['hair', 'hair'], ['mediumDashed', 'mediumDashed'], ['dashDot', 'dashDot'], ['mediumDashDot', 'mediumDashDot'],\n ['dashDotDot', 'dashDotDot'], ['mediumDashDotDot', 'mediumDashDotDot'], ['slantDashDot', 'slantedDashDot'],\n]);\n\n/** The engine's line style for the file's: the same thirteen (ADR-0071). */\nexport function lineStyle(style: XlsxBorderStyle): BorderLineStyle {\n const engine = fromFile.get(style);\n return engine === undefined ? 'none' : engine;\n}\n\n/** The file's line style for the engine's. */\nexport function fileLineStyle(style: BorderLineStyle): XlsxBorderStyle {\n for (const [file, engine] of fromFile) {\n if (engine === style) return file;\n }\n return 'none';\n}\n", "import { NumberFormat, type Culture } from '@ex-grid/sheet-engine';\nimport { firstCustomNumberFormat } from '@ex-grid/data-xlsx';\nimport { equalsIgnoreCase } from './text-casing';\n\n// A Number Format between an .xlsx's id and code and the engine's NumberFormat, both ways (ADR-0330 \u00A74, ADR-0071), as\n// ExSheet.Xlsx's XlsxNumberFormats crosses it. A built-in id is the engine's format of the same meaning: the dates and the\n// time Excel shows in the culture's own form (the short date 14 and 22, 15, 16, 20) are the engine's built-ins of the same\n// invariant code, which it shows in the Workbook's culture as Excel shows them in the computer's; the rest are their fixed\n// codes (ECMA-376 Part 1, \u00A718.8.30). The currencies 5 to 8 are read from the code the file spells, as every other id whose\n// code follows the computer's locale: an amount is never shown in the reader's currency where the file meant another.\n// Written, the engine's built-in currency is a code of the file's own that spells the Workbook culture's currency, so that\n// it means the same amount under every locale Excel opens it in. A format of the file's own is read as written. A code the\n// engine does not read, or a built-in id whose code follows the computer's locale and that the file does not spell out,\n// cannot cross, and the file is refused by name: a cell shown in General instead would show a date as `45000`, or drop a\n// currency symbol, and look plausible.\n\n/**\n * The built-ins whose meaning is fixed, by id, in the engine's invariant codes. 14 and 22 are the engine's built-in short\n * dates (ECMA-376 spells them `mm-dd-yy` and `m/d/yy h:mm`, and Excel shows both in the computer's short-date pattern). The\n * currencies 5 to 8 are not here: Excel shows them in the computer's currency.\n */\nconst builtIns: ReadonlyMap<number, string> = new Map([\n [0, 'General'],\n [1, '0'],\n [2, '0.00'],\n [3, '#,##0'],\n [4, '#,##0.00'],\n [9, '0%'],\n [10, '0.00%'],\n [11, '0.00E+00'],\n [12, '# ?/?'],\n [13, '# ??/??'],\n [14, 'm/d/yyyy'],\n [15, 'd-mmm-yy'],\n [16, 'd-mmm'],\n [17, 'mmm-yy'],\n [18, 'h:mm AM/PM'],\n [19, 'h:mm:ss AM/PM'],\n [20, 'h:mm'],\n [21, 'h:mm:ss'],\n [22, 'm/d/yyyy h:mm'],\n [37, '#,##0 ;(#,##0)'],\n [38, '#,##0 ;[Red](#,##0)'],\n [39, '#,##0.00;(#,##0.00)'],\n [40, '#,##0.00;[Red](#,##0.00)'],\n [45, 'mm:ss'],\n [46, '[h]:mm:ss'],\n [47, 'mmss.0'],\n [48, '##0.0E+0'],\n [49, '@'],\n]);\n\n/** The built-ins the engine shows in the culture's own form; a code of the engine's that spells one, in any case, is it. */\nconst localised: ReadonlySet<number> = new Set([14, 15, 16, 20, 22]);\n\n/** The engine's built-in currency, in its invariant codes, with and without decimals (`NumberFormat.builtInCurrency`). */\nconst builtInCurrencies = ['$#,##0.00_);[Red]($#,##0.00)', '$#,##0_);[Red]($#,##0)'];\n\n/**\n * The code a format of the file's own writes for `format` under the Workbook's `culture`: the engine's built-in currency\n * spelled in the culture's currency (`NumberFormat.localCode`), so that the file says which currency it is; any other format\n * its own code.\n */\nexport function writtenCode(format: NumberFormat, culture: Culture): string {\n return builtInCurrencies.some(c => equalsIgnoreCase(c, format.code)) ? format.localCode(culture) : format.code;\n}\n\n/** What reading a cell format's Number Format gives: the format, or why it cannot cross and what the refusal names as held. */\nexport type NumberFormatRead =\n | { readonly format: NumberFormat; readonly reason?: undefined; readonly held?: undefined }\n | { readonly format?: undefined; readonly reason: string; readonly held: string };\n\n/**\n * The format a cell format's `id` names, with the `code` the styles part writes for it, or the reason it cannot cross and\n * what to name. A built-in the engine knows is that built-in, whatever code the part writes beside it; any other id is the\n * code the part writes.\n */\nexport function readNumberFormat(id: number, code: string | undefined): NumberFormatRead {\n const builtIn = builtIns.get(id);\n if (builtIn !== undefined) {\n const reading = NumberFormat.tryParse(builtIn);\n if (reading.format !== undefined) return { format: reading.format };\n return { reason: `Excel's built-in Number Format ${String(id)} (${builtIn}) is not one the engine reads: ${reading.reason}`, held: builtIn };\n }\n if (code === undefined) {\n return {\n held: `Number Format ${String(id)}`,\n reason: id < firstCustomNumberFormat\n ? `The cell takes Excel's built-in Number Format ${String(id)}, whose code follows the computer's locale, and the file does not spell it out.`\n : `The cell takes the Number Format ${String(id)}, which the file does not hold.`,\n };\n }\n const reading = NumberFormat.tryParseAsWritten(code);\n if (reading.format !== undefined) return { format: reading.format };\n return { reason: `The Number Format '${code}' is not one the engine reads: ${reading.reason}`, held: code };\n}\n\n/**\n * The built-in id `format` is written as, or `undefined` for one written as a format of the file's own. A built-in the engine\n * shows in the culture's form is its id whatever the case of its code, as the engine reads it; any other is its id only when\n * its code is the built-in's exactly.\n */\nexport function builtInId(format: NumberFormat): number | undefined {\n for (const [id, code] of builtIns) {\n const same = localised.has(id) ? equalsIgnoreCase(code, format.code) : code === format.code;\n if (same) return id;\n }\n return format.isGeneral ? 0 : undefined;\n}\n", "import {\n CellAddress, Sheet,\n type Culture, type Entry, type LinkedTable, type SheetDocument, type Value, type Workbook,\n} from '@ex-grid/sheet-engine';\nimport {\n createXlsxWriter, defaultMaxCells, defaultMaxUncompressedBytes, formatCell, isValidTableName, maxColumns, maxRows, XlsxError,\n type XlsxCellInput, type XlsxSheetWriter, type XlsxWriter,\n} from '@ex-grid/data-xlsx';\nimport { FormatParts } from './format-parts';\nimport { grouped, roundTrip } from './invariant';\nimport { elementAt } from './must';\nimport { XlsxSaveError, type XlsxSaveOptions } from './save-error';\nimport { SavePacer } from './save-pacer';\nimport { SheetFormatPlan } from './sheet-format-plan';\nimport { StyleTable } from './style-table';\nimport { foldCase } from './text-casing';\nimport { maxArguments, maxDepth, maxText, writeFormula } from './written-formula';\n\n// Writes a Workbook as it stands to an .xlsx (ADR-0330 \u00A76), as ExSheet.Xlsx's XlsxWorkbookWriter writes it: every Sheet, in\n// order, as a worksheet of its name, the Sheet shown shown; every constant; every Formula with the Value it shows, Excel's\n// stored prefixes put back; the cells an array spills into with their Values; the Cell Formats at cell, row and column level\n// and the column widths in Excel's unit. Each Linked Table is written after the Sheets as an Excel Table of its name, on a\n// worksheet of its name, holding its rows as they stand, so that a Formula that reads it (`Positions[PV]`) reads it in Excel\n// too. The workbook is marked to be calculated in full when Excel opens it, and a program that does not calculate reads the\n// Values the user saw, `RAND()`'s included. What cannot be written faithfully is refused by name, and nothing is returned.\n//\n// Every Formula is written as a dynamic array (`t=\"array\"`, marked by the workbook's cell metadata as Excel 365 marks one),\n// over the cells it spills into or its own cell alone: written plainly, Excel reads it as one of an earlier version, where a\n// range an operator or a function's argument takes is implicitly intersected, and its Value would change (ADR-0125).\n\n/** The longest Formula Excel holds, in characters, without its `=`. */\nexport const maxFormulaLength = 8_192;\n\n/** The longest text a cell of Excel holds, in characters. */\nexport const maxTextLength = 32_767;\n\n/** The most rows a Linked Table written as an Excel Table holds: a worksheet's 1,048,576, less its header's. */\nexport const maxLinkedTableRows = maxRows - 1;\n\n/**\n * Writes `workbook` as it stands as an .xlsx, or refuses it by name (`XlsxSaveError`), returning nothing.\n *\n * The Workbook's snapshot is taken before the write first yields \u2014 every Sheet's document, every Value it shows, its spills\n * and each Linked Table's rows \u2014 and the file is built from that snapshot while yielding (ADR-0330 \u00A79): the file is the\n * Workbook as it stood when the call was made, and the Workbook may change once the returned promise is under way. A Linked\n * Table's worksheet is written for Excel, and is not read back as a Linked Table (ADR-0330 \u00A76): opened again, it is a\n * worksheet of the table's cells.\n *\n * @param workbook - The Workbook.\n * @param options - What the write may produce, and how it paces itself; the defaults when left out.\n * @returns The file, as a Blob of the spreadsheet's media type.\n * @throws XlsxSaveError - The Workbook is refused, and nothing was written.\n * @throws RangeError - `maxUncompressedBytes` lies outside 1 to `defaultMaxUncompressedBytes`, or `maxCells` is not a number.\n */\nexport async function saveXlsxWorkbook(workbook: Workbook, options: XlsxSaveOptions = {}): Promise<Blob> {\n options.signal?.throwIfAborted();\n const maxBytes = options.maxUncompressedBytes === undefined ? defaultMaxUncompressedBytes : options.maxUncompressedBytes;\n if (!(maxBytes >= 1 && maxBytes <= defaultMaxUncompressedBytes)) {\n throw new RangeError(`MaxUncompressedBytes is 1 to ${grouped(defaultMaxUncompressedBytes)}.`);\n }\n const maxCells = options.maxCells === undefined ? defaultMaxCells : options.maxCells;\n if (typeof maxCells !== 'number' || Number.isNaN(maxCells)) throw new RangeError(`MaxCells is a number of elements, not ${String(maxCells)}.`);\n\n // Everything the file says is taken here, synchronously, before the write first yields; the rest reads only this.\n const snapshot = snapshotOf(workbook);\n const pacer = new SavePacer(options);\n let writer: XlsxWriter | undefined;\n try {\n writer = await build(snapshot, maxCells, maxBytes, pacer);\n // The parts written last are written here; a write cancelled meanwhile returns nothing.\n const file = await writer.complete();\n options.signal?.throwIfAborted();\n return file;\n } catch (e) {\n await writer?.abandon();\n if (e instanceof XlsxError && e.reason === 'tooLarge') throw tooLarge(e, maxBytes);\n throw e;\n }\n}\n\nfunction tooLarge(e: XlsxError, maxBytes: number): XlsxSaveError {\n const part = e.part === undefined ? '' : e.part;\n return new XlsxSaveError('tooLarge',\n `The workbook would hold more than the ${grouped(maxBytes)} uncompressed bytes a file is written with, and read with by default; the part '${part}' went past it.`,\n { sheet: e.sheet });\n}\n\n/** A Sheet as it stood: its document, the Value of every cell holding one, and the Anchor each spilled cell spills from. */\ninterface SheetSnapshot {\n readonly name: string;\n readonly document: SheetDocument;\n /** By the cell's key. */\n readonly values: ReadonlyMap<number, Value>;\n /** The Anchor of each spilled cell, by the cell's key, in the order the Sheet lists them. */\n readonly spilledFrom: ReadonlyMap<number, { readonly at: CellAddress; readonly anchor: CellAddress }>;\n}\n\n/** A Linked Table as it stood: its declaration, and its rows column by column, or `undefined` while it waits. */\ninterface TableSnapshot {\n readonly table: LinkedTable;\n readonly columns: readonly (readonly (Value | undefined)[])[] | undefined;\n}\n\n/**\n * The Workbook as it stood when the write was called: all the write reads, taken synchronously, in time that grows with the\n * cells holding a Value and not with what the file writes for them.\n */\ninterface Snapshot {\n readonly culture: Culture;\n readonly shown: number;\n readonly sheets: readonly SheetSnapshot[];\n /** Each Sheet's name, by its name folded. */\n readonly sheetNames: ReadonlyMap<string, string>;\n readonly tables: readonly TableSnapshot[];\n}\n\nfunction snapshotOf(workbook: Workbook): Snapshot {\n const document = workbook.toDocument();\n const sheets: SheetSnapshot[] = [];\n const names = new Map<string, string>();\n workbook.sheets.forEach((sheet, i) => {\n const values = new Map<number, Value>();\n const spilledFrom = new Map<number, { readonly at: CellAddress; readonly anchor: CellAddress }>();\n for (const at of sheet.valueAddresses) {\n const value = sheet.getValue(at);\n if (value !== undefined) values.set(at.key, value);\n const anchor = sheet.spilledFrom(at);\n if (anchor !== undefined) spilledFrom.set(at.key, { at, anchor });\n }\n sheets.push({ name: sheet.name, document: elementAt(document.sheets, i), values, spilledFrom });\n if (!names.has(foldCase(sheet.name))) names.set(foldCase(sheet.name), sheet.name);\n });\n // A table's rows are read-only, and replaced whole by a later snapshot: holding the reference holds them as they are.\n const tables = workbook.linkedTables.map(table => ({ table, columns: table.isWaiting ? undefined : workbook.linkedTableColumns(table.name) }));\n return { culture: workbook.culture, shown: indexOf(workbook, workbook.shown), sheets, sheetNames: names, tables };\n}\n\nfunction indexOf(workbook: Workbook, sheet: Sheet): number {\n const sheets = workbook.sheets;\n for (let i = 0; i < sheets.length; i++) {\n if (sheets[i] === sheet) return i;\n }\n return 0;\n}\n\n/** One cell element a Sheet writes of its own: an Entry, a spilled Value, or a format. */\ninterface Recorded {\n readonly at: CellAddress;\n readonly entry: Entry | undefined;\n readonly style: number;\n}\n\ninterface OwnCell {\n readonly at: CellAddress;\n readonly entry: Entry | undefined;\n readonly own: FormatParts;\n}\n\ninterface Planned {\n readonly sheet: SheetSnapshot;\n readonly plan: SheetFormatPlan;\n readonly cells: readonly OwnCell[];\n}\n\n/** A Linked Table to write as an Excel Table: its declaration, and its snapshot column by column. */\ninterface PlannedTable {\n readonly table: LinkedTable;\n readonly columns: readonly (readonly (Value | undefined)[])[];\n}\n\n/**\n * The snapshot written into a package held in memory, every part but those written on completion: first every element\n * counted against the limit, then written, yielding between slices.\n */\nasync function build(snapshot: Snapshot, maxCells: number, maxBytes: number, pacer: SavePacer): Promise<XlsxWriter> {\n pacer.sheets = snapshot.sheets.length + snapshot.tables.length;\n const tables = await tablesOf(snapshot, pacer);\n const planned: Planned[] = [];\n let cells = 0;\n for (const sheet of snapshot.sheets) {\n if (!carries(sheet.name, true)) {\n throw new XlsxSaveError('text',\n 'The Sheet\\'s name holds a character a file cannot carry in a worksheet\\'s name: a control character below U+0020, U+FFFE or U+FFFF, or half of a surrogate pair.',\n { sheet: sheet.name });\n }\n const own = ownCells(sheet);\n const plan = new SheetFormatPlan(sheet.document);\n const crossings = plan.crossings(own.map(c => c.at));\n const rows = plan.formattedRows;\n cells += own.length + crossings + rows;\n if (cells > maxCells) {\n throw new XlsxSaveError('tooManyCells',\n `The workbook would write more than the ${grouped(maxCells)} elements it may (XlsxSaveOptions.MaxCells, which counts the cells written and each row a row format writes; by default the cells a file is read with): this Sheet writes ${grouped(own.length)} cells of its own, ${grouped(crossings)} where its formatted rows cross its formatted columns, and ${grouped(rows)} rows its row formats write.`,\n { sheet: sheet.name });\n }\n planned.push({ sheet, plan, cells: own });\n await pacer.checkpoint();\n }\n for (const { table, columns } of tables) {\n cells += table.columns.length;\n for (const column of columns) {\n for (const value of column) if (value !== undefined) cells++;\n }\n if (cells > maxCells) {\n throw new XlsxSaveError('tooManyCells',\n `The workbook would write more than the ${grouped(maxCells)} elements it may (XlsxSaveOptions.MaxCells, which counts the cells written and each row a row format writes; by default the cells a file is read with): the Linked Table '${table.name}' writes ${grouped(table.rowCount)} rows of ${grouped(table.columns.length)} columns under its header.`,\n { sheet: table.name });\n }\n }\n\n const styles = new StyleTable(snapshot.culture);\n const sheets: { readonly sheet: SheetSnapshot; readonly plan: SheetFormatPlan; readonly cells: readonly Recorded[]; readonly spills: ReadonlyMap<number, CellAddress> }[] = [];\n for (const { sheet, plan, cells: own } of planned) {\n plan.build(styles);\n const recorded: Recorded[] = [];\n for (const { at, entry, own: parts } of own) {\n recorded.push({ at, entry, style: plan.style(styles, parts, at) });\n const step = pacer.step(0);\n if (step !== undefined) await step;\n }\n sheets.push({ sheet, plan, cells: recorded, spills: spillsOf(sheet) });\n }\n\n pacer.total = cells;\n pacer.sheet = 0;\n const writer = createXlsxWriter({\n styles: styles.build(),\n activeSheet: snapshot.shown,\n fullCalculationOnLoad: true,\n maxUncompressedBytes: maxBytes,\n });\n const declared = new Map<string, readonly string[]>();\n for (const { table } of snapshot.tables) {\n if (!declared.has(foldCase(table.name))) declared.set(foldCase(table.name), table.columns);\n }\n const columnsOf = (name: string): readonly string[] | undefined => declared.get(foldCase(name));\n const hasSheet = (name: string): boolean => snapshot.sheetNames.has(foldCase(name));\n try {\n for (const { sheet, plan, cells: recorded, spills } of sheets) {\n const out = new Paced(writer.addSheet(sheet.name, plan.columns), pacer);\n await writeSheet(out, sheet, plan, recorded, spills, hasSheet, columnsOf);\n pacer.sheet++;\n }\n for (const table of tables) {\n await writeTable(new Paced(writer.addSheet(table.table.name), pacer), table);\n pacer.sheet++;\n }\n pacer.sheet = Math.max(0, pacer.sheets - 1);\n pacer.report();\n return writer;\n } catch (e) {\n await writer.abandon();\n throw e;\n }\n}\n\n/** The elements written between two flushes of a sheet's text, so that memory holds it compressed. */\nconst flushEvery = 4096;\n\n/** A worksheet's writer that counts each element against the pacer, and flushes its text between batches. */\nclass Paced {\n readonly sheet: XlsxSheetWriter;\n readonly #pacer: SavePacer;\n #since = 0;\n\n constructor(sheet: XlsxSheetWriter, pacer: SavePacer) {\n this.sheet = sheet;\n this.#pacer = pacer;\n }\n\n async row(row: number, style: number): Promise<void> {\n this.sheet.writeRow({ row, styleIndex: style });\n await this.#step();\n }\n\n async cell(cell: XlsxCellInput): Promise<void> {\n this.sheet.write(cell);\n await this.#step();\n }\n\n async #step(): Promise<void> {\n if (++this.#since >= flushEvery) {\n this.#since = 0;\n await this.sheet.flush();\n }\n const step = this.#pacer.step();\n if (step !== undefined) await step;\n }\n}\n\n/**\n * Each Linked Table with its snapshot, in the order they were declared, or the refusal of the first that cannot be written\n * as an Excel Table on a worksheet of its name (ADR-0330 \u00A76).\n */\nasync function tablesOf(snapshot: Snapshot, pacer: SavePacer): Promise<PlannedTable[]> {\n const tables: PlannedTable[] = [];\n for (const { table, columns } of snapshot.tables) {\n const name = table.name;\n const where = { sheet: name };\n if (table.isWaiting || columns === undefined) {\n throw new XlsxSaveError('linkedTable',\n `The Linked Table '${name}' has not answered: it holds no rows yet, or its last snapshot was refused, and every Formula that reads it shows #GETTING_DATA. Its rows are written as they stand, and it has none to write.`, where);\n }\n const sheet = snapshot.sheetNames.get(foldCase(name));\n if (sheet !== undefined) {\n throw new XlsxSaveError('linkedTable', `The Linked Table '${name}' is written on a worksheet of its name, and the Sheet '${sheet}' already has it.`, where);\n }\n if (!isValidTableName(name)) {\n // The engine takes some names Excel gives no Table, such as A01, which a file reads as the cell A1.\n throw new XlsxSaveError('linkedTable',\n `The Linked Table '${name}' is written as an Excel Table of its name, and Excel gives a Table no such name: it reads as a cell's address, or holds a character a Table's name does not.`, where);\n }\n const why = Sheet.whyNotAName(name);\n if (why !== undefined) {\n throw new XlsxSaveError('linkedTable', `The Linked Table '${name}' is written on a worksheet of its name, and a worksheet cannot have it: ${why}`, where);\n }\n if (table.columns.length > maxColumns) {\n throw new XlsxSaveError('linkedTable',\n `The Linked Table '${name}' has ${grouped(table.columns.length)} columns, and a worksheet of Excel holds ${grouped(maxColumns)}.`, where);\n }\n if (table.rowCount === 0) {\n // ROWS(Positions[PV]) is 0 in ExSheet, and 1 in Excel, which holds a table of no rows as one empty row.\n throw new XlsxSaveError('linkedTable',\n `The Linked Table '${name}' holds no rows, and an Excel Table holds at least one: written with one empty row, its Formulas would answer otherwise in Excel (ROWS gives 1, COUNTBLANK 1, the column itself 0 where ExSheet shows #VALUE!).`, where);\n }\n if (table.rowCount > maxLinkedTableRows) {\n throw new XlsxSaveError('linkedTable',\n `The Linked Table '${name}' holds ${grouped(table.rowCount)} rows, and a worksheet of Excel holds ${grouped(maxRows)}, its header's included.`, where);\n }\n for (let c = 0; c < columns.length; c++) {\n const columnName = elementAt(table.columns, c);\n checkTableText(name, columnName, 0, c, 'as a column\\'s name');\n const column = elementAt(columns, c);\n for (let r = 0; r < column.length; r++) {\n const value = column[r];\n if (value !== undefined && value.kind === 'text') {\n checkTableText(name, value.text, r + 1, c, `in its column '${columnName}', row ${grouped(r + 1)},`);\n }\n const step = pacer.step(0);\n if (step !== undefined) await step;\n }\n }\n tables.push({ table, columns });\n }\n return tables;\n}\n\n/**\n * Refuses text of a Linked Table that a cell of Excel cannot hold: longer than 32,767 characters, or holding half of a\n * surrogate pair.\n * @param table - The table's name, which its worksheet has.\n * @param text - The text.\n * @param row - The worksheet's row it is written in, from zero: the header's is 0.\n * @param column - The worksheet's column it is written in, from zero.\n * @param at - Where the table holds it, in words.\n */\nfunction checkTableText(table: string, text: string, row: number, column: number, at: string): void {\n const cell = formatCell(row, column);\n if (text.length > maxTextLength) {\n throw new XlsxSaveError('text',\n `The Linked Table '${table}' holds, ${at} text ${grouped(text.length)} characters long, and a cell of Excel holds at most ${grouped(maxTextLength)}.`, { sheet: table, cell });\n }\n if (!carries(text, false)) {\n throw new XlsxSaveError('text', `The Linked Table '${table}' holds, ${at} text with half of a surrogate pair, which a file cannot carry.`, { sheet: table, cell });\n }\n}\n\n/** A Linked Table's worksheet: its header at A1, each column's name, and its rows below as they stand, as an Excel Table of its name. */\nasync function writeTable(out: Paced, { table, columns }: PlannedTable): Promise<void> {\n out.sheet.addTable({ name: table.name, headerRow: 0, firstColumn: 0, columns: table.columns, dataRows: table.rowCount });\n for (let c = 0; c < table.columns.length; c++) {\n await out.cell({ row: 0, column: c, type: 'sharedString', text: elementAt(table.columns, c) });\n }\n for (let r = 0; r < table.rowCount; r++) {\n for (let c = 0; c < columns.length; c++) {\n const value = elementAt(columns, c)[r];\n if (value === undefined) continue;\n const row = r + 1;\n switch (value.kind) {\n case 'number':\n await out.cell({ row, column: c, type: 'number', value: roundTrip(value.number) });\n break;\n case 'text':\n await out.cell({ row, column: c, type: 'sharedString', text: value.text });\n break;\n case 'boolean':\n await out.cell({ row, column: c, type: 'boolean', value: value.boolean ? '1' : '0' });\n break;\n case 'error':\n await out.cell({ row, column: c, type: 'error', value: value.toString() });\n break;\n }\n }\n }\n}\n\n/**\n * The cells a Sheet writes of its own, in the sheet's order: each the document records (an Entry, or a format of its own),\n * and each an array spills into.\n */\nfunction ownCells(sheet: SheetSnapshot): OwnCell[] {\n const cells = new Map<number, OwnCell>();\n for (const cell of sheet.document.cells) {\n cells.set(cell.address.key, {\n at: cell.address, entry: cell.entry, own: new FormatParts(cell.numberFormat, cell.alignment, cell.font, cell.fill, cell.borders),\n });\n }\n for (const [key, { at }] of sheet.spilledFrom) {\n if (!cells.has(key)) cells.set(key, { at, entry: undefined, own: FormatParts.empty });\n }\n return [...cells.values()].toSorted((a, b) => a.at.compareTo(b.at));\n}\n\n/** Each spilling Anchor, by its key, with the last cell of its Spill Range. */\nfunction spillsOf(sheet: SheetSnapshot): Map<number, CellAddress> {\n const spills = new Map<number, CellAddress>();\n for (const { at, anchor } of sheet.spilledFrom.values()) {\n const last = spills.get(anchor.key);\n spills.set(anchor.key, last === undefined ? at : new CellAddress(Math.max(last.row, at.row), Math.max(last.column, at.column)));\n }\n return spills;\n}\n\n/** A Sheet's rows, in order: each formatted row with its format, and every cell element in it, its own and its crossings'. */\nasync function writeSheet(\n out: Paced, sheet: SheetSnapshot, plan: SheetFormatPlan, cells: readonly Recorded[], spills: ReadonlyMap<number, CellAddress>,\n hasSheet: (name: string) => boolean, columnsOf: (name: string) => readonly string[] | undefined,\n): Promise<void> {\n const write = (cell: Recorded): Promise<void> => out.cell(cellOf(sheet, cell, spills, hasSheet, columnsOf));\n const runs = plan.rows;\n let run = 0;\n let runRow = runs.length > 0 ? elementAt(runs, 0).first : Number.MAX_SAFE_INTEGER;\n let next = 0;\n while (next < cells.length || run < runs.length) {\n const cellRow = next < cells.length ? elementAt(cells, next).at.row : Number.MAX_SAFE_INTEGER;\n const row = Math.min(cellRow, runRow);\n let end = next;\n while (end < cells.length && elementAt(cells, end).at.row === row) end++;\n if (row === runRow) {\n const formatted = elementAt(runs, run);\n await out.row(row, formatted.style);\n let at = next;\n for (const crossing of formatted.crossings) {\n for (let column = crossing.first; column <= crossing.last; column++) {\n while (at < end && elementAt(cells, at).at.column < column) await write(elementAt(cells, at++));\n if (at < end && elementAt(cells, at).at.column === column) continue;\n await out.cell({ row, column, type: 'number', value: null, styleIndex: crossing.style });\n }\n }\n while (at < end) await write(elementAt(cells, at++));\n runRow++;\n if (runRow > formatted.last) {\n run++;\n runRow = run < runs.length ? elementAt(runs, run).first : Number.MAX_SAFE_INTEGER;\n }\n } else {\n for (let at = next; at < end; at++) await write(elementAt(cells, at));\n }\n next = end;\n }\n}\n\n/** One cell of the Sheet's own: its constant, or its Formula with the Value it shows, or a spilled Value, or its format alone. */\nfunction cellOf(\n sheet: SheetSnapshot, cell: Recorded, spills: ReadonlyMap<number, CellAddress>,\n hasSheet: (name: string) => boolean, columnsOf: (name: string) => readonly string[] | undefined,\n): XlsxCellInput {\n const at = cell.at;\n const empty: XlsxCellInput = { row: at.row, column: at.column, type: 'number', value: null, styleIndex: cell.style };\n const entry = cell.entry;\n const constant = entry?.constant;\n if (constant !== undefined) {\n if (constant.kind !== 'text') return valued(sheet, at, constant, empty, undefined);\n checkText(sheet, at, constant.text, undefined);\n return { ...empty, type: 'sharedString', text: constant.text };\n }\n const value = sheet.values.get(at.key);\n const formula = entry?.formula;\n if (entry !== undefined && formula !== undefined) {\n const where = { sheet: sheet.name, cell: at.toString(), held: formula };\n if (formula.length - 1 > maxFormulaLength) {\n throw new XlsxSaveError('formula',\n `The Formula is ${grouped(formula.length - 1)} characters long, and Excel holds at most ${grouped(maxFormulaLength)}.`, { sheet: sheet.name, cell: at.toString() });\n }\n if (!carries(formula, false)) throw new XlsxSaveError('formula', 'The Formula holds half of a surrogate pair, which a file cannot carry.', where);\n const { text: stored, problem } = writeFormula(entry, hasSheet, columnsOf);\n switch (problem) {\n case 'boundCall':\n throw new XlsxSaveError('formula', 'The Formula calls a name a LET binds or a LAMBDA takes, which ExSheet reads as an unknown function and Excel would call.', where);\n case 'longText':\n throw new XlsxSaveError('formula', `The Formula holds a text constant longer than the ${String(maxText)} characters Excel takes in one.`, where);\n case 'tooDeep':\n throw new XlsxSaveError('formula', `The Formula nests its calls deeper than the ${String(maxDepth)} levels Excel takes.`, where);\n case 'tooManyArguments':\n throw new XlsxSaveError('formula', `The Formula makes a call with more than the ${String(maxArguments)} arguments Excel takes.`, where);\n case 'missingSheet':\n throw new XlsxSaveError('formula', 'The Formula reads a Sheet the Workbook does not have, which Excel would read as another workbook\\'s.', where);\n case 'structuredReference':\n throw new XlsxSaveError('formula',\n 'The Formula reads, by a structured reference, a Linked Table or a column the Workbook does not declare; the file would hold no Excel Table of it for Excel to read.', where);\n case 'columnName':\n throw new XlsxSaveError('formula',\n 'The Formula reads a Linked Table\\'s column whose name begins or ends with a space, which a structured reference in Excel does not keep, or holds @ or one of , : . \" { } $ ^ & * + = - < > / or a tab or line break, whose form in a structured reference Excel has not been seen to write.', where);\n case 'tableName':\n throw new XlsxSaveError('formula',\n 'The Formula reads a Linked Table\\'s name as a name of its own, which ExSheet shows as #NAME? and Excel would read as the Excel Table written.', where);\n case 'unreadable':\n throw new XlsxSaveError('formula', 'The Formula cannot be written as Excel stores it: its names do not bind as the engine binds them.', where);\n case 'none':\n break;\n }\n const last = spills.get(at.key);\n const range = last === undefined ? at.toString() : `${at.toString()}:${last.toString()}`;\n const written = { text: stored, kind: 'array' as const, reference: range, isDynamicArray: true };\n return { ...(value === undefined ? empty : valued(sheet, at, value, empty, formula)), formula: written };\n }\n return value === undefined ? empty : valued(sheet, at, value, empty, undefined);\n}\n\n/** A cell holding `value`: a number, a boolean or an Error Value in the cell, text in the cell as a Formula's result. */\nfunction valued(sheet: SheetSnapshot, at: CellAddress, value: Value, cell: XlsxCellInput, formula: string | undefined): XlsxCellInput {\n switch (value.kind) {\n case 'number':\n return { ...cell, value: roundTrip(value.number) };\n case 'boolean':\n return { ...cell, type: 'boolean', value: value.boolean ? '1' : '0' };\n case 'text':\n checkText(sheet, at, value.text, formula);\n return { ...cell, type: 'formulaString', value: value.text };\n case 'error':\n break;\n }\n const where = { sheet: sheet.name, cell: at.toString(), held: formula };\n if (value.error === '#CIRC!') {\n throw new XlsxSaveError('circularReference',\n 'The cell shows #CIRC!: it is part of a circular reference, or depends on one. A file holds no such Error Value, and Excel shows 0 there; no Value it can hold is the one shown.',\n where);\n }\n if (value.error === '#GETTING_DATA') {\n throw new XlsxSaveError('linkedTable', 'The cell shows #GETTING_DATA: it waits on a Linked Table that has not answered.', where);\n }\n return { ...cell, type: 'error', value: value.toString() };\n}\n\nfunction isHighSurrogate(c: number): boolean {\n return c >= 0xD800 && c <= 0xDBFF;\n}\n\nfunction isLowSurrogate(c: number): boolean {\n return c >= 0xDC00 && c <= 0xDFFF;\n}\n\n/**\n * Whether a file carries `text`, as the file layer writes it: no half of a surrogate pair anywhere, and in a worksheet's\n * name, which is written as it is, no control character below U+0020 and no U+FFFE or U+FFFF. Elsewhere the file layer\n * escapes those (`_x0001_`).\n */\nfunction carries(text: string, inName: boolean): boolean {\n for (let i = 0; i < text.length; i++) {\n const c = text.charCodeAt(i);\n if (isHighSurrogate(c) && i + 1 < text.length && isLowSurrogate(text.charCodeAt(i + 1))) {\n i++;\n continue;\n }\n if (isHighSurrogate(c) || isLowSurrogate(c)) return false;\n if (inName && (c < 0x20 || c === 0xFFFE || c === 0xFFFF)) return false;\n }\n return true;\n}\n\nfunction checkText(sheet: SheetSnapshot, at: CellAddress, text: string, formula: string | undefined): void {\n const where = { sheet: sheet.name, cell: at.toString(), held: formula };\n if (text.length > maxTextLength) {\n throw new XlsxSaveError('text', `The cell's text is ${grouped(text.length)} characters long, and a cell of Excel holds at most ${grouped(maxTextLength)}.`, where);\n }\n if (!carries(text, false)) throw new XlsxSaveError('text', 'The cell\\'s text holds half of a surrogate pair, which a file cannot carry.', where);\n}\n", "import { formatted } from './open-error';\n\n// A Workbook not written, refused by name (ADR-0330 \u00A76), as ExSheet.Xlsx's XlsxSaveException refuses it: the reason, the\n// Sheet and the cell, and what the cell held, as far as the refusal is about one \u2014 `Sheet 'Trades', cell B7 (=B6*2): \u2026`, as\n// a refused opening names them. Nothing was written.\n\n/**\n * Why a Workbook was not written, and nothing was (ADR-0330 \u00A76): what it holds cannot be written as a file Excel reads with\n * the Values the user saw, or would make a file too large to open again.\n */\nexport type XlsxSaveRefusal =\n /**\n * A Linked Table cannot be written as an Excel Table on a worksheet of its name, holding its rows as they stand\n * (ADR-0330 \u00A76): it has not answered (every Formula that reads it shows `#GETTING_DATA`), it holds no rows (an Excel Table\n * holds at least one, and its Formulas would answer otherwise over one empty row), it holds more rows than a worksheet's\n * 1,048,576 less its header's or more columns than its 16,384, or its name is already a Sheet's or is one a worksheet\n * cannot have (longer than 31 characters, holding `\\`, or `History`). Or a cell shows `#GETTING_DATA`. The refusal names\n * the table, and a cell's refusal the Sheet and the cell.\n */\n | 'linkedTable'\n /**\n * A cell shows `#CIRC!`: it is part of a circular reference, or depends on one. A file holds only Excel's Error Values, and\n * Excel shows 0 there, which ExSheet refuses to show (ADR-0047); no Value the file can hold is the one the user saw.\n */\n | 'circularReference'\n /**\n * A Formula that cannot be written as Excel stores it, or as Excel takes it: its text is longer than Excel's 8,192\n * characters, holds a text constant longer than 255, nests its calls deeper than 64 levels or makes one with more than 255\n * arguments; it holds half of a surrogate pair, which a file cannot carry; it reads a Sheet the Workbook does not have\n * (Excel would read another workbook's); it calls a name a `LET` binds or a `LAMBDA` takes, which ExSheet reads as an\n * unknown function and Excel would call; it reads, by a structured reference, a Linked Table or a column the Workbook does\n * not declare, or a column whose name begins or ends with a space or holds `@`, a tab, a line break or one of\n * `, : . \" { } $ ^ & * + = - < > /`, whose form Excel has not been seen to write; it reads a Linked Table's name as a name\n * of its own (`=SUM(Positions)`), which ExSheet shows as `#NAME?` and Excel would read as the table; or it does not read\n * back as the Formula it is.\n */\n | 'formula'\n /**\n * A cell's text is longer than the 32,767 characters a cell of Excel holds, or holds half of a surrogate pair, which a file\n * cannot carry; or a Sheet's name holds a character a worksheet's name cannot carry in a file: a control character below\n * U+0020, U+FFFE or U+FFFF, or half of a surrogate pair. The refusal then names the Sheet and no cell.\n */\n | 'text'\n /**\n * The workbook would write more elements than `XlsxSaveOptions.maxCells`, which counts each cell written and each row a\n * row format writes. A Sheet formatted on many rows and many columns writes a cell wherever a formatted row crosses a\n * formatted column that records a part the row does not, and a row format writes a row element for every row it covers,\n * holding a cell or not. The default limit is the cells a file is read with (`defaultMaxCells`); the reader counts cells\n * only, so a file within it opens again, and rows are counted here so that a row format over every row is bounded too.\n */\n | 'tooManyCells'\n /**\n * The workbook would hold more uncompressed bytes than `XlsxSaveOptions.maxUncompressedBytes`: by default, more than a\n * file is read with (`defaultMaxUncompressedBytes`), so it would not open again. The refusal names the Sheet whose\n * worksheet went past it, when one did.\n */\n | 'tooLarge';\n\n/** Where a save's refusal met what it refuses, as far as it is about one Sheet and cell. */\nexport interface XlsxSavePlace {\n /** The name of the Sheet it met. */\n readonly sheet?: string | undefined;\n /** The cell it met, as `B7`. */\n readonly cell?: string | undefined;\n /** What the cell held, as a Formula's text with its `=`. */\n readonly held?: string | undefined;\n}\n\n/** A Workbook not written, refused by name (ADR-0330 \u00A76). */\nexport class XlsxSaveError extends Error {\n /** Why the Workbook was not written. */\n readonly reason: XlsxSaveRefusal;\n /** The name of the Sheet the refusal met, or `undefined` when it is not about one Sheet. */\n readonly sheet: string | undefined;\n /** The cell the refusal met, as `B7`, or `undefined` when it is not about one cell. */\n readonly cell: string | undefined;\n /** What the cell held \u2014 a Formula's text with its `=` \u2014 or `undefined`. */\n readonly held: string | undefined;\n\n /**\n * A refusal naming what it met.\n * @param reason - Why the Workbook is not written.\n * @param message - What was wrong, as a sentence that follows the Sheet and the cell.\n * @param where - The Sheet, the cell and what the cell held, as far as it is about one.\n */\n constructor(reason: XlsxSaveRefusal, message: string, where: XlsxSavePlace = {}) {\n super(formatted(where.sheet, where.cell, where.held, message));\n this.name = 'XlsxSaveError';\n this.reason = reason;\n this.sheet = where.sheet;\n this.cell = where.cell;\n this.held = where.held;\n }\n}\n\n/** How far a write has come (`XlsxSaveOptions.onProgress`): the Workbook's snapshot being planned, then the worksheets being\n * written. */\nexport interface XlsxSaveProgress {\n /** The index of the worksheet being written, in the file's order, from zero, a Linked Table's after the Sheets'; -1 while\n * the snapshot is planned: its cells counted against the limit and checked. */\n readonly sheet: number;\n /** The worksheets the file holds: one for each Sheet and one for each Linked Table. */\n readonly sheets: number;\n /** The elements written so far, counted as `maxCells` counts them; 0 while the snapshot is planned. */\n readonly elements: number;\n /** The elements the file writes, counted as `maxCells` counts them; 0 while the snapshot is planned. */\n readonly totalElements: number;\n}\n\n/**\n * What a write may produce, and how it paces itself (ADR-0330 \u00A76, \u00A79). Beyond either limit the Workbook is refused by name,\n * never written in part. The write takes its snapshot of the Workbook before it first yields, then builds the file from it in\n * slices sized by time, yielding between them so that a browser keeps painting, and reports its progress after each, as a\n * read does. A key left out takes the default its comment names.\n */\nexport interface XlsxSaveOptions {\n /**\n * The cells the whole workbook may write, every worksheet counted, each element a cell: the Sheets' own cells, the cells an\n * array spills into, the cells of no value written where a formatted row crosses a formatted column, a Linked Table's cells\n * and its header's, and each row a row format writes, which is an element of its own whether or not it holds a cell (a row\n * format over every row writes 1,048,576). `defaultMaxCells` when left out, the most a file is read with by default, so\n * that what is written opens again. Beyond it the write is refused by name (`tooManyCells`) before anything is written.\n */\n readonly maxCells?: number;\n /**\n * The uncompressed bytes the file's parts may hold together: 1 to `defaultMaxUncompressedBytes`, which it is when left\n * out, the most a file is read with by default. Beyond it the write is refused by name (`tooLarge`).\n */\n readonly maxUncompressedBytes?: number;\n /** Told how far the write has come after every slice, and once more when every element is written. */\n readonly onProgress?: (progress: XlsxSaveProgress) => void;\n /** How long one slice works, in milliseconds, before the write yields; 30 when left out, a read's. A slice always does\n * some work, so 0 yields after every batch. */\n readonly sliceBudgetMs?: number;\n /** What the write awaits between slices; a macrotask (`setTimeout(\u2026, 0)`) when left out, as a read's. */\n readonly yield?: () => Promise<void>;\n /** Cancels the write: it rejects with the signal's reason, looked at between slices. Cancelled, it writes nothing. */\n readonly signal?: AbortSignal;\n}\n", "import type { XlsxSaveOptions, XlsxSaveProgress } from './save-error';\n\n// Paces a write in slices sized by time (ADR-0330 \u00A79, as a read is paced), as ExSheet.Xlsx's SavePacer paces it: a slice\n// works until its budget is spent, then the write reports its progress and yields, so a browser \u2014 which has one thread \u2014\n// keeps painting while a large Workbook is written. Cancellation is looked at between batches of elements.\n\n/** The elements written between two looks at the clock and the signal. */\nconst batch = 256;\n\nfunction macrotask(): Promise<void> {\n return new Promise(resolve => {\n setTimeout(resolve, 0);\n });\n}\n\nexport class SavePacer {\n readonly #budget: number;\n readonly #yield: () => Promise<void>;\n readonly #onProgress: ((progress: XlsxSaveProgress) => void) | undefined;\n readonly #signal: AbortSignal | undefined;\n #sliceStart = performance.now();\n #sinceLook = 0;\n\n /** The worksheets the file holds. */\n sheets = 0;\n /** The elements the file writes; 0 until the snapshot is planned. */\n total = 0;\n /** The worksheet being written; -1 while the snapshot is planned. */\n sheet = -1;\n /** The elements written so far. */\n written = 0;\n\n constructor(options: XlsxSaveOptions) {\n const budget = options.sliceBudgetMs === undefined ? 30 : options.sliceBudgetMs;\n if (typeof budget !== 'number' || Number.isNaN(budget)) throw new TypeError(`The slice budget ${String(budget)} is not a number of milliseconds.`);\n this.#budget = Math.max(0, budget);\n this.#yield = options.yield === undefined ? macrotask : options.yield;\n this.#onProgress = options.onProgress;\n this.#signal = options.signal;\n }\n\n /** Throws the signal's reason when the write is cancelled. */\n cancelled(): void {\n this.#signal?.throwIfAborted();\n }\n\n /**\n * One step of work, which wrote `elements` (none while the snapshot is planned); every batch of steps answers the\n * checkpoint to await, and every other step nothing, so a step costs no turn of the event loop.\n */\n step(elements = 1): Promise<void> | undefined {\n this.written += elements;\n if (++this.#sinceLook < batch) return undefined;\n this.#sinceLook = 0;\n return this.checkpoint();\n }\n\n /** Looks at the signal and, past the budget, reports the progress and yields. */\n async checkpoint(): Promise<void> {\n this.cancelled();\n if (performance.now() < this.#sliceStart + this.#budget) return;\n this.report();\n await this.#yield();\n this.cancelled();\n this.#sliceStart = performance.now();\n }\n\n /** Tells the progress as it stands. */\n report(): void {\n this.#onProgress?.({\n sheet: this.sheet,\n sheets: this.sheets,\n elements: this.sheet < 0 ? 0 : this.written,\n totalElements: this.sheet < 0 ? 0 : this.total,\n });\n }\n}\n", "import type { BorderLine, CellColour, CellFormat, Culture } from '@ex-grid/sheet-engine';\nimport {\n defaultAlignment, firstCustomNumberFormat, gray125Fill, noBorder, noBorderEdge, noFill, rgbColor, solidFill,\n type XlsxAlignment, type XlsxBorder, type XlsxBorderEdge, type XlsxCellFormat, type XlsxColor, type XlsxFill, type XlsxFont, type XlsxStyles,\n} from '@ex-grid/data-xlsx';\nimport { defaultFormat } from './format-parts';\nimport { builtInId, writtenCode } from './number-formats';\nimport { fileLineStyle } from './style-reading';\n\n// The styles part a written workbook's Cell Formats need (ADR-0330 \u00A74, \u00A78, ADR-0071), as ExSheet.Xlsx's StyleTable builds\n// it, as the formats are met: each distinct Cell Format one cell format of the file, its index what a cell, a row or a column\n// names. Index 0 is the default Cell Format. Every font is the workbook's own, Calibri 11, with the Font's emphasis; a colour\n// is written as its RGB value, and Automatic as none, which Excel paints as its automatic colour. A Number Format is its\n// built-in id where it is one, and a format of the file's own from 164 otherwise, the engine's built-in currency spelled in\n// the Workbook culture's currency.\n\n/** The workbook's font: the one a written workbook's widths are counted in. */\nconst workbookFont: XlsxFont = Object.freeze({ name: 'Calibri', size: 11, bold: false, italic: false, underline: 'none', strike: false, color: null });\n\nexport class StyleTable {\n readonly #formats = new Map<string, number>();\n readonly #cellFormats: XlsxCellFormat[] = [];\n readonly #codes = new Map<string, number>();\n readonly #fonts = new Map<string, readonly [XlsxFont, number]>();\n readonly #fills = new Map<string, readonly [XlsxFill, number]>();\n readonly #borders = new Map<string, readonly [XlsxBorder, number]>();\n readonly #culture: Culture;\n\n /** A table for a Workbook of `culture`, holding the default Cell Format. */\n constructor(culture: Culture) {\n this.#culture = culture;\n this.#font(workbookFont);\n this.#fill(noFill);\n this.#fill(gray125Fill);\n this.#border(noBorder);\n this.index(defaultFormat);\n }\n\n /** The index of the cell format that writes `format`, added when it is new. */\n index(format: CellFormat): number {\n const known = this.#formats.get(format.key);\n if (known !== undefined) return known;\n const id = builtInId(format.numberFormat);\n const numberFormat = id === undefined ? this.#code(writtenCode(format.numberFormat, this.#culture)) : id;\n const f = format.font;\n const font = this.#font({\n ...workbookFont, bold: f.bold, italic: f.italic, underline: f.underline ? 'single' : 'none', strike: f.strikethrough, color: color(f.colour),\n });\n const fill = format.fill.colour === undefined ? 0 : this.#fill(solidFill(solidColor(format.fill.colour)));\n const b = format.borders;\n const border = this.#border({\n left: edge(b.left), right: edge(b.right), top: edge(b.top), bottom: edge(b.bottom), diagonal: noBorderEdge, diagonalUp: false, diagonalDown: false,\n });\n let alignment: XlsxAlignment | null;\n switch (format.alignment) {\n case 'left':\n case 'center':\n case 'right':\n alignment = { ...defaultAlignment, horizontal: format.alignment };\n break;\n case 'general':\n alignment = null;\n break;\n default:\n return unreachableAlignment(format.alignment);\n }\n const index = this.#cellFormats.length;\n this.#cellFormats.push({ numberFormatId: numberFormat, fontId: font, fillId: fill, borderId: border, alignment });\n this.#formats.set(format.key, index);\n return index;\n }\n\n /** The styles part, holding every format met so far. */\n build(): XlsxStyles {\n return {\n numberFormats: new Map([...this.#codes].map(([code, id]) => [id, code])),\n fonts: [...this.#fonts.values()].map(([font]) => font),\n fills: [...this.#fills.values()].map(([fill]) => fill),\n borders: [...this.#borders.values()].map(([border]) => border),\n cellFormats: [...this.#cellFormats],\n indexedColors: null,\n };\n }\n\n #code(code: string): number {\n let id = this.#codes.get(code);\n if (id === undefined) {\n id = firstCustomNumberFormat + this.#codes.size;\n this.#codes.set(code, id);\n }\n return id;\n }\n\n #font(font: XlsxFont): number {\n return add(this.#fonts, `${String(font.name)}|${String(font.size)}|${String(font.bold)}|${String(font.italic)}|${font.underline}|${String(font.strike)}|${colorKey(font.color)}`, font);\n }\n\n #fill(fill: XlsxFill): number {\n return add(this.#fills, `${String(fill.pattern)}|${colorKey(fill.foreground)}|${colorKey(fill.background)}|${String(fill.isGradient)}`, fill);\n }\n\n #border(border: XlsxBorder): number {\n return add(this.#borders, `${edgeKey(border.left)}|${edgeKey(border.right)}|${edgeKey(border.top)}|${edgeKey(border.bottom)}|${edgeKey(border.diagonal)}|${String(border.diagonalUp)}|${String(border.diagonalDown)}`, border);\n }\n}\n\nfunction add<T>(table: Map<string, readonly [T, number]>, key: string, item: T): number {\n const known = table.get(key);\n if (known !== undefined) return known[1];\n const index = table.size;\n table.set(key, [item, index]);\n return index;\n}\n\nfunction colorKey(c: XlsxColor | null): string {\n return c === null ? '-' : `${c.kind}:${String(c.value)}:${String(c.tint)}`;\n}\n\nfunction edgeKey(side: XlsxBorderEdge): string {\n return `${side.style}:${colorKey(side.color)}`;\n}\n\nfunction color(colour: CellColour): XlsxColor | null {\n return colour.isAutomatic ? null : rgbColor((0xFF000000 | colour.rgb) >>> 0);\n}\n\n/** A solid Fill's colour, which is never Automatic. */\nfunction solidColor(colour: CellColour): XlsxColor {\n const written = color(colour);\n if (written === null) throw new Error('Internal: a solid Fill has no colour.');\n return written;\n}\n\nfunction edge(line: BorderLine): XlsxBorderEdge {\n return line.isNone ? noBorderEdge : { style: fileLineStyle(line.style), color: color(line.colour) };\n}\n\nfunction unreachableAlignment(value: never): never {\n throw new Error(`Internal: ${String(value)} is not a horizontal alignment.`);\n}\n", "import { CellAddress, DeclaredFunction, Sheet, type Entry } from '@ex-grid/sheet-engine';\nimport { elementAt } from './must';\nimport { equalsIgnoreCase, foldCase, startsWithIgnoreCase } from './text-casing';\n\n// A Formula as ExSheet holds it, in the engine's invariant syntax (ADR-0047), written as an .xlsx stores it (ADR-0330 \u00A74), as\n// ExSheet.Xlsx's WrittenFormula writes it, the reverse of stored-formula.ts: `_xlfn.` put back before each function newer\n// than Excel 2007, `_xlfn._xlws.` before `FILTER` and `SORT`, `_xlpm.` before each name a `LET` binds or a `LAMBDA` takes, and\n// the Spill Range reference `A1#` written `_xlfn.ANCHORARRAY(A1)`. Without its prefix, Excel reads a newer function as a name\n// it does not know, and shows `#NAME?`. Text in quotes, a Sheet's name, a Reference and a number are never touched. A\n// structured reference to a Linked Table, which is written as an Excel Table of its name (ADR-0330 \u00A76), is written as the\n// engine stores it, which is Excel's own form: single brackets whatever the column's name holds, with `'` before each of\n// `[ ] # '` (`Positions[Market Value]`, `Positions[Rate'#]`; observed, verification/2026-09-27-windows-excel, TEXT-021 and\n// TEXT-022).\n//\n// The text is split as the engine's lexer splits it. Which names a `LET` or a `LAMBDA` binds is read from the calls'\n// arguments, and checked against what the engine itself found unbound (`Entry.unboundNames`): where the two disagree, the\n// Formula is refused rather than written with a prefix in the wrong place.\n\n/** Why a Formula cannot be written as Excel stores it. */\nexport type WrittenFormulaProblem =\n | 'none'\n /** A structured reference (`Positions[PV]`) to a table, or to a column of one, the Workbook does not declare: the engine\n * shows `#NAME?` or `#REF!`, and the file would hold no Excel Table for Excel to read. */\n | 'structuredReference'\n /** A structured reference to a Linked Table's column whose name begins or ends with a space, which a structured reference\n * in Excel does not keep; holds `@`, which Excel reads at the start as the row the Formula stands in; or holds a character\n * whose form in a structured reference has not been seen in Excel (`unseenInColumns`). */\n | 'columnName'\n /** A Linked Table's name read as a name of its own (`=SUM(Positions)`): ExSheet shows `#NAME?` there, and Excel, once the\n * file holds the Excel Table, reads the table's rows. */\n | 'tableName'\n /** The text does not split into the tokens the engine reads, or its names do not bind as the engine binds them. */\n | 'unreadable'\n /** A Reference names a Sheet the Workbook does not have: Excel would read it as another workbook's. */\n | 'missingSheet'\n /** A name a `LET` binds or a `LAMBDA` takes is called, and the engine declares no function of that name: the engine reads\n * the call as one of an unknown function (`#NAME?`), and Excel calls what the name is bound to. */\n | 'boundCall'\n /** A text constant in the Formula is longer than the 255 characters Excel takes in one. */\n | 'longText'\n /** Calls are nested deeper than the 64 levels Excel takes. */\n | 'tooDeep'\n /** A call has more than the 255 arguments Excel takes. */\n | 'tooManyArguments';\n\n/**\n * Excel's functions newer than Excel 2007, which a file stores with `_xlfn.` before them (ECMA-376's future functions, and the\n * ones Excel has added since), every one of Excel's, declared by the engine or not: a Formula naming one the engine does not\n * declare is carried as written, and Excel computes it.\n */\nexport const newerFunctions: readonly string[] = Object.freeze([\n 'ACOT', 'ACOTH', 'AGGREGATE', 'ARABIC', 'ARRAYTOTEXT', 'BASE', 'BETA.DIST', 'BETA.INV', 'BINOM.DIST',\n 'BINOM.DIST.RANGE', 'BINOM.INV', 'BITAND', 'BITLSHIFT', 'BITOR', 'BITRSHIFT', 'BITXOR', 'BYCOL', 'BYROW',\n 'CEILING.MATH', 'CEILING.PRECISE', 'CHISQ.DIST', 'CHISQ.DIST.RT', 'CHISQ.INV', 'CHISQ.INV.RT', 'CHISQ.TEST',\n 'CHOOSECOLS', 'CHOOSEROWS', 'COMBINA', 'CONCAT', 'CONFIDENCE.NORM', 'CONFIDENCE.T', 'COPILOT', 'COT', 'COTH',\n 'COVARIANCE.P', 'COVARIANCE.S', 'CSC', 'CSCH', 'DAYS', 'DECIMAL', 'DETECTLANGUAGE', 'DROP', 'ECMA.CEILING',\n 'ENCODEURL', 'ERF.PRECISE', 'ERFC.PRECISE', 'EXPAND', 'EXPON.DIST', 'F.DIST', 'F.DIST.RT', 'F.INV', 'F.INV.RT',\n 'F.TEST', 'FIELDVALUE', 'FILTER', 'FILTERXML', 'FLOOR.MATH', 'FLOOR.PRECISE', 'FORECAST.ETS',\n 'FORECAST.ETS.CONFINT', 'FORECAST.ETS.SEASONALITY', 'FORECAST.ETS.STAT', 'FORECAST.LINEAR', 'FORMULATEXT',\n 'GAMMA', 'GAMMA.DIST', 'GAMMA.INV', 'GAMMALN.PRECISE', 'GAUSS', 'GROUPBY', 'HSTACK', 'HYPGEOM.DIST', 'IFNA', 'IFS',\n 'IMAGE', 'IMCOSH', 'IMCOT', 'IMCSC', 'IMCSCH', 'IMSEC', 'IMSECH', 'IMSINH', 'IMTAN', 'ISFORMULA', 'ISOMITTED',\n 'ISOWEEKNUM', 'LAMBDA', 'LET', 'LOGNORM.DIST', 'LOGNORM.INV', 'MAKEARRAY', 'MAP', 'MAXIFS', 'MINIFS', 'MODE.MULT',\n 'MODE.SNGL', 'MUNIT', 'NEGBINOM.DIST', 'NETWORKDAYS.INTL', 'NORM.DIST', 'NORM.INV', 'NORM.S.DIST', 'NORM.S.INV',\n 'NUMBERVALUE', 'PDURATION', 'PERCENTILE.EXC', 'PERCENTILE.INC', 'PERCENTOF', 'PERCENTRANK.EXC', 'PERCENTRANK.INC',\n 'PERMUTATIONA', 'PHI', 'PIVOTBY', 'POISSON.DIST', 'QUARTILE.EXC', 'QUARTILE.INC', 'RANDARRAY', 'RANK.AVG',\n 'RANK.EQ', 'REDUCE', 'REGEXEXTRACT', 'REGEXREPLACE', 'REGEXTEST', 'RRI', 'SCAN', 'SEC', 'SECH', 'SEQUENCE',\n 'SHEET', 'SHEETS', 'SKEW.P', 'SORT', 'SORTBY', 'STDEV.P', 'STDEV.S', 'STOCKHISTORY', 'SWITCH', 'T.DIST',\n 'T.DIST.2T', 'T.DIST.RT', 'T.INV', 'T.INV.2T', 'T.TEST', 'TAKE', 'TEXTAFTER', 'TEXTBEFORE', 'TEXTJOIN',\n 'TEXTSPLIT', 'TOCOL', 'TOROW', 'TRANSLATE', 'TRIMRANGE', 'UNICHAR', 'UNICODE', 'UNIQUE', 'VALUETOTEXT', 'VAR.P',\n 'VAR.S', 'VSTACK', 'WEBSERVICE', 'WEIBULL.DIST', 'WORKDAY.INTL', 'WRAPCOLS', 'WRAPROWS', 'XLOOKUP', 'XMATCH',\n 'XOR', 'Z.TEST',\n]);\n\nconst newer: ReadonlySet<string> = new Set(newerFunctions.map(foldCase));\n\n/** Whether `name` is one of Excel's functions newer than Excel 2007, without regard to case. */\nexport function isNewerFunction(name: string): boolean {\n return newer.has(foldCase(name));\n}\n\n/** The functions Excel stores as worksheet-only as well as newer: `_xlfn._xlws.`. */\nconst worksheetOnly: ReadonlySet<string> = new Set(['FILTER', 'SORT']);\n\nconst errors = ['#NULL!', '#DIV/0!', '#VALUE!', '#REF!', '#NAME?', '#NUM!', '#N/A'];\n\n/** The longest text constant Excel takes in a Formula, in characters. */\nexport const maxText = 255;\n\n/** The deepest Excel nests calls in a Formula. */\nexport const maxDepth = 64;\n\n/** The most arguments Excel takes in one call. */\nexport const maxArguments = 255;\n\n/**\n * The characters of a column's name whose form in a structured reference Excel has not been seen to write: `@`, and those\n * Microsoft's documentation of structured references lists as needing the column in double brackets, which single brackets\n * (TEXT-021, TEXT-022) may not carry as Excel stores them.\n */\nconst unseenInColumns = /[@,:.\"{}$^&*+=\\-<>/\\t\\n\\r]/;\n\ntype Kind = 'space' | 'text' | 'error' | 'reference' | 'number' | 'name' | 'open' | 'close' | 'comma' | 'operator' | 'structuredReference';\n\nclass Token {\n readonly kind: Kind;\n readonly text: string;\n /** A Reference written with `#` after it: the Spill Range of the Formula in that cell. */\n readonly spilled: boolean;\n /** The Sheet a Reference names, unquoted, or `undefined` for one of its own Sheet; for a 3D Reference, the Sheet its span\n * begins on. */\n readonly sheet: string | undefined;\n /** For a 3D Reference (`Sheet1:Sheet3!B2`), the Sheet its span ends on, unquoted. */\n readonly lastSheet: string | undefined;\n /** A name that a `(` follows: a function's. */\n readonly called: boolean;\n /** A name a `LET` binds or a `LAMBDA` takes, or a use of one where it is bound. */\n bound = false;\n\n constructor(kind: Kind, text: string, more: { spilled?: boolean; sheet?: string | undefined; lastSheet?: string; called?: boolean } = {}) {\n this.kind = kind;\n this.text = text;\n this.spilled = more.spilled === true;\n this.sheet = more.sheet;\n this.lastSheet = more.lastSheet;\n this.called = more.called === true;\n }\n}\n\n/**\n * The Formula's text as the file stores it, without its `=`, and the problem that refuses it, `none` when it can be written.\n * @param entry - A Formula Entry.\n * @param hasSheet - Whether the Workbook written has a Sheet of a name a Reference qualifies, without regard to case;\n * `undefined` to take every name.\n * @param columnsOf - The columns of the Linked Table of a name, without regard to case, as declared, or `undefined` where none\n * is; `undefined` itself to declare none, so that every structured reference is refused.\n */\nexport function writeFormula(\n entry: Entry,\n hasSheet: ((name: string) => boolean) | undefined,\n columnsOf?: (name: string) => readonly string[] | undefined,\n): { readonly text: string; readonly problem: WrittenFormulaProblem } {\n const formula = entry.formula;\n if (formula === undefined) throw new Error('Internal: only a Formula Entry is written as a Formula.');\n const refused = (problem: WrittenFormulaProblem): { readonly text: string; readonly problem: WrittenFormulaProblem } => ({ text: formula.slice(1), problem });\n const split = splitFormula(formula, columnsOf);\n if (split.problem !== 'none') return refused(split.problem);\n const tokens = split.tokens;\n if (hasSheet !== undefined && tokens.some(t => (t.sheet !== undefined && !hasSheet(t.sheet)) || (t.lastSheet !== undefined && !hasSheet(t.lastSheet)))) {\n return refused('missingSheet');\n }\n const bound = bind(tokens);\n if (bound !== 'none') return refused(bound);\n if (columnsOf !== undefined && tokens.some(t => t.kind === 'name' && !t.called && !t.bound && columnsOf(t.text) !== undefined)) return refused('tableName');\n if (tokens.some(t => t.kind === 'text' && t.text.length - 2 - count(t.text, '\"\"') > maxText)) return refused('longText');\n if (!sameUnbound(tokens, entry.unboundNames)) return refused('unreadable');\n let text = '';\n for (const token of tokens) {\n if (token.kind === 'reference' && token.spilled) text += `_xlfn.ANCHORARRAY(${token.text})`;\n else if (token.kind === 'name' && token.bound) text += `_xlpm.${token.text}`;\n else if (token.kind === 'name' && token.called && isNewerFunction(token.text)) text += (worksheetOnly.has(foldCase(token.text)) ? '_xlfn._xlws.' : '_xlfn.') + token.text;\n else text += token.text;\n }\n return { text, problem: 'none' };\n}\n\nfunction count(text: string, of: string): number {\n let n = 0;\n for (let at = text.indexOf(of); at >= 0; at = text.indexOf(of, at + of.length)) n++;\n return n;\n}\n\n// The engine's own grammar (ExSheet.Engine's Lexer), which the invariant text it holds follows. Each is sticky: it matches at\n// `lastIndex` alone, as .NET's \\G does.\n\nconst referencePattern = new RegExp(\n String.raw`(?:(?<sheet>'(?:[^']|'')+'|[A-Za-z_][A-Za-z0-9_.]*)!)?`\n + String.raw`(?:(?<c1>\\$?[A-Za-z]{1,3})(?<r1>\\$?[0-9]{1,7})(?::(?<c2>\\$?[A-Za-z]{1,3})(?<r2>\\$?[0-9]{1,7}))?`\n + String.raw`|(?<cc1>\\$?[A-Za-z]{1,3}):(?<cc2>\\$?[A-Za-z]{1,3})`\n + String.raw`|(?<rr1>\\$?[0-9]{1,7}):(?<rr2>\\$?[0-9]{1,7}))`\n + String.raw`(?![A-Za-z0-9_.(\\[!:$])`,\n 'y');\n\nconst qualifiedRefError = /(?<sheet>'(?:[^']|'')+'|[A-Za-z_][A-Za-z0-9_.]*)!#REF!/iy;\n\n/** A 3D Reference's span before its `!`, as the engine's lexer reads one: `Sheet1:Sheet3!`, `'Q1 Sales:Sheet3'!`. */\nconst sheetSpanPattern = /(?:'(?<quotedFirst>(?:[^':]|'')+):(?<quotedLast>(?:[^':]|'')+)'|(?<first>[A-Za-z_][A-Za-z0-9_.]*):(?<last>[A-Za-z_][A-Za-z0-9_.]*))!/y;\n\nconst numberPattern = /(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?/y;\n\n// \\p{L} of one UTF-16 code unit, as .NET matches it: a letter outside the Basic Multilingual Plane is two code units, neither a\n// letter, so it is kept out here too.\nconst namePattern = /(?=[\\0-\uFFFF])[\\p{L}_\\\\](?:(?=[\\0-\uFFFF])[\\p{L}0-9_.])*/uy;\n\nfunction matchAt(pattern: RegExp, text: string, at: number): RegExpExecArray | null {\n pattern.lastIndex = at;\n return pattern.exec(text);\n}\n\nconst operators = ['<>', '<=', '>=', '=', '<', '>', '+', '-', '*', '/', '^', '&', '%'];\n\n/** The Formula's tokens after its `=`, split as the engine's lexer splits them. */\nfunction splitFormula(formula: string, columnsOf: ((name: string) => readonly string[] | undefined) | undefined): { readonly tokens: readonly Token[]; readonly problem: WrittenFormulaProblem } {\n const tokens: Token[] = [];\n const unreadable = { tokens: [], problem: 'unreadable' } as const;\n let i = 1;\n while (i < formula.length) {\n const c = formula.charAt(i);\n if (c === ' ' || c === '\\n' || c === '\\r') {\n const start = i;\n while (i < formula.length && (formula.charAt(i) === ' ' || formula.charAt(i) === '\\n' || formula.charAt(i) === '\\r')) i++;\n tokens.push(new Token('space', formula.slice(start, i)));\n continue;\n }\n if (c === '\"') {\n let j = i + 1;\n while (j < formula.length && !(formula.charAt(j) === '\"' && (j + 1 >= formula.length || formula.charAt(j + 1) !== '\"'))) j += formula.charAt(j) === '\"' ? 2 : 1;\n if (j >= formula.length) return unreadable;\n tokens.push(new Token('text', formula.slice(i, j + 1)));\n i = j + 1;\n continue;\n }\n if (c === '#') {\n const error = errors.find(e => startsWithIgnoreCase(formula, i, e));\n if (error === undefined) return unreadable;\n tokens.push(new Token('error', formula.slice(i, i + error.length)));\n i += error.length;\n continue;\n }\n if (c === '(' || c === ')' || c === ',') {\n tokens.push(new Token(c === '(' ? 'open' : c === ')' ? 'close' : 'comma', c));\n i++;\n continue;\n }\n const qualifiedError = matchAt(qualifiedRefError, formula, i);\n if (qualifiedError !== null) {\n tokens.push(new Token('error', qualifiedError[0], { sheet: sheetOf(qualifiedError) }));\n i += qualifiedError[0].length;\n continue;\n }\n const span = matchAt(sheetSpanPattern, formula, i);\n if (span !== null) {\n const place = matchAt(referencePattern, formula, i + span[0].length);\n if (place?.groups !== undefined && place.groups['sheet'] === undefined && isReference(place)) {\n // Sheet1:Sheet3!B2#, which the engine reads as #REF!, is stored as Excel stored it: SUM(_xlfn.ANCHORARRAY(Sheet2:Sheet4!B2))\n // (verification/2026-10-24-windows-workbook-12/records/spill-xml.txt).\n const end = i + span[0].length + place[0].length;\n const spannedSpill = place.groups['c1'] !== undefined && place.groups['c2'] === undefined && end < formula.length && formula.charAt(end) === '#';\n const g = span.groups;\n const first = g?.['quotedFirst'] ?? g?.['first'];\n const last = g?.['quotedLast'] ?? g?.['last'];\n if (first === undefined || last === undefined) throw new Error('Internal: a span names no Sheets.');\n tokens.push(new Token('reference', span[0] + place[0], { spilled: spannedSpill, sheet: first.replaceAll(\"''\", \"'\"), lastSheet: last.replaceAll(\"''\", \"'\") }));\n i = end + (spannedSpill ? 1 : 0);\n continue;\n }\n }\n const reference = matchAt(referencePattern, formula, i);\n if (reference?.groups !== undefined && isReference(reference)) {\n const end = i + reference[0].length;\n const spilled = reference.groups['c1'] !== undefined && reference.groups['c2'] === undefined && end < formula.length && formula.charAt(end) === '#';\n tokens.push(new Token('reference', reference[0], { spilled, sheet: sheetOf(reference) }));\n i = end + (spilled ? 1 : 0);\n continue;\n }\n if ((c >= '0' && c <= '9') || c === '.') {\n const number = matchAt(numberPattern, formula, i);\n if (number === null) return unreadable;\n tokens.push(new Token('number', number[0]));\n i += number[0].length;\n continue;\n }\n const name = matchAt(namePattern, formula, i);\n if (name !== null) {\n const end = i + name[0].length;\n if (end < formula.length && formula.charAt(end) === '[') {\n const column = structuredColumn(formula, end);\n if (column.name === undefined) {\n if (!column.at) return unreadable;\n return { tokens, problem: 'columnName' };\n }\n const declared = columnsOf?.(name[0]);\n const columnName = column.name;\n if (declared === undefined || !declared.some(d => equalsIgnoreCase(d, columnName))) return { tokens, problem: 'structuredReference' };\n if (columnName.startsWith(' ') || columnName.endsWith(' ') || unseenInColumns.test(columnName)) {\n return { tokens, problem: 'columnName' };\n }\n tokens.push(new Token('structuredReference', name[0] + storedColumn(columnName)));\n i = column.after;\n continue;\n }\n tokens.push(new Token('name', name[0], { called: end < formula.length && formula.charAt(end) === '(' }));\n i = end;\n continue;\n }\n const op = operators.find(o => formula.startsWith(o, i));\n if (op !== undefined) {\n tokens.push(new Token('operator', op));\n i += op.length;\n continue;\n }\n return unreadable;\n }\n return { tokens, problem: 'none' };\n}\n\n/**\n * The column a structured reference names, read from its `[` as the engine's lexer reads it \u2014 `[Column]` or `[[Column]]`, with\n * `'` taking the next character as it is \u2014 or no name where the engine reads none; then `at` says whether it met an\n * unescaped `@`, which the engine reads in no column's name.\n */\nfunction structuredColumn(formula: string, open: number): { readonly name: string | undefined; readonly after: number; readonly at: boolean } {\n const none = (at: boolean): { readonly name: undefined; readonly after: number; readonly at: boolean } => ({ name: undefined, after: open, at });\n const doubled = open + 1 < formula.length && formula.charAt(open + 1) === '[';\n let i = open + (doubled ? 2 : 1);\n let column = '';\n for (;;) {\n if (i >= formula.length) return none(false);\n const c = formula.charAt(i);\n if (c === \"'\" && i + 1 < formula.length) {\n column += formula.charAt(i + 1);\n i += 2;\n continue;\n }\n if (c === '[' || c === '#' || c === '@') return none(c === '@');\n if (c === ']') break;\n column += c;\n i++;\n }\n if (doubled) {\n if (i + 1 >= formula.length || formula.charAt(i + 1) !== ']') return none(false);\n i++;\n }\n if (column.length === 0) return none(false);\n return { name: column, after: i + 1, at: false };\n}\n\n/** A column of a structured reference as the engine stores it and Excel writes it back (TEXT-021, TEXT-022): in single\n * brackets, with `'` before each of `[ ] # '`. */\nfunction storedColumn(column: string): string {\n let text = '[';\n for (const c of column) {\n if (c === '[' || c === ']' || c === '#' || c === \"'\") text += \"'\";\n text += c;\n }\n return `${text}]`;\n}\n\n/** The Sheet a match's qualifier names, unquoted, or `undefined` where it has none. */\nfunction sheetOf(match: RegExpExecArray): string | undefined {\n const raw = match.groups?.['sheet'];\n if (raw === undefined) return undefined;\n return raw.startsWith(\"'\") ? raw.slice(1, -1).replaceAll(\"''\", \"'\") : raw;\n}\n\n/** One call, or one pair of parentheses, as its arguments stand: the indexes of each argument's tokens. */\ninterface Frame {\n readonly function: Token | undefined;\n readonly arguments: number[][];\n}\n\ninterface Binding { readonly name: string; readonly first: number; readonly last: number }\n\n/**\n * Marks every name a `LET` binds or a `LAMBDA` takes, and each use of one where it is bound; or the problem that refuses the\n * Formula: calls nested or argued beyond Excel's limits, or a bound name called.\n */\nfunction bind(tokens: readonly Token[]): WrittenFormulaProblem {\n const bindings: Binding[] = [];\n const frames: Frame[] = [{ function: undefined, arguments: [[]] }];\n const top = (): Frame => elementAt(frames, frames.length - 1);\n const lastArgument = (frame: Frame): number[] => elementAt(frame.arguments, frame.arguments.length - 1);\n let calls = 0;\n for (let i = 0; i < tokens.length; i++) {\n const token = elementAt(tokens, i);\n switch (token.kind) {\n case 'open': {\n lastArgument(top()).push(i);\n const previous = i > 0 ? elementAt(tokens, i - 1) : undefined;\n const called = previous !== undefined && previous.kind === 'name' && previous.called ? previous : undefined;\n if (called !== undefined && ++calls > maxDepth) return 'tooDeep';\n frames.push({ function: called, arguments: [[]] });\n break;\n }\n case 'comma':\n if (frames.length > 1) {\n top().arguments.push([]);\n if (top().function !== undefined && top().arguments.length > maxArguments) return 'tooManyArguments';\n } else {\n lastArgument(top()).push(i);\n }\n break;\n case 'close':\n if (frames.length > 1) {\n const frame = elementAt(frames, frames.length - 1);\n frames.pop();\n if (frame.function !== undefined) calls--;\n lastArgument(top()).push(i);\n binds(frame, tokens, i, bindings);\n } else {\n lastArgument(top()).push(i);\n }\n break;\n case 'space':\n break;\n case 'text':\n case 'error':\n case 'reference':\n case 'number':\n case 'name':\n case 'operator':\n case 'structuredReference':\n lastArgument(top()).push(i);\n break;\n default:\n return unreachableKind(token.kind);\n }\n }\n for (let i = 0; i < tokens.length; i++) {\n const name = elementAt(tokens, i);\n if (name.kind !== 'name' || !bindings.some(b => b.first <= i && i <= b.last && equalsIgnoreCase(b.name, name.text))) continue;\n // A call is of a function wherever the engine declares one of its name, bound or not, as the engine's parser takes it;\n // a bound name called otherwise is a call the engine and Excel read differently.\n if (!name.called) name.bound = true;\n else if (DeclaredFunction.find(name.text) === undefined) return 'boundCall';\n }\n return 'none';\n}\n\nfunction unreachableKind(kind: never): never {\n throw new Error(`Internal: ${String(kind)} is not a token's kind.`);\n}\n\n/** What a closed `LET` or `LAMBDA` call binds: a `LET`'s names over what follows each in the call, and a `LAMBDA`'s parameters\n * over its last argument. */\nfunction binds(frame: Frame, tokens: readonly Token[], close: number, bindings: Binding[]): void {\n const fn = frame.function;\n if (fn === undefined) return;\n const args = frame.arguments;\n const loneName = (argument: readonly number[]): readonly [number, Token] | undefined => {\n if (argument.length !== 1) return undefined;\n const at = elementAt(argument, 0);\n const token = elementAt(tokens, at);\n return token.kind === 'name' && !token.called ? [at, token] : undefined;\n };\n if (equalsIgnoreCase(fn.text, 'LET')) {\n for (let k = 0; k + 1 < args.length; k += 2) {\n const named = loneName(elementAt(args, k));\n if (named !== undefined) bindings.push({ name: named[1].text, first: named[0], last: close });\n }\n } else if (equalsIgnoreCase(fn.text, 'LAMBDA') && args.length > 0 && elementAt(args, args.length - 1).length > 0) {\n const body = elementAt(args, args.length - 1);\n for (let k = 0; k + 1 < args.length; k++) {\n const named = loneName(elementAt(args, k));\n if (named !== undefined) {\n bindings.push({ name: named[1].text, first: named[0], last: named[0] });\n bindings.push({ name: named[1].text, first: elementAt(body, 0), last: elementAt(body, body.length - 1) });\n }\n }\n }\n}\n\n/**\n * Whether the names left unbound here are the ones the engine found unbound: what it parsed is what is written. A name of\n * another script is one the engine takes only where a `LET` binds it, and lists in neither.\n */\nfunction sameUnbound(tokens: readonly Token[], engine: readonly string[]): boolean {\n const unbound = new Set(tokens\n .filter(t => t.kind === 'name' && !t.called && !t.bound && !isBoolean(t.text) && isAscii(t.text))\n .map(t => foldCase(t.text)));\n const found = new Set(engine.map(foldCase));\n return unbound.size === found.size && [...found].every(name => unbound.has(name));\n}\n\n/** Whether every UTF-16 code unit of `text` is ASCII. */\nfunction isAscii(text: string): boolean {\n for (let i = 0; i < text.length; i++) {\n if (text.charCodeAt(i) >= 0x80) return false;\n }\n return true;\n}\n\nfunction isBoolean(name: string): boolean {\n return equalsIgnoreCase(name, 'TRUE') || equalsIgnoreCase(name, 'FALSE');\n}\n\n/** Whether a Reference's column, as matched, is one the engine reads; one not matched is. */\nfunction readsColumn(value: string | undefined): boolean {\n return value === undefined || CellAddress.tryParseColumn(trimDollars(value)) !== undefined;\n}\n\n/** Whether a Reference's row, as matched, is one the engine reads; one not matched is. */\nfunction readsRow(value: string | undefined): boolean {\n if (value === undefined) return true;\n const digits = trimDollars(value);\n return !digits.startsWith('0') && /^[0-9]+$/.test(digits) && Number(digits) <= Sheet.rowCount;\n}\n\n/** Whether a match of `referencePattern` is a Reference the engine reads: no column past `XFD`, no row past the Sheet's last. */\nfunction isReference(match: RegExpExecArray): boolean {\n const g = match.groups;\n if (g === undefined) return false;\n return readsColumn(g['c1']) && readsColumn(g['c2']) && readsColumn(g['cc1']) && readsColumn(g['cc2'])\n && readsRow(g['r1']) && readsRow(g['r2']) && readsRow(g['rr1']) && readsRow(g['rr2']);\n}\n\nfunction trimDollars(text: string): string {\n let i = 0;\n while (i < text.length && text.charAt(i) === '$') i++;\n return text.slice(i);\n}\n\n\n"],
5
+ "mappings": ";AAAA;AAAA,EACI;AAAA,EAAa,eAAAA;AAAA,EAAa,YAAAC;AAAA,EAAU,YAAAC;AAAA,EAAU;AAAA,EAAW;AAAA,EAAS;AAAA,EAAO;AAAA,EAAoB,gBAAAC;AAAA,EAAc,SAAAC;AAAA,EAAO;AAAA,EAClH;AAAA,EAAyB;AAAA,EAAmB;AAAA,EAA0B;AAAA,EAAO;AAAA,OAC1E;AACP;A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GAAoB;AACxC,SAAO,KAAK,SAAU,KAAK;AAC/B;AAOA,SAAS,QAAQ,MAAc,QAA0B;AACrD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AAClC,UAAM,IAAI,KAAK,WAAW,CAAC;AAC3B,QAAI,gBAAgB,CAAC,KAAK,IAAI,IAAI,KAAK,UAAU,eAAe,KAAK,WAAW,IAAI,CAAC,CAAC,GAAG;AACrF;AACA;AAAA,IACJ;AACA,QAAI,gBAAgB,CAAC,KAAK,eAAe,CAAC,EAAG,QAAO;AACpD,QAAI,WAAW,IAAI,MAAQ,MAAM,SAAU,MAAM,OAAS,QAAO;AAAA,EACrE;AACA,SAAO;AACX;AAEA,SAAS,UAAU,OAAsB,IAAiB,MAAc,SAAmC;AACvG,QAAM,QAAQ,EAAE,OAAO,MAAM,MAAM,MAAM,GAAG,SAAS,GAAG,MAAM,QAAQ;AACtE,MAAI,KAAK,SAAS,eAAe;AAC7B,UAAM,IAAI,cAAc,QAAQ,sBAAsB,QAAQ,KAAK,MAAM,CAAC,uDAAuD,QAAQ,aAAa,CAAC,KAAK,KAAK;AAAA,EACrK;AACA,MAAI,CAAC,QAAQ,MAAM,KAAK,EAAG,OAAM,IAAI,cAAc,QAAQ,8EAA+E,KAAK;AACnJ;",
6
+ "names": ["CellBorders", "CellFill", "CellFont", "NumberFormat", "Sheet", "XlsxError", "lower", "held", "Sheet", "count", "widths", "Sheet", "add", "held", "CellBorders", "CellFill", "CellFont", "CellFormat", "NumberFormat", "NumberFormat", "reading", "NumberFormat", "same", "color", "held", "NumberFormat", "CellFont", "CellFill", "edge", "CellBorders", "CellFormat", "XlsxError", "Sheet", "same", "add", "NumberFormat", "CellFont", "CellFill", "CellBorders", "CellAddress", "Sheet", "formatCell", "XlsxError", "defaultAlignment", "firstCustomNumberFormat", "defaultAlignment", "unreachableAlignment", "firstCustomNumberFormat", "CellAddress", "Sheet", "CellAddress", "Sheet", "XlsxError", "Sheet", "formatCell", "CellAddress", "formatted"]
7
+ }