@nouxwell/tabula-core 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["refused","readOptions","NUMERIC","compare","sameValue","isObject","comparable","plain","readRule","isObject","describe","at","plain","compare","HUNDRED","compareValues","compare","NUMERIC","compare","SYMBOLS","NUMERIC","NUMERIC","compare","NUMERIC","compare","EMPTY","plain","plain","describe","TabulaError","message","code","SchemaError","lines","problems","problem","subject","DECIMAL","normalizeDecimal","text","input","match","whole","fraction","body","compareDecimal","negativeA","a","negativeB","b","magnitude","compareMagnitude","wholeA","fractionA","wholeB","fractionB","length","paddedA","paddedB","INVISIBLE_SPACES","PHP_TRIM","phpTrim","clean","fold","escapeRegex","MACHINE_DECIMAL","LARGEST_INTEGER","decimalText","value","isWholeNumberText","isTooLarge","readNumber","raw","negative","isNegative","separators","separatorsOf","settings","cleaned","last","at","lastSeparator","signed","digitsOnly","head","tail","isDecimalSeparator","removeAll","readMoney","symbol","symbolCandidates","currency","quoted","readPercent","symbolFor","formatNumber","rounded","roundDecimal","digits","grouped","editNumber","rawWhole","rawFraction","roundUp","bumped","increment","zero","list","index","other","separator","found","position","result","candidates","usable","candidate","TOKENS","ISO_DATE","ISO_DATE_TIME","ISO_INPUT","EXCEL_EPOCH_OFFSET","MAX_EXCEL_SERIAL","MIN_TEXT_SERIAL","compiled","compilePattern","pattern","source","tokens","char","token","readDate","isZeroDate","parts","fromPattern","fromSerial","otherPattern","fromIso","toIso","withTime","isIsoDate","parseIso","formatDate","two","number","year","month","day","hour","minute","second","valid","compiledPattern","serial","date","days","TRUE_WORDS","FALSE_WORDS","readInput","field","refused$1","numberResult","readBool","readDateValue","readOptions$1","valueProblem","isFieldValue","describeValue","canonicalValue","isOptionValue","item","isLookupValue","record","option","needle","unique","datePatternOf","part","values","params","extra","messageFor","seen","word","words","key","COMPARISONS","CONDITION_OPS","NUMERIC$5","ORDERED","CHECK_PROPERTIES","CONDITION_PROPERTIES","readChecks","add","byKey","fields","ids","checks","path","check","readCheck","first","checkToJson","json","conditionToJson","checkFields","keys","condition","breaksCheck","holds","get","rowsBreaking","schema","store","rowId","conditionHolds","own","left","readable","right","order","compare$2","sameValue$1","isObject$2","failed","fail","name","id","assert","readCondition","when","severity","readMessage","before","op","hasValue","hasOther","otherField","comparable$1","given","language","Listeners","entry","listener","event","#listeners","error","report","scope","MARK_COLORS","CellMarks","#history","options","cells","mark","#put","cleanMark","#version","count","#cells","checkChange","change","#change","next","on","cell","style","keep","rowIds","data","after","old","made","now","sameMark","#apply","entries","rowsMarked","marks","readMarks","rows","plain$4","read","color","RULE_PROPERTIES","readStyleRules","rules","rule","readRule$1","styleRuleToJson","styleApplies","rowStyles","styles","rowsStyled","isObject$1","fill","bold","LEVELS","parseFormula","tokenize","peek","binary","level","unary","operand","postfix","node","primary","callArgs","inner","args","tree","formulaFields","walk","current","TWO_CHARACTER","ONE_CHARACTER","where","start","close","FIELD_TYPES","CUSTOMIZATIONS","MODULE_PROPERTIES","COMMON_PROPERTIES","FORMULA_TYPES","TYPE_PROPERTIES","TYPED_PROPERTIES","NUMERIC_TYPES","RULE_KINDS","ModuleSchema","#byKey","Problems","readModule","isObject","fieldToJson","describe$2","module","readText","schemaVersion","readSchemaVersion","title","customization","readCustomization","readFields","items","firstIndex","readField","checkFormulas","reads","indexOf","fieldsRead","done","reported","circle","member","type","readType","readKey","label","required","readBoolean","editable","submit","example","formula","readRules","at$1","aFieldOf","base","readTone","readPattern","readDecimals","readOptions","fallback","readDefault","why","hint","broken","brokenRule","checkFieldProperties","allowed","optionPath","optionValue","rulePath","readRule","min","limitOf","max","minLength","lengthOf","maxLength","kind","ruleApplies","limit","randomPart","sequence","random","counter","prefix","MAX_DEPTH","toCellValue","convert","refused","depth","prototype","copy","got","sameValue","RowStore","#createRowId","sessionRowIds","#prepare","#rows","row","#order","#revision","#positions","#row","frozenCopy","fn","operations","#derivers","#log","log","derive","#revert","#write","assign","#record","write","writes","inits","blankRows","prepared","doomed","removed","kept","changes","listOf","#standalone","#undo","each","operation","#redo","batch","init","inserted","#restore","#swap","#expectRows","#putBack","from","to","present","total","previous","end","run","requireField","raced","abort","reject","abortError","signal","promise","resolve","wait","ms","neverAborted","LOOKUP_ORIGIN","DEFAULT_BATCH","DEFAULT_CACHE_FOR","LookupResolver","batchSize","#schema","#store","#adapters","#batchSize","#cacheFor","#now","#requestId","#stop","#onChange","#pending","#failure","lookup","#lookupOf","query","cached","#fresh","#searches","requestId","response","readSearchResponse","#enqueue","#flushing","#queue","#scheduled","#disposed","names","cellKey","#schedule","#flush","queue","known","#matches","unknown","#setPending","labels","answer","#learn","readResolveResponse","#setFailure","answers","schemaField","pending","#changed","root","plain$3","readItem","UNDO_ORIGIN","REDO_ORIGIN","DEFAULT_LIMIT","UndoHistory","#limit","#joins","firstChange","step","#trim","recorded","#recorded","#take","#making","TEXT","B0","B1","B2","B10","B1000","ZERO","ONE","parseDecimal","units","simplify","decimalToText","x","y","scale","aligned","subtract","multiply","divide","round","negate","absolute","compare$1","isZero","isInteger","places","drop","rest","mode","power","exponent","times","isFormulaError","formulaErrorValue","EMPTY","numberValue","textValue","boolValue","TRUE","FALSE","errorValue","formulaNumber","decimal","numberArgument","toNumber","HUNDRED$1","toText","toBool","evaluate","context","arithmetic","call","nullError","compareValues$1","emptyLike","rank","FUNCTIONS","branch","arg","builtIn","BUILT_IN","custom","numbers","rounding","logical","all","truth","average","FORMULA_ORIGIN","FormulaEngine","#functions","upperKeys","compile","#affected","affected","#derive","#workOut","changed","#formulasFor","formulas","workOut","applyFormulas","named","functions","fromCell","toCell","placed","place","readers","reached","visit","NAME_START","NAME_PART","formulaCaret","caret","calls","inText","fieldAt","innermost","tokenAt","callOf","formulaWithLabels","mapFields","formulaWithKeys","byLabel","open","map","ADDRESS","formulaFromAddresses","closingQuote","column","addressColumn","columns","formulaParts","plain","upper","letter","DEFAULT_FILTER","RowView","#filters","#ids","filter","#rebuild","filters","shown","added","rowsWithIssues","issues","rowsWithResult","outcome","results","outcomes","NUMERIC$4","AVERAGE_PLACES","summarizeCells","filled","sum","formatCell","digitsFor","editText","SYMBOLS$1","VALUE_SETTINGS","defineValueSettings","refuse","NUMERIC$3","DATES","hasRange","filterKey","normal","filterKeys","eachValue","rowsMatching","tests","inRange","test","rowsContaining","locale","written","point","comparable","compare","compareNumbers","compareTexts","sortText","compareValues","rankA","rankB","rowOrder","sort","sign","rankLeft","rankRight","distinctValues","NUMERIC$2","DAY_MS","DAY_SECONDS","TRAILING_NUMBER","ISO_PARTS","fillValues","backward","series","seriesOf","distance","numberSeries","dateSeries","textSeries","decimals","stepOf","matches","width","d","dates","partsOf","months","monthSeries","points","secondOf","dayOf","isoOf","fromSecond","fromDay","sameDay","inMonth","daysIn","counts","single","texts","iso","moment","NUMERIC$1","HUNDRED","isAdjustable","adjustValue","operandOf","adjustment","SheetChanges","#settings","#fields","#key","#takeBaseline","#added","missing","#baseline","#holding","#changedNow","#keys","#compared","#keyOf","#follow","touched","#forget","was","EMPTY$1","rowsChanged","DEFAULT_COLUMN_SIZING","resolveColumnSizing","layers","sizing","headerDisplayText","characters","autoColumnWidth","clamp","contentWidth","clampColumnWidth","COLUMN_ALIGNS","MAX_SHOWN_DECIMALS","arrangeColumns","hidden","layout","pinned","ordered","withColumn","toggle","withColumnFormat","formats","alignOf","decimalsOf","freezeColumnLayout","readColumnLayout","plainObject","format","isShownDecimals","mapColumnLayout","sameColumnFormats","VIEWS_FORMAT","VIEWS_VERSION","VIEW_NAME_LIMIT","PLAIN_VIEW","emptyViews","freezeViews","viewFor","state","freezeState","sameView","arranged","sameRecord","sameCondition","viewNameProblem","trimmed","collator","except","views","view","addView","saved","checkedName","updateView","pickState","renameView","checked","removeView","setDefaultView","readViews","plain$2","readView","defaultId","line","collators","update","same","readViewState","readLayout","readWidths","readFilters","readSort","columnWidths","widths","bound","side","TEMPLATE_FORMAT","TEMPLATE_VERSION","CHANGES","NUMERIC","readTemplate","plain$1","fieldsRoot","describeProblems","templateProblems","merge","template","applyTemplate","applied","withDefaults","defaults","ownChecks","ownStyles","merged","narrowed","heading","STEPS","Selection","#rowCount","requireCount","rowCount","#colCount","colCount","#isEmpty","#active","#pivot","#head","rangeOf","range","within","col","target","#clamp","#commit","cols","edgeOf","direction","isBlank","active","pivot","#clampCell","settled","inside","blank","advance","parseTsv","cellStart","quoteAt","literalAt","toTsv","quoteCell","DELIMITERS","parseCsv","delimiter","detectDelimiter","started","endCell","endRow","best","toCsv","special","decodeText","bytes","FORMULA_START","NUMBER_TYPES","exportTable","cellText","csvDelimiterFor","importTable","header","table","taken","fieldNamed","unreadable","MAX_TARGETS","SheetValidator","hasRule","#groups","#checksOf","#checkAll","#unsubscribe","#broken","issue","shared","#uniqueIssue","errors","warnings","groups","group","#checkRow","#checkCell","#checkChecks","#sorted","checkIssue","checkValue","#regroup","uniqueKey","cacheKey","sorted","others","describe$1","cellIssue","sent","checkRule","comparison","normalize","SYMBOLS","ENGLISH_COMPARISONS","english","trimmedWhole","trimmedFraction","SCOPES","SEVERITIES","STATUSES","OUTCOMES","ACTIONS","readCheckResponse","reader","Reader","optional","readProcessResponse","status","#problems","describe","optionalValue","blocking","param","plan","action","DRAFT_FORMAT","DRAFT_VERSION","createDraft","session","freezeMarks","openDraft","draft","rename","renames","mapDraft","targets","losing","dropped","suggestRenames","fresh","pairs","score","likeness","pair","keyWords","retyped","renamed","gone","readDraft","sheetId","savedAt","revision","readRow","sessionRoot","readResult","readPending","request","WORKBOOK_FORMAT","WORKBOOK_VERSION","createWorkbook","sheet","sheetOf","freeSheetId","freeze","readWorkbook","listed","sheets","readMeta","addSheet","workbook","withSheet","patch","removeSheet","moveSheet","openSheet","meta","DEFAULT_DELAY","DraftSaver","delay","#options","#delay","#name","#stops","#onSession","#state","#changes","#saved","#setState","#clearTimer","#running","#run","stop","#timer","DEFAULT_POLL_INTERVAL","SheetSession","pollInterval","#ownValidator","#pollInterval","#merged","MergedIssues","#results","Results","ask","#checking","controller","#request","#answered","failure","#toIssue","checkRecord","plans","#checked","send","blocked","#blockedRows","sending","#lose","#payload","#rowPlan","#query","checking","#setRun","stage","answered","final","server","blockedByServer","lookupPayload","scopeOf","#changedSince","#rowChanged","#cellChanged","touches","#local","local","#server","remote","#indexed","stale","#index","updated","push","#inFlight","invalid","REPLACE_ORIGIN","findCells","matcher","replaceCells","skipped","replaced","replacement","wanted","haystack","version"],"sources":["../src/errors.ts","../src/decimal.ts","../src/values/text.ts","../src/values/number.ts","../src/values/date.ts","../src/values/read.ts","../src/checks.ts","../src/listeners.ts","../src/marks.ts","../src/styles.ts","../src/formula/parse.ts","../src/schema.ts","../src/ids.ts","../src/value.ts","../src/rows.ts","../src/async.ts","../src/lookup.ts","../src/history.ts","../src/formula/decimal.ts","../src/formula/error.ts","../src/formula/evaluate.ts","../src/formula/engine.ts","../src/formula/assist.ts","../src/view.ts","../src/summary.ts","../src/values/format.ts","../src/values/settings.ts","../src/filters.ts","../src/fill.ts","../src/adjust.ts","../src/changes.ts","../src/columns.ts","../src/views.ts","../src/templates.ts","../src/selection.ts","../src/clipboard.ts","../src/csv.ts","../src/table.ts","../src/validation.ts","../src/contract.ts","../src/draft.ts","../src/workbook.ts","../src/saver.ts","../src/session.ts","../src/find.ts","../src/index.ts"],"sourcesContent":["/** What went wrong, in a form code can branch on. */\nexport type TabulaErrorCode =\n\t| \"invalid_schema\"\n\t| \"unknown_field\"\n\t| \"unknown_row\"\n\t| \"duplicate_row\"\n\t| \"invalid_argument\"\n\t| \"invalid_value\"\n\t| \"conflict\"\n\t| \"invalid_response\"\n\t| \"invalid_draft\"\n\t| \"invalid_workbook\"\n\t| \"invalid_views\"\n\t| \"invalid_template\"\n\t| \"invalid_formula\"\n\n/**\n * The one error class this package throws.\n *\n * The message is English and written for the developer reading the console. Code that reacts to an\n * error looks at `code`, which is never renamed; a message may be reworded in any release.\n */\nexport class TabulaError extends Error {\n\toverride name = \"TabulaError\"\n\treadonly code: TabulaErrorCode\n\n\tconstructor(code: TabulaErrorCode, message: string) {\n\t\tsuper(message)\n\t\tthis.code = code\n\t}\n}\n\nexport interface SchemaProblem {\n\t/** Where in the schema, such as `fields[2].rules[0].value`. `(root)` is the schema itself. */\n\treadonly path: string\n\treadonly message: string\n}\n\n/**\n * A module schema that cannot be used, with every problem in it.\n *\n * All of them, not the first: a developer fixing a schema one complaint per reload is a developer\n * reloading a dozen times.\n */\nexport class SchemaError extends TabulaError {\n\toverride name = \"SchemaError\"\n\treadonly problems: readonly SchemaProblem[]\n\n\tconstructor(subject: string, problems: readonly SchemaProblem[]) {\n\t\tconst lines = problems.map(problem => ` ${problem.path}: ${problem.message}`)\n\t\tsuper(\"invalid_schema\", `${subject} is not valid:\\n${lines.join(\"\\n\")}`)\n\t\tthis.problems = Object.freeze([...problems])\n\t}\n}\n","/**\n * Decimal numbers written as text, compared without ever becoming a float.\n *\n * A limit such as a minimum price arrives from the backend as text (\"0.30\") so that it means what it\n * says. As floats, 0.1 + 0.2 is not 0.3, and a rule saying \"at least 0.30\" would refuse a sum that\n * meets it.\n */\n\nconst DECIMAL = /^([+-]?)(\\d+)(?:\\.(\\d+))?$/\n\n/**\n * One way of writing each number: no sign on zero, no leading zeros, no trailing zeros after the\n * point, no point with nothing after it. `\"-0012.3400\"` becomes `\"-12.34\"`.\n *\n * Null for anything else, exponents (`1e21`), thousands separators and a decimal comma included.\n * Those belong to what a user types, and are read elsewhere with the sheet's own number settings.\n */\nexport function normalizeDecimal(input: string | number): string | null {\n\tlet text: string\n\n\tif (typeof input === \"number\") {\n\t\tif (!Number.isFinite(input)) {\n\t\t\treturn null\n\t\t}\n\n\t\ttext = String(input)\n\t} else {\n\t\ttext = input.trim()\n\t}\n\n\tconst match = DECIMAL.exec(text)\n\n\tif (!match) {\n\t\treturn null\n\t}\n\n\tconst whole = (match[2] ?? \"0\").replace(/^0+(?=\\d)/, \"\")\n\tconst fraction = (match[3] ?? \"\").replace(/0+$/, \"\")\n\tconst body = fraction === \"\" ? whole : `${whole}.${fraction}`\n\n\tif (body === \"0\") {\n\t\treturn \"0\"\n\t}\n\n\treturn match[1] === \"-\" ? `-${body}` : body\n}\n\n/** -1, 0 or 1 as `a` is below, equal to or above `b`. Both must be as `normalizeDecimal()` writes them. */\nexport function compareDecimal(a: string, b: string): -1 | 0 | 1 {\n\tconst negativeA = a.startsWith(\"-\")\n\tconst negativeB = b.startsWith(\"-\")\n\n\tif (negativeA !== negativeB) {\n\t\treturn negativeA ? -1 : 1\n\t}\n\n\tconst magnitude = compareMagnitude(negativeA ? a.slice(1) : a, negativeB ? b.slice(1) : b)\n\n\t// 0 - magnitude, not -magnitude: the latter turns an equal pair into -0.\n\treturn negativeA ? ((0 - magnitude) as -1 | 0 | 1) : magnitude\n}\n\nfunction compareMagnitude(a: string, b: string): -1 | 0 | 1 {\n\tconst [wholeA = \"\", fractionA = \"\"] = a.split(\".\")\n\tconst [wholeB = \"\", fractionB = \"\"] = b.split(\".\")\n\n\t// No leading zeros, so the longer whole part is the larger number.\n\tif (wholeA.length !== wholeB.length) {\n\t\treturn wholeA.length < wholeB.length ? -1 : 1\n\t}\n\n\tif (wholeA !== wholeB) {\n\t\treturn wholeA < wholeB ? -1 : 1\n\t}\n\n\tconst length = Math.max(fractionA.length, fractionB.length)\n\tconst paddedA = fractionA.padEnd(length, \"0\")\n\tconst paddedB = fractionB.padEnd(length, \"0\")\n\n\tif (paddedA === paddedB) {\n\t\treturn 0\n\t}\n\n\treturn paddedA < paddedB ? -1 : 1\n}\n","/**\n * The text rules every reader shares, written as nouxwell/tabula's `StringParser` writes them, so\n * the two sides call the same cell empty and compare the same two words as equal.\n */\n\nconst INVISIBLE_SPACES = /[\\u00A0\\u202F\\u2009\\uFEFF]/g\n\n// PHP's trim(): space, tab, line breaks, NUL and vertical tab. JavaScript's own trim() also takes\n// every other Unicode space, and the two sides would then disagree on what a cell holds.\n// eslint-disable-next-line no-control-regex\nconst PHP_TRIM = /^[ \\t\\n\\r\\0\\x0B]+|[ \\t\\n\\r\\0\\x0B]+$/g\n\nexport function phpTrim(text: string): string {\n\treturn text.replace(PHP_TRIM, \"\")\n}\n\n/** Invisible spaces become ordinary ones, then the ends are trimmed: what a cell really holds. */\nexport function clean(text: string): string {\n\treturn phpTrim(text.replace(INVISIBLE_SPACES, \" \"))\n}\n\n/**\n * The form two words are compared in: cleaned and lower-cased.\n *\n * Lower-cased without a locale, as `mb_strtolower()` does. That keeps the comparison the same on\n * every machine, and it also means \"AÇIK\" does not meet \"açık\": the I's lower case is \"i\", not \"ı\".\n */\nexport function fold(text: string): string {\n\treturn clean(text).toLowerCase()\n}\n\nexport function escapeRegex(text: string): string {\n\treturn text.replace(/[.*+?^${}()|[\\]\\\\/-]/g, \"\\\\$&\")\n}\n","import { compareDecimal, normalizeDecimal } from \"../decimal.js\"\nimport type { ValueSettings } from \"./settings.js\"\nimport { clean, escapeRegex, phpTrim } from \"./text.js\"\n\n/**\n * Numbers as a cell holds them: decimal text such as \"1234.56\", never a float, so a price is\n * exactly what was typed. Reading follows nouxwell/tabula's `NumberFormatter::parse()` rule for rule.\n * Where PHP turns the text into a float, this keeps the digits: same value, no rounding.\n */\n\n/** How a number is written by machines: an optional minus, digits, and a point with digits after it. */\nconst MACHINE_DECIMAL = /^-?\\d+(?:\\.\\d+)?$/\n\n/** The largest whole number PHP keeps as an integer, PHP_INT_MAX. */\nconst LARGEST_INTEGER = \"9223372036854775807\"\n\n/** A number value as decimal text, or null when it is not one. Strings must be in machine form. */\nexport function decimalText(value: unknown): string | null {\n\tif (typeof value === \"string\") {\n\t\treturn MACHINE_DECIMAL.test(value) ? value : null\n\t}\n\n\tif (typeof value !== \"number\" || !Number.isFinite(value)) {\n\t\treturn null\n\t}\n\n\tconst text = String(value)\n\n\t// String() writes 1e21 and 1e-7 with an exponent; spelled out, they are decimal text again.\n\treturn /e/i.test(text) ? value.toLocaleString(\"en-US\", { useGrouping: false, maximumFractionDigits: 20 }) : text\n}\n\nexport function isWholeNumberText(text: string): boolean {\n\treturn /^-?\\d+$/.test(text)\n}\n\n/** Whether a whole number is past what PHP can hold as an integer. */\nexport function isTooLarge(text: string): boolean {\n\treturn compareDecimal(text.replace(/^-/, \"\"), LARGEST_INTEGER) > 0\n}\n\n/**\n * Reads a number as a person wrote it, with the sheet's separators.\n *\n * \"1.234,56\", \"1,234.56\", \"1.234 ₺\", \"(1.234,56)\" and \"1.234,56-\" are all understood, and a lone\n * thousands separator followed by three digits is grouping: \"1.234\" is 1234 with Turkish settings.\n * Letters and symbols around the number are dropped, as on the PHP side: \"12 adet\" is 12.\n */\nexport function readNumber(raw: string, settings: ValueSettings): string | null {\n\tconst text = phpTrim(raw)\n\n\tif (text === \"\") {\n\t\treturn null\n\t}\n\n\tconst negative = isNegative(text)\n\tconst separators = separatorsOf(settings)\n\tconst spaced = text.replace(/[\\u00A0\\u202F\\u2009]/g, \" \")\n\tconst cleaned = spaced.replace(new RegExp(`[^0-9${escapeRegex(separators.join(\"\"))}]`, \"gu\"), \"\")\n\n\tif (cleaned === \"\") {\n\t\treturn null\n\t}\n\n\tconst [last, at] = lastSeparator(cleaned, separators)\n\n\tif (last === null) {\n\t\treturn signed(digitsOnly(cleaned), negative)\n\t}\n\n\tconst head = cleaned.slice(0, at)\n\tconst tail = cleaned.slice(at + last.length)\n\n\tif (!isDecimalSeparator(last, head, tail, separators, settings)) {\n\t\treturn signed(digitsOnly(removeAll(cleaned, separators)), negative)\n\t}\n\n\tconst whole = removeAll(head, separators) || \"0\"\n\n\tif (!/^\\d+$/.test(whole) || !/^\\d+$/.test(tail)) {\n\t\treturn null\n\t}\n\n\treturn signed(normalizeDecimal(`${whole}.${tail}`), negative)\n}\n\n/**\n * Reads an amount: the currency symbols and codes the settings know, and the field's own, are taken\n * off either end first. Taken off rather than left to the number reader, because a symbol holding a\n * point, such as \"S/.\", would leave a point behind and multiply the amount by a hundred.\n */\nexport function readMoney(raw: string, currency: string | null, settings: ValueSettings): string | null {\n\tlet text = clean(raw)\n\n\tfor (const symbol of symbolCandidates(currency, settings)) {\n\t\tconst quoted = escapeRegex(symbol)\n\n\t\ttext = text.replace(new RegExp(`^\\\\s*${quoted}\\\\s*|\\\\s*${quoted}\\\\s*$`, \"giu\"), \"\")\n\t}\n\n\treturn readNumber(phpTrim(text), settings)\n}\n\n/** Reads a percentage written with or without its sign, before or after: \"%15\", \"15 %\", \"15\". */\nexport function readPercent(raw: string, settings: ValueSettings): string | null {\n\treturn readNumber(clean(raw).replace(/^%\\s*|\\s*%$/g, \"\"), settings)\n}\n\n/** The symbol a currency is shown with, or null when symbols are not shown. */\nexport function symbolFor(currency: string | null, settings: ValueSettings): string | null {\n\tif (currency === null || settings.symbolPosition === \"none\") {\n\t\treturn null\n\t}\n\n\treturn settings.currencySymbols[currency] ?? currency\n}\n\n/**\n * Decimal text rounded to `digits` places and written the sheet's way: \"1234.565\" with Turkish\n * settings and two digits is \"1.234,57\". Rounded half away from zero, on the digits themselves.\n */\nexport function formatNumber(value: string, digits: number, settings: ValueSettings): string {\n\tconst rounded = roundDecimal(value, digits)\n\tconst negative = rounded.startsWith(\"-\")\n\tconst [whole = \"0\", fraction] = (negative ? rounded.slice(1) : rounded).split(\".\")\n\tconst grouped = whole.replace(/\\B(?=(\\d{3})+(?!\\d))/g, settings.thousandSeparator)\n\n\treturn `${negative ? \"-\" : \"\"}${grouped}${fraction === undefined ? \"\" : settings.decimalSeparator + fraction}`\n}\n\n/** Decimal text as a person edits it: every digit kept, the sheet's decimal separator, no grouping. */\nexport function editNumber(value: string, settings: ValueSettings): string {\n\treturn value.replace(\".\", settings.decimalSeparator)\n}\n\n/** Rounds decimal text to exactly `digits` places, half away from zero. \"-0.001\" to two places is \"0.00\". */\nexport function roundDecimal(value: string, digits: number): string {\n\tconst negative = value.startsWith(\"-\")\n\tconst [rawWhole = \"0\", rawFraction = \"\"] = (negative ? value.slice(1) : value).split(\".\")\n\tlet whole = rawWhole.replace(/^0+(?=\\d)/, \"\")\n\tlet fraction = rawFraction\n\n\tif (fraction.length <= digits) {\n\t\tfraction = fraction.padEnd(digits, \"0\")\n\t} else {\n\t\tconst roundUp = (fraction.charAt(digits) || \"0\") >= \"5\"\n\n\t\tfraction = fraction.slice(0, digits)\n\n\t\tif (roundUp) {\n\t\t\tconst bumped = increment(whole + fraction)\n\n\t\t\twhole = bumped.slice(0, bumped.length - digits) || \"0\"\n\t\t\tfraction = bumped.slice(bumped.length - digits)\n\t\t}\n\t}\n\n\tconst zero = /^0*$/.test(whole + fraction)\n\n\treturn `${negative && !zero ? \"-\" : \"\"}${whole}${digits > 0 ? `.${fraction}` : \"\"}`\n}\n\nfunction increment(digits: string): string {\n\tconst list = digits.split(\"\")\n\n\tfor (let index = list.length - 1; index >= 0; index--) {\n\t\tif (list[index] === \"9\") {\n\t\t\tlist[index] = \"0\"\n\t\t} else {\n\t\t\tlist[index] = String(Number(list[index]) + 1)\n\n\t\t\treturn list.join(\"\")\n\t\t}\n\t}\n\n\treturn `1${list.join(\"\")}`\n}\n\n/**\n * The negative notations: a leading or trailing minus, accounting parentheses, and a minus right\n * before the digits after a symbol (\"₺ -1.234,56\"). Looked for before the cleanup, which loses them.\n */\nfunction isNegative(text: string): boolean {\n\tif (text.includes(\"(\") && text.includes(\")\")) {\n\t\treturn true\n\t}\n\n\tif (text.startsWith(\"-\") || text.endsWith(\"-\")) {\n\t\treturn true\n\t}\n\n\treturn /^\\D*-\\s*\\d/u.test(text)\n}\n\n/**\n * Whether the right-most separator is the decimal point, in the order nouxwell/tabula decides it:\n * another kind of separator before it; the same one twice; the configured decimal separator; the\n * configured thousands separator with exactly three digits after it; anything else is decimal.\n */\nfunction isDecimalSeparator(\n\tseparator: string,\n\thead: string,\n\ttail: string,\n\tseparators: readonly string[],\n\tsettings: ValueSettings\n): boolean {\n\tif (tail === \"\" || !/^\\d+$/.test(tail)) {\n\t\treturn false\n\t}\n\n\tif (separators.some(other => other !== separator && head.includes(other))) {\n\t\treturn true\n\t}\n\n\tif (head.includes(separator)) {\n\t\treturn false\n\t}\n\n\tif (separator === settings.decimalSeparator) {\n\t\treturn true\n\t}\n\n\tif (separator === settings.thousandSeparator) {\n\t\treturn tail.length !== 3\n\t}\n\n\treturn true\n}\n\n/** The configured separators, then the universal point and comma: \"1,234.56\" is read with Turkish settings too. */\nfunction separatorsOf(settings: ValueSettings): string[] {\n\treturn [...new Set([settings.decimalSeparator, settings.thousandSeparator, \".\", \",\"].filter(Boolean))]\n}\n\nfunction lastSeparator(text: string, separators: readonly string[]): [string | null, number] {\n\tlet found: string | null = null\n\tlet at = -1\n\n\tfor (const separator of separators) {\n\t\tconst position = text.lastIndexOf(separator)\n\n\t\tif (position > at) {\n\t\t\tfound = separator\n\t\t\tat = position\n\t\t}\n\t}\n\n\treturn [found, at]\n}\n\nfunction removeAll(text: string, separators: readonly string[]): string {\n\treturn separators.reduce((result, separator) => result.split(separator).join(\"\"), text)\n}\n\nfunction digitsOnly(text: string): string | null {\n\treturn /^\\d+$/.test(text) ? normalizeDecimal(text) : null\n}\n\nfunction signed(text: string | null, negative: boolean): string | null {\n\treturn text === null || !negative || text === \"0\" ? text : `-${text}`\n}\n\n/**\n * Every symbol and code that could stand around an amount, longest first, so \"US$\" goes before \"$\"\n * and leaves no \"US\" behind. One that could be part of a number, such as a separator, is never one.\n */\nfunction symbolCandidates(currency: string | null, settings: ValueSettings): string[] {\n\tconst candidates = [...Object.values(settings.currencySymbols), ...Object.keys(settings.currencySymbols)]\n\n\tif (currency !== null) {\n\t\tcandidates.push(currency)\n\n\t\tconst symbol = symbolFor(currency, settings)\n\n\t\tif (symbol !== null) {\n\t\t\tcandidates.push(symbol)\n\t\t}\n\t}\n\n\tconst separators = [settings.decimalSeparator, settings.thousandSeparator]\n\tconst usable = candidates\n\t\t.map(candidate => phpTrim(candidate))\n\t\t.filter(candidate => candidate !== \"\" && !separators.includes(candidate) && !/^[0-9.,\\s]+$/u.test(candidate))\n\n\treturn [...new Set(usable)].sort((a, b) => Array.from(b).length - Array.from(a).length)\n}\n","import { clean, escapeRegex } from \"./text.js\"\n\n/**\n * Dates as a cell holds them: ISO text, \"2026-12-31\" for a date and \"2026-12-31T09:30:00\" for a\n * date and time, with no time zone. What the user typed is what is kept, as on the PHP side: a cell\n * reading 09:00 is never moved to 06:00 by an offset.\n */\n\ninterface Parts {\n\tyear: number\n\tmonth: number\n\tday: number\n\thour: number\n\tminute: number\n\tsecond: number\n}\n\ntype Token = \"day\" | \"month\" | \"year\" | \"shortYear\" | \"hour\" | \"minute\" | \"second\"\n\ninterface CompiledPattern {\n\treadonly regex: RegExp\n\treadonly tokens: readonly Token[]\n}\n\nconst TOKENS: Readonly<Record<string, readonly [Token, string]>> = {\n\td: [\"day\", \"(\\\\d{1,2})\"],\n\tj: [\"day\", \"(\\\\d{1,2})\"],\n\tm: [\"month\", \"(\\\\d{1,2})\"],\n\tn: [\"month\", \"(\\\\d{1,2})\"],\n\tY: [\"year\", \"(\\\\d{4})\"],\n\ty: [\"shortYear\", \"(\\\\d{2})\"],\n\tH: [\"hour\", \"(\\\\d{1,2})\"],\n\tG: [\"hour\", \"(\\\\d{1,2})\"],\n\ti: [\"minute\", \"(\\\\d{2})\"],\n\ts: [\"second\", \"(\\\\d{2})\"]\n}\n\nconst ISO_DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/\nconst ISO_DATE_TIME = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})$/\nconst ISO_INPUT = /^(\\d{4})-(\\d{1,2})-(\\d{1,2})(?:[T ](\\d{1,2}):(\\d{2})(?::(\\d{2}))?)?$/\n\n/** Where the Unix epoch sits in Excel's day count, and the last day Excel still reads as a date. */\nconst EXCEL_EPOCH_OFFSET = 25569\nconst MAX_EXCEL_SERIAL = 2958465\n/** A digits-only text below this is a year or a code, not a serial number: \"2024\" is not 1905-07-16. */\nconst MIN_TEXT_SERIAL = 10000\n\nconst compiled = new Map<string, CompiledPattern | null>()\n\n/**\n * A pattern in PHP's notation as a regular expression, or null when it uses a letter this reader\n * does not know. Every other character must match itself, a space matches any run of spaces, and a\n * backslash makes the next letter literal.\n */\nexport function compilePattern(pattern: string): CompiledPattern | null {\n\tif (compiled.has(pattern)) {\n\t\treturn compiled.get(pattern) ?? null\n\t}\n\n\tlet source = \"\"\n\tconst tokens: Token[] = []\n\tlet result: CompiledPattern | null = null\n\tlet index = 0\n\n\tfor (; index < pattern.length; index++) {\n\t\tconst char = pattern.charAt(index)\n\t\tconst token = TOKENS[char]\n\n\t\tif (token) {\n\t\t\ttokens.push(token[0])\n\t\t\tsource += token[1]\n\t\t} else if (char === \"\\\\\") {\n\t\t\tindex++\n\t\t\tsource += escapeRegex(pattern.charAt(index))\n\t\t} else if (char === \"!\" || char === \"|\") {\n\t\t\t// PHP's markers for \"reset what the pattern leaves out\", which is what happens here anyway.\n\t\t} else if (char === \" \") {\n\t\t\tsource += \"[ \\\\t\\\\u00A0\\\\u202F]*\"\n\t\t} else if (/[A-Za-z]/.test(char)) {\n\t\t\tbreak\n\t\t} else {\n\t\t\tsource += escapeRegex(char)\n\t\t}\n\t}\n\n\tif (index >= pattern.length) {\n\t\tresult = Object.freeze({ regex: new RegExp(`^${source}$`), tokens: Object.freeze(tokens) })\n\t}\n\n\tcompiled.set(pattern, result)\n\n\treturn result\n}\n\n/**\n * Reads a date as a person wrote it. In order: the pattern; a digits-only Excel serial number; the\n * other pattern (the date and time pattern for a date, and the other way round); ISO. A date that\n * does not exist, such as 31.02.2026, is refused rather than rolled into March.\n *\n * @returns ISO text, with the time for a date-time field and without it for a date field\n */\nexport function readDate(raw: string, withTime: boolean, pattern: string, otherPattern: string): string | null {\n\tconst text = clean(raw)\n\n\tif (text === \"\" || isZeroDate(text)) {\n\t\treturn null\n\t}\n\n\tconst parts =\n\t\tfromPattern(text, pattern) ??\n\t\t(/^\\d+$/.test(text) ? fromSerial(Number(text)) : null) ??\n\t\tfromPattern(text, otherPattern) ??\n\t\tfromIso(text)\n\n\treturn parts === null ? null : toIso(parts, withTime)\n}\n\n/** Whether a value is a date, or a date and time, in the ISO form a cell holds. */\nexport function isIsoDate(value: unknown, withTime: boolean): value is string {\n\treturn typeof value === \"string\" && parseIso(value, withTime) !== null\n}\n\n/** An ISO date written with a pattern, or null when it is not one. */\nexport function formatDate(value: string, withTime: boolean, pattern: string): string | null {\n\tconst parts = parseIso(value, withTime)\n\n\tif (parts === null) {\n\t\treturn null\n\t}\n\n\tconst two = (number: number): string => String(number).padStart(2, \"0\")\n\tlet text = \"\"\n\n\tfor (let index = 0; index < pattern.length; index++) {\n\t\tconst char = pattern.charAt(index)\n\n\t\tswitch (char) {\n\t\t\tcase \"d\":\n\t\t\t\ttext += two(parts.day)\n\t\t\t\tbreak\n\t\t\tcase \"j\":\n\t\t\t\ttext += String(parts.day)\n\t\t\t\tbreak\n\t\t\tcase \"m\":\n\t\t\t\ttext += two(parts.month)\n\t\t\t\tbreak\n\t\t\tcase \"n\":\n\t\t\t\ttext += String(parts.month)\n\t\t\t\tbreak\n\t\t\tcase \"Y\":\n\t\t\t\ttext += String(parts.year).padStart(4, \"0\")\n\t\t\t\tbreak\n\t\t\tcase \"y\":\n\t\t\t\ttext += two(parts.year % 100)\n\t\t\t\tbreak\n\t\t\tcase \"H\":\n\t\t\t\ttext += two(parts.hour)\n\t\t\t\tbreak\n\t\t\tcase \"G\":\n\t\t\t\ttext += String(parts.hour)\n\t\t\t\tbreak\n\t\t\tcase \"i\":\n\t\t\t\ttext += two(parts.minute)\n\t\t\t\tbreak\n\t\t\tcase \"s\":\n\t\t\t\ttext += two(parts.second)\n\t\t\t\tbreak\n\t\t\tcase \"\\\\\":\n\t\t\t\tindex++\n\t\t\t\ttext += pattern.charAt(index)\n\t\t\t\tbreak\n\t\t\tcase \"!\":\n\t\t\tcase \"|\":\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\ttext += char\n\t\t}\n\t}\n\n\treturn text\n}\n\nfunction parseIso(value: string, withTime: boolean): Parts | null {\n\tconst match = (withTime ? ISO_DATE_TIME : ISO_DATE).exec(value)\n\n\tif (!match) {\n\t\treturn null\n\t}\n\n\tconst [, year, month, day, hour = \"0\", minute = \"0\", second = \"0\"] = match\n\n\treturn valid({\n\t\tyear: Number(year),\n\t\tmonth: Number(month),\n\t\tday: Number(day),\n\t\thour: Number(hour),\n\t\tminute: Number(minute),\n\t\tsecond: Number(second)\n\t})\n}\n\nfunction fromPattern(text: string, pattern: string): Parts | null {\n\tconst compiledPattern = compilePattern(pattern)\n\tconst match = compiledPattern?.regex.exec(text)\n\n\tif (!compiledPattern || !match) {\n\t\treturn null\n\t}\n\n\t// What the pattern leaves out starts from the epoch, as PHP's \"!\" does: a pattern without a day\n\t// reads the first, never today.\n\tconst parts: Parts = { year: 1970, month: 1, day: 1, hour: 0, minute: 0, second: 0 }\n\n\tcompiledPattern.tokens.forEach((token, index) => {\n\t\tconst number = Number(match[index + 1])\n\n\t\tswitch (token) {\n\t\t\tcase \"shortYear\":\n\t\t\t\t// As PHP reads \"y\": 70 to 99 are the 1900s, 00 to 69 the 2000s.\n\t\t\t\tparts.year = number < 70 ? 2000 + number : 1900 + number\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tparts[token] = number\n\t\t}\n\t})\n\n\treturn valid(parts)\n}\n\nfunction fromSerial(serial: number): Parts | null {\n\tif (!Number.isFinite(serial) || serial < MIN_TEXT_SERIAL || serial > MAX_EXCEL_SERIAL) {\n\t\treturn null\n\t}\n\n\tconst date = new Date(Math.round((serial - EXCEL_EPOCH_OFFSET) * 86400) * 1000)\n\n\treturn {\n\t\tyear: date.getUTCFullYear(),\n\t\tmonth: date.getUTCMonth() + 1,\n\t\tday: date.getUTCDate(),\n\t\thour: date.getUTCHours(),\n\t\tminute: date.getUTCMinutes(),\n\t\tsecond: date.getUTCSeconds()\n\t}\n}\n\nfunction fromIso(text: string): Parts | null {\n\tconst match = ISO_INPUT.exec(text)\n\n\tif (!match) {\n\t\treturn null\n\t}\n\n\tconst [, year, month, day, hour = \"0\", minute = \"0\", second = \"0\"] = match\n\n\treturn valid({\n\t\tyear: Number(year),\n\t\tmonth: Number(month),\n\t\tday: Number(day),\n\t\thour: Number(hour),\n\t\tminute: Number(minute),\n\t\tsecond: Number(second)\n\t})\n}\n\n/** The parts when they make a real moment, or null: no 31 February, no 24:00. */\nfunction valid(parts: Parts): Parts | null {\n\tconst days = new Date(Date.UTC(parts.year, parts.month, 0)).getUTCDate()\n\n\tif (\n\t\tparts.year < 1 ||\n\t\tparts.month < 1 ||\n\t\tparts.month > 12 ||\n\t\tparts.day < 1 ||\n\t\tparts.day > days ||\n\t\tparts.hour > 23 ||\n\t\tparts.minute > 59 ||\n\t\tparts.second > 59\n\t) {\n\t\treturn null\n\t}\n\n\treturn parts\n}\n\nfunction toIso(parts: Parts, withTime: boolean): string {\n\tconst two = (number: number): string => String(number).padStart(2, \"0\")\n\tconst date = `${String(parts.year).padStart(4, \"0\")}-${two(parts.month)}-${two(parts.day)}`\n\n\treturn withTime ? `${date}T${two(parts.hour)}:${two(parts.minute)}:${two(parts.second)}` : date\n}\n\n/** MySQL's zero date, the broken output of another system rather than a date. */\nfunction isZeroDate(text: string): boolean {\n\tconst digits = text.replace(/\\D/g, \"\")\n\n\treturn digits.length >= 8 && /^0+$/.test(digits)\n}\n","import type { FieldSchema, OptionsField } from \"../schema.js\"\nimport type { CellValue } from \"../value.js\"\nimport { isIsoDate, readDate } from \"./date.js\"\nimport { decimalText, isTooLarge, isWholeNumberText, readMoney, readNumber, readPercent } from \"./number.js\"\nimport type { ValueSettings } from \"./settings.js\"\nimport { clean, fold } from \"./text.js\"\n\n/**\n * Reading what a person typed or pasted into a cell, and telling whether what a cell holds is a\n * value of its field's type.\n *\n * Text that cannot be read is not thrown away. The cell keeps it as typed, so the user can see it\n * and fix it, and the problem says what was expected. The codes and their params are nouxwell/tabula's\n * `RowErrorCode`: an application that words the import's errors already words these.\n */\n\n/**\n * `not_matched` is this package's own, for a lookup holding text no record was matched to; the rest\n * are nouxwell/tabula's.\n */\nexport type ValueProblemCode =\n\t\"not_a_number\" | \"not_an_integer\" | \"not_a_date\" | \"not_a_boolean\" | \"not_an_option\" | \"not_matched\"\n\nexport interface ValueProblem {\n\treadonly code: ValueProblemCode\n\t/** English, as nouxwell/tabula words it. An application in another language words it from code and params. */\n\treadonly message: string\n\t/** `field`, `type` and `value` always; `format`, `accepted` or `options` as the code needs. */\n\treadonly params: Readonly<Record<string, string>>\n}\n\nexport interface ReadResult {\n\t/** What the cell should hold: the value, or the text as typed when it could not be read. */\n\treadonly value: CellValue\n\treadonly problem: ValueProblem | null\n}\n\n/** The words accepted for yes and no besides the settings' own, as nouxwell/tabula's BoolParser accepts them. */\nconst TRUE_WORDS = new Set([\"1\", \"true\", \"yes\", \"on\", \"y\", \"t\", \"evet\", \"e\"])\nconst FALSE_WORDS = new Set([\"0\", \"false\", \"no\", \"off\", \"n\", \"f\", \"hayır\", \"hayir\", \"h\"])\n\n/**\n * Reads text into the field's type.\n *\n * Text with nothing in it is an empty cell, never a problem: whether a field may be empty is a rule,\n * checked with the other rules.\n */\nexport function readInput(field: FieldSchema, input: string, settings: ValueSettings): ReadResult {\n\tconst text = clean(input)\n\n\tif (text === \"\") {\n\t\treturn { value: null, problem: null }\n\t}\n\n\tswitch (field.type) {\n\t\tcase \"string\":\n\t\t\treturn { value: text, problem: null }\n\t\tcase \"lookup\":\n\t\t\t// Text is a record's name, not the record: a `LookupResolver` matches it to one, and until\n\t\t\t// then the backend has no id to take.\n\t\t\treturn refused(field, text, \"not_matched\")\n\t\tcase \"integer\": {\n\t\t\tconst number = readNumber(input, settings)\n\n\t\t\tif (number === null) {\n\t\t\t\treturn refused(field, text, \"not_a_number\")\n\t\t\t}\n\n\t\t\treturn isWholeNumberText(number) && !isTooLarge(number)\n\t\t\t\t? { value: number, problem: null }\n\t\t\t\t: refused(field, text, \"not_an_integer\")\n\t\t}\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\t\treturn numberResult(field, text, readNumber(input, settings))\n\t\tcase \"money\":\n\t\t\treturn numberResult(field, text, readMoney(input, field.currency, settings))\n\t\tcase \"percent\":\n\t\t\treturn numberResult(field, text, readPercent(input, settings))\n\t\tcase \"bool\":\n\t\t\treturn readBool(field, text, settings)\n\t\tcase \"date\":\n\t\tcase \"datetime\":\n\t\t\treturn readDateValue(field, text, settings)\n\t\tcase \"options\":\n\t\t\treturn readOptions(field, text)\n\t}\n}\n\n/**\n * The problem with what a cell holds, or null when it holds a value of its field's type.\n *\n * A value in the form the grid writes is fine as it is. Anything else is read as text, so a value\n * a host loaded as \"1.234,56\" into a money column is accepted, and a cell still holding what a user\n * typed and the grid could not read reports why.\n */\nexport function valueProblem(field: FieldSchema, value: CellValue, settings: ValueSettings): ValueProblem | null {\n\tif (value === null || isFieldValue(field, value)) {\n\t\treturn null\n\t}\n\n\treturn readInput(field, describeValue(value), settings).problem\n}\n\n/**\n * A value in the form the grid writes, as a backend is sent it: \"1.234,56\" a host loaded into a\n * money column goes as \"1234.56\", the value `valueProblem` accepted it as. Text the grid could not\n * read goes as it stands, for the backend to refuse as the grid did.\n */\nexport function canonicalValue(field: FieldSchema, value: CellValue, settings: ValueSettings): CellValue {\n\tif (value === null || isFieldValue(field, value)) {\n\t\treturn value\n\t}\n\n\tconst text = describeValue(value)\n\tconst result = readInput(field, text, settings)\n\n\tif (result.problem === null) {\n\t\treturn result.value\n\t}\n\n\t// \"12,5\" in an integer column was read, only not as a whole number: sent as 12.5, the backend\n\t// refuses it for the same reason the grid did, rather than as text it cannot read.\n\treturn result.problem.code === \"not_an_integer\" ? (readNumber(text, settings) ?? value) : value\n}\n\n/** Whether a value is already in the form a cell of this field holds. */\nexport function isFieldValue(field: FieldSchema, value: CellValue): boolean {\n\tswitch (field.type) {\n\t\tcase \"string\":\n\t\t\treturn typeof value === \"string\"\n\t\tcase \"integer\":\n\t\t\treturn (\n\t\t\t\t(typeof value === \"number\" && Number.isSafeInteger(value)) ||\n\t\t\t\t(typeof value === \"string\" && isWholeNumberText(value) && !isTooLarge(value))\n\t\t\t)\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\tcase \"money\":\n\t\tcase \"percent\":\n\t\t\treturn decimalText(value) !== null\n\t\tcase \"bool\":\n\t\t\treturn typeof value === \"boolean\"\n\t\tcase \"date\":\n\t\t\treturn isIsoDate(value, false)\n\t\tcase \"datetime\":\n\t\t\treturn isIsoDate(value, true)\n\t\tcase \"options\":\n\t\t\treturn field.multiple\n\t\t\t\t? Array.isArray(value) && value.every(item => isOptionValue(field, item))\n\t\t\t\t: isOptionValue(field, value)\n\t\tcase \"lookup\":\n\t\t\treturn isLookupValue(value)\n\t}\n}\n\n/** A value as text, for reading it again or for showing it as it stands. */\nexport function describeValue(value: CellValue): string {\n\tif (value === null) {\n\t\treturn \"\"\n\t}\n\n\tswitch (typeof value) {\n\t\tcase \"string\":\n\t\t\treturn value\n\t\tcase \"number\":\n\t\t\treturn decimalText(value) ?? String(value)\n\t\tcase \"boolean\":\n\t\t\treturn value ? \"true\" : \"false\"\n\t}\n\n\treturn JSON.stringify(value)\n}\n\nexport function isLookupValue(value: CellValue): value is { readonly id: string | number; readonly label: string } {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn false\n\t}\n\n\tconst record = value as Readonly<Record<string, CellValue>>\n\n\treturn (typeof record.id === \"string\" || typeof record.id === \"number\") && typeof record.label === \"string\"\n}\n\nfunction isOptionValue(field: OptionsField, value: CellValue): boolean {\n\treturn field.options.some(option => option.value === value)\n}\n\nfunction numberResult(field: FieldSchema, text: string, number: string | null): ReadResult {\n\treturn number === null ? refused(field, text, \"not_a_number\") : { value: number, problem: null }\n}\n\nfunction readBool(field: FieldSchema, text: string, settings: ValueSettings): ReadResult {\n\tconst needle = fold(text)\n\n\t// The settings' own words first: they are what the grid shows, and what a template's list offers.\n\tif (needle === fold(settings.trueWord)) {\n\t\treturn { value: true, problem: null }\n\t}\n\n\tif (needle === fold(settings.falseWord)) {\n\t\treturn { value: false, problem: null }\n\t}\n\n\tif (TRUE_WORDS.has(needle)) {\n\t\treturn { value: true, problem: null }\n\t}\n\n\tif (FALSE_WORDS.has(needle)) {\n\t\treturn { value: false, problem: null }\n\t}\n\n\tconst accepted = unique([settings.trueWord, settings.falseWord, \"Evet\", \"Hayır\", \"1\", \"0\", \"true\", \"false\"])\n\n\treturn refused(field, text, \"not_a_boolean\", { accepted: accepted.join(\", \") })\n}\n\nfunction readDateValue(\n\tfield: FieldSchema & { type: \"date\" | \"datetime\" },\n\ttext: string,\n\tsettings: ValueSettings\n): ReadResult {\n\tconst withTime = field.type === \"datetime\"\n\tconst pattern = datePatternOf(field, settings)\n\tconst other = withTime ? settings.datePattern : settings.dateTimePattern\n\tconst value = readDate(text, withTime, pattern, other)\n\n\treturn value === null ? refused(field, text, \"not_a_date\", { format: pattern }) : { value, problem: null }\n}\n\n/** The pattern a date field is shown and read with: its own, or the settings' for its type. */\nexport function datePatternOf(field: FieldSchema & { type: \"date\" | \"datetime\" }, settings: ValueSettings): string {\n\treturn field.pattern ?? (field.type === \"datetime\" ? settings.dateTimePattern : settings.datePattern)\n}\n\n/**\n * An option by its label first, then by its value, as nouxwell/tabula matches them: if one option's\n * label is another's value, the label wins, because it is what the user sees. A field that holds\n * several takes them separated by commas.\n */\nfunction readOptions(field: OptionsField, text: string): ReadResult {\n\tconst parts = field.multiple\n\t\t? text\n\t\t\t\t.split(\",\")\n\t\t\t\t.map(part => clean(part))\n\t\t\t\t.filter(part => part !== \"\")\n\t\t: [text]\n\tconst values: (string | number)[] = []\n\n\tfor (const part of parts) {\n\t\tconst needle = fold(part)\n\t\tconst option =\n\t\t\tfield.options.find(candidate => fold(candidate.label) === needle) ??\n\t\t\tfield.options.find(candidate => fold(String(candidate.value)) === needle)\n\n\t\tif (!option) {\n\t\t\treturn refused(field, text, \"not_an_option\", {\n\t\t\t\toptions: unique(field.options.map(candidate => candidate.label)).join(\", \")\n\t\t\t})\n\t\t}\n\n\t\tvalues.push(option.value)\n\t}\n\n\treturn { value: field.multiple ? Object.freeze(values) : (values[0] ?? null), problem: null }\n}\n\nfunction refused(\n\tfield: FieldSchema,\n\ttext: string,\n\tcode: ValueProblemCode,\n\textra: Readonly<Record<string, string>> = {}\n): ReadResult {\n\tconst params = Object.freeze({ field: field.key, type: field.type, value: text, ...extra })\n\n\treturn { value: text, problem: Object.freeze({ code, message: messageFor(code, params), params }) }\n}\n\n/** The same sentences as nouxwell/tabula's ParseException. */\nfunction messageFor(code: ValueProblemCode, params: Readonly<Record<string, string>>): string {\n\tconst value = params.value ?? \"\"\n\n\tswitch (code) {\n\t\tcase \"not_a_number\":\n\t\t\treturn `\"${value}\" could not be read as a number.`\n\t\tcase \"not_an_integer\":\n\t\t\treturn `\"${value}\" is not a whole number.`\n\t\tcase \"not_a_date\":\n\t\t\treturn `\"${value}\" could not be read as a date; expected format: ${params.format ?? \"\"}`\n\t\tcase \"not_a_boolean\":\n\t\t\treturn `\"${value}\" is not a Yes/No value. Accepted: ${params.accepted ?? \"\"}`\n\t\tcase \"not_an_option\":\n\t\t\treturn `\"${value}\" is not in the list. Options: ${params.options || \"(no options defined)\"}`\n\t\tcase \"not_matched\":\n\t\t\treturn `\"${value}\" is not matched to a record; pick one from the list.`\n\t}\n}\n\n/** Without repeats, comparing as `fold()` does, keeping the first spelling of each. */\nfunction unique(words: readonly string[]): string[] {\n\tconst seen = new Map<string, string>()\n\n\tfor (const word of words) {\n\t\tconst key = fold(word)\n\n\t\tif (key !== \"\" && !seen.has(key)) {\n\t\t\tseen.set(key, word)\n\t\t}\n\t}\n\n\treturn [...seen.values()]\n}\n","import { compareDecimal, normalizeDecimal } from \"./decimal.js\"\nimport type { RowId, RowStore } from \"./rows.js\"\nimport type { FieldSchema, FieldType, ModuleSchema } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport { decimalText } from \"./values/number.js\"\nimport { canonicalValue, isFieldValue, isLookupValue, valueProblem } from \"./values/read.js\"\nimport type { ValueSettings } from \"./values/settings.js\"\n\n/**\n * Row checks: rules about a row rather than one cell, as a module schema or a template writes them.\n * \"Not is required when Aktif is no\", \"Yeni fiyat cannot be below Mevcut fiyat\", \"Geçerlilik cannot\n * be before 2026-12-01 when Para birimi is USD\".\n *\n * A check says what must hold for one field of the row (`assert`), and when (`when`: every condition\n * holding, or always when there is none). What it asserts is a condition too: the field filled,\n * empty, or compared with a value or with another field of the row. Its issue lands on that field's\n * cell, as an error that keeps the row from being processed or as a warning that does not.\n */\n\nexport const COMPARISONS = Object.freeze([\"=\", \"!=\", \"<\", \"<=\", \">\", \">=\"] as const)\nexport type Comparison = (typeof COMPARISONS)[number]\n\nexport const CONDITION_OPS = Object.freeze([...COMPARISONS, \"filled\", \"empty\"] as const)\nexport type ConditionOp = (typeof CONDITION_OPS)[number]\n\n/** One thing about one field of a row. */\nexport interface RowCondition {\n\treadonly field: string\n\treadonly op: ConditionOp\n\t/** What a comparison compares with: a value in the form a cell holds it, or null… */\n\treadonly value: CellValue\n\t/** …or another field of the row, by key. */\n\treadonly other: string | null\n}\n\nexport type CheckSeverity = \"error\" | \"warning\"\n\nexport interface RowCheck {\n\t/** Names the check: its issues' ids, and an editor's list. Unique in the schema with its template. */\n\treadonly id: string\n\t/** What must hold for the row. The issue lands on this field's cell. */\n\treadonly assert: RowCondition\n\t/** When the check applies: every condition holding. Empty: always. */\n\treadonly when: readonly RowCondition[]\n\treadonly severity: CheckSeverity\n\t/** The words to say, by language, such as `{ \"tr\": \"…\", \"en\": \"…\" }`; null leaves them to the grid. */\n\treadonly message: Readonly<Record<string, string>> | null\n}\n\n/** A condition as it is written in the JSON. */\nexport interface ConditionInput {\n\tfield: string\n\top: ConditionOp\n\tvalue?: string | number | boolean | readonly (string | number)[]\n\tother?: string\n}\n\n/** A check as it is written in the JSON. */\nexport interface CheckInput {\n\tid: string\n\tassert: ConditionInput\n\twhen?: ConditionInput[]\n\tseverity?: CheckSeverity\n\tmessage?: Record<string, string>\n}\n\nconst NUMERIC: ReadonlySet<FieldType> = new Set([\"integer\", \"decimal\", \"money\", \"quantity\", \"percent\"])\nconst ORDERED: ReadonlySet<FieldType> = new Set([...NUMERIC, \"date\", \"datetime\"])\nconst CHECK_PROPERTIES = [\"id\", \"assert\", \"when\", \"severity\", \"message\"]\nconst CONDITION_PROPERTIES = [\"field\", \"op\", \"value\", \"other\"]\n\ntype Add = (path: string, message: string) => void\ntype Json = Record<string, unknown>\n\n/** Reads a schema's checks against its fields, reporting every problem with where it is. */\nexport function readChecks(value: unknown, fields: readonly FieldSchema[], add: Add): RowCheck[] {\n\tif (value === undefined || value === null) {\n\t\treturn []\n\t}\n\n\tif (!Array.isArray(value)) {\n\t\tadd(\"checks\", \"must be an array of checks\")\n\n\t\treturn []\n\t}\n\n\tconst byKey = new Map(fields.map(field => [field.key, field]))\n\tconst ids = new Map<string, number>()\n\tconst checks: RowCheck[] = []\n\n\t;(value as unknown[]).forEach((raw, index) => {\n\t\tconst path = `checks[${index}]`\n\t\tconst check = readCheck(raw, path, byKey, add)\n\n\t\tif (!check) {\n\t\t\treturn\n\t\t}\n\n\t\tconst first = ids.get(check.id)\n\n\t\tif (first !== undefined) {\n\t\t\tadd(`${path}.id`, `\"${check.id}\" is already the id of checks[${first}]; an id names one check only`)\n\n\t\t\treturn\n\t\t}\n\n\t\tids.set(check.id, index)\n\t\tchecks.push(check)\n\t})\n\n\treturn checks\n}\n\n/** A check written out again as JSON. */\nexport function checkToJson(check: RowCheck): CheckInput {\n\tconst json: CheckInput = { id: check.id, assert: conditionToJson(check.assert) }\n\n\tif (check.when.length > 0) {\n\t\tjson.when = check.when.map(conditionToJson)\n\t}\n\n\tjson.severity = check.severity\n\n\tif (check.message !== null) {\n\t\tjson.message = { ...check.message }\n\t}\n\n\treturn json\n}\n\n/** The fields a check reads: what it asserts, what it compares with, and its conditions. */\nexport function checkFields(check: RowCheck): string[] {\n\tconst keys = new Set<string>()\n\n\tfor (const condition of [check.assert, ...check.when]) {\n\t\tkeys.add(condition.field)\n\n\t\tif (condition.other !== null) {\n\t\t\tkeys.add(condition.other)\n\t\t}\n\t}\n\n\treturn [...keys]\n}\n\n/**\n * Whether a row breaks the check: every condition of `when` holds, and what it asserts does not. A\n * comparison with nothing on one side asserts nothing: a field's being filled is a check of its own.\n * A value that cannot be read as its field's is nothing to compare either; its cell says why.\n */\nexport function breaksCheck(\n\tcheck: RowCheck,\n\tfield: (key: string) => FieldSchema,\n\tget: (key: string) => CellValue,\n\tsettings: ValueSettings\n): boolean {\n\tfor (const condition of check.when) {\n\t\tif (holds(condition, field, get, settings) !== true) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn holds(check.assert, field, get, settings) === false\n}\n\n/**\n * The rows that break a check, in the order they stand in the sheet: what a rule editor counts and\n * shows while the rule is still being written, before it is saved anywhere. `schema` is one that has\n * the check, such as the template applied with it.\n */\nexport function rowsBreaking(schema: ModuleSchema, store: RowStore, check: RowCheck, settings: ValueSettings): RowId[] {\n\tconst field = (key: string): FieldSchema => schema.field(key)\n\n\treturn store.rowIds().filter(rowId => breaksCheck(check, field, key => store.get(rowId, key), settings))\n}\n\n/**\n * Whether a condition holds for a row: what a colour rule asks. A comparison with nothing on one side\n * does not hold, nor does one with a value that cannot be read as its field's.\n */\nexport function conditionHolds(\n\tcondition: RowCondition,\n\tfield: (key: string) => FieldSchema,\n\tget: (key: string) => CellValue,\n\tsettings: ValueSettings\n): boolean {\n\treturn holds(condition, field, get, settings) === true\n}\n\n// ---------------------------------------------------------------- inside\n\n/** True or false, or null when a comparison has nothing to compare on one side. */\nfunction holds(\n\tcondition: RowCondition,\n\tfield: (key: string) => FieldSchema,\n\tget: (key: string) => CellValue,\n\tsettings: ValueSettings\n): boolean | null {\n\tconst own = field(condition.field)\n\tconst raw = get(condition.field)\n\n\tif (condition.op === \"filled\") {\n\t\treturn raw !== null\n\t}\n\n\tif (condition.op === \"empty\") {\n\t\treturn raw === null\n\t}\n\n\tconst left = readable(own, raw, settings)\n\tconst right =\n\t\tcondition.other === null ? condition.value : readable(field(condition.other), get(condition.other), settings)\n\n\tif (left === null || right === null) {\n\t\treturn null\n\t}\n\n\tconst order = compare(own, left, right)\n\n\tswitch (condition.op) {\n\t\tcase \"=\":\n\t\t\treturn order === 0\n\t\tcase \"!=\":\n\t\t\treturn order !== 0\n\t\tcase \"<\":\n\t\t\treturn order < 0\n\t\tcase \"<=\":\n\t\t\treturn order <= 0\n\t\tcase \">\":\n\t\t\treturn order > 0\n\t\tcase \">=\":\n\t\t\treturn order >= 0\n\t}\n}\n\n/** The value as the backend is sent it; null for an empty cell or one that cannot be read. */\nfunction readable(field: FieldSchema, value: CellValue, settings: ValueSettings): CellValue {\n\tif (value === null || valueProblem(field, value, settings) !== null) {\n\t\treturn null\n\t}\n\n\treturn canonicalValue(field, value, settings)\n}\n\n/** Below zero, zero or above, as the values stand; for kinds with no order, zero or not. */\nfunction compare(field: FieldSchema, a: CellValue, b: CellValue): number {\n\tif (NUMERIC.has(field.type)) {\n\t\tconst left = normalizeDecimal(decimalText(a) ?? \"\")\n\t\tconst right = normalizeDecimal(decimalText(b) ?? \"\")\n\n\t\treturn left === null || right === null ? 1 : compareDecimal(left, right)\n\t}\n\n\tif (field.type === \"date\" || field.type === \"datetime\") {\n\t\treturn String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0\n\t}\n\n\treturn sameValue(a, b) ? 0 : 1\n}\n\nfunction sameValue(a: CellValue, b: CellValue): boolean {\n\tif (isLookupValue(a) && isLookupValue(b)) {\n\t\treturn String(a.id) === String(b.id)\n\t}\n\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\treturn JSON.stringify([...a].map(String).sort()) === JSON.stringify([...b].map(String).sort())\n\t}\n\n\treturn a === b || (typeof a !== \"object\" && typeof b !== \"object\" && String(a) === String(b))\n}\n\nfunction readCheck(raw: unknown, path: string, fields: ReadonlyMap<string, FieldSchema>, add: Add): RowCheck | null {\n\tif (!isObject(raw)) {\n\t\tadd(path, 'must be an object such as { \"id\": \"…\", \"assert\": { \"field\": \"…\", \"op\": \"filled\" } }')\n\n\t\treturn null\n\t}\n\n\tlet failed = false\n\tconst fail: Add = (at, message) => {\n\t\tfailed = true\n\t\tadd(at, message)\n\t}\n\n\tfor (const name of Object.keys(raw)) {\n\t\tif (!CHECK_PROPERTIES.includes(name)) {\n\t\t\tfail(`${path}.${name}`, `is not a check property; a check takes ${CHECK_PROPERTIES.join(\", \")}`)\n\t\t}\n\t}\n\n\tconst id = typeof raw.id === \"string\" && raw.id.trim() !== \"\" ? raw.id : null\n\n\tif (id === null) {\n\t\tfail(`${path}.id`, \"must be a non-empty string\")\n\t}\n\n\tconst assert = readCondition(raw.assert, `${path}.assert`, fields, fail)\n\tconst when: RowCondition[] = []\n\n\tif (raw.when !== undefined && raw.when !== null) {\n\t\tif (!Array.isArray(raw.when)) {\n\t\t\tfail(`${path}.when`, \"must be an array of conditions, every one of which must hold\")\n\t\t} else {\n\t\t\t;(raw.when as unknown[]).forEach((item, index) => {\n\t\t\t\tconst condition = readCondition(item, `${path}.when[${index}]`, fields, fail)\n\n\t\t\t\tif (condition) {\n\t\t\t\t\twhen.push(condition)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tconst severity = raw.severity === undefined || raw.severity === null ? \"error\" : raw.severity\n\n\tif (severity !== \"error\" && severity !== \"warning\") {\n\t\tfail(`${path}.severity`, `must be \"error\" or \"warning\"; got ${JSON.stringify(severity)}`)\n\t}\n\n\tconst message = readMessage(raw.message, `${path}.message`, fail)\n\n\tif (failed || id === null || assert === null) {\n\t\treturn null\n\t}\n\n\treturn Object.freeze({\n\t\tid,\n\t\tassert,\n\t\twhen: Object.freeze(when),\n\t\tseverity: severity as CheckSeverity,\n\t\tmessage\n\t})\n}\n\n/** Reads one condition against the fields, as a check's and a colour rule's are written. */\nexport function readCondition(\n\traw: unknown,\n\tpath: string,\n\tfields: ReadonlyMap<string, FieldSchema>,\n\tadd: Add\n): RowCondition | null {\n\tif (!isObject(raw)) {\n\t\tadd(path, 'must be an object such as { \"field\": \"active\", \"op\": \"=\", \"value\": false }')\n\n\t\treturn null\n\t}\n\n\tconst before = { failed: false }\n\tconst fail: Add = (at, message) => {\n\t\tbefore.failed = true\n\t\tadd(at, message)\n\t}\n\n\tfor (const name of Object.keys(raw)) {\n\t\tif (!CONDITION_PROPERTIES.includes(name)) {\n\t\t\tfail(`${path}.${name}`, `is not a condition property; a condition takes ${CONDITION_PROPERTIES.join(\", \")}`)\n\t\t}\n\t}\n\n\tconst field = typeof raw.field === \"string\" ? fields.get(raw.field) : undefined\n\n\tif (!field) {\n\t\tfail(`${path}.field`, `${JSON.stringify(raw.field)} is not a field of this schema`)\n\t}\n\n\tconst op = raw.op as ConditionOp\n\n\tif (!(CONDITION_OPS as readonly unknown[]).includes(op)) {\n\t\tfail(`${path}.op`, `${JSON.stringify(raw.op)} is not a condition; expected one of ${CONDITION_OPS.join(\", \")}`)\n\n\t\treturn null\n\t}\n\n\tconst hasValue = raw.value !== undefined && raw.value !== null\n\tconst hasOther = raw.other !== undefined && raw.other !== null\n\n\tif (op === \"filled\" || op === \"empty\") {\n\t\tif (hasValue || hasOther) {\n\t\t\tfail(path, `${op} takes no value and no other field`)\n\t\t}\n\n\t\treturn before.failed || !field ? null : Object.freeze({ field: field.key, op, value: null, other: null })\n\t}\n\n\tif (hasValue === hasOther) {\n\t\tfail(path, `${op} compares with a value or with another field: give one of value and other`)\n\n\t\treturn null\n\t}\n\n\tif (field && (op === \"<\" || op === \"<=\" || op === \">\" || op === \">=\") && !ORDERED.has(field.type)) {\n\t\tfail(`${path}.op`, `${op} needs an order; a ${field.type} field only takes = and !=`)\n\t}\n\n\tlet other: string | null = null\n\tlet value: CellValue = null\n\n\tif (hasOther) {\n\t\tconst otherField = typeof raw.other === \"string\" ? fields.get(raw.other) : undefined\n\n\t\tif (!otherField) {\n\t\t\tfail(`${path}.other`, `${JSON.stringify(raw.other)} is not a field of this schema`)\n\t\t} else if (field && !comparable(field.type, otherField.type)) {\n\t\t\tfail(`${path}.other`, `a ${field.type} field cannot be compared with a ${otherField.type} field`)\n\t\t} else if (field && otherField.key === field.key) {\n\t\t\tfail(`${path}.other`, \"is the field itself\")\n\t\t} else {\n\t\t\tother = otherField.key\n\t\t}\n\t} else if (field) {\n\t\t// A number is kept as decimal text, as every cell of a numeric field holds one.\n\t\tconst given = (NUMERIC.has(field.type) ? (decimalText(raw.value) ?? raw.value) : raw.value) as CellValue\n\n\t\tif (field.type === \"lookup\" || !isFieldValue(field, given)) {\n\t\t\tfail(\n\t\t\t\t`${path}.value`,\n\t\t\t\t`${JSON.stringify(raw.value)} is not a value of the ${field.type} field \"${field.key}\"`\n\t\t\t)\n\t\t} else {\n\t\t\tvalue = Array.isArray(given) ? (Object.freeze([...(given as unknown[])]) as CellValue) : given\n\t\t}\n\t}\n\n\treturn before.failed || !field ? null : Object.freeze({ field: field.key, op, value, other })\n}\n\nfunction comparable(a: FieldType, b: FieldType): boolean {\n\treturn (NUMERIC.has(a) && NUMERIC.has(b)) || a === b\n}\n\nfunction readMessage(raw: unknown, path: string, add: Add): Readonly<Record<string, string>> | null {\n\tif (raw === undefined || raw === null) {\n\t\treturn null\n\t}\n\n\tif (!isObject(raw) || Object.keys(raw).length === 0) {\n\t\tadd(path, 'must be an object of words by language, such as { \"tr\": \"…\", \"en\": \"…\" }')\n\n\t\treturn null\n\t}\n\n\tfor (const [language, text] of Object.entries(raw)) {\n\t\tif (typeof text !== \"string\" || text.trim() === \"\") {\n\t\t\tadd(`${path}.${language}`, \"must be a non-empty string\")\n\t\t}\n\t}\n\n\treturn Object.freeze({ ...(raw as Record<string, string>) })\n}\n\n/** A condition written out again as JSON. */\nexport function conditionToJson(condition: RowCondition): ConditionInput {\n\tconst json: ConditionInput = { field: condition.field, op: condition.op }\n\n\tif (condition.other !== null) {\n\t\tjson.other = condition.other\n\t} else if (condition.value !== null) {\n\t\tjson.value = condition.value as NonNullable<ConditionInput[\"value\"]>\n\t}\n\n\treturn json\n}\n\nfunction isObject(value: unknown): value is Json {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n","type Listener<T> = (event: T) => void\n\n/**\n * A list of listeners, called in the order they subscribed.\n *\n * A listener that throws does not stop the others, and does not undo the change it was told about:\n * the change has happened. The error is reported the way a browser reports one thrown from an event\n * listener, so it is seen rather than swallowed.\n */\nexport class Listeners<T> {\n\treadonly #listeners = new Set<Listener<T>>()\n\n\tadd(listener: Listener<T>): () => void {\n\t\t// Wrapped, so the same function subscribed twice is two subscriptions, each with its own way out.\n\t\tconst entry: Listener<T> = event => listener(event)\n\t\tthis.#listeners.add(entry)\n\n\t\treturn () => {\n\t\t\tthis.#listeners.delete(entry)\n\t\t}\n\t}\n\n\temit(event: T): void {\n\t\tfor (const listener of [...this.#listeners]) {\n\t\t\t// One that an earlier listener unsubscribed is not called.\n\t\t\tif (!this.#listeners.has(listener)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tlistener(event)\n\t\t\t} catch (error) {\n\t\t\t\treport(error)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction report(error: unknown): void {\n\tconst scope = globalThis as { reportError?: (error: unknown) => void }\n\n\tif (typeof scope.reportError === \"function\") {\n\t\tscope.reportError(error)\n\n\t\treturn\n\t}\n\n\t// Where there is no reportError, an unhandled rejection is the nearest thing: seen, and not in the way.\n\tvoid Promise.reject(error)\n}\n","import { TabulaError } from \"./errors.js\"\nimport type { UndoHistory } from \"./history.js\"\nimport { Listeners } from \"./listeners.js\"\nimport type { RowId } from \"./rows.js\"\n\n/**\n * What a user puts on cells by hand to find them again: a fill, a text colour, bold, italic. \"These\n * I will look at later\", \"this one is wrong at the supplier's\". Never a value: a mark is kept with\n * the draft, beside the rows, and nothing of it is sent to the backend.\n *\n * Colours are names, not codes, so a theme draws each in its own shade, light or dark.\n */\n\nexport const MARK_COLORS = Object.freeze([\n\t\"yellow\",\n\t\"green\",\n\t\"blue\",\n\t\"purple\",\n\t\"pink\",\n\t\"orange\",\n\t\"grey\",\n\t\"red\"\n] as const)\nexport type MarkColor = (typeof MARK_COLORS)[number]\n\nexport interface CellMark {\n\treadonly fill?: MarkColor\n\treadonly color?: MarkColor\n\treadonly bold?: true\n\treadonly italic?: true\n}\n\n/** A change to cells' marks: a colour, or null to take it off; bold and italic on or off. */\nexport interface CellMarkChange {\n\treadonly fill?: MarkColor | null\n\treadonly color?: MarkColor | null\n\treadonly bold?: boolean\n\treadonly italic?: boolean\n}\n\n/** One cell, by its row's id and its field's key. */\nexport interface MarkedCell {\n\treadonly rowId: RowId\n\treadonly field: string\n}\n\n/** The marks as JSON keeps them: by row id, then by field key. */\nexport type MarksData = Readonly<Record<RowId, Readonly<Record<string, CellMark>>>>\n\nexport interface CellMarksOptions {\n\t/** Marks to start with, such as a draft's. */\n\treadonly marks?: MarksData\n\t/** Each change becomes a step of it, so Ctrl+Z takes it back in its turn with the rows' changes. */\n\treadonly history?: UndoHistory\n}\n\n/** The marks on a sheet's cells: read by the grid, changed by the toolbar, kept by the draft. */\nexport class CellMarks {\n\treadonly #cells = new Map<RowId, Map<string, CellMark>>()\n\treadonly #history: UndoHistory | null\n\treadonly #listeners = new Listeners<CellMarks>()\n\t#version = 0\n\n\tconstructor(options: CellMarksOptions = {}) {\n\t\tthis.#history = options.history ?? null\n\n\t\tfor (const [rowId, cells] of Object.entries(options.marks ?? {})) {\n\t\t\tfor (const [field, mark] of Object.entries(cells)) {\n\t\t\t\tthis.#put(rowId, field, cleanMark(mark))\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Moves on with every change, for a view to redraw by. */\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\t/** How many cells carry a mark. */\n\tget size(): number {\n\t\tlet count = 0\n\n\t\tfor (const cells of this.#cells.values()) {\n\t\t\tcount += cells.size\n\t\t}\n\n\t\treturn count\n\t}\n\n\tget(rowId: RowId, field: string): CellMark | null {\n\t\treturn this.#cells.get(rowId)?.get(field) ?? null\n\t}\n\n\t/** Whether any cell of the row carries a mark. */\n\thasRow(rowId: RowId): boolean {\n\t\treturn this.#cells.has(rowId)\n\t}\n\n\t/** The rows with a marked cell. */\n\trows(): RowId[] {\n\t\treturn [...this.#cells.keys()]\n\t}\n\n\t/** Puts the change on every cell given: a colour given replaces the one there, null takes it off. */\n\tmark(cells: readonly MarkedCell[], change: CellMarkChange): void {\n\t\tcheckChange(change)\n\t\tthis.#change(cells, mark => {\n\t\t\tconst next: { fill?: MarkColor; color?: MarkColor; bold?: true; italic?: true } = { ...mark }\n\n\t\t\tfor (const name of [\"fill\", \"color\"] as const) {\n\t\t\t\tif (change[name] === null) {\n\t\t\t\t\tdelete next[name]\n\t\t\t\t} else if (change[name] !== undefined) {\n\t\t\t\t\tnext[name] = change[name]\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const name of [\"bold\", \"italic\"] as const) {\n\t\t\t\tif (change[name] === false) {\n\t\t\t\t\tdelete next[name]\n\t\t\t\t} else if (change[name] === true) {\n\t\t\t\t\tnext[name] = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn next\n\t\t})\n\t}\n\n\t/** Bold or italic on every cell given, or off when every one already has it, as a spreadsheet's button. */\n\ttoggle(cells: readonly MarkedCell[], style: \"bold\" | \"italic\"): void {\n\t\tconst on = !cells.every(cell => this.get(cell.rowId, cell.field)?.[style] === true)\n\n\t\tthis.mark(cells, { [style]: on })\n\t}\n\n\t/** Takes every mark off the cells given. */\n\tclear(cells: readonly MarkedCell[]): void {\n\t\tthis.#change(cells, () => ({}))\n\t}\n\n\t/** Every mark, as JSON keeps them; only the rows given, such as the rows the sheet still has. */\n\ttoJSON(rowIds?: Iterable<RowId>): MarksData {\n\t\tconst keep = rowIds === undefined ? null : new Set(rowIds)\n\t\tconst data: Record<RowId, Record<string, CellMark>> = {}\n\n\t\tfor (const [rowId, cells] of this.#cells) {\n\t\t\tif (keep === null || keep.has(rowId)) {\n\t\t\t\tdata[rowId] = Object.fromEntries(cells)\n\t\t\t}\n\t\t}\n\n\t\treturn data\n\t}\n\n\t/** Called after each change. Returns the way to stop. */\n\tsubscribe(listener: (marks: CellMarks) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Changes the cells, as one step of the history when there is one. */\n\t#change(cells: readonly MarkedCell[], next: (mark: CellMark) => CellMark): void {\n\t\tconst before: [MarkedCell, CellMark | null][] = []\n\t\tconst after: [MarkedCell, CellMark | null][] = []\n\n\t\tfor (const cell of cells) {\n\t\t\tconst old = this.get(cell.rowId, cell.field)\n\t\t\tconst made = cleanMark(next(old ?? {}))\n\t\t\tconst now = Object.keys(made).length === 0 ? null : made\n\n\t\t\tif (!sameMark(old, now)) {\n\t\t\t\tbefore.push([cell, old])\n\t\t\t\tafter.push([cell, now])\n\t\t\t}\n\t\t}\n\n\t\tif (after.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#apply(after)\n\t\tthis.#history?.record({ undo: () => this.#apply(before), redo: () => this.#apply(after) })\n\t}\n\n\t#apply(entries: readonly (readonly [MarkedCell, CellMark | null])[]): void {\n\t\tfor (const [cell, mark] of entries) {\n\t\t\tthis.#put(cell.rowId, cell.field, mark)\n\t\t}\n\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n\n\t#put(rowId: RowId, field: string, mark: CellMark | null): void {\n\t\tconst cells = this.#cells.get(rowId)\n\n\t\tif (mark === null || Object.keys(mark).length === 0) {\n\t\t\tcells?.delete(field)\n\n\t\t\tif (cells?.size === 0) {\n\t\t\t\tthis.#cells.delete(rowId)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tif (cells) {\n\t\t\tcells.set(field, mark)\n\t\t} else {\n\t\t\tthis.#cells.set(rowId, new Map([[field, mark]]))\n\t\t}\n\t}\n}\n\n/** The rows with a marked cell, for a `RowView` filter: the sheet's \"Renkli\" rows. */\nexport function rowsMarked(marks: CellMarks): (rowId: RowId) => boolean {\n\treturn rowId => marks.hasRow(rowId)\n}\n\n/**\n * Marks read from JSON, such as a draft's, each problem reported under `path`. A colour that is not\n * one, or a cell that is not an object, is a problem; an empty mark is dropped.\n */\nexport function readMarks(input: unknown, path: string, problem: (path: string, message: string) => void): MarksData {\n\tif (input === undefined || input === null) {\n\t\treturn {}\n\t}\n\n\tconst rows = plain(input)\n\n\tif (!rows) {\n\t\tproblem(path, \"must be an object of marks by row id, then field key.\")\n\n\t\treturn {}\n\t}\n\n\tconst data: Record<RowId, Record<string, CellMark>> = {}\n\n\tfor (const [rowId, value] of Object.entries(rows)) {\n\t\tconst cells = plain(value)\n\n\t\tif (!cells) {\n\t\t\tproblem(`${path}.${rowId}`, \"must be an object of marks by field key.\")\n\t\t\tcontinue\n\t\t}\n\n\t\tfor (const [field, raw] of Object.entries(cells)) {\n\t\t\tconst mark = plain(raw)\n\t\t\tconst at = `${path}.${rowId}.${field}`\n\n\t\t\tif (!mark) {\n\t\t\t\tproblem(at, 'must be an object such as { fill: \"yellow\", bold: true }.')\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst read: { fill?: MarkColor; color?: MarkColor; bold?: true; italic?: true } = {}\n\n\t\t\tfor (const name of [\"fill\", \"color\"] as const) {\n\t\t\t\tif (mark[name] === undefined) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif ((MARK_COLORS as readonly unknown[]).includes(mark[name])) {\n\t\t\t\t\tread[name] = mark[name] as MarkColor\n\t\t\t\t} else {\n\t\t\t\t\tproblem(`${at}.${name}`, `must be one of ${MARK_COLORS.join(\", \")}.`)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const name of [\"bold\", \"italic\"] as const) {\n\t\t\t\tif (mark[name] === true) {\n\t\t\t\t\tread[name] = true\n\t\t\t\t} else if (mark[name] !== undefined && mark[name] !== false) {\n\t\t\t\t\tproblem(`${at}.${name}`, \"must be true or false.\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Object.keys(read).length > 0) {\n\t\t\t\tdata[rowId] = { ...data[rowId], [field]: Object.freeze(read) }\n\t\t\t}\n\t\t}\n\t}\n\n\treturn data\n}\n\nfunction checkChange(change: CellMarkChange): void {\n\tfor (const name of [\"fill\", \"color\"] as const) {\n\t\tconst color = change[name]\n\n\t\tif (color !== undefined && color !== null && !(MARK_COLORS as readonly unknown[]).includes(color)) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_argument\",\n\t\t\t\t`A mark's ${name} is one of ${MARK_COLORS.join(\", \")}; got ${color}.`\n\t\t\t)\n\t\t}\n\t}\n}\n\nfunction cleanMark(mark: CellMark): CellMark {\n\treturn Object.freeze({\n\t\t...(mark.fill ? { fill: mark.fill } : {}),\n\t\t...(mark.color ? { color: mark.color } : {}),\n\t\t...(mark.bold ? { bold: true as const } : {}),\n\t\t...(mark.italic ? { italic: true as const } : {})\n\t})\n}\n\nfunction sameMark(a: CellMark | null, b: CellMark | null): boolean {\n\treturn (\n\t\t(a?.fill ?? null) === (b?.fill ?? null) &&\n\t\t(a?.color ?? null) === (b?.color ?? null) &&\n\t\t(a?.bold ?? false) === (b?.bold ?? false) &&\n\t\t(a?.italic ?? false) === (b?.italic ?? false)\n\t)\n}\n\nfunction plain(value: unknown): Record<string, unknown> | null {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: null\n}\n","import { conditionHolds, conditionToJson, readCondition, type ConditionInput, type RowCondition } from \"./checks.js\"\nimport { MARK_COLORS, type MarkColor } from \"./marks.js\"\nimport type { RowId, RowStore } from \"./rows.js\"\nimport type { FieldSchema, ModuleSchema } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport type { ValueSettings } from \"./values/settings.js\"\n\n/**\n * Colour rules: cells coloured by what the row holds, as a module schema or a template writes them.\n * \"Yeni fiyat below 100: orange\", \"Para birimi not TRY: blue text\", \"Aktif is no: the whole row\n * grey\". A rule's conditions are a check's: a field compared with a value or another field, filled\n * or empty, every one holding. When they hold, the rule's cell, or the whole row, takes its colours.\n *\n * Only how the sheet is drawn: a rule changes no value, and nothing of it is sent to the backend.\n * Everyone who opens the template sees the same colours, and they follow the values as they change.\n */\n\nexport interface StyleRule {\n\t/** Names the rule: an editor's list. Unique in the schema with its template. */\n\treadonly id: string\n\t/** When the rule colours: every condition holding. Never empty. */\n\treadonly when: readonly RowCondition[]\n\t/** The cell coloured, by field key; null colours the whole row. */\n\treadonly field: string | null\n\treadonly fill: MarkColor | null\n\treadonly color: MarkColor | null\n\treadonly bold: boolean\n}\n\n/** A colour rule as it is written in the JSON. */\nexport interface StyleRuleInput {\n\tid: string\n\twhen: ConditionInput[]\n\t/** Left out, the whole row. */\n\tfield?: string\n\tfill?: MarkColor\n\tcolor?: MarkColor\n\tbold?: boolean\n}\n\n/** What rules put on one cell: the last rule to say a thing wins, as later rules are written over earlier ones. */\nexport interface CellStyle {\n\treadonly fill: MarkColor | null\n\treadonly color: MarkColor | null\n\treadonly bold: boolean\n}\n\nconst RULE_PROPERTIES = [\"id\", \"when\", \"field\", \"fill\", \"color\", \"bold\"]\n\ntype Add = (path: string, message: string) => void\n\n/** Reads a schema's colour rules against its fields, reporting every problem with where it is. */\nexport function readStyleRules(value: unknown, fields: readonly FieldSchema[], add: Add): StyleRule[] {\n\tif (value === undefined || value === null) {\n\t\treturn []\n\t}\n\n\tif (!Array.isArray(value)) {\n\t\tadd(\"styles\", \"must be an array of colour rules\")\n\n\t\treturn []\n\t}\n\n\tconst byKey = new Map(fields.map(field => [field.key, field]))\n\tconst ids = new Map<string, number>()\n\tconst rules: StyleRule[] = []\n\n\tvalue.forEach((raw: unknown, index) => {\n\t\tconst path = `styles[${index}]`\n\t\tconst rule = readRule(raw, path, byKey, add)\n\n\t\tif (rule === null) {\n\t\t\treturn\n\t\t}\n\n\t\tconst seen = ids.get(rule.id)\n\n\t\tif (seen !== undefined) {\n\t\t\tadd(`${path}.id`, `\"${rule.id}\" is the id of styles[${seen}] too`)\n\n\t\t\treturn\n\t\t}\n\n\t\tids.set(rule.id, index)\n\t\trules.push(rule)\n\t})\n\n\treturn rules\n}\n\n/** A colour rule written out again as JSON. */\nexport function styleRuleToJson(rule: StyleRule): StyleRuleInput {\n\treturn {\n\t\tid: rule.id,\n\t\twhen: rule.when.map(conditionToJson),\n\t\t...(rule.field === null ? {} : { field: rule.field }),\n\t\t...(rule.fill === null ? {} : { fill: rule.fill }),\n\t\t...(rule.color === null ? {} : { color: rule.color }),\n\t\t...(rule.bold ? { bold: true } : {})\n\t}\n}\n\n/** Whether the rule colours the row: every one of its conditions holds. */\nexport function styleApplies(\n\trule: StyleRule,\n\tfield: (key: string) => FieldSchema,\n\tget: (key: string) => CellValue,\n\tsettings: ValueSettings\n): boolean {\n\treturn rule.when.every(condition => conditionHolds(condition, field, get, settings))\n}\n\n/**\n * What the rules put on each cell of a row, by field key, and on the row itself under `null`. Empty\n * when no rule colours the row.\n */\nexport function rowStyles(\n\trules: readonly StyleRule[],\n\tfield: (key: string) => FieldSchema,\n\tget: (key: string) => CellValue,\n\tsettings: ValueSettings\n): Map<string | null, CellStyle> {\n\tconst styles = new Map<string | null, CellStyle>()\n\n\tfor (const rule of rules) {\n\t\tif (!styleApplies(rule, field, get, settings)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst before = styles.get(rule.field)\n\n\t\tstyles.set(rule.field, {\n\t\t\tfill: rule.fill ?? before?.fill ?? null,\n\t\t\tcolor: rule.color ?? before?.color ?? null,\n\t\t\tbold: rule.bold || (before?.bold ?? false)\n\t\t})\n\t}\n\n\treturn styles\n}\n\n/**\n * The rows a rule colours, in the order they stand in the sheet: what a rule editor counts while the\n * rule is being written. `schema` is one that has the rule's fields.\n */\nexport function rowsStyled(schema: ModuleSchema, store: RowStore, rule: StyleRule, settings: ValueSettings): RowId[] {\n\tconst field = (key: string): FieldSchema => schema.field(key)\n\n\treturn store.rowIds().filter(rowId => styleApplies(rule, field, key => store.get(rowId, key), settings))\n}\n\nfunction readRule(raw: unknown, path: string, fields: ReadonlyMap<string, FieldSchema>, add: Add): StyleRule | null {\n\tif (!isObject(raw)) {\n\t\tadd(\n\t\t\tpath,\n\t\t\t'must be an object such as { \"id\": \"…\", \"when\": [{ \"field\": \"…\", \"op\": \"<\", \"value\": 100 }], \"fill\": \"orange\" }'\n\t\t)\n\n\t\treturn null\n\t}\n\n\tlet failed = false\n\tconst fail: Add = (at, message) => {\n\t\tfailed = true\n\t\tadd(at, message)\n\t}\n\n\tfor (const name of Object.keys(raw)) {\n\t\tif (!RULE_PROPERTIES.includes(name)) {\n\t\t\tfail(`${path}.${name}`, `is not a colour rule property; a rule takes ${RULE_PROPERTIES.join(\", \")}`)\n\t\t}\n\t}\n\n\tconst id = typeof raw.id === \"string\" && raw.id.trim() !== \"\" ? raw.id : null\n\n\tif (id === null) {\n\t\tfail(`${path}.id`, \"must be a non-empty string\")\n\t}\n\n\tconst when: RowCondition[] = []\n\n\tif (!Array.isArray(raw.when) || raw.when.length === 0) {\n\t\tfail(`${path}.when`, \"must be an array of one condition or more, every one of which must hold\")\n\t} else {\n\t\t;(raw.when as unknown[]).forEach((item, index) => {\n\t\t\tconst condition = readCondition(item, `${path}.when[${index}]`, fields, fail)\n\n\t\t\tif (condition) {\n\t\t\t\twhen.push(condition)\n\t\t\t}\n\t\t})\n\t}\n\n\tlet field: string | null = null\n\n\tif (raw.field !== undefined && raw.field !== null) {\n\t\tif (typeof raw.field === \"string\" && fields.has(raw.field)) {\n\t\t\tfield = raw.field\n\t\t} else {\n\t\t\tfail(`${path}.field`, `${JSON.stringify(raw.field)} is not a field of this schema`)\n\t\t}\n\t}\n\n\tconst color = (name: \"fill\" | \"color\"): MarkColor | null => {\n\t\tconst value = raw[name]\n\n\t\tif (value === undefined || value === null) {\n\t\t\treturn null\n\t\t}\n\n\t\tif ((MARK_COLORS as readonly unknown[]).includes(value)) {\n\t\t\treturn value as MarkColor\n\t\t}\n\n\t\tfail(`${path}.${name}`, `must be one of ${MARK_COLORS.join(\", \")}`)\n\n\t\treturn null\n\t}\n\n\tconst fill = color(\"fill\")\n\tconst text = color(\"color\")\n\n\tif (raw.bold !== undefined && typeof raw.bold !== \"boolean\") {\n\t\tfail(`${path}.bold`, \"must be true or false\")\n\t}\n\n\tconst bold = raw.bold === true\n\n\tif (fill === null && text === null && !bold && !failed) {\n\t\tfail(path, \"colours nothing: give a fill, a colour or bold\")\n\t}\n\n\tif (failed || id === null) {\n\t\treturn null\n\t}\n\n\treturn Object.freeze({ id, when: Object.freeze(when), field, fill, color: text, bold })\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n","import { TabulaError } from \"../errors.js\"\n\n/**\n * The formula language: what a spreadsheet user already writes, minus cell addresses. A formula\n * reads the fields of its own row by key, in brackets, and never runs code: it is parsed into a tree\n * and that tree is evaluated, so no text a user writes is ever executed.\n *\n * ROUND(([newPrice] - [currentPrice]) / [currentPrice] * 100, 1)\n * IF([quantity] > 0, [price] * [quantity], \"\")\n *\n * Numbers use a point, function names are English, arguments are separated by commas or by\n * semicolons, as a Turkish Excel separates them. A leading `=` is allowed and means nothing.\n */\n\nexport type BinaryOperator = \"+\" | \"-\" | \"*\" | \"/\" | \"^\" | \"&\" | \"=\" | \"<>\" | \"<\" | \">\" | \"<=\" | \">=\"\n\nexport type FormulaNode =\n\t| { readonly kind: \"number\"; readonly value: string }\n\t| { readonly kind: \"text\"; readonly value: string }\n\t| { readonly kind: \"bool\"; readonly value: boolean }\n\t| { readonly kind: \"field\"; readonly key: string }\n\t| { readonly kind: \"call\"; readonly name: string; readonly args: readonly FormulaNode[] }\n\t| { readonly kind: \"negate\"; readonly operand: FormulaNode }\n\t| { readonly kind: \"percent\"; readonly operand: FormulaNode }\n\t| { readonly kind: \"binary\"; readonly op: BinaryOperator; readonly left: FormulaNode; readonly right: FormulaNode }\n\ntype Token =\n\t| { readonly kind: \"number\" | \"text\" | \"field\" | \"name\"; readonly text: string; readonly at: number }\n\t| { readonly kind: \"op\"; readonly text: string; readonly at: number }\n\t| { readonly kind: \"end\"; readonly text: \"\"; readonly at: number }\n\n/** Lowest first. Exponents are left to right, and a minus sign binds tighter than them, as in Excel. */\nconst LEVELS: readonly (readonly string[])[] = [[\"=\", \"<>\", \"<\", \">\", \"<=\", \">=\"], [\"&\"], [\"+\", \"-\"], [\"*\", \"/\"], [\"^\"]]\n\n/**\n * Parses a formula.\n *\n * @throws TabulaError `invalid_formula`, saying where the text stopped making sense\n */\nexport function parseFormula(source: string): FormulaNode {\n\tconst tokens = tokenize(source)\n\tlet at = 0\n\tconst peek = (): Token => tokens[at] as Token\n\tconst next = (): Token => tokens[at++] as Token\n\tconst fail = (token: Token, message: string): never => {\n\t\tthrow new TabulaError(\"invalid_formula\", `${message} at character ${token.at + 1} of \"${source}\".`)\n\t}\n\n\tconst binary = (level: number): FormulaNode => {\n\t\tif (level >= LEVELS.length) {\n\t\t\treturn unary()\n\t\t}\n\n\t\tlet left = binary(level + 1)\n\n\t\twhile (peek().kind === \"op\" && (LEVELS[level] as readonly string[]).includes(peek().text)) {\n\t\t\tconst op = next().text as BinaryOperator\n\n\t\t\tleft = Object.freeze({ kind: \"binary\", op, left, right: binary(level + 1) })\n\t\t}\n\n\t\treturn left\n\t}\n\n\tconst unary = (): FormulaNode => {\n\t\tconst token = peek()\n\n\t\tif (token.kind === \"op\" && (token.text === \"-\" || token.text === \"+\")) {\n\t\t\tnext()\n\n\t\t\tconst operand = unary()\n\n\t\t\treturn token.text === \"-\" ? Object.freeze({ kind: \"negate\", operand }) : operand\n\t\t}\n\n\t\treturn postfix()\n\t}\n\n\tconst postfix = (): FormulaNode => {\n\t\tlet node = primary()\n\n\t\twhile (peek().kind === \"op\" && peek().text === \"%\") {\n\t\t\tnext()\n\t\t\tnode = Object.freeze({ kind: \"percent\", operand: node })\n\t\t}\n\n\t\treturn node\n\t}\n\n\tconst primary = (): FormulaNode => {\n\t\tconst token = next()\n\n\t\tswitch (token.kind) {\n\t\t\tcase \"number\":\n\t\t\t\treturn Object.freeze({ kind: \"number\", value: token.text })\n\t\t\tcase \"text\":\n\t\t\t\treturn Object.freeze({ kind: \"text\", value: token.text })\n\t\t\tcase \"field\":\n\t\t\t\treturn Object.freeze({ kind: \"field\", key: token.text })\n\t\t\tcase \"name\": {\n\t\t\t\tconst name = token.text.toUpperCase()\n\n\t\t\t\tif (peek().kind === \"op\" && peek().text === \"(\") {\n\t\t\t\t\tnext()\n\n\t\t\t\t\treturn Object.freeze({ kind: \"call\", name, args: Object.freeze(callArgs()) })\n\t\t\t\t}\n\n\t\t\t\tif (name === \"TRUE\" || name === \"FALSE\") {\n\t\t\t\t\treturn Object.freeze({ kind: \"bool\", value: name === \"TRUE\" })\n\t\t\t\t}\n\n\t\t\t\treturn fail(\n\t\t\t\t\ttoken,\n\t\t\t\t\t`\"${token.text}\" is neither a function, which takes parentheses, nor TRUE or FALSE; a field is written in brackets, [${token.text}]`\n\t\t\t\t)\n\t\t\t}\n\t\t\tcase \"op\":\n\t\t\t\tif (token.text === \"(\") {\n\t\t\t\t\tconst inner = binary(0)\n\n\t\t\t\t\tif (next().text !== \")\") {\n\t\t\t\t\t\tfail(tokens[at - 1] as Token, 'A \")\" is missing')\n\t\t\t\t\t}\n\n\t\t\t\t\treturn inner\n\t\t\t\t}\n\n\t\t\t\treturn fail(token, `\"${token.text}\" cannot start a value`)\n\t\t\tcase \"end\":\n\t\t\t\treturn fail(token, \"The formula ends where a value is expected\")\n\t\t}\n\t}\n\n\tconst callArgs = (): FormulaNode[] => {\n\t\tconst args: FormulaNode[] = []\n\n\t\tif (peek().kind === \"op\" && peek().text === \")\") {\n\t\t\tnext()\n\n\t\t\treturn args\n\t\t}\n\n\t\tfor (;;) {\n\t\t\targs.push(binary(0))\n\n\t\t\tconst token = next()\n\n\t\t\tif (token.kind === \"op\" && token.text === \")\") {\n\t\t\t\treturn args\n\t\t\t}\n\n\t\t\tif (!(token.kind === \"op\" && (token.text === \",\" || token.text === \";\"))) {\n\t\t\t\tfail(token, 'A \",\" or a \")\" is expected')\n\t\t\t}\n\t\t}\n\t}\n\n\tconst tree = binary(0)\n\n\tif (peek().kind !== \"end\") {\n\t\tfail(peek(), `\"${peek().text}\" is not expected here`)\n\t}\n\n\treturn tree\n}\n\n/** The field keys a formula reads, each once, in the order they first appear. */\nexport function formulaFields(node: FormulaNode): string[] {\n\tconst keys = new Set<string>()\n\tconst walk = (current: FormulaNode): void => {\n\t\tswitch (current.kind) {\n\t\t\tcase \"field\":\n\t\t\t\tkeys.add(current.key)\n\t\t\t\tbreak\n\t\t\tcase \"call\":\n\t\t\t\tcurrent.args.forEach(walk)\n\t\t\t\tbreak\n\t\t\tcase \"negate\":\n\t\t\tcase \"percent\":\n\t\t\t\twalk(current.operand)\n\t\t\t\tbreak\n\t\t\tcase \"binary\":\n\t\t\t\twalk(current.left)\n\t\t\t\twalk(current.right)\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\twalk(node)\n\n\treturn [...keys]\n}\n\nconst TWO_CHARACTER = [\"<>\", \"<=\", \">=\"]\nconst ONE_CHARACTER = \"+-*/^&=<>(),;%\"\n\nfunction tokenize(source: string): Token[] {\n\tconst tokens: Token[] = []\n\tlet at = source.trimStart().startsWith(\"=\") ? source.indexOf(\"=\") + 1 : 0\n\n\tconst fail = (where: number, message: string): never => {\n\t\tthrow new TabulaError(\"invalid_formula\", `${message} at character ${where + 1} of \"${source}\".`)\n\t}\n\n\twhile (at < source.length) {\n\t\tconst char = source.charAt(at)\n\n\t\tif (/\\s/.test(char)) {\n\t\t\tat++\n\t\t\tcontinue\n\t\t}\n\n\t\tconst start = at\n\n\t\tif (/\\d/.test(char) || (char === \".\" && /\\d/.test(source.charAt(at + 1)))) {\n\t\t\tconst match = /^\\d*(?:\\.\\d+)?/.exec(source.slice(at)) as RegExpExecArray\n\n\t\t\tat += match[0].length\n\t\t\ttokens.push({ kind: \"number\", text: match[0].startsWith(\".\") ? `0${match[0]}` : match[0], at: start })\n\t\t} else if (char === '\"') {\n\t\t\tlet text = \"\"\n\n\t\t\tat++\n\n\t\t\tfor (;;) {\n\t\t\t\tif (at >= source.length) {\n\t\t\t\t\tfail(start, \"A text is not closed with a quote\")\n\t\t\t\t}\n\n\t\t\t\tconst next = source.charAt(at)\n\n\t\t\t\tif (next === '\"') {\n\t\t\t\t\tif (source.charAt(at + 1) === '\"') {\n\t\t\t\t\t\ttext += '\"'\n\t\t\t\t\t\tat += 2\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tat++\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\ttext += next\n\t\t\t\tat++\n\t\t\t}\n\n\t\t\ttokens.push({ kind: \"text\", text, at: start })\n\t\t} else if (char === \"[\") {\n\t\t\tconst close = source.indexOf(\"]\", at)\n\n\t\t\tif (close < 0) {\n\t\t\t\tfail(start, 'A field is not closed with \"]\"')\n\t\t\t}\n\n\t\t\tconst key = source.slice(at + 1, close).trim()\n\n\t\t\tif (key === \"\") {\n\t\t\t\tfail(start, \"A field has no key between its brackets\")\n\t\t\t}\n\n\t\t\ttokens.push({ kind: \"field\", text: key, at: start })\n\t\t\tat = close + 1\n\t\t} else if (/[A-Za-z_]/.test(char)) {\n\t\t\tconst match = /^[A-Za-z_][A-Za-z0-9_.]*/.exec(source.slice(at)) as RegExpExecArray\n\n\t\t\tat += match[0].length\n\t\t\ttokens.push({ kind: \"name\", text: match[0], at: start })\n\t\t} else if (TWO_CHARACTER.includes(source.slice(at, at + 2))) {\n\t\t\ttokens.push({ kind: \"op\", text: source.slice(at, at + 2), at: start })\n\t\t\tat += 2\n\t\t} else if (ONE_CHARACTER.includes(char)) {\n\t\t\ttokens.push({ kind: \"op\", text: char, at: start })\n\t\t\tat++\n\t\t} else {\n\t\t\tfail(start, `\"${char}\" has no meaning in a formula`)\n\t\t}\n\t}\n\n\ttokens.push({ kind: \"end\", text: \"\", at: source.length })\n\n\treturn tokens\n}\n","import { checkToJson, readChecks, type CheckInput, type RowCheck } from \"./checks.js\"\nimport { readStyleRules, styleRuleToJson, type StyleRule, type StyleRuleInput } from \"./styles.js\"\nimport { compareDecimal, normalizeDecimal } from \"./decimal.js\"\nimport { SchemaError, TabulaError, type SchemaProblem } from \"./errors.js\"\nimport { formulaFields, parseFormula } from \"./formula/parse.js\"\nimport type { CellValue } from \"./value.js\"\nimport { compilePattern } from \"./values/date.js\"\nimport { decimalText } from \"./values/number.js\"\nimport { isFieldValue } from \"./values/read.js\"\n\n/**\n * The module schema: the developer's definition of a sheet, as the backend sends it.\n *\n * It is the same vocabulary as `Field` in nouxwell/tabula, written as JSON: one key per column that\n * never changes, a type, and the rules nobody further down may loosen. A user's template and view\n * are layered on top of it later; nothing here can be overridden by them.\n *\n * A schema this package does not fully understand is refused, not half applied. An unknown property\n * or rule is an error rather than something skipped, because a skipped rule is a rule that quietly\n * stops being checked.\n */\n\nexport const FIELD_TYPES = Object.freeze([\n\t\"string\",\n\t\"integer\",\n\t\"decimal\",\n\t\"money\",\n\t\"quantity\",\n\t\"percent\",\n\t\"bool\",\n\t\"date\",\n\t\"datetime\",\n\t\"options\",\n\t\"lookup\"\n] as const)\n\nexport type FieldType = (typeof FIELD_TYPES)[number]\n\n/** How far a user's template may change the sheet: not at all, within the schema's limits, or freely. */\nexport const CUSTOMIZATIONS = Object.freeze([\"fixed\", \"controlled\", \"free\"] as const)\n\nexport type Customization = (typeof CUSTOMIZATIONS)[number]\n\n/** A limit on a field's value. `min` and `max` are decimal text, so they mean exactly what they say. */\nexport type FieldRule =\n\t| { readonly rule: \"min\" | \"max\"; readonly value: string }\n\t| { readonly rule: \"minLength\" | \"maxLength\"; readonly value: number }\n\t| { readonly rule: \"unique\" }\n\nexport interface FieldOption {\n\t/** What is stored and sent. */\n\treadonly value: string | number\n\t/** What the user reads. */\n\treadonly label: string\n}\n\ninterface FieldBase {\n\t/** The field's identity: what the backend receives and what every rule, issue and formula refers to. */\n\treadonly key: string\n\t/** The column's header. Changing it changes nothing else. */\n\treadonly label: string\n\treadonly required: boolean\n\treadonly editable: boolean\n\t/** Whether the field is part of what is sent for processing. False for a column shown for reference. */\n\treadonly submit: boolean\n\treadonly rules: readonly FieldRule[]\n\t/** A sample value, as text, for the column's help. */\n\treadonly example: string | null\n\t/**\n\t * Worked out from the row's other fields rather than typed, such as\n\t * `ROUND([newPrice] - [currentPrice], 2)`. Such a field is never editable.\n\t */\n\treadonly formula: string | null\n\t/**\n\t * What a new row holds here when nothing else is given, in the form a cell holds it: a number as\n\t * decimal text, a date as ISO text, an option by its value. Null for none. A row the grid or an\n\t * import adds takes it (`withDefaults`); a row already there is never changed by it.\n\t */\n\treadonly default: CellValue | null\n}\n\nexport interface TextField extends FieldBase {\n\treadonly type: \"string\"\n}\n\n/**\n * How a number's own value colours it: `sign` shows a rise in the positive colour, with its plus, and\n * a fall in the negative one, as a change column wants.\n */\nexport type FieldTone = \"sign\"\n\nexport interface IntegerField extends FieldBase {\n\treadonly type: \"integer\"\n\treadonly tone: FieldTone | null\n}\n\nexport interface DecimalField extends FieldBase {\n\treadonly type: \"decimal\" | \"quantity\" | \"percent\"\n\t/** Digits after the point; null leaves it to the sheet's settings for the type. */\n\treadonly decimals: number | null\n\treadonly tone: FieldTone | null\n}\n\nexport interface MoneyField extends FieldBase {\n\treadonly type: \"money\"\n\treadonly decimals: number | null\n\t/** A fixed currency code, or null when the currency comes from elsewhere. */\n\treadonly currency: string | null\n\treadonly tone: FieldTone | null\n}\n\nexport interface BoolField extends FieldBase {\n\treadonly type: \"bool\"\n}\n\nexport interface DateField extends FieldBase {\n\treadonly type: \"date\" | \"datetime\"\n\t/** The field's own pattern in PHP's notation, such as `d.m.Y`; null leaves it to the sheet's settings. */\n\treadonly pattern: string | null\n}\n\nexport interface OptionsField extends FieldBase {\n\treadonly type: \"options\"\n\treadonly options: readonly FieldOption[]\n\t/** Whether a cell holds a list of options rather than one. */\n\treadonly multiple: boolean\n}\n\nexport interface LookupField extends FieldBase {\n\treadonly type: \"lookup\"\n\t/**\n\t * Which lookup the application's adapter is asked, such as `\"product\"`. The cell shows a label and\n\t * sends an id; the adapter is what turns one into the other.\n\t */\n\treadonly lookup: string\n}\n\nexport type FieldSchema =\n\tTextField | IntegerField | DecimalField | MoneyField | BoolField | DateField | OptionsField | LookupField\n\n/** A rule as it is written in the JSON. */\nexport type RuleInput =\n\t| { rule: \"min\" | \"max\"; value: string | number }\n\t| { rule: \"minLength\" | \"maxLength\"; value: number }\n\t| { rule: \"unique\" }\n\nexport interface OptionInput {\n\tvalue: string | number\n\tlabel?: string\n}\n\n/** A field as it is written in the JSON. Which properties a field takes depends on its type. */\nexport interface FieldInput {\n\tkey: string\n\ttype: FieldType\n\tlabel?: string\n\trequired?: boolean\n\teditable?: boolean\n\tsubmit?: boolean\n\trules?: RuleInput[]\n\texample?: string\n\t/** Worked out from the row's other fields; see `FieldSchema.formula`. */\n\tformula?: string\n\t/** A new row's value; see `FieldSchema.default`. Not for a lookup, a formula or a unique field. */\n\tdefault?: string | number | boolean | readonly (string | number)[]\n\t/** decimal, quantity, percent and money */\n\tdecimals?: number\n\t/** money */\n\tcurrency?: string\n\t/** integer, decimal, quantity, percent and money */\n\ttone?: FieldTone\n\t/** options */\n\toptions?: OptionInput[]\n\t/** options */\n\tmultiple?: boolean\n\t/** lookup */\n\tlookup?: string\n\t/** date and datetime */\n\tpattern?: string\n}\n\n/** The module schema as it is written in the JSON. */\nexport interface ModuleSchemaInput {\n\tmodule: string\n\tschemaVersion: number\n\ttitle?: string\n\tcustomization?: Customization\n\tfields: FieldInput[]\n\t/** Rules about a row rather than one cell; see `RowCheck`. */\n\tchecks?: CheckInput[]\n\t/** Cells coloured by what the row holds; see `StyleRule`. */\n\tstyles?: StyleRuleInput[]\n}\n\nconst MODULE_PROPERTIES = [\"module\", \"schemaVersion\", \"title\", \"customization\", \"fields\", \"checks\", \"styles\"]\nconst COMMON_PROPERTIES = [\n\t\"key\",\n\t\"type\",\n\t\"label\",\n\t\"required\",\n\t\"editable\",\n\t\"submit\",\n\t\"rules\",\n\t\"example\",\n\t\"formula\",\n\t\"default\"\n]\n\n/** Kinds of field a formula can fill: a value worked out, never a record or a choice from a list. */\nconst FORMULA_TYPES: readonly FieldType[] = [\n\t\"string\",\n\t\"integer\",\n\t\"decimal\",\n\t\"quantity\",\n\t\"percent\",\n\t\"money\",\n\t\"bool\",\n\t\"date\"\n]\n\nconst TYPE_PROPERTIES: Readonly<Record<FieldType, readonly string[]>> = {\n\tstring: [],\n\tinteger: [\"tone\"],\n\tdecimal: [\"decimals\", \"tone\"],\n\tmoney: [\"decimals\", \"currency\", \"tone\"],\n\tquantity: [\"decimals\", \"tone\"],\n\tpercent: [\"decimals\", \"tone\"],\n\tbool: [],\n\tdate: [\"pattern\"],\n\tdatetime: [\"pattern\"],\n\toptions: [\"options\", \"multiple\"],\n\tlookup: [\"lookup\"]\n}\n\nconst TYPED_PROPERTIES: ReadonlySet<string> = new Set(Object.values(TYPE_PROPERTIES).flat())\nconst NUMERIC_TYPES: ReadonlySet<FieldType> = new Set([\"integer\", \"decimal\", \"money\", \"quantity\", \"percent\"])\nconst RULE_KINDS = [\"min\", \"max\", \"minLength\", \"maxLength\", \"unique\"] as const\n\ntype RuleKind = (typeof RULE_KINDS)[number]\ntype Json = Record<string, unknown>\n\ninterface ModuleData {\n\treadonly module: string\n\treadonly schemaVersion: number\n\treadonly title: string | null\n\treadonly customization: Customization\n\treadonly fields: readonly FieldSchema[]\n\treadonly checks: readonly RowCheck[]\n\treadonly styles: readonly StyleRule[]\n}\n\nexport class ModuleSchema {\n\t/** The module's name, such as `product.price_update`. */\n\treadonly module: string\n\t/** The schema's own version. A draft records it, so a draft made against another version is noticed. */\n\treadonly schemaVersion: number\n\treadonly title: string | null\n\treadonly customization: Customization\n\t/** In the order the backend declared them. */\n\treadonly fields: readonly FieldSchema[]\n\t/** Rules about a row rather than one cell: a field required when another holds a value, two compared. */\n\treadonly checks: readonly RowCheck[]\n\t/** Cells coloured by what the row holds, in order: a later rule is drawn over an earlier one. */\n\treadonly styles: readonly StyleRule[]\n\treadonly #byKey: ReadonlyMap<string, FieldSchema>\n\n\tprivate constructor(data: ModuleData) {\n\t\tthis.module = data.module\n\t\tthis.schemaVersion = data.schemaVersion\n\t\tthis.title = data.title\n\t\tthis.customization = data.customization\n\t\tthis.fields = Object.freeze([...data.fields])\n\t\tthis.checks = Object.freeze([...data.checks])\n\t\tthis.styles = Object.freeze([...data.styles])\n\t\tthis.#byKey = new Map(data.fields.map(field => [field.key, field]))\n\t\tObject.freeze(this)\n\t}\n\n\t/**\n\t * Reads a module schema, typically the JSON the backend sent, and checks all of it.\n\t *\n\t * @throws SchemaError listing every problem found, each with where it is\n\t */\n\tstatic from(input: unknown): ModuleSchema {\n\t\tconst problems = new Problems()\n\t\tconst data = readModule(input, problems)\n\n\t\tif (data === null || problems.items.length > 0) {\n\t\t\tconst name =\n\t\t\t\tisObject(input) && typeof input.module === \"string\" && input.module.trim() !== \"\"\n\t\t\t\t\t? `Module schema \"${input.module}\"`\n\t\t\t\t\t: \"The module schema\"\n\n\t\t\tthrow new SchemaError(name, problems.items)\n\t\t}\n\n\t\treturn new ModuleSchema(data)\n\t}\n\n\thas(key: string): boolean {\n\t\treturn this.#byKey.has(key)\n\t}\n\n\t/** The field with this key. An unknown key is an error rather than undefined: a typo shows up at once. */\n\tfield(key: string): FieldSchema {\n\t\tconst field = this.#byKey.get(key)\n\n\t\tif (!field) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"unknown_field\",\n\t\t\t\t`Module \"${this.module}\" has no field \"${key}\". Its fields are: ${this.keys().join(\", \")}.`\n\t\t\t)\n\t\t}\n\n\t\treturn field\n\t}\n\n\tkeys(): string[] {\n\t\treturn this.fields.map(field => field.key)\n\t}\n\n\t/** The schema written out again as JSON, every default spelled out. `from()` reads it back unchanged. */\n\ttoJSON(): ModuleSchemaInput {\n\t\tconst json: ModuleSchemaInput = {\n\t\t\tmodule: this.module,\n\t\t\tschemaVersion: this.schemaVersion,\n\t\t\tcustomization: this.customization,\n\t\t\tfields: this.fields.map(fieldToJson)\n\t\t}\n\n\t\tif (this.title !== null) {\n\t\t\tjson.title = this.title\n\t\t}\n\n\t\tif (this.checks.length > 0) {\n\t\t\tjson.checks = this.checks.map(checkToJson)\n\t\t}\n\n\t\tif (this.styles.length > 0) {\n\t\t\tjson.styles = this.styles.map(styleRuleToJson)\n\t\t}\n\n\t\treturn json\n\t}\n}\n\nfunction fieldToJson(field: FieldSchema): FieldInput {\n\tconst json: FieldInput = {\n\t\tkey: field.key,\n\t\ttype: field.type,\n\t\tlabel: field.label,\n\t\trequired: field.required,\n\t\teditable: field.editable,\n\t\tsubmit: field.submit\n\t}\n\n\tif (field.rules.length > 0) {\n\t\tjson.rules = field.rules.map(rule => ({ ...rule }))\n\t}\n\n\tif (field.example !== null) {\n\t\tjson.example = field.example\n\t}\n\n\tif (field.formula !== null) {\n\t\tjson.formula = field.formula\n\t}\n\n\tif (field.default !== null) {\n\t\tjson.default = field.default as NonNullable<FieldInput[\"default\"]>\n\t}\n\n\tswitch (field.type) {\n\t\tcase \"integer\":\n\t\t\tif (field.tone !== null) {\n\t\t\t\tjson.tone = field.tone\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\tcase \"percent\":\n\t\t\tif (field.decimals !== null) {\n\t\t\t\tjson.decimals = field.decimals\n\t\t\t}\n\t\t\tif (field.tone !== null) {\n\t\t\t\tjson.tone = field.tone\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"money\":\n\t\t\tif (field.decimals !== null) {\n\t\t\t\tjson.decimals = field.decimals\n\t\t\t}\n\t\t\tif (field.currency !== null) {\n\t\t\t\tjson.currency = field.currency\n\t\t\t}\n\t\t\tif (field.tone !== null) {\n\t\t\t\tjson.tone = field.tone\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"options\":\n\t\t\tjson.options = field.options.map(option => ({ ...option }))\n\t\t\tjson.multiple = field.multiple\n\t\t\tbreak\n\t\tcase \"date\":\n\t\tcase \"datetime\":\n\t\t\tif (field.pattern !== null) {\n\t\t\t\tjson.pattern = field.pattern\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"lookup\":\n\t\t\tjson.lookup = field.lookup\n\t\t\tbreak\n\t}\n\n\treturn json\n}\n\n// ---------------------------------------------------------------- reading\n\nclass Problems {\n\treadonly items: SchemaProblem[] = []\n\n\tadd(path: string, message: string): void {\n\t\tthis.items.push(Object.freeze({ path, message }))\n\t}\n}\n\nfunction readModule(input: unknown, problems: Problems): ModuleData | null {\n\tif (!isObject(input)) {\n\t\tproblems.add(\"(root)\", `must be an object; got ${describe(input)}`)\n\n\t\treturn null\n\t}\n\n\tfor (const name of Object.keys(input)) {\n\t\tif (!MODULE_PROPERTIES.includes(name)) {\n\t\t\tproblems.add(name, `is not a module schema property; expected one of ${MODULE_PROPERTIES.join(\", \")}`)\n\t\t}\n\t}\n\n\tconst module = readText(input, \"module\", \"\", problems, true)\n\tconst schemaVersion = readSchemaVersion(input, problems)\n\tconst title = readText(input, \"title\", \"\", problems, false)\n\tconst customization = readCustomization(input, problems)\n\tconst fields = readFields(input.fields, problems)\n\tconst checks =\n\t\tfields === null ? [] : readChecks(input.checks, fields, (path, message) => problems.add(path, message))\n\n\tconst styles =\n\t\tfields === null ? [] : readStyleRules(input.styles, fields, (path, message) => problems.add(path, message))\n\n\tif (module === null || schemaVersion === null || fields === null) {\n\t\treturn null\n\t}\n\n\treturn { module, schemaVersion, title, customization, fields, checks, styles }\n}\n\nfunction readSchemaVersion(input: Json, problems: Problems): number | null {\n\tconst value = input.schemaVersion\n\n\tif (value === undefined || value === null) {\n\t\tproblems.add(\"schemaVersion\", \"is required\")\n\n\t\treturn null\n\t}\n\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 1) {\n\t\tproblems.add(\"schemaVersion\", `must be a whole number, 1 or more; got ${describe(value)}`)\n\n\t\treturn null\n\t}\n\n\treturn value\n}\n\nfunction readCustomization(input: Json, problems: Problems): Customization {\n\tconst value = input.customization\n\n\tif (value === undefined || value === null) {\n\t\treturn \"fixed\"\n\t}\n\n\tif (typeof value !== \"string\" || !(CUSTOMIZATIONS as readonly string[]).includes(value)) {\n\t\tproblems.add(\n\t\t\t\"customization\",\n\t\t\t`${describe(value)} is not a customization; expected one of ${CUSTOMIZATIONS.join(\", \")}`\n\t\t)\n\n\t\treturn \"fixed\"\n\t}\n\n\treturn value as Customization\n}\n\nfunction readFields(value: unknown, problems: Problems): FieldSchema[] | null {\n\tif (value === undefined || value === null) {\n\t\tproblems.add(\"fields\", \"is required\")\n\n\t\treturn null\n\t}\n\n\tif (!Array.isArray(value) || value.length === 0) {\n\t\tproblems.add(\"fields\", `must be a non-empty array of fields; got ${describe(value)}`)\n\n\t\treturn null\n\t}\n\n\tconst items = value as unknown[]\n\tconst firstIndex = new Map<string, number>()\n\n\titems.forEach((raw, index) => {\n\t\tif (!isObject(raw) || typeof raw.key !== \"string\") {\n\t\t\treturn\n\t\t}\n\n\t\tconst first = firstIndex.get(raw.key)\n\n\t\tif (first === undefined) {\n\t\t\tfirstIndex.set(raw.key, index)\n\t\t} else {\n\t\t\tproblems.add(\n\t\t\t\t`fields[${index}].key`,\n\t\t\t\t`\"${raw.key}\" is already the key of fields[${first}]; a key names one field only`\n\t\t\t)\n\t\t}\n\t})\n\n\tconst fields: FieldSchema[] = []\n\n\titems.forEach((raw, index) => {\n\t\tconst field = readField(raw, `fields[${index}]`, problems)\n\n\t\tif (field) {\n\t\t\tfields.push(field)\n\t\t}\n\t})\n\n\tcheckFormulas(fields, firstIndex, problems)\n\n\treturn fields\n}\n\n/**\n * Every formula parses, reads only fields the schema has, never itself, and no formula reads, through\n * others, the field it fills: a circle has no value to start from.\n */\nfunction checkFormulas(fields: readonly FieldSchema[], indexOf: ReadonlyMap<string, number>, problems: Problems): void {\n\tconst keys = new Set(fields.map(field => field.key))\n\tconst reads = new Map<string, string[]>()\n\n\tfor (const field of fields) {\n\t\tif (field.formula === null) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst path = `fields[${indexOf.get(field.key) ?? 0}].formula`\n\t\tlet fieldsRead: string[]\n\n\t\ttry {\n\t\t\tfieldsRead = formulaFields(parseFormula(field.formula))\n\t\t} catch (error) {\n\t\t\tproblems.add(path, error instanceof Error ? error.message : String(error))\n\t\t\tcontinue\n\t\t}\n\n\t\tfor (const key of fieldsRead) {\n\t\t\tif (key === field.key) {\n\t\t\t\tproblems.add(path, `reads [${key}], the field it fills`)\n\t\t\t} else if (!keys.has(key)) {\n\t\t\t\tproblems.add(path, `reads [${key}], which is not a field of this schema`)\n\t\t\t}\n\t\t}\n\n\t\treads.set(\n\t\t\tfield.key,\n\t\t\tfieldsRead.filter(key => key !== field.key)\n\t\t)\n\t}\n\n\t// A depth-first walk over the formulas: meeting a field still on the path is a circle.\n\tconst done = new Set<string>()\n\tconst reported = new Set<string>()\n\tconst walk = (key: string, path: string[]): void => {\n\t\tif (done.has(key)) {\n\t\t\treturn\n\t\t}\n\n\t\tconst at = path.indexOf(key)\n\n\t\tif (at >= 0) {\n\t\t\tconst circle = [...path.slice(at), key]\n\n\t\t\tif (!circle.some(member => reported.has(member))) {\n\t\t\t\tcircle.forEach(member => reported.add(member))\n\t\t\t\tproblems.add(\n\t\t\t\t\t`fields[${indexOf.get(key) ?? 0}].formula`,\n\t\t\t\t\t`is part of a circle of formulas: ${circle.map(member => `[${member}]`).join(\" → \")}`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tfor (const next of reads.get(key) ?? []) {\n\t\t\tif (reads.has(next)) {\n\t\t\t\twalk(next, [...path, key])\n\t\t\t}\n\t\t}\n\n\t\tdone.add(key)\n\t}\n\n\tfor (const key of reads.keys()) {\n\t\twalk(key, [])\n\t}\n}\n\nfunction readField(raw: unknown, path: string, problems: Problems): FieldSchema | null {\n\tif (!isObject(raw)) {\n\t\tproblems.add(path, `must be an object; got ${describe(raw)}`)\n\n\t\treturn null\n\t}\n\n\tconst before = problems.items.length\n\tconst type = readType(raw, path, problems)\n\n\tcheckFieldProperties(raw, type, path, problems)\n\n\tconst key = readKey(raw, path, problems)\n\tconst label = readText(raw, \"label\", path, problems, false)\n\tconst required = readBoolean(raw, \"required\", false, path, problems)\n\tconst editable = readBoolean(raw, \"editable\", true, path, problems)\n\tconst submit = readBoolean(raw, \"submit\", true, path, problems)\n\tconst example = readText(raw, \"example\", path, problems, false)\n\tconst formula = readText(raw, \"formula\", path, problems, false)\n\tconst rules = readRules(raw.rules, at(path, \"rules\"), type, problems)\n\n\tif (type === null || key === null) {\n\t\treturn null\n\t}\n\n\tif (formula !== null && !FORMULA_TYPES.includes(type)) {\n\t\tproblems.add(\n\t\t\tat(path, \"formula\"),\n\t\t\t`cannot fill ${aFieldOf(type)}; a formula works out a text, a number, a date or yes and no`\n\t\t)\n\t}\n\n\t// A value worked out is not typed over: a formula field is never editable, whatever it says.\n\tconst base = {\n\t\tkey,\n\t\tlabel: label ?? key,\n\t\trequired,\n\t\teditable: formula === null && editable,\n\t\tsubmit,\n\t\trules: Object.freeze(rules),\n\t\texample,\n\t\tformula,\n\t\tdefault: null\n\t}\n\tlet field: FieldSchema\n\n\tswitch (type) {\n\t\tcase \"string\":\n\t\tcase \"bool\":\n\t\t\tfield = { ...base, type }\n\t\t\tbreak\n\t\tcase \"integer\":\n\t\t\tfield = { ...base, type, tone: readTone(raw, path, problems) }\n\t\t\tbreak\n\t\tcase \"date\":\n\t\tcase \"datetime\":\n\t\t\tfield = { ...base, type, pattern: readPattern(raw, path, problems) }\n\t\t\tbreak\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\tcase \"percent\":\n\t\t\tfield = { ...base, type, decimals: readDecimals(raw, path, problems), tone: readTone(raw, path, problems) }\n\t\t\tbreak\n\t\tcase \"money\":\n\t\t\tfield = {\n\t\t\t\t...base,\n\t\t\t\ttype,\n\t\t\t\tdecimals: readDecimals(raw, path, problems),\n\t\t\t\tcurrency: readText(raw, \"currency\", path, problems, false),\n\t\t\t\ttone: readTone(raw, path, problems)\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"options\":\n\t\t\tfield = {\n\t\t\t\t...base,\n\t\t\t\ttype,\n\t\t\t\toptions: Object.freeze(readOptions(raw.options, at(path, \"options\"), problems)),\n\t\t\t\tmultiple: readBoolean(raw, \"multiple\", false, path, problems)\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"lookup\":\n\t\t\tfield = { ...base, type, lookup: readText(raw, \"lookup\", path, problems, true) ?? \"\" }\n\t\t\tbreak\n\t}\n\n\tif (problems.items.length > before) {\n\t\treturn null\n\t}\n\n\tconst fallback = readDefault(raw, field, path, problems)\n\n\treturn problems.items.length > before ? null : Object.freeze({ ...field, default: fallback })\n}\n\n/**\n * A field's default, checked as a value of the field: its type, its options, its limits. A lookup\n * takes none (a record is an id the backend gives), nor does a formula (its value is worked out),\n * nor a unique field (every new row would hold the same value).\n */\nfunction readDefault(raw: Json, field: FieldSchema, path: string, problems: Problems): CellValue | null {\n\tconst value = raw.default\n\tconst where = at(path, \"default\")\n\n\tif (value === undefined || value === null) {\n\t\treturn null\n\t}\n\n\tif (field.type === \"lookup\" || field.formula !== null || field.rules.some(rule => rule.rule === \"unique\")) {\n\t\tconst why =\n\t\t\tfield.type === \"lookup\"\n\t\t\t\t? \"a lookup's value is a record the backend gives\"\n\t\t\t\t: field.formula !== null\n\t\t\t\t\t? \"its value is worked out by its formula\"\n\t\t\t\t\t: \"every new row would hold the same value, and it is unique\"\n\n\t\tproblems.add(where, `cannot be given: ${why}`)\n\n\t\treturn null\n\t}\n\n\t// A number is kept as decimal text, as every cell of a numeric field holds one.\n\tconst given = NUMERIC_TYPES.has(field.type) ? (decimalText(value) ?? value) : value\n\n\tif (!isFieldValue(field, given as CellValue)) {\n\t\tproblems.add(where, `${describe(value)} is not a value of ${aFieldOf(field.type)}${hint(field)}`)\n\n\t\treturn null\n\t}\n\n\tconst broken = brokenRule(field, given as CellValue)\n\n\tif (broken !== null) {\n\t\tproblems.add(where, `${describe(value)} breaks the field's ${broken} rule`)\n\n\t\treturn null\n\t}\n\n\treturn Array.isArray(given) ? (Object.freeze([...(given as unknown[])]) as CellValue) : (given as CellValue)\n}\n\nfunction hint(field: FieldSchema): string {\n\tswitch (field.type) {\n\t\tcase \"options\":\n\t\t\treturn `; it takes ${field.multiple ? \"a list of \" : \"one of \"}${field.options.map(option => JSON.stringify(option.value)).join(\", \")}`\n\t\tcase \"date\":\n\t\t\treturn '; write it as \"2026-12-31\"'\n\t\tcase \"datetime\":\n\t\t\treturn '; write it as \"2026-12-31T09:30:00\"'\n\t\tcase \"bool\":\n\t\t\treturn \"; it takes true or false\"\n\t\tdefault:\n\t\t\treturn NUMERIC_TYPES.has(field.type) ? '; write it as a number or decimal text, such as \"12.5\"' : \"\"\n\t}\n}\n\n/** The first of the field's limits the value breaks, or null. */\nfunction brokenRule(field: FieldSchema, value: CellValue): string | null {\n\tfor (const rule of field.rules) {\n\t\tif ((rule.rule === \"min\" || rule.rule === \"max\") && typeof value === \"string\") {\n\t\t\tconst order = compareDecimal(normalizeDecimal(value) ?? value, rule.value)\n\n\t\t\tif (rule.rule === \"min\" ? order < 0 : order > 0) {\n\t\t\t\treturn `${rule.rule} ${rule.value}`\n\t\t\t}\n\t\t}\n\n\t\tif ((rule.rule === \"minLength\" || rule.rule === \"maxLength\") && typeof value === \"string\") {\n\t\t\tconst length = [...value].length\n\n\t\t\tif (rule.rule === \"minLength\" ? length < rule.value : length > rule.value) {\n\t\t\t\treturn `${rule.rule} ${rule.value}`\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null\n}\n\nfunction readType(raw: Json, path: string, problems: Problems): FieldType | null {\n\tconst value = raw.type\n\n\tif (value === undefined || value === null) {\n\t\tproblems.add(at(path, \"type\"), \"is required\")\n\n\t\treturn null\n\t}\n\n\tif (typeof value !== \"string\" || !(FIELD_TYPES as readonly string[]).includes(value)) {\n\t\tproblems.add(\n\t\t\tat(path, \"type\"),\n\t\t\t`${describe(value)} is not a field type; expected one of ${FIELD_TYPES.join(\", \")}`\n\t\t)\n\n\t\treturn null\n\t}\n\n\treturn value as FieldType\n}\n\nfunction checkFieldProperties(raw: Json, type: FieldType | null, path: string, problems: Problems): void {\n\tconst allowed = new Set([...COMMON_PROPERTIES, ...(type === null ? TYPED_PROPERTIES : TYPE_PROPERTIES[type])])\n\n\tfor (const name of Object.keys(raw)) {\n\t\tif (allowed.has(name)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif (type !== null && TYPED_PROPERTIES.has(name)) {\n\t\t\tproblems.add(at(path, name), `does not apply to ${aFieldOf(type)}`)\n\t\t} else if (type !== null) {\n\t\t\tproblems.add(at(path, name), `is not a field property; ${aFieldOf(type)} takes ${[...allowed].join(\", \")}`)\n\t\t} else {\n\t\t\tproblems.add(at(path, name), \"is not a field property\")\n\t\t}\n\t}\n}\n\nfunction readKey(raw: Json, path: string, problems: Problems): string | null {\n\tconst key = readText(raw, \"key\", path, problems, true)\n\n\tif (key !== null && key.trim() !== key) {\n\t\tproblems.add(at(path, \"key\"), `\"${key}\" starts or ends with a space; a key is an identifier, not a label`)\n\n\t\treturn null\n\t}\n\n\treturn key\n}\n\nfunction readPattern(raw: Json, path: string, problems: Problems): string | null {\n\tconst pattern = readText(raw, \"pattern\", path, problems, false)\n\n\tif (pattern !== null && compilePattern(pattern) === null) {\n\t\tproblems.add(\n\t\t\tat(path, \"pattern\"),\n\t\t\t`\"${pattern}\" uses a letter that is not one of d, j, m, n, Y, y, H, G, i, s; write other letters with a backslash before them`\n\t\t)\n\n\t\treturn null\n\t}\n\n\treturn pattern\n}\n\nfunction readDecimals(raw: Json, path: string, problems: Problems): number | null {\n\tconst value = raw.decimals\n\n\tif (value === undefined || value === null) {\n\t\treturn null\n\t}\n\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n\t\tproblems.add(at(path, \"decimals\"), `must be a whole number, 0 or more; got ${describe(value)}`)\n\n\t\treturn null\n\t}\n\n\treturn value\n}\n\nfunction readTone(raw: Json, path: string, problems: Problems): FieldTone | null {\n\tconst value = raw.tone\n\n\tif (value === undefined || value === null) {\n\t\treturn null\n\t}\n\n\tif (value !== \"sign\") {\n\t\tproblems.add(at(path, \"tone\"), `must be \"sign\"; got ${describe(value)}`)\n\n\t\treturn null\n\t}\n\n\treturn value\n}\n\nfunction readOptions(value: unknown, path: string, problems: Problems): FieldOption[] {\n\tif (value === undefined || value === null) {\n\t\tproblems.add(path, \"is required for an options field\")\n\n\t\treturn []\n\t}\n\n\tif (!Array.isArray(value)) {\n\t\tproblems.add(path, `must be an array of options; got ${describe(value)}`)\n\n\t\treturn []\n\t}\n\n\tconst options: FieldOption[] = []\n\t// By their text: an option 1 and an option \"1\" cannot be told apart once pasted into a cell.\n\tconst firstIndex = new Map<string, number>()\n\n\t;(value as unknown[]).forEach((raw, index) => {\n\t\tconst optionPath = `${path}[${index}]`\n\n\t\tif (!isObject(raw)) {\n\t\t\tproblems.add(optionPath, `must be an object such as { \"value\": \"in\", \"label\": \"In\" }; got ${describe(raw)}`)\n\n\t\t\treturn\n\t\t}\n\n\t\tfor (const name of Object.keys(raw)) {\n\t\t\tif (name !== \"value\" && name !== \"label\") {\n\t\t\t\tproblems.add(at(optionPath, name), \"is not an option property; an option takes value, label\")\n\t\t\t}\n\t\t}\n\n\t\tconst optionValue = raw.value\n\n\t\tif (\n\t\t\t!(typeof optionValue === \"string\" && optionValue !== \"\") &&\n\t\t\t!(typeof optionValue === \"number\" && Number.isFinite(optionValue))\n\t\t) {\n\t\t\tproblems.add(\n\t\t\t\tat(optionPath, \"value\"),\n\t\t\t\t`must be a non-empty string or a finite number; got ${describe(optionValue)}`\n\t\t\t)\n\n\t\t\treturn\n\t\t}\n\n\t\tconst text = String(optionValue)\n\t\tconst first = firstIndex.get(text)\n\n\t\tif (first !== undefined) {\n\t\t\tproblems.add(at(optionPath, \"value\"), `${describe(optionValue)} is already the value of ${path}[${first}]`)\n\n\t\t\treturn\n\t\t}\n\n\t\tfirstIndex.set(text, index)\n\n\t\tconst label = readText(raw, \"label\", optionPath, problems, false)\n\n\t\toptions.push(Object.freeze({ value: optionValue, label: label ?? text }))\n\t})\n\n\treturn options\n}\n\nfunction readRules(value: unknown, path: string, type: FieldType | null, problems: Problems): FieldRule[] {\n\tif (value === undefined || value === null) {\n\t\treturn []\n\t}\n\n\tif (!Array.isArray(value)) {\n\t\tproblems.add(path, `must be an array of rules; got ${describe(value)}`)\n\n\t\treturn []\n\t}\n\n\tconst rules: FieldRule[] = []\n\tconst firstIndex = new Map<RuleKind, number>()\n\n\t;(value as unknown[]).forEach((raw, index) => {\n\t\tconst rulePath = `${path}[${index}]`\n\t\tconst rule = readRule(raw, rulePath, type, problems)\n\n\t\tif (!rule) {\n\t\t\treturn\n\t\t}\n\n\t\tconst first = firstIndex.get(rule.rule)\n\n\t\tif (first !== undefined) {\n\t\t\tproblems.add(rulePath, `${rule.rule} is already given at ${path}[${first}]; give each rule once`)\n\n\t\t\treturn\n\t\t}\n\n\t\tfirstIndex.set(rule.rule, index)\n\t\trules.push(rule)\n\t})\n\n\tconst min = limitOf(rules, \"min\")\n\tconst max = limitOf(rules, \"max\")\n\n\tif (min !== undefined && max !== undefined && compareDecimal(min, max) > 0) {\n\t\tproblems.add(path, `min ${min} is above max ${max}; no value can satisfy both`)\n\t}\n\n\tconst minLength = lengthOf(rules, \"minLength\")\n\tconst maxLength = lengthOf(rules, \"maxLength\")\n\n\tif (minLength !== undefined && maxLength !== undefined && minLength > maxLength) {\n\t\tproblems.add(path, `minLength ${minLength} is above maxLength ${maxLength}; no text can satisfy both`)\n\t}\n\n\treturn rules\n}\n\nfunction limitOf(rules: readonly FieldRule[], kind: \"min\" | \"max\"): string | undefined {\n\tfor (const rule of rules) {\n\t\tif ((rule.rule === \"min\" || rule.rule === \"max\") && rule.rule === kind) {\n\t\t\treturn rule.value\n\t\t}\n\t}\n\n\treturn undefined\n}\n\nfunction lengthOf(rules: readonly FieldRule[], kind: \"minLength\" | \"maxLength\"): number | undefined {\n\tfor (const rule of rules) {\n\t\tif ((rule.rule === \"minLength\" || rule.rule === \"maxLength\") && rule.rule === kind) {\n\t\t\treturn rule.value\n\t\t}\n\t}\n\n\treturn undefined\n}\n\nfunction readRule(raw: unknown, path: string, type: FieldType | null, problems: Problems): FieldRule | null {\n\tif (!isObject(raw)) {\n\t\tproblems.add(path, `must be an object such as { \"rule\": \"min\", \"value\": \"0\" }; got ${describe(raw)}`)\n\n\t\treturn null\n\t}\n\n\tconst kind = raw.rule\n\n\tif (typeof kind !== \"string\" || !(RULE_KINDS as readonly string[]).includes(kind)) {\n\t\tproblems.add(at(path, \"rule\"), `${describe(kind)} is not a rule; expected one of ${RULE_KINDS.join(\", \")}`)\n\n\t\treturn null\n\t}\n\n\tconst rule = kind as RuleKind\n\n\tfor (const name of Object.keys(raw)) {\n\t\tif (name === \"rule\" || (name === \"value\" && rule !== \"unique\")) {\n\t\t\tcontinue\n\t\t}\n\n\t\tproblems.add(\n\t\t\tat(path, name),\n\t\t\trule === \"unique\" && name === \"value\" ? \"unique takes no value\" : `is not a property of a ${rule} rule`\n\t\t)\n\t}\n\n\tif (type !== null && !ruleApplies(rule, type)) {\n\t\tproblems.add(path, `${rule} does not apply to ${aFieldOf(type)}`)\n\n\t\treturn null\n\t}\n\n\tconst value = raw.value\n\n\tswitch (rule) {\n\t\tcase \"min\":\n\t\tcase \"max\": {\n\t\t\tconst limit = typeof value === \"string\" || typeof value === \"number\" ? normalizeDecimal(value) : null\n\n\t\t\tif (limit === null) {\n\t\t\t\tproblems.add(\n\t\t\t\t\tat(path, \"value\"),\n\t\t\t\t\tvalue === undefined\n\t\t\t\t\t\t? \"is required\"\n\t\t\t\t\t\t: `must be a decimal number such as \"0\" or \"12.5\", with a point and no exponent; got ${describe(value)}`\n\t\t\t\t)\n\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\treturn Object.freeze({ rule, value: limit })\n\t\t}\n\t\tcase \"minLength\":\n\t\tcase \"maxLength\":\n\t\t\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n\t\t\t\tproblems.add(\n\t\t\t\t\tat(path, \"value\"),\n\t\t\t\t\tvalue === undefined\n\t\t\t\t\t\t? \"is required\"\n\t\t\t\t\t\t: `must be a whole number of characters, 0 or more; got ${describe(value)}`\n\t\t\t\t)\n\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\treturn Object.freeze({ rule, value })\n\t\tcase \"unique\":\n\t\t\treturn Object.freeze({ rule })\n\t}\n}\n\nfunction ruleApplies(rule: RuleKind, type: FieldType): boolean {\n\tswitch (rule) {\n\t\tcase \"min\":\n\t\tcase \"max\":\n\t\t\treturn NUMERIC_TYPES.has(type)\n\t\tcase \"minLength\":\n\t\tcase \"maxLength\":\n\t\t\treturn type === \"string\"\n\t\tcase \"unique\":\n\t\t\treturn true\n\t}\n}\n\nfunction readText(source: Json, name: string, path: string, problems: Problems, required: boolean): string | null {\n\tconst value = source[name]\n\n\tif (value === undefined || value === null) {\n\t\tif (required) {\n\t\t\tproblems.add(at(path, name), \"is required\")\n\t\t}\n\n\t\treturn null\n\t}\n\n\tif (typeof value !== \"string\" || value.trim() === \"\") {\n\t\tproblems.add(at(path, name), `must be a non-empty string; got ${describe(value)}`)\n\n\t\treturn null\n\t}\n\n\treturn value\n}\n\nfunction readBoolean(source: Json, name: string, fallback: boolean, path: string, problems: Problems): boolean {\n\tconst value = source[name]\n\n\tif (value === undefined || value === null) {\n\t\treturn fallback\n\t}\n\n\tif (typeof value !== \"boolean\") {\n\t\tproblems.add(at(path, name), `must be true or false; got ${describe(value)}`)\n\n\t\treturn fallback\n\t}\n\n\treturn value\n}\n\n/** \"a money field\", \"an integer field\". */\nfunction aFieldOf(type: FieldType): string {\n\treturn `${/^[aeiou]/.test(type) ? \"an\" : \"a\"} ${type} field`\n}\n\nfunction isObject(value: unknown): value is Json {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction at(path: string, name: string): string {\n\treturn path === \"\" ? name : `${path}.${name}`\n}\n\nfunction describe(value: unknown): string {\n\tif (value === undefined) {\n\t\treturn \"nothing\"\n\t}\n\n\tif (Array.isArray(value)) {\n\t\treturn \"an array\"\n\t}\n\n\tif (typeof value === \"object\" && value !== null) {\n\t\treturn \"an object\"\n\t}\n\n\treturn JSON.stringify(value) ?? String(value)\n}\n","/**\n * A random part for ids such as row ids and request ids: 7 base-36 characters drawn from\n * `crypto.getRandomValues`, which, unlike `randomUUID`, also works on plain http.\n */\nexport function randomPart(): string {\n\tconst scope = globalThis as { crypto?: { getRandomValues?: (array: Uint32Array) => Uint32Array } }\n\tconst word = new Uint32Array(1)\n\n\tif (typeof scope.crypto?.getRandomValues === \"function\") {\n\t\tscope.crypto.getRandomValues(word)\n\t} else {\n\t\tword[0] = Math.floor(Math.random() * 2 ** 32)\n\t}\n\n\treturn (word[0] ?? 0).toString(36).padStart(7, \"0\")\n}\n\n/** Ids such as `r_1k3x9q2_1`: a random part drawn once, then a counter. */\nexport function sequence(prefix: string): () => string {\n\tconst random = randomPart()\n\tlet counter = 0\n\n\treturn () => `${prefix}_${random}_${(++counter).toString(36)}`\n}\n","import { TabulaError } from \"./errors.js\"\n\n/**\n * What a cell holds.\n *\n * Anything JSON can carry, and nothing else. A draft is the store's own content written out, so a\n * value that does not survive `JSON.stringify` would come back from a draft as something else, or\n * not at all: a `Date` as a string, a `Map` as `{}`, `NaN` as `null`.\n */\nexport type CellValue = null | boolean | number | string | readonly CellValue[] | CellObject\n\nexport interface CellObject {\n\treadonly [key: string]: CellValue\n}\n\nconst MAX_DEPTH = 32\n\n/**\n * A frozen copy of the input as a cell value, or an error saying why it cannot be one.\n *\n * A copy, so a caller who changes their array afterwards does not change the sheet behind its back.\n * Frozen, so a caller holding what the sheet returned cannot either. `undefined` is an empty cell,\n * `-0` is `0`, and an object's `undefined` properties are dropped: what `JSON.stringify` does.\n *\n * @param subject how the error names the value, such as `The value of \"price\" in row \"r_7\"`\n */\nexport function toCellValue(input: unknown, subject = \"A cell value\"): CellValue {\n\treturn convert(input, subject, 0)\n}\n\nfunction convert(input: unknown, subject: string, depth: number): CellValue {\n\tif (input === null || input === undefined) {\n\t\treturn null\n\t}\n\n\tswitch (typeof input) {\n\t\tcase \"boolean\":\n\t\tcase \"string\":\n\t\t\treturn input\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(input)) {\n\t\t\t\tthrow refused(subject, String(input))\n\t\t\t}\n\n\t\t\t// JSON writes -0 as 0. Kept as -0, two cells that read the same would not be equal.\n\t\t\treturn input === 0 ? 0 : input\n\t\tcase \"object\":\n\t\t\tbreak\n\t\tdefault:\n\t\t\tthrow refused(subject, `a ${typeof input}`)\n\t}\n\n\tif (depth >= MAX_DEPTH) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_value\",\n\t\t\t`${subject} is nested more than ${MAX_DEPTH} levels deep. A value that contains itself never ends.`\n\t\t)\n\t}\n\n\tif (Array.isArray(input)) {\n\t\t// Array.from, not map: map skips the holes of a sparse array and keeps them as holes.\n\t\treturn Object.freeze(Array.from(input as unknown[], item => convert(item, subject, depth + 1)))\n\t}\n\n\tconst prototype: unknown = Object.getPrototypeOf(input)\n\n\tif (prototype !== Object.prototype && prototype !== null) {\n\t\tconst name = (input as { constructor?: { name?: string } }).constructor?.name\n\n\t\tthrow refused(subject, name ? `a ${name}` : \"an object that is not a plain object\")\n\t}\n\n\t// No prototype: a key named \"__proto__\" is then an ordinary key rather than a way to replace it.\n\tconst copy = Object.create(null) as Record<string, CellValue>\n\n\tfor (const [key, item] of Object.entries(input)) {\n\t\tif (item !== undefined) {\n\t\t\tcopy[key] = convert(item, subject, depth + 1)\n\t\t}\n\t}\n\n\treturn Object.freeze(copy)\n}\n\nfunction refused(subject: string, got: string): TabulaError {\n\treturn new TabulaError(\n\t\t\"invalid_value\",\n\t\t`${subject} must be null, a boolean, a finite number, a string, or an array or plain object of these; got ${got}.`\n\t)\n}\n\n/** Whether two cell values are the same, comparing arrays and objects by content. */\nexport function sameValue(a: CellValue, b: CellValue): boolean {\n\tif (a === b) {\n\t\treturn true\n\t}\n\n\tif (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) {\n\t\treturn false\n\t}\n\n\tif (Array.isArray(a) || Array.isArray(b)) {\n\t\tif (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst other: readonly CellValue[] = b\n\n\t\treturn a.every((item: CellValue, index) => sameValue(item, other[index] ?? null))\n\t}\n\n\tconst left = a as CellObject\n\tconst right = b as CellObject\n\tconst keys = Object.keys(left)\n\n\tif (keys.length !== Object.keys(right).length) {\n\t\treturn false\n\t}\n\n\treturn keys.every(key => Object.hasOwn(right, key) && sameValue(left[key] ?? null, right[key] ?? null))\n}\n","import { TabulaError } from \"./errors.js\"\nimport { sequence } from \"./ids.js\"\nimport { Listeners } from \"./listeners.js\"\nimport { sameValue, toCellValue, type CellValue } from \"./value.js\"\n\n/**\n * A row's identity: the same from the moment the row is created until it is deleted, whatever is\n * sorted, filtered, inserted or pasted around it.\n *\n * It is not a database id and not a position. Every issue, result and formula refers to a row by\n * this id, which is what keeps \"row 37\" from meaning a different row after a sort.\n */\nexport type RowId = string\n\n/** A cell value per field key. A field with no entry is an empty cell. */\nexport type RowValues = Readonly<Record<string, CellValue>>\n\nexport interface RowInit {\n\t/** The id to keep, such as one read back from a draft. Left out, the store makes one. */\n\treadonly rowId?: RowId\n\treadonly values?: Readonly<Record<string, CellValue | undefined>>\n}\n\nexport interface RowEntry {\n\treadonly rowId: RowId\n\treadonly values: RowValues\n}\n\nexport interface RemovedRow extends RowEntry {\n\t/** Where the row stood before the removal. */\n\treadonly index: number\n}\n\n/**\n * One step of a change, carrying what it needs to be undone.\n *\n * `insert` puts a run of rows in at one place. `remove` takes rows out from anywhere, listed in the\n * order they stood; putting each back at its `index`, in that order, restores the sheet exactly.\n */\nexport type StoreOperation =\n\t| {\n\t\t\treadonly kind: \"set\"\n\t\t\treadonly rowId: RowId\n\t\t\treadonly field: string\n\t\t\treadonly before: CellValue\n\t\t\treadonly after: CellValue\n\t }\n\t| { readonly kind: \"insert\"; readonly index: number; readonly rows: readonly RowEntry[] }\n\t| { readonly kind: \"remove\"; readonly rows: readonly RemovedRow[] }\n\nexport interface StoreChange {\n\t/** The store's revision after this change. */\n\treadonly revision: number\n\t/** What the change was for, as given to `transact()`, such as `\"paste\"`. */\n\treadonly origin: string | null\n\t/** In the order they were made. */\n\treadonly operations: readonly StoreOperation[]\n}\n\nexport interface TransactOptions {\n\treadonly origin?: string\n}\n\nexport interface CellWrite {\n\treadonly rowId: RowId\n\treadonly field: string\n\treadonly value: CellValue | undefined\n}\n\nexport interface RowStoreOptions {\n\treadonly rows?: readonly RowInit[]\n\t/** Makes the id of a new row. The default is unique within the page and very unlikely to repeat across sessions. */\n\treadonly createRowId?: () => RowId\n}\n\ntype MutableRow = Record<string, CellValue>\n\n/**\n * The rows of one sheet, each under an id of its own.\n *\n * Plain data, kept out of any framework's reactivity: a view learns about changes by subscribing,\n * and redraws what the change touched. Every change is a transaction with a revision number, so a\n * backend answer can say which state of the sheet it checked.\n *\n * Only cells that hold something are kept. An empty cell is no entry at all, so a sheet of 50,000\n * mostly empty rows costs what its contents cost.\n */\nexport class RowStore {\n\t#order: RowId[] = []\n\treadonly #rows = new Map<RowId, MutableRow>()\n\t#positions: Map<RowId, number> | null = null\n\t#revision = 0\n\t#log: StoreOperation[] | null = null\n\treadonly #createRowId: () => RowId\n\treadonly #listeners = new Listeners<StoreChange>()\n\treadonly #derivers = new Set<(operations: readonly StoreOperation[]) => void>()\n\n\tconstructor(options: RowStoreOptions = {}) {\n\t\tthis.#createRowId = options.createRowId ?? sessionRowIds()\n\n\t\tfor (const { rowId, row } of this.#prepare(options.rows ?? [])) {\n\t\t\tthis.#rows.set(rowId, row)\n\t\t\tthis.#order.push(rowId)\n\t\t}\n\t}\n\n\t// ---------------------------------------------------------------- reading\n\n\t/** Counts changes: 0 for a new store, one more for each transaction that changed something. */\n\tget revision(): number {\n\t\treturn this.#revision\n\t}\n\n\tget size(): number {\n\t\treturn this.#order.length\n\t}\n\n\thas(rowId: RowId): boolean {\n\t\treturn this.#rows.has(rowId)\n\t}\n\n\trowIdAt(index: number): RowId | undefined {\n\t\treturn this.#order[index]\n\t}\n\n\t/** Where the row stands, or -1 when there is no such row. */\n\tindexOf(rowId: RowId): number {\n\t\tif (this.#positions === null) {\n\t\t\tthis.#positions = new Map(this.#order.map((id, index) => [id, index]))\n\t\t}\n\n\t\treturn this.#positions.get(rowId) ?? -1\n\t}\n\n\t/** Every row id, in order. A copy: O(rows), so a view drawing one screen reads `rowIdAt()` instead. */\n\trowIds(): RowId[] {\n\t\treturn [...this.#order]\n\t}\n\n\t/** The cell's value; null when it is empty. */\n\tget(rowId: RowId, field: string): CellValue {\n\t\treturn this.#row(rowId)[field] ?? null\n\t}\n\n\t/** The row's cells that hold something, as a frozen copy. */\n\tvalues(rowId: RowId): RowValues {\n\t\treturn frozenCopy(this.#row(rowId))\n\t}\n\n\t/** Every row with its id and values, in order: what a draft keeps. It survives `JSON.stringify` as it is. */\n\tsnapshot(): RowEntry[] {\n\t\treturn this.#order.map(rowId => Object.freeze({ rowId, values: frozenCopy(this.#row(rowId)) }))\n\t}\n\n\t/** Called after each transaction that changed something. Returns the way to stop. */\n\tsubscribe(listener: (change: StoreChange) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/**\n\t * Adds work that belongs to every change, such as working formulas out. `fn` is called at the\n\t * end of each transaction that changed something, before it is done, with what it changed; what\n\t * `fn` writes is part of the same change: one revision, one notice, one step to undo. Listeners\n\t * never see a sheet whose formulas are behind its values.\n\t *\n\t * Returns the way to stop.\n\t */\n\tderive(fn: (operations: readonly StoreOperation[]) => void): () => void {\n\t\tconst entry = (operations: readonly StoreOperation[]): void => fn(operations)\n\n\t\tthis.#derivers.add(entry)\n\n\t\treturn () => {\n\t\t\tthis.#derivers.delete(entry)\n\t\t}\n\t}\n\n\t// ---------------------------------------------------------------- writing\n\n\t/**\n\t * Makes every write inside `fn` one change: one revision, one notice to the listeners, one step\n\t * to undo. If `fn` throws, everything it wrote is taken back and the error is rethrown.\n\t *\n\t * A transaction started inside another joins it, and its writes stand or fall with the outer one.\n\t *\n\t * @returns the change, or null when nothing changed or the call joined an outer transaction\n\t */\n\ttransact(fn: () => void, options: TransactOptions = {}): StoreChange | null {\n\t\tif (this.#log !== null) {\n\t\t\tfn()\n\n\t\t\treturn null\n\t\t}\n\n\t\tconst log: StoreOperation[] = []\n\t\tthis.#log = log\n\n\t\ttry {\n\t\t\tfn()\n\n\t\t\t// What follows from the change goes in with it; a deriver that throws takes it all back.\n\t\t\tif (log.length > 0) {\n\t\t\t\tfor (const derive of [...this.#derivers]) {\n\t\t\t\t\tderive([...log])\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.#log = null\n\n\t\t\tfor (let index = log.length - 1; index >= 0; index--) {\n\t\t\t\tthis.#revert(log[index] as StoreOperation)\n\t\t\t}\n\n\t\t\tthrow error\n\t\t}\n\n\t\tthis.#log = null\n\n\t\tif (log.length === 0) {\n\t\t\treturn null\n\t\t}\n\n\t\tthis.#revision++\n\n\t\tconst change: StoreChange = Object.freeze({\n\t\t\trevision: this.#revision,\n\t\t\torigin: options.origin ?? null,\n\t\t\toperations: Object.freeze(log)\n\t\t})\n\n\t\tthis.#listeners.emit(change)\n\n\t\treturn change\n\t}\n\n\t/**\n\t * Writes one cell. Null or undefined empties it. A value equal to the one there already is no\n\t * change at all, so it does not move the revision.\n\t */\n\tsetCell(rowId: RowId, field: string, value: CellValue | undefined): void {\n\t\tthis.#write(() => {\n\t\t\tconst row = this.#row(rowId)\n\n\t\t\trequireField(field)\n\n\t\t\tconst after = toCellValue(value, `The value of \"${field}\" in row \"${rowId}\"`)\n\t\t\tconst before = row[field] ?? null\n\n\t\t\tif (sameValue(before, after)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tassign(row, field, after)\n\t\t\tthis.#record({ kind: \"set\", rowId, field, before, after })\n\t\t})\n\t}\n\n\t/** Writes many cells as one change, such as a paste. */\n\tsetCells(writes: Iterable<CellWrite>, options: TransactOptions = {}): StoreChange | null {\n\t\treturn this.transact(() => {\n\t\t\tfor (const write of writes) {\n\t\t\t\tthis.setCell(write.rowId, write.field, write.value)\n\t\t\t}\n\t\t}, options)\n\t}\n\n\t/**\n\t * Puts rows in at `index`, 0 to `size`: a number of empty rows, or rows with ids and values.\n\t *\n\t * @returns the ids of the new rows, in order\n\t */\n\tinsertRows(index: number, rows: number | readonly RowInit[]): RowId[] {\n\t\tif (!Number.isInteger(index) || index < 0 || index > this.#order.length) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_argument\",\n\t\t\t\t`Rows can be inserted at 0 to ${this.#order.length}; got ${index}.`\n\t\t\t)\n\t\t}\n\n\t\tconst inits = typeof rows === \"number\" ? blankRows(rows) : rows\n\t\tlet ids: RowId[] = []\n\n\t\tthis.#write(() => {\n\t\t\tconst prepared = this.#prepare(inits)\n\n\t\t\tif (prepared.length === 0) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tids = prepared.map(entry => entry.rowId)\n\n\t\t\tfor (const { rowId, row } of prepared) {\n\t\t\t\tthis.#rows.set(rowId, row)\n\t\t\t}\n\n\t\t\t// Spread into a new array rather than into splice(): as arguments, a paste of 200,000 rows\n\t\t\t// overflows the call stack.\n\t\t\tthis.#order = [...this.#order.slice(0, index), ...ids, ...this.#order.slice(index)]\n\t\t\tthis.#positions = null\n\t\t\tthis.#record({\n\t\t\t\tkind: \"insert\",\n\t\t\t\tindex,\n\t\t\t\trows: Object.freeze(prepared.map(({ rowId, row }) => Object.freeze({ rowId, values: frozenCopy(row) })))\n\t\t\t})\n\t\t})\n\n\t\treturn ids\n\t}\n\n\tappendRows(rows: number | readonly RowInit[]): RowId[] {\n\t\treturn this.insertRows(this.#order.length, rows)\n\t}\n\n\t/**\n\t * Takes rows out, wherever they stand. Every id must exist: one unknown id and nothing is removed.\n\t */\n\tremoveRows(rowIds: Iterable<RowId>): void {\n\t\tconst doomed = new Set(rowIds)\n\n\t\tfor (const rowId of doomed) {\n\t\t\tthis.#row(rowId)\n\t\t}\n\n\t\tif (doomed.size === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#write(() => {\n\t\t\tconst removed: RemovedRow[] = []\n\t\t\tconst kept: RowId[] = []\n\n\t\t\t// One pass whatever the number of rows: removing them one at a time is a pass per row.\n\t\t\tthis.#order.forEach((rowId, index) => {\n\t\t\t\tif (!doomed.has(rowId)) {\n\t\t\t\t\tkept.push(rowId)\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tremoved.push(Object.freeze({ index, rowId, values: frozenCopy(this.#row(rowId)) }))\n\t\t\t\tthis.#rows.delete(rowId)\n\t\t\t})\n\n\t\t\tthis.#order = kept\n\t\t\tthis.#positions = null\n\t\t\tthis.#record({ kind: \"remove\", rows: Object.freeze(removed) })\n\t\t})\n\t}\n\n\t// ---------------------------------------------------------------- taking back\n\n\t/**\n\t * Takes a change back, or several made one after another: their operations undone, the last\n\t * first, as one new change with a revision of its own. Rows come back under the ids they had, to\n\t * the places they stood.\n\t *\n\t * The sheet must be as the change left it: nothing changed since, or every later change taken\n\t * back first. Otherwise nothing is written and a `conflict` is thrown, rather than mixing the\n\t * change into a sheet it never saw.\n\t *\n\t * @returns the change that took it back\n\t */\n\trevert(change: StoreChange | readonly StoreChange[], options: TransactOptions = {}): StoreChange | null {\n\t\tconst changes = listOf(change)\n\n\t\treturn this.#standalone(\"revert\", options, () => {\n\t\t\tfor (let at = changes.length - 1; at >= 0; at--) {\n\t\t\t\tconst operations = (changes[at] as StoreChange).operations\n\n\t\t\t\tfor (let index = operations.length - 1; index >= 0; index--) {\n\t\t\t\t\tthis.#undo(operations[index] as StoreOperation)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Makes a change again once `revert()` has taken it back, with the same row ids; several, in the\n\t * order they were made. The sheet must be as it was before them, or a `conflict` is thrown and\n\t * nothing is written.\n\t *\n\t * @returns the change that made it again\n\t */\n\treplay(change: StoreChange | readonly StoreChange[], options: TransactOptions = {}): StoreChange | null {\n\t\tconst changes = listOf(change)\n\n\t\treturn this.#standalone(\"replay\", options, () => {\n\t\t\tfor (const each of changes) {\n\t\t\t\tfor (const operation of each.operations) {\n\t\t\t\t\tthis.#redo(operation)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\t// ---------------------------------------------------------------- internals\n\n\t#write(fn: () => void): void {\n\t\tif (this.#log === null) {\n\t\t\tthis.transact(fn)\n\t\t} else {\n\t\t\tfn()\n\t\t}\n\t}\n\n\t#record(operation: StoreOperation): void {\n\t\tthis.#log?.push(Object.freeze(operation))\n\t}\n\n\t#row(rowId: RowId): MutableRow {\n\t\tconst row = this.#rows.get(rowId)\n\n\t\tif (!row) {\n\t\t\tthrow new TabulaError(\"unknown_row\", `There is no row \"${rowId}\" in this sheet.`)\n\t\t}\n\n\t\treturn row\n\t}\n\n\t/** Checks the ids and values of new rows without touching the store, so a refusal leaves it as it was. */\n\t#prepare(inits: readonly RowInit[]): { rowId: RowId; row: MutableRow }[] {\n\t\tconst batch = new Set<RowId>()\n\n\t\treturn inits.map(init => {\n\t\t\tconst given = init.rowId !== undefined\n\t\t\tconst rowId = given ? init.rowId : this.#createRowId()\n\n\t\t\tif (typeof rowId !== \"string\" || rowId === \"\") {\n\t\t\t\tthrow new TabulaError(\"invalid_argument\", `A row id must be a non-empty string; got ${String(rowId)}.`)\n\t\t\t}\n\n\t\t\tif (this.#rows.has(rowId) || batch.has(rowId)) {\n\t\t\t\tthrow new TabulaError(\n\t\t\t\t\t\"duplicate_row\",\n\t\t\t\t\tgiven\n\t\t\t\t\t\t? `There is already a row \"${rowId}\" in this sheet.`\n\t\t\t\t\t\t: `createRowId() returned \"${rowId}\", an id already in use.`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tbatch.add(rowId)\n\n\t\t\tconst row = Object.create(null) as MutableRow\n\n\t\t\tfor (const [field, value] of Object.entries(init.values ?? {})) {\n\t\t\t\trequireField(field)\n\n\t\t\t\tconst cell = toCellValue(value, `The value of \"${field}\" in row \"${rowId}\"`)\n\n\t\t\t\tif (cell !== null) {\n\t\t\t\t\trow[field] = cell\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn { rowId, row }\n\t\t})\n\t}\n\n\t#revert(operation: StoreOperation): void {\n\t\tswitch (operation.kind) {\n\t\t\tcase \"set\":\n\t\t\t\tassign(this.#row(operation.rowId), operation.field, operation.before)\n\t\t\t\tbreak\n\t\t\tcase \"insert\": {\n\t\t\t\tconst inserted = new Set(operation.rows.map(entry => entry.rowId))\n\n\t\t\t\tthis.#order = this.#order.filter(rowId => !inserted.has(rowId))\n\n\t\t\t\tfor (const rowId of inserted) {\n\t\t\t\t\tthis.#rows.delete(rowId)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase \"remove\":\n\t\t\t\tthis.#restore(operation.rows)\n\t\t\t\tbreak\n\t\t}\n\n\t\tthis.#positions = null\n\t}\n\n\t/** A transaction that must be a change of its own, never part of an outer one. */\n\t#standalone(name: string, options: TransactOptions, fn: () => void): StoreChange | null {\n\t\tif (this.#log !== null) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_argument\",\n\t\t\t\t`${name}() makes a change of its own and cannot run inside a transaction.`\n\t\t\t)\n\t\t}\n\n\t\treturn this.transact(fn, options)\n\t}\n\n\t#undo(operation: StoreOperation): void {\n\t\tswitch (operation.kind) {\n\t\t\tcase \"set\":\n\t\t\t\tthis.#swap(operation.rowId, operation.field, operation.after, operation.before)\n\t\t\t\tbreak\n\t\t\tcase \"insert\":\n\t\t\t\tthis.#expectRows(operation.rows, true)\n\t\t\t\tthis.removeRows(operation.rows.map(entry => entry.rowId))\n\t\t\t\tbreak\n\t\t\tcase \"remove\":\n\t\t\t\tthis.#putBack(operation.rows)\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\t#redo(operation: StoreOperation): void {\n\t\tswitch (operation.kind) {\n\t\t\tcase \"set\":\n\t\t\t\tthis.#swap(operation.rowId, operation.field, operation.before, operation.after)\n\t\t\t\tbreak\n\t\t\tcase \"insert\":\n\t\t\t\tthis.#expectRows(operation.rows, false)\n\n\t\t\t\tif (operation.index > this.#order.length) {\n\t\t\t\t\tthrow new TabulaError(\n\t\t\t\t\t\t\"conflict\",\n\t\t\t\t\t\t`Rows went in at ${operation.index}, past the end of this sheet of ${this.#order.length} rows.`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tthis.insertRows(operation.index, operation.rows)\n\t\t\t\tbreak\n\t\t\tcase \"remove\":\n\t\t\t\tthis.#expectRows(operation.rows, true)\n\t\t\t\tthis.removeRows(operation.rows.map(entry => entry.rowId))\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\t/** Writes `to` into a cell that must hold `from`. */\n\t#swap(rowId: RowId, field: string, from: CellValue, to: CellValue): void {\n\t\tconst row = this.#rows.get(rowId)\n\n\t\tif (!row) {\n\t\t\tthrow new TabulaError(\"conflict\", `There is no row \"${rowId}\" in this sheet any more.`)\n\t\t}\n\n\t\tif (!sameValue(row[field] ?? null, from)) {\n\t\t\tthrow new TabulaError(\"conflict\", `The cell \"${field}\" in row \"${rowId}\" has changed since.`)\n\t\t}\n\n\t\tassign(row, field, to)\n\t\tthis.#record({ kind: \"set\", rowId, field, before: from, after: to })\n\t}\n\n\t#expectRows(entries: readonly RowEntry[], present: boolean): void {\n\t\tfor (const { rowId } of entries) {\n\t\t\tif (this.#rows.has(rowId) !== present) {\n\t\t\t\tthrow new TabulaError(\n\t\t\t\t\t\"conflict\",\n\t\t\t\t\tpresent\n\t\t\t\t\t\t? `There is no row \"${rowId}\" in this sheet any more.`\n\t\t\t\t\t\t: `There is a row \"${rowId}\" in this sheet already.`\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Puts removed rows back where they stood, in one pass, and records it as one insert for each run\n\t * of rows that stood together: replaying those inserts in order puts every row back in its place.\n\t */\n\t#putBack(entries: readonly RemovedRow[]): void {\n\t\tthis.#expectRows(entries, false)\n\n\t\tconst total = this.#order.length + entries.length\n\t\tlet previous = -1\n\n\t\tfor (const entry of entries) {\n\t\t\tif (!Number.isInteger(entry.index) || entry.index <= previous || entry.index >= total) {\n\t\t\t\tthrow new TabulaError(\n\t\t\t\t\t\"conflict\",\n\t\t\t\t\t`Row \"${entry.rowId}\" stood at ${entry.index}, which is not a place in this sheet of ${total} rows.`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tprevious = entry.index\n\t\t}\n\n\t\tif (entries.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#restore(entries)\n\t\tthis.#positions = null\n\n\t\tlet start = 0\n\n\t\tfor (let end = 1; end <= entries.length; end++) {\n\t\t\tconst next = entries[end]\n\n\t\t\tif (next === undefined || next.index !== (entries[end - 1] as RemovedRow).index + 1) {\n\t\t\t\tconst run = entries.slice(start, end)\n\n\t\t\t\tthis.#record({\n\t\t\t\t\tkind: \"insert\",\n\t\t\t\t\tindex: (run[0] as RemovedRow).index,\n\t\t\t\t\trows: Object.freeze(run.map(({ rowId, values }) => Object.freeze({ rowId, values })))\n\t\t\t\t})\n\t\t\t\tstart = end\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Puts removed rows back where they stood, in one pass. */\n\t#restore(entries: readonly RemovedRow[]): void {\n\t\tconst order: RowId[] = []\n\t\tconst total = this.#order.length + entries.length\n\t\tlet next = 0\n\t\tlet from = 0\n\n\t\tfor (let position = 0; position < total; position++) {\n\t\t\tconst entry = entries[next]\n\n\t\t\tif (entry !== undefined && entry.index === position) {\n\t\t\t\torder.push(entry.rowId)\n\t\t\t\tthis.#rows.set(entry.rowId, Object.assign(Object.create(null) as MutableRow, entry.values))\n\t\t\t\tnext++\n\t\t\t} else {\n\t\t\t\torder.push(this.#order[from++] as RowId)\n\t\t\t}\n\t\t}\n\n\t\tthis.#order = order\n\t}\n}\n\nfunction listOf(change: StoreChange | readonly StoreChange[]): readonly StoreChange[] {\n\treturn \"operations\" in change ? [change] : change\n}\n\nfunction assign(row: MutableRow, field: string, value: CellValue): void {\n\tif (value === null) {\n\t\tdelete row[field]\n\t} else {\n\t\trow[field] = value\n\t}\n}\n\nfunction frozenCopy(row: MutableRow): RowValues {\n\treturn Object.freeze(Object.assign(Object.create(null) as MutableRow, row))\n}\n\nfunction requireField(field: string): void {\n\tif (typeof field !== \"string\" || field === \"\") {\n\t\tthrow new TabulaError(\"invalid_argument\", `A field key must be a non-empty string; got ${String(field)}.`)\n\t}\n}\n\nfunction blankRows(count: number): RowInit[] {\n\tif (!Number.isSafeInteger(count) || count < 0) {\n\t\tthrow new TabulaError(\"invalid_argument\", `A number of rows must be a whole number, 0 or more; got ${count}.`)\n\t}\n\n\treturn Array.from({ length: count }, () => ({}))\n}\n\n/**\n * Ids such as `r_1k3x9q2_1`: a random part drawn once per store, then a counter.\n *\n * The counter keeps them unique within the page. The random part keeps a row made today from taking\n * the id of a row in a draft saved yesterday, which would let yesterday's backend answer land on it.\n */\nfunction sessionRowIds(): () => RowId {\n\treturn sequence(\"r\")\n}\n","/** Settles as the promise does, or rejects once the signal aborts, whichever comes first. */\nexport function raced<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst abort = (): void => reject(abortError())\n\n\t\tif (signal.aborted) {\n\t\t\tabort()\n\n\t\t\treturn\n\t\t}\n\n\t\tsignal.addEventListener(\"abort\", abort, { once: true })\n\t\tpromise.then(\n\t\t\tvalue => {\n\t\t\t\tsignal.removeEventListener(\"abort\", abort)\n\t\t\t\tresolve(value)\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", abort)\n\t\t\t\treject(error instanceof Error ? error : new Error(String(error)))\n\t\t\t}\n\t\t)\n\t})\n}\n\n/** Resolves after `ms`, or rejects once the signal aborts. */\nexport function wait(ms: number, signal: AbortSignal): Promise<void> {\n\treturn raced(new Promise<void>(resolve => setTimeout(resolve, ms)), signal)\n}\n\nexport function abortError(): Error {\n\tconst error = new Error(\"The request was cancelled.\")\n\n\terror.name = \"AbortError\"\n\n\treturn error\n}\n\n/** A signal that never aborts, for a request nobody will cancel. */\nexport function neverAborted(): AbortSignal {\n\treturn new AbortController().signal\n}\n","import { neverAborted, raced } from \"./async.js\"\nimport type { AdapterContext } from \"./contract.js\"\nimport { TabulaError } from \"./errors.js\"\nimport { sequence } from \"./ids.js\"\nimport { Listeners } from \"./listeners.js\"\nimport type { CellWrite, RowId, RowStore, StoreChange } from \"./rows.js\"\nimport type { LookupField, ModuleSchema } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport { clean } from \"./values/text.js\"\n\n/**\n * Lookups: a record picked by its name, kept as `{ id, label }`. The user sees the label, the\n * backend takes the id. A name typed or pasted is text until a record is matched to it, and text\n * in a lookup is an error (`not_matched`): there is no id to send.\n */\n\n/** A record a lookup can hold. */\nexport interface LookupItem {\n\treadonly id: string | number\n\treadonly label: string\n\t/** A second line in the list, such as a product's code. */\n\treadonly description?: string\n\t/** Shown, not picked, such as an inactive product; never matched to a name. */\n\treadonly disabled?: boolean\n}\n\nexport interface LookupSearchRequest {\n\t/** The schema's name for the lookup, such as `\"product\"`. */\n\treadonly lookup: string\n\t/** The field being edited, for a backend whose choice depends on it. */\n\treadonly field: string\n\treadonly query: string\n\treadonly limit: number\n}\n\nexport interface LookupSearchResponse {\n\treadonly items: readonly LookupItem[]\n\t/** Whether more records fit the query than were sent. */\n\treadonly more?: boolean\n}\n\n/** Many names at once, such as from one paste: one request, not one per cell. */\nexport interface LookupResolveRequest {\n\treadonly lookup: string\n\treadonly labels: readonly string[]\n}\n\nexport interface LookupResolveResponse {\n\t/**\n\t * For each name, as it was sent, the records it may mean: one is a match, none or several is not.\n\t * Matching is the backend's: in the user's language, and by more than the name if it likes, such\n\t * as by a product code. The browser compares nothing, so \"ÇELİK\" and \"çelik\" are two names to it.\n\t */\n\treadonly matches: readonly { readonly label: string; readonly items: readonly LookupItem[] }[]\n}\n\n/** What an editor needs to list a lookup's records as the user types: a `LookupResolver` is one. */\nexport interface LookupSearch {\n\tsearch(field: string, query: string, signal?: AbortSignal, limit?: number): Promise<LookupSearchResponse>\n}\n\n/** How a sheet reaches its records. Without `resolve`, names are matched only by picking from the list. */\nexport interface LookupAdapters {\n\tsearch(request: LookupSearchRequest, context: AdapterContext): Promise<LookupSearchResponse>\n\tresolve?(request: LookupResolveRequest, context: AdapterContext): Promise<LookupResolveResponse>\n}\n\n/**\n * The origin of the change that puts a matched record in place of a name. An undo history adds such\n * a change to the step before it, so one Ctrl+Z takes back a paste and what was matched in it.\n */\nexport const LOOKUP_ORIGIN = \"lookup\"\n\nexport interface LookupResolverOptions {\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\treadonly adapters: LookupAdapters\n\t/** How many names go in one resolve request. 200 by default. */\n\treadonly batchSize?: number\n\t/** Milliseconds an answer is used again rather than asked for anew. 60,000 by default. */\n\treadonly cacheFor?: number\n\treadonly now?: () => number\n\treadonly createRequestId?: () => string\n}\n\ninterface Cached<T> {\n\treadonly value: T\n\treadonly at: number\n}\n\n/** The names waiting to be matched in one lookup: by name as written, cleaned, and the cells holding it. */\ntype Names = Map<string, { readonly label: string; readonly cells: Set<string> }>\n\n/** By lookup. */\ntype Queue = Map<string, Names>\n\nconst DEFAULT_BATCH = 200\nconst DEFAULT_CACHE_FOR = 60_000\n\n/**\n * Searches a sheet's lookups for the editor's list, and matches the names typed or pasted into them\n * to records, many at a time.\n *\n * Every name that lands in a lookup cell is gathered, and all of them, from one paste or several\n * edits in a row, go to the backend as one request per lookup (or a few, for thousands). A name\n * that means exactly one record becomes that record; one that means none or several stays text,\n * marked, for the user to pick from the list. An answer is used again for a minute, so pasting the\n * same names twice asks once.\n */\nexport class LookupResolver implements LookupSearch {\n\treadonly #schema: ModuleSchema\n\treadonly #store: RowStore\n\treadonly #adapters: LookupAdapters\n\treadonly #batchSize: number\n\treadonly #cacheFor: number\n\treadonly #now: () => number\n\treadonly #requestId: () => string\n\treadonly #listeners = new Listeners<LookupResolver>()\n\treadonly #stop: () => void\n\treadonly #searches = new Map<string, Cached<LookupSearchResponse>>()\n\t/** By lookup, then name: the record the name means, or null for none or several. */\n\treadonly #matches = new Map<string, Map<string, Cached<LookupItem | null>>>()\n\t#queue: Queue = new Map()\n\t#flushing: Promise<void> = Promise.resolve()\n\t#scheduled = false\n\t#pending = 0\n\t#failure: { readonly message: string; readonly error: unknown } | null = null\n\t#version = 0\n\t#disposed = false\n\n\tconstructor(options: LookupResolverOptions) {\n\t\tconst batchSize = options.batchSize ?? DEFAULT_BATCH\n\n\t\tif (!Number.isSafeInteger(batchSize) || batchSize < 1) {\n\t\t\tthrow new TabulaError(\"invalid_argument\", `batchSize must be a whole number, 1 or more; got ${batchSize}.`)\n\t\t}\n\n\t\tthis.#schema = options.schema\n\t\tthis.#store = options.store\n\t\tthis.#adapters = options.adapters\n\t\tthis.#batchSize = batchSize\n\t\tthis.#cacheFor = options.cacheFor ?? DEFAULT_CACHE_FOR\n\t\tthis.#now = options.now ?? (() => Date.now())\n\t\tthis.#requestId = options.createRequestId ?? sequence(\"lookup\")\n\t\tthis.#stop = this.#store.subscribe(change => this.#onChange(change))\n\t}\n\n\t/** Moves when the number of names waiting changes, or a request fails or recovers. */\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\t/** How many names are waiting for the backend. */\n\tget pending(): number {\n\t\treturn this.#pending\n\t}\n\n\t/** What went wrong with the last resolve request, until one goes through again. */\n\tget failure(): { readonly message: string; readonly error: unknown } | null {\n\t\treturn this.#failure\n\t}\n\n\tsubscribe(listener: (resolver: LookupResolver) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Searches the records of a lookup field, for the editor's list. */\n\tasync search(\n\t\tfield: string,\n\t\tquery: string,\n\t\tsignal: AbortSignal = neverAborted(),\n\t\tlimit = 20\n\t): Promise<LookupSearchResponse> {\n\t\tconst lookup = this.#lookupOf(field)\n\n\t\tif (!lookup) {\n\t\t\tthrow new TabulaError(\"invalid_argument\", `\"${field}\" is not a lookup field.`)\n\t\t}\n\n\t\tconst key = `${lookup.lookup}\\u0000${limit}\\u0000${clean(query)}`\n\t\tconst cached = this.#fresh(this.#searches.get(key))\n\n\t\tif (cached) {\n\t\t\treturn cached\n\t\t}\n\n\t\tconst requestId = this.#requestId()\n\t\tconst answer = await raced(\n\t\t\tthis.#adapters.search({ lookup: lookup.lookup, field, query, limit }, { signal, requestId }),\n\t\t\tsignal\n\t\t)\n\t\tconst response = readSearchResponse(answer)\n\n\t\tthis.#searches.set(key, { value: response, at: this.#now() })\n\n\t\treturn response\n\t}\n\n\t/** Matches every lookup cell holding a name, such as after a draft is opened. */\n\tresolveAll(): Promise<void> {\n\t\tfor (const rowId of this.#store.rowIds()) {\n\t\t\tfor (const field of this.#schema.fields) {\n\t\t\t\tthis.#enqueue(rowId, field.key, this.#store.get(rowId, field.key))\n\t\t\t}\n\t\t}\n\n\t\treturn this.settled()\n\t}\n\n\t/** Settles once every name gathered so far has had its answer. */\n\tasync settled(): Promise<void> {\n\t\tdo {\n\t\t\tawait Promise.resolve()\n\t\t\tawait this.#flushing\n\t\t} while (this.#queue.size > 0 || this.#scheduled)\n\t}\n\n\t/** Stops following the store. Answers still on their way are not written. */\n\tdispose(): void {\n\t\tthis.#disposed = true\n\t\tthis.#stop()\n\t}\n\n\t// ---------------------------------------------------------------- gathering\n\n\t#onChange(change: StoreChange): void {\n\t\t// An undo puts back what was there; matching it again would be a new change, and end the redo.\n\t\tif (change.origin === \"undo\" || change.origin === \"redo\" || change.origin === LOOKUP_ORIGIN) {\n\t\t\treturn\n\t\t}\n\n\t\tfor (const operation of change.operations) {\n\t\t\tif (operation.kind === \"set\") {\n\t\t\t\tthis.#enqueue(operation.rowId, operation.field, operation.after)\n\t\t\t} else if (operation.kind === \"insert\") {\n\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\tfor (const [field, value] of Object.entries(row.values)) {\n\t\t\t\t\t\tthis.#enqueue(row.rowId, field, value)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t#enqueue(rowId: RowId, field: string, value: CellValue): void {\n\t\tconst lookup = this.#lookupOf(field)\n\n\t\tif (!lookup || !this.#adapters.resolve || typeof value !== \"string\" || value.trim() === \"\") {\n\t\t\treturn\n\t\t}\n\n\t\tlet names = this.#queue.get(lookup.lookup)\n\n\t\tif (!names) {\n\t\t\tnames = new Map()\n\t\t\tthis.#queue.set(lookup.lookup, names)\n\t\t}\n\n\t\tconst key = clean(value)\n\t\tconst entry = names.get(key) ?? { label: value, cells: new Set<string>() }\n\n\t\tentry.cells.add(cellKey(rowId, field))\n\t\tnames.set(key, entry)\n\t\tthis.#schedule()\n\t}\n\n\t#schedule(): void {\n\t\tif (this.#scheduled || this.#disposed) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#scheduled = true\n\t\t// After the change that gathered the names: everything one paste or one script writes in a\n\t\t// row goes in one request.\n\t\tthis.#flushing = this.#flushing.then(async () => {\n\t\t\tawait Promise.resolve()\n\t\t\tthis.#scheduled = false\n\t\t\tawait this.#flush()\n\t\t})\n\t}\n\n\t// ---------------------------------------------------------------- matching\n\n\tasync #flush(): Promise<void> {\n\t\tconst queue = this.#queue\n\t\tconst resolve = this.#adapters.resolve\n\n\t\tthis.#queue = new Map()\n\n\t\tif (!resolve || this.#disposed) {\n\t\t\treturn\n\t\t}\n\n\t\tfor (const [lookup, names] of queue) {\n\t\t\tconst known = this.#matches.get(lookup) ?? new Map<string, Cached<LookupItem | null>>()\n\t\t\tconst unknown = [...names].filter(([key]) => !this.#fresh(known.get(key))).map(([, entry]) => entry.label)\n\n\t\t\tthis.#matches.set(lookup, known)\n\t\t\tthis.#setPending(this.#pending + unknown.length)\n\n\t\t\tfor (let start = 0; start < unknown.length; start += this.#batchSize) {\n\t\t\t\tconst labels = unknown.slice(start, start + this.#batchSize)\n\n\t\t\t\ttry {\n\t\t\t\t\tconst answer = await resolve(\n\t\t\t\t\t\t{ lookup, labels },\n\t\t\t\t\t\t{ signal: neverAborted(), requestId: this.#requestId() }\n\t\t\t\t\t)\n\n\t\t\t\t\tthis.#learn(known, labels, readResolveResponse(answer))\n\t\t\t\t\tthis.#setFailure(null)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.#setFailure(error)\n\t\t\t\t} finally {\n\t\t\t\t\tthis.#setPending(this.#pending - labels.length)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.#write(names, known)\n\t\t}\n\t}\n\n\t/** Keeps what the backend said each name means: one record that can be picked, or nothing. */\n\t#learn(\n\t\tknown: Map<string, Cached<LookupItem | null>>,\n\t\tlabels: readonly string[],\n\t\tresponse: LookupResolveResponse\n\t): void {\n\t\tconst at = this.#now()\n\t\tconst answers = new Map(response.matches.map(match => [clean(match.label), match.items] as const))\n\n\t\tfor (const label of labels) {\n\t\t\tconst items = (answers.get(clean(label)) ?? []).filter(item => !item.disabled)\n\n\t\t\tknown.set(clean(label), { value: items.length === 1 ? (items[0] as LookupItem) : null, at })\n\t\t}\n\t}\n\n\t/** Puts each matched record in the cells still holding its name, as one change. */\n\t#write(names: Names, known: Map<string, Cached<LookupItem | null>>): void {\n\t\tif (this.#disposed) {\n\t\t\treturn\n\t\t}\n\n\t\tconst writes: CellWrite[] = []\n\n\t\tfor (const [key, entry] of names) {\n\t\t\tconst item = this.#fresh(known.get(key))\n\n\t\t\tif (!item) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor (const cell of entry.cells) {\n\t\t\t\tconst [rowId, field] = cell.split(\"\\u0000\") as [RowId, string]\n\t\t\t\tconst value = this.#store.has(rowId) ? this.#store.get(rowId, field) : null\n\n\t\t\t\t// Only where the name still stands: the user may have typed something else meanwhile.\n\t\t\t\tif (typeof value === \"string\" && clean(value) === key) {\n\t\t\t\t\twrites.push({ rowId, field, value: Object.freeze({ id: item.id, label: item.label }) })\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (writes.length > 0) {\n\t\t\tthis.#store.setCells(writes, { origin: LOOKUP_ORIGIN })\n\t\t}\n\t}\n\n\t// ---------------------------------------------------------------- helpers\n\n\t#lookupOf(field: string): LookupField | null {\n\t\tif (!this.#schema.has(field)) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst schemaField = this.#schema.field(field)\n\n\t\treturn schemaField.type === \"lookup\" ? schemaField : null\n\t}\n\n\t#fresh<T>(cached: Cached<T> | undefined): T | undefined {\n\t\treturn cached && this.#now() - cached.at < this.#cacheFor ? cached.value : undefined\n\t}\n\n\t#setPending(pending: number): void {\n\t\tif (pending !== this.#pending) {\n\t\t\tthis.#pending = pending\n\t\t\tthis.#changed()\n\t\t}\n\t}\n\n\t#setFailure(error: unknown): void {\n\t\tif (error === null && this.#failure === null) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#failure =\n\t\t\terror === null\n\t\t\t\t? null\n\t\t\t\t: Object.freeze({ message: error instanceof Error ? error.message : String(error), error })\n\t\tthis.#changed()\n\t}\n\n\t#changed(): void {\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n}\n\nfunction cellKey(rowId: RowId, field: string): string {\n\treturn `${rowId}\\u0000${field}`\n}\n\n// ---------------------------------------------------------------- reading answers\n\nfunction readSearchResponse(input: unknown): LookupSearchResponse {\n\tconst root = plain(input)\n\n\tif (!root || !Array.isArray(root.items)) {\n\t\tthrow new TabulaError(\"invalid_response\", \"A lookup search answer must be an object with an items array.\")\n\t}\n\n\treturn Object.freeze({\n\t\titems: Object.freeze(root.items.map((item, index) => readItem(item, `items[${index}]`))),\n\t\tmore: root.more === true\n\t})\n}\n\nfunction readResolveResponse(input: unknown): LookupResolveResponse {\n\tconst root = plain(input)\n\n\tif (!root || !Array.isArray(root.matches)) {\n\t\tthrow new TabulaError(\"invalid_response\", \"A lookup resolve answer must be an object with a matches array.\")\n\t}\n\n\treturn Object.freeze({\n\t\tmatches: Object.freeze(\n\t\t\troot.matches.map((match, index) => {\n\t\t\t\tconst entry = plain(match)\n\n\t\t\t\tif (!entry || typeof entry.label !== \"string\" || !Array.isArray(entry.items)) {\n\t\t\t\t\tthrow new TabulaError(\"invalid_response\", `matches[${index}] must have a label and an items array.`)\n\t\t\t\t}\n\n\t\t\t\treturn Object.freeze({\n\t\t\t\t\tlabel: entry.label,\n\t\t\t\t\titems: Object.freeze(\n\t\t\t\t\t\tentry.items.map((item, at) => readItem(item, `matches[${index}].items[${at}]`))\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t})\n\t\t)\n\t})\n}\n\nfunction readItem(input: unknown, path: string): LookupItem {\n\tconst item = plain(input)\n\tconst id = item?.id\n\n\tif (!item || (typeof id !== \"string\" && typeof id !== \"number\") || typeof item.label !== \"string\") {\n\t\tthrow new TabulaError(\"invalid_response\", `${path} must have an id (text or a number) and a label.`)\n\t}\n\n\treturn Object.freeze({\n\t\tid,\n\t\tlabel: item.label,\n\t\t...(typeof item.description === \"string\" ? { description: item.description } : {}),\n\t\t...(item.disabled === true ? { disabled: true } : {})\n\t})\n}\n\nfunction plain(value: unknown): Record<string, unknown> | null {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: null\n}\n","import { TabulaError } from \"./errors.js\"\nimport { Listeners } from \"./listeners.js\"\nimport { LOOKUP_ORIGIN } from \"./lookup.js\"\nimport type { RowStore, StoreChange } from \"./rows.js\"\n\nexport interface UndoHistoryOptions {\n\t/** How many steps can be taken back; the oldest is forgotten past that. 100 by default. */\n\treadonly limit?: number\n\t/**\n\t * Whether a change belongs to the step before it rather than being a step of its own. By default,\n\t * a lookup matching the names an edit put in (`\"lookup\"`): one Ctrl+Z takes back both. Formulas\n\t * need no joining: what they work out is part of the edit's own change.\n\t */\n\treadonly joins?: (change: StoreChange) => boolean\n}\n\n/** The origin of the change that takes a step back, as `StoreChange.origin` gives it. */\nexport const UNDO_ORIGIN = \"undo\"\n/** The origin of the change that makes a step again. */\nexport const REDO_ORIGIN = \"redo\"\n\nconst DEFAULT_LIMIT = 100\n\n/**\n * A step of something kept beside the store, such as the colours put on cells: taken back and made\n * again by the one who recorded it. It has no revision; the rows are not changed by it.\n */\nexport interface HistoryStep {\n\treadonly undo: () => void\n\treadonly redo: () => void\n}\n\n/** One step: a change, and any that joined it, in the order they were made; or a step kept beside the store. */\ntype Step = StoreChange[] | HistoryStep\n\n/**\n * Undo and redo for a sheet: every change to the store is a step, whoever made it.\n *\n * A step is one transaction, so a paste of 500 rows goes back in one go, the rows it added included.\n * A change that follows from the one before, such as a lookup matching the names a paste put in,\n * joins that step rather than making one of its own. Taking a step back is itself a change, with a\n * revision of its own and `\"undo\"` as its origin: an answer from the backend about the sheet before\n * the undo is out of date after it, as it should be.\n *\n * Steps are taken back strictly last first. Any new change, including one a listener makes in answer\n * to an undo, ends the way forward: what was taken back can no longer be made again on top of it.\n */\nexport class UndoHistory {\n\treadonly #store: RowStore\n\treadonly #limit: number\n\treadonly #joins: (change: StoreChange) => boolean\n\treadonly #undo: Step[] = []\n\t#redo: Step[] = []\n\t/** The revision of the change an undo or a redo is making, which is not a step of its own. */\n\t#making = -1\n\t/** Changes recorded so far, to tell whether a listener wrote while a step was being taken. */\n\t#recorded = 0\n\t#version = 0\n\treadonly #listeners = new Listeners<UndoHistory>()\n\t#stop: (() => void) | null\n\n\tconstructor(store: RowStore, options: UndoHistoryOptions = {}) {\n\t\tconst limit = options.limit ?? DEFAULT_LIMIT\n\n\t\tif (!Number.isSafeInteger(limit) || limit < 1) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_argument\",\n\t\t\t\t`The limit of an undo history must be a whole number, 1 or more; got ${limit}.`\n\t\t\t)\n\t\t}\n\n\t\tthis.#store = store\n\t\tthis.#limit = limit\n\t\tthis.#joins = options.joins ?? (change => change.origin === LOOKUP_ORIGIN)\n\t\tthis.#stop = store.subscribe(change => this.#record(change))\n\t}\n\n\t/** Moves on every change to what can be undone or redone, for a view to redraw its buttons by. */\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\tget canUndo(): boolean {\n\t\treturn this.#undo.length > 0\n\t}\n\n\tget canRedo(): boolean {\n\t\treturn this.#redo.length > 0\n\t}\n\n\t/**\n\t * The change that began the step `undo()` would take back, such as one whose origin is `\"paste\"`.\n\t * Null when there is none.\n\t */\n\tget nextUndo(): StoreChange | null {\n\t\treturn firstChange(this.#undo[this.#undo.length - 1])\n\t}\n\n\t/** The change that began the step `redo()` would make again. Null when there is none. */\n\tget nextRedo(): StoreChange | null {\n\t\treturn firstChange(this.#redo[this.#redo.length - 1])\n\t}\n\n\t/**\n\t * Records a step of something kept beside the store, such as colours put on cells, so Ctrl+Z\n\t * takes it back in its turn with the rows' changes. It ends the way forward, as any change does.\n\t */\n\trecord(step: HistoryStep): void {\n\t\tthis.#undo.push(step)\n\t\tthis.#trim()\n\t\tthis.#redo = []\n\t\tthis.#changed()\n\t}\n\n\t/**\n\t * Takes the last step back.\n\t *\n\t * @returns the change that took it back, for a view to show where it landed; null when there was\n\t * nothing to undo\n\t * @throws TabulaError `conflict` when the sheet is not as the step left it, which only a store\n\t * changed while this history was not listening can be. Nothing is written, and the history,\n\t * which no longer describes the sheet, is cleared.\n\t */\n\tundo(): StoreChange | null {\n\t\tconst step = this.#undo.pop()\n\n\t\tif (step === undefined) {\n\t\t\treturn null\n\t\t}\n\n\t\tif (!Array.isArray(step)) {\n\t\t\tstep.undo()\n\t\t\tthis.#redo.push(step)\n\t\t\tthis.#changed()\n\n\t\t\treturn null\n\t\t}\n\n\t\tconst recorded = this.#recorded\n\t\tconst made = this.#take(step, this.#undo, () => this.#store.revert(step, { origin: UNDO_ORIGIN }))\n\n\t\t// A listener that wrote in answer made a change on top of the undo: the step stays undone.\n\t\tif (this.#recorded === recorded) {\n\t\t\tthis.#redo.push(step)\n\t\t}\n\n\t\tthis.#changed()\n\n\t\treturn made\n\t}\n\n\t/**\n\t * Makes the last step taken back again.\n\t *\n\t * @returns the change that made it again; null when there was nothing to redo\n\t * @throws TabulaError `conflict`, as `undo()` does\n\t */\n\tredo(): StoreChange | null {\n\t\tconst step = this.#redo.pop()\n\n\t\tif (step === undefined) {\n\t\t\treturn null\n\t\t}\n\n\t\tif (!Array.isArray(step)) {\n\t\t\tstep.redo()\n\t\t\tthis.#undo.push(step)\n\t\t\tthis.#trim()\n\t\t\tthis.#changed()\n\n\t\t\treturn null\n\t\t}\n\n\t\tconst recorded = this.#recorded\n\t\tconst made = this.#take(step, this.#redo, () => this.#store.replay(step, { origin: REDO_ORIGIN }))\n\n\t\t// Changes listeners made in answer were recorded already, and came after this one.\n\t\tthis.#undo.splice(Math.max(0, this.#undo.length - (this.#recorded - recorded)), 0, step)\n\t\tthis.#trim()\n\t\tthis.#changed()\n\n\t\treturn made\n\t}\n\n\t/** Forgets every step, such as after a draft is loaded into the store. */\n\tclear(): void {\n\t\tif (this.#undo.length === 0 && this.#redo.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#undo.length = 0\n\t\tthis.#redo = []\n\t\tthis.#changed()\n\t}\n\n\t/** Called after each change to what can be undone or redone. Returns the way to stop. */\n\tsubscribe(listener: (history: UndoHistory) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Stops following the store and forgets every step. */\n\tdispose(): void {\n\t\tthis.#stop?.()\n\t\tthis.#stop = null\n\t\tthis.clear()\n\t}\n\n\t/** Runs an undo or a redo; on failure puts the step back, or clears everything on a conflict. */\n\t#take(step: StoreChange[], from: Step[], fn: () => StoreChange | null): StoreChange | null {\n\t\tthis.#making = this.#store.revision + 1\n\n\t\ttry {\n\t\t\treturn fn()\n\t\t} catch (error) {\n\t\t\tif (error instanceof TabulaError && error.code === \"conflict\") {\n\t\t\t\tthis.#undo.length = 0\n\t\t\t\tthis.#redo = []\n\t\t\t\tthis.#changed()\n\t\t\t} else {\n\t\t\t\tfrom.push(step)\n\t\t\t}\n\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tthis.#making = -1\n\t\t}\n\t}\n\n\t#record(change: StoreChange): void {\n\t\tif (change.revision === this.#making) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#recorded++\n\n\t\tconst last = this.#undo[this.#undo.length - 1]\n\n\t\t// Never while a step is being taken: what a listener writes then comes after that step, not\n\t\t// inside the one below it.\n\t\tif (Array.isArray(last) && this.#making === -1 && this.#joins(change)) {\n\t\t\tlast.push(change)\n\t\t} else {\n\t\t\tthis.#undo.push([change])\n\t\t\tthis.#trim()\n\t\t}\n\n\t\tthis.#redo = []\n\t\tthis.#changed()\n\t}\n\n\t#trim(): void {\n\t\tif (this.#undo.length > this.#limit) {\n\t\t\tthis.#undo.splice(0, this.#undo.length - this.#limit)\n\t\t}\n\t}\n\n\t#changed(): void {\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n}\n\nfunction firstChange(step: Step | undefined): StoreChange | null {\n\treturn Array.isArray(step) ? (step[0] ?? null) : null\n}\n","/**\n * Decimal arithmetic for formulas, exact where floats are not: a number is an integer and a count of\n * places after the point, so 0.1 + 0.2 is 0.3 and a price times a quantity is what a till says.\n */\n\n/** `units / 10^scale`. */\nexport interface Decimal {\n\treadonly units: bigint\n\treadonly scale: number\n}\n\n/** Places after the point a division is carried to before it is rounded. */\nexport const DIVISION_PLACES = 20\n\nconst TEXT = /^([+-]?)(\\d+)(?:\\.(\\d+))?$/\n\n// BigInt(…) rather than literals such as 10n: a build that aims at an older JavaScript, as Nuxt's\n// server build does, warns that the literals may not run, though anything that runs this has BigInt.\nconst B0 = BigInt(0)\nconst B1 = BigInt(1)\nconst B2 = BigInt(2)\nconst B10 = BigInt(10)\nconst B1000 = BigInt(1000)\n\nexport const ZERO: Decimal = Object.freeze({ units: B0, scale: 0 })\nexport const ONE: Decimal = Object.freeze({ units: B1, scale: 0 })\n\n/** A decimal from text such as `\"-12.50\"`; null for anything else. */\nexport function parseDecimal(text: string): Decimal | null {\n\tconst match = TEXT.exec(text.trim())\n\n\tif (!match) {\n\t\treturn null\n\t}\n\n\tconst fraction = match[3] ?? \"\"\n\tconst units = BigInt(`${match[2] ?? \"0\"}${fraction}`)\n\n\treturn simplify({ units: match[1] === \"-\" ? -units : units, scale: fraction.length })\n}\n\n/** The decimal as `normalizeDecimal` writes numbers: `\"-12.5\"`, `\"0\"`. */\nexport function decimalToText(value: Decimal): string {\n\tconst negative = value.units < B0\n\tconst digits = (negative ? -value.units : value.units).toString().padStart(value.scale + 1, \"0\")\n\tconst whole = digits.slice(0, digits.length - value.scale)\n\tconst fraction = digits.slice(digits.length - value.scale).replace(/0+$/, \"\")\n\tconst body = fraction === \"\" ? whole : `${whole}.${fraction}`\n\n\treturn negative && body !== \"0\" ? `-${body}` : body\n}\n\nexport function add(a: Decimal, b: Decimal): Decimal {\n\tconst [x, y, scale] = aligned(a, b)\n\n\treturn simplify({ units: x + y, scale })\n}\n\nexport function subtract(a: Decimal, b: Decimal): Decimal {\n\tconst [x, y, scale] = aligned(a, b)\n\n\treturn simplify({ units: x - y, scale })\n}\n\nexport function multiply(a: Decimal, b: Decimal): Decimal {\n\treturn simplify({ units: a.units * b.units, scale: a.scale + b.scale })\n}\n\n/** Null when dividing by zero. Carried to `DIVISION_PLACES` places, rounded half away from zero. */\nexport function divide(a: Decimal, b: Decimal): Decimal | null {\n\tif (b.units === B0) {\n\t\treturn null\n\t}\n\n\t// a / b = (a.units / 10^a.scale) / (b.units / 10^b.scale); one place more than kept, to round on.\n\tconst places = DIVISION_PLACES + 1\n\tconst numerator = a.units * B10 ** BigInt(places + b.scale)\n\tconst denominator = b.units * B10 ** BigInt(a.scale)\n\n\treturn round({ units: numerator / denominator, scale: places }, DIVISION_PLACES, \"half\")\n}\n\nexport function negate(value: Decimal): Decimal {\n\treturn { units: -value.units, scale: value.scale }\n}\n\nexport function absolute(value: Decimal): Decimal {\n\treturn value.units < B0 ? negate(value) : value\n}\n\n/** -1, 0 or 1. */\nexport function compare(a: Decimal, b: Decimal): -1 | 0 | 1 {\n\tconst [x, y] = aligned(a, b)\n\n\treturn x < y ? -1 : x > y ? 1 : 0\n}\n\nexport function isZero(value: Decimal): boolean {\n\treturn value.units === B0\n}\n\nexport function isInteger(value: Decimal): boolean {\n\treturn value.scale === 0\n}\n\n/**\n * Rounded to `places` after the point (negative rounds to tens, hundreds…). `half` is away from zero\n * at five, as Excel and nouxwell/tabula round; `up` is away from zero, `down` towards it.\n */\nexport function round(value: Decimal, places: number, mode: \"half\" | \"up\" | \"down\"): Decimal {\n\tif (value.scale <= places) {\n\t\treturn value\n\t}\n\n\tconst drop = B10 ** BigInt(value.scale - places)\n\tconst negative = value.units < B0\n\tconst magnitude = negative ? -value.units : value.units\n\tlet kept = magnitude / drop\n\tconst rest = magnitude % drop\n\n\tif (rest !== B0 && (mode === \"up\" || (mode === \"half\" && rest * B2 >= drop))) {\n\t\tkept += B1\n\t}\n\n\tconst units = negative ? -kept : kept\n\n\treturn places >= 0\n\t\t? simplify({ units, scale: places })\n\t\t: simplify({ units: units * B10 ** BigInt(-places), scale: 0 })\n}\n\n/** A whole power: exact for a whole exponent, null for any other, which the caller reports. */\nexport function power(base: Decimal, exponent: Decimal): Decimal | null {\n\tif (!isInteger(exponent) || exponent.units > B1000 || exponent.units < -B1000) {\n\t\treturn null\n\t}\n\n\tconst times = Number(exponent.units < B0 ? -exponent.units : exponent.units)\n\tlet result: Decimal = ONE\n\n\tfor (let step = 0; step < times; step++) {\n\t\tresult = multiply(result, base)\n\t}\n\n\treturn exponent.units < B0 ? divide(ONE, result) : result\n}\n\n/** Both as integers of the same scale. */\nfunction aligned(a: Decimal, b: Decimal): [bigint, bigint, number] {\n\tconst scale = Math.max(a.scale, b.scale)\n\n\treturn [a.units * B10 ** BigInt(scale - a.scale), b.units * B10 ** BigInt(scale - b.scale), scale]\n}\n\n/** Without trailing zeros after the point. */\nfunction simplify(value: Decimal): Decimal {\n\tlet { units, scale } = value\n\n\twhile (scale > 0 && units % B10 === B0) {\n\t\tunits /= B10\n\t\tscale--\n\t}\n\n\treturn Object.freeze({ units, scale })\n}\n","import type { CellValue } from \"../value.js\"\n\n/**\n * What a formula gives when it cannot give a value, as Excel writes it: `#DIV/0!` for a division by\n * zero, `#VALUE!` for a value of the wrong kind (text where a number goes), `#NAME?` for a function\n * nobody defined, `#NUM!` for a number that cannot be (a fractional power).\n */\nexport type FormulaErrorCode = \"#DIV/0!\" | \"#VALUE!\" | \"#NAME?\" | \"#NUM!\"\n\n/** A cell holding a formula's error: kept in the cell, as the value it shows, and reported as an issue. */\n// A type rather than an interface, so it is a cell value as it stands.\nexport type FormulaErrorValue = { readonly formulaError: FormulaErrorCode }\n\nexport function isFormulaError(value: CellValue): value is FormulaErrorValue {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t!Array.isArray(value) &&\n\t\ttypeof (value as Record<string, CellValue>).formulaError === \"string\"\n\t)\n}\n\nexport function formulaErrorValue(code: FormulaErrorCode): FormulaErrorValue {\n\treturn Object.freeze({ formulaError: code })\n}\n","import {\n\tabsolute,\n\tadd,\n\tcompare,\n\tdecimalToText,\n\tdivide,\n\tisZero,\n\tmultiply,\n\tONE,\n\tparseDecimal,\n\tpower,\n\tround,\n\tsubtract,\n\tZERO,\n\ttype Decimal\n} from \"./decimal.js\"\nimport type { FormulaErrorCode } from \"./error.js\"\nimport type { FormulaNode } from \"./parse.js\"\n\n/** A value while a formula is worked out. */\nexport type FormulaValue =\n\t| { readonly type: \"number\"; readonly value: Decimal }\n\t| { readonly type: \"text\"; readonly value: string }\n\t| { readonly type: \"bool\"; readonly value: boolean }\n\t| { readonly type: \"empty\" }\n\t| { readonly type: \"error\"; readonly code: FormulaErrorCode }\n\n/**\n * A function an application adds to the language, such as a margin rule of its own. It works out a\n * value from its arguments and nothing else: no request, no write, no side effect. Whatever it\n * throws becomes `#VALUE!`.\n */\nexport type FormulaFunction = (args: readonly FormulaValue[]) => FormulaValue\n\nexport interface EvaluationContext {\n\t/** A field of the row, by key. */\n\tfield(key: string): FormulaValue\n\t/** The application's functions, by name in capitals. The built-in ones cannot be replaced. */\n\treadonly functions: Readonly<Record<string, FormulaFunction>>\n}\n\nexport const EMPTY: FormulaValue = Object.freeze({ type: \"empty\" })\n\nexport function numberValue(value: Decimal): FormulaValue {\n\treturn Object.freeze({ type: \"number\", value })\n}\n\nexport function textValue(value: string): FormulaValue {\n\treturn Object.freeze({ type: \"text\", value })\n}\n\nexport function boolValue(value: boolean): FormulaValue {\n\treturn value ? TRUE : FALSE\n}\n\nexport function errorValue(code: FormulaErrorCode): FormulaValue {\n\treturn Object.freeze({ type: \"error\", code })\n}\n\n// ---------------------------------------------------------------- for an application's functions\n\n/** A number for a formula, from decimal text or a JavaScript number; `#NUM!` for one that is not finite. */\nexport function formulaNumber(value: string | number): FormulaValue {\n\tconst decimal = typeof value === \"number\" && !Number.isFinite(value) ? null : parseDecimal(String(value))\n\n\treturn decimal ? numberValue(decimal) : errorValue(\"#NUM!\")\n}\n\n/** An argument as decimal text, as numbers are kept; null when it is no number. */\nexport function numberArgument(value: FormulaValue): string | null {\n\tconst number = toNumber(value)\n\n\treturn failed(number) ? null : decimalToText(number)\n}\n\nconst TRUE: FormulaValue = Object.freeze({ type: \"bool\", value: true })\nconst FALSE: FormulaValue = Object.freeze({ type: \"bool\", value: false })\nconst HUNDRED = parseDecimal(\"100\") as Decimal\n\ntype Failed = Extract<FormulaValue, { type: \"error\" }>\n\nfunction failed(value: unknown): value is Failed {\n\treturn typeof value === \"object\" && value !== null && (value as FormulaValue).type === \"error\"\n}\n\n// ---------------------------------------------------------------- coercions, as Excel makes them\n\n/** Empty is 0, yes and no are 1 and 0, text that is a number is that number. */\nexport function toNumber(value: FormulaValue): Decimal | Failed {\n\tswitch (value.type) {\n\t\tcase \"number\":\n\t\t\treturn value.value\n\t\tcase \"empty\":\n\t\t\treturn ZERO\n\t\tcase \"bool\":\n\t\t\treturn value.value ? ONE : ZERO\n\t\tcase \"text\":\n\t\t\treturn parseDecimal(value.value) ?? (errorValue(\"#VALUE!\") as Failed)\n\t\tcase \"error\":\n\t\t\treturn value\n\t}\n}\n\nexport function toText(value: FormulaValue): string | Failed {\n\tswitch (value.type) {\n\t\tcase \"number\":\n\t\t\treturn decimalToText(value.value)\n\t\tcase \"empty\":\n\t\t\treturn \"\"\n\t\tcase \"bool\":\n\t\t\treturn value.value ? \"TRUE\" : \"FALSE\"\n\t\tcase \"text\":\n\t\t\treturn value.value\n\t\tcase \"error\":\n\t\t\treturn value\n\t}\n}\n\nexport function toBool(value: FormulaValue): boolean | Failed {\n\tswitch (value.type) {\n\t\tcase \"bool\":\n\t\t\treturn value.value\n\t\tcase \"number\":\n\t\t\treturn !isZero(value.value)\n\t\tcase \"empty\":\n\t\t\treturn false\n\t\tcase \"text\": {\n\t\t\tconst word = value.value.trim().toUpperCase()\n\n\t\t\treturn word === \"TRUE\" ? true : word === \"FALSE\" ? false : (errorValue(\"#VALUE!\") as Failed)\n\t\t}\n\t\tcase \"error\":\n\t\t\treturn value\n\t}\n}\n\n// ---------------------------------------------------------------- evaluation\n\n/** Works a formula out. Never throws: what goes wrong is an error value, as in a spreadsheet. */\nexport function evaluate(node: FormulaNode, context: EvaluationContext): FormulaValue {\n\tswitch (node.kind) {\n\t\tcase \"number\":\n\t\t\treturn numberValue(parseDecimal(node.value) ?? ZERO)\n\t\tcase \"text\":\n\t\t\treturn textValue(node.value)\n\t\tcase \"bool\":\n\t\t\treturn boolValue(node.value)\n\t\tcase \"field\":\n\t\t\treturn context.field(node.key)\n\t\tcase \"negate\":\n\t\t\treturn arithmetic(evaluate(node.operand, context), numberValue(ZERO), (a, b) => subtract(b, a))\n\t\tcase \"percent\":\n\t\t\treturn arithmetic(evaluate(node.operand, context), numberValue(HUNDRED), divide)\n\t\tcase \"binary\":\n\t\t\treturn binary(node.op, evaluate(node.left, context), evaluate(node.right, context))\n\t\tcase \"call\":\n\t\t\treturn call(node.name, node.args, context)\n\t}\n}\n\nfunction arithmetic(\n\tleft: FormulaValue,\n\tright: FormulaValue,\n\top: (a: Decimal, b: Decimal) => Decimal | null,\n\tnullError: FormulaErrorCode = \"#DIV/0!\"\n): FormulaValue {\n\tconst a = toNumber(left)\n\n\tif (failed(a)) {\n\t\treturn a\n\t}\n\n\tconst b = toNumber(right)\n\n\tif (failed(b)) {\n\t\treturn b\n\t}\n\n\tconst result = op(a, b)\n\n\treturn result === null ? errorValue(nullError) : numberValue(result)\n}\n\nfunction binary(op: string, left: FormulaValue, right: FormulaValue): FormulaValue {\n\tswitch (op) {\n\t\tcase \"+\":\n\t\t\treturn arithmetic(left, right, add)\n\t\tcase \"-\":\n\t\t\treturn arithmetic(left, right, subtract)\n\t\tcase \"*\":\n\t\t\treturn arithmetic(left, right, multiply)\n\t\tcase \"/\":\n\t\t\treturn arithmetic(left, right, divide)\n\t\tcase \"^\":\n\t\t\treturn arithmetic(left, right, power, \"#NUM!\")\n\t\tcase \"&\": {\n\t\t\tconst a = toText(left)\n\n\t\t\tif (failed(a)) {\n\t\t\t\treturn a\n\t\t\t}\n\n\t\t\tconst b = toText(right)\n\n\t\t\treturn failed(b) ? b : textValue(a + b)\n\t\t}\n\t\tdefault: {\n\t\t\tconst order = compareValues(left, right)\n\n\t\t\tif (failed(order)) {\n\t\t\t\treturn order\n\t\t\t}\n\n\t\t\treturn boolValue(\n\t\t\t\top === \"=\"\n\t\t\t\t\t? order === 0\n\t\t\t\t\t: op === \"<>\"\n\t\t\t\t\t\t? order !== 0\n\t\t\t\t\t\t: op === \"<\"\n\t\t\t\t\t\t\t? order < 0\n\t\t\t\t\t\t\t: op === \">\"\n\t\t\t\t\t\t\t\t? order > 0\n\t\t\t\t\t\t\t\t: op === \"<=\"\n\t\t\t\t\t\t\t\t\t? order <= 0\n\t\t\t\t\t\t\t\t\t: order >= 0\n\t\t\t)\n\t\t}\n\t}\n}\n\n/**\n * As Excel compares: numbers with numbers, text with text regardless of case, and across kinds\n * numbers before text before yes and no. Empty is 0, \"\" or FALSE, whatever the other side is.\n */\nfunction compareValues(left: FormulaValue, right: FormulaValue): -1 | 0 | 1 | Failed {\n\tif (left.type === \"error\") {\n\t\treturn left\n\t}\n\n\tif (right.type === \"error\") {\n\t\treturn right\n\t}\n\n\tconst a = left.type === \"empty\" ? emptyLike(right) : left\n\tconst b = right.type === \"empty\" ? emptyLike(a) : right\n\tconst rank = { number: 0, text: 1, bool: 2, empty: 0 } as const\n\n\tif (a.type !== b.type) {\n\t\treturn rank[a.type as keyof typeof rank] < rank[b.type as keyof typeof rank] ? -1 : 1\n\t}\n\n\tif (a.type === \"number\" && b.type === \"number\") {\n\t\treturn compare(a.value, b.value)\n\t}\n\n\tif (a.type === \"text\" && b.type === \"text\") {\n\t\tconst x = a.value.toLowerCase()\n\t\tconst y = b.value.toLowerCase()\n\n\t\treturn x < y ? -1 : x > y ? 1 : 0\n\t}\n\n\tif (a.type === \"bool\" && b.type === \"bool\") {\n\t\treturn a.value === b.value ? 0 : a.value ? 1 : -1\n\t}\n\n\treturn 0\n}\n\nfunction emptyLike(other: FormulaValue): FormulaValue {\n\treturn other.type === \"text\" ? textValue(\"\") : other.type === \"bool\" ? FALSE : numberValue(ZERO)\n}\n\n// ---------------------------------------------------------------- functions\n\n/** The functions every formula has. A function the application adds goes by its own name. */\nexport const FUNCTIONS: readonly string[] = [\n\t\"ABS\",\n\t\"AND\",\n\t\"AVERAGE\",\n\t\"CONCAT\",\n\t\"IF\",\n\t\"IFERROR\",\n\t\"ISBLANK\",\n\t\"LEN\",\n\t\"MAX\",\n\t\"MIN\",\n\t\"NOT\",\n\t\"OR\",\n\t\"ROUND\",\n\t\"ROUNDDOWN\",\n\t\"ROUNDUP\",\n\t\"SUM\"\n]\n\nfunction call(name: string, args: readonly FormulaNode[], context: EvaluationContext): FormulaValue {\n\t// The ones that work out only what they need, so IF(x > 0, 1 / x, 0) is never a division by zero.\n\tswitch (name) {\n\t\tcase \"IF\": {\n\t\t\tif (args.length < 2 || args.length > 3) {\n\t\t\t\treturn errorValue(\"#VALUE!\")\n\t\t\t}\n\n\t\t\tconst condition = toBool(evaluate(args[0] as FormulaNode, context))\n\n\t\t\tif (failed(condition)) {\n\t\t\t\treturn condition\n\t\t\t}\n\n\t\t\tconst branch = condition ? args[1] : args[2]\n\n\t\t\treturn branch ? evaluate(branch, context) : FALSE\n\t\t}\n\t\tcase \"IFERROR\": {\n\t\t\tif (args.length !== 2) {\n\t\t\t\treturn errorValue(\"#VALUE!\")\n\t\t\t}\n\n\t\t\tconst value = evaluate(args[0] as FormulaNode, context)\n\n\t\t\treturn value.type === \"error\" ? evaluate(args[1] as FormulaNode, context) : value\n\t\t}\n\t\tcase \"ISBLANK\":\n\t\t\treturn args.length === 1\n\t\t\t\t? boolValue(evaluate(args[0] as FormulaNode, context).type === \"empty\")\n\t\t\t\t: errorValue(\"#VALUE!\")\n\t}\n\n\tconst values = args.map(arg => evaluate(arg, context))\n\tconst builtIn = BUILT_IN[name]\n\n\tif (builtIn) {\n\t\treturn builtIn(values)\n\t}\n\n\tconst custom = context.functions[name]\n\n\tif (!custom) {\n\t\treturn errorValue(\"#NAME?\")\n\t}\n\n\ttry {\n\t\treturn custom(values)\n\t} catch {\n\t\treturn errorValue(\"#VALUE!\")\n\t}\n}\n\n/** The numbers among the arguments; an empty field is passed over, an error is the answer. */\nfunction numbers(values: readonly FormulaValue[]): Decimal[] | Failed {\n\tconst list: Decimal[] = []\n\n\tfor (const value of values) {\n\t\tif (value.type === \"empty\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst number = toNumber(value)\n\n\t\tif (failed(number)) {\n\t\t\treturn number\n\t\t}\n\n\t\tlist.push(number)\n\t}\n\n\treturn list\n}\n\nfunction rounding(mode: \"half\" | \"up\" | \"down\"): FormulaFunction {\n\treturn values => {\n\t\tif (values.length < 1 || values.length > 2) {\n\t\t\treturn errorValue(\"#VALUE!\")\n\t\t}\n\n\t\tconst value = toNumber(values[0] as FormulaValue)\n\t\tconst places = toNumber(values[1] ?? numberValue(ZERO))\n\n\t\tif (failed(value)) {\n\t\t\treturn value\n\t\t}\n\n\t\tif (failed(places)) {\n\t\t\treturn places\n\t\t}\n\n\t\t// The places are a whole number, cut towards zero as Excel cuts them.\n\t\tconst whole = Number(decimalToText(round(places, 0, \"down\")))\n\n\t\treturn numberValue(round(value, whole, mode))\n\t}\n}\n\nfunction logical(all: boolean): FormulaFunction {\n\treturn values => {\n\t\tif (values.length === 0) {\n\t\t\treturn errorValue(\"#VALUE!\")\n\t\t}\n\n\t\tlet result = all\n\n\t\tfor (const value of values) {\n\t\t\tconst truth = toBool(value)\n\n\t\t\tif (failed(truth)) {\n\t\t\t\treturn truth\n\t\t\t}\n\n\t\t\tresult = all ? result && truth : result || truth\n\t\t}\n\n\t\treturn boolValue(result)\n\t}\n}\n\nconst BUILT_IN: Readonly<Record<string, FormulaFunction>> = {\n\tSUM: values => {\n\t\tconst list = numbers(values)\n\n\t\treturn failed(list) ? list : numberValue(list.reduce(add, ZERO))\n\t},\n\tAVERAGE: values => {\n\t\tconst list = numbers(values)\n\n\t\tif (failed(list)) {\n\t\t\treturn list\n\t\t}\n\n\t\tif (list.length === 0) {\n\t\t\treturn errorValue(\"#DIV/0!\")\n\t\t}\n\n\t\tconst average = divide(list.reduce(add, ZERO), parseDecimal(String(list.length)) as Decimal)\n\n\t\treturn average === null ? errorValue(\"#DIV/0!\") : numberValue(average)\n\t},\n\tMIN: values => {\n\t\tconst list = numbers(values)\n\n\t\treturn failed(list) ? list : numberValue(list.reduce((a, b) => (compare(a, b) <= 0 ? a : b), list[0] ?? ZERO))\n\t},\n\tMAX: values => {\n\t\tconst list = numbers(values)\n\n\t\treturn failed(list) ? list : numberValue(list.reduce((a, b) => (compare(a, b) >= 0 ? a : b), list[0] ?? ZERO))\n\t},\n\tROUND: rounding(\"half\"),\n\tROUNDUP: rounding(\"up\"),\n\tROUNDDOWN: rounding(\"down\"),\n\tABS: values => {\n\t\tif (values.length !== 1) {\n\t\t\treturn errorValue(\"#VALUE!\")\n\t\t}\n\n\t\tconst value = toNumber(values[0] as FormulaValue)\n\n\t\treturn failed(value) ? value : numberValue(absolute(value))\n\t},\n\tAND: logical(true),\n\tOR: logical(false),\n\tNOT: values => {\n\t\tif (values.length !== 1) {\n\t\t\treturn errorValue(\"#VALUE!\")\n\t\t}\n\n\t\tconst truth = toBool(values[0] as FormulaValue)\n\n\t\treturn failed(truth) ? truth : boolValue(!truth)\n\t},\n\tLEN: values => {\n\t\tif (values.length !== 1) {\n\t\t\treturn errorValue(\"#VALUE!\")\n\t\t}\n\n\t\tconst text = toText(values[0] as FormulaValue)\n\n\t\treturn failed(text) ? text : numberValue(parseDecimal(String(Array.from(text).length)) as Decimal)\n\t},\n\tCONCAT: values => {\n\t\tlet text = \"\"\n\n\t\tfor (const value of values) {\n\t\t\tconst part = toText(value)\n\n\t\t\tif (failed(part)) {\n\t\t\t\treturn part\n\t\t\t}\n\n\t\t\ttext += part\n\t\t}\n\n\t\treturn textValue(text)\n\t}\n}\n","import type { RowId, RowInit, RowStore, StoreOperation } from \"../rows.js\"\nimport type { FieldSchema, ModuleSchema } from \"../schema.js\"\nimport { sameValue, type CellValue } from \"../value.js\"\nimport { decimalText } from \"../values/number.js\"\nimport { describeValue, isLookupValue } from \"../values/read.js\"\nimport { decimalToText, parseDecimal, round } from \"./decimal.js\"\nimport { formulaErrorValue, isFormulaError } from \"./error.js\"\nimport {\n\tboolValue,\n\tEMPTY,\n\tevaluate,\n\tnumberValue,\n\ttextValue,\n\ttoBool,\n\ttoNumber,\n\ttoText,\n\ttype FormulaFunction,\n\ttype FormulaValue\n} from \"./evaluate.js\"\nimport { formulaFields, parseFormula, type FormulaNode } from \"./parse.js\"\n\n/**\n * The origin of the change that works out, as an engine starts, the formulas of rows a store was\n * given as they were, where they differ. Every later formula value goes in with the change that\n * called for it.\n */\nexport const FORMULA_ORIGIN = \"formula\"\n\nexport interface FormulaEngineOptions {\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\t/**\n\t * The application's own functions, by name. They work a value out of their arguments and do\n\t * nothing else; the built-in ones cannot be replaced.\n\t */\n\treadonly functions?: Readonly<Record<string, FormulaFunction>>\n}\n\ninterface Compiled {\n\treadonly field: FieldSchema\n\treadonly tree: FormulaNode\n}\n\n/**\n * Keeps a sheet's formula fields worked out. Every change to the store works out again, inside that\n * very change, the formulas that read what it changed, for the rows it changed, each after the\n * formulas it reads: an edit and what follows from it are one change, one revision, one step to undo.\n *\n * The values are written into the store like any other, so the validator checks them, a draft keeps\n * them and the backend receives them. The backend works them out again: a value the browser worked\n * out is never to be trusted on its own. A formula that cannot be worked out leaves its error in the\n * cell, such as `#DIV/0!`, and that is an issue.\n */\nexport class FormulaEngine {\n\treadonly #schema: ModuleSchema\n\treadonly #store: RowStore\n\treadonly #functions: Readonly<Record<string, FormulaFunction>>\n\treadonly #order: readonly Compiled[]\n\t/** By field: the formulas to work out again when it changes, in order. */\n\treadonly #affected: ReadonlyMap<string, readonly Compiled[]>\n\treadonly #stop: () => void\n\n\tconstructor(options: FormulaEngineOptions) {\n\t\tthis.#schema = options.schema\n\t\tthis.#store = options.store\n\t\tthis.#functions = upperKeys(options.functions ?? {})\n\t\tthis.#order = compile(options.schema)\n\t\tthis.#affected = affected(this.#order)\n\t\tthis.#stop = this.#store.derive(operations => this.#derive(operations))\n\n\t\t// Rows the store was given as they were: what differs is written now, as a change of its own.\n\t\t// `applyFormulas` before the store is made leaves nothing to write.\n\t\tthis.#store.transact(\n\t\t\t() => {\n\t\t\t\tfor (const rowId of this.#store.rowIds()) {\n\t\t\t\t\tthis.#write(rowId, this.#order)\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ origin: FORMULA_ORIGIN }\n\t\t)\n\t}\n\n\t/** What a formula field works out to for a row as it stands now. */\n\tcompute(rowId: RowId, key: string): CellValue {\n\t\tconst formula = this.#order.find(compiled => compiled.field.key === key)\n\n\t\tif (!formula) {\n\t\t\treturn this.#store.get(rowId, key)\n\t\t}\n\n\t\treturn this.#workOut(rowId, this.#order.slice(0, this.#order.indexOf(formula) + 1)).get(key) ?? null\n\t}\n\n\t/** Stops working formulas out. */\n\tdispose(): void {\n\t\tthis.#stop()\n\t}\n\n\t/** Inside a change: the formulas its writes reach, for each row it wrote to or added. */\n\t#derive(operations: readonly StoreOperation[]): void {\n\t\tconst rows = new Map<RowId, Set<string> | \"all\">()\n\n\t\tfor (const operation of operations) {\n\t\t\tif (operation.kind === \"set\") {\n\t\t\t\tif (this.#affected.has(operation.field)) {\n\t\t\t\t\tconst changed = rows.get(operation.rowId)\n\n\t\t\t\t\tif (changed !== \"all\") {\n\t\t\t\t\t\trows.set(operation.rowId, (changed ?? new Set()).add(operation.field))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (operation.kind === \"insert\") {\n\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\trows.set(row.rowId, \"all\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const [rowId, changed] of rows) {\n\t\t\tif (this.#store.has(rowId)) {\n\t\t\t\tthis.#write(rowId, changed === \"all\" ? this.#order : this.#formulasFor(changed))\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Writes what the formulas work out to where it differs from what the row holds. */\n\t#write(rowId: RowId, formulas: readonly Compiled[]): void {\n\t\tfor (const [key, value] of this.#workOut(rowId, formulas)) {\n\t\t\tif (!sameValue(this.#store.get(rowId, key), value)) {\n\t\t\t\tthis.#store.setCell(rowId, key, value)\n\t\t\t}\n\t\t}\n\t}\n\n\t#formulasFor(changed: ReadonlySet<string>): Compiled[] {\n\t\tconst keys = new Set<string>()\n\n\t\tfor (const field of changed) {\n\t\t\tfor (const formula of this.#affected.get(field) ?? []) {\n\t\t\t\tkeys.add(formula.field.key)\n\t\t\t}\n\t\t}\n\n\t\treturn this.#order.filter(formula => keys.has(formula.field.key))\n\t}\n\n\t/** The formulas' values for a row, each seeing the ones worked out before it. */\n\t#workOut(rowId: RowId, formulas: readonly Compiled[]): Map<string, CellValue> {\n\t\tconst values = new Map<string, CellValue>()\n\t\tconst read = (key: string): CellValue =>\n\t\t\tvalues.has(key) ? (values.get(key) as CellValue) : this.#store.get(rowId, key)\n\n\t\tfor (const formula of formulas) {\n\t\t\tvalues.set(formula.field.key, workOut(formula, this.#schema, read, this.#functions))\n\t\t}\n\n\t\treturn values\n\t}\n}\n\n/**\n * Rows with their formula fields worked out, before there is a store: so a sheet opens with the\n * values in place, rather than with a first change that is no user's.\n */\nexport function applyFormulas(\n\tschema: ModuleSchema,\n\trows: readonly RowInit[],\n\tfunctions: Readonly<Record<string, FormulaFunction>> = {}\n): RowInit[] {\n\tconst order = compile(schema)\n\tconst named = upperKeys(functions)\n\n\tif (order.length === 0) {\n\t\treturn [...rows]\n\t}\n\n\treturn rows.map(row => {\n\t\tconst values: Record<string, CellValue | undefined> = { ...row.values }\n\t\tconst read = (key: string): CellValue => values[key] ?? null\n\n\t\tfor (const formula of order) {\n\t\t\tvalues[formula.field.key] = workOut(formula, schema, read, named)\n\t\t}\n\n\t\treturn { ...row, values }\n\t})\n}\n\n// ---------------------------------------------------------------- working out\n\nfunction workOut(\n\tformula: Compiled,\n\tschema: ModuleSchema,\n\tread: (key: string) => CellValue,\n\tfunctions: Readonly<Record<string, FormulaFunction>>\n): CellValue {\n\tconst result = evaluate(formula.tree, {\n\t\tfield: key => (schema.has(key) ? fromCell(schema.field(key), read(key)) : EMPTY),\n\t\tfunctions\n\t})\n\n\treturn toCell(formula.field, result)\n}\n\n/** A cell's value as a formula sees it: by its field's type, as the user does. */\nexport function fromCell(field: FieldSchema, value: CellValue): FormulaValue {\n\tif (value === null) {\n\t\treturn EMPTY\n\t}\n\n\tif (isFormulaError(value)) {\n\t\treturn { type: \"error\", code: value.formulaError }\n\t}\n\n\tswitch (field.type) {\n\t\tcase \"integer\":\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\tcase \"money\":\n\t\tcase \"percent\": {\n\t\t\tconst text = decimalText(value)\n\t\t\tconst number = text === null ? null : parseDecimal(text)\n\n\t\t\t// Text a user typed that is no number stays text, and a sum over it is #VALUE!.\n\t\t\treturn number ? numberValue(number) : textValue(describeValue(value))\n\t\t}\n\t\tcase \"bool\":\n\t\t\treturn typeof value === \"boolean\" ? boolValue(value) : textValue(describeValue(value))\n\t\tcase \"lookup\":\n\t\t\treturn textValue(isLookupValue(value) ? value.label : describeValue(value))\n\t\tcase \"options\": {\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\treturn textValue(value.map(describeValue).join(\", \"))\n\t\t\t}\n\n\t\t\tconst number = typeof value === \"number\" ? parseDecimal(describeValue(value)) : null\n\n\t\t\treturn number ? numberValue(number) : textValue(describeValue(value))\n\t\t}\n\t\tdefault:\n\t\t\treturn textValue(describeValue(value))\n\t}\n}\n\n/** A formula's result as the field it fills holds it: a number to its places, an error as itself. */\nfunction toCell(field: FieldSchema, result: FormulaValue): CellValue {\n\tif (result.type === \"error\") {\n\t\treturn formulaErrorValue(result.code)\n\t}\n\n\tif (result.type === \"empty\") {\n\t\treturn null\n\t}\n\n\tswitch (field.type) {\n\t\tcase \"integer\":\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\tcase \"money\":\n\t\tcase \"percent\": {\n\t\t\tconst number = toNumber(result)\n\n\t\t\tif (\"type\" in number) {\n\t\t\t\treturn formulaErrorValue(number.code)\n\t\t\t}\n\n\t\t\tconst places = field.type === \"integer\" ? 0 : field.decimals\n\n\t\t\treturn decimalToText(places === null ? number : round(number, places, \"half\"))\n\t\t}\n\t\tcase \"bool\": {\n\t\t\tconst truth = toBool(result)\n\n\t\t\treturn typeof truth === \"boolean\" ? truth : formulaErrorValue(truth.code)\n\t\t}\n\t\tdefault: {\n\t\t\tconst text = toText(result)\n\n\t\t\treturn typeof text === \"string\" ? text : formulaErrorValue(text.code)\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------- compiling\n\n/** The schema's formulas, each after the formulas it reads. The schema has already refused a circle. */\nfunction compile(schema: ModuleSchema): Compiled[] {\n\tconst formulas = new Map<string, Compiled & { readonly reads: readonly string[] }>()\n\n\tfor (const field of schema.fields) {\n\t\tif (field.formula !== null) {\n\t\t\tconst tree = parseFormula(field.formula)\n\n\t\t\tformulas.set(field.key, { field, tree, reads: formulaFields(tree) })\n\t\t}\n\t}\n\n\tconst order: Compiled[] = []\n\tconst placed = new Set<string>()\n\tconst place = (key: string): void => {\n\t\tconst formula = formulas.get(key)\n\n\t\tif (!formula || placed.has(key)) {\n\t\t\treturn\n\t\t}\n\n\t\tplaced.add(key)\n\t\tformula.reads.forEach(place)\n\t\torder.push({ field: formula.field, tree: formula.tree })\n\t}\n\n\tfor (const key of formulas.keys()) {\n\t\tplace(key)\n\t}\n\n\treturn order\n}\n\n/** For each field, every formula that reads it, directly or through another formula, in order. */\nfunction affected(order: readonly Compiled[]): Map<string, Compiled[]> {\n\tconst readers = new Map<string, Compiled[]>()\n\n\tfor (const formula of order) {\n\t\tfor (const key of formulaFields(formula.tree)) {\n\t\t\tconst list = readers.get(key) ?? []\n\n\t\t\tlist.push(formula)\n\t\t\treaders.set(key, list)\n\t\t}\n\t}\n\n\tconst result = new Map<string, Compiled[]>()\n\n\tfor (const key of readers.keys()) {\n\t\tconst reached = new Set<string>()\n\t\tconst visit = (field: string): void => {\n\t\t\tfor (const formula of readers.get(field) ?? []) {\n\t\t\t\tif (!reached.has(formula.field.key)) {\n\t\t\t\t\treached.add(formula.field.key)\n\t\t\t\t\tvisit(formula.field.key)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvisit(key)\n\t\tresult.set(\n\t\t\tkey,\n\t\t\torder.filter(formula => reached.has(formula.field.key))\n\t\t)\n\t}\n\n\treturn result\n}\n\nfunction upperKeys(functions: Readonly<Record<string, FormulaFunction>>): Record<string, FormulaFunction> {\n\treturn Object.fromEntries(Object.entries(functions).map(([name, fn]) => [name.toUpperCase(), fn]))\n}\n","/**\n * Help for a person writing a formula: what is being typed where the caret is, which function the\n * caret is inside and at which of its arguments, and the formula written with the fields' labels in\n * place of their keys and back. A formula editor builds its suggestions and its hints from these;\n * the formula itself, and what is saved, is unchanged.\n */\n\n/** A field and the words a person knows it by. */\nexport interface NamedField {\n\treadonly key: string\n\treadonly label: string\n}\n\n/** What is being typed at the caret, to be completed: a field after \"[\", or a function's name. */\nexport interface FormulaToken {\n\treadonly kind: \"field\" | \"function\"\n\t/** What is typed so far, without the \"[\". */\n\treadonly query: string\n\t/** The text a completion replaces: from the \"[\" or the name's first letter to where it ends. */\n\treadonly start: number\n\treadonly end: number\n}\n\n/** The function call the caret is inside, by its name in capitals, and at which argument, from 0. */\nexport interface FormulaCall {\n\treadonly name: string\n\treadonly argument: number\n}\n\nexport interface FormulaCaret {\n\treadonly token: FormulaToken | null\n\treadonly call: FormulaCall | null\n}\n\nconst NAME_START = /[A-Za-z_]/\nconst NAME_PART = /[A-Za-z0-9_.]/\n\n/**\n * Reads a formula up to the caret as the parser would: text in quotes and fields in brackets are\n * passed over, parentheses open and close calls, commas and semicolons move to the next argument.\n */\nexport function formulaCaret(text: string, caret: number): FormulaCaret {\n\tconst end = Math.max(0, Math.min(caret, text.length))\n\tconst calls: { name: string | null; argument: number }[] = []\n\tlet inText = false\n\tlet fieldAt = -1\n\tlet name = \"\"\n\n\tfor (let at = 0; at < end; at++) {\n\t\tconst char = text.charAt(at)\n\n\t\tif (inText) {\n\t\t\tif (char === '\"') {\n\t\t\t\tif (text.charAt(at + 1) === '\"' && at + 1 < end) {\n\t\t\t\t\tat++\n\t\t\t\t} else {\n\t\t\t\t\tinText = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif (fieldAt >= 0) {\n\t\t\tif (char === \"]\") {\n\t\t\t\tfieldAt = -1\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\tinText = true\n\t\t\tname = \"\"\n\t\t} else if (char === \"[\") {\n\t\t\tfieldAt = at\n\t\t\tname = \"\"\n\t\t} else if (char === \"(\") {\n\t\t\tcalls.push({ name: name === \"\" ? null : name.toUpperCase(), argument: 0 })\n\t\t\tname = \"\"\n\t\t} else if (char === \")\") {\n\t\t\tcalls.pop()\n\t\t\tname = \"\"\n\t\t} else if (char === \",\" || char === \";\") {\n\t\t\tconst innermost = calls[calls.length - 1]\n\n\t\t\tif (innermost) {\n\t\t\t\tinnermost.argument++\n\t\t\t}\n\n\t\t\tname = \"\"\n\t\t} else if (name === \"\" ? NAME_START.test(char) : NAME_PART.test(char)) {\n\t\t\tname += char\n\t\t} else {\n\t\t\tname = \"\"\n\t\t}\n\t}\n\n\treturn { token: tokenAt(text, end, inText, fieldAt, name), call: callOf(calls) }\n}\n\n/** The formula with each field it reads written by its label: \"[Aralık fiyatı] * 1.2\". */\nexport function formulaWithLabels(formula: string, fields: readonly NamedField[]): string {\n\tconst labels = new Map(fields.map(field => [field.key, field.label]))\n\n\treturn mapFields(formula, name => labels.get(name) ?? name)\n}\n\n/**\n * The formula with each field written by its key again, as it is saved. A name that is a key stays\n * one; a label names the field only when no other field has it, and is left as written otherwise,\n * for the formula to say it reads a field the schema does not have.\n */\nexport function formulaWithKeys(text: string, fields: readonly NamedField[]): string {\n\tconst keys = new Set(fields.map(field => field.key))\n\tconst byLabel = new Map<string, string | null>()\n\n\tfor (const field of fields) {\n\t\tbyLabel.set(field.label, byLabel.has(field.label) ? null : field.key)\n\t}\n\n\treturn mapFields(text, name => (keys.has(name) ? name : (byLabel.get(name) ?? name)))\n}\n\n// ---------------------------------------------------------------- inside\n\nfunction tokenAt(text: string, caret: number, inText: boolean, fieldAt: number, name: string): FormulaToken | null {\n\tif (inText) {\n\t\treturn null\n\t}\n\n\tif (fieldAt >= 0) {\n\t\t// Editing inside \"[Mevcut fi|yat]\": the completion replaces the whole reference.\n\t\tconst close = text.indexOf(\"]\", caret)\n\t\tconst open = text.indexOf(\"[\", caret)\n\t\tconst end = close >= 0 && (open < 0 || close < open) ? close + 1 : caret\n\n\t\treturn { kind: \"field\", query: text.slice(fieldAt + 1, caret), start: fieldAt, end }\n\t}\n\n\tif (name === \"\" || /^[0-9.]/.test(name)) {\n\t\treturn null\n\t}\n\n\tlet end = caret\n\n\twhile (end < text.length && NAME_PART.test(text.charAt(end))) {\n\t\tend++\n\t}\n\n\treturn { kind: \"function\", query: name, start: caret - name.length, end }\n}\n\n/** The innermost call with a name: inside \"ROUND((a - b) / c\" it is ROUND, at its first argument. */\nfunction callOf(calls: readonly { name: string | null; argument: number }[]): FormulaCall | null {\n\tfor (let index = calls.length - 1; index >= 0; index--) {\n\t\tconst call = calls[index]\n\n\t\tif (call?.name) {\n\t\t\treturn { name: call.name, argument: call.argument }\n\t\t}\n\t}\n\n\treturn null\n}\n\n/** Rewrites every field reference outside quotes; text in quotes is left as it is. */\nfunction mapFields(formula: string, map: (name: string) => string): string {\n\tlet result = \"\"\n\tlet inText = false\n\n\tfor (let at = 0; at < formula.length; at++) {\n\t\tconst char = formula.charAt(at)\n\n\t\tif (inText) {\n\t\t\tresult += char\n\n\t\t\tif (char === '\"') {\n\t\t\t\tif (formula.charAt(at + 1) === '\"') {\n\t\t\t\t\tresult += '\"'\n\t\t\t\t\tat++\n\t\t\t\t} else {\n\t\t\t\t\tinText = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\tinText = true\n\t\t\tresult += char\n\t\t\tcontinue\n\t\t}\n\n\t\tif (char === \"[\") {\n\t\t\tconst close = formula.indexOf(\"]\", at + 1)\n\n\t\t\tif (close < 0) {\n\t\t\t\tresult += formula.slice(at)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tresult += `[${map(formula.slice(at + 1, close))}]`\n\t\t\tat = close\n\t\t\tcontinue\n\t\t}\n\n\t\tresult += char\n\t}\n\n\treturn result\n}\n\n// ---------------------------------------------------------------- addresses and parts\n\nconst ADDRESS = /^([A-Za-z]{1,3})([0-9]*)$/\n\n/**\n * The formula with each cell address read as the field of its column, written with its label:\n * \"D * 1.2\" and \"D2 * 1.2\" alike are \"[Yeni fiyat] * 1.2\". A column formula reads its own row, so\n * an address's row number says nothing. `columns` are the fields as the columns stand on screen, A\n * first. A name followed by \"(\" is a function, TRUE and FALSE are values, and an address past the\n * last column is left as written, for the parser to refuse. Text in quotes and fields in brackets\n * are left as they are.\n */\nexport function formulaFromAddresses(text: string, columns: readonly NamedField[]): string {\n\tlet result = \"\"\n\tlet at = 0\n\n\twhile (at < text.length) {\n\t\tconst char = text.charAt(at)\n\n\t\tif (char === '\"') {\n\t\t\tconst close = closingQuote(text, at)\n\n\t\t\tresult += text.slice(at, close)\n\t\t\tat = close\n\t\t} else if (char === \"[\") {\n\t\t\tconst close = text.indexOf(\"]\", at + 1)\n\t\t\tconst end = close < 0 ? text.length : close + 1\n\n\t\t\tresult += text.slice(at, end)\n\t\t\tat = end\n\t\t} else if (NAME_START.test(char) && !NAME_PART.test(text.charAt(at - 1))) {\n\t\t\tlet end = at\n\n\t\t\twhile (end < text.length && NAME_PART.test(text.charAt(end))) {\n\t\t\t\tend++\n\t\t\t}\n\n\t\t\tconst name = text.slice(at, end)\n\t\t\tconst column = addressColumn(name, text.slice(end))\n\t\t\tconst field = column === null ? undefined : columns[column]\n\n\t\t\tresult += field ? `[${field.label}]` : name\n\t\t\tat = end\n\t\t} else {\n\t\t\tresult += char\n\t\t\tat++\n\t\t}\n\t}\n\n\treturn result\n}\n\n/** Each of the formula's pieces, to draw it: text as written, and each field it reads, with its label. */\nexport interface FormulaPart {\n\treadonly text: string\n\t/** The key of the field this piece reads; null for the rest of the formula. */\n\treadonly field: string | null\n}\n\n/**\n * The formula in pieces, its fields written by their labels: for a formula bar that colours each\n * field it reads, as the sheet colours its column.\n */\nexport function formulaParts(formula: string, fields: readonly NamedField[]): FormulaPart[] {\n\tconst labels = new Map(fields.map(field => [field.key, field.label]))\n\tconst parts: FormulaPart[] = []\n\tlet plain = \"\"\n\tlet at = 0\n\n\twhile (at < formula.length) {\n\t\tconst char = formula.charAt(at)\n\n\t\tif (char === '\"') {\n\t\t\tconst close = closingQuote(formula, at)\n\n\t\t\tplain += formula.slice(at, close)\n\t\t\tat = close\n\t\t} else if (char === \"[\") {\n\t\t\tconst close = formula.indexOf(\"]\", at + 1)\n\n\t\t\tif (close < 0) {\n\t\t\t\tplain += formula.slice(at)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tconst key = formula.slice(at + 1, close)\n\n\t\t\tif (plain !== \"\") {\n\t\t\t\tparts.push({ text: plain, field: null })\n\t\t\t\tplain = \"\"\n\t\t\t}\n\n\t\t\tparts.push({ text: `[${labels.get(key) ?? key}]`, field: key })\n\t\t\tat = close + 1\n\t\t} else {\n\t\t\tplain += char\n\t\t\tat++\n\t\t}\n\t}\n\n\tif (plain !== \"\") {\n\t\tparts.push({ text: plain, field: null })\n\t}\n\n\treturn parts\n}\n\n/** Where the text in quotes that opens at `at` ends: past its closing quote, a doubled quote passed over. */\nfunction closingQuote(text: string, at: number): number {\n\tlet end = at + 1\n\n\twhile (end < text.length) {\n\t\tif (text.charAt(end) === '\"') {\n\t\t\tif (text.charAt(end + 1) === '\"') {\n\t\t\t\tend += 2\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treturn end + 1\n\t\t}\n\n\t\tend++\n\t}\n\n\treturn text.length\n}\n\n/** The column an address names, from 0, or null when the name is not an address: a function, TRUE or FALSE. */\nfunction addressColumn(name: string, after: string): number | null {\n\tconst match = ADDRESS.exec(name)\n\tconst upper = name.toUpperCase()\n\n\tif (!match || after.trimStart().startsWith(\"(\") || upper === \"TRUE\" || upper === \"FALSE\") {\n\t\treturn null\n\t}\n\n\tlet column = 0\n\n\tfor (const letter of (match[1] ?? \"\").toUpperCase()) {\n\t\tcolumn = column * 26 + (letter.charCodeAt(0) - 64)\n\t}\n\n\treturn column - 1\n}\n","import type { RowOutcome } from \"./contract.js\"\nimport { Listeners } from \"./listeners.js\"\nimport type { RowId, RowStore, StoreChange } from \"./rows.js\"\nimport type { RowResults } from \"./session.js\"\nimport type { IssueSet } from \"./validation.js\"\n\n/** Whether a row is to be shown. */\nexport type RowFilter = (rowId: RowId) => boolean\n\n/** Which of two rows comes first: below zero for `a`, above zero for `b`, zero for either. */\nexport type RowOrder = (a: RowId, b: RowId) => number\n\n/** The filter `filter()` sets when given no name. */\nconst DEFAULT_FILTER = \"default\"\n\n/**\n * The rows on screen: all of them in the sheet's order, or those its filters keep, in the order a\n * sort puts them.\n *\n * Filters have names, so several stand together and each is taken away alone: the grid's column\n * filters and an issue panel's \"only rows with issues\" are two, and a row is shown when every one\n * keeps it. Filters and a sort are applied at a moment, as a spreadsheet's are. Fixing the issue that\n * put a row in the view does not take it out under the user's cursor, and changing a price does not\n * move its row; `refresh()` applies them again. Rows added meanwhile are shown, at their places in\n * the sheet's order, or after the others while a sort stands, so a paste lands where the user can\n * see it; rows removed go.\n *\n * Positions on screen are positions in the view; a row's place in the sheet is the store's.\n */\nexport class RowView {\n\treadonly store: RowStore\n\treadonly #listeners = new Listeners<RowView>()\n\treadonly #stop: () => void\n\treadonly #filters = new Map<string, RowFilter>()\n\t#order: RowOrder | null = null\n\t/** The rows shown, while a filter or a sort stands; null when every row is, in the sheet's order. */\n\t#ids: RowId[] | null = null\n\t#positions: Map<RowId, number> | null = null\n\t#version = 0\n\n\tconstructor(store: RowStore) {\n\t\tthis.store = store\n\t\tthis.#stop = store.subscribe(change => this.#onChange(change))\n\t}\n\n\t/** Moves whenever the rows shown change: a filter, a sort, a refresh, rows added or removed. */\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\t/** Whether a filter stands. */\n\tget filtered(): boolean {\n\t\treturn this.#filters.size > 0\n\t}\n\n\t/** Whether a sort stands. */\n\tget sorted(): boolean {\n\t\treturn this.#order !== null\n\t}\n\n\t/**\n\t * Whether the rows shown are other than every row in the sheet's order, filtered or sorted:\n\t * positions on screen and in the sheet then differ.\n\t */\n\tget arranged(): boolean {\n\t\treturn this.#ids !== null\n\t}\n\n\t/** How many rows are shown. */\n\tget size(): number {\n\t\treturn this.#ids?.length ?? this.store.size\n\t}\n\n\trowIdAt(index: number): RowId | undefined {\n\t\treturn this.#ids ? this.#ids[index] : this.store.rowIdAt(index)\n\t}\n\n\t/** Where the row is shown, or -1 when it is not. */\n\tindexOf(rowId: RowId): number {\n\t\tif (!this.#ids) {\n\t\t\treturn this.store.indexOf(rowId)\n\t\t}\n\n\t\tif (!this.#positions) {\n\t\t\tthis.#positions = new Map(this.#ids.map((id, index) => [id, index]))\n\t\t}\n\n\t\treturn this.#positions.get(rowId) ?? -1\n\t}\n\n\t/**\n\t * Shows only the rows `filter` keeps, with the others that stand, as the sheet is now. A filter\n\t * of the same name is replaced.\n\t */\n\tfilter(filter: RowFilter, name: string = DEFAULT_FILTER): void {\n\t\tthis.#filters.set(name, filter)\n\t\tthis.#apply()\n\t}\n\n\t/** Puts the rows shown in this order, as the sheet is now; null goes back to the sheet's. */\n\tsort(order: RowOrder | null): void {\n\t\tif (order === null && this.#order === null) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#order = order\n\t\tthis.#apply()\n\t}\n\n\t/** Applies the filters and the sort again, to the sheet as it is now. */\n\trefresh(): void {\n\t\tif (this.#ids !== null) {\n\t\t\tthis.#apply()\n\t\t}\n\t}\n\n\t/** Takes away the filter of that name; with none, every filter and the sort, showing every row. */\n\tclear(name?: string): void {\n\t\tif (name !== undefined) {\n\t\t\tif (this.#filters.delete(name)) {\n\t\t\t\tthis.#apply()\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tif (this.#ids === null && this.#filters.size === 0 && this.#order === null) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#filters.clear()\n\t\tthis.#order = null\n\t\tthis.#apply()\n\t}\n\n\t/**\n\t * Shows a row a filter left out, in its place among the others, such as when the user goes to an\n\t * issue on it. False when there is no such row.\n\t */\n\tshow(rowId: RowId): boolean {\n\t\tif (!this.store.has(rowId)) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst ids = this.#ids\n\n\t\tif (ids && this.indexOf(rowId) < 0) {\n\t\t\tif (this.#order) {\n\t\t\t\tconst order = this.#order\n\t\t\t\tconst at = ids.findIndex(other => order(rowId, other) < 0)\n\n\t\t\t\tids.splice(at < 0 ? ids.length : at, 0, rowId)\n\t\t\t\tthis.#positions = null\n\t\t\t\tthis.#changed()\n\t\t\t} else {\n\t\t\t\tthis.#rebuild(new Set(ids).add(rowId))\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n\n\tsubscribe(listener: (view: RowView) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Stops following the store. */\n\tdispose(): void {\n\t\tthis.#stop()\n\t}\n\n\t#apply(): void {\n\t\tif (this.#filters.size === 0 && this.#order === null) {\n\t\t\tif (this.#ids !== null) {\n\t\t\t\tthis.#ids = null\n\t\t\t\tthis.#positions = null\n\t\t\t\tthis.#changed()\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tconst filters = [...this.#filters.values()]\n\t\tconst ids = this.store.rowIds().filter(rowId => filters.every(filter => filter(rowId)))\n\n\t\t// Array.prototype.sort is stable: rows the order holds equal keep the sheet's order.\n\t\tif (this.#order) {\n\t\t\tids.sort(this.#order)\n\t\t}\n\n\t\tthis.#ids = ids\n\t\tthis.#positions = null\n\t\tthis.#changed()\n\t}\n\n\t#onChange(change: StoreChange): void {\n\t\tconst shape = change.operations.some(operation => operation.kind !== \"set\")\n\n\t\tif (!shape) {\n\t\t\treturn\n\t\t}\n\n\t\tif (this.#ids) {\n\t\t\tconst shown = new Set(this.#ids)\n\n\t\t\tfor (const operation of change.operations) {\n\t\t\t\tif (operation.kind === \"insert\") {\n\t\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\t\tshown.add(row.rowId)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Rows removed drop out by themselves: the rebuild keeps only rows the store still has.\n\t\t\tthis.#rebuild(shown)\n\t\t} else {\n\t\t\tthis.#changed()\n\t\t}\n\t}\n\n\t/**\n\t * The rows in `shown` the store still has: in the sheet's order, or, while a sort stands, in the\n\t * order shown so far, with rows new to the view after them in the sheet's order.\n\t */\n\t#rebuild(shown: ReadonlySet<RowId>): void {\n\t\tif (this.#order && this.#ids) {\n\t\t\tconst kept = this.#ids.filter(rowId => this.store.has(rowId))\n\t\t\tconst present = new Set(kept)\n\t\t\tconst added = this.store.rowIds().filter(rowId => shown.has(rowId) && !present.has(rowId))\n\n\t\t\tthis.#ids = [...kept, ...added]\n\t\t} else {\n\t\t\tthis.#ids = this.store.rowIds().filter(rowId => shown.has(rowId))\n\t\t}\n\n\t\tthis.#positions = null\n\t\tthis.#changed()\n\t}\n\n\t#changed(): void {\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n}\n\n/** The rows with an issue on them, standing or waiting to be checked again. */\nexport function rowsWithIssues(issues: IssueSet): RowFilter {\n\treturn rowId => issues.hasIssues(rowId)\n}\n\n/** The rows whose last result from the backend is one of `outcomes`, such as the ones that failed. */\nexport function rowsWithResult(results: RowResults, outcomes: readonly RowOutcome[]): RowFilter {\n\treturn rowId => {\n\t\tconst outcome = results.resultOf(rowId)?.outcome\n\n\t\treturn outcome !== undefined && outcomes.includes(outcome)\n\t}\n}\n","import { add, compare, decimalToText, divide, parseDecimal, round, ZERO, type Decimal } from \"./formula/decimal.js\"\nimport { isFormulaError } from \"./formula/error.js\"\nimport type { FieldSchema, FieldType } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport { decimalText } from \"./values/number.js\"\n\n/**\n * What a status bar says about the cells selected, as a spreadsheet's does: how many hold\n * something, how many hold numbers, and their sum and average, worked out exactly.\n */\nexport interface CellSummary {\n\t/** Cells holding anything. */\n\treadonly filled: number\n\t/** Cells of a numeric field holding a number. */\n\treadonly numbers: number\n\t/** Decimal text, such as `\"3819.8\"`; null when no cell holds a number. */\n\treadonly sum: string | null\n\t/** Decimal text, to 10 places at most; null when no cell holds a number. */\n\treadonly average: string | null\n\t/** The smallest number, as decimal text; null when no cell holds a number. */\n\treadonly min: string | null\n\t/** The largest number, as decimal text; null when no cell holds a number. */\n\treadonly max: string | null\n}\n\nconst NUMERIC: ReadonlySet<FieldType> = new Set([\"integer\", \"decimal\", \"money\", \"quantity\", \"percent\"])\nconst AVERAGE_PLACES = 10\n\n/**\n * Sums the numbers among the cells given, each with its field. Only a numeric field's numbers\n * count: \"123\" typed into a text column is text, as in a spreadsheet, and so is what a cell holds\n * that could not be read as its field's number.\n */\nexport function summarizeCells(\n\tcells: Iterable<{ readonly field: FieldSchema; readonly value: CellValue }>\n): CellSummary {\n\tlet filled = 0\n\tlet numbers = 0\n\tlet sum: Decimal = ZERO\n\tlet min: Decimal | null = null\n\tlet max: Decimal | null = null\n\n\tfor (const { field, value } of cells) {\n\t\tif (value === null) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfilled++\n\n\t\tif (!NUMERIC.has(field.type) || isFormulaError(value)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst text = decimalText(value)\n\t\tconst number = text === null ? null : parseDecimal(text)\n\n\t\tif (number !== null) {\n\t\t\tnumbers++\n\t\t\tsum = add(sum, number)\n\t\t\tmin = min === null || compare(number, min) < 0 ? number : min\n\t\t\tmax = max === null || compare(number, max) > 0 ? number : max\n\t\t}\n\t}\n\n\tif (numbers === 0 || min === null || max === null) {\n\t\treturn Object.freeze({ filled, numbers, sum: null, average: null, min: null, max: null })\n\t}\n\n\tconst average = divide(sum, parseDecimal(String(numbers)) ?? ZERO)\n\n\treturn Object.freeze({\n\t\tfilled,\n\t\tnumbers,\n\t\tsum: decimalToText(sum),\n\t\taverage: average === null ? null : decimalToText(round(average, AVERAGE_PLACES, \"half\")),\n\t\tmin: decimalToText(min),\n\t\tmax: decimalToText(max)\n\t})\n}\n","import { isFormulaError } from \"../formula/error.js\"\nimport type { FieldSchema } from \"../schema.js\"\nimport type { CellValue } from \"../value.js\"\nimport { formatDate } from \"./date.js\"\nimport { decimalText, editNumber, formatNumber, symbolFor } from \"./number.js\"\nimport { datePatternOf, describeValue, isFieldValue, isLookupValue } from \"./read.js\"\nimport type { ValueSettings } from \"./settings.js\"\n\n/** How one column is drawn over its field's own way: a column's format. */\nexport interface CellFormatOptions {\n\t/** Digits after the point a number shows, in place of its field's. The value is not rounded. */\n\treadonly decimals?: number\n}\n\n/**\n * What a cell shows: its value written the sheet's way, \"1.571,41 ₺\", \"31.12.2026\", \"Evet\". A cell\n * still holding text that could not be read shows that text as it was typed.\n */\nexport function formatCell(\n\tfield: FieldSchema,\n\tvalue: CellValue,\n\tsettings: ValueSettings,\n\toptions: CellFormatOptions = {}\n): string {\n\tif (value === null) {\n\t\treturn \"\"\n\t}\n\n\t// A formula that could not be worked out shows its error, as a spreadsheet's cell does.\n\tif (isFormulaError(value)) {\n\t\treturn value.formulaError\n\t}\n\n\tif (!isFieldValue(field, value)) {\n\t\treturn describeValue(value)\n\t}\n\n\tswitch (field.type) {\n\t\tcase \"integer\":\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\tcase \"percent\":\n\t\t\treturn formatNumber(decimalText(value) ?? \"0\", options.decimals ?? digitsFor(field, settings), settings)\n\t\tcase \"money\": {\n\t\t\tconst number = formatNumber(\n\t\t\t\tdecimalText(value) ?? \"0\",\n\t\t\t\toptions.decimals ?? digitsFor(field, settings),\n\t\t\t\tsettings\n\t\t\t)\n\t\t\tconst symbol = symbolFor(field.currency, settings)\n\n\t\t\tif (symbol === null || symbol === \"\") {\n\t\t\t\treturn number\n\t\t\t}\n\n\t\t\treturn settings.symbolPosition === \"before\" ? `${symbol} ${number}` : `${number} ${symbol}`\n\t\t}\n\t\tcase \"bool\":\n\t\t\treturn value ? settings.trueWord : settings.falseWord\n\t\tcase \"date\":\n\t\tcase \"datetime\":\n\t\t\treturn (\n\t\t\t\tformatDate(value as string, field.type === \"datetime\", datePatternOf(field, settings)) ??\n\t\t\t\tdescribeValue(value)\n\t\t\t)\n\t\tcase \"options\": {\n\t\t\tconst values = Array.isArray(value) ? (value as readonly CellValue[]) : [value]\n\n\t\t\treturn values\n\t\t\t\t.map(item => field.options.find(option => option.value === item)?.label ?? describeValue(item))\n\t\t\t\t.join(\", \")\n\t\t}\n\t\tcase \"lookup\":\n\t\t\treturn isLookupValue(value) ? value.label : describeValue(value)\n\t\tcase \"string\":\n\t\t\treturn describeValue(value)\n\t}\n}\n\n/**\n * The text an editor opens with. A number keeps every digit it has and drops the grouping and the\n * symbol, \"1571,4125\" rather than \"1.571,41 ₺\", so editing it never rounds it. The rest is what the\n * cell shows. Either way, reading the text back gives the same value.\n */\nexport function editText(field: FieldSchema, value: CellValue, settings: ValueSettings): string {\n\tif (value === null) {\n\t\treturn \"\"\n\t}\n\n\tif (isFormulaError(value)) {\n\t\treturn value.formulaError\n\t}\n\n\tswitch (field.type) {\n\t\tcase \"integer\":\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\tcase \"percent\":\n\t\tcase \"money\": {\n\t\t\tconst number = isFieldValue(field, value) ? decimalText(value) : null\n\n\t\t\treturn number === null ? describeValue(value) : editNumber(number, settings)\n\t\t}\n\t\tdefault:\n\t\t\treturn formatCell(field, value, settings)\n\t}\n}\n\n/** Digits after the point: the field's own, or the settings' default for its type. An integer has none. */\nexport function digitsFor(field: FieldSchema, settings: ValueSettings): number {\n\tswitch (field.type) {\n\t\tcase \"decimal\":\n\t\t\treturn field.decimals ?? settings.decimalDigits\n\t\tcase \"quantity\":\n\t\t\treturn field.decimals ?? settings.quantityDigits\n\t\tcase \"percent\":\n\t\t\treturn field.decimals ?? settings.percentDigits\n\t\tcase \"money\":\n\t\t\treturn field.decimals ?? settings.moneyDigits\n\t\tdefault:\n\t\t\treturn 0\n\t}\n}\n","import { TabulaError } from \"../errors.js\"\nimport { compilePattern } from \"./date.js\"\nimport { fold } from \"./text.js\"\n\n/**\n * How values are written and read in one language: separators, digits, currency symbols, date\n * patterns and the words for yes and no.\n *\n * The same settings as nouxwell/tabula's `NumberSettings`, `DateSettings` and bool words, so a\n * value a template wrote in Turkish is read back here as the PHP side reads it.\n */\nexport interface ValueSettings {\n\treadonly decimalSeparator: string\n\treadonly thousandSeparator: string\n\t/** Digits after the point for a decimal field that does not set its own. */\n\treadonly decimalDigits: number\n\treadonly quantityDigits: number\n\treadonly moneyDigits: number\n\treadonly percentDigits: number\n\t/** Currency code to symbol, such as `{ TRY: \"₺\" }`. A code with no symbol is shown as the code. */\n\treadonly currencySymbols: Readonly<Record<string, string>>\n\t/** Where a money cell's symbol goes, or `none` for no symbol. */\n\treadonly symbolPosition: \"before\" | \"after\" | \"none\"\n\t/** In PHP's notation: `d.m.Y`. The tokens read are d, j, m, n, Y, y, H, G, i and s. */\n\treadonly datePattern: string\n\treadonly dateTimePattern: string\n\treadonly trueWord: string\n\treadonly falseWord: string\n}\n\nconst SYMBOLS = Object.freeze({ TRY: \"₺\", USD: \"$\", EUR: \"€\", GBP: \"£\" })\n\nexport const VALUE_SETTINGS: Readonly<{ tr: ValueSettings; en: ValueSettings }> = Object.freeze({\n\t/** nouxwell/tabula's own defaults, with the Turkish words for yes and no. */\n\ttr: Object.freeze({\n\t\tdecimalSeparator: \",\",\n\t\tthousandSeparator: \".\",\n\t\tdecimalDigits: 2,\n\t\tquantityDigits: 3,\n\t\tmoneyDigits: 2,\n\t\tpercentDigits: 2,\n\t\tcurrencySymbols: SYMBOLS,\n\t\tsymbolPosition: \"after\",\n\t\tdatePattern: \"d.m.Y\",\n\t\tdateTimePattern: \"d.m.Y H:i\",\n\t\ttrueWord: \"Evet\",\n\t\tfalseWord: \"Hayır\"\n\t}),\n\t/** English separators, with ISO dates: \"05/03\" reads two ways in English, \"2026-03-05\" one. */\n\ten: Object.freeze({\n\t\tdecimalSeparator: \".\",\n\t\tthousandSeparator: \",\",\n\t\tdecimalDigits: 2,\n\t\tquantityDigits: 3,\n\t\tmoneyDigits: 2,\n\t\tpercentDigits: 2,\n\t\tcurrencySymbols: SYMBOLS,\n\t\tsymbolPosition: \"before\",\n\t\tdatePattern: \"Y-m-d\",\n\t\tdateTimePattern: \"Y-m-d H:i\",\n\t\ttrueWord: \"Yes\",\n\t\tfalseWord: \"No\"\n\t})\n})\n\n/**\n * Settings from a base with some of them changed, checked.\n *\n * @throws TabulaError when the settings would make values ambiguous, such as the same separator\n * for decimals and thousands\n */\nexport function defineValueSettings(\n\tchanges: Partial<ValueSettings>,\n\tbase: ValueSettings = VALUE_SETTINGS.tr\n): ValueSettings {\n\tconst settings: ValueSettings = { ...base, ...changes }\n\tconst refuse = (message: string): never => {\n\t\tthrow new TabulaError(\"invalid_argument\", `Value settings: ${message}`)\n\t}\n\n\tif (settings.decimalSeparator === \"\" || /\\d/.test(settings.decimalSeparator + settings.thousandSeparator)) {\n\t\trefuse(\"the decimal separator must be given, and neither separator may hold a digit.\")\n\t}\n\n\tif (settings.decimalSeparator === settings.thousandSeparator) {\n\t\trefuse(`\"${settings.decimalSeparator}\" cannot separate both decimals and thousands.`)\n\t}\n\n\tfor (const name of [\"decimalDigits\", \"quantityDigits\", \"moneyDigits\", \"percentDigits\"] as const) {\n\t\tif (!Number.isSafeInteger(settings[name]) || settings[name] < 0) {\n\t\t\trefuse(`${name} must be a whole number, 0 or more; got ${settings[name]}.`)\n\t\t}\n\t}\n\n\tfor (const name of [\"datePattern\", \"dateTimePattern\"] as const) {\n\t\tif (compilePattern(settings[name]) === null) {\n\t\t\trefuse(`${name} \"${settings[name]}\" uses a letter that is not one of d, j, m, n, Y, y, H, G, i, s.`)\n\t\t}\n\t}\n\n\tif (fold(settings.trueWord) === \"\" || fold(settings.trueWord) === fold(settings.falseWord)) {\n\t\trefuse(\"the words for yes and no must be given, and must differ.\")\n\t}\n\n\treturn Object.freeze({ ...settings, currencySymbols: Object.freeze({ ...settings.currencySymbols }) })\n}\n","import { compareDecimal, normalizeDecimal } from \"./decimal.js\"\nimport { isFormulaError } from \"./formula/error.js\"\nimport type { RowId, RowStore } from \"./rows.js\"\nimport type { FieldSchema, ModuleSchema } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport { editText, formatCell } from \"./values/format.js\"\nimport { decimalText } from \"./values/number.js\"\nimport { isLookupValue } from \"./values/read.js\"\nimport { VALUE_SETTINGS, type ValueSettings } from \"./values/settings.js\"\nimport type { RowFilter, RowOrder } from \"./view.js\"\n\n/**\n * Column filters and sorting, as a spreadsheet's header offers them: which values of a column to\n * show, or a range of its numbers or dates, and the order of the rows by one column.\n *\n * Values are told apart by what they are, not by how they are written: 12.5 and \"12.50\" are one\n * number, a record is its id, an option its value. How a value is shown is the grid's business.\n */\n\n/**\n * What a column keeps. `values`: the rows whose value has one of these keys (`filterKey()`; \"\" for\n * an empty cell). `range`: the rows whose number or date lies between `from` and `to`, both kept,\n * either open; written as the cell holds them, decimal text or ISO dates.\n */\nexport type ColumnCondition =\n\t| { readonly kind: \"values\"; readonly keys: readonly string[] }\n\t| { readonly kind: \"range\"; readonly from: string | null; readonly to: string | null }\n\n/** Conditions by field key; a row is shown when it meets every one. */\nexport type ColumnFilters = Readonly<Record<string, ColumnCondition>>\n\nexport interface ColumnSort {\n\treadonly key: string\n\treadonly direction: \"asc\" | \"desc\"\n}\n\n/** One value a column holds, for a filter's list: its key, the value itself, and how many rows hold it. */\nexport interface DistinctValue {\n\treadonly key: string\n\t/** The value as the cell holds it, for the grid to write the sheet's way. Null for empty cells. */\n\treadonly value: CellValue\n\treadonly count: number\n}\n\nconst NUMERIC: ReadonlySet<FieldSchema[\"type\"]> = new Set([\"integer\", \"decimal\", \"money\", \"quantity\", \"percent\"])\nconst DATES: ReadonlySet<FieldSchema[\"type\"]> = new Set([\"date\", \"datetime\"])\n\n/** Whether a field's filter can be a range: numbers and dates. */\nexport function hasRange(field: FieldSchema): boolean {\n\treturn NUMERIC.has(field.type) || DATES.has(field.type)\n}\n\n/**\n * What a value is filtered and listed by. Two values with one key are the same to a filter: 12.5\n * and \"12.50\", a record by its id. \"\" is an empty cell.\n */\nexport function filterKey(field: FieldSchema, value: CellValue): string {\n\tif (value === null) {\n\t\treturn \"\"\n\t}\n\n\tif (isFormulaError(value)) {\n\t\treturn `error:${value.formulaError}`\n\t}\n\n\tif (field.type === \"lookup\") {\n\t\treturn isLookupValue(value) ? `id:${typeof value.id}:${value.id}` : `text:${String(value)}`\n\t}\n\n\tif (NUMERIC.has(field.type)) {\n\t\tconst number = decimalText(value)\n\t\tconst normal = number === null ? null : normalizeDecimal(number)\n\n\t\tif (normal !== null) {\n\t\t\treturn `number:${normal}`\n\t\t}\n\t}\n\n\tif (typeof value === \"boolean\") {\n\t\treturn value ? \"true\" : \"false\"\n\t}\n\n\treturn typeof value === \"string\" ? `text:${value}` : `json:${JSON.stringify(value)}`\n}\n\n/**\n * The keys a cell is filtered by: its value's, or for a cell of several options one per option, so\n * a filter keeping \"Web\" keeps every row that holds it, whatever else it holds. \"\" for an empty cell.\n */\nexport function filterKeys(field: FieldSchema, value: CellValue): string[] {\n\treturn eachValue(field, value).map(([key]) => key)\n}\n\n/** A cell's values with their keys: one, or one per option of a multi-select cell. */\nfunction eachValue(field: FieldSchema, value: CellValue): (readonly [string, CellValue])[] {\n\tif (field.type === \"options\" && field.multiple && Array.isArray(value)) {\n\t\tconst items = [...new Set(value as readonly CellValue[])]\n\n\t\treturn items.length === 0 ? [[\"\", null]] : items.map(item => [filterKey(field, item), item] as const)\n\t}\n\n\treturn [[filterKey(field, value), value]]\n}\n\n/** Shows the rows that meet every column's condition; a key the schema no longer has is passed over. */\nexport function rowsMatching(store: RowStore, schema: ModuleSchema, filters: ColumnFilters): RowFilter {\n\tconst tests: ((rowId: RowId) => boolean)[] = []\n\n\tfor (const [key, condition] of Object.entries(filters)) {\n\t\tif (!schema.has(key)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst field = schema.field(key)\n\n\t\tif (condition.kind === \"values\") {\n\t\t\tconst keys = new Set(condition.keys)\n\n\t\t\ttests.push(rowId => filterKeys(field, store.get(rowId, key)).some(each => keys.has(each)))\n\t\t} else {\n\t\t\ttests.push(rowId => inRange(field, store.get(rowId, key), condition.from, condition.to))\n\t\t}\n\t}\n\n\treturn rowId => tests.every(test => test(rowId))\n}\n\nexport interface SearchOptions {\n\t/** How values are written, to find them as the cells show them. Turkish by default. */\n\treadonly settings?: ValueSettings\n\t/** Whose rules lower the case, such as \"tr\", where \"I\" lowers to \"ı\". \"tr\" by default. */\n\treadonly locale?: string\n\t/** The fields searched; every field of the schema by default. */\n\treadonly fields?: readonly string[]\n}\n\n/**\n * The rows where a cell holds `text`, as the cell shows it (\"1.533,80\", \"Mağaza, Web\", the record's\n * name), case aside. A number is found as it is typed too, \"1533,8\". Empty text keeps every row.\n */\nexport function rowsContaining(\n\tstore: RowStore,\n\tschema: ModuleSchema,\n\ttext: string,\n\toptions: SearchOptions = {}\n): RowFilter {\n\tconst locale = options.locale ?? \"tr\"\n\tconst settings = options.settings ?? VALUE_SETTINGS.tr\n\tconst needle = text.trim().toLocaleLowerCase(locale)\n\tconst fields = (options.fields ?? schema.fields.map(field => field.key))\n\t\t.filter(key => schema.has(key))\n\t\t.map(key => schema.field(key))\n\n\tif (needle === \"\") {\n\t\treturn () => true\n\t}\n\n\tconst holds = (written: string): boolean => written.toLocaleLowerCase(locale).includes(needle)\n\n\treturn rowId =>\n\t\tfields.some(field => {\n\t\t\tconst value = store.get(rowId, field.key)\n\n\t\t\treturn (\n\t\t\t\tvalue !== null &&\n\t\t\t\t(holds(formatCell(field, value, settings)) ||\n\t\t\t\t\t(NUMERIC.has(field.type) && holds(editText(field, value, settings))))\n\t\t\t)\n\t\t})\n}\n\nfunction inRange(field: FieldSchema, value: CellValue, from: string | null, to: string | null): boolean {\n\tconst point = comparable(field, value)\n\n\tif (point === null) {\n\t\treturn false\n\t}\n\n\tconst compare = NUMERIC.has(field.type) ? compareNumbers : compareTexts\n\n\treturn (from === null || compare(point, from) >= 0) && (to === null || compare(point, to) <= 0)\n}\n\n/** A number as normalized decimal text, a date as ISO text; null for empty cells and what is neither. */\nfunction comparable(field: FieldSchema, value: CellValue): string | null {\n\tif (value === null || isFormulaError(value)) {\n\t\treturn null\n\t}\n\n\tif (NUMERIC.has(field.type)) {\n\t\tconst number = decimalText(value)\n\n\t\treturn number === null ? null : normalizeDecimal(number)\n\t}\n\n\tif (DATES.has(field.type)) {\n\t\treturn typeof value === \"string\" && /^\\d{4}-\\d{2}-\\d{2}/.test(value) ? value : null\n\t}\n\n\treturn null\n}\n\nfunction compareNumbers(a: string, b: string): number {\n\tconst left = normalizeDecimal(a)\n\tconst right = normalizeDecimal(b)\n\n\treturn left === null || right === null ? 0 : compareDecimal(left, right)\n}\n\nfunction compareTexts(a: string, b: string): number {\n\treturn a < b ? -1 : a > b ? 1 : 0\n}\n\n/** How a cell ranks before it is compared: values of the field's type, then anything else, then empty. */\nfunction rank(field: FieldSchema, value: CellValue): 0 | 1 | 2 {\n\tif (value === null) {\n\t\treturn 2\n\t}\n\n\tif (isFormulaError(value)) {\n\t\treturn 1\n\t}\n\n\tswitch (field.type) {\n\t\tcase \"integer\":\n\t\tcase \"decimal\":\n\t\tcase \"money\":\n\t\tcase \"quantity\":\n\t\tcase \"percent\":\n\t\tcase \"date\":\n\t\tcase \"datetime\":\n\t\t\treturn comparable(field, value) === null ? 1 : 0\n\t\tcase \"bool\":\n\t\t\treturn typeof value === \"boolean\" ? 0 : 1\n\t\tcase \"lookup\":\n\t\t\treturn isLookupValue(value) ? 0 : 1\n\t\tdefault:\n\t\t\treturn 0\n\t}\n}\n\n/** The text a value is ordered by among text: an option's label, a record's name, the text itself. */\nfunction sortText(field: FieldSchema, value: CellValue): string {\n\tif (field.type === \"options\") {\n\t\tconst values = Array.isArray(value) ? value : [value]\n\n\t\treturn values.map(item => field.options.find(option => option.value === item)?.label ?? String(item)).join(\", \")\n\t}\n\n\tif (isLookupValue(value)) {\n\t\treturn value.label\n\t}\n\n\tif (isFormulaError(value)) {\n\t\treturn value.formulaError\n\t}\n\n\treturn typeof value === \"string\" ? value : JSON.stringify(value)\n}\n\n/**\n * Compares two values of a field, as a sort of its column orders them: numbers by their value,\n * dates in time, no before yes, text in the language's order with numbers in it read as numbers\n * (\"Ürün 9\" before \"Ürün 10\"). Empty cells come last, and cells holding something not of the\n * field's type just before them.\n */\nexport function compareValues(field: FieldSchema, a: CellValue, b: CellValue, locale = \"tr\"): number {\n\tconst rankA = rank(field, a)\n\tconst rankB = rank(field, b)\n\n\tif (rankA !== rankB) {\n\t\treturn rankA - rankB\n\t}\n\n\tif (rankA === 2) {\n\t\treturn 0\n\t}\n\n\tif (rankA === 0) {\n\t\tif (NUMERIC.has(field.type)) {\n\t\t\treturn compareNumbers(comparable(field, a) ?? \"0\", comparable(field, b) ?? \"0\")\n\t\t}\n\n\t\tif (DATES.has(field.type)) {\n\t\t\treturn compareTexts(String(a), String(b))\n\t\t}\n\n\t\tif (field.type === \"bool\") {\n\t\t\treturn Number(a) - Number(b)\n\t\t}\n\t}\n\n\treturn sortText(field, a).localeCompare(sortText(field, b), locale, { numeric: true, sensitivity: \"base\" })\n}\n\n/**\n * The rows in the order of one column. Whichever way it goes, the cells that hold something not of\n * the column's type and then the empty ones stay last: a descending sort of prices puts the dearest\n * first, and \"on iki\" typed into a price and the rows with no price still at the end, where what\n * needs fixing is found together.\n */\nexport function rowOrder(store: RowStore, schema: ModuleSchema, sort: ColumnSort, locale = \"tr\"): RowOrder {\n\tconst field = schema.field(sort.key)\n\tconst sign = sort.direction === \"asc\" ? 1 : -1\n\n\treturn (a, b) => {\n\t\tconst left = store.get(a, field.key)\n\t\tconst right = store.get(b, field.key)\n\t\tconst rankLeft = rank(field, left)\n\t\tconst rankRight = rank(field, right)\n\n\t\tif (rankLeft !== rankRight) {\n\t\t\treturn rankLeft - rankRight\n\t\t}\n\n\t\treturn rankLeft === 2 ? 0 : sign * compareValues(field, left, right, locale)\n\t}\n}\n\n/**\n * The values a column holds among these rows, each once with how many rows hold it, in the order a\n * sort of the column would put them, the empty cells last. `limit` keeps a list of 50,000 different\n * notes from being built whole: the rest are counted in `more`.\n */\nexport function distinctValues(\n\tstore: RowStore,\n\tfield: FieldSchema,\n\trowIds: Iterable<RowId>,\n\toptions: { readonly limit?: number; readonly locale?: string } = {}\n): { readonly values: readonly DistinctValue[]; readonly more: number } {\n\tconst found = new Map<string, { value: CellValue; count: number }>()\n\n\tfor (const rowId of rowIds) {\n\t\tconst value = store.get(rowId, field.key)\n\n\t\t// A cell holding several options counts once under each of them.\n\t\tfor (const [key, each] of eachValue(field, value)) {\n\t\t\tconst entry = found.get(key)\n\n\t\t\tif (entry) {\n\t\t\t\tentry.count++\n\t\t\t} else {\n\t\t\t\tfound.set(key, { value: each, count: 1 })\n\t\t\t}\n\t\t}\n\t}\n\n\tconst locale = options.locale ?? \"tr\"\n\tconst all = [...found.entries()]\n\t\t.map(([key, entry]) => ({ key, value: entry.value, count: entry.count }))\n\t\t.sort((a, b) => compareValues(field, a.value, b.value, locale))\n\tconst limit = options.limit ?? 1000\n\n\treturn { values: all.slice(0, limit), more: Math.max(0, all.length - limit) }\n}\n","import { add, compare, decimalToText, multiply, parseDecimal, subtract, type Decimal } from \"./formula/decimal.js\"\nimport type { FieldSchema, FieldType } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport { isIsoDate } from \"./values/date.js\"\nimport { decimalText } from \"./values/number.js\"\n\n/**\n * Filling cells from those selected, as a spreadsheet's fill handle does: the values go on as a\n * series where they make one, and repeat where they do not.\n *\n * - **One number** is copied; **one date** goes on a day at a time; **one text ending in a number**\n * counts on, \"Ürün 9\" to \"Ürün 10\", keeping leading zeros, \"A009\" to \"A010\".\n * - **Several values with one step between them** go on by that step: 10, 20 gives 30, 40; dates a\n * week apart go on by weeks, and dates on one day of the month go on by months.\n * - **Anything else repeats**, in its order: yes, no, yes, no; or 1, 3, 2, 1, 3, 2.\n *\n * A number is worked out exactly, as decimal text, so 0.1 steps never drift to 0.30000000000000004.\n */\n\n/**\n * - `auto`: as above.\n * - `alternate`: as with Ctrl held in Excel. A fill that would count repeats instead, and one number,\n * which would be copied, counts by one.\n * - `copy`: the values repeat, whatever they are, as Ctrl+D fills.\n */\nexport type FillMode = \"auto\" | \"alternate\" | \"copy\"\n\nexport interface FillOptions {\n\t/** Filling up or left: the values are worked out going back from the first. */\n\treadonly backward?: boolean\n\treadonly mode?: FillMode\n}\n\nconst NUMERIC: ReadonlySet<FieldType> = new Set([\"integer\", \"decimal\", \"money\", \"quantity\", \"percent\"])\nconst DAY_MS = 86_400_000\nconst DAY_SECONDS = 86_400\n/** Text that ends in a number: what comes before it, and its digits. */\nconst TRAILING_NUMBER = /^([\\s\\S]*?)(\\d+)$/\nconst ISO_PARTS = /^(\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}):(\\d{2}):(\\d{2}))?$/\n\n/**\n * The values for `count` cells beyond those given, in the field's own form. `values[0]` goes next\n * to the source and each after it one cell further away: below the last value, or, `backward`,\n * above the first.\n *\n * `field` is the field of every cell given, or null when they come from fields of different kinds,\n * as a fill across columns can: the values then repeat.\n */\nexport function fillValues(\n\tfield: FieldSchema | null,\n\tsource: readonly CellValue[],\n\tcount: number,\n\toptions: FillOptions = {}\n): CellValue[] {\n\tconst length = source.length\n\tconst backward = options.backward ?? false\n\tconst mode = options.mode ?? \"auto\"\n\n\tif (length === 0 || count <= 0) {\n\t\treturn []\n\t}\n\n\tconst series = mode === \"copy\" || field === null ? null : seriesOf(field, source, mode)\n\n\treturn Array.from({ length: count }, (_, index) => {\n\t\tconst distance = index + 1\n\n\t\tif (series !== null) {\n\t\t\treturn series(backward ? -distance : length - 1 + distance)\n\t\t}\n\n\t\t// Repeating backwards keeps the pattern in step: the cell above the first holds the last.\n\t\treturn source[backward ? (length - (distance % length)) % length : index % length] ?? null\n\t})\n}\n\n/**\n * The value at a place in the series the source starts, the first value at 0, or null when the\n * values make none and are to repeat.\n */\ntype Series = (place: number) => CellValue\n\nfunction seriesOf(field: FieldSchema, source: readonly CellValue[], mode: FillMode): Series | null {\n\tif (NUMERIC.has(field.type)) {\n\t\treturn numberSeries(source, mode)\n\t}\n\n\tif (field.type === \"date\" || field.type === \"datetime\") {\n\t\treturn dateSeries(source, field.type === \"datetime\", mode)\n\t}\n\n\tif (field.type === \"string\") {\n\t\treturn textSeries(source, mode)\n\t}\n\n\treturn null\n}\n\nfunction numberSeries(source: readonly CellValue[], mode: FillMode): Series | null {\n\tconst numbers = decimals(source.map(value => decimalText(value)))\n\n\tif (numbers === null) {\n\t\treturn null\n\t}\n\n\tconst step = stepOf(numbers, mode)\n\n\treturn step === null ? null : place => decimalToText(at(numbers, step, place))\n}\n\n/**\n * Text that ends in a number counts on its own, where a number does not: \"Ürün 9\" is a name in a\n * row of names. Text that is only digits fills as a number does.\n */\nfunction textSeries(source: readonly CellValue[], mode: FillMode): Series | null {\n\tconst matches = source.map(value => (typeof value === \"string\" ? TRAILING_NUMBER.exec(value) : null))\n\tconst prefix = matches[0]?.[1]\n\n\tif (prefix === undefined || matches.some(match => match === null || match[1] !== prefix)) {\n\t\treturn null\n\t}\n\n\tconst digits = matches.map(match => match?.[2] ?? \"\")\n\tconst numbers = decimals(digits)\n\t// Alone, a number with a name before it counts; digits alone are copied, as a number is.\n\tconst step = numbers === null ? null : stepOf(numbers, mode, prefix !== \"\")\n\n\tif (numbers === null || step === null) {\n\t\treturn null\n\t}\n\n\t// \"A009\" keeps its three digits; \"A9\" grows to \"A10\" as a number does.\n\tconst width = digits.some(text => text.length > 1 && text.startsWith(\"0\"))\n\t\t? Math.max(...digits.map(d => d.length))\n\t\t: 0\n\n\treturn place => {\n\t\t// As Excel does, a count going below zero is written without its sign: \"Hafta 1\", \"Hafta 0\", \"Hafta 1\".\n\t\tconst number = decimalToText(at(numbers, step, place)).replace(/^-/, \"\")\n\n\t\treturn prefix + number.padStart(width, \"0\")\n\t}\n}\n\nfunction dateSeries(source: readonly CellValue[], withTime: boolean, mode: FillMode): Series | null {\n\tconst dates = source.map(value => (isIsoDate(value, withTime) ? partsOf(value) : null))\n\n\tif (dates.some(date => date === null)) {\n\t\treturn null\n\t}\n\n\tconst parts = dates as DateParts[]\n\tconst months = monthSeries(parts, withTime, mode)\n\n\tif (months !== null) {\n\t\treturn months\n\t}\n\n\t// One date goes on a day at a time; several, by the days (or seconds) between them.\n\tconst points = decimals(parts.map(date => String(withTime ? secondOf(date) : dayOf(date))))\n\tconst step = points === null ? null : stepOf(points, mode, true, withTime ? DAY_SECONDS : 1)\n\n\tif (points === null || step === null) {\n\t\treturn null\n\t}\n\n\treturn place => {\n\t\tconst point = Number(decimalToText(at(points, step, place)))\n\n\t\treturn withTime ? isoOf(fromSecond(point), true) : isoOf(fromDay(point), false)\n\t}\n}\n\n/**\n * Dates on one day of the month, at one time, months apart: the 15th of January, then of February,\n * go on to the 15th of March, as a day count could not. A month too short for the day ends the\n * date at its last: 31 January a month on is 28 February.\n */\nfunction monthSeries(dates: readonly DateParts[], withTime: boolean, mode: FillMode): Series | null {\n\tconst first = dates[0]\n\n\tif (mode !== \"auto\" || dates.length < 2 || first === undefined) {\n\t\treturn null\n\t}\n\n\tconst sameDay = dates.every(\n\t\tdate =>\n\t\t\tdate.day === first.day &&\n\t\t\tdate.hour === first.hour &&\n\t\t\tdate.minute === first.minute &&\n\t\t\tdate.second === first.second\n\t)\n\tconst months = dates.map(date => date.year * 12 + date.month - 1)\n\tconst step = (months[1] ?? 0) - (months[0] ?? 0)\n\n\tif (!sameDay || step === 0 || months.some((month, index) => month - (months[0] ?? 0) !== step * index)) {\n\t\treturn null\n\t}\n\n\treturn place => {\n\t\tconst month = (months[0] ?? 0) + step * place\n\t\tconst year = Math.floor(month / 12)\n\t\tconst inMonth = (month % 12) + 1\n\t\tconst day = Math.min(first.day, daysIn(year, inMonth))\n\n\t\treturn isoOf({ ...first, year, month: inMonth, day }, withTime)\n\t}\n}\n\n// ---------------------------------------------------------------- steps\n\n/**\n * The step between the values, or null when they repeat instead. One value has none of its own:\n * it counts by `single` when `counts` says a lone value of its kind does, and repeats otherwise;\n * `alternate` turns that round, and makes several values repeat.\n */\nfunction stepOf(numbers: readonly Decimal[], mode: FillMode, counts = false, single = 1): Decimal | null {\n\tconst [first, second] = numbers\n\n\tif (first === undefined) {\n\t\treturn null\n\t}\n\n\tif (second === undefined) {\n\t\tconst counting = mode === \"alternate\" ? !counts : counts\n\n\t\treturn counting ? (parseDecimal(String(single)) ?? null) : null\n\t}\n\n\tif (mode === \"alternate\") {\n\t\treturn null\n\t}\n\n\tconst step = subtract(second, first)\n\n\tfor (let index = 2; index < numbers.length; index++) {\n\t\tconst value = numbers[index]\n\t\tconst before = numbers[index - 1]\n\n\t\tif (value === undefined || before === undefined || compare(subtract(value, before), step) !== 0) {\n\t\t\treturn null\n\t\t}\n\t}\n\n\treturn step\n}\n\n/** The value at a place in the series: the first plus so many steps. */\nfunction at(numbers: readonly Decimal[], step: Decimal, place: number): Decimal {\n\tconst first = numbers[0] as Decimal\n\n\treturn add(first, multiply(step, parseDecimal(String(place)) as Decimal))\n}\n\nfunction decimals(texts: readonly (string | null)[]): Decimal[] | null {\n\tconst numbers: Decimal[] = []\n\n\tfor (const text of texts) {\n\t\tconst number = text === null ? null : parseDecimal(text)\n\n\t\tif (number === null) {\n\t\t\treturn null\n\t\t}\n\n\t\tnumbers.push(number)\n\t}\n\n\treturn numbers\n}\n\n// ---------------------------------------------------------------- dates\n\ninterface DateParts {\n\treadonly year: number\n\treadonly month: number\n\treadonly day: number\n\treadonly hour: number\n\treadonly minute: number\n\treadonly second: number\n}\n\nfunction partsOf(iso: string): DateParts | null {\n\tconst match = ISO_PARTS.exec(iso)\n\n\tif (!match) {\n\t\treturn null\n\t}\n\n\tconst [, year, month, day, hour = \"0\", minute = \"0\", second = \"0\"] = match\n\n\treturn {\n\t\tyear: Number(year),\n\t\tmonth: Number(month),\n\t\tday: Number(day),\n\t\thour: Number(hour),\n\t\tminute: Number(minute),\n\t\tsecond: Number(second)\n\t}\n}\n\n/** Days since 1970-01-01. Set field by field: Date.UTC reads the years 0 to 99 as 1900 to 1999. */\nfunction dayOf(date: DateParts): number {\n\tconst moment = new Date(0)\n\n\tmoment.setUTCFullYear(date.year, date.month - 1, date.day)\n\n\treturn Math.round(moment.getTime() / DAY_MS)\n}\n\nfunction secondOf(date: DateParts): number {\n\treturn dayOf(date) * DAY_SECONDS + date.hour * 3600 + date.minute * 60 + date.second\n}\n\nfunction fromDay(day: number): DateParts {\n\tconst moment = new Date(day * DAY_MS)\n\n\treturn {\n\t\tyear: moment.getUTCFullYear(),\n\t\tmonth: moment.getUTCMonth() + 1,\n\t\tday: moment.getUTCDate(),\n\t\thour: 0,\n\t\tminute: 0,\n\t\tsecond: 0\n\t}\n}\n\nfunction fromSecond(second: number): DateParts {\n\tconst day = Math.floor(second / DAY_SECONDS)\n\tconst rest = second - day * DAY_SECONDS\n\n\treturn {\n\t\t...fromDay(day),\n\t\thour: Math.floor(rest / 3600),\n\t\tminute: Math.floor((rest % 3600) / 60),\n\t\tsecond: rest % 60\n\t}\n}\n\nfunction daysIn(year: number, month: number): number {\n\treturn fromDay(dayOf({ year, month: month + 1, day: 1, hour: 0, minute: 0, second: 0 }) - 1).day\n}\n\n/** ISO text, or null past what a cell can hold: the years 1 to 9999. */\nfunction isoOf(date: DateParts, withTime: boolean): string | null {\n\tif (date.year < 1 || date.year > 9999) {\n\t\treturn null\n\t}\n\n\tconst two = (value: number): string => String(value).padStart(2, \"0\")\n\tconst day = `${String(date.year).padStart(4, \"0\")}-${two(date.month)}-${two(date.day)}`\n\n\treturn withTime ? `${day}T${two(date.hour)}:${two(date.minute)}:${two(date.second)}` : day\n}\n","import { normalizeDecimal } from \"./decimal.js\"\nimport { TabulaError } from \"./errors.js\"\nimport {\n\tadd,\n\tcompare,\n\tdecimalToText,\n\tdivide,\n\tmultiply,\n\tONE,\n\tparseDecimal,\n\tround,\n\tZERO,\n\ttype Decimal\n} from \"./formula/decimal.js\"\nimport type { FieldSchema } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport { digitsFor } from \"./values/format.js\"\nimport { decimalText } from \"./values/number.js\"\nimport { canonicalValue } from \"./values/read.js\"\nimport { VALUE_SETTINGS, type ValueSettings } from \"./values/settings.js\"\n\n/**\n * A change made to many numbers at once, as a price list is raised. Amounts are decimal text, so a\n * rise of 5% is worked out exactly.\n *\n * - `percent`: `by` percent more: \"5\" raises by 5%, \"-10\" takes a tenth off.\n * - `add`: `by` more: \"10\", \"-2.5\".\n * - `round`: to a multiple of `step` (\"0.05\", \"1\", \"10\"): the nearest (`half`, the default, with a\n * five going away from zero), the one away from zero (`up`), or the one towards it (`down`).\n */\nexport type Adjustment =\n\t| { readonly kind: \"percent\"; readonly by: string }\n\t| { readonly kind: \"add\"; readonly by: string }\n\t| { readonly kind: \"round\"; readonly step: string; readonly mode?: \"half\" | \"up\" | \"down\" }\n\nconst NUMERIC: ReadonlySet<FieldSchema[\"type\"]> = new Set([\"integer\", \"decimal\", \"money\", \"quantity\", \"percent\"])\nconst HUNDRED: Decimal = Object.freeze({ units: BigInt(100), scale: 0 })\n\n/** Whether the field holds numbers an adjustment can change. */\nexport function isAdjustable(field: FieldSchema): boolean {\n\treturn NUMERIC.has(field.type)\n}\n\n/**\n * The value a number cell holds after `adjustment`, as decimal text with no more digits after the\n * point than the field shows (rounded half away from zero). Null when there is nothing to change:\n * an empty cell, one that holds no number, a field that does not hold numbers, or a value the\n * adjustment leaves as it was.\n *\n * @throws TabulaError `invalid_argument` for an amount that is not decimal text, or a step that is\n * not above zero\n */\nexport function adjustValue(\n\tfield: FieldSchema,\n\tvalue: CellValue,\n\tadjustment: Adjustment,\n\tsettings: ValueSettings = VALUE_SETTINGS.tr\n): string | null {\n\tconst operand = operandOf(adjustment)\n\n\tif (!isAdjustable(field) || value === null) {\n\t\treturn null\n\t}\n\n\tconst text = decimalText(canonicalValue(field, value, settings))\n\tconst number = text === null ? null : parseDecimal(text)\n\n\tif (text === null || number === null) {\n\t\treturn null\n\t}\n\n\tlet result: Decimal\n\n\tswitch (adjustment.kind) {\n\t\tcase \"percent\":\n\t\t\tresult = multiply(number, add(ONE, divide(operand, HUNDRED) ?? ZERO))\n\t\t\tbreak\n\t\tcase \"add\":\n\t\t\tresult = add(number, operand)\n\t\t\tbreak\n\t\tcase \"round\":\n\t\t\tresult = multiply(round(divide(number, operand) ?? ZERO, 0, adjustment.mode ?? \"half\"), operand)\n\t\t\tbreak\n\t}\n\n\tconst written = decimalToText(round(result, digitsFor(field, settings), \"half\"))\n\n\treturn written === normalizeDecimal(text) ? null : written\n}\n\n/** The amount or step, read and checked before any cell is. */\nfunction operandOf(adjustment: Adjustment): Decimal {\n\tconst text = adjustment.kind === \"round\" ? adjustment.step : adjustment.by\n\tconst operand = typeof text === \"string\" ? parseDecimal(text) : null\n\n\tif (operand === null) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_argument\",\n\t\t\t`An adjustment's ${adjustment.kind === \"round\" ? \"step\" : \"amount\"} must be decimal text such as \"5\" or \"0.05\"; got ${JSON.stringify(text)}.`\n\t\t)\n\t}\n\n\tif (adjustment.kind === \"round\" && compare(operand, ZERO) <= 0) {\n\t\tthrow new TabulaError(\"invalid_argument\", `A rounding step must be above zero; got \"${text}\".`)\n\t}\n\n\treturn operand\n}\n","import { filterKeys } from \"./filters.js\"\nimport { Listeners } from \"./listeners.js\"\nimport type { RowId, RowInit, RowStore, StoreChange } from \"./rows.js\"\nimport type { FieldSchema, ModuleSchema } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport type { RowFilter } from \"./view.js\"\nimport { canonicalValue } from \"./values/read.js\"\nimport { VALUE_SETTINGS, type ValueSettings } from \"./values/settings.js\"\n\nexport interface SheetChangesOptions {\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\t/**\n\t * The rows as they were loaded, to compare the sheet with: the backend's rows, say, when a draft\n\t * is opened over them. Left out, the store as it is now.\n\t */\n\treadonly baseline?: readonly RowInit[]\n\t/**\n\t * The field that names a row in the baseline and in the sheet alike, such as its product: rows\n\t * are matched by it. Left out, rows are matched by their ids, which the baseline must then carry.\n\t */\n\treadonly key?: string\n\treadonly settings?: ValueSettings\n}\n\nexport interface ChangeSummary {\n\t/** Rows with a change, the added ones among them. */\n\treadonly rows: number\n\t/** Cells holding other than they did. */\n\treadonly cells: number\n\t/** Rows the baseline did not have. */\n\treadonly added: number\n\t/** Rows of the baseline the sheet no longer has. */\n\treadonly missing: number\n}\n\n/**\n * What the user changed since the sheet was loaded: each cell that holds other than it did, and each\n * row added since. Only fields that are sent are followed; a column worked out from others, or one\n * shown for reference, moves with them and has no change of its own.\n *\n * Values are compared as the backend would read them: 12.5 and \"12.50\" are the same, a record is its\n * id, a multi-select's options count in any order. A row whose key changes is another row: an added\n * one, while the one it was goes missing. Taking a change back takes its mark away.\n */\nexport class SheetChanges {\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\n\treadonly #fields: readonly FieldSchema[]\n\treadonly #key: FieldSchema | null\n\treadonly #settings: ValueSettings\n\treadonly #listeners = new Listeners<SheetChanges>()\n\treadonly #stop: () => void\n\t/** Each baseline row by its key, with each followed field's value as it is compared. */\n\treadonly #baseline = new Map<string, ReadonlyMap<string, string>>()\n\t/** The fields changed in each row; in a row added, every one with a value. */\n\treadonly #changed = new Map<RowId, ReadonlySet<string>>()\n\treadonly #added = new Set<RowId>()\n\t/** Each row's key now, and how many rows hold each key, for the baseline rows gone missing. */\n\treadonly #keys = new Map<RowId, string>()\n\treadonly #holding = new Map<string, number>()\n\t#version = 0\n\n\tconstructor(options: SheetChangesOptions) {\n\t\tthis.schema = options.schema\n\t\tthis.store = options.store\n\t\tthis.#settings = options.settings ?? VALUE_SETTINGS.tr\n\t\tthis.#fields = options.schema.fields.filter(field => field.submit)\n\t\tthis.#key =\n\t\t\toptions.key !== undefined && options.schema.has(options.key) ? options.schema.field(options.key) : null\n\t\tthis.#takeBaseline(options.baseline)\n\t\tthis.#stop = this.store.subscribe(change => this.#onChange(change))\n\t}\n\n\t/** Moves on every change of what is changed. */\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\t/** Whether the cell holds other than it did, or is in a row added since. */\n\tisChanged(rowId: RowId, field: string): boolean {\n\t\treturn this.#changed.get(rowId)?.has(field) ?? false\n\t}\n\n\t/** Whether anything in the row changed, or the row was added. */\n\thasChanges(rowId: RowId): boolean {\n\t\treturn this.#changed.has(rowId)\n\t}\n\n\t/** Whether the baseline had no such row. */\n\tisAdded(rowId: RowId): boolean {\n\t\treturn this.#added.has(rowId)\n\t}\n\n\t/** The rows with a change, in sheet order. */\n\tchangedRows(): RowId[] {\n\t\treturn this.store.rowIds().filter(rowId => this.#changed.has(rowId))\n\t}\n\n\tsummary(): ChangeSummary {\n\t\tlet cells = 0\n\t\tlet missing = 0\n\n\t\tfor (const fields of this.#changed.values()) {\n\t\t\tcells += fields.size\n\t\t}\n\n\t\tfor (const key of this.#baseline.keys()) {\n\t\t\tif ((this.#holding.get(key) ?? 0) === 0) {\n\t\t\t\tmissing++\n\t\t\t}\n\t\t}\n\n\t\treturn { rows: this.#changed.size, cells, added: this.#added.size, missing }\n\t}\n\n\t/** Takes the sheet as it is now as what it is compared with, such as after its changes were sent. */\n\treset(): void {\n\t\tthis.#takeBaseline(undefined)\n\t\tthis.#changedNow()\n\t}\n\n\t/** Called after each change of what is changed. Returns the way to stop. */\n\tsubscribe(listener: (changes: SheetChanges) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Stops following the store. */\n\tdispose(): void {\n\t\tthis.#stop()\n\t}\n\n\t#takeBaseline(rows: readonly RowInit[] | undefined): void {\n\t\tthis.#baseline.clear()\n\t\tthis.#changed.clear()\n\t\tthis.#added.clear()\n\t\tthis.#keys.clear()\n\t\tthis.#holding.clear()\n\n\t\tconst entries: [string, ReadonlyMap<string, string>][] = rows\n\t\t\t? rows.flatMap(row => {\n\t\t\t\t\tconst key = this.#key ? this.#compared(this.#key, row.values?.[this.#key.key] ?? null) : row.rowId\n\t\t\t\t\tconst values = new Map(\n\t\t\t\t\t\tthis.#fields.map(field => [field.key, this.#compared(field, row.values?.[field.key] ?? null)])\n\t\t\t\t\t)\n\n\t\t\t\t\treturn key === undefined ? [] : [[this.#key ? key : `id:${key}`, values] as const]\n\t\t\t\t})\n\t\t\t: this.store\n\t\t\t\t\t.rowIds()\n\t\t\t\t\t.map(rowId => [\n\t\t\t\t\t\tthis.#keyOf(rowId),\n\t\t\t\t\t\tnew Map(\n\t\t\t\t\t\t\tthis.#fields.map(field => [\n\t\t\t\t\t\t\t\tfield.key,\n\t\t\t\t\t\t\t\tthis.#compared(field, this.store.get(rowId, field.key))\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t)\n\t\t\t\t\t])\n\n\t\tfor (const [key, values] of entries) {\n\t\t\tif (!this.#baseline.has(key)) {\n\t\t\t\tthis.#baseline.set(key, values)\n\t\t\t}\n\t\t}\n\n\t\tfor (const rowId of this.store.rowIds()) {\n\t\t\tthis.#follow(rowId)\n\t\t}\n\t}\n\n\t#onChange(change: StoreChange): void {\n\t\tconst touched = new Set<RowId>()\n\n\t\tfor (const operation of change.operations) {\n\t\t\tif (operation.kind === \"set\") {\n\t\t\t\ttouched.add(operation.rowId)\n\t\t\t} else if (operation.kind === \"insert\") {\n\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\ttouched.add(row.rowId)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\tthis.#forget(row.rowId)\n\t\t\t\t\ttouched.delete(row.rowId)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const rowId of touched) {\n\t\t\tif (this.store.has(rowId)) {\n\t\t\t\tthis.#follow(rowId)\n\t\t\t}\n\t\t}\n\n\t\tthis.#changedNow()\n\t}\n\n\t/** Compares the row with the baseline's row of its key. */\n\t#follow(rowId: RowId): void {\n\t\tconst key = this.#keyOf(rowId)\n\t\tconst was = this.#keys.get(rowId)\n\n\t\tif (was !== key) {\n\t\t\tif (was !== undefined) {\n\t\t\t\tthis.#holding.set(was, (this.#holding.get(was) ?? 1) - 1)\n\t\t\t}\n\n\t\t\tthis.#keys.set(rowId, key)\n\t\t\tthis.#holding.set(key, (this.#holding.get(key) ?? 0) + 1)\n\t\t}\n\n\t\tconst base = this.#baseline.get(key)\n\t\tconst changed = new Set<string>()\n\n\t\tfor (const field of this.#fields) {\n\t\t\tconst now = this.#compared(field, this.store.get(rowId, field.key))\n\n\t\t\tif (base ? base.get(field.key) !== now : now !== EMPTY) {\n\t\t\t\tchanged.add(field.key)\n\t\t\t}\n\t\t}\n\n\t\tif (changed.size > 0) {\n\t\t\tthis.#changed.set(rowId, changed)\n\t\t} else {\n\t\t\tthis.#changed.delete(rowId)\n\t\t}\n\n\t\tif (base === undefined && changed.size > 0) {\n\t\t\tthis.#added.add(rowId)\n\t\t} else {\n\t\t\tthis.#added.delete(rowId)\n\t\t}\n\t}\n\n\t#forget(rowId: RowId): void {\n\t\tconst key = this.#keys.get(rowId)\n\n\t\tif (key !== undefined) {\n\t\t\tthis.#holding.set(key, (this.#holding.get(key) ?? 1) - 1)\n\t\t\tthis.#keys.delete(rowId)\n\t\t}\n\n\t\tthis.#changed.delete(rowId)\n\t\tthis.#added.delete(rowId)\n\t}\n\n\t#keyOf(rowId: RowId): string {\n\t\treturn this.#key ? this.#compared(this.#key, this.store.get(rowId, this.#key.key)) : `id:${rowId}`\n\t}\n\n\t/** A value as it is compared: what the backend would read it as, options in any order. */\n\t#compared(field: FieldSchema, value: CellValue | undefined): string {\n\t\tif (value === undefined || value === null || value === \"\") {\n\t\t\treturn EMPTY\n\t\t}\n\n\t\tconst read = field.type === \"lookup\" ? value : canonicalValue(field, value, this.#settings)\n\n\t\treturn JSON.stringify(filterKeys(field, read).sort())\n\t}\n\n\t#changedNow(): void {\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n}\n\n/** An empty cell as it is compared; an empty list of options is one too. */\nconst EMPTY = JSON.stringify([\"\"])\n\n/** The rows with a change since the baseline, the added ones among them. */\nexport function rowsChanged(changes: SheetChanges): RowFilter {\n\treturn rowId => changes.hasChanges(rowId)\n}\n","import { TabulaError } from \"./errors.js\"\n\n/**\n * How wide a column may be, and how much of its header is shown.\n *\n * Two upper limits, kept apart on purpose. A column sized from its header stops at `maxAutoWidth`,\n * so one long header does not push the rest of the sheet off screen. A user dragging a column can go\n * on to `maxWidth`, because they asked for it.\n *\n * Characters and pixels are separate too. A header longer than `headerDisplayMaxLength` characters\n * is cut and ends in \"…\"; a shorter one that is still too wide for its column is cut by the column.\n * Either way the full header stays available as the column's tooltip, and no cell value is ever cut\n * in the data, only in how it is drawn.\n */\nexport interface ColumnSizing {\n\t/** Pixels. No column is narrower, however it is sized. */\n\treadonly minWidth: number\n\t/** Pixels. The widest a column is made on its own. */\n\treadonly maxAutoWidth: number\n\t/** Pixels. The widest a user can make a column. */\n\treadonly maxWidth: number\n\t/** Characters of a header shown before it is cut with \"…\". */\n\treadonly headerDisplayMaxLength: number\n\t/** Whether the user can drag the column's edge. */\n\treadonly resizable: boolean\n}\n\nexport const DEFAULT_COLUMN_SIZING: ColumnSizing = Object.freeze({\n\tminWidth: 100,\n\tmaxAutoWidth: 320,\n\tmaxWidth: 1000,\n\theaderDisplayMaxLength: 100,\n\tresizable: true\n})\n\n/**\n * The sizing for one column: the defaults, then each layer over the one before, such as the\n * module's settings and then the column's own.\n *\n * @throws TabulaError when the limits cannot all hold, such as a minimum above a maximum\n */\nexport function resolveColumnSizing(...layers: readonly (Partial<ColumnSizing> | undefined)[]): ColumnSizing {\n\tconst sizing: ColumnSizing = Object.assign({}, DEFAULT_COLUMN_SIZING, ...layers.filter(Boolean))\n\n\tfor (const name of [\"minWidth\", \"maxAutoWidth\", \"maxWidth\", \"headerDisplayMaxLength\"] as const) {\n\t\tconst value = sizing[name]\n\n\t\tif (typeof value !== \"number\" || !Number.isFinite(value) || value < 1) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_argument\",\n\t\t\t\t`Column sizing ${name} must be a number, 1 or more; got ${String(value)}.`\n\t\t\t)\n\t\t}\n\t}\n\n\tif (sizing.minWidth > sizing.maxAutoWidth) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_argument\",\n\t\t\t`Column sizing minWidth ${sizing.minWidth} is above maxAutoWidth ${sizing.maxAutoWidth}.`\n\t\t)\n\t}\n\n\tif (sizing.minWidth > sizing.maxWidth) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_argument\",\n\t\t\t`Column sizing minWidth ${sizing.minWidth} is above maxWidth ${sizing.maxWidth}.`\n\t\t)\n\t}\n\n\treturn Object.freeze(sizing)\n}\n\n/**\n * The header as it is drawn: whole when it fits the character limit, cut and ending in \"…\" when it\n * does not. Counted in characters a reader sees, so a cut never splits one in half.\n */\nexport function headerDisplayText(label: string, maxLength: number): string {\n\tconst characters = Array.from(label)\n\n\treturn characters.length <= maxLength ? label : `${characters.slice(0, maxLength).join(\"\")}…`\n}\n\n/** The width for content of this many pixels, kept between `minWidth` and the automatic maximum. */\nexport function autoColumnWidth(contentWidth: number, sizing: ColumnSizing): number {\n\treturn clamp(Math.ceil(contentWidth), sizing.minWidth, Math.min(sizing.maxAutoWidth, sizing.maxWidth))\n}\n\n/** A width the user set, kept between `minWidth` and `maxWidth`. */\nexport function clampColumnWidth(width: number, sizing: ColumnSizing): number {\n\treturn clamp(Math.round(width), sizing.minWidth, sizing.maxWidth)\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n\treturn Math.min(max, Math.max(min, value))\n}\n\nexport const COLUMN_ALIGNS = Object.freeze([\"left\", \"center\", \"right\"] as const)\nexport type ColumnAlign = (typeof COLUMN_ALIGNS)[number]\n\n/** The most digits after the point a column can be told to show. */\nexport const MAX_SHOWN_DECIMALS = 6\n\n/**\n * How a column's values are drawn. Never what they are: a number shown with fewer digits keeps every\n * digit it has, and the backend is sent the same value whatever is shown.\n */\nexport interface ColumnFormat {\n\t/** Where the values sit in their cells. Left out, numbers on the right and the rest on the left. */\n\treadonly align?: ColumnAlign\n\t/** Digits after the point a number column shows, 0 to `MAX_SHOWN_DECIMALS`. Left out, its field's. */\n\treadonly decimals?: number\n}\n\n/**\n * A user's arrangement of the columns, kept with their view of the sheet. Only how the columns are\n * shown: hiding a required column relaxes nothing, and its issues are still listed.\n *\n * Keys the schema does not have are passed over, so a layout saved before a column was removed\n * still applies.\n */\nexport interface ColumnLayout {\n\t/** Columns in the order to show them; those left out follow, in the schema's order. */\n\treadonly order?: readonly string[]\n\treadonly hidden?: readonly string[]\n\t/** Columns kept in place on the left while the sheet scrolls sideways. They are shown first. */\n\treadonly pinned?: readonly string[]\n\t/** How each column's values are drawn, by field key. */\n\treadonly formats?: Readonly<Record<string, ColumnFormat>>\n}\n\nexport interface ArrangedColumns<F> {\n\t/** The columns shown, in order: the pinned ones first. */\n\treadonly fields: readonly F[]\n\t/** How many of the first are pinned. */\n\treadonly pinned: number\n}\n\n/** The columns a layout shows, in the order it shows them. */\nexport function arrangeColumns<F extends { readonly key: string }>(\n\tfields: readonly F[],\n\tlayout: ColumnLayout = {}\n): ArrangedColumns<F> {\n\tconst byKey = new Map(fields.map(field => [field.key, field]))\n\tconst hidden = new Set(layout.hidden ?? [])\n\tconst pinned = new Set(layout.pinned ?? [])\n\tconst ordered: F[] = []\n\tconst seen = new Set<string>()\n\n\tfor (const key of [...(layout.order ?? []), ...fields.map(field => field.key)]) {\n\t\tconst field = byKey.get(key)\n\n\t\tif (field && !seen.has(key)) {\n\t\t\tseen.add(key)\n\t\t\tordered.push(field)\n\t\t}\n\t}\n\n\tconst shown = ordered.filter(field => !hidden.has(field.key))\n\tconst first = shown.filter(field => pinned.has(field.key))\n\n\treturn Object.freeze({\n\t\tfields: Object.freeze([...first, ...shown.filter(field => !pinned.has(field.key))]),\n\t\tpinned: first.length\n\t})\n}\n\n/** The layout with one column hidden or shown, pinned or let go. */\nexport function withColumn(\n\tlayout: ColumnLayout,\n\tkey: string,\n\tchange: { readonly hidden?: boolean; readonly pinned?: boolean }\n): ColumnLayout {\n\tconst toggle = (list: readonly string[] | undefined, on: boolean | undefined): readonly string[] | undefined => {\n\t\tif (on === undefined) {\n\t\t\treturn list\n\t\t}\n\n\t\tconst rest = (list ?? []).filter(item => item !== key)\n\n\t\treturn Object.freeze(on ? [...rest, key] : rest)\n\t}\n\n\treturn Object.freeze({\n\t\t...layout,\n\t\t...(change.hidden === undefined ? {} : { hidden: toggle(layout.hidden, change.hidden) }),\n\t\t...(change.pinned === undefined ? {} : { pinned: toggle(layout.pinned, change.pinned) })\n\t})\n}\n\n/**\n * The layout with one column drawn another way: what `change` gives replaces what the column had,\n * a property given as `undefined` goes back to the default, and `null` takes the whole format off.\n *\n * @throws TabulaError `invalid_argument` for an alignment that is not one, or decimals out of 0–6\n */\nexport function withColumnFormat(\n\tlayout: ColumnLayout,\n\tkey: string,\n\tchange: { readonly align?: ColumnAlign | undefined; readonly decimals?: number | undefined } | null\n): ColumnLayout {\n\tconst formats: Record<string, ColumnFormat> = { ...layout.formats }\n\n\tif (change === null) {\n\t\tdelete formats[key]\n\t} else {\n\t\tconst next: { align?: ColumnAlign; decimals?: number } = { ...formats[key] }\n\n\t\tfor (const name of [\"align\", \"decimals\"] as const) {\n\t\t\tif (!(name in change)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst value = change[name]\n\n\t\t\tif (value === undefined) {\n\t\t\t\tdelete next[name]\n\t\t\t} else if (name === \"align\") {\n\t\t\t\tnext.align = alignOf(value)\n\t\t\t} else {\n\t\t\t\tnext.decimals = decimalsOf(value)\n\t\t\t}\n\t\t}\n\n\t\tif (Object.keys(next).length === 0) {\n\t\t\tdelete formats[key]\n\t\t} else {\n\t\t\tformats[key] = next\n\t\t}\n\t}\n\n\tconst rest: ColumnLayout = Object.fromEntries(Object.entries(layout).filter(([name]) => name !== \"formats\"))\n\n\treturn freezeColumnLayout(Object.keys(formats).length === 0 ? rest : { ...rest, formats })\n}\n\n/**\n * A layout read from JSON, each problem reported under `path`: what a view, a draft and a template\n * keep. Undefined when there is none.\n */\nexport function readColumnLayout(\n\tinput: unknown,\n\tpath: string,\n\tproblem: (path: string, message: string) => void\n): ColumnLayout | undefined {\n\tif (input === undefined || input === null) {\n\t\treturn undefined\n\t}\n\n\tconst layout = plainObject(input)\n\n\tif (!layout) {\n\t\tproblem(path, \"must be an object.\")\n\n\t\treturn undefined\n\t}\n\n\tconst result: {\n\t\torder?: readonly string[]\n\t\thidden?: readonly string[]\n\t\tpinned?: readonly string[]\n\t\tformats?: Record<string, ColumnFormat>\n\t} = {}\n\n\tfor (const name of [\"order\", \"hidden\", \"pinned\"] as const) {\n\t\tconst value = layout[name]\n\n\t\tif (value === undefined) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif (!Array.isArray(value) || value.some(item => typeof item !== \"string\")) {\n\t\t\tproblem(`${path}.${name}`, \"must be a list of field keys.\")\n\t\t} else {\n\t\t\tresult[name] = value as string[]\n\t\t}\n\t}\n\n\tif (layout.formats !== undefined && layout.formats !== null) {\n\t\tconst formats = plainObject(layout.formats)\n\n\t\tif (!formats) {\n\t\t\tproblem(`${path}.formats`, \"must be an object of formats by field key.\")\n\t\t} else {\n\t\t\tconst read: Record<string, ColumnFormat> = {}\n\n\t\t\tfor (const [key, value] of Object.entries(formats)) {\n\t\t\t\tconst format = plainObject(value)\n\t\t\t\tconst at = `${path}.formats.${key}`\n\n\t\t\t\tif (!format) {\n\t\t\t\t\tproblem(at, 'must be an object such as { align: \"center\", decimals: 2 }.')\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tconst next: { align?: ColumnAlign; decimals?: number } = {}\n\n\t\t\t\tif (format.align !== undefined) {\n\t\t\t\t\tif ((COLUMN_ALIGNS as readonly unknown[]).includes(format.align)) {\n\t\t\t\t\t\tnext.align = format.align as ColumnAlign\n\t\t\t\t\t} else {\n\t\t\t\t\t\tproblem(`${at}.align`, `must be one of ${COLUMN_ALIGNS.join(\", \")}.`)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (format.decimals !== undefined) {\n\t\t\t\t\tif (isShownDecimals(format.decimals)) {\n\t\t\t\t\t\tnext.decimals = format.decimals\n\t\t\t\t\t} else {\n\t\t\t\t\t\tproblem(`${at}.decimals`, `must be a whole number from 0 to ${MAX_SHOWN_DECIMALS}.`)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (Object.keys(next).length > 0) {\n\t\t\t\t\tread[key] = next\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Object.keys(read).length > 0) {\n\t\t\t\tresult.formats = read\n\t\t\t}\n\t\t}\n\t}\n\n\treturn freezeColumnLayout(result)\n}\n\n/** A copy of the layout that cannot be changed, with nothing in it that it does not hold. */\nexport function freezeColumnLayout(layout: ColumnLayout): ColumnLayout {\n\treturn Object.freeze({\n\t\t...(layout.order ? { order: Object.freeze([...layout.order]) } : {}),\n\t\t...(layout.hidden ? { hidden: Object.freeze([...layout.hidden]) } : {}),\n\t\t...(layout.pinned ? { pinned: Object.freeze([...layout.pinned]) } : {}),\n\t\t...(layout.formats && Object.keys(layout.formats).length > 0\n\t\t\t? {\n\t\t\t\t\tformats: Object.freeze(\n\t\t\t\t\t\tObject.fromEntries(\n\t\t\t\t\t\t\tObject.entries(layout.formats).map(([key, format]) => [key, Object.freeze({ ...format })])\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t: {})\n\t})\n}\n\n/** The layout with its keys passed through `key`: kept, renamed, or dropped where it gives null. */\nexport function mapColumnLayout(layout: ColumnLayout, key: (key: string) => string | null): ColumnLayout {\n\tconst keys = (list: readonly string[]): string[] => list.map(key).filter((item): item is string => item !== null)\n\tconst formats: Record<string, ColumnFormat> = {}\n\n\tfor (const [from, format] of Object.entries(layout.formats ?? {})) {\n\t\tconst to = key(from)\n\n\t\tif (to !== null) {\n\t\t\tformats[to] = format\n\t\t}\n\t}\n\n\treturn freezeColumnLayout({\n\t\t...(layout.order ? { order: keys(layout.order) } : {}),\n\t\t...(layout.hidden ? { hidden: keys(layout.hidden) } : {}),\n\t\t...(layout.pinned ? { pinned: keys(layout.pinned) } : {}),\n\t\t...(Object.keys(formats).length > 0 ? { formats } : {})\n\t})\n}\n\n/** Whether two layouts draw their columns alike: the same formats on the same columns. */\nexport function sameColumnFormats(a: ColumnLayout, b: ColumnLayout): boolean {\n\tconst left = a.formats ?? {}\n\tconst right = b.formats ?? {}\n\tconst keys = Object.keys(left)\n\n\treturn (\n\t\tkeys.length === Object.keys(right).length &&\n\t\tkeys.every(key => left[key]?.align === right[key]?.align && left[key]?.decimals === right[key]?.decimals)\n\t)\n}\n\nfunction alignOf(value: unknown): ColumnAlign {\n\tif (!(COLUMN_ALIGNS as readonly unknown[]).includes(value)) {\n\t\tthrow new TabulaError(\"invalid_argument\", `A column aligns ${COLUMN_ALIGNS.join(\", \")}; got ${String(value)}.`)\n\t}\n\n\treturn value as ColumnAlign\n}\n\nfunction decimalsOf(value: unknown): number {\n\tif (!isShownDecimals(value)) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_argument\",\n\t\t\t`A column shows 0 to ${MAX_SHOWN_DECIMALS} digits after the point; got ${String(value)}.`\n\t\t)\n\t}\n\n\treturn value\n}\n\nfunction isShownDecimals(value: unknown): value is number {\n\treturn Number.isSafeInteger(value) && (value as number) >= 0 && (value as number) <= MAX_SHOWN_DECIMALS\n}\n\nfunction plainObject(value: unknown): Record<string, unknown> | null {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: null\n}\n","import {\n\tarrangeColumns,\n\tfreezeColumnLayout,\n\treadColumnLayout,\n\tsameColumnFormats,\n\ttype ColumnFormat,\n\ttype ColumnLayout\n} from \"./columns.js\"\nimport { TabulaError } from \"./errors.js\"\nimport { hasRange, type ColumnCondition, type ColumnFilters, type ColumnSort } from \"./filters.js\"\nimport type { ModuleSchema } from \"./schema.js\"\n\n/**\n * Saved views of a sheet: how a user arranged it, under a name, to come back to. A view holds what\n * the grid's models hold: the columns (order, hidden, pinned), their widths, the column filters and\n * the sort. Never rows or values: a view is how to look, not what is there.\n *\n * The views of one module are one plain JSON document, kept wherever the application keeps it: in\n * the browser, or on its server for each user. The functions here change it by returning a new one,\n * so it can sit in a Vue ref as it is.\n */\n\nexport const VIEWS_FORMAT = \"tabula-grid.views\"\nexport const VIEWS_VERSION = 1\n/** The longest a view's name may be, in characters. */\nexport const VIEW_NAME_LIMIT = 60\n\n/** How the sheet is arranged, as the grid's `columns`, `column-widths`, `filters` and `sort` hold it. */\nexport interface ViewState {\n\treadonly columns: ColumnLayout\n\treadonly columnWidths: Readonly<Record<string, number>>\n\treadonly filters: ColumnFilters\n\treadonly sort: ColumnSort | null\n}\n\nexport interface SavedView extends ViewState {\n\t/** Made by the application, so a view keeps its id through a rename. */\n\treadonly id: string\n\treadonly name: string\n}\n\nexport interface SavedViews {\n\treadonly format: typeof VIEWS_FORMAT\n\t/** The version of this format. */\n\treadonly version: typeof VIEWS_VERSION\n\treadonly module: string\n\treadonly views: readonly SavedView[]\n\t/** The view a sheet opens in; null for the sheet as its schema lays it out. */\n\treadonly defaultId: string | null\n}\n\n/** The sheet as its schema lays it out: every column in its place, no filter, no sort. */\nexport const PLAIN_VIEW: ViewState = Object.freeze({\n\tcolumns: Object.freeze({}),\n\tcolumnWidths: Object.freeze({}),\n\tfilters: Object.freeze({}),\n\tsort: null\n})\n\n/** Why a name cannot be a view's: empty, longer than `VIEW_NAME_LIMIT`, or another view's. */\nexport type ViewNameProblem = \"empty\" | \"too_long\" | \"taken\"\n\n/** A module with no views saved yet. */\nexport function emptyViews(module: string): SavedViews {\n\treturn freezeViews({ module, views: [], defaultId: null })\n}\n\n/**\n * The view as it applies to the schema now. A column the schema no longer has is passed over, and\n * so is a filter or a sort on one; a range kept on a column that no longer holds numbers or dates is\n * dropped. A view saved before the schema moved on still opens.\n */\nexport function viewFor(state: ViewState, schema: ModuleSchema): ViewState {\n\tconst known = (key: string): boolean => schema.has(key)\n\tconst keys = (list: readonly string[] | undefined): readonly string[] | undefined =>\n\t\tlist === undefined ? undefined : list.filter(known)\n\tconst columns = state.columns\n\tconst order = keys(columns.order)\n\tconst hidden = keys(columns.hidden)\n\tconst pinned = keys(columns.pinned)\n\tconst formats = Object.fromEntries(Object.entries(columns.formats ?? {}).filter(([key]) => known(key))) as Record<\n\t\tstring,\n\t\tColumnFormat\n\t>\n\tconst filters: Record<string, ColumnCondition> = {}\n\n\tfor (const [key, condition] of Object.entries(state.filters)) {\n\t\tif (known(key) && (condition.kind === \"values\" || hasRange(schema.field(key)))) {\n\t\t\tfilters[key] = condition\n\t\t}\n\t}\n\n\treturn freezeState({\n\t\tcolumns: {\n\t\t\t...(order ? { order } : {}),\n\t\t\t...(hidden ? { hidden } : {}),\n\t\t\t...(pinned ? { pinned } : {}),\n\t\t\t...(Object.keys(formats).length > 0 ? { formats } : {})\n\t\t},\n\t\tcolumnWidths: Object.fromEntries(Object.entries(state.columnWidths).filter(([key]) => known(key))),\n\t\tfilters,\n\t\tsort: state.sort && known(state.sort.key) ? state.sort : null\n\t})\n}\n\n/**\n * Whether two states show the sheet alike, against the schema: the same columns in the same places,\n * the same widths, filters and sort. A layout that only writes out the schema's own order is the\n * same as one that leaves it out, and ticked values are the same in any order. What tells a user\n * that the view on screen is no longer the one they chose.\n */\nexport function sameView(schema: ModuleSchema, a: ViewState, b: ViewState): boolean {\n\tconst left = viewFor(a, schema)\n\tconst right = viewFor(b, schema)\n\tconst arranged = (state: ViewState): string => {\n\t\tconst { fields, pinned } = arrangeColumns(schema.fields, state.columns)\n\n\t\treturn `${pinned}|${fields.map(field => field.key).join(\",\")}`\n\t}\n\n\treturn (\n\t\tarranged(left) === arranged(right) &&\n\t\tsameColumnFormats(left.columns, right.columns) &&\n\t\tsameRecord(left.columnWidths, right.columnWidths, (x, y) => x === y) &&\n\t\tsameRecord(left.filters, right.filters, sameCondition) &&\n\t\t(left.sort === null || right.sort === null\n\t\t\t? left.sort === right.sort\n\t\t\t: left.sort.key === right.sort.key && left.sort.direction === right.sort.direction)\n\t)\n}\n\n/**\n * How a view's name is checked. `except` is the view being renamed, which may keep its own name.\n * `locale` is the language names are compared in, the page's: in Turkish \"HAFTALIK\" is \"Haftalık\"\n * in capitals, in English it is not. Left out, the runtime's own, which differs from one machine to\n * the next.\n */\nexport interface ViewNameOptions {\n\treadonly except?: string | null\n\treadonly locale?: string\n}\n\n/** What is wrong with a name for a view, or null when it will do. */\nexport function viewNameProblem(\n\tviews: SavedViews,\n\tname: string,\n\toptions: ViewNameOptions = {}\n): ViewNameProblem | null {\n\tconst trimmed = name.trim()\n\n\tif (trimmed === \"\") {\n\t\treturn \"empty\"\n\t}\n\n\tif ([...trimmed].length > VIEW_NAME_LIMIT) {\n\t\treturn \"too_long\"\n\t}\n\n\tconst names = collator(options.locale)\n\tconst except = options.except ?? null\n\n\treturn views.views.some(view => view.id !== except && names.compare(view.name, trimmed) === 0) ? \"taken\" : null\n}\n\n/**\n * A new view of the sheet as it stands, at the end of the list.\n *\n * @throws TabulaError `invalid_argument` for a name `viewNameProblem` refuses, or an id taken\n */\nexport function addView(\n\tviews: SavedViews,\n\tview: { readonly id: string; readonly name: string } & ViewState,\n\toptions: Pick<ViewNameOptions, \"locale\"> = {}\n): SavedViews {\n\tif (view.id === \"\" || views.views.some(saved => saved.id === view.id)) {\n\t\tthrow new TabulaError(\"invalid_argument\", `A view's id must be new and not empty: \"${view.id}\".`)\n\t}\n\n\tconst name = checkedName(views, view.name, { locale: options.locale })\n\n\treturn freezeViews({ ...views, views: [...views.views, { ...view, name }] })\n}\n\n/** The view saved again with the sheet as it stands now, under its own name. */\nexport function updateView(views: SavedViews, id: string, state: ViewState): SavedViews {\n\treturn change(views, id, view => ({ ...view, ...pickState(state) }))\n}\n\n/** @throws TabulaError `invalid_argument` for a name `viewNameProblem` refuses */\nexport function renameView(\n\tviews: SavedViews,\n\tid: string,\n\tname: string,\n\toptions: Pick<ViewNameOptions, \"locale\"> = {}\n): SavedViews {\n\tconst checked = checkedName(views, name, { except: id, locale: options.locale })\n\n\treturn change(views, id, view => ({ ...view, name: checked }))\n}\n\n/** The views without this one. When it was the one the sheet opens in, the sheet opens as laid out. */\nexport function removeView(views: SavedViews, id: string): SavedViews {\n\tsaved(views, id)\n\n\treturn freezeViews({\n\t\t...views,\n\t\tviews: views.views.filter(view => view.id !== id),\n\t\tdefaultId: views.defaultId === id ? null : views.defaultId\n\t})\n}\n\n/** The view the sheet opens in; null for the sheet as its schema lays it out. */\nexport function setDefaultView(views: SavedViews, id: string | null): SavedViews {\n\tif (id !== null) {\n\t\tsaved(views, id)\n\t}\n\n\treturn freezeViews({ ...views, defaultId: id })\n}\n\n/**\n * Checks what was read back from storage against the views format, every problem at once.\n *\n * @throws TabulaError `invalid_views`, also for views of another module\n */\nexport function readViews(input: unknown, module: string): SavedViews {\n\tconst problems: string[] = []\n\tconst problem = (path: string, message: string): void => {\n\t\tproblems.push(`${path}: ${message}`)\n\t}\n\tconst root = plain(input)\n\n\tif (!root) {\n\t\tthrow new TabulaError(\"invalid_views\", \"Saved views must be an object.\")\n\t}\n\n\tif (root.format !== VIEWS_FORMAT) {\n\t\tproblem(\"format\", `must be \"${VIEWS_FORMAT}\".`)\n\t}\n\n\tif (root.version !== VIEWS_VERSION) {\n\t\tproblem(\"version\", `must be ${VIEWS_VERSION}; views of another version of this format cannot be read.`)\n\t}\n\n\tif (root.module !== module) {\n\t\tproblem(\"module\", `must be \"${module}\", the module these views are read for.`)\n\t}\n\n\tconst views: SavedView[] = []\n\tconst ids = new Set<string>()\n\n\tif (!Array.isArray(root.views)) {\n\t\tproblem(\"views\", \"must be a list.\")\n\t} else {\n\t\troot.views.forEach((item, index) => {\n\t\t\tconst view = readView(item, `views[${index}]`, problem)\n\n\t\t\tif (view && ids.has(view.id)) {\n\t\t\t\tproblem(`views[${index}].id`, `\"${view.id}\" is the id of another view.`)\n\t\t\t} else if (view) {\n\t\t\t\tids.add(view.id)\n\t\t\t\tviews.push(view)\n\t\t\t}\n\t\t})\n\t}\n\n\tconst defaultId = root.defaultId === undefined || root.defaultId === null ? null : root.defaultId\n\n\tif (defaultId !== null && (typeof defaultId !== \"string\" || !ids.has(defaultId))) {\n\t\tproblem(\"defaultId\", \"must be the id of one of the views, or null.\")\n\t}\n\n\tif (problems.length > 0) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_views\",\n\t\t\t`The views cannot be read:\\n${problems.map(line => ` ${line}`).join(\"\\n\")}`\n\t\t)\n\t}\n\n\treturn freezeViews({ module, views, defaultId: defaultId as string | null })\n}\n\n// ---------------------------------------------------------------- inside\n\n/** Names compared as a person reads them, by language: \"Haftalık\" and \"haftalık\" are one name. */\nconst collators = new Map<string, Intl.Collator>()\n\nfunction collator(locale: string | undefined): Intl.Collator {\n\tconst key = locale ?? \"\"\n\tlet found = collators.get(key)\n\n\tif (!found) {\n\t\tfound = new Intl.Collator(locale, { sensitivity: \"accent\" })\n\t\tcollators.set(key, found)\n\t}\n\n\treturn found\n}\n\ntype Plain = Record<string, unknown>\ntype Problem = (path: string, message: string) => void\n\nfunction checkedName(views: SavedViews, name: string, options: ViewNameOptions): string {\n\tconst problem = viewNameProblem(views, name, options)\n\n\tif (problem !== null) {\n\t\tthrow new TabulaError(\"invalid_argument\", `\"${name}\" cannot be a view's name: ${problem}.`)\n\t}\n\n\treturn name.trim()\n}\n\nfunction saved(views: SavedViews, id: string): SavedView {\n\tconst view = views.views.find(item => item.id === id)\n\n\tif (!view) {\n\t\tthrow new TabulaError(\"invalid_argument\", `There is no view \"${id}\".`)\n\t}\n\n\treturn view\n}\n\nfunction change(views: SavedViews, id: string, update: (view: SavedView) => SavedView): SavedViews {\n\tsaved(views, id)\n\n\treturn freezeViews({ ...views, views: views.views.map(view => (view.id === id ? update(view) : view)) })\n}\n\nfunction pickState(state: ViewState): ViewState {\n\treturn { columns: state.columns, columnWidths: state.columnWidths, filters: state.filters, sort: state.sort }\n}\n\nfunction sameRecord<T>(\n\ta: Readonly<Record<string, T>>,\n\tb: Readonly<Record<string, T>>,\n\tsame: (x: T, y: T) => boolean\n): boolean {\n\tconst keys = Object.keys(a)\n\n\treturn keys.length === Object.keys(b).length && keys.every(key => key in b && same(a[key] as T, b[key] as T))\n}\n\nfunction sameCondition(a: ColumnCondition, b: ColumnCondition): boolean {\n\tif (a.kind === \"range\" || b.kind === \"range\") {\n\t\treturn a.kind === \"range\" && b.kind === \"range\" && a.from === b.from && a.to === b.to\n\t}\n\n\tconst keys = new Set(a.keys)\n\n\treturn keys.size === new Set(b.keys).size && b.keys.every(key => keys.has(key))\n}\n\n/**\n * An arrangement read from JSON, each problem reported under `path`: what a template carries for\n * the sheet to open in. Not a saved view: it has no id or name.\n */\nexport function readViewState(\n\tinput: unknown,\n\tpath: string,\n\tproblem: (path: string, message: string) => void\n): ViewState {\n\tconst view = plain(input)\n\n\tif (!view) {\n\t\tproblem(path, \"must be an object.\")\n\n\t\treturn PLAIN_VIEW\n\t}\n\n\treturn freezeState({\n\t\tcolumns: readLayout(view.columns, `${path}.columns`, problem),\n\t\tcolumnWidths: readWidths(view.columnWidths, `${path}.columnWidths`, problem),\n\t\tfilters: readFilters(view.filters, `${path}.filters`, problem),\n\t\tsort: readSort(view.sort, `${path}.sort`, problem)\n\t})\n}\n\nfunction readView(input: unknown, path: string, problem: Problem): SavedView | null {\n\tconst view = plain(input)\n\n\tif (!view) {\n\t\tproblem(path, \"must be an object.\")\n\n\t\treturn null\n\t}\n\n\tlet failed = false\n\tconst fail: Problem = (at, message) => {\n\t\tfailed = true\n\t\tproblem(at, message)\n\t}\n\n\tconst id = typeof view.id === \"string\" && view.id !== \"\" ? view.id : null\n\tconst name = typeof view.name === \"string\" && view.name.trim() !== \"\" ? view.name.trim() : null\n\n\tif (id === null) {\n\t\tfail(`${path}.id`, \"must be a non-empty string.\")\n\t}\n\n\tif (name === null) {\n\t\tfail(`${path}.name`, \"must be a non-empty string.\")\n\t}\n\n\tconst columns = readLayout(view.columns, `${path}.columns`, fail)\n\tconst columnWidths = readWidths(view.columnWidths, `${path}.columnWidths`, fail)\n\tconst filters = readFilters(view.filters, `${path}.filters`, fail)\n\tconst sort = readSort(view.sort, `${path}.sort`, fail)\n\n\treturn failed || id === null || name === null ? null : { id, name, columns, columnWidths, filters, sort }\n}\n\nfunction readLayout(input: unknown, path: string, problem: Problem): ColumnLayout {\n\treturn readColumnLayout(input, path, problem) ?? {}\n}\n\nfunction readWidths(input: unknown, path: string, problem: Problem): Record<string, number> {\n\tif (input === undefined || input === null) {\n\t\treturn {}\n\t}\n\n\tconst widths = plain(input)\n\n\tif (!widths) {\n\t\tproblem(path, \"must be an object of widths by field key.\")\n\n\t\treturn {}\n\t}\n\n\tconst result: Record<string, number> = {}\n\n\tfor (const [key, width] of Object.entries(widths)) {\n\t\tif (typeof width === \"number\" && Number.isFinite(width) && width > 0) {\n\t\t\tresult[key] = width\n\t\t} else {\n\t\t\tproblem(`${path}.${key}`, \"must be a number of pixels.\")\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunction readFilters(input: unknown, path: string, problem: Problem): Record<string, ColumnCondition> {\n\tif (input === undefined || input === null) {\n\t\treturn {}\n\t}\n\n\tconst filters = plain(input)\n\n\tif (!filters) {\n\t\tproblem(path, \"must be an object of conditions by field key.\")\n\n\t\treturn {}\n\t}\n\n\tconst result: Record<string, ColumnCondition> = {}\n\n\tfor (const [key, value] of Object.entries(filters)) {\n\t\tconst condition = plain(value)\n\t\tconst bound = (side: unknown): side is string | null => side === null || typeof side === \"string\"\n\n\t\tif (\n\t\t\tcondition?.kind === \"values\" &&\n\t\t\tArray.isArray(condition.keys) &&\n\t\t\tcondition.keys.every(item => typeof item === \"string\")\n\t\t) {\n\t\t\tresult[key] = { kind: \"values\", keys: condition.keys as string[] }\n\t\t} else if (condition?.kind === \"range\" && bound(condition.from) && bound(condition.to)) {\n\t\t\tresult[key] = { kind: \"range\", from: condition.from, to: condition.to }\n\t\t} else {\n\t\t\tproblem(\n\t\t\t\t`${path}.${key}`,\n\t\t\t\t'must be { kind: \"values\", keys: [...] } or { kind: \"range\", from, to }, each bound text or null.'\n\t\t\t)\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunction readSort(input: unknown, path: string, problem: Problem): ColumnSort | null {\n\tif (input === undefined || input === null) {\n\t\treturn null\n\t}\n\n\tconst sort = plain(input)\n\n\tif (\n\t\tsort &&\n\t\ttypeof sort.key === \"string\" &&\n\t\tsort.key !== \"\" &&\n\t\t(sort.direction === \"asc\" || sort.direction === \"desc\")\n\t) {\n\t\treturn { key: sort.key, direction: sort.direction }\n\t}\n\n\tproblem(path, 'must be { key, direction: \"asc\" or \"desc\" }, or null.')\n\n\treturn null\n}\n\nfunction freezeState(state: ViewState): ViewState {\n\tconst columns = state.columns\n\n\treturn Object.freeze({\n\t\tcolumns: freezeColumnLayout(columns),\n\t\tcolumnWidths: Object.freeze({ ...state.columnWidths }),\n\t\tfilters: Object.freeze(\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(state.filters).map(([key, condition]) => [\n\t\t\t\t\tkey,\n\t\t\t\t\tObject.freeze(\n\t\t\t\t\t\tcondition.kind === \"values\"\n\t\t\t\t\t\t\t? { kind: \"values\", keys: Object.freeze([...condition.keys]) }\n\t\t\t\t\t\t\t: { ...condition }\n\t\t\t\t\t)\n\t\t\t\t])\n\t\t\t)\n\t\t) as ColumnFilters,\n\t\tsort: state.sort ? Object.freeze({ key: state.sort.key, direction: state.sort.direction }) : null\n\t})\n}\n\nfunction freezeViews(views: Pick<SavedViews, \"module\" | \"views\" | \"defaultId\">): SavedViews {\n\treturn Object.freeze({\n\t\tformat: VIEWS_FORMAT,\n\t\tversion: VIEWS_VERSION,\n\t\tmodule: views.module,\n\t\tviews: Object.freeze(\n\t\t\tviews.views.map(view => Object.freeze({ id: view.id, name: view.name, ...freezeState(view) }))\n\t\t),\n\t\tdefaultId: views.defaultId\n\t})\n}\n\nfunction plain(value: unknown): Plain | null {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as Plain) : null\n}\n","import type { CheckInput } from \"./checks.js\"\nimport { compareDecimal, normalizeDecimal } from \"./decimal.js\"\nimport { SchemaError, TabulaError } from \"./errors.js\"\nimport type { RowInit } from \"./rows.js\"\nimport {\n\tModuleSchema,\n\ttype FieldInput,\n\ttype FieldSchema,\n\ttype FieldType,\n\ttype ModuleSchemaInput,\n\ttype RuleInput\n} from \"./schema.js\"\nimport type { StyleRuleInput } from \"./styles.js\"\nimport type { CellValue } from \"./value.js\"\nimport { readViewState, type ViewState } from \"./views.js\"\n\n/**\n * A template: the sheet as an authorized user prepares it for a task, layered on the module schema\n * the developer wrote and under each user's own views. \"Aralık zam listesi\" on the price update.\n *\n * It may change a column's header, require a field the schema leaves optional, keep a column from\n * being typed into, narrow a field's limits, give new rows a value, add columns of its own, add row\n * checks (a field required when another holds a value, two fields compared), and say how the sheet\n * opens. A check only adds to what is refused, so a template may add any; it cannot take one away. It may never loosen what the schema asks: a field the schema requires stays\n * required, a limit can only get narrower, and a column the schema keeps read-only stays so. Its own\n * columns are never sent for processing: they are a helper the user works with, kept in the draft,\n * or worked out from the row by a formula.\n *\n * Only a module whose schema says `customization: \"controlled\"` (or `\"free\"`) takes a template. A\n * template the schema does not allow is refused whole, not half applied: a rule it would have\n * tightened and quietly did not is a rule nobody checks.\n */\n\nexport const TEMPLATE_FORMAT = \"tabula-grid.template\"\nexport const TEMPLATE_VERSION = 1\n\n/** What a template changes about one of the schema's fields. */\nexport interface TemplateFieldChange {\n\t/** The column's header. The key, and everything the backend sees, stays the same. */\n\treadonly label?: string\n\t/** Only `true`: a field the schema requires cannot be made optional. */\n\treadonly required?: boolean\n\t/** Only `false`: a column the schema keeps read-only cannot be opened. */\n\treadonly editable?: boolean\n\t/** Limits added or narrowed: a `min` above the schema's, a `max` below it, `unique`. */\n\treadonly rules?: readonly RuleInput[]\n\t/** A new row's value, as the schema's `default`. */\n\treadonly default?: FieldInput[\"default\"]\n}\n\nexport interface GridTemplate {\n\treadonly format: typeof TEMPLATE_FORMAT\n\t/** The version of this format. */\n\treadonly version: typeof TEMPLATE_VERSION\n\treadonly module: string\n\treadonly id: string\n\treadonly name: string\n\t/** Changes to the schema's fields, by key. */\n\treadonly fields: Readonly<Record<string, TemplateFieldChange>>\n\t/** Columns of the template's own, after the schema's: written as a schema's fields are, never sent. */\n\treadonly columns: readonly FieldInput[]\n\t/** Row checks added after the schema's own, written as a schema's; see `RowCheck`. */\n\treadonly checks: readonly CheckInput[]\n\t/** Colour rules added after the schema's own, written as a schema's; see `StyleRule`. */\n\treadonly styles: readonly StyleRuleInput[]\n\t/** How the sheet opens: the columns, widths, filters and sort, under each user's own views. */\n\treadonly view: ViewState | null\n}\n\n/** One thing wrong with a template, and where: `fields.newPrice.rules[0]`, `columns[1].key`. */\nexport interface TemplateProblem {\n\treadonly path: string\n\treadonly message: string\n}\n\nconst CHANGES = [\"label\", \"required\", \"editable\", \"rules\", \"default\"] as const\nconst NUMERIC: ReadonlySet<FieldType> = new Set([\"integer\", \"decimal\", \"money\", \"quantity\", \"percent\"])\n\n/**\n * Checks what was read back from storage, or sent by the backend, against the template format:\n * its shape, every problem at once. Whether the template fits the schema is `templateProblems`.\n *\n * @throws TabulaError `invalid_template`, also for a template of another module\n */\nexport function readTemplate(input: unknown, module: string): GridTemplate {\n\tconst problems: TemplateProblem[] = []\n\tconst problem = (path: string, message: string): void => {\n\t\tproblems.push({ path, message })\n\t}\n\tconst root = plain(input)\n\n\tif (!root) {\n\t\tthrow new TabulaError(\"invalid_template\", \"A template must be an object.\")\n\t}\n\n\tif (root.format !== TEMPLATE_FORMAT) {\n\t\tproblem(\"format\", `must be \"${TEMPLATE_FORMAT}\".`)\n\t}\n\n\tif (root.version !== TEMPLATE_VERSION) {\n\t\tproblem(\"version\", `must be ${TEMPLATE_VERSION}; a template of another version of this format cannot be read.`)\n\t}\n\n\tif (root.module !== module) {\n\t\tproblem(\"module\", `must be \"${module}\", the module the template is read for.`)\n\t}\n\n\tconst text = (name: \"id\" | \"name\"): string => {\n\t\tconst value = root[name]\n\n\t\tif (typeof value !== \"string\" || value.trim() === \"\") {\n\t\t\tproblem(name, \"must be a non-empty string.\")\n\n\t\t\treturn \"\"\n\t\t}\n\n\t\treturn name === \"name\" ? value.trim() : value\n\t}\n\n\tconst id = text(\"id\")\n\tconst name = text(\"name\")\n\tconst fields: Record<string, TemplateFieldChange> = {}\n\tconst fieldsRoot = root.fields === undefined ? {} : plain(root.fields)\n\n\tif (!fieldsRoot) {\n\t\tproblem(\"fields\", \"must be an object of changes by field key.\")\n\t} else {\n\t\tfor (const [key, change] of Object.entries(fieldsRoot)) {\n\t\t\tif (plain(change)) {\n\t\t\t\tfields[key] = change as TemplateFieldChange\n\t\t\t} else {\n\t\t\t\tproblem(`fields.${key}`, \"must be an object of changes.\")\n\t\t\t}\n\t\t}\n\t}\n\n\tconst columns: FieldInput[] = []\n\n\tif (root.columns !== undefined && !Array.isArray(root.columns)) {\n\t\tproblem(\"columns\", \"must be a list of columns.\")\n\t} else {\n\t\t;((root.columns as unknown[] | undefined) ?? []).forEach((column, index) => {\n\t\t\tif (plain(column)) {\n\t\t\t\tcolumns.push(column as unknown as FieldInput)\n\t\t\t} else {\n\t\t\t\tproblem(`columns[${index}]`, \"must be an object, written as a schema's field.\")\n\t\t\t}\n\t\t})\n\t}\n\n\tconst checks: CheckInput[] = []\n\n\tif (root.checks !== undefined && !Array.isArray(root.checks)) {\n\t\tproblem(\"checks\", \"must be a list of row checks.\")\n\t} else {\n\t\t;((root.checks as unknown[] | undefined) ?? []).forEach((check, index) => {\n\t\t\tif (plain(check)) {\n\t\t\t\tchecks.push(check as unknown as CheckInput)\n\t\t\t} else {\n\t\t\t\tproblem(`checks[${index}]`, \"must be an object, written as a schema's check.\")\n\t\t\t}\n\t\t})\n\t}\n\n\tconst styles: StyleRuleInput[] = []\n\n\tif (root.styles !== undefined && !Array.isArray(root.styles)) {\n\t\tproblem(\"styles\", \"must be a list of colour rules.\")\n\t} else {\n\t\t;((root.styles as unknown[] | undefined) ?? []).forEach((rule, index) => {\n\t\t\tif (plain(rule)) {\n\t\t\t\tstyles.push(rule as unknown as StyleRuleInput)\n\t\t\t} else {\n\t\t\t\tproblem(`styles[${index}]`, \"must be an object, written as a schema's colour rule.\")\n\t\t\t}\n\t\t})\n\t}\n\n\tconst view = root.view === undefined || root.view === null ? null : readViewState(root.view, \"view\", problem)\n\n\tif (problems.length > 0) {\n\t\tthrow new TabulaError(\"invalid_template\", describeProblems(\"The template cannot be read\", problems))\n\t}\n\n\treturn Object.freeze({\n\t\tformat: TEMPLATE_FORMAT,\n\t\tversion: TEMPLATE_VERSION,\n\t\tmodule,\n\t\tid,\n\t\tname,\n\t\tfields: Object.freeze(fields),\n\t\tcolumns: Object.freeze(columns),\n\t\tchecks: Object.freeze(checks),\n\t\tstyles: Object.freeze(styles),\n\t\tview\n\t})\n}\n\n/**\n * Everything that keeps a template from applying to the schema, each with where it is: a change\n * that loosens the schema, a field the module does not have, a column with a field's key, a limit\n * that leaves no value possible. Empty when it applies.\n */\nexport function templateProblems(schema: ModuleSchema, template: GridTemplate): TemplateProblem[] {\n\treturn merge(schema, template).problems\n}\n\n/**\n * The module schema with the template on it: the schema the sheet works with, its checks and its\n * formulas. The template's columns come after the schema's fields, never sent.\n *\n * @throws TabulaError `invalid_template` with every problem `templateProblems` finds\n */\nexport function applyTemplate(schema: ModuleSchema, template: GridTemplate): ModuleSchema {\n\tconst { problems, applied } = merge(schema, template)\n\n\tif (problems.length > 0 || applied === null) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_template\",\n\t\t\tdescribeProblems(`Template \"${template.name}\" cannot be applied to module \"${schema.module}\"`, problems)\n\t\t)\n\t}\n\n\treturn applied\n}\n\n/**\n * New rows with the schema's defaults where they give no value: the rows a paste or an import adds.\n * A value given, even an empty one, is kept; only a field the row leaves out takes its default.\n */\nexport function withDefaults(schema: ModuleSchema, rows: number | readonly RowInit[]): RowInit[] {\n\tconst list: readonly RowInit[] = typeof rows === \"number\" ? Array.from({ length: rows }, () => ({})) : rows\n\tconst defaults = schema.fields.filter(field => field.default !== null)\n\n\tif (defaults.length === 0) {\n\t\treturn [...list]\n\t}\n\n\treturn list.map(row => {\n\t\tconst values: Record<string, CellValue> = {}\n\n\t\tfor (const field of defaults) {\n\t\t\tvalues[field.key] = field.default\n\t\t}\n\n\t\tfor (const [key, value] of Object.entries(row.values ?? {})) {\n\t\t\tif (value !== undefined) {\n\t\t\t\tvalues[key] = value\n\t\t\t}\n\t\t}\n\n\t\treturn { ...row, values }\n\t})\n}\n\n// ---------------------------------------------------------------- inside\n\ntype Plain = Record<string, unknown>\ntype Problem = (path: string, message: string) => void\n\nfunction merge(\n\tschema: ModuleSchema,\n\ttemplate: GridTemplate\n): { problems: TemplateProblem[]; applied: ModuleSchema | null } {\n\tconst problems: TemplateProblem[] = []\n\tconst problem: Problem = (path, message) => {\n\t\tproblems.push({ path, message })\n\t}\n\n\tif (schema.customization === \"fixed\") {\n\t\tproblem(\"(root)\", `module \"${schema.module}\" is fixed: its schema says no template may change it.`)\n\t}\n\n\tif (template.module !== schema.module) {\n\t\tproblem(\"module\", `is \"${template.module}\"; the schema is module \"${schema.module}\".`)\n\t}\n\n\tfor (const key of Object.keys(template.fields)) {\n\t\tif (!schema.has(key)) {\n\t\t\tproblem(`fields.${key}`, `is not a field of module \"${schema.module}\".`)\n\t\t}\n\t}\n\n\tconst json = schema.toJSON()\n\tconst fields: FieldInput[] = json.fields.map(field => {\n\t\tconst change = template.fields[field.key]\n\n\t\treturn change ? changed(field, schema.field(field.key), change, `fields.${field.key}`, problem) : field\n\t})\n\n\tconst columns = template.columns.map((column, index) => {\n\t\tconst path = `columns[${index}]`\n\n\t\tif (typeof column.key === \"string\" && schema.has(column.key)) {\n\t\t\tproblem(\n\t\t\t\t`${path}.key`,\n\t\t\t\t`\"${column.key}\" is a field of the module; a template's column needs a key of its own.`\n\t\t\t)\n\t\t}\n\n\t\tif (column.type === \"lookup\") {\n\t\t\tproblem(\n\t\t\t\t`${path}.type`,\n\t\t\t\t\"cannot be lookup: a record is something the backend gives, and a template's column is never sent.\"\n\t\t\t)\n\t\t}\n\n\t\tif ((column as { submit?: unknown }).submit === true) {\n\t\t\tproblem(`${path}.submit`, \"cannot be true: a template's column is never sent for processing.\")\n\t\t}\n\n\t\treturn { ...column, submit: false }\n\t})\n\n\tif (problems.length > 0) {\n\t\treturn { problems, applied: null }\n\t}\n\n\tconst ownChecks = json.checks ?? []\n\tconst ownStyles = json.styles ?? []\n\tconst merged: ModuleSchemaInput = {\n\t\t...json,\n\t\tfields: [...fields, ...columns],\n\t\t...(ownChecks.length + template.checks.length > 0 ? { checks: [...ownChecks, ...template.checks] } : {}),\n\t\t...(ownStyles.length + template.styles.length > 0 ? { styles: [...ownStyles, ...template.styles] } : {})\n\t}\n\n\ttry {\n\t\treturn { problems, applied: ModuleSchema.from(merged) }\n\t} catch (error) {\n\t\tif (!(error instanceof SchemaError)) {\n\t\t\tthrow error\n\t\t}\n\n\t\t// The schema's own reading found it: its paths name the merged fields and checks, so they are\n\t\t// put back as the template's, a field by its key, a column and a check by its place.\n\t\tfor (const item of error.problems) {\n\t\t\tconst field = /^fields\\[(\\d+)\\](.*)$/.exec(item.path)\n\t\t\tconst check = /^checks\\[(\\d+)\\](.*)$/.exec(item.path)\n\t\t\tconst style = /^styles\\[(\\d+)\\](.*)$/.exec(item.path)\n\t\t\tlet path = item.path\n\n\t\t\tif (field) {\n\t\t\t\tconst index = Number(field[1])\n\n\t\t\t\tpath =\n\t\t\t\t\tindex < json.fields.length\n\t\t\t\t\t\t? `fields.${json.fields[index]?.key ?? index}${field[2] ?? \"\"}`\n\t\t\t\t\t\t: `columns[${index - json.fields.length}]${field[2] ?? \"\"}`\n\t\t\t} else if (check && Number(check[1]) >= ownChecks.length) {\n\t\t\t\tpath = `checks[${Number(check[1]) - ownChecks.length}]${check[2] ?? \"\"}`\n\t\t\t} else if (style && Number(style[1]) >= ownStyles.length) {\n\t\t\t\tpath = `styles[${Number(style[1]) - ownStyles.length}]${style[2] ?? \"\"}`\n\t\t\t}\n\n\t\t\tproblem(path, item.message)\n\t\t}\n\n\t\treturn { problems, applied: null }\n\t}\n}\n\n/** One of the schema's fields, as the template changes it, as long as it only narrows. */\nfunction changed(\n\tjson: FieldInput,\n\tfield: FieldSchema,\n\tchange: TemplateFieldChange,\n\tpath: string,\n\tproblem: Problem\n): FieldInput {\n\tconst next: FieldInput = { ...json }\n\n\tfor (const name of Object.keys(change)) {\n\t\tif (!(CHANGES as readonly string[]).includes(name)) {\n\t\t\tproblem(`${path}.${name}`, `is not something a template changes; it changes ${CHANGES.join(\", \")}.`)\n\t\t}\n\t}\n\n\tif (change.label !== undefined) {\n\t\tnext.label = change.label\n\t}\n\n\tif (change.required !== undefined) {\n\t\tif (typeof change.required !== \"boolean\") {\n\t\t\tproblem(`${path}.required`, \"must be true or false.\")\n\t\t} else if (!change.required && field.required) {\n\t\t\tproblem(\n\t\t\t\t`${path}.required`,\n\t\t\t\t\"would make the field optional; the schema requires it, and a template only narrows.\"\n\t\t\t)\n\t\t} else if (change.required) {\n\t\t\tnext.required = true\n\t\t}\n\t}\n\n\tif (change.editable !== undefined) {\n\t\tif (typeof change.editable !== \"boolean\") {\n\t\t\tproblem(`${path}.editable`, \"must be true or false.\")\n\t\t} else if (change.editable && !field.editable) {\n\t\t\tproblem(\n\t\t\t\t`${path}.editable`,\n\t\t\t\t\"would open the column for typing; the schema keeps it read-only, and a template only narrows.\"\n\t\t\t)\n\t\t} else if (!change.editable) {\n\t\t\tnext.editable = false\n\t\t}\n\t}\n\n\tif (change.rules !== undefined) {\n\t\tnext.rules = narrowed(field, change.rules, `${path}.rules`, problem)\n\t}\n\n\tif (change.default !== undefined) {\n\t\tnext.default = change.default\n\t}\n\n\treturn next\n}\n\n/**\n * The field's rules with the template's: each the narrower of the two. A rule the schema does not\n * have is added; one that would let through what the schema refuses is a problem.\n */\nfunction narrowed(field: FieldSchema, rules: unknown, path: string, problem: Problem): RuleInput[] {\n\tconst result = new Map<string, RuleInput>(field.rules.map(rule => [rule.rule, { ...rule } as RuleInput]))\n\n\tif (!Array.isArray(rules)) {\n\t\tproblem(path, \"must be a list of rules.\")\n\n\t\treturn [...result.values()]\n\t}\n\n\trules.forEach((raw: unknown, index) => {\n\t\tconst at = `${path}[${index}]`\n\t\tconst rule = plain(raw)\n\t\tconst kind = rule?.rule\n\t\tconst own = field.rules.find(item => item.rule === kind)\n\n\t\tif (!rule || typeof kind !== \"string\") {\n\t\t\tproblem(at, 'must be a rule such as { \"rule\": \"min\", \"value\": \"1\" }.')\n\n\t\t\treturn\n\t\t}\n\n\t\tswitch (kind) {\n\t\t\tcase \"min\":\n\t\t\tcase \"max\": {\n\t\t\t\tconst value =\n\t\t\t\t\ttypeof rule.value === \"string\" || typeof rule.value === \"number\"\n\t\t\t\t\t\t? normalizeDecimal(rule.value)\n\t\t\t\t\t\t: null\n\n\t\t\t\tif (!NUMERIC.has(field.type)) {\n\t\t\t\t\tproblem(at, `${kind} does not apply to a ${field.type} field.`)\n\t\t\t\t} else if (value === null) {\n\t\t\t\t\tproblem(`${at}.value`, 'must be a decimal number such as \"1\" or \"12.5\".')\n\t\t\t\t} else if (\n\t\t\t\t\town &&\n\t\t\t\t\t\"value\" in own &&\n\t\t\t\t\tcompareDecimal(value, String(own.value)) * (kind === \"min\" ? 1 : -1) < 0\n\t\t\t\t) {\n\t\t\t\t\tproblem(\n\t\t\t\t\t\tat,\n\t\t\t\t\t\t`${kind} ${value} would let through what the schema's ${kind} ${own.value} refuses; a template only narrows.`\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tresult.set(kind, { rule: kind, value })\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcase \"minLength\":\n\t\t\tcase \"maxLength\": {\n\t\t\t\tconst value = rule.value\n\n\t\t\t\tif (field.type !== \"string\") {\n\t\t\t\t\tproblem(at, `${kind} does not apply to a ${field.type} field.`)\n\t\t\t\t} else if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n\t\t\t\t\tproblem(`${at}.value`, \"must be a whole number of characters, 0 or more.\")\n\t\t\t\t} else if (own && \"value\" in own && (value - Number(own.value)) * (kind === \"minLength\" ? 1 : -1) < 0) {\n\t\t\t\t\tproblem(\n\t\t\t\t\t\tat,\n\t\t\t\t\t\t`${kind} ${value} would let through what the schema's ${kind} ${own.value} refuses; a template only narrows.`\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tresult.set(kind, { rule: kind, value })\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcase \"unique\":\n\t\t\t\tresult.set(kind, { rule: kind })\n\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tproblem(\n\t\t\t\t\t`${at}.rule`,\n\t\t\t\t\t`${JSON.stringify(kind)} is not a rule; expected one of min, max, minLength, maxLength, unique.`\n\t\t\t\t)\n\t\t}\n\t})\n\n\treturn [...result.values()]\n}\n\nfunction describeProblems(heading: string, problems: readonly TemplateProblem[]): string {\n\treturn `${heading}:\\n${problems.map(item => ` ${item.path}: ${item.message}`).join(\"\\n\")}`\n}\n\nfunction plain(value: unknown): Plain | null {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as Plain) : null\n}\n","import { TabulaError } from \"./errors.js\"\nimport { Listeners } from \"./listeners.js\"\n\n/**\n * Which cells are selected, in the positions the user sees: row and column indexes on screen, after\n * sorting, filtering and hiding. Turning a position into a row id and a field is the view's job.\n *\n * It follows Excel. The active cell, the one typing goes into, stays put while Shift extends the\n * selection; what moves is the opposite corner, the head. A plain move collapses the selection onto\n * one cell again.\n */\n\nexport interface CellPosition {\n\treadonly row: number\n\treadonly col: number\n}\n\n/** Inclusive on all four sides. */\nexport interface CellRange {\n\treadonly top: number\n\treadonly left: number\n\treadonly bottom: number\n\treadonly right: number\n}\n\nexport type Direction = \"up\" | \"down\" | \"left\" | \"right\"\n\nexport interface MoveOptions {\n\t/** Move the head and keep the active cell, as Shift does. */\n\treadonly extend?: boolean\n}\n\n/** Whether the cell at a position is empty, for `jump()`. */\nexport type IsBlank = (row: number, col: number) => boolean\n\nconst STEPS: Readonly<Record<Direction, CellPosition>> = {\n\tup: { row: -1, col: 0 },\n\tdown: { row: 1, col: 0 },\n\tleft: { row: 0, col: -1 },\n\tright: { row: 0, col: 1 }\n}\n\nexport class Selection {\n\t#rowCount: number\n\t#colCount: number\n\t#active: CellPosition | null = null\n\t/** The corner that stays when Shift extends the selection; usually the active cell. */\n\t#pivot: CellPosition | null = null\n\t#head: CellPosition | null = null\n\treadonly #listeners = new Listeners<Selection>()\n\n\tconstructor(rowCount: number, colCount: number) {\n\t\tthis.#rowCount = requireCount(rowCount, \"rowCount\")\n\t\tthis.#colCount = requireCount(colCount, \"colCount\")\n\n\t\tif (!this.#isEmpty()) {\n\t\t\tthis.#active = this.#pivot = this.#head = cell(0, 0)\n\t\t}\n\t}\n\n\tget rowCount(): number {\n\t\treturn this.#rowCount\n\t}\n\n\tget colCount(): number {\n\t\treturn this.#colCount\n\t}\n\n\t/** The cell typing goes into. Null when the grid has no cells. */\n\tget active(): CellPosition | null {\n\t\treturn this.#active\n\t}\n\n\t/** The corner Shift moves; the one to keep on screen while extending. Null when the grid has no cells. */\n\tget head(): CellPosition | null {\n\t\treturn this.#head\n\t}\n\n\tget range(): CellRange | null {\n\t\treturn this.#pivot && this.#head ? rangeOf(this.#pivot, this.#head) : null\n\t}\n\n\tcontains(row: number, col: number): boolean {\n\t\tconst range = this.range\n\n\t\treturn range !== null && within(range, cell(row, col))\n\t}\n\n\tisActive(row: number, col: number): boolean {\n\t\treturn this.#active !== null && this.#active.row === row && this.#active.col === col\n\t}\n\n\t/** Goes to a cell, kept inside the grid: `moveTo(Infinity, Infinity)` is the last cell. */\n\tmoveTo(row: number, col: number, options: MoveOptions = {}): void {\n\t\tconst target = this.#clamp(row, col)\n\n\t\tif (target === null || this.#active === null || this.#pivot === null) {\n\t\t\treturn\n\t\t}\n\n\t\tif (options.extend) {\n\t\t\tthis.#commit(this.#active, this.#pivot, target)\n\t\t} else {\n\t\t\tthis.#commit(target, target, target)\n\t\t}\n\t}\n\n\t/** Moves by a number of rows and columns: from the head when extending, from the active cell otherwise. */\n\tmove(rows: number, cols: number, options: MoveOptions = {}): void {\n\t\tconst from = options.extend ? this.#head : this.#active\n\n\t\tif (from !== null) {\n\t\t\tthis.moveTo(from.row + rows, from.col + cols, options)\n\t\t}\n\t}\n\n\t/**\n\t * Ctrl and an arrow, as in Excel: inside a run of filled cells, to the end of the run; otherwise to\n\t * the next filled cell, or to the edge of the grid when there is none.\n\t */\n\tjump(direction: Direction, isBlank: IsBlank, options: MoveOptions = {}): void {\n\t\tconst from = options.extend ? this.#head : this.#active\n\n\t\tif (from === null) {\n\t\t\treturn\n\t\t}\n\n\t\tconst target = edgeOf(from, STEPS[direction], this.#rowCount, this.#colCount, isBlank)\n\n\t\tthis.moveTo(target.row, target.col, options)\n\t}\n\n\t/** Whole rows, `from` through `to`. The active cell goes to the first column of `from`. */\n\tselectRows(from: number, to: number = from): void {\n\t\tconst start = this.#clamp(from, 0)\n\t\tconst end = this.#clamp(to, Infinity)\n\n\t\tif (start !== null && end !== null) {\n\t\t\tthis.#commit(start, start, end)\n\t\t}\n\t}\n\n\t/** Whole columns, `from` through `to`. The active cell goes to the first row of `from`. */\n\tselectColumns(from: number, to: number = from): void {\n\t\tconst start = this.#clamp(0, from)\n\t\tconst end = this.#clamp(Infinity, to)\n\n\t\tif (start !== null && end !== null) {\n\t\t\tthis.#commit(start, start, end)\n\t\t}\n\t}\n\n\t/** Every cell. The active cell stays where it is. */\n\tselectAll(): void {\n\t\tconst start = this.#clamp(0, 0)\n\t\tconst end = this.#clamp(Infinity, Infinity)\n\n\t\tif (start !== null && end !== null && this.#active !== null) {\n\t\t\tthis.#commit(this.#active, start, end)\n\t\t}\n\t}\n\n\t/** The grid changed size, such as after rows were deleted. Everything is kept inside it. */\n\tresize(rowCount: number, colCount: number): void {\n\t\tthis.#rowCount = requireCount(rowCount, \"rowCount\")\n\t\tthis.#colCount = requireCount(colCount, \"colCount\")\n\n\t\tif (this.#isEmpty()) {\n\t\t\tif (this.#active !== null) {\n\t\t\t\tthis.#active = this.#pivot = this.#head = null\n\t\t\t\tthis.#listeners.emit(this)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tconst active = this.#active ?? cell(0, 0)\n\t\tconst pivot = this.#pivot ?? active\n\t\tconst head = this.#head ?? active\n\n\t\tthis.#commit(this.#clampCell(active), this.#clampCell(pivot), this.#clampCell(head))\n\t}\n\n\t/** Called after each change of the selection. Returns the way to stop. */\n\tsubscribe(listener: (selection: Selection) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t#isEmpty(): boolean {\n\t\treturn this.#rowCount === 0 || this.#colCount === 0\n\t}\n\n\t#clamp(row: number, col: number): CellPosition | null {\n\t\tif (Number.isNaN(row) || Number.isNaN(col)) {\n\t\t\tthrow new TabulaError(\"invalid_argument\", `A cell position must be a number; got ${row}, ${col}.`)\n\t\t}\n\n\t\treturn this.#isEmpty() ? null : this.#clampCell(cell(row, col))\n\t}\n\n\t#clampCell(position: CellPosition): CellPosition {\n\t\treturn cell(\n\t\t\tMath.min(this.#rowCount - 1, Math.max(0, Math.trunc(position.row))),\n\t\t\tMath.min(this.#colCount - 1, Math.max(0, Math.trunc(position.col)))\n\t\t)\n\t}\n\n\t#commit(active: CellPosition, pivot: CellPosition, head: CellPosition): void {\n\t\t// Shrinking the selection past the active cell would leave typing going into a cell that is not\n\t\t// selected. The fixed corner takes over.\n\t\tconst settled = within(rangeOf(pivot, head), active) ? active : pivot\n\n\t\tif (same(settled, this.#active) && same(pivot, this.#pivot) && same(head, this.#head)) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#active = settled\n\t\tthis.#pivot = pivot\n\t\tthis.#head = head\n\t\tthis.#listeners.emit(this)\n\t}\n}\n\nfunction edgeOf(\n\tfrom: CellPosition,\n\tstep: CellPosition,\n\trowCount: number,\n\tcolCount: number,\n\tisBlank: IsBlank\n): CellPosition {\n\tconst inside = (position: CellPosition): boolean =>\n\t\tposition.row >= 0 && position.row < rowCount && position.col >= 0 && position.col < colCount\n\tconst blank = (position: CellPosition): boolean => isBlank(position.row, position.col)\n\tconst advance = (position: CellPosition): CellPosition => cell(position.row + step.row, position.col + step.col)\n\n\tlet current = from\n\tlet next = advance(current)\n\n\tif (!inside(next)) {\n\t\treturn current\n\t}\n\n\tif (!blank(current) && !blank(next)) {\n\t\twhile (inside(next) && !blank(next)) {\n\t\t\tcurrent = next\n\t\t\tnext = advance(next)\n\t\t}\n\n\t\treturn current\n\t}\n\n\tcurrent = next\n\n\twhile (blank(current)) {\n\t\tnext = advance(current)\n\n\t\tif (!inside(next)) {\n\t\t\treturn current\n\t\t}\n\n\t\tcurrent = next\n\t}\n\n\treturn current\n}\n\nfunction cell(row: number, col: number): CellPosition {\n\treturn Object.freeze({ row, col })\n}\n\nfunction rangeOf(a: CellPosition, b: CellPosition): CellRange {\n\treturn Object.freeze({\n\t\ttop: Math.min(a.row, b.row),\n\t\tleft: Math.min(a.col, b.col),\n\t\tbottom: Math.max(a.row, b.row),\n\t\tright: Math.max(a.col, b.col)\n\t})\n}\n\nfunction within(range: CellRange, position: CellPosition): boolean {\n\treturn (\n\t\tposition.row >= range.top &&\n\t\tposition.row <= range.bottom &&\n\t\tposition.col >= range.left &&\n\t\tposition.col <= range.right\n\t)\n}\n\nfunction same(a: CellPosition, b: CellPosition | null): boolean {\n\treturn b !== null && a.row === b.row && a.col === b.col\n}\n\nfunction requireCount(count: number, name: string): number {\n\tif (!Number.isSafeInteger(count) || count < 0) {\n\t\tthrow new TabulaError(\"invalid_argument\", `${name} must be a whole number, 0 or more; got ${count}.`)\n\t}\n\n\treturn count\n}\n","/**\n * Cells as a spreadsheet puts them on the clipboard: separated by tabs, rows separated by line\n * breaks. A cell holding a tab, a line break or a quote is wrapped in quotes, its own quotes doubled.\n * Excel, Google Sheets and LibreOffice all write this and read it back.\n */\n\n/**\n * The rows and cells in clipboard text.\n *\n * One line break at the very end ends the last row rather than starting another: Excel puts one\n * after every copied range. Rows may differ in length; nothing is padded. A line break inside a\n * quoted cell is always \"\\n\", however it arrived.\n *\n * A quote opens a quoted cell only at the start of a cell. One that never closes was a character,\n * not a wrapper, and the cell is read again from it as plain text: otherwise a cell that merely\n * starts with `\"` would swallow every row after it.\n */\nexport function parseTsv(text: string): string[][] {\n\tif (text === \"\") {\n\t\treturn []\n\t}\n\n\tconst rows: string[][] = []\n\tlet row: string[] = []\n\tlet cell = \"\"\n\tlet index = 0\n\tlet cellStart = true\n\tlet quoteAt = -1\n\tlet literalAt = -1\n\n\tfor (;;) {\n\t\twhile (index < text.length) {\n\t\t\tconst char = text.charAt(index)\n\n\t\t\tif (quoteAt >= 0) {\n\t\t\t\tif (char === '\"') {\n\t\t\t\t\tif (text.charAt(index + 1) === '\"') {\n\t\t\t\t\t\tcell += '\"'\n\t\t\t\t\t\tindex += 2\n\t\t\t\t\t} else {\n\t\t\t\t\t\tquoteAt = -1\n\t\t\t\t\t\tindex++\n\t\t\t\t\t}\n\t\t\t\t} else if (char === \"\\r\") {\n\t\t\t\t\t// One way of writing a line break inside a cell. The Windows clipboard turns \"\\n\" into\n\t\t\t\t\t// \"\\r\\n\" on the way through, so the same text would otherwise arrive two ways.\n\t\t\t\t\tcell += \"\\n\"\n\t\t\t\t\tindex += text.charAt(index + 1) === \"\\n\" ? 2 : 1\n\t\t\t\t} else {\n\t\t\t\t\tcell += char\n\t\t\t\t\tindex++\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (char === '\"' && cellStart && index !== literalAt) {\n\t\t\t\tquoteAt = index\n\t\t\t\tcellStart = false\n\t\t\t\tindex++\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (char === \"\\t\") {\n\t\t\t\trow.push(cell)\n\t\t\t\tcell = \"\"\n\t\t\t\tcellStart = true\n\t\t\t\tindex++\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (char === \"\\n\" || char === \"\\r\") {\n\t\t\t\trow.push(cell)\n\t\t\t\trows.push(row)\n\t\t\t\trow = []\n\t\t\t\tcell = \"\"\n\t\t\t\tcellStart = true\n\t\t\t\tindex += char === \"\\r\" && text.charAt(index + 1) === \"\\n\" ? 2 : 1\n\n\t\t\t\tif (index >= text.length) {\n\t\t\t\t\treturn rows\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcell += char\n\t\t\tcellStart = false\n\t\t\tindex++\n\t\t}\n\n\t\tif (quoteAt < 0) {\n\t\t\tbreak\n\t\t}\n\n\t\tliteralAt = quoteAt\n\t\tindex = quoteAt\n\t\tquoteAt = -1\n\t\tcell = \"\"\n\t\tcellStart = true\n\t}\n\n\trow.push(cell)\n\trows.push(row)\n\n\treturn rows\n}\n\n/** Rows of cells as clipboard text, quoting the cells that need it. No line break after the last row. */\nexport function toTsv(rows: readonly (readonly string[])[]): string {\n\treturn rows.map(row => row.map(quoteCell).join(\"\\t\")).join(\"\\r\\n\")\n}\n\nfunction quoteCell(text: string): string {\n\treturn /[\\t\\n\\r\"]/.test(text) ? `\"${text.replace(/\"/g, '\"\"')}\"` : text\n}\n","/**\n * CSV as spreadsheets write it (RFC 4180): cells separated by a delimiter, rows by line breaks, a\n * cell holding the delimiter, a quote or a line break wrapped in quotes, its own quotes doubled.\n *\n * Which delimiter depends on who wrote the file. Excel uses the list separator of the machine's\n * language, and in Turkish, where the comma is the decimal separator, that is a semicolon.\n */\n\nexport type CsvDelimiter = \",\" | \";\" | \"\\t\"\n\nconst DELIMITERS: readonly CsvDelimiter[] = [\";\", \",\", \"\\t\"]\n\nexport interface CsvReadOptions {\n\t/** Left out, it is told from the first line: whichever of `;`, `,` and tab splits it most. */\n\treadonly delimiter?: CsvDelimiter\n}\n\n/**\n * The rows and cells of CSV text. A byte order mark at the start is dropped, line breaks are\n * `\\r\\n` or `\\n`, a line break inside a quoted cell is kept as `\\n`, and the line break that ends the\n * last row starts no other. Empty lines are rows with one empty cell, as in the file.\n */\nexport function parseCsv(text: string, options: CsvReadOptions = {}): string[][] {\n\tconst source = text.startsWith(\"\\uFEFF\") ? text.slice(1) : text\n\n\tif (source === \"\") {\n\t\treturn []\n\t}\n\n\tconst delimiter = options.delimiter ?? detectDelimiter(source)\n\tconst rows: string[][] = []\n\tlet row: string[] = []\n\tlet cell = \"\"\n\tlet quoted = false\n\t// Whether the row has begun: a last row of one empty quoted cell is still a row.\n\tlet started = false\n\tlet index = 0\n\n\tconst endCell = (): void => {\n\t\trow.push(cell)\n\t\tcell = \"\"\n\t}\n\n\tconst endRow = (): void => {\n\t\tendCell()\n\t\trows.push(row)\n\t\trow = []\n\t\tstarted = false\n\t}\n\n\twhile (index < source.length) {\n\t\tconst char = source.charAt(index)\n\n\t\tstarted = true\n\n\t\tif (quoted) {\n\t\t\tif (char === '\"') {\n\t\t\t\tif (source.charAt(index + 1) === '\"') {\n\t\t\t\t\tcell += '\"'\n\t\t\t\t\tindex += 2\n\t\t\t\t} else {\n\t\t\t\t\tquoted = false\n\t\t\t\t\tindex++\n\t\t\t\t}\n\t\t\t} else if (char === \"\\r\") {\n\t\t\t\tcell += \"\\n\"\n\t\t\t\tindex += source.charAt(index + 1) === \"\\n\" ? 2 : 1\n\t\t\t} else {\n\t\t\t\tcell += char\n\t\t\t\tindex++\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif (char === '\"' && cell === \"\") {\n\t\t\tquoted = true\n\t\t\tindex++\n\t\t} else if (char === delimiter) {\n\t\t\tendCell()\n\t\t\tindex++\n\t\t} else if (char === \"\\r\" || char === \"\\n\") {\n\t\t\tendRow()\n\t\t\tindex += char === \"\\r\" && source.charAt(index + 1) === \"\\n\" ? 2 : 1\n\t\t} else {\n\t\t\tcell += char\n\t\t\tindex++\n\t\t}\n\t}\n\n\t// The last row, unless the text ended with its line break.\n\tif (started) {\n\t\tendRow()\n\t}\n\n\treturn rows\n}\n\n/** The delimiter that splits the first line into the most cells, quotes respected. A semicolon wins a tie. */\nexport function detectDelimiter(text: string): CsvDelimiter {\n\tconst counts = new Map<CsvDelimiter, number>(DELIMITERS.map(delimiter => [delimiter, 0]))\n\tlet quoted = false\n\n\tfor (const char of text) {\n\t\tif (char === '\"') {\n\t\t\tquoted = !quoted\n\t\t} else if (!quoted && (char === \"\\n\" || char === \"\\r\")) {\n\t\t\tbreak\n\t\t} else if (!quoted && counts.has(char as CsvDelimiter)) {\n\t\t\tcounts.set(char as CsvDelimiter, (counts.get(char as CsvDelimiter) ?? 0) + 1)\n\t\t}\n\t}\n\n\tlet best: CsvDelimiter = \";\"\n\n\tfor (const delimiter of DELIMITERS) {\n\t\tif ((counts.get(delimiter) ?? 0) > (counts.get(best) ?? 0)) {\n\t\t\tbest = delimiter\n\t\t}\n\t}\n\n\treturn best\n}\n\nexport interface CsvWriteOptions {\n\treadonly delimiter?: CsvDelimiter\n\t/** A byte order mark at the start, which Excel needs to read the text as UTF-8. True by default. */\n\treadonly bom?: boolean\n}\n\n/** CSV text for rows of cells, lines ending in `\\r\\n` as RFC 4180 and Excel have them. */\nexport function toCsv(rows: readonly (readonly string[])[], options: CsvWriteOptions = {}): string {\n\tconst delimiter = options.delimiter ?? \",\"\n\tconst special = new RegExp(`[\"\\\\r\\\\n${delimiter === \"\\t\" ? \"\\\\t\" : delimiter}]`)\n\tconst text = rows\n\t\t.map(row => row.map(cell => (special.test(cell) ? `\"${cell.replace(/\"/g, '\"\"')}\"` : cell)).join(delimiter))\n\t\t.join(\"\\r\\n\")\n\n\treturn `${options.bom === false ? \"\" : \"\\uFEFF\"}${text}\\r\\n`\n}\n\n/**\n * The text in a file's bytes: UTF-8 when they are UTF-8, otherwise the code page given, Windows-1254\n * by default, which is what Excel writes a Turkish \"CSV\" in.\n */\nexport function decodeText(bytes: Uint8Array, fallback = \"windows-1254\"): string {\n\ttry {\n\t\treturn new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes)\n\t} catch {\n\t\treturn new TextDecoder(fallback).decode(bytes)\n\t}\n}\n","import type { CsvDelimiter } from \"./csv.js\"\nimport type { RowId, RowInit, RowStore } from \"./rows.js\"\nimport type { FieldSchema, ModuleSchema } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport { editText } from \"./values/format.js\"\nimport { isFieldValue, readInput } from \"./values/read.js\"\nimport type { ValueSettings } from \"./values/settings.js\"\n\n/**\n * A sheet as a table of text and back: what a CSV file, or any file a backend has read, holds.\n *\n * The text is the sheet's own: numbers with its decimal mark and every digit, dates in its pattern,\n * yes and no in its words, a lookup by its name. Read back with the same settings, it gives the same\n * values.\n */\n\n// ---------------------------------------------------------------- export\n\nexport interface TableExportOptions {\n\treadonly store: RowStore\n\t/** The columns to write, in order, such as the ones shown. */\n\treadonly fields: readonly FieldSchema[]\n\t/** The rows to write, in order, such as a filtered view's. Every row by default. */\n\treadonly rowIds?: readonly RowId[]\n\treadonly settings: ValueSettings\n\t/** What the first row holds: the columns' labels, their keys, or nothing. Labels by default. */\n\treadonly header?: \"label\" | \"key\" | \"none\"\n}\n\n/**\n * Text a spreadsheet would take for a formula and run when the file is opened: `=`, `+`, `-`, `@`, a\n * tab or a carriage return at the start. Such a cell is written with `'` before it, which a\n * spreadsheet shows as text. A number in a number column is never touched: `-12` stays a number.\n */\nconst FORMULA_START = /^[=+\\-@\\t\\r]/\n\nconst NUMBER_TYPES: ReadonlySet<string> = new Set([\"integer\", \"decimal\", \"quantity\", \"money\", \"percent\"])\n\nexport function exportTable(options: TableExportOptions): string[][] {\n\tconst { store, fields, settings } = options\n\tconst rows: string[][] = []\n\n\tif ((options.header ?? \"label\") !== \"none\") {\n\t\trows.push(fields.map(field => (options.header === \"key\" ? field.key : field.label)))\n\t}\n\n\tfor (const rowId of options.rowIds ?? store.rowIds()) {\n\t\trows.push(fields.map(field => cellText(field, store.get(rowId, field.key), settings)))\n\t}\n\n\treturn rows\n}\n\nfunction cellText(field: FieldSchema, value: CellValue, settings: ValueSettings): string {\n\tconst text = editText(field, value, settings)\n\tconst number = NUMBER_TYPES.has(field.type) && value !== null && isFieldValue(field, value)\n\n\treturn !number && FORMULA_START.test(text) ? `'${text}` : text\n}\n\n/** The delimiter a spreadsheet in the sheet's language expects: `;` where the comma is the decimal mark. */\nexport function csvDelimiterFor(settings: ValueSettings): CsvDelimiter {\n\treturn settings.decimalSeparator === \",\" ? \";\" : \",\"\n}\n\n// ---------------------------------------------------------------- import\n\nexport interface TableImportOptions {\n\treadonly schema: ModuleSchema\n\treadonly settings: ValueSettings\n\t/**\n\t * Which field each column goes to, by the column's position, over what its header says. Null\n\t * leaves a column out.\n\t */\n\treadonly columns?: Readonly<Record<number, string | null>>\n}\n\n/**\n * What became of a column. `unknown`: no field has its header. `duplicate`: an earlier column went\n * to the same field. `read_only`: its field is not typed into, such as one shown for reference or\n * worked out by a formula. `skipped`: left out on purpose.\n */\nexport type ColumnStatus = \"matched\" | \"unknown\" | \"duplicate\" | \"read_only\" | \"skipped\"\n\nexport interface ColumnMatch {\n\treadonly index: number\n\treadonly header: string\n\t/** The field the column went to; null unless it was `matched`. */\n\treadonly field: string | null\n\treadonly status: ColumnStatus\n}\n\nexport interface TableImport {\n\treadonly columns: readonly ColumnMatch[]\n\t/** For `RowStore.appendRows`: new rows, ids to be made. Empty lines are left out. */\n\treadonly rows: RowInit[]\n\t/** Required fields no column brought: every row lacks them, and will say so. */\n\treadonly missing: readonly string[]\n\t/**\n\t * Cells whose text is not a value of their field's type: kept as written, and marked, as a paste\n\t * keeps them. A lookup's name is not counted: matching it to a record is the lookup's work.\n\t */\n\treadonly unreadable: number\n}\n\n/**\n * Rows from a table whose first row names the columns, by each field's label or key, in any case.\n * Each cell is read as what a user typed into the field would be.\n */\nexport function importTable(table: readonly (readonly string[])[], options: TableImportOptions): TableImport {\n\tconst { schema, settings } = options\n\tconst [header = [], ...body] = table\n\tconst taken = new Set<string>()\n\n\tconst columns: ColumnMatch[] = header.map((raw, index) => {\n\t\tconst name = raw.trim()\n\t\tconst given = options.columns?.[index]\n\n\t\tif (given === null) {\n\t\t\treturn { index, header: name, field: null, status: \"skipped\" }\n\t\t}\n\n\t\tconst field = given !== undefined ? (schema.has(given) ? schema.field(given) : null) : fieldNamed(schema, name)\n\n\t\tif (!field) {\n\t\t\treturn { index, header: name, field: null, status: \"unknown\" }\n\t\t}\n\n\t\tif (!field.editable) {\n\t\t\treturn { index, header: name, field: null, status: \"read_only\" }\n\t\t}\n\n\t\tif (taken.has(field.key)) {\n\t\t\treturn { index, header: name, field: null, status: \"duplicate\" }\n\t\t}\n\n\t\ttaken.add(field.key)\n\n\t\treturn { index, header: name, field: field.key, status: \"matched\" }\n\t})\n\n\tconst rows: RowInit[] = []\n\tlet unreadable = 0\n\n\tfor (const line of body) {\n\t\tif (line.every(cell => cell.trim() === \"\")) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst values: Record<string, CellValue> = {}\n\n\t\tfor (const column of columns) {\n\t\t\tif (column.field === null) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst field = schema.field(column.field)\n\t\t\tconst result = readInput(field, line[column.index] ?? \"\", settings)\n\n\t\t\tif (result.value !== null) {\n\t\t\t\tvalues[field.key] = result.value\n\t\t\t}\n\n\t\t\tif (result.problem && result.problem.code !== \"not_matched\") {\n\t\t\t\tunreadable++\n\t\t\t}\n\t\t}\n\n\t\trows.push({ values })\n\t}\n\n\tconst missing = schema.fields\n\t\t.filter(field => field.required && field.editable && !taken.has(field.key))\n\t\t.map(field => field.key)\n\n\treturn { columns, rows, missing, unreadable }\n}\n\n/** The field a header names: by label, then by key, regardless of case, Turkish or not. */\nfunction fieldNamed(schema: ModuleSchema, name: string): FieldSchema | null {\n\tconst same = (a: string, b: string): boolean =>\n\t\ta.toLocaleLowerCase(\"tr\") === b.toLocaleLowerCase(\"tr\") || a.toLowerCase() === b.toLowerCase()\n\n\treturn (\n\t\tschema.fields.find(field => same(field.label.trim(), name)) ??\n\t\tschema.fields.find(field => same(field.key, name)) ??\n\t\tnull\n\t)\n}\n","import { breaksCheck, checkFields, type ConditionOp, type RowCheck, type RowCondition } from \"./checks.js\"\nimport { compareDecimal } from \"./decimal.js\"\nimport { isFormulaError } from \"./formula/error.js\"\nimport { Listeners } from \"./listeners.js\"\nimport type { RowId, RowStore, StoreChange } from \"./rows.js\"\nimport type { FieldRule, FieldSchema, ModuleSchema } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport { decimalText } from \"./values/number.js\"\nimport { formatCell } from \"./values/format.js\"\nimport { canonicalValue, isLookupValue, valueProblem, type ValueProblemCode } from \"./values/read.js\"\nimport { VALUE_SETTINGS, type ValueSettings } from \"./values/settings.js\"\n\n/**\n * What is wrong in a sheet, bound to rows by id and to fields by key, never to a row number or a\n * column header: a sort or a renamed header moves nothing.\n *\n * Local issues are the schema's own rules, checked in the browser as the user types. A backend's\n * answers arrive in the same shape (see `SheetSession`). A backend still checks everything again;\n * passing here promises nothing.\n */\n\nexport type LocalIssueCode =\n\t| ValueProblemCode\n\t| \"required\"\n\t| \"min_value\"\n\t| \"max_value\"\n\t| \"min_length\"\n\t| \"max_length\"\n\t| \"not_unique\"\n\t| \"formula_error\"\n\t| \"check_filled\"\n\t| \"check_empty\"\n\t| \"check_compare\"\n\nexport type IssueSeverity = \"error\" | \"warning\"\n\nexport type IssueScope = \"cell\" | \"row\" | \"sheet\" | \"workbook\"\n\nexport interface IssueTarget {\n\treadonly rowId: RowId\n\treadonly field: string\n}\n\nexport interface Issue {\n\t/** Stable while the problem stands: the same issue on the same cell keeps its id. */\n\treadonly id: string\n\treadonly scope: IssueScope\n\t/** Who found it: `local` is this package, `preflight` and `process` are the backend's checks. */\n\treadonly source: string\n\treadonly rowId: RowId | null\n\treadonly field: string | null\n\t/** Other cells the issue is about, such as the rows holding the same value as this one. */\n\treadonly targets: readonly IssueTarget[]\n\t/** Never renamed: what an application words its messages from. */\n\treadonly code: string\n\treadonly severity: IssueSeverity\n\t/** Whether it stops the sheet from being processed. Every local error does; no warning does. */\n\treadonly blocking: boolean\n\t/**\n\t * A backend found it, and a cell it is about has changed since. It is not taken as fixed: only\n\t * checking again can say. A stale issue counts apart, and blocks nothing.\n\t */\n\treadonly stale: boolean\n\t/** A sentence to show when an interface has no wording of its own for the code. */\n\treadonly message: string\n\treadonly params: Readonly<Record<string, string>>\n}\n\nexport interface IssueSummary {\n\t/** Errors still standing; stale ones are counted apart. */\n\treadonly errors: number\n\treadonly warnings: number\n\t/** Issues waiting for the backend to check again. */\n\treadonly stale: number\n\t/** Rows with at least one issue. */\n\treadonly rows: number\n}\n\n/**\n * Issues a view can show: a validator's own, or those merged with a backend's answers. The grid and\n * the issue panel read either through this.\n */\nexport interface IssueSet {\n\t/** Moves on every change, for a view to redraw by. */\n\treadonly version: number\n\t/** The issues on one cell. */\n\tissuesAt(rowId: RowId, field: string): readonly Issue[]\n\t/** The issues about a row as a whole rather than one of its cells. */\n\trowIssues(rowId: RowId): readonly Issue[]\n\t/** Whether any issue is on the row, on one of its cells or about it as a whole. */\n\thasIssues(rowId: RowId): boolean\n\t/** Every issue: those about the whole sheet first, then by row as the rows stand, then by column. */\n\tissues(): Issue[]\n\tsummary(): IssueSummary\n\t/** Called after each change. Returns the way to stop. */\n\tsubscribe(listener: () => void): () => void\n}\n\ntype CellIssues = Map<string, readonly Issue[]>\n\n/**\n * How many other rows a \"same value\" issue points at. Its `count` param says how many there are in\n * all. Listing every one would put 49,999 targets on each of 50,000 rows after one paste.\n */\nconst MAX_TARGETS = 10\n\n/**\n * Checks a sheet against its schema and keeps the result current.\n *\n * It listens to the row store and, after each change, checks only the cells the change touched.\n * A field with a `unique` rule is the one exception that looks across rows: changing one value can\n * clear or raise the issue on every other row holding it, and only those rows are touched.\n *\n * The schema's row checks are checked for the row a change touched, and only those that read the\n * field it changed. Their issues land on the cell each check is about, as errors or as warnings.\n */\nexport class SheetValidator implements IssueSet {\n\treadonly #schema: ModuleSchema\n\treadonly #store: RowStore\n\t#settings: ValueSettings\n\treadonly #cells = new Map<RowId, CellIssues>()\n\t/** For each unique field: value key to the rows holding it, and each row's key. */\n\treadonly #groups = new Map<string, Map<string, Set<RowId>>>()\n\treadonly #keys = new Map<string, Map<RowId, string>>()\n\t/** Groups of rows holding one value, in sheet order: sorted once per change, when first asked. */\n\treadonly #sorted = new Map<string, readonly RowId[]>()\n\t/** The row checks that read each field: what to check again when it changes. */\n\treadonly #checksOf = new Map<string, RowCheck[]>()\n\t/** Each row's broken checks, by check id. */\n\treadonly #broken = new Map<RowId, Map<string, Issue>>()\n\treadonly #listeners = new Listeners<SheetValidator>()\n\treadonly #unsubscribe: () => void\n\t#version = 0\n\n\tconstructor(schema: ModuleSchema, store: RowStore, settings: ValueSettings = VALUE_SETTINGS.tr) {\n\t\tthis.#schema = schema\n\t\tthis.#store = store\n\t\tthis.#settings = settings\n\n\t\tfor (const field of schema.fields) {\n\t\t\tif (hasRule(field, \"unique\")) {\n\t\t\t\tthis.#groups.set(field.key, new Map())\n\t\t\t\tthis.#keys.set(field.key, new Map())\n\t\t\t}\n\t\t}\n\n\t\tfor (const check of schema.checks) {\n\t\t\tfor (const key of checkFields(check)) {\n\t\t\t\tthis.#checksOf.set(key, [...(this.#checksOf.get(key) ?? []), check])\n\t\t\t}\n\t\t}\n\n\t\tthis.#checkAll()\n\t\tthis.#unsubscribe = store.subscribe(change => this.#apply(change))\n\t}\n\n\t/** Counts changes to the issues: a view redraws when it moves. */\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\t/** The issues on one cell, in a fixed order: the cell's own first, then any across rows. */\n\tissuesAt(rowId: RowId, field: string): readonly Issue[] {\n\t\tconst own = this.#cells.get(rowId)?.get(field) ?? []\n\t\tconst broken = this.#broken.get(rowId)\n\t\tconst checks = broken ? [...broken.values()].filter(issue => issue.field === field) : []\n\t\tconst shared = this.#uniqueIssue(rowId, field)\n\n\t\tif (checks.length === 0 && !shared) {\n\t\t\treturn own\n\t\t}\n\n\t\treturn shared ? [...own, ...checks, shared] : [...own, ...checks]\n\t}\n\n\t/** None: every local issue, a row check's too, lands on a cell. */\n\trowIssues(): readonly Issue[] {\n\t\treturn []\n\t}\n\n\t/** Every issue, in sheet order: by row as the rows stand now, then by column. */\n\tissues(): Issue[] {\n\t\tconst result: Issue[] = []\n\n\t\tfor (const rowId of this.#store.rowIds()) {\n\t\t\tfor (const field of this.#schema.fields) {\n\t\t\t\tresult.push(...this.issuesAt(rowId, field.key))\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n\t/** Counted without building the issues, so a sheet with 50,000 of them counts as fast as one with ten. */\n\tsummary(): IssueSummary {\n\t\tlet errors = 0\n\t\tlet warnings = 0\n\n\t\tfor (const cells of this.#cells.values()) {\n\t\t\tfor (const issues of cells.values()) {\n\t\t\t\tfor (const issue of issues) {\n\t\t\t\t\tif (issue.severity === \"error\") {\n\t\t\t\t\t\terrors++\n\t\t\t\t\t} else {\n\t\t\t\t\t\twarnings++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const groups of this.#groups.values()) {\n\t\t\tfor (const group of groups.values()) {\n\t\t\t\tif (group.size > 1) {\n\t\t\t\t\terrors += group.size\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const broken of this.#broken.values()) {\n\t\t\tfor (const issue of broken.values()) {\n\t\t\t\tif (issue.severity === \"error\") {\n\t\t\t\t\terrors++\n\t\t\t\t} else {\n\t\t\t\t\twarnings++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { errors, warnings, stale: 0, rows: this.affectedRows().size }\n\t}\n\n\t/** The rows with at least one issue. */\n\taffectedRows(): Set<RowId> {\n\t\tconst rows = new Set([...this.#cells.keys(), ...this.#broken.keys()])\n\n\t\tfor (const groups of this.#groups.values()) {\n\t\t\tfor (const group of groups.values()) {\n\t\t\t\tif (group.size > 1) {\n\t\t\t\t\tfor (const rowId of group) {\n\t\t\t\t\t\trows.add(rowId)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn rows\n\t}\n\n\thasIssues(rowId: RowId): boolean {\n\t\t// A row check may be a warning; every other local issue is an error.\n\t\treturn this.#broken.has(rowId) || this.hasErrors(rowId)\n\t}\n\n\t/** Whether any error stands on the row: such a row is not sent to be processed. */\n\thasErrors(rowId: RowId): boolean {\n\t\tconst cells = this.#cells.get(rowId)\n\n\t\tif (cells) {\n\t\t\tfor (const issues of cells.values()) {\n\t\t\t\tif (issues.some(issue => issue.severity === \"error\")) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const issue of this.#broken.get(rowId)?.values() ?? []) {\n\t\t\tif (issue.severity === \"error\") {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\tfor (const [field, keys] of this.#keys) {\n\t\t\tconst key = keys.get(rowId)\n\n\t\t\tif (key !== undefined && (this.#groups.get(field)?.get(key)?.size ?? 0) > 1) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\n\t/** The settings text is read with: a backend is sent what they read a host's text as. */\n\tget settings(): ValueSettings {\n\t\treturn this.#settings\n\t}\n\n\t/** Settings decide which text reads as a value, so changing them checks every cell again. */\n\tsetSettings(settings: ValueSettings): void {\n\t\tif (settings === this.#settings) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#settings = settings\n\t\tthis.#checkAll()\n\t\tthis.#changed()\n\t}\n\n\t/** Called after each change to the issues. Returns the way to stop. */\n\tsubscribe(listener: (validator: SheetValidator) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Stops listening to the store. */\n\tdispose(): void {\n\t\tthis.#unsubscribe()\n\t}\n\n\t// ---------------------------------------------------------------- internals\n\n\t#checkAll(): void {\n\t\tthis.#cells.clear()\n\t\tthis.#broken.clear()\n\n\t\tfor (const groups of this.#groups.values()) {\n\t\t\tgroups.clear()\n\t\t}\n\n\t\tfor (const keys of this.#keys.values()) {\n\t\t\tkeys.clear()\n\t\t}\n\n\t\tfor (const rowId of this.#store.rowIds()) {\n\t\t\tthis.#checkRow(rowId)\n\t\t}\n\t}\n\n\t#apply(change: StoreChange): void {\n\t\tfor (const operation of change.operations) {\n\t\t\tswitch (operation.kind) {\n\t\t\t\tcase \"set\":\n\t\t\t\t\tif (this.#store.has(operation.rowId) && this.#schema.has(operation.field)) {\n\t\t\t\t\t\tthis.#checkCell(operation.rowId, this.#schema.field(operation.field))\n\t\t\t\t\t\tthis.#checkChecks(operation.rowId, this.#checksOf.get(operation.field) ?? [])\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase \"insert\":\n\t\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\t\tif (this.#store.has(row.rowId)) {\n\t\t\t\t\t\t\tthis.#checkRow(row.rowId)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase \"remove\":\n\t\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\t\tthis.#forget(row.rowId)\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tthis.#changed()\n\t}\n\n\t#changed(): void {\n\t\tthis.#sorted.clear()\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n\n\t#checkRow(rowId: RowId): void {\n\t\tfor (const field of this.#schema.fields) {\n\t\t\tthis.#checkCell(rowId, field)\n\t\t}\n\n\t\tthis.#checkChecks(rowId, this.#schema.checks)\n\t}\n\n\t#checkChecks(rowId: RowId, checks: readonly RowCheck[]): void {\n\t\tif (checks.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tconst get = (key: string): CellValue => this.#store.get(rowId, key)\n\t\tconst field = (key: string): FieldSchema => this.#schema.field(key)\n\t\tlet broken = this.#broken.get(rowId)\n\n\t\tfor (const check of checks) {\n\t\t\tif (breaksCheck(check, field, get, this.#settings)) {\n\t\t\t\tif (!broken) {\n\t\t\t\t\tbroken = new Map()\n\t\t\t\t\tthis.#broken.set(rowId, broken)\n\t\t\t\t}\n\n\t\t\t\tbroken.set(check.id, checkIssue(rowId, check, this.#schema, this.#settings))\n\t\t\t} else {\n\t\t\t\tbroken?.delete(check.id)\n\t\t\t}\n\t\t}\n\n\t\tif (broken?.size === 0) {\n\t\t\tthis.#broken.delete(rowId)\n\t\t}\n\t}\n\n\t#checkCell(rowId: RowId, field: FieldSchema): void {\n\t\tconst value = this.#store.get(rowId, field.key)\n\t\tconst issues = checkValue(rowId, field, value, this.#settings)\n\t\tlet row = this.#cells.get(rowId)\n\n\t\tif (issues.length > 0) {\n\t\t\tif (!row) {\n\t\t\t\trow = new Map()\n\t\t\t\tthis.#cells.set(rowId, row)\n\t\t\t}\n\n\t\t\trow.set(field.key, issues)\n\t\t} else if (row) {\n\t\t\trow.delete(field.key)\n\n\t\t\tif (row.size === 0) {\n\t\t\t\tthis.#cells.delete(rowId)\n\t\t\t}\n\t\t}\n\n\t\tif (this.#groups.has(field.key)) {\n\t\t\t// A value with a problem of its own takes no part in uniqueness: \"abc\" in a number column is\n\t\t\t// not the same number as anything. The rest are compared as the backend is sent them, so a\n\t\t\t// host's \"1.234\" is the same number as 1234.\n\t\t\tthis.#regroup(\n\t\t\t\trowId,\n\t\t\t\tfield.key,\n\t\t\t\tissues.length === 0 ? uniqueKey(canonicalValue(field, value, this.#settings)) : null\n\t\t\t)\n\t\t}\n\t}\n\n\t#forget(rowId: RowId): void {\n\t\tthis.#cells.delete(rowId)\n\t\tthis.#broken.delete(rowId)\n\n\t\tfor (const field of this.#groups.keys()) {\n\t\t\tthis.#regroup(rowId, field, null)\n\t\t}\n\t}\n\n\t#regroup(rowId: RowId, field: string, key: string | null): void {\n\t\tconst groups = this.#groups.get(field)\n\t\tconst keys = this.#keys.get(field)\n\n\t\tif (!groups || !keys) {\n\t\t\treturn\n\t\t}\n\n\t\tconst previous = keys.get(rowId)\n\n\t\tif (previous !== undefined) {\n\t\t\tconst group = groups.get(previous)\n\n\t\t\tgroup?.delete(rowId)\n\n\t\t\tif (group?.size === 0) {\n\t\t\t\tgroups.delete(previous)\n\t\t\t}\n\n\t\t\tkeys.delete(rowId)\n\t\t}\n\n\t\tif (key !== null) {\n\t\t\tconst group = groups.get(key) ?? new Set<RowId>()\n\n\t\t\tgroup.add(rowId)\n\t\t\tgroups.set(key, group)\n\t\t\tkeys.set(rowId, key)\n\t\t}\n\t}\n\n\t#uniqueIssue(rowId: RowId, field: string): Issue | null {\n\t\tconst key = this.#keys.get(field)?.get(rowId)\n\t\tconst group = key === undefined ? undefined : this.#groups.get(field)?.get(key)\n\n\t\tif (!group || group.size < 2) {\n\t\t\treturn null\n\t\t}\n\n\t\t// The first others in the order the sheet has them, so the list reads top to bottom. The\n\t\t// group is sorted once per change and shared by every row in it.\n\t\tconst cacheKey = `${field}\\u0000${key}`\n\t\tlet sorted = this.#sorted.get(cacheKey)\n\n\t\tif (!sorted) {\n\t\t\tsorted = [...group].sort((a, b) => this.#store.indexOf(a) - this.#store.indexOf(b))\n\t\t\tthis.#sorted.set(cacheKey, sorted)\n\t\t}\n\n\t\tconst others = sorted\n\t\t\t.slice(0, MAX_TARGETS + 1)\n\t\t\t.filter(other => other !== rowId)\n\t\t\t.slice(0, MAX_TARGETS)\n\t\tconst value = describe(this.#store.get(rowId, field))\n\t\tconst params = Object.freeze({ field, value, count: String(group.size) })\n\n\t\treturn Object.freeze({\n\t\t\tid: `local|not_unique|${rowId}|${field}`,\n\t\t\tscope: \"cell\",\n\t\t\tsource: \"local\",\n\t\t\trowId,\n\t\t\tfield,\n\t\t\ttargets: Object.freeze(others.map(other => Object.freeze({ rowId: other, field }))),\n\t\t\tcode: \"not_unique\",\n\t\t\tseverity: \"error\",\n\t\t\tblocking: true,\n\t\t\tstale: false,\n\t\t\tmessage: `\"${value}\" appears ${group.size} times in this column; it may appear once.`,\n\t\t\tparams\n\t\t})\n\t}\n}\n\n/** The issues of one value, apart from uniqueness, which needs the other rows. */\nexport function checkValue(rowId: RowId, field: FieldSchema, value: CellValue, settings: ValueSettings): Issue[] {\n\t// A formula that could not be worked out: its error is the only thing to say about the cell.\n\tif (isFormulaError(value)) {\n\t\treturn [\n\t\t\tcellIssue(rowId, field, \"formula_error\", `The formula gives ${value.formulaError}.`, {\n\t\t\t\terror: value.formulaError\n\t\t\t})\n\t\t]\n\t}\n\n\tconst problem = valueProblem(field, value, settings)\n\n\t// A value that is not of its type is only that: a minimum means nothing for \"abc\".\n\tif (problem) {\n\t\treturn [cellIssue(rowId, field, problem.code, problem.message, problem.params)]\n\t}\n\n\tif (value === null) {\n\t\treturn field.required\n\t\t\t? [cellIssue(rowId, field, \"required\", \"This field is required and cannot be left empty.\", {})]\n\t\t\t: []\n\t}\n\n\tconst issues: Issue[] = []\n\t// The rules hold for the value the backend is sent: a host's \"1.234,5\" is 1234.5 against a maximum.\n\tconst sent = canonicalValue(field, value, settings)\n\n\tfor (const rule of field.rules) {\n\t\tconst issue = checkRule(rowId, field, rule, sent)\n\n\t\tif (issue) {\n\t\t\tissues.push(issue)\n\t\t}\n\t}\n\n\treturn issues\n}\n\nfunction checkRule(rowId: RowId, field: FieldSchema, rule: FieldRule, value: CellValue): Issue | null {\n\tswitch (rule.rule) {\n\t\tcase \"min\":\n\t\tcase \"max\": {\n\t\t\tconst number = decimalText(value)\n\n\t\t\tif (number === null) {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\tconst comparison = compareDecimal(normalize(number), rule.value)\n\n\t\t\tif (rule.rule === \"min\" && comparison < 0) {\n\t\t\t\treturn cellIssue(rowId, field, \"min_value\", `${number} is below the minimum of ${rule.value}.`, {\n\t\t\t\t\tvalue: number,\n\t\t\t\t\tmin: rule.value\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (rule.rule === \"max\" && comparison > 0) {\n\t\t\t\treturn cellIssue(rowId, field, \"max_value\", `${number} is above the maximum of ${rule.value}.`, {\n\t\t\t\t\tvalue: number,\n\t\t\t\t\tmax: rule.value\n\t\t\t\t})\n\t\t\t}\n\n\t\t\treturn null\n\t\t}\n\t\tcase \"minLength\":\n\t\tcase \"maxLength\": {\n\t\t\tif (typeof value !== \"string\") {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\t// Characters a reader counts, not UTF-16 units: an emoji is one.\n\t\t\tconst length = Array.from(value).length\n\n\t\t\tif (rule.rule === \"minLength\" && length < rule.value) {\n\t\t\t\treturn cellIssue(rowId, field, \"min_length\", `\"${value}\" is shorter than ${rule.value} characters.`, {\n\t\t\t\t\tvalue,\n\t\t\t\t\tmin: String(rule.value),\n\t\t\t\t\tlength: String(length)\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (rule.rule === \"maxLength\" && length > rule.value) {\n\t\t\t\treturn cellIssue(rowId, field, \"max_length\", `\"${value}\" is longer than ${rule.value} characters.`, {\n\t\t\t\t\tvalue,\n\t\t\t\t\tmax: String(rule.value),\n\t\t\t\t\tlength: String(length)\n\t\t\t\t})\n\t\t\t}\n\n\t\t\treturn null\n\t\t}\n\t\tcase \"unique\":\n\t\t\treturn null\n\t}\n}\n\nfunction cellIssue(\n\trowId: RowId,\n\tfield: FieldSchema,\n\tcode: LocalIssueCode,\n\tmessage: string,\n\tparams: Readonly<Record<string, string>>\n): Issue {\n\treturn Object.freeze({\n\t\tid: `local|${code}|${rowId}|${field.key}`,\n\t\tscope: \"cell\",\n\t\tsource: \"local\",\n\t\trowId,\n\t\tfield: field.key,\n\t\ttargets: Object.freeze([]),\n\t\tcode,\n\t\tseverity: \"error\",\n\t\tblocking: true,\n\t\tstale: false,\n\t\tmessage,\n\t\tparams: Object.freeze({ field: field.key, type: field.type, ...params })\n\t})\n}\n\nconst SYMBOLS: Readonly<Record<ConditionOp, string>> = {\n\t\"=\": \"=\",\n\t\"!=\": \"≠\",\n\t\"<\": \"<\",\n\t\"<=\": \"≤\",\n\t\">\": \">\",\n\t\">=\": \"≥\",\n\tfilled: \"filled\",\n\tempty: \"empty\"\n}\n\nconst ENGLISH_COMPARISONS: Readonly<Record<string, string>> = {\n\t\"=\": \"equal to\",\n\t\"!=\": \"different from\",\n\t\"<\": \"less than\",\n\t\"<=\": \"at most\",\n\t\">\": \"greater than\",\n\t\">=\": \"at least\"\n}\n\n/**\n * A broken row check as an issue on the cell it is about. Its params carry what an interface words\n * it from, in the sheet's own writing: the other field by its label, a value as the sheet writes\n * it, each condition of `when` as `when0Field`, `when0Op` and `when0Value`, and a check's own\n * words as `message.tr`, `message.en`.\n */\nfunction checkIssue(rowId: RowId, check: RowCheck, schema: ModuleSchema, settings: ValueSettings): Issue {\n\tconst field = schema.field(check.assert.field)\n\tconst label = (key: string): string => schema.field(key).label\n\tconst operand = (condition: RowCondition): string =>\n\t\tcondition.other !== null\n\t\t\t? label(condition.other)\n\t\t\t: condition.value === null\n\t\t\t\t? \"\"\n\t\t\t\t: formatCell(schema.field(condition.field), condition.value, settings)\n\tconst op = check.assert.op\n\tconst code: LocalIssueCode = op === \"filled\" ? \"check_filled\" : op === \"empty\" ? \"check_empty\" : \"check_compare\"\n\tconst params: Record<string, string> = {\n\t\tfield: field.key,\n\t\ttype: field.type,\n\t\tcheck: check.id,\n\t\top,\n\t\twhen: String(check.when.length)\n\t}\n\n\tif (code === \"check_compare\") {\n\t\tparams.operand = operand(check.assert)\n\t}\n\n\tcheck.when.forEach((condition, index) => {\n\t\tparams[`when${index}Field`] = label(condition.field)\n\t\tparams[`when${index}Op`] = condition.op\n\t\tparams[`when${index}Value`] = operand(condition)\n\t})\n\n\tfor (const [language, text] of Object.entries(check.message ?? {})) {\n\t\tparams[`message.${language}`] = text\n\t}\n\n\tconst when =\n\t\tcheck.when.length === 0\n\t\t\t? \"\"\n\t\t\t: ` when ${check.when\n\t\t\t\t\t.map(condition =>\n\t\t\t\t\t\tcondition.op === \"filled\" || condition.op === \"empty\"\n\t\t\t\t\t\t\t? `${label(condition.field)} is ${condition.op}`\n\t\t\t\t\t\t\t: `${label(condition.field)} ${SYMBOLS[condition.op]} ${operand(condition)}`\n\t\t\t\t\t)\n\t\t\t\t\t.join(\" and \")}`\n\tconst english =\n\t\tcode === \"check_filled\"\n\t\t\t? `${field.label} is required${when}.`\n\t\t\t: code === \"check_empty\"\n\t\t\t\t? `${field.label} must be left empty${when}.`\n\t\t\t\t: `${field.label} must be ${ENGLISH_COMPARISONS[op] ?? op} ${params.operand}${when}.`\n\n\treturn Object.freeze({\n\t\tid: `local|check|${check.id}|${rowId}`,\n\t\tscope: \"cell\",\n\t\tsource: \"local\",\n\t\trowId,\n\t\tfield: field.key,\n\t\ttargets: Object.freeze(\n\t\t\tcheck.assert.other === null ? [] : [Object.freeze({ rowId, field: check.assert.other })]\n\t\t),\n\t\tcode,\n\t\tseverity: check.severity,\n\t\tblocking: check.severity === \"error\",\n\t\tstale: false,\n\t\tmessage: check.message?.en ?? english,\n\t\tparams: Object.freeze(params)\n\t})\n}\n\nfunction hasRule(field: FieldSchema, rule: FieldRule[\"rule\"]): boolean {\n\treturn field.rules.some(candidate => candidate.rule === rule)\n}\n\n/** What makes two values the same for uniqueness: a lookup by its id, anything else by its content. */\nfunction uniqueKey(value: CellValue): string | null {\n\tif (value === null) {\n\t\treturn null\n\t}\n\n\tif (isLookupValue(value)) {\n\t\treturn `id:${typeof value.id}:${value.id}`\n\t}\n\n\tconst number = typeof value === \"number\" || typeof value === \"string\" ? decimalText(value) : null\n\n\t// \"12.50\" and 12.5 are one number.\n\treturn number !== null ? `number:${normalize(number)}` : `value:${JSON.stringify(value)}`\n}\n\n/** Decimal text in one form, so \"12.50\" and \"12.5\" compare and group as one number. */\nfunction normalize(number: string): string {\n\tconst negative = number.startsWith(\"-\")\n\tconst [whole = \"0\", fraction = \"\"] = (negative ? number.slice(1) : number).split(\".\")\n\tconst trimmedWhole = whole.replace(/^0+(?=\\d)/, \"\")\n\tconst trimmedFraction = fraction.replace(/0+$/, \"\")\n\tconst body = trimmedFraction === \"\" ? trimmedWhole : `${trimmedWhole}.${trimmedFraction}`\n\n\treturn body === \"0\" || !negative ? body : `-${body}`\n}\n\nfunction describe(value: CellValue): string {\n\tif (isLookupValue(value)) {\n\t\treturn value.label\n\t}\n\n\treturn typeof value === \"string\" ? value : JSON.stringify(value)\n}\n","import { TabulaError } from \"./errors.js\"\nimport type { RowId } from \"./rows.js\"\nimport type { IssueScope, IssueSeverity, IssueTarget } from \"./validation.js\"\nimport type { CellValue } from \"./value.js\"\n\n/**\n * What passes between a sheet and the backend of the application that embeds it.\n *\n * The package never chooses how: an application gives a `SheetAdapters` object, and each adapter\n * calls its backend however it likes and turns the answer into the shapes here. That is also where\n * a backend with answers of its own shape is adapted.\n */\n\n/** One row as a backend receives it, under the id it keeps in the sheet. */\nexport interface PayloadRow {\n\treadonly rowId: RowId\n\t/**\n\t * Every field of the schema that is submitted (`submit`), empty ones as null, in the form the grid\n\t * writes: a number as decimal text with a point, a date as ISO 8601, a yes/no as a boolean, an\n\t * option as its value. Text a host loaded, such as \"1.234,56\", goes as what it reads to; text the\n\t * grid could not read goes as it stands. A lookup is sent as its id; one holding text never\n\t * matched to a record is sent as `{ label }`, for the backend to match or refuse.\n\t */\n\treadonly values: Readonly<Record<string, CellValue>>\n}\n\n/** What a pre-flight check is sent, and what a process run is sent with its key. */\nexport interface SheetRequest {\n\t/** Pairs an answer with its question; new for every request. */\n\treadonly requestId: string\n\treadonly module: string\n\treadonly schemaVersion: number\n\treadonly sheetId: string\n\t/** The revision of the sheet the rows were read at: what the answer will be about. */\n\treadonly revision: number\n\treadonly rows: readonly PayloadRow[]\n}\n\nexport interface ProcessRequest extends SheetRequest {\n\t/**\n\t * The same for every attempt at one run, so a backend that has seen it answers with what it did\n\t * rather than doing it twice. A run that got a definite answer is never sent again; the next one\n\t * gets a new key.\n\t */\n\treadonly idempotencyKey: string\n}\n\n/** An issue as a backend reports it. Everything but `code` has a sensible default. */\nexport interface IssueInput {\n\t/** Left out: `cell` with a row and a field, `row` with a row only, `sheet` with neither. */\n\treadonly scope?: IssueScope\n\t/** Another sheet's issue is passed over. */\n\treadonly sheetId?: string | null\n\treadonly rowId?: RowId | null\n\treadonly field?: string | null\n\treadonly targets?: readonly IssueTarget[]\n\treadonly code: string\n\t/** `error` by default. */\n\treadonly severity?: IssueSeverity\n\t/** Whether it stops the sheet from being processed; by default, an error does and a warning does not. */\n\treadonly blocking?: boolean\n\t/** Shown when the interface has no wording of its own for the code; the code itself by default. */\n\treadonly message?: string\n\treadonly params?: Readonly<Record<string, string | number | boolean | null>>\n}\n\n/**\n * What processing a row would do: make a new record, change one, or leave one as it is. Only the\n * backend can tell, for only it holds the records.\n */\nexport type RowAction = \"create\" | \"update\" | \"unchanged\"\n\n/** What a pre-flight check says a row would do, for a preview before the run. */\nexport interface RowPlanInput {\n\treadonly rowId: RowId\n\treadonly action: RowAction\n\t/**\n\t * For an update, each field that would change, with the value the backend holds now, in the form\n\t * rows are sent in; a lookup may come as `{ id, label }`, to be shown by its label. A field left\n\t * out is not changing.\n\t */\n\treadonly previous?: Readonly<Record<string, CellValue>>\n}\n\nexport interface CheckResponse {\n\t/** When given, it must be the request's. */\n\treadonly requestId?: string\n\treadonly issues?: readonly IssueInput[]\n\t/**\n\t * What each row would do if it were processed now. A backend that cannot tell leaves it out, and\n\t * a preview then has only the count of rows to show; so does a row it leaves out.\n\t */\n\treadonly plan?: readonly RowPlanInput[]\n}\n\n/**\n * `pending`: accepted and still running; the session asks `processStatus` until it is not.\n * `partial`: some rows went through and some did not, which only a backend that allows it says.\n * `cancelled`: stopped on request. Rows done before the stop stay done: a cancel takes nothing back.\n */\nexport type ProcessStatus = \"pending\" | \"succeeded\" | \"partial\" | \"failed\" | \"cancelled\"\n\n/** `skipped`: not processed at all, such as after another row failed in an all-or-nothing run. */\nexport type RowOutcome = \"succeeded\" | \"failed\" | \"skipped\"\n\nexport interface RowResultInput {\n\treadonly rowId: RowId\n\treadonly result: RowOutcome\n\t/** Bound to this row unless they name another. */\n\treadonly issues?: readonly IssueInput[]\n\t/** Whatever the backend wants kept with the row, such as the id of the record it created. */\n\treadonly data?: Readonly<Record<string, CellValue>>\n}\n\nexport interface ProcessProgress {\n\treadonly done: number\n\treadonly total: number\n}\n\nexport interface ProcessResponse {\n\t/** When given, it must be the request's. */\n\treadonly requestId?: string\n\t/** The backend's name for the run, to ask about it or cancel it by. */\n\treadonly operationId?: string | null\n\treadonly status: ProcessStatus\n\t/**\n\t * A row of the request left out is taken as not processed, unless the run as a whole succeeded.\n\t * A row the request did not hold is passed over.\n\t */\n\treadonly rows?: readonly RowResultInput[]\n\t/** About the run as a whole rather than one row. */\n\treadonly issues?: readonly IssueInput[]\n\treadonly progress?: ProcessProgress | null\n}\n\n/** How a run is asked about or cancelled: by its operation id when known, always by its key. */\nexport interface StatusQuery {\n\treadonly requestId: string\n\treadonly idempotencyKey: string\n\treadonly operationId: string | null\n}\n\nexport interface AdapterContext {\n\t/** Aborted when the answer is no longer wanted. An adapter passes it on to its HTTP client. */\n\treadonly signal: AbortSignal\n\treadonly requestId: string\n}\n\n/**\n * How a sheet reaches its backend. Each is optional: a sheet with no `preflight` has no backend\n * check, one with no `processStatus` cannot follow a run that answers `pending`.\n *\n * An adapter that throws, such as on a network error, is a failure of the request, kept apart from\n * the issues of the data. One that answers in the wrong shape is a failure too.\n */\nexport interface SheetAdapters {\n\tpreflight?(request: SheetRequest, context: AdapterContext): Promise<CheckResponse>\n\tprocess?(request: ProcessRequest, context: AdapterContext): Promise<ProcessResponse>\n\tprocessStatus?(query: StatusQuery, context: AdapterContext): Promise<ProcessResponse>\n\tcancelProcess?(query: StatusQuery, context: AdapterContext): Promise<void>\n}\n\n// ---------------------------------------------------------------- reading answers\n\nconst SCOPES: readonly string[] = [\"cell\", \"row\", \"sheet\", \"workbook\"]\nconst SEVERITIES: readonly string[] = [\"error\", \"warning\"]\nconst STATUSES: readonly string[] = [\"pending\", \"succeeded\", \"partial\", \"failed\", \"cancelled\"]\nconst OUTCOMES: readonly string[] = [\"succeeded\", \"failed\", \"skipped\"]\nconst ACTIONS: readonly string[] = [\"create\", \"update\", \"unchanged\"]\n\n/**\n * Checks a pre-flight answer against the contract. Properties it does not know are passed over, so\n * a backend may send more; a known one of the wrong kind is refused, with every problem at once.\n *\n * @throws TabulaError `invalid_response`\n */\nexport function readCheckResponse(input: unknown): CheckResponse {\n\tconst reader = new Reader()\n\tconst root = reader.object(input, \"(root)\")\n\n\tif (root === null) {\n\t\treturn reader.done({})\n\t}\n\n\treturn reader.done({\n\t\t...optional(\"requestId\", reader.string(root.requestId, \"requestId\", true)),\n\t\t...optional(\"issues\", reader.issues(root.issues, \"issues\")),\n\t\t...optional(\"plan\", reader.plans(root.plan, \"plan\"))\n\t})\n}\n\n/**\n * Checks a process answer, or a status answer, against the contract.\n *\n * @throws TabulaError `invalid_response`\n */\nexport function readProcessResponse(input: unknown): ProcessResponse {\n\tconst reader = new Reader()\n\tconst root = reader.object(input, \"(root)\")\n\n\tif (root === null) {\n\t\treturn reader.done({ status: \"failed\" })\n\t}\n\n\tconst status = reader.oneOf(root.status, \"status\", STATUSES)\n\n\treturn reader.done({\n\t\tstatus: (status ?? \"failed\") as ProcessStatus,\n\t\t...optional(\"requestId\", reader.string(root.requestId, \"requestId\", true)),\n\t\t...optional(\"operationId\", reader.nullableString(root.operationId, \"operationId\")),\n\t\t...optional(\"rows\", reader.rows(root.rows, \"rows\")),\n\t\t...optional(\"issues\", reader.issues(root.issues, \"issues\")),\n\t\t...optional(\"progress\", reader.progress(root.progress, \"progress\"))\n\t})\n}\n\nfunction optional<K extends string, V>(key: K, value: V | undefined): { [P in K]?: V } {\n\treturn value === undefined ? {} : ({ [key]: value } as { [P in K]?: V })\n}\n\ntype Plain = Record<string, unknown>\n\nclass Reader {\n\treadonly #problems: string[] = []\n\n\tdone<T>(value: T): T {\n\t\tif (this.#problems.length > 0) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_response\",\n\t\t\t\t`The backend's answer is not in the expected shape:\\n${this.#problems.map(line => ` ${line}`).join(\"\\n\")}`\n\t\t\t)\n\t\t}\n\n\t\treturn value\n\t}\n\n\tproblem(path: string, message: string): void {\n\t\tthis.#problems.push(`${path}: ${message}`)\n\t}\n\n\tobject(value: unknown, path: string): Plain | null {\n\t\tif (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n\t\t\treturn value as Plain\n\t\t}\n\n\t\tthis.problem(path, `must be an object; got ${describe(value)}.`)\n\n\t\treturn null\n\t}\n\n\t/** `undefined` when missing and allowed to be. */\n\tstring(value: unknown, path: string, optionalValue = false): string | undefined {\n\t\tif (value === undefined && optionalValue) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (typeof value === \"string\" && value !== \"\") {\n\t\t\treturn value\n\t\t}\n\n\t\tthis.problem(path, `must be a non-empty string; got ${describe(value)}.`)\n\n\t\treturn undefined\n\t}\n\n\tnullableString(value: unknown, path: string): string | null | undefined {\n\t\treturn value === null ? null : this.string(value, path, true)\n\t}\n\n\toneOf(value: unknown, path: string, allowed: readonly string[], optionalValue = false): string | undefined {\n\t\tif (value === undefined && optionalValue) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (typeof value === \"string\" && allowed.includes(value)) {\n\t\t\treturn value\n\t\t}\n\n\t\tthis.problem(path, `must be one of ${allowed.join(\", \")}; got ${describe(value)}.`)\n\n\t\treturn undefined\n\t}\n\n\tarray(value: unknown, path: string): unknown[] | undefined {\n\t\tif (value === undefined) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (Array.isArray(value)) {\n\t\t\treturn value\n\t\t}\n\n\t\tthis.problem(path, `must be an array; got ${describe(value)}.`)\n\n\t\treturn undefined\n\t}\n\n\tissues(value: unknown, path: string): IssueInput[] | undefined {\n\t\treturn this.array(value, path)\n\t\t\t?.map((item, index) => this.issue(item, `${path}[${index}]`))\n\t\t\t.filter((issue): issue is IssueInput => issue !== null)\n\t}\n\n\tissue(value: unknown, path: string): IssueInput | null {\n\t\tconst item = this.object(value, path)\n\n\t\tif (item === null) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst code = this.string(item.code, `${path}.code`)\n\t\tconst blocking = item.blocking\n\n\t\tif (blocking !== undefined && typeof blocking !== \"boolean\") {\n\t\t\tthis.problem(`${path}.blocking`, `must be true or false; got ${describe(blocking)}.`)\n\t\t}\n\n\t\treturn {\n\t\t\tcode: code ?? \"\",\n\t\t\t...optional(\"scope\", this.oneOf(item.scope, `${path}.scope`, SCOPES, true) as IssueScope | undefined),\n\t\t\t...optional(\"sheetId\", this.nullableString(item.sheetId, `${path}.sheetId`)),\n\t\t\t...optional(\"rowId\", this.nullableString(item.rowId, `${path}.rowId`)),\n\t\t\t...optional(\"field\", this.nullableString(item.field, `${path}.field`)),\n\t\t\t...optional(\"targets\", this.targets(item.targets, `${path}.targets`)),\n\t\t\t...optional(\n\t\t\t\t\"severity\",\n\t\t\t\tthis.oneOf(item.severity, `${path}.severity`, SEVERITIES, true) as IssueSeverity | undefined\n\t\t\t),\n\t\t\t...optional(\"blocking\", typeof blocking === \"boolean\" ? blocking : undefined),\n\t\t\t...optional(\"message\", this.string(item.message, `${path}.message`, true)),\n\t\t\t...optional(\"params\", this.params(item.params, `${path}.params`))\n\t\t}\n\t}\n\n\ttargets(value: unknown, path: string): IssueTarget[] | undefined {\n\t\treturn this.array(value, path)\n\t\t\t?.map((item, index) => {\n\t\t\t\tconst target = this.object(item, `${path}[${index}]`)\n\t\t\t\tconst rowId = target && this.string(target.rowId, `${path}[${index}].rowId`)\n\t\t\t\tconst field = target && this.string(target.field, `${path}[${index}].field`)\n\n\t\t\t\treturn rowId && field ? { rowId, field } : null\n\t\t\t})\n\t\t\t.filter((target): target is IssueTarget => target !== null)\n\t}\n\n\tparams(value: unknown, path: string): Record<string, string | number | boolean | null> | undefined {\n\t\tif (value === undefined) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tconst params = this.object(value, path)\n\n\t\tif (params === null) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tfor (const [key, param] of Object.entries(params)) {\n\t\t\tif (param !== null && ![\"string\", \"number\", \"boolean\"].includes(typeof param)) {\n\t\t\t\tthis.problem(`${path}.${key}`, `must be text, a number, true, false or null; got ${describe(param)}.`)\n\t\t\t}\n\t\t}\n\n\t\treturn params as Record<string, string | number | boolean | null>\n\t}\n\n\trows(value: unknown, path: string): RowResultInput[] | undefined {\n\t\treturn this.array(value, path)\n\t\t\t?.map((item, index) => this.row(item, `${path}[${index}]`))\n\t\t\t.filter((row): row is RowResultInput => row !== null)\n\t}\n\n\trow(value: unknown, path: string): RowResultInput | null {\n\t\tconst item = this.object(value, path)\n\n\t\tif (item === null) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst rowId = this.string(item.rowId, `${path}.rowId`)\n\t\tconst result = this.oneOf(item.result, `${path}.result`, OUTCOMES) as RowOutcome | undefined\n\t\tconst data = item.data === undefined ? undefined : this.object(item.data, `${path}.data`)\n\n\t\tif (rowId === undefined || result === undefined) {\n\t\t\treturn null\n\t\t}\n\n\t\treturn {\n\t\t\trowId,\n\t\t\tresult,\n\t\t\t...optional(\"issues\", this.issues(item.issues, `${path}.issues`)),\n\t\t\t...optional(\"data\", data === null ? undefined : (data as Record<string, CellValue>))\n\t\t}\n\t}\n\n\tplans(value: unknown, path: string): RowPlanInput[] | undefined {\n\t\treturn this.array(value, path)\n\t\t\t?.map((item, index) => this.plan(item, `${path}[${index}]`))\n\t\t\t.filter((plan): plan is RowPlanInput => plan !== null)\n\t}\n\n\tplan(value: unknown, path: string): RowPlanInput | null {\n\t\tconst item = this.object(value, path)\n\n\t\tif (item === null) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst rowId = this.string(item.rowId, `${path}.rowId`)\n\t\tconst action = this.oneOf(item.action, `${path}.action`, ACTIONS) as RowAction | undefined\n\t\tconst previous = item.previous === undefined ? undefined : this.object(item.previous, `${path}.previous`)\n\n\t\tif (rowId === undefined || action === undefined) {\n\t\t\treturn null\n\t\t}\n\n\t\treturn {\n\t\t\trowId,\n\t\t\taction,\n\t\t\t...optional(\"previous\", previous === null ? undefined : (previous as Record<string, CellValue>))\n\t\t}\n\t}\n\n\tprogress(value: unknown, path: string): ProcessProgress | null | undefined {\n\t\tif (value === undefined || value === null) {\n\t\t\treturn value\n\t\t}\n\n\t\tconst item = this.object(value, path)\n\t\tconst done = item?.done\n\t\tconst total = item?.total\n\n\t\tif (item === null) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (typeof done !== \"number\" || typeof total !== \"number\" || done < 0 || total < 0) {\n\t\t\tthis.problem(path, \"must have a done and a total, each a number, 0 or more.\")\n\n\t\t\treturn undefined\n\t\t}\n\n\t\treturn { done, total }\n\t}\n}\n\nfunction describe(value: unknown): string {\n\tif (value === null) {\n\t\treturn \"null\"\n\t}\n\n\tif (Array.isArray(value)) {\n\t\treturn \"an array\"\n\t}\n\n\treturn typeof value === \"string\" ? JSON.stringify(value) : typeof value\n}\n","import { freezeColumnLayout, mapColumnLayout, readColumnLayout, type ColumnLayout } from \"./columns.js\"\nimport type { ProcessRequest } from \"./contract.js\"\nimport { TabulaError } from \"./errors.js\"\nimport { readMarks, type CellMark, type CellMarks, type MarksData } from \"./marks.js\"\nimport type { RowEntry, RowInit, RowStore } from \"./rows.js\"\nimport { FIELD_TYPES, type FieldSchema, type FieldType, type ModuleSchema } from \"./schema.js\"\nimport type { PendingRun, PersistedSession, RowResult, SheetSession } from \"./session.js\"\nimport { toCellValue, type CellValue } from \"./value.js\"\nimport { valueProblem } from \"./values/read.js\"\nimport { VALUE_SETTINGS, type ValueSettings } from \"./values/settings.js\"\n\n/**\n * A sheet saved to go on with later. Saving a draft creates no business record: it is the sheet as\n * it stands, its rows under their ids, and what the backend said about each.\n *\n * It is plain JSON, kept wherever the application keeps it. The rows were written against one\n * version of the module's schema; `openDraft` tells when the schema has moved on since, and opens\n * such a draft only once that has been seen and accepted.\n */\n\nexport const DRAFT_FORMAT = \"tabula-grid.draft\"\nexport const DRAFT_VERSION = 1\n\n/** A field as the draft's rows were written against it. */\nexport interface DraftField {\n\treadonly key: string\n\treadonly type: FieldType\n\t/** Its label then, so a field gone since is still known by name. Drafts saved before it was kept have none. */\n\treadonly label?: string\n}\n\n/** The user's view of the sheet. */\nexport interface DraftView {\n\t/** Widths the user set, by field key, as the grid's `columnWidths` holds them. */\n\treadonly columnWidths: Readonly<Record<string, number>>\n\t/** Which columns are hidden, pinned or moved, as the grid's `columns` holds them. */\n\treadonly columns?: ColumnLayout\n}\n\nexport interface Draft {\n\treadonly format: typeof DRAFT_FORMAT\n\t/** The version of this format, not of the module's schema. */\n\treadonly version: typeof DRAFT_VERSION\n\t/** Made by the browser, so every save of one draft is the same draft: a lost answer makes no second one. */\n\treadonly id: string\n\treadonly name: string | null\n\treadonly module: string\n\treadonly schemaVersion: number\n\treadonly sheetId: string\n\treadonly fields: readonly DraftField[]\n\t/** When it was saved, as ISO 8601 text. */\n\treadonly savedAt: string\n\t/** The sheet's revision when it was saved. */\n\treadonly revision: number\n\treadonly rows: readonly RowEntry[]\n\treadonly session: PersistedSession\n\treadonly view: DraftView\n\t/** What the user put on cells by hand, by row id then field key; left out when nothing is. */\n\treadonly marks?: MarksData\n}\n\nexport interface CreateDraftOptions {\n\treadonly id: string\n\treadonly name?: string | null\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\t/** Its results and any run with no answer go into the draft. */\n\treadonly session?: SheetSession | null\n\treadonly view?: DraftView\n\t/** The marks on the cells: kept for the rows the sheet has. */\n\treadonly marks?: CellMarks | null\n\treadonly now?: () => Date\n}\n\n/** The sheet as it stands, as a draft. */\nexport function createDraft(options: CreateDraftOptions): Draft {\n\tconst { schema, store, session } = options\n\tconst marks = options.marks ? options.marks.toJSON(store.rowIds()) : {}\n\n\treturn Object.freeze({\n\t\tformat: DRAFT_FORMAT,\n\t\tversion: DRAFT_VERSION,\n\t\tid: options.id,\n\t\tname: options.name ?? null,\n\t\tmodule: schema.module,\n\t\tschemaVersion: schema.schemaVersion,\n\t\tsheetId: session?.sheetId ?? schema.module,\n\t\tfields: Object.freeze(\n\t\t\tschema.fields.map(field => Object.freeze({ key: field.key, type: field.type, label: field.label }))\n\t\t),\n\t\tsavedAt: (options.now?.() ?? new Date()).toISOString(),\n\t\trevision: store.revision,\n\t\trows: Object.freeze(store.snapshot()),\n\t\tsession: session?.persisted() ?? Object.freeze({ results: Object.freeze([]), pending: null }),\n\t\tview: Object.freeze({\n\t\t\tcolumnWidths: Object.freeze({ ...options.view?.columnWidths }),\n\t\t\t...(options.view?.columns ? { columns: freezeColumnLayout(options.view.columns) } : {})\n\t\t}),\n\t\t...(Object.keys(marks).length > 0 ? { marks: freezeMarks(marks) } : {})\n\t})\n}\n\n// ---------------------------------------------------------------- opening\n\n/** How the module's schema has moved on since a draft was saved. */\nexport interface DraftChanges {\n\treadonly fromVersion: number\n\treadonly toVersion: number\n\t/** Fields the draft has no values for: they open empty. */\n\treadonly added: readonly string[]\n\t/** Fields the schema no longer has: their values are dropped. */\n\treadonly removed: readonly string[]\n\t/** Fields of another type now: their values are kept, and checked again as the new type. */\n\treadonly retyped: readonly { readonly key: string; readonly from: FieldType; readonly to: FieldType }[]\n\treadonly renamed: readonly { readonly from: string; readonly to: string }[]\n\t/** How many rows hold a value in a removed field: what dropping them loses. */\n\treadonly losing: number\n}\n\nexport interface OpenDraftOptions {\n\t/** Open even though the schema has moved on, once the user has seen `changes` and agreed. */\n\treadonly accept?: boolean\n\t/** A field renamed since, by its old key: its values go to the new one. */\n\treadonly rename?: Readonly<Record<string, string>>\n}\n\nexport type DraftOpening =\n\t| {\n\t\t\treadonly status: \"opened\"\n\t\t\t/** For a new `RowStore`, under the ids the rows had. */\n\t\t\treadonly rows: RowInit[]\n\t\t\t/** For a new `SheetSession`'s `restore`. */\n\t\t\treadonly session: PersistedSession\n\t\t\treadonly view: DraftView\n\t\t\t/** For a new `CellMarks`: the marks on the cells, by row id then field key. */\n\t\t\treadonly marks: MarksData\n\t\t\t/** What moved on since the draft was saved, or null when nothing did. */\n\t\t\treadonly changes: DraftChanges | null\n\t }\n\t/** The schema has moved on: show `changes`, and open again with `accept` if the user agrees. */\n\t| { readonly status: \"review\"; readonly changes: DraftChanges }\n\t/** A draft of another module altogether. */\n\t| { readonly status: \"wrong_module\"; readonly module: string }\n\n/**\n * Opens a draft against the module's schema as it is now. A draft saved under another schema\n * version is not opened silently: it comes back for review, with what changed, until it is opened\n * again with `accept`. Every value is then checked again by the sheet's validator, as any is.\n */\nexport function openDraft(draft: Draft, schema: ModuleSchema, options: OpenDraftOptions = {}): DraftOpening {\n\tif (draft.module !== schema.module) {\n\t\treturn { status: \"wrong_module\", module: draft.module }\n\t}\n\n\tconst rename = renames(draft, schema, options.rename ?? {})\n\tconst changes = compare(draft, schema, rename)\n\n\tif (changes && !options.accept) {\n\t\treturn { status: \"review\", changes }\n\t}\n\n\tconst keep = (key: string): string | null => {\n\t\tconst target = rename.get(key) ?? key\n\n\t\treturn schema.has(target) ? target : null\n\t}\n\n\tconst rows = draft.rows.map(row => {\n\t\tconst values: Record<string, CellValue> = {}\n\n\t\tfor (const [key, value] of Object.entries(row.values)) {\n\t\t\tconst target = keep(key)\n\n\t\t\tif (target !== null) {\n\t\t\t\tvalues[target] = value\n\t\t\t}\n\t\t}\n\n\t\treturn { rowId: row.rowId, values }\n\t})\n\n\tconst columnWidths: Record<string, number> = {}\n\n\tfor (const [key, width] of Object.entries(draft.view.columnWidths)) {\n\t\tconst target = keep(key)\n\n\t\tif (target !== null) {\n\t\t\tcolumnWidths[target] = width\n\t\t}\n\t}\n\n\t// The layout and the marks follow renamed fields, and let go of removed ones.\n\tconst columns = draft.view.columns ? mapColumnLayout(draft.view.columns, keep) : undefined\n\tconst marks: Record<string, Record<string, CellMark>> = {}\n\n\tfor (const [rowId, cells] of Object.entries(draft.marks ?? {})) {\n\t\tfor (const [key, mark] of Object.entries(cells)) {\n\t\t\tconst target = keep(key)\n\n\t\t\tif (target !== null) {\n\t\t\t\tmarks[rowId] = { ...marks[rowId], [target]: mark }\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tstatus: \"opened\",\n\t\trows,\n\t\tsession: draft.session,\n\t\tview: Object.freeze({ columnWidths: Object.freeze(columnWidths), ...(columns ? { columns } : {}) }),\n\t\tmarks: freezeMarks(marks),\n\t\tchanges\n\t}\n}\n\nfunction renames(draft: Draft, schema: ModuleSchema, given: Readonly<Record<string, string>>): Map<string, string> {\n\tconst keys = new Set(draft.fields.map(field => field.key))\n\tconst map = new Map<string, string>()\n\n\tfor (const [from, to] of Object.entries(given)) {\n\t\tif (!keys.has(from)) {\n\t\t\tthrow new TabulaError(\"invalid_argument\", `The draft has no field \"${from}\" to rename.`)\n\t\t}\n\n\t\tif (!schema.has(to)) {\n\t\t\tthrow new TabulaError(\"unknown_field\", `The schema has no field \"${to}\" to rename \"${from}\" to.`)\n\t\t}\n\n\t\tmap.set(from, to)\n\t}\n\n\treturn map\n}\n\n/** A field of a draft, as a review before opening it shows it. */\nexport interface DraftFieldMapping {\n\treadonly key: string\n\t/** As the draft wrote it; null for a draft saved before labels were kept. */\n\treadonly label: string | null\n\treadonly type: FieldType\n\t/** Where its values go: its own field, the one it is renamed to, or null when they are dropped. */\n\treadonly target: string | null\n\t/** How many rows hold a value in it. */\n\treadonly filled: number\n\t/** Its first values, three at most, to know it by. */\n\treadonly samples: readonly CellValue[]\n\t/** How many of its values the target cannot read as its type: they open marked. */\n\treadonly unreadable: number\n}\n\nexport interface DraftMapping {\n\t/** Every field of the draft, in its order. */\n\treadonly fields: readonly DraftFieldMapping[]\n\t/** The schema's fields no field of the draft goes to: they open empty. */\n\treadonly added: readonly string[]\n\t/** How many rows lose a value in a field that is dropped. */\n\treadonly losing: number\n}\n\nexport interface MapDraftOptions {\n\t/** A field renamed since, by its old key, as `openDraft` takes it. */\n\treadonly rename?: Readonly<Record<string, string>>\n\t/** How values are read, to count what a field of another type cannot. Turkish by default. */\n\treadonly settings?: ValueSettings\n}\n\n/**\n * What opening a draft would do to each of its fields, with `rename` as given: for a screen that\n * lets the user map the fields of a draft saved under another schema before it opens.\n *\n * @throws TabulaError `invalid_argument` or `unknown_field` for a rename `openDraft` refuses\n */\nexport function mapDraft(draft: Draft, schema: ModuleSchema, options: MapDraftOptions = {}): DraftMapping {\n\tconst rename = renames(draft, schema, options.rename ?? {})\n\tconst settings = options.settings ?? VALUE_SETTINGS.tr\n\tconst targets = new Set<string>()\n\tlet losing = 0\n\n\tconst fields = draft.fields.map(field => {\n\t\tconst to = rename.get(field.key) ?? field.key\n\t\tconst target = schema.has(to) ? to : null\n\t\tconst values = draft.rows.map(row => row.values[field.key] ?? null).filter(value => value !== null)\n\t\tconst moved = target !== null && (target !== field.key || schema.field(target).type !== field.type)\n\t\tconst unreadable = moved\n\t\t\t? values.filter(value => valueProblem(schema.field(target), value, settings) !== null).length\n\t\t\t: 0\n\n\t\tif (target !== null) {\n\t\t\ttargets.add(target)\n\t\t}\n\n\t\treturn Object.freeze({\n\t\t\tkey: field.key,\n\t\t\tlabel: field.label ?? null,\n\t\t\ttype: field.type,\n\t\t\ttarget,\n\t\t\tfilled: values.length,\n\t\t\tsamples: Object.freeze(values.slice(0, 3)),\n\t\t\tunreadable\n\t\t})\n\t})\n\n\tconst dropped = new Set(fields.filter(field => field.target === null).map(field => field.key))\n\n\tfor (const row of draft.rows) {\n\t\tif (Object.entries(row.values).some(([key, value]) => value !== null && dropped.has(key))) {\n\t\t\tlosing++\n\t\t}\n\t}\n\n\treturn Object.freeze({\n\t\tfields: Object.freeze(fields),\n\t\tadded: Object.freeze(schema.fields.filter(field => !targets.has(field.key)).map(field => field.key)),\n\t\tlosing\n\t})\n}\n\n/**\n * The renames that look meant: each field the schema no longer has, paired with a new field of the\n * same type whose name shares a word with its own (\"Fiyat\" and \"Yeni fiyat\", \"price\" and\n * \"newPrice\"), the closest first, each new field taken once. A suggestion for the user to confirm,\n * never applied on its own.\n */\nexport function suggestRenames(draft: Draft, schema: ModuleSchema): Record<string, string> {\n\tconst kept = new Set(draft.fields.map(field => field.key))\n\tconst fresh = schema.fields.filter(field => !kept.has(field.key))\n\tconst pairs: { readonly from: string; readonly to: string; readonly score: number }[] = []\n\n\tfor (const old of draft.fields.filter(field => !schema.has(field.key))) {\n\t\tfor (const field of fresh) {\n\t\t\tconst score = field.type === old.type ? likeness(old, field) : 0\n\n\t\t\tif (score > 0) {\n\t\t\t\tpairs.push({ from: old.key, to: field.key, score })\n\t\t\t}\n\t\t}\n\t}\n\n\tpairs.sort((a, b) => b.score - a.score)\n\n\tconst result: Record<string, string> = {}\n\tconst taken = new Set<string>()\n\n\tfor (const pair of pairs) {\n\t\tif (!(pair.from in result) && !taken.has(pair.to)) {\n\t\t\tresult[pair.from] = pair.to\n\t\t\ttaken.add(pair.to)\n\t\t}\n\t}\n\n\treturn result\n}\n\n/** How alike two fields' names are: shared words of their labels count double, of their keys once. */\nfunction likeness(old: DraftField, field: FieldSchema): number {\n\tconst shared = (a: readonly string[], b: readonly string[]): number => a.filter(word => b.includes(word)).length\n\n\treturn 2 * shared(words(old.label ?? \"\"), words(field.label)) + shared(keyWords(old.key), keyWords(field.key))\n}\n\nfunction words(text: string): string[] {\n\treturn text\n\t\t.toLocaleLowerCase(\"tr\")\n\t\t.split(/[^\\p{L}\\p{N}]+/u)\n\t\t.filter(word => word.length > 1)\n}\n\n/** \"newPrice\", \"new_price\" and \"new-price\" alike: new, price. */\nfunction keyWords(key: string): string[] {\n\treturn words(key.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\"))\n}\n\n/** What moved on between the draft's schema and this one; null when nothing did. */\nfunction compare(draft: Draft, schema: ModuleSchema, rename: ReadonlyMap<string, string>): DraftChanges | null {\n\tconst old = new Map(draft.fields.map(field => [rename.get(field.key) ?? field.key, field] as const))\n\tconst added = schema.fields.filter(field => !old.has(field.key)).map(field => field.key)\n\tconst removed = draft.fields\n\t\t.filter(field => !schema.has(rename.get(field.key) ?? field.key))\n\t\t.map(field => field.key)\n\tconst retyped = schema.fields.flatMap(field => {\n\t\tconst before = old.get(field.key)\n\n\t\treturn before && before.type !== field.type ? [{ key: field.key, from: before.type, to: field.type }] : []\n\t})\n\tconst renamed = [...rename].map(([from, to]) => ({ from, to }))\n\n\tconst same =\n\t\tdraft.schemaVersion === schema.schemaVersion &&\n\t\tadded.length === 0 &&\n\t\tremoved.length === 0 &&\n\t\tretyped.length === 0 &&\n\t\trenamed.length === 0\n\n\tif (same) {\n\t\treturn null\n\t}\n\n\tconst gone = new Set(removed)\n\tconst losing = draft.rows.filter(row => Object.keys(row.values).some(key => gone.has(key))).length\n\n\treturn {\n\t\tfromVersion: draft.schemaVersion,\n\t\ttoVersion: schema.schemaVersion,\n\t\tadded,\n\t\tremoved,\n\t\tretyped,\n\t\trenamed,\n\t\tlosing\n\t}\n}\n\n// ---------------------------------------------------------------- reading\n\n/**\n * Checks what was read back from storage against the draft format, every problem at once.\n *\n * @throws TabulaError `invalid_draft`\n */\nexport function readDraft(input: unknown): Draft {\n\tconst problems: string[] = []\n\tconst problem = (path: string, message: string): void => {\n\t\tproblems.push(`${path}: ${message}`)\n\t}\n\tconst root = plain(input)\n\n\tif (!root) {\n\t\tthrow new TabulaError(\"invalid_draft\", \"A draft must be an object.\")\n\t}\n\n\tif (root.format !== DRAFT_FORMAT) {\n\t\tproblem(\"format\", `must be \"${DRAFT_FORMAT}\".`)\n\t}\n\n\tif (root.version !== DRAFT_VERSION) {\n\t\tproblem(\"version\", `must be ${DRAFT_VERSION}; a draft of another version of this format cannot be read.`)\n\t}\n\n\tconst text = (value: unknown, path: string): string => {\n\t\tif (typeof value !== \"string\" || value === \"\") {\n\t\t\tproblem(path, \"must be a non-empty string.\")\n\n\t\t\treturn \"\"\n\t\t}\n\n\t\treturn value\n\t}\n\tconst whole = (value: unknown, path: string): number => {\n\t\tif (!Number.isSafeInteger(value) || (value as number) < 0) {\n\t\t\tproblem(path, \"must be a whole number, 0 or more.\")\n\n\t\t\treturn 0\n\t\t}\n\n\t\treturn value as number\n\t}\n\n\tconst id = text(root.id, \"id\")\n\tconst name = root.name === null || root.name === undefined ? null : text(root.name, \"name\")\n\tconst module = text(root.module, \"module\")\n\tconst schemaVersion = whole(root.schemaVersion, \"schemaVersion\")\n\tconst sheetId = text(root.sheetId, \"sheetId\")\n\tconst savedAt = text(root.savedAt, \"savedAt\")\n\tconst revision = whole(root.revision, \"revision\")\n\n\tconst fields: DraftField[] = list(root.fields, \"fields\", problem).flatMap((item, index) => {\n\t\tconst field = plain(item)\n\t\tconst type = field?.type\n\n\t\tif (!field || !FIELD_TYPES.includes(type as FieldType)) {\n\t\t\tproblem(`fields[${index}]`, `must have a key and one of the field types (${FIELD_TYPES.join(\", \")}).`)\n\n\t\t\treturn []\n\t\t}\n\n\t\tconst label = field.label === undefined ? undefined : text(field.label, `fields[${index}].label`)\n\n\t\treturn [{ key: text(field.key, `fields[${index}].key`), type: type as FieldType, ...(label ? { label } : {}) }]\n\t})\n\n\tconst rows = list(root.rows, \"rows\", problem).flatMap((item, index) => {\n\t\tconst row = readRow(item, `rows[${index}]`, problem)\n\n\t\treturn row ? [row] : []\n\t})\n\n\tconst sessionRoot = plain(root.session)\n\tconst results = list(sessionRoot?.results, \"session.results\", problem).flatMap((item, index) => {\n\t\tconst result = readResult(item, `session.results[${index}]`, problem)\n\n\t\treturn result ? [result] : []\n\t})\n\tconst pending =\n\t\tsessionRoot?.pending === null || sessionRoot?.pending === undefined\n\t\t\t? null\n\t\t\t: readPending(sessionRoot.pending, \"session.pending\", problem)\n\n\tconst widths = plain(plain(root.view)?.columnWidths) ?? {}\n\tconst columnWidths: Record<string, number> = {}\n\n\tfor (const [key, width] of Object.entries(widths)) {\n\t\tif (typeof width === \"number\" && Number.isFinite(width) && width > 0) {\n\t\t\tcolumnWidths[key] = width\n\t\t} else {\n\t\t\tproblem(`view.columnWidths.${key}`, \"must be a number of pixels.\")\n\t\t}\n\t}\n\n\tconst columns = readColumnLayout(plain(root.view)?.columns, \"view.columns\", problem)\n\tconst marks = readMarks(root.marks, \"marks\", problem)\n\n\tif (problems.length > 0) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_draft\",\n\t\t\t`The draft cannot be read:\\n${problems.map(line => ` ${line}`).join(\"\\n\")}`\n\t\t)\n\t}\n\n\treturn Object.freeze({\n\t\tformat: DRAFT_FORMAT,\n\t\tversion: DRAFT_VERSION,\n\t\tid,\n\t\tname,\n\t\tmodule,\n\t\tschemaVersion,\n\t\tsheetId,\n\t\tfields: Object.freeze(fields),\n\t\tsavedAt,\n\t\trevision,\n\t\trows: Object.freeze(rows),\n\t\tsession: Object.freeze({ results: Object.freeze(results), pending }),\n\t\tview: Object.freeze({ columnWidths: Object.freeze(columnWidths), ...(columns ? { columns } : {}) }),\n\t\t...(Object.keys(marks).length > 0 ? { marks: freezeMarks(marks) } : {})\n\t})\n}\n\nfunction freezeMarks(marks: MarksData): MarksData {\n\treturn Object.freeze(\n\t\tObject.fromEntries(Object.entries(marks).map(([rowId, cells]) => [rowId, Object.freeze({ ...cells })]))\n\t)\n}\n\ntype Plain = Record<string, unknown>\ntype Problem = (path: string, message: string) => void\n\nfunction plain(value: unknown): Plain | null {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as Plain) : null\n}\n\nfunction list(value: unknown, path: string, problem: Problem): unknown[] {\n\tif (Array.isArray(value)) {\n\t\treturn value\n\t}\n\n\tproblem(path, \"must be an array.\")\n\n\treturn []\n}\n\nfunction readRow(item: unknown, path: string, problem: Problem): RowEntry | null {\n\tconst row = plain(item)\n\tconst values = plain(row?.values)\n\n\tif (!row || typeof row.rowId !== \"string\" || row.rowId === \"\" || !values) {\n\t\tproblem(path, \"must have a rowId and values.\")\n\n\t\treturn null\n\t}\n\n\tconst read: Record<string, CellValue> = {}\n\n\tfor (const [key, value] of Object.entries(values)) {\n\t\ttry {\n\t\t\tread[key] = toCellValue(value, `${path}.values.${key}`)\n\t\t} catch (error) {\n\t\t\tproblem(`${path}.values.${key}`, error instanceof Error ? error.message : String(error))\n\t\t}\n\t}\n\n\treturn Object.freeze({ rowId: row.rowId, values: Object.freeze(read) })\n}\n\nfunction readResult(item: unknown, path: string, problem: Problem): RowResult | null {\n\tconst result = plain(item)\n\tconst outcome = result?.outcome\n\n\tif (\n\t\t!result ||\n\t\ttypeof result.rowId !== \"string\" ||\n\t\ttypeof result.requestId !== \"string\" ||\n\t\t(outcome !== \"succeeded\" && outcome !== \"failed\" && outcome !== \"skipped\")\n\t) {\n\t\tproblem(path, \"must have a rowId, a requestId and an outcome of succeeded, failed or skipped.\")\n\n\t\treturn null\n\t}\n\n\tlet data: Record<string, CellValue> = {}\n\n\ttry {\n\t\tdata = toCellValue(plain(result.data) ?? {}, `${path}.data`) as Record<string, CellValue>\n\t} catch (error) {\n\t\tproblem(`${path}.data`, error instanceof Error ? error.message : String(error))\n\t}\n\n\treturn Object.freeze({ rowId: result.rowId, outcome, requestId: result.requestId, data })\n}\n\nfunction readPending(item: unknown, path: string, problem: Problem): PendingRun | null {\n\tconst pending = plain(item)\n\tconst request = plain(pending?.request)\n\tconst strings = [\"requestId\", \"idempotencyKey\", \"module\", \"sheetId\"] as const\n\tconst numbers = [\"schemaVersion\", \"revision\"] as const\n\n\tif (\n\t\t!pending ||\n\t\t!request ||\n\t\tstrings.some(key => typeof request[key] !== \"string\") ||\n\t\tnumbers.some(key => !Number.isSafeInteger(request[key])) ||\n\t\t!(pending.operationId === null || typeof pending.operationId === \"string\")\n\t) {\n\t\tproblem(path, \"must hold the request of the run with no answer, and its operationId or null.\")\n\n\t\treturn null\n\t}\n\n\tconst rows = list(request.rows, `${path}.request.rows`, problem).flatMap((row, index) => {\n\t\tconst read = readRow(row, `${path}.request.rows[${index}]`, problem)\n\n\t\treturn read ? [read] : []\n\t})\n\n\treturn Object.freeze({\n\t\trequest: Object.freeze({ ...(request as unknown as ProcessRequest), rows: Object.freeze(rows) }),\n\t\toperationId: pending.operationId as string | null\n\t})\n}\n","import { DRAFT_FORMAT, readDraft, type Draft } from \"./draft.js\"\nimport { TabulaError } from \"./errors.js\"\n\n/**\n * Several sheets kept together, as a spreadsheet keeps its tabs: each one a sheet of the same module\n * with rows, a template and a draft of its own, in the order the tabs stand, and the one that was\n * open. It is plain JSON, kept wherever the application keeps its drafts.\n *\n * Each sheet's draft is a draft as `createDraft` writes it, opened with `openDraft`; a sheet not yet\n * saved has none. A draft of one sheet, from before there were workbooks, reads as a workbook of\n * that one sheet.\n */\n\nexport const WORKBOOK_FORMAT = \"tabula-grid.workbook\"\nexport const WORKBOOK_VERSION = 1\n\n/** A value the application keeps with a sheet: text, a number, true or false, or null. */\nexport type SheetMeta = Readonly<Record<string, string | number | boolean | null>>\n\nexport interface WorkbookSheet {\n\t/** The sheet's id in requests and issues: a session over it takes it as its `sheetId`. */\n\treadonly sheetId: string\n\t/** What its tab says. */\n\treadonly name: string\n\t/** The template it works with, by its id; null for the module schema as it is. */\n\treadonly template: string | null\n\t/** The sheet as last saved; null before it was. */\n\treadonly draft: Draft | null\n\t/** What the application keeps with the sheet, such as the counts its tab shows while it is closed. */\n\treadonly meta: SheetMeta\n}\n\nexport interface Workbook {\n\treadonly format: typeof WORKBOOK_FORMAT\n\treadonly version: typeof WORKBOOK_VERSION\n\treadonly id: string\n\treadonly module: string\n\t/** The sheet that is open, by its id. */\n\treadonly active: string\n\t/** In the order their tabs stand; never empty. */\n\treadonly sheets: readonly WorkbookSheet[]\n}\n\nexport interface NewSheet {\n\treadonly name: string\n\treadonly template?: string | null\n\treadonly draft?: Draft | null\n\treadonly meta?: SheetMeta\n}\n\n/** A workbook of one sheet, open: where a module's work starts. */\nexport function createWorkbook(options: {\n\treadonly id: string\n\treadonly module: string\n\treadonly sheet: NewSheet\n}): Workbook {\n\tconst sheet = sheetOf(freeSheetId([]), options.sheet)\n\n\treturn freeze({\n\t\tformat: WORKBOOK_FORMAT,\n\t\tversion: WORKBOOK_VERSION,\n\t\tid: options.id,\n\t\tmodule: options.module,\n\t\tactive: sheet.sheetId,\n\t\tsheets: [sheet]\n\t})\n}\n\n/**\n * Checks what was read back from storage against the workbook format, every problem at once. A\n * draft of one sheet comes back as a workbook of that sheet, named `name`, or by its own name.\n *\n * @throws TabulaError `invalid_workbook`, or `invalid_draft` for a draft of one sheet that does not read\n */\nexport function readWorkbook(input: unknown, options: { readonly name?: string } = {}): Workbook {\n\tconst root = typeof input === \"object\" && input !== null && !Array.isArray(input) ? (input as Plain) : null\n\n\tif (!root) {\n\t\tthrow new TabulaError(\"invalid_workbook\", \"A workbook must be an object.\")\n\t}\n\n\tif (root.format === DRAFT_FORMAT) {\n\t\tconst draft = readDraft(input)\n\n\t\treturn freeze({\n\t\t\tformat: WORKBOOK_FORMAT,\n\t\t\tversion: WORKBOOK_VERSION,\n\t\t\tid: draft.id,\n\t\t\tmodule: draft.module,\n\t\t\tactive: draft.sheetId,\n\t\t\tsheets: [\n\t\t\t\t{\n\t\t\t\t\tsheetId: draft.sheetId,\n\t\t\t\t\tname: options.name ?? draft.name ?? draft.sheetId,\n\t\t\t\t\ttemplate: null,\n\t\t\t\t\tdraft,\n\t\t\t\t\tmeta: {}\n\t\t\t\t}\n\t\t\t]\n\t\t})\n\t}\n\n\tconst problems: string[] = []\n\tconst problem = (path: string, message: string): void => {\n\t\tproblems.push(`${path}: ${message}`)\n\t}\n\tconst text = (value: unknown, path: string): string => {\n\t\tif (typeof value !== \"string\" || value.trim() === \"\") {\n\t\t\tproblem(path, \"must be a non-empty string.\")\n\n\t\t\treturn \"\"\n\t\t}\n\n\t\treturn value\n\t}\n\n\tif (root.format !== WORKBOOK_FORMAT) {\n\t\tproblem(\"format\", `must be \"${WORKBOOK_FORMAT}\".`)\n\t}\n\n\tif (root.version !== WORKBOOK_VERSION) {\n\t\tproblem(\"version\", `must be ${WORKBOOK_VERSION}.`)\n\t}\n\n\tconst id = text(root.id, \"id\")\n\tconst module = text(root.module, \"module\")\n\tconst listed = Array.isArray(root.sheets) ? root.sheets : []\n\tconst seen = new Set<string>()\n\n\tif (!Array.isArray(root.sheets) || listed.length === 0) {\n\t\tproblem(\"sheets\", \"must be a list of one sheet or more.\")\n\t}\n\n\tconst sheets = listed.flatMap((item, index): WorkbookSheet[] => {\n\t\tconst path = `sheets[${index}]`\n\t\tconst sheet = typeof item === \"object\" && item !== null && !Array.isArray(item) ? (item as Plain) : null\n\n\t\tif (!sheet) {\n\t\t\tproblem(path, \"must be an object.\")\n\n\t\t\treturn []\n\t\t}\n\n\t\tconst sheetId = text(sheet.sheetId, `${path}.sheetId`)\n\n\t\tif (seen.has(sheetId)) {\n\t\t\tproblem(`${path}.sheetId`, `\"${sheetId}\" is another sheet's too.`)\n\t\t}\n\n\t\tseen.add(sheetId)\n\n\t\tconst template =\n\t\t\tsheet.template === null || sheet.template === undefined ? null : text(sheet.template, `${path}.template`)\n\t\tlet draft: Draft | null = null\n\n\t\tif (sheet.draft !== null && sheet.draft !== undefined) {\n\t\t\ttry {\n\t\t\t\tdraft = readDraft(sheet.draft)\n\n\t\t\t\tif (draft.module !== module) {\n\t\t\t\t\tproblem(`${path}.draft.module`, `must be \"${module}\", the workbook's.`)\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tproblem(`${path}.draft`, error instanceof Error ? (error.message.split(\"\\n\")[0] ?? \"\") : String(error))\n\t\t\t}\n\t\t}\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tsheetId,\n\t\t\t\tname: text(sheet.name, `${path}.name`),\n\t\t\t\ttemplate,\n\t\t\t\tdraft,\n\t\t\t\tmeta: readMeta(sheet.meta, `${path}.meta`, problem)\n\t\t\t}\n\t\t]\n\t})\n\n\tif (problems.length > 0) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_workbook\",\n\t\t\t`The workbook cannot be read:\\n${problems.map(line => ` ${line}`).join(\"\\n\")}`\n\t\t)\n\t}\n\n\tconst active = typeof root.active === \"string\" && seen.has(root.active) ? root.active : (sheets[0]?.sheetId ?? \"\")\n\n\treturn freeze({ format: WORKBOOK_FORMAT, version: WORKBOOK_VERSION, id, module, active, sheets })\n}\n\n/** An id no sheet of these has: \"sheet-1\", \"sheet-2\"… */\nexport function freeSheetId(sheets: readonly Pick<WorkbookSheet, \"sheetId\">[]): string {\n\tconst taken = new Set(sheets.map(sheet => sheet.sheetId))\n\tlet number = 1\n\n\twhile (taken.has(`sheet-${number}`)) {\n\t\tnumber++\n\t}\n\n\treturn `sheet-${number}`\n}\n\n/** The workbook with a new sheet, after `after` (the last by default), open; and the sheet's id. */\nexport function addSheet(\n\tworkbook: Workbook,\n\tsheet: NewSheet,\n\tafter?: string\n): { readonly workbook: Workbook; readonly sheetId: string } {\n\tconst added = sheetOf(freeSheetId(workbook.sheets), sheet)\n\tconst at = after === undefined ? -1 : workbook.sheets.findIndex(each => each.sheetId === after)\n\tconst sheets = [...workbook.sheets]\n\n\tsheets.splice(at < 0 ? sheets.length : at + 1, 0, added)\n\n\treturn { workbook: freeze({ ...workbook, active: added.sheetId, sheets }), sheetId: added.sheetId }\n}\n\n/**\n * The workbook with one sheet changed: its name, template, draft or what the application keeps\n * with it.\n *\n * @throws TabulaError `invalid_argument` for a sheet the workbook does not have, or an empty name\n */\nexport function withSheet(\n\tworkbook: Workbook,\n\tsheetId: string,\n\tpatch: Partial<Pick<WorkbookSheet, \"name\" | \"template\" | \"draft\" | \"meta\">>\n): Workbook {\n\tfound(workbook, sheetId)\n\n\tif (patch.name !== undefined && patch.name.trim() === \"\") {\n\t\tthrow new TabulaError(\"invalid_argument\", \"A sheet's name must not be empty.\")\n\t}\n\n\treturn freeze({\n\t\t...workbook,\n\t\tsheets: workbook.sheets.map(sheet =>\n\t\t\tsheet.sheetId === sheetId\n\t\t\t\t? { ...sheet, ...patch, ...(patch.name === undefined ? {} : { name: patch.name.trim() }) }\n\t\t\t\t: sheet\n\t\t)\n\t})\n}\n\n/**\n * The workbook without a sheet. The one open then is its neighbour, the next or, for the last, the\n * one before.\n *\n * @throws TabulaError `invalid_argument` for the only sheet, or one the workbook does not have\n */\nexport function removeSheet(workbook: Workbook, sheetId: string): Workbook {\n\tfound(workbook, sheetId)\n\n\tif (workbook.sheets.length === 1) {\n\t\tthrow new TabulaError(\"invalid_argument\", \"A workbook keeps one sheet at least.\")\n\t}\n\n\tconst at = workbook.sheets.findIndex(sheet => sheet.sheetId === sheetId)\n\tconst sheets = workbook.sheets.filter(sheet => sheet.sheetId !== sheetId)\n\tconst active =\n\t\tworkbook.active === sheetId ? (sheets[Math.min(at, sheets.length - 1)]?.sheetId ?? \"\") : workbook.active\n\n\treturn freeze({ ...workbook, active, sheets })\n}\n\n/**\n * The workbook with a sheet moved among the tabs, to place `to` counted among the others: 0 first,\n * their number last. The open sheet stays open.\n *\n * @throws TabulaError `invalid_argument` for a sheet the workbook does not have\n */\nexport function moveSheet(workbook: Workbook, sheetId: string, to: number): Workbook {\n\tconst sheet = found(workbook, sheetId)\n\tconst sheets = workbook.sheets.filter(each => each.sheetId !== sheetId)\n\n\tsheets.splice(Math.max(0, Math.min(Math.trunc(to), sheets.length)), 0, sheet)\n\n\treturn freeze({ ...workbook, sheets })\n}\n\n/**\n * The workbook with another sheet open.\n *\n * @throws TabulaError `invalid_argument` for a sheet the workbook does not have\n */\nexport function openSheet(workbook: Workbook, sheetId: string): Workbook {\n\tfound(workbook, sheetId)\n\n\treturn freeze({ ...workbook, active: sheetId })\n}\n\ntype Plain = Record<string, unknown>\n\nfunction sheetOf(sheetId: string, sheet: NewSheet): WorkbookSheet {\n\tif (sheet.name.trim() === \"\") {\n\t\tthrow new TabulaError(\"invalid_argument\", \"A sheet's name must not be empty.\")\n\t}\n\n\treturn {\n\t\tsheetId,\n\t\tname: sheet.name.trim(),\n\t\ttemplate: sheet.template ?? null,\n\t\tdraft: sheet.draft ?? null,\n\t\tmeta: sheet.meta ?? {}\n\t}\n}\n\nfunction found(workbook: Workbook, sheetId: string): WorkbookSheet {\n\tconst sheet = workbook.sheets.find(each => each.sheetId === sheetId)\n\n\tif (!sheet) {\n\t\tthrow new TabulaError(\"invalid_argument\", `The workbook has no sheet \"${sheetId}\".`)\n\t}\n\n\treturn sheet\n}\n\nfunction readMeta(value: unknown, path: string, problem: (path: string, message: string) => void): SheetMeta {\n\tif (value === undefined || value === null) {\n\t\treturn {}\n\t}\n\n\tif (typeof value !== \"object\" || Array.isArray(value)) {\n\t\tproblem(path, \"must be an object.\")\n\n\t\treturn {}\n\t}\n\n\tconst meta: Record<string, string | number | boolean | null> = {}\n\n\tfor (const [key, item] of Object.entries(value as Plain)) {\n\t\tif (item === null || [\"string\", \"number\", \"boolean\"].includes(typeof item)) {\n\t\t\tmeta[key] = item as string | number | boolean | null\n\t\t} else {\n\t\t\tproblem(`${path}.${key}`, \"must be text, a number, true, false or null.\")\n\t\t}\n\t}\n\n\treturn meta\n}\n\nfunction freeze(workbook: Workbook): Workbook {\n\treturn Object.freeze({\n\t\t...workbook,\n\t\tsheets: Object.freeze(\n\t\t\tworkbook.sheets.map(sheet => Object.freeze({ ...sheet, meta: Object.freeze({ ...sheet.meta }) }))\n\t\t)\n\t})\n}\n","import type { AdapterContext } from \"./contract.js\"\nimport { createDraft, type Draft, type DraftView } from \"./draft.js\"\nimport { TabulaError } from \"./errors.js\"\nimport { sequence } from \"./ids.js\"\nimport { Listeners } from \"./listeners.js\"\nimport type { CellMarks } from \"./marks.js\"\nimport type { RowStore } from \"./rows.js\"\nimport type { ModuleSchema } from \"./schema.js\"\nimport type { SheetSession } from \"./session.js\"\n\nexport interface DraftSaverOptions {\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\t/** Its results go into each draft, and a change to them is a change to save. */\n\treadonly session?: SheetSession\n\t/**\n\t * Keeps a draft wherever the application keeps them: its backend, the browser's storage. A draft\n\t * carries its own id, so the same draft saved again replaces the last one rather than adding one.\n\t */\n\treadonly save: (draft: Draft, context: AdapterContext) => Promise<void>\n\t/** The id of the draft being continued. Left out, a new one is made. */\n\treadonly id?: string\n\treadonly name?: string | null\n\t/** Read at each save: the user's view of the sheet, such as the grid's column widths. */\n\treadonly view?: () => DraftView\n\t/** The marks on the cells: kept with each draft, and a change to them is a change to save. */\n\treadonly marks?: CellMarks\n\t/** Milliseconds after the last change before it saves on its own; 0 saves only when asked. 2,000 by default. */\n\treadonly delay?: number\n\treadonly createId?: () => string\n\treadonly now?: () => Date\n}\n\n/** `saved`: nothing changed since the last save. `failed`: the last save did not go through. */\nexport type SaverStatus = \"saved\" | \"unsaved\" | \"saving\" | \"failed\"\n\nexport interface SaverState {\n\treadonly status: SaverStatus\n\t/** When the last save went through, as ISO 8601 text; null before the first. */\n\treadonly savedAt: string | null\n\t/** What went wrong with the last save, when it did not go through. */\n\treadonly failure: { readonly message: string; readonly error: unknown } | null\n}\n\nconst DEFAULT_DELAY = 2000\n\n/**\n * Saves a sheet as a draft: on its own, a moment after the user stops changing it, and whenever\n * asked. Only one save is under way at a time; changes made during one are saved by the next.\n *\n * A save that fails leaves the sheet as it is and the state `failed`; the next change, or a call to\n * `save()`, tries again.\n */\nexport class DraftSaver {\n\t/** The draft's id: the same for every save. */\n\treadonly id: string\n\n\treadonly #options: DraftSaverOptions\n\treadonly #delay: number\n\treadonly #listeners = new Listeners<DraftSaver>()\n\treadonly #stops: (() => void)[] = []\n\t#name: string | null\n\t#state: SaverState = Object.freeze({ status: \"saved\", savedAt: null, failure: null })\n\t#version = 0\n\t/** Counts changes; the count a save started at is what it saved. */\n\t#changes = 0\n\t#saved = 0\n\t#timer: ReturnType<typeof setTimeout> | null = null\n\t#running: Promise<boolean> | null = null\n\t#disposed = false\n\n\tconstructor(options: DraftSaverOptions) {\n\t\tconst delay = options.delay ?? DEFAULT_DELAY\n\n\t\tif (!Number.isFinite(delay) || delay < 0) {\n\t\t\tthrow new TabulaError(\"invalid_argument\", `delay must be 0 or more milliseconds; got ${delay}.`)\n\t\t}\n\n\t\tthis.#options = options\n\t\tthis.#delay = delay\n\t\tthis.#name = options.name ?? null\n\t\tthis.id = options.id ?? (options.createId ?? sequence(\"d\"))()\n\t\tthis.#stops.push(options.store.subscribe(() => this.changed()))\n\n\t\tif (options.marks) {\n\t\t\tthis.#stops.push(options.marks.subscribe(() => this.changed()))\n\t\t}\n\n\t\tif (options.session) {\n\t\t\tthis.#stops.push(options.session.results.subscribe(() => this.changed()))\n\t\t\tthis.#stops.push(options.session.subscribe(() => this.#onSession()))\n\t\t}\n\t}\n\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\tget state(): SaverState {\n\t\treturn this.#state\n\t}\n\n\tget name(): string | null {\n\t\treturn this.#name\n\t}\n\n\t/** Whether something changed since the last save that went through. */\n\tget dirty(): boolean {\n\t\treturn this.#changes !== this.#saved\n\t}\n\n\tsubscribe(listener: (saver: DraftSaver) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Something the draft holds changed outside the store, such as a column width: save it in a moment. */\n\tchanged(): void {\n\t\tif (this.#disposed) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#changes++\n\n\t\tif (this.#state.status !== \"saving\") {\n\t\t\tthis.#setState({ status: \"unsaved\" })\n\t\t}\n\n\t\tthis.#schedule()\n\t}\n\n\t/** Names the draft, and saves the name with it. */\n\trename(name: string | null): void {\n\t\tthis.#name = name\n\t\tthis.changed()\n\t}\n\n\t/**\n\t * Saves now, after any save under way. Resolves true once everything changed until now is saved,\n\t * false when a save failed.\n\t */\n\tasync save(): Promise<boolean> {\n\t\tthis.#clearTimer()\n\n\t\twhile (this.#running) {\n\t\t\tawait this.#running\n\t\t}\n\n\t\tif (this.#disposed) {\n\t\t\treturn false\n\t\t}\n\n\t\tif (!this.dirty && this.#state.status === \"saved\" && this.#state.savedAt !== null) {\n\t\t\treturn true\n\t\t}\n\n\t\tconst run = this.#run()\n\n\t\tthis.#running = run\n\n\t\ttry {\n\t\t\treturn await run\n\t\t} finally {\n\t\t\tthis.#running = null\n\t\t}\n\t}\n\n\t/** Saves what is not saved yet, such as before the page goes away. Resolves at once when nothing is. */\n\tasync flush(): Promise<boolean> {\n\t\treturn this.dirty || this.#running ? this.save() : true\n\t}\n\n\t/** Stops saving on its own. A save under way still finishes. */\n\tdispose(): void {\n\t\tthis.#disposed = true\n\t\tthis.#clearTimer()\n\n\t\tfor (const stop of this.#stops) {\n\t\t\tstop()\n\t\t}\n\t}\n\n\tasync #run(): Promise<boolean> {\n\t\tconst options = this.#options\n\t\tconst at = this.#changes\n\t\tconst draft = createDraft({\n\t\t\tid: this.id,\n\t\t\tname: this.#name,\n\t\t\tschema: options.schema,\n\t\t\tstore: options.store,\n\t\t\tsession: options.session ?? null,\n\t\t\t...(options.view ? { view: options.view() } : {}),\n\t\t\t...(options.marks ? { marks: options.marks } : {}),\n\t\t\t...(options.now ? { now: options.now } : {})\n\t\t})\n\n\t\tthis.#setState({ status: \"saving\", failure: null })\n\n\t\ttry {\n\t\t\tawait options.save(draft, {\n\t\t\t\tsignal: new AbortController().signal,\n\t\t\t\trequestId: `${this.id}@${draft.revision}`\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthis.#setState({\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tfailure: Object.freeze({ message: error instanceof Error ? error.message : String(error), error })\n\t\t\t})\n\n\t\t\treturn false\n\t\t}\n\n\t\tthis.#saved = at\n\t\tthis.#setState({ status: this.dirty ? \"unsaved\" : \"saved\", savedAt: draft.savedAt, failure: null })\n\n\t\t// Changes made while it was saving are saved by the next one.\n\t\tif (this.dirty) {\n\t\t\tthis.#schedule()\n\t\t}\n\n\t\treturn true\n\t}\n\n\t/**\n\t * A run starting, going unknown or ending changes what a draft holds of the session: a page closed\n\t * mid-run must open again knowing the run is out there. A check changes nothing a draft keeps.\n\t */\n\t#onSession(): void {\n\t\tif (this.#options.session?.state.phase !== \"checking\") {\n\t\t\tthis.changed()\n\t\t}\n\t}\n\n\t#schedule(): void {\n\t\tif (this.#delay === 0 || this.#disposed) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#clearTimer()\n\t\tthis.#timer = setTimeout(() => {\n\t\t\tthis.#timer = null\n\t\t\tvoid this.save()\n\t\t}, this.#delay)\n\t}\n\n\t#clearTimer(): void {\n\t\tif (this.#timer !== null) {\n\t\t\tclearTimeout(this.#timer)\n\t\t\tthis.#timer = null\n\t\t}\n\t}\n\n\t#setState(patch: Partial<SaverState>): void {\n\t\tthis.#state = Object.freeze({ ...this.#state, ...patch })\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n}\n","import {\n\treadCheckResponse,\n\treadProcessResponse,\n\ttype CheckResponse,\n\ttype IssueInput,\n\ttype ProcessProgress,\n\ttype ProcessRequest,\n\ttype ProcessResponse,\n\ttype ProcessStatus,\n\ttype RowAction,\n\ttype RowOutcome,\n\ttype RowPlanInput,\n\ttype SheetAdapters,\n\ttype SheetRequest,\n\ttype StatusQuery\n} from \"./contract.js\"\nimport { neverAborted, raced, wait } from \"./async.js\"\nimport { TabulaError } from \"./errors.js\"\nimport { isFormulaError } from \"./formula/error.js\"\nimport type { UndoHistory } from \"./history.js\"\nimport { randomPart, sequence } from \"./ids.js\"\nimport { Listeners } from \"./listeners.js\"\nimport type { RowId, RowStore, StoreChange } from \"./rows.js\"\nimport type { ModuleSchema } from \"./schema.js\"\nimport { SheetValidator, type Issue, type IssueScope, type IssueSet, type IssueSummary } from \"./validation.js\"\nimport type { CellValue } from \"./value.js\"\nimport { canonicalValue, isLookupValue } from \"./values/read.js\"\nimport type { ValueSettings } from \"./values/settings.js\"\n\nexport interface SheetSessionOptions {\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\treadonly adapters: SheetAdapters\n\t/** The local checks. Left out, the session makes its own, with `settings`, and disposes of it. */\n\treadonly validator?: SheetValidator\n\treadonly settings?: ValueSettings\n\t/**\n\t * Cleared when rows are sent to be processed. Once a backend has them, taking an edit back in the\n\t * sheet alone would show what was never done.\n\t */\n\treadonly history?: UndoHistory\n\t/** The sheet's name in requests and issues. The schema's module by default. */\n\treadonly sheetId?: string\n\treadonly createRequestId?: () => string\n\t/** Milliseconds between status questions while a run answers `pending`. 1,000 by default. */\n\treadonly pollInterval?: number\n\t/** What a draft kept of an earlier session over the same rows, to go on from where it stood. */\n\treadonly restore?: PersistedSession\n}\n\n/**\n * What a session hands to a draft: enough that opening the draft again neither unlocks a processed\n * row nor forgets a run that never answered.\n */\nexport interface PersistedSession {\n\t/** Each row's result, for the rows still in the sheet. */\n\treadonly results: readonly RowResult[]\n\t/** A run with no final answer, to be sent again under its key, or asked about. */\n\treadonly pending: PendingRun | null\n}\n\nexport interface PendingRun {\n\treadonly request: ProcessRequest\n\treadonly operationId: string | null\n}\n\n/**\n * `unknown`: rows were sent and no answer came back, so whether they were processed is not known.\n * The session sends the same request again, under the same key, or asks how it went; it never\n * sends those rows as a new run, which could do them twice.\n */\nexport type SessionPhase = \"idle\" | \"checking\" | \"processing\" | \"unknown\"\n\nexport interface SessionFailure {\n\treadonly stage: \"preflight\" | \"process\" | \"status\" | \"cancel\"\n\t/**\n\t * `request_failed`: the adapter threw, such as on a network error. `invalid_response`: the answer\n\t * was not in the contract's shape. `unavailable`: there is no adapter to go on with.\n\t */\n\treadonly code: \"request_failed\" | \"invalid_response\" | \"unavailable\"\n\treadonly message: string\n\treadonly error: unknown\n}\n\nexport interface CheckRecord {\n\treadonly requestId: string\n\treadonly revision: number\n\treadonly outcome: \"valid\" | \"invalid\" | \"failed\" | \"cancelled\"\n}\n\n/** `sending`: no answer yet. `unknown`: none came, and none can be counted on. */\nexport type RunStatus = ProcessStatus | \"sending\" | \"unknown\"\n\nexport interface RunRecord {\n\treadonly requestId: string\n\treadonly idempotencyKey: string\n\treadonly operationId: string | null\n\treadonly revision: number\n\t/** How many rows were sent. */\n\treadonly rows: number\n\treadonly status: RunStatus\n\treadonly progress: ProcessProgress | null\n}\n\nexport interface SessionState {\n\treadonly phase: SessionPhase\n\treadonly check: CheckRecord | null\n\treadonly run: RunRecord | null\n\t/** What went wrong with the last request, apart from the issues of the data. */\n\treadonly failure: SessionFailure | null\n}\n\nexport interface CheckOutcome {\n\treadonly status: \"valid\" | \"invalid\" | \"failed\" | \"cancelled\" | \"busy\" | \"unavailable\"\n\t/** How many issues the backend reported. */\n\treadonly issues: number\n}\n\nexport interface ProcessOutcome {\n\t/**\n\t * A run's final status, or why there was none: `blocked` by issues, `nothing` to send, `busy`\n\t * with another request, `unavailable` for want of an adapter, or `unknown` for want of an answer.\n\t */\n\treadonly status: ProcessStatus | \"blocked\" | \"nothing\" | \"busy\" | \"unavailable\" | \"unknown\"\n\treadonly succeeded: number\n\treadonly failed: number\n\treadonly skipped: number\n\t/** Rows held back by an issue that blocks, when the status is `blocked`. */\n\treadonly blocked: number\n}\n\nexport interface RowResult {\n\treadonly rowId: RowId\n\treadonly outcome: RowOutcome\n\treadonly data: Readonly<Record<string, CellValue>>\n\t/** The run it came from. */\n\treadonly requestId: string\n}\n\n/** Each row's result from the backend, for a view to show and to lock rows by. */\nexport interface RowResults {\n\treadonly version: number\n\tresultOf(rowId: RowId): RowResult | null\n\t/** A processed row cannot be changed, nor can one on its way to the backend. */\n\tisLocked(rowId: RowId): boolean\n\tsubscribe(listener: () => void): () => void\n}\n\n/** A field a run would write: what the backend holds now, and what the sheet holds. */\nexport interface PlannedChange {\n\treadonly field: string\n\t/** As the backend sent it; null for a new record. */\n\treadonly before: CellValue\n\t/** As the sheet holds it, to be shown the way its cell shows it. */\n\treadonly after: CellValue\n}\n\n/** `unknown`: the check said nothing of the row, or the row changed after it. */\nexport type PlannedAction = RowAction | \"unknown\"\n\nexport interface RowPlan {\n\treadonly rowId: RowId\n\treadonly action: PlannedAction\n\t/**\n\t * For an update, the fields that would change, as far as the backend said; for a new record,\n\t * every field it would be given. Empty otherwise.\n\t */\n\treadonly changes: readonly PlannedChange[]\n}\n\n/** What a run would do, row by row, by the last check's answer: for a preview before it is sent. */\nexport interface ProcessPlan {\n\t/** The check the plan comes from; null when there is none to go by. */\n\treadonly check: CheckRecord | null\n\t/**\n\t * Whether that check saw every row a run would send just as the run would send it. When it did\n\t * not, check again before showing the plan as what will be done.\n\t */\n\treadonly current: boolean\n\t/** Every row a run would send, in sheet order. */\n\treadonly rows: readonly RowPlan[]\n\treadonly counts: Readonly<Record<PlannedAction, number>>\n}\n\n/** A check's answer, kept to build a plan from: what each row was sent as, and what it would become. */\ninterface CheckedPlan {\n\treadonly record: CheckRecord\n\treadonly payloads: ReadonlyMap<RowId, string>\n\treadonly plans: ReadonlyMap<RowId, RowPlanInput>\n}\n\nconst DEFAULT_POLL_INTERVAL = 1000\n\n/**\n * A sheet's way to its backend: the pre-flight check and the process run, through the adapters it\n * is given, with the backend's issues merged into the local ones.\n *\n * Every answer is about a revision of the sheet. An answer about an older one still lands, but an\n * issue on a cell changed since is marked stale rather than shown as standing; so is an issue whose\n * cell is changed after it arrived. Nothing a backend said is taken as fixed until it says so.\n *\n * Rows that went through are locked and are not sent again. A run with no answer leaves the session\n * `unknown`, its rows locked, until the same request is sent again or the backend says how it went.\n */\nexport class SheetSession {\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\treadonly sheetId: string\n\treadonly validator: SheetValidator\n\t/** The local issues and the backend's, for the grid and the issue panel. */\n\treadonly issues: IssueSet\n\treadonly results: RowResults\n\n\treadonly #adapters: SheetAdapters\n\treadonly #history: UndoHistory | null\n\treadonly #ownValidator: boolean\n\treadonly #requestId: () => string\n\treadonly #pollInterval: number\n\treadonly #merged: MergedIssues\n\treadonly #results: Results\n\treadonly #listeners = new Listeners<SheetSession>()\n\treadonly #stop: () => void\n\t/** The revision each cell and each row last changed at, to tell what an answer could not have seen. */\n\treadonly #cellChanged = new Map<RowId, Map<string, number>>()\n\treadonly #rowChanged = new Map<RowId, number>()\n\t#state: SessionState = Object.freeze({ phase: \"idle\", check: null, run: null, failure: null })\n\t#version = 0\n\t#checking: { readonly controller: AbortController; readonly request: SheetRequest } | null = null\n\t#running: AbortController | null = null\n\t/** The request of a run without a final answer: what is sent again, under the same key. */\n\t#pending: ProcessRequest | null = null\n\t/** The last check that was answered, until a run changes what the backend holds. */\n\t#checked: CheckedPlan | null = null\n\t#disposed = false\n\n\tconstructor(options: SheetSessionOptions) {\n\t\tconst pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL\n\n\t\tif (!Number.isFinite(pollInterval) || pollInterval < 0) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_argument\",\n\t\t\t\t`pollInterval must be 0 or more milliseconds; got ${pollInterval}.`\n\t\t\t)\n\t\t}\n\n\t\tthis.schema = options.schema\n\t\tthis.store = options.store\n\t\tthis.sheetId = options.sheetId ?? options.schema.module\n\t\tthis.#ownValidator = options.validator === undefined\n\t\tthis.validator = options.validator ?? new SheetValidator(options.schema, options.store, options.settings)\n\t\tthis.#adapters = options.adapters\n\t\tthis.#history = options.history ?? null\n\t\tthis.#requestId = options.createRequestId ?? sequence(\"req\")\n\t\tthis.#pollInterval = pollInterval\n\t\tthis.#merged = new MergedIssues(this.validator, this.store, this.schema)\n\t\tthis.#results = new Results()\n\t\tthis.issues = this.#merged\n\t\tthis.results = this.#results\n\t\tthis.#stop = this.store.subscribe(change => this.#onChange(change))\n\n\t\tif (options.restore) {\n\t\t\tthis.#restore(options.restore)\n\t\t}\n\t}\n\n\t/**\n\t * What a draft keeps of this session: each row's result, and a run with no final answer. A run\n\t * still going is kept as one with no answer: opened again, it is sent again under its key, or\n\t * asked about, and never run twice.\n\t */\n\tpersisted(): PersistedSession {\n\t\tconst results: RowResult[] = []\n\n\t\tfor (const rowId of this.store.rowIds()) {\n\t\t\tconst result = this.#results.resultOf(rowId)\n\n\t\t\tif (result) {\n\t\t\t\tresults.push(result)\n\t\t\t}\n\t\t}\n\n\t\tconst pending = this.#pending\n\t\t\t? Object.freeze({ request: this.#pending, operationId: this.#state.run?.operationId ?? null })\n\t\t\t: null\n\n\t\treturn Object.freeze({ results: Object.freeze(results), pending })\n\t}\n\n\t/** Moves on every change of `state`. */\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\tget state(): SessionState {\n\t\treturn this.#state\n\t}\n\n\t/** Called after each change of `state`. Returns the way to stop. */\n\tsubscribe(listener: (session: SheetSession) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** The rows a check or a run would send, in sheet order: every row with something in it, bar those processed. */\n\tunfinishedRows(): RowId[] {\n\t\treturn this.store\n\t\t\t.rowIds()\n\t\t\t.filter(rowId => this.#results.resultOf(rowId)?.outcome !== \"succeeded\" && !this.#isEmpty(rowId))\n\t}\n\n\t/**\n\t * Asks the backend to check the sheet. A check started while another runs replaces it, and the\n\t * answer to the older one is passed over.\n\t */\n\tasync check(): Promise<CheckOutcome> {\n\t\tconst ask = this.#adapters.preflight\n\n\t\tif (!ask) {\n\t\t\treturn { status: \"unavailable\", issues: 0 }\n\t\t}\n\n\t\tif (this.#state.phase === \"processing\" || this.#state.phase === \"unknown\") {\n\t\t\treturn { status: \"busy\", issues: 0 }\n\t\t}\n\n\t\tthis.#checking?.controller.abort()\n\n\t\tconst controller = new AbortController()\n\t\tconst request = this.#request(this.unfinishedRows())\n\t\tconst current = { controller, request }\n\n\t\tthis.#checking = current\n\t\tthis.#setState({ phase: \"checking\", failure: null })\n\n\t\tlet response: CheckResponse\n\n\t\ttry {\n\t\t\tconst answer = await raced(\n\t\t\t\task(request, { signal: controller.signal, requestId: request.requestId }),\n\t\t\t\tcontroller.signal\n\t\t\t)\n\n\t\t\tresponse = this.#answered(request.requestId, readCheckResponse(answer))\n\t\t} catch (error) {\n\t\t\tif (this.#checking !== current) {\n\t\t\t\treturn { status: \"cancelled\", issues: 0 }\n\t\t\t}\n\n\t\t\tthis.#checking = null\n\t\t\tthis.#setState({\n\t\t\t\tphase: \"idle\",\n\t\t\t\tcheck: record(request, \"failed\"),\n\t\t\t\tfailure: failure(\"preflight\", error)\n\t\t\t})\n\n\t\t\treturn { status: \"failed\", issues: 0 }\n\t\t}\n\n\t\tif (this.#checking !== current) {\n\t\t\treturn { status: \"cancelled\", issues: 0 }\n\t\t}\n\n\t\tthis.#checking = null\n\n\t\tconst issues = (response.issues ?? [])\n\t\t\t.map((input, index) => this.#toIssue(input, \"preflight\", String(index), request.revision, null))\n\t\t\t.filter((issue): issue is Issue => issue !== null)\n\n\t\tthis.#merged.replace(issue => issue.source === \"preflight\", issues)\n\n\t\tconst outcome = issues.some(issue => issue.blocking && !issue.stale) ? \"invalid\" : \"valid\"\n\t\tconst checkRecord = record(request, outcome)\n\t\tconst plans = new Map<RowId, RowPlanInput>()\n\t\tconst sent = new Set(request.rows.map(row => row.rowId))\n\n\t\tfor (const plan of response.plan ?? []) {\n\t\t\tif (sent.has(plan.rowId) && !plans.has(plan.rowId)) {\n\t\t\t\tplans.set(plan.rowId, plan)\n\t\t\t}\n\t\t}\n\n\t\tthis.#checked = {\n\t\t\trecord: checkRecord,\n\t\t\tpayloads: new Map(request.rows.map(row => [row.rowId, JSON.stringify(row.values)])),\n\t\t\tplans\n\t\t}\n\t\tthis.#setState({ phase: \"idle\", check: checkRecord })\n\n\t\treturn { status: outcome, issues: issues.length }\n\t}\n\n\t/**\n\t * Sends the unfinished rows to be processed, or, while the last run is `unknown`, the same\n\t * request again under the same key. Rows with an error standing, local or the backend's, hold\n\t * back the whole run: the backend checks again anyway, and a run is not the place to find out.\n\t */\n\tasync process(): Promise<ProcessOutcome> {\n\t\tconst send = this.#adapters.process\n\n\t\tif (!send) {\n\t\t\treturn outcome(\"unavailable\")\n\t\t}\n\n\t\tif (this.#state.phase === \"checking\" || this.#state.phase === \"processing\") {\n\t\t\treturn outcome(\"busy\")\n\t\t}\n\n\t\tlet request = this.#state.phase === \"unknown\" ? this.#pending : null\n\n\t\tif (request === null) {\n\t\t\tconst rowIds = this.unfinishedRows()\n\n\t\t\tif (rowIds.length === 0) {\n\t\t\t\treturn outcome(\"nothing\")\n\t\t\t}\n\n\t\t\tconst blocked = this.#blockedRows(rowIds)\n\n\t\t\tif (blocked > 0) {\n\t\t\t\treturn { ...outcome(\"blocked\"), blocked }\n\t\t\t}\n\n\t\t\trequest = Object.freeze({\n\t\t\t\t...this.#request(rowIds),\n\t\t\t\tidempotencyKey: `${this.sheetId}:${this.store.revision}:${randomPart()}`\n\t\t\t})\n\t\t\tthis.#history?.clear()\n\t\t}\n\n\t\tconst sending = request\n\t\tconst controller = new AbortController()\n\n\t\tthis.#pending = sending\n\t\tthis.#running = controller\n\t\tthis.#results.setInFlight(new Set(sending.rows.map(row => row.rowId)))\n\t\tthis.#setState({\n\t\t\tphase: \"processing\",\n\t\t\tfailure: null,\n\t\t\trun: {\n\t\t\t\trequestId: sending.requestId,\n\t\t\t\tidempotencyKey: sending.idempotencyKey,\n\t\t\t\toperationId: this.#state.run?.requestId === sending.requestId ? this.#state.run.operationId : null,\n\t\t\t\trevision: sending.revision,\n\t\t\t\trows: sending.rows.length,\n\t\t\t\tstatus: \"sending\",\n\t\t\t\tprogress: null\n\t\t\t}\n\t\t})\n\n\t\tlet response: ProcessResponse\n\n\t\ttry {\n\t\t\tconst answer = await raced(\n\t\t\t\tsend(sending, { signal: controller.signal, requestId: sending.requestId }),\n\t\t\t\tcontroller.signal\n\t\t\t)\n\n\t\t\tresponse = this.#answered(sending.requestId, readProcessResponse(answer))\n\t\t} catch (error) {\n\t\t\treturn this.#lose(\"process\", error)\n\t\t}\n\n\t\treturn this.#follow(sending, response, controller)\n\t}\n\n\t/**\n\t * What a run would do now, by the last check's answer: each row it would send, in sheet order,\n\t * with what the backend said would become of it. A row the backend said nothing of, or one that\n\t * changed or was added after the check, is `unknown`. A finished run leaves nothing to go by,\n\t * since it changed what the backend holds.\n\t */\n\tplan(): ProcessPlan {\n\t\tconst checked = this.#checked\n\t\tconst counts: Record<PlannedAction, number> = { create: 0, update: 0, unchanged: 0, unknown: 0 }\n\t\tlet current = checked !== null\n\t\tconst rows = this.unfinishedRows().map(rowId => {\n\t\t\tconst same = checked?.payloads.get(rowId) === JSON.stringify(this.#payload(rowId))\n\t\t\tconst plan = this.#rowPlan(rowId, same ? checked?.plans.get(rowId) : undefined)\n\n\t\t\tcurrent &&= same\n\t\t\tcounts[plan.action]++\n\n\t\t\treturn plan\n\t\t})\n\n\t\treturn Object.freeze({\n\t\t\tcheck: checked?.record ?? null,\n\t\t\tcurrent,\n\t\t\trows: Object.freeze(rows),\n\t\t\tcounts: Object.freeze(counts)\n\t\t})\n\t}\n\n\t/** How many rows an error, the sheet's own or the backend's, holds back from a run now. */\n\tblocked(): number {\n\t\treturn this.#blockedRows(this.unfinishedRows())\n\t}\n\n\t/** Asks the backend how a run with no answer went, while the session is `unknown`. */\n\tasync refresh(): Promise<ProcessOutcome> {\n\t\tconst ask = this.#adapters.processStatus\n\t\tconst request = this.#pending\n\n\t\tif (this.#state.phase !== \"unknown\" || request === null) {\n\t\t\treturn outcome(this.#state.phase === \"idle\" ? \"nothing\" : \"busy\")\n\t\t}\n\n\t\tif (!ask) {\n\t\t\treturn outcome(\"unavailable\")\n\t\t}\n\n\t\tconst controller = new AbortController()\n\n\t\tthis.#running = controller\n\t\tthis.#setState({ phase: \"processing\", failure: null })\n\n\t\tlet response: ProcessResponse\n\n\t\ttry {\n\t\t\tconst answer = await raced(\n\t\t\t\task(this.#query(), { signal: controller.signal, requestId: request.requestId }),\n\t\t\t\tcontroller.signal\n\t\t\t)\n\n\t\t\tresponse = this.#answered(request.requestId, readProcessResponse(answer))\n\t\t} catch (error) {\n\t\t\treturn this.#lose(\"status\", error)\n\t\t}\n\n\t\treturn this.#follow(request, response, controller)\n\t}\n\n\t/**\n\t * Stops a check, or asks the backend to stop a run. A run the backend cannot be asked about,\n\t * for want of an operation id or a `cancelProcess` adapter, is no longer waited for, and its\n\t * outcome is then unknown. Rows done before a stop stay done: a cancel takes nothing back.\n\t */\n\tasync cancel(): Promise<void> {\n\t\tconst checking = this.#checking\n\n\t\tif (checking) {\n\t\t\tthis.#checking = null\n\t\t\tchecking.controller.abort()\n\t\t\tthis.#setState({ phase: \"idle\", check: record(checking.request, \"cancelled\") })\n\n\t\t\treturn\n\t\t}\n\n\t\tconst run = this.#state.run\n\t\tconst stop = this.#adapters.cancelProcess\n\n\t\tif (this.#state.phase !== \"processing\" || !run) {\n\t\t\treturn\n\t\t}\n\n\t\tif (run.operationId !== null && stop) {\n\t\t\ttry {\n\t\t\t\tawait stop(this.#query(), { signal: neverAborted(), requestId: run.requestId })\n\t\t\t} catch (error) {\n\t\t\t\tthis.#setState({ failure: failure(\"cancel\", error) })\n\t\t\t}\n\n\t\t\t// The run's own answer says what was stopped and what was done first.\n\t\t\treturn\n\t\t}\n\n\t\tthis.#running?.abort()\n\t}\n\n\t/**\n\t * Takes the rows that went through out of the sheet, as one change, so work goes on with the rest.\n\t * Their results stay: an undo brings them back as they were, processed and locked.\n\t *\n\t * @returns how many rows were taken out\n\t */\n\tremoveSucceeded(): number {\n\t\tconst done = this.store.rowIds().filter(rowId => this.#results.resultOf(rowId)?.outcome === \"succeeded\")\n\n\t\tif (done.length > 0) {\n\t\t\tthis.store.transact(() => this.store.removeRows(done), { origin: \"processed\" })\n\t\t}\n\n\t\treturn done.length\n\t}\n\n\t/** Stops every request and stops following the store. */\n\tdispose(): void {\n\t\tthis.#disposed = true\n\t\tthis.#checking?.controller.abort()\n\t\tthis.#checking = null\n\t\tthis.#running?.abort()\n\t\tthis.#running = null\n\t\tthis.#stop()\n\t\tthis.#merged.dispose()\n\n\t\tif (this.#ownValidator) {\n\t\t\tthis.validator.dispose()\n\t\t}\n\t}\n\n\t// ---------------------------------------------------------------- runs\n\n\tasync #follow(\n\t\trequest: ProcessRequest,\n\t\tfirst: ProcessResponse,\n\t\tcontroller: AbortController\n\t): Promise<ProcessOutcome> {\n\t\tlet response = first\n\n\t\twhile (response.status === \"pending\") {\n\t\t\tthis.#record(request, response, false)\n\t\t\tthis.#setRun({\n\t\t\t\toperationId: response.operationId ?? this.#state.run?.operationId ?? null,\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tprogress: response.progress ?? this.#state.run?.progress ?? null\n\t\t\t})\n\n\t\t\tconst ask = this.#adapters.processStatus\n\n\t\t\tif (!ask) {\n\t\t\t\treturn this.#lose(\n\t\t\t\t\t\"status\",\n\t\t\t\t\tnew TabulaError(\n\t\t\t\t\t\t\"invalid_argument\",\n\t\t\t\t\t\t\"The run is still going, and there is no processStatus adapter to follow it.\"\n\t\t\t\t\t),\n\t\t\t\t\t\"unavailable\"\n\t\t\t\t)\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tawait wait(this.#pollInterval, controller.signal)\n\n\t\t\t\tconst answer = await raced(\n\t\t\t\t\task(this.#query(), { signal: controller.signal, requestId: request.requestId }),\n\t\t\t\t\tcontroller.signal\n\t\t\t\t)\n\n\t\t\t\tresponse = this.#answered(request.requestId, readProcessResponse(answer))\n\t\t\t} catch (error) {\n\t\t\t\treturn this.#lose(\"status\", error)\n\t\t\t}\n\t\t}\n\n\t\tif (this.#disposed) {\n\t\t\treturn outcome(\"unknown\")\n\t\t}\n\n\t\tthis.#record(request, response, true)\n\t\tthis.#pending = null\n\t\tthis.#checked = null\n\t\tthis.#running = null\n\t\tthis.#results.setInFlight(new Set())\n\t\tthis.#setState({\n\t\t\tphase: \"idle\",\n\t\t\tfailure: null,\n\t\t\trun: {\n\t\t\t\t...(this.#state.run as RunRecord),\n\t\t\t\toperationId: response.operationId ?? this.#state.run?.operationId ?? null,\n\t\t\t\tstatus: response.status,\n\t\t\t\tprogress: response.progress ?? this.#state.run?.progress ?? null\n\t\t\t}\n\t\t})\n\n\t\tconst counts = { succeeded: 0, failed: 0, skipped: 0 }\n\n\t\tfor (const row of request.rows) {\n\t\t\tconst result = this.#results.resultOf(row.rowId)\n\n\t\t\tif (result?.requestId === request.requestId) {\n\t\t\t\tcounts[result.outcome]++\n\t\t\t}\n\t\t}\n\n\t\treturn { status: response.status, ...counts, blocked: 0 }\n\t}\n\n\t/** No answer to go by: the rows stay locked and the request stays ready to be sent again. */\n\t#lose(stage: SessionFailure[\"stage\"], error: unknown, code?: SessionFailure[\"code\"]): ProcessOutcome {\n\t\tif (!this.#disposed) {\n\t\t\tconst run = this.#state.run\n\n\t\t\tthis.#running = null\n\t\t\tthis.#setState({\n\t\t\t\tphase: \"unknown\",\n\t\t\t\tfailure: failure(stage, error, code),\n\t\t\t\trun: run ? Object.freeze({ ...run, status: \"unknown\" }) : null\n\t\t\t})\n\t\t}\n\n\t\treturn outcome(\"unknown\")\n\t}\n\n\t/** Keeps what an answer says about each row it was sent. */\n\t#record(request: ProcessRequest, response: ProcessResponse, final: boolean): void {\n\t\tconst sent = new Set(request.rows.map(row => row.rowId))\n\t\tconst answered = new Set<RowId>()\n\t\tconst results: RowResult[] = []\n\t\tconst issues: Issue[] = []\n\n\t\tresponse.rows?.forEach((row, index) => {\n\t\t\tif (!sent.has(row.rowId) || answered.has(row.rowId)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tanswered.add(row.rowId)\n\t\t\tresults.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\trowId: row.rowId,\n\t\t\t\t\toutcome: row.result,\n\t\t\t\t\tdata: Object.freeze({ ...row.data }),\n\t\t\t\t\trequestId: request.requestId\n\t\t\t\t})\n\t\t\t)\n\t\t\trow.issues?.forEach((input, at) => {\n\t\t\t\tconst issue = this.#toIssue(input, \"process\", `${index}.${at}`, request.revision, row.rowId)\n\n\t\t\t\tif (issue) {\n\t\t\t\t\tissues.push(issue)\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\n\t\tif (final) {\n\t\t\tfor (const rowId of sent) {\n\t\t\t\t// A row an earlier `pending` answer settled keeps that result.\n\t\t\t\tconst settled = this.#results.resultOf(rowId)?.requestId === request.requestId\n\n\t\t\t\tif (!answered.has(rowId) && !settled) {\n\t\t\t\t\tconst kind = response.status === \"succeeded\" ? \"succeeded\" : \"skipped\"\n\n\t\t\t\t\tanswered.add(rowId)\n\t\t\t\t\tresults.push(\n\t\t\t\t\t\tObject.freeze({ rowId, outcome: kind, data: Object.freeze({}), requestId: request.requestId })\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse.issues?.forEach((input, index) => {\n\t\t\t\tconst issue = this.#toIssue(input, \"process\", `run.${index}`, request.revision, null)\n\n\t\t\t\tif (issue) {\n\t\t\t\t\tissues.push(issue)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\n\t\tconst done = new Set(results.filter(result => result.outcome === \"succeeded\").map(result => result.rowId))\n\n\t\t// What a run says about a row replaces what the last one said; a row that went through has\n\t\t// nothing left for a pre-flight check to say.\n\t\tthis.#merged.replace(\n\t\t\tissue =>\n\t\t\t\t(issue.source === \"process\" && (issue.rowId === null ? final : answered.has(issue.rowId))) ||\n\t\t\t\t(issue.source === \"preflight\" && issue.rowId !== null && done.has(issue.rowId)),\n\t\t\tissues\n\t\t)\n\t\tthis.#results.record(results)\n\t}\n\n\t#rowPlan(rowId: RowId, given: RowPlanInput | undefined): RowPlan {\n\t\tif (given === undefined) {\n\t\t\treturn Object.freeze({ rowId, action: \"unknown\", changes: Object.freeze([]) })\n\t\t}\n\n\t\tconst changes: PlannedChange[] = []\n\t\tconst previous = given.previous ?? {}\n\n\t\tfor (const field of this.schema.fields) {\n\t\t\tif (!field.submit) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst value = this.store.get(rowId, field.key)\n\t\t\t// An error a formula gave is not sent, so it is not written either.\n\t\t\tconst after = isFormulaError(value) ? null : value\n\n\t\t\tif (given.action === \"create\" && after !== null) {\n\t\t\t\tchanges.push(Object.freeze({ field: field.key, before: null, after }))\n\t\t\t} else if (given.action === \"update\" && Object.hasOwn(previous, field.key)) {\n\t\t\t\tchanges.push(Object.freeze({ field: field.key, before: previous[field.key] ?? null, after }))\n\t\t\t}\n\t\t}\n\n\t\treturn Object.freeze({ rowId, action: given.action, changes: Object.freeze(changes) })\n\t}\n\n\t#query(): StatusQuery {\n\t\tconst request = this.#pending as ProcessRequest\n\n\t\treturn Object.freeze({\n\t\t\trequestId: request.requestId,\n\t\t\tidempotencyKey: request.idempotencyKey,\n\t\t\toperationId: this.#state.run?.operationId ?? null\n\t\t})\n\t}\n\n\t#blockedRows(rowIds: readonly RowId[]): number {\n\t\tconst server = this.#merged.server.filter(issue => issue.blocking && !issue.stale)\n\n\t\tif (server.some(issue => issue.rowId === null)) {\n\t\t\treturn rowIds.length\n\t\t}\n\n\t\tconst blockedByServer = new Set(server.map(issue => issue.rowId))\n\n\t\treturn rowIds.filter(rowId => blockedByServer.has(rowId) || this.validator.hasErrors(rowId)).length\n\t}\n\n\t// ---------------------------------------------------------------- requests and answers\n\n\t#request(rowIds: readonly RowId[]): SheetRequest {\n\t\treturn Object.freeze({\n\t\t\trequestId: this.#requestId(),\n\t\t\tmodule: this.schema.module,\n\t\t\tschemaVersion: this.schema.schemaVersion,\n\t\t\tsheetId: this.sheetId,\n\t\t\trevision: this.store.revision,\n\t\t\trows: Object.freeze(rowIds.map(rowId => Object.freeze({ rowId, values: this.#payload(rowId) })))\n\t\t})\n\t}\n\n\t#payload(rowId: RowId): Readonly<Record<string, CellValue>> {\n\t\tconst values: Record<string, CellValue> = {}\n\n\t\tfor (const field of this.schema.fields) {\n\t\t\tif (field.submit) {\n\t\t\t\tconst value = this.store.get(rowId, field.key)\n\n\t\t\t\t// An error a formula gave is no value to send; the backend works the formula out again.\n\t\t\t\tvalues[field.key] = isFormulaError(value)\n\t\t\t\t\t? null\n\t\t\t\t\t: field.type === \"lookup\"\n\t\t\t\t\t\t? lookupPayload(value)\n\t\t\t\t\t\t: canonicalValue(field, value, this.validator.settings)\n\t\t\t}\n\t\t}\n\n\t\treturn Object.freeze(values)\n\t}\n\n\t/** Nothing to send: a row holding only columns shown for reference is empty too. */\n\t#isEmpty(rowId: RowId): boolean {\n\t\treturn this.schema.fields.every(field => !field.submit || this.store.get(rowId, field.key) === null)\n\t}\n\n\t/** An answer that names a request must name this one. */\n\t#answered<T extends { readonly requestId?: string }>(requestId: string, response: T): T {\n\t\tif (response.requestId !== undefined && response.requestId !== requestId) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_response\",\n\t\t\t\t`The answer is to request \"${response.requestId}\", not to \"${requestId}\", the one it came back for.`\n\t\t\t)\n\t\t}\n\n\t\treturn response\n\t}\n\n\t/**\n\t * An issue from a backend as the sheet holds it. One for another sheet or for a row no longer in\n\t * this one is passed over. One for a field the schema does not have is kept as the row's, the key\n\t * in its params, so it is still seen.\n\t */\n\t#toIssue(input: IssueInput, source: string, key: string, revision: number, row: RowId | null): Issue | null {\n\t\tif (input.sheetId != null && input.sheetId !== this.sheetId) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst rowId = input.rowId === undefined ? row : input.rowId\n\n\t\tif (rowId !== null && !this.store.has(rowId)) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst params: Record<string, string> = {}\n\n\t\tfor (const [name, value] of Object.entries(input.params ?? {})) {\n\t\t\tparams[name] = value === null ? \"\" : String(value)\n\t\t}\n\n\t\tlet field = input.field ?? null\n\n\t\tif (field !== null && !this.schema.has(field)) {\n\t\t\tparams.field ??= field\n\t\t\tfield = null\n\t\t}\n\n\t\tconst scope = scopeOf(input.scope, rowId, field)\n\t\tconst severity = input.severity ?? \"error\"\n\t\tconst issue: Issue = {\n\t\t\tid: `${source}|${key}|${input.code}|${rowId ?? \"\"}|${field ?? \"\"}`,\n\t\t\tscope,\n\t\t\tsource,\n\t\t\trowId: scope === \"sheet\" || scope === \"workbook\" ? null : rowId,\n\t\t\tfield: scope === \"cell\" ? field : null,\n\t\t\ttargets: Object.freeze((input.targets ?? []).map(target => Object.freeze({ ...target }))),\n\t\t\tcode: input.code,\n\t\t\tseverity,\n\t\t\tblocking: input.blocking ?? severity === \"error\",\n\t\t\tstale: false,\n\t\t\tmessage: input.message ?? input.code,\n\t\t\tparams: Object.freeze(params)\n\t\t}\n\n\t\treturn Object.freeze({ ...issue, stale: this.#changedSince(issue, revision) })\n\t}\n\n\t/** Whether a cell the issue is about changed after the revision it was found at. */\n\t#changedSince(issue: Issue, revision: number): boolean {\n\t\tif (issue.rowId === null) {\n\t\t\treturn this.store.revision > revision\n\t\t}\n\n\t\tconst changed =\n\t\t\tissue.scope === \"row\"\n\t\t\t\t? (this.#rowChanged.get(issue.rowId) ?? -1)\n\t\t\t\t: (this.#cellChanged.get(issue.rowId)?.get(issue.field ?? \"\") ?? -1)\n\n\t\treturn (\n\t\t\tchanged > revision ||\n\t\t\tissue.targets.some(\n\t\t\t\ttarget =>\n\t\t\t\t\t!this.store.has(target.rowId) ||\n\t\t\t\t\t(this.#cellChanged.get(target.rowId)?.get(target.field) ?? -1) > revision\n\t\t\t)\n\t\t)\n\t}\n\n\t// ---------------------------------------------------------------- the sheet changing\n\n\t#onChange(change: StoreChange): void {\n\t\tconst cells = new Map<RowId, Set<string>>()\n\t\tconst removed = new Set<RowId>()\n\n\t\tfor (const operation of change.operations) {\n\t\t\tif (operation.kind === \"set\") {\n\t\t\t\tlet fields = this.#cellChanged.get(operation.rowId)\n\n\t\t\t\tif (!fields) {\n\t\t\t\t\tfields = new Map()\n\t\t\t\t\tthis.#cellChanged.set(operation.rowId, fields)\n\t\t\t\t}\n\n\t\t\t\tfields.set(operation.field, change.revision)\n\t\t\t\tthis.#rowChanged.set(operation.rowId, change.revision)\n\n\t\t\t\tconst touched = cells.get(operation.rowId) ?? new Set()\n\n\t\t\t\ttouched.add(operation.field)\n\t\t\t\tcells.set(operation.rowId, touched)\n\t\t\t} else if (operation.kind === \"insert\") {\n\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\tthis.#rowChanged.set(row.rowId, change.revision)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\tremoved.add(row.rowId)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst touches = (rowId: RowId, field: string): boolean =>\n\t\t\tremoved.has(rowId) || (cells.get(rowId)?.has(field) ?? false)\n\n\t\tthis.#merged.update(issue => {\n\t\t\tif (issue.rowId !== null && !this.store.has(issue.rowId)) {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\tif (issue.stale) {\n\t\t\t\treturn issue\n\t\t\t}\n\n\t\t\tconst affected =\n\t\t\t\tissue.rowId === null ||\n\t\t\t\t(issue.scope === \"row\" ? cells.has(issue.rowId) : touches(issue.rowId, issue.field ?? \"\")) ||\n\t\t\t\tissue.targets.some(target => touches(target.rowId, target.field))\n\n\t\t\treturn affected ? Object.freeze({ ...issue, stale: true }) : issue\n\t\t})\n\t}\n\n\t// ---------------------------------------------------------------- state\n\n\t/** Takes up where a draft left off: results back on their rows, a run with no answer still unknown. */\n\t#restore(saved: PersistedSession): void {\n\t\tthis.#results.record(saved.results.filter(result => this.store.has(result.rowId)))\n\n\t\tconst pending = saved.pending\n\n\t\tif (!pending) {\n\t\t\treturn\n\t\t}\n\n\t\tconst request = pending.request\n\n\t\tthis.#pending = request\n\t\tthis.#results.setInFlight(new Set(request.rows.map(row => row.rowId)))\n\t\tthis.#setState({\n\t\t\tphase: \"unknown\",\n\t\t\trun: Object.freeze({\n\t\t\t\trequestId: request.requestId,\n\t\t\t\tidempotencyKey: request.idempotencyKey,\n\t\t\t\toperationId: pending.operationId,\n\t\t\t\trevision: request.revision,\n\t\t\t\trows: request.rows.length,\n\t\t\t\tstatus: \"unknown\",\n\t\t\t\tprogress: null\n\t\t\t})\n\t\t})\n\t}\n\n\t#setState(patch: Partial<SessionState>): void {\n\t\tif (this.#disposed) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#state = Object.freeze({ ...this.#state, ...patch })\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n\n\t#setRun(patch: Partial<RunRecord>): void {\n\t\tconst run = this.#state.run\n\n\t\tif (run) {\n\t\t\tthis.#setState({ run: Object.freeze({ ...run, ...patch }) })\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------- the merged issues\n\ninterface IssueIndex {\n\treadonly sheet: Issue[]\n\treadonly rows: Map<RowId, Issue[]>\n\treadonly cells: Map<RowId, Map<string, Issue[]>>\n}\n\n/** The local validator's issues and the backend's, read as one set. */\nclass MergedIssues implements IssueSet {\n\treadonly #local: SheetValidator\n\treadonly #store: RowStore\n\treadonly #schema: ModuleSchema\n\treadonly #listeners = new Listeners<MergedIssues>()\n\treadonly #stop: () => void\n\t#server: readonly Issue[] = []\n\t#index: IssueIndex | null = null\n\t#version = 0\n\n\tconstructor(local: SheetValidator, store: RowStore, schema: ModuleSchema) {\n\t\tthis.#local = local\n\t\tthis.#store = store\n\t\tthis.#schema = schema\n\t\tthis.#stop = local.subscribe(() => this.#changed())\n\t}\n\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\t/** The backend's issues alone. */\n\tget server(): readonly Issue[] {\n\t\treturn this.#server\n\t}\n\n\tissuesAt(rowId: RowId, field: string): readonly Issue[] {\n\t\tconst own = this.#local.issuesAt(rowId, field)\n\t\tconst remote = this.#indexed().cells.get(rowId)?.get(field)\n\n\t\treturn remote ? [...own, ...remote] : own\n\t}\n\n\trowIssues(rowId: RowId): readonly Issue[] {\n\t\treturn this.#indexed().rows.get(rowId) ?? []\n\t}\n\n\thasIssues(rowId: RowId): boolean {\n\t\tconst index = this.#indexed()\n\n\t\treturn this.#local.hasIssues(rowId) || index.rows.has(rowId) || index.cells.has(rowId)\n\t}\n\n\tissues(): Issue[] {\n\t\tconst index = this.#indexed()\n\t\tconst result: Issue[] = [...index.sheet]\n\n\t\tfor (const rowId of this.#store.rowIds()) {\n\t\t\tresult.push(...(index.rows.get(rowId) ?? []))\n\n\t\t\tfor (const field of this.#schema.fields) {\n\t\t\t\tresult.push(...this.issuesAt(rowId, field.key))\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n\tsummary(): IssueSummary {\n\t\tconst local = this.#local.summary()\n\t\tconst rows = this.#local.affectedRows()\n\t\tlet errors = local.errors\n\t\tlet warnings = local.warnings\n\t\tlet stale = 0\n\n\t\tfor (const issue of this.#server) {\n\t\t\tif (issue.stale) {\n\t\t\t\tstale++\n\t\t\t} else if (issue.severity === \"error\") {\n\t\t\t\terrors++\n\t\t\t} else {\n\t\t\t\twarnings++\n\t\t\t}\n\n\t\t\tif (issue.rowId !== null) {\n\t\t\t\trows.add(issue.rowId)\n\t\t\t}\n\t\t}\n\n\t\treturn { errors, warnings, stale, rows: rows.size }\n\t}\n\n\tsubscribe(listener: () => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Takes out the backend's issues `drop` picks, and adds `add`. */\n\treplace(drop: (issue: Issue) => boolean, add: readonly Issue[]): void {\n\t\tconst kept = this.#server.filter(issue => !drop(issue))\n\n\t\tif (kept.length === this.#server.length && add.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#server = [...kept, ...add]\n\t\tthis.#index = null\n\t\tthis.#changed()\n\t}\n\n\t/** Passes each of the backend's issues through `fn`: the same issue, a changed one, or null to drop it. */\n\tupdate(fn: (issue: Issue) => Issue | null): void {\n\t\tlet changed = false\n\t\tconst next: Issue[] = []\n\n\t\tfor (const issue of this.#server) {\n\t\t\tconst updated = fn(issue)\n\n\t\t\tchanged ||= updated !== issue\n\n\t\t\tif (updated) {\n\t\t\t\tnext.push(updated)\n\t\t\t}\n\t\t}\n\n\t\tif (changed) {\n\t\t\tthis.#server = next\n\t\t\tthis.#index = null\n\t\t\tthis.#changed()\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.#stop()\n\t}\n\n\t#indexed(): IssueIndex {\n\t\tif (this.#index) {\n\t\t\treturn this.#index\n\t\t}\n\n\t\tconst index: IssueIndex = { sheet: [], rows: new Map(), cells: new Map() }\n\n\t\tfor (const issue of this.#server) {\n\t\t\tif (issue.rowId === null) {\n\t\t\t\tindex.sheet.push(issue)\n\t\t\t} else if (issue.field === null) {\n\t\t\t\tpush(index.rows, issue.rowId, issue)\n\t\t\t} else {\n\t\t\t\tlet fields = index.cells.get(issue.rowId)\n\n\t\t\t\tif (!fields) {\n\t\t\t\t\tfields = new Map()\n\t\t\t\t\tindex.cells.set(issue.rowId, fields)\n\t\t\t\t}\n\n\t\t\t\tpush(fields, issue.field, issue)\n\t\t\t}\n\t\t}\n\n\t\tthis.#index = index\n\n\t\treturn index\n\t}\n\n\t#changed(): void {\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n}\n\n// ---------------------------------------------------------------- results\n\nclass Results implements RowResults {\n\treadonly #results = new Map<RowId, RowResult>()\n\treadonly #listeners = new Listeners<Results>()\n\t#inFlight: ReadonlySet<RowId> = new Set()\n\t#version = 0\n\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\tresultOf(rowId: RowId): RowResult | null {\n\t\treturn this.#results.get(rowId) ?? null\n\t}\n\n\tisLocked(rowId: RowId): boolean {\n\t\treturn this.#inFlight.has(rowId) || this.#results.get(rowId)?.outcome === \"succeeded\"\n\t}\n\n\tsubscribe(listener: () => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\tsetInFlight(rows: ReadonlySet<RowId>): void {\n\t\tif (rows.size === 0 && this.#inFlight.size === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#inFlight = rows\n\t\tthis.#changed()\n\t}\n\n\trecord(results: readonly RowResult[]): void {\n\t\tif (results.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tfor (const result of results) {\n\t\t\tthis.#results.set(result.rowId, result)\n\t\t}\n\n\t\tthis.#changed()\n\t}\n\n\t#changed(): void {\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n}\n\n// ---------------------------------------------------------------- helpers\n\nfunction outcome(status: ProcessOutcome[\"status\"]): ProcessOutcome {\n\treturn { status, succeeded: 0, failed: 0, skipped: 0, blocked: 0 }\n}\n\nfunction record(request: SheetRequest, outcome: CheckRecord[\"outcome\"]): CheckRecord {\n\treturn Object.freeze({ requestId: request.requestId, revision: request.revision, outcome })\n}\n\nfunction failure(stage: SessionFailure[\"stage\"], error: unknown, code?: SessionFailure[\"code\"]): SessionFailure {\n\tconst invalid = error instanceof TabulaError && error.code === \"invalid_response\"\n\n\treturn Object.freeze({\n\t\tstage,\n\t\tcode: code ?? (invalid ? \"invalid_response\" : \"request_failed\"),\n\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\terror\n\t})\n}\n\n/** The widest scope the ids can carry, when the one given needs more than they have. */\nfunction scopeOf(given: IssueScope | undefined, rowId: RowId | null, field: string | null): IssueScope {\n\tconst scope = given ?? (rowId === null ? \"sheet\" : field === null ? \"row\" : \"cell\")\n\n\tif (scope === \"cell\" && field === null) {\n\t\treturn rowId === null ? \"sheet\" : \"row\"\n\t}\n\n\tif (scope === \"row\" && rowId === null) {\n\t\treturn \"sheet\"\n\t}\n\n\treturn scope\n}\n\nfunction lookupPayload(value: CellValue): CellValue {\n\tif (isLookupValue(value)) {\n\t\treturn value.id\n\t}\n\n\treturn typeof value === \"string\" ? Object.freeze({ label: value }) : value\n}\n\nfunction push<K>(map: Map<K, Issue[]>, key: K, issue: Issue): void {\n\tconst list = map.get(key)\n\n\tif (list) {\n\t\tlist.push(issue)\n\t} else {\n\t\tmap.set(key, [issue])\n\t}\n}\n","import type { RowId, RowStore, StoreChange } from \"./rows.js\"\nimport type { ModuleSchema } from \"./schema.js\"\nimport { formatCell } from \"./values/format.js\"\nimport { readInput } from \"./values/read.js\"\nimport type { ValueSettings } from \"./values/settings.js\"\n\n/**\n * Find and replace over a sheet, as a spreadsheet's Ctrl+H: text looked for in the cells as they are\n * shown, \"1.533,80\", \"Mağaza, Web\", and replaced as if it had been typed into each, so a number stays\n * a number and an option an option. Every replacement is one change of the store: one Ctrl+Z.\n */\n\n/** The origin of the change `replaceCells` makes, as `StoreChange.origin` gives it. */\nexport const REPLACE_ORIGIN = \"replace\"\n\nexport interface FindOptions {\n\treadonly settings: ValueSettings\n\t/** Upper and lower case told apart. Off by default. */\n\treadonly matchCase?: boolean\n\t/** Only a cell whose whole text is what is looked for. Off by default. */\n\treadonly whole?: boolean\n\t/** The language case is folded in, the page's: in Turkish \"I\" is \"ı\" in lower case. */\n\treadonly locale?: string\n}\n\n/** A cell, by its row's id and its field's key. */\nexport interface FoundCell {\n\treadonly rowId: RowId\n\treadonly field: string\n}\n\n/**\n * The cells holding `text`, row by row in the order given, and in each row field by field in the\n * order given: where Next goes. Empty text finds nothing.\n */\nexport function findCells(\n\tstore: RowStore,\n\tschema: ModuleSchema,\n\trowIds: readonly RowId[],\n\tfields: readonly string[],\n\ttext: string,\n\toptions: FindOptions\n): FoundCell[] {\n\tif (text === \"\") {\n\t\treturn []\n\t}\n\n\tconst matches = matcher(text, options)\n\tconst known = fields.filter(key => schema.has(key))\n\tconst found: FoundCell[] = []\n\n\tfor (const rowId of rowIds) {\n\t\tfor (const field of known) {\n\t\t\tif (matches(formatCell(schema.field(field), store.get(rowId, field), options.settings))) {\n\t\t\t\tfound.push({ rowId, field })\n\t\t\t}\n\t\t}\n\t}\n\n\treturn found\n}\n\nexport interface ReplaceOptions extends FindOptions {\n\t/** Whether a cell may be written; a cell refused is left as it is and counted. All may by default. */\n\treadonly editable?: (rowId: RowId, field: string) => boolean\n\treadonly origin?: string\n}\n\nexport interface ReplaceResult {\n\t/** Cells written. */\n\treadonly replaced: number\n\t/** Cells left as they were: their column or row cannot be written. */\n\treadonly skipped: number\n\t/** The store's change; null when nothing was written. */\n\treadonly change: StoreChange | null\n}\n\n/**\n * Replaces `text` with `replacement` in the cells given, such as `findCells`' answer, in one change.\n * Each cell's new text is read as typing it would be read; text that cannot be read is kept as typed\n * and its cell says why, as a paste does. A column that cannot be typed into, or a formula's, is\n * left as it is.\n */\nexport function replaceCells(\n\tstore: RowStore,\n\tschema: ModuleSchema,\n\tcells: readonly FoundCell[],\n\ttext: string,\n\treplacement: string,\n\toptions: ReplaceOptions\n): ReplaceResult {\n\tif (text === \"\") {\n\t\treturn { replaced: 0, skipped: 0, change: null }\n\t}\n\n\tconst writes: { rowId: RowId; field: string; value: ReturnType<typeof readInput>[\"value\"] }[] = []\n\tlet skipped = 0\n\n\tfor (const cell of cells) {\n\t\tif (!schema.has(cell.field) || !store.has(cell.rowId)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst field = schema.field(cell.field)\n\n\t\tif (!field.editable || field.formula || options.editable?.(cell.rowId, cell.field) === false) {\n\t\t\tskipped++\n\t\t\tcontinue\n\t\t}\n\n\t\tconst shown = formatCell(field, store.get(cell.rowId, cell.field), options.settings)\n\t\tconst next = replaced(shown, text, replacement, options)\n\n\t\tif (next === null) {\n\t\t\tcontinue\n\t\t}\n\n\t\twrites.push({ rowId: cell.rowId, field: cell.field, value: readInput(field, next, options.settings).value })\n\t}\n\n\tconst change = writes.length === 0 ? null : store.setCells(writes, { origin: options.origin ?? REPLACE_ORIGIN })\n\n\treturn { replaced: writes.length, skipped, change }\n}\n\nfunction matcher(text: string, options: FindOptions): (shown: string) => boolean {\n\tconst fold = (value: string): string => (options.matchCase ? value : value.toLocaleLowerCase(options.locale))\n\tconst wanted = fold(text)\n\n\treturn shown => (options.whole ? fold(shown) === wanted : fold(shown).includes(wanted))\n}\n\n/** The cell's text with every match replaced; null when it holds none. */\nfunction replaced(shown: string, text: string, replacement: string, options: FindOptions): string | null {\n\tconst fold = (value: string): string => (options.matchCase ? value : value.toLocaleLowerCase(options.locale))\n\n\tif (options.whole) {\n\t\treturn fold(shown) === fold(text) ? replacement : null\n\t}\n\n\tconst haystack = fold(shown)\n\tconst needle = fold(text)\n\tlet at = haystack.indexOf(needle)\n\n\tif (at < 0) {\n\t\treturn null\n\t}\n\n\t// Folding case can change a text's length (\"İ\" in some languages); then the match is replaced whole.\n\tif (haystack.length !== shown.length) {\n\t\treturn haystack.split(needle).join(replacement)\n\t}\n\n\tlet result = \"\"\n\tlet from = 0\n\n\twhile (at >= 0) {\n\t\tresult += shown.slice(from, at) + replacement\n\t\tfrom = at + needle.length\n\t\tat = haystack.indexOf(needle, from)\n\t}\n\n\treturn result + shown.slice(from)\n}\n","/**\n * The version of this package.\n *\n * It repeats what `package.json` says, and a test holds the two together: a release that bumps\n * one and forgets the other fails before it is tagged.\n */\nexport const version = \"0.4.0\"\n\nexport { SchemaError, TabulaError } from \"./errors.js\"\nexport type { SchemaProblem, TabulaErrorCode } from \"./errors.js\"\n\nexport type { CellObject, CellValue } from \"./value.js\"\n\nexport { CUSTOMIZATIONS, FIELD_TYPES, ModuleSchema } from \"./schema.js\"\nexport type {\n\tBoolField,\n\tCustomization,\n\tDateField,\n\tDecimalField,\n\tFieldInput,\n\tFieldOption,\n\tFieldRule,\n\tFieldSchema,\n\tFieldTone,\n\tFieldType,\n\tIntegerField,\n\tLookupField,\n\tModuleSchemaInput,\n\tMoneyField,\n\tOptionInput,\n\tOptionsField,\n\tRuleInput,\n\tTextField\n} from \"./schema.js\"\n\nexport { RowStore } from \"./rows.js\"\nexport type {\n\tCellWrite,\n\tRemovedRow,\n\tRowEntry,\n\tRowId,\n\tRowInit,\n\tRowStoreOptions,\n\tRowValues,\n\tStoreChange,\n\tStoreOperation,\n\tTransactOptions\n} from \"./rows.js\"\n\nexport { REDO_ORIGIN, UNDO_ORIGIN, UndoHistory } from \"./history.js\"\nexport type { HistoryStep, UndoHistoryOptions } from \"./history.js\"\n\nexport { LOOKUP_ORIGIN, LookupResolver } from \"./lookup.js\"\nexport type {\n\tLookupAdapters,\n\tLookupItem,\n\tLookupResolveRequest,\n\tLookupResolveResponse,\n\tLookupResolverOptions,\n\tLookupSearch,\n\tLookupSearchRequest,\n\tLookupSearchResponse\n} from \"./lookup.js\"\n\nexport { applyFormulas, FORMULA_ORIGIN, FormulaEngine } from \"./formula/engine.js\"\nexport type { FormulaEngineOptions } from \"./formula/engine.js\"\nexport {\n\tboolValue as formulaBool,\n\tEMPTY as FORMULA_EMPTY,\n\terrorValue as formulaError,\n\tFUNCTIONS as FORMULA_FUNCTIONS,\n\tformulaNumber,\n\tnumberArgument,\n\ttextValue as formulaText\n} from \"./formula/evaluate.js\"\nexport type { FormulaFunction, FormulaValue } from \"./formula/evaluate.js\"\nexport { formulaFields, parseFormula } from \"./formula/parse.js\"\nexport {\n\tformulaCaret,\n\tformulaFromAddresses,\n\tformulaParts,\n\tformulaWithKeys,\n\tformulaWithLabels\n} from \"./formula/assist.js\"\nexport type { FormulaCall, FormulaCaret, FormulaPart, FormulaToken, NamedField } from \"./formula/assist.js\"\nexport type { BinaryOperator, FormulaNode } from \"./formula/parse.js\"\nexport { isFormulaError } from \"./formula/error.js\"\nexport type { FormulaErrorCode, FormulaErrorValue } from \"./formula/error.js\"\n\nexport { RowView, rowsWithIssues, rowsWithResult } from \"./view.js\"\nexport type { RowFilter, RowOrder } from \"./view.js\"\nexport { summarizeCells } from \"./summary.js\"\nexport {\n\tcompareValues,\n\tdistinctValues,\n\tfilterKey,\n\tfilterKeys,\n\thasRange,\n\trowOrder,\n\trowsContaining,\n\trowsMatching\n} from \"./filters.js\"\nexport { fillValues } from \"./fill.js\"\nexport { adjustValue, isAdjustable } from \"./adjust.js\"\nexport type { Adjustment } from \"./adjust.js\"\nexport { rowsChanged, SheetChanges } from \"./changes.js\"\nexport type { ChangeSummary, SheetChangesOptions } from \"./changes.js\"\nexport { breaksCheck, checkFields, COMPARISONS, CONDITION_OPS, conditionHolds, rowsBreaking } from \"./checks.js\"\nexport type {\n\tCheckInput,\n\tCheckSeverity,\n\tComparison,\n\tConditionInput,\n\tConditionOp,\n\tRowCheck,\n\tRowCondition\n} from \"./checks.js\"\nexport {\n\tapplyTemplate,\n\treadTemplate,\n\tTEMPLATE_FORMAT,\n\tTEMPLATE_VERSION,\n\ttemplateProblems,\n\twithDefaults\n} from \"./templates.js\"\nexport type { GridTemplate, TemplateFieldChange, TemplateProblem } from \"./templates.js\"\nexport {\n\taddView,\n\temptyViews,\n\tPLAIN_VIEW,\n\treadViews,\n\treadViewState,\n\tremoveView,\n\trenameView,\n\tsameView,\n\tsetDefaultView,\n\tupdateView,\n\tVIEW_NAME_LIMIT,\n\tviewFor,\n\tviewNameProblem,\n\tVIEWS_FORMAT,\n\tVIEWS_VERSION\n} from \"./views.js\"\nexport type { SavedView, SavedViews, ViewNameOptions, ViewNameProblem, ViewState } from \"./views.js\"\nexport type { FillMode, FillOptions } from \"./fill.js\"\nexport type { ColumnCondition, ColumnFilters, ColumnSort, DistinctValue, SearchOptions } from \"./filters.js\"\nexport type { CellSummary } from \"./summary.js\"\n\nexport { Selection } from \"./selection.js\"\nexport type { CellPosition, CellRange, Direction, IsBlank, MoveOptions } from \"./selection.js\"\n\nexport { parseTsv, toTsv } from \"./clipboard.js\"\n\nexport { decodeText, detectDelimiter, parseCsv, toCsv } from \"./csv.js\"\nexport type { CsvDelimiter, CsvReadOptions, CsvWriteOptions } from \"./csv.js\"\nexport { csvDelimiterFor, exportTable, importTable } from \"./table.js\"\nexport type { ColumnMatch, ColumnStatus, TableExportOptions, TableImport, TableImportOptions } from \"./table.js\"\n\nexport { checkValue, SheetValidator } from \"./validation.js\"\nexport type {\n\tIssue,\n\tIssueScope,\n\tIssueSet,\n\tIssueSeverity,\n\tIssueSummary,\n\tIssueTarget,\n\tLocalIssueCode\n} from \"./validation.js\"\n\nexport { readCheckResponse, readProcessResponse } from \"./contract.js\"\nexport type {\n\tAdapterContext,\n\tCheckResponse,\n\tIssueInput,\n\tPayloadRow,\n\tProcessProgress,\n\tProcessRequest,\n\tProcessResponse,\n\tProcessStatus,\n\tRowAction,\n\tRowOutcome,\n\tRowPlanInput,\n\tRowResultInput,\n\tSheetAdapters,\n\tSheetRequest,\n\tStatusQuery\n} from \"./contract.js\"\n\nexport { createDraft, DRAFT_FORMAT, DRAFT_VERSION, mapDraft, openDraft, readDraft, suggestRenames } from \"./draft.js\"\nexport type {\n\tCreateDraftOptions,\n\tDraft,\n\tDraftChanges,\n\tDraftField,\n\tDraftFieldMapping,\n\tDraftMapping,\n\tDraftOpening,\n\tDraftView,\n\tMapDraftOptions,\n\tOpenDraftOptions\n} from \"./draft.js\"\n\nexport {\n\taddSheet,\n\tcreateWorkbook,\n\tfreeSheetId,\n\tmoveSheet,\n\topenSheet,\n\treadWorkbook,\n\tremoveSheet,\n\twithSheet,\n\tWORKBOOK_FORMAT,\n\tWORKBOOK_VERSION\n} from \"./workbook.js\"\nexport type { NewSheet, SheetMeta, Workbook, WorkbookSheet } from \"./workbook.js\"\n\nexport { DraftSaver } from \"./saver.js\"\nexport type { DraftSaverOptions, SaverState, SaverStatus } from \"./saver.js\"\n\nexport { SheetSession } from \"./session.js\"\nexport type {\n\tCheckOutcome,\n\tCheckRecord,\n\tPendingRun,\n\tPersistedSession,\n\tPlannedAction,\n\tPlannedChange,\n\tProcessOutcome,\n\tProcessPlan,\n\tRowPlan,\n\tRowResult,\n\tRowResults,\n\tRunRecord,\n\tRunStatus,\n\tSessionFailure,\n\tSessionPhase,\n\tSessionState,\n\tSheetSessionOptions\n} from \"./session.js\"\n\nexport { defineValueSettings, VALUE_SETTINGS } from \"./values/settings.js\"\nexport type { ValueSettings } from \"./values/settings.js\"\nexport { isFieldValue, readInput, valueProblem } from \"./values/read.js\"\nexport type { ReadResult, ValueProblem, ValueProblemCode } from \"./values/read.js\"\nexport { digitsFor, editText, formatCell } from \"./values/format.js\"\nexport type { CellFormatOptions } from \"./values/format.js\"\nexport { CellMarks, MARK_COLORS, readMarks, rowsMarked } from \"./marks.js\"\nexport type { CellMark, CellMarkChange, CellMarksOptions, MarkColor, MarkedCell, MarksData } from \"./marks.js\"\nexport { readStyleRules, rowStyles, rowsStyled, styleApplies, styleRuleToJson } from \"./styles.js\"\nexport type { CellStyle, StyleRule, StyleRuleInput } from \"./styles.js\"\nexport { findCells, REPLACE_ORIGIN, replaceCells } from \"./find.js\"\nexport type { FindOptions, FoundCell, ReplaceOptions, ReplaceResult } from \"./find.js\"\n\nexport {\n\tarrangeColumns,\n\tautoColumnWidth,\n\tclampColumnWidth,\n\tDEFAULT_COLUMN_SIZING,\n\tCOLUMN_ALIGNS,\n\tfreezeColumnLayout,\n\theaderDisplayText,\n\tmapColumnLayout,\n\tMAX_SHOWN_DECIMALS,\n\treadColumnLayout,\n\tresolveColumnSizing,\n\tsameColumnFormats,\n\twithColumn,\n\twithColumnFormat\n} from \"./columns.js\"\nexport type { ArrangedColumns, ColumnAlign, ColumnFormat, ColumnLayout, ColumnSizing } from \"./columns.js\"\n"],"mappings":";AAsBA,IAAa6B,IAAb,cAAiC,MAAM;CACtC,OAAgB;CAChB;CAEA,YAAY,GAAuB,GAAiB;EAEnD,AADA,MAAMC,CAAO,GACb,KAAK,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AS0pB,GAAQ,GAAc,GAAkD;CAChF,IAAMzgC,KAAQ,MAA2B6L,EAAQ,YAAYxL,IAAQA,EAAM,kBAAkBwL,EAAQ,MAAM,GACrGi1B,IAAS9gC,EAAKxB,CAAI;CAExB,QAAO,MAAUqN,EAAQ,QAAQ7L,EAAKklB,CAAK,MAAM4b,IAAS9gC,EAAKklB,CAAK,CAAC,CAAC,SAAS4b,CAAM;AACtF;AAGA,SAASF,GAAS,GAAe,GAAc,GAAqB,GAAqC;CACxG,IAAM5gC,KAAQ,MAA2B6L,EAAQ,YAAYxL,IAAQA,EAAM,kBAAkBwL,EAAQ,MAAM;CAE3G,IAAIA,EAAQ,OACX,OAAO7L,EAAKklB,CAAK,MAAMllB,EAAKxB,CAAI,IAAIqiC,IAAc;CAGnD,IAAME,IAAW/gC,EAAKklB,CAAK,GACrBne,IAAS/G,EAAKxB,CAAI,GACpByC,IAAK8/B,EAAS,QAAQh6B,CAAM;CAEhC,IAAI9F,IAAK,GACR,OAAO;CAIR,IAAI8/B,EAAS,WAAW7b,EAAM,QAC7B,OAAO6b,EAAS,MAAMh6B,CAAM,CAAC,CAAC,KAAK85B,CAAW;CAG/C,IAAI39B,IAAS,IACTkV,IAAO;CAEX,OAAOnX,KAAM,IAGZ,AAFA,KAAUikB,EAAM,MAAM9M,GAAMnX,CAAE,IAAI4/B,GAClC,IAAO5/B,IAAK8F,EAAO,QACnB,IAAKg6B,EAAS,QAAQh6B,GAAQqR,CAAI;CAGnC,OAAOlV,IAASgiB,EAAM,MAAM9M,CAAI;AACjC;;AC7JA,IAAa4oB,KAAU"}
1
+ {"version":3,"file":"index.js","names":["refused","readOptions","NUMERIC","compare","sameValue","isObject","comparable","plain","readRule","isObject","describe","at","plain","compare","HUNDRED","compareValues","compare","NUMERIC","compare","SYMBOLS","NUMERIC","NUMERIC","compare","NUMERIC","compare","EMPTY","plain","plain","describe","TabulaError","message","code","SchemaError","lines","problems","problem","subject","DECIMAL","normalizeDecimal","text","input","match","whole","fraction","body","compareDecimal","negativeA","a","negativeB","b","magnitude","compareMagnitude","wholeA","fractionA","wholeB","fractionB","length","paddedA","paddedB","INVISIBLE_SPACES","PHP_TRIM","phpTrim","clean","fold","escapeRegex","MACHINE_DECIMAL","LARGEST_INTEGER","decimalText","value","isWholeNumberText","isTooLarge","readNumber","raw","negative","isNegative","separators","separatorsOf","settings","cleaned","last","at","lastSeparator","signed","digitsOnly","head","tail","isDecimalSeparator","removeAll","readMoney","symbol","symbolCandidates","currency","quoted","readPercent","symbolFor","formatNumber","rounded","roundDecimal","digits","grouped","editNumber","rawWhole","rawFraction","roundUp","bumped","increment","zero","list","index","other","separator","found","position","result","candidates","usable","candidate","TOKENS","ISO_DATE","ISO_DATE_TIME","ISO_INPUT","EXCEL_EPOCH_OFFSET","MAX_EXCEL_SERIAL","MIN_TEXT_SERIAL","compiled","compilePattern","pattern","source","tokens","char","token","readDate","isZeroDate","parts","fromPattern","fromSerial","otherPattern","fromIso","toIso","withTime","isIsoDate","parseIso","formatDate","two","number","year","month","day","hour","minute","second","valid","compiledPattern","serial","date","days","TRUE_WORDS","FALSE_WORDS","readInput","field","refused$1","numberResult","readBool","readDateValue","readOptions$1","valueProblem","isFieldValue","describeValue","canonicalValue","isOptionValue","item","isLookupValue","record","option","needle","unique","datePatternOf","part","values","params","extra","messageFor","seen","word","words","key","COMPARISONS","CONDITION_OPS","NUMERIC$5","ORDERED","CHECK_PROPERTIES","CONDITION_PROPERTIES","readChecks","add","byKey","fields","ids","checks","path","check","readCheck","first","checkToJson","json","conditionToJson","checkFields","keys","condition","breaksCheck","holds","get","rowsBreaking","schema","store","rowId","conditionHolds","own","left","readable","right","order","compare$2","sameValue$1","isObject$2","failed","fail","name","id","assert","readCondition","when","severity","readMessage","before","op","hasValue","hasOther","otherField","comparable$1","given","language","Listeners","entry","listener","event","#listeners","error","report","scope","MARK_COLORS","CellMarks","#history","options","cells","mark","#put","cleanMark","#version","count","#cells","checkChange","change","#change","next","on","cell","style","keep","rowIds","data","after","old","made","now","sameMark","#apply","entries","rowsMarked","marks","readMarks","rows","plain$4","read","color","RULE_PROPERTIES","readStyleRules","rules","rule","readRule$1","styleRuleToJson","styleApplies","rowStyles","styles","rowsStyled","isObject$1","fill","bold","LEVELS","parseFormula","tokenize","peek","binary","level","unary","operand","postfix","node","primary","callArgs","inner","args","tree","formulaFields","walk","current","TWO_CHARACTER","ONE_CHARACTER","where","start","close","FIELD_TYPES","CUSTOMIZATIONS","MODULE_PROPERTIES","COMMON_PROPERTIES","FORMULA_TYPES","TYPE_PROPERTIES","TYPED_PROPERTIES","NUMERIC_TYPES","RULE_KINDS","ModuleSchema","#byKey","Problems","readModule","isObject","fieldToJson","describe$2","module","readText","schemaVersion","readSchemaVersion","title","customization","readCustomization","readFields","items","firstIndex","readField","checkFormulas","reads","indexOf","fieldsRead","done","reported","circle","member","type","readType","readKey","label","required","readBoolean","editable","submit","example","formula","readRules","at$1","aFieldOf","base","readTone","readPattern","readDecimals","readOptions","fallback","readDefault","why","hint","broken","brokenRule","checkFieldProperties","allowed","optionPath","optionValue","rulePath","readRule","min","limitOf","max","minLength","lengthOf","maxLength","kind","ruleApplies","limit","randomPart","sequence","random","counter","prefix","MAX_DEPTH","toCellValue","convert","refused","depth","prototype","copy","got","sameValue","RowStore","#createRowId","sessionRowIds","#prepare","#rows","row","#order","#revision","#positions","#row","frozenCopy","fn","operations","#derivers","#log","log","derive","#revert","#write","assign","#record","write","writes","inits","blankRows","prepared","doomed","removed","kept","changes","listOf","#standalone","#undo","each","operation","#redo","batch","init","inserted","#restore","#swap","#expectRows","#putBack","from","to","present","total","previous","end","run","requireField","raced","abort","reject","abortError","signal","promise","resolve","wait","ms","neverAborted","LOOKUP_ORIGIN","DEFAULT_BATCH","DEFAULT_CACHE_FOR","LookupResolver","batchSize","#schema","#store","#adapters","#batchSize","#cacheFor","#now","#requestId","#stop","#onChange","#pending","#failure","lookup","#lookupOf","query","cached","#fresh","#searches","requestId","response","readSearchResponse","#enqueue","#flushing","#queue","#scheduled","#disposed","names","cellKey","#schedule","#flush","queue","known","#matches","unknown","#setPending","labels","answer","#learn","readResolveResponse","#setFailure","answers","schemaField","pending","#changed","root","plain$3","readItem","UNDO_ORIGIN","REDO_ORIGIN","DEFAULT_LIMIT","UndoHistory","#limit","#joins","firstChange","step","#trim","recorded","#recorded","#take","#making","TEXT","B0","B1","B2","B10","B1000","ZERO","ONE","parseDecimal","units","simplify","decimalToText","x","y","scale","aligned","subtract","multiply","divide","round","negate","absolute","compare$1","isZero","isInteger","places","drop","rest","mode","power","exponent","times","isFormulaError","formulaErrorValue","EMPTY","numberValue","textValue","boolValue","TRUE","FALSE","errorValue","formulaNumber","decimal","numberArgument","toNumber","HUNDRED$1","toText","toBool","evaluate","context","arithmetic","call","nullError","compareValues$1","emptyLike","rank","FUNCTIONS","branch","arg","builtIn","BUILT_IN","custom","numbers","rounding","logical","all","truth","average","FORMULA_ORIGIN","FormulaEngine","#functions","upperKeys","compile","#affected","affected","#derive","#workOut","changed","#formulasFor","formulas","workOut","applyFormulas","named","functions","fromCell","toCell","placed","place","readers","reached","visit","NAME_START","NAME_PART","formulaCaret","caret","calls","inText","fieldAt","innermost","tokenAt","callOf","formulaWithLabels","mapFields","formulaWithKeys","byLabel","open","map","ADDRESS","formulaFromAddresses","closingQuote","column","addressColumn","columns","formulaParts","plain","upper","letter","DEFAULT_FILTER","RowView","#filters","#ids","filter","#rebuild","filters","shown","added","rowsWithIssues","issues","rowsWithResult","outcome","results","outcomes","NUMERIC$4","AVERAGE_PLACES","summarizeCells","filled","sum","formatCell","digitsFor","editText","SYMBOLS$1","VALUE_SETTINGS","defineValueSettings","refuse","NUMERIC$3","DATES","hasRange","filterKey","normal","filterKeys","eachValue","rowsMatching","tests","inRange","test","rowsContaining","locale","written","point","comparable","compare","compareNumbers","compareTexts","sortText","compareValues","rankA","rankB","rowOrder","sort","sign","rankLeft","rankRight","distinctValues","NUMERIC$2","DAY_MS","DAY_SECONDS","TRAILING_NUMBER","ISO_PARTS","fillValues","backward","series","seriesOf","distance","numberSeries","dateSeries","textSeries","decimals","stepOf","matches","width","d","dates","partsOf","months","monthSeries","points","secondOf","dayOf","isoOf","fromSecond","fromDay","sameDay","inMonth","daysIn","counts","single","texts","iso","moment","NUMERIC$1","HUNDRED","isAdjustable","adjustValue","operandOf","adjustment","SheetChanges","#settings","#fields","#key","#takeBaseline","#added","missing","#baseline","#holding","#changedNow","#keys","#compared","#keyOf","#follow","touched","#forget","was","EMPTY$1","rowsChanged","DEFAULT_COLUMN_SIZING","resolveColumnSizing","layers","sizing","headerDisplayText","characters","autoColumnWidth","clamp","contentWidth","clampColumnWidth","COLUMN_ALIGNS","MAX_SHOWN_DECIMALS","arrangeColumns","hidden","layout","pinned","ordered","withColumn","toggle","withColumnFormat","formats","alignOf","decimalsOf","freezeColumnLayout","mergeColumnFormats","merged","layer","format","withoutColumnFormats","under","readColumnLayout","plainObject","isShownDecimals","mapColumnLayout","sameColumnFormats","VIEWS_FORMAT","VIEWS_VERSION","VIEW_NAME_LIMIT","PLAIN_VIEW","emptyViews","freezeViews","viewFor","state","freezeState","sameView","arranged","sameRecord","sameCondition","viewNameProblem","trimmed","collator","except","views","view","addView","saved","checkedName","updateView","pickState","renameView","checked","removeView","setDefaultView","readViews","plain$2","readView","defaultId","line","collators","update","same","readViewState","readLayout","readWidths","readFilters","readSort","columnWidths","widths","bound","side","TEMPLATE_FORMAT","TEMPLATE_VERSION","CHANGES","NUMERIC","readTemplate","plain$1","fieldsRoot","describeProblems","templateProblems","merge","template","applyTemplate","applied","withDefaults","defaults","ownChecks","ownStyles","narrowed","heading","STEPS","Selection","#rowCount","requireCount","rowCount","#colCount","colCount","#isEmpty","#active","#pivot","#head","rangeOf","range","within","col","target","#clamp","#commit","cols","edgeOf","direction","isBlank","active","pivot","#clampCell","settled","inside","blank","advance","parseTsv","cellStart","quoteAt","literalAt","toTsv","quoteCell","DELIMITERS","parseCsv","delimiter","detectDelimiter","started","endCell","endRow","best","toCsv","special","decodeText","bytes","FORMULA_START","NUMBER_TYPES","exportTable","cellText","csvDelimiterFor","SAMPLES","importTable","header","table","taken","matched","fieldNamed","unreadable","samplesOf","PROBE","READABLE","suggestColumns","choose","free","headerKey","wordsOf","scored","overlap","top","readsAs","TURKISH","shared","KEY_TYPES","suggestMatch","indexes","bestShare","share","textKey","matchRows","valueKey","canonical","IMPORT_ORIGIN","applyImport","imported","adding","skipped","targets","MAX_TARGETS","isBlankRow","SheetValidator","hasRule","#groups","#checksOf","#checkAll","#unsubscribe","#broken","issue","#uniqueIssue","errors","warnings","groups","group","#blank","#checkRow","#isBlank","#checkCell","#checkChecks","#sorted","checkIssue","checkValue","#regroup","uniqueKey","cacheKey","sorted","others","describe$1","cellIssue","sent","checkRule","comparison","normalize","SYMBOLS","ENGLISH_COMPARISONS","english","trimmedWhole","trimmedFraction","SCOPES","SEVERITIES","STATUSES","OUTCOMES","ACTIONS","readCheckResponse","reader","Reader","optional","readProcessResponse","status","#problems","describe","optionalValue","blocking","param","plan","action","DRAFT_FORMAT","DRAFT_VERSION","createDraft","session","freezeMarks","openDraft","draft","rename","renames","mapDraft","losing","dropped","suggestRenames","fresh","pairs","score","likeness","pair","keyWords","retyped","renamed","gone","readDraft","sheetId","savedAt","revision","readRow","sessionRoot","readResult","readPending","request","WORKBOOK_FORMAT","WORKBOOK_VERSION","createWorkbook","sheet","sheetOf","freeSheetId","freeze","readWorkbook","listed","sheets","readMeta","addSheet","workbook","withSheet","patch","removeSheet","moveSheet","openSheet","meta","DEFAULT_DELAY","DraftSaver","delay","#options","#delay","#name","#stops","#onSession","#state","#changes","#saved","#setState","#clearTimer","#running","#run","stop","#timer","DEFAULT_POLL_INTERVAL","SheetSession","pollInterval","#ownValidator","#pollInterval","#merged","MergedIssues","#results","Results","ask","#checking","controller","#request","#answered","failure","#toIssue","checkRecord","plans","#checked","send","blocked","#blockedRows","sending","#lose","#payload","#rowPlan","#query","checking","#setRun","stage","answered","final","server","blockedByServer","lookupPayload","scopeOf","#changedSince","#rowChanged","#cellChanged","touches","#local","local","#server","remote","#indexed","stale","#index","updated","push","#inFlight","invalid","REPLACE_ORIGIN","findCells","matcher","replaceCells","replaced","replacement","wanted","haystack","version"],"sources":["../src/errors.ts","../src/decimal.ts","../src/values/text.ts","../src/values/number.ts","../src/values/date.ts","../src/values/read.ts","../src/checks.ts","../src/listeners.ts","../src/marks.ts","../src/styles.ts","../src/formula/parse.ts","../src/schema.ts","../src/ids.ts","../src/value.ts","../src/rows.ts","../src/async.ts","../src/lookup.ts","../src/history.ts","../src/formula/decimal.ts","../src/formula/error.ts","../src/formula/evaluate.ts","../src/formula/engine.ts","../src/formula/assist.ts","../src/view.ts","../src/summary.ts","../src/values/format.ts","../src/values/settings.ts","../src/filters.ts","../src/fill.ts","../src/adjust.ts","../src/changes.ts","../src/columns.ts","../src/views.ts","../src/templates.ts","../src/selection.ts","../src/clipboard.ts","../src/csv.ts","../src/table.ts","../src/validation.ts","../src/contract.ts","../src/draft.ts","../src/workbook.ts","../src/saver.ts","../src/session.ts","../src/find.ts","../src/index.ts"],"sourcesContent":["/** What went wrong, in a form code can branch on. */\nexport type TabulaErrorCode =\n\t| \"invalid_schema\"\n\t| \"unknown_field\"\n\t| \"unknown_row\"\n\t| \"duplicate_row\"\n\t| \"invalid_argument\"\n\t| \"invalid_value\"\n\t| \"conflict\"\n\t| \"invalid_response\"\n\t| \"invalid_draft\"\n\t| \"invalid_workbook\"\n\t| \"invalid_views\"\n\t| \"invalid_template\"\n\t| \"invalid_formula\"\n\n/**\n * The one error class this package throws.\n *\n * The message is English and written for the developer reading the console. Code that reacts to an\n * error looks at `code`, which is never renamed; a message may be reworded in any release.\n */\nexport class TabulaError extends Error {\n\toverride name = \"TabulaError\"\n\treadonly code: TabulaErrorCode\n\n\tconstructor(code: TabulaErrorCode, message: string) {\n\t\tsuper(message)\n\t\tthis.code = code\n\t}\n}\n\nexport interface SchemaProblem {\n\t/** Where in the schema, such as `fields[2].rules[0].value`. `(root)` is the schema itself. */\n\treadonly path: string\n\treadonly message: string\n}\n\n/**\n * A module schema that cannot be used, with every problem in it.\n *\n * All of them, not the first: a developer fixing a schema one complaint per reload is a developer\n * reloading a dozen times.\n */\nexport class SchemaError extends TabulaError {\n\toverride name = \"SchemaError\"\n\treadonly problems: readonly SchemaProblem[]\n\n\tconstructor(subject: string, problems: readonly SchemaProblem[]) {\n\t\tconst lines = problems.map(problem => ` ${problem.path}: ${problem.message}`)\n\t\tsuper(\"invalid_schema\", `${subject} is not valid:\\n${lines.join(\"\\n\")}`)\n\t\tthis.problems = Object.freeze([...problems])\n\t}\n}\n","/**\n * Decimal numbers written as text, compared without ever becoming a float.\n *\n * A limit such as a minimum price arrives from the backend as text (\"0.30\") so that it means what it\n * says. As floats, 0.1 + 0.2 is not 0.3, and a rule saying \"at least 0.30\" would refuse a sum that\n * meets it.\n */\n\nconst DECIMAL = /^([+-]?)(\\d+)(?:\\.(\\d+))?$/\n\n/**\n * One way of writing each number: no sign on zero, no leading zeros, no trailing zeros after the\n * point, no point with nothing after it. `\"-0012.3400\"` becomes `\"-12.34\"`.\n *\n * Null for anything else, exponents (`1e21`), thousands separators and a decimal comma included.\n * Those belong to what a user types, and are read elsewhere with the sheet's own number settings.\n */\nexport function normalizeDecimal(input: string | number): string | null {\n\tlet text: string\n\n\tif (typeof input === \"number\") {\n\t\tif (!Number.isFinite(input)) {\n\t\t\treturn null\n\t\t}\n\n\t\ttext = String(input)\n\t} else {\n\t\ttext = input.trim()\n\t}\n\n\tconst match = DECIMAL.exec(text)\n\n\tif (!match) {\n\t\treturn null\n\t}\n\n\tconst whole = (match[2] ?? \"0\").replace(/^0+(?=\\d)/, \"\")\n\tconst fraction = (match[3] ?? \"\").replace(/0+$/, \"\")\n\tconst body = fraction === \"\" ? whole : `${whole}.${fraction}`\n\n\tif (body === \"0\") {\n\t\treturn \"0\"\n\t}\n\n\treturn match[1] === \"-\" ? `-${body}` : body\n}\n\n/** -1, 0 or 1 as `a` is below, equal to or above `b`. Both must be as `normalizeDecimal()` writes them. */\nexport function compareDecimal(a: string, b: string): -1 | 0 | 1 {\n\tconst negativeA = a.startsWith(\"-\")\n\tconst negativeB = b.startsWith(\"-\")\n\n\tif (negativeA !== negativeB) {\n\t\treturn negativeA ? -1 : 1\n\t}\n\n\tconst magnitude = compareMagnitude(negativeA ? a.slice(1) : a, negativeB ? b.slice(1) : b)\n\n\t// 0 - magnitude, not -magnitude: the latter turns an equal pair into -0.\n\treturn negativeA ? ((0 - magnitude) as -1 | 0 | 1) : magnitude\n}\n\nfunction compareMagnitude(a: string, b: string): -1 | 0 | 1 {\n\tconst [wholeA = \"\", fractionA = \"\"] = a.split(\".\")\n\tconst [wholeB = \"\", fractionB = \"\"] = b.split(\".\")\n\n\t// No leading zeros, so the longer whole part is the larger number.\n\tif (wholeA.length !== wholeB.length) {\n\t\treturn wholeA.length < wholeB.length ? -1 : 1\n\t}\n\n\tif (wholeA !== wholeB) {\n\t\treturn wholeA < wholeB ? -1 : 1\n\t}\n\n\tconst length = Math.max(fractionA.length, fractionB.length)\n\tconst paddedA = fractionA.padEnd(length, \"0\")\n\tconst paddedB = fractionB.padEnd(length, \"0\")\n\n\tif (paddedA === paddedB) {\n\t\treturn 0\n\t}\n\n\treturn paddedA < paddedB ? -1 : 1\n}\n","/**\n * The text rules every reader shares, written as nouxwell/tabula's `StringParser` writes them, so\n * the two sides call the same cell empty and compare the same two words as equal.\n */\n\nconst INVISIBLE_SPACES = /[\\u00A0\\u202F\\u2009\\uFEFF]/g\n\n// PHP's trim(): space, tab, line breaks, NUL and vertical tab. JavaScript's own trim() also takes\n// every other Unicode space, and the two sides would then disagree on what a cell holds.\n// eslint-disable-next-line no-control-regex\nconst PHP_TRIM = /^[ \\t\\n\\r\\0\\x0B]+|[ \\t\\n\\r\\0\\x0B]+$/g\n\nexport function phpTrim(text: string): string {\n\treturn text.replace(PHP_TRIM, \"\")\n}\n\n/** Invisible spaces become ordinary ones, then the ends are trimmed: what a cell really holds. */\nexport function clean(text: string): string {\n\treturn phpTrim(text.replace(INVISIBLE_SPACES, \" \"))\n}\n\n/**\n * The form two words are compared in: cleaned and lower-cased.\n *\n * Lower-cased without a locale, as `mb_strtolower()` does. That keeps the comparison the same on\n * every machine, and it also means \"AÇIK\" does not meet \"açık\": the I's lower case is \"i\", not \"ı\".\n */\nexport function fold(text: string): string {\n\treturn clean(text).toLowerCase()\n}\n\nexport function escapeRegex(text: string): string {\n\treturn text.replace(/[.*+?^${}()|[\\]\\\\/-]/g, \"\\\\$&\")\n}\n","import { compareDecimal, normalizeDecimal } from \"../decimal.js\"\nimport type { ValueSettings } from \"./settings.js\"\nimport { clean, escapeRegex, phpTrim } from \"./text.js\"\n\n/**\n * Numbers as a cell holds them: decimal text such as \"1234.56\", never a float, so a price is\n * exactly what was typed. Reading follows nouxwell/tabula's `NumberFormatter::parse()` rule for rule.\n * Where PHP turns the text into a float, this keeps the digits: same value, no rounding.\n */\n\n/** How a number is written by machines: an optional minus, digits, and a point with digits after it. */\nconst MACHINE_DECIMAL = /^-?\\d+(?:\\.\\d+)?$/\n\n/** The largest whole number PHP keeps as an integer, PHP_INT_MAX. */\nconst LARGEST_INTEGER = \"9223372036854775807\"\n\n/** A number value as decimal text, or null when it is not one. Strings must be in machine form. */\nexport function decimalText(value: unknown): string | null {\n\tif (typeof value === \"string\") {\n\t\treturn MACHINE_DECIMAL.test(value) ? value : null\n\t}\n\n\tif (typeof value !== \"number\" || !Number.isFinite(value)) {\n\t\treturn null\n\t}\n\n\tconst text = String(value)\n\n\t// String() writes 1e21 and 1e-7 with an exponent; spelled out, they are decimal text again.\n\treturn /e/i.test(text) ? value.toLocaleString(\"en-US\", { useGrouping: false, maximumFractionDigits: 20 }) : text\n}\n\nexport function isWholeNumberText(text: string): boolean {\n\treturn /^-?\\d+$/.test(text)\n}\n\n/** Whether a whole number is past what PHP can hold as an integer. */\nexport function isTooLarge(text: string): boolean {\n\treturn compareDecimal(text.replace(/^-/, \"\"), LARGEST_INTEGER) > 0\n}\n\n/**\n * Reads a number as a person wrote it, with the sheet's separators.\n *\n * \"1.234,56\", \"1,234.56\", \"1.234 ₺\", \"(1.234,56)\" and \"1.234,56-\" are all understood, and a lone\n * thousands separator followed by three digits is grouping: \"1.234\" is 1234 with Turkish settings.\n * Letters and symbols around the number are dropped, as on the PHP side: \"12 adet\" is 12.\n */\nexport function readNumber(raw: string, settings: ValueSettings): string | null {\n\tconst text = phpTrim(raw)\n\n\tif (text === \"\") {\n\t\treturn null\n\t}\n\n\tconst negative = isNegative(text)\n\tconst separators = separatorsOf(settings)\n\tconst spaced = text.replace(/[\\u00A0\\u202F\\u2009]/g, \" \")\n\tconst cleaned = spaced.replace(new RegExp(`[^0-9${escapeRegex(separators.join(\"\"))}]`, \"gu\"), \"\")\n\n\tif (cleaned === \"\") {\n\t\treturn null\n\t}\n\n\tconst [last, at] = lastSeparator(cleaned, separators)\n\n\tif (last === null) {\n\t\treturn signed(digitsOnly(cleaned), negative)\n\t}\n\n\tconst head = cleaned.slice(0, at)\n\tconst tail = cleaned.slice(at + last.length)\n\n\tif (!isDecimalSeparator(last, head, tail, separators, settings)) {\n\t\treturn signed(digitsOnly(removeAll(cleaned, separators)), negative)\n\t}\n\n\tconst whole = removeAll(head, separators) || \"0\"\n\n\tif (!/^\\d+$/.test(whole) || !/^\\d+$/.test(tail)) {\n\t\treturn null\n\t}\n\n\treturn signed(normalizeDecimal(`${whole}.${tail}`), negative)\n}\n\n/**\n * Reads an amount: the currency symbols and codes the settings know, and the field's own, are taken\n * off either end first. Taken off rather than left to the number reader, because a symbol holding a\n * point, such as \"S/.\", would leave a point behind and multiply the amount by a hundred.\n */\nexport function readMoney(raw: string, currency: string | null, settings: ValueSettings): string | null {\n\tlet text = clean(raw)\n\n\tfor (const symbol of symbolCandidates(currency, settings)) {\n\t\tconst quoted = escapeRegex(symbol)\n\n\t\ttext = text.replace(new RegExp(`^\\\\s*${quoted}\\\\s*|\\\\s*${quoted}\\\\s*$`, \"giu\"), \"\")\n\t}\n\n\treturn readNumber(phpTrim(text), settings)\n}\n\n/** Reads a percentage written with or without its sign, before or after: \"%15\", \"15 %\", \"15\". */\nexport function readPercent(raw: string, settings: ValueSettings): string | null {\n\treturn readNumber(clean(raw).replace(/^%\\s*|\\s*%$/g, \"\"), settings)\n}\n\n/** The symbol a currency is shown with, or null when symbols are not shown. */\nexport function symbolFor(currency: string | null, settings: ValueSettings): string | null {\n\tif (currency === null || settings.symbolPosition === \"none\") {\n\t\treturn null\n\t}\n\n\treturn settings.currencySymbols[currency] ?? currency\n}\n\n/**\n * Decimal text rounded to `digits` places and written the sheet's way: \"1234.565\" with Turkish\n * settings and two digits is \"1.234,57\". Rounded half away from zero, on the digits themselves.\n */\nexport function formatNumber(value: string, digits: number, settings: ValueSettings): string {\n\tconst rounded = roundDecimal(value, digits)\n\tconst negative = rounded.startsWith(\"-\")\n\tconst [whole = \"0\", fraction] = (negative ? rounded.slice(1) : rounded).split(\".\")\n\tconst grouped = whole.replace(/\\B(?=(\\d{3})+(?!\\d))/g, settings.thousandSeparator)\n\n\treturn `${negative ? \"-\" : \"\"}${grouped}${fraction === undefined ? \"\" : settings.decimalSeparator + fraction}`\n}\n\n/** Decimal text as a person edits it: every digit kept, the sheet's decimal separator, no grouping. */\nexport function editNumber(value: string, settings: ValueSettings): string {\n\treturn value.replace(\".\", settings.decimalSeparator)\n}\n\n/** Rounds decimal text to exactly `digits` places, half away from zero. \"-0.001\" to two places is \"0.00\". */\nexport function roundDecimal(value: string, digits: number): string {\n\tconst negative = value.startsWith(\"-\")\n\tconst [rawWhole = \"0\", rawFraction = \"\"] = (negative ? value.slice(1) : value).split(\".\")\n\tlet whole = rawWhole.replace(/^0+(?=\\d)/, \"\")\n\tlet fraction = rawFraction\n\n\tif (fraction.length <= digits) {\n\t\tfraction = fraction.padEnd(digits, \"0\")\n\t} else {\n\t\tconst roundUp = (fraction.charAt(digits) || \"0\") >= \"5\"\n\n\t\tfraction = fraction.slice(0, digits)\n\n\t\tif (roundUp) {\n\t\t\tconst bumped = increment(whole + fraction)\n\n\t\t\twhole = bumped.slice(0, bumped.length - digits) || \"0\"\n\t\t\tfraction = bumped.slice(bumped.length - digits)\n\t\t}\n\t}\n\n\tconst zero = /^0*$/.test(whole + fraction)\n\n\treturn `${negative && !zero ? \"-\" : \"\"}${whole}${digits > 0 ? `.${fraction}` : \"\"}`\n}\n\nfunction increment(digits: string): string {\n\tconst list = digits.split(\"\")\n\n\tfor (let index = list.length - 1; index >= 0; index--) {\n\t\tif (list[index] === \"9\") {\n\t\t\tlist[index] = \"0\"\n\t\t} else {\n\t\t\tlist[index] = String(Number(list[index]) + 1)\n\n\t\t\treturn list.join(\"\")\n\t\t}\n\t}\n\n\treturn `1${list.join(\"\")}`\n}\n\n/**\n * The negative notations: a leading or trailing minus, accounting parentheses, and a minus right\n * before the digits after a symbol (\"₺ -1.234,56\"). Looked for before the cleanup, which loses them.\n */\nfunction isNegative(text: string): boolean {\n\tif (text.includes(\"(\") && text.includes(\")\")) {\n\t\treturn true\n\t}\n\n\tif (text.startsWith(\"-\") || text.endsWith(\"-\")) {\n\t\treturn true\n\t}\n\n\treturn /^\\D*-\\s*\\d/u.test(text)\n}\n\n/**\n * Whether the right-most separator is the decimal point, in the order nouxwell/tabula decides it:\n * another kind of separator before it; the same one twice; the configured decimal separator; the\n * configured thousands separator with exactly three digits after it; anything else is decimal.\n */\nfunction isDecimalSeparator(\n\tseparator: string,\n\thead: string,\n\ttail: string,\n\tseparators: readonly string[],\n\tsettings: ValueSettings\n): boolean {\n\tif (tail === \"\" || !/^\\d+$/.test(tail)) {\n\t\treturn false\n\t}\n\n\tif (separators.some(other => other !== separator && head.includes(other))) {\n\t\treturn true\n\t}\n\n\tif (head.includes(separator)) {\n\t\treturn false\n\t}\n\n\tif (separator === settings.decimalSeparator) {\n\t\treturn true\n\t}\n\n\tif (separator === settings.thousandSeparator) {\n\t\treturn tail.length !== 3\n\t}\n\n\treturn true\n}\n\n/** The configured separators, then the universal point and comma: \"1,234.56\" is read with Turkish settings too. */\nfunction separatorsOf(settings: ValueSettings): string[] {\n\treturn [...new Set([settings.decimalSeparator, settings.thousandSeparator, \".\", \",\"].filter(Boolean))]\n}\n\nfunction lastSeparator(text: string, separators: readonly string[]): [string | null, number] {\n\tlet found: string | null = null\n\tlet at = -1\n\n\tfor (const separator of separators) {\n\t\tconst position = text.lastIndexOf(separator)\n\n\t\tif (position > at) {\n\t\t\tfound = separator\n\t\t\tat = position\n\t\t}\n\t}\n\n\treturn [found, at]\n}\n\nfunction removeAll(text: string, separators: readonly string[]): string {\n\treturn separators.reduce((result, separator) => result.split(separator).join(\"\"), text)\n}\n\nfunction digitsOnly(text: string): string | null {\n\treturn /^\\d+$/.test(text) ? normalizeDecimal(text) : null\n}\n\nfunction signed(text: string | null, negative: boolean): string | null {\n\treturn text === null || !negative || text === \"0\" ? text : `-${text}`\n}\n\n/**\n * Every symbol and code that could stand around an amount, longest first, so \"US$\" goes before \"$\"\n * and leaves no \"US\" behind. One that could be part of a number, such as a separator, is never one.\n */\nfunction symbolCandidates(currency: string | null, settings: ValueSettings): string[] {\n\tconst candidates = [...Object.values(settings.currencySymbols), ...Object.keys(settings.currencySymbols)]\n\n\tif (currency !== null) {\n\t\tcandidates.push(currency)\n\n\t\tconst symbol = symbolFor(currency, settings)\n\n\t\tif (symbol !== null) {\n\t\t\tcandidates.push(symbol)\n\t\t}\n\t}\n\n\tconst separators = [settings.decimalSeparator, settings.thousandSeparator]\n\tconst usable = candidates\n\t\t.map(candidate => phpTrim(candidate))\n\t\t.filter(candidate => candidate !== \"\" && !separators.includes(candidate) && !/^[0-9.,\\s]+$/u.test(candidate))\n\n\treturn [...new Set(usable)].sort((a, b) => Array.from(b).length - Array.from(a).length)\n}\n","import { clean, escapeRegex } from \"./text.js\"\n\n/**\n * Dates as a cell holds them: ISO text, \"2026-12-31\" for a date and \"2026-12-31T09:30:00\" for a\n * date and time, with no time zone. What the user typed is what is kept, as on the PHP side: a cell\n * reading 09:00 is never moved to 06:00 by an offset.\n */\n\ninterface Parts {\n\tyear: number\n\tmonth: number\n\tday: number\n\thour: number\n\tminute: number\n\tsecond: number\n}\n\ntype Token = \"day\" | \"month\" | \"year\" | \"shortYear\" | \"hour\" | \"minute\" | \"second\"\n\ninterface CompiledPattern {\n\treadonly regex: RegExp\n\treadonly tokens: readonly Token[]\n}\n\nconst TOKENS: Readonly<Record<string, readonly [Token, string]>> = {\n\td: [\"day\", \"(\\\\d{1,2})\"],\n\tj: [\"day\", \"(\\\\d{1,2})\"],\n\tm: [\"month\", \"(\\\\d{1,2})\"],\n\tn: [\"month\", \"(\\\\d{1,2})\"],\n\tY: [\"year\", \"(\\\\d{4})\"],\n\ty: [\"shortYear\", \"(\\\\d{2})\"],\n\tH: [\"hour\", \"(\\\\d{1,2})\"],\n\tG: [\"hour\", \"(\\\\d{1,2})\"],\n\ti: [\"minute\", \"(\\\\d{2})\"],\n\ts: [\"second\", \"(\\\\d{2})\"]\n}\n\nconst ISO_DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/\nconst ISO_DATE_TIME = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})$/\nconst ISO_INPUT = /^(\\d{4})-(\\d{1,2})-(\\d{1,2})(?:[T ](\\d{1,2}):(\\d{2})(?::(\\d{2}))?)?$/\n\n/** Where the Unix epoch sits in Excel's day count, and the last day Excel still reads as a date. */\nconst EXCEL_EPOCH_OFFSET = 25569\nconst MAX_EXCEL_SERIAL = 2958465\n/** A digits-only text below this is a year or a code, not a serial number: \"2024\" is not 1905-07-16. */\nconst MIN_TEXT_SERIAL = 10000\n\nconst compiled = new Map<string, CompiledPattern | null>()\n\n/**\n * A pattern in PHP's notation as a regular expression, or null when it uses a letter this reader\n * does not know. Every other character must match itself, a space matches any run of spaces, and a\n * backslash makes the next letter literal.\n */\nexport function compilePattern(pattern: string): CompiledPattern | null {\n\tif (compiled.has(pattern)) {\n\t\treturn compiled.get(pattern) ?? null\n\t}\n\n\tlet source = \"\"\n\tconst tokens: Token[] = []\n\tlet result: CompiledPattern | null = null\n\tlet index = 0\n\n\tfor (; index < pattern.length; index++) {\n\t\tconst char = pattern.charAt(index)\n\t\tconst token = TOKENS[char]\n\n\t\tif (token) {\n\t\t\ttokens.push(token[0])\n\t\t\tsource += token[1]\n\t\t} else if (char === \"\\\\\") {\n\t\t\tindex++\n\t\t\tsource += escapeRegex(pattern.charAt(index))\n\t\t} else if (char === \"!\" || char === \"|\") {\n\t\t\t// PHP's markers for \"reset what the pattern leaves out\", which is what happens here anyway.\n\t\t} else if (char === \" \") {\n\t\t\tsource += \"[ \\\\t\\\\u00A0\\\\u202F]*\"\n\t\t} else if (/[A-Za-z]/.test(char)) {\n\t\t\tbreak\n\t\t} else {\n\t\t\tsource += escapeRegex(char)\n\t\t}\n\t}\n\n\tif (index >= pattern.length) {\n\t\tresult = Object.freeze({ regex: new RegExp(`^${source}$`), tokens: Object.freeze(tokens) })\n\t}\n\n\tcompiled.set(pattern, result)\n\n\treturn result\n}\n\n/**\n * Reads a date as a person wrote it. In order: the pattern; a digits-only Excel serial number; the\n * other pattern (the date and time pattern for a date, and the other way round); ISO. A date that\n * does not exist, such as 31.02.2026, is refused rather than rolled into March.\n *\n * @returns ISO text, with the time for a date-time field and without it for a date field\n */\nexport function readDate(raw: string, withTime: boolean, pattern: string, otherPattern: string): string | null {\n\tconst text = clean(raw)\n\n\tif (text === \"\" || isZeroDate(text)) {\n\t\treturn null\n\t}\n\n\tconst parts =\n\t\tfromPattern(text, pattern) ??\n\t\t(/^\\d+$/.test(text) ? fromSerial(Number(text)) : null) ??\n\t\tfromPattern(text, otherPattern) ??\n\t\tfromIso(text)\n\n\treturn parts === null ? null : toIso(parts, withTime)\n}\n\n/** Whether a value is a date, or a date and time, in the ISO form a cell holds. */\nexport function isIsoDate(value: unknown, withTime: boolean): value is string {\n\treturn typeof value === \"string\" && parseIso(value, withTime) !== null\n}\n\n/** An ISO date written with a pattern, or null when it is not one. */\nexport function formatDate(value: string, withTime: boolean, pattern: string): string | null {\n\tconst parts = parseIso(value, withTime)\n\n\tif (parts === null) {\n\t\treturn null\n\t}\n\n\tconst two = (number: number): string => String(number).padStart(2, \"0\")\n\tlet text = \"\"\n\n\tfor (let index = 0; index < pattern.length; index++) {\n\t\tconst char = pattern.charAt(index)\n\n\t\tswitch (char) {\n\t\t\tcase \"d\":\n\t\t\t\ttext += two(parts.day)\n\t\t\t\tbreak\n\t\t\tcase \"j\":\n\t\t\t\ttext += String(parts.day)\n\t\t\t\tbreak\n\t\t\tcase \"m\":\n\t\t\t\ttext += two(parts.month)\n\t\t\t\tbreak\n\t\t\tcase \"n\":\n\t\t\t\ttext += String(parts.month)\n\t\t\t\tbreak\n\t\t\tcase \"Y\":\n\t\t\t\ttext += String(parts.year).padStart(4, \"0\")\n\t\t\t\tbreak\n\t\t\tcase \"y\":\n\t\t\t\ttext += two(parts.year % 100)\n\t\t\t\tbreak\n\t\t\tcase \"H\":\n\t\t\t\ttext += two(parts.hour)\n\t\t\t\tbreak\n\t\t\tcase \"G\":\n\t\t\t\ttext += String(parts.hour)\n\t\t\t\tbreak\n\t\t\tcase \"i\":\n\t\t\t\ttext += two(parts.minute)\n\t\t\t\tbreak\n\t\t\tcase \"s\":\n\t\t\t\ttext += two(parts.second)\n\t\t\t\tbreak\n\t\t\tcase \"\\\\\":\n\t\t\t\tindex++\n\t\t\t\ttext += pattern.charAt(index)\n\t\t\t\tbreak\n\t\t\tcase \"!\":\n\t\t\tcase \"|\":\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\ttext += char\n\t\t}\n\t}\n\n\treturn text\n}\n\nfunction parseIso(value: string, withTime: boolean): Parts | null {\n\tconst match = (withTime ? ISO_DATE_TIME : ISO_DATE).exec(value)\n\n\tif (!match) {\n\t\treturn null\n\t}\n\n\tconst [, year, month, day, hour = \"0\", minute = \"0\", second = \"0\"] = match\n\n\treturn valid({\n\t\tyear: Number(year),\n\t\tmonth: Number(month),\n\t\tday: Number(day),\n\t\thour: Number(hour),\n\t\tminute: Number(minute),\n\t\tsecond: Number(second)\n\t})\n}\n\nfunction fromPattern(text: string, pattern: string): Parts | null {\n\tconst compiledPattern = compilePattern(pattern)\n\tconst match = compiledPattern?.regex.exec(text)\n\n\tif (!compiledPattern || !match) {\n\t\treturn null\n\t}\n\n\t// What the pattern leaves out starts from the epoch, as PHP's \"!\" does: a pattern without a day\n\t// reads the first, never today.\n\tconst parts: Parts = { year: 1970, month: 1, day: 1, hour: 0, minute: 0, second: 0 }\n\n\tcompiledPattern.tokens.forEach((token, index) => {\n\t\tconst number = Number(match[index + 1])\n\n\t\tswitch (token) {\n\t\t\tcase \"shortYear\":\n\t\t\t\t// As PHP reads \"y\": 70 to 99 are the 1900s, 00 to 69 the 2000s.\n\t\t\t\tparts.year = number < 70 ? 2000 + number : 1900 + number\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tparts[token] = number\n\t\t}\n\t})\n\n\treturn valid(parts)\n}\n\nfunction fromSerial(serial: number): Parts | null {\n\tif (!Number.isFinite(serial) || serial < MIN_TEXT_SERIAL || serial > MAX_EXCEL_SERIAL) {\n\t\treturn null\n\t}\n\n\tconst date = new Date(Math.round((serial - EXCEL_EPOCH_OFFSET) * 86400) * 1000)\n\n\treturn {\n\t\tyear: date.getUTCFullYear(),\n\t\tmonth: date.getUTCMonth() + 1,\n\t\tday: date.getUTCDate(),\n\t\thour: date.getUTCHours(),\n\t\tminute: date.getUTCMinutes(),\n\t\tsecond: date.getUTCSeconds()\n\t}\n}\n\nfunction fromIso(text: string): Parts | null {\n\tconst match = ISO_INPUT.exec(text)\n\n\tif (!match) {\n\t\treturn null\n\t}\n\n\tconst [, year, month, day, hour = \"0\", minute = \"0\", second = \"0\"] = match\n\n\treturn valid({\n\t\tyear: Number(year),\n\t\tmonth: Number(month),\n\t\tday: Number(day),\n\t\thour: Number(hour),\n\t\tminute: Number(minute),\n\t\tsecond: Number(second)\n\t})\n}\n\n/** The parts when they make a real moment, or null: no 31 February, no 24:00. */\nfunction valid(parts: Parts): Parts | null {\n\tconst days = new Date(Date.UTC(parts.year, parts.month, 0)).getUTCDate()\n\n\tif (\n\t\tparts.year < 1 ||\n\t\tparts.month < 1 ||\n\t\tparts.month > 12 ||\n\t\tparts.day < 1 ||\n\t\tparts.day > days ||\n\t\tparts.hour > 23 ||\n\t\tparts.minute > 59 ||\n\t\tparts.second > 59\n\t) {\n\t\treturn null\n\t}\n\n\treturn parts\n}\n\nfunction toIso(parts: Parts, withTime: boolean): string {\n\tconst two = (number: number): string => String(number).padStart(2, \"0\")\n\tconst date = `${String(parts.year).padStart(4, \"0\")}-${two(parts.month)}-${two(parts.day)}`\n\n\treturn withTime ? `${date}T${two(parts.hour)}:${two(parts.minute)}:${two(parts.second)}` : date\n}\n\n/** MySQL's zero date, the broken output of another system rather than a date. */\nfunction isZeroDate(text: string): boolean {\n\tconst digits = text.replace(/\\D/g, \"\")\n\n\treturn digits.length >= 8 && /^0+$/.test(digits)\n}\n","import type { FieldSchema, OptionsField } from \"../schema.js\"\nimport type { CellValue } from \"../value.js\"\nimport { isIsoDate, readDate } from \"./date.js\"\nimport { decimalText, isTooLarge, isWholeNumberText, readMoney, readNumber, readPercent } from \"./number.js\"\nimport type { ValueSettings } from \"./settings.js\"\nimport { clean, fold } from \"./text.js\"\n\n/**\n * Reading what a person typed or pasted into a cell, and telling whether what a cell holds is a\n * value of its field's type.\n *\n * Text that cannot be read is not thrown away. The cell keeps it as typed, so the user can see it\n * and fix it, and the problem says what was expected. The codes and their params are nouxwell/tabula's\n * `RowErrorCode`: an application that words the import's errors already words these.\n */\n\n/**\n * `not_matched` is this package's own, for a lookup holding text no record was matched to; the rest\n * are nouxwell/tabula's.\n */\nexport type ValueProblemCode =\n\t\"not_a_number\" | \"not_an_integer\" | \"not_a_date\" | \"not_a_boolean\" | \"not_an_option\" | \"not_matched\"\n\nexport interface ValueProblem {\n\treadonly code: ValueProblemCode\n\t/** English, as nouxwell/tabula words it. An application in another language words it from code and params. */\n\treadonly message: string\n\t/** `field`, `type` and `value` always; `format`, `accepted` or `options` as the code needs. */\n\treadonly params: Readonly<Record<string, string>>\n}\n\nexport interface ReadResult {\n\t/** What the cell should hold: the value, or the text as typed when it could not be read. */\n\treadonly value: CellValue\n\treadonly problem: ValueProblem | null\n}\n\n/** The words accepted for yes and no besides the settings' own, as nouxwell/tabula's BoolParser accepts them. */\nconst TRUE_WORDS = new Set([\"1\", \"true\", \"yes\", \"on\", \"y\", \"t\", \"evet\", \"e\"])\nconst FALSE_WORDS = new Set([\"0\", \"false\", \"no\", \"off\", \"n\", \"f\", \"hayır\", \"hayir\", \"h\"])\n\n/**\n * Reads text into the field's type.\n *\n * Text with nothing in it is an empty cell, never a problem: whether a field may be empty is a rule,\n * checked with the other rules.\n */\nexport function readInput(field: FieldSchema, input: string, settings: ValueSettings): ReadResult {\n\tconst text = clean(input)\n\n\tif (text === \"\") {\n\t\treturn { value: null, problem: null }\n\t}\n\n\tswitch (field.type) {\n\t\tcase \"string\":\n\t\t\treturn { value: text, problem: null }\n\t\tcase \"lookup\":\n\t\t\t// Text is a record's name, not the record: a `LookupResolver` matches it to one, and until\n\t\t\t// then the backend has no id to take.\n\t\t\treturn refused(field, text, \"not_matched\")\n\t\tcase \"integer\": {\n\t\t\tconst number = readNumber(input, settings)\n\n\t\t\tif (number === null) {\n\t\t\t\treturn refused(field, text, \"not_a_number\")\n\t\t\t}\n\n\t\t\treturn isWholeNumberText(number) && !isTooLarge(number)\n\t\t\t\t? { value: number, problem: null }\n\t\t\t\t: refused(field, text, \"not_an_integer\")\n\t\t}\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\t\treturn numberResult(field, text, readNumber(input, settings))\n\t\tcase \"money\":\n\t\t\treturn numberResult(field, text, readMoney(input, field.currency, settings))\n\t\tcase \"percent\":\n\t\t\treturn numberResult(field, text, readPercent(input, settings))\n\t\tcase \"bool\":\n\t\t\treturn readBool(field, text, settings)\n\t\tcase \"date\":\n\t\tcase \"datetime\":\n\t\t\treturn readDateValue(field, text, settings)\n\t\tcase \"options\":\n\t\t\treturn readOptions(field, text)\n\t}\n}\n\n/**\n * The problem with what a cell holds, or null when it holds a value of its field's type.\n *\n * A value in the form the grid writes is fine as it is. Anything else is read as text, so a value\n * a host loaded as \"1.234,56\" into a money column is accepted, and a cell still holding what a user\n * typed and the grid could not read reports why.\n */\nexport function valueProblem(field: FieldSchema, value: CellValue, settings: ValueSettings): ValueProblem | null {\n\tif (value === null || isFieldValue(field, value)) {\n\t\treturn null\n\t}\n\n\treturn readInput(field, describeValue(value), settings).problem\n}\n\n/**\n * A value in the form the grid writes, as a backend is sent it: \"1.234,56\" a host loaded into a\n * money column goes as \"1234.56\", the value `valueProblem` accepted it as. Text the grid could not\n * read goes as it stands, for the backend to refuse as the grid did.\n */\nexport function canonicalValue(field: FieldSchema, value: CellValue, settings: ValueSettings): CellValue {\n\tif (value === null || isFieldValue(field, value)) {\n\t\treturn value\n\t}\n\n\tconst text = describeValue(value)\n\tconst result = readInput(field, text, settings)\n\n\tif (result.problem === null) {\n\t\treturn result.value\n\t}\n\n\t// \"12,5\" in an integer column was read, only not as a whole number: sent as 12.5, the backend\n\t// refuses it for the same reason the grid did, rather than as text it cannot read.\n\treturn result.problem.code === \"not_an_integer\" ? (readNumber(text, settings) ?? value) : value\n}\n\n/** Whether a value is already in the form a cell of this field holds. */\nexport function isFieldValue(field: FieldSchema, value: CellValue): boolean {\n\tswitch (field.type) {\n\t\tcase \"string\":\n\t\t\treturn typeof value === \"string\"\n\t\tcase \"integer\":\n\t\t\treturn (\n\t\t\t\t(typeof value === \"number\" && Number.isSafeInteger(value)) ||\n\t\t\t\t(typeof value === \"string\" && isWholeNumberText(value) && !isTooLarge(value))\n\t\t\t)\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\tcase \"money\":\n\t\tcase \"percent\":\n\t\t\treturn decimalText(value) !== null\n\t\tcase \"bool\":\n\t\t\treturn typeof value === \"boolean\"\n\t\tcase \"date\":\n\t\t\treturn isIsoDate(value, false)\n\t\tcase \"datetime\":\n\t\t\treturn isIsoDate(value, true)\n\t\tcase \"options\":\n\t\t\treturn field.multiple\n\t\t\t\t? Array.isArray(value) && value.every(item => isOptionValue(field, item))\n\t\t\t\t: isOptionValue(field, value)\n\t\tcase \"lookup\":\n\t\t\treturn isLookupValue(value)\n\t}\n}\n\n/** A value as text, for reading it again or for showing it as it stands. */\nexport function describeValue(value: CellValue): string {\n\tif (value === null) {\n\t\treturn \"\"\n\t}\n\n\tswitch (typeof value) {\n\t\tcase \"string\":\n\t\t\treturn value\n\t\tcase \"number\":\n\t\t\treturn decimalText(value) ?? String(value)\n\t\tcase \"boolean\":\n\t\t\treturn value ? \"true\" : \"false\"\n\t}\n\n\treturn JSON.stringify(value)\n}\n\nexport function isLookupValue(value: CellValue): value is { readonly id: string | number; readonly label: string } {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\treturn false\n\t}\n\n\tconst record = value as Readonly<Record<string, CellValue>>\n\n\treturn (typeof record.id === \"string\" || typeof record.id === \"number\") && typeof record.label === \"string\"\n}\n\nfunction isOptionValue(field: OptionsField, value: CellValue): boolean {\n\treturn field.options.some(option => option.value === value)\n}\n\nfunction numberResult(field: FieldSchema, text: string, number: string | null): ReadResult {\n\treturn number === null ? refused(field, text, \"not_a_number\") : { value: number, problem: null }\n}\n\nfunction readBool(field: FieldSchema, text: string, settings: ValueSettings): ReadResult {\n\tconst needle = fold(text)\n\n\t// The settings' own words first: they are what the grid shows, and what a template's list offers.\n\tif (needle === fold(settings.trueWord)) {\n\t\treturn { value: true, problem: null }\n\t}\n\n\tif (needle === fold(settings.falseWord)) {\n\t\treturn { value: false, problem: null }\n\t}\n\n\tif (TRUE_WORDS.has(needle)) {\n\t\treturn { value: true, problem: null }\n\t}\n\n\tif (FALSE_WORDS.has(needle)) {\n\t\treturn { value: false, problem: null }\n\t}\n\n\tconst accepted = unique([settings.trueWord, settings.falseWord, \"Evet\", \"Hayır\", \"1\", \"0\", \"true\", \"false\"])\n\n\treturn refused(field, text, \"not_a_boolean\", { accepted: accepted.join(\", \") })\n}\n\nfunction readDateValue(\n\tfield: FieldSchema & { type: \"date\" | \"datetime\" },\n\ttext: string,\n\tsettings: ValueSettings\n): ReadResult {\n\tconst withTime = field.type === \"datetime\"\n\tconst pattern = datePatternOf(field, settings)\n\tconst other = withTime ? settings.datePattern : settings.dateTimePattern\n\tconst value = readDate(text, withTime, pattern, other)\n\n\treturn value === null ? refused(field, text, \"not_a_date\", { format: pattern }) : { value, problem: null }\n}\n\n/** The pattern a date field is shown and read with: its own, or the settings' for its type. */\nexport function datePatternOf(field: FieldSchema & { type: \"date\" | \"datetime\" }, settings: ValueSettings): string {\n\treturn field.pattern ?? (field.type === \"datetime\" ? settings.dateTimePattern : settings.datePattern)\n}\n\n/**\n * An option by its label first, then by its value, as nouxwell/tabula matches them: if one option's\n * label is another's value, the label wins, because it is what the user sees. A field that holds\n * several takes them separated by commas.\n */\nfunction readOptions(field: OptionsField, text: string): ReadResult {\n\tconst parts = field.multiple\n\t\t? text\n\t\t\t\t.split(\",\")\n\t\t\t\t.map(part => clean(part))\n\t\t\t\t.filter(part => part !== \"\")\n\t\t: [text]\n\tconst values: (string | number)[] = []\n\n\tfor (const part of parts) {\n\t\tconst needle = fold(part)\n\t\tconst option =\n\t\t\tfield.options.find(candidate => fold(candidate.label) === needle) ??\n\t\t\tfield.options.find(candidate => fold(String(candidate.value)) === needle)\n\n\t\tif (!option) {\n\t\t\treturn refused(field, text, \"not_an_option\", {\n\t\t\t\toptions: unique(field.options.map(candidate => candidate.label)).join(\", \")\n\t\t\t})\n\t\t}\n\n\t\tvalues.push(option.value)\n\t}\n\n\treturn { value: field.multiple ? Object.freeze(values) : (values[0] ?? null), problem: null }\n}\n\nfunction refused(\n\tfield: FieldSchema,\n\ttext: string,\n\tcode: ValueProblemCode,\n\textra: Readonly<Record<string, string>> = {}\n): ReadResult {\n\tconst params = Object.freeze({ field: field.key, type: field.type, value: text, ...extra })\n\n\treturn { value: text, problem: Object.freeze({ code, message: messageFor(code, params), params }) }\n}\n\n/** The same sentences as nouxwell/tabula's ParseException. */\nfunction messageFor(code: ValueProblemCode, params: Readonly<Record<string, string>>): string {\n\tconst value = params.value ?? \"\"\n\n\tswitch (code) {\n\t\tcase \"not_a_number\":\n\t\t\treturn `\"${value}\" could not be read as a number.`\n\t\tcase \"not_an_integer\":\n\t\t\treturn `\"${value}\" is not a whole number.`\n\t\tcase \"not_a_date\":\n\t\t\treturn `\"${value}\" could not be read as a date; expected format: ${params.format ?? \"\"}`\n\t\tcase \"not_a_boolean\":\n\t\t\treturn `\"${value}\" is not a Yes/No value. Accepted: ${params.accepted ?? \"\"}`\n\t\tcase \"not_an_option\":\n\t\t\treturn `\"${value}\" is not in the list. Options: ${params.options || \"(no options defined)\"}`\n\t\tcase \"not_matched\":\n\t\t\treturn `\"${value}\" is not matched to a record; pick one from the list.`\n\t}\n}\n\n/** Without repeats, comparing as `fold()` does, keeping the first spelling of each. */\nfunction unique(words: readonly string[]): string[] {\n\tconst seen = new Map<string, string>()\n\n\tfor (const word of words) {\n\t\tconst key = fold(word)\n\n\t\tif (key !== \"\" && !seen.has(key)) {\n\t\t\tseen.set(key, word)\n\t\t}\n\t}\n\n\treturn [...seen.values()]\n}\n","import { compareDecimal, normalizeDecimal } from \"./decimal.js\"\nimport type { RowId, RowStore } from \"./rows.js\"\nimport type { FieldSchema, FieldType, ModuleSchema } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport { decimalText } from \"./values/number.js\"\nimport { canonicalValue, isFieldValue, isLookupValue, valueProblem } from \"./values/read.js\"\nimport type { ValueSettings } from \"./values/settings.js\"\n\n/**\n * Row checks: rules about a row rather than one cell, as a module schema or a template writes them.\n * \"Not is required when Aktif is no\", \"Yeni fiyat cannot be below Mevcut fiyat\", \"Geçerlilik cannot\n * be before 2026-12-01 when Para birimi is USD\".\n *\n * A check says what must hold for one field of the row (`assert`), and when (`when`: every condition\n * holding, or always when there is none). What it asserts is a condition too: the field filled,\n * empty, or compared with a value or with another field of the row. Its issue lands on that field's\n * cell, as an error that keeps the row from being processed or as a warning that does not.\n */\n\nexport const COMPARISONS = Object.freeze([\"=\", \"!=\", \"<\", \"<=\", \">\", \">=\"] as const)\nexport type Comparison = (typeof COMPARISONS)[number]\n\nexport const CONDITION_OPS = Object.freeze([...COMPARISONS, \"filled\", \"empty\"] as const)\nexport type ConditionOp = (typeof CONDITION_OPS)[number]\n\n/** One thing about one field of a row. */\nexport interface RowCondition {\n\treadonly field: string\n\treadonly op: ConditionOp\n\t/** What a comparison compares with: a value in the form a cell holds it, or null… */\n\treadonly value: CellValue\n\t/** …or another field of the row, by key. */\n\treadonly other: string | null\n}\n\nexport type CheckSeverity = \"error\" | \"warning\"\n\nexport interface RowCheck {\n\t/** Names the check: its issues' ids, and an editor's list. Unique in the schema with its template. */\n\treadonly id: string\n\t/** What must hold for the row. The issue lands on this field's cell. */\n\treadonly assert: RowCondition\n\t/** When the check applies: every condition holding. Empty: always. */\n\treadonly when: readonly RowCondition[]\n\treadonly severity: CheckSeverity\n\t/** The words to say, by language, such as `{ \"tr\": \"…\", \"en\": \"…\" }`; null leaves them to the grid. */\n\treadonly message: Readonly<Record<string, string>> | null\n}\n\n/** A condition as it is written in the JSON. */\nexport interface ConditionInput {\n\tfield: string\n\top: ConditionOp\n\tvalue?: string | number | boolean | readonly (string | number)[]\n\tother?: string\n}\n\n/** A check as it is written in the JSON. */\nexport interface CheckInput {\n\tid: string\n\tassert: ConditionInput\n\twhen?: ConditionInput[]\n\tseverity?: CheckSeverity\n\tmessage?: Record<string, string>\n}\n\nconst NUMERIC: ReadonlySet<FieldType> = new Set([\"integer\", \"decimal\", \"money\", \"quantity\", \"percent\"])\nconst ORDERED: ReadonlySet<FieldType> = new Set([...NUMERIC, \"date\", \"datetime\"])\nconst CHECK_PROPERTIES = [\"id\", \"assert\", \"when\", \"severity\", \"message\"]\nconst CONDITION_PROPERTIES = [\"field\", \"op\", \"value\", \"other\"]\n\ntype Add = (path: string, message: string) => void\ntype Json = Record<string, unknown>\n\n/** Reads a schema's checks against its fields, reporting every problem with where it is. */\nexport function readChecks(value: unknown, fields: readonly FieldSchema[], add: Add): RowCheck[] {\n\tif (value === undefined || value === null) {\n\t\treturn []\n\t}\n\n\tif (!Array.isArray(value)) {\n\t\tadd(\"checks\", \"must be an array of checks\")\n\n\t\treturn []\n\t}\n\n\tconst byKey = new Map(fields.map(field => [field.key, field]))\n\tconst ids = new Map<string, number>()\n\tconst checks: RowCheck[] = []\n\n\t;(value as unknown[]).forEach((raw, index) => {\n\t\tconst path = `checks[${index}]`\n\t\tconst check = readCheck(raw, path, byKey, add)\n\n\t\tif (!check) {\n\t\t\treturn\n\t\t}\n\n\t\tconst first = ids.get(check.id)\n\n\t\tif (first !== undefined) {\n\t\t\tadd(`${path}.id`, `\"${check.id}\" is already the id of checks[${first}]; an id names one check only`)\n\n\t\t\treturn\n\t\t}\n\n\t\tids.set(check.id, index)\n\t\tchecks.push(check)\n\t})\n\n\treturn checks\n}\n\n/** A check written out again as JSON. */\nexport function checkToJson(check: RowCheck): CheckInput {\n\tconst json: CheckInput = { id: check.id, assert: conditionToJson(check.assert) }\n\n\tif (check.when.length > 0) {\n\t\tjson.when = check.when.map(conditionToJson)\n\t}\n\n\tjson.severity = check.severity\n\n\tif (check.message !== null) {\n\t\tjson.message = { ...check.message }\n\t}\n\n\treturn json\n}\n\n/** The fields a check reads: what it asserts, what it compares with, and its conditions. */\nexport function checkFields(check: RowCheck): string[] {\n\tconst keys = new Set<string>()\n\n\tfor (const condition of [check.assert, ...check.when]) {\n\t\tkeys.add(condition.field)\n\n\t\tif (condition.other !== null) {\n\t\t\tkeys.add(condition.other)\n\t\t}\n\t}\n\n\treturn [...keys]\n}\n\n/**\n * Whether a row breaks the check: every condition of `when` holds, and what it asserts does not. A\n * comparison with nothing on one side asserts nothing: a field's being filled is a check of its own.\n * A value that cannot be read as its field's is nothing to compare either; its cell says why.\n */\nexport function breaksCheck(\n\tcheck: RowCheck,\n\tfield: (key: string) => FieldSchema,\n\tget: (key: string) => CellValue,\n\tsettings: ValueSettings\n): boolean {\n\tfor (const condition of check.when) {\n\t\tif (holds(condition, field, get, settings) !== true) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn holds(check.assert, field, get, settings) === false\n}\n\n/**\n * The rows that break a check, in the order they stand in the sheet: what a rule editor counts and\n * shows while the rule is still being written, before it is saved anywhere. `schema` is one that has\n * the check, such as the template applied with it.\n */\nexport function rowsBreaking(schema: ModuleSchema, store: RowStore, check: RowCheck, settings: ValueSettings): RowId[] {\n\tconst field = (key: string): FieldSchema => schema.field(key)\n\n\treturn store.rowIds().filter(rowId => breaksCheck(check, field, key => store.get(rowId, key), settings))\n}\n\n/**\n * Whether a condition holds for a row: what a colour rule asks. A comparison with nothing on one side\n * does not hold, nor does one with a value that cannot be read as its field's.\n */\nexport function conditionHolds(\n\tcondition: RowCondition,\n\tfield: (key: string) => FieldSchema,\n\tget: (key: string) => CellValue,\n\tsettings: ValueSettings\n): boolean {\n\treturn holds(condition, field, get, settings) === true\n}\n\n// ---------------------------------------------------------------- inside\n\n/** True or false, or null when a comparison has nothing to compare on one side. */\nfunction holds(\n\tcondition: RowCondition,\n\tfield: (key: string) => FieldSchema,\n\tget: (key: string) => CellValue,\n\tsettings: ValueSettings\n): boolean | null {\n\tconst own = field(condition.field)\n\tconst raw = get(condition.field)\n\n\tif (condition.op === \"filled\") {\n\t\treturn raw !== null\n\t}\n\n\tif (condition.op === \"empty\") {\n\t\treturn raw === null\n\t}\n\n\tconst left = readable(own, raw, settings)\n\tconst right =\n\t\tcondition.other === null ? condition.value : readable(field(condition.other), get(condition.other), settings)\n\n\tif (left === null || right === null) {\n\t\treturn null\n\t}\n\n\tconst order = compare(own, left, right)\n\n\tswitch (condition.op) {\n\t\tcase \"=\":\n\t\t\treturn order === 0\n\t\tcase \"!=\":\n\t\t\treturn order !== 0\n\t\tcase \"<\":\n\t\t\treturn order < 0\n\t\tcase \"<=\":\n\t\t\treturn order <= 0\n\t\tcase \">\":\n\t\t\treturn order > 0\n\t\tcase \">=\":\n\t\t\treturn order >= 0\n\t}\n}\n\n/** The value as the backend is sent it; null for an empty cell or one that cannot be read. */\nfunction readable(field: FieldSchema, value: CellValue, settings: ValueSettings): CellValue {\n\tif (value === null || valueProblem(field, value, settings) !== null) {\n\t\treturn null\n\t}\n\n\treturn canonicalValue(field, value, settings)\n}\n\n/** Below zero, zero or above, as the values stand; for kinds with no order, zero or not. */\nfunction compare(field: FieldSchema, a: CellValue, b: CellValue): number {\n\tif (NUMERIC.has(field.type)) {\n\t\tconst left = normalizeDecimal(decimalText(a) ?? \"\")\n\t\tconst right = normalizeDecimal(decimalText(b) ?? \"\")\n\n\t\treturn left === null || right === null ? 1 : compareDecimal(left, right)\n\t}\n\n\tif (field.type === \"date\" || field.type === \"datetime\") {\n\t\treturn String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0\n\t}\n\n\treturn sameValue(a, b) ? 0 : 1\n}\n\nfunction sameValue(a: CellValue, b: CellValue): boolean {\n\tif (isLookupValue(a) && isLookupValue(b)) {\n\t\treturn String(a.id) === String(b.id)\n\t}\n\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\treturn JSON.stringify([...a].map(String).sort()) === JSON.stringify([...b].map(String).sort())\n\t}\n\n\treturn a === b || (typeof a !== \"object\" && typeof b !== \"object\" && String(a) === String(b))\n}\n\nfunction readCheck(raw: unknown, path: string, fields: ReadonlyMap<string, FieldSchema>, add: Add): RowCheck | null {\n\tif (!isObject(raw)) {\n\t\tadd(path, 'must be an object such as { \"id\": \"…\", \"assert\": { \"field\": \"…\", \"op\": \"filled\" } }')\n\n\t\treturn null\n\t}\n\n\tlet failed = false\n\tconst fail: Add = (at, message) => {\n\t\tfailed = true\n\t\tadd(at, message)\n\t}\n\n\tfor (const name of Object.keys(raw)) {\n\t\tif (!CHECK_PROPERTIES.includes(name)) {\n\t\t\tfail(`${path}.${name}`, `is not a check property; a check takes ${CHECK_PROPERTIES.join(\", \")}`)\n\t\t}\n\t}\n\n\tconst id = typeof raw.id === \"string\" && raw.id.trim() !== \"\" ? raw.id : null\n\n\tif (id === null) {\n\t\tfail(`${path}.id`, \"must be a non-empty string\")\n\t}\n\n\tconst assert = readCondition(raw.assert, `${path}.assert`, fields, fail)\n\tconst when: RowCondition[] = []\n\n\tif (raw.when !== undefined && raw.when !== null) {\n\t\tif (!Array.isArray(raw.when)) {\n\t\t\tfail(`${path}.when`, \"must be an array of conditions, every one of which must hold\")\n\t\t} else {\n\t\t\t;(raw.when as unknown[]).forEach((item, index) => {\n\t\t\t\tconst condition = readCondition(item, `${path}.when[${index}]`, fields, fail)\n\n\t\t\t\tif (condition) {\n\t\t\t\t\twhen.push(condition)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tconst severity = raw.severity === undefined || raw.severity === null ? \"error\" : raw.severity\n\n\tif (severity !== \"error\" && severity !== \"warning\") {\n\t\tfail(`${path}.severity`, `must be \"error\" or \"warning\"; got ${JSON.stringify(severity)}`)\n\t}\n\n\tconst message = readMessage(raw.message, `${path}.message`, fail)\n\n\tif (failed || id === null || assert === null) {\n\t\treturn null\n\t}\n\n\treturn Object.freeze({\n\t\tid,\n\t\tassert,\n\t\twhen: Object.freeze(when),\n\t\tseverity: severity as CheckSeverity,\n\t\tmessage\n\t})\n}\n\n/** Reads one condition against the fields, as a check's and a colour rule's are written. */\nexport function readCondition(\n\traw: unknown,\n\tpath: string,\n\tfields: ReadonlyMap<string, FieldSchema>,\n\tadd: Add\n): RowCondition | null {\n\tif (!isObject(raw)) {\n\t\tadd(path, 'must be an object such as { \"field\": \"active\", \"op\": \"=\", \"value\": false }')\n\n\t\treturn null\n\t}\n\n\tconst before = { failed: false }\n\tconst fail: Add = (at, message) => {\n\t\tbefore.failed = true\n\t\tadd(at, message)\n\t}\n\n\tfor (const name of Object.keys(raw)) {\n\t\tif (!CONDITION_PROPERTIES.includes(name)) {\n\t\t\tfail(`${path}.${name}`, `is not a condition property; a condition takes ${CONDITION_PROPERTIES.join(\", \")}`)\n\t\t}\n\t}\n\n\tconst field = typeof raw.field === \"string\" ? fields.get(raw.field) : undefined\n\n\tif (!field) {\n\t\tfail(`${path}.field`, `${JSON.stringify(raw.field)} is not a field of this schema`)\n\t}\n\n\tconst op = raw.op as ConditionOp\n\n\tif (!(CONDITION_OPS as readonly unknown[]).includes(op)) {\n\t\tfail(`${path}.op`, `${JSON.stringify(raw.op)} is not a condition; expected one of ${CONDITION_OPS.join(\", \")}`)\n\n\t\treturn null\n\t}\n\n\tconst hasValue = raw.value !== undefined && raw.value !== null\n\tconst hasOther = raw.other !== undefined && raw.other !== null\n\n\tif (op === \"filled\" || op === \"empty\") {\n\t\tif (hasValue || hasOther) {\n\t\t\tfail(path, `${op} takes no value and no other field`)\n\t\t}\n\n\t\treturn before.failed || !field ? null : Object.freeze({ field: field.key, op, value: null, other: null })\n\t}\n\n\tif (hasValue === hasOther) {\n\t\tfail(path, `${op} compares with a value or with another field: give one of value and other`)\n\n\t\treturn null\n\t}\n\n\tif (field && (op === \"<\" || op === \"<=\" || op === \">\" || op === \">=\") && !ORDERED.has(field.type)) {\n\t\tfail(`${path}.op`, `${op} needs an order; a ${field.type} field only takes = and !=`)\n\t}\n\n\tlet other: string | null = null\n\tlet value: CellValue = null\n\n\tif (hasOther) {\n\t\tconst otherField = typeof raw.other === \"string\" ? fields.get(raw.other) : undefined\n\n\t\tif (!otherField) {\n\t\t\tfail(`${path}.other`, `${JSON.stringify(raw.other)} is not a field of this schema`)\n\t\t} else if (field && !comparable(field.type, otherField.type)) {\n\t\t\tfail(`${path}.other`, `a ${field.type} field cannot be compared with a ${otherField.type} field`)\n\t\t} else if (field && otherField.key === field.key) {\n\t\t\tfail(`${path}.other`, \"is the field itself\")\n\t\t} else {\n\t\t\tother = otherField.key\n\t\t}\n\t} else if (field) {\n\t\t// A number is kept as decimal text, as every cell of a numeric field holds one.\n\t\tconst given = (NUMERIC.has(field.type) ? (decimalText(raw.value) ?? raw.value) : raw.value) as CellValue\n\n\t\tif (field.type === \"lookup\" || !isFieldValue(field, given)) {\n\t\t\tfail(\n\t\t\t\t`${path}.value`,\n\t\t\t\t`${JSON.stringify(raw.value)} is not a value of the ${field.type} field \"${field.key}\"`\n\t\t\t)\n\t\t} else {\n\t\t\tvalue = Array.isArray(given) ? (Object.freeze([...(given as unknown[])]) as CellValue) : given\n\t\t}\n\t}\n\n\treturn before.failed || !field ? null : Object.freeze({ field: field.key, op, value, other })\n}\n\nfunction comparable(a: FieldType, b: FieldType): boolean {\n\treturn (NUMERIC.has(a) && NUMERIC.has(b)) || a === b\n}\n\nfunction readMessage(raw: unknown, path: string, add: Add): Readonly<Record<string, string>> | null {\n\tif (raw === undefined || raw === null) {\n\t\treturn null\n\t}\n\n\tif (!isObject(raw) || Object.keys(raw).length === 0) {\n\t\tadd(path, 'must be an object of words by language, such as { \"tr\": \"…\", \"en\": \"…\" }')\n\n\t\treturn null\n\t}\n\n\tfor (const [language, text] of Object.entries(raw)) {\n\t\tif (typeof text !== \"string\" || text.trim() === \"\") {\n\t\t\tadd(`${path}.${language}`, \"must be a non-empty string\")\n\t\t}\n\t}\n\n\treturn Object.freeze({ ...(raw as Record<string, string>) })\n}\n\n/** A condition written out again as JSON. */\nexport function conditionToJson(condition: RowCondition): ConditionInput {\n\tconst json: ConditionInput = { field: condition.field, op: condition.op }\n\n\tif (condition.other !== null) {\n\t\tjson.other = condition.other\n\t} else if (condition.value !== null) {\n\t\tjson.value = condition.value as NonNullable<ConditionInput[\"value\"]>\n\t}\n\n\treturn json\n}\n\nfunction isObject(value: unknown): value is Json {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n","type Listener<T> = (event: T) => void\n\n/**\n * A list of listeners, called in the order they subscribed.\n *\n * A listener that throws does not stop the others, and does not undo the change it was told about:\n * the change has happened. The error is reported the way a browser reports one thrown from an event\n * listener, so it is seen rather than swallowed.\n */\nexport class Listeners<T> {\n\treadonly #listeners = new Set<Listener<T>>()\n\n\tadd(listener: Listener<T>): () => void {\n\t\t// Wrapped, so the same function subscribed twice is two subscriptions, each with its own way out.\n\t\tconst entry: Listener<T> = event => listener(event)\n\t\tthis.#listeners.add(entry)\n\n\t\treturn () => {\n\t\t\tthis.#listeners.delete(entry)\n\t\t}\n\t}\n\n\temit(event: T): void {\n\t\tfor (const listener of [...this.#listeners]) {\n\t\t\t// One that an earlier listener unsubscribed is not called.\n\t\t\tif (!this.#listeners.has(listener)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tlistener(event)\n\t\t\t} catch (error) {\n\t\t\t\treport(error)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction report(error: unknown): void {\n\tconst scope = globalThis as { reportError?: (error: unknown) => void }\n\n\tif (typeof scope.reportError === \"function\") {\n\t\tscope.reportError(error)\n\n\t\treturn\n\t}\n\n\t// Where there is no reportError, an unhandled rejection is the nearest thing: seen, and not in the way.\n\tvoid Promise.reject(error)\n}\n","import { TabulaError } from \"./errors.js\"\nimport type { UndoHistory } from \"./history.js\"\nimport { Listeners } from \"./listeners.js\"\nimport type { RowId } from \"./rows.js\"\n\n/**\n * What a user puts on cells by hand to find them again: a fill, a text colour, bold, italic. \"These\n * I will look at later\", \"this one is wrong at the supplier's\". Never a value: a mark is kept with\n * the draft, beside the rows, and nothing of it is sent to the backend.\n *\n * Colours are names, not codes, so a theme draws each in its own shade, light or dark.\n */\n\nexport const MARK_COLORS = Object.freeze([\n\t\"yellow\",\n\t\"green\",\n\t\"blue\",\n\t\"purple\",\n\t\"pink\",\n\t\"orange\",\n\t\"grey\",\n\t\"red\"\n] as const)\nexport type MarkColor = (typeof MARK_COLORS)[number]\n\nexport interface CellMark {\n\treadonly fill?: MarkColor\n\treadonly color?: MarkColor\n\treadonly bold?: true\n\treadonly italic?: true\n}\n\n/** A change to cells' marks: a colour, or null to take it off; bold and italic on or off. */\nexport interface CellMarkChange {\n\treadonly fill?: MarkColor | null\n\treadonly color?: MarkColor | null\n\treadonly bold?: boolean\n\treadonly italic?: boolean\n}\n\n/** One cell, by its row's id and its field's key. */\nexport interface MarkedCell {\n\treadonly rowId: RowId\n\treadonly field: string\n}\n\n/** The marks as JSON keeps them: by row id, then by field key. */\nexport type MarksData = Readonly<Record<RowId, Readonly<Record<string, CellMark>>>>\n\nexport interface CellMarksOptions {\n\t/** Marks to start with, such as a draft's. */\n\treadonly marks?: MarksData\n\t/** Each change becomes a step of it, so Ctrl+Z takes it back in its turn with the rows' changes. */\n\treadonly history?: UndoHistory\n}\n\n/** The marks on a sheet's cells: read by the grid, changed by the toolbar, kept by the draft. */\nexport class CellMarks {\n\treadonly #cells = new Map<RowId, Map<string, CellMark>>()\n\treadonly #history: UndoHistory | null\n\treadonly #listeners = new Listeners<CellMarks>()\n\t#version = 0\n\n\tconstructor(options: CellMarksOptions = {}) {\n\t\tthis.#history = options.history ?? null\n\n\t\tfor (const [rowId, cells] of Object.entries(options.marks ?? {})) {\n\t\t\tfor (const [field, mark] of Object.entries(cells)) {\n\t\t\t\tthis.#put(rowId, field, cleanMark(mark))\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Moves on with every change, for a view to redraw by. */\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\t/** How many cells carry a mark. */\n\tget size(): number {\n\t\tlet count = 0\n\n\t\tfor (const cells of this.#cells.values()) {\n\t\t\tcount += cells.size\n\t\t}\n\n\t\treturn count\n\t}\n\n\tget(rowId: RowId, field: string): CellMark | null {\n\t\treturn this.#cells.get(rowId)?.get(field) ?? null\n\t}\n\n\t/** Whether any cell of the row carries a mark. */\n\thasRow(rowId: RowId): boolean {\n\t\treturn this.#cells.has(rowId)\n\t}\n\n\t/** The rows with a marked cell. */\n\trows(): RowId[] {\n\t\treturn [...this.#cells.keys()]\n\t}\n\n\t/** Puts the change on every cell given: a colour given replaces the one there, null takes it off. */\n\tmark(cells: readonly MarkedCell[], change: CellMarkChange): void {\n\t\tcheckChange(change)\n\t\tthis.#change(cells, mark => {\n\t\t\tconst next: { fill?: MarkColor; color?: MarkColor; bold?: true; italic?: true } = { ...mark }\n\n\t\t\tfor (const name of [\"fill\", \"color\"] as const) {\n\t\t\t\tif (change[name] === null) {\n\t\t\t\t\tdelete next[name]\n\t\t\t\t} else if (change[name] !== undefined) {\n\t\t\t\t\tnext[name] = change[name]\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const name of [\"bold\", \"italic\"] as const) {\n\t\t\t\tif (change[name] === false) {\n\t\t\t\t\tdelete next[name]\n\t\t\t\t} else if (change[name] === true) {\n\t\t\t\t\tnext[name] = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn next\n\t\t})\n\t}\n\n\t/** Bold or italic on every cell given, or off when every one already has it, as a spreadsheet's button. */\n\ttoggle(cells: readonly MarkedCell[], style: \"bold\" | \"italic\"): void {\n\t\tconst on = !cells.every(cell => this.get(cell.rowId, cell.field)?.[style] === true)\n\n\t\tthis.mark(cells, { [style]: on })\n\t}\n\n\t/** Takes every mark off the cells given. */\n\tclear(cells: readonly MarkedCell[]): void {\n\t\tthis.#change(cells, () => ({}))\n\t}\n\n\t/** Every mark, as JSON keeps them; only the rows given, such as the rows the sheet still has. */\n\ttoJSON(rowIds?: Iterable<RowId>): MarksData {\n\t\tconst keep = rowIds === undefined ? null : new Set(rowIds)\n\t\tconst data: Record<RowId, Record<string, CellMark>> = {}\n\n\t\tfor (const [rowId, cells] of this.#cells) {\n\t\t\tif (keep === null || keep.has(rowId)) {\n\t\t\t\tdata[rowId] = Object.fromEntries(cells)\n\t\t\t}\n\t\t}\n\n\t\treturn data\n\t}\n\n\t/** Called after each change. Returns the way to stop. */\n\tsubscribe(listener: (marks: CellMarks) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Changes the cells, as one step of the history when there is one. */\n\t#change(cells: readonly MarkedCell[], next: (mark: CellMark) => CellMark): void {\n\t\tconst before: [MarkedCell, CellMark | null][] = []\n\t\tconst after: [MarkedCell, CellMark | null][] = []\n\n\t\tfor (const cell of cells) {\n\t\t\tconst old = this.get(cell.rowId, cell.field)\n\t\t\tconst made = cleanMark(next(old ?? {}))\n\t\t\tconst now = Object.keys(made).length === 0 ? null : made\n\n\t\t\tif (!sameMark(old, now)) {\n\t\t\t\tbefore.push([cell, old])\n\t\t\t\tafter.push([cell, now])\n\t\t\t}\n\t\t}\n\n\t\tif (after.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#apply(after)\n\t\tthis.#history?.record({ undo: () => this.#apply(before), redo: () => this.#apply(after) })\n\t}\n\n\t#apply(entries: readonly (readonly [MarkedCell, CellMark | null])[]): void {\n\t\tfor (const [cell, mark] of entries) {\n\t\t\tthis.#put(cell.rowId, cell.field, mark)\n\t\t}\n\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n\n\t#put(rowId: RowId, field: string, mark: CellMark | null): void {\n\t\tconst cells = this.#cells.get(rowId)\n\n\t\tif (mark === null || Object.keys(mark).length === 0) {\n\t\t\tcells?.delete(field)\n\n\t\t\tif (cells?.size === 0) {\n\t\t\t\tthis.#cells.delete(rowId)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tif (cells) {\n\t\t\tcells.set(field, mark)\n\t\t} else {\n\t\t\tthis.#cells.set(rowId, new Map([[field, mark]]))\n\t\t}\n\t}\n}\n\n/** The rows with a marked cell, for a `RowView` filter: the sheet's \"Renkli\" rows. */\nexport function rowsMarked(marks: CellMarks): (rowId: RowId) => boolean {\n\treturn rowId => marks.hasRow(rowId)\n}\n\n/**\n * Marks read from JSON, such as a draft's, each problem reported under `path`. A colour that is not\n * one, or a cell that is not an object, is a problem; an empty mark is dropped.\n */\nexport function readMarks(input: unknown, path: string, problem: (path: string, message: string) => void): MarksData {\n\tif (input === undefined || input === null) {\n\t\treturn {}\n\t}\n\n\tconst rows = plain(input)\n\n\tif (!rows) {\n\t\tproblem(path, \"must be an object of marks by row id, then field key.\")\n\n\t\treturn {}\n\t}\n\n\tconst data: Record<RowId, Record<string, CellMark>> = {}\n\n\tfor (const [rowId, value] of Object.entries(rows)) {\n\t\tconst cells = plain(value)\n\n\t\tif (!cells) {\n\t\t\tproblem(`${path}.${rowId}`, \"must be an object of marks by field key.\")\n\t\t\tcontinue\n\t\t}\n\n\t\tfor (const [field, raw] of Object.entries(cells)) {\n\t\t\tconst mark = plain(raw)\n\t\t\tconst at = `${path}.${rowId}.${field}`\n\n\t\t\tif (!mark) {\n\t\t\t\tproblem(at, 'must be an object such as { fill: \"yellow\", bold: true }.')\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst read: { fill?: MarkColor; color?: MarkColor; bold?: true; italic?: true } = {}\n\n\t\t\tfor (const name of [\"fill\", \"color\"] as const) {\n\t\t\t\tif (mark[name] === undefined) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif ((MARK_COLORS as readonly unknown[]).includes(mark[name])) {\n\t\t\t\t\tread[name] = mark[name] as MarkColor\n\t\t\t\t} else {\n\t\t\t\t\tproblem(`${at}.${name}`, `must be one of ${MARK_COLORS.join(\", \")}.`)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const name of [\"bold\", \"italic\"] as const) {\n\t\t\t\tif (mark[name] === true) {\n\t\t\t\t\tread[name] = true\n\t\t\t\t} else if (mark[name] !== undefined && mark[name] !== false) {\n\t\t\t\t\tproblem(`${at}.${name}`, \"must be true or false.\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Object.keys(read).length > 0) {\n\t\t\t\tdata[rowId] = { ...data[rowId], [field]: Object.freeze(read) }\n\t\t\t}\n\t\t}\n\t}\n\n\treturn data\n}\n\nfunction checkChange(change: CellMarkChange): void {\n\tfor (const name of [\"fill\", \"color\"] as const) {\n\t\tconst color = change[name]\n\n\t\tif (color !== undefined && color !== null && !(MARK_COLORS as readonly unknown[]).includes(color)) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_argument\",\n\t\t\t\t`A mark's ${name} is one of ${MARK_COLORS.join(\", \")}; got ${color}.`\n\t\t\t)\n\t\t}\n\t}\n}\n\nfunction cleanMark(mark: CellMark): CellMark {\n\treturn Object.freeze({\n\t\t...(mark.fill ? { fill: mark.fill } : {}),\n\t\t...(mark.color ? { color: mark.color } : {}),\n\t\t...(mark.bold ? { bold: true as const } : {}),\n\t\t...(mark.italic ? { italic: true as const } : {})\n\t})\n}\n\nfunction sameMark(a: CellMark | null, b: CellMark | null): boolean {\n\treturn (\n\t\t(a?.fill ?? null) === (b?.fill ?? null) &&\n\t\t(a?.color ?? null) === (b?.color ?? null) &&\n\t\t(a?.bold ?? false) === (b?.bold ?? false) &&\n\t\t(a?.italic ?? false) === (b?.italic ?? false)\n\t)\n}\n\nfunction plain(value: unknown): Record<string, unknown> | null {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: null\n}\n","import { conditionHolds, conditionToJson, readCondition, type ConditionInput, type RowCondition } from \"./checks.js\"\nimport { MARK_COLORS, type MarkColor } from \"./marks.js\"\nimport type { RowId, RowStore } from \"./rows.js\"\nimport type { FieldSchema, ModuleSchema } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport type { ValueSettings } from \"./values/settings.js\"\n\n/**\n * Colour rules: cells coloured by what the row holds, as a module schema or a template writes them.\n * \"Yeni fiyat below 100: orange\", \"Para birimi not TRY: blue text\", \"Aktif is no: the whole row\n * grey\". A rule's conditions are a check's: a field compared with a value or another field, filled\n * or empty, every one holding. When they hold, the rule's cell, or the whole row, takes its colours.\n *\n * Only how the sheet is drawn: a rule changes no value, and nothing of it is sent to the backend.\n * Everyone who opens the template sees the same colours, and they follow the values as they change.\n */\n\nexport interface StyleRule {\n\t/** Names the rule: an editor's list. Unique in the schema with its template. */\n\treadonly id: string\n\t/** When the rule colours: every condition holding. Never empty. */\n\treadonly when: readonly RowCondition[]\n\t/** The cell coloured, by field key; null colours the whole row. */\n\treadonly field: string | null\n\treadonly fill: MarkColor | null\n\treadonly color: MarkColor | null\n\treadonly bold: boolean\n}\n\n/** A colour rule as it is written in the JSON. */\nexport interface StyleRuleInput {\n\tid: string\n\twhen: ConditionInput[]\n\t/** Left out, the whole row. */\n\tfield?: string\n\tfill?: MarkColor\n\tcolor?: MarkColor\n\tbold?: boolean\n}\n\n/** What rules put on one cell: the last rule to say a thing wins, as later rules are written over earlier ones. */\nexport interface CellStyle {\n\treadonly fill: MarkColor | null\n\treadonly color: MarkColor | null\n\treadonly bold: boolean\n}\n\nconst RULE_PROPERTIES = [\"id\", \"when\", \"field\", \"fill\", \"color\", \"bold\"]\n\ntype Add = (path: string, message: string) => void\n\n/** Reads a schema's colour rules against its fields, reporting every problem with where it is. */\nexport function readStyleRules(value: unknown, fields: readonly FieldSchema[], add: Add): StyleRule[] {\n\tif (value === undefined || value === null) {\n\t\treturn []\n\t}\n\n\tif (!Array.isArray(value)) {\n\t\tadd(\"styles\", \"must be an array of colour rules\")\n\n\t\treturn []\n\t}\n\n\tconst byKey = new Map(fields.map(field => [field.key, field]))\n\tconst ids = new Map<string, number>()\n\tconst rules: StyleRule[] = []\n\n\tvalue.forEach((raw: unknown, index) => {\n\t\tconst path = `styles[${index}]`\n\t\tconst rule = readRule(raw, path, byKey, add)\n\n\t\tif (rule === null) {\n\t\t\treturn\n\t\t}\n\n\t\tconst seen = ids.get(rule.id)\n\n\t\tif (seen !== undefined) {\n\t\t\tadd(`${path}.id`, `\"${rule.id}\" is the id of styles[${seen}] too`)\n\n\t\t\treturn\n\t\t}\n\n\t\tids.set(rule.id, index)\n\t\trules.push(rule)\n\t})\n\n\treturn rules\n}\n\n/** A colour rule written out again as JSON. */\nexport function styleRuleToJson(rule: StyleRule): StyleRuleInput {\n\treturn {\n\t\tid: rule.id,\n\t\twhen: rule.when.map(conditionToJson),\n\t\t...(rule.field === null ? {} : { field: rule.field }),\n\t\t...(rule.fill === null ? {} : { fill: rule.fill }),\n\t\t...(rule.color === null ? {} : { color: rule.color }),\n\t\t...(rule.bold ? { bold: true } : {})\n\t}\n}\n\n/** Whether the rule colours the row: every one of its conditions holds. */\nexport function styleApplies(\n\trule: StyleRule,\n\tfield: (key: string) => FieldSchema,\n\tget: (key: string) => CellValue,\n\tsettings: ValueSettings\n): boolean {\n\treturn rule.when.every(condition => conditionHolds(condition, field, get, settings))\n}\n\n/**\n * What the rules put on each cell of a row, by field key, and on the row itself under `null`. Empty\n * when no rule colours the row.\n */\nexport function rowStyles(\n\trules: readonly StyleRule[],\n\tfield: (key: string) => FieldSchema,\n\tget: (key: string) => CellValue,\n\tsettings: ValueSettings\n): Map<string | null, CellStyle> {\n\tconst styles = new Map<string | null, CellStyle>()\n\n\tfor (const rule of rules) {\n\t\tif (!styleApplies(rule, field, get, settings)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst before = styles.get(rule.field)\n\n\t\tstyles.set(rule.field, {\n\t\t\tfill: rule.fill ?? before?.fill ?? null,\n\t\t\tcolor: rule.color ?? before?.color ?? null,\n\t\t\tbold: rule.bold || (before?.bold ?? false)\n\t\t})\n\t}\n\n\treturn styles\n}\n\n/**\n * The rows a rule colours, in the order they stand in the sheet: what a rule editor counts while the\n * rule is being written. `schema` is one that has the rule's fields.\n */\nexport function rowsStyled(schema: ModuleSchema, store: RowStore, rule: StyleRule, settings: ValueSettings): RowId[] {\n\tconst field = (key: string): FieldSchema => schema.field(key)\n\n\treturn store.rowIds().filter(rowId => styleApplies(rule, field, key => store.get(rowId, key), settings))\n}\n\nfunction readRule(raw: unknown, path: string, fields: ReadonlyMap<string, FieldSchema>, add: Add): StyleRule | null {\n\tif (!isObject(raw)) {\n\t\tadd(\n\t\t\tpath,\n\t\t\t'must be an object such as { \"id\": \"…\", \"when\": [{ \"field\": \"…\", \"op\": \"<\", \"value\": 100 }], \"fill\": \"orange\" }'\n\t\t)\n\n\t\treturn null\n\t}\n\n\tlet failed = false\n\tconst fail: Add = (at, message) => {\n\t\tfailed = true\n\t\tadd(at, message)\n\t}\n\n\tfor (const name of Object.keys(raw)) {\n\t\tif (!RULE_PROPERTIES.includes(name)) {\n\t\t\tfail(`${path}.${name}`, `is not a colour rule property; a rule takes ${RULE_PROPERTIES.join(\", \")}`)\n\t\t}\n\t}\n\n\tconst id = typeof raw.id === \"string\" && raw.id.trim() !== \"\" ? raw.id : null\n\n\tif (id === null) {\n\t\tfail(`${path}.id`, \"must be a non-empty string\")\n\t}\n\n\tconst when: RowCondition[] = []\n\n\tif (!Array.isArray(raw.when) || raw.when.length === 0) {\n\t\tfail(`${path}.when`, \"must be an array of one condition or more, every one of which must hold\")\n\t} else {\n\t\t;(raw.when as unknown[]).forEach((item, index) => {\n\t\t\tconst condition = readCondition(item, `${path}.when[${index}]`, fields, fail)\n\n\t\t\tif (condition) {\n\t\t\t\twhen.push(condition)\n\t\t\t}\n\t\t})\n\t}\n\n\tlet field: string | null = null\n\n\tif (raw.field !== undefined && raw.field !== null) {\n\t\tif (typeof raw.field === \"string\" && fields.has(raw.field)) {\n\t\t\tfield = raw.field\n\t\t} else {\n\t\t\tfail(`${path}.field`, `${JSON.stringify(raw.field)} is not a field of this schema`)\n\t\t}\n\t}\n\n\tconst color = (name: \"fill\" | \"color\"): MarkColor | null => {\n\t\tconst value = raw[name]\n\n\t\tif (value === undefined || value === null) {\n\t\t\treturn null\n\t\t}\n\n\t\tif ((MARK_COLORS as readonly unknown[]).includes(value)) {\n\t\t\treturn value as MarkColor\n\t\t}\n\n\t\tfail(`${path}.${name}`, `must be one of ${MARK_COLORS.join(\", \")}`)\n\n\t\treturn null\n\t}\n\n\tconst fill = color(\"fill\")\n\tconst text = color(\"color\")\n\n\tif (raw.bold !== undefined && typeof raw.bold !== \"boolean\") {\n\t\tfail(`${path}.bold`, \"must be true or false\")\n\t}\n\n\tconst bold = raw.bold === true\n\n\tif (fill === null && text === null && !bold && !failed) {\n\t\tfail(path, \"colours nothing: give a fill, a colour or bold\")\n\t}\n\n\tif (failed || id === null) {\n\t\treturn null\n\t}\n\n\treturn Object.freeze({ id, when: Object.freeze(when), field, fill, color: text, bold })\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n","import { TabulaError } from \"../errors.js\"\n\n/**\n * The formula language: what a spreadsheet user already writes, minus cell addresses. A formula\n * reads the fields of its own row by key, in brackets, and never runs code: it is parsed into a tree\n * and that tree is evaluated, so no text a user writes is ever executed.\n *\n * ROUND(([newPrice] - [currentPrice]) / [currentPrice] * 100, 1)\n * IF([quantity] > 0, [price] * [quantity], \"\")\n *\n * Numbers use a point, function names are English, arguments are separated by commas or by\n * semicolons, as a Turkish Excel separates them. A leading `=` is allowed and means nothing.\n */\n\nexport type BinaryOperator = \"+\" | \"-\" | \"*\" | \"/\" | \"^\" | \"&\" | \"=\" | \"<>\" | \"<\" | \">\" | \"<=\" | \">=\"\n\nexport type FormulaNode =\n\t| { readonly kind: \"number\"; readonly value: string }\n\t| { readonly kind: \"text\"; readonly value: string }\n\t| { readonly kind: \"bool\"; readonly value: boolean }\n\t| { readonly kind: \"field\"; readonly key: string }\n\t| { readonly kind: \"call\"; readonly name: string; readonly args: readonly FormulaNode[] }\n\t| { readonly kind: \"negate\"; readonly operand: FormulaNode }\n\t| { readonly kind: \"percent\"; readonly operand: FormulaNode }\n\t| { readonly kind: \"binary\"; readonly op: BinaryOperator; readonly left: FormulaNode; readonly right: FormulaNode }\n\ntype Token =\n\t| { readonly kind: \"number\" | \"text\" | \"field\" | \"name\"; readonly text: string; readonly at: number }\n\t| { readonly kind: \"op\"; readonly text: string; readonly at: number }\n\t| { readonly kind: \"end\"; readonly text: \"\"; readonly at: number }\n\n/** Lowest first. Exponents are left to right, and a minus sign binds tighter than them, as in Excel. */\nconst LEVELS: readonly (readonly string[])[] = [[\"=\", \"<>\", \"<\", \">\", \"<=\", \">=\"], [\"&\"], [\"+\", \"-\"], [\"*\", \"/\"], [\"^\"]]\n\n/**\n * Parses a formula.\n *\n * @throws TabulaError `invalid_formula`, saying where the text stopped making sense\n */\nexport function parseFormula(source: string): FormulaNode {\n\tconst tokens = tokenize(source)\n\tlet at = 0\n\tconst peek = (): Token => tokens[at] as Token\n\tconst next = (): Token => tokens[at++] as Token\n\tconst fail = (token: Token, message: string): never => {\n\t\tthrow new TabulaError(\"invalid_formula\", `${message} at character ${token.at + 1} of \"${source}\".`)\n\t}\n\n\tconst binary = (level: number): FormulaNode => {\n\t\tif (level >= LEVELS.length) {\n\t\t\treturn unary()\n\t\t}\n\n\t\tlet left = binary(level + 1)\n\n\t\twhile (peek().kind === \"op\" && (LEVELS[level] as readonly string[]).includes(peek().text)) {\n\t\t\tconst op = next().text as BinaryOperator\n\n\t\t\tleft = Object.freeze({ kind: \"binary\", op, left, right: binary(level + 1) })\n\t\t}\n\n\t\treturn left\n\t}\n\n\tconst unary = (): FormulaNode => {\n\t\tconst token = peek()\n\n\t\tif (token.kind === \"op\" && (token.text === \"-\" || token.text === \"+\")) {\n\t\t\tnext()\n\n\t\t\tconst operand = unary()\n\n\t\t\treturn token.text === \"-\" ? Object.freeze({ kind: \"negate\", operand }) : operand\n\t\t}\n\n\t\treturn postfix()\n\t}\n\n\tconst postfix = (): FormulaNode => {\n\t\tlet node = primary()\n\n\t\twhile (peek().kind === \"op\" && peek().text === \"%\") {\n\t\t\tnext()\n\t\t\tnode = Object.freeze({ kind: \"percent\", operand: node })\n\t\t}\n\n\t\treturn node\n\t}\n\n\tconst primary = (): FormulaNode => {\n\t\tconst token = next()\n\n\t\tswitch (token.kind) {\n\t\t\tcase \"number\":\n\t\t\t\treturn Object.freeze({ kind: \"number\", value: token.text })\n\t\t\tcase \"text\":\n\t\t\t\treturn Object.freeze({ kind: \"text\", value: token.text })\n\t\t\tcase \"field\":\n\t\t\t\treturn Object.freeze({ kind: \"field\", key: token.text })\n\t\t\tcase \"name\": {\n\t\t\t\tconst name = token.text.toUpperCase()\n\n\t\t\t\tif (peek().kind === \"op\" && peek().text === \"(\") {\n\t\t\t\t\tnext()\n\n\t\t\t\t\treturn Object.freeze({ kind: \"call\", name, args: Object.freeze(callArgs()) })\n\t\t\t\t}\n\n\t\t\t\tif (name === \"TRUE\" || name === \"FALSE\") {\n\t\t\t\t\treturn Object.freeze({ kind: \"bool\", value: name === \"TRUE\" })\n\t\t\t\t}\n\n\t\t\t\treturn fail(\n\t\t\t\t\ttoken,\n\t\t\t\t\t`\"${token.text}\" is neither a function, which takes parentheses, nor TRUE or FALSE; a field is written in brackets, [${token.text}]`\n\t\t\t\t)\n\t\t\t}\n\t\t\tcase \"op\":\n\t\t\t\tif (token.text === \"(\") {\n\t\t\t\t\tconst inner = binary(0)\n\n\t\t\t\t\tif (next().text !== \")\") {\n\t\t\t\t\t\tfail(tokens[at - 1] as Token, 'A \")\" is missing')\n\t\t\t\t\t}\n\n\t\t\t\t\treturn inner\n\t\t\t\t}\n\n\t\t\t\treturn fail(token, `\"${token.text}\" cannot start a value`)\n\t\t\tcase \"end\":\n\t\t\t\treturn fail(token, \"The formula ends where a value is expected\")\n\t\t}\n\t}\n\n\tconst callArgs = (): FormulaNode[] => {\n\t\tconst args: FormulaNode[] = []\n\n\t\tif (peek().kind === \"op\" && peek().text === \")\") {\n\t\t\tnext()\n\n\t\t\treturn args\n\t\t}\n\n\t\tfor (;;) {\n\t\t\targs.push(binary(0))\n\n\t\t\tconst token = next()\n\n\t\t\tif (token.kind === \"op\" && token.text === \")\") {\n\t\t\t\treturn args\n\t\t\t}\n\n\t\t\tif (!(token.kind === \"op\" && (token.text === \",\" || token.text === \";\"))) {\n\t\t\t\tfail(token, 'A \",\" or a \")\" is expected')\n\t\t\t}\n\t\t}\n\t}\n\n\tconst tree = binary(0)\n\n\tif (peek().kind !== \"end\") {\n\t\tfail(peek(), `\"${peek().text}\" is not expected here`)\n\t}\n\n\treturn tree\n}\n\n/** The field keys a formula reads, each once, in the order they first appear. */\nexport function formulaFields(node: FormulaNode): string[] {\n\tconst keys = new Set<string>()\n\tconst walk = (current: FormulaNode): void => {\n\t\tswitch (current.kind) {\n\t\t\tcase \"field\":\n\t\t\t\tkeys.add(current.key)\n\t\t\t\tbreak\n\t\t\tcase \"call\":\n\t\t\t\tcurrent.args.forEach(walk)\n\t\t\t\tbreak\n\t\t\tcase \"negate\":\n\t\t\tcase \"percent\":\n\t\t\t\twalk(current.operand)\n\t\t\t\tbreak\n\t\t\tcase \"binary\":\n\t\t\t\twalk(current.left)\n\t\t\t\twalk(current.right)\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\twalk(node)\n\n\treturn [...keys]\n}\n\nconst TWO_CHARACTER = [\"<>\", \"<=\", \">=\"]\nconst ONE_CHARACTER = \"+-*/^&=<>(),;%\"\n\nfunction tokenize(source: string): Token[] {\n\tconst tokens: Token[] = []\n\tlet at = source.trimStart().startsWith(\"=\") ? source.indexOf(\"=\") + 1 : 0\n\n\tconst fail = (where: number, message: string): never => {\n\t\tthrow new TabulaError(\"invalid_formula\", `${message} at character ${where + 1} of \"${source}\".`)\n\t}\n\n\twhile (at < source.length) {\n\t\tconst char = source.charAt(at)\n\n\t\tif (/\\s/.test(char)) {\n\t\t\tat++\n\t\t\tcontinue\n\t\t}\n\n\t\tconst start = at\n\n\t\tif (/\\d/.test(char) || (char === \".\" && /\\d/.test(source.charAt(at + 1)))) {\n\t\t\tconst match = /^\\d*(?:\\.\\d+)?/.exec(source.slice(at)) as RegExpExecArray\n\n\t\t\tat += match[0].length\n\t\t\ttokens.push({ kind: \"number\", text: match[0].startsWith(\".\") ? `0${match[0]}` : match[0], at: start })\n\t\t} else if (char === '\"') {\n\t\t\tlet text = \"\"\n\n\t\t\tat++\n\n\t\t\tfor (;;) {\n\t\t\t\tif (at >= source.length) {\n\t\t\t\t\tfail(start, \"A text is not closed with a quote\")\n\t\t\t\t}\n\n\t\t\t\tconst next = source.charAt(at)\n\n\t\t\t\tif (next === '\"') {\n\t\t\t\t\tif (source.charAt(at + 1) === '\"') {\n\t\t\t\t\t\ttext += '\"'\n\t\t\t\t\t\tat += 2\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tat++\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\ttext += next\n\t\t\t\tat++\n\t\t\t}\n\n\t\t\ttokens.push({ kind: \"text\", text, at: start })\n\t\t} else if (char === \"[\") {\n\t\t\tconst close = source.indexOf(\"]\", at)\n\n\t\t\tif (close < 0) {\n\t\t\t\tfail(start, 'A field is not closed with \"]\"')\n\t\t\t}\n\n\t\t\tconst key = source.slice(at + 1, close).trim()\n\n\t\t\tif (key === \"\") {\n\t\t\t\tfail(start, \"A field has no key between its brackets\")\n\t\t\t}\n\n\t\t\ttokens.push({ kind: \"field\", text: key, at: start })\n\t\t\tat = close + 1\n\t\t} else if (/[A-Za-z_]/.test(char)) {\n\t\t\tconst match = /^[A-Za-z_][A-Za-z0-9_.]*/.exec(source.slice(at)) as RegExpExecArray\n\n\t\t\tat += match[0].length\n\t\t\ttokens.push({ kind: \"name\", text: match[0], at: start })\n\t\t} else if (TWO_CHARACTER.includes(source.slice(at, at + 2))) {\n\t\t\ttokens.push({ kind: \"op\", text: source.slice(at, at + 2), at: start })\n\t\t\tat += 2\n\t\t} else if (ONE_CHARACTER.includes(char)) {\n\t\t\ttokens.push({ kind: \"op\", text: char, at: start })\n\t\t\tat++\n\t\t} else {\n\t\t\tfail(start, `\"${char}\" has no meaning in a formula`)\n\t\t}\n\t}\n\n\ttokens.push({ kind: \"end\", text: \"\", at: source.length })\n\n\treturn tokens\n}\n","import { checkToJson, readChecks, type CheckInput, type RowCheck } from \"./checks.js\"\nimport { readStyleRules, styleRuleToJson, type StyleRule, type StyleRuleInput } from \"./styles.js\"\nimport { compareDecimal, normalizeDecimal } from \"./decimal.js\"\nimport { SchemaError, TabulaError, type SchemaProblem } from \"./errors.js\"\nimport { formulaFields, parseFormula } from \"./formula/parse.js\"\nimport type { CellValue } from \"./value.js\"\nimport { compilePattern } from \"./values/date.js\"\nimport { decimalText } from \"./values/number.js\"\nimport { isFieldValue } from \"./values/read.js\"\n\n/**\n * The module schema: the developer's definition of a sheet, as the backend sends it.\n *\n * It is the same vocabulary as `Field` in nouxwell/tabula, written as JSON: one key per column that\n * never changes, a type, and the rules nobody further down may loosen. A user's template and view\n * are layered on top of it later; nothing here can be overridden by them.\n *\n * A schema this package does not fully understand is refused, not half applied. An unknown property\n * or rule is an error rather than something skipped, because a skipped rule is a rule that quietly\n * stops being checked.\n */\n\nexport const FIELD_TYPES = Object.freeze([\n\t\"string\",\n\t\"integer\",\n\t\"decimal\",\n\t\"money\",\n\t\"quantity\",\n\t\"percent\",\n\t\"bool\",\n\t\"date\",\n\t\"datetime\",\n\t\"options\",\n\t\"lookup\"\n] as const)\n\nexport type FieldType = (typeof FIELD_TYPES)[number]\n\n/** How far a user's template may change the sheet: not at all, within the schema's limits, or freely. */\nexport const CUSTOMIZATIONS = Object.freeze([\"fixed\", \"controlled\", \"free\"] as const)\n\nexport type Customization = (typeof CUSTOMIZATIONS)[number]\n\n/** A limit on a field's value. `min` and `max` are decimal text, so they mean exactly what they say. */\nexport type FieldRule =\n\t| { readonly rule: \"min\" | \"max\"; readonly value: string }\n\t| { readonly rule: \"minLength\" | \"maxLength\"; readonly value: number }\n\t| { readonly rule: \"unique\" }\n\nexport interface FieldOption {\n\t/** What is stored and sent. */\n\treadonly value: string | number\n\t/** What the user reads. */\n\treadonly label: string\n}\n\ninterface FieldBase {\n\t/** The field's identity: what the backend receives and what every rule, issue and formula refers to. */\n\treadonly key: string\n\t/** The column's header. Changing it changes nothing else. */\n\treadonly label: string\n\treadonly required: boolean\n\treadonly editable: boolean\n\t/** Whether the field is part of what is sent for processing. False for a column shown for reference. */\n\treadonly submit: boolean\n\treadonly rules: readonly FieldRule[]\n\t/** A sample value, as text, for the column's help. */\n\treadonly example: string | null\n\t/**\n\t * Worked out from the row's other fields rather than typed, such as\n\t * `ROUND([newPrice] - [currentPrice], 2)`. Such a field is never editable.\n\t */\n\treadonly formula: string | null\n\t/**\n\t * What a new row holds here when nothing else is given, in the form a cell holds it: a number as\n\t * decimal text, a date as ISO text, an option by its value. Null for none. A row the grid or an\n\t * import adds takes it (`withDefaults`); a row already there is never changed by it.\n\t */\n\treadonly default: CellValue | null\n}\n\nexport interface TextField extends FieldBase {\n\treadonly type: \"string\"\n}\n\n/**\n * How a number's own value colours it: `sign` shows a rise in the positive colour, with its plus, and\n * a fall in the negative one, as a change column wants.\n */\nexport type FieldTone = \"sign\"\n\nexport interface IntegerField extends FieldBase {\n\treadonly type: \"integer\"\n\treadonly tone: FieldTone | null\n}\n\nexport interface DecimalField extends FieldBase {\n\treadonly type: \"decimal\" | \"quantity\" | \"percent\"\n\t/** Digits after the point; null leaves it to the sheet's settings for the type. */\n\treadonly decimals: number | null\n\treadonly tone: FieldTone | null\n}\n\nexport interface MoneyField extends FieldBase {\n\treadonly type: \"money\"\n\treadonly decimals: number | null\n\t/** A fixed currency code, or null when the currency comes from elsewhere. */\n\treadonly currency: string | null\n\treadonly tone: FieldTone | null\n}\n\nexport interface BoolField extends FieldBase {\n\treadonly type: \"bool\"\n}\n\nexport interface DateField extends FieldBase {\n\treadonly type: \"date\" | \"datetime\"\n\t/** The field's own pattern in PHP's notation, such as `d.m.Y`; null leaves it to the sheet's settings. */\n\treadonly pattern: string | null\n}\n\nexport interface OptionsField extends FieldBase {\n\treadonly type: \"options\"\n\treadonly options: readonly FieldOption[]\n\t/** Whether a cell holds a list of options rather than one. */\n\treadonly multiple: boolean\n}\n\nexport interface LookupField extends FieldBase {\n\treadonly type: \"lookup\"\n\t/**\n\t * Which lookup the application's adapter is asked, such as `\"product\"`. The cell shows a label and\n\t * sends an id; the adapter is what turns one into the other.\n\t */\n\treadonly lookup: string\n}\n\nexport type FieldSchema =\n\tTextField | IntegerField | DecimalField | MoneyField | BoolField | DateField | OptionsField | LookupField\n\n/** A rule as it is written in the JSON. */\nexport type RuleInput =\n\t| { rule: \"min\" | \"max\"; value: string | number }\n\t| { rule: \"minLength\" | \"maxLength\"; value: number }\n\t| { rule: \"unique\" }\n\nexport interface OptionInput {\n\tvalue: string | number\n\tlabel?: string\n}\n\n/** A field as it is written in the JSON. Which properties a field takes depends on its type. */\nexport interface FieldInput {\n\tkey: string\n\ttype: FieldType\n\tlabel?: string\n\trequired?: boolean\n\teditable?: boolean\n\tsubmit?: boolean\n\trules?: RuleInput[]\n\texample?: string\n\t/** Worked out from the row's other fields; see `FieldSchema.formula`. */\n\tformula?: string\n\t/** A new row's value; see `FieldSchema.default`. Not for a lookup, a formula or a unique field. */\n\tdefault?: string | number | boolean | readonly (string | number)[]\n\t/** decimal, quantity, percent and money */\n\tdecimals?: number\n\t/** money */\n\tcurrency?: string\n\t/** integer, decimal, quantity, percent and money */\n\ttone?: FieldTone\n\t/** options */\n\toptions?: OptionInput[]\n\t/** options */\n\tmultiple?: boolean\n\t/** lookup */\n\tlookup?: string\n\t/** date and datetime */\n\tpattern?: string\n}\n\n/** The module schema as it is written in the JSON. */\nexport interface ModuleSchemaInput {\n\tmodule: string\n\tschemaVersion: number\n\ttitle?: string\n\tcustomization?: Customization\n\tfields: FieldInput[]\n\t/** Rules about a row rather than one cell; see `RowCheck`. */\n\tchecks?: CheckInput[]\n\t/** Cells coloured by what the row holds; see `StyleRule`. */\n\tstyles?: StyleRuleInput[]\n}\n\nconst MODULE_PROPERTIES = [\"module\", \"schemaVersion\", \"title\", \"customization\", \"fields\", \"checks\", \"styles\"]\nconst COMMON_PROPERTIES = [\n\t\"key\",\n\t\"type\",\n\t\"label\",\n\t\"required\",\n\t\"editable\",\n\t\"submit\",\n\t\"rules\",\n\t\"example\",\n\t\"formula\",\n\t\"default\"\n]\n\n/** Kinds of field a formula can fill: a value worked out, never a record or a choice from a list. */\nconst FORMULA_TYPES: readonly FieldType[] = [\n\t\"string\",\n\t\"integer\",\n\t\"decimal\",\n\t\"quantity\",\n\t\"percent\",\n\t\"money\",\n\t\"bool\",\n\t\"date\"\n]\n\nconst TYPE_PROPERTIES: Readonly<Record<FieldType, readonly string[]>> = {\n\tstring: [],\n\tinteger: [\"tone\"],\n\tdecimal: [\"decimals\", \"tone\"],\n\tmoney: [\"decimals\", \"currency\", \"tone\"],\n\tquantity: [\"decimals\", \"tone\"],\n\tpercent: [\"decimals\", \"tone\"],\n\tbool: [],\n\tdate: [\"pattern\"],\n\tdatetime: [\"pattern\"],\n\toptions: [\"options\", \"multiple\"],\n\tlookup: [\"lookup\"]\n}\n\nconst TYPED_PROPERTIES: ReadonlySet<string> = new Set(Object.values(TYPE_PROPERTIES).flat())\nconst NUMERIC_TYPES: ReadonlySet<FieldType> = new Set([\"integer\", \"decimal\", \"money\", \"quantity\", \"percent\"])\nconst RULE_KINDS = [\"min\", \"max\", \"minLength\", \"maxLength\", \"unique\"] as const\n\ntype RuleKind = (typeof RULE_KINDS)[number]\ntype Json = Record<string, unknown>\n\ninterface ModuleData {\n\treadonly module: string\n\treadonly schemaVersion: number\n\treadonly title: string | null\n\treadonly customization: Customization\n\treadonly fields: readonly FieldSchema[]\n\treadonly checks: readonly RowCheck[]\n\treadonly styles: readonly StyleRule[]\n}\n\nexport class ModuleSchema {\n\t/** The module's name, such as `product.price_update`. */\n\treadonly module: string\n\t/** The schema's own version. A draft records it, so a draft made against another version is noticed. */\n\treadonly schemaVersion: number\n\treadonly title: string | null\n\treadonly customization: Customization\n\t/** In the order the backend declared them. */\n\treadonly fields: readonly FieldSchema[]\n\t/** Rules about a row rather than one cell: a field required when another holds a value, two compared. */\n\treadonly checks: readonly RowCheck[]\n\t/** Cells coloured by what the row holds, in order: a later rule is drawn over an earlier one. */\n\treadonly styles: readonly StyleRule[]\n\treadonly #byKey: ReadonlyMap<string, FieldSchema>\n\n\tprivate constructor(data: ModuleData) {\n\t\tthis.module = data.module\n\t\tthis.schemaVersion = data.schemaVersion\n\t\tthis.title = data.title\n\t\tthis.customization = data.customization\n\t\tthis.fields = Object.freeze([...data.fields])\n\t\tthis.checks = Object.freeze([...data.checks])\n\t\tthis.styles = Object.freeze([...data.styles])\n\t\tthis.#byKey = new Map(data.fields.map(field => [field.key, field]))\n\t\tObject.freeze(this)\n\t}\n\n\t/**\n\t * Reads a module schema, typically the JSON the backend sent, and checks all of it.\n\t *\n\t * @throws SchemaError listing every problem found, each with where it is\n\t */\n\tstatic from(input: unknown): ModuleSchema {\n\t\tconst problems = new Problems()\n\t\tconst data = readModule(input, problems)\n\n\t\tif (data === null || problems.items.length > 0) {\n\t\t\tconst name =\n\t\t\t\tisObject(input) && typeof input.module === \"string\" && input.module.trim() !== \"\"\n\t\t\t\t\t? `Module schema \"${input.module}\"`\n\t\t\t\t\t: \"The module schema\"\n\n\t\t\tthrow new SchemaError(name, problems.items)\n\t\t}\n\n\t\treturn new ModuleSchema(data)\n\t}\n\n\thas(key: string): boolean {\n\t\treturn this.#byKey.has(key)\n\t}\n\n\t/** The field with this key. An unknown key is an error rather than undefined: a typo shows up at once. */\n\tfield(key: string): FieldSchema {\n\t\tconst field = this.#byKey.get(key)\n\n\t\tif (!field) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"unknown_field\",\n\t\t\t\t`Module \"${this.module}\" has no field \"${key}\". Its fields are: ${this.keys().join(\", \")}.`\n\t\t\t)\n\t\t}\n\n\t\treturn field\n\t}\n\n\tkeys(): string[] {\n\t\treturn this.fields.map(field => field.key)\n\t}\n\n\t/** The schema written out again as JSON, every default spelled out. `from()` reads it back unchanged. */\n\ttoJSON(): ModuleSchemaInput {\n\t\tconst json: ModuleSchemaInput = {\n\t\t\tmodule: this.module,\n\t\t\tschemaVersion: this.schemaVersion,\n\t\t\tcustomization: this.customization,\n\t\t\tfields: this.fields.map(fieldToJson)\n\t\t}\n\n\t\tif (this.title !== null) {\n\t\t\tjson.title = this.title\n\t\t}\n\n\t\tif (this.checks.length > 0) {\n\t\t\tjson.checks = this.checks.map(checkToJson)\n\t\t}\n\n\t\tif (this.styles.length > 0) {\n\t\t\tjson.styles = this.styles.map(styleRuleToJson)\n\t\t}\n\n\t\treturn json\n\t}\n}\n\nfunction fieldToJson(field: FieldSchema): FieldInput {\n\tconst json: FieldInput = {\n\t\tkey: field.key,\n\t\ttype: field.type,\n\t\tlabel: field.label,\n\t\trequired: field.required,\n\t\teditable: field.editable,\n\t\tsubmit: field.submit\n\t}\n\n\tif (field.rules.length > 0) {\n\t\tjson.rules = field.rules.map(rule => ({ ...rule }))\n\t}\n\n\tif (field.example !== null) {\n\t\tjson.example = field.example\n\t}\n\n\tif (field.formula !== null) {\n\t\tjson.formula = field.formula\n\t}\n\n\tif (field.default !== null) {\n\t\tjson.default = field.default as NonNullable<FieldInput[\"default\"]>\n\t}\n\n\tswitch (field.type) {\n\t\tcase \"integer\":\n\t\t\tif (field.tone !== null) {\n\t\t\t\tjson.tone = field.tone\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\tcase \"percent\":\n\t\t\tif (field.decimals !== null) {\n\t\t\t\tjson.decimals = field.decimals\n\t\t\t}\n\t\t\tif (field.tone !== null) {\n\t\t\t\tjson.tone = field.tone\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"money\":\n\t\t\tif (field.decimals !== null) {\n\t\t\t\tjson.decimals = field.decimals\n\t\t\t}\n\t\t\tif (field.currency !== null) {\n\t\t\t\tjson.currency = field.currency\n\t\t\t}\n\t\t\tif (field.tone !== null) {\n\t\t\t\tjson.tone = field.tone\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"options\":\n\t\t\tjson.options = field.options.map(option => ({ ...option }))\n\t\t\tjson.multiple = field.multiple\n\t\t\tbreak\n\t\tcase \"date\":\n\t\tcase \"datetime\":\n\t\t\tif (field.pattern !== null) {\n\t\t\t\tjson.pattern = field.pattern\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"lookup\":\n\t\t\tjson.lookup = field.lookup\n\t\t\tbreak\n\t}\n\n\treturn json\n}\n\n// ---------------------------------------------------------------- reading\n\nclass Problems {\n\treadonly items: SchemaProblem[] = []\n\n\tadd(path: string, message: string): void {\n\t\tthis.items.push(Object.freeze({ path, message }))\n\t}\n}\n\nfunction readModule(input: unknown, problems: Problems): ModuleData | null {\n\tif (!isObject(input)) {\n\t\tproblems.add(\"(root)\", `must be an object; got ${describe(input)}`)\n\n\t\treturn null\n\t}\n\n\tfor (const name of Object.keys(input)) {\n\t\tif (!MODULE_PROPERTIES.includes(name)) {\n\t\t\tproblems.add(name, `is not a module schema property; expected one of ${MODULE_PROPERTIES.join(\", \")}`)\n\t\t}\n\t}\n\n\tconst module = readText(input, \"module\", \"\", problems, true)\n\tconst schemaVersion = readSchemaVersion(input, problems)\n\tconst title = readText(input, \"title\", \"\", problems, false)\n\tconst customization = readCustomization(input, problems)\n\tconst fields = readFields(input.fields, problems)\n\tconst checks =\n\t\tfields === null ? [] : readChecks(input.checks, fields, (path, message) => problems.add(path, message))\n\n\tconst styles =\n\t\tfields === null ? [] : readStyleRules(input.styles, fields, (path, message) => problems.add(path, message))\n\n\tif (module === null || schemaVersion === null || fields === null) {\n\t\treturn null\n\t}\n\n\treturn { module, schemaVersion, title, customization, fields, checks, styles }\n}\n\nfunction readSchemaVersion(input: Json, problems: Problems): number | null {\n\tconst value = input.schemaVersion\n\n\tif (value === undefined || value === null) {\n\t\tproblems.add(\"schemaVersion\", \"is required\")\n\n\t\treturn null\n\t}\n\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 1) {\n\t\tproblems.add(\"schemaVersion\", `must be a whole number, 1 or more; got ${describe(value)}`)\n\n\t\treturn null\n\t}\n\n\treturn value\n}\n\nfunction readCustomization(input: Json, problems: Problems): Customization {\n\tconst value = input.customization\n\n\tif (value === undefined || value === null) {\n\t\treturn \"fixed\"\n\t}\n\n\tif (typeof value !== \"string\" || !(CUSTOMIZATIONS as readonly string[]).includes(value)) {\n\t\tproblems.add(\n\t\t\t\"customization\",\n\t\t\t`${describe(value)} is not a customization; expected one of ${CUSTOMIZATIONS.join(\", \")}`\n\t\t)\n\n\t\treturn \"fixed\"\n\t}\n\n\treturn value as Customization\n}\n\nfunction readFields(value: unknown, problems: Problems): FieldSchema[] | null {\n\tif (value === undefined || value === null) {\n\t\tproblems.add(\"fields\", \"is required\")\n\n\t\treturn null\n\t}\n\n\tif (!Array.isArray(value) || value.length === 0) {\n\t\tproblems.add(\"fields\", `must be a non-empty array of fields; got ${describe(value)}`)\n\n\t\treturn null\n\t}\n\n\tconst items = value as unknown[]\n\tconst firstIndex = new Map<string, number>()\n\n\titems.forEach((raw, index) => {\n\t\tif (!isObject(raw) || typeof raw.key !== \"string\") {\n\t\t\treturn\n\t\t}\n\n\t\tconst first = firstIndex.get(raw.key)\n\n\t\tif (first === undefined) {\n\t\t\tfirstIndex.set(raw.key, index)\n\t\t} else {\n\t\t\tproblems.add(\n\t\t\t\t`fields[${index}].key`,\n\t\t\t\t`\"${raw.key}\" is already the key of fields[${first}]; a key names one field only`\n\t\t\t)\n\t\t}\n\t})\n\n\tconst fields: FieldSchema[] = []\n\n\titems.forEach((raw, index) => {\n\t\tconst field = readField(raw, `fields[${index}]`, problems)\n\n\t\tif (field) {\n\t\t\tfields.push(field)\n\t\t}\n\t})\n\n\tcheckFormulas(fields, firstIndex, problems)\n\n\treturn fields\n}\n\n/**\n * Every formula parses, reads only fields the schema has, never itself, and no formula reads, through\n * others, the field it fills: a circle has no value to start from.\n */\nfunction checkFormulas(fields: readonly FieldSchema[], indexOf: ReadonlyMap<string, number>, problems: Problems): void {\n\tconst keys = new Set(fields.map(field => field.key))\n\tconst reads = new Map<string, string[]>()\n\n\tfor (const field of fields) {\n\t\tif (field.formula === null) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst path = `fields[${indexOf.get(field.key) ?? 0}].formula`\n\t\tlet fieldsRead: string[]\n\n\t\ttry {\n\t\t\tfieldsRead = formulaFields(parseFormula(field.formula))\n\t\t} catch (error) {\n\t\t\tproblems.add(path, error instanceof Error ? error.message : String(error))\n\t\t\tcontinue\n\t\t}\n\n\t\tfor (const key of fieldsRead) {\n\t\t\tif (key === field.key) {\n\t\t\t\tproblems.add(path, `reads [${key}], the field it fills`)\n\t\t\t} else if (!keys.has(key)) {\n\t\t\t\tproblems.add(path, `reads [${key}], which is not a field of this schema`)\n\t\t\t}\n\t\t}\n\n\t\treads.set(\n\t\t\tfield.key,\n\t\t\tfieldsRead.filter(key => key !== field.key)\n\t\t)\n\t}\n\n\t// A depth-first walk over the formulas: meeting a field still on the path is a circle.\n\tconst done = new Set<string>()\n\tconst reported = new Set<string>()\n\tconst walk = (key: string, path: string[]): void => {\n\t\tif (done.has(key)) {\n\t\t\treturn\n\t\t}\n\n\t\tconst at = path.indexOf(key)\n\n\t\tif (at >= 0) {\n\t\t\tconst circle = [...path.slice(at), key]\n\n\t\t\tif (!circle.some(member => reported.has(member))) {\n\t\t\t\tcircle.forEach(member => reported.add(member))\n\t\t\t\tproblems.add(\n\t\t\t\t\t`fields[${indexOf.get(key) ?? 0}].formula`,\n\t\t\t\t\t`is part of a circle of formulas: ${circle.map(member => `[${member}]`).join(\" → \")}`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tfor (const next of reads.get(key) ?? []) {\n\t\t\tif (reads.has(next)) {\n\t\t\t\twalk(next, [...path, key])\n\t\t\t}\n\t\t}\n\n\t\tdone.add(key)\n\t}\n\n\tfor (const key of reads.keys()) {\n\t\twalk(key, [])\n\t}\n}\n\nfunction readField(raw: unknown, path: string, problems: Problems): FieldSchema | null {\n\tif (!isObject(raw)) {\n\t\tproblems.add(path, `must be an object; got ${describe(raw)}`)\n\n\t\treturn null\n\t}\n\n\tconst before = problems.items.length\n\tconst type = readType(raw, path, problems)\n\n\tcheckFieldProperties(raw, type, path, problems)\n\n\tconst key = readKey(raw, path, problems)\n\tconst label = readText(raw, \"label\", path, problems, false)\n\tconst required = readBoolean(raw, \"required\", false, path, problems)\n\tconst editable = readBoolean(raw, \"editable\", true, path, problems)\n\tconst submit = readBoolean(raw, \"submit\", true, path, problems)\n\tconst example = readText(raw, \"example\", path, problems, false)\n\tconst formula = readText(raw, \"formula\", path, problems, false)\n\tconst rules = readRules(raw.rules, at(path, \"rules\"), type, problems)\n\n\tif (type === null || key === null) {\n\t\treturn null\n\t}\n\n\tif (formula !== null && !FORMULA_TYPES.includes(type)) {\n\t\tproblems.add(\n\t\t\tat(path, \"formula\"),\n\t\t\t`cannot fill ${aFieldOf(type)}; a formula works out a text, a number, a date or yes and no`\n\t\t)\n\t}\n\n\t// A value worked out is not typed over: a formula field is never editable, whatever it says.\n\tconst base = {\n\t\tkey,\n\t\tlabel: label ?? key,\n\t\trequired,\n\t\teditable: formula === null && editable,\n\t\tsubmit,\n\t\trules: Object.freeze(rules),\n\t\texample,\n\t\tformula,\n\t\tdefault: null\n\t}\n\tlet field: FieldSchema\n\n\tswitch (type) {\n\t\tcase \"string\":\n\t\tcase \"bool\":\n\t\t\tfield = { ...base, type }\n\t\t\tbreak\n\t\tcase \"integer\":\n\t\t\tfield = { ...base, type, tone: readTone(raw, path, problems) }\n\t\t\tbreak\n\t\tcase \"date\":\n\t\tcase \"datetime\":\n\t\t\tfield = { ...base, type, pattern: readPattern(raw, path, problems) }\n\t\t\tbreak\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\tcase \"percent\":\n\t\t\tfield = { ...base, type, decimals: readDecimals(raw, path, problems), tone: readTone(raw, path, problems) }\n\t\t\tbreak\n\t\tcase \"money\":\n\t\t\tfield = {\n\t\t\t\t...base,\n\t\t\t\ttype,\n\t\t\t\tdecimals: readDecimals(raw, path, problems),\n\t\t\t\tcurrency: readText(raw, \"currency\", path, problems, false),\n\t\t\t\ttone: readTone(raw, path, problems)\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"options\":\n\t\t\tfield = {\n\t\t\t\t...base,\n\t\t\t\ttype,\n\t\t\t\toptions: Object.freeze(readOptions(raw.options, at(path, \"options\"), problems)),\n\t\t\t\tmultiple: readBoolean(raw, \"multiple\", false, path, problems)\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"lookup\":\n\t\t\tfield = { ...base, type, lookup: readText(raw, \"lookup\", path, problems, true) ?? \"\" }\n\t\t\tbreak\n\t}\n\n\tif (problems.items.length > before) {\n\t\treturn null\n\t}\n\n\tconst fallback = readDefault(raw, field, path, problems)\n\n\treturn problems.items.length > before ? null : Object.freeze({ ...field, default: fallback })\n}\n\n/**\n * A field's default, checked as a value of the field: its type, its options, its limits. A lookup\n * takes none (a record is an id the backend gives), nor does a formula (its value is worked out),\n * nor a unique field (every new row would hold the same value).\n */\nfunction readDefault(raw: Json, field: FieldSchema, path: string, problems: Problems): CellValue | null {\n\tconst value = raw.default\n\tconst where = at(path, \"default\")\n\n\tif (value === undefined || value === null) {\n\t\treturn null\n\t}\n\n\tif (field.type === \"lookup\" || field.formula !== null || field.rules.some(rule => rule.rule === \"unique\")) {\n\t\tconst why =\n\t\t\tfield.type === \"lookup\"\n\t\t\t\t? \"a lookup's value is a record the backend gives\"\n\t\t\t\t: field.formula !== null\n\t\t\t\t\t? \"its value is worked out by its formula\"\n\t\t\t\t\t: \"every new row would hold the same value, and it is unique\"\n\n\t\tproblems.add(where, `cannot be given: ${why}`)\n\n\t\treturn null\n\t}\n\n\t// A number is kept as decimal text, as every cell of a numeric field holds one.\n\tconst given = NUMERIC_TYPES.has(field.type) ? (decimalText(value) ?? value) : value\n\n\tif (!isFieldValue(field, given as CellValue)) {\n\t\tproblems.add(where, `${describe(value)} is not a value of ${aFieldOf(field.type)}${hint(field)}`)\n\n\t\treturn null\n\t}\n\n\tconst broken = brokenRule(field, given as CellValue)\n\n\tif (broken !== null) {\n\t\tproblems.add(where, `${describe(value)} breaks the field's ${broken} rule`)\n\n\t\treturn null\n\t}\n\n\treturn Array.isArray(given) ? (Object.freeze([...(given as unknown[])]) as CellValue) : (given as CellValue)\n}\n\nfunction hint(field: FieldSchema): string {\n\tswitch (field.type) {\n\t\tcase \"options\":\n\t\t\treturn `; it takes ${field.multiple ? \"a list of \" : \"one of \"}${field.options.map(option => JSON.stringify(option.value)).join(\", \")}`\n\t\tcase \"date\":\n\t\t\treturn '; write it as \"2026-12-31\"'\n\t\tcase \"datetime\":\n\t\t\treturn '; write it as \"2026-12-31T09:30:00\"'\n\t\tcase \"bool\":\n\t\t\treturn \"; it takes true or false\"\n\t\tdefault:\n\t\t\treturn NUMERIC_TYPES.has(field.type) ? '; write it as a number or decimal text, such as \"12.5\"' : \"\"\n\t}\n}\n\n/** The first of the field's limits the value breaks, or null. */\nfunction brokenRule(field: FieldSchema, value: CellValue): string | null {\n\tfor (const rule of field.rules) {\n\t\tif ((rule.rule === \"min\" || rule.rule === \"max\") && typeof value === \"string\") {\n\t\t\tconst order = compareDecimal(normalizeDecimal(value) ?? value, rule.value)\n\n\t\t\tif (rule.rule === \"min\" ? order < 0 : order > 0) {\n\t\t\t\treturn `${rule.rule} ${rule.value}`\n\t\t\t}\n\t\t}\n\n\t\tif ((rule.rule === \"minLength\" || rule.rule === \"maxLength\") && typeof value === \"string\") {\n\t\t\tconst length = [...value].length\n\n\t\t\tif (rule.rule === \"minLength\" ? length < rule.value : length > rule.value) {\n\t\t\t\treturn `${rule.rule} ${rule.value}`\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null\n}\n\nfunction readType(raw: Json, path: string, problems: Problems): FieldType | null {\n\tconst value = raw.type\n\n\tif (value === undefined || value === null) {\n\t\tproblems.add(at(path, \"type\"), \"is required\")\n\n\t\treturn null\n\t}\n\n\tif (typeof value !== \"string\" || !(FIELD_TYPES as readonly string[]).includes(value)) {\n\t\tproblems.add(\n\t\t\tat(path, \"type\"),\n\t\t\t`${describe(value)} is not a field type; expected one of ${FIELD_TYPES.join(\", \")}`\n\t\t)\n\n\t\treturn null\n\t}\n\n\treturn value as FieldType\n}\n\nfunction checkFieldProperties(raw: Json, type: FieldType | null, path: string, problems: Problems): void {\n\tconst allowed = new Set([...COMMON_PROPERTIES, ...(type === null ? TYPED_PROPERTIES : TYPE_PROPERTIES[type])])\n\n\tfor (const name of Object.keys(raw)) {\n\t\tif (allowed.has(name)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif (type !== null && TYPED_PROPERTIES.has(name)) {\n\t\t\tproblems.add(at(path, name), `does not apply to ${aFieldOf(type)}`)\n\t\t} else if (type !== null) {\n\t\t\tproblems.add(at(path, name), `is not a field property; ${aFieldOf(type)} takes ${[...allowed].join(\", \")}`)\n\t\t} else {\n\t\t\tproblems.add(at(path, name), \"is not a field property\")\n\t\t}\n\t}\n}\n\nfunction readKey(raw: Json, path: string, problems: Problems): string | null {\n\tconst key = readText(raw, \"key\", path, problems, true)\n\n\tif (key !== null && key.trim() !== key) {\n\t\tproblems.add(at(path, \"key\"), `\"${key}\" starts or ends with a space; a key is an identifier, not a label`)\n\n\t\treturn null\n\t}\n\n\treturn key\n}\n\nfunction readPattern(raw: Json, path: string, problems: Problems): string | null {\n\tconst pattern = readText(raw, \"pattern\", path, problems, false)\n\n\tif (pattern !== null && compilePattern(pattern) === null) {\n\t\tproblems.add(\n\t\t\tat(path, \"pattern\"),\n\t\t\t`\"${pattern}\" uses a letter that is not one of d, j, m, n, Y, y, H, G, i, s; write other letters with a backslash before them`\n\t\t)\n\n\t\treturn null\n\t}\n\n\treturn pattern\n}\n\nfunction readDecimals(raw: Json, path: string, problems: Problems): number | null {\n\tconst value = raw.decimals\n\n\tif (value === undefined || value === null) {\n\t\treturn null\n\t}\n\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n\t\tproblems.add(at(path, \"decimals\"), `must be a whole number, 0 or more; got ${describe(value)}`)\n\n\t\treturn null\n\t}\n\n\treturn value\n}\n\nfunction readTone(raw: Json, path: string, problems: Problems): FieldTone | null {\n\tconst value = raw.tone\n\n\tif (value === undefined || value === null) {\n\t\treturn null\n\t}\n\n\tif (value !== \"sign\") {\n\t\tproblems.add(at(path, \"tone\"), `must be \"sign\"; got ${describe(value)}`)\n\n\t\treturn null\n\t}\n\n\treturn value\n}\n\nfunction readOptions(value: unknown, path: string, problems: Problems): FieldOption[] {\n\tif (value === undefined || value === null) {\n\t\tproblems.add(path, \"is required for an options field\")\n\n\t\treturn []\n\t}\n\n\tif (!Array.isArray(value)) {\n\t\tproblems.add(path, `must be an array of options; got ${describe(value)}`)\n\n\t\treturn []\n\t}\n\n\tconst options: FieldOption[] = []\n\t// By their text: an option 1 and an option \"1\" cannot be told apart once pasted into a cell.\n\tconst firstIndex = new Map<string, number>()\n\n\t;(value as unknown[]).forEach((raw, index) => {\n\t\tconst optionPath = `${path}[${index}]`\n\n\t\tif (!isObject(raw)) {\n\t\t\tproblems.add(optionPath, `must be an object such as { \"value\": \"in\", \"label\": \"In\" }; got ${describe(raw)}`)\n\n\t\t\treturn\n\t\t}\n\n\t\tfor (const name of Object.keys(raw)) {\n\t\t\tif (name !== \"value\" && name !== \"label\") {\n\t\t\t\tproblems.add(at(optionPath, name), \"is not an option property; an option takes value, label\")\n\t\t\t}\n\t\t}\n\n\t\tconst optionValue = raw.value\n\n\t\tif (\n\t\t\t!(typeof optionValue === \"string\" && optionValue !== \"\") &&\n\t\t\t!(typeof optionValue === \"number\" && Number.isFinite(optionValue))\n\t\t) {\n\t\t\tproblems.add(\n\t\t\t\tat(optionPath, \"value\"),\n\t\t\t\t`must be a non-empty string or a finite number; got ${describe(optionValue)}`\n\t\t\t)\n\n\t\t\treturn\n\t\t}\n\n\t\tconst text = String(optionValue)\n\t\tconst first = firstIndex.get(text)\n\n\t\tif (first !== undefined) {\n\t\t\tproblems.add(at(optionPath, \"value\"), `${describe(optionValue)} is already the value of ${path}[${first}]`)\n\n\t\t\treturn\n\t\t}\n\n\t\tfirstIndex.set(text, index)\n\n\t\tconst label = readText(raw, \"label\", optionPath, problems, false)\n\n\t\toptions.push(Object.freeze({ value: optionValue, label: label ?? text }))\n\t})\n\n\treturn options\n}\n\nfunction readRules(value: unknown, path: string, type: FieldType | null, problems: Problems): FieldRule[] {\n\tif (value === undefined || value === null) {\n\t\treturn []\n\t}\n\n\tif (!Array.isArray(value)) {\n\t\tproblems.add(path, `must be an array of rules; got ${describe(value)}`)\n\n\t\treturn []\n\t}\n\n\tconst rules: FieldRule[] = []\n\tconst firstIndex = new Map<RuleKind, number>()\n\n\t;(value as unknown[]).forEach((raw, index) => {\n\t\tconst rulePath = `${path}[${index}]`\n\t\tconst rule = readRule(raw, rulePath, type, problems)\n\n\t\tif (!rule) {\n\t\t\treturn\n\t\t}\n\n\t\tconst first = firstIndex.get(rule.rule)\n\n\t\tif (first !== undefined) {\n\t\t\tproblems.add(rulePath, `${rule.rule} is already given at ${path}[${first}]; give each rule once`)\n\n\t\t\treturn\n\t\t}\n\n\t\tfirstIndex.set(rule.rule, index)\n\t\trules.push(rule)\n\t})\n\n\tconst min = limitOf(rules, \"min\")\n\tconst max = limitOf(rules, \"max\")\n\n\tif (min !== undefined && max !== undefined && compareDecimal(min, max) > 0) {\n\t\tproblems.add(path, `min ${min} is above max ${max}; no value can satisfy both`)\n\t}\n\n\tconst minLength = lengthOf(rules, \"minLength\")\n\tconst maxLength = lengthOf(rules, \"maxLength\")\n\n\tif (minLength !== undefined && maxLength !== undefined && minLength > maxLength) {\n\t\tproblems.add(path, `minLength ${minLength} is above maxLength ${maxLength}; no text can satisfy both`)\n\t}\n\n\treturn rules\n}\n\nfunction limitOf(rules: readonly FieldRule[], kind: \"min\" | \"max\"): string | undefined {\n\tfor (const rule of rules) {\n\t\tif ((rule.rule === \"min\" || rule.rule === \"max\") && rule.rule === kind) {\n\t\t\treturn rule.value\n\t\t}\n\t}\n\n\treturn undefined\n}\n\nfunction lengthOf(rules: readonly FieldRule[], kind: \"minLength\" | \"maxLength\"): number | undefined {\n\tfor (const rule of rules) {\n\t\tif ((rule.rule === \"minLength\" || rule.rule === \"maxLength\") && rule.rule === kind) {\n\t\t\treturn rule.value\n\t\t}\n\t}\n\n\treturn undefined\n}\n\nfunction readRule(raw: unknown, path: string, type: FieldType | null, problems: Problems): FieldRule | null {\n\tif (!isObject(raw)) {\n\t\tproblems.add(path, `must be an object such as { \"rule\": \"min\", \"value\": \"0\" }; got ${describe(raw)}`)\n\n\t\treturn null\n\t}\n\n\tconst kind = raw.rule\n\n\tif (typeof kind !== \"string\" || !(RULE_KINDS as readonly string[]).includes(kind)) {\n\t\tproblems.add(at(path, \"rule\"), `${describe(kind)} is not a rule; expected one of ${RULE_KINDS.join(\", \")}`)\n\n\t\treturn null\n\t}\n\n\tconst rule = kind as RuleKind\n\n\tfor (const name of Object.keys(raw)) {\n\t\tif (name === \"rule\" || (name === \"value\" && rule !== \"unique\")) {\n\t\t\tcontinue\n\t\t}\n\n\t\tproblems.add(\n\t\t\tat(path, name),\n\t\t\trule === \"unique\" && name === \"value\" ? \"unique takes no value\" : `is not a property of a ${rule} rule`\n\t\t)\n\t}\n\n\tif (type !== null && !ruleApplies(rule, type)) {\n\t\tproblems.add(path, `${rule} does not apply to ${aFieldOf(type)}`)\n\n\t\treturn null\n\t}\n\n\tconst value = raw.value\n\n\tswitch (rule) {\n\t\tcase \"min\":\n\t\tcase \"max\": {\n\t\t\tconst limit = typeof value === \"string\" || typeof value === \"number\" ? normalizeDecimal(value) : null\n\n\t\t\tif (limit === null) {\n\t\t\t\tproblems.add(\n\t\t\t\t\tat(path, \"value\"),\n\t\t\t\t\tvalue === undefined\n\t\t\t\t\t\t? \"is required\"\n\t\t\t\t\t\t: `must be a decimal number such as \"0\" or \"12.5\", with a point and no exponent; got ${describe(value)}`\n\t\t\t\t)\n\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\treturn Object.freeze({ rule, value: limit })\n\t\t}\n\t\tcase \"minLength\":\n\t\tcase \"maxLength\":\n\t\t\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n\t\t\t\tproblems.add(\n\t\t\t\t\tat(path, \"value\"),\n\t\t\t\t\tvalue === undefined\n\t\t\t\t\t\t? \"is required\"\n\t\t\t\t\t\t: `must be a whole number of characters, 0 or more; got ${describe(value)}`\n\t\t\t\t)\n\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\treturn Object.freeze({ rule, value })\n\t\tcase \"unique\":\n\t\t\treturn Object.freeze({ rule })\n\t}\n}\n\nfunction ruleApplies(rule: RuleKind, type: FieldType): boolean {\n\tswitch (rule) {\n\t\tcase \"min\":\n\t\tcase \"max\":\n\t\t\treturn NUMERIC_TYPES.has(type)\n\t\tcase \"minLength\":\n\t\tcase \"maxLength\":\n\t\t\treturn type === \"string\"\n\t\tcase \"unique\":\n\t\t\treturn true\n\t}\n}\n\nfunction readText(source: Json, name: string, path: string, problems: Problems, required: boolean): string | null {\n\tconst value = source[name]\n\n\tif (value === undefined || value === null) {\n\t\tif (required) {\n\t\t\tproblems.add(at(path, name), \"is required\")\n\t\t}\n\n\t\treturn null\n\t}\n\n\tif (typeof value !== \"string\" || value.trim() === \"\") {\n\t\tproblems.add(at(path, name), `must be a non-empty string; got ${describe(value)}`)\n\n\t\treturn null\n\t}\n\n\treturn value\n}\n\nfunction readBoolean(source: Json, name: string, fallback: boolean, path: string, problems: Problems): boolean {\n\tconst value = source[name]\n\n\tif (value === undefined || value === null) {\n\t\treturn fallback\n\t}\n\n\tif (typeof value !== \"boolean\") {\n\t\tproblems.add(at(path, name), `must be true or false; got ${describe(value)}`)\n\n\t\treturn fallback\n\t}\n\n\treturn value\n}\n\n/** \"a money field\", \"an integer field\". */\nfunction aFieldOf(type: FieldType): string {\n\treturn `${/^[aeiou]/.test(type) ? \"an\" : \"a\"} ${type} field`\n}\n\nfunction isObject(value: unknown): value is Json {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction at(path: string, name: string): string {\n\treturn path === \"\" ? name : `${path}.${name}`\n}\n\nfunction describe(value: unknown): string {\n\tif (value === undefined) {\n\t\treturn \"nothing\"\n\t}\n\n\tif (Array.isArray(value)) {\n\t\treturn \"an array\"\n\t}\n\n\tif (typeof value === \"object\" && value !== null) {\n\t\treturn \"an object\"\n\t}\n\n\treturn JSON.stringify(value) ?? String(value)\n}\n","/**\n * A random part for ids such as row ids and request ids: 7 base-36 characters drawn from\n * `crypto.getRandomValues`, which, unlike `randomUUID`, also works on plain http.\n */\nexport function randomPart(): string {\n\tconst scope = globalThis as { crypto?: { getRandomValues?: (array: Uint32Array) => Uint32Array } }\n\tconst word = new Uint32Array(1)\n\n\tif (typeof scope.crypto?.getRandomValues === \"function\") {\n\t\tscope.crypto.getRandomValues(word)\n\t} else {\n\t\tword[0] = Math.floor(Math.random() * 2 ** 32)\n\t}\n\n\treturn (word[0] ?? 0).toString(36).padStart(7, \"0\")\n}\n\n/** Ids such as `r_1k3x9q2_1`: a random part drawn once, then a counter. */\nexport function sequence(prefix: string): () => string {\n\tconst random = randomPart()\n\tlet counter = 0\n\n\treturn () => `${prefix}_${random}_${(++counter).toString(36)}`\n}\n","import { TabulaError } from \"./errors.js\"\n\n/**\n * What a cell holds.\n *\n * Anything JSON can carry, and nothing else. A draft is the store's own content written out, so a\n * value that does not survive `JSON.stringify` would come back from a draft as something else, or\n * not at all: a `Date` as a string, a `Map` as `{}`, `NaN` as `null`.\n */\nexport type CellValue = null | boolean | number | string | readonly CellValue[] | CellObject\n\nexport interface CellObject {\n\treadonly [key: string]: CellValue\n}\n\nconst MAX_DEPTH = 32\n\n/**\n * A frozen copy of the input as a cell value, or an error saying why it cannot be one.\n *\n * A copy, so a caller who changes their array afterwards does not change the sheet behind its back.\n * Frozen, so a caller holding what the sheet returned cannot either. `undefined` is an empty cell,\n * `-0` is `0`, and an object's `undefined` properties are dropped: what `JSON.stringify` does.\n *\n * @param subject how the error names the value, such as `The value of \"price\" in row \"r_7\"`\n */\nexport function toCellValue(input: unknown, subject = \"A cell value\"): CellValue {\n\treturn convert(input, subject, 0)\n}\n\nfunction convert(input: unknown, subject: string, depth: number): CellValue {\n\tif (input === null || input === undefined) {\n\t\treturn null\n\t}\n\n\tswitch (typeof input) {\n\t\tcase \"boolean\":\n\t\tcase \"string\":\n\t\t\treturn input\n\t\tcase \"number\":\n\t\t\tif (!Number.isFinite(input)) {\n\t\t\t\tthrow refused(subject, String(input))\n\t\t\t}\n\n\t\t\t// JSON writes -0 as 0. Kept as -0, two cells that read the same would not be equal.\n\t\t\treturn input === 0 ? 0 : input\n\t\tcase \"object\":\n\t\t\tbreak\n\t\tdefault:\n\t\t\tthrow refused(subject, `a ${typeof input}`)\n\t}\n\n\tif (depth >= MAX_DEPTH) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_value\",\n\t\t\t`${subject} is nested more than ${MAX_DEPTH} levels deep. A value that contains itself never ends.`\n\t\t)\n\t}\n\n\tif (Array.isArray(input)) {\n\t\t// Array.from, not map: map skips the holes of a sparse array and keeps them as holes.\n\t\treturn Object.freeze(Array.from(input as unknown[], item => convert(item, subject, depth + 1)))\n\t}\n\n\tconst prototype: unknown = Object.getPrototypeOf(input)\n\n\tif (prototype !== Object.prototype && prototype !== null) {\n\t\tconst name = (input as { constructor?: { name?: string } }).constructor?.name\n\n\t\tthrow refused(subject, name ? `a ${name}` : \"an object that is not a plain object\")\n\t}\n\n\t// No prototype: a key named \"__proto__\" is then an ordinary key rather than a way to replace it.\n\tconst copy = Object.create(null) as Record<string, CellValue>\n\n\tfor (const [key, item] of Object.entries(input)) {\n\t\tif (item !== undefined) {\n\t\t\tcopy[key] = convert(item, subject, depth + 1)\n\t\t}\n\t}\n\n\treturn Object.freeze(copy)\n}\n\nfunction refused(subject: string, got: string): TabulaError {\n\treturn new TabulaError(\n\t\t\"invalid_value\",\n\t\t`${subject} must be null, a boolean, a finite number, a string, or an array or plain object of these; got ${got}.`\n\t)\n}\n\n/** Whether two cell values are the same, comparing arrays and objects by content. */\nexport function sameValue(a: CellValue, b: CellValue): boolean {\n\tif (a === b) {\n\t\treturn true\n\t}\n\n\tif (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) {\n\t\treturn false\n\t}\n\n\tif (Array.isArray(a) || Array.isArray(b)) {\n\t\tif (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst other: readonly CellValue[] = b\n\n\t\treturn a.every((item: CellValue, index) => sameValue(item, other[index] ?? null))\n\t}\n\n\tconst left = a as CellObject\n\tconst right = b as CellObject\n\tconst keys = Object.keys(left)\n\n\tif (keys.length !== Object.keys(right).length) {\n\t\treturn false\n\t}\n\n\treturn keys.every(key => Object.hasOwn(right, key) && sameValue(left[key] ?? null, right[key] ?? null))\n}\n","import { TabulaError } from \"./errors.js\"\nimport { sequence } from \"./ids.js\"\nimport { Listeners } from \"./listeners.js\"\nimport { sameValue, toCellValue, type CellValue } from \"./value.js\"\n\n/**\n * A row's identity: the same from the moment the row is created until it is deleted, whatever is\n * sorted, filtered, inserted or pasted around it.\n *\n * It is not a database id and not a position. Every issue, result and formula refers to a row by\n * this id, which is what keeps \"row 37\" from meaning a different row after a sort.\n */\nexport type RowId = string\n\n/** A cell value per field key. A field with no entry is an empty cell. */\nexport type RowValues = Readonly<Record<string, CellValue>>\n\nexport interface RowInit {\n\t/** The id to keep, such as one read back from a draft. Left out, the store makes one. */\n\treadonly rowId?: RowId\n\treadonly values?: Readonly<Record<string, CellValue | undefined>>\n}\n\nexport interface RowEntry {\n\treadonly rowId: RowId\n\treadonly values: RowValues\n}\n\nexport interface RemovedRow extends RowEntry {\n\t/** Where the row stood before the removal. */\n\treadonly index: number\n}\n\n/**\n * One step of a change, carrying what it needs to be undone.\n *\n * `insert` puts a run of rows in at one place. `remove` takes rows out from anywhere, listed in the\n * order they stood; putting each back at its `index`, in that order, restores the sheet exactly.\n */\nexport type StoreOperation =\n\t| {\n\t\t\treadonly kind: \"set\"\n\t\t\treadonly rowId: RowId\n\t\t\treadonly field: string\n\t\t\treadonly before: CellValue\n\t\t\treadonly after: CellValue\n\t }\n\t| { readonly kind: \"insert\"; readonly index: number; readonly rows: readonly RowEntry[] }\n\t| { readonly kind: \"remove\"; readonly rows: readonly RemovedRow[] }\n\nexport interface StoreChange {\n\t/** The store's revision after this change. */\n\treadonly revision: number\n\t/** What the change was for, as given to `transact()`, such as `\"paste\"`. */\n\treadonly origin: string | null\n\t/** In the order they were made. */\n\treadonly operations: readonly StoreOperation[]\n}\n\nexport interface TransactOptions {\n\treadonly origin?: string\n}\n\nexport interface CellWrite {\n\treadonly rowId: RowId\n\treadonly field: string\n\treadonly value: CellValue | undefined\n}\n\nexport interface RowStoreOptions {\n\treadonly rows?: readonly RowInit[]\n\t/** Makes the id of a new row. The default is unique within the page and very unlikely to repeat across sessions. */\n\treadonly createRowId?: () => RowId\n}\n\ntype MutableRow = Record<string, CellValue>\n\n/**\n * The rows of one sheet, each under an id of its own.\n *\n * Plain data, kept out of any framework's reactivity: a view learns about changes by subscribing,\n * and redraws what the change touched. Every change is a transaction with a revision number, so a\n * backend answer can say which state of the sheet it checked.\n *\n * Only cells that hold something are kept. An empty cell is no entry at all, so a sheet of 50,000\n * mostly empty rows costs what its contents cost.\n */\nexport class RowStore {\n\t#order: RowId[] = []\n\treadonly #rows = new Map<RowId, MutableRow>()\n\t#positions: Map<RowId, number> | null = null\n\t#revision = 0\n\t#log: StoreOperation[] | null = null\n\treadonly #createRowId: () => RowId\n\treadonly #listeners = new Listeners<StoreChange>()\n\treadonly #derivers = new Set<(operations: readonly StoreOperation[]) => void>()\n\n\tconstructor(options: RowStoreOptions = {}) {\n\t\tthis.#createRowId = options.createRowId ?? sessionRowIds()\n\n\t\tfor (const { rowId, row } of this.#prepare(options.rows ?? [])) {\n\t\t\tthis.#rows.set(rowId, row)\n\t\t\tthis.#order.push(rowId)\n\t\t}\n\t}\n\n\t// ---------------------------------------------------------------- reading\n\n\t/** Counts changes: 0 for a new store, one more for each transaction that changed something. */\n\tget revision(): number {\n\t\treturn this.#revision\n\t}\n\n\tget size(): number {\n\t\treturn this.#order.length\n\t}\n\n\thas(rowId: RowId): boolean {\n\t\treturn this.#rows.has(rowId)\n\t}\n\n\trowIdAt(index: number): RowId | undefined {\n\t\treturn this.#order[index]\n\t}\n\n\t/** Where the row stands, or -1 when there is no such row. */\n\tindexOf(rowId: RowId): number {\n\t\tif (this.#positions === null) {\n\t\t\tthis.#positions = new Map(this.#order.map((id, index) => [id, index]))\n\t\t}\n\n\t\treturn this.#positions.get(rowId) ?? -1\n\t}\n\n\t/** Every row id, in order. A copy: O(rows), so a view drawing one screen reads `rowIdAt()` instead. */\n\trowIds(): RowId[] {\n\t\treturn [...this.#order]\n\t}\n\n\t/** The cell's value; null when it is empty. */\n\tget(rowId: RowId, field: string): CellValue {\n\t\treturn this.#row(rowId)[field] ?? null\n\t}\n\n\t/** The row's cells that hold something, as a frozen copy. */\n\tvalues(rowId: RowId): RowValues {\n\t\treturn frozenCopy(this.#row(rowId))\n\t}\n\n\t/** Every row with its id and values, in order: what a draft keeps. It survives `JSON.stringify` as it is. */\n\tsnapshot(): RowEntry[] {\n\t\treturn this.#order.map(rowId => Object.freeze({ rowId, values: frozenCopy(this.#row(rowId)) }))\n\t}\n\n\t/** Called after each transaction that changed something. Returns the way to stop. */\n\tsubscribe(listener: (change: StoreChange) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/**\n\t * Adds work that belongs to every change, such as working formulas out. `fn` is called at the\n\t * end of each transaction that changed something, before it is done, with what it changed; what\n\t * `fn` writes is part of the same change: one revision, one notice, one step to undo. Listeners\n\t * never see a sheet whose formulas are behind its values.\n\t *\n\t * Returns the way to stop.\n\t */\n\tderive(fn: (operations: readonly StoreOperation[]) => void): () => void {\n\t\tconst entry = (operations: readonly StoreOperation[]): void => fn(operations)\n\n\t\tthis.#derivers.add(entry)\n\n\t\treturn () => {\n\t\t\tthis.#derivers.delete(entry)\n\t\t}\n\t}\n\n\t// ---------------------------------------------------------------- writing\n\n\t/**\n\t * Makes every write inside `fn` one change: one revision, one notice to the listeners, one step\n\t * to undo. If `fn` throws, everything it wrote is taken back and the error is rethrown.\n\t *\n\t * A transaction started inside another joins it, and its writes stand or fall with the outer one.\n\t *\n\t * @returns the change, or null when nothing changed or the call joined an outer transaction\n\t */\n\ttransact(fn: () => void, options: TransactOptions = {}): StoreChange | null {\n\t\tif (this.#log !== null) {\n\t\t\tfn()\n\n\t\t\treturn null\n\t\t}\n\n\t\tconst log: StoreOperation[] = []\n\t\tthis.#log = log\n\n\t\ttry {\n\t\t\tfn()\n\n\t\t\t// What follows from the change goes in with it; a deriver that throws takes it all back.\n\t\t\tif (log.length > 0) {\n\t\t\t\tfor (const derive of [...this.#derivers]) {\n\t\t\t\t\tderive([...log])\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.#log = null\n\n\t\t\tfor (let index = log.length - 1; index >= 0; index--) {\n\t\t\t\tthis.#revert(log[index] as StoreOperation)\n\t\t\t}\n\n\t\t\tthrow error\n\t\t}\n\n\t\tthis.#log = null\n\n\t\tif (log.length === 0) {\n\t\t\treturn null\n\t\t}\n\n\t\tthis.#revision++\n\n\t\tconst change: StoreChange = Object.freeze({\n\t\t\trevision: this.#revision,\n\t\t\torigin: options.origin ?? null,\n\t\t\toperations: Object.freeze(log)\n\t\t})\n\n\t\tthis.#listeners.emit(change)\n\n\t\treturn change\n\t}\n\n\t/**\n\t * Writes one cell. Null or undefined empties it. A value equal to the one there already is no\n\t * change at all, so it does not move the revision.\n\t */\n\tsetCell(rowId: RowId, field: string, value: CellValue | undefined): void {\n\t\tthis.#write(() => {\n\t\t\tconst row = this.#row(rowId)\n\n\t\t\trequireField(field)\n\n\t\t\tconst after = toCellValue(value, `The value of \"${field}\" in row \"${rowId}\"`)\n\t\t\tconst before = row[field] ?? null\n\n\t\t\tif (sameValue(before, after)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tassign(row, field, after)\n\t\t\tthis.#record({ kind: \"set\", rowId, field, before, after })\n\t\t})\n\t}\n\n\t/** Writes many cells as one change, such as a paste. */\n\tsetCells(writes: Iterable<CellWrite>, options: TransactOptions = {}): StoreChange | null {\n\t\treturn this.transact(() => {\n\t\t\tfor (const write of writes) {\n\t\t\t\tthis.setCell(write.rowId, write.field, write.value)\n\t\t\t}\n\t\t}, options)\n\t}\n\n\t/**\n\t * Puts rows in at `index`, 0 to `size`: a number of empty rows, or rows with ids and values.\n\t *\n\t * @returns the ids of the new rows, in order\n\t */\n\tinsertRows(index: number, rows: number | readonly RowInit[]): RowId[] {\n\t\tif (!Number.isInteger(index) || index < 0 || index > this.#order.length) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_argument\",\n\t\t\t\t`Rows can be inserted at 0 to ${this.#order.length}; got ${index}.`\n\t\t\t)\n\t\t}\n\n\t\tconst inits = typeof rows === \"number\" ? blankRows(rows) : rows\n\t\tlet ids: RowId[] = []\n\n\t\tthis.#write(() => {\n\t\t\tconst prepared = this.#prepare(inits)\n\n\t\t\tif (prepared.length === 0) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tids = prepared.map(entry => entry.rowId)\n\n\t\t\tfor (const { rowId, row } of prepared) {\n\t\t\t\tthis.#rows.set(rowId, row)\n\t\t\t}\n\n\t\t\t// Spread into a new array rather than into splice(): as arguments, a paste of 200,000 rows\n\t\t\t// overflows the call stack.\n\t\t\tthis.#order = [...this.#order.slice(0, index), ...ids, ...this.#order.slice(index)]\n\t\t\tthis.#positions = null\n\t\t\tthis.#record({\n\t\t\t\tkind: \"insert\",\n\t\t\t\tindex,\n\t\t\t\trows: Object.freeze(prepared.map(({ rowId, row }) => Object.freeze({ rowId, values: frozenCopy(row) })))\n\t\t\t})\n\t\t})\n\n\t\treturn ids\n\t}\n\n\tappendRows(rows: number | readonly RowInit[]): RowId[] {\n\t\treturn this.insertRows(this.#order.length, rows)\n\t}\n\n\t/**\n\t * Takes rows out, wherever they stand. Every id must exist: one unknown id and nothing is removed.\n\t */\n\tremoveRows(rowIds: Iterable<RowId>): void {\n\t\tconst doomed = new Set(rowIds)\n\n\t\tfor (const rowId of doomed) {\n\t\t\tthis.#row(rowId)\n\t\t}\n\n\t\tif (doomed.size === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#write(() => {\n\t\t\tconst removed: RemovedRow[] = []\n\t\t\tconst kept: RowId[] = []\n\n\t\t\t// One pass whatever the number of rows: removing them one at a time is a pass per row.\n\t\t\tthis.#order.forEach((rowId, index) => {\n\t\t\t\tif (!doomed.has(rowId)) {\n\t\t\t\t\tkept.push(rowId)\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tremoved.push(Object.freeze({ index, rowId, values: frozenCopy(this.#row(rowId)) }))\n\t\t\t\tthis.#rows.delete(rowId)\n\t\t\t})\n\n\t\t\tthis.#order = kept\n\t\t\tthis.#positions = null\n\t\t\tthis.#record({ kind: \"remove\", rows: Object.freeze(removed) })\n\t\t})\n\t}\n\n\t// ---------------------------------------------------------------- taking back\n\n\t/**\n\t * Takes a change back, or several made one after another: their operations undone, the last\n\t * first, as one new change with a revision of its own. Rows come back under the ids they had, to\n\t * the places they stood.\n\t *\n\t * The sheet must be as the change left it: nothing changed since, or every later change taken\n\t * back first. Otherwise nothing is written and a `conflict` is thrown, rather than mixing the\n\t * change into a sheet it never saw.\n\t *\n\t * @returns the change that took it back\n\t */\n\trevert(change: StoreChange | readonly StoreChange[], options: TransactOptions = {}): StoreChange | null {\n\t\tconst changes = listOf(change)\n\n\t\treturn this.#standalone(\"revert\", options, () => {\n\t\t\tfor (let at = changes.length - 1; at >= 0; at--) {\n\t\t\t\tconst operations = (changes[at] as StoreChange).operations\n\n\t\t\t\tfor (let index = operations.length - 1; index >= 0; index--) {\n\t\t\t\t\tthis.#undo(operations[index] as StoreOperation)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Makes a change again once `revert()` has taken it back, with the same row ids; several, in the\n\t * order they were made. The sheet must be as it was before them, or a `conflict` is thrown and\n\t * nothing is written.\n\t *\n\t * @returns the change that made it again\n\t */\n\treplay(change: StoreChange | readonly StoreChange[], options: TransactOptions = {}): StoreChange | null {\n\t\tconst changes = listOf(change)\n\n\t\treturn this.#standalone(\"replay\", options, () => {\n\t\t\tfor (const each of changes) {\n\t\t\t\tfor (const operation of each.operations) {\n\t\t\t\t\tthis.#redo(operation)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\t// ---------------------------------------------------------------- internals\n\n\t#write(fn: () => void): void {\n\t\tif (this.#log === null) {\n\t\t\tthis.transact(fn)\n\t\t} else {\n\t\t\tfn()\n\t\t}\n\t}\n\n\t#record(operation: StoreOperation): void {\n\t\tthis.#log?.push(Object.freeze(operation))\n\t}\n\n\t#row(rowId: RowId): MutableRow {\n\t\tconst row = this.#rows.get(rowId)\n\n\t\tif (!row) {\n\t\t\tthrow new TabulaError(\"unknown_row\", `There is no row \"${rowId}\" in this sheet.`)\n\t\t}\n\n\t\treturn row\n\t}\n\n\t/** Checks the ids and values of new rows without touching the store, so a refusal leaves it as it was. */\n\t#prepare(inits: readonly RowInit[]): { rowId: RowId; row: MutableRow }[] {\n\t\tconst batch = new Set<RowId>()\n\n\t\treturn inits.map(init => {\n\t\t\tconst given = init.rowId !== undefined\n\t\t\tconst rowId = given ? init.rowId : this.#createRowId()\n\n\t\t\tif (typeof rowId !== \"string\" || rowId === \"\") {\n\t\t\t\tthrow new TabulaError(\"invalid_argument\", `A row id must be a non-empty string; got ${String(rowId)}.`)\n\t\t\t}\n\n\t\t\tif (this.#rows.has(rowId) || batch.has(rowId)) {\n\t\t\t\tthrow new TabulaError(\n\t\t\t\t\t\"duplicate_row\",\n\t\t\t\t\tgiven\n\t\t\t\t\t\t? `There is already a row \"${rowId}\" in this sheet.`\n\t\t\t\t\t\t: `createRowId() returned \"${rowId}\", an id already in use.`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tbatch.add(rowId)\n\n\t\t\tconst row = Object.create(null) as MutableRow\n\n\t\t\tfor (const [field, value] of Object.entries(init.values ?? {})) {\n\t\t\t\trequireField(field)\n\n\t\t\t\tconst cell = toCellValue(value, `The value of \"${field}\" in row \"${rowId}\"`)\n\n\t\t\t\tif (cell !== null) {\n\t\t\t\t\trow[field] = cell\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn { rowId, row }\n\t\t})\n\t}\n\n\t#revert(operation: StoreOperation): void {\n\t\tswitch (operation.kind) {\n\t\t\tcase \"set\":\n\t\t\t\tassign(this.#row(operation.rowId), operation.field, operation.before)\n\t\t\t\tbreak\n\t\t\tcase \"insert\": {\n\t\t\t\tconst inserted = new Set(operation.rows.map(entry => entry.rowId))\n\n\t\t\t\tthis.#order = this.#order.filter(rowId => !inserted.has(rowId))\n\n\t\t\t\tfor (const rowId of inserted) {\n\t\t\t\t\tthis.#rows.delete(rowId)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase \"remove\":\n\t\t\t\tthis.#restore(operation.rows)\n\t\t\t\tbreak\n\t\t}\n\n\t\tthis.#positions = null\n\t}\n\n\t/** A transaction that must be a change of its own, never part of an outer one. */\n\t#standalone(name: string, options: TransactOptions, fn: () => void): StoreChange | null {\n\t\tif (this.#log !== null) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_argument\",\n\t\t\t\t`${name}() makes a change of its own and cannot run inside a transaction.`\n\t\t\t)\n\t\t}\n\n\t\treturn this.transact(fn, options)\n\t}\n\n\t#undo(operation: StoreOperation): void {\n\t\tswitch (operation.kind) {\n\t\t\tcase \"set\":\n\t\t\t\tthis.#swap(operation.rowId, operation.field, operation.after, operation.before)\n\t\t\t\tbreak\n\t\t\tcase \"insert\":\n\t\t\t\tthis.#expectRows(operation.rows, true)\n\t\t\t\tthis.removeRows(operation.rows.map(entry => entry.rowId))\n\t\t\t\tbreak\n\t\t\tcase \"remove\":\n\t\t\t\tthis.#putBack(operation.rows)\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\t#redo(operation: StoreOperation): void {\n\t\tswitch (operation.kind) {\n\t\t\tcase \"set\":\n\t\t\t\tthis.#swap(operation.rowId, operation.field, operation.before, operation.after)\n\t\t\t\tbreak\n\t\t\tcase \"insert\":\n\t\t\t\tthis.#expectRows(operation.rows, false)\n\n\t\t\t\tif (operation.index > this.#order.length) {\n\t\t\t\t\tthrow new TabulaError(\n\t\t\t\t\t\t\"conflict\",\n\t\t\t\t\t\t`Rows went in at ${operation.index}, past the end of this sheet of ${this.#order.length} rows.`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tthis.insertRows(operation.index, operation.rows)\n\t\t\t\tbreak\n\t\t\tcase \"remove\":\n\t\t\t\tthis.#expectRows(operation.rows, true)\n\t\t\t\tthis.removeRows(operation.rows.map(entry => entry.rowId))\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\t/** Writes `to` into a cell that must hold `from`. */\n\t#swap(rowId: RowId, field: string, from: CellValue, to: CellValue): void {\n\t\tconst row = this.#rows.get(rowId)\n\n\t\tif (!row) {\n\t\t\tthrow new TabulaError(\"conflict\", `There is no row \"${rowId}\" in this sheet any more.`)\n\t\t}\n\n\t\tif (!sameValue(row[field] ?? null, from)) {\n\t\t\tthrow new TabulaError(\"conflict\", `The cell \"${field}\" in row \"${rowId}\" has changed since.`)\n\t\t}\n\n\t\tassign(row, field, to)\n\t\tthis.#record({ kind: \"set\", rowId, field, before: from, after: to })\n\t}\n\n\t#expectRows(entries: readonly RowEntry[], present: boolean): void {\n\t\tfor (const { rowId } of entries) {\n\t\t\tif (this.#rows.has(rowId) !== present) {\n\t\t\t\tthrow new TabulaError(\n\t\t\t\t\t\"conflict\",\n\t\t\t\t\tpresent\n\t\t\t\t\t\t? `There is no row \"${rowId}\" in this sheet any more.`\n\t\t\t\t\t\t: `There is a row \"${rowId}\" in this sheet already.`\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Puts removed rows back where they stood, in one pass, and records it as one insert for each run\n\t * of rows that stood together: replaying those inserts in order puts every row back in its place.\n\t */\n\t#putBack(entries: readonly RemovedRow[]): void {\n\t\tthis.#expectRows(entries, false)\n\n\t\tconst total = this.#order.length + entries.length\n\t\tlet previous = -1\n\n\t\tfor (const entry of entries) {\n\t\t\tif (!Number.isInteger(entry.index) || entry.index <= previous || entry.index >= total) {\n\t\t\t\tthrow new TabulaError(\n\t\t\t\t\t\"conflict\",\n\t\t\t\t\t`Row \"${entry.rowId}\" stood at ${entry.index}, which is not a place in this sheet of ${total} rows.`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tprevious = entry.index\n\t\t}\n\n\t\tif (entries.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#restore(entries)\n\t\tthis.#positions = null\n\n\t\tlet start = 0\n\n\t\tfor (let end = 1; end <= entries.length; end++) {\n\t\t\tconst next = entries[end]\n\n\t\t\tif (next === undefined || next.index !== (entries[end - 1] as RemovedRow).index + 1) {\n\t\t\t\tconst run = entries.slice(start, end)\n\n\t\t\t\tthis.#record({\n\t\t\t\t\tkind: \"insert\",\n\t\t\t\t\tindex: (run[0] as RemovedRow).index,\n\t\t\t\t\trows: Object.freeze(run.map(({ rowId, values }) => Object.freeze({ rowId, values })))\n\t\t\t\t})\n\t\t\t\tstart = end\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Puts removed rows back where they stood, in one pass. */\n\t#restore(entries: readonly RemovedRow[]): void {\n\t\tconst order: RowId[] = []\n\t\tconst total = this.#order.length + entries.length\n\t\tlet next = 0\n\t\tlet from = 0\n\n\t\tfor (let position = 0; position < total; position++) {\n\t\t\tconst entry = entries[next]\n\n\t\t\tif (entry !== undefined && entry.index === position) {\n\t\t\t\torder.push(entry.rowId)\n\t\t\t\tthis.#rows.set(entry.rowId, Object.assign(Object.create(null) as MutableRow, entry.values))\n\t\t\t\tnext++\n\t\t\t} else {\n\t\t\t\torder.push(this.#order[from++] as RowId)\n\t\t\t}\n\t\t}\n\n\t\tthis.#order = order\n\t}\n}\n\nfunction listOf(change: StoreChange | readonly StoreChange[]): readonly StoreChange[] {\n\treturn \"operations\" in change ? [change] : change\n}\n\nfunction assign(row: MutableRow, field: string, value: CellValue): void {\n\tif (value === null) {\n\t\tdelete row[field]\n\t} else {\n\t\trow[field] = value\n\t}\n}\n\nfunction frozenCopy(row: MutableRow): RowValues {\n\treturn Object.freeze(Object.assign(Object.create(null) as MutableRow, row))\n}\n\nfunction requireField(field: string): void {\n\tif (typeof field !== \"string\" || field === \"\") {\n\t\tthrow new TabulaError(\"invalid_argument\", `A field key must be a non-empty string; got ${String(field)}.`)\n\t}\n}\n\nfunction blankRows(count: number): RowInit[] {\n\tif (!Number.isSafeInteger(count) || count < 0) {\n\t\tthrow new TabulaError(\"invalid_argument\", `A number of rows must be a whole number, 0 or more; got ${count}.`)\n\t}\n\n\treturn Array.from({ length: count }, () => ({}))\n}\n\n/**\n * Ids such as `r_1k3x9q2_1`: a random part drawn once per store, then a counter.\n *\n * The counter keeps them unique within the page. The random part keeps a row made today from taking\n * the id of a row in a draft saved yesterday, which would let yesterday's backend answer land on it.\n */\nfunction sessionRowIds(): () => RowId {\n\treturn sequence(\"r\")\n}\n","/** Settles as the promise does, or rejects once the signal aborts, whichever comes first. */\nexport function raced<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst abort = (): void => reject(abortError())\n\n\t\tif (signal.aborted) {\n\t\t\tabort()\n\n\t\t\treturn\n\t\t}\n\n\t\tsignal.addEventListener(\"abort\", abort, { once: true })\n\t\tpromise.then(\n\t\t\tvalue => {\n\t\t\t\tsignal.removeEventListener(\"abort\", abort)\n\t\t\t\tresolve(value)\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", abort)\n\t\t\t\treject(error instanceof Error ? error : new Error(String(error)))\n\t\t\t}\n\t\t)\n\t})\n}\n\n/** Resolves after `ms`, or rejects once the signal aborts. */\nexport function wait(ms: number, signal: AbortSignal): Promise<void> {\n\treturn raced(new Promise<void>(resolve => setTimeout(resolve, ms)), signal)\n}\n\nexport function abortError(): Error {\n\tconst error = new Error(\"The request was cancelled.\")\n\n\terror.name = \"AbortError\"\n\n\treturn error\n}\n\n/** A signal that never aborts, for a request nobody will cancel. */\nexport function neverAborted(): AbortSignal {\n\treturn new AbortController().signal\n}\n","import { neverAborted, raced } from \"./async.js\"\nimport type { AdapterContext } from \"./contract.js\"\nimport { TabulaError } from \"./errors.js\"\nimport { sequence } from \"./ids.js\"\nimport { Listeners } from \"./listeners.js\"\nimport type { CellWrite, RowId, RowStore, StoreChange } from \"./rows.js\"\nimport type { LookupField, ModuleSchema } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport { clean } from \"./values/text.js\"\n\n/**\n * Lookups: a record picked by its name, kept as `{ id, label }`. The user sees the label, the\n * backend takes the id. A name typed or pasted is text until a record is matched to it, and text\n * in a lookup is an error (`not_matched`): there is no id to send.\n */\n\n/** A record a lookup can hold. */\nexport interface LookupItem {\n\treadonly id: string | number\n\treadonly label: string\n\t/** A second line in the list, such as a product's code. */\n\treadonly description?: string\n\t/** Shown, not picked, such as an inactive product; never matched to a name. */\n\treadonly disabled?: boolean\n}\n\nexport interface LookupSearchRequest {\n\t/** The schema's name for the lookup, such as `\"product\"`. */\n\treadonly lookup: string\n\t/** The field being edited, for a backend whose choice depends on it. */\n\treadonly field: string\n\treadonly query: string\n\treadonly limit: number\n}\n\nexport interface LookupSearchResponse {\n\treadonly items: readonly LookupItem[]\n\t/** Whether more records fit the query than were sent. */\n\treadonly more?: boolean\n}\n\n/** Many names at once, such as from one paste: one request, not one per cell. */\nexport interface LookupResolveRequest {\n\treadonly lookup: string\n\treadonly labels: readonly string[]\n}\n\nexport interface LookupResolveResponse {\n\t/**\n\t * For each name, as it was sent, the records it may mean: one is a match, none or several is not.\n\t * Matching is the backend's: in the user's language, and by more than the name if it likes, such\n\t * as by a product code. The browser compares nothing, so \"ÇELİK\" and \"çelik\" are two names to it.\n\t */\n\treadonly matches: readonly { readonly label: string; readonly items: readonly LookupItem[] }[]\n}\n\n/** What an editor needs to list a lookup's records as the user types: a `LookupResolver` is one. */\nexport interface LookupSearch {\n\tsearch(field: string, query: string, signal?: AbortSignal, limit?: number): Promise<LookupSearchResponse>\n}\n\n/** How a sheet reaches its records. Without `resolve`, names are matched only by picking from the list. */\nexport interface LookupAdapters {\n\tsearch(request: LookupSearchRequest, context: AdapterContext): Promise<LookupSearchResponse>\n\tresolve?(request: LookupResolveRequest, context: AdapterContext): Promise<LookupResolveResponse>\n}\n\n/**\n * The origin of the change that puts a matched record in place of a name. An undo history adds such\n * a change to the step before it, so one Ctrl+Z takes back a paste and what was matched in it.\n */\nexport const LOOKUP_ORIGIN = \"lookup\"\n\nexport interface LookupResolverOptions {\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\treadonly adapters: LookupAdapters\n\t/** How many names go in one resolve request. 200 by default. */\n\treadonly batchSize?: number\n\t/** Milliseconds an answer is used again rather than asked for anew. 60,000 by default. */\n\treadonly cacheFor?: number\n\treadonly now?: () => number\n\treadonly createRequestId?: () => string\n}\n\ninterface Cached<T> {\n\treadonly value: T\n\treadonly at: number\n}\n\n/** The names waiting to be matched in one lookup: by name as written, cleaned, and the cells holding it. */\ntype Names = Map<string, { readonly label: string; readonly cells: Set<string> }>\n\n/** By lookup. */\ntype Queue = Map<string, Names>\n\nconst DEFAULT_BATCH = 200\nconst DEFAULT_CACHE_FOR = 60_000\n\n/**\n * Searches a sheet's lookups for the editor's list, and matches the names typed or pasted into them\n * to records, many at a time.\n *\n * Every name that lands in a lookup cell is gathered, and all of them, from one paste or several\n * edits in a row, go to the backend as one request per lookup (or a few, for thousands). A name\n * that means exactly one record becomes that record; one that means none or several stays text,\n * marked, for the user to pick from the list. An answer is used again for a minute, so pasting the\n * same names twice asks once.\n */\nexport class LookupResolver implements LookupSearch {\n\treadonly #schema: ModuleSchema\n\treadonly #store: RowStore\n\treadonly #adapters: LookupAdapters\n\treadonly #batchSize: number\n\treadonly #cacheFor: number\n\treadonly #now: () => number\n\treadonly #requestId: () => string\n\treadonly #listeners = new Listeners<LookupResolver>()\n\treadonly #stop: () => void\n\treadonly #searches = new Map<string, Cached<LookupSearchResponse>>()\n\t/** By lookup, then name: the record the name means, or null for none or several. */\n\treadonly #matches = new Map<string, Map<string, Cached<LookupItem | null>>>()\n\t#queue: Queue = new Map()\n\t#flushing: Promise<void> = Promise.resolve()\n\t#scheduled = false\n\t#pending = 0\n\t#failure: { readonly message: string; readonly error: unknown } | null = null\n\t#version = 0\n\t#disposed = false\n\n\tconstructor(options: LookupResolverOptions) {\n\t\tconst batchSize = options.batchSize ?? DEFAULT_BATCH\n\n\t\tif (!Number.isSafeInteger(batchSize) || batchSize < 1) {\n\t\t\tthrow new TabulaError(\"invalid_argument\", `batchSize must be a whole number, 1 or more; got ${batchSize}.`)\n\t\t}\n\n\t\tthis.#schema = options.schema\n\t\tthis.#store = options.store\n\t\tthis.#adapters = options.adapters\n\t\tthis.#batchSize = batchSize\n\t\tthis.#cacheFor = options.cacheFor ?? DEFAULT_CACHE_FOR\n\t\tthis.#now = options.now ?? (() => Date.now())\n\t\tthis.#requestId = options.createRequestId ?? sequence(\"lookup\")\n\t\tthis.#stop = this.#store.subscribe(change => this.#onChange(change))\n\t}\n\n\t/** Moves when the number of names waiting changes, or a request fails or recovers. */\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\t/** How many names are waiting for the backend. */\n\tget pending(): number {\n\t\treturn this.#pending\n\t}\n\n\t/** What went wrong with the last resolve request, until one goes through again. */\n\tget failure(): { readonly message: string; readonly error: unknown } | null {\n\t\treturn this.#failure\n\t}\n\n\tsubscribe(listener: (resolver: LookupResolver) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Searches the records of a lookup field, for the editor's list. */\n\tasync search(\n\t\tfield: string,\n\t\tquery: string,\n\t\tsignal: AbortSignal = neverAborted(),\n\t\tlimit = 20\n\t): Promise<LookupSearchResponse> {\n\t\tconst lookup = this.#lookupOf(field)\n\n\t\tif (!lookup) {\n\t\t\tthrow new TabulaError(\"invalid_argument\", `\"${field}\" is not a lookup field.`)\n\t\t}\n\n\t\tconst key = `${lookup.lookup}\\u0000${limit}\\u0000${clean(query)}`\n\t\tconst cached = this.#fresh(this.#searches.get(key))\n\n\t\tif (cached) {\n\t\t\treturn cached\n\t\t}\n\n\t\tconst requestId = this.#requestId()\n\t\tconst answer = await raced(\n\t\t\tthis.#adapters.search({ lookup: lookup.lookup, field, query, limit }, { signal, requestId }),\n\t\t\tsignal\n\t\t)\n\t\tconst response = readSearchResponse(answer)\n\n\t\tthis.#searches.set(key, { value: response, at: this.#now() })\n\n\t\treturn response\n\t}\n\n\t/** Matches every lookup cell holding a name, such as after a draft is opened. */\n\tresolveAll(): Promise<void> {\n\t\tfor (const rowId of this.#store.rowIds()) {\n\t\t\tfor (const field of this.#schema.fields) {\n\t\t\t\tthis.#enqueue(rowId, field.key, this.#store.get(rowId, field.key))\n\t\t\t}\n\t\t}\n\n\t\treturn this.settled()\n\t}\n\n\t/** Settles once every name gathered so far has had its answer. */\n\tasync settled(): Promise<void> {\n\t\tdo {\n\t\t\tawait Promise.resolve()\n\t\t\tawait this.#flushing\n\t\t} while (this.#queue.size > 0 || this.#scheduled)\n\t}\n\n\t/** Stops following the store. Answers still on their way are not written. */\n\tdispose(): void {\n\t\tthis.#disposed = true\n\t\tthis.#stop()\n\t}\n\n\t// ---------------------------------------------------------------- gathering\n\n\t#onChange(change: StoreChange): void {\n\t\t// An undo puts back what was there; matching it again would be a new change, and end the redo.\n\t\tif (change.origin === \"undo\" || change.origin === \"redo\" || change.origin === LOOKUP_ORIGIN) {\n\t\t\treturn\n\t\t}\n\n\t\tfor (const operation of change.operations) {\n\t\t\tif (operation.kind === \"set\") {\n\t\t\t\tthis.#enqueue(operation.rowId, operation.field, operation.after)\n\t\t\t} else if (operation.kind === \"insert\") {\n\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\tfor (const [field, value] of Object.entries(row.values)) {\n\t\t\t\t\t\tthis.#enqueue(row.rowId, field, value)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t#enqueue(rowId: RowId, field: string, value: CellValue): void {\n\t\tconst lookup = this.#lookupOf(field)\n\n\t\tif (!lookup || !this.#adapters.resolve || typeof value !== \"string\" || value.trim() === \"\") {\n\t\t\treturn\n\t\t}\n\n\t\tlet names = this.#queue.get(lookup.lookup)\n\n\t\tif (!names) {\n\t\t\tnames = new Map()\n\t\t\tthis.#queue.set(lookup.lookup, names)\n\t\t}\n\n\t\tconst key = clean(value)\n\t\tconst entry = names.get(key) ?? { label: value, cells: new Set<string>() }\n\n\t\tentry.cells.add(cellKey(rowId, field))\n\t\tnames.set(key, entry)\n\t\tthis.#schedule()\n\t}\n\n\t#schedule(): void {\n\t\tif (this.#scheduled || this.#disposed) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#scheduled = true\n\t\t// After the change that gathered the names: everything one paste or one script writes in a\n\t\t// row goes in one request.\n\t\tthis.#flushing = this.#flushing.then(async () => {\n\t\t\tawait Promise.resolve()\n\t\t\tthis.#scheduled = false\n\t\t\tawait this.#flush()\n\t\t})\n\t}\n\n\t// ---------------------------------------------------------------- matching\n\n\tasync #flush(): Promise<void> {\n\t\tconst queue = this.#queue\n\t\tconst resolve = this.#adapters.resolve\n\n\t\tthis.#queue = new Map()\n\n\t\tif (!resolve || this.#disposed) {\n\t\t\treturn\n\t\t}\n\n\t\tfor (const [lookup, names] of queue) {\n\t\t\tconst known = this.#matches.get(lookup) ?? new Map<string, Cached<LookupItem | null>>()\n\t\t\tconst unknown = [...names].filter(([key]) => !this.#fresh(known.get(key))).map(([, entry]) => entry.label)\n\n\t\t\tthis.#matches.set(lookup, known)\n\t\t\tthis.#setPending(this.#pending + unknown.length)\n\n\t\t\tfor (let start = 0; start < unknown.length; start += this.#batchSize) {\n\t\t\t\tconst labels = unknown.slice(start, start + this.#batchSize)\n\n\t\t\t\ttry {\n\t\t\t\t\tconst answer = await resolve(\n\t\t\t\t\t\t{ lookup, labels },\n\t\t\t\t\t\t{ signal: neverAborted(), requestId: this.#requestId() }\n\t\t\t\t\t)\n\n\t\t\t\t\tthis.#learn(known, labels, readResolveResponse(answer))\n\t\t\t\t\tthis.#setFailure(null)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.#setFailure(error)\n\t\t\t\t} finally {\n\t\t\t\t\tthis.#setPending(this.#pending - labels.length)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.#write(names, known)\n\t\t}\n\t}\n\n\t/** Keeps what the backend said each name means: one record that can be picked, or nothing. */\n\t#learn(\n\t\tknown: Map<string, Cached<LookupItem | null>>,\n\t\tlabels: readonly string[],\n\t\tresponse: LookupResolveResponse\n\t): void {\n\t\tconst at = this.#now()\n\t\tconst answers = new Map(response.matches.map(match => [clean(match.label), match.items] as const))\n\n\t\tfor (const label of labels) {\n\t\t\tconst items = (answers.get(clean(label)) ?? []).filter(item => !item.disabled)\n\n\t\t\tknown.set(clean(label), { value: items.length === 1 ? (items[0] as LookupItem) : null, at })\n\t\t}\n\t}\n\n\t/** Puts each matched record in the cells still holding its name, as one change. */\n\t#write(names: Names, known: Map<string, Cached<LookupItem | null>>): void {\n\t\tif (this.#disposed) {\n\t\t\treturn\n\t\t}\n\n\t\tconst writes: CellWrite[] = []\n\n\t\tfor (const [key, entry] of names) {\n\t\t\tconst item = this.#fresh(known.get(key))\n\n\t\t\tif (!item) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor (const cell of entry.cells) {\n\t\t\t\tconst [rowId, field] = cell.split(\"\\u0000\") as [RowId, string]\n\t\t\t\tconst value = this.#store.has(rowId) ? this.#store.get(rowId, field) : null\n\n\t\t\t\t// Only where the name still stands: the user may have typed something else meanwhile.\n\t\t\t\tif (typeof value === \"string\" && clean(value) === key) {\n\t\t\t\t\twrites.push({ rowId, field, value: Object.freeze({ id: item.id, label: item.label }) })\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (writes.length > 0) {\n\t\t\tthis.#store.setCells(writes, { origin: LOOKUP_ORIGIN })\n\t\t}\n\t}\n\n\t// ---------------------------------------------------------------- helpers\n\n\t#lookupOf(field: string): LookupField | null {\n\t\tif (!this.#schema.has(field)) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst schemaField = this.#schema.field(field)\n\n\t\treturn schemaField.type === \"lookup\" ? schemaField : null\n\t}\n\n\t#fresh<T>(cached: Cached<T> | undefined): T | undefined {\n\t\treturn cached && this.#now() - cached.at < this.#cacheFor ? cached.value : undefined\n\t}\n\n\t#setPending(pending: number): void {\n\t\tif (pending !== this.#pending) {\n\t\t\tthis.#pending = pending\n\t\t\tthis.#changed()\n\t\t}\n\t}\n\n\t#setFailure(error: unknown): void {\n\t\tif (error === null && this.#failure === null) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#failure =\n\t\t\terror === null\n\t\t\t\t? null\n\t\t\t\t: Object.freeze({ message: error instanceof Error ? error.message : String(error), error })\n\t\tthis.#changed()\n\t}\n\n\t#changed(): void {\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n}\n\nfunction cellKey(rowId: RowId, field: string): string {\n\treturn `${rowId}\\u0000${field}`\n}\n\n// ---------------------------------------------------------------- reading answers\n\nfunction readSearchResponse(input: unknown): LookupSearchResponse {\n\tconst root = plain(input)\n\n\tif (!root || !Array.isArray(root.items)) {\n\t\tthrow new TabulaError(\"invalid_response\", \"A lookup search answer must be an object with an items array.\")\n\t}\n\n\treturn Object.freeze({\n\t\titems: Object.freeze(root.items.map((item, index) => readItem(item, `items[${index}]`))),\n\t\tmore: root.more === true\n\t})\n}\n\nfunction readResolveResponse(input: unknown): LookupResolveResponse {\n\tconst root = plain(input)\n\n\tif (!root || !Array.isArray(root.matches)) {\n\t\tthrow new TabulaError(\"invalid_response\", \"A lookup resolve answer must be an object with a matches array.\")\n\t}\n\n\treturn Object.freeze({\n\t\tmatches: Object.freeze(\n\t\t\troot.matches.map((match, index) => {\n\t\t\t\tconst entry = plain(match)\n\n\t\t\t\tif (!entry || typeof entry.label !== \"string\" || !Array.isArray(entry.items)) {\n\t\t\t\t\tthrow new TabulaError(\"invalid_response\", `matches[${index}] must have a label and an items array.`)\n\t\t\t\t}\n\n\t\t\t\treturn Object.freeze({\n\t\t\t\t\tlabel: entry.label,\n\t\t\t\t\titems: Object.freeze(\n\t\t\t\t\t\tentry.items.map((item, at) => readItem(item, `matches[${index}].items[${at}]`))\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t})\n\t\t)\n\t})\n}\n\nfunction readItem(input: unknown, path: string): LookupItem {\n\tconst item = plain(input)\n\tconst id = item?.id\n\n\tif (!item || (typeof id !== \"string\" && typeof id !== \"number\") || typeof item.label !== \"string\") {\n\t\tthrow new TabulaError(\"invalid_response\", `${path} must have an id (text or a number) and a label.`)\n\t}\n\n\treturn Object.freeze({\n\t\tid,\n\t\tlabel: item.label,\n\t\t...(typeof item.description === \"string\" ? { description: item.description } : {}),\n\t\t...(item.disabled === true ? { disabled: true } : {})\n\t})\n}\n\nfunction plain(value: unknown): Record<string, unknown> | null {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: null\n}\n","import { TabulaError } from \"./errors.js\"\nimport { Listeners } from \"./listeners.js\"\nimport { LOOKUP_ORIGIN } from \"./lookup.js\"\nimport type { RowStore, StoreChange } from \"./rows.js\"\n\nexport interface UndoHistoryOptions {\n\t/** How many steps can be taken back; the oldest is forgotten past that. 100 by default. */\n\treadonly limit?: number\n\t/**\n\t * Whether a change belongs to the step before it rather than being a step of its own. By default,\n\t * a lookup matching the names an edit put in (`\"lookup\"`): one Ctrl+Z takes back both. Formulas\n\t * need no joining: what they work out is part of the edit's own change.\n\t */\n\treadonly joins?: (change: StoreChange) => boolean\n}\n\n/** The origin of the change that takes a step back, as `StoreChange.origin` gives it. */\nexport const UNDO_ORIGIN = \"undo\"\n/** The origin of the change that makes a step again. */\nexport const REDO_ORIGIN = \"redo\"\n\nconst DEFAULT_LIMIT = 100\n\n/**\n * A step of something kept beside the store, such as the colours put on cells: taken back and made\n * again by the one who recorded it. It has no revision; the rows are not changed by it.\n */\nexport interface HistoryStep {\n\treadonly undo: () => void\n\treadonly redo: () => void\n}\n\n/** One step: a change, and any that joined it, in the order they were made; or a step kept beside the store. */\ntype Step = StoreChange[] | HistoryStep\n\n/**\n * Undo and redo for a sheet: every change to the store is a step, whoever made it.\n *\n * A step is one transaction, so a paste of 500 rows goes back in one go, the rows it added included.\n * A change that follows from the one before, such as a lookup matching the names a paste put in,\n * joins that step rather than making one of its own. Taking a step back is itself a change, with a\n * revision of its own and `\"undo\"` as its origin: an answer from the backend about the sheet before\n * the undo is out of date after it, as it should be.\n *\n * Steps are taken back strictly last first. Any new change, including one a listener makes in answer\n * to an undo, ends the way forward: what was taken back can no longer be made again on top of it.\n */\nexport class UndoHistory {\n\treadonly #store: RowStore\n\treadonly #limit: number\n\treadonly #joins: (change: StoreChange) => boolean\n\treadonly #undo: Step[] = []\n\t#redo: Step[] = []\n\t/** The revision of the change an undo or a redo is making, which is not a step of its own. */\n\t#making = -1\n\t/** Changes recorded so far, to tell whether a listener wrote while a step was being taken. */\n\t#recorded = 0\n\t#version = 0\n\treadonly #listeners = new Listeners<UndoHistory>()\n\t#stop: (() => void) | null\n\n\tconstructor(store: RowStore, options: UndoHistoryOptions = {}) {\n\t\tconst limit = options.limit ?? DEFAULT_LIMIT\n\n\t\tif (!Number.isSafeInteger(limit) || limit < 1) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_argument\",\n\t\t\t\t`The limit of an undo history must be a whole number, 1 or more; got ${limit}.`\n\t\t\t)\n\t\t}\n\n\t\tthis.#store = store\n\t\tthis.#limit = limit\n\t\tthis.#joins = options.joins ?? (change => change.origin === LOOKUP_ORIGIN)\n\t\tthis.#stop = store.subscribe(change => this.#record(change))\n\t}\n\n\t/** Moves on every change to what can be undone or redone, for a view to redraw its buttons by. */\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\tget canUndo(): boolean {\n\t\treturn this.#undo.length > 0\n\t}\n\n\tget canRedo(): boolean {\n\t\treturn this.#redo.length > 0\n\t}\n\n\t/**\n\t * The change that began the step `undo()` would take back, such as one whose origin is `\"paste\"`.\n\t * Null when there is none.\n\t */\n\tget nextUndo(): StoreChange | null {\n\t\treturn firstChange(this.#undo[this.#undo.length - 1])\n\t}\n\n\t/** The change that began the step `redo()` would make again. Null when there is none. */\n\tget nextRedo(): StoreChange | null {\n\t\treturn firstChange(this.#redo[this.#redo.length - 1])\n\t}\n\n\t/**\n\t * Records a step of something kept beside the store, such as colours put on cells, so Ctrl+Z\n\t * takes it back in its turn with the rows' changes. It ends the way forward, as any change does.\n\t */\n\trecord(step: HistoryStep): void {\n\t\tthis.#undo.push(step)\n\t\tthis.#trim()\n\t\tthis.#redo = []\n\t\tthis.#changed()\n\t}\n\n\t/**\n\t * Takes the last step back.\n\t *\n\t * @returns the change that took it back, for a view to show where it landed; null when there was\n\t * nothing to undo\n\t * @throws TabulaError `conflict` when the sheet is not as the step left it, which only a store\n\t * changed while this history was not listening can be. Nothing is written, and the history,\n\t * which no longer describes the sheet, is cleared.\n\t */\n\tundo(): StoreChange | null {\n\t\tconst step = this.#undo.pop()\n\n\t\tif (step === undefined) {\n\t\t\treturn null\n\t\t}\n\n\t\tif (!Array.isArray(step)) {\n\t\t\tstep.undo()\n\t\t\tthis.#redo.push(step)\n\t\t\tthis.#changed()\n\n\t\t\treturn null\n\t\t}\n\n\t\tconst recorded = this.#recorded\n\t\tconst made = this.#take(step, this.#undo, () => this.#store.revert(step, { origin: UNDO_ORIGIN }))\n\n\t\t// A listener that wrote in answer made a change on top of the undo: the step stays undone.\n\t\tif (this.#recorded === recorded) {\n\t\t\tthis.#redo.push(step)\n\t\t}\n\n\t\tthis.#changed()\n\n\t\treturn made\n\t}\n\n\t/**\n\t * Makes the last step taken back again.\n\t *\n\t * @returns the change that made it again; null when there was nothing to redo\n\t * @throws TabulaError `conflict`, as `undo()` does\n\t */\n\tredo(): StoreChange | null {\n\t\tconst step = this.#redo.pop()\n\n\t\tif (step === undefined) {\n\t\t\treturn null\n\t\t}\n\n\t\tif (!Array.isArray(step)) {\n\t\t\tstep.redo()\n\t\t\tthis.#undo.push(step)\n\t\t\tthis.#trim()\n\t\t\tthis.#changed()\n\n\t\t\treturn null\n\t\t}\n\n\t\tconst recorded = this.#recorded\n\t\tconst made = this.#take(step, this.#redo, () => this.#store.replay(step, { origin: REDO_ORIGIN }))\n\n\t\t// Changes listeners made in answer were recorded already, and came after this one.\n\t\tthis.#undo.splice(Math.max(0, this.#undo.length - (this.#recorded - recorded)), 0, step)\n\t\tthis.#trim()\n\t\tthis.#changed()\n\n\t\treturn made\n\t}\n\n\t/** Forgets every step, such as after a draft is loaded into the store. */\n\tclear(): void {\n\t\tif (this.#undo.length === 0 && this.#redo.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#undo.length = 0\n\t\tthis.#redo = []\n\t\tthis.#changed()\n\t}\n\n\t/** Called after each change to what can be undone or redone. Returns the way to stop. */\n\tsubscribe(listener: (history: UndoHistory) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Stops following the store and forgets every step. */\n\tdispose(): void {\n\t\tthis.#stop?.()\n\t\tthis.#stop = null\n\t\tthis.clear()\n\t}\n\n\t/** Runs an undo or a redo; on failure puts the step back, or clears everything on a conflict. */\n\t#take(step: StoreChange[], from: Step[], fn: () => StoreChange | null): StoreChange | null {\n\t\tthis.#making = this.#store.revision + 1\n\n\t\ttry {\n\t\t\treturn fn()\n\t\t} catch (error) {\n\t\t\tif (error instanceof TabulaError && error.code === \"conflict\") {\n\t\t\t\tthis.#undo.length = 0\n\t\t\t\tthis.#redo = []\n\t\t\t\tthis.#changed()\n\t\t\t} else {\n\t\t\t\tfrom.push(step)\n\t\t\t}\n\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tthis.#making = -1\n\t\t}\n\t}\n\n\t#record(change: StoreChange): void {\n\t\tif (change.revision === this.#making) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#recorded++\n\n\t\tconst last = this.#undo[this.#undo.length - 1]\n\n\t\t// Never while a step is being taken: what a listener writes then comes after that step, not\n\t\t// inside the one below it.\n\t\tif (Array.isArray(last) && this.#making === -1 && this.#joins(change)) {\n\t\t\tlast.push(change)\n\t\t} else {\n\t\t\tthis.#undo.push([change])\n\t\t\tthis.#trim()\n\t\t}\n\n\t\tthis.#redo = []\n\t\tthis.#changed()\n\t}\n\n\t#trim(): void {\n\t\tif (this.#undo.length > this.#limit) {\n\t\t\tthis.#undo.splice(0, this.#undo.length - this.#limit)\n\t\t}\n\t}\n\n\t#changed(): void {\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n}\n\nfunction firstChange(step: Step | undefined): StoreChange | null {\n\treturn Array.isArray(step) ? (step[0] ?? null) : null\n}\n","/**\n * Decimal arithmetic for formulas, exact where floats are not: a number is an integer and a count of\n * places after the point, so 0.1 + 0.2 is 0.3 and a price times a quantity is what a till says.\n */\n\n/** `units / 10^scale`. */\nexport interface Decimal {\n\treadonly units: bigint\n\treadonly scale: number\n}\n\n/** Places after the point a division is carried to before it is rounded. */\nexport const DIVISION_PLACES = 20\n\nconst TEXT = /^([+-]?)(\\d+)(?:\\.(\\d+))?$/\n\n// BigInt(…) rather than literals such as 10n: a build that aims at an older JavaScript, as Nuxt's\n// server build does, warns that the literals may not run, though anything that runs this has BigInt.\nconst B0 = BigInt(0)\nconst B1 = BigInt(1)\nconst B2 = BigInt(2)\nconst B10 = BigInt(10)\nconst B1000 = BigInt(1000)\n\nexport const ZERO: Decimal = Object.freeze({ units: B0, scale: 0 })\nexport const ONE: Decimal = Object.freeze({ units: B1, scale: 0 })\n\n/** A decimal from text such as `\"-12.50\"`; null for anything else. */\nexport function parseDecimal(text: string): Decimal | null {\n\tconst match = TEXT.exec(text.trim())\n\n\tif (!match) {\n\t\treturn null\n\t}\n\n\tconst fraction = match[3] ?? \"\"\n\tconst units = BigInt(`${match[2] ?? \"0\"}${fraction}`)\n\n\treturn simplify({ units: match[1] === \"-\" ? -units : units, scale: fraction.length })\n}\n\n/** The decimal as `normalizeDecimal` writes numbers: `\"-12.5\"`, `\"0\"`. */\nexport function decimalToText(value: Decimal): string {\n\tconst negative = value.units < B0\n\tconst digits = (negative ? -value.units : value.units).toString().padStart(value.scale + 1, \"0\")\n\tconst whole = digits.slice(0, digits.length - value.scale)\n\tconst fraction = digits.slice(digits.length - value.scale).replace(/0+$/, \"\")\n\tconst body = fraction === \"\" ? whole : `${whole}.${fraction}`\n\n\treturn negative && body !== \"0\" ? `-${body}` : body\n}\n\nexport function add(a: Decimal, b: Decimal): Decimal {\n\tconst [x, y, scale] = aligned(a, b)\n\n\treturn simplify({ units: x + y, scale })\n}\n\nexport function subtract(a: Decimal, b: Decimal): Decimal {\n\tconst [x, y, scale] = aligned(a, b)\n\n\treturn simplify({ units: x - y, scale })\n}\n\nexport function multiply(a: Decimal, b: Decimal): Decimal {\n\treturn simplify({ units: a.units * b.units, scale: a.scale + b.scale })\n}\n\n/** Null when dividing by zero. Carried to `DIVISION_PLACES` places, rounded half away from zero. */\nexport function divide(a: Decimal, b: Decimal): Decimal | null {\n\tif (b.units === B0) {\n\t\treturn null\n\t}\n\n\t// a / b = (a.units / 10^a.scale) / (b.units / 10^b.scale); one place more than kept, to round on.\n\tconst places = DIVISION_PLACES + 1\n\tconst numerator = a.units * B10 ** BigInt(places + b.scale)\n\tconst denominator = b.units * B10 ** BigInt(a.scale)\n\n\treturn round({ units: numerator / denominator, scale: places }, DIVISION_PLACES, \"half\")\n}\n\nexport function negate(value: Decimal): Decimal {\n\treturn { units: -value.units, scale: value.scale }\n}\n\nexport function absolute(value: Decimal): Decimal {\n\treturn value.units < B0 ? negate(value) : value\n}\n\n/** -1, 0 or 1. */\nexport function compare(a: Decimal, b: Decimal): -1 | 0 | 1 {\n\tconst [x, y] = aligned(a, b)\n\n\treturn x < y ? -1 : x > y ? 1 : 0\n}\n\nexport function isZero(value: Decimal): boolean {\n\treturn value.units === B0\n}\n\nexport function isInteger(value: Decimal): boolean {\n\treturn value.scale === 0\n}\n\n/**\n * Rounded to `places` after the point (negative rounds to tens, hundreds…). `half` is away from zero\n * at five, as Excel and nouxwell/tabula round; `up` is away from zero, `down` towards it.\n */\nexport function round(value: Decimal, places: number, mode: \"half\" | \"up\" | \"down\"): Decimal {\n\tif (value.scale <= places) {\n\t\treturn value\n\t}\n\n\tconst drop = B10 ** BigInt(value.scale - places)\n\tconst negative = value.units < B0\n\tconst magnitude = negative ? -value.units : value.units\n\tlet kept = magnitude / drop\n\tconst rest = magnitude % drop\n\n\tif (rest !== B0 && (mode === \"up\" || (mode === \"half\" && rest * B2 >= drop))) {\n\t\tkept += B1\n\t}\n\n\tconst units = negative ? -kept : kept\n\n\treturn places >= 0\n\t\t? simplify({ units, scale: places })\n\t\t: simplify({ units: units * B10 ** BigInt(-places), scale: 0 })\n}\n\n/** A whole power: exact for a whole exponent, null for any other, which the caller reports. */\nexport function power(base: Decimal, exponent: Decimal): Decimal | null {\n\tif (!isInteger(exponent) || exponent.units > B1000 || exponent.units < -B1000) {\n\t\treturn null\n\t}\n\n\tconst times = Number(exponent.units < B0 ? -exponent.units : exponent.units)\n\tlet result: Decimal = ONE\n\n\tfor (let step = 0; step < times; step++) {\n\t\tresult = multiply(result, base)\n\t}\n\n\treturn exponent.units < B0 ? divide(ONE, result) : result\n}\n\n/** Both as integers of the same scale. */\nfunction aligned(a: Decimal, b: Decimal): [bigint, bigint, number] {\n\tconst scale = Math.max(a.scale, b.scale)\n\n\treturn [a.units * B10 ** BigInt(scale - a.scale), b.units * B10 ** BigInt(scale - b.scale), scale]\n}\n\n/** Without trailing zeros after the point. */\nfunction simplify(value: Decimal): Decimal {\n\tlet { units, scale } = value\n\n\twhile (scale > 0 && units % B10 === B0) {\n\t\tunits /= B10\n\t\tscale--\n\t}\n\n\treturn Object.freeze({ units, scale })\n}\n","import type { CellValue } from \"../value.js\"\n\n/**\n * What a formula gives when it cannot give a value, as Excel writes it: `#DIV/0!` for a division by\n * zero, `#VALUE!` for a value of the wrong kind (text where a number goes), `#NAME?` for a function\n * nobody defined, `#NUM!` for a number that cannot be (a fractional power).\n */\nexport type FormulaErrorCode = \"#DIV/0!\" | \"#VALUE!\" | \"#NAME?\" | \"#NUM!\"\n\n/** A cell holding a formula's error: kept in the cell, as the value it shows, and reported as an issue. */\n// A type rather than an interface, so it is a cell value as it stands.\nexport type FormulaErrorValue = { readonly formulaError: FormulaErrorCode }\n\nexport function isFormulaError(value: CellValue): value is FormulaErrorValue {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t!Array.isArray(value) &&\n\t\ttypeof (value as Record<string, CellValue>).formulaError === \"string\"\n\t)\n}\n\nexport function formulaErrorValue(code: FormulaErrorCode): FormulaErrorValue {\n\treturn Object.freeze({ formulaError: code })\n}\n","import {\n\tabsolute,\n\tadd,\n\tcompare,\n\tdecimalToText,\n\tdivide,\n\tisZero,\n\tmultiply,\n\tONE,\n\tparseDecimal,\n\tpower,\n\tround,\n\tsubtract,\n\tZERO,\n\ttype Decimal\n} from \"./decimal.js\"\nimport type { FormulaErrorCode } from \"./error.js\"\nimport type { FormulaNode } from \"./parse.js\"\n\n/** A value while a formula is worked out. */\nexport type FormulaValue =\n\t| { readonly type: \"number\"; readonly value: Decimal }\n\t| { readonly type: \"text\"; readonly value: string }\n\t| { readonly type: \"bool\"; readonly value: boolean }\n\t| { readonly type: \"empty\" }\n\t| { readonly type: \"error\"; readonly code: FormulaErrorCode }\n\n/**\n * A function an application adds to the language, such as a margin rule of its own. It works out a\n * value from its arguments and nothing else: no request, no write, no side effect. Whatever it\n * throws becomes `#VALUE!`.\n */\nexport type FormulaFunction = (args: readonly FormulaValue[]) => FormulaValue\n\nexport interface EvaluationContext {\n\t/** A field of the row, by key. */\n\tfield(key: string): FormulaValue\n\t/** The application's functions, by name in capitals. The built-in ones cannot be replaced. */\n\treadonly functions: Readonly<Record<string, FormulaFunction>>\n}\n\nexport const EMPTY: FormulaValue = Object.freeze({ type: \"empty\" })\n\nexport function numberValue(value: Decimal): FormulaValue {\n\treturn Object.freeze({ type: \"number\", value })\n}\n\nexport function textValue(value: string): FormulaValue {\n\treturn Object.freeze({ type: \"text\", value })\n}\n\nexport function boolValue(value: boolean): FormulaValue {\n\treturn value ? TRUE : FALSE\n}\n\nexport function errorValue(code: FormulaErrorCode): FormulaValue {\n\treturn Object.freeze({ type: \"error\", code })\n}\n\n// ---------------------------------------------------------------- for an application's functions\n\n/** A number for a formula, from decimal text or a JavaScript number; `#NUM!` for one that is not finite. */\nexport function formulaNumber(value: string | number): FormulaValue {\n\tconst decimal = typeof value === \"number\" && !Number.isFinite(value) ? null : parseDecimal(String(value))\n\n\treturn decimal ? numberValue(decimal) : errorValue(\"#NUM!\")\n}\n\n/** An argument as decimal text, as numbers are kept; null when it is no number. */\nexport function numberArgument(value: FormulaValue): string | null {\n\tconst number = toNumber(value)\n\n\treturn failed(number) ? null : decimalToText(number)\n}\n\nconst TRUE: FormulaValue = Object.freeze({ type: \"bool\", value: true })\nconst FALSE: FormulaValue = Object.freeze({ type: \"bool\", value: false })\nconst HUNDRED = parseDecimal(\"100\") as Decimal\n\ntype Failed = Extract<FormulaValue, { type: \"error\" }>\n\nfunction failed(value: unknown): value is Failed {\n\treturn typeof value === \"object\" && value !== null && (value as FormulaValue).type === \"error\"\n}\n\n// ---------------------------------------------------------------- coercions, as Excel makes them\n\n/** Empty is 0, yes and no are 1 and 0, text that is a number is that number. */\nexport function toNumber(value: FormulaValue): Decimal | Failed {\n\tswitch (value.type) {\n\t\tcase \"number\":\n\t\t\treturn value.value\n\t\tcase \"empty\":\n\t\t\treturn ZERO\n\t\tcase \"bool\":\n\t\t\treturn value.value ? ONE : ZERO\n\t\tcase \"text\":\n\t\t\treturn parseDecimal(value.value) ?? (errorValue(\"#VALUE!\") as Failed)\n\t\tcase \"error\":\n\t\t\treturn value\n\t}\n}\n\nexport function toText(value: FormulaValue): string | Failed {\n\tswitch (value.type) {\n\t\tcase \"number\":\n\t\t\treturn decimalToText(value.value)\n\t\tcase \"empty\":\n\t\t\treturn \"\"\n\t\tcase \"bool\":\n\t\t\treturn value.value ? \"TRUE\" : \"FALSE\"\n\t\tcase \"text\":\n\t\t\treturn value.value\n\t\tcase \"error\":\n\t\t\treturn value\n\t}\n}\n\nexport function toBool(value: FormulaValue): boolean | Failed {\n\tswitch (value.type) {\n\t\tcase \"bool\":\n\t\t\treturn value.value\n\t\tcase \"number\":\n\t\t\treturn !isZero(value.value)\n\t\tcase \"empty\":\n\t\t\treturn false\n\t\tcase \"text\": {\n\t\t\tconst word = value.value.trim().toUpperCase()\n\n\t\t\treturn word === \"TRUE\" ? true : word === \"FALSE\" ? false : (errorValue(\"#VALUE!\") as Failed)\n\t\t}\n\t\tcase \"error\":\n\t\t\treturn value\n\t}\n}\n\n// ---------------------------------------------------------------- evaluation\n\n/** Works a formula out. Never throws: what goes wrong is an error value, as in a spreadsheet. */\nexport function evaluate(node: FormulaNode, context: EvaluationContext): FormulaValue {\n\tswitch (node.kind) {\n\t\tcase \"number\":\n\t\t\treturn numberValue(parseDecimal(node.value) ?? ZERO)\n\t\tcase \"text\":\n\t\t\treturn textValue(node.value)\n\t\tcase \"bool\":\n\t\t\treturn boolValue(node.value)\n\t\tcase \"field\":\n\t\t\treturn context.field(node.key)\n\t\tcase \"negate\":\n\t\t\treturn arithmetic(evaluate(node.operand, context), numberValue(ZERO), (a, b) => subtract(b, a))\n\t\tcase \"percent\":\n\t\t\treturn arithmetic(evaluate(node.operand, context), numberValue(HUNDRED), divide)\n\t\tcase \"binary\":\n\t\t\treturn binary(node.op, evaluate(node.left, context), evaluate(node.right, context))\n\t\tcase \"call\":\n\t\t\treturn call(node.name, node.args, context)\n\t}\n}\n\nfunction arithmetic(\n\tleft: FormulaValue,\n\tright: FormulaValue,\n\top: (a: Decimal, b: Decimal) => Decimal | null,\n\tnullError: FormulaErrorCode = \"#DIV/0!\"\n): FormulaValue {\n\tconst a = toNumber(left)\n\n\tif (failed(a)) {\n\t\treturn a\n\t}\n\n\tconst b = toNumber(right)\n\n\tif (failed(b)) {\n\t\treturn b\n\t}\n\n\tconst result = op(a, b)\n\n\treturn result === null ? errorValue(nullError) : numberValue(result)\n}\n\nfunction binary(op: string, left: FormulaValue, right: FormulaValue): FormulaValue {\n\tswitch (op) {\n\t\tcase \"+\":\n\t\t\treturn arithmetic(left, right, add)\n\t\tcase \"-\":\n\t\t\treturn arithmetic(left, right, subtract)\n\t\tcase \"*\":\n\t\t\treturn arithmetic(left, right, multiply)\n\t\tcase \"/\":\n\t\t\treturn arithmetic(left, right, divide)\n\t\tcase \"^\":\n\t\t\treturn arithmetic(left, right, power, \"#NUM!\")\n\t\tcase \"&\": {\n\t\t\tconst a = toText(left)\n\n\t\t\tif (failed(a)) {\n\t\t\t\treturn a\n\t\t\t}\n\n\t\t\tconst b = toText(right)\n\n\t\t\treturn failed(b) ? b : textValue(a + b)\n\t\t}\n\t\tdefault: {\n\t\t\tconst order = compareValues(left, right)\n\n\t\t\tif (failed(order)) {\n\t\t\t\treturn order\n\t\t\t}\n\n\t\t\treturn boolValue(\n\t\t\t\top === \"=\"\n\t\t\t\t\t? order === 0\n\t\t\t\t\t: op === \"<>\"\n\t\t\t\t\t\t? order !== 0\n\t\t\t\t\t\t: op === \"<\"\n\t\t\t\t\t\t\t? order < 0\n\t\t\t\t\t\t\t: op === \">\"\n\t\t\t\t\t\t\t\t? order > 0\n\t\t\t\t\t\t\t\t: op === \"<=\"\n\t\t\t\t\t\t\t\t\t? order <= 0\n\t\t\t\t\t\t\t\t\t: order >= 0\n\t\t\t)\n\t\t}\n\t}\n}\n\n/**\n * As Excel compares: numbers with numbers, text with text regardless of case, and across kinds\n * numbers before text before yes and no. Empty is 0, \"\" or FALSE, whatever the other side is.\n */\nfunction compareValues(left: FormulaValue, right: FormulaValue): -1 | 0 | 1 | Failed {\n\tif (left.type === \"error\") {\n\t\treturn left\n\t}\n\n\tif (right.type === \"error\") {\n\t\treturn right\n\t}\n\n\tconst a = left.type === \"empty\" ? emptyLike(right) : left\n\tconst b = right.type === \"empty\" ? emptyLike(a) : right\n\tconst rank = { number: 0, text: 1, bool: 2, empty: 0 } as const\n\n\tif (a.type !== b.type) {\n\t\treturn rank[a.type as keyof typeof rank] < rank[b.type as keyof typeof rank] ? -1 : 1\n\t}\n\n\tif (a.type === \"number\" && b.type === \"number\") {\n\t\treturn compare(a.value, b.value)\n\t}\n\n\tif (a.type === \"text\" && b.type === \"text\") {\n\t\tconst x = a.value.toLowerCase()\n\t\tconst y = b.value.toLowerCase()\n\n\t\treturn x < y ? -1 : x > y ? 1 : 0\n\t}\n\n\tif (a.type === \"bool\" && b.type === \"bool\") {\n\t\treturn a.value === b.value ? 0 : a.value ? 1 : -1\n\t}\n\n\treturn 0\n}\n\nfunction emptyLike(other: FormulaValue): FormulaValue {\n\treturn other.type === \"text\" ? textValue(\"\") : other.type === \"bool\" ? FALSE : numberValue(ZERO)\n}\n\n// ---------------------------------------------------------------- functions\n\n/** The functions every formula has. A function the application adds goes by its own name. */\nexport const FUNCTIONS: readonly string[] = [\n\t\"ABS\",\n\t\"AND\",\n\t\"AVERAGE\",\n\t\"CONCAT\",\n\t\"IF\",\n\t\"IFERROR\",\n\t\"ISBLANK\",\n\t\"LEN\",\n\t\"MAX\",\n\t\"MIN\",\n\t\"NOT\",\n\t\"OR\",\n\t\"ROUND\",\n\t\"ROUNDDOWN\",\n\t\"ROUNDUP\",\n\t\"SUM\"\n]\n\nfunction call(name: string, args: readonly FormulaNode[], context: EvaluationContext): FormulaValue {\n\t// The ones that work out only what they need, so IF(x > 0, 1 / x, 0) is never a division by zero.\n\tswitch (name) {\n\t\tcase \"IF\": {\n\t\t\tif (args.length < 2 || args.length > 3) {\n\t\t\t\treturn errorValue(\"#VALUE!\")\n\t\t\t}\n\n\t\t\tconst condition = toBool(evaluate(args[0] as FormulaNode, context))\n\n\t\t\tif (failed(condition)) {\n\t\t\t\treturn condition\n\t\t\t}\n\n\t\t\tconst branch = condition ? args[1] : args[2]\n\n\t\t\treturn branch ? evaluate(branch, context) : FALSE\n\t\t}\n\t\tcase \"IFERROR\": {\n\t\t\tif (args.length !== 2) {\n\t\t\t\treturn errorValue(\"#VALUE!\")\n\t\t\t}\n\n\t\t\tconst value = evaluate(args[0] as FormulaNode, context)\n\n\t\t\treturn value.type === \"error\" ? evaluate(args[1] as FormulaNode, context) : value\n\t\t}\n\t\tcase \"ISBLANK\":\n\t\t\treturn args.length === 1\n\t\t\t\t? boolValue(evaluate(args[0] as FormulaNode, context).type === \"empty\")\n\t\t\t\t: errorValue(\"#VALUE!\")\n\t}\n\n\tconst values = args.map(arg => evaluate(arg, context))\n\tconst builtIn = BUILT_IN[name]\n\n\tif (builtIn) {\n\t\treturn builtIn(values)\n\t}\n\n\tconst custom = context.functions[name]\n\n\tif (!custom) {\n\t\treturn errorValue(\"#NAME?\")\n\t}\n\n\ttry {\n\t\treturn custom(values)\n\t} catch {\n\t\treturn errorValue(\"#VALUE!\")\n\t}\n}\n\n/** The numbers among the arguments; an empty field is passed over, an error is the answer. */\nfunction numbers(values: readonly FormulaValue[]): Decimal[] | Failed {\n\tconst list: Decimal[] = []\n\n\tfor (const value of values) {\n\t\tif (value.type === \"empty\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst number = toNumber(value)\n\n\t\tif (failed(number)) {\n\t\t\treturn number\n\t\t}\n\n\t\tlist.push(number)\n\t}\n\n\treturn list\n}\n\nfunction rounding(mode: \"half\" | \"up\" | \"down\"): FormulaFunction {\n\treturn values => {\n\t\tif (values.length < 1 || values.length > 2) {\n\t\t\treturn errorValue(\"#VALUE!\")\n\t\t}\n\n\t\tconst value = toNumber(values[0] as FormulaValue)\n\t\tconst places = toNumber(values[1] ?? numberValue(ZERO))\n\n\t\tif (failed(value)) {\n\t\t\treturn value\n\t\t}\n\n\t\tif (failed(places)) {\n\t\t\treturn places\n\t\t}\n\n\t\t// The places are a whole number, cut towards zero as Excel cuts them.\n\t\tconst whole = Number(decimalToText(round(places, 0, \"down\")))\n\n\t\treturn numberValue(round(value, whole, mode))\n\t}\n}\n\nfunction logical(all: boolean): FormulaFunction {\n\treturn values => {\n\t\tif (values.length === 0) {\n\t\t\treturn errorValue(\"#VALUE!\")\n\t\t}\n\n\t\tlet result = all\n\n\t\tfor (const value of values) {\n\t\t\tconst truth = toBool(value)\n\n\t\t\tif (failed(truth)) {\n\t\t\t\treturn truth\n\t\t\t}\n\n\t\t\tresult = all ? result && truth : result || truth\n\t\t}\n\n\t\treturn boolValue(result)\n\t}\n}\n\nconst BUILT_IN: Readonly<Record<string, FormulaFunction>> = {\n\tSUM: values => {\n\t\tconst list = numbers(values)\n\n\t\treturn failed(list) ? list : numberValue(list.reduce(add, ZERO))\n\t},\n\tAVERAGE: values => {\n\t\tconst list = numbers(values)\n\n\t\tif (failed(list)) {\n\t\t\treturn list\n\t\t}\n\n\t\tif (list.length === 0) {\n\t\t\treturn errorValue(\"#DIV/0!\")\n\t\t}\n\n\t\tconst average = divide(list.reduce(add, ZERO), parseDecimal(String(list.length)) as Decimal)\n\n\t\treturn average === null ? errorValue(\"#DIV/0!\") : numberValue(average)\n\t},\n\tMIN: values => {\n\t\tconst list = numbers(values)\n\n\t\treturn failed(list) ? list : numberValue(list.reduce((a, b) => (compare(a, b) <= 0 ? a : b), list[0] ?? ZERO))\n\t},\n\tMAX: values => {\n\t\tconst list = numbers(values)\n\n\t\treturn failed(list) ? list : numberValue(list.reduce((a, b) => (compare(a, b) >= 0 ? a : b), list[0] ?? ZERO))\n\t},\n\tROUND: rounding(\"half\"),\n\tROUNDUP: rounding(\"up\"),\n\tROUNDDOWN: rounding(\"down\"),\n\tABS: values => {\n\t\tif (values.length !== 1) {\n\t\t\treturn errorValue(\"#VALUE!\")\n\t\t}\n\n\t\tconst value = toNumber(values[0] as FormulaValue)\n\n\t\treturn failed(value) ? value : numberValue(absolute(value))\n\t},\n\tAND: logical(true),\n\tOR: logical(false),\n\tNOT: values => {\n\t\tif (values.length !== 1) {\n\t\t\treturn errorValue(\"#VALUE!\")\n\t\t}\n\n\t\tconst truth = toBool(values[0] as FormulaValue)\n\n\t\treturn failed(truth) ? truth : boolValue(!truth)\n\t},\n\tLEN: values => {\n\t\tif (values.length !== 1) {\n\t\t\treturn errorValue(\"#VALUE!\")\n\t\t}\n\n\t\tconst text = toText(values[0] as FormulaValue)\n\n\t\treturn failed(text) ? text : numberValue(parseDecimal(String(Array.from(text).length)) as Decimal)\n\t},\n\tCONCAT: values => {\n\t\tlet text = \"\"\n\n\t\tfor (const value of values) {\n\t\t\tconst part = toText(value)\n\n\t\t\tif (failed(part)) {\n\t\t\t\treturn part\n\t\t\t}\n\n\t\t\ttext += part\n\t\t}\n\n\t\treturn textValue(text)\n\t}\n}\n","import type { RowId, RowInit, RowStore, StoreOperation } from \"../rows.js\"\nimport type { FieldSchema, ModuleSchema } from \"../schema.js\"\nimport { sameValue, type CellValue } from \"../value.js\"\nimport { decimalText } from \"../values/number.js\"\nimport { describeValue, isLookupValue } from \"../values/read.js\"\nimport { decimalToText, parseDecimal, round } from \"./decimal.js\"\nimport { formulaErrorValue, isFormulaError } from \"./error.js\"\nimport {\n\tboolValue,\n\tEMPTY,\n\tevaluate,\n\tnumberValue,\n\ttextValue,\n\ttoBool,\n\ttoNumber,\n\ttoText,\n\ttype FormulaFunction,\n\ttype FormulaValue\n} from \"./evaluate.js\"\nimport { formulaFields, parseFormula, type FormulaNode } from \"./parse.js\"\n\n/**\n * The origin of the change that works out, as an engine starts, the formulas of rows a store was\n * given as they were, where they differ. Every later formula value goes in with the change that\n * called for it.\n */\nexport const FORMULA_ORIGIN = \"formula\"\n\nexport interface FormulaEngineOptions {\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\t/**\n\t * The application's own functions, by name. They work a value out of their arguments and do\n\t * nothing else; the built-in ones cannot be replaced.\n\t */\n\treadonly functions?: Readonly<Record<string, FormulaFunction>>\n}\n\ninterface Compiled {\n\treadonly field: FieldSchema\n\treadonly tree: FormulaNode\n}\n\n/**\n * Keeps a sheet's formula fields worked out. Every change to the store works out again, inside that\n * very change, the formulas that read what it changed, for the rows it changed, each after the\n * formulas it reads: an edit and what follows from it are one change, one revision, one step to undo.\n *\n * The values are written into the store like any other, so the validator checks them, a draft keeps\n * them and the backend receives them. The backend works them out again: a value the browser worked\n * out is never to be trusted on its own. A formula that cannot be worked out leaves its error in the\n * cell, such as `#DIV/0!`, and that is an issue.\n */\nexport class FormulaEngine {\n\treadonly #schema: ModuleSchema\n\treadonly #store: RowStore\n\treadonly #functions: Readonly<Record<string, FormulaFunction>>\n\treadonly #order: readonly Compiled[]\n\t/** By field: the formulas to work out again when it changes, in order. */\n\treadonly #affected: ReadonlyMap<string, readonly Compiled[]>\n\treadonly #stop: () => void\n\n\tconstructor(options: FormulaEngineOptions) {\n\t\tthis.#schema = options.schema\n\t\tthis.#store = options.store\n\t\tthis.#functions = upperKeys(options.functions ?? {})\n\t\tthis.#order = compile(options.schema)\n\t\tthis.#affected = affected(this.#order)\n\t\tthis.#stop = this.#store.derive(operations => this.#derive(operations))\n\n\t\t// Rows the store was given as they were: what differs is written now, as a change of its own.\n\t\t// `applyFormulas` before the store is made leaves nothing to write.\n\t\tthis.#store.transact(\n\t\t\t() => {\n\t\t\t\tfor (const rowId of this.#store.rowIds()) {\n\t\t\t\t\tthis.#write(rowId, this.#order)\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ origin: FORMULA_ORIGIN }\n\t\t)\n\t}\n\n\t/** What a formula field works out to for a row as it stands now. */\n\tcompute(rowId: RowId, key: string): CellValue {\n\t\tconst formula = this.#order.find(compiled => compiled.field.key === key)\n\n\t\tif (!formula) {\n\t\t\treturn this.#store.get(rowId, key)\n\t\t}\n\n\t\treturn this.#workOut(rowId, this.#order.slice(0, this.#order.indexOf(formula) + 1)).get(key) ?? null\n\t}\n\n\t/** Stops working formulas out. */\n\tdispose(): void {\n\t\tthis.#stop()\n\t}\n\n\t/** Inside a change: the formulas its writes reach, for each row it wrote to or added. */\n\t#derive(operations: readonly StoreOperation[]): void {\n\t\tconst rows = new Map<RowId, Set<string> | \"all\">()\n\n\t\tfor (const operation of operations) {\n\t\t\tif (operation.kind === \"set\") {\n\t\t\t\tif (this.#affected.has(operation.field)) {\n\t\t\t\t\tconst changed = rows.get(operation.rowId)\n\n\t\t\t\t\tif (changed !== \"all\") {\n\t\t\t\t\t\trows.set(operation.rowId, (changed ?? new Set()).add(operation.field))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (operation.kind === \"insert\") {\n\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\trows.set(row.rowId, \"all\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const [rowId, changed] of rows) {\n\t\t\tif (this.#store.has(rowId)) {\n\t\t\t\tthis.#write(rowId, changed === \"all\" ? this.#order : this.#formulasFor(changed))\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Writes what the formulas work out to where it differs from what the row holds. */\n\t#write(rowId: RowId, formulas: readonly Compiled[]): void {\n\t\tfor (const [key, value] of this.#workOut(rowId, formulas)) {\n\t\t\tif (!sameValue(this.#store.get(rowId, key), value)) {\n\t\t\t\tthis.#store.setCell(rowId, key, value)\n\t\t\t}\n\t\t}\n\t}\n\n\t#formulasFor(changed: ReadonlySet<string>): Compiled[] {\n\t\tconst keys = new Set<string>()\n\n\t\tfor (const field of changed) {\n\t\t\tfor (const formula of this.#affected.get(field) ?? []) {\n\t\t\t\tkeys.add(formula.field.key)\n\t\t\t}\n\t\t}\n\n\t\treturn this.#order.filter(formula => keys.has(formula.field.key))\n\t}\n\n\t/** The formulas' values for a row, each seeing the ones worked out before it. */\n\t#workOut(rowId: RowId, formulas: readonly Compiled[]): Map<string, CellValue> {\n\t\tconst values = new Map<string, CellValue>()\n\t\tconst read = (key: string): CellValue =>\n\t\t\tvalues.has(key) ? (values.get(key) as CellValue) : this.#store.get(rowId, key)\n\n\t\tfor (const formula of formulas) {\n\t\t\tvalues.set(formula.field.key, workOut(formula, this.#schema, read, this.#functions))\n\t\t}\n\n\t\treturn values\n\t}\n}\n\n/**\n * Rows with their formula fields worked out, before there is a store: so a sheet opens with the\n * values in place, rather than with a first change that is no user's.\n */\nexport function applyFormulas(\n\tschema: ModuleSchema,\n\trows: readonly RowInit[],\n\tfunctions: Readonly<Record<string, FormulaFunction>> = {}\n): RowInit[] {\n\tconst order = compile(schema)\n\tconst named = upperKeys(functions)\n\n\tif (order.length === 0) {\n\t\treturn [...rows]\n\t}\n\n\treturn rows.map(row => {\n\t\tconst values: Record<string, CellValue | undefined> = { ...row.values }\n\t\tconst read = (key: string): CellValue => values[key] ?? null\n\n\t\tfor (const formula of order) {\n\t\t\tvalues[formula.field.key] = workOut(formula, schema, read, named)\n\t\t}\n\n\t\treturn { ...row, values }\n\t})\n}\n\n// ---------------------------------------------------------------- working out\n\nfunction workOut(\n\tformula: Compiled,\n\tschema: ModuleSchema,\n\tread: (key: string) => CellValue,\n\tfunctions: Readonly<Record<string, FormulaFunction>>\n): CellValue {\n\tconst result = evaluate(formula.tree, {\n\t\tfield: key => (schema.has(key) ? fromCell(schema.field(key), read(key)) : EMPTY),\n\t\tfunctions\n\t})\n\n\treturn toCell(formula.field, result)\n}\n\n/** A cell's value as a formula sees it: by its field's type, as the user does. */\nexport function fromCell(field: FieldSchema, value: CellValue): FormulaValue {\n\tif (value === null) {\n\t\treturn EMPTY\n\t}\n\n\tif (isFormulaError(value)) {\n\t\treturn { type: \"error\", code: value.formulaError }\n\t}\n\n\tswitch (field.type) {\n\t\tcase \"integer\":\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\tcase \"money\":\n\t\tcase \"percent\": {\n\t\t\tconst text = decimalText(value)\n\t\t\tconst number = text === null ? null : parseDecimal(text)\n\n\t\t\t// Text a user typed that is no number stays text, and a sum over it is #VALUE!.\n\t\t\treturn number ? numberValue(number) : textValue(describeValue(value))\n\t\t}\n\t\tcase \"bool\":\n\t\t\treturn typeof value === \"boolean\" ? boolValue(value) : textValue(describeValue(value))\n\t\tcase \"lookup\":\n\t\t\treturn textValue(isLookupValue(value) ? value.label : describeValue(value))\n\t\tcase \"options\": {\n\t\t\tif (Array.isArray(value)) {\n\t\t\t\treturn textValue(value.map(describeValue).join(\", \"))\n\t\t\t}\n\n\t\t\tconst number = typeof value === \"number\" ? parseDecimal(describeValue(value)) : null\n\n\t\t\treturn number ? numberValue(number) : textValue(describeValue(value))\n\t\t}\n\t\tdefault:\n\t\t\treturn textValue(describeValue(value))\n\t}\n}\n\n/** A formula's result as the field it fills holds it: a number to its places, an error as itself. */\nfunction toCell(field: FieldSchema, result: FormulaValue): CellValue {\n\tif (result.type === \"error\") {\n\t\treturn formulaErrorValue(result.code)\n\t}\n\n\tif (result.type === \"empty\") {\n\t\treturn null\n\t}\n\n\tswitch (field.type) {\n\t\tcase \"integer\":\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\tcase \"money\":\n\t\tcase \"percent\": {\n\t\t\tconst number = toNumber(result)\n\n\t\t\tif (\"type\" in number) {\n\t\t\t\treturn formulaErrorValue(number.code)\n\t\t\t}\n\n\t\t\tconst places = field.type === \"integer\" ? 0 : field.decimals\n\n\t\t\treturn decimalToText(places === null ? number : round(number, places, \"half\"))\n\t\t}\n\t\tcase \"bool\": {\n\t\t\tconst truth = toBool(result)\n\n\t\t\treturn typeof truth === \"boolean\" ? truth : formulaErrorValue(truth.code)\n\t\t}\n\t\tdefault: {\n\t\t\tconst text = toText(result)\n\n\t\t\treturn typeof text === \"string\" ? text : formulaErrorValue(text.code)\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------- compiling\n\n/** The schema's formulas, each after the formulas it reads. The schema has already refused a circle. */\nfunction compile(schema: ModuleSchema): Compiled[] {\n\tconst formulas = new Map<string, Compiled & { readonly reads: readonly string[] }>()\n\n\tfor (const field of schema.fields) {\n\t\tif (field.formula !== null) {\n\t\t\tconst tree = parseFormula(field.formula)\n\n\t\t\tformulas.set(field.key, { field, tree, reads: formulaFields(tree) })\n\t\t}\n\t}\n\n\tconst order: Compiled[] = []\n\tconst placed = new Set<string>()\n\tconst place = (key: string): void => {\n\t\tconst formula = formulas.get(key)\n\n\t\tif (!formula || placed.has(key)) {\n\t\t\treturn\n\t\t}\n\n\t\tplaced.add(key)\n\t\tformula.reads.forEach(place)\n\t\torder.push({ field: formula.field, tree: formula.tree })\n\t}\n\n\tfor (const key of formulas.keys()) {\n\t\tplace(key)\n\t}\n\n\treturn order\n}\n\n/** For each field, every formula that reads it, directly or through another formula, in order. */\nfunction affected(order: readonly Compiled[]): Map<string, Compiled[]> {\n\tconst readers = new Map<string, Compiled[]>()\n\n\tfor (const formula of order) {\n\t\tfor (const key of formulaFields(formula.tree)) {\n\t\t\tconst list = readers.get(key) ?? []\n\n\t\t\tlist.push(formula)\n\t\t\treaders.set(key, list)\n\t\t}\n\t}\n\n\tconst result = new Map<string, Compiled[]>()\n\n\tfor (const key of readers.keys()) {\n\t\tconst reached = new Set<string>()\n\t\tconst visit = (field: string): void => {\n\t\t\tfor (const formula of readers.get(field) ?? []) {\n\t\t\t\tif (!reached.has(formula.field.key)) {\n\t\t\t\t\treached.add(formula.field.key)\n\t\t\t\t\tvisit(formula.field.key)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvisit(key)\n\t\tresult.set(\n\t\t\tkey,\n\t\t\torder.filter(formula => reached.has(formula.field.key))\n\t\t)\n\t}\n\n\treturn result\n}\n\nfunction upperKeys(functions: Readonly<Record<string, FormulaFunction>>): Record<string, FormulaFunction> {\n\treturn Object.fromEntries(Object.entries(functions).map(([name, fn]) => [name.toUpperCase(), fn]))\n}\n","/**\n * Help for a person writing a formula: what is being typed where the caret is, which function the\n * caret is inside and at which of its arguments, and the formula written with the fields' labels in\n * place of their keys and back. A formula editor builds its suggestions and its hints from these;\n * the formula itself, and what is saved, is unchanged.\n */\n\n/** A field and the words a person knows it by. */\nexport interface NamedField {\n\treadonly key: string\n\treadonly label: string\n}\n\n/** What is being typed at the caret, to be completed: a field after \"[\", or a function's name. */\nexport interface FormulaToken {\n\treadonly kind: \"field\" | \"function\"\n\t/** What is typed so far, without the \"[\". */\n\treadonly query: string\n\t/** The text a completion replaces: from the \"[\" or the name's first letter to where it ends. */\n\treadonly start: number\n\treadonly end: number\n}\n\n/** The function call the caret is inside, by its name in capitals, and at which argument, from 0. */\nexport interface FormulaCall {\n\treadonly name: string\n\treadonly argument: number\n}\n\nexport interface FormulaCaret {\n\treadonly token: FormulaToken | null\n\treadonly call: FormulaCall | null\n}\n\nconst NAME_START = /[A-Za-z_]/\nconst NAME_PART = /[A-Za-z0-9_.]/\n\n/**\n * Reads a formula up to the caret as the parser would: text in quotes and fields in brackets are\n * passed over, parentheses open and close calls, commas and semicolons move to the next argument.\n */\nexport function formulaCaret(text: string, caret: number): FormulaCaret {\n\tconst end = Math.max(0, Math.min(caret, text.length))\n\tconst calls: { name: string | null; argument: number }[] = []\n\tlet inText = false\n\tlet fieldAt = -1\n\tlet name = \"\"\n\n\tfor (let at = 0; at < end; at++) {\n\t\tconst char = text.charAt(at)\n\n\t\tif (inText) {\n\t\t\tif (char === '\"') {\n\t\t\t\tif (text.charAt(at + 1) === '\"' && at + 1 < end) {\n\t\t\t\t\tat++\n\t\t\t\t} else {\n\t\t\t\t\tinText = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif (fieldAt >= 0) {\n\t\t\tif (char === \"]\") {\n\t\t\t\tfieldAt = -1\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\tinText = true\n\t\t\tname = \"\"\n\t\t} else if (char === \"[\") {\n\t\t\tfieldAt = at\n\t\t\tname = \"\"\n\t\t} else if (char === \"(\") {\n\t\t\tcalls.push({ name: name === \"\" ? null : name.toUpperCase(), argument: 0 })\n\t\t\tname = \"\"\n\t\t} else if (char === \")\") {\n\t\t\tcalls.pop()\n\t\t\tname = \"\"\n\t\t} else if (char === \",\" || char === \";\") {\n\t\t\tconst innermost = calls[calls.length - 1]\n\n\t\t\tif (innermost) {\n\t\t\t\tinnermost.argument++\n\t\t\t}\n\n\t\t\tname = \"\"\n\t\t} else if (name === \"\" ? NAME_START.test(char) : NAME_PART.test(char)) {\n\t\t\tname += char\n\t\t} else {\n\t\t\tname = \"\"\n\t\t}\n\t}\n\n\treturn { token: tokenAt(text, end, inText, fieldAt, name), call: callOf(calls) }\n}\n\n/** The formula with each field it reads written by its label: \"[Aralık fiyatı] * 1.2\". */\nexport function formulaWithLabels(formula: string, fields: readonly NamedField[]): string {\n\tconst labels = new Map(fields.map(field => [field.key, field.label]))\n\n\treturn mapFields(formula, name => labels.get(name) ?? name)\n}\n\n/**\n * The formula with each field written by its key again, as it is saved. A name that is a key stays\n * one; a label names the field only when no other field has it, and is left as written otherwise,\n * for the formula to say it reads a field the schema does not have.\n */\nexport function formulaWithKeys(text: string, fields: readonly NamedField[]): string {\n\tconst keys = new Set(fields.map(field => field.key))\n\tconst byLabel = new Map<string, string | null>()\n\n\tfor (const field of fields) {\n\t\tbyLabel.set(field.label, byLabel.has(field.label) ? null : field.key)\n\t}\n\n\treturn mapFields(text, name => (keys.has(name) ? name : (byLabel.get(name) ?? name)))\n}\n\n// ---------------------------------------------------------------- inside\n\nfunction tokenAt(text: string, caret: number, inText: boolean, fieldAt: number, name: string): FormulaToken | null {\n\tif (inText) {\n\t\treturn null\n\t}\n\n\tif (fieldAt >= 0) {\n\t\t// Editing inside \"[Mevcut fi|yat]\": the completion replaces the whole reference.\n\t\tconst close = text.indexOf(\"]\", caret)\n\t\tconst open = text.indexOf(\"[\", caret)\n\t\tconst end = close >= 0 && (open < 0 || close < open) ? close + 1 : caret\n\n\t\treturn { kind: \"field\", query: text.slice(fieldAt + 1, caret), start: fieldAt, end }\n\t}\n\n\tif (name === \"\" || /^[0-9.]/.test(name)) {\n\t\treturn null\n\t}\n\n\tlet end = caret\n\n\twhile (end < text.length && NAME_PART.test(text.charAt(end))) {\n\t\tend++\n\t}\n\n\treturn { kind: \"function\", query: name, start: caret - name.length, end }\n}\n\n/** The innermost call with a name: inside \"ROUND((a - b) / c\" it is ROUND, at its first argument. */\nfunction callOf(calls: readonly { name: string | null; argument: number }[]): FormulaCall | null {\n\tfor (let index = calls.length - 1; index >= 0; index--) {\n\t\tconst call = calls[index]\n\n\t\tif (call?.name) {\n\t\t\treturn { name: call.name, argument: call.argument }\n\t\t}\n\t}\n\n\treturn null\n}\n\n/** Rewrites every field reference outside quotes; text in quotes is left as it is. */\nfunction mapFields(formula: string, map: (name: string) => string): string {\n\tlet result = \"\"\n\tlet inText = false\n\n\tfor (let at = 0; at < formula.length; at++) {\n\t\tconst char = formula.charAt(at)\n\n\t\tif (inText) {\n\t\t\tresult += char\n\n\t\t\tif (char === '\"') {\n\t\t\t\tif (formula.charAt(at + 1) === '\"') {\n\t\t\t\t\tresult += '\"'\n\t\t\t\t\tat++\n\t\t\t\t} else {\n\t\t\t\t\tinText = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\tinText = true\n\t\t\tresult += char\n\t\t\tcontinue\n\t\t}\n\n\t\tif (char === \"[\") {\n\t\t\tconst close = formula.indexOf(\"]\", at + 1)\n\n\t\t\tif (close < 0) {\n\t\t\t\tresult += formula.slice(at)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tresult += `[${map(formula.slice(at + 1, close))}]`\n\t\t\tat = close\n\t\t\tcontinue\n\t\t}\n\n\t\tresult += char\n\t}\n\n\treturn result\n}\n\n// ---------------------------------------------------------------- addresses and parts\n\nconst ADDRESS = /^([A-Za-z]{1,3})([0-9]*)$/\n\n/**\n * The formula with each cell address read as the field of its column, written with its label:\n * \"D * 1.2\" and \"D2 * 1.2\" alike are \"[Yeni fiyat] * 1.2\". A column formula reads its own row, so\n * an address's row number says nothing. `columns` are the fields as the columns stand on screen, A\n * first. A name followed by \"(\" is a function, TRUE and FALSE are values, and an address past the\n * last column is left as written, for the parser to refuse. Text in quotes and fields in brackets\n * are left as they are.\n */\nexport function formulaFromAddresses(text: string, columns: readonly NamedField[]): string {\n\tlet result = \"\"\n\tlet at = 0\n\n\twhile (at < text.length) {\n\t\tconst char = text.charAt(at)\n\n\t\tif (char === '\"') {\n\t\t\tconst close = closingQuote(text, at)\n\n\t\t\tresult += text.slice(at, close)\n\t\t\tat = close\n\t\t} else if (char === \"[\") {\n\t\t\tconst close = text.indexOf(\"]\", at + 1)\n\t\t\tconst end = close < 0 ? text.length : close + 1\n\n\t\t\tresult += text.slice(at, end)\n\t\t\tat = end\n\t\t} else if (NAME_START.test(char) && !NAME_PART.test(text.charAt(at - 1))) {\n\t\t\tlet end = at\n\n\t\t\twhile (end < text.length && NAME_PART.test(text.charAt(end))) {\n\t\t\t\tend++\n\t\t\t}\n\n\t\t\tconst name = text.slice(at, end)\n\t\t\tconst column = addressColumn(name, text.slice(end))\n\t\t\tconst field = column === null ? undefined : columns[column]\n\n\t\t\tresult += field ? `[${field.label}]` : name\n\t\t\tat = end\n\t\t} else {\n\t\t\tresult += char\n\t\t\tat++\n\t\t}\n\t}\n\n\treturn result\n}\n\n/** Each of the formula's pieces, to draw it: text as written, and each field it reads, with its label. */\nexport interface FormulaPart {\n\treadonly text: string\n\t/** The key of the field this piece reads; null for the rest of the formula. */\n\treadonly field: string | null\n}\n\n/**\n * The formula in pieces, its fields written by their labels: for a formula bar that colours each\n * field it reads, as the sheet colours its column.\n */\nexport function formulaParts(formula: string, fields: readonly NamedField[]): FormulaPart[] {\n\tconst labels = new Map(fields.map(field => [field.key, field.label]))\n\tconst parts: FormulaPart[] = []\n\tlet plain = \"\"\n\tlet at = 0\n\n\twhile (at < formula.length) {\n\t\tconst char = formula.charAt(at)\n\n\t\tif (char === '\"') {\n\t\t\tconst close = closingQuote(formula, at)\n\n\t\t\tplain += formula.slice(at, close)\n\t\t\tat = close\n\t\t} else if (char === \"[\") {\n\t\t\tconst close = formula.indexOf(\"]\", at + 1)\n\n\t\t\tif (close < 0) {\n\t\t\t\tplain += formula.slice(at)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tconst key = formula.slice(at + 1, close)\n\n\t\t\tif (plain !== \"\") {\n\t\t\t\tparts.push({ text: plain, field: null })\n\t\t\t\tplain = \"\"\n\t\t\t}\n\n\t\t\tparts.push({ text: `[${labels.get(key) ?? key}]`, field: key })\n\t\t\tat = close + 1\n\t\t} else {\n\t\t\tplain += char\n\t\t\tat++\n\t\t}\n\t}\n\n\tif (plain !== \"\") {\n\t\tparts.push({ text: plain, field: null })\n\t}\n\n\treturn parts\n}\n\n/** Where the text in quotes that opens at `at` ends: past its closing quote, a doubled quote passed over. */\nfunction closingQuote(text: string, at: number): number {\n\tlet end = at + 1\n\n\twhile (end < text.length) {\n\t\tif (text.charAt(end) === '\"') {\n\t\t\tif (text.charAt(end + 1) === '\"') {\n\t\t\t\tend += 2\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treturn end + 1\n\t\t}\n\n\t\tend++\n\t}\n\n\treturn text.length\n}\n\n/** The column an address names, from 0, or null when the name is not an address: a function, TRUE or FALSE. */\nfunction addressColumn(name: string, after: string): number | null {\n\tconst match = ADDRESS.exec(name)\n\tconst upper = name.toUpperCase()\n\n\tif (!match || after.trimStart().startsWith(\"(\") || upper === \"TRUE\" || upper === \"FALSE\") {\n\t\treturn null\n\t}\n\n\tlet column = 0\n\n\tfor (const letter of (match[1] ?? \"\").toUpperCase()) {\n\t\tcolumn = column * 26 + (letter.charCodeAt(0) - 64)\n\t}\n\n\treturn column - 1\n}\n","import type { RowOutcome } from \"./contract.js\"\nimport { Listeners } from \"./listeners.js\"\nimport type { RowId, RowStore, StoreChange } from \"./rows.js\"\nimport type { RowResults } from \"./session.js\"\nimport type { IssueSet } from \"./validation.js\"\n\n/** Whether a row is to be shown. */\nexport type RowFilter = (rowId: RowId) => boolean\n\n/** Which of two rows comes first: below zero for `a`, above zero for `b`, zero for either. */\nexport type RowOrder = (a: RowId, b: RowId) => number\n\n/** The filter `filter()` sets when given no name. */\nconst DEFAULT_FILTER = \"default\"\n\n/**\n * The rows on screen: all of them in the sheet's order, or those its filters keep, in the order a\n * sort puts them.\n *\n * Filters have names, so several stand together and each is taken away alone: the grid's column\n * filters and an issue panel's \"only rows with issues\" are two, and a row is shown when every one\n * keeps it. Filters and a sort are applied at a moment, as a spreadsheet's are. Fixing the issue that\n * put a row in the view does not take it out under the user's cursor, and changing a price does not\n * move its row; `refresh()` applies them again. Rows added meanwhile are shown, at their places in\n * the sheet's order, or after the others while a sort stands, so a paste lands where the user can\n * see it; rows removed go.\n *\n * Positions on screen are positions in the view; a row's place in the sheet is the store's.\n */\nexport class RowView {\n\treadonly store: RowStore\n\treadonly #listeners = new Listeners<RowView>()\n\treadonly #stop: () => void\n\treadonly #filters = new Map<string, RowFilter>()\n\t#order: RowOrder | null = null\n\t/** The rows shown, while a filter or a sort stands; null when every row is, in the sheet's order. */\n\t#ids: RowId[] | null = null\n\t#positions: Map<RowId, number> | null = null\n\t#version = 0\n\n\tconstructor(store: RowStore) {\n\t\tthis.store = store\n\t\tthis.#stop = store.subscribe(change => this.#onChange(change))\n\t}\n\n\t/** Moves whenever the rows shown change: a filter, a sort, a refresh, rows added or removed. */\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\t/** Whether a filter stands. */\n\tget filtered(): boolean {\n\t\treturn this.#filters.size > 0\n\t}\n\n\t/** Whether a sort stands. */\n\tget sorted(): boolean {\n\t\treturn this.#order !== null\n\t}\n\n\t/**\n\t * Whether the rows shown are other than every row in the sheet's order, filtered or sorted:\n\t * positions on screen and in the sheet then differ.\n\t */\n\tget arranged(): boolean {\n\t\treturn this.#ids !== null\n\t}\n\n\t/** How many rows are shown. */\n\tget size(): number {\n\t\treturn this.#ids?.length ?? this.store.size\n\t}\n\n\trowIdAt(index: number): RowId | undefined {\n\t\treturn this.#ids ? this.#ids[index] : this.store.rowIdAt(index)\n\t}\n\n\t/** Where the row is shown, or -1 when it is not. */\n\tindexOf(rowId: RowId): number {\n\t\tif (!this.#ids) {\n\t\t\treturn this.store.indexOf(rowId)\n\t\t}\n\n\t\tif (!this.#positions) {\n\t\t\tthis.#positions = new Map(this.#ids.map((id, index) => [id, index]))\n\t\t}\n\n\t\treturn this.#positions.get(rowId) ?? -1\n\t}\n\n\t/**\n\t * Shows only the rows `filter` keeps, with the others that stand, as the sheet is now. A filter\n\t * of the same name is replaced.\n\t */\n\tfilter(filter: RowFilter, name: string = DEFAULT_FILTER): void {\n\t\tthis.#filters.set(name, filter)\n\t\tthis.#apply()\n\t}\n\n\t/** Puts the rows shown in this order, as the sheet is now; null goes back to the sheet's. */\n\tsort(order: RowOrder | null): void {\n\t\tif (order === null && this.#order === null) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#order = order\n\t\tthis.#apply()\n\t}\n\n\t/** Applies the filters and the sort again, to the sheet as it is now. */\n\trefresh(): void {\n\t\tif (this.#ids !== null) {\n\t\t\tthis.#apply()\n\t\t}\n\t}\n\n\t/** Takes away the filter of that name; with none, every filter and the sort, showing every row. */\n\tclear(name?: string): void {\n\t\tif (name !== undefined) {\n\t\t\tif (this.#filters.delete(name)) {\n\t\t\t\tthis.#apply()\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tif (this.#ids === null && this.#filters.size === 0 && this.#order === null) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#filters.clear()\n\t\tthis.#order = null\n\t\tthis.#apply()\n\t}\n\n\t/**\n\t * Shows a row a filter left out, in its place among the others, such as when the user goes to an\n\t * issue on it. False when there is no such row.\n\t */\n\tshow(rowId: RowId): boolean {\n\t\tif (!this.store.has(rowId)) {\n\t\t\treturn false\n\t\t}\n\n\t\tconst ids = this.#ids\n\n\t\tif (ids && this.indexOf(rowId) < 0) {\n\t\t\tif (this.#order) {\n\t\t\t\tconst order = this.#order\n\t\t\t\tconst at = ids.findIndex(other => order(rowId, other) < 0)\n\n\t\t\t\tids.splice(at < 0 ? ids.length : at, 0, rowId)\n\t\t\t\tthis.#positions = null\n\t\t\t\tthis.#changed()\n\t\t\t} else {\n\t\t\t\tthis.#rebuild(new Set(ids).add(rowId))\n\t\t\t}\n\t\t}\n\n\t\treturn true\n\t}\n\n\tsubscribe(listener: (view: RowView) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Stops following the store. */\n\tdispose(): void {\n\t\tthis.#stop()\n\t}\n\n\t#apply(): void {\n\t\tif (this.#filters.size === 0 && this.#order === null) {\n\t\t\tif (this.#ids !== null) {\n\t\t\t\tthis.#ids = null\n\t\t\t\tthis.#positions = null\n\t\t\t\tthis.#changed()\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tconst filters = [...this.#filters.values()]\n\t\tconst ids = this.store.rowIds().filter(rowId => filters.every(filter => filter(rowId)))\n\n\t\t// Array.prototype.sort is stable: rows the order holds equal keep the sheet's order.\n\t\tif (this.#order) {\n\t\t\tids.sort(this.#order)\n\t\t}\n\n\t\tthis.#ids = ids\n\t\tthis.#positions = null\n\t\tthis.#changed()\n\t}\n\n\t#onChange(change: StoreChange): void {\n\t\tconst shape = change.operations.some(operation => operation.kind !== \"set\")\n\n\t\tif (!shape) {\n\t\t\treturn\n\t\t}\n\n\t\tif (this.#ids) {\n\t\t\tconst shown = new Set(this.#ids)\n\n\t\t\tfor (const operation of change.operations) {\n\t\t\t\tif (operation.kind === \"insert\") {\n\t\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\t\tshown.add(row.rowId)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Rows removed drop out by themselves: the rebuild keeps only rows the store still has.\n\t\t\tthis.#rebuild(shown)\n\t\t} else {\n\t\t\tthis.#changed()\n\t\t}\n\t}\n\n\t/**\n\t * The rows in `shown` the store still has: in the sheet's order, or, while a sort stands, in the\n\t * order shown so far, with rows new to the view after them in the sheet's order.\n\t */\n\t#rebuild(shown: ReadonlySet<RowId>): void {\n\t\tif (this.#order && this.#ids) {\n\t\t\tconst kept = this.#ids.filter(rowId => this.store.has(rowId))\n\t\t\tconst present = new Set(kept)\n\t\t\tconst added = this.store.rowIds().filter(rowId => shown.has(rowId) && !present.has(rowId))\n\n\t\t\tthis.#ids = [...kept, ...added]\n\t\t} else {\n\t\t\tthis.#ids = this.store.rowIds().filter(rowId => shown.has(rowId))\n\t\t}\n\n\t\tthis.#positions = null\n\t\tthis.#changed()\n\t}\n\n\t#changed(): void {\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n}\n\n/** The rows with an issue on them, standing or waiting to be checked again. */\nexport function rowsWithIssues(issues: IssueSet): RowFilter {\n\treturn rowId => issues.hasIssues(rowId)\n}\n\n/** The rows whose last result from the backend is one of `outcomes`, such as the ones that failed. */\nexport function rowsWithResult(results: RowResults, outcomes: readonly RowOutcome[]): RowFilter {\n\treturn rowId => {\n\t\tconst outcome = results.resultOf(rowId)?.outcome\n\n\t\treturn outcome !== undefined && outcomes.includes(outcome)\n\t}\n}\n","import { add, compare, decimalToText, divide, parseDecimal, round, ZERO, type Decimal } from \"./formula/decimal.js\"\nimport { isFormulaError } from \"./formula/error.js\"\nimport type { FieldSchema, FieldType } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport { decimalText } from \"./values/number.js\"\n\n/**\n * What a status bar says about the cells selected, as a spreadsheet's does: how many hold\n * something, how many hold numbers, and their sum and average, worked out exactly.\n */\nexport interface CellSummary {\n\t/** Cells holding anything. */\n\treadonly filled: number\n\t/** Cells of a numeric field holding a number. */\n\treadonly numbers: number\n\t/** Decimal text, such as `\"3819.8\"`; null when no cell holds a number. */\n\treadonly sum: string | null\n\t/** Decimal text, to 10 places at most; null when no cell holds a number. */\n\treadonly average: string | null\n\t/** The smallest number, as decimal text; null when no cell holds a number. */\n\treadonly min: string | null\n\t/** The largest number, as decimal text; null when no cell holds a number. */\n\treadonly max: string | null\n}\n\nconst NUMERIC: ReadonlySet<FieldType> = new Set([\"integer\", \"decimal\", \"money\", \"quantity\", \"percent\"])\nconst AVERAGE_PLACES = 10\n\n/**\n * Sums the numbers among the cells given, each with its field. Only a numeric field's numbers\n * count: \"123\" typed into a text column is text, as in a spreadsheet, and so is what a cell holds\n * that could not be read as its field's number.\n */\nexport function summarizeCells(\n\tcells: Iterable<{ readonly field: FieldSchema; readonly value: CellValue }>\n): CellSummary {\n\tlet filled = 0\n\tlet numbers = 0\n\tlet sum: Decimal = ZERO\n\tlet min: Decimal | null = null\n\tlet max: Decimal | null = null\n\n\tfor (const { field, value } of cells) {\n\t\tif (value === null) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfilled++\n\n\t\tif (!NUMERIC.has(field.type) || isFormulaError(value)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst text = decimalText(value)\n\t\tconst number = text === null ? null : parseDecimal(text)\n\n\t\tif (number !== null) {\n\t\t\tnumbers++\n\t\t\tsum = add(sum, number)\n\t\t\tmin = min === null || compare(number, min) < 0 ? number : min\n\t\t\tmax = max === null || compare(number, max) > 0 ? number : max\n\t\t}\n\t}\n\n\tif (numbers === 0 || min === null || max === null) {\n\t\treturn Object.freeze({ filled, numbers, sum: null, average: null, min: null, max: null })\n\t}\n\n\tconst average = divide(sum, parseDecimal(String(numbers)) ?? ZERO)\n\n\treturn Object.freeze({\n\t\tfilled,\n\t\tnumbers,\n\t\tsum: decimalToText(sum),\n\t\taverage: average === null ? null : decimalToText(round(average, AVERAGE_PLACES, \"half\")),\n\t\tmin: decimalToText(min),\n\t\tmax: decimalToText(max)\n\t})\n}\n","import { isFormulaError } from \"../formula/error.js\"\nimport type { FieldSchema } from \"../schema.js\"\nimport type { CellValue } from \"../value.js\"\nimport { formatDate } from \"./date.js\"\nimport { decimalText, editNumber, formatNumber, symbolFor } from \"./number.js\"\nimport { datePatternOf, describeValue, isFieldValue, isLookupValue } from \"./read.js\"\nimport type { ValueSettings } from \"./settings.js\"\n\n/** How one column is drawn over its field's own way: a column's format. */\nexport interface CellFormatOptions {\n\t/** Digits after the point a number shows, in place of its field's. The value is not rounded. */\n\treadonly decimals?: number\n}\n\n/**\n * What a cell shows: its value written the sheet's way, \"1.571,41 ₺\", \"31.12.2026\", \"Evet\". A cell\n * still holding text that could not be read shows that text as it was typed.\n */\nexport function formatCell(\n\tfield: FieldSchema,\n\tvalue: CellValue,\n\tsettings: ValueSettings,\n\toptions: CellFormatOptions = {}\n): string {\n\tif (value === null) {\n\t\treturn \"\"\n\t}\n\n\t// A formula that could not be worked out shows its error, as a spreadsheet's cell does.\n\tif (isFormulaError(value)) {\n\t\treturn value.formulaError\n\t}\n\n\tif (!isFieldValue(field, value)) {\n\t\treturn describeValue(value)\n\t}\n\n\tswitch (field.type) {\n\t\tcase \"integer\":\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\tcase \"percent\":\n\t\t\treturn formatNumber(decimalText(value) ?? \"0\", options.decimals ?? digitsFor(field, settings), settings)\n\t\tcase \"money\": {\n\t\t\tconst number = formatNumber(\n\t\t\t\tdecimalText(value) ?? \"0\",\n\t\t\t\toptions.decimals ?? digitsFor(field, settings),\n\t\t\t\tsettings\n\t\t\t)\n\t\t\tconst symbol = symbolFor(field.currency, settings)\n\n\t\t\tif (symbol === null || symbol === \"\") {\n\t\t\t\treturn number\n\t\t\t}\n\n\t\t\treturn settings.symbolPosition === \"before\" ? `${symbol} ${number}` : `${number} ${symbol}`\n\t\t}\n\t\tcase \"bool\":\n\t\t\treturn value ? settings.trueWord : settings.falseWord\n\t\tcase \"date\":\n\t\tcase \"datetime\":\n\t\t\treturn (\n\t\t\t\tformatDate(value as string, field.type === \"datetime\", datePatternOf(field, settings)) ??\n\t\t\t\tdescribeValue(value)\n\t\t\t)\n\t\tcase \"options\": {\n\t\t\tconst values = Array.isArray(value) ? (value as readonly CellValue[]) : [value]\n\n\t\t\treturn values\n\t\t\t\t.map(item => field.options.find(option => option.value === item)?.label ?? describeValue(item))\n\t\t\t\t.join(\", \")\n\t\t}\n\t\tcase \"lookup\":\n\t\t\treturn isLookupValue(value) ? value.label : describeValue(value)\n\t\tcase \"string\":\n\t\t\treturn describeValue(value)\n\t}\n}\n\n/**\n * The text an editor opens with. A number keeps every digit it has and drops the grouping and the\n * symbol, \"1571,4125\" rather than \"1.571,41 ₺\", so editing it never rounds it. The rest is what the\n * cell shows. Either way, reading the text back gives the same value.\n */\nexport function editText(field: FieldSchema, value: CellValue, settings: ValueSettings): string {\n\tif (value === null) {\n\t\treturn \"\"\n\t}\n\n\tif (isFormulaError(value)) {\n\t\treturn value.formulaError\n\t}\n\n\tswitch (field.type) {\n\t\tcase \"integer\":\n\t\tcase \"decimal\":\n\t\tcase \"quantity\":\n\t\tcase \"percent\":\n\t\tcase \"money\": {\n\t\t\tconst number = isFieldValue(field, value) ? decimalText(value) : null\n\n\t\t\treturn number === null ? describeValue(value) : editNumber(number, settings)\n\t\t}\n\t\tdefault:\n\t\t\treturn formatCell(field, value, settings)\n\t}\n}\n\n/** Digits after the point: the field's own, or the settings' default for its type. An integer has none. */\nexport function digitsFor(field: FieldSchema, settings: ValueSettings): number {\n\tswitch (field.type) {\n\t\tcase \"decimal\":\n\t\t\treturn field.decimals ?? settings.decimalDigits\n\t\tcase \"quantity\":\n\t\t\treturn field.decimals ?? settings.quantityDigits\n\t\tcase \"percent\":\n\t\t\treturn field.decimals ?? settings.percentDigits\n\t\tcase \"money\":\n\t\t\treturn field.decimals ?? settings.moneyDigits\n\t\tdefault:\n\t\t\treturn 0\n\t}\n}\n","import { TabulaError } from \"../errors.js\"\nimport { compilePattern } from \"./date.js\"\nimport { fold } from \"./text.js\"\n\n/**\n * How values are written and read in one language: separators, digits, currency symbols, date\n * patterns and the words for yes and no.\n *\n * The same settings as nouxwell/tabula's `NumberSettings`, `DateSettings` and bool words, so a\n * value a template wrote in Turkish is read back here as the PHP side reads it.\n */\nexport interface ValueSettings {\n\treadonly decimalSeparator: string\n\treadonly thousandSeparator: string\n\t/** Digits after the point for a decimal field that does not set its own. */\n\treadonly decimalDigits: number\n\treadonly quantityDigits: number\n\treadonly moneyDigits: number\n\treadonly percentDigits: number\n\t/** Currency code to symbol, such as `{ TRY: \"₺\" }`. A code with no symbol is shown as the code. */\n\treadonly currencySymbols: Readonly<Record<string, string>>\n\t/** Where a money cell's symbol goes, or `none` for no symbol. */\n\treadonly symbolPosition: \"before\" | \"after\" | \"none\"\n\t/** In PHP's notation: `d.m.Y`. The tokens read are d, j, m, n, Y, y, H, G, i and s. */\n\treadonly datePattern: string\n\treadonly dateTimePattern: string\n\treadonly trueWord: string\n\treadonly falseWord: string\n}\n\nconst SYMBOLS = Object.freeze({ TRY: \"₺\", USD: \"$\", EUR: \"€\", GBP: \"£\" })\n\nexport const VALUE_SETTINGS: Readonly<{ tr: ValueSettings; en: ValueSettings }> = Object.freeze({\n\t/** nouxwell/tabula's own defaults, with the Turkish words for yes and no. */\n\ttr: Object.freeze({\n\t\tdecimalSeparator: \",\",\n\t\tthousandSeparator: \".\",\n\t\tdecimalDigits: 2,\n\t\tquantityDigits: 3,\n\t\tmoneyDigits: 2,\n\t\tpercentDigits: 2,\n\t\tcurrencySymbols: SYMBOLS,\n\t\tsymbolPosition: \"after\",\n\t\tdatePattern: \"d.m.Y\",\n\t\tdateTimePattern: \"d.m.Y H:i\",\n\t\ttrueWord: \"Evet\",\n\t\tfalseWord: \"Hayır\"\n\t}),\n\t/** English separators, with ISO dates: \"05/03\" reads two ways in English, \"2026-03-05\" one. */\n\ten: Object.freeze({\n\t\tdecimalSeparator: \".\",\n\t\tthousandSeparator: \",\",\n\t\tdecimalDigits: 2,\n\t\tquantityDigits: 3,\n\t\tmoneyDigits: 2,\n\t\tpercentDigits: 2,\n\t\tcurrencySymbols: SYMBOLS,\n\t\tsymbolPosition: \"before\",\n\t\tdatePattern: \"Y-m-d\",\n\t\tdateTimePattern: \"Y-m-d H:i\",\n\t\ttrueWord: \"Yes\",\n\t\tfalseWord: \"No\"\n\t})\n})\n\n/**\n * Settings from a base with some of them changed, checked.\n *\n * @throws TabulaError when the settings would make values ambiguous, such as the same separator\n * for decimals and thousands\n */\nexport function defineValueSettings(\n\tchanges: Partial<ValueSettings>,\n\tbase: ValueSettings = VALUE_SETTINGS.tr\n): ValueSettings {\n\tconst settings: ValueSettings = { ...base, ...changes }\n\tconst refuse = (message: string): never => {\n\t\tthrow new TabulaError(\"invalid_argument\", `Value settings: ${message}`)\n\t}\n\n\tif (settings.decimalSeparator === \"\" || /\\d/.test(settings.decimalSeparator + settings.thousandSeparator)) {\n\t\trefuse(\"the decimal separator must be given, and neither separator may hold a digit.\")\n\t}\n\n\tif (settings.decimalSeparator === settings.thousandSeparator) {\n\t\trefuse(`\"${settings.decimalSeparator}\" cannot separate both decimals and thousands.`)\n\t}\n\n\tfor (const name of [\"decimalDigits\", \"quantityDigits\", \"moneyDigits\", \"percentDigits\"] as const) {\n\t\tif (!Number.isSafeInteger(settings[name]) || settings[name] < 0) {\n\t\t\trefuse(`${name} must be a whole number, 0 or more; got ${settings[name]}.`)\n\t\t}\n\t}\n\n\tfor (const name of [\"datePattern\", \"dateTimePattern\"] as const) {\n\t\tif (compilePattern(settings[name]) === null) {\n\t\t\trefuse(`${name} \"${settings[name]}\" uses a letter that is not one of d, j, m, n, Y, y, H, G, i, s.`)\n\t\t}\n\t}\n\n\tif (fold(settings.trueWord) === \"\" || fold(settings.trueWord) === fold(settings.falseWord)) {\n\t\trefuse(\"the words for yes and no must be given, and must differ.\")\n\t}\n\n\treturn Object.freeze({ ...settings, currencySymbols: Object.freeze({ ...settings.currencySymbols }) })\n}\n","import { compareDecimal, normalizeDecimal } from \"./decimal.js\"\nimport { isFormulaError } from \"./formula/error.js\"\nimport type { RowId, RowStore } from \"./rows.js\"\nimport type { FieldSchema, ModuleSchema } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport { editText, formatCell } from \"./values/format.js\"\nimport { decimalText } from \"./values/number.js\"\nimport { isLookupValue } from \"./values/read.js\"\nimport { VALUE_SETTINGS, type ValueSettings } from \"./values/settings.js\"\nimport type { RowFilter, RowOrder } from \"./view.js\"\n\n/**\n * Column filters and sorting, as a spreadsheet's header offers them: which values of a column to\n * show, or a range of its numbers or dates, and the order of the rows by one column.\n *\n * Values are told apart by what they are, not by how they are written: 12.5 and \"12.50\" are one\n * number, a record is its id, an option its value. How a value is shown is the grid's business.\n */\n\n/**\n * What a column keeps. `values`: the rows whose value has one of these keys (`filterKey()`; \"\" for\n * an empty cell). `range`: the rows whose number or date lies between `from` and `to`, both kept,\n * either open; written as the cell holds them, decimal text or ISO dates.\n */\nexport type ColumnCondition =\n\t| { readonly kind: \"values\"; readonly keys: readonly string[] }\n\t| { readonly kind: \"range\"; readonly from: string | null; readonly to: string | null }\n\n/** Conditions by field key; a row is shown when it meets every one. */\nexport type ColumnFilters = Readonly<Record<string, ColumnCondition>>\n\nexport interface ColumnSort {\n\treadonly key: string\n\treadonly direction: \"asc\" | \"desc\"\n}\n\n/** One value a column holds, for a filter's list: its key, the value itself, and how many rows hold it. */\nexport interface DistinctValue {\n\treadonly key: string\n\t/** The value as the cell holds it, for the grid to write the sheet's way. Null for empty cells. */\n\treadonly value: CellValue\n\treadonly count: number\n}\n\nconst NUMERIC: ReadonlySet<FieldSchema[\"type\"]> = new Set([\"integer\", \"decimal\", \"money\", \"quantity\", \"percent\"])\nconst DATES: ReadonlySet<FieldSchema[\"type\"]> = new Set([\"date\", \"datetime\"])\n\n/** Whether a field's filter can be a range: numbers and dates. */\nexport function hasRange(field: FieldSchema): boolean {\n\treturn NUMERIC.has(field.type) || DATES.has(field.type)\n}\n\n/**\n * What a value is filtered and listed by. Two values with one key are the same to a filter: 12.5\n * and \"12.50\", a record by its id. \"\" is an empty cell.\n */\nexport function filterKey(field: FieldSchema, value: CellValue): string {\n\tif (value === null) {\n\t\treturn \"\"\n\t}\n\n\tif (isFormulaError(value)) {\n\t\treturn `error:${value.formulaError}`\n\t}\n\n\tif (field.type === \"lookup\") {\n\t\treturn isLookupValue(value) ? `id:${typeof value.id}:${value.id}` : `text:${String(value)}`\n\t}\n\n\tif (NUMERIC.has(field.type)) {\n\t\tconst number = decimalText(value)\n\t\tconst normal = number === null ? null : normalizeDecimal(number)\n\n\t\tif (normal !== null) {\n\t\t\treturn `number:${normal}`\n\t\t}\n\t}\n\n\tif (typeof value === \"boolean\") {\n\t\treturn value ? \"true\" : \"false\"\n\t}\n\n\treturn typeof value === \"string\" ? `text:${value}` : `json:${JSON.stringify(value)}`\n}\n\n/**\n * The keys a cell is filtered by: its value's, or for a cell of several options one per option, so\n * a filter keeping \"Web\" keeps every row that holds it, whatever else it holds. \"\" for an empty cell.\n */\nexport function filterKeys(field: FieldSchema, value: CellValue): string[] {\n\treturn eachValue(field, value).map(([key]) => key)\n}\n\n/** A cell's values with their keys: one, or one per option of a multi-select cell. */\nfunction eachValue(field: FieldSchema, value: CellValue): (readonly [string, CellValue])[] {\n\tif (field.type === \"options\" && field.multiple && Array.isArray(value)) {\n\t\tconst items = [...new Set(value as readonly CellValue[])]\n\n\t\treturn items.length === 0 ? [[\"\", null]] : items.map(item => [filterKey(field, item), item] as const)\n\t}\n\n\treturn [[filterKey(field, value), value]]\n}\n\n/** Shows the rows that meet every column's condition; a key the schema no longer has is passed over. */\nexport function rowsMatching(store: RowStore, schema: ModuleSchema, filters: ColumnFilters): RowFilter {\n\tconst tests: ((rowId: RowId) => boolean)[] = []\n\n\tfor (const [key, condition] of Object.entries(filters)) {\n\t\tif (!schema.has(key)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst field = schema.field(key)\n\n\t\tif (condition.kind === \"values\") {\n\t\t\tconst keys = new Set(condition.keys)\n\n\t\t\ttests.push(rowId => filterKeys(field, store.get(rowId, key)).some(each => keys.has(each)))\n\t\t} else {\n\t\t\ttests.push(rowId => inRange(field, store.get(rowId, key), condition.from, condition.to))\n\t\t}\n\t}\n\n\treturn rowId => tests.every(test => test(rowId))\n}\n\nexport interface SearchOptions {\n\t/** How values are written, to find them as the cells show them. Turkish by default. */\n\treadonly settings?: ValueSettings\n\t/** Whose rules lower the case, such as \"tr\", where \"I\" lowers to \"ı\". \"tr\" by default. */\n\treadonly locale?: string\n\t/** The fields searched; every field of the schema by default. */\n\treadonly fields?: readonly string[]\n}\n\n/**\n * The rows where a cell holds `text`, as the cell shows it (\"1.533,80\", \"Mağaza, Web\", the record's\n * name), case aside. A number is found as it is typed too, \"1533,8\". Empty text keeps every row.\n */\nexport function rowsContaining(\n\tstore: RowStore,\n\tschema: ModuleSchema,\n\ttext: string,\n\toptions: SearchOptions = {}\n): RowFilter {\n\tconst locale = options.locale ?? \"tr\"\n\tconst settings = options.settings ?? VALUE_SETTINGS.tr\n\tconst needle = text.trim().toLocaleLowerCase(locale)\n\tconst fields = (options.fields ?? schema.fields.map(field => field.key))\n\t\t.filter(key => schema.has(key))\n\t\t.map(key => schema.field(key))\n\n\tif (needle === \"\") {\n\t\treturn () => true\n\t}\n\n\tconst holds = (written: string): boolean => written.toLocaleLowerCase(locale).includes(needle)\n\n\treturn rowId =>\n\t\tfields.some(field => {\n\t\t\tconst value = store.get(rowId, field.key)\n\n\t\t\treturn (\n\t\t\t\tvalue !== null &&\n\t\t\t\t(holds(formatCell(field, value, settings)) ||\n\t\t\t\t\t(NUMERIC.has(field.type) && holds(editText(field, value, settings))))\n\t\t\t)\n\t\t})\n}\n\nfunction inRange(field: FieldSchema, value: CellValue, from: string | null, to: string | null): boolean {\n\tconst point = comparable(field, value)\n\n\tif (point === null) {\n\t\treturn false\n\t}\n\n\tconst compare = NUMERIC.has(field.type) ? compareNumbers : compareTexts\n\n\treturn (from === null || compare(point, from) >= 0) && (to === null || compare(point, to) <= 0)\n}\n\n/** A number as normalized decimal text, a date as ISO text; null for empty cells and what is neither. */\nfunction comparable(field: FieldSchema, value: CellValue): string | null {\n\tif (value === null || isFormulaError(value)) {\n\t\treturn null\n\t}\n\n\tif (NUMERIC.has(field.type)) {\n\t\tconst number = decimalText(value)\n\n\t\treturn number === null ? null : normalizeDecimal(number)\n\t}\n\n\tif (DATES.has(field.type)) {\n\t\treturn typeof value === \"string\" && /^\\d{4}-\\d{2}-\\d{2}/.test(value) ? value : null\n\t}\n\n\treturn null\n}\n\nfunction compareNumbers(a: string, b: string): number {\n\tconst left = normalizeDecimal(a)\n\tconst right = normalizeDecimal(b)\n\n\treturn left === null || right === null ? 0 : compareDecimal(left, right)\n}\n\nfunction compareTexts(a: string, b: string): number {\n\treturn a < b ? -1 : a > b ? 1 : 0\n}\n\n/** How a cell ranks before it is compared: values of the field's type, then anything else, then empty. */\nfunction rank(field: FieldSchema, value: CellValue): 0 | 1 | 2 {\n\tif (value === null) {\n\t\treturn 2\n\t}\n\n\tif (isFormulaError(value)) {\n\t\treturn 1\n\t}\n\n\tswitch (field.type) {\n\t\tcase \"integer\":\n\t\tcase \"decimal\":\n\t\tcase \"money\":\n\t\tcase \"quantity\":\n\t\tcase \"percent\":\n\t\tcase \"date\":\n\t\tcase \"datetime\":\n\t\t\treturn comparable(field, value) === null ? 1 : 0\n\t\tcase \"bool\":\n\t\t\treturn typeof value === \"boolean\" ? 0 : 1\n\t\tcase \"lookup\":\n\t\t\treturn isLookupValue(value) ? 0 : 1\n\t\tdefault:\n\t\t\treturn 0\n\t}\n}\n\n/** The text a value is ordered by among text: an option's label, a record's name, the text itself. */\nfunction sortText(field: FieldSchema, value: CellValue): string {\n\tif (field.type === \"options\") {\n\t\tconst values = Array.isArray(value) ? value : [value]\n\n\t\treturn values.map(item => field.options.find(option => option.value === item)?.label ?? String(item)).join(\", \")\n\t}\n\n\tif (isLookupValue(value)) {\n\t\treturn value.label\n\t}\n\n\tif (isFormulaError(value)) {\n\t\treturn value.formulaError\n\t}\n\n\treturn typeof value === \"string\" ? value : JSON.stringify(value)\n}\n\n/**\n * Compares two values of a field, as a sort of its column orders them: numbers by their value,\n * dates in time, no before yes, text in the language's order with numbers in it read as numbers\n * (\"Ürün 9\" before \"Ürün 10\"). Empty cells come last, and cells holding something not of the\n * field's type just before them.\n */\nexport function compareValues(field: FieldSchema, a: CellValue, b: CellValue, locale = \"tr\"): number {\n\tconst rankA = rank(field, a)\n\tconst rankB = rank(field, b)\n\n\tif (rankA !== rankB) {\n\t\treturn rankA - rankB\n\t}\n\n\tif (rankA === 2) {\n\t\treturn 0\n\t}\n\n\tif (rankA === 0) {\n\t\tif (NUMERIC.has(field.type)) {\n\t\t\treturn compareNumbers(comparable(field, a) ?? \"0\", comparable(field, b) ?? \"0\")\n\t\t}\n\n\t\tif (DATES.has(field.type)) {\n\t\t\treturn compareTexts(String(a), String(b))\n\t\t}\n\n\t\tif (field.type === \"bool\") {\n\t\t\treturn Number(a) - Number(b)\n\t\t}\n\t}\n\n\treturn sortText(field, a).localeCompare(sortText(field, b), locale, { numeric: true, sensitivity: \"base\" })\n}\n\n/**\n * The rows in the order of one column. Whichever way it goes, the cells that hold something not of\n * the column's type and then the empty ones stay last: a descending sort of prices puts the dearest\n * first, and \"on iki\" typed into a price and the rows with no price still at the end, where what\n * needs fixing is found together.\n */\nexport function rowOrder(store: RowStore, schema: ModuleSchema, sort: ColumnSort, locale = \"tr\"): RowOrder {\n\tconst field = schema.field(sort.key)\n\tconst sign = sort.direction === \"asc\" ? 1 : -1\n\n\treturn (a, b) => {\n\t\tconst left = store.get(a, field.key)\n\t\tconst right = store.get(b, field.key)\n\t\tconst rankLeft = rank(field, left)\n\t\tconst rankRight = rank(field, right)\n\n\t\tif (rankLeft !== rankRight) {\n\t\t\treturn rankLeft - rankRight\n\t\t}\n\n\t\treturn rankLeft === 2 ? 0 : sign * compareValues(field, left, right, locale)\n\t}\n}\n\n/**\n * The values a column holds among these rows, each once with how many rows hold it, in the order a\n * sort of the column would put them, the empty cells last. `limit` keeps a list of 50,000 different\n * notes from being built whole: the rest are counted in `more`.\n */\nexport function distinctValues(\n\tstore: RowStore,\n\tfield: FieldSchema,\n\trowIds: Iterable<RowId>,\n\toptions: { readonly limit?: number; readonly locale?: string } = {}\n): { readonly values: readonly DistinctValue[]; readonly more: number } {\n\tconst found = new Map<string, { value: CellValue; count: number }>()\n\n\tfor (const rowId of rowIds) {\n\t\tconst value = store.get(rowId, field.key)\n\n\t\t// A cell holding several options counts once under each of them.\n\t\tfor (const [key, each] of eachValue(field, value)) {\n\t\t\tconst entry = found.get(key)\n\n\t\t\tif (entry) {\n\t\t\t\tentry.count++\n\t\t\t} else {\n\t\t\t\tfound.set(key, { value: each, count: 1 })\n\t\t\t}\n\t\t}\n\t}\n\n\tconst locale = options.locale ?? \"tr\"\n\tconst all = [...found.entries()]\n\t\t.map(([key, entry]) => ({ key, value: entry.value, count: entry.count }))\n\t\t.sort((a, b) => compareValues(field, a.value, b.value, locale))\n\tconst limit = options.limit ?? 1000\n\n\treturn { values: all.slice(0, limit), more: Math.max(0, all.length - limit) }\n}\n","import { add, compare, decimalToText, multiply, parseDecimal, subtract, type Decimal } from \"./formula/decimal.js\"\nimport type { FieldSchema, FieldType } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport { isIsoDate } from \"./values/date.js\"\nimport { decimalText } from \"./values/number.js\"\n\n/**\n * Filling cells from those selected, as a spreadsheet's fill handle does: the values go on as a\n * series where they make one, and repeat where they do not.\n *\n * - **One number** is copied; **one date** goes on a day at a time; **one text ending in a number**\n * counts on, \"Ürün 9\" to \"Ürün 10\", keeping leading zeros, \"A009\" to \"A010\".\n * - **Several values with one step between them** go on by that step: 10, 20 gives 30, 40; dates a\n * week apart go on by weeks, and dates on one day of the month go on by months.\n * - **Anything else repeats**, in its order: yes, no, yes, no; or 1, 3, 2, 1, 3, 2.\n *\n * A number is worked out exactly, as decimal text, so 0.1 steps never drift to 0.30000000000000004.\n */\n\n/**\n * - `auto`: as above.\n * - `alternate`: as with Ctrl held in Excel. A fill that would count repeats instead, and one number,\n * which would be copied, counts by one.\n * - `copy`: the values repeat, whatever they are, as Ctrl+D fills.\n */\nexport type FillMode = \"auto\" | \"alternate\" | \"copy\"\n\nexport interface FillOptions {\n\t/** Filling up or left: the values are worked out going back from the first. */\n\treadonly backward?: boolean\n\treadonly mode?: FillMode\n}\n\nconst NUMERIC: ReadonlySet<FieldType> = new Set([\"integer\", \"decimal\", \"money\", \"quantity\", \"percent\"])\nconst DAY_MS = 86_400_000\nconst DAY_SECONDS = 86_400\n/** Text that ends in a number: what comes before it, and its digits. */\nconst TRAILING_NUMBER = /^([\\s\\S]*?)(\\d+)$/\nconst ISO_PARTS = /^(\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}):(\\d{2}):(\\d{2}))?$/\n\n/**\n * The values for `count` cells beyond those given, in the field's own form. `values[0]` goes next\n * to the source and each after it one cell further away: below the last value, or, `backward`,\n * above the first.\n *\n * `field` is the field of every cell given, or null when they come from fields of different kinds,\n * as a fill across columns can: the values then repeat.\n */\nexport function fillValues(\n\tfield: FieldSchema | null,\n\tsource: readonly CellValue[],\n\tcount: number,\n\toptions: FillOptions = {}\n): CellValue[] {\n\tconst length = source.length\n\tconst backward = options.backward ?? false\n\tconst mode = options.mode ?? \"auto\"\n\n\tif (length === 0 || count <= 0) {\n\t\treturn []\n\t}\n\n\tconst series = mode === \"copy\" || field === null ? null : seriesOf(field, source, mode)\n\n\treturn Array.from({ length: count }, (_, index) => {\n\t\tconst distance = index + 1\n\n\t\tif (series !== null) {\n\t\t\treturn series(backward ? -distance : length - 1 + distance)\n\t\t}\n\n\t\t// Repeating backwards keeps the pattern in step: the cell above the first holds the last.\n\t\treturn source[backward ? (length - (distance % length)) % length : index % length] ?? null\n\t})\n}\n\n/**\n * The value at a place in the series the source starts, the first value at 0, or null when the\n * values make none and are to repeat.\n */\ntype Series = (place: number) => CellValue\n\nfunction seriesOf(field: FieldSchema, source: readonly CellValue[], mode: FillMode): Series | null {\n\tif (NUMERIC.has(field.type)) {\n\t\treturn numberSeries(source, mode)\n\t}\n\n\tif (field.type === \"date\" || field.type === \"datetime\") {\n\t\treturn dateSeries(source, field.type === \"datetime\", mode)\n\t}\n\n\tif (field.type === \"string\") {\n\t\treturn textSeries(source, mode)\n\t}\n\n\treturn null\n}\n\nfunction numberSeries(source: readonly CellValue[], mode: FillMode): Series | null {\n\tconst numbers = decimals(source.map(value => decimalText(value)))\n\n\tif (numbers === null) {\n\t\treturn null\n\t}\n\n\tconst step = stepOf(numbers, mode)\n\n\treturn step === null ? null : place => decimalToText(at(numbers, step, place))\n}\n\n/**\n * Text that ends in a number counts on its own, where a number does not: \"Ürün 9\" is a name in a\n * row of names. Text that is only digits fills as a number does.\n */\nfunction textSeries(source: readonly CellValue[], mode: FillMode): Series | null {\n\tconst matches = source.map(value => (typeof value === \"string\" ? TRAILING_NUMBER.exec(value) : null))\n\tconst prefix = matches[0]?.[1]\n\n\tif (prefix === undefined || matches.some(match => match === null || match[1] !== prefix)) {\n\t\treturn null\n\t}\n\n\tconst digits = matches.map(match => match?.[2] ?? \"\")\n\tconst numbers = decimals(digits)\n\t// Alone, a number with a name before it counts; digits alone are copied, as a number is.\n\tconst step = numbers === null ? null : stepOf(numbers, mode, prefix !== \"\")\n\n\tif (numbers === null || step === null) {\n\t\treturn null\n\t}\n\n\t// \"A009\" keeps its three digits; \"A9\" grows to \"A10\" as a number does.\n\tconst width = digits.some(text => text.length > 1 && text.startsWith(\"0\"))\n\t\t? Math.max(...digits.map(d => d.length))\n\t\t: 0\n\n\treturn place => {\n\t\t// As Excel does, a count going below zero is written without its sign: \"Hafta 1\", \"Hafta 0\", \"Hafta 1\".\n\t\tconst number = decimalToText(at(numbers, step, place)).replace(/^-/, \"\")\n\n\t\treturn prefix + number.padStart(width, \"0\")\n\t}\n}\n\nfunction dateSeries(source: readonly CellValue[], withTime: boolean, mode: FillMode): Series | null {\n\tconst dates = source.map(value => (isIsoDate(value, withTime) ? partsOf(value) : null))\n\n\tif (dates.some(date => date === null)) {\n\t\treturn null\n\t}\n\n\tconst parts = dates as DateParts[]\n\tconst months = monthSeries(parts, withTime, mode)\n\n\tif (months !== null) {\n\t\treturn months\n\t}\n\n\t// One date goes on a day at a time; several, by the days (or seconds) between them.\n\tconst points = decimals(parts.map(date => String(withTime ? secondOf(date) : dayOf(date))))\n\tconst step = points === null ? null : stepOf(points, mode, true, withTime ? DAY_SECONDS : 1)\n\n\tif (points === null || step === null) {\n\t\treturn null\n\t}\n\n\treturn place => {\n\t\tconst point = Number(decimalToText(at(points, step, place)))\n\n\t\treturn withTime ? isoOf(fromSecond(point), true) : isoOf(fromDay(point), false)\n\t}\n}\n\n/**\n * Dates on one day of the month, at one time, months apart: the 15th of January, then of February,\n * go on to the 15th of March, as a day count could not. A month too short for the day ends the\n * date at its last: 31 January a month on is 28 February.\n */\nfunction monthSeries(dates: readonly DateParts[], withTime: boolean, mode: FillMode): Series | null {\n\tconst first = dates[0]\n\n\tif (mode !== \"auto\" || dates.length < 2 || first === undefined) {\n\t\treturn null\n\t}\n\n\tconst sameDay = dates.every(\n\t\tdate =>\n\t\t\tdate.day === first.day &&\n\t\t\tdate.hour === first.hour &&\n\t\t\tdate.minute === first.minute &&\n\t\t\tdate.second === first.second\n\t)\n\tconst months = dates.map(date => date.year * 12 + date.month - 1)\n\tconst step = (months[1] ?? 0) - (months[0] ?? 0)\n\n\tif (!sameDay || step === 0 || months.some((month, index) => month - (months[0] ?? 0) !== step * index)) {\n\t\treturn null\n\t}\n\n\treturn place => {\n\t\tconst month = (months[0] ?? 0) + step * place\n\t\tconst year = Math.floor(month / 12)\n\t\tconst inMonth = (month % 12) + 1\n\t\tconst day = Math.min(first.day, daysIn(year, inMonth))\n\n\t\treturn isoOf({ ...first, year, month: inMonth, day }, withTime)\n\t}\n}\n\n// ---------------------------------------------------------------- steps\n\n/**\n * The step between the values, or null when they repeat instead. One value has none of its own:\n * it counts by `single` when `counts` says a lone value of its kind does, and repeats otherwise;\n * `alternate` turns that round, and makes several values repeat.\n */\nfunction stepOf(numbers: readonly Decimal[], mode: FillMode, counts = false, single = 1): Decimal | null {\n\tconst [first, second] = numbers\n\n\tif (first === undefined) {\n\t\treturn null\n\t}\n\n\tif (second === undefined) {\n\t\tconst counting = mode === \"alternate\" ? !counts : counts\n\n\t\treturn counting ? (parseDecimal(String(single)) ?? null) : null\n\t}\n\n\tif (mode === \"alternate\") {\n\t\treturn null\n\t}\n\n\tconst step = subtract(second, first)\n\n\tfor (let index = 2; index < numbers.length; index++) {\n\t\tconst value = numbers[index]\n\t\tconst before = numbers[index - 1]\n\n\t\tif (value === undefined || before === undefined || compare(subtract(value, before), step) !== 0) {\n\t\t\treturn null\n\t\t}\n\t}\n\n\treturn step\n}\n\n/** The value at a place in the series: the first plus so many steps. */\nfunction at(numbers: readonly Decimal[], step: Decimal, place: number): Decimal {\n\tconst first = numbers[0] as Decimal\n\n\treturn add(first, multiply(step, parseDecimal(String(place)) as Decimal))\n}\n\nfunction decimals(texts: readonly (string | null)[]): Decimal[] | null {\n\tconst numbers: Decimal[] = []\n\n\tfor (const text of texts) {\n\t\tconst number = text === null ? null : parseDecimal(text)\n\n\t\tif (number === null) {\n\t\t\treturn null\n\t\t}\n\n\t\tnumbers.push(number)\n\t}\n\n\treturn numbers\n}\n\n// ---------------------------------------------------------------- dates\n\ninterface DateParts {\n\treadonly year: number\n\treadonly month: number\n\treadonly day: number\n\treadonly hour: number\n\treadonly minute: number\n\treadonly second: number\n}\n\nfunction partsOf(iso: string): DateParts | null {\n\tconst match = ISO_PARTS.exec(iso)\n\n\tif (!match) {\n\t\treturn null\n\t}\n\n\tconst [, year, month, day, hour = \"0\", minute = \"0\", second = \"0\"] = match\n\n\treturn {\n\t\tyear: Number(year),\n\t\tmonth: Number(month),\n\t\tday: Number(day),\n\t\thour: Number(hour),\n\t\tminute: Number(minute),\n\t\tsecond: Number(second)\n\t}\n}\n\n/** Days since 1970-01-01. Set field by field: Date.UTC reads the years 0 to 99 as 1900 to 1999. */\nfunction dayOf(date: DateParts): number {\n\tconst moment = new Date(0)\n\n\tmoment.setUTCFullYear(date.year, date.month - 1, date.day)\n\n\treturn Math.round(moment.getTime() / DAY_MS)\n}\n\nfunction secondOf(date: DateParts): number {\n\treturn dayOf(date) * DAY_SECONDS + date.hour * 3600 + date.minute * 60 + date.second\n}\n\nfunction fromDay(day: number): DateParts {\n\tconst moment = new Date(day * DAY_MS)\n\n\treturn {\n\t\tyear: moment.getUTCFullYear(),\n\t\tmonth: moment.getUTCMonth() + 1,\n\t\tday: moment.getUTCDate(),\n\t\thour: 0,\n\t\tminute: 0,\n\t\tsecond: 0\n\t}\n}\n\nfunction fromSecond(second: number): DateParts {\n\tconst day = Math.floor(second / DAY_SECONDS)\n\tconst rest = second - day * DAY_SECONDS\n\n\treturn {\n\t\t...fromDay(day),\n\t\thour: Math.floor(rest / 3600),\n\t\tminute: Math.floor((rest % 3600) / 60),\n\t\tsecond: rest % 60\n\t}\n}\n\nfunction daysIn(year: number, month: number): number {\n\treturn fromDay(dayOf({ year, month: month + 1, day: 1, hour: 0, minute: 0, second: 0 }) - 1).day\n}\n\n/** ISO text, or null past what a cell can hold: the years 1 to 9999. */\nfunction isoOf(date: DateParts, withTime: boolean): string | null {\n\tif (date.year < 1 || date.year > 9999) {\n\t\treturn null\n\t}\n\n\tconst two = (value: number): string => String(value).padStart(2, \"0\")\n\tconst day = `${String(date.year).padStart(4, \"0\")}-${two(date.month)}-${two(date.day)}`\n\n\treturn withTime ? `${day}T${two(date.hour)}:${two(date.minute)}:${two(date.second)}` : day\n}\n","import { normalizeDecimal } from \"./decimal.js\"\nimport { TabulaError } from \"./errors.js\"\nimport {\n\tadd,\n\tcompare,\n\tdecimalToText,\n\tdivide,\n\tmultiply,\n\tONE,\n\tparseDecimal,\n\tround,\n\tZERO,\n\ttype Decimal\n} from \"./formula/decimal.js\"\nimport type { FieldSchema } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport { digitsFor } from \"./values/format.js\"\nimport { decimalText } from \"./values/number.js\"\nimport { canonicalValue } from \"./values/read.js\"\nimport { VALUE_SETTINGS, type ValueSettings } from \"./values/settings.js\"\n\n/**\n * A change made to many numbers at once, as a price list is raised. Amounts are decimal text, so a\n * rise of 5% is worked out exactly.\n *\n * - `percent`: `by` percent more: \"5\" raises by 5%, \"-10\" takes a tenth off.\n * - `add`: `by` more: \"10\", \"-2.5\".\n * - `round`: to a multiple of `step` (\"0.05\", \"1\", \"10\"): the nearest (`half`, the default, with a\n * five going away from zero), the one away from zero (`up`), or the one towards it (`down`).\n */\nexport type Adjustment =\n\t| { readonly kind: \"percent\"; readonly by: string }\n\t| { readonly kind: \"add\"; readonly by: string }\n\t| { readonly kind: \"round\"; readonly step: string; readonly mode?: \"half\" | \"up\" | \"down\" }\n\nconst NUMERIC: ReadonlySet<FieldSchema[\"type\"]> = new Set([\"integer\", \"decimal\", \"money\", \"quantity\", \"percent\"])\nconst HUNDRED: Decimal = Object.freeze({ units: BigInt(100), scale: 0 })\n\n/** Whether the field holds numbers an adjustment can change. */\nexport function isAdjustable(field: FieldSchema): boolean {\n\treturn NUMERIC.has(field.type)\n}\n\n/**\n * The value a number cell holds after `adjustment`, as decimal text with no more digits after the\n * point than the field shows (rounded half away from zero). Null when there is nothing to change:\n * an empty cell, one that holds no number, a field that does not hold numbers, or a value the\n * adjustment leaves as it was.\n *\n * @throws TabulaError `invalid_argument` for an amount that is not decimal text, or a step that is\n * not above zero\n */\nexport function adjustValue(\n\tfield: FieldSchema,\n\tvalue: CellValue,\n\tadjustment: Adjustment,\n\tsettings: ValueSettings = VALUE_SETTINGS.tr\n): string | null {\n\tconst operand = operandOf(adjustment)\n\n\tif (!isAdjustable(field) || value === null) {\n\t\treturn null\n\t}\n\n\tconst text = decimalText(canonicalValue(field, value, settings))\n\tconst number = text === null ? null : parseDecimal(text)\n\n\tif (text === null || number === null) {\n\t\treturn null\n\t}\n\n\tlet result: Decimal\n\n\tswitch (adjustment.kind) {\n\t\tcase \"percent\":\n\t\t\tresult = multiply(number, add(ONE, divide(operand, HUNDRED) ?? ZERO))\n\t\t\tbreak\n\t\tcase \"add\":\n\t\t\tresult = add(number, operand)\n\t\t\tbreak\n\t\tcase \"round\":\n\t\t\tresult = multiply(round(divide(number, operand) ?? ZERO, 0, adjustment.mode ?? \"half\"), operand)\n\t\t\tbreak\n\t}\n\n\tconst written = decimalToText(round(result, digitsFor(field, settings), \"half\"))\n\n\treturn written === normalizeDecimal(text) ? null : written\n}\n\n/** The amount or step, read and checked before any cell is. */\nfunction operandOf(adjustment: Adjustment): Decimal {\n\tconst text = adjustment.kind === \"round\" ? adjustment.step : adjustment.by\n\tconst operand = typeof text === \"string\" ? parseDecimal(text) : null\n\n\tif (operand === null) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_argument\",\n\t\t\t`An adjustment's ${adjustment.kind === \"round\" ? \"step\" : \"amount\"} must be decimal text such as \"5\" or \"0.05\"; got ${JSON.stringify(text)}.`\n\t\t)\n\t}\n\n\tif (adjustment.kind === \"round\" && compare(operand, ZERO) <= 0) {\n\t\tthrow new TabulaError(\"invalid_argument\", `A rounding step must be above zero; got \"${text}\".`)\n\t}\n\n\treturn operand\n}\n","import { filterKeys } from \"./filters.js\"\nimport { Listeners } from \"./listeners.js\"\nimport type { RowId, RowInit, RowStore, StoreChange } from \"./rows.js\"\nimport type { FieldSchema, ModuleSchema } from \"./schema.js\"\nimport type { CellValue } from \"./value.js\"\nimport type { RowFilter } from \"./view.js\"\nimport { canonicalValue } from \"./values/read.js\"\nimport { VALUE_SETTINGS, type ValueSettings } from \"./values/settings.js\"\n\nexport interface SheetChangesOptions {\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\t/**\n\t * The rows as they were loaded, to compare the sheet with: the backend's rows, say, when a draft\n\t * is opened over them. Left out, the store as it is now.\n\t */\n\treadonly baseline?: readonly RowInit[]\n\t/**\n\t * The field that names a row in the baseline and in the sheet alike, such as its product: rows\n\t * are matched by it. Left out, rows are matched by their ids, which the baseline must then carry.\n\t */\n\treadonly key?: string\n\treadonly settings?: ValueSettings\n}\n\nexport interface ChangeSummary {\n\t/** Rows with a change, the added ones among them. */\n\treadonly rows: number\n\t/** Cells holding other than they did. */\n\treadonly cells: number\n\t/** Rows the baseline did not have. */\n\treadonly added: number\n\t/** Rows of the baseline the sheet no longer has. */\n\treadonly missing: number\n}\n\n/**\n * What the user changed since the sheet was loaded: each cell that holds other than it did, and each\n * row added since. Only fields that are sent are followed; a column worked out from others, or one\n * shown for reference, moves with them and has no change of its own.\n *\n * Values are compared as the backend would read them: 12.5 and \"12.50\" are the same, a record is its\n * id, a multi-select's options count in any order. A row whose key changes is another row: an added\n * one, while the one it was goes missing. Taking a change back takes its mark away.\n */\nexport class SheetChanges {\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\n\treadonly #fields: readonly FieldSchema[]\n\treadonly #key: FieldSchema | null\n\treadonly #settings: ValueSettings\n\treadonly #listeners = new Listeners<SheetChanges>()\n\treadonly #stop: () => void\n\t/** Each baseline row by its key, with each followed field's value as it is compared. */\n\treadonly #baseline = new Map<string, ReadonlyMap<string, string>>()\n\t/** The fields changed in each row; in a row added, every one with a value. */\n\treadonly #changed = new Map<RowId, ReadonlySet<string>>()\n\treadonly #added = new Set<RowId>()\n\t/** Each row's key now, and how many rows hold each key, for the baseline rows gone missing. */\n\treadonly #keys = new Map<RowId, string>()\n\treadonly #holding = new Map<string, number>()\n\t#version = 0\n\n\tconstructor(options: SheetChangesOptions) {\n\t\tthis.schema = options.schema\n\t\tthis.store = options.store\n\t\tthis.#settings = options.settings ?? VALUE_SETTINGS.tr\n\t\tthis.#fields = options.schema.fields.filter(field => field.submit)\n\t\tthis.#key =\n\t\t\toptions.key !== undefined && options.schema.has(options.key) ? options.schema.field(options.key) : null\n\t\tthis.#takeBaseline(options.baseline)\n\t\tthis.#stop = this.store.subscribe(change => this.#onChange(change))\n\t}\n\n\t/** Moves on every change of what is changed. */\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\t/** Whether the cell holds other than it did, or is in a row added since. */\n\tisChanged(rowId: RowId, field: string): boolean {\n\t\treturn this.#changed.get(rowId)?.has(field) ?? false\n\t}\n\n\t/** Whether anything in the row changed, or the row was added. */\n\thasChanges(rowId: RowId): boolean {\n\t\treturn this.#changed.has(rowId)\n\t}\n\n\t/** Whether the baseline had no such row. */\n\tisAdded(rowId: RowId): boolean {\n\t\treturn this.#added.has(rowId)\n\t}\n\n\t/** The rows with a change, in sheet order. */\n\tchangedRows(): RowId[] {\n\t\treturn this.store.rowIds().filter(rowId => this.#changed.has(rowId))\n\t}\n\n\tsummary(): ChangeSummary {\n\t\tlet cells = 0\n\t\tlet missing = 0\n\n\t\tfor (const fields of this.#changed.values()) {\n\t\t\tcells += fields.size\n\t\t}\n\n\t\tfor (const key of this.#baseline.keys()) {\n\t\t\tif ((this.#holding.get(key) ?? 0) === 0) {\n\t\t\t\tmissing++\n\t\t\t}\n\t\t}\n\n\t\treturn { rows: this.#changed.size, cells, added: this.#added.size, missing }\n\t}\n\n\t/** Takes the sheet as it is now as what it is compared with, such as after its changes were sent. */\n\treset(): void {\n\t\tthis.#takeBaseline(undefined)\n\t\tthis.#changedNow()\n\t}\n\n\t/** Called after each change of what is changed. Returns the way to stop. */\n\tsubscribe(listener: (changes: SheetChanges) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Stops following the store. */\n\tdispose(): void {\n\t\tthis.#stop()\n\t}\n\n\t#takeBaseline(rows: readonly RowInit[] | undefined): void {\n\t\tthis.#baseline.clear()\n\t\tthis.#changed.clear()\n\t\tthis.#added.clear()\n\t\tthis.#keys.clear()\n\t\tthis.#holding.clear()\n\n\t\tconst entries: [string, ReadonlyMap<string, string>][] = rows\n\t\t\t? rows.flatMap(row => {\n\t\t\t\t\tconst key = this.#key ? this.#compared(this.#key, row.values?.[this.#key.key] ?? null) : row.rowId\n\t\t\t\t\tconst values = new Map(\n\t\t\t\t\t\tthis.#fields.map(field => [field.key, this.#compared(field, row.values?.[field.key] ?? null)])\n\t\t\t\t\t)\n\n\t\t\t\t\treturn key === undefined ? [] : [[this.#key ? key : `id:${key}`, values] as const]\n\t\t\t\t})\n\t\t\t: this.store\n\t\t\t\t\t.rowIds()\n\t\t\t\t\t.map(rowId => [\n\t\t\t\t\t\tthis.#keyOf(rowId),\n\t\t\t\t\t\tnew Map(\n\t\t\t\t\t\t\tthis.#fields.map(field => [\n\t\t\t\t\t\t\t\tfield.key,\n\t\t\t\t\t\t\t\tthis.#compared(field, this.store.get(rowId, field.key))\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t)\n\t\t\t\t\t])\n\n\t\tfor (const [key, values] of entries) {\n\t\t\tif (!this.#baseline.has(key)) {\n\t\t\t\tthis.#baseline.set(key, values)\n\t\t\t}\n\t\t}\n\n\t\tfor (const rowId of this.store.rowIds()) {\n\t\t\tthis.#follow(rowId)\n\t\t}\n\t}\n\n\t#onChange(change: StoreChange): void {\n\t\tconst touched = new Set<RowId>()\n\n\t\tfor (const operation of change.operations) {\n\t\t\tif (operation.kind === \"set\") {\n\t\t\t\ttouched.add(operation.rowId)\n\t\t\t} else if (operation.kind === \"insert\") {\n\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\ttouched.add(row.rowId)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\tthis.#forget(row.rowId)\n\t\t\t\t\ttouched.delete(row.rowId)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const rowId of touched) {\n\t\t\tif (this.store.has(rowId)) {\n\t\t\t\tthis.#follow(rowId)\n\t\t\t}\n\t\t}\n\n\t\tthis.#changedNow()\n\t}\n\n\t/** Compares the row with the baseline's row of its key. */\n\t#follow(rowId: RowId): void {\n\t\tconst key = this.#keyOf(rowId)\n\t\tconst was = this.#keys.get(rowId)\n\n\t\tif (was !== key) {\n\t\t\tif (was !== undefined) {\n\t\t\t\tthis.#holding.set(was, (this.#holding.get(was) ?? 1) - 1)\n\t\t\t}\n\n\t\t\tthis.#keys.set(rowId, key)\n\t\t\tthis.#holding.set(key, (this.#holding.get(key) ?? 0) + 1)\n\t\t}\n\n\t\tconst base = this.#baseline.get(key)\n\t\tconst changed = new Set<string>()\n\n\t\tfor (const field of this.#fields) {\n\t\t\tconst now = this.#compared(field, this.store.get(rowId, field.key))\n\n\t\t\tif (base ? base.get(field.key) !== now : now !== EMPTY) {\n\t\t\t\tchanged.add(field.key)\n\t\t\t}\n\t\t}\n\n\t\tif (changed.size > 0) {\n\t\t\tthis.#changed.set(rowId, changed)\n\t\t} else {\n\t\t\tthis.#changed.delete(rowId)\n\t\t}\n\n\t\tif (base === undefined && changed.size > 0) {\n\t\t\tthis.#added.add(rowId)\n\t\t} else {\n\t\t\tthis.#added.delete(rowId)\n\t\t}\n\t}\n\n\t#forget(rowId: RowId): void {\n\t\tconst key = this.#keys.get(rowId)\n\n\t\tif (key !== undefined) {\n\t\t\tthis.#holding.set(key, (this.#holding.get(key) ?? 1) - 1)\n\t\t\tthis.#keys.delete(rowId)\n\t\t}\n\n\t\tthis.#changed.delete(rowId)\n\t\tthis.#added.delete(rowId)\n\t}\n\n\t#keyOf(rowId: RowId): string {\n\t\treturn this.#key ? this.#compared(this.#key, this.store.get(rowId, this.#key.key)) : `id:${rowId}`\n\t}\n\n\t/** A value as it is compared: what the backend would read it as, options in any order. */\n\t#compared(field: FieldSchema, value: CellValue | undefined): string {\n\t\tif (value === undefined || value === null || value === \"\") {\n\t\t\treturn EMPTY\n\t\t}\n\n\t\tconst read = field.type === \"lookup\" ? value : canonicalValue(field, value, this.#settings)\n\n\t\treturn JSON.stringify(filterKeys(field, read).sort())\n\t}\n\n\t#changedNow(): void {\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n}\n\n/** An empty cell as it is compared; an empty list of options is one too. */\nconst EMPTY = JSON.stringify([\"\"])\n\n/** The rows with a change since the baseline, the added ones among them. */\nexport function rowsChanged(changes: SheetChanges): RowFilter {\n\treturn rowId => changes.hasChanges(rowId)\n}\n","import { TabulaError } from \"./errors.js\"\n\n/**\n * How wide a column may be, and how much of its header is shown.\n *\n * Two upper limits, kept apart on purpose. A column sized from its header stops at `maxAutoWidth`,\n * so one long header does not push the rest of the sheet off screen. A user dragging a column can go\n * on to `maxWidth`, because they asked for it.\n *\n * Characters and pixels are separate too. A header longer than `headerDisplayMaxLength` characters\n * is cut and ends in \"…\"; a shorter one that is still too wide for its column is cut by the column.\n * Either way the full header stays available as the column's tooltip, and no cell value is ever cut\n * in the data, only in how it is drawn.\n */\nexport interface ColumnSizing {\n\t/** Pixels. No column is narrower, however it is sized. */\n\treadonly minWidth: number\n\t/** Pixels. The widest a column is made on its own. */\n\treadonly maxAutoWidth: number\n\t/** Pixels. The widest a user can make a column. */\n\treadonly maxWidth: number\n\t/** Characters of a header shown before it is cut with \"…\". */\n\treadonly headerDisplayMaxLength: number\n\t/** Whether the user can drag the column's edge. */\n\treadonly resizable: boolean\n}\n\nexport const DEFAULT_COLUMN_SIZING: ColumnSizing = Object.freeze({\n\tminWidth: 100,\n\tmaxAutoWidth: 320,\n\tmaxWidth: 1000,\n\theaderDisplayMaxLength: 100,\n\tresizable: true\n})\n\n/**\n * The sizing for one column: the defaults, then each layer over the one before, such as the\n * module's settings and then the column's own.\n *\n * @throws TabulaError when the limits cannot all hold, such as a minimum above a maximum\n */\nexport function resolveColumnSizing(...layers: readonly (Partial<ColumnSizing> | undefined)[]): ColumnSizing {\n\tconst sizing: ColumnSizing = Object.assign({}, DEFAULT_COLUMN_SIZING, ...layers.filter(Boolean))\n\n\tfor (const name of [\"minWidth\", \"maxAutoWidth\", \"maxWidth\", \"headerDisplayMaxLength\"] as const) {\n\t\tconst value = sizing[name]\n\n\t\tif (typeof value !== \"number\" || !Number.isFinite(value) || value < 1) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_argument\",\n\t\t\t\t`Column sizing ${name} must be a number, 1 or more; got ${String(value)}.`\n\t\t\t)\n\t\t}\n\t}\n\n\tif (sizing.minWidth > sizing.maxAutoWidth) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_argument\",\n\t\t\t`Column sizing minWidth ${sizing.minWidth} is above maxAutoWidth ${sizing.maxAutoWidth}.`\n\t\t)\n\t}\n\n\tif (sizing.minWidth > sizing.maxWidth) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_argument\",\n\t\t\t`Column sizing minWidth ${sizing.minWidth} is above maxWidth ${sizing.maxWidth}.`\n\t\t)\n\t}\n\n\treturn Object.freeze(sizing)\n}\n\n/**\n * The header as it is drawn: whole when it fits the character limit, cut and ending in \"…\" when it\n * does not. Counted in characters a reader sees, so a cut never splits one in half.\n */\nexport function headerDisplayText(label: string, maxLength: number): string {\n\tconst characters = Array.from(label)\n\n\treturn characters.length <= maxLength ? label : `${characters.slice(0, maxLength).join(\"\")}…`\n}\n\n/** The width for content of this many pixels, kept between `minWidth` and the automatic maximum. */\nexport function autoColumnWidth(contentWidth: number, sizing: ColumnSizing): number {\n\treturn clamp(Math.ceil(contentWidth), sizing.minWidth, Math.min(sizing.maxAutoWidth, sizing.maxWidth))\n}\n\n/** A width the user set, kept between `minWidth` and `maxWidth`. */\nexport function clampColumnWidth(width: number, sizing: ColumnSizing): number {\n\treturn clamp(Math.round(width), sizing.minWidth, sizing.maxWidth)\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n\treturn Math.min(max, Math.max(min, value))\n}\n\nexport const COLUMN_ALIGNS = Object.freeze([\"left\", \"center\", \"right\"] as const)\nexport type ColumnAlign = (typeof COLUMN_ALIGNS)[number]\n\n/** The most digits after the point a column can be told to show. */\nexport const MAX_SHOWN_DECIMALS = 6\n\n/**\n * How a column's values are drawn. Never what they are: a number shown with fewer digits keeps every\n * digit it has, and the backend is sent the same value whatever is shown.\n */\nexport interface ColumnFormat {\n\t/** Where the values sit in their cells. Left out, numbers on the right and the rest on the left. */\n\treadonly align?: ColumnAlign\n\t/** Digits after the point a number column shows, 0 to `MAX_SHOWN_DECIMALS`. Left out, its field's. */\n\treadonly decimals?: number\n}\n\n/** Each column's format, by field key. */\nexport type ColumnFormats = Readonly<Record<string, ColumnFormat>>\n\n/**\n * A user's arrangement of the columns, kept with their view of the sheet. Only how the columns are\n * shown: hiding a required column relaxes nothing, and its issues are still listed.\n *\n * Keys the schema does not have are passed over, so a layout saved before a column was removed\n * still applies.\n */\nexport interface ColumnLayout {\n\t/** Columns in the order to show them; those left out follow, in the schema's order. */\n\treadonly order?: readonly string[]\n\treadonly hidden?: readonly string[]\n\t/** Columns kept in place on the left while the sheet scrolls sideways. They are shown first. */\n\treadonly pinned?: readonly string[]\n\t/** How each column's values are drawn, by field key. */\n\treadonly formats?: ColumnFormats\n}\n\nexport interface ArrangedColumns<F> {\n\t/** The columns shown, in order: the pinned ones first. */\n\treadonly fields: readonly F[]\n\t/** How many of the first are pinned. */\n\treadonly pinned: number\n}\n\n/** The columns a layout shows, in the order it shows them. */\nexport function arrangeColumns<F extends { readonly key: string }>(\n\tfields: readonly F[],\n\tlayout: ColumnLayout = {}\n): ArrangedColumns<F> {\n\tconst byKey = new Map(fields.map(field => [field.key, field]))\n\tconst hidden = new Set(layout.hidden ?? [])\n\tconst pinned = new Set(layout.pinned ?? [])\n\tconst ordered: F[] = []\n\tconst seen = new Set<string>()\n\n\tfor (const key of [...(layout.order ?? []), ...fields.map(field => field.key)]) {\n\t\tconst field = byKey.get(key)\n\n\t\tif (field && !seen.has(key)) {\n\t\t\tseen.add(key)\n\t\t\tordered.push(field)\n\t\t}\n\t}\n\n\tconst shown = ordered.filter(field => !hidden.has(field.key))\n\tconst first = shown.filter(field => pinned.has(field.key))\n\n\treturn Object.freeze({\n\t\tfields: Object.freeze([...first, ...shown.filter(field => !pinned.has(field.key))]),\n\t\tpinned: first.length\n\t})\n}\n\n/** The layout with one column hidden or shown, pinned or let go. */\nexport function withColumn(\n\tlayout: ColumnLayout,\n\tkey: string,\n\tchange: { readonly hidden?: boolean; readonly pinned?: boolean }\n): ColumnLayout {\n\tconst toggle = (list: readonly string[] | undefined, on: boolean | undefined): readonly string[] | undefined => {\n\t\tif (on === undefined) {\n\t\t\treturn list\n\t\t}\n\n\t\tconst rest = (list ?? []).filter(item => item !== key)\n\n\t\treturn Object.freeze(on ? [...rest, key] : rest)\n\t}\n\n\treturn Object.freeze({\n\t\t...layout,\n\t\t...(change.hidden === undefined ? {} : { hidden: toggle(layout.hidden, change.hidden) }),\n\t\t...(change.pinned === undefined ? {} : { pinned: toggle(layout.pinned, change.pinned) })\n\t})\n}\n\n/**\n * The layout with one column drawn another way: what `change` gives replaces what the column had,\n * a property given as `undefined` goes back to the default, and `null` takes the whole format off.\n *\n * @throws TabulaError `invalid_argument` for an alignment that is not one, or decimals out of 0–6\n */\nexport function withColumnFormat(\n\tlayout: ColumnLayout,\n\tkey: string,\n\tchange: { readonly align?: ColumnAlign | undefined; readonly decimals?: number | undefined } | null\n): ColumnLayout {\n\tconst formats: Record<string, ColumnFormat> = { ...layout.formats }\n\n\tif (change === null) {\n\t\tdelete formats[key]\n\t} else {\n\t\tconst next: { align?: ColumnAlign; decimals?: number } = { ...formats[key] }\n\n\t\tfor (const name of [\"align\", \"decimals\"] as const) {\n\t\t\tif (!(name in change)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst value = change[name]\n\n\t\t\tif (value === undefined) {\n\t\t\t\tdelete next[name]\n\t\t\t} else if (name === \"align\") {\n\t\t\t\tnext.align = alignOf(value)\n\t\t\t} else {\n\t\t\t\tnext.decimals = decimalsOf(value)\n\t\t\t}\n\t\t}\n\n\t\tif (Object.keys(next).length === 0) {\n\t\t\tdelete formats[key]\n\t\t} else {\n\t\t\tformats[key] = next\n\t\t}\n\t}\n\n\tconst rest: ColumnLayout = Object.fromEntries(Object.entries(layout).filter(([name]) => name !== \"formats\"))\n\n\treturn freezeColumnLayout(Object.keys(formats).length === 0 ? rest : { ...rest, formats })\n}\n\n/**\n * Each column's format with each layer over the one before, property by property: a template's\n * formats, then the user's own. What a layer leaves out, a column or one property of it, is the\n * layer under's.\n */\nexport function mergeColumnFormats(...layers: readonly (ColumnFormats | undefined)[]): ColumnFormats {\n\tconst merged: Record<string, { align?: ColumnAlign; decimals?: number }> = {}\n\n\tfor (const layer of layers) {\n\t\tfor (const [key, format] of Object.entries(layer ?? {})) {\n\t\t\tconst next = { ...merged[key] }\n\n\t\t\tif (format.align !== undefined) {\n\t\t\t\tnext.align = format.align\n\t\t\t}\n\n\t\t\tif (format.decimals !== undefined) {\n\t\t\t\tnext.decimals = format.decimals\n\t\t\t}\n\n\t\t\tif (Object.keys(next).length > 0) {\n\t\t\t\tmerged[key] = next\n\t\t\t}\n\t\t}\n\t}\n\n\treturn Object.freeze(\n\t\tObject.fromEntries(Object.entries(merged).map(([key, format]) => [key, Object.freeze(format)]))\n\t)\n}\n\n/**\n * The layout without what `under` already draws: each property of a column's format that `under`\n * gives the same is taken off, and a format left with none goes. What a user keeps of their own once\n * a template says the same, so that a change to the template later reaches them.\n */\nexport function withoutColumnFormats(layout: ColumnLayout, under: ColumnFormats | undefined): ColumnLayout {\n\tlet next = layout\n\n\tfor (const [key, format] of Object.entries(layout.formats ?? {})) {\n\t\tconst base = under?.[key]\n\n\t\tif (!base) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst change: { align?: undefined; decimals?: undefined } = {}\n\n\t\tif (format.align !== undefined && format.align === base.align) {\n\t\t\tchange.align = undefined\n\t\t}\n\n\t\tif (format.decimals !== undefined && format.decimals === base.decimals) {\n\t\t\tchange.decimals = undefined\n\t\t}\n\n\t\tif (Object.keys(change).length > 0) {\n\t\t\tnext = withColumnFormat(next, key, change)\n\t\t}\n\t}\n\n\treturn next\n}\n\n/**\n * A layout read from JSON, each problem reported under `path`: what a view, a draft and a template\n * keep. Undefined when there is none.\n */\nexport function readColumnLayout(\n\tinput: unknown,\n\tpath: string,\n\tproblem: (path: string, message: string) => void\n): ColumnLayout | undefined {\n\tif (input === undefined || input === null) {\n\t\treturn undefined\n\t}\n\n\tconst layout = plainObject(input)\n\n\tif (!layout) {\n\t\tproblem(path, \"must be an object.\")\n\n\t\treturn undefined\n\t}\n\n\tconst result: {\n\t\torder?: readonly string[]\n\t\thidden?: readonly string[]\n\t\tpinned?: readonly string[]\n\t\tformats?: Record<string, ColumnFormat>\n\t} = {}\n\n\tfor (const name of [\"order\", \"hidden\", \"pinned\"] as const) {\n\t\tconst value = layout[name]\n\n\t\tif (value === undefined) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif (!Array.isArray(value) || value.some(item => typeof item !== \"string\")) {\n\t\t\tproblem(`${path}.${name}`, \"must be a list of field keys.\")\n\t\t} else {\n\t\t\tresult[name] = value as string[]\n\t\t}\n\t}\n\n\tif (layout.formats !== undefined && layout.formats !== null) {\n\t\tconst formats = plainObject(layout.formats)\n\n\t\tif (!formats) {\n\t\t\tproblem(`${path}.formats`, \"must be an object of formats by field key.\")\n\t\t} else {\n\t\t\tconst read: Record<string, ColumnFormat> = {}\n\n\t\t\tfor (const [key, value] of Object.entries(formats)) {\n\t\t\t\tconst format = plainObject(value)\n\t\t\t\tconst at = `${path}.formats.${key}`\n\n\t\t\t\tif (!format) {\n\t\t\t\t\tproblem(at, 'must be an object such as { align: \"center\", decimals: 2 }.')\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tconst next: { align?: ColumnAlign; decimals?: number } = {}\n\n\t\t\t\tif (format.align !== undefined) {\n\t\t\t\t\tif ((COLUMN_ALIGNS as readonly unknown[]).includes(format.align)) {\n\t\t\t\t\t\tnext.align = format.align as ColumnAlign\n\t\t\t\t\t} else {\n\t\t\t\t\t\tproblem(`${at}.align`, `must be one of ${COLUMN_ALIGNS.join(\", \")}.`)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (format.decimals !== undefined) {\n\t\t\t\t\tif (isShownDecimals(format.decimals)) {\n\t\t\t\t\t\tnext.decimals = format.decimals\n\t\t\t\t\t} else {\n\t\t\t\t\t\tproblem(`${at}.decimals`, `must be a whole number from 0 to ${MAX_SHOWN_DECIMALS}.`)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (Object.keys(next).length > 0) {\n\t\t\t\t\tread[key] = next\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Object.keys(read).length > 0) {\n\t\t\t\tresult.formats = read\n\t\t\t}\n\t\t}\n\t}\n\n\treturn freezeColumnLayout(result)\n}\n\n/** A copy of the layout that cannot be changed, with nothing in it that it does not hold. */\nexport function freezeColumnLayout(layout: ColumnLayout): ColumnLayout {\n\treturn Object.freeze({\n\t\t...(layout.order ? { order: Object.freeze([...layout.order]) } : {}),\n\t\t...(layout.hidden ? { hidden: Object.freeze([...layout.hidden]) } : {}),\n\t\t...(layout.pinned ? { pinned: Object.freeze([...layout.pinned]) } : {}),\n\t\t...(layout.formats && Object.keys(layout.formats).length > 0\n\t\t\t? {\n\t\t\t\t\tformats: Object.freeze(\n\t\t\t\t\t\tObject.fromEntries(\n\t\t\t\t\t\t\tObject.entries(layout.formats).map(([key, format]) => [key, Object.freeze({ ...format })])\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t: {})\n\t})\n}\n\n/** The layout with its keys passed through `key`: kept, renamed, or dropped where it gives null. */\nexport function mapColumnLayout(layout: ColumnLayout, key: (key: string) => string | null): ColumnLayout {\n\tconst keys = (list: readonly string[]): string[] => list.map(key).filter((item): item is string => item !== null)\n\tconst formats: Record<string, ColumnFormat> = {}\n\n\tfor (const [from, format] of Object.entries(layout.formats ?? {})) {\n\t\tconst to = key(from)\n\n\t\tif (to !== null) {\n\t\t\tformats[to] = format\n\t\t}\n\t}\n\n\treturn freezeColumnLayout({\n\t\t...(layout.order ? { order: keys(layout.order) } : {}),\n\t\t...(layout.hidden ? { hidden: keys(layout.hidden) } : {}),\n\t\t...(layout.pinned ? { pinned: keys(layout.pinned) } : {}),\n\t\t...(Object.keys(formats).length > 0 ? { formats } : {})\n\t})\n}\n\n/** Whether two layouts draw their columns alike: the same formats on the same columns. */\nexport function sameColumnFormats(a: ColumnLayout, b: ColumnLayout): boolean {\n\tconst left = a.formats ?? {}\n\tconst right = b.formats ?? {}\n\tconst keys = Object.keys(left)\n\n\treturn (\n\t\tkeys.length === Object.keys(right).length &&\n\t\tkeys.every(key => left[key]?.align === right[key]?.align && left[key]?.decimals === right[key]?.decimals)\n\t)\n}\n\nfunction alignOf(value: unknown): ColumnAlign {\n\tif (!(COLUMN_ALIGNS as readonly unknown[]).includes(value)) {\n\t\tthrow new TabulaError(\"invalid_argument\", `A column aligns ${COLUMN_ALIGNS.join(\", \")}; got ${String(value)}.`)\n\t}\n\n\treturn value as ColumnAlign\n}\n\nfunction decimalsOf(value: unknown): number {\n\tif (!isShownDecimals(value)) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_argument\",\n\t\t\t`A column shows 0 to ${MAX_SHOWN_DECIMALS} digits after the point; got ${String(value)}.`\n\t\t)\n\t}\n\n\treturn value\n}\n\nfunction isShownDecimals(value: unknown): value is number {\n\treturn Number.isSafeInteger(value) && (value as number) >= 0 && (value as number) <= MAX_SHOWN_DECIMALS\n}\n\nfunction plainObject(value: unknown): Record<string, unknown> | null {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: null\n}\n","import {\n\tarrangeColumns,\n\tfreezeColumnLayout,\n\treadColumnLayout,\n\tsameColumnFormats,\n\ttype ColumnFormat,\n\ttype ColumnLayout\n} from \"./columns.js\"\nimport { TabulaError } from \"./errors.js\"\nimport { hasRange, type ColumnCondition, type ColumnFilters, type ColumnSort } from \"./filters.js\"\nimport type { ModuleSchema } from \"./schema.js\"\n\n/**\n * Saved views of a sheet: how a user arranged it, under a name, to come back to. A view holds what\n * the grid's models hold: the columns (order, hidden, pinned), their widths, the column filters and\n * the sort. Never rows or values: a view is how to look, not what is there.\n *\n * The views of one module are one plain JSON document, kept wherever the application keeps it: in\n * the browser, or on its server for each user. The functions here change it by returning a new one,\n * so it can sit in a Vue ref as it is.\n */\n\nexport const VIEWS_FORMAT = \"tabula-grid.views\"\nexport const VIEWS_VERSION = 1\n/** The longest a view's name may be, in characters. */\nexport const VIEW_NAME_LIMIT = 60\n\n/** How the sheet is arranged, as the grid's `columns`, `column-widths`, `filters` and `sort` hold it. */\nexport interface ViewState {\n\treadonly columns: ColumnLayout\n\treadonly columnWidths: Readonly<Record<string, number>>\n\treadonly filters: ColumnFilters\n\treadonly sort: ColumnSort | null\n}\n\nexport interface SavedView extends ViewState {\n\t/** Made by the application, so a view keeps its id through a rename. */\n\treadonly id: string\n\treadonly name: string\n}\n\nexport interface SavedViews {\n\treadonly format: typeof VIEWS_FORMAT\n\t/** The version of this format. */\n\treadonly version: typeof VIEWS_VERSION\n\treadonly module: string\n\treadonly views: readonly SavedView[]\n\t/** The view a sheet opens in; null for the sheet as its schema lays it out. */\n\treadonly defaultId: string | null\n}\n\n/** The sheet as its schema lays it out: every column in its place, no filter, no sort. */\nexport const PLAIN_VIEW: ViewState = Object.freeze({\n\tcolumns: Object.freeze({}),\n\tcolumnWidths: Object.freeze({}),\n\tfilters: Object.freeze({}),\n\tsort: null\n})\n\n/** Why a name cannot be a view's: empty, longer than `VIEW_NAME_LIMIT`, or another view's. */\nexport type ViewNameProblem = \"empty\" | \"too_long\" | \"taken\"\n\n/** A module with no views saved yet. */\nexport function emptyViews(module: string): SavedViews {\n\treturn freezeViews({ module, views: [], defaultId: null })\n}\n\n/**\n * The view as it applies to the schema now. A column the schema no longer has is passed over, and\n * so is a filter or a sort on one; a range kept on a column that no longer holds numbers or dates is\n * dropped. A view saved before the schema moved on still opens.\n */\nexport function viewFor(state: ViewState, schema: ModuleSchema): ViewState {\n\tconst known = (key: string): boolean => schema.has(key)\n\tconst keys = (list: readonly string[] | undefined): readonly string[] | undefined =>\n\t\tlist === undefined ? undefined : list.filter(known)\n\tconst columns = state.columns\n\tconst order = keys(columns.order)\n\tconst hidden = keys(columns.hidden)\n\tconst pinned = keys(columns.pinned)\n\tconst formats = Object.fromEntries(Object.entries(columns.formats ?? {}).filter(([key]) => known(key))) as Record<\n\t\tstring,\n\t\tColumnFormat\n\t>\n\tconst filters: Record<string, ColumnCondition> = {}\n\n\tfor (const [key, condition] of Object.entries(state.filters)) {\n\t\tif (known(key) && (condition.kind === \"values\" || hasRange(schema.field(key)))) {\n\t\t\tfilters[key] = condition\n\t\t}\n\t}\n\n\treturn freezeState({\n\t\tcolumns: {\n\t\t\t...(order ? { order } : {}),\n\t\t\t...(hidden ? { hidden } : {}),\n\t\t\t...(pinned ? { pinned } : {}),\n\t\t\t...(Object.keys(formats).length > 0 ? { formats } : {})\n\t\t},\n\t\tcolumnWidths: Object.fromEntries(Object.entries(state.columnWidths).filter(([key]) => known(key))),\n\t\tfilters,\n\t\tsort: state.sort && known(state.sort.key) ? state.sort : null\n\t})\n}\n\n/**\n * Whether two states show the sheet alike, against the schema: the same columns in the same places,\n * the same widths, filters and sort. A layout that only writes out the schema's own order is the\n * same as one that leaves it out, and ticked values are the same in any order. What tells a user\n * that the view on screen is no longer the one they chose.\n */\nexport function sameView(schema: ModuleSchema, a: ViewState, b: ViewState): boolean {\n\tconst left = viewFor(a, schema)\n\tconst right = viewFor(b, schema)\n\tconst arranged = (state: ViewState): string => {\n\t\tconst { fields, pinned } = arrangeColumns(schema.fields, state.columns)\n\n\t\treturn `${pinned}|${fields.map(field => field.key).join(\",\")}`\n\t}\n\n\treturn (\n\t\tarranged(left) === arranged(right) &&\n\t\tsameColumnFormats(left.columns, right.columns) &&\n\t\tsameRecord(left.columnWidths, right.columnWidths, (x, y) => x === y) &&\n\t\tsameRecord(left.filters, right.filters, sameCondition) &&\n\t\t(left.sort === null || right.sort === null\n\t\t\t? left.sort === right.sort\n\t\t\t: left.sort.key === right.sort.key && left.sort.direction === right.sort.direction)\n\t)\n}\n\n/**\n * How a view's name is checked. `except` is the view being renamed, which may keep its own name.\n * `locale` is the language names are compared in, the page's: in Turkish \"HAFTALIK\" is \"Haftalık\"\n * in capitals, in English it is not. Left out, the runtime's own, which differs from one machine to\n * the next.\n */\nexport interface ViewNameOptions {\n\treadonly except?: string | null\n\treadonly locale?: string\n}\n\n/** What is wrong with a name for a view, or null when it will do. */\nexport function viewNameProblem(\n\tviews: SavedViews,\n\tname: string,\n\toptions: ViewNameOptions = {}\n): ViewNameProblem | null {\n\tconst trimmed = name.trim()\n\n\tif (trimmed === \"\") {\n\t\treturn \"empty\"\n\t}\n\n\tif ([...trimmed].length > VIEW_NAME_LIMIT) {\n\t\treturn \"too_long\"\n\t}\n\n\tconst names = collator(options.locale)\n\tconst except = options.except ?? null\n\n\treturn views.views.some(view => view.id !== except && names.compare(view.name, trimmed) === 0) ? \"taken\" : null\n}\n\n/**\n * A new view of the sheet as it stands, at the end of the list.\n *\n * @throws TabulaError `invalid_argument` for a name `viewNameProblem` refuses, or an id taken\n */\nexport function addView(\n\tviews: SavedViews,\n\tview: { readonly id: string; readonly name: string } & ViewState,\n\toptions: Pick<ViewNameOptions, \"locale\"> = {}\n): SavedViews {\n\tif (view.id === \"\" || views.views.some(saved => saved.id === view.id)) {\n\t\tthrow new TabulaError(\"invalid_argument\", `A view's id must be new and not empty: \"${view.id}\".`)\n\t}\n\n\tconst name = checkedName(views, view.name, { locale: options.locale })\n\n\treturn freezeViews({ ...views, views: [...views.views, { ...view, name }] })\n}\n\n/** The view saved again with the sheet as it stands now, under its own name. */\nexport function updateView(views: SavedViews, id: string, state: ViewState): SavedViews {\n\treturn change(views, id, view => ({ ...view, ...pickState(state) }))\n}\n\n/** @throws TabulaError `invalid_argument` for a name `viewNameProblem` refuses */\nexport function renameView(\n\tviews: SavedViews,\n\tid: string,\n\tname: string,\n\toptions: Pick<ViewNameOptions, \"locale\"> = {}\n): SavedViews {\n\tconst checked = checkedName(views, name, { except: id, locale: options.locale })\n\n\treturn change(views, id, view => ({ ...view, name: checked }))\n}\n\n/** The views without this one. When it was the one the sheet opens in, the sheet opens as laid out. */\nexport function removeView(views: SavedViews, id: string): SavedViews {\n\tsaved(views, id)\n\n\treturn freezeViews({\n\t\t...views,\n\t\tviews: views.views.filter(view => view.id !== id),\n\t\tdefaultId: views.defaultId === id ? null : views.defaultId\n\t})\n}\n\n/** The view the sheet opens in; null for the sheet as its schema lays it out. */\nexport function setDefaultView(views: SavedViews, id: string | null): SavedViews {\n\tif (id !== null) {\n\t\tsaved(views, id)\n\t}\n\n\treturn freezeViews({ ...views, defaultId: id })\n}\n\n/**\n * Checks what was read back from storage against the views format, every problem at once.\n *\n * @throws TabulaError `invalid_views`, also for views of another module\n */\nexport function readViews(input: unknown, module: string): SavedViews {\n\tconst problems: string[] = []\n\tconst problem = (path: string, message: string): void => {\n\t\tproblems.push(`${path}: ${message}`)\n\t}\n\tconst root = plain(input)\n\n\tif (!root) {\n\t\tthrow new TabulaError(\"invalid_views\", \"Saved views must be an object.\")\n\t}\n\n\tif (root.format !== VIEWS_FORMAT) {\n\t\tproblem(\"format\", `must be \"${VIEWS_FORMAT}\".`)\n\t}\n\n\tif (root.version !== VIEWS_VERSION) {\n\t\tproblem(\"version\", `must be ${VIEWS_VERSION}; views of another version of this format cannot be read.`)\n\t}\n\n\tif (root.module !== module) {\n\t\tproblem(\"module\", `must be \"${module}\", the module these views are read for.`)\n\t}\n\n\tconst views: SavedView[] = []\n\tconst ids = new Set<string>()\n\n\tif (!Array.isArray(root.views)) {\n\t\tproblem(\"views\", \"must be a list.\")\n\t} else {\n\t\troot.views.forEach((item, index) => {\n\t\t\tconst view = readView(item, `views[${index}]`, problem)\n\n\t\t\tif (view && ids.has(view.id)) {\n\t\t\t\tproblem(`views[${index}].id`, `\"${view.id}\" is the id of another view.`)\n\t\t\t} else if (view) {\n\t\t\t\tids.add(view.id)\n\t\t\t\tviews.push(view)\n\t\t\t}\n\t\t})\n\t}\n\n\tconst defaultId = root.defaultId === undefined || root.defaultId === null ? null : root.defaultId\n\n\tif (defaultId !== null && (typeof defaultId !== \"string\" || !ids.has(defaultId))) {\n\t\tproblem(\"defaultId\", \"must be the id of one of the views, or null.\")\n\t}\n\n\tif (problems.length > 0) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_views\",\n\t\t\t`The views cannot be read:\\n${problems.map(line => ` ${line}`).join(\"\\n\")}`\n\t\t)\n\t}\n\n\treturn freezeViews({ module, views, defaultId: defaultId as string | null })\n}\n\n// ---------------------------------------------------------------- inside\n\n/** Names compared as a person reads them, by language: \"Haftalık\" and \"haftalık\" are one name. */\nconst collators = new Map<string, Intl.Collator>()\n\nfunction collator(locale: string | undefined): Intl.Collator {\n\tconst key = locale ?? \"\"\n\tlet found = collators.get(key)\n\n\tif (!found) {\n\t\tfound = new Intl.Collator(locale, { sensitivity: \"accent\" })\n\t\tcollators.set(key, found)\n\t}\n\n\treturn found\n}\n\ntype Plain = Record<string, unknown>\ntype Problem = (path: string, message: string) => void\n\nfunction checkedName(views: SavedViews, name: string, options: ViewNameOptions): string {\n\tconst problem = viewNameProblem(views, name, options)\n\n\tif (problem !== null) {\n\t\tthrow new TabulaError(\"invalid_argument\", `\"${name}\" cannot be a view's name: ${problem}.`)\n\t}\n\n\treturn name.trim()\n}\n\nfunction saved(views: SavedViews, id: string): SavedView {\n\tconst view = views.views.find(item => item.id === id)\n\n\tif (!view) {\n\t\tthrow new TabulaError(\"invalid_argument\", `There is no view \"${id}\".`)\n\t}\n\n\treturn view\n}\n\nfunction change(views: SavedViews, id: string, update: (view: SavedView) => SavedView): SavedViews {\n\tsaved(views, id)\n\n\treturn freezeViews({ ...views, views: views.views.map(view => (view.id === id ? update(view) : view)) })\n}\n\nfunction pickState(state: ViewState): ViewState {\n\treturn { columns: state.columns, columnWidths: state.columnWidths, filters: state.filters, sort: state.sort }\n}\n\nfunction sameRecord<T>(\n\ta: Readonly<Record<string, T>>,\n\tb: Readonly<Record<string, T>>,\n\tsame: (x: T, y: T) => boolean\n): boolean {\n\tconst keys = Object.keys(a)\n\n\treturn keys.length === Object.keys(b).length && keys.every(key => key in b && same(a[key] as T, b[key] as T))\n}\n\nfunction sameCondition(a: ColumnCondition, b: ColumnCondition): boolean {\n\tif (a.kind === \"range\" || b.kind === \"range\") {\n\t\treturn a.kind === \"range\" && b.kind === \"range\" && a.from === b.from && a.to === b.to\n\t}\n\n\tconst keys = new Set(a.keys)\n\n\treturn keys.size === new Set(b.keys).size && b.keys.every(key => keys.has(key))\n}\n\n/**\n * An arrangement read from JSON, each problem reported under `path`: what a template carries for\n * the sheet to open in. Not a saved view: it has no id or name.\n */\nexport function readViewState(\n\tinput: unknown,\n\tpath: string,\n\tproblem: (path: string, message: string) => void\n): ViewState {\n\tconst view = plain(input)\n\n\tif (!view) {\n\t\tproblem(path, \"must be an object.\")\n\n\t\treturn PLAIN_VIEW\n\t}\n\n\treturn freezeState({\n\t\tcolumns: readLayout(view.columns, `${path}.columns`, problem),\n\t\tcolumnWidths: readWidths(view.columnWidths, `${path}.columnWidths`, problem),\n\t\tfilters: readFilters(view.filters, `${path}.filters`, problem),\n\t\tsort: readSort(view.sort, `${path}.sort`, problem)\n\t})\n}\n\nfunction readView(input: unknown, path: string, problem: Problem): SavedView | null {\n\tconst view = plain(input)\n\n\tif (!view) {\n\t\tproblem(path, \"must be an object.\")\n\n\t\treturn null\n\t}\n\n\tlet failed = false\n\tconst fail: Problem = (at, message) => {\n\t\tfailed = true\n\t\tproblem(at, message)\n\t}\n\n\tconst id = typeof view.id === \"string\" && view.id !== \"\" ? view.id : null\n\tconst name = typeof view.name === \"string\" && view.name.trim() !== \"\" ? view.name.trim() : null\n\n\tif (id === null) {\n\t\tfail(`${path}.id`, \"must be a non-empty string.\")\n\t}\n\n\tif (name === null) {\n\t\tfail(`${path}.name`, \"must be a non-empty string.\")\n\t}\n\n\tconst columns = readLayout(view.columns, `${path}.columns`, fail)\n\tconst columnWidths = readWidths(view.columnWidths, `${path}.columnWidths`, fail)\n\tconst filters = readFilters(view.filters, `${path}.filters`, fail)\n\tconst sort = readSort(view.sort, `${path}.sort`, fail)\n\n\treturn failed || id === null || name === null ? null : { id, name, columns, columnWidths, filters, sort }\n}\n\nfunction readLayout(input: unknown, path: string, problem: Problem): ColumnLayout {\n\treturn readColumnLayout(input, path, problem) ?? {}\n}\n\nfunction readWidths(input: unknown, path: string, problem: Problem): Record<string, number> {\n\tif (input === undefined || input === null) {\n\t\treturn {}\n\t}\n\n\tconst widths = plain(input)\n\n\tif (!widths) {\n\t\tproblem(path, \"must be an object of widths by field key.\")\n\n\t\treturn {}\n\t}\n\n\tconst result: Record<string, number> = {}\n\n\tfor (const [key, width] of Object.entries(widths)) {\n\t\tif (typeof width === \"number\" && Number.isFinite(width) && width > 0) {\n\t\t\tresult[key] = width\n\t\t} else {\n\t\t\tproblem(`${path}.${key}`, \"must be a number of pixels.\")\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunction readFilters(input: unknown, path: string, problem: Problem): Record<string, ColumnCondition> {\n\tif (input === undefined || input === null) {\n\t\treturn {}\n\t}\n\n\tconst filters = plain(input)\n\n\tif (!filters) {\n\t\tproblem(path, \"must be an object of conditions by field key.\")\n\n\t\treturn {}\n\t}\n\n\tconst result: Record<string, ColumnCondition> = {}\n\n\tfor (const [key, value] of Object.entries(filters)) {\n\t\tconst condition = plain(value)\n\t\tconst bound = (side: unknown): side is string | null => side === null || typeof side === \"string\"\n\n\t\tif (\n\t\t\tcondition?.kind === \"values\" &&\n\t\t\tArray.isArray(condition.keys) &&\n\t\t\tcondition.keys.every(item => typeof item === \"string\")\n\t\t) {\n\t\t\tresult[key] = { kind: \"values\", keys: condition.keys as string[] }\n\t\t} else if (condition?.kind === \"range\" && bound(condition.from) && bound(condition.to)) {\n\t\t\tresult[key] = { kind: \"range\", from: condition.from, to: condition.to }\n\t\t} else {\n\t\t\tproblem(\n\t\t\t\t`${path}.${key}`,\n\t\t\t\t'must be { kind: \"values\", keys: [...] } or { kind: \"range\", from, to }, each bound text or null.'\n\t\t\t)\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunction readSort(input: unknown, path: string, problem: Problem): ColumnSort | null {\n\tif (input === undefined || input === null) {\n\t\treturn null\n\t}\n\n\tconst sort = plain(input)\n\n\tif (\n\t\tsort &&\n\t\ttypeof sort.key === \"string\" &&\n\t\tsort.key !== \"\" &&\n\t\t(sort.direction === \"asc\" || sort.direction === \"desc\")\n\t) {\n\t\treturn { key: sort.key, direction: sort.direction }\n\t}\n\n\tproblem(path, 'must be { key, direction: \"asc\" or \"desc\" }, or null.')\n\n\treturn null\n}\n\nfunction freezeState(state: ViewState): ViewState {\n\tconst columns = state.columns\n\n\treturn Object.freeze({\n\t\tcolumns: freezeColumnLayout(columns),\n\t\tcolumnWidths: Object.freeze({ ...state.columnWidths }),\n\t\tfilters: Object.freeze(\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(state.filters).map(([key, condition]) => [\n\t\t\t\t\tkey,\n\t\t\t\t\tObject.freeze(\n\t\t\t\t\t\tcondition.kind === \"values\"\n\t\t\t\t\t\t\t? { kind: \"values\", keys: Object.freeze([...condition.keys]) }\n\t\t\t\t\t\t\t: { ...condition }\n\t\t\t\t\t)\n\t\t\t\t])\n\t\t\t)\n\t\t) as ColumnFilters,\n\t\tsort: state.sort ? Object.freeze({ key: state.sort.key, direction: state.sort.direction }) : null\n\t})\n}\n\nfunction freezeViews(views: Pick<SavedViews, \"module\" | \"views\" | \"defaultId\">): SavedViews {\n\treturn Object.freeze({\n\t\tformat: VIEWS_FORMAT,\n\t\tversion: VIEWS_VERSION,\n\t\tmodule: views.module,\n\t\tviews: Object.freeze(\n\t\t\tviews.views.map(view => Object.freeze({ id: view.id, name: view.name, ...freezeState(view) }))\n\t\t),\n\t\tdefaultId: views.defaultId\n\t})\n}\n\nfunction plain(value: unknown): Plain | null {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as Plain) : null\n}\n","import type { CheckInput } from \"./checks.js\"\nimport { compareDecimal, normalizeDecimal } from \"./decimal.js\"\nimport { SchemaError, TabulaError } from \"./errors.js\"\nimport type { RowInit } from \"./rows.js\"\nimport {\n\tModuleSchema,\n\ttype FieldInput,\n\ttype FieldSchema,\n\ttype FieldType,\n\ttype ModuleSchemaInput,\n\ttype RuleInput\n} from \"./schema.js\"\nimport type { StyleRuleInput } from \"./styles.js\"\nimport type { CellValue } from \"./value.js\"\nimport { readViewState, type ViewState } from \"./views.js\"\n\n/**\n * A template: the sheet as an authorized user prepares it for a task, layered on the module schema\n * the developer wrote and under each user's own views. \"Aralık zam listesi\" on the price update.\n *\n * It may change a column's header, require a field the schema leaves optional, keep a column from\n * being typed into, narrow a field's limits, give new rows a value, add columns of its own, add row\n * checks (a field required when another holds a value, two fields compared), and say how the sheet\n * opens. A check only adds to what is refused, so a template may add any; it cannot take one away. It may never loosen what the schema asks: a field the schema requires stays\n * required, a limit can only get narrower, and a column the schema keeps read-only stays so. Its own\n * columns are never sent for processing: they are a helper the user works with, kept in the draft,\n * or worked out from the row by a formula.\n *\n * Only a module whose schema says `customization: \"controlled\"` (or `\"free\"`) takes a template. A\n * template the schema does not allow is refused whole, not half applied: a rule it would have\n * tightened and quietly did not is a rule nobody checks.\n */\n\nexport const TEMPLATE_FORMAT = \"tabula-grid.template\"\nexport const TEMPLATE_VERSION = 1\n\n/** What a template changes about one of the schema's fields. */\nexport interface TemplateFieldChange {\n\t/** The column's header. The key, and everything the backend sees, stays the same. */\n\treadonly label?: string\n\t/** Only `true`: a field the schema requires cannot be made optional. */\n\treadonly required?: boolean\n\t/** Only `false`: a column the schema keeps read-only cannot be opened. */\n\treadonly editable?: boolean\n\t/** Limits added or narrowed: a `min` above the schema's, a `max` below it, `unique`. */\n\treadonly rules?: readonly RuleInput[]\n\t/** A new row's value, as the schema's `default`. */\n\treadonly default?: FieldInput[\"default\"]\n}\n\nexport interface GridTemplate {\n\treadonly format: typeof TEMPLATE_FORMAT\n\t/** The version of this format. */\n\treadonly version: typeof TEMPLATE_VERSION\n\treadonly module: string\n\treadonly id: string\n\treadonly name: string\n\t/** Changes to the schema's fields, by key. */\n\treadonly fields: Readonly<Record<string, TemplateFieldChange>>\n\t/** Columns of the template's own, after the schema's: written as a schema's fields are, never sent. */\n\treadonly columns: readonly FieldInput[]\n\t/** Row checks added after the schema's own, written as a schema's; see `RowCheck`. */\n\treadonly checks: readonly CheckInput[]\n\t/** Colour rules added after the schema's own, written as a schema's; see `StyleRule`. */\n\treadonly styles: readonly StyleRuleInput[]\n\t/**\n\t * How the sheet opens: the columns, widths, filters and sort, under each user's own views. Its\n\t * column formats are not only where the sheet starts: they lie under each user's own whatever view\n\t * is open, so every user of the template sees them (`mergeColumnFormats`, the grid's\n\t * `defaultFormats`).\n\t */\n\treadonly view: ViewState | null\n}\n\n/** One thing wrong with a template, and where: `fields.newPrice.rules[0]`, `columns[1].key`. */\nexport interface TemplateProblem {\n\treadonly path: string\n\treadonly message: string\n}\n\nconst CHANGES = [\"label\", \"required\", \"editable\", \"rules\", \"default\"] as const\nconst NUMERIC: ReadonlySet<FieldType> = new Set([\"integer\", \"decimal\", \"money\", \"quantity\", \"percent\"])\n\n/**\n * Checks what was read back from storage, or sent by the backend, against the template format:\n * its shape, every problem at once. Whether the template fits the schema is `templateProblems`.\n *\n * @throws TabulaError `invalid_template`, also for a template of another module\n */\nexport function readTemplate(input: unknown, module: string): GridTemplate {\n\tconst problems: TemplateProblem[] = []\n\tconst problem = (path: string, message: string): void => {\n\t\tproblems.push({ path, message })\n\t}\n\tconst root = plain(input)\n\n\tif (!root) {\n\t\tthrow new TabulaError(\"invalid_template\", \"A template must be an object.\")\n\t}\n\n\tif (root.format !== TEMPLATE_FORMAT) {\n\t\tproblem(\"format\", `must be \"${TEMPLATE_FORMAT}\".`)\n\t}\n\n\tif (root.version !== TEMPLATE_VERSION) {\n\t\tproblem(\"version\", `must be ${TEMPLATE_VERSION}; a template of another version of this format cannot be read.`)\n\t}\n\n\tif (root.module !== module) {\n\t\tproblem(\"module\", `must be \"${module}\", the module the template is read for.`)\n\t}\n\n\tconst text = (name: \"id\" | \"name\"): string => {\n\t\tconst value = root[name]\n\n\t\tif (typeof value !== \"string\" || value.trim() === \"\") {\n\t\t\tproblem(name, \"must be a non-empty string.\")\n\n\t\t\treturn \"\"\n\t\t}\n\n\t\treturn name === \"name\" ? value.trim() : value\n\t}\n\n\tconst id = text(\"id\")\n\tconst name = text(\"name\")\n\tconst fields: Record<string, TemplateFieldChange> = {}\n\tconst fieldsRoot = root.fields === undefined ? {} : plain(root.fields)\n\n\tif (!fieldsRoot) {\n\t\tproblem(\"fields\", \"must be an object of changes by field key.\")\n\t} else {\n\t\tfor (const [key, change] of Object.entries(fieldsRoot)) {\n\t\t\tif (plain(change)) {\n\t\t\t\tfields[key] = change as TemplateFieldChange\n\t\t\t} else {\n\t\t\t\tproblem(`fields.${key}`, \"must be an object of changes.\")\n\t\t\t}\n\t\t}\n\t}\n\n\tconst columns: FieldInput[] = []\n\n\tif (root.columns !== undefined && !Array.isArray(root.columns)) {\n\t\tproblem(\"columns\", \"must be a list of columns.\")\n\t} else {\n\t\t;((root.columns as unknown[] | undefined) ?? []).forEach((column, index) => {\n\t\t\tif (plain(column)) {\n\t\t\t\tcolumns.push(column as unknown as FieldInput)\n\t\t\t} else {\n\t\t\t\tproblem(`columns[${index}]`, \"must be an object, written as a schema's field.\")\n\t\t\t}\n\t\t})\n\t}\n\n\tconst checks: CheckInput[] = []\n\n\tif (root.checks !== undefined && !Array.isArray(root.checks)) {\n\t\tproblem(\"checks\", \"must be a list of row checks.\")\n\t} else {\n\t\t;((root.checks as unknown[] | undefined) ?? []).forEach((check, index) => {\n\t\t\tif (plain(check)) {\n\t\t\t\tchecks.push(check as unknown as CheckInput)\n\t\t\t} else {\n\t\t\t\tproblem(`checks[${index}]`, \"must be an object, written as a schema's check.\")\n\t\t\t}\n\t\t})\n\t}\n\n\tconst styles: StyleRuleInput[] = []\n\n\tif (root.styles !== undefined && !Array.isArray(root.styles)) {\n\t\tproblem(\"styles\", \"must be a list of colour rules.\")\n\t} else {\n\t\t;((root.styles as unknown[] | undefined) ?? []).forEach((rule, index) => {\n\t\t\tif (plain(rule)) {\n\t\t\t\tstyles.push(rule as unknown as StyleRuleInput)\n\t\t\t} else {\n\t\t\t\tproblem(`styles[${index}]`, \"must be an object, written as a schema's colour rule.\")\n\t\t\t}\n\t\t})\n\t}\n\n\tconst view = root.view === undefined || root.view === null ? null : readViewState(root.view, \"view\", problem)\n\n\tif (problems.length > 0) {\n\t\tthrow new TabulaError(\"invalid_template\", describeProblems(\"The template cannot be read\", problems))\n\t}\n\n\treturn Object.freeze({\n\t\tformat: TEMPLATE_FORMAT,\n\t\tversion: TEMPLATE_VERSION,\n\t\tmodule,\n\t\tid,\n\t\tname,\n\t\tfields: Object.freeze(fields),\n\t\tcolumns: Object.freeze(columns),\n\t\tchecks: Object.freeze(checks),\n\t\tstyles: Object.freeze(styles),\n\t\tview\n\t})\n}\n\n/**\n * Everything that keeps a template from applying to the schema, each with where it is: a change\n * that loosens the schema, a field the module does not have, a column with a field's key, a limit\n * that leaves no value possible. Empty when it applies.\n */\nexport function templateProblems(schema: ModuleSchema, template: GridTemplate): TemplateProblem[] {\n\treturn merge(schema, template).problems\n}\n\n/**\n * The module schema with the template on it: the schema the sheet works with, its checks and its\n * formulas. The template's columns come after the schema's fields, never sent.\n *\n * @throws TabulaError `invalid_template` with every problem `templateProblems` finds\n */\nexport function applyTemplate(schema: ModuleSchema, template: GridTemplate): ModuleSchema {\n\tconst { problems, applied } = merge(schema, template)\n\n\tif (problems.length > 0 || applied === null) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_template\",\n\t\t\tdescribeProblems(`Template \"${template.name}\" cannot be applied to module \"${schema.module}\"`, problems)\n\t\t)\n\t}\n\n\treturn applied\n}\n\n/**\n * New rows with the schema's defaults where they give no value: the rows a paste or an import adds.\n * A value given, even an empty one, is kept; only a field the row leaves out takes its default.\n */\nexport function withDefaults(schema: ModuleSchema, rows: number | readonly RowInit[]): RowInit[] {\n\tconst list: readonly RowInit[] = typeof rows === \"number\" ? Array.from({ length: rows }, () => ({})) : rows\n\tconst defaults = schema.fields.filter(field => field.default !== null)\n\n\tif (defaults.length === 0) {\n\t\treturn [...list]\n\t}\n\n\treturn list.map(row => {\n\t\tconst values: Record<string, CellValue> = {}\n\n\t\tfor (const field of defaults) {\n\t\t\tvalues[field.key] = field.default\n\t\t}\n\n\t\tfor (const [key, value] of Object.entries(row.values ?? {})) {\n\t\t\tif (value !== undefined) {\n\t\t\t\tvalues[key] = value\n\t\t\t}\n\t\t}\n\n\t\treturn { ...row, values }\n\t})\n}\n\n// ---------------------------------------------------------------- inside\n\ntype Plain = Record<string, unknown>\ntype Problem = (path: string, message: string) => void\n\nfunction merge(\n\tschema: ModuleSchema,\n\ttemplate: GridTemplate\n): { problems: TemplateProblem[]; applied: ModuleSchema | null } {\n\tconst problems: TemplateProblem[] = []\n\tconst problem: Problem = (path, message) => {\n\t\tproblems.push({ path, message })\n\t}\n\n\tif (schema.customization === \"fixed\") {\n\t\tproblem(\"(root)\", `module \"${schema.module}\" is fixed: its schema says no template may change it.`)\n\t}\n\n\tif (template.module !== schema.module) {\n\t\tproblem(\"module\", `is \"${template.module}\"; the schema is module \"${schema.module}\".`)\n\t}\n\n\tfor (const key of Object.keys(template.fields)) {\n\t\tif (!schema.has(key)) {\n\t\t\tproblem(`fields.${key}`, `is not a field of module \"${schema.module}\".`)\n\t\t}\n\t}\n\n\tconst json = schema.toJSON()\n\tconst fields: FieldInput[] = json.fields.map(field => {\n\t\tconst change = template.fields[field.key]\n\n\t\treturn change ? changed(field, schema.field(field.key), change, `fields.${field.key}`, problem) : field\n\t})\n\n\tconst columns = template.columns.map((column, index) => {\n\t\tconst path = `columns[${index}]`\n\n\t\tif (typeof column.key === \"string\" && schema.has(column.key)) {\n\t\t\tproblem(\n\t\t\t\t`${path}.key`,\n\t\t\t\t`\"${column.key}\" is a field of the module; a template's column needs a key of its own.`\n\t\t\t)\n\t\t}\n\n\t\tif (column.type === \"lookup\") {\n\t\t\tproblem(\n\t\t\t\t`${path}.type`,\n\t\t\t\t\"cannot be lookup: a record is something the backend gives, and a template's column is never sent.\"\n\t\t\t)\n\t\t}\n\n\t\tif ((column as { submit?: unknown }).submit === true) {\n\t\t\tproblem(`${path}.submit`, \"cannot be true: a template's column is never sent for processing.\")\n\t\t}\n\n\t\treturn { ...column, submit: false }\n\t})\n\n\tif (problems.length > 0) {\n\t\treturn { problems, applied: null }\n\t}\n\n\tconst ownChecks = json.checks ?? []\n\tconst ownStyles = json.styles ?? []\n\tconst merged: ModuleSchemaInput = {\n\t\t...json,\n\t\tfields: [...fields, ...columns],\n\t\t...(ownChecks.length + template.checks.length > 0 ? { checks: [...ownChecks, ...template.checks] } : {}),\n\t\t...(ownStyles.length + template.styles.length > 0 ? { styles: [...ownStyles, ...template.styles] } : {})\n\t}\n\n\ttry {\n\t\treturn { problems, applied: ModuleSchema.from(merged) }\n\t} catch (error) {\n\t\tif (!(error instanceof SchemaError)) {\n\t\t\tthrow error\n\t\t}\n\n\t\t// The schema's own reading found it: its paths name the merged fields and checks, so they are\n\t\t// put back as the template's, a field by its key, a column and a check by its place.\n\t\tfor (const item of error.problems) {\n\t\t\tconst field = /^fields\\[(\\d+)\\](.*)$/.exec(item.path)\n\t\t\tconst check = /^checks\\[(\\d+)\\](.*)$/.exec(item.path)\n\t\t\tconst style = /^styles\\[(\\d+)\\](.*)$/.exec(item.path)\n\t\t\tlet path = item.path\n\n\t\t\tif (field) {\n\t\t\t\tconst index = Number(field[1])\n\n\t\t\t\tpath =\n\t\t\t\t\tindex < json.fields.length\n\t\t\t\t\t\t? `fields.${json.fields[index]?.key ?? index}${field[2] ?? \"\"}`\n\t\t\t\t\t\t: `columns[${index - json.fields.length}]${field[2] ?? \"\"}`\n\t\t\t} else if (check && Number(check[1]) >= ownChecks.length) {\n\t\t\t\tpath = `checks[${Number(check[1]) - ownChecks.length}]${check[2] ?? \"\"}`\n\t\t\t} else if (style && Number(style[1]) >= ownStyles.length) {\n\t\t\t\tpath = `styles[${Number(style[1]) - ownStyles.length}]${style[2] ?? \"\"}`\n\t\t\t}\n\n\t\t\tproblem(path, item.message)\n\t\t}\n\n\t\treturn { problems, applied: null }\n\t}\n}\n\n/** One of the schema's fields, as the template changes it, as long as it only narrows. */\nfunction changed(\n\tjson: FieldInput,\n\tfield: FieldSchema,\n\tchange: TemplateFieldChange,\n\tpath: string,\n\tproblem: Problem\n): FieldInput {\n\tconst next: FieldInput = { ...json }\n\n\tfor (const name of Object.keys(change)) {\n\t\tif (!(CHANGES as readonly string[]).includes(name)) {\n\t\t\tproblem(`${path}.${name}`, `is not something a template changes; it changes ${CHANGES.join(\", \")}.`)\n\t\t}\n\t}\n\n\tif (change.label !== undefined) {\n\t\tnext.label = change.label\n\t}\n\n\tif (change.required !== undefined) {\n\t\tif (typeof change.required !== \"boolean\") {\n\t\t\tproblem(`${path}.required`, \"must be true or false.\")\n\t\t} else if (!change.required && field.required) {\n\t\t\tproblem(\n\t\t\t\t`${path}.required`,\n\t\t\t\t\"would make the field optional; the schema requires it, and a template only narrows.\"\n\t\t\t)\n\t\t} else if (change.required) {\n\t\t\tnext.required = true\n\t\t}\n\t}\n\n\tif (change.editable !== undefined) {\n\t\tif (typeof change.editable !== \"boolean\") {\n\t\t\tproblem(`${path}.editable`, \"must be true or false.\")\n\t\t} else if (change.editable && !field.editable) {\n\t\t\tproblem(\n\t\t\t\t`${path}.editable`,\n\t\t\t\t\"would open the column for typing; the schema keeps it read-only, and a template only narrows.\"\n\t\t\t)\n\t\t} else if (!change.editable) {\n\t\t\tnext.editable = false\n\t\t}\n\t}\n\n\tif (change.rules !== undefined) {\n\t\tnext.rules = narrowed(field, change.rules, `${path}.rules`, problem)\n\t}\n\n\tif (change.default !== undefined) {\n\t\tnext.default = change.default\n\t}\n\n\treturn next\n}\n\n/**\n * The field's rules with the template's: each the narrower of the two. A rule the schema does not\n * have is added; one that would let through what the schema refuses is a problem.\n */\nfunction narrowed(field: FieldSchema, rules: unknown, path: string, problem: Problem): RuleInput[] {\n\tconst result = new Map<string, RuleInput>(field.rules.map(rule => [rule.rule, { ...rule } as RuleInput]))\n\n\tif (!Array.isArray(rules)) {\n\t\tproblem(path, \"must be a list of rules.\")\n\n\t\treturn [...result.values()]\n\t}\n\n\trules.forEach((raw: unknown, index) => {\n\t\tconst at = `${path}[${index}]`\n\t\tconst rule = plain(raw)\n\t\tconst kind = rule?.rule\n\t\tconst own = field.rules.find(item => item.rule === kind)\n\n\t\tif (!rule || typeof kind !== \"string\") {\n\t\t\tproblem(at, 'must be a rule such as { \"rule\": \"min\", \"value\": \"1\" }.')\n\n\t\t\treturn\n\t\t}\n\n\t\tswitch (kind) {\n\t\t\tcase \"min\":\n\t\t\tcase \"max\": {\n\t\t\t\tconst value =\n\t\t\t\t\ttypeof rule.value === \"string\" || typeof rule.value === \"number\"\n\t\t\t\t\t\t? normalizeDecimal(rule.value)\n\t\t\t\t\t\t: null\n\n\t\t\t\tif (!NUMERIC.has(field.type)) {\n\t\t\t\t\tproblem(at, `${kind} does not apply to a ${field.type} field.`)\n\t\t\t\t} else if (value === null) {\n\t\t\t\t\tproblem(`${at}.value`, 'must be a decimal number such as \"1\" or \"12.5\".')\n\t\t\t\t} else if (\n\t\t\t\t\town &&\n\t\t\t\t\t\"value\" in own &&\n\t\t\t\t\tcompareDecimal(value, String(own.value)) * (kind === \"min\" ? 1 : -1) < 0\n\t\t\t\t) {\n\t\t\t\t\tproblem(\n\t\t\t\t\t\tat,\n\t\t\t\t\t\t`${kind} ${value} would let through what the schema's ${kind} ${own.value} refuses; a template only narrows.`\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tresult.set(kind, { rule: kind, value })\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcase \"minLength\":\n\t\t\tcase \"maxLength\": {\n\t\t\t\tconst value = rule.value\n\n\t\t\t\tif (field.type !== \"string\") {\n\t\t\t\t\tproblem(at, `${kind} does not apply to a ${field.type} field.`)\n\t\t\t\t} else if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n\t\t\t\t\tproblem(`${at}.value`, \"must be a whole number of characters, 0 or more.\")\n\t\t\t\t} else if (own && \"value\" in own && (value - Number(own.value)) * (kind === \"minLength\" ? 1 : -1) < 0) {\n\t\t\t\t\tproblem(\n\t\t\t\t\t\tat,\n\t\t\t\t\t\t`${kind} ${value} would let through what the schema's ${kind} ${own.value} refuses; a template only narrows.`\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tresult.set(kind, { rule: kind, value })\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcase \"unique\":\n\t\t\t\tresult.set(kind, { rule: kind })\n\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tproblem(\n\t\t\t\t\t`${at}.rule`,\n\t\t\t\t\t`${JSON.stringify(kind)} is not a rule; expected one of min, max, minLength, maxLength, unique.`\n\t\t\t\t)\n\t\t}\n\t})\n\n\treturn [...result.values()]\n}\n\nfunction describeProblems(heading: string, problems: readonly TemplateProblem[]): string {\n\treturn `${heading}:\\n${problems.map(item => ` ${item.path}: ${item.message}`).join(\"\\n\")}`\n}\n\nfunction plain(value: unknown): Plain | null {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as Plain) : null\n}\n","import { TabulaError } from \"./errors.js\"\nimport { Listeners } from \"./listeners.js\"\n\n/**\n * Which cells are selected, in the positions the user sees: row and column indexes on screen, after\n * sorting, filtering and hiding. Turning a position into a row id and a field is the view's job.\n *\n * It follows Excel. The active cell, the one typing goes into, stays put while Shift extends the\n * selection; what moves is the opposite corner, the head. A plain move collapses the selection onto\n * one cell again.\n */\n\nexport interface CellPosition {\n\treadonly row: number\n\treadonly col: number\n}\n\n/** Inclusive on all four sides. */\nexport interface CellRange {\n\treadonly top: number\n\treadonly left: number\n\treadonly bottom: number\n\treadonly right: number\n}\n\nexport type Direction = \"up\" | \"down\" | \"left\" | \"right\"\n\nexport interface MoveOptions {\n\t/** Move the head and keep the active cell, as Shift does. */\n\treadonly extend?: boolean\n}\n\n/** Whether the cell at a position is empty, for `jump()`. */\nexport type IsBlank = (row: number, col: number) => boolean\n\nconst STEPS: Readonly<Record<Direction, CellPosition>> = {\n\tup: { row: -1, col: 0 },\n\tdown: { row: 1, col: 0 },\n\tleft: { row: 0, col: -1 },\n\tright: { row: 0, col: 1 }\n}\n\nexport class Selection {\n\t#rowCount: number\n\t#colCount: number\n\t#active: CellPosition | null = null\n\t/** The corner that stays when Shift extends the selection; usually the active cell. */\n\t#pivot: CellPosition | null = null\n\t#head: CellPosition | null = null\n\treadonly #listeners = new Listeners<Selection>()\n\n\tconstructor(rowCount: number, colCount: number) {\n\t\tthis.#rowCount = requireCount(rowCount, \"rowCount\")\n\t\tthis.#colCount = requireCount(colCount, \"colCount\")\n\n\t\tif (!this.#isEmpty()) {\n\t\t\tthis.#active = this.#pivot = this.#head = cell(0, 0)\n\t\t}\n\t}\n\n\tget rowCount(): number {\n\t\treturn this.#rowCount\n\t}\n\n\tget colCount(): number {\n\t\treturn this.#colCount\n\t}\n\n\t/** The cell typing goes into. Null when the grid has no cells. */\n\tget active(): CellPosition | null {\n\t\treturn this.#active\n\t}\n\n\t/** The corner Shift moves; the one to keep on screen while extending. Null when the grid has no cells. */\n\tget head(): CellPosition | null {\n\t\treturn this.#head\n\t}\n\n\tget range(): CellRange | null {\n\t\treturn this.#pivot && this.#head ? rangeOf(this.#pivot, this.#head) : null\n\t}\n\n\tcontains(row: number, col: number): boolean {\n\t\tconst range = this.range\n\n\t\treturn range !== null && within(range, cell(row, col))\n\t}\n\n\tisActive(row: number, col: number): boolean {\n\t\treturn this.#active !== null && this.#active.row === row && this.#active.col === col\n\t}\n\n\t/** Goes to a cell, kept inside the grid: `moveTo(Infinity, Infinity)` is the last cell. */\n\tmoveTo(row: number, col: number, options: MoveOptions = {}): void {\n\t\tconst target = this.#clamp(row, col)\n\n\t\tif (target === null || this.#active === null || this.#pivot === null) {\n\t\t\treturn\n\t\t}\n\n\t\tif (options.extend) {\n\t\t\tthis.#commit(this.#active, this.#pivot, target)\n\t\t} else {\n\t\t\tthis.#commit(target, target, target)\n\t\t}\n\t}\n\n\t/** Moves by a number of rows and columns: from the head when extending, from the active cell otherwise. */\n\tmove(rows: number, cols: number, options: MoveOptions = {}): void {\n\t\tconst from = options.extend ? this.#head : this.#active\n\n\t\tif (from !== null) {\n\t\t\tthis.moveTo(from.row + rows, from.col + cols, options)\n\t\t}\n\t}\n\n\t/**\n\t * Ctrl and an arrow, as in Excel: inside a run of filled cells, to the end of the run; otherwise to\n\t * the next filled cell, or to the edge of the grid when there is none.\n\t */\n\tjump(direction: Direction, isBlank: IsBlank, options: MoveOptions = {}): void {\n\t\tconst from = options.extend ? this.#head : this.#active\n\n\t\tif (from === null) {\n\t\t\treturn\n\t\t}\n\n\t\tconst target = edgeOf(from, STEPS[direction], this.#rowCount, this.#colCount, isBlank)\n\n\t\tthis.moveTo(target.row, target.col, options)\n\t}\n\n\t/** Whole rows, `from` through `to`. The active cell goes to the first column of `from`. */\n\tselectRows(from: number, to: number = from): void {\n\t\tconst start = this.#clamp(from, 0)\n\t\tconst end = this.#clamp(to, Infinity)\n\n\t\tif (start !== null && end !== null) {\n\t\t\tthis.#commit(start, start, end)\n\t\t}\n\t}\n\n\t/** Whole columns, `from` through `to`. The active cell goes to the first row of `from`. */\n\tselectColumns(from: number, to: number = from): void {\n\t\tconst start = this.#clamp(0, from)\n\t\tconst end = this.#clamp(Infinity, to)\n\n\t\tif (start !== null && end !== null) {\n\t\t\tthis.#commit(start, start, end)\n\t\t}\n\t}\n\n\t/** Every cell. The active cell stays where it is. */\n\tselectAll(): void {\n\t\tconst start = this.#clamp(0, 0)\n\t\tconst end = this.#clamp(Infinity, Infinity)\n\n\t\tif (start !== null && end !== null && this.#active !== null) {\n\t\t\tthis.#commit(this.#active, start, end)\n\t\t}\n\t}\n\n\t/** The grid changed size, such as after rows were deleted. Everything is kept inside it. */\n\tresize(rowCount: number, colCount: number): void {\n\t\tthis.#rowCount = requireCount(rowCount, \"rowCount\")\n\t\tthis.#colCount = requireCount(colCount, \"colCount\")\n\n\t\tif (this.#isEmpty()) {\n\t\t\tif (this.#active !== null) {\n\t\t\t\tthis.#active = this.#pivot = this.#head = null\n\t\t\t\tthis.#listeners.emit(this)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tconst active = this.#active ?? cell(0, 0)\n\t\tconst pivot = this.#pivot ?? active\n\t\tconst head = this.#head ?? active\n\n\t\tthis.#commit(this.#clampCell(active), this.#clampCell(pivot), this.#clampCell(head))\n\t}\n\n\t/** Called after each change of the selection. Returns the way to stop. */\n\tsubscribe(listener: (selection: Selection) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t#isEmpty(): boolean {\n\t\treturn this.#rowCount === 0 || this.#colCount === 0\n\t}\n\n\t#clamp(row: number, col: number): CellPosition | null {\n\t\tif (Number.isNaN(row) || Number.isNaN(col)) {\n\t\t\tthrow new TabulaError(\"invalid_argument\", `A cell position must be a number; got ${row}, ${col}.`)\n\t\t}\n\n\t\treturn this.#isEmpty() ? null : this.#clampCell(cell(row, col))\n\t}\n\n\t#clampCell(position: CellPosition): CellPosition {\n\t\treturn cell(\n\t\t\tMath.min(this.#rowCount - 1, Math.max(0, Math.trunc(position.row))),\n\t\t\tMath.min(this.#colCount - 1, Math.max(0, Math.trunc(position.col)))\n\t\t)\n\t}\n\n\t#commit(active: CellPosition, pivot: CellPosition, head: CellPosition): void {\n\t\t// Shrinking the selection past the active cell would leave typing going into a cell that is not\n\t\t// selected. The fixed corner takes over.\n\t\tconst settled = within(rangeOf(pivot, head), active) ? active : pivot\n\n\t\tif (same(settled, this.#active) && same(pivot, this.#pivot) && same(head, this.#head)) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#active = settled\n\t\tthis.#pivot = pivot\n\t\tthis.#head = head\n\t\tthis.#listeners.emit(this)\n\t}\n}\n\nfunction edgeOf(\n\tfrom: CellPosition,\n\tstep: CellPosition,\n\trowCount: number,\n\tcolCount: number,\n\tisBlank: IsBlank\n): CellPosition {\n\tconst inside = (position: CellPosition): boolean =>\n\t\tposition.row >= 0 && position.row < rowCount && position.col >= 0 && position.col < colCount\n\tconst blank = (position: CellPosition): boolean => isBlank(position.row, position.col)\n\tconst advance = (position: CellPosition): CellPosition => cell(position.row + step.row, position.col + step.col)\n\n\tlet current = from\n\tlet next = advance(current)\n\n\tif (!inside(next)) {\n\t\treturn current\n\t}\n\n\tif (!blank(current) && !blank(next)) {\n\t\twhile (inside(next) && !blank(next)) {\n\t\t\tcurrent = next\n\t\t\tnext = advance(next)\n\t\t}\n\n\t\treturn current\n\t}\n\n\tcurrent = next\n\n\twhile (blank(current)) {\n\t\tnext = advance(current)\n\n\t\tif (!inside(next)) {\n\t\t\treturn current\n\t\t}\n\n\t\tcurrent = next\n\t}\n\n\treturn current\n}\n\nfunction cell(row: number, col: number): CellPosition {\n\treturn Object.freeze({ row, col })\n}\n\nfunction rangeOf(a: CellPosition, b: CellPosition): CellRange {\n\treturn Object.freeze({\n\t\ttop: Math.min(a.row, b.row),\n\t\tleft: Math.min(a.col, b.col),\n\t\tbottom: Math.max(a.row, b.row),\n\t\tright: Math.max(a.col, b.col)\n\t})\n}\n\nfunction within(range: CellRange, position: CellPosition): boolean {\n\treturn (\n\t\tposition.row >= range.top &&\n\t\tposition.row <= range.bottom &&\n\t\tposition.col >= range.left &&\n\t\tposition.col <= range.right\n\t)\n}\n\nfunction same(a: CellPosition, b: CellPosition | null): boolean {\n\treturn b !== null && a.row === b.row && a.col === b.col\n}\n\nfunction requireCount(count: number, name: string): number {\n\tif (!Number.isSafeInteger(count) || count < 0) {\n\t\tthrow new TabulaError(\"invalid_argument\", `${name} must be a whole number, 0 or more; got ${count}.`)\n\t}\n\n\treturn count\n}\n","/**\n * Cells as a spreadsheet puts them on the clipboard: separated by tabs, rows separated by line\n * breaks. A cell holding a tab, a line break or a quote is wrapped in quotes, its own quotes doubled.\n * Excel, Google Sheets and LibreOffice all write this and read it back.\n */\n\n/**\n * The rows and cells in clipboard text.\n *\n * One line break at the very end ends the last row rather than starting another: Excel puts one\n * after every copied range. Rows may differ in length; nothing is padded. A line break inside a\n * quoted cell is always \"\\n\", however it arrived.\n *\n * A quote opens a quoted cell only at the start of a cell. One that never closes was a character,\n * not a wrapper, and the cell is read again from it as plain text: otherwise a cell that merely\n * starts with `\"` would swallow every row after it.\n */\nexport function parseTsv(text: string): string[][] {\n\tif (text === \"\") {\n\t\treturn []\n\t}\n\n\tconst rows: string[][] = []\n\tlet row: string[] = []\n\tlet cell = \"\"\n\tlet index = 0\n\tlet cellStart = true\n\tlet quoteAt = -1\n\tlet literalAt = -1\n\n\tfor (;;) {\n\t\twhile (index < text.length) {\n\t\t\tconst char = text.charAt(index)\n\n\t\t\tif (quoteAt >= 0) {\n\t\t\t\tif (char === '\"') {\n\t\t\t\t\tif (text.charAt(index + 1) === '\"') {\n\t\t\t\t\t\tcell += '\"'\n\t\t\t\t\t\tindex += 2\n\t\t\t\t\t} else {\n\t\t\t\t\t\tquoteAt = -1\n\t\t\t\t\t\tindex++\n\t\t\t\t\t}\n\t\t\t\t} else if (char === \"\\r\") {\n\t\t\t\t\t// One way of writing a line break inside a cell. The Windows clipboard turns \"\\n\" into\n\t\t\t\t\t// \"\\r\\n\" on the way through, so the same text would otherwise arrive two ways.\n\t\t\t\t\tcell += \"\\n\"\n\t\t\t\t\tindex += text.charAt(index + 1) === \"\\n\" ? 2 : 1\n\t\t\t\t} else {\n\t\t\t\t\tcell += char\n\t\t\t\t\tindex++\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (char === '\"' && cellStart && index !== literalAt) {\n\t\t\t\tquoteAt = index\n\t\t\t\tcellStart = false\n\t\t\t\tindex++\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (char === \"\\t\") {\n\t\t\t\trow.push(cell)\n\t\t\t\tcell = \"\"\n\t\t\t\tcellStart = true\n\t\t\t\tindex++\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (char === \"\\n\" || char === \"\\r\") {\n\t\t\t\trow.push(cell)\n\t\t\t\trows.push(row)\n\t\t\t\trow = []\n\t\t\t\tcell = \"\"\n\t\t\t\tcellStart = true\n\t\t\t\tindex += char === \"\\r\" && text.charAt(index + 1) === \"\\n\" ? 2 : 1\n\n\t\t\t\tif (index >= text.length) {\n\t\t\t\t\treturn rows\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcell += char\n\t\t\tcellStart = false\n\t\t\tindex++\n\t\t}\n\n\t\tif (quoteAt < 0) {\n\t\t\tbreak\n\t\t}\n\n\t\tliteralAt = quoteAt\n\t\tindex = quoteAt\n\t\tquoteAt = -1\n\t\tcell = \"\"\n\t\tcellStart = true\n\t}\n\n\trow.push(cell)\n\trows.push(row)\n\n\treturn rows\n}\n\n/** Rows of cells as clipboard text, quoting the cells that need it. No line break after the last row. */\nexport function toTsv(rows: readonly (readonly string[])[]): string {\n\treturn rows.map(row => row.map(quoteCell).join(\"\\t\")).join(\"\\r\\n\")\n}\n\nfunction quoteCell(text: string): string {\n\treturn /[\\t\\n\\r\"]/.test(text) ? `\"${text.replace(/\"/g, '\"\"')}\"` : text\n}\n","/**\n * CSV as spreadsheets write it (RFC 4180): cells separated by a delimiter, rows by line breaks, a\n * cell holding the delimiter, a quote or a line break wrapped in quotes, its own quotes doubled.\n *\n * Which delimiter depends on who wrote the file. Excel uses the list separator of the machine's\n * language, and in Turkish, where the comma is the decimal separator, that is a semicolon.\n */\n\nexport type CsvDelimiter = \",\" | \";\" | \"\\t\"\n\nconst DELIMITERS: readonly CsvDelimiter[] = [\";\", \",\", \"\\t\"]\n\nexport interface CsvReadOptions {\n\t/** Left out, it is told from the first line: whichever of `;`, `,` and tab splits it most. */\n\treadonly delimiter?: CsvDelimiter\n}\n\n/**\n * The rows and cells of CSV text. A byte order mark at the start is dropped, line breaks are\n * `\\r\\n` or `\\n`, a line break inside a quoted cell is kept as `\\n`, and the line break that ends the\n * last row starts no other. Empty lines are rows with one empty cell, as in the file.\n */\nexport function parseCsv(text: string, options: CsvReadOptions = {}): string[][] {\n\tconst source = text.startsWith(\"\\uFEFF\") ? text.slice(1) : text\n\n\tif (source === \"\") {\n\t\treturn []\n\t}\n\n\tconst delimiter = options.delimiter ?? detectDelimiter(source)\n\tconst rows: string[][] = []\n\tlet row: string[] = []\n\tlet cell = \"\"\n\tlet quoted = false\n\t// Whether the row has begun: a last row of one empty quoted cell is still a row.\n\tlet started = false\n\tlet index = 0\n\n\tconst endCell = (): void => {\n\t\trow.push(cell)\n\t\tcell = \"\"\n\t}\n\n\tconst endRow = (): void => {\n\t\tendCell()\n\t\trows.push(row)\n\t\trow = []\n\t\tstarted = false\n\t}\n\n\twhile (index < source.length) {\n\t\tconst char = source.charAt(index)\n\n\t\tstarted = true\n\n\t\tif (quoted) {\n\t\t\tif (char === '\"') {\n\t\t\t\tif (source.charAt(index + 1) === '\"') {\n\t\t\t\t\tcell += '\"'\n\t\t\t\t\tindex += 2\n\t\t\t\t} else {\n\t\t\t\t\tquoted = false\n\t\t\t\t\tindex++\n\t\t\t\t}\n\t\t\t} else if (char === \"\\r\") {\n\t\t\t\tcell += \"\\n\"\n\t\t\t\tindex += source.charAt(index + 1) === \"\\n\" ? 2 : 1\n\t\t\t} else {\n\t\t\t\tcell += char\n\t\t\t\tindex++\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif (char === '\"' && cell === \"\") {\n\t\t\tquoted = true\n\t\t\tindex++\n\t\t} else if (char === delimiter) {\n\t\t\tendCell()\n\t\t\tindex++\n\t\t} else if (char === \"\\r\" || char === \"\\n\") {\n\t\t\tendRow()\n\t\t\tindex += char === \"\\r\" && source.charAt(index + 1) === \"\\n\" ? 2 : 1\n\t\t} else {\n\t\t\tcell += char\n\t\t\tindex++\n\t\t}\n\t}\n\n\t// The last row, unless the text ended with its line break.\n\tif (started) {\n\t\tendRow()\n\t}\n\n\treturn rows\n}\n\n/** The delimiter that splits the first line into the most cells, quotes respected. A semicolon wins a tie. */\nexport function detectDelimiter(text: string): CsvDelimiter {\n\tconst counts = new Map<CsvDelimiter, number>(DELIMITERS.map(delimiter => [delimiter, 0]))\n\tlet quoted = false\n\n\tfor (const char of text) {\n\t\tif (char === '\"') {\n\t\t\tquoted = !quoted\n\t\t} else if (!quoted && (char === \"\\n\" || char === \"\\r\")) {\n\t\t\tbreak\n\t\t} else if (!quoted && counts.has(char as CsvDelimiter)) {\n\t\t\tcounts.set(char as CsvDelimiter, (counts.get(char as CsvDelimiter) ?? 0) + 1)\n\t\t}\n\t}\n\n\tlet best: CsvDelimiter = \";\"\n\n\tfor (const delimiter of DELIMITERS) {\n\t\tif ((counts.get(delimiter) ?? 0) > (counts.get(best) ?? 0)) {\n\t\t\tbest = delimiter\n\t\t}\n\t}\n\n\treturn best\n}\n\nexport interface CsvWriteOptions {\n\treadonly delimiter?: CsvDelimiter\n\t/** A byte order mark at the start, which Excel needs to read the text as UTF-8. True by default. */\n\treadonly bom?: boolean\n}\n\n/** CSV text for rows of cells, lines ending in `\\r\\n` as RFC 4180 and Excel have them. */\nexport function toCsv(rows: readonly (readonly string[])[], options: CsvWriteOptions = {}): string {\n\tconst delimiter = options.delimiter ?? \",\"\n\tconst special = new RegExp(`[\"\\\\r\\\\n${delimiter === \"\\t\" ? \"\\\\t\" : delimiter}]`)\n\tconst text = rows\n\t\t.map(row => row.map(cell => (special.test(cell) ? `\"${cell.replace(/\"/g, '\"\"')}\"` : cell)).join(delimiter))\n\t\t.join(\"\\r\\n\")\n\n\treturn `${options.bom === false ? \"\" : \"\\uFEFF\"}${text}\\r\\n`\n}\n\n/**\n * The text in a file's bytes: UTF-8 when they are UTF-8, otherwise the code page given, Windows-1254\n * by default, which is what Excel writes a Turkish \"CSV\" in.\n */\nexport function decodeText(bytes: Uint8Array, fallback = \"windows-1254\"): string {\n\ttry {\n\t\treturn new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes)\n\t} catch {\n\t\treturn new TextDecoder(fallback).decode(bytes)\n\t}\n}\n","import type { CsvDelimiter } from \"./csv.js\"\nimport type { RowId, RowInit, RowStore } from \"./rows.js\"\nimport type { FieldSchema, ModuleSchema } from \"./schema.js\"\nimport { withDefaults } from \"./templates.js\"\nimport type { CellValue } from \"./value.js\"\nimport { editText } from \"./values/format.js\"\nimport { canonicalValue, isFieldValue, isLookupValue, readInput } from \"./values/read.js\"\nimport type { ValueSettings } from \"./values/settings.js\"\nimport { fold } from \"./values/text.js\"\n\n/**\n * A sheet as a table of text and back: what a CSV file, or any file a backend has read, holds.\n *\n * The text is the sheet's own: numbers with its decimal mark and every digit, dates in its pattern,\n * yes and no in its words, a lookup by its name. Read back with the same settings, it gives the same\n * values.\n */\n\n// ---------------------------------------------------------------- export\n\nexport interface TableExportOptions {\n\treadonly store: RowStore\n\t/** The columns to write, in order, such as the ones shown. */\n\treadonly fields: readonly FieldSchema[]\n\t/** The rows to write, in order, such as a filtered view's. Every row by default. */\n\treadonly rowIds?: readonly RowId[]\n\treadonly settings: ValueSettings\n\t/** What the first row holds: the columns' labels, their keys, or nothing. Labels by default. */\n\treadonly header?: \"label\" | \"key\" | \"none\"\n\t/**\n\t * Columns of the host's own, written as text before or after the fields' (after by default), such\n\t * as each row's number or its issues. Nothing reads them back as a value.\n\t */\n\treadonly extra?: readonly ExtraColumn[]\n}\n\nexport interface ExtraColumn {\n\treadonly header: string\n\treadonly text: (rowId: RowId) => string\n\treadonly at?: \"start\" | \"end\"\n}\n\n/**\n * Text a spreadsheet would take for a formula and run when the file is opened: `=`, `+`, `-`, `@`, a\n * tab or a carriage return at the start. Such a cell is written with `'` before it, which a\n * spreadsheet shows as text. A number in a number column is never touched: `-12` stays a number.\n */\nconst FORMULA_START = /^[=+\\-@\\t\\r]/\n\nconst NUMBER_TYPES: ReadonlySet<string> = new Set([\"integer\", \"decimal\", \"quantity\", \"money\", \"percent\"])\n\nexport function exportTable(options: TableExportOptions): string[][] {\n\tconst { store, fields, settings } = options\n\tconst before = (options.extra ?? []).filter(column => column.at === \"start\")\n\tconst after = (options.extra ?? []).filter(column => column.at !== \"start\")\n\tconst own = (columns: readonly ExtraColumn[], rowId: RowId): string[] =>\n\t\tcolumns.map(column => {\n\t\t\tconst text = column.text(rowId)\n\n\t\t\treturn FORMULA_START.test(text) ? `'${text}` : text\n\t\t})\n\tconst rows: string[][] = []\n\n\tif ((options.header ?? \"label\") !== \"none\") {\n\t\trows.push([\n\t\t\t...before.map(column => column.header),\n\t\t\t...fields.map(field => (options.header === \"key\" ? field.key : field.label)),\n\t\t\t...after.map(column => column.header)\n\t\t])\n\t}\n\n\tfor (const rowId of options.rowIds ?? store.rowIds()) {\n\t\trows.push([\n\t\t\t...own(before, rowId),\n\t\t\t...fields.map(field => cellText(field, store.get(rowId, field.key), settings)),\n\t\t\t...own(after, rowId)\n\t\t])\n\t}\n\n\treturn rows\n}\n\nfunction cellText(field: FieldSchema, value: CellValue, settings: ValueSettings): string {\n\tconst text = editText(field, value, settings)\n\tconst number = NUMBER_TYPES.has(field.type) && value !== null && isFieldValue(field, value)\n\n\treturn !number && FORMULA_START.test(text) ? `'${text}` : text\n}\n\n/** The delimiter a spreadsheet in the sheet's language expects: `;` where the comma is the decimal mark. */\nexport function csvDelimiterFor(settings: ValueSettings): CsvDelimiter {\n\treturn settings.decimalSeparator === \",\" ? \";\" : \",\"\n}\n\n// ---------------------------------------------------------------- import\n\nexport interface TableImportOptions {\n\treadonly schema: ModuleSchema\n\treadonly settings: ValueSettings\n\t/**\n\t * Which field each column goes to, by the column's position, over what its header says. Null\n\t * leaves a column out.\n\t */\n\treadonly columns?: Readonly<Record<number, string | null>>\n\t/**\n\t * The column that finds each row in the sheet, for `matchRows`, by its position: its text is kept\n\t * in `keys`, and it brings no value.\n\t */\n\treadonly key?: number | null\n}\n\n/**\n * What became of a column. `unknown`: no field has its header. `duplicate`: an earlier column went\n * to the same field. `read_only`: its field is not typed into, such as one shown for reference or\n * worked out by a formula. `skipped`: left out on purpose. `key`: it finds the rows (`key`).\n */\nexport type ColumnStatus = \"matched\" | \"unknown\" | \"duplicate\" | \"read_only\" | \"skipped\" | \"key\"\n\nexport interface ColumnMatch {\n\treadonly index: number\n\treadonly header: string\n\t/** The field the column went to; null unless it was `matched`. */\n\treadonly field: string | null\n\treadonly status: ColumnStatus\n\t/** Its first few values that are not empty, as written: what a column is told by. */\n\treadonly samples: readonly string[]\n\t/** Its cells whose text is not a value of its field's type. */\n\treadonly unreadable: number\n}\n\nexport interface TableImport {\n\treadonly columns: readonly ColumnMatch[]\n\t/** For `RowStore.appendRows`: new rows, ids to be made. Empty lines are left out. */\n\treadonly rows: RowInit[]\n\t/** With `key`, that column's text in each row, trimmed, in the order of `rows`; empty otherwise. */\n\treadonly keys: readonly string[]\n\t/** Required fields no column brought: every row lacks them, and will say so. */\n\treadonly missing: readonly string[]\n\t/**\n\t * Cells whose text is not a value of their field's type: kept as written, and marked, as a paste\n\t * keeps them. A lookup's name is not counted: matching it to a record is the lookup's work.\n\t */\n\treadonly unreadable: number\n}\n\n/** How many of a column's first values `ColumnMatch.samples` shows. */\nconst SAMPLES = 3\n\n/**\n * Rows from a table whose first row names the columns, by each field's label or key, in any case.\n * Each cell is read as what a user typed into the field would be.\n */\nexport function importTable(table: readonly (readonly string[])[], options: TableImportOptions): TableImport {\n\tconst { schema, settings } = options\n\tconst [header = [], ...lines] = table\n\tconst body = lines.filter(line => !line.every(cell => cell.trim() === \"\"))\n\tconst key = options.key ?? null\n\tconst taken = new Set<string>()\n\n\tconst matched = header.map((raw, index): Omit<ColumnMatch, \"samples\" | \"unreadable\"> => {\n\t\tconst name = raw.trim()\n\t\tconst given = options.columns?.[index]\n\n\t\tif (index === key) {\n\t\t\treturn { index, header: name, field: null, status: \"key\" }\n\t\t}\n\n\t\tif (given === null) {\n\t\t\treturn { index, header: name, field: null, status: \"skipped\" }\n\t\t}\n\n\t\tconst field = given !== undefined ? (schema.has(given) ? schema.field(given) : null) : fieldNamed(schema, name)\n\n\t\tif (!field) {\n\t\t\treturn { index, header: name, field: null, status: \"unknown\" }\n\t\t}\n\n\t\tif (!field.editable) {\n\t\t\treturn { index, header: name, field: null, status: \"read_only\" }\n\t\t}\n\n\t\tif (taken.has(field.key)) {\n\t\t\treturn { index, header: name, field: null, status: \"duplicate\" }\n\t\t}\n\n\t\ttaken.add(field.key)\n\n\t\treturn { index, header: name, field: field.key, status: \"matched\" }\n\t})\n\n\tconst rows: RowInit[] = []\n\tconst keys: string[] = []\n\tconst unreadable = matched.map(() => 0)\n\n\tfor (const line of body) {\n\t\tconst values: Record<string, CellValue> = {}\n\n\t\tfor (const column of matched) {\n\t\t\tif (column.field === null) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst field = schema.field(column.field)\n\t\t\tconst result = readInput(field, line[column.index] ?? \"\", settings)\n\n\t\t\tif (result.value !== null) {\n\t\t\t\tvalues[field.key] = result.value\n\t\t\t}\n\n\t\t\tif (result.problem && result.problem.code !== \"not_matched\") {\n\t\t\t\tunreadable[column.index] = (unreadable[column.index] ?? 0) + 1\n\t\t\t}\n\t\t}\n\n\t\trows.push({ values })\n\n\t\tif (key !== null) {\n\t\t\tkeys.push((line[key] ?? \"\").trim())\n\t\t}\n\t}\n\n\tconst columns = matched.map(column => ({\n\t\t...column,\n\t\tsamples: samplesOf(body, column.index, SAMPLES),\n\t\tunreadable: unreadable[column.index] ?? 0\n\t}))\n\tconst missing = schema.fields\n\t\t.filter(field => field.required && field.editable && !taken.has(field.key))\n\t\t.map(field => field.key)\n\n\treturn { columns, rows, keys, missing, unreadable: unreadable.reduce((sum, count) => sum + count, 0) }\n}\n\n// ---------------------------------------------------------------- where the columns go\n\n/**\n * Why a column is suggested for a field. `remembered`: the host said this header went there before.\n * `name`: the header is the field's label or key. `similar`: the header shares a word with the\n * label, \"Fiyat\" with \"Yeni fiyat\". `values`: the column's values read as that field's and as no\n * other's, \"TRY\" and \"USD\" as a currency's options.\n */\nexport type SuggestionReason = \"remembered\" | \"name\" | \"similar\" | \"values\"\n\nexport interface ColumnSuggestion {\n\t/** The field the column would go to; null to leave it out. */\n\treadonly field: string | null\n\treadonly reason: SuggestionReason | null\n}\n\nexport interface SuggestOptions {\n\treadonly schema: ModuleSchema\n\treadonly settings: ValueSettings\n\t/**\n\t * Where headers went before, by `headerKey`: a field's key, or null for a column left out. Kept by\n\t * the host, such as from the user's last import.\n\t */\n\treadonly remembered?: Readonly<Record<string, string | null>>\n}\n\n/** How many of a column's values are read to tell what it holds. */\nconst PROBE = 50\n/**\n * The share of a column's values that must read as a field's for the column to go there: most, so\n * a few values written another way, such as \"31/12/26\" among dates, still let it.\n */\nconst READABLE = 0.6\n\n/**\n * Where each column of a table would go, and why, for an import the user then looks over: what the\n * host remembered, then the header as a field's name, then a word the two share, then values only\n * one field reads. Only fields typed into are suggested, each for one column at most; a column\n * nothing fits is left out.\n */\nexport function suggestColumns(table: readonly (readonly string[])[], options: SuggestOptions): ColumnSuggestion[] {\n\tconst { schema, settings } = options\n\tconst [header = [], ...lines] = table\n\tconst body = lines.filter(line => !line.every(cell => cell.trim() === \"\"))\n\tconst open = schema.fields.filter(field => field.editable)\n\tconst taken = new Set<string>()\n\tconst result: (ColumnSuggestion | undefined)[] = header.map(() => undefined)\n\tconst choose = (index: number, field: string | null, reason: SuggestionReason): void => {\n\t\tresult[index] = { field, reason }\n\n\t\tif (field !== null) {\n\t\t\ttaken.add(field)\n\t\t}\n\t}\n\tconst free = (field: FieldSchema): boolean => !taken.has(field.key)\n\n\theader.forEach((name, index) => {\n\t\tconst key = headerKey(name)\n\n\t\tif (options.remembered && Object.hasOwn(options.remembered, key)) {\n\t\t\tconst field = options.remembered[key] ?? null\n\n\t\t\tif (field === null) {\n\t\t\t\tchoose(index, null, \"remembered\")\n\t\t\t} else if (schema.has(field) && schema.field(field).editable && !taken.has(field)) {\n\t\t\t\tchoose(index, field, \"remembered\")\n\t\t\t}\n\t\t}\n\t})\n\n\theader.forEach((name, index) => {\n\t\tconst field = result[index] ? null : fieldNamed(schema, name.trim())\n\n\t\tif (field?.editable && free(field)) {\n\t\t\tchoose(index, field.key, \"name\")\n\t\t}\n\t})\n\n\theader.forEach((name, index) => {\n\t\tconst words = wordsOf(name)\n\n\t\tif (result[index] || words.size === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tconst scored = open.filter(free).map(field => ({ field, score: overlap(words, wordsOf(field.label)) }))\n\t\tconst best = Math.max(0, ...scored.map(item => item.score))\n\t\tconst top = scored.filter(item => item.score === best)\n\n\t\tif (best > 0 && top.length === 1 && top[0]) {\n\t\t\tchoose(index, top[0].field.key, \"similar\")\n\t\t}\n\t})\n\n\theader.forEach((_, index) => {\n\t\tif (result[index]) {\n\t\t\treturn\n\t\t}\n\n\t\tconst texts = samplesOf(body, index, PROBE)\n\t\tconst readers = open.filter(\n\t\t\tfield =>\n\t\t\t\tfree(field) && field.type !== \"string\" && field.type !== \"lookup\" && readsAs(field, texts, settings)\n\t\t)\n\n\t\tif (texts.length > 0 && readers.length === 1 && readers[0]) {\n\t\t\tchoose(index, readers[0].key, \"values\")\n\t\t}\n\t})\n\n\treturn result.map(item => item ?? { field: null, reason: null })\n}\n\n/** A header as `SuggestOptions.remembered` keeps it: trimmed and lower-cased, in Turkish. */\nexport function headerKey(header: string): string {\n\treturn header.trim().toLocaleLowerCase(\"tr\")\n}\n\nfunction readsAs(field: FieldSchema, texts: readonly string[], settings: ValueSettings): boolean {\n\tconst read = texts.filter(text => readInput(field, text, settings).problem === null).length\n\n\treturn texts.length > 0 && read / texts.length >= READABLE\n}\n\nconst TURKISH: Readonly<Record<string, string>> = { ç: \"c\", ğ: \"g\", ı: \"i\", ö: \"o\", ş: \"s\", ü: \"u\" }\n\n/** The words of a header or a label, compared without case or Turkish letters: \"Döviz kuru\" is döviz, kuru. */\nfunction wordsOf(text: string): Set<string> {\n\tconst plain = text\n\t\t.toLocaleLowerCase(\"tr\")\n\t\t.replace(/[çğıöşü]/g, letter => TURKISH[letter] ?? letter)\n\t\t.normalize(\"NFD\")\n\t\t.replace(/[\\u0300-\\u036f]/g, \"\")\n\n\treturn new Set(plain.split(/[^a-z0-9]+/).filter(word => word.length > 1))\n}\n\nfunction overlap(a: ReadonlySet<string>, b: ReadonlySet<string>): number {\n\tconst shared = [...a].filter(word => b.has(word)).length\n\n\treturn shared === 0 ? 0 : shared / new Set([...a, ...b]).size\n}\n\nfunction samplesOf(body: readonly (readonly string[])[], index: number, limit: number): string[] {\n\tconst found: string[] = []\n\n\tfor (const line of body) {\n\t\tconst text = (line[index] ?? \"\").trim()\n\n\t\tif (text !== \"\") {\n\t\t\tfound.push(text)\n\n\t\t\tif (found.length === limit) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn found\n}\n\n// ---------------------------------------------------------------- finding the rows\n\n/** The field types rows are found by: a code, a number, a record's name. */\nconst KEY_TYPES: ReadonlySet<string> = new Set([\"string\", \"integer\", \"lookup\"])\n\nexport interface MatchSuggestion {\n\t/** The table's column that finds the rows, by position. */\n\treadonly column: number\n\t/** The field of the sheet it finds them by. */\n\treadonly field: string\n}\n\n/**\n * The column most likely to find a table's rows in the sheet, and the field it finds them by: the\n * column whose values most often stand in some row's text, whole-number or lookup field, such as a\n * product code. Null when none finds half of the values it holds.\n */\nexport function suggestMatch(\n\ttable: readonly (readonly string[])[],\n\tstore: RowStore,\n\toptions: { readonly schema: ModuleSchema; readonly settings: ValueSettings }\n): MatchSuggestion | null {\n\tconst { schema, settings } = options\n\tconst [header = [], ...lines] = table\n\tconst body = lines.filter(line => !line.every(cell => cell.trim() === \"\"))\n\tconst fields = schema.fields.filter(field => KEY_TYPES.has(field.type))\n\tconst indexes = new Map<string, Map<string, RowId[]>>()\n\tlet best: MatchSuggestion | null = null\n\tlet bestShare = 0\n\n\tfor (let column = 0; column < header.length; column++) {\n\t\tconst texts = samplesOf(body, column, PROBE)\n\n\t\tfor (const field of texts.length === 0 ? [] : fields) {\n\t\t\tconst index = indexes.get(field.key) ?? indexOf(store, field, settings)\n\n\t\t\tindexes.set(field.key, index)\n\n\t\t\tconst found = texts.filter(text => {\n\t\t\t\tconst key = textKey(field, text, settings)\n\n\t\t\t\treturn key !== null && index.has(key)\n\t\t\t}).length\n\t\t\tconst share = found / texts.length\n\n\t\t\tif (share >= 0.5 && share > bestShare) {\n\t\t\t\tbest = { column, field: field.key }\n\t\t\t\tbestShare = share\n\t\t\t}\n\t\t}\n\t}\n\n\treturn best\n}\n\n/**\n * The rows of the sheet each key finds: those whose `field` holds what the key's text reads as,\n * compared as a backend is sent them, so \"1.001\" finds 1001, and text without regard to case or the\n * spaces around it. A key that finds none gives an empty list; one that finds several, all of them.\n */\nexport function matchRows(\n\tstore: RowStore,\n\tfield: FieldSchema,\n\tkeys: readonly string[],\n\tsettings: ValueSettings\n): RowId[][] {\n\tconst index = indexOf(store, field, settings)\n\n\treturn keys.map(text => {\n\t\tconst key = textKey(field, text, settings)\n\n\t\treturn key === null ? [] : [...(index.get(key) ?? [])]\n\t})\n}\n\nfunction indexOf(store: RowStore, field: FieldSchema, settings: ValueSettings): Map<string, RowId[]> {\n\tconst index = new Map<string, RowId[]>()\n\n\tfor (const rowId of store.rowIds()) {\n\t\tconst key = valueKey(field, store.get(rowId, field.key), settings)\n\n\t\tif (key !== null) {\n\t\t\tconst rows = index.get(key)\n\n\t\t\tif (rows) {\n\t\t\t\trows.push(rowId)\n\t\t\t} else {\n\t\t\t\tindex.set(key, [rowId])\n\t\t\t}\n\t\t}\n\t}\n\n\treturn index\n}\n\nfunction textKey(field: FieldSchema, text: string, settings: ValueSettings): string | null {\n\tif (text.trim() === \"\") {\n\t\treturn null\n\t}\n\n\treturn field.type === \"lookup\" ? fold(text) : valueKey(field, readInput(field, text, settings).value, settings)\n}\n\nfunction valueKey(field: FieldSchema, value: CellValue, settings: ValueSettings): string | null {\n\tif (value === null) {\n\t\treturn null\n\t}\n\n\tif (isLookupValue(value)) {\n\t\treturn fold(value.label)\n\t}\n\n\tconst canonical = canonicalValue(field, value, settings)\n\n\treturn typeof canonical === \"string\" ? fold(canonical) : JSON.stringify(canonical)\n}\n\n// ---------------------------------------------------------------- into the sheet\n\n/** The origin an import's change carries in the store and in the undo history. */\nexport const IMPORT_ORIGIN = \"import\"\n\nexport interface ImportApplyOptions {\n\t/**\n\t * For each row of the import, the rows of the sheet it is written into, as `matchRows` found\n\t * them: the values the file brought, an empty cell emptying the cell it lands in. Left out, every\n\t * row is added.\n\t */\n\treadonly matches?: readonly (readonly RowId[])[]\n\t/** With `matches`, what becomes of a row that found none: added at the end, or left out. */\n\treadonly unmatched?: \"add\" | \"skip\"\n\t/** Rows not to be written into, such as those the backend has processed. */\n\treadonly locked?: (rowId: RowId) => boolean\n\treadonly origin?: string\n}\n\nexport interface ImportApplied {\n\t/** The rows added at the end, in order. */\n\treadonly added: readonly RowId[]\n\t/** How many rows of the sheet were written into. */\n\treadonly updated: number\n\t/** Rows of the file left out: finding none with `unmatched: \"skip\"`, or only rows locked. */\n\treadonly skipped: number\n}\n\n/**\n * An import put into the sheet as one change, taken back with one Ctrl+Z: rows written into where\n * `matches` found them, the others added at the end with the schema's defaults, or left out.\n */\nexport function applyImport(\n\tstore: RowStore,\n\tschema: ModuleSchema,\n\timported: TableImport,\n\toptions: ImportApplyOptions = {}\n): ImportApplied {\n\tconst fields = imported.columns.flatMap(column =>\n\t\tcolumn.status === \"matched\" && column.field ? [column.field] : []\n\t)\n\tconst adding: RowInit[] = []\n\tconst written = new Set<RowId>()\n\tlet added: RowId[] = []\n\tlet skipped = 0\n\n\tstore.transact(\n\t\t() => {\n\t\t\timported.rows.forEach((row, index) => {\n\t\t\t\tconst targets = options.matches?.[index] ?? []\n\n\t\t\t\tif (targets.length === 0) {\n\t\t\t\t\tif (options.matches && options.unmatched === \"skip\") {\n\t\t\t\t\t\tskipped++\n\t\t\t\t\t} else {\n\t\t\t\t\t\tadding.push(row)\n\t\t\t\t\t}\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst open = targets.filter(rowId => store.has(rowId) && !options.locked?.(rowId))\n\n\t\t\t\tif (open.length === 0) {\n\t\t\t\t\tskipped++\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tfor (const rowId of open) {\n\t\t\t\t\tfor (const key of fields) {\n\t\t\t\t\t\tstore.setCell(rowId, key, row.values?.[key] ?? null)\n\t\t\t\t\t}\n\n\t\t\t\t\twritten.add(rowId)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tif (adding.length > 0) {\n\t\t\t\tadded = store.appendRows(withDefaults(schema, adding))\n\t\t\t}\n\t\t},\n\t\t{ origin: options.origin ?? IMPORT_ORIGIN }\n\t)\n\n\treturn { added, updated: written.size, skipped }\n}\n\n/** The field a header names: by label, then by key, regardless of case, Turkish or not. */\nfunction fieldNamed(schema: ModuleSchema, name: string): FieldSchema | null {\n\tconst same = (a: string, b: string): boolean =>\n\t\ta.toLocaleLowerCase(\"tr\") === b.toLocaleLowerCase(\"tr\") || a.toLowerCase() === b.toLowerCase()\n\n\treturn (\n\t\tschema.fields.find(field => same(field.label.trim(), name)) ??\n\t\tschema.fields.find(field => same(field.key, name)) ??\n\t\tnull\n\t)\n}\n","import { breaksCheck, checkFields, type ConditionOp, type RowCheck, type RowCondition } from \"./checks.js\"\nimport { compareDecimal } from \"./decimal.js\"\nimport { isFormulaError } from \"./formula/error.js\"\nimport { Listeners } from \"./listeners.js\"\nimport type { RowId, RowStore, StoreChange } from \"./rows.js\"\nimport type { FieldRule, FieldSchema, ModuleSchema } from \"./schema.js\"\nimport { sameValue, type CellValue } from \"./value.js\"\nimport { decimalText } from \"./values/number.js\"\nimport { formatCell } from \"./values/format.js\"\nimport { canonicalValue, isLookupValue, valueProblem, type ValueProblemCode } from \"./values/read.js\"\nimport { VALUE_SETTINGS, type ValueSettings } from \"./values/settings.js\"\n\n/**\n * What is wrong in a sheet, bound to rows by id and to fields by key, never to a row number or a\n * column header: a sort or a renamed header moves nothing.\n *\n * Local issues are the schema's own rules, checked in the browser as the user types. A backend's\n * answers arrive in the same shape (see `SheetSession`). A backend still checks everything again;\n * passing here promises nothing.\n */\n\nexport type LocalIssueCode =\n\t| ValueProblemCode\n\t| \"required\"\n\t| \"min_value\"\n\t| \"max_value\"\n\t| \"min_length\"\n\t| \"max_length\"\n\t| \"not_unique\"\n\t| \"formula_error\"\n\t| \"check_filled\"\n\t| \"check_empty\"\n\t| \"check_compare\"\n\nexport type IssueSeverity = \"error\" | \"warning\"\n\nexport type IssueScope = \"cell\" | \"row\" | \"sheet\" | \"workbook\"\n\nexport interface IssueTarget {\n\treadonly rowId: RowId\n\treadonly field: string\n}\n\nexport interface Issue {\n\t/** Stable while the problem stands: the same issue on the same cell keeps its id. */\n\treadonly id: string\n\treadonly scope: IssueScope\n\t/** Who found it: `local` is this package, `preflight` and `process` are the backend's checks. */\n\treadonly source: string\n\treadonly rowId: RowId | null\n\treadonly field: string | null\n\t/** Other cells the issue is about, such as the rows holding the same value as this one. */\n\treadonly targets: readonly IssueTarget[]\n\t/** Never renamed: what an application words its messages from. */\n\treadonly code: string\n\treadonly severity: IssueSeverity\n\t/** Whether it stops the sheet from being processed. Every local error does; no warning does. */\n\treadonly blocking: boolean\n\t/**\n\t * A backend found it, and a cell it is about has changed since. It is not taken as fixed: only\n\t * checking again can say. A stale issue counts apart, and blocks nothing.\n\t */\n\treadonly stale: boolean\n\t/** A sentence to show when an interface has no wording of its own for the code. */\n\treadonly message: string\n\treadonly params: Readonly<Record<string, string>>\n}\n\nexport interface IssueSummary {\n\t/** Errors still standing; stale ones are counted apart. */\n\treadonly errors: number\n\treadonly warnings: number\n\t/** Issues waiting for the backend to check again. */\n\treadonly stale: number\n\t/** Rows with at least one issue. */\n\treadonly rows: number\n}\n\n/**\n * Issues a view can show: a validator's own, or those merged with a backend's answers. The grid and\n * the issue panel read either through this.\n */\nexport interface IssueSet {\n\t/** Moves on every change, for a view to redraw by. */\n\treadonly version: number\n\t/** The issues on one cell. */\n\tissuesAt(rowId: RowId, field: string): readonly Issue[]\n\t/** The issues about a row as a whole rather than one of its cells. */\n\trowIssues(rowId: RowId): readonly Issue[]\n\t/** Whether any issue is on the row, on one of its cells or about it as a whole. */\n\thasIssues(rowId: RowId): boolean\n\t/** Every issue: those about the whole sheet first, then by row as the rows stand, then by column. */\n\tissues(): Issue[]\n\tsummary(): IssueSummary\n\t/** Called after each change. Returns the way to stop. */\n\tsubscribe(listener: () => void): () => void\n}\n\ntype CellIssues = Map<string, readonly Issue[]>\n\n/**\n * How many other rows a \"same value\" issue points at. Its `count` param says how many there are in\n * all. Listing every one would put 49,999 targets on each of 50,000 rows after one paste.\n */\nconst MAX_TARGETS = 10\n\n/**\n * Checks a sheet against its schema and keeps the result current.\n *\n * It listens to the row store and, after each change, checks only the cells the change touched.\n * A field with a `unique` rule is the one exception that looks across rows: changing one value can\n * clear or raise the issue on every other row holding it, and only those rows are touched.\n *\n * The schema's row checks are checked for the row a change touched, and only those that read the\n * field it changed. Their issues land on the cell each check is about, as errors or as warnings.\n */\n/**\n * Whether a row holds nothing anyone gave it: every field empty or at its default, a formula's\n * aside. Such a row, a new one nobody typed into or a pasted block's empty line, is neither checked\n * nor sent; it is still the user's, kept with the draft until they delete it.\n */\nexport function isBlankRow(schema: ModuleSchema, get: (key: string) => CellValue): boolean {\n\treturn schema.fields.every(field => {\n\t\tif (field.formula !== null) {\n\t\t\treturn true\n\t\t}\n\n\t\tconst value = get(field.key)\n\n\t\treturn (\n\t\t\tvalue === null ||\n\t\t\tvalue === \"\" ||\n\t\t\t(Array.isArray(value) && value.length === 0) ||\n\t\t\t(field.default !== null && sameValue(value, field.default))\n\t\t)\n\t})\n}\n\nexport class SheetValidator implements IssueSet {\n\treadonly #schema: ModuleSchema\n\treadonly #store: RowStore\n\t#settings: ValueSettings\n\treadonly #cells = new Map<RowId, CellIssues>()\n\t/** For each unique field: value key to the rows holding it, and each row's key. */\n\treadonly #groups = new Map<string, Map<string, Set<RowId>>>()\n\treadonly #keys = new Map<string, Map<RowId, string>>()\n\t/** Groups of rows holding one value, in sheet order: sorted once per change, when first asked. */\n\treadonly #sorted = new Map<string, readonly RowId[]>()\n\t/** The row checks that read each field: what to check again when it changes. */\n\treadonly #checksOf = new Map<string, RowCheck[]>()\n\t/** Each row's broken checks, by check id. */\n\treadonly #broken = new Map<RowId, Map<string, Issue>>()\n\t/** Rows holding nothing anyone gave them (`isBlankRow`): not checked. */\n\treadonly #blank = new Set<RowId>()\n\treadonly #listeners = new Listeners<SheetValidator>()\n\treadonly #unsubscribe: () => void\n\t#version = 0\n\n\tconstructor(schema: ModuleSchema, store: RowStore, settings: ValueSettings = VALUE_SETTINGS.tr) {\n\t\tthis.#schema = schema\n\t\tthis.#store = store\n\t\tthis.#settings = settings\n\n\t\tfor (const field of schema.fields) {\n\t\t\tif (hasRule(field, \"unique\")) {\n\t\t\t\tthis.#groups.set(field.key, new Map())\n\t\t\t\tthis.#keys.set(field.key, new Map())\n\t\t\t}\n\t\t}\n\n\t\tfor (const check of schema.checks) {\n\t\t\tfor (const key of checkFields(check)) {\n\t\t\t\tthis.#checksOf.set(key, [...(this.#checksOf.get(key) ?? []), check])\n\t\t\t}\n\t\t}\n\n\t\tthis.#checkAll()\n\t\tthis.#unsubscribe = store.subscribe(change => this.#apply(change))\n\t}\n\n\t/** Counts changes to the issues: a view redraws when it moves. */\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\t/** The issues on one cell, in a fixed order: the cell's own first, then any across rows. */\n\tissuesAt(rowId: RowId, field: string): readonly Issue[] {\n\t\tconst own = this.#cells.get(rowId)?.get(field) ?? []\n\t\tconst broken = this.#broken.get(rowId)\n\t\tconst checks = broken ? [...broken.values()].filter(issue => issue.field === field) : []\n\t\tconst shared = this.#uniqueIssue(rowId, field)\n\n\t\tif (checks.length === 0 && !shared) {\n\t\t\treturn own\n\t\t}\n\n\t\treturn shared ? [...own, ...checks, shared] : [...own, ...checks]\n\t}\n\n\t/** None: every local issue, a row check's too, lands on a cell. */\n\trowIssues(): readonly Issue[] {\n\t\treturn []\n\t}\n\n\t/** Every issue, in sheet order: by row as the rows stand now, then by column. */\n\tissues(): Issue[] {\n\t\tconst result: Issue[] = []\n\n\t\tfor (const rowId of this.#store.rowIds()) {\n\t\t\tfor (const field of this.#schema.fields) {\n\t\t\t\tresult.push(...this.issuesAt(rowId, field.key))\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n\t/** Counted without building the issues, so a sheet with 50,000 of them counts as fast as one with ten. */\n\tsummary(): IssueSummary {\n\t\tlet errors = 0\n\t\tlet warnings = 0\n\n\t\tfor (const cells of this.#cells.values()) {\n\t\t\tfor (const issues of cells.values()) {\n\t\t\t\tfor (const issue of issues) {\n\t\t\t\t\tif (issue.severity === \"error\") {\n\t\t\t\t\t\terrors++\n\t\t\t\t\t} else {\n\t\t\t\t\t\twarnings++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const groups of this.#groups.values()) {\n\t\t\tfor (const group of groups.values()) {\n\t\t\t\tif (group.size > 1) {\n\t\t\t\t\terrors += group.size\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const broken of this.#broken.values()) {\n\t\t\tfor (const issue of broken.values()) {\n\t\t\t\tif (issue.severity === \"error\") {\n\t\t\t\t\terrors++\n\t\t\t\t} else {\n\t\t\t\t\twarnings++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { errors, warnings, stale: 0, rows: this.affectedRows().size }\n\t}\n\n\t/** The rows with at least one issue. */\n\taffectedRows(): Set<RowId> {\n\t\tconst rows = new Set([...this.#cells.keys(), ...this.#broken.keys()])\n\n\t\tfor (const groups of this.#groups.values()) {\n\t\t\tfor (const group of groups.values()) {\n\t\t\t\tif (group.size > 1) {\n\t\t\t\t\tfor (const rowId of group) {\n\t\t\t\t\t\trows.add(rowId)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn rows\n\t}\n\n\thasIssues(rowId: RowId): boolean {\n\t\t// A row check may be a warning; every other local issue is an error.\n\t\treturn this.#broken.has(rowId) || this.hasErrors(rowId)\n\t}\n\n\t/** Whether any error stands on the row: such a row is not sent to be processed. */\n\thasErrors(rowId: RowId): boolean {\n\t\tconst cells = this.#cells.get(rowId)\n\n\t\tif (cells) {\n\t\t\tfor (const issues of cells.values()) {\n\t\t\t\tif (issues.some(issue => issue.severity === \"error\")) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (const issue of this.#broken.get(rowId)?.values() ?? []) {\n\t\t\tif (issue.severity === \"error\") {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\tfor (const [field, keys] of this.#keys) {\n\t\t\tconst key = keys.get(rowId)\n\n\t\t\tif (key !== undefined && (this.#groups.get(field)?.get(key)?.size ?? 0) > 1) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\n\t/** The settings text is read with: a backend is sent what they read a host's text as. */\n\tget settings(): ValueSettings {\n\t\treturn this.#settings\n\t}\n\n\t/** Settings decide which text reads as a value, so changing them checks every cell again. */\n\tsetSettings(settings: ValueSettings): void {\n\t\tif (settings === this.#settings) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#settings = settings\n\t\tthis.#checkAll()\n\t\tthis.#changed()\n\t}\n\n\t/** Called after each change to the issues. Returns the way to stop. */\n\tsubscribe(listener: (validator: SheetValidator) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Stops listening to the store. */\n\tdispose(): void {\n\t\tthis.#unsubscribe()\n\t}\n\n\t// ---------------------------------------------------------------- internals\n\n\t#checkAll(): void {\n\t\tthis.#cells.clear()\n\t\tthis.#broken.clear()\n\t\tthis.#blank.clear()\n\n\t\tfor (const groups of this.#groups.values()) {\n\t\t\tgroups.clear()\n\t\t}\n\n\t\tfor (const keys of this.#keys.values()) {\n\t\t\tkeys.clear()\n\t\t}\n\n\t\tfor (const rowId of this.#store.rowIds()) {\n\t\t\tthis.#checkRow(rowId)\n\t\t}\n\t}\n\n\t#apply(change: StoreChange): void {\n\t\tfor (const operation of change.operations) {\n\t\t\tswitch (operation.kind) {\n\t\t\t\tcase \"set\":\n\t\t\t\t\tif (!this.#store.has(operation.rowId) || !this.#schema.has(operation.field)) {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\t// A row that was blank is checked whole once something is in it, and one left blank\n\t\t\t\t\t// says nothing.\n\t\t\t\t\tif (this.#blank.has(operation.rowId) || this.#isBlank(operation.rowId)) {\n\t\t\t\t\t\tthis.#checkRow(operation.rowId)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.#checkCell(operation.rowId, this.#schema.field(operation.field))\n\t\t\t\t\t\tthis.#checkChecks(operation.rowId, this.#checksOf.get(operation.field) ?? [])\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase \"insert\":\n\t\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\t\tif (this.#store.has(row.rowId)) {\n\t\t\t\t\t\t\tthis.#checkRow(row.rowId)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\tcase \"remove\":\n\t\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\t\tthis.#forget(row.rowId)\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tthis.#changed()\n\t}\n\n\t#changed(): void {\n\t\tthis.#sorted.clear()\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n\n\t#checkRow(rowId: RowId): void {\n\t\tif (this.#isBlank(rowId)) {\n\t\t\tthis.#forget(rowId)\n\t\t\tthis.#blank.add(rowId)\n\n\t\t\treturn\n\t\t}\n\n\t\tthis.#blank.delete(rowId)\n\n\t\tfor (const field of this.#schema.fields) {\n\t\t\tthis.#checkCell(rowId, field)\n\t\t}\n\n\t\tthis.#checkChecks(rowId, this.#schema.checks)\n\t}\n\n\t#checkChecks(rowId: RowId, checks: readonly RowCheck[]): void {\n\t\tif (checks.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tconst get = (key: string): CellValue => this.#store.get(rowId, key)\n\t\tconst field = (key: string): FieldSchema => this.#schema.field(key)\n\t\tlet broken = this.#broken.get(rowId)\n\n\t\tfor (const check of checks) {\n\t\t\tif (breaksCheck(check, field, get, this.#settings)) {\n\t\t\t\tif (!broken) {\n\t\t\t\t\tbroken = new Map()\n\t\t\t\t\tthis.#broken.set(rowId, broken)\n\t\t\t\t}\n\n\t\t\t\tbroken.set(check.id, checkIssue(rowId, check, this.#schema, this.#settings))\n\t\t\t} else {\n\t\t\t\tbroken?.delete(check.id)\n\t\t\t}\n\t\t}\n\n\t\tif (broken?.size === 0) {\n\t\t\tthis.#broken.delete(rowId)\n\t\t}\n\t}\n\n\t#checkCell(rowId: RowId, field: FieldSchema): void {\n\t\tconst value = this.#store.get(rowId, field.key)\n\t\tconst issues = checkValue(rowId, field, value, this.#settings)\n\t\tlet row = this.#cells.get(rowId)\n\n\t\tif (issues.length > 0) {\n\t\t\tif (!row) {\n\t\t\t\trow = new Map()\n\t\t\t\tthis.#cells.set(rowId, row)\n\t\t\t}\n\n\t\t\trow.set(field.key, issues)\n\t\t} else if (row) {\n\t\t\trow.delete(field.key)\n\n\t\t\tif (row.size === 0) {\n\t\t\t\tthis.#cells.delete(rowId)\n\t\t\t}\n\t\t}\n\n\t\tif (this.#groups.has(field.key)) {\n\t\t\t// A value with a problem of its own takes no part in uniqueness: \"abc\" in a number column is\n\t\t\t// not the same number as anything. The rest are compared as the backend is sent them, so a\n\t\t\t// host's \"1.234\" is the same number as 1234.\n\t\t\tthis.#regroup(\n\t\t\t\trowId,\n\t\t\t\tfield.key,\n\t\t\t\tissues.length === 0 ? uniqueKey(canonicalValue(field, value, this.#settings)) : null\n\t\t\t)\n\t\t}\n\t}\n\n\t#isBlank(rowId: RowId): boolean {\n\t\treturn isBlankRow(this.#schema, key => this.#store.get(rowId, key))\n\t}\n\n\t#forget(rowId: RowId): void {\n\t\tthis.#cells.delete(rowId)\n\t\tthis.#broken.delete(rowId)\n\t\tthis.#blank.delete(rowId)\n\n\t\tfor (const field of this.#groups.keys()) {\n\t\t\tthis.#regroup(rowId, field, null)\n\t\t}\n\t}\n\n\t#regroup(rowId: RowId, field: string, key: string | null): void {\n\t\tconst groups = this.#groups.get(field)\n\t\tconst keys = this.#keys.get(field)\n\n\t\tif (!groups || !keys) {\n\t\t\treturn\n\t\t}\n\n\t\tconst previous = keys.get(rowId)\n\n\t\tif (previous !== undefined) {\n\t\t\tconst group = groups.get(previous)\n\n\t\t\tgroup?.delete(rowId)\n\n\t\t\tif (group?.size === 0) {\n\t\t\t\tgroups.delete(previous)\n\t\t\t}\n\n\t\t\tkeys.delete(rowId)\n\t\t}\n\n\t\tif (key !== null) {\n\t\t\tconst group = groups.get(key) ?? new Set<RowId>()\n\n\t\t\tgroup.add(rowId)\n\t\t\tgroups.set(key, group)\n\t\t\tkeys.set(rowId, key)\n\t\t}\n\t}\n\n\t#uniqueIssue(rowId: RowId, field: string): Issue | null {\n\t\tconst key = this.#keys.get(field)?.get(rowId)\n\t\tconst group = key === undefined ? undefined : this.#groups.get(field)?.get(key)\n\n\t\tif (!group || group.size < 2) {\n\t\t\treturn null\n\t\t}\n\n\t\t// The first others in the order the sheet has them, so the list reads top to bottom. The\n\t\t// group is sorted once per change and shared by every row in it.\n\t\tconst cacheKey = `${field}\\u0000${key}`\n\t\tlet sorted = this.#sorted.get(cacheKey)\n\n\t\tif (!sorted) {\n\t\t\tsorted = [...group].sort((a, b) => this.#store.indexOf(a) - this.#store.indexOf(b))\n\t\t\tthis.#sorted.set(cacheKey, sorted)\n\t\t}\n\n\t\tconst others = sorted\n\t\t\t.slice(0, MAX_TARGETS + 1)\n\t\t\t.filter(other => other !== rowId)\n\t\t\t.slice(0, MAX_TARGETS)\n\t\tconst value = describe(this.#store.get(rowId, field))\n\t\tconst params = Object.freeze({ field, value, count: String(group.size) })\n\n\t\treturn Object.freeze({\n\t\t\tid: `local|not_unique|${rowId}|${field}`,\n\t\t\tscope: \"cell\",\n\t\t\tsource: \"local\",\n\t\t\trowId,\n\t\t\tfield,\n\t\t\ttargets: Object.freeze(others.map(other => Object.freeze({ rowId: other, field }))),\n\t\t\tcode: \"not_unique\",\n\t\t\tseverity: \"error\",\n\t\t\tblocking: true,\n\t\t\tstale: false,\n\t\t\tmessage: `\"${value}\" appears ${group.size} times in this column; it may appear once.`,\n\t\t\tparams\n\t\t})\n\t}\n}\n\n/** The issues of one value, apart from uniqueness, which needs the other rows. */\nexport function checkValue(rowId: RowId, field: FieldSchema, value: CellValue, settings: ValueSettings): Issue[] {\n\t// A formula that could not be worked out: its error is the only thing to say about the cell.\n\tif (isFormulaError(value)) {\n\t\treturn [\n\t\t\tcellIssue(rowId, field, \"formula_error\", `The formula gives ${value.formulaError}.`, {\n\t\t\t\terror: value.formulaError\n\t\t\t})\n\t\t]\n\t}\n\n\tconst problem = valueProblem(field, value, settings)\n\n\t// A value that is not of its type is only that: a minimum means nothing for \"abc\".\n\tif (problem) {\n\t\treturn [cellIssue(rowId, field, problem.code, problem.message, problem.params)]\n\t}\n\n\tif (value === null) {\n\t\treturn field.required\n\t\t\t? [cellIssue(rowId, field, \"required\", \"This field is required and cannot be left empty.\", {})]\n\t\t\t: []\n\t}\n\n\tconst issues: Issue[] = []\n\t// The rules hold for the value the backend is sent: a host's \"1.234,5\" is 1234.5 against a maximum.\n\tconst sent = canonicalValue(field, value, settings)\n\n\tfor (const rule of field.rules) {\n\t\tconst issue = checkRule(rowId, field, rule, sent)\n\n\t\tif (issue) {\n\t\t\tissues.push(issue)\n\t\t}\n\t}\n\n\treturn issues\n}\n\nfunction checkRule(rowId: RowId, field: FieldSchema, rule: FieldRule, value: CellValue): Issue | null {\n\tswitch (rule.rule) {\n\t\tcase \"min\":\n\t\tcase \"max\": {\n\t\t\tconst number = decimalText(value)\n\n\t\t\tif (number === null) {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\tconst comparison = compareDecimal(normalize(number), rule.value)\n\n\t\t\tif (rule.rule === \"min\" && comparison < 0) {\n\t\t\t\treturn cellIssue(rowId, field, \"min_value\", `${number} is below the minimum of ${rule.value}.`, {\n\t\t\t\t\tvalue: number,\n\t\t\t\t\tmin: rule.value\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (rule.rule === \"max\" && comparison > 0) {\n\t\t\t\treturn cellIssue(rowId, field, \"max_value\", `${number} is above the maximum of ${rule.value}.`, {\n\t\t\t\t\tvalue: number,\n\t\t\t\t\tmax: rule.value\n\t\t\t\t})\n\t\t\t}\n\n\t\t\treturn null\n\t\t}\n\t\tcase \"minLength\":\n\t\tcase \"maxLength\": {\n\t\t\tif (typeof value !== \"string\") {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\t// Characters a reader counts, not UTF-16 units: an emoji is one.\n\t\t\tconst length = Array.from(value).length\n\n\t\t\tif (rule.rule === \"minLength\" && length < rule.value) {\n\t\t\t\treturn cellIssue(rowId, field, \"min_length\", `\"${value}\" is shorter than ${rule.value} characters.`, {\n\t\t\t\t\tvalue,\n\t\t\t\t\tmin: String(rule.value),\n\t\t\t\t\tlength: String(length)\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (rule.rule === \"maxLength\" && length > rule.value) {\n\t\t\t\treturn cellIssue(rowId, field, \"max_length\", `\"${value}\" is longer than ${rule.value} characters.`, {\n\t\t\t\t\tvalue,\n\t\t\t\t\tmax: String(rule.value),\n\t\t\t\t\tlength: String(length)\n\t\t\t\t})\n\t\t\t}\n\n\t\t\treturn null\n\t\t}\n\t\tcase \"unique\":\n\t\t\treturn null\n\t}\n}\n\nfunction cellIssue(\n\trowId: RowId,\n\tfield: FieldSchema,\n\tcode: LocalIssueCode,\n\tmessage: string,\n\tparams: Readonly<Record<string, string>>\n): Issue {\n\treturn Object.freeze({\n\t\tid: `local|${code}|${rowId}|${field.key}`,\n\t\tscope: \"cell\",\n\t\tsource: \"local\",\n\t\trowId,\n\t\tfield: field.key,\n\t\ttargets: Object.freeze([]),\n\t\tcode,\n\t\tseverity: \"error\",\n\t\tblocking: true,\n\t\tstale: false,\n\t\tmessage,\n\t\tparams: Object.freeze({ field: field.key, type: field.type, ...params })\n\t})\n}\n\nconst SYMBOLS: Readonly<Record<ConditionOp, string>> = {\n\t\"=\": \"=\",\n\t\"!=\": \"≠\",\n\t\"<\": \"<\",\n\t\"<=\": \"≤\",\n\t\">\": \">\",\n\t\">=\": \"≥\",\n\tfilled: \"filled\",\n\tempty: \"empty\"\n}\n\nconst ENGLISH_COMPARISONS: Readonly<Record<string, string>> = {\n\t\"=\": \"equal to\",\n\t\"!=\": \"different from\",\n\t\"<\": \"less than\",\n\t\"<=\": \"at most\",\n\t\">\": \"greater than\",\n\t\">=\": \"at least\"\n}\n\n/**\n * A broken row check as an issue on the cell it is about. Its params carry what an interface words\n * it from, in the sheet's own writing: the other field by its label, a value as the sheet writes\n * it, each condition of `when` as `when0Field`, `when0Op` and `when0Value`, and a check's own\n * words as `message.tr`, `message.en`.\n */\nfunction checkIssue(rowId: RowId, check: RowCheck, schema: ModuleSchema, settings: ValueSettings): Issue {\n\tconst field = schema.field(check.assert.field)\n\tconst label = (key: string): string => schema.field(key).label\n\tconst operand = (condition: RowCondition): string =>\n\t\tcondition.other !== null\n\t\t\t? label(condition.other)\n\t\t\t: condition.value === null\n\t\t\t\t? \"\"\n\t\t\t\t: formatCell(schema.field(condition.field), condition.value, settings)\n\tconst op = check.assert.op\n\tconst code: LocalIssueCode = op === \"filled\" ? \"check_filled\" : op === \"empty\" ? \"check_empty\" : \"check_compare\"\n\tconst params: Record<string, string> = {\n\t\tfield: field.key,\n\t\ttype: field.type,\n\t\tcheck: check.id,\n\t\top,\n\t\twhen: String(check.when.length)\n\t}\n\n\tif (code === \"check_compare\") {\n\t\tparams.operand = operand(check.assert)\n\t}\n\n\tcheck.when.forEach((condition, index) => {\n\t\tparams[`when${index}Field`] = label(condition.field)\n\t\tparams[`when${index}Op`] = condition.op\n\t\tparams[`when${index}Value`] = operand(condition)\n\t})\n\n\tfor (const [language, text] of Object.entries(check.message ?? {})) {\n\t\tparams[`message.${language}`] = text\n\t}\n\n\tconst when =\n\t\tcheck.when.length === 0\n\t\t\t? \"\"\n\t\t\t: ` when ${check.when\n\t\t\t\t\t.map(condition =>\n\t\t\t\t\t\tcondition.op === \"filled\" || condition.op === \"empty\"\n\t\t\t\t\t\t\t? `${label(condition.field)} is ${condition.op}`\n\t\t\t\t\t\t\t: `${label(condition.field)} ${SYMBOLS[condition.op]} ${operand(condition)}`\n\t\t\t\t\t)\n\t\t\t\t\t.join(\" and \")}`\n\tconst english =\n\t\tcode === \"check_filled\"\n\t\t\t? `${field.label} is required${when}.`\n\t\t\t: code === \"check_empty\"\n\t\t\t\t? `${field.label} must be left empty${when}.`\n\t\t\t\t: `${field.label} must be ${ENGLISH_COMPARISONS[op] ?? op} ${params.operand}${when}.`\n\n\treturn Object.freeze({\n\t\tid: `local|check|${check.id}|${rowId}`,\n\t\tscope: \"cell\",\n\t\tsource: \"local\",\n\t\trowId,\n\t\tfield: field.key,\n\t\ttargets: Object.freeze(\n\t\t\tcheck.assert.other === null ? [] : [Object.freeze({ rowId, field: check.assert.other })]\n\t\t),\n\t\tcode,\n\t\tseverity: check.severity,\n\t\tblocking: check.severity === \"error\",\n\t\tstale: false,\n\t\tmessage: check.message?.en ?? english,\n\t\tparams: Object.freeze(params)\n\t})\n}\n\nfunction hasRule(field: FieldSchema, rule: FieldRule[\"rule\"]): boolean {\n\treturn field.rules.some(candidate => candidate.rule === rule)\n}\n\n/** What makes two values the same for uniqueness: a lookup by its id, anything else by its content. */\nfunction uniqueKey(value: CellValue): string | null {\n\tif (value === null) {\n\t\treturn null\n\t}\n\n\tif (isLookupValue(value)) {\n\t\treturn `id:${typeof value.id}:${value.id}`\n\t}\n\n\tconst number = typeof value === \"number\" || typeof value === \"string\" ? decimalText(value) : null\n\n\t// \"12.50\" and 12.5 are one number.\n\treturn number !== null ? `number:${normalize(number)}` : `value:${JSON.stringify(value)}`\n}\n\n/** Decimal text in one form, so \"12.50\" and \"12.5\" compare and group as one number. */\nfunction normalize(number: string): string {\n\tconst negative = number.startsWith(\"-\")\n\tconst [whole = \"0\", fraction = \"\"] = (negative ? number.slice(1) : number).split(\".\")\n\tconst trimmedWhole = whole.replace(/^0+(?=\\d)/, \"\")\n\tconst trimmedFraction = fraction.replace(/0+$/, \"\")\n\tconst body = trimmedFraction === \"\" ? trimmedWhole : `${trimmedWhole}.${trimmedFraction}`\n\n\treturn body === \"0\" || !negative ? body : `-${body}`\n}\n\nfunction describe(value: CellValue): string {\n\tif (isLookupValue(value)) {\n\t\treturn value.label\n\t}\n\n\treturn typeof value === \"string\" ? value : JSON.stringify(value)\n}\n","import { TabulaError } from \"./errors.js\"\nimport type { RowId } from \"./rows.js\"\nimport type { IssueScope, IssueSeverity, IssueTarget } from \"./validation.js\"\nimport type { CellValue } from \"./value.js\"\n\n/**\n * What passes between a sheet and the backend of the application that embeds it.\n *\n * The package never chooses how: an application gives a `SheetAdapters` object, and each adapter\n * calls its backend however it likes and turns the answer into the shapes here. That is also where\n * a backend with answers of its own shape is adapted.\n */\n\n/** One row as a backend receives it, under the id it keeps in the sheet. */\nexport interface PayloadRow {\n\treadonly rowId: RowId\n\t/**\n\t * Every field of the schema that is submitted (`submit`), empty ones as null, in the form the grid\n\t * writes: a number as decimal text with a point, a date as ISO 8601, a yes/no as a boolean, an\n\t * option as its value. Text a host loaded, such as \"1.234,56\", goes as what it reads to; text the\n\t * grid could not read goes as it stands. A lookup is sent as its id; one holding text never\n\t * matched to a record is sent as `{ label }`, for the backend to match or refuse.\n\t */\n\treadonly values: Readonly<Record<string, CellValue>>\n}\n\n/** What a pre-flight check is sent, and what a process run is sent with its key. */\nexport interface SheetRequest {\n\t/** Pairs an answer with its question; new for every request. */\n\treadonly requestId: string\n\treadonly module: string\n\treadonly schemaVersion: number\n\treadonly sheetId: string\n\t/** The revision of the sheet the rows were read at: what the answer will be about. */\n\treadonly revision: number\n\treadonly rows: readonly PayloadRow[]\n}\n\nexport interface ProcessRequest extends SheetRequest {\n\t/**\n\t * The same for every attempt at one run, so a backend that has seen it answers with what it did\n\t * rather than doing it twice. A run that got a definite answer is never sent again; the next one\n\t * gets a new key.\n\t */\n\treadonly idempotencyKey: string\n}\n\n/** An issue as a backend reports it. Everything but `code` has a sensible default. */\nexport interface IssueInput {\n\t/** Left out: `cell` with a row and a field, `row` with a row only, `sheet` with neither. */\n\treadonly scope?: IssueScope\n\t/** Another sheet's issue is passed over. */\n\treadonly sheetId?: string | null\n\treadonly rowId?: RowId | null\n\treadonly field?: string | null\n\treadonly targets?: readonly IssueTarget[]\n\treadonly code: string\n\t/** `error` by default. */\n\treadonly severity?: IssueSeverity\n\t/** Whether it stops the sheet from being processed; by default, an error does and a warning does not. */\n\treadonly blocking?: boolean\n\t/** Shown when the interface has no wording of its own for the code; the code itself by default. */\n\treadonly message?: string\n\treadonly params?: Readonly<Record<string, string | number | boolean | null>>\n}\n\n/**\n * What processing a row would do: make a new record, change one, or leave one as it is. Only the\n * backend can tell, for only it holds the records.\n */\nexport type RowAction = \"create\" | \"update\" | \"unchanged\"\n\n/** What a pre-flight check says a row would do, for a preview before the run. */\nexport interface RowPlanInput {\n\treadonly rowId: RowId\n\treadonly action: RowAction\n\t/**\n\t * For an update, each field that would change, with the value the backend holds now, in the form\n\t * rows are sent in; a lookup may come as `{ id, label }`, to be shown by its label. A field left\n\t * out is not changing.\n\t */\n\treadonly previous?: Readonly<Record<string, CellValue>>\n}\n\nexport interface CheckResponse {\n\t/** When given, it must be the request's. */\n\treadonly requestId?: string\n\treadonly issues?: readonly IssueInput[]\n\t/**\n\t * What each row would do if it were processed now. A backend that cannot tell leaves it out, and\n\t * a preview then has only the count of rows to show; so does a row it leaves out.\n\t */\n\treadonly plan?: readonly RowPlanInput[]\n}\n\n/**\n * `pending`: accepted and still running; the session asks `processStatus` until it is not.\n * `partial`: some rows went through and some did not, which only a backend that allows it says.\n * `cancelled`: stopped on request. Rows done before the stop stay done: a cancel takes nothing back.\n */\nexport type ProcessStatus = \"pending\" | \"succeeded\" | \"partial\" | \"failed\" | \"cancelled\"\n\n/** `skipped`: not processed at all, such as after another row failed in an all-or-nothing run. */\nexport type RowOutcome = \"succeeded\" | \"failed\" | \"skipped\"\n\nexport interface RowResultInput {\n\treadonly rowId: RowId\n\treadonly result: RowOutcome\n\t/** Bound to this row unless they name another. */\n\treadonly issues?: readonly IssueInput[]\n\t/** Whatever the backend wants kept with the row, such as the id of the record it created. */\n\treadonly data?: Readonly<Record<string, CellValue>>\n}\n\nexport interface ProcessProgress {\n\treadonly done: number\n\treadonly total: number\n}\n\nexport interface ProcessResponse {\n\t/** When given, it must be the request's. */\n\treadonly requestId?: string\n\t/** The backend's name for the run, to ask about it or cancel it by. */\n\treadonly operationId?: string | null\n\treadonly status: ProcessStatus\n\t/**\n\t * A row of the request left out is taken as not processed, unless the run as a whole succeeded.\n\t * A row the request did not hold is passed over.\n\t */\n\treadonly rows?: readonly RowResultInput[]\n\t/** About the run as a whole rather than one row. */\n\treadonly issues?: readonly IssueInput[]\n\treadonly progress?: ProcessProgress | null\n}\n\n/** How a run is asked about or cancelled: by its operation id when known, always by its key. */\nexport interface StatusQuery {\n\treadonly requestId: string\n\treadonly idempotencyKey: string\n\treadonly operationId: string | null\n}\n\nexport interface AdapterContext {\n\t/** Aborted when the answer is no longer wanted. An adapter passes it on to its HTTP client. */\n\treadonly signal: AbortSignal\n\treadonly requestId: string\n}\n\n/**\n * How a sheet reaches its backend. Each is optional: a sheet with no `preflight` has no backend\n * check, one with no `processStatus` cannot follow a run that answers `pending`.\n *\n * An adapter that throws, such as on a network error, is a failure of the request, kept apart from\n * the issues of the data. One that answers in the wrong shape is a failure too.\n */\nexport interface SheetAdapters {\n\tpreflight?(request: SheetRequest, context: AdapterContext): Promise<CheckResponse>\n\tprocess?(request: ProcessRequest, context: AdapterContext): Promise<ProcessResponse>\n\tprocessStatus?(query: StatusQuery, context: AdapterContext): Promise<ProcessResponse>\n\tcancelProcess?(query: StatusQuery, context: AdapterContext): Promise<void>\n}\n\n// ---------------------------------------------------------------- reading answers\n\nconst SCOPES: readonly string[] = [\"cell\", \"row\", \"sheet\", \"workbook\"]\nconst SEVERITIES: readonly string[] = [\"error\", \"warning\"]\nconst STATUSES: readonly string[] = [\"pending\", \"succeeded\", \"partial\", \"failed\", \"cancelled\"]\nconst OUTCOMES: readonly string[] = [\"succeeded\", \"failed\", \"skipped\"]\nconst ACTIONS: readonly string[] = [\"create\", \"update\", \"unchanged\"]\n\n/**\n * Checks a pre-flight answer against the contract. Properties it does not know are passed over, so\n * a backend may send more; a known one of the wrong kind is refused, with every problem at once.\n *\n * @throws TabulaError `invalid_response`\n */\nexport function readCheckResponse(input: unknown): CheckResponse {\n\tconst reader = new Reader()\n\tconst root = reader.object(input, \"(root)\")\n\n\tif (root === null) {\n\t\treturn reader.done({})\n\t}\n\n\treturn reader.done({\n\t\t...optional(\"requestId\", reader.string(root.requestId, \"requestId\", true)),\n\t\t...optional(\"issues\", reader.issues(root.issues, \"issues\")),\n\t\t...optional(\"plan\", reader.plans(root.plan, \"plan\"))\n\t})\n}\n\n/**\n * Checks a process answer, or a status answer, against the contract.\n *\n * @throws TabulaError `invalid_response`\n */\nexport function readProcessResponse(input: unknown): ProcessResponse {\n\tconst reader = new Reader()\n\tconst root = reader.object(input, \"(root)\")\n\n\tif (root === null) {\n\t\treturn reader.done({ status: \"failed\" })\n\t}\n\n\tconst status = reader.oneOf(root.status, \"status\", STATUSES)\n\n\treturn reader.done({\n\t\tstatus: (status ?? \"failed\") as ProcessStatus,\n\t\t...optional(\"requestId\", reader.string(root.requestId, \"requestId\", true)),\n\t\t...optional(\"operationId\", reader.nullableString(root.operationId, \"operationId\")),\n\t\t...optional(\"rows\", reader.rows(root.rows, \"rows\")),\n\t\t...optional(\"issues\", reader.issues(root.issues, \"issues\")),\n\t\t...optional(\"progress\", reader.progress(root.progress, \"progress\"))\n\t})\n}\n\nfunction optional<K extends string, V>(key: K, value: V | undefined): { [P in K]?: V } {\n\treturn value === undefined ? {} : ({ [key]: value } as { [P in K]?: V })\n}\n\ntype Plain = Record<string, unknown>\n\nclass Reader {\n\treadonly #problems: string[] = []\n\n\tdone<T>(value: T): T {\n\t\tif (this.#problems.length > 0) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_response\",\n\t\t\t\t`The backend's answer is not in the expected shape:\\n${this.#problems.map(line => ` ${line}`).join(\"\\n\")}`\n\t\t\t)\n\t\t}\n\n\t\treturn value\n\t}\n\n\tproblem(path: string, message: string): void {\n\t\tthis.#problems.push(`${path}: ${message}`)\n\t}\n\n\tobject(value: unknown, path: string): Plain | null {\n\t\tif (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n\t\t\treturn value as Plain\n\t\t}\n\n\t\tthis.problem(path, `must be an object; got ${describe(value)}.`)\n\n\t\treturn null\n\t}\n\n\t/** `undefined` when missing and allowed to be. */\n\tstring(value: unknown, path: string, optionalValue = false): string | undefined {\n\t\tif (value === undefined && optionalValue) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (typeof value === \"string\" && value !== \"\") {\n\t\t\treturn value\n\t\t}\n\n\t\tthis.problem(path, `must be a non-empty string; got ${describe(value)}.`)\n\n\t\treturn undefined\n\t}\n\n\tnullableString(value: unknown, path: string): string | null | undefined {\n\t\treturn value === null ? null : this.string(value, path, true)\n\t}\n\n\toneOf(value: unknown, path: string, allowed: readonly string[], optionalValue = false): string | undefined {\n\t\tif (value === undefined && optionalValue) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (typeof value === \"string\" && allowed.includes(value)) {\n\t\t\treturn value\n\t\t}\n\n\t\tthis.problem(path, `must be one of ${allowed.join(\", \")}; got ${describe(value)}.`)\n\n\t\treturn undefined\n\t}\n\n\tarray(value: unknown, path: string): unknown[] | undefined {\n\t\tif (value === undefined) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (Array.isArray(value)) {\n\t\t\treturn value\n\t\t}\n\n\t\tthis.problem(path, `must be an array; got ${describe(value)}.`)\n\n\t\treturn undefined\n\t}\n\n\tissues(value: unknown, path: string): IssueInput[] | undefined {\n\t\treturn this.array(value, path)\n\t\t\t?.map((item, index) => this.issue(item, `${path}[${index}]`))\n\t\t\t.filter((issue): issue is IssueInput => issue !== null)\n\t}\n\n\tissue(value: unknown, path: string): IssueInput | null {\n\t\tconst item = this.object(value, path)\n\n\t\tif (item === null) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst code = this.string(item.code, `${path}.code`)\n\t\tconst blocking = item.blocking\n\n\t\tif (blocking !== undefined && typeof blocking !== \"boolean\") {\n\t\t\tthis.problem(`${path}.blocking`, `must be true or false; got ${describe(blocking)}.`)\n\t\t}\n\n\t\treturn {\n\t\t\tcode: code ?? \"\",\n\t\t\t...optional(\"scope\", this.oneOf(item.scope, `${path}.scope`, SCOPES, true) as IssueScope | undefined),\n\t\t\t...optional(\"sheetId\", this.nullableString(item.sheetId, `${path}.sheetId`)),\n\t\t\t...optional(\"rowId\", this.nullableString(item.rowId, `${path}.rowId`)),\n\t\t\t...optional(\"field\", this.nullableString(item.field, `${path}.field`)),\n\t\t\t...optional(\"targets\", this.targets(item.targets, `${path}.targets`)),\n\t\t\t...optional(\n\t\t\t\t\"severity\",\n\t\t\t\tthis.oneOf(item.severity, `${path}.severity`, SEVERITIES, true) as IssueSeverity | undefined\n\t\t\t),\n\t\t\t...optional(\"blocking\", typeof blocking === \"boolean\" ? blocking : undefined),\n\t\t\t...optional(\"message\", this.string(item.message, `${path}.message`, true)),\n\t\t\t...optional(\"params\", this.params(item.params, `${path}.params`))\n\t\t}\n\t}\n\n\ttargets(value: unknown, path: string): IssueTarget[] | undefined {\n\t\treturn this.array(value, path)\n\t\t\t?.map((item, index) => {\n\t\t\t\tconst target = this.object(item, `${path}[${index}]`)\n\t\t\t\tconst rowId = target && this.string(target.rowId, `${path}[${index}].rowId`)\n\t\t\t\tconst field = target && this.string(target.field, `${path}[${index}].field`)\n\n\t\t\t\treturn rowId && field ? { rowId, field } : null\n\t\t\t})\n\t\t\t.filter((target): target is IssueTarget => target !== null)\n\t}\n\n\tparams(value: unknown, path: string): Record<string, string | number | boolean | null> | undefined {\n\t\tif (value === undefined) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tconst params = this.object(value, path)\n\n\t\tif (params === null) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tfor (const [key, param] of Object.entries(params)) {\n\t\t\tif (param !== null && ![\"string\", \"number\", \"boolean\"].includes(typeof param)) {\n\t\t\t\tthis.problem(`${path}.${key}`, `must be text, a number, true, false or null; got ${describe(param)}.`)\n\t\t\t}\n\t\t}\n\n\t\treturn params as Record<string, string | number | boolean | null>\n\t}\n\n\trows(value: unknown, path: string): RowResultInput[] | undefined {\n\t\treturn this.array(value, path)\n\t\t\t?.map((item, index) => this.row(item, `${path}[${index}]`))\n\t\t\t.filter((row): row is RowResultInput => row !== null)\n\t}\n\n\trow(value: unknown, path: string): RowResultInput | null {\n\t\tconst item = this.object(value, path)\n\n\t\tif (item === null) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst rowId = this.string(item.rowId, `${path}.rowId`)\n\t\tconst result = this.oneOf(item.result, `${path}.result`, OUTCOMES) as RowOutcome | undefined\n\t\tconst data = item.data === undefined ? undefined : this.object(item.data, `${path}.data`)\n\n\t\tif (rowId === undefined || result === undefined) {\n\t\t\treturn null\n\t\t}\n\n\t\treturn {\n\t\t\trowId,\n\t\t\tresult,\n\t\t\t...optional(\"issues\", this.issues(item.issues, `${path}.issues`)),\n\t\t\t...optional(\"data\", data === null ? undefined : (data as Record<string, CellValue>))\n\t\t}\n\t}\n\n\tplans(value: unknown, path: string): RowPlanInput[] | undefined {\n\t\treturn this.array(value, path)\n\t\t\t?.map((item, index) => this.plan(item, `${path}[${index}]`))\n\t\t\t.filter((plan): plan is RowPlanInput => plan !== null)\n\t}\n\n\tplan(value: unknown, path: string): RowPlanInput | null {\n\t\tconst item = this.object(value, path)\n\n\t\tif (item === null) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst rowId = this.string(item.rowId, `${path}.rowId`)\n\t\tconst action = this.oneOf(item.action, `${path}.action`, ACTIONS) as RowAction | undefined\n\t\tconst previous = item.previous === undefined ? undefined : this.object(item.previous, `${path}.previous`)\n\n\t\tif (rowId === undefined || action === undefined) {\n\t\t\treturn null\n\t\t}\n\n\t\treturn {\n\t\t\trowId,\n\t\t\taction,\n\t\t\t...optional(\"previous\", previous === null ? undefined : (previous as Record<string, CellValue>))\n\t\t}\n\t}\n\n\tprogress(value: unknown, path: string): ProcessProgress | null | undefined {\n\t\tif (value === undefined || value === null) {\n\t\t\treturn value\n\t\t}\n\n\t\tconst item = this.object(value, path)\n\t\tconst done = item?.done\n\t\tconst total = item?.total\n\n\t\tif (item === null) {\n\t\t\treturn undefined\n\t\t}\n\n\t\tif (typeof done !== \"number\" || typeof total !== \"number\" || done < 0 || total < 0) {\n\t\t\tthis.problem(path, \"must have a done and a total, each a number, 0 or more.\")\n\n\t\t\treturn undefined\n\t\t}\n\n\t\treturn { done, total }\n\t}\n}\n\nfunction describe(value: unknown): string {\n\tif (value === null) {\n\t\treturn \"null\"\n\t}\n\n\tif (Array.isArray(value)) {\n\t\treturn \"an array\"\n\t}\n\n\treturn typeof value === \"string\" ? JSON.stringify(value) : typeof value\n}\n","import { freezeColumnLayout, mapColumnLayout, readColumnLayout, type ColumnLayout } from \"./columns.js\"\nimport type { ProcessRequest } from \"./contract.js\"\nimport { TabulaError } from \"./errors.js\"\nimport { readMarks, type CellMark, type CellMarks, type MarksData } from \"./marks.js\"\nimport type { RowEntry, RowInit, RowStore } from \"./rows.js\"\nimport { FIELD_TYPES, type FieldSchema, type FieldType, type ModuleSchema } from \"./schema.js\"\nimport type { PendingRun, PersistedSession, RowResult, SheetSession } from \"./session.js\"\nimport { toCellValue, type CellValue } from \"./value.js\"\nimport { valueProblem } from \"./values/read.js\"\nimport { VALUE_SETTINGS, type ValueSettings } from \"./values/settings.js\"\n\n/**\n * A sheet saved to go on with later. Saving a draft creates no business record: it is the sheet as\n * it stands, its rows under their ids, and what the backend said about each.\n *\n * It is plain JSON, kept wherever the application keeps it. The rows were written against one\n * version of the module's schema; `openDraft` tells when the schema has moved on since, and opens\n * such a draft only once that has been seen and accepted.\n */\n\nexport const DRAFT_FORMAT = \"tabula-grid.draft\"\nexport const DRAFT_VERSION = 1\n\n/** A field as the draft's rows were written against it. */\nexport interface DraftField {\n\treadonly key: string\n\treadonly type: FieldType\n\t/** Its label then, so a field gone since is still known by name. Drafts saved before it was kept have none. */\n\treadonly label?: string\n}\n\n/** The user's view of the sheet. */\nexport interface DraftView {\n\t/** Widths the user set, by field key, as the grid's `columnWidths` holds them. */\n\treadonly columnWidths: Readonly<Record<string, number>>\n\t/** Which columns are hidden, pinned or moved, as the grid's `columns` holds them. */\n\treadonly columns?: ColumnLayout\n}\n\nexport interface Draft {\n\treadonly format: typeof DRAFT_FORMAT\n\t/** The version of this format, not of the module's schema. */\n\treadonly version: typeof DRAFT_VERSION\n\t/** Made by the browser, so every save of one draft is the same draft: a lost answer makes no second one. */\n\treadonly id: string\n\treadonly name: string | null\n\treadonly module: string\n\treadonly schemaVersion: number\n\treadonly sheetId: string\n\treadonly fields: readonly DraftField[]\n\t/** When it was saved, as ISO 8601 text. */\n\treadonly savedAt: string\n\t/** The sheet's revision when it was saved. */\n\treadonly revision: number\n\treadonly rows: readonly RowEntry[]\n\treadonly session: PersistedSession\n\treadonly view: DraftView\n\t/** What the user put on cells by hand, by row id then field key; left out when nothing is. */\n\treadonly marks?: MarksData\n}\n\nexport interface CreateDraftOptions {\n\treadonly id: string\n\treadonly name?: string | null\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\t/** Its results and any run with no answer go into the draft. */\n\treadonly session?: SheetSession | null\n\treadonly view?: DraftView\n\t/** The marks on the cells: kept for the rows the sheet has. */\n\treadonly marks?: CellMarks | null\n\treadonly now?: () => Date\n}\n\n/** The sheet as it stands, as a draft. */\nexport function createDraft(options: CreateDraftOptions): Draft {\n\tconst { schema, store, session } = options\n\tconst marks = options.marks ? options.marks.toJSON(store.rowIds()) : {}\n\n\treturn Object.freeze({\n\t\tformat: DRAFT_FORMAT,\n\t\tversion: DRAFT_VERSION,\n\t\tid: options.id,\n\t\tname: options.name ?? null,\n\t\tmodule: schema.module,\n\t\tschemaVersion: schema.schemaVersion,\n\t\tsheetId: session?.sheetId ?? schema.module,\n\t\tfields: Object.freeze(\n\t\t\tschema.fields.map(field => Object.freeze({ key: field.key, type: field.type, label: field.label }))\n\t\t),\n\t\tsavedAt: (options.now?.() ?? new Date()).toISOString(),\n\t\trevision: store.revision,\n\t\trows: Object.freeze(store.snapshot()),\n\t\tsession: session?.persisted() ?? Object.freeze({ results: Object.freeze([]), pending: null }),\n\t\tview: Object.freeze({\n\t\t\tcolumnWidths: Object.freeze({ ...options.view?.columnWidths }),\n\t\t\t...(options.view?.columns ? { columns: freezeColumnLayout(options.view.columns) } : {})\n\t\t}),\n\t\t...(Object.keys(marks).length > 0 ? { marks: freezeMarks(marks) } : {})\n\t})\n}\n\n// ---------------------------------------------------------------- opening\n\n/** How the module's schema has moved on since a draft was saved. */\nexport interface DraftChanges {\n\treadonly fromVersion: number\n\treadonly toVersion: number\n\t/** Fields the draft has no values for: they open empty. */\n\treadonly added: readonly string[]\n\t/** Fields the schema no longer has: their values are dropped. */\n\treadonly removed: readonly string[]\n\t/** Fields of another type now: their values are kept, and checked again as the new type. */\n\treadonly retyped: readonly { readonly key: string; readonly from: FieldType; readonly to: FieldType }[]\n\treadonly renamed: readonly { readonly from: string; readonly to: string }[]\n\t/** How many rows hold a value in a removed field: what dropping them loses. */\n\treadonly losing: number\n}\n\nexport interface OpenDraftOptions {\n\t/** Open even though the schema has moved on, once the user has seen `changes` and agreed. */\n\treadonly accept?: boolean\n\t/** A field renamed since, by its old key: its values go to the new one. */\n\treadonly rename?: Readonly<Record<string, string>>\n}\n\nexport type DraftOpening =\n\t| {\n\t\t\treadonly status: \"opened\"\n\t\t\t/** For a new `RowStore`, under the ids the rows had. */\n\t\t\treadonly rows: RowInit[]\n\t\t\t/** For a new `SheetSession`'s `restore`. */\n\t\t\treadonly session: PersistedSession\n\t\t\treadonly view: DraftView\n\t\t\t/** For a new `CellMarks`: the marks on the cells, by row id then field key. */\n\t\t\treadonly marks: MarksData\n\t\t\t/** What moved on since the draft was saved, or null when nothing did. */\n\t\t\treadonly changes: DraftChanges | null\n\t }\n\t/** The schema has moved on: show `changes`, and open again with `accept` if the user agrees. */\n\t| { readonly status: \"review\"; readonly changes: DraftChanges }\n\t/** A draft of another module altogether. */\n\t| { readonly status: \"wrong_module\"; readonly module: string }\n\n/**\n * Opens a draft against the module's schema as it is now. A draft saved under another schema\n * version is not opened silently: it comes back for review, with what changed, until it is opened\n * again with `accept`. Every value is then checked again by the sheet's validator, as any is.\n */\nexport function openDraft(draft: Draft, schema: ModuleSchema, options: OpenDraftOptions = {}): DraftOpening {\n\tif (draft.module !== schema.module) {\n\t\treturn { status: \"wrong_module\", module: draft.module }\n\t}\n\n\tconst rename = renames(draft, schema, options.rename ?? {})\n\tconst changes = compare(draft, schema, rename)\n\n\tif (changes && !options.accept) {\n\t\treturn { status: \"review\", changes }\n\t}\n\n\tconst keep = (key: string): string | null => {\n\t\tconst target = rename.get(key) ?? key\n\n\t\treturn schema.has(target) ? target : null\n\t}\n\n\tconst rows = draft.rows.map(row => {\n\t\tconst values: Record<string, CellValue> = {}\n\n\t\tfor (const [key, value] of Object.entries(row.values)) {\n\t\t\tconst target = keep(key)\n\n\t\t\tif (target !== null) {\n\t\t\t\tvalues[target] = value\n\t\t\t}\n\t\t}\n\n\t\treturn { rowId: row.rowId, values }\n\t})\n\n\tconst columnWidths: Record<string, number> = {}\n\n\tfor (const [key, width] of Object.entries(draft.view.columnWidths)) {\n\t\tconst target = keep(key)\n\n\t\tif (target !== null) {\n\t\t\tcolumnWidths[target] = width\n\t\t}\n\t}\n\n\t// The layout and the marks follow renamed fields, and let go of removed ones.\n\tconst columns = draft.view.columns ? mapColumnLayout(draft.view.columns, keep) : undefined\n\tconst marks: Record<string, Record<string, CellMark>> = {}\n\n\tfor (const [rowId, cells] of Object.entries(draft.marks ?? {})) {\n\t\tfor (const [key, mark] of Object.entries(cells)) {\n\t\t\tconst target = keep(key)\n\n\t\t\tif (target !== null) {\n\t\t\t\tmarks[rowId] = { ...marks[rowId], [target]: mark }\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tstatus: \"opened\",\n\t\trows,\n\t\tsession: draft.session,\n\t\tview: Object.freeze({ columnWidths: Object.freeze(columnWidths), ...(columns ? { columns } : {}) }),\n\t\tmarks: freezeMarks(marks),\n\t\tchanges\n\t}\n}\n\nfunction renames(draft: Draft, schema: ModuleSchema, given: Readonly<Record<string, string>>): Map<string, string> {\n\tconst keys = new Set(draft.fields.map(field => field.key))\n\tconst map = new Map<string, string>()\n\n\tfor (const [from, to] of Object.entries(given)) {\n\t\tif (!keys.has(from)) {\n\t\t\tthrow new TabulaError(\"invalid_argument\", `The draft has no field \"${from}\" to rename.`)\n\t\t}\n\n\t\tif (!schema.has(to)) {\n\t\t\tthrow new TabulaError(\"unknown_field\", `The schema has no field \"${to}\" to rename \"${from}\" to.`)\n\t\t}\n\n\t\tmap.set(from, to)\n\t}\n\n\treturn map\n}\n\n/** A field of a draft, as a review before opening it shows it. */\nexport interface DraftFieldMapping {\n\treadonly key: string\n\t/** As the draft wrote it; null for a draft saved before labels were kept. */\n\treadonly label: string | null\n\treadonly type: FieldType\n\t/** Where its values go: its own field, the one it is renamed to, or null when they are dropped. */\n\treadonly target: string | null\n\t/** How many rows hold a value in it. */\n\treadonly filled: number\n\t/** Its first values, three at most, to know it by. */\n\treadonly samples: readonly CellValue[]\n\t/** How many of its values the target cannot read as its type: they open marked. */\n\treadonly unreadable: number\n}\n\nexport interface DraftMapping {\n\t/** Every field of the draft, in its order. */\n\treadonly fields: readonly DraftFieldMapping[]\n\t/** The schema's fields no field of the draft goes to: they open empty. */\n\treadonly added: readonly string[]\n\t/** How many rows lose a value in a field that is dropped. */\n\treadonly losing: number\n}\n\nexport interface MapDraftOptions {\n\t/** A field renamed since, by its old key, as `openDraft` takes it. */\n\treadonly rename?: Readonly<Record<string, string>>\n\t/** How values are read, to count what a field of another type cannot. Turkish by default. */\n\treadonly settings?: ValueSettings\n}\n\n/**\n * What opening a draft would do to each of its fields, with `rename` as given: for a screen that\n * lets the user map the fields of a draft saved under another schema before it opens.\n *\n * @throws TabulaError `invalid_argument` or `unknown_field` for a rename `openDraft` refuses\n */\nexport function mapDraft(draft: Draft, schema: ModuleSchema, options: MapDraftOptions = {}): DraftMapping {\n\tconst rename = renames(draft, schema, options.rename ?? {})\n\tconst settings = options.settings ?? VALUE_SETTINGS.tr\n\tconst targets = new Set<string>()\n\tlet losing = 0\n\n\tconst fields = draft.fields.map(field => {\n\t\tconst to = rename.get(field.key) ?? field.key\n\t\tconst target = schema.has(to) ? to : null\n\t\tconst values = draft.rows.map(row => row.values[field.key] ?? null).filter(value => value !== null)\n\t\tconst moved = target !== null && (target !== field.key || schema.field(target).type !== field.type)\n\t\tconst unreadable = moved\n\t\t\t? values.filter(value => valueProblem(schema.field(target), value, settings) !== null).length\n\t\t\t: 0\n\n\t\tif (target !== null) {\n\t\t\ttargets.add(target)\n\t\t}\n\n\t\treturn Object.freeze({\n\t\t\tkey: field.key,\n\t\t\tlabel: field.label ?? null,\n\t\t\ttype: field.type,\n\t\t\ttarget,\n\t\t\tfilled: values.length,\n\t\t\tsamples: Object.freeze(values.slice(0, 3)),\n\t\t\tunreadable\n\t\t})\n\t})\n\n\tconst dropped = new Set(fields.filter(field => field.target === null).map(field => field.key))\n\n\tfor (const row of draft.rows) {\n\t\tif (Object.entries(row.values).some(([key, value]) => value !== null && dropped.has(key))) {\n\t\t\tlosing++\n\t\t}\n\t}\n\n\treturn Object.freeze({\n\t\tfields: Object.freeze(fields),\n\t\tadded: Object.freeze(schema.fields.filter(field => !targets.has(field.key)).map(field => field.key)),\n\t\tlosing\n\t})\n}\n\n/**\n * The renames that look meant: each field the schema no longer has, paired with a new field of the\n * same type whose name shares a word with its own (\"Fiyat\" and \"Yeni fiyat\", \"price\" and\n * \"newPrice\"), the closest first, each new field taken once. A suggestion for the user to confirm,\n * never applied on its own.\n */\nexport function suggestRenames(draft: Draft, schema: ModuleSchema): Record<string, string> {\n\tconst kept = new Set(draft.fields.map(field => field.key))\n\tconst fresh = schema.fields.filter(field => !kept.has(field.key))\n\tconst pairs: { readonly from: string; readonly to: string; readonly score: number }[] = []\n\n\tfor (const old of draft.fields.filter(field => !schema.has(field.key))) {\n\t\tfor (const field of fresh) {\n\t\t\tconst score = field.type === old.type ? likeness(old, field) : 0\n\n\t\t\tif (score > 0) {\n\t\t\t\tpairs.push({ from: old.key, to: field.key, score })\n\t\t\t}\n\t\t}\n\t}\n\n\tpairs.sort((a, b) => b.score - a.score)\n\n\tconst result: Record<string, string> = {}\n\tconst taken = new Set<string>()\n\n\tfor (const pair of pairs) {\n\t\tif (!(pair.from in result) && !taken.has(pair.to)) {\n\t\t\tresult[pair.from] = pair.to\n\t\t\ttaken.add(pair.to)\n\t\t}\n\t}\n\n\treturn result\n}\n\n/** How alike two fields' names are: shared words of their labels count double, of their keys once. */\nfunction likeness(old: DraftField, field: FieldSchema): number {\n\tconst shared = (a: readonly string[], b: readonly string[]): number => a.filter(word => b.includes(word)).length\n\n\treturn 2 * shared(words(old.label ?? \"\"), words(field.label)) + shared(keyWords(old.key), keyWords(field.key))\n}\n\nfunction words(text: string): string[] {\n\treturn text\n\t\t.toLocaleLowerCase(\"tr\")\n\t\t.split(/[^\\p{L}\\p{N}]+/u)\n\t\t.filter(word => word.length > 1)\n}\n\n/** \"newPrice\", \"new_price\" and \"new-price\" alike: new, price. */\nfunction keyWords(key: string): string[] {\n\treturn words(key.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\"))\n}\n\n/** What moved on between the draft's schema and this one; null when nothing did. */\nfunction compare(draft: Draft, schema: ModuleSchema, rename: ReadonlyMap<string, string>): DraftChanges | null {\n\tconst old = new Map(draft.fields.map(field => [rename.get(field.key) ?? field.key, field] as const))\n\tconst added = schema.fields.filter(field => !old.has(field.key)).map(field => field.key)\n\tconst removed = draft.fields\n\t\t.filter(field => !schema.has(rename.get(field.key) ?? field.key))\n\t\t.map(field => field.key)\n\tconst retyped = schema.fields.flatMap(field => {\n\t\tconst before = old.get(field.key)\n\n\t\treturn before && before.type !== field.type ? [{ key: field.key, from: before.type, to: field.type }] : []\n\t})\n\tconst renamed = [...rename].map(([from, to]) => ({ from, to }))\n\n\tconst same =\n\t\tdraft.schemaVersion === schema.schemaVersion &&\n\t\tadded.length === 0 &&\n\t\tremoved.length === 0 &&\n\t\tretyped.length === 0 &&\n\t\trenamed.length === 0\n\n\tif (same) {\n\t\treturn null\n\t}\n\n\tconst gone = new Set(removed)\n\tconst losing = draft.rows.filter(row => Object.keys(row.values).some(key => gone.has(key))).length\n\n\treturn {\n\t\tfromVersion: draft.schemaVersion,\n\t\ttoVersion: schema.schemaVersion,\n\t\tadded,\n\t\tremoved,\n\t\tretyped,\n\t\trenamed,\n\t\tlosing\n\t}\n}\n\n// ---------------------------------------------------------------- reading\n\n/**\n * Checks what was read back from storage against the draft format, every problem at once.\n *\n * @throws TabulaError `invalid_draft`\n */\nexport function readDraft(input: unknown): Draft {\n\tconst problems: string[] = []\n\tconst problem = (path: string, message: string): void => {\n\t\tproblems.push(`${path}: ${message}`)\n\t}\n\tconst root = plain(input)\n\n\tif (!root) {\n\t\tthrow new TabulaError(\"invalid_draft\", \"A draft must be an object.\")\n\t}\n\n\tif (root.format !== DRAFT_FORMAT) {\n\t\tproblem(\"format\", `must be \"${DRAFT_FORMAT}\".`)\n\t}\n\n\tif (root.version !== DRAFT_VERSION) {\n\t\tproblem(\"version\", `must be ${DRAFT_VERSION}; a draft of another version of this format cannot be read.`)\n\t}\n\n\tconst text = (value: unknown, path: string): string => {\n\t\tif (typeof value !== \"string\" || value === \"\") {\n\t\t\tproblem(path, \"must be a non-empty string.\")\n\n\t\t\treturn \"\"\n\t\t}\n\n\t\treturn value\n\t}\n\tconst whole = (value: unknown, path: string): number => {\n\t\tif (!Number.isSafeInteger(value) || (value as number) < 0) {\n\t\t\tproblem(path, \"must be a whole number, 0 or more.\")\n\n\t\t\treturn 0\n\t\t}\n\n\t\treturn value as number\n\t}\n\n\tconst id = text(root.id, \"id\")\n\tconst name = root.name === null || root.name === undefined ? null : text(root.name, \"name\")\n\tconst module = text(root.module, \"module\")\n\tconst schemaVersion = whole(root.schemaVersion, \"schemaVersion\")\n\tconst sheetId = text(root.sheetId, \"sheetId\")\n\tconst savedAt = text(root.savedAt, \"savedAt\")\n\tconst revision = whole(root.revision, \"revision\")\n\n\tconst fields: DraftField[] = list(root.fields, \"fields\", problem).flatMap((item, index) => {\n\t\tconst field = plain(item)\n\t\tconst type = field?.type\n\n\t\tif (!field || !FIELD_TYPES.includes(type as FieldType)) {\n\t\t\tproblem(`fields[${index}]`, `must have a key and one of the field types (${FIELD_TYPES.join(\", \")}).`)\n\n\t\t\treturn []\n\t\t}\n\n\t\tconst label = field.label === undefined ? undefined : text(field.label, `fields[${index}].label`)\n\n\t\treturn [{ key: text(field.key, `fields[${index}].key`), type: type as FieldType, ...(label ? { label } : {}) }]\n\t})\n\n\tconst rows = list(root.rows, \"rows\", problem).flatMap((item, index) => {\n\t\tconst row = readRow(item, `rows[${index}]`, problem)\n\n\t\treturn row ? [row] : []\n\t})\n\n\tconst sessionRoot = plain(root.session)\n\tconst results = list(sessionRoot?.results, \"session.results\", problem).flatMap((item, index) => {\n\t\tconst result = readResult(item, `session.results[${index}]`, problem)\n\n\t\treturn result ? [result] : []\n\t})\n\tconst pending =\n\t\tsessionRoot?.pending === null || sessionRoot?.pending === undefined\n\t\t\t? null\n\t\t\t: readPending(sessionRoot.pending, \"session.pending\", problem)\n\n\tconst widths = plain(plain(root.view)?.columnWidths) ?? {}\n\tconst columnWidths: Record<string, number> = {}\n\n\tfor (const [key, width] of Object.entries(widths)) {\n\t\tif (typeof width === \"number\" && Number.isFinite(width) && width > 0) {\n\t\t\tcolumnWidths[key] = width\n\t\t} else {\n\t\t\tproblem(`view.columnWidths.${key}`, \"must be a number of pixels.\")\n\t\t}\n\t}\n\n\tconst columns = readColumnLayout(plain(root.view)?.columns, \"view.columns\", problem)\n\tconst marks = readMarks(root.marks, \"marks\", problem)\n\n\tif (problems.length > 0) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_draft\",\n\t\t\t`The draft cannot be read:\\n${problems.map(line => ` ${line}`).join(\"\\n\")}`\n\t\t)\n\t}\n\n\treturn Object.freeze({\n\t\tformat: DRAFT_FORMAT,\n\t\tversion: DRAFT_VERSION,\n\t\tid,\n\t\tname,\n\t\tmodule,\n\t\tschemaVersion,\n\t\tsheetId,\n\t\tfields: Object.freeze(fields),\n\t\tsavedAt,\n\t\trevision,\n\t\trows: Object.freeze(rows),\n\t\tsession: Object.freeze({ results: Object.freeze(results), pending }),\n\t\tview: Object.freeze({ columnWidths: Object.freeze(columnWidths), ...(columns ? { columns } : {}) }),\n\t\t...(Object.keys(marks).length > 0 ? { marks: freezeMarks(marks) } : {})\n\t})\n}\n\nfunction freezeMarks(marks: MarksData): MarksData {\n\treturn Object.freeze(\n\t\tObject.fromEntries(Object.entries(marks).map(([rowId, cells]) => [rowId, Object.freeze({ ...cells })]))\n\t)\n}\n\ntype Plain = Record<string, unknown>\ntype Problem = (path: string, message: string) => void\n\nfunction plain(value: unknown): Plain | null {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as Plain) : null\n}\n\nfunction list(value: unknown, path: string, problem: Problem): unknown[] {\n\tif (Array.isArray(value)) {\n\t\treturn value\n\t}\n\n\tproblem(path, \"must be an array.\")\n\n\treturn []\n}\n\nfunction readRow(item: unknown, path: string, problem: Problem): RowEntry | null {\n\tconst row = plain(item)\n\tconst values = plain(row?.values)\n\n\tif (!row || typeof row.rowId !== \"string\" || row.rowId === \"\" || !values) {\n\t\tproblem(path, \"must have a rowId and values.\")\n\n\t\treturn null\n\t}\n\n\tconst read: Record<string, CellValue> = {}\n\n\tfor (const [key, value] of Object.entries(values)) {\n\t\ttry {\n\t\t\tread[key] = toCellValue(value, `${path}.values.${key}`)\n\t\t} catch (error) {\n\t\t\tproblem(`${path}.values.${key}`, error instanceof Error ? error.message : String(error))\n\t\t}\n\t}\n\n\treturn Object.freeze({ rowId: row.rowId, values: Object.freeze(read) })\n}\n\nfunction readResult(item: unknown, path: string, problem: Problem): RowResult | null {\n\tconst result = plain(item)\n\tconst outcome = result?.outcome\n\n\tif (\n\t\t!result ||\n\t\ttypeof result.rowId !== \"string\" ||\n\t\ttypeof result.requestId !== \"string\" ||\n\t\t(outcome !== \"succeeded\" && outcome !== \"failed\" && outcome !== \"skipped\")\n\t) {\n\t\tproblem(path, \"must have a rowId, a requestId and an outcome of succeeded, failed or skipped.\")\n\n\t\treturn null\n\t}\n\n\tlet data: Record<string, CellValue> = {}\n\n\ttry {\n\t\tdata = toCellValue(plain(result.data) ?? {}, `${path}.data`) as Record<string, CellValue>\n\t} catch (error) {\n\t\tproblem(`${path}.data`, error instanceof Error ? error.message : String(error))\n\t}\n\n\treturn Object.freeze({ rowId: result.rowId, outcome, requestId: result.requestId, data })\n}\n\nfunction readPending(item: unknown, path: string, problem: Problem): PendingRun | null {\n\tconst pending = plain(item)\n\tconst request = plain(pending?.request)\n\tconst strings = [\"requestId\", \"idempotencyKey\", \"module\", \"sheetId\"] as const\n\tconst numbers = [\"schemaVersion\", \"revision\"] as const\n\n\tif (\n\t\t!pending ||\n\t\t!request ||\n\t\tstrings.some(key => typeof request[key] !== \"string\") ||\n\t\tnumbers.some(key => !Number.isSafeInteger(request[key])) ||\n\t\t!(pending.operationId === null || typeof pending.operationId === \"string\")\n\t) {\n\t\tproblem(path, \"must hold the request of the run with no answer, and its operationId or null.\")\n\n\t\treturn null\n\t}\n\n\tconst rows = list(request.rows, `${path}.request.rows`, problem).flatMap((row, index) => {\n\t\tconst read = readRow(row, `${path}.request.rows[${index}]`, problem)\n\n\t\treturn read ? [read] : []\n\t})\n\n\treturn Object.freeze({\n\t\trequest: Object.freeze({ ...(request as unknown as ProcessRequest), rows: Object.freeze(rows) }),\n\t\toperationId: pending.operationId as string | null\n\t})\n}\n","import { DRAFT_FORMAT, readDraft, type Draft } from \"./draft.js\"\nimport { TabulaError } from \"./errors.js\"\n\n/**\n * Several sheets kept together, as a spreadsheet keeps its tabs: each one a sheet of the same module\n * with rows, a template and a draft of its own, in the order the tabs stand, and the one that was\n * open. It is plain JSON, kept wherever the application keeps its drafts.\n *\n * Each sheet's draft is a draft as `createDraft` writes it, opened with `openDraft`; a sheet not yet\n * saved has none. A draft of one sheet, from before there were workbooks, reads as a workbook of\n * that one sheet.\n */\n\nexport const WORKBOOK_FORMAT = \"tabula-grid.workbook\"\nexport const WORKBOOK_VERSION = 1\n\n/** A value the application keeps with a sheet: text, a number, true or false, or null. */\nexport type SheetMeta = Readonly<Record<string, string | number | boolean | null>>\n\nexport interface WorkbookSheet {\n\t/** The sheet's id in requests and issues: a session over it takes it as its `sheetId`. */\n\treadonly sheetId: string\n\t/** What its tab says. */\n\treadonly name: string\n\t/** The template it works with, by its id; null for the module schema as it is. */\n\treadonly template: string | null\n\t/** The sheet as last saved; null before it was. */\n\treadonly draft: Draft | null\n\t/** What the application keeps with the sheet, such as the counts its tab shows while it is closed. */\n\treadonly meta: SheetMeta\n}\n\nexport interface Workbook {\n\treadonly format: typeof WORKBOOK_FORMAT\n\treadonly version: typeof WORKBOOK_VERSION\n\treadonly id: string\n\treadonly module: string\n\t/** The sheet that is open, by its id. */\n\treadonly active: string\n\t/** In the order their tabs stand; never empty. */\n\treadonly sheets: readonly WorkbookSheet[]\n}\n\nexport interface NewSheet {\n\treadonly name: string\n\treadonly template?: string | null\n\treadonly draft?: Draft | null\n\treadonly meta?: SheetMeta\n}\n\n/** A workbook of one sheet, open: where a module's work starts. */\nexport function createWorkbook(options: {\n\treadonly id: string\n\treadonly module: string\n\treadonly sheet: NewSheet\n}): Workbook {\n\tconst sheet = sheetOf(freeSheetId([]), options.sheet)\n\n\treturn freeze({\n\t\tformat: WORKBOOK_FORMAT,\n\t\tversion: WORKBOOK_VERSION,\n\t\tid: options.id,\n\t\tmodule: options.module,\n\t\tactive: sheet.sheetId,\n\t\tsheets: [sheet]\n\t})\n}\n\n/**\n * Checks what was read back from storage against the workbook format, every problem at once. A\n * draft of one sheet comes back as a workbook of that sheet, named `name`, or by its own name.\n *\n * @throws TabulaError `invalid_workbook`, or `invalid_draft` for a draft of one sheet that does not read\n */\nexport function readWorkbook(input: unknown, options: { readonly name?: string } = {}): Workbook {\n\tconst root = typeof input === \"object\" && input !== null && !Array.isArray(input) ? (input as Plain) : null\n\n\tif (!root) {\n\t\tthrow new TabulaError(\"invalid_workbook\", \"A workbook must be an object.\")\n\t}\n\n\tif (root.format === DRAFT_FORMAT) {\n\t\tconst draft = readDraft(input)\n\n\t\treturn freeze({\n\t\t\tformat: WORKBOOK_FORMAT,\n\t\t\tversion: WORKBOOK_VERSION,\n\t\t\tid: draft.id,\n\t\t\tmodule: draft.module,\n\t\t\tactive: draft.sheetId,\n\t\t\tsheets: [\n\t\t\t\t{\n\t\t\t\t\tsheetId: draft.sheetId,\n\t\t\t\t\tname: options.name ?? draft.name ?? draft.sheetId,\n\t\t\t\t\ttemplate: null,\n\t\t\t\t\tdraft,\n\t\t\t\t\tmeta: {}\n\t\t\t\t}\n\t\t\t]\n\t\t})\n\t}\n\n\tconst problems: string[] = []\n\tconst problem = (path: string, message: string): void => {\n\t\tproblems.push(`${path}: ${message}`)\n\t}\n\tconst text = (value: unknown, path: string): string => {\n\t\tif (typeof value !== \"string\" || value.trim() === \"\") {\n\t\t\tproblem(path, \"must be a non-empty string.\")\n\n\t\t\treturn \"\"\n\t\t}\n\n\t\treturn value\n\t}\n\n\tif (root.format !== WORKBOOK_FORMAT) {\n\t\tproblem(\"format\", `must be \"${WORKBOOK_FORMAT}\".`)\n\t}\n\n\tif (root.version !== WORKBOOK_VERSION) {\n\t\tproblem(\"version\", `must be ${WORKBOOK_VERSION}.`)\n\t}\n\n\tconst id = text(root.id, \"id\")\n\tconst module = text(root.module, \"module\")\n\tconst listed = Array.isArray(root.sheets) ? root.sheets : []\n\tconst seen = new Set<string>()\n\n\tif (!Array.isArray(root.sheets) || listed.length === 0) {\n\t\tproblem(\"sheets\", \"must be a list of one sheet or more.\")\n\t}\n\n\tconst sheets = listed.flatMap((item, index): WorkbookSheet[] => {\n\t\tconst path = `sheets[${index}]`\n\t\tconst sheet = typeof item === \"object\" && item !== null && !Array.isArray(item) ? (item as Plain) : null\n\n\t\tif (!sheet) {\n\t\t\tproblem(path, \"must be an object.\")\n\n\t\t\treturn []\n\t\t}\n\n\t\tconst sheetId = text(sheet.sheetId, `${path}.sheetId`)\n\n\t\tif (seen.has(sheetId)) {\n\t\t\tproblem(`${path}.sheetId`, `\"${sheetId}\" is another sheet's too.`)\n\t\t}\n\n\t\tseen.add(sheetId)\n\n\t\tconst template =\n\t\t\tsheet.template === null || sheet.template === undefined ? null : text(sheet.template, `${path}.template`)\n\t\tlet draft: Draft | null = null\n\n\t\tif (sheet.draft !== null && sheet.draft !== undefined) {\n\t\t\ttry {\n\t\t\t\tdraft = readDraft(sheet.draft)\n\n\t\t\t\tif (draft.module !== module) {\n\t\t\t\t\tproblem(`${path}.draft.module`, `must be \"${module}\", the workbook's.`)\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tproblem(`${path}.draft`, error instanceof Error ? (error.message.split(\"\\n\")[0] ?? \"\") : String(error))\n\t\t\t}\n\t\t}\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tsheetId,\n\t\t\t\tname: text(sheet.name, `${path}.name`),\n\t\t\t\ttemplate,\n\t\t\t\tdraft,\n\t\t\t\tmeta: readMeta(sheet.meta, `${path}.meta`, problem)\n\t\t\t}\n\t\t]\n\t})\n\n\tif (problems.length > 0) {\n\t\tthrow new TabulaError(\n\t\t\t\"invalid_workbook\",\n\t\t\t`The workbook cannot be read:\\n${problems.map(line => ` ${line}`).join(\"\\n\")}`\n\t\t)\n\t}\n\n\tconst active = typeof root.active === \"string\" && seen.has(root.active) ? root.active : (sheets[0]?.sheetId ?? \"\")\n\n\treturn freeze({ format: WORKBOOK_FORMAT, version: WORKBOOK_VERSION, id, module, active, sheets })\n}\n\n/** An id no sheet of these has: \"sheet-1\", \"sheet-2\"… */\nexport function freeSheetId(sheets: readonly Pick<WorkbookSheet, \"sheetId\">[]): string {\n\tconst taken = new Set(sheets.map(sheet => sheet.sheetId))\n\tlet number = 1\n\n\twhile (taken.has(`sheet-${number}`)) {\n\t\tnumber++\n\t}\n\n\treturn `sheet-${number}`\n}\n\n/** The workbook with a new sheet, after `after` (the last by default), open; and the sheet's id. */\nexport function addSheet(\n\tworkbook: Workbook,\n\tsheet: NewSheet,\n\tafter?: string\n): { readonly workbook: Workbook; readonly sheetId: string } {\n\tconst added = sheetOf(freeSheetId(workbook.sheets), sheet)\n\tconst at = after === undefined ? -1 : workbook.sheets.findIndex(each => each.sheetId === after)\n\tconst sheets = [...workbook.sheets]\n\n\tsheets.splice(at < 0 ? sheets.length : at + 1, 0, added)\n\n\treturn { workbook: freeze({ ...workbook, active: added.sheetId, sheets }), sheetId: added.sheetId }\n}\n\n/**\n * The workbook with one sheet changed: its name, template, draft or what the application keeps\n * with it.\n *\n * @throws TabulaError `invalid_argument` for a sheet the workbook does not have, or an empty name\n */\nexport function withSheet(\n\tworkbook: Workbook,\n\tsheetId: string,\n\tpatch: Partial<Pick<WorkbookSheet, \"name\" | \"template\" | \"draft\" | \"meta\">>\n): Workbook {\n\tfound(workbook, sheetId)\n\n\tif (patch.name !== undefined && patch.name.trim() === \"\") {\n\t\tthrow new TabulaError(\"invalid_argument\", \"A sheet's name must not be empty.\")\n\t}\n\n\treturn freeze({\n\t\t...workbook,\n\t\tsheets: workbook.sheets.map(sheet =>\n\t\t\tsheet.sheetId === sheetId\n\t\t\t\t? { ...sheet, ...patch, ...(patch.name === undefined ? {} : { name: patch.name.trim() }) }\n\t\t\t\t: sheet\n\t\t)\n\t})\n}\n\n/**\n * The workbook without a sheet. The one open then is its neighbour, the next or, for the last, the\n * one before.\n *\n * @throws TabulaError `invalid_argument` for the only sheet, or one the workbook does not have\n */\nexport function removeSheet(workbook: Workbook, sheetId: string): Workbook {\n\tfound(workbook, sheetId)\n\n\tif (workbook.sheets.length === 1) {\n\t\tthrow new TabulaError(\"invalid_argument\", \"A workbook keeps one sheet at least.\")\n\t}\n\n\tconst at = workbook.sheets.findIndex(sheet => sheet.sheetId === sheetId)\n\tconst sheets = workbook.sheets.filter(sheet => sheet.sheetId !== sheetId)\n\tconst active =\n\t\tworkbook.active === sheetId ? (sheets[Math.min(at, sheets.length - 1)]?.sheetId ?? \"\") : workbook.active\n\n\treturn freeze({ ...workbook, active, sheets })\n}\n\n/**\n * The workbook with a sheet moved among the tabs, to place `to` counted among the others: 0 first,\n * their number last. The open sheet stays open.\n *\n * @throws TabulaError `invalid_argument` for a sheet the workbook does not have\n */\nexport function moveSheet(workbook: Workbook, sheetId: string, to: number): Workbook {\n\tconst sheet = found(workbook, sheetId)\n\tconst sheets = workbook.sheets.filter(each => each.sheetId !== sheetId)\n\n\tsheets.splice(Math.max(0, Math.min(Math.trunc(to), sheets.length)), 0, sheet)\n\n\treturn freeze({ ...workbook, sheets })\n}\n\n/**\n * The workbook with another sheet open.\n *\n * @throws TabulaError `invalid_argument` for a sheet the workbook does not have\n */\nexport function openSheet(workbook: Workbook, sheetId: string): Workbook {\n\tfound(workbook, sheetId)\n\n\treturn freeze({ ...workbook, active: sheetId })\n}\n\ntype Plain = Record<string, unknown>\n\nfunction sheetOf(sheetId: string, sheet: NewSheet): WorkbookSheet {\n\tif (sheet.name.trim() === \"\") {\n\t\tthrow new TabulaError(\"invalid_argument\", \"A sheet's name must not be empty.\")\n\t}\n\n\treturn {\n\t\tsheetId,\n\t\tname: sheet.name.trim(),\n\t\ttemplate: sheet.template ?? null,\n\t\tdraft: sheet.draft ?? null,\n\t\tmeta: sheet.meta ?? {}\n\t}\n}\n\nfunction found(workbook: Workbook, sheetId: string): WorkbookSheet {\n\tconst sheet = workbook.sheets.find(each => each.sheetId === sheetId)\n\n\tif (!sheet) {\n\t\tthrow new TabulaError(\"invalid_argument\", `The workbook has no sheet \"${sheetId}\".`)\n\t}\n\n\treturn sheet\n}\n\nfunction readMeta(value: unknown, path: string, problem: (path: string, message: string) => void): SheetMeta {\n\tif (value === undefined || value === null) {\n\t\treturn {}\n\t}\n\n\tif (typeof value !== \"object\" || Array.isArray(value)) {\n\t\tproblem(path, \"must be an object.\")\n\n\t\treturn {}\n\t}\n\n\tconst meta: Record<string, string | number | boolean | null> = {}\n\n\tfor (const [key, item] of Object.entries(value as Plain)) {\n\t\tif (item === null || [\"string\", \"number\", \"boolean\"].includes(typeof item)) {\n\t\t\tmeta[key] = item as string | number | boolean | null\n\t\t} else {\n\t\t\tproblem(`${path}.${key}`, \"must be text, a number, true, false or null.\")\n\t\t}\n\t}\n\n\treturn meta\n}\n\nfunction freeze(workbook: Workbook): Workbook {\n\treturn Object.freeze({\n\t\t...workbook,\n\t\tsheets: Object.freeze(\n\t\t\tworkbook.sheets.map(sheet => Object.freeze({ ...sheet, meta: Object.freeze({ ...sheet.meta }) }))\n\t\t)\n\t})\n}\n","import type { AdapterContext } from \"./contract.js\"\nimport { createDraft, type Draft, type DraftView } from \"./draft.js\"\nimport { TabulaError } from \"./errors.js\"\nimport { sequence } from \"./ids.js\"\nimport { Listeners } from \"./listeners.js\"\nimport type { CellMarks } from \"./marks.js\"\nimport type { RowStore } from \"./rows.js\"\nimport type { ModuleSchema } from \"./schema.js\"\nimport type { SheetSession } from \"./session.js\"\n\nexport interface DraftSaverOptions {\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\t/** Its results go into each draft, and a change to them is a change to save. */\n\treadonly session?: SheetSession\n\t/**\n\t * Keeps a draft wherever the application keeps them: its backend, the browser's storage. A draft\n\t * carries its own id, so the same draft saved again replaces the last one rather than adding one.\n\t */\n\treadonly save: (draft: Draft, context: AdapterContext) => Promise<void>\n\t/** The id of the draft being continued. Left out, a new one is made. */\n\treadonly id?: string\n\treadonly name?: string | null\n\t/** Read at each save: the user's view of the sheet, such as the grid's column widths. */\n\treadonly view?: () => DraftView\n\t/** The marks on the cells: kept with each draft, and a change to them is a change to save. */\n\treadonly marks?: CellMarks\n\t/** Milliseconds after the last change before it saves on its own; 0 saves only when asked. 2,000 by default. */\n\treadonly delay?: number\n\treadonly createId?: () => string\n\treadonly now?: () => Date\n}\n\n/** `saved`: nothing changed since the last save. `failed`: the last save did not go through. */\nexport type SaverStatus = \"saved\" | \"unsaved\" | \"saving\" | \"failed\"\n\nexport interface SaverState {\n\treadonly status: SaverStatus\n\t/** When the last save went through, as ISO 8601 text; null before the first. */\n\treadonly savedAt: string | null\n\t/** What went wrong with the last save, when it did not go through. */\n\treadonly failure: { readonly message: string; readonly error: unknown } | null\n}\n\nconst DEFAULT_DELAY = 2000\n\n/**\n * Saves a sheet as a draft: on its own, a moment after the user stops changing it, and whenever\n * asked. Only one save is under way at a time; changes made during one are saved by the next.\n *\n * A save that fails leaves the sheet as it is and the state `failed`; the next change, or a call to\n * `save()`, tries again.\n */\nexport class DraftSaver {\n\t/** The draft's id: the same for every save. */\n\treadonly id: string\n\n\treadonly #options: DraftSaverOptions\n\treadonly #delay: number\n\treadonly #listeners = new Listeners<DraftSaver>()\n\treadonly #stops: (() => void)[] = []\n\t#name: string | null\n\t#state: SaverState = Object.freeze({ status: \"saved\", savedAt: null, failure: null })\n\t#version = 0\n\t/** Counts changes; the count a save started at is what it saved. */\n\t#changes = 0\n\t#saved = 0\n\t#timer: ReturnType<typeof setTimeout> | null = null\n\t#running: Promise<boolean> | null = null\n\t#disposed = false\n\n\tconstructor(options: DraftSaverOptions) {\n\t\tconst delay = options.delay ?? DEFAULT_DELAY\n\n\t\tif (!Number.isFinite(delay) || delay < 0) {\n\t\t\tthrow new TabulaError(\"invalid_argument\", `delay must be 0 or more milliseconds; got ${delay}.`)\n\t\t}\n\n\t\tthis.#options = options\n\t\tthis.#delay = delay\n\t\tthis.#name = options.name ?? null\n\t\tthis.id = options.id ?? (options.createId ?? sequence(\"d\"))()\n\t\tthis.#stops.push(options.store.subscribe(() => this.changed()))\n\n\t\tif (options.marks) {\n\t\t\tthis.#stops.push(options.marks.subscribe(() => this.changed()))\n\t\t}\n\n\t\tif (options.session) {\n\t\t\tthis.#stops.push(options.session.results.subscribe(() => this.changed()))\n\t\t\tthis.#stops.push(options.session.subscribe(() => this.#onSession()))\n\t\t}\n\t}\n\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\tget state(): SaverState {\n\t\treturn this.#state\n\t}\n\n\tget name(): string | null {\n\t\treturn this.#name\n\t}\n\n\t/** Whether something changed since the last save that went through. */\n\tget dirty(): boolean {\n\t\treturn this.#changes !== this.#saved\n\t}\n\n\tsubscribe(listener: (saver: DraftSaver) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Something the draft holds changed outside the store, such as a column width: save it in a moment. */\n\tchanged(): void {\n\t\tif (this.#disposed) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#changes++\n\n\t\tif (this.#state.status !== \"saving\") {\n\t\t\tthis.#setState({ status: \"unsaved\" })\n\t\t}\n\n\t\tthis.#schedule()\n\t}\n\n\t/** Names the draft, and saves the name with it. */\n\trename(name: string | null): void {\n\t\tthis.#name = name\n\t\tthis.changed()\n\t}\n\n\t/**\n\t * Saves now, after any save under way. Resolves true once everything changed until now is saved,\n\t * false when a save failed.\n\t */\n\tasync save(): Promise<boolean> {\n\t\tthis.#clearTimer()\n\n\t\twhile (this.#running) {\n\t\t\tawait this.#running\n\t\t}\n\n\t\tif (this.#disposed) {\n\t\t\treturn false\n\t\t}\n\n\t\tif (!this.dirty && this.#state.status === \"saved\" && this.#state.savedAt !== null) {\n\t\t\treturn true\n\t\t}\n\n\t\tconst run = this.#run()\n\n\t\tthis.#running = run\n\n\t\ttry {\n\t\t\treturn await run\n\t\t} finally {\n\t\t\tthis.#running = null\n\t\t}\n\t}\n\n\t/** Saves what is not saved yet, such as before the page goes away. Resolves at once when nothing is. */\n\tasync flush(): Promise<boolean> {\n\t\treturn this.dirty || this.#running ? this.save() : true\n\t}\n\n\t/** Stops saving on its own. A save under way still finishes. */\n\tdispose(): void {\n\t\tthis.#disposed = true\n\t\tthis.#clearTimer()\n\n\t\tfor (const stop of this.#stops) {\n\t\t\tstop()\n\t\t}\n\t}\n\n\tasync #run(): Promise<boolean> {\n\t\tconst options = this.#options\n\t\tconst at = this.#changes\n\t\tconst draft = createDraft({\n\t\t\tid: this.id,\n\t\t\tname: this.#name,\n\t\t\tschema: options.schema,\n\t\t\tstore: options.store,\n\t\t\tsession: options.session ?? null,\n\t\t\t...(options.view ? { view: options.view() } : {}),\n\t\t\t...(options.marks ? { marks: options.marks } : {}),\n\t\t\t...(options.now ? { now: options.now } : {})\n\t\t})\n\n\t\tthis.#setState({ status: \"saving\", failure: null })\n\n\t\ttry {\n\t\t\tawait options.save(draft, {\n\t\t\t\tsignal: new AbortController().signal,\n\t\t\t\trequestId: `${this.id}@${draft.revision}`\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthis.#setState({\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tfailure: Object.freeze({ message: error instanceof Error ? error.message : String(error), error })\n\t\t\t})\n\n\t\t\treturn false\n\t\t}\n\n\t\tthis.#saved = at\n\t\tthis.#setState({ status: this.dirty ? \"unsaved\" : \"saved\", savedAt: draft.savedAt, failure: null })\n\n\t\t// Changes made while it was saving are saved by the next one.\n\t\tif (this.dirty) {\n\t\t\tthis.#schedule()\n\t\t}\n\n\t\treturn true\n\t}\n\n\t/**\n\t * A run starting, going unknown or ending changes what a draft holds of the session: a page closed\n\t * mid-run must open again knowing the run is out there. A check changes nothing a draft keeps.\n\t */\n\t#onSession(): void {\n\t\tif (this.#options.session?.state.phase !== \"checking\") {\n\t\t\tthis.changed()\n\t\t}\n\t}\n\n\t#schedule(): void {\n\t\tif (this.#delay === 0 || this.#disposed) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#clearTimer()\n\t\tthis.#timer = setTimeout(() => {\n\t\t\tthis.#timer = null\n\t\t\tvoid this.save()\n\t\t}, this.#delay)\n\t}\n\n\t#clearTimer(): void {\n\t\tif (this.#timer !== null) {\n\t\t\tclearTimeout(this.#timer)\n\t\t\tthis.#timer = null\n\t\t}\n\t}\n\n\t#setState(patch: Partial<SaverState>): void {\n\t\tthis.#state = Object.freeze({ ...this.#state, ...patch })\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n}\n","import {\n\treadCheckResponse,\n\treadProcessResponse,\n\ttype CheckResponse,\n\ttype IssueInput,\n\ttype ProcessProgress,\n\ttype ProcessRequest,\n\ttype ProcessResponse,\n\ttype ProcessStatus,\n\ttype RowAction,\n\ttype RowOutcome,\n\ttype RowPlanInput,\n\ttype SheetAdapters,\n\ttype SheetRequest,\n\ttype StatusQuery\n} from \"./contract.js\"\nimport { neverAborted, raced, wait } from \"./async.js\"\nimport { TabulaError } from \"./errors.js\"\nimport { isFormulaError } from \"./formula/error.js\"\nimport type { UndoHistory } from \"./history.js\"\nimport { randomPart, sequence } from \"./ids.js\"\nimport { Listeners } from \"./listeners.js\"\nimport type { RowId, RowStore, StoreChange } from \"./rows.js\"\nimport type { ModuleSchema } from \"./schema.js\"\nimport {\n\tisBlankRow,\n\tSheetValidator,\n\ttype Issue,\n\ttype IssueScope,\n\ttype IssueSet,\n\ttype IssueSummary\n} from \"./validation.js\"\nimport type { CellValue } from \"./value.js\"\nimport { canonicalValue, isLookupValue } from \"./values/read.js\"\nimport type { ValueSettings } from \"./values/settings.js\"\n\nexport interface SheetSessionOptions {\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\treadonly adapters: SheetAdapters\n\t/** The local checks. Left out, the session makes its own, with `settings`, and disposes of it. */\n\treadonly validator?: SheetValidator\n\treadonly settings?: ValueSettings\n\t/**\n\t * Cleared when rows are sent to be processed. Once a backend has them, taking an edit back in the\n\t * sheet alone would show what was never done.\n\t */\n\treadonly history?: UndoHistory\n\t/** The sheet's name in requests and issues. The schema's module by default. */\n\treadonly sheetId?: string\n\treadonly createRequestId?: () => string\n\t/** Milliseconds between status questions while a run answers `pending`. 1,000 by default. */\n\treadonly pollInterval?: number\n\t/** What a draft kept of an earlier session over the same rows, to go on from where it stood. */\n\treadonly restore?: PersistedSession\n}\n\n/**\n * What a session hands to a draft: enough that opening the draft again neither unlocks a processed\n * row nor forgets a run that never answered.\n */\nexport interface PersistedSession {\n\t/** Each row's result, for the rows still in the sheet. */\n\treadonly results: readonly RowResult[]\n\t/** A run with no final answer, to be sent again under its key, or asked about. */\n\treadonly pending: PendingRun | null\n}\n\nexport interface PendingRun {\n\treadonly request: ProcessRequest\n\treadonly operationId: string | null\n}\n\n/**\n * `unknown`: rows were sent and no answer came back, so whether they were processed is not known.\n * The session sends the same request again, under the same key, or asks how it went; it never\n * sends those rows as a new run, which could do them twice.\n */\nexport type SessionPhase = \"idle\" | \"checking\" | \"processing\" | \"unknown\"\n\nexport interface SessionFailure {\n\treadonly stage: \"preflight\" | \"process\" | \"status\" | \"cancel\"\n\t/**\n\t * `request_failed`: the adapter threw, such as on a network error. `invalid_response`: the answer\n\t * was not in the contract's shape. `unavailable`: there is no adapter to go on with.\n\t */\n\treadonly code: \"request_failed\" | \"invalid_response\" | \"unavailable\"\n\treadonly message: string\n\treadonly error: unknown\n}\n\nexport interface CheckRecord {\n\treadonly requestId: string\n\treadonly revision: number\n\treadonly outcome: \"valid\" | \"invalid\" | \"failed\" | \"cancelled\"\n}\n\n/** `sending`: no answer yet. `unknown`: none came, and none can be counted on. */\nexport type RunStatus = ProcessStatus | \"sending\" | \"unknown\"\n\nexport interface RunRecord {\n\treadonly requestId: string\n\treadonly idempotencyKey: string\n\treadonly operationId: string | null\n\treadonly revision: number\n\t/** How many rows were sent. */\n\treadonly rows: number\n\treadonly status: RunStatus\n\treadonly progress: ProcessProgress | null\n}\n\nexport interface SessionState {\n\treadonly phase: SessionPhase\n\treadonly check: CheckRecord | null\n\treadonly run: RunRecord | null\n\t/** What went wrong with the last request, apart from the issues of the data. */\n\treadonly failure: SessionFailure | null\n}\n\nexport interface CheckOutcome {\n\treadonly status: \"valid\" | \"invalid\" | \"failed\" | \"cancelled\" | \"busy\" | \"unavailable\"\n\t/** How many issues the backend reported. */\n\treadonly issues: number\n}\n\nexport interface ProcessOutcome {\n\t/**\n\t * A run's final status, or why there was none: `blocked` by issues, `nothing` to send, `busy`\n\t * with another request, `unavailable` for want of an adapter, or `unknown` for want of an answer.\n\t */\n\treadonly status: ProcessStatus | \"blocked\" | \"nothing\" | \"busy\" | \"unavailable\" | \"unknown\"\n\treadonly succeeded: number\n\treadonly failed: number\n\treadonly skipped: number\n\t/** Rows held back by an issue that blocks, when the status is `blocked`. */\n\treadonly blocked: number\n}\n\nexport interface RowResult {\n\treadonly rowId: RowId\n\treadonly outcome: RowOutcome\n\treadonly data: Readonly<Record<string, CellValue>>\n\t/** The run it came from. */\n\treadonly requestId: string\n}\n\n/** Each row's result from the backend, for a view to show and to lock rows by. */\nexport interface RowResults {\n\treadonly version: number\n\tresultOf(rowId: RowId): RowResult | null\n\t/** A processed row cannot be changed, nor can one on its way to the backend. */\n\tisLocked(rowId: RowId): boolean\n\tsubscribe(listener: () => void): () => void\n}\n\n/** A field a run would write: what the backend holds now, and what the sheet holds. */\nexport interface PlannedChange {\n\treadonly field: string\n\t/** As the backend sent it; null for a new record. */\n\treadonly before: CellValue\n\t/** As the sheet holds it, to be shown the way its cell shows it. */\n\treadonly after: CellValue\n}\n\n/** `unknown`: the check said nothing of the row, or the row changed after it. */\nexport type PlannedAction = RowAction | \"unknown\"\n\nexport interface RowPlan {\n\treadonly rowId: RowId\n\treadonly action: PlannedAction\n\t/**\n\t * For an update, the fields that would change, as far as the backend said; for a new record,\n\t * every field it would be given. Empty otherwise.\n\t */\n\treadonly changes: readonly PlannedChange[]\n}\n\n/** What a run would do, row by row, by the last check's answer: for a preview before it is sent. */\nexport interface ProcessPlan {\n\t/** The check the plan comes from; null when there is none to go by. */\n\treadonly check: CheckRecord | null\n\t/**\n\t * Whether that check saw every row a run would send just as the run would send it. When it did\n\t * not, check again before showing the plan as what will be done.\n\t */\n\treadonly current: boolean\n\t/** Every row a run would send, in sheet order. */\n\treadonly rows: readonly RowPlan[]\n\treadonly counts: Readonly<Record<PlannedAction, number>>\n}\n\n/** A check's answer, kept to build a plan from: what each row was sent as, and what it would become. */\ninterface CheckedPlan {\n\treadonly record: CheckRecord\n\treadonly payloads: ReadonlyMap<RowId, string>\n\treadonly plans: ReadonlyMap<RowId, RowPlanInput>\n}\n\nconst DEFAULT_POLL_INTERVAL = 1000\n\n/**\n * A sheet's way to its backend: the pre-flight check and the process run, through the adapters it\n * is given, with the backend's issues merged into the local ones.\n *\n * Every answer is about a revision of the sheet. An answer about an older one still lands, but an\n * issue on a cell changed since is marked stale rather than shown as standing; so is an issue whose\n * cell is changed after it arrived. Nothing a backend said is taken as fixed until it says so.\n *\n * Rows that went through are locked and are not sent again. A run with no answer leaves the session\n * `unknown`, its rows locked, until the same request is sent again or the backend says how it went.\n */\nexport class SheetSession {\n\treadonly schema: ModuleSchema\n\treadonly store: RowStore\n\treadonly sheetId: string\n\treadonly validator: SheetValidator\n\t/** The local issues and the backend's, for the grid and the issue panel. */\n\treadonly issues: IssueSet\n\treadonly results: RowResults\n\n\treadonly #adapters: SheetAdapters\n\treadonly #history: UndoHistory | null\n\treadonly #ownValidator: boolean\n\treadonly #requestId: () => string\n\treadonly #pollInterval: number\n\treadonly #merged: MergedIssues\n\treadonly #results: Results\n\treadonly #listeners = new Listeners<SheetSession>()\n\treadonly #stop: () => void\n\t/** The revision each cell and each row last changed at, to tell what an answer could not have seen. */\n\treadonly #cellChanged = new Map<RowId, Map<string, number>>()\n\treadonly #rowChanged = new Map<RowId, number>()\n\t#state: SessionState = Object.freeze({ phase: \"idle\", check: null, run: null, failure: null })\n\t#version = 0\n\t#checking: { readonly controller: AbortController; readonly request: SheetRequest } | null = null\n\t#running: AbortController | null = null\n\t/** The request of a run without a final answer: what is sent again, under the same key. */\n\t#pending: ProcessRequest | null = null\n\t/** The last check that was answered, until a run changes what the backend holds. */\n\t#checked: CheckedPlan | null = null\n\t#disposed = false\n\n\tconstructor(options: SheetSessionOptions) {\n\t\tconst pollInterval = options.pollInterval ?? DEFAULT_POLL_INTERVAL\n\n\t\tif (!Number.isFinite(pollInterval) || pollInterval < 0) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_argument\",\n\t\t\t\t`pollInterval must be 0 or more milliseconds; got ${pollInterval}.`\n\t\t\t)\n\t\t}\n\n\t\tthis.schema = options.schema\n\t\tthis.store = options.store\n\t\tthis.sheetId = options.sheetId ?? options.schema.module\n\t\tthis.#ownValidator = options.validator === undefined\n\t\tthis.validator = options.validator ?? new SheetValidator(options.schema, options.store, options.settings)\n\t\tthis.#adapters = options.adapters\n\t\tthis.#history = options.history ?? null\n\t\tthis.#requestId = options.createRequestId ?? sequence(\"req\")\n\t\tthis.#pollInterval = pollInterval\n\t\tthis.#merged = new MergedIssues(this.validator, this.store, this.schema)\n\t\tthis.#results = new Results()\n\t\tthis.issues = this.#merged\n\t\tthis.results = this.#results\n\t\tthis.#stop = this.store.subscribe(change => this.#onChange(change))\n\n\t\tif (options.restore) {\n\t\t\tthis.#restore(options.restore)\n\t\t}\n\t}\n\n\t/**\n\t * What a draft keeps of this session: each row's result, and a run with no final answer. A run\n\t * still going is kept as one with no answer: opened again, it is sent again under its key, or\n\t * asked about, and never run twice.\n\t */\n\tpersisted(): PersistedSession {\n\t\tconst results: RowResult[] = []\n\n\t\tfor (const rowId of this.store.rowIds()) {\n\t\t\tconst result = this.#results.resultOf(rowId)\n\n\t\t\tif (result) {\n\t\t\t\tresults.push(result)\n\t\t\t}\n\t\t}\n\n\t\tconst pending = this.#pending\n\t\t\t? Object.freeze({ request: this.#pending, operationId: this.#state.run?.operationId ?? null })\n\t\t\t: null\n\n\t\treturn Object.freeze({ results: Object.freeze(results), pending })\n\t}\n\n\t/** Moves on every change of `state`. */\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\tget state(): SessionState {\n\t\treturn this.#state\n\t}\n\n\t/** Called after each change of `state`. Returns the way to stop. */\n\tsubscribe(listener: (session: SheetSession) => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** The rows a check or a run would send, in sheet order: every row with something in it, bar those processed. */\n\tunfinishedRows(): RowId[] {\n\t\treturn this.store\n\t\t\t.rowIds()\n\t\t\t.filter(rowId => this.#results.resultOf(rowId)?.outcome !== \"succeeded\" && !this.#isEmpty(rowId))\n\t}\n\n\t/**\n\t * Asks the backend to check the sheet. A check started while another runs replaces it, and the\n\t * answer to the older one is passed over.\n\t */\n\tasync check(): Promise<CheckOutcome> {\n\t\tconst ask = this.#adapters.preflight\n\n\t\tif (!ask) {\n\t\t\treturn { status: \"unavailable\", issues: 0 }\n\t\t}\n\n\t\tif (this.#state.phase === \"processing\" || this.#state.phase === \"unknown\") {\n\t\t\treturn { status: \"busy\", issues: 0 }\n\t\t}\n\n\t\tthis.#checking?.controller.abort()\n\n\t\tconst controller = new AbortController()\n\t\tconst request = this.#request(this.unfinishedRows())\n\t\tconst current = { controller, request }\n\n\t\tthis.#checking = current\n\t\tthis.#setState({ phase: \"checking\", failure: null })\n\n\t\tlet response: CheckResponse\n\n\t\ttry {\n\t\t\tconst answer = await raced(\n\t\t\t\task(request, { signal: controller.signal, requestId: request.requestId }),\n\t\t\t\tcontroller.signal\n\t\t\t)\n\n\t\t\tresponse = this.#answered(request.requestId, readCheckResponse(answer))\n\t\t} catch (error) {\n\t\t\tif (this.#checking !== current) {\n\t\t\t\treturn { status: \"cancelled\", issues: 0 }\n\t\t\t}\n\n\t\t\tthis.#checking = null\n\t\t\tthis.#setState({\n\t\t\t\tphase: \"idle\",\n\t\t\t\tcheck: record(request, \"failed\"),\n\t\t\t\tfailure: failure(\"preflight\", error)\n\t\t\t})\n\n\t\t\treturn { status: \"failed\", issues: 0 }\n\t\t}\n\n\t\tif (this.#checking !== current) {\n\t\t\treturn { status: \"cancelled\", issues: 0 }\n\t\t}\n\n\t\tthis.#checking = null\n\n\t\tconst issues = (response.issues ?? [])\n\t\t\t.map((input, index) => this.#toIssue(input, \"preflight\", String(index), request.revision, null))\n\t\t\t.filter((issue): issue is Issue => issue !== null)\n\n\t\tthis.#merged.replace(issue => issue.source === \"preflight\", issues)\n\n\t\tconst outcome = issues.some(issue => issue.blocking && !issue.stale) ? \"invalid\" : \"valid\"\n\t\tconst checkRecord = record(request, outcome)\n\t\tconst plans = new Map<RowId, RowPlanInput>()\n\t\tconst sent = new Set(request.rows.map(row => row.rowId))\n\n\t\tfor (const plan of response.plan ?? []) {\n\t\t\tif (sent.has(plan.rowId) && !plans.has(plan.rowId)) {\n\t\t\t\tplans.set(plan.rowId, plan)\n\t\t\t}\n\t\t}\n\n\t\tthis.#checked = {\n\t\t\trecord: checkRecord,\n\t\t\tpayloads: new Map(request.rows.map(row => [row.rowId, JSON.stringify(row.values)])),\n\t\t\tplans\n\t\t}\n\t\tthis.#setState({ phase: \"idle\", check: checkRecord })\n\n\t\treturn { status: outcome, issues: issues.length }\n\t}\n\n\t/**\n\t * Sends the unfinished rows to be processed, or, while the last run is `unknown`, the same\n\t * request again under the same key. Rows with an error standing, local or the backend's, hold\n\t * back the whole run: the backend checks again anyway, and a run is not the place to find out.\n\t */\n\tasync process(): Promise<ProcessOutcome> {\n\t\tconst send = this.#adapters.process\n\n\t\tif (!send) {\n\t\t\treturn outcome(\"unavailable\")\n\t\t}\n\n\t\tif (this.#state.phase === \"checking\" || this.#state.phase === \"processing\") {\n\t\t\treturn outcome(\"busy\")\n\t\t}\n\n\t\tlet request = this.#state.phase === \"unknown\" ? this.#pending : null\n\n\t\tif (request === null) {\n\t\t\tconst rowIds = this.unfinishedRows()\n\n\t\t\tif (rowIds.length === 0) {\n\t\t\t\treturn outcome(\"nothing\")\n\t\t\t}\n\n\t\t\tconst blocked = this.#blockedRows(rowIds)\n\n\t\t\tif (blocked > 0) {\n\t\t\t\treturn { ...outcome(\"blocked\"), blocked }\n\t\t\t}\n\n\t\t\trequest = Object.freeze({\n\t\t\t\t...this.#request(rowIds),\n\t\t\t\tidempotencyKey: `${this.sheetId}:${this.store.revision}:${randomPart()}`\n\t\t\t})\n\t\t\tthis.#history?.clear()\n\t\t}\n\n\t\tconst sending = request\n\t\tconst controller = new AbortController()\n\n\t\tthis.#pending = sending\n\t\tthis.#running = controller\n\t\tthis.#results.setInFlight(new Set(sending.rows.map(row => row.rowId)))\n\t\tthis.#setState({\n\t\t\tphase: \"processing\",\n\t\t\tfailure: null,\n\t\t\trun: {\n\t\t\t\trequestId: sending.requestId,\n\t\t\t\tidempotencyKey: sending.idempotencyKey,\n\t\t\t\toperationId: this.#state.run?.requestId === sending.requestId ? this.#state.run.operationId : null,\n\t\t\t\trevision: sending.revision,\n\t\t\t\trows: sending.rows.length,\n\t\t\t\tstatus: \"sending\",\n\t\t\t\tprogress: null\n\t\t\t}\n\t\t})\n\n\t\tlet response: ProcessResponse\n\n\t\ttry {\n\t\t\tconst answer = await raced(\n\t\t\t\tsend(sending, { signal: controller.signal, requestId: sending.requestId }),\n\t\t\t\tcontroller.signal\n\t\t\t)\n\n\t\t\tresponse = this.#answered(sending.requestId, readProcessResponse(answer))\n\t\t} catch (error) {\n\t\t\treturn this.#lose(\"process\", error)\n\t\t}\n\n\t\treturn this.#follow(sending, response, controller)\n\t}\n\n\t/**\n\t * What a run would do now, by the last check's answer: each row it would send, in sheet order,\n\t * with what the backend said would become of it. A row the backend said nothing of, or one that\n\t * changed or was added after the check, is `unknown`. A finished run leaves nothing to go by,\n\t * since it changed what the backend holds.\n\t */\n\tplan(): ProcessPlan {\n\t\tconst checked = this.#checked\n\t\tconst counts: Record<PlannedAction, number> = { create: 0, update: 0, unchanged: 0, unknown: 0 }\n\t\tlet current = checked !== null\n\t\tconst rows = this.unfinishedRows().map(rowId => {\n\t\t\tconst same = checked?.payloads.get(rowId) === JSON.stringify(this.#payload(rowId))\n\t\t\tconst plan = this.#rowPlan(rowId, same ? checked?.plans.get(rowId) : undefined)\n\n\t\t\tcurrent &&= same\n\t\t\tcounts[plan.action]++\n\n\t\t\treturn plan\n\t\t})\n\n\t\treturn Object.freeze({\n\t\t\tcheck: checked?.record ?? null,\n\t\t\tcurrent,\n\t\t\trows: Object.freeze(rows),\n\t\t\tcounts: Object.freeze(counts)\n\t\t})\n\t}\n\n\t/** How many rows an error, the sheet's own or the backend's, holds back from a run now. */\n\tblocked(): number {\n\t\treturn this.#blockedRows(this.unfinishedRows())\n\t}\n\n\t/** Asks the backend how a run with no answer went, while the session is `unknown`. */\n\tasync refresh(): Promise<ProcessOutcome> {\n\t\tconst ask = this.#adapters.processStatus\n\t\tconst request = this.#pending\n\n\t\tif (this.#state.phase !== \"unknown\" || request === null) {\n\t\t\treturn outcome(this.#state.phase === \"idle\" ? \"nothing\" : \"busy\")\n\t\t}\n\n\t\tif (!ask) {\n\t\t\treturn outcome(\"unavailable\")\n\t\t}\n\n\t\tconst controller = new AbortController()\n\n\t\tthis.#running = controller\n\t\tthis.#setState({ phase: \"processing\", failure: null })\n\n\t\tlet response: ProcessResponse\n\n\t\ttry {\n\t\t\tconst answer = await raced(\n\t\t\t\task(this.#query(), { signal: controller.signal, requestId: request.requestId }),\n\t\t\t\tcontroller.signal\n\t\t\t)\n\n\t\t\tresponse = this.#answered(request.requestId, readProcessResponse(answer))\n\t\t} catch (error) {\n\t\t\treturn this.#lose(\"status\", error)\n\t\t}\n\n\t\treturn this.#follow(request, response, controller)\n\t}\n\n\t/**\n\t * Stops a check, or asks the backend to stop a run. A run the backend cannot be asked about,\n\t * for want of an operation id or a `cancelProcess` adapter, is no longer waited for, and its\n\t * outcome is then unknown. Rows done before a stop stay done: a cancel takes nothing back.\n\t */\n\tasync cancel(): Promise<void> {\n\t\tconst checking = this.#checking\n\n\t\tif (checking) {\n\t\t\tthis.#checking = null\n\t\t\tchecking.controller.abort()\n\t\t\tthis.#setState({ phase: \"idle\", check: record(checking.request, \"cancelled\") })\n\n\t\t\treturn\n\t\t}\n\n\t\tconst run = this.#state.run\n\t\tconst stop = this.#adapters.cancelProcess\n\n\t\tif (this.#state.phase !== \"processing\" || !run) {\n\t\t\treturn\n\t\t}\n\n\t\tif (run.operationId !== null && stop) {\n\t\t\ttry {\n\t\t\t\tawait stop(this.#query(), { signal: neverAborted(), requestId: run.requestId })\n\t\t\t} catch (error) {\n\t\t\t\tthis.#setState({ failure: failure(\"cancel\", error) })\n\t\t\t}\n\n\t\t\t// The run's own answer says what was stopped and what was done first.\n\t\t\treturn\n\t\t}\n\n\t\tthis.#running?.abort()\n\t}\n\n\t/**\n\t * Takes the rows that went through out of the sheet, as one change, so work goes on with the rest.\n\t * Their results stay: an undo brings them back as they were, processed and locked.\n\t *\n\t * @returns how many rows were taken out\n\t */\n\tremoveSucceeded(): number {\n\t\tconst done = this.store.rowIds().filter(rowId => this.#results.resultOf(rowId)?.outcome === \"succeeded\")\n\n\t\tif (done.length > 0) {\n\t\t\tthis.store.transact(() => this.store.removeRows(done), { origin: \"processed\" })\n\t\t}\n\n\t\treturn done.length\n\t}\n\n\t/** Stops every request and stops following the store. */\n\tdispose(): void {\n\t\tthis.#disposed = true\n\t\tthis.#checking?.controller.abort()\n\t\tthis.#checking = null\n\t\tthis.#running?.abort()\n\t\tthis.#running = null\n\t\tthis.#stop()\n\t\tthis.#merged.dispose()\n\n\t\tif (this.#ownValidator) {\n\t\t\tthis.validator.dispose()\n\t\t}\n\t}\n\n\t// ---------------------------------------------------------------- runs\n\n\tasync #follow(\n\t\trequest: ProcessRequest,\n\t\tfirst: ProcessResponse,\n\t\tcontroller: AbortController\n\t): Promise<ProcessOutcome> {\n\t\tlet response = first\n\n\t\twhile (response.status === \"pending\") {\n\t\t\tthis.#record(request, response, false)\n\t\t\tthis.#setRun({\n\t\t\t\toperationId: response.operationId ?? this.#state.run?.operationId ?? null,\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tprogress: response.progress ?? this.#state.run?.progress ?? null\n\t\t\t})\n\n\t\t\tconst ask = this.#adapters.processStatus\n\n\t\t\tif (!ask) {\n\t\t\t\treturn this.#lose(\n\t\t\t\t\t\"status\",\n\t\t\t\t\tnew TabulaError(\n\t\t\t\t\t\t\"invalid_argument\",\n\t\t\t\t\t\t\"The run is still going, and there is no processStatus adapter to follow it.\"\n\t\t\t\t\t),\n\t\t\t\t\t\"unavailable\"\n\t\t\t\t)\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tawait wait(this.#pollInterval, controller.signal)\n\n\t\t\t\tconst answer = await raced(\n\t\t\t\t\task(this.#query(), { signal: controller.signal, requestId: request.requestId }),\n\t\t\t\t\tcontroller.signal\n\t\t\t\t)\n\n\t\t\t\tresponse = this.#answered(request.requestId, readProcessResponse(answer))\n\t\t\t} catch (error) {\n\t\t\t\treturn this.#lose(\"status\", error)\n\t\t\t}\n\t\t}\n\n\t\tif (this.#disposed) {\n\t\t\treturn outcome(\"unknown\")\n\t\t}\n\n\t\tthis.#record(request, response, true)\n\t\tthis.#pending = null\n\t\tthis.#checked = null\n\t\tthis.#running = null\n\t\tthis.#results.setInFlight(new Set())\n\t\tthis.#setState({\n\t\t\tphase: \"idle\",\n\t\t\tfailure: null,\n\t\t\trun: {\n\t\t\t\t...(this.#state.run as RunRecord),\n\t\t\t\toperationId: response.operationId ?? this.#state.run?.operationId ?? null,\n\t\t\t\tstatus: response.status,\n\t\t\t\tprogress: response.progress ?? this.#state.run?.progress ?? null\n\t\t\t}\n\t\t})\n\n\t\tconst counts = { succeeded: 0, failed: 0, skipped: 0 }\n\n\t\tfor (const row of request.rows) {\n\t\t\tconst result = this.#results.resultOf(row.rowId)\n\n\t\t\tif (result?.requestId === request.requestId) {\n\t\t\t\tcounts[result.outcome]++\n\t\t\t}\n\t\t}\n\n\t\treturn { status: response.status, ...counts, blocked: 0 }\n\t}\n\n\t/** No answer to go by: the rows stay locked and the request stays ready to be sent again. */\n\t#lose(stage: SessionFailure[\"stage\"], error: unknown, code?: SessionFailure[\"code\"]): ProcessOutcome {\n\t\tif (!this.#disposed) {\n\t\t\tconst run = this.#state.run\n\n\t\t\tthis.#running = null\n\t\t\tthis.#setState({\n\t\t\t\tphase: \"unknown\",\n\t\t\t\tfailure: failure(stage, error, code),\n\t\t\t\trun: run ? Object.freeze({ ...run, status: \"unknown\" }) : null\n\t\t\t})\n\t\t}\n\n\t\treturn outcome(\"unknown\")\n\t}\n\n\t/** Keeps what an answer says about each row it was sent. */\n\t#record(request: ProcessRequest, response: ProcessResponse, final: boolean): void {\n\t\tconst sent = new Set(request.rows.map(row => row.rowId))\n\t\tconst answered = new Set<RowId>()\n\t\tconst results: RowResult[] = []\n\t\tconst issues: Issue[] = []\n\n\t\tresponse.rows?.forEach((row, index) => {\n\t\t\tif (!sent.has(row.rowId) || answered.has(row.rowId)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tanswered.add(row.rowId)\n\t\t\tresults.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\trowId: row.rowId,\n\t\t\t\t\toutcome: row.result,\n\t\t\t\t\tdata: Object.freeze({ ...row.data }),\n\t\t\t\t\trequestId: request.requestId\n\t\t\t\t})\n\t\t\t)\n\t\t\trow.issues?.forEach((input, at) => {\n\t\t\t\tconst issue = this.#toIssue(input, \"process\", `${index}.${at}`, request.revision, row.rowId)\n\n\t\t\t\tif (issue) {\n\t\t\t\t\tissues.push(issue)\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\n\t\tif (final) {\n\t\t\tfor (const rowId of sent) {\n\t\t\t\t// A row an earlier `pending` answer settled keeps that result.\n\t\t\t\tconst settled = this.#results.resultOf(rowId)?.requestId === request.requestId\n\n\t\t\t\tif (!answered.has(rowId) && !settled) {\n\t\t\t\t\tconst kind = response.status === \"succeeded\" ? \"succeeded\" : \"skipped\"\n\n\t\t\t\t\tanswered.add(rowId)\n\t\t\t\t\tresults.push(\n\t\t\t\t\t\tObject.freeze({ rowId, outcome: kind, data: Object.freeze({}), requestId: request.requestId })\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse.issues?.forEach((input, index) => {\n\t\t\t\tconst issue = this.#toIssue(input, \"process\", `run.${index}`, request.revision, null)\n\n\t\t\t\tif (issue) {\n\t\t\t\t\tissues.push(issue)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\n\t\tconst done = new Set(results.filter(result => result.outcome === \"succeeded\").map(result => result.rowId))\n\n\t\t// What a run says about a row replaces what the last one said; a row that went through has\n\t\t// nothing left for a pre-flight check to say.\n\t\tthis.#merged.replace(\n\t\t\tissue =>\n\t\t\t\t(issue.source === \"process\" && (issue.rowId === null ? final : answered.has(issue.rowId))) ||\n\t\t\t\t(issue.source === \"preflight\" && issue.rowId !== null && done.has(issue.rowId)),\n\t\t\tissues\n\t\t)\n\t\tthis.#results.record(results)\n\t}\n\n\t#rowPlan(rowId: RowId, given: RowPlanInput | undefined): RowPlan {\n\t\tif (given === undefined) {\n\t\t\treturn Object.freeze({ rowId, action: \"unknown\", changes: Object.freeze([]) })\n\t\t}\n\n\t\tconst changes: PlannedChange[] = []\n\t\tconst previous = given.previous ?? {}\n\n\t\tfor (const field of this.schema.fields) {\n\t\t\tif (!field.submit) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst value = this.store.get(rowId, field.key)\n\t\t\t// An error a formula gave is not sent, so it is not written either.\n\t\t\tconst after = isFormulaError(value) ? null : value\n\n\t\t\tif (given.action === \"create\" && after !== null) {\n\t\t\t\tchanges.push(Object.freeze({ field: field.key, before: null, after }))\n\t\t\t} else if (given.action === \"update\" && Object.hasOwn(previous, field.key)) {\n\t\t\t\tchanges.push(Object.freeze({ field: field.key, before: previous[field.key] ?? null, after }))\n\t\t\t}\n\t\t}\n\n\t\treturn Object.freeze({ rowId, action: given.action, changes: Object.freeze(changes) })\n\t}\n\n\t#query(): StatusQuery {\n\t\tconst request = this.#pending as ProcessRequest\n\n\t\treturn Object.freeze({\n\t\t\trequestId: request.requestId,\n\t\t\tidempotencyKey: request.idempotencyKey,\n\t\t\toperationId: this.#state.run?.operationId ?? null\n\t\t})\n\t}\n\n\t#blockedRows(rowIds: readonly RowId[]): number {\n\t\tconst server = this.#merged.server.filter(issue => issue.blocking && !issue.stale)\n\n\t\tif (server.some(issue => issue.rowId === null)) {\n\t\t\treturn rowIds.length\n\t\t}\n\n\t\tconst blockedByServer = new Set(server.map(issue => issue.rowId))\n\n\t\treturn rowIds.filter(rowId => blockedByServer.has(rowId) || this.validator.hasErrors(rowId)).length\n\t}\n\n\t// ---------------------------------------------------------------- requests and answers\n\n\t#request(rowIds: readonly RowId[]): SheetRequest {\n\t\treturn Object.freeze({\n\t\t\trequestId: this.#requestId(),\n\t\t\tmodule: this.schema.module,\n\t\t\tschemaVersion: this.schema.schemaVersion,\n\t\t\tsheetId: this.sheetId,\n\t\t\trevision: this.store.revision,\n\t\t\trows: Object.freeze(rowIds.map(rowId => Object.freeze({ rowId, values: this.#payload(rowId) })))\n\t\t})\n\t}\n\n\t#payload(rowId: RowId): Readonly<Record<string, CellValue>> {\n\t\tconst values: Record<string, CellValue> = {}\n\n\t\tfor (const field of this.schema.fields) {\n\t\t\tif (field.submit) {\n\t\t\t\tconst value = this.store.get(rowId, field.key)\n\n\t\t\t\t// An error a formula gave is no value to send; the backend works the formula out again.\n\t\t\t\tvalues[field.key] = isFormulaError(value)\n\t\t\t\t\t? null\n\t\t\t\t\t: field.type === \"lookup\"\n\t\t\t\t\t\t? lookupPayload(value)\n\t\t\t\t\t\t: canonicalValue(field, value, this.validator.settings)\n\t\t\t}\n\t\t}\n\n\t\treturn Object.freeze(values)\n\t}\n\n\t/**\n\t * Nothing to send: a row holding only columns shown for reference is empty too, and so is one\n\t * holding nothing anyone gave it (`isBlankRow`).\n\t */\n\t#isEmpty(rowId: RowId): boolean {\n\t\treturn (\n\t\t\tthis.schema.fields.every(field => !field.submit || this.store.get(rowId, field.key) === null) ||\n\t\t\tisBlankRow(this.schema, key => this.store.get(rowId, key))\n\t\t)\n\t}\n\n\t/** An answer that names a request must name this one. */\n\t#answered<T extends { readonly requestId?: string }>(requestId: string, response: T): T {\n\t\tif (response.requestId !== undefined && response.requestId !== requestId) {\n\t\t\tthrow new TabulaError(\n\t\t\t\t\"invalid_response\",\n\t\t\t\t`The answer is to request \"${response.requestId}\", not to \"${requestId}\", the one it came back for.`\n\t\t\t)\n\t\t}\n\n\t\treturn response\n\t}\n\n\t/**\n\t * An issue from a backend as the sheet holds it. One for another sheet or for a row no longer in\n\t * this one is passed over. One for a field the schema does not have is kept as the row's, the key\n\t * in its params, so it is still seen.\n\t */\n\t#toIssue(input: IssueInput, source: string, key: string, revision: number, row: RowId | null): Issue | null {\n\t\tif (input.sheetId != null && input.sheetId !== this.sheetId) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst rowId = input.rowId === undefined ? row : input.rowId\n\n\t\tif (rowId !== null && !this.store.has(rowId)) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst params: Record<string, string> = {}\n\n\t\tfor (const [name, value] of Object.entries(input.params ?? {})) {\n\t\t\tparams[name] = value === null ? \"\" : String(value)\n\t\t}\n\n\t\tlet field = input.field ?? null\n\n\t\tif (field !== null && !this.schema.has(field)) {\n\t\t\tparams.field ??= field\n\t\t\tfield = null\n\t\t}\n\n\t\tconst scope = scopeOf(input.scope, rowId, field)\n\t\tconst severity = input.severity ?? \"error\"\n\t\tconst issue: Issue = {\n\t\t\tid: `${source}|${key}|${input.code}|${rowId ?? \"\"}|${field ?? \"\"}`,\n\t\t\tscope,\n\t\t\tsource,\n\t\t\trowId: scope === \"sheet\" || scope === \"workbook\" ? null : rowId,\n\t\t\tfield: scope === \"cell\" ? field : null,\n\t\t\ttargets: Object.freeze((input.targets ?? []).map(target => Object.freeze({ ...target }))),\n\t\t\tcode: input.code,\n\t\t\tseverity,\n\t\t\tblocking: input.blocking ?? severity === \"error\",\n\t\t\tstale: false,\n\t\t\tmessage: input.message ?? input.code,\n\t\t\tparams: Object.freeze(params)\n\t\t}\n\n\t\treturn Object.freeze({ ...issue, stale: this.#changedSince(issue, revision) })\n\t}\n\n\t/** Whether a cell the issue is about changed after the revision it was found at. */\n\t#changedSince(issue: Issue, revision: number): boolean {\n\t\tif (issue.rowId === null) {\n\t\t\treturn this.store.revision > revision\n\t\t}\n\n\t\tconst changed =\n\t\t\tissue.scope === \"row\"\n\t\t\t\t? (this.#rowChanged.get(issue.rowId) ?? -1)\n\t\t\t\t: (this.#cellChanged.get(issue.rowId)?.get(issue.field ?? \"\") ?? -1)\n\n\t\treturn (\n\t\t\tchanged > revision ||\n\t\t\tissue.targets.some(\n\t\t\t\ttarget =>\n\t\t\t\t\t!this.store.has(target.rowId) ||\n\t\t\t\t\t(this.#cellChanged.get(target.rowId)?.get(target.field) ?? -1) > revision\n\t\t\t)\n\t\t)\n\t}\n\n\t// ---------------------------------------------------------------- the sheet changing\n\n\t#onChange(change: StoreChange): void {\n\t\tconst cells = new Map<RowId, Set<string>>()\n\t\tconst removed = new Set<RowId>()\n\n\t\tfor (const operation of change.operations) {\n\t\t\tif (operation.kind === \"set\") {\n\t\t\t\tlet fields = this.#cellChanged.get(operation.rowId)\n\n\t\t\t\tif (!fields) {\n\t\t\t\t\tfields = new Map()\n\t\t\t\t\tthis.#cellChanged.set(operation.rowId, fields)\n\t\t\t\t}\n\n\t\t\t\tfields.set(operation.field, change.revision)\n\t\t\t\tthis.#rowChanged.set(operation.rowId, change.revision)\n\n\t\t\t\tconst touched = cells.get(operation.rowId) ?? new Set()\n\n\t\t\t\ttouched.add(operation.field)\n\t\t\t\tcells.set(operation.rowId, touched)\n\t\t\t} else if (operation.kind === \"insert\") {\n\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\tthis.#rowChanged.set(row.rowId, change.revision)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (const row of operation.rows) {\n\t\t\t\t\tremoved.add(row.rowId)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst touches = (rowId: RowId, field: string): boolean =>\n\t\t\tremoved.has(rowId) || (cells.get(rowId)?.has(field) ?? false)\n\n\t\tthis.#merged.update(issue => {\n\t\t\tif (issue.rowId !== null && !this.store.has(issue.rowId)) {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\tif (issue.stale) {\n\t\t\t\treturn issue\n\t\t\t}\n\n\t\t\tconst affected =\n\t\t\t\tissue.rowId === null ||\n\t\t\t\t(issue.scope === \"row\" ? cells.has(issue.rowId) : touches(issue.rowId, issue.field ?? \"\")) ||\n\t\t\t\tissue.targets.some(target => touches(target.rowId, target.field))\n\n\t\t\treturn affected ? Object.freeze({ ...issue, stale: true }) : issue\n\t\t})\n\t}\n\n\t// ---------------------------------------------------------------- state\n\n\t/** Takes up where a draft left off: results back on their rows, a run with no answer still unknown. */\n\t#restore(saved: PersistedSession): void {\n\t\tthis.#results.record(saved.results.filter(result => this.store.has(result.rowId)))\n\n\t\tconst pending = saved.pending\n\n\t\tif (!pending) {\n\t\t\treturn\n\t\t}\n\n\t\tconst request = pending.request\n\n\t\tthis.#pending = request\n\t\tthis.#results.setInFlight(new Set(request.rows.map(row => row.rowId)))\n\t\tthis.#setState({\n\t\t\tphase: \"unknown\",\n\t\t\trun: Object.freeze({\n\t\t\t\trequestId: request.requestId,\n\t\t\t\tidempotencyKey: request.idempotencyKey,\n\t\t\t\toperationId: pending.operationId,\n\t\t\t\trevision: request.revision,\n\t\t\t\trows: request.rows.length,\n\t\t\t\tstatus: \"unknown\",\n\t\t\t\tprogress: null\n\t\t\t})\n\t\t})\n\t}\n\n\t#setState(patch: Partial<SessionState>): void {\n\t\tif (this.#disposed) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#state = Object.freeze({ ...this.#state, ...patch })\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n\n\t#setRun(patch: Partial<RunRecord>): void {\n\t\tconst run = this.#state.run\n\n\t\tif (run) {\n\t\t\tthis.#setState({ run: Object.freeze({ ...run, ...patch }) })\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------- the merged issues\n\ninterface IssueIndex {\n\treadonly sheet: Issue[]\n\treadonly rows: Map<RowId, Issue[]>\n\treadonly cells: Map<RowId, Map<string, Issue[]>>\n}\n\n/** The local validator's issues and the backend's, read as one set. */\nclass MergedIssues implements IssueSet {\n\treadonly #local: SheetValidator\n\treadonly #store: RowStore\n\treadonly #schema: ModuleSchema\n\treadonly #listeners = new Listeners<MergedIssues>()\n\treadonly #stop: () => void\n\t#server: readonly Issue[] = []\n\t#index: IssueIndex | null = null\n\t#version = 0\n\n\tconstructor(local: SheetValidator, store: RowStore, schema: ModuleSchema) {\n\t\tthis.#local = local\n\t\tthis.#store = store\n\t\tthis.#schema = schema\n\t\tthis.#stop = local.subscribe(() => this.#changed())\n\t}\n\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\t/** The backend's issues alone. */\n\tget server(): readonly Issue[] {\n\t\treturn this.#server\n\t}\n\n\tissuesAt(rowId: RowId, field: string): readonly Issue[] {\n\t\tconst own = this.#local.issuesAt(rowId, field)\n\t\tconst remote = this.#indexed().cells.get(rowId)?.get(field)\n\n\t\treturn remote ? [...own, ...remote] : own\n\t}\n\n\trowIssues(rowId: RowId): readonly Issue[] {\n\t\treturn this.#indexed().rows.get(rowId) ?? []\n\t}\n\n\thasIssues(rowId: RowId): boolean {\n\t\tconst index = this.#indexed()\n\n\t\treturn this.#local.hasIssues(rowId) || index.rows.has(rowId) || index.cells.has(rowId)\n\t}\n\n\tissues(): Issue[] {\n\t\tconst index = this.#indexed()\n\t\tconst result: Issue[] = [...index.sheet]\n\n\t\tfor (const rowId of this.#store.rowIds()) {\n\t\t\tresult.push(...(index.rows.get(rowId) ?? []))\n\n\t\t\tfor (const field of this.#schema.fields) {\n\t\t\t\tresult.push(...this.issuesAt(rowId, field.key))\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n\tsummary(): IssueSummary {\n\t\tconst local = this.#local.summary()\n\t\tconst rows = this.#local.affectedRows()\n\t\tlet errors = local.errors\n\t\tlet warnings = local.warnings\n\t\tlet stale = 0\n\n\t\tfor (const issue of this.#server) {\n\t\t\tif (issue.stale) {\n\t\t\t\tstale++\n\t\t\t} else if (issue.severity === \"error\") {\n\t\t\t\terrors++\n\t\t\t} else {\n\t\t\t\twarnings++\n\t\t\t}\n\n\t\t\tif (issue.rowId !== null) {\n\t\t\t\trows.add(issue.rowId)\n\t\t\t}\n\t\t}\n\n\t\treturn { errors, warnings, stale, rows: rows.size }\n\t}\n\n\tsubscribe(listener: () => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\t/** Takes out the backend's issues `drop` picks, and adds `add`. */\n\treplace(drop: (issue: Issue) => boolean, add: readonly Issue[]): void {\n\t\tconst kept = this.#server.filter(issue => !drop(issue))\n\n\t\tif (kept.length === this.#server.length && add.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#server = [...kept, ...add]\n\t\tthis.#index = null\n\t\tthis.#changed()\n\t}\n\n\t/** Passes each of the backend's issues through `fn`: the same issue, a changed one, or null to drop it. */\n\tupdate(fn: (issue: Issue) => Issue | null): void {\n\t\tlet changed = false\n\t\tconst next: Issue[] = []\n\n\t\tfor (const issue of this.#server) {\n\t\t\tconst updated = fn(issue)\n\n\t\t\tchanged ||= updated !== issue\n\n\t\t\tif (updated) {\n\t\t\t\tnext.push(updated)\n\t\t\t}\n\t\t}\n\n\t\tif (changed) {\n\t\t\tthis.#server = next\n\t\t\tthis.#index = null\n\t\t\tthis.#changed()\n\t\t}\n\t}\n\n\tdispose(): void {\n\t\tthis.#stop()\n\t}\n\n\t#indexed(): IssueIndex {\n\t\tif (this.#index) {\n\t\t\treturn this.#index\n\t\t}\n\n\t\tconst index: IssueIndex = { sheet: [], rows: new Map(), cells: new Map() }\n\n\t\tfor (const issue of this.#server) {\n\t\t\tif (issue.rowId === null) {\n\t\t\t\tindex.sheet.push(issue)\n\t\t\t} else if (issue.field === null) {\n\t\t\t\tpush(index.rows, issue.rowId, issue)\n\t\t\t} else {\n\t\t\t\tlet fields = index.cells.get(issue.rowId)\n\n\t\t\t\tif (!fields) {\n\t\t\t\t\tfields = new Map()\n\t\t\t\t\tindex.cells.set(issue.rowId, fields)\n\t\t\t\t}\n\n\t\t\t\tpush(fields, issue.field, issue)\n\t\t\t}\n\t\t}\n\n\t\tthis.#index = index\n\n\t\treturn index\n\t}\n\n\t#changed(): void {\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n}\n\n// ---------------------------------------------------------------- results\n\nclass Results implements RowResults {\n\treadonly #results = new Map<RowId, RowResult>()\n\treadonly #listeners = new Listeners<Results>()\n\t#inFlight: ReadonlySet<RowId> = new Set()\n\t#version = 0\n\n\tget version(): number {\n\t\treturn this.#version\n\t}\n\n\tresultOf(rowId: RowId): RowResult | null {\n\t\treturn this.#results.get(rowId) ?? null\n\t}\n\n\tisLocked(rowId: RowId): boolean {\n\t\treturn this.#inFlight.has(rowId) || this.#results.get(rowId)?.outcome === \"succeeded\"\n\t}\n\n\tsubscribe(listener: () => void): () => void {\n\t\treturn this.#listeners.add(listener)\n\t}\n\n\tsetInFlight(rows: ReadonlySet<RowId>): void {\n\t\tif (rows.size === 0 && this.#inFlight.size === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.#inFlight = rows\n\t\tthis.#changed()\n\t}\n\n\trecord(results: readonly RowResult[]): void {\n\t\tif (results.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tfor (const result of results) {\n\t\t\tthis.#results.set(result.rowId, result)\n\t\t}\n\n\t\tthis.#changed()\n\t}\n\n\t#changed(): void {\n\t\tthis.#version++\n\t\tthis.#listeners.emit(this)\n\t}\n}\n\n// ---------------------------------------------------------------- helpers\n\nfunction outcome(status: ProcessOutcome[\"status\"]): ProcessOutcome {\n\treturn { status, succeeded: 0, failed: 0, skipped: 0, blocked: 0 }\n}\n\nfunction record(request: SheetRequest, outcome: CheckRecord[\"outcome\"]): CheckRecord {\n\treturn Object.freeze({ requestId: request.requestId, revision: request.revision, outcome })\n}\n\nfunction failure(stage: SessionFailure[\"stage\"], error: unknown, code?: SessionFailure[\"code\"]): SessionFailure {\n\tconst invalid = error instanceof TabulaError && error.code === \"invalid_response\"\n\n\treturn Object.freeze({\n\t\tstage,\n\t\tcode: code ?? (invalid ? \"invalid_response\" : \"request_failed\"),\n\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\terror\n\t})\n}\n\n/** The widest scope the ids can carry, when the one given needs more than they have. */\nfunction scopeOf(given: IssueScope | undefined, rowId: RowId | null, field: string | null): IssueScope {\n\tconst scope = given ?? (rowId === null ? \"sheet\" : field === null ? \"row\" : \"cell\")\n\n\tif (scope === \"cell\" && field === null) {\n\t\treturn rowId === null ? \"sheet\" : \"row\"\n\t}\n\n\tif (scope === \"row\" && rowId === null) {\n\t\treturn \"sheet\"\n\t}\n\n\treturn scope\n}\n\nfunction lookupPayload(value: CellValue): CellValue {\n\tif (isLookupValue(value)) {\n\t\treturn value.id\n\t}\n\n\treturn typeof value === \"string\" ? Object.freeze({ label: value }) : value\n}\n\nfunction push<K>(map: Map<K, Issue[]>, key: K, issue: Issue): void {\n\tconst list = map.get(key)\n\n\tif (list) {\n\t\tlist.push(issue)\n\t} else {\n\t\tmap.set(key, [issue])\n\t}\n}\n","import type { RowId, RowStore, StoreChange } from \"./rows.js\"\nimport type { ModuleSchema } from \"./schema.js\"\nimport { formatCell } from \"./values/format.js\"\nimport { readInput } from \"./values/read.js\"\nimport type { ValueSettings } from \"./values/settings.js\"\n\n/**\n * Find and replace over a sheet, as a spreadsheet's Ctrl+H: text looked for in the cells as they are\n * shown, \"1.533,80\", \"Mağaza, Web\", and replaced as if it had been typed into each, so a number stays\n * a number and an option an option. Every replacement is one change of the store: one Ctrl+Z.\n */\n\n/** The origin of the change `replaceCells` makes, as `StoreChange.origin` gives it. */\nexport const REPLACE_ORIGIN = \"replace\"\n\nexport interface FindOptions {\n\treadonly settings: ValueSettings\n\t/** Upper and lower case told apart. Off by default. */\n\treadonly matchCase?: boolean\n\t/** Only a cell whose whole text is what is looked for. Off by default. */\n\treadonly whole?: boolean\n\t/** The language case is folded in, the page's: in Turkish \"I\" is \"ı\" in lower case. */\n\treadonly locale?: string\n}\n\n/** A cell, by its row's id and its field's key. */\nexport interface FoundCell {\n\treadonly rowId: RowId\n\treadonly field: string\n}\n\n/**\n * The cells holding `text`, row by row in the order given, and in each row field by field in the\n * order given: where Next goes. Empty text finds nothing.\n */\nexport function findCells(\n\tstore: RowStore,\n\tschema: ModuleSchema,\n\trowIds: readonly RowId[],\n\tfields: readonly string[],\n\ttext: string,\n\toptions: FindOptions\n): FoundCell[] {\n\tif (text === \"\") {\n\t\treturn []\n\t}\n\n\tconst matches = matcher(text, options)\n\tconst known = fields.filter(key => schema.has(key))\n\tconst found: FoundCell[] = []\n\n\tfor (const rowId of rowIds) {\n\t\tfor (const field of known) {\n\t\t\tif (matches(formatCell(schema.field(field), store.get(rowId, field), options.settings))) {\n\t\t\t\tfound.push({ rowId, field })\n\t\t\t}\n\t\t}\n\t}\n\n\treturn found\n}\n\nexport interface ReplaceOptions extends FindOptions {\n\t/** Whether a cell may be written; a cell refused is left as it is and counted. All may by default. */\n\treadonly editable?: (rowId: RowId, field: string) => boolean\n\treadonly origin?: string\n}\n\nexport interface ReplaceResult {\n\t/** Cells written. */\n\treadonly replaced: number\n\t/** Cells left as they were: their column or row cannot be written. */\n\treadonly skipped: number\n\t/** The store's change; null when nothing was written. */\n\treadonly change: StoreChange | null\n}\n\n/**\n * Replaces `text` with `replacement` in the cells given, such as `findCells`' answer, in one change.\n * Each cell's new text is read as typing it would be read; text that cannot be read is kept as typed\n * and its cell says why, as a paste does. A column that cannot be typed into, or a formula's, is\n * left as it is.\n */\nexport function replaceCells(\n\tstore: RowStore,\n\tschema: ModuleSchema,\n\tcells: readonly FoundCell[],\n\ttext: string,\n\treplacement: string,\n\toptions: ReplaceOptions\n): ReplaceResult {\n\tif (text === \"\") {\n\t\treturn { replaced: 0, skipped: 0, change: null }\n\t}\n\n\tconst writes: { rowId: RowId; field: string; value: ReturnType<typeof readInput>[\"value\"] }[] = []\n\tlet skipped = 0\n\n\tfor (const cell of cells) {\n\t\tif (!schema.has(cell.field) || !store.has(cell.rowId)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst field = schema.field(cell.field)\n\n\t\tif (!field.editable || field.formula || options.editable?.(cell.rowId, cell.field) === false) {\n\t\t\tskipped++\n\t\t\tcontinue\n\t\t}\n\n\t\tconst shown = formatCell(field, store.get(cell.rowId, cell.field), options.settings)\n\t\tconst next = replaced(shown, text, replacement, options)\n\n\t\tif (next === null) {\n\t\t\tcontinue\n\t\t}\n\n\t\twrites.push({ rowId: cell.rowId, field: cell.field, value: readInput(field, next, options.settings).value })\n\t}\n\n\tconst change = writes.length === 0 ? null : store.setCells(writes, { origin: options.origin ?? REPLACE_ORIGIN })\n\n\treturn { replaced: writes.length, skipped, change }\n}\n\nfunction matcher(text: string, options: FindOptions): (shown: string) => boolean {\n\tconst fold = (value: string): string => (options.matchCase ? value : value.toLocaleLowerCase(options.locale))\n\tconst wanted = fold(text)\n\n\treturn shown => (options.whole ? fold(shown) === wanted : fold(shown).includes(wanted))\n}\n\n/** The cell's text with every match replaced; null when it holds none. */\nfunction replaced(shown: string, text: string, replacement: string, options: FindOptions): string | null {\n\tconst fold = (value: string): string => (options.matchCase ? value : value.toLocaleLowerCase(options.locale))\n\n\tif (options.whole) {\n\t\treturn fold(shown) === fold(text) ? replacement : null\n\t}\n\n\tconst haystack = fold(shown)\n\tconst needle = fold(text)\n\tlet at = haystack.indexOf(needle)\n\n\tif (at < 0) {\n\t\treturn null\n\t}\n\n\t// Folding case can change a text's length (\"İ\" in some languages); then the match is replaced whole.\n\tif (haystack.length !== shown.length) {\n\t\treturn haystack.split(needle).join(replacement)\n\t}\n\n\tlet result = \"\"\n\tlet from = 0\n\n\twhile (at >= 0) {\n\t\tresult += shown.slice(from, at) + replacement\n\t\tfrom = at + needle.length\n\t\tat = haystack.indexOf(needle, from)\n\t}\n\n\treturn result + shown.slice(from)\n}\n","/**\n * The version of this package.\n *\n * It repeats what `package.json` says, and a test holds the two together: a release that bumps\n * one and forgets the other fails before it is tagged.\n */\nexport const version = \"0.5.0\"\n\nexport { SchemaError, TabulaError } from \"./errors.js\"\nexport type { SchemaProblem, TabulaErrorCode } from \"./errors.js\"\n\nexport type { CellObject, CellValue } from \"./value.js\"\n\nexport { CUSTOMIZATIONS, FIELD_TYPES, ModuleSchema } from \"./schema.js\"\nexport type {\n\tBoolField,\n\tCustomization,\n\tDateField,\n\tDecimalField,\n\tFieldInput,\n\tFieldOption,\n\tFieldRule,\n\tFieldSchema,\n\tFieldTone,\n\tFieldType,\n\tIntegerField,\n\tLookupField,\n\tModuleSchemaInput,\n\tMoneyField,\n\tOptionInput,\n\tOptionsField,\n\tRuleInput,\n\tTextField\n} from \"./schema.js\"\n\nexport { RowStore } from \"./rows.js\"\nexport type {\n\tCellWrite,\n\tRemovedRow,\n\tRowEntry,\n\tRowId,\n\tRowInit,\n\tRowStoreOptions,\n\tRowValues,\n\tStoreChange,\n\tStoreOperation,\n\tTransactOptions\n} from \"./rows.js\"\n\nexport { REDO_ORIGIN, UNDO_ORIGIN, UndoHistory } from \"./history.js\"\nexport type { HistoryStep, UndoHistoryOptions } from \"./history.js\"\n\nexport { LOOKUP_ORIGIN, LookupResolver } from \"./lookup.js\"\nexport type {\n\tLookupAdapters,\n\tLookupItem,\n\tLookupResolveRequest,\n\tLookupResolveResponse,\n\tLookupResolverOptions,\n\tLookupSearch,\n\tLookupSearchRequest,\n\tLookupSearchResponse\n} from \"./lookup.js\"\n\nexport { applyFormulas, FORMULA_ORIGIN, FormulaEngine } from \"./formula/engine.js\"\nexport type { FormulaEngineOptions } from \"./formula/engine.js\"\nexport {\n\tboolValue as formulaBool,\n\tEMPTY as FORMULA_EMPTY,\n\terrorValue as formulaError,\n\tFUNCTIONS as FORMULA_FUNCTIONS,\n\tformulaNumber,\n\tnumberArgument,\n\ttextValue as formulaText\n} from \"./formula/evaluate.js\"\nexport type { FormulaFunction, FormulaValue } from \"./formula/evaluate.js\"\nexport { formulaFields, parseFormula } from \"./formula/parse.js\"\nexport {\n\tformulaCaret,\n\tformulaFromAddresses,\n\tformulaParts,\n\tformulaWithKeys,\n\tformulaWithLabels\n} from \"./formula/assist.js\"\nexport type { FormulaCall, FormulaCaret, FormulaPart, FormulaToken, NamedField } from \"./formula/assist.js\"\nexport type { BinaryOperator, FormulaNode } from \"./formula/parse.js\"\nexport { isFormulaError } from \"./formula/error.js\"\nexport type { FormulaErrorCode, FormulaErrorValue } from \"./formula/error.js\"\n\nexport { RowView, rowsWithIssues, rowsWithResult } from \"./view.js\"\nexport type { RowFilter, RowOrder } from \"./view.js\"\nexport { summarizeCells } from \"./summary.js\"\nexport {\n\tcompareValues,\n\tdistinctValues,\n\tfilterKey,\n\tfilterKeys,\n\thasRange,\n\trowOrder,\n\trowsContaining,\n\trowsMatching\n} from \"./filters.js\"\nexport { fillValues } from \"./fill.js\"\nexport { adjustValue, isAdjustable } from \"./adjust.js\"\nexport type { Adjustment } from \"./adjust.js\"\nexport { rowsChanged, SheetChanges } from \"./changes.js\"\nexport type { ChangeSummary, SheetChangesOptions } from \"./changes.js\"\nexport { breaksCheck, checkFields, COMPARISONS, CONDITION_OPS, conditionHolds, rowsBreaking } from \"./checks.js\"\nexport type {\n\tCheckInput,\n\tCheckSeverity,\n\tComparison,\n\tConditionInput,\n\tConditionOp,\n\tRowCheck,\n\tRowCondition\n} from \"./checks.js\"\nexport {\n\tapplyTemplate,\n\treadTemplate,\n\tTEMPLATE_FORMAT,\n\tTEMPLATE_VERSION,\n\ttemplateProblems,\n\twithDefaults\n} from \"./templates.js\"\nexport type { GridTemplate, TemplateFieldChange, TemplateProblem } from \"./templates.js\"\nexport {\n\taddView,\n\temptyViews,\n\tPLAIN_VIEW,\n\treadViews,\n\treadViewState,\n\tremoveView,\n\trenameView,\n\tsameView,\n\tsetDefaultView,\n\tupdateView,\n\tVIEW_NAME_LIMIT,\n\tviewFor,\n\tviewNameProblem,\n\tVIEWS_FORMAT,\n\tVIEWS_VERSION\n} from \"./views.js\"\nexport type { SavedView, SavedViews, ViewNameOptions, ViewNameProblem, ViewState } from \"./views.js\"\nexport type { FillMode, FillOptions } from \"./fill.js\"\nexport type { ColumnCondition, ColumnFilters, ColumnSort, DistinctValue, SearchOptions } from \"./filters.js\"\nexport type { CellSummary } from \"./summary.js\"\n\nexport { Selection } from \"./selection.js\"\nexport type { CellPosition, CellRange, Direction, IsBlank, MoveOptions } from \"./selection.js\"\n\nexport { parseTsv, toTsv } from \"./clipboard.js\"\n\nexport { decodeText, detectDelimiter, parseCsv, toCsv } from \"./csv.js\"\nexport type { CsvDelimiter, CsvReadOptions, CsvWriteOptions } from \"./csv.js\"\nexport {\n\tapplyImport,\n\tcsvDelimiterFor,\n\texportTable,\n\theaderKey,\n\tIMPORT_ORIGIN,\n\timportTable,\n\tmatchRows,\n\tsuggestColumns,\n\tsuggestMatch\n} from \"./table.js\"\nexport type {\n\tColumnMatch,\n\tColumnStatus,\n\tColumnSuggestion,\n\tExtraColumn,\n\tImportApplied,\n\tImportApplyOptions,\n\tMatchSuggestion,\n\tSuggestionReason,\n\tSuggestOptions,\n\tTableExportOptions,\n\tTableImport,\n\tTableImportOptions\n} from \"./table.js\"\n\nexport { checkValue, isBlankRow, SheetValidator } from \"./validation.js\"\nexport type {\n\tIssue,\n\tIssueScope,\n\tIssueSet,\n\tIssueSeverity,\n\tIssueSummary,\n\tIssueTarget,\n\tLocalIssueCode\n} from \"./validation.js\"\n\nexport { readCheckResponse, readProcessResponse } from \"./contract.js\"\nexport type {\n\tAdapterContext,\n\tCheckResponse,\n\tIssueInput,\n\tPayloadRow,\n\tProcessProgress,\n\tProcessRequest,\n\tProcessResponse,\n\tProcessStatus,\n\tRowAction,\n\tRowOutcome,\n\tRowPlanInput,\n\tRowResultInput,\n\tSheetAdapters,\n\tSheetRequest,\n\tStatusQuery\n} from \"./contract.js\"\n\nexport { createDraft, DRAFT_FORMAT, DRAFT_VERSION, mapDraft, openDraft, readDraft, suggestRenames } from \"./draft.js\"\nexport type {\n\tCreateDraftOptions,\n\tDraft,\n\tDraftChanges,\n\tDraftField,\n\tDraftFieldMapping,\n\tDraftMapping,\n\tDraftOpening,\n\tDraftView,\n\tMapDraftOptions,\n\tOpenDraftOptions\n} from \"./draft.js\"\n\nexport {\n\taddSheet,\n\tcreateWorkbook,\n\tfreeSheetId,\n\tmoveSheet,\n\topenSheet,\n\treadWorkbook,\n\tremoveSheet,\n\twithSheet,\n\tWORKBOOK_FORMAT,\n\tWORKBOOK_VERSION\n} from \"./workbook.js\"\nexport type { NewSheet, SheetMeta, Workbook, WorkbookSheet } from \"./workbook.js\"\n\nexport { DraftSaver } from \"./saver.js\"\nexport type { DraftSaverOptions, SaverState, SaverStatus } from \"./saver.js\"\n\nexport { SheetSession } from \"./session.js\"\nexport type {\n\tCheckOutcome,\n\tCheckRecord,\n\tPendingRun,\n\tPersistedSession,\n\tPlannedAction,\n\tPlannedChange,\n\tProcessOutcome,\n\tProcessPlan,\n\tRowPlan,\n\tRowResult,\n\tRowResults,\n\tRunRecord,\n\tRunStatus,\n\tSessionFailure,\n\tSessionPhase,\n\tSessionState,\n\tSheetSessionOptions\n} from \"./session.js\"\n\nexport { defineValueSettings, VALUE_SETTINGS } from \"./values/settings.js\"\nexport type { ValueSettings } from \"./values/settings.js\"\nexport { isFieldValue, readInput, valueProblem } from \"./values/read.js\"\nexport type { ReadResult, ValueProblem, ValueProblemCode } from \"./values/read.js\"\nexport { digitsFor, editText, formatCell } from \"./values/format.js\"\nexport type { CellFormatOptions } from \"./values/format.js\"\nexport { CellMarks, MARK_COLORS, readMarks, rowsMarked } from \"./marks.js\"\nexport type { CellMark, CellMarkChange, CellMarksOptions, MarkColor, MarkedCell, MarksData } from \"./marks.js\"\nexport { readStyleRules, rowStyles, rowsStyled, styleApplies, styleRuleToJson } from \"./styles.js\"\nexport type { CellStyle, StyleRule, StyleRuleInput } from \"./styles.js\"\nexport { findCells, REPLACE_ORIGIN, replaceCells } from \"./find.js\"\nexport type { FindOptions, FoundCell, ReplaceOptions, ReplaceResult } from \"./find.js\"\n\nexport {\n\tarrangeColumns,\n\tautoColumnWidth,\n\tclampColumnWidth,\n\tDEFAULT_COLUMN_SIZING,\n\tCOLUMN_ALIGNS,\n\tfreezeColumnLayout,\n\theaderDisplayText,\n\tmapColumnLayout,\n\tMAX_SHOWN_DECIMALS,\n\tmergeColumnFormats,\n\treadColumnLayout,\n\tresolveColumnSizing,\n\tsameColumnFormats,\n\twithColumn,\n\twithColumnFormat,\n\twithoutColumnFormats\n} from \"./columns.js\"\nexport type {\n\tArrangedColumns,\n\tColumnAlign,\n\tColumnFormat,\n\tColumnFormats,\n\tColumnLayout,\n\tColumnSizing\n} from \"./columns.js\"\n"],"mappings":";AAsBA,IAAa6B,IAAb,cAAiC,MAAM;CACtC,OAAgB;CAChB;CAEA,YAAY,GAAuB,GAAiB;EAEnD,AADA,MAAMC,CAAO,GACb,KAAK,OAAOC;CACb;AACD,GAcaC,IAAb,cAAiCH,EAAY;CAC5C,OAAgB;CAChB;CAEA,YAAY,GAAiB,GAAoC;EAChE,IAAMI,IAAQC,EAAS,KAAI,MAAW,KAAKC,EAAQ,KAAK,IAAIA,EAAQ,SAAS;EAE7E,AADA,MAAM,kBAAkB,GAAGC,EAAQ,kBAAkBH,EAAM,KAAK,IAAI,GAAG,GACvE,KAAK,WAAW,OAAO,OAAO,CAAC,GAAGC,CAAQ,CAAC;CAC5C;AACD,GC7CMG,IAAU;AAShB,SAAgBC,EAAiB,GAAuC;CACvE,IAAIC;CAEJ,IAAI,OAAOC,KAAU,UAAU;EAC9B,IAAI,CAAC,OAAO,SAASA,CAAK,GACzB,OAAO;EAGR,IAAO,OAAOA,CAAK;CACpB,OACC,IAAOA,EAAM,KAAK;CAGnB,IAAMC,IAAQJ,EAAQ,K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