@eidos.space/eidos-file 3.1.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/{adapter-contract-SrPzXysz.d.mts → adapter-contract-vfw3_C3w.d.mts} +2 -2
  2. package/dist/{adapter-contract-SrPzXysz.d.mts.map → adapter-contract-vfw3_C3w.d.mts.map} +1 -1
  3. package/dist/better-sqlite3.d.mts +2 -2
  4. package/dist/better-sqlite3.mjs +1 -1
  5. package/dist/browser.d.mts +4 -4
  6. package/dist/browser.mjs +2 -2
  7. package/dist/csv.d.mts +1 -1
  8. package/dist/index.d.mts +6 -5
  9. package/dist/index.d.mts.map +1 -1
  10. package/dist/index.mjs +6 -3
  11. package/dist/index.mjs.map +1 -1
  12. package/dist/node-sqlite.d.mts +3 -3
  13. package/dist/node-sqlite.mjs +2 -2
  14. package/dist/{runtime-CUCgAnbo.d.mts → runtime-CtP7-fVC.d.mts} +25 -2
  15. package/dist/runtime-CtP7-fVC.d.mts.map +1 -0
  16. package/dist/{runtime-CrsC-uwG.mjs → runtime-mvRkk__c.mjs} +99 -1
  17. package/dist/runtime-mvRkk__c.mjs.map +1 -0
  18. package/dist/{sqlite-wasm-BQqcna0d.mjs → sqlite-wasm-BhRD8n56.mjs} +5 -2
  19. package/dist/sqlite-wasm-BhRD8n56.mjs.map +1 -0
  20. package/dist/{system-metadata-merge-BY7ebqnp.d.mts → system-metadata-merge-CKMMBV4p.d.mts} +2 -2
  21. package/dist/{system-metadata-merge-BY7ebqnp.d.mts.map → system-metadata-merge-CKMMBV4p.d.mts.map} +1 -1
  22. package/dist/{system-metadata-merge-CVa87L1C.mjs → system-metadata-merge-CickEFxi.mjs} +2 -2
  23. package/dist/{system-metadata-merge-CVa87L1C.mjs.map → system-metadata-merge-CickEFxi.mjs.map} +1 -1
  24. package/dist/{temporal-BMFnxGcx.d.mts → temporal-DS4fCGpj.d.mts} +5 -3
  25. package/dist/temporal-DS4fCGpj.d.mts.map +1 -0
  26. package/package.json +1 -1
  27. package/dist/runtime-CUCgAnbo.d.mts.map +0 -1
  28. package/dist/runtime-CrsC-uwG.mjs.map +0 -1
  29. package/dist/sqlite-wasm-BQqcna0d.mjs.map +0 -1
  30. package/dist/temporal-BMFnxGcx.d.mts.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"runtime-CrsC-uwG.mjs","names":["INT64_MIN","INT64_MAX","INT64_MIN","INT64_MAX","asNumber","asInteger","FILTER_OPERATORS","INT64_MIN","INT64_MAX","finiteNumber","boundedInteger","RUNTIME_FILTER_OPERATORS","uuid"],"sources":["../src/connection-port.ts","../src/canonical-conversion.ts","../src/column-stats.ts","../src/constants.ts","../src/field-query-capabilities.ts","../src/formula.ts","../src/lookup.ts","../src/query.ts","../src/protocol-types.ts","../src/relation-values.ts","../src/formula-functions.ts","../src/lookup-functions.ts","../src/schema.ts","../src/stable-row-scan.ts","../src/dependency-graph.ts","../src/validation.ts","../src/runtime.ts"],"sourcesContent":["import type {\n AdapterError,\n AdapterErrorCode,\n ConnectionPort,\n SqlValue,\n} from \"./adapter-contract\"\nimport type { EidosFileConnection, EidosFileSqlPrimitive } from \"./connection\"\n\nconst INT64_MIN = -9_223_372_036_854_775_808n\nconst INT64_MAX = 9_223_372_036_854_775_807n\n\n/** Validates the exact `?1` through `?N` EA-Connection binding grammar. */\nexport function exactConnectionBindingCount(sql: string): number {\n const occurrences = new Map<number, number>()\n const skipQuoted = (start: number, terminator: string): number => {\n for (let index = start + 1; index < sql.length; index += 1) {\n if (sql[index] !== terminator) continue\n if (terminator !== \"]\" && sql[index + 1] === terminator) {\n index += 1\n continue\n }\n return index\n }\n return sql.length\n }\n for (let index = 0; index < sql.length; index += 1) {\n const character = sql[index]!\n if (character === \"'\" || character === '\"' || character === \"`\") {\n index = skipQuoted(index, character)\n continue\n }\n if (character === \"[\") {\n index = skipQuoted(index, \"]\")\n continue\n }\n if (character === \"-\" && sql[index + 1] === \"-\") {\n while (index < sql.length && sql[index] !== \"\\n\") index += 1\n continue\n }\n if (character === \"/\" && sql[index + 1] === \"*\") {\n index += 2\n while (\n index < sql.length &&\n !(sql[index] === \"*\" && sql[index + 1] === \"/\")\n )\n index += 1\n index += 1\n continue\n }\n if (character === \":\" || character === \"@\" || character === \"$\") {\n throw new EidosAdapterError(\n \"invalid-argument\",\n \"ConnectionPort forbids named SQL parameters\"\n )\n }\n if (character !== \"?\") continue\n let end = index + 1\n while (end < sql.length && /[0-9]/.test(sql[end]!)) end += 1\n const token = sql.slice(index + 1, end)\n if (!/^[1-9][0-9]*$/.test(token)) {\n throw new EidosAdapterError(\n \"invalid-argument\",\n \"ConnectionPort parameters must use canonical ?1 through ?N tokens\"\n )\n }\n const parameter = Number(token)\n if (!Number.isSafeInteger(parameter)) {\n throw new EidosAdapterError(\n \"invalid-argument\",\n \"ConnectionPort parameter index is out of range\"\n )\n }\n occurrences.set(parameter, (occurrences.get(parameter) ?? 0) + 1)\n index = end - 1\n }\n const count = occurrences.size\n for (let parameter = 1; parameter <= count; parameter += 1) {\n if (occurrences.get(parameter) !== 1) {\n throw new EidosAdapterError(\n \"invalid-argument\",\n \"ConnectionPort requires each parameter ?1 through ?N exactly once\"\n )\n }\n }\n return count\n}\n\nexport function assertExactConnectionBindings(\n sql: string,\n bindings: readonly SqlValue[]\n): void {\n const count = exactConnectionBindingCount(sql)\n if (count !== bindings.length) {\n throw new EidosAdapterError(\n \"invalid-argument\",\n `Statement requires ${count} bindings, received ${bindings.length}`\n )\n }\n}\n\nfunction canonicalizeLegacyConnectionSql(sql: string): string {\n let result = \"\"\n let parameter = 0\n for (let index = 0; index < sql.length; index += 1) {\n const character = sql[index]!\n result += character\n if (character === \"'\" || character === '\"' || character === \"`\") {\n for (index += 1; index < sql.length; index += 1) {\n result += sql[index]!\n if (sql[index] !== character) continue\n if (sql[index + 1] === character) {\n result += sql[++index]!\n continue\n }\n break\n }\n continue\n }\n if (character === \"[\") {\n for (index += 1; index < sql.length; index += 1) {\n result += sql[index]!\n if (sql[index] === \"]\") break\n }\n continue\n }\n if (character === \"-\" && sql[index + 1] === \"-\") {\n while (++index < sql.length) {\n result += sql[index]!\n if (sql[index] === \"\\n\") break\n }\n continue\n }\n if (character === \"/\" && sql[index + 1] === \"*\") {\n result += sql[++index]!\n while (++index < sql.length) {\n result += sql[index]!\n if (sql[index] === \"*\" && sql[index + 1] === \"/\") {\n result += sql[++index]!\n break\n }\n }\n continue\n }\n if (character === \"?\") {\n if (/[0-9]/.test(sql[index + 1] ?? \"\")) {\n throw new EidosAdapterError(\n \"invalid-argument\",\n \"Legacy Runtime SQL cannot mix numbered parameters\"\n )\n }\n result += String(++parameter)\n }\n }\n return result\n}\n\nexport class EidosAdapterError extends Error implements AdapterError {\n readonly name = \"EidosAdapterError\"\n\n constructor(\n readonly code: AdapterErrorCode,\n message: string,\n readonly retryable = false,\n readonly fatal = false,\n readonly sqlitePrimaryCode?: number,\n readonly sqliteExtendedCode?: number\n ) {\n super(message)\n }\n}\n\nexport function assertInt64Decimal(value: string): bigint {\n if (!/^(?:0|-[1-9][0-9]*|[1-9][0-9]*)$/.test(value) || value === \"-0\") {\n throw new EidosAdapterError(\n \"invalid-sql-value\",\n \"INTEGER must use canonical signed int64 decimal text\"\n )\n }\n const parsed = BigInt(value)\n if (parsed < INT64_MIN || parsed > INT64_MAX) {\n throw new EidosAdapterError(\n \"invalid-sql-value\",\n \"INTEGER is outside signed int64 range\"\n )\n }\n return parsed\n}\n\nexport function assertUnicodeString(value: string, label = \"TEXT\"): string {\n if (\n /[\\uD800-\\uDFFF]/u.test(\n Array.from(value)\n .filter((part) => part.length === 1)\n .join(\"\")\n )\n ) {\n throw new EidosAdapterError(\n \"invalid-sql-value\",\n label + \" contains an unpaired surrogate\"\n )\n }\n return value\n}\n\nexport function sqlValueToNative(value: SqlValue): EidosFileSqlPrimitive {\n switch (value.tag) {\n case \"null\":\n return null\n case \"integer\":\n return assertInt64Decimal(value.value)\n case \"real\":\n if (!Number.isFinite(value.value)) {\n throw new EidosAdapterError(\n \"invalid-sql-value\",\n \"REAL must be finite binary64\"\n )\n }\n return Object.is(value.value, -0) ? 0 : value.value\n case \"text\":\n return assertUnicodeString(value.value)\n case \"blob\":\n return value.value.slice()\n }\n}\n\nexport function nativeToSqlValue(value: unknown): SqlValue {\n if (value === null) return { tag: \"null\" }\n if (typeof value === \"bigint\") {\n if (value < INT64_MIN || value > INT64_MAX) {\n throw new EidosAdapterError(\n \"invalid-sql-value\",\n \"SQLite returned an INTEGER outside signed int64 range\",\n false,\n true\n )\n }\n return { tag: \"integer\", value: String(value) }\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new EidosAdapterError(\n \"invalid-sql-value\",\n \"SQLite returned a non-finite REAL\",\n false,\n true\n )\n }\n return { tag: \"real\", value: Object.is(value, -0) ? 0 : value }\n }\n if (typeof value === \"string\") {\n return { tag: \"text\", value: assertUnicodeString(value) }\n }\n if (\n ArrayBuffer.isView(value) &&\n Object.prototype.toString.call(value) === \"[object Uint8Array]\"\n ) {\n // Buffer overrides Uint8Array#slice() to return another Buffer. Copy via\n // a fresh Uint8Array so every Adapter binding publishes the exact\n // cross-host ABI, including when Electron supplies a foreign-realm Buffer.\n const view = value as ArrayBufferView\n const bytes = new Uint8Array(view.byteLength)\n bytes.set(new Uint8Array(view.buffer, view.byteOffset, view.byteLength))\n return { tag: \"blob\", value: bytes }\n }\n if (Object.prototype.toString.call(value) === \"[object ArrayBuffer]\") {\n const source = new Uint8Array(value as ArrayBuffer)\n return { tag: \"blob\", value: new Uint8Array(source) }\n }\n throw new EidosAdapterError(\n \"invalid-sql-value\",\n \"Unsupported SQLite storage value: \" + typeof value,\n false,\n true\n )\n}\n\n/**\n * Compatibility bridge for the pre-1.0 synchronous engine. New Adapter code\n * exposes ConnectionPort; this bridge is kept inside Runtime composition and\n * is never handed to UI/application code.\n */\nexport class ConnectionPortEidosFileConnection implements EidosFileConnection {\n readonly capabilities\n\n constructor(readonly port: ConnectionPort) {\n const capabilities = port.capabilities()\n this.capabilities = {\n int64: capabilities.int64,\n json1: capabilities.json1,\n returning: capabilities.returning,\n interrupt: capabilities.interrupt,\n scalarFunctions: capabilities.scalarFunctions,\n }\n }\n\n exec(sql: string): void {\n // ConnectionPort adapters establish mandatory connection PRAGMAs before\n // Runtime composition. The compatibility core repeats the same setup in\n // its constructor; suppress only that exact, idempotent initialization so\n // Runtime.open can compose over a genuinely read-only Adapter connection.\n if (\n sql.trim() === \"PRAGMA foreign_keys = ON; PRAGMA trusted_schema = OFF;\"\n ) {\n return\n }\n this.port.execSchema(sql)\n }\n\n query<T extends object>(\n sql: string,\n params: readonly EidosFileSqlPrimitive[] = []\n ): T[] {\n const result = this.port.query(\n canonicalizeLegacyConnectionSql(sql),\n params.map(nativeParameterToSqlValue)\n )\n return result.rows.map((row) =>\n Object.fromEntries(\n row.map((value, index) => [\n result.columns[index]!.name,\n sqlValueToLegacy(value),\n ])\n )\n ) as T[]\n }\n\n get<T extends object>(\n sql: string,\n params: readonly EidosFileSqlPrimitive[] = []\n ): T | undefined {\n const result = this.port.get(\n canonicalizeLegacyConnectionSql(sql),\n params.map(nativeParameterToSqlValue)\n )\n if (!result.row) return undefined\n return Object.fromEntries(\n result.row.map((value, index) => [\n result.columns[index]!.name,\n sqlValueToLegacy(value),\n ])\n ) as T\n }\n\n run(sql: string, params: readonly EidosFileSqlPrimitive[] = []) {\n const result = this.port.run(\n canonicalizeLegacyConnectionSql(sql),\n params.map(nativeParameterToSqlValue)\n )\n return {\n changes: Number(assertInt64Decimal(result.changes)),\n lastInsertRowid: assertInt64Decimal(result.lastInsertRowid),\n }\n }\n\n runMany(\n sql: string,\n parameterSets: readonly (readonly EidosFileSqlPrimitive[])[]\n ): void {\n this.port.runMany(\n canonicalizeLegacyConnectionSql(sql),\n parameterSets.map((params) => params.map(nativeParameterToSqlValue))\n )\n }\n\n registerFunction(\n name: string,\n operation: (...values: EidosFileSqlPrimitive[]) => EidosFileSqlPrimitive,\n arity = operation.length\n ): void {\n this.port.registerScalar(\n { name, arity, deterministic: true, directOnly: true },\n (...values) =>\n nativeToSqlValue(operation(...values.map(sqlValueToLegacy)))\n )\n }\n\n transaction<T>(operation: () => T): T {\n return this.port.transaction(\"write\", operation)\n }\n\n dataVersion(): number {\n const token = this.port.dataVersion()\n let hash = 2_166_136_261\n for (const character of token) {\n hash ^= character.codePointAt(0) ?? 0\n hash = Math.imul(hash, 16_777_619)\n }\n return hash >>> 0\n }\n\n interrupt(): void {\n this.port.interrupt()\n }\n\n close(): void {\n this.port.close()\n }\n}\n\nfunction nativeParameterToSqlValue(value: EidosFileSqlPrimitive): SqlValue {\n if (value === null) return { tag: \"null\" }\n if (typeof value === \"bigint\") return { tag: \"integer\", value: String(value) }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new EidosAdapterError(\n \"invalid-sql-value\",\n \"SQL number must be finite\"\n )\n }\n return Number.isSafeInteger(value)\n ? { tag: \"integer\", value: String(value) }\n : { tag: \"real\", value }\n }\n if (typeof value === \"string\") return { tag: \"text\", value }\n return { tag: \"blob\", value: value.slice() }\n}\n\nfunction sqlValueToLegacy(value: SqlValue): EidosFileSqlPrimitive {\n switch (value.tag) {\n case \"null\":\n return null\n case \"integer\": {\n const integer = assertInt64Decimal(value.value)\n return integer >= BigInt(Number.MIN_SAFE_INTEGER) &&\n integer <= BigInt(Number.MAX_SAFE_INTEGER)\n ? Number(integer)\n : integer\n }\n case \"real\":\n return value.value\n case \"text\":\n return value.value\n case \"blob\":\n return value.value.slice()\n }\n}\n","import {\n canonicalizeEidosFileJson,\n isCanonicalEidosFileJson,\n parseEidosFileJson,\n} from \"./canonical-json\"\nimport type { EidosFileSqlPrimitive } from \"./connection\"\nimport { decodeEidosFileValues } from \"./file-values\"\nimport { isEidosFileUuid } from \"./identifiers\"\nimport type {\n ConversionPolicy,\n SchemaValueChangeCode,\n StoredFieldType,\n} from \"./runtime-contract\"\nimport {\n isCanonicalEidosFileDate,\n isCanonicalEidosFileInstant,\n} from \"./temporal\"\n\nexport type CanonicalConversionClassification =\n | \"metadata-only\"\n | \"lossless-rewrite\"\n | \"explicit-lossy\"\n | \"forbidden\"\n\nexport interface CanonicalConversionRow {\n id: string\n value: EidosFileSqlPrimitive\n}\n\nexport interface CanonicalConvertedRow extends CanonicalConversionRow {\n changed: boolean\n}\n\nexport interface CanonicalConversionPlan {\n classification: CanonicalConversionClassification\n rows: CanonicalConvertedRow[]\n affectedRows: string\n valueChanges: Array<{ code: SchemaValueChangeCode; rows: string }>\n error?: string\n}\n\nexport interface CanonicalConversionInput {\n from: StoredFieldType\n to: StoredFieldType\n toNullable: boolean\n policies?: readonly ConversionPolicy[]\n rows: readonly CanonicalConversionRow[]\n relationIdValid?: (id: string) => boolean\n relationCardinality?: \"one\" | \"many\"\n}\n\ntype Converted = {\n value: EidosFileSqlPrimitive\n class: 0 | 1 | 2\n code?: SchemaValueChangeCode\n}\n\n/**\n * Product defaults for conversions requested by the Eidos File editor.\n *\n * These policies are intentionally explicit: the Runtime still reports an\n * `explicit-lossy` preflight and requires confirmation whenever the values in\n * the current Field would actually lose information.\n */\nexport function recommendedEidosFileConversionPolicies(\n from: StoredFieldType,\n to: StoredFieldType\n): ConversionPolicy[] {\n const policies: ConversionPolicy[] = []\n if (from === \"integer\" && to === \"number\") {\n policies.push(\"round-binary64\")\n }\n if (from === \"number\" && to === \"integer\") {\n policies.push(\"round-ties-even\")\n }\n if ((from === \"integer\" || from === \"number\") && to === \"checkbox\") {\n policies.push(\"zero-false-nonzero-true\")\n }\n if (from === \"datetime\" && to === \"date\") policies.push(\"utc-date\")\n if (from === \"multi-select\" && to === \"select\") policies.push(\"first\")\n if (!LIST_TYPES.has(from) && LIST_TYPES.has(to)) {\n policies.push(\"null-to-empty-list\")\n }\n return policies\n}\n\n/** Returns the nullable shape used by editor-initiated conversions. */\nexport function eidosFileConversionTargetNullable(\n from: StoredFieldType,\n to: StoredFieldType,\n sourceNullable: boolean\n): boolean {\n // List and forward-Relation destinations are structurally non-null and\n // encode empty as [] rather than SQL NULL.\n if (LIST_TYPES.has(to)) return false\n // List and Relation sources are non-null for the same structural reason, not\n // because the user asked for a required Field. A scalar destination encodes\n // empty as SQL NULL, so grant it SQL NULL; otherwise a converted cell could\n // never be cleared.\n if (LIST_TYPES.has(from)) return true\n return sourceNullable\n}\n\n/**\n * Splits a Text value into Multi-select option names using the Runtime rule.\n *\n * A JSON array of strings is read as its ordered choice names; any other text\n * (including malformed JSON, non-string arrays, or commas) is one choice. The\n * Editor reuses this so inferred Field options match converted cell values.\n */\nexport function eidosFileTextMultiSelectChoices(text: string): string[] {\n try {\n const parsed: unknown = JSON.parse(text)\n if (\n Array.isArray(parsed) &&\n parsed.every((item) => typeof item === \"string\")\n ) {\n return parsed\n }\n } catch {\n // Ordinary text remains one choice, including commas and brackets.\n }\n return [text]\n}\n\nconst INT64_MIN = -9_223_372_036_854_775_808n\nconst INT64_MAX = 9_223_372_036_854_775_807n\nconst INT64 = /^(?:0|-[1-9][0-9]*|[1-9][0-9]*)$/u\nconst LIST_TYPES = new Set<StoredFieldType>([\n \"multi-select\",\n \"file\",\n \"relation\",\n])\nconst TEXT_TYPES = new Set<StoredFieldType>([\n \"text\",\n \"date\",\n \"datetime\",\n \"url\",\n \"select\",\n])\nconst SHARED_TEXT_COLUMN_TYPES = new Set<StoredFieldType>([\n \"text\",\n \"select\",\n \"url\",\n])\n\n/** True when a conversion can retain the exact nullable SQLite column DDL. */\nexport function eidosFileConversionCanReusePhysicalColumn(\n from: StoredFieldType,\n to: StoredFieldType,\n sourceNullable: boolean,\n targetNullable: boolean\n): boolean {\n return (\n sourceNullable === targetNullable &&\n SHARED_TEXT_COLUMN_TYPES.has(from) &&\n SHARED_TEXT_COLUMN_TYPES.has(to)\n )\n}\n\nexport function planCanonicalFieldConversion(\n input: CanonicalConversionInput\n): CanonicalConversionPlan {\n const policies = new Set(input.policies ?? [])\n const sourceHasEmptyList = input.rows.some((row) => {\n if (row.value === null || typeof row.value !== \"string\") return false\n return row.value === \"[]\"\n })\n const changes = new Map<SchemaValueChangeCode, number>()\n const rows: CanonicalConvertedRow[] = []\n let severity: 0 | 1 | 2 | 3 = 0\n let error: string | undefined\n\n for (const row of input.rows) {\n try {\n let converted: Converted\n if (row.value === null) {\n converted = convertNull(input, policies, sourceHasEmptyList)\n } else {\n converted = convertNonNull(input, row.value, policies)\n }\n if (\n converted.value === null &&\n !input.toNullable &&\n !LIST_TYPES.has(input.to)\n ) {\n throw new Error(\"Destination non-nullability rejects SQL NULL\")\n }\n validateDestination(input, converted.value)\n const changed =\n storageClass(input.from) !== storageClass(input.to) ||\n !sameStorageValue(row.value, converted.value)\n rows.push({ id: row.id, value: converted.value, changed })\n if (changed) {\n severity = Math.max(severity, converted.class) as 0 | 1 | 2 | 3\n changes.set(\n \"value-reencoded\",\n (changes.get(\"value-reencoded\") ?? 0) + 1\n )\n if (converted.code) {\n changes.set(converted.code, (changes.get(converted.code) ?? 0) + 1)\n }\n }\n } catch (cause) {\n severity = 3\n error = cause instanceof Error ? cause.message : \"Conversion is forbidden\"\n break\n }\n }\n\n if (severity === 3) {\n return {\n classification: \"forbidden\",\n rows: [],\n affectedRows: \"0\",\n valueChanges: [],\n error,\n }\n }\n const affectedRows = rows.filter((row) => row.changed).length\n return {\n classification:\n severity === 2\n ? \"explicit-lossy\"\n : severity === 1\n ? \"lossless-rewrite\"\n : \"metadata-only\",\n rows,\n affectedRows: String(affectedRows),\n valueChanges: Array.from(changes, ([code, count]) => ({\n code,\n rows: String(count),\n })),\n }\n}\n\nfunction convertNull(\n input: CanonicalConversionInput,\n policies: ReadonlySet<ConversionPolicy>,\n sourceHasEmptyList: boolean\n): Converted {\n if (LIST_TYPES.has(input.to)) {\n if (!policies.has(\"null-to-empty-list\")) {\n throw new Error(\n \"SQL NULL requires null-to-empty-list for a list destination\"\n )\n }\n return {\n value: \"[]\",\n class: sourceHasEmptyList ? 2 : 1,\n code: \"null-to-empty-list\",\n }\n }\n if (!input.toNullable) {\n throw new Error(\"Destination non-nullability rejects SQL NULL\")\n }\n return { value: null, class: 0 }\n}\n\nfunction convertNonNull(\n input: CanonicalConversionInput,\n value: Exclude<EidosFileSqlPrimitive, null>,\n policies: ReadonlySet<ConversionPolicy>\n): Converted {\n const { from, to } = input\n if (from === to) return { value, class: 0 }\n\n if (TEXT_TYPES.has(from) && TEXT_TYPES.has(to)) {\n if (to === \"datetime\" && from === \"date\") {\n return { value: `${asText(value)}T00:00:00.000Z`, class: 1 }\n }\n if (to === \"date\" && from === \"datetime\") {\n const text = asText(value)\n if (text.endsWith(\"T00:00:00.000Z\")) {\n return { value: text.slice(0, 10), class: 1 }\n }\n if (!policies.has(\"utc-date\")) {\n throw new Error(\"Datetime with a time component requires utc-date\")\n }\n return { value: text.slice(0, 10), class: 2, code: \"datetime-to-date\" }\n }\n return { value: asText(value), class: 0 }\n }\n\n if (to === \"text\") {\n if (from === \"number\")\n return { value: canonicalNumber(asNumber(value)), class: 1 }\n if (from === \"integer\") return { value: String(asInteger(value)), class: 1 }\n if (from === \"checkbox\")\n return { value: asCheckbox(value) ? \"true\" : \"false\", class: 1 }\n if (LIST_TYPES.has(from)) return { value: asText(value), class: 0 }\n }\n\n if (to === \"select\") {\n if (from === \"number\")\n return { value: canonicalNumber(asNumber(value)), class: 1 }\n if (from === \"integer\") return { value: String(asInteger(value)), class: 1 }\n if (from === \"checkbox\")\n return { value: asCheckbox(value) ? \"true\" : \"false\", class: 1 }\n if (from === \"multi-select\") {\n const list = parseStringList(value)\n if (list.length === 1) return { value: list[0]!, class: 1 }\n if (!policies.has(\"first\")) {\n throw new Error(\"Multi-select to Select requires a singleton or first\")\n }\n if (list.length === 0) {\n if (!input.toNullable)\n throw new Error(\"Empty list requires nullable Select\")\n return { value: null, class: 1, code: \"list-empty-to-null\" }\n }\n return { value: list[0]!, class: 2, code: \"list-tail-dropped\" }\n }\n }\n\n if (to === \"number\") {\n if (from === \"integer\") {\n const integer = asInteger(value)\n const number = Number(integer)\n if (Number.isInteger(number) && BigInt(number) === integer) {\n return { value: number, class: 1 }\n }\n if (!policies.has(\"round-binary64\") || !Number.isFinite(number)) {\n throw new Error(\"Integer is not exactly representable as binary64\")\n }\n return { value: number, class: 2, code: \"binary64-rounded\" }\n }\n if (from === \"checkbox\")\n return { value: asCheckbox(value) ? 1 : 0, class: 1 }\n if (from === \"text\" || from === \"select\") {\n const text = asText(value)\n const number = Number(text)\n if (!Number.isFinite(number) || canonicalNumber(number) !== text) {\n throw new Error(\"Text is not the exact inverse binary64 spelling\")\n }\n return { value: number, class: 1 }\n }\n }\n\n if (to === \"integer\") {\n if (from === \"checkbox\")\n return { value: asCheckbox(value) ? 1n : 0n, class: 0 }\n if (from === \"text\" || from === \"select\") {\n return { value: parseInt64(asText(value)), class: 1 }\n }\n if (from === \"number\") return numberToInteger(asNumber(value), policies)\n }\n\n if (to === \"checkbox\") {\n if (from === \"text\" || from === \"select\") {\n const text = asText(value)\n if (text === \"true\") return { value: 1n, class: 1 }\n if (text === \"false\") return { value: 0n, class: 1 }\n throw new Error(\"Text is not lowercase true or false\")\n }\n if (from === \"integer\") {\n const integer = asInteger(value)\n if (integer === 0n || integer === 1n) return { value: integer, class: 0 }\n if (!policies.has(\"zero-false-nonzero-true\")) {\n throw new Error(\"Integer Checkbox conversion requires exact 0/1\")\n }\n return {\n value: integer === 0n ? 0n : 1n,\n class: 2,\n code: \"numeric-to-checkbox\",\n }\n }\n if (from === \"number\") {\n const number = asNumber(value)\n if (number === 0 || number === 1)\n return { value: BigInt(number), class: 1 }\n if (!policies.has(\"zero-false-nonzero-true\")) {\n throw new Error(\"Number Checkbox conversion requires exact 0.0/1.0\")\n }\n return {\n value: number === 0 ? 0n : 1n,\n class: 2,\n code: \"numeric-to-checkbox\",\n }\n }\n }\n\n if (LIST_TYPES.has(to)) {\n if (from === \"select\" && to === \"multi-select\") {\n return { value: canonicalizeEidosFileJson([asText(value)]), class: 1 }\n }\n if (from === \"text\" && to === \"multi-select\") {\n const text = asText(value)\n // Destination validation still rejects duplicate option names.\n const encoded = canonicalizeEidosFileJson(\n eidosFileTextMultiSelectChoices(text)\n )\n return { value: encoded, class: encoded === text ? 0 : 1 }\n }\n if (\n (from === \"multi-select\" && to === \"relation\") ||\n (from === \"relation\" && to === \"multi-select\") ||\n from === to\n ) {\n return { value: asText(value), class: 0 }\n }\n }\n\n throw new Error(`Conversion from ${from} to ${to} is forbidden`)\n}\n\nfunction numberToInteger(\n number: number,\n policies: ReadonlySet<ConversionPolicy>\n): Converted {\n let result = number\n let code: SchemaValueChangeCode | undefined\n let classification: 1 | 2 = 1\n if (!Number.isInteger(result)) {\n if (policies.has(\"truncate-toward-zero\")) {\n result = Math.trunc(result)\n code = \"fraction-truncated\"\n } else if (policies.has(\"round-ties-even\")) {\n result = roundTiesEven(result)\n code = \"integer-rounded\"\n } else {\n throw new Error(\"Fractional Number requires an Integer rounding policy\")\n }\n classification = 2\n }\n if (!Number.isInteger(result)) {\n throw new Error(\"Integer result is not integral\")\n }\n const integer = BigInt(result)\n if (integer < INT64_MIN || integer > INT64_MAX) {\n throw new Error(\"Integer result is outside signed int64\")\n }\n return { value: integer, class: classification, ...(code ? { code } : {}) }\n}\n\nfunction validateDestination(\n input: CanonicalConversionInput,\n value: EidosFileSqlPrimitive\n): void {\n if (value === null) return\n switch (input.to) {\n case \"number\":\n asNumber(value)\n return\n case \"integer\":\n asInteger(value)\n return\n case \"checkbox\":\n asCheckbox(value)\n return\n case \"date\":\n if (!isCanonicalEidosFileDate(value))\n throw new Error(\"Invalid Date value\")\n return\n case \"datetime\":\n if (!isCanonicalEidosFileInstant(value))\n throw new Error(\"Invalid Datetime value\")\n return\n case \"url\":\n if (!isEidosFileUriReference(asText(value)))\n throw new Error(\"Invalid URI-reference\")\n return\n case \"multi-select\":\n parseStringList(value)\n return\n case \"file\": {\n decodeEidosFileValues(asText(value))\n return\n }\n case \"relation\": {\n const ids = parseStringList(value)\n if (!ids.every(isEidosFileUuid))\n throw new Error(\"Invalid Relation Row ID\")\n if (input.relationCardinality === \"one\" && ids.length > 1) {\n throw new Error(\n \"One-cardinality Relation contains more than one Row ID\"\n )\n }\n if (input.relationIdValid && !ids.every(input.relationIdValid)) {\n throw new Error(\"Relation Row ID does not resolve in the target Table\")\n }\n return\n }\n case \"text\":\n case \"select\":\n asText(value)\n return\n }\n}\n\nfunction parseStringList(\n value: Exclude<EidosFileSqlPrimitive, null>\n): string[] {\n const text = asText(value)\n if (!isCanonicalEidosFileJson(text))\n throw new Error(\"List is not canonical JSON\")\n const parsed = parseEidosFileJson(text)\n if (\n !Array.isArray(parsed) ||\n !parsed.every((entry) => typeof entry === \"string\")\n ) {\n throw new Error(\"List must contain only strings\")\n }\n if (new Set(parsed).size !== parsed.length) {\n throw new Error(\"List values must be unique\")\n }\n return parsed\n}\n\nfunction asText(value: Exclude<EidosFileSqlPrimitive, null>): string {\n if (typeof value !== \"string\") throw new Error(\"Expected TEXT storage\")\n return value\n}\n\nfunction asNumber(value: Exclude<EidosFileSqlPrimitive, null>): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new Error(\"Expected finite REAL storage\")\n }\n return Object.is(value, -0) ? 0 : value\n}\n\nfunction asInteger(value: Exclude<EidosFileSqlPrimitive, null>): bigint {\n if (typeof value === \"bigint\") {\n if (value < INT64_MIN || value > INT64_MAX)\n throw new Error(\"INTEGER outside int64\")\n return value\n }\n if (typeof value !== \"number\" || !Number.isSafeInteger(value)) {\n throw new Error(\"Expected exact INTEGER storage\")\n }\n return BigInt(value)\n}\n\nfunction asCheckbox(value: Exclude<EidosFileSqlPrimitive, null>): boolean {\n const integer = asInteger(value)\n if (integer !== 0n && integer !== 1n)\n throw new Error(\"Checkbox must be 0 or 1\")\n return integer === 1n\n}\n\nfunction parseInt64(value: string): bigint {\n if (!INT64.test(value) || value === \"-0\")\n throw new Error(\"Invalid int64 spelling\")\n const integer = BigInt(value)\n if (integer < INT64_MIN || integer > INT64_MAX)\n throw new Error(\"INTEGER outside int64\")\n return integer\n}\n\nfunction canonicalNumber(value: number): string {\n return canonicalizeEidosFileJson(value)\n}\n\nfunction roundTiesEven(value: number): number {\n const floor = Math.floor(value)\n const fraction = value - floor\n if (fraction < 0.5) return floor\n if (fraction > 0.5) return floor + 1\n return floor % 2 === 0 ? floor : floor + 1\n}\n\n/** RFC 3986 URI-reference lexical validation shared by writes and conversions. */\nexport function isEidosFileUriReference(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n /^(?:[A-Za-z0-9\\-._~!$&'()*+,;=:@/?#\\[\\]]|%[0-9A-Fa-f]{2})*$/u.test(value)\n )\n}\n\nfunction sameStorageValue(\n left: EidosFileSqlPrimitive,\n right: EidosFileSqlPrimitive\n): boolean {\n if (left instanceof Uint8Array || right instanceof Uint8Array) {\n return (\n left instanceof Uint8Array &&\n right instanceof Uint8Array &&\n left.byteLength === right.byteLength &&\n left.every((byte, index) => byte === right[index])\n )\n }\n if (\n (typeof left === \"bigint\" ||\n (typeof left === \"number\" && Number.isSafeInteger(left))) &&\n (typeof right === \"bigint\" ||\n (typeof right === \"number\" && Number.isSafeInteger(right)))\n ) {\n return BigInt(left) === BigInt(right)\n }\n return typeof left === typeof right && Object.is(left, right)\n}\n\nfunction storageClass(type: StoredFieldType): \"integer\" | \"real\" | \"text\" {\n if (type === \"integer\" || type === \"checkbox\") return \"integer\"\n if (type === \"number\") return \"real\"\n return \"text\"\n}\n","import { EidosFileError } from \"./errors\"\nimport { quoteIdentifier } from \"./identifiers\"\nimport type {\n EidosFileColumnStatConfig,\n EidosFileColumnStatType,\n EidosFileFieldInfo,\n} from \"./types\"\n\nconst COMMON_STATS: readonly EidosFileColumnStatType[] = [\n \"count-all\",\n \"count-non-null\",\n \"count-distinct\",\n \"count-empty\",\n]\n\nconst NUMERIC_STATS: readonly EidosFileColumnStatType[] = [\n ...COMMON_STATS,\n \"sum\",\n \"average\",\n \"min\",\n \"max\",\n]\n\nconst DATE_STATS: readonly EidosFileColumnStatType[] = [\n ...COMMON_STATS,\n \"min\",\n \"max\",\n]\n\nconst CHECKBOX_STATS: readonly EidosFileColumnStatType[] = [\n ...COMMON_STATS,\n \"percent-checked\",\n \"percent-unchecked\",\n]\n\nconst MULTI_VALUE_STATS: readonly EidosFileColumnStatType[] = [...COMMON_STATS]\n\nconst RELATION_STATS: readonly EidosFileColumnStatType[] = [\n ...MULTI_VALUE_STATS,\n \"relation-value-count\",\n \"relation-row-count\",\n \"relation-distinct-target-count\",\n]\n\nconst LABELS: Record<EidosFileColumnStatType, string> = {\n \"count-all\": \"Count all\",\n \"count-non-null\": \"Count non-null\",\n \"count-distinct\": \"Count distinct\",\n \"count-empty\": \"Count empty\",\n \"percent-checked\": \"Percent checked\",\n \"percent-unchecked\": \"Percent unchecked\",\n sum: \"Sum\",\n average: \"Average\",\n min: \"Minimum\",\n max: \"Maximum\",\n \"relation-value-count\": \"Relation value count\",\n \"relation-row-count\": \"Relation row count\",\n \"relation-distinct-target-count\": \"Distinct Relation targets\",\n}\n\nfunction displayType(\n field: EidosFileFieldInfo\n): EidosFileFieldInfo[\"type\"] | string {\n if (\n (field.type === \"formula\" || field.type === \"lookup\") &&\n typeof field.property?.displayType === \"string\"\n ) {\n return field.property.displayType\n }\n return field.type\n}\n\nexport function eidosFileColumnStatTypesForField(\n field: EidosFileFieldInfo\n): readonly EidosFileColumnStatType[] {\n const type = displayType(field)\n if (type === \"number\" || type === \"integer\" || type === \"rating\") {\n return NUMERIC_STATS\n }\n if (\n type === \"date\" ||\n type === \"datetime\" ||\n type === \"created-time\" ||\n type === \"last-edited-time\"\n ) {\n return DATE_STATS\n }\n if (type === \"checkbox\") return CHECKBOX_STATS\n if (type === \"relation\") return RELATION_STATS\n if (type === \"file\" || type === \"multi-select\") {\n return MULTI_VALUE_STATS\n }\n return COMMON_STATS\n}\n\nexport function eidosFileColumnStatLabel(\n type: EidosFileColumnStatType\n): string {\n return LABELS[type]\n}\n\nexport function normalizeEidosFileColumnStatConfigs(\n value: unknown,\n fields: EidosFileFieldInfo[]\n): EidosFileColumnStatConfig[] {\n if (!Array.isArray(value)) {\n throw new EidosFileError(\n \"invalid-query\",\n \"Eidos File column stats must be an array\"\n )\n }\n if (value.length > 64) {\n throw new EidosFileError(\n \"invalid-query\",\n \"Eidos File column stats cannot contain more than 64 calculations\"\n )\n }\n const byId = new Map(\n fields.flatMap((field) => (field.id ? [[field.id, field]] : []))\n )\n return value.map((entry) => {\n if (\n typeof entry !== \"object\" ||\n entry === null ||\n typeof (entry as { fieldId?: unknown }).fieldId !== \"string\" ||\n typeof (entry as { type?: unknown }).type !== \"string\"\n ) {\n throw new EidosFileError(\n \"invalid-query\",\n \"Invalid Eidos File column stat\"\n )\n }\n const config = entry as EidosFileColumnStatConfig\n const field = byId.get(config.fieldId)\n if (!field) {\n throw new EidosFileError(\n \"field-not-found\",\n `Eidos File field not found: ${config.fieldId}`\n )\n }\n if (!eidosFileColumnStatTypesForField(field).includes(config.type)) {\n throw new EidosFileError(\n \"invalid-query\",\n `${eidosFileColumnStatLabel(config.type)} is not supported for ${field.name}`\n )\n }\n return { fieldId: field.id!, type: config.type }\n })\n}\n\nexport function compileEidosFileColumnStatExpression(\n field: EidosFileFieldInfo,\n type: EidosFileColumnStatType\n): string {\n const fieldDisplayType = displayType(field)\n const column = quoteIdentifier(field.tableColumnName)\n const isArrayCodec =\n field.storageCodec === \"json_array\" || field.storageCodec === \"relation\"\n const empty = isArrayCodec\n ? `(${column} IS NULL OR (json_valid(${column}) AND json_type(${column}) = 'array' AND json_array_length(${column}) = 0))`\n : `(${column} IS NULL)`\n const present = `NOT ${empty}`\n\n switch (type) {\n case \"count-all\":\n return \"COUNT(*)\"\n case \"count-non-null\":\n return `COUNT(${column})`\n case \"count-distinct\":\n return `COUNT(DISTINCT CASE WHEN ${present} THEN ${column} END)`\n case \"count-empty\":\n return `COUNT(CASE WHEN ${empty} THEN 1 END)`\n case \"percent-checked\":\n return `CASE WHEN COUNT(*) = 0 THEN 0 ELSE ROUND(100.0 * COUNT(CASE WHEN ${column} = 1 THEN 1 END) / COUNT(*), 2) END`\n case \"percent-unchecked\":\n return `CASE WHEN COUNT(*) = 0 THEN 0 ELSE ROUND(100.0 * COUNT(CASE WHEN ${column} = 1 THEN NULL ELSE 1 END) / COUNT(*), 2) END`\n case \"sum\":\n return fieldDisplayType === \"integer\" || fieldDisplayType === \"rating\"\n ? `SUM(CASE WHEN ${present} THEN ${column} END)`\n : `SUM(CASE WHEN ${present} THEN CAST(${column} AS REAL) END)`\n case \"average\":\n return `AVG(CASE WHEN ${present} THEN CAST(${column} AS REAL) END)`\n case \"min\":\n return `MIN(CASE WHEN ${present} THEN ${column} END)`\n case \"max\":\n return `MAX(CASE WHEN ${present} THEN ${column} END)`\n case \"relation-value-count\":\n return `COALESCE(SUM(json_array_length(${column})), 0)`\n case \"relation-row-count\":\n return `COUNT(CASE WHEN json_array_length(${column}) > 0 THEN 1 END)`\n case \"relation-distinct-target-count\":\n return `COUNT(DISTINCT ${column})`\n }\n}\n","/** Eidos File 1.0 application-file identity. */\nexport const EIDOS_FILE_FORMAT = \"eidos-file\" as const\nexport const EIDOS_FILE_FORMAT_VERSION = \"1.0\" as const\nexport const EIDOS_FILE_SCHEMA_VERSION = 1 as const\nexport const EIDOS_FILE_APPLICATION_ID = 0x45494453 as const\nexport const EIDOS_FILE_EXTENSION = \".eidos\" as const\nexport const EIDOS_FILE_MIME_TYPE = \"application/vnd.eidos+sqlite3\" as const\nexport const SQLITE_HEADER = \"SQLite format 3\\u0000\" as const\n\nexport function hasEidosFileSqliteHeader(\n bytes: ArrayBuffer | Uint8Array\n): boolean {\n const source = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)\n if (source.byteLength < SQLITE_HEADER.length) return false\n for (let index = 0; index < SQLITE_HEADER.length; index += 1) {\n if (source[index] !== SQLITE_HEADER.charCodeAt(index)) return false\n }\n return true\n}\n\nexport const EIDOS_FILE_META_TABLE = \"eidos__meta\" as const\nexport const EIDOS_FILE_FEATURES_TABLE = \"eidos__features\" as const\nexport const EIDOS_FILE_TABLES_TABLE = \"eidos__tables\" as const\nexport const EIDOS_FILE_FIELDS_TABLE = \"eidos__fields\" as const\nexport const EIDOS_FILE_RELATION_FIELDS_TABLE =\n \"eidos__relation_fields\" as const\nexport const EIDOS_FILE_FORMULA_FIELDS_TABLE = \"eidos__formula_fields\" as const\nexport const EIDOS_FILE_LOOKUP_FIELDS_TABLE = \"eidos__lookup_fields\" as const\nexport const EIDOS_FILE_VIEWS_TABLE = \"eidos__views\" as const\n\nexport const EIDOS_FILE_REQUIRED_TABLES = [\n EIDOS_FILE_META_TABLE,\n EIDOS_FILE_FEATURES_TABLE,\n EIDOS_FILE_TABLES_TABLE,\n EIDOS_FILE_FIELDS_TABLE,\n EIDOS_FILE_RELATION_FIELDS_TABLE,\n EIDOS_FILE_FORMULA_FIELDS_TABLE,\n EIDOS_FILE_LOOKUP_FIELDS_TABLE,\n EIDOS_FILE_VIEWS_TABLE,\n] as const\n\nexport const EIDOS_FILE_SYSTEM_COLUMNS = [\n \"_id\",\n \"_created_at\",\n \"_updated_at\",\n] as const\n","import type { AtomicType, TypeRef } from \"./runtime-contract\"\nimport type { EidosFileFieldInfo, EidosFileFilterOperator } from \"./types\"\n\nexport type EidosFileSortPosition = \"any\" | \"last\" | null\n\nexport interface EidosFileFieldQueryCapabilities {\n /** Filter operations the shared editor can construct without raw typed data. */\n filterOperators: readonly EidosFileFilterOperator[]\n /** Whether the Runtime can compare values with ordered operators. */\n ordered: boolean\n /** Whether list membership operators are valid for the logical type. */\n membership: boolean\n /** Whether the Runtime can evaluate string-fragment operators. */\n stringMatch: boolean\n /** Whether this type participates in the current Runtime search profile. */\n searchable: boolean\n /** Whether this type can be sorted. */\n sortable: boolean\n /** Row ID is only valid as the terminal explicit sort. */\n sortPosition: EidosFileSortPosition\n /** Whether this type can be used as a Runtime group key. */\n groupable: boolean\n}\n\nconst EMPTY_OPERATORS = [\n \"is-empty\",\n \"is-not-empty\",\n] as const satisfies readonly EidosFileFilterOperator[]\n\nconst EQUALITY_OPERATORS = [\n \"equals\",\n \"not-equals\",\n] as const satisfies readonly EidosFileFilterOperator[]\n\nconst STRING_OPERATORS = [\n ...EQUALITY_OPERATORS,\n \"contains\",\n \"not-contains\",\n \"starts-with\",\n \"ends-with\",\n ...EMPTY_OPERATORS,\n] as const satisfies readonly EidosFileFilterOperator[]\n\nconst ORDERED_OPERATORS = [\n ...EQUALITY_OPERATORS,\n \"greater-than\",\n \"greater-than-or-equal\",\n \"less-than\",\n \"less-than-or-equal\",\n ...EMPTY_OPERATORS,\n] as const satisfies readonly EidosFileFilterOperator[]\n\nconst TEMPORAL_OPERATORS = [\n ...ORDERED_OPERATORS,\n \"is-between\",\n \"is-relative-to-today\",\n] as const satisfies readonly EidosFileFilterOperator[]\n\nconst LIST_OPERATORS = [\n \"contains\",\n \"not-contains\",\n \"is-any-of\",\n \"is-all-of\",\n \"is-none-of\",\n ...EMPTY_OPERATORS,\n] as const satisfies readonly EidosFileFilterOperator[]\n\nconst CHECKBOX_OPERATORS = [\n ...EQUALITY_OPERATORS,\n ...EMPTY_OPERATORS,\n] as const satisfies readonly EidosFileFilterOperator[]\n\nconst FILE_OPERATORS = [\n ...EMPTY_OPERATORS,\n] as const satisfies readonly EidosFileFilterOperator[]\n\nconst TYPE_REF_ATOMS = new Set<string>([\n \"text\",\n \"number\",\n \"integer\",\n \"checkbox\",\n \"date\",\n \"datetime\",\n \"url\",\n \"select\",\n \"multi-select\",\n \"file\",\n \"relation\",\n \"row-id\",\n \"file-entry\",\n])\n\nconst LIST_ATOMS = new Set<string>([\n \"text\",\n \"number\",\n \"integer\",\n \"checkbox\",\n \"date\",\n \"datetime\",\n \"url\",\n \"select\",\n \"row-id\",\n \"file-entry\",\n])\n\nexport function configuredTypeRef(value: unknown): TypeRef | null {\n if (typeof value === \"string\" && TYPE_REF_ATOMS.has(value)) {\n return value as TypeRef\n }\n if (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n (value as { kind?: unknown }).kind === \"list\" &&\n typeof (value as { element?: unknown }).element === \"string\" &&\n LIST_ATOMS.has((value as { element: string }).element)\n ) {\n return {\n kind: \"list\",\n element: (value as { element: AtomicType }).element,\n }\n }\n return null\n}\n\n/** Resolve the public logical TypeRef represented by an editor/runtime Field. */\nexport function eidosFileFieldValueType(\n field: Pick<\n EidosFileFieldInfo,\n \"type\" | \"systemRole\" | \"property\" | \"storageCodec\"\n >\n): TypeRef {\n if (field.systemRole === \"row-id\" || field.type === \"row-id\") {\n return \"row-id\"\n }\n if (\n field.systemRole === \"created-time\" ||\n field.systemRole === \"updated-time\" ||\n field.type === \"created-time\" ||\n field.type === \"last-edited-time\"\n ) {\n return \"datetime\"\n }\n if (field.type === \"rating\") return \"integer\"\n if (field.type === \"formula\" || field.type === \"lookup\") {\n const generated = configuredTypeRef(field.property?.valueType)\n if (generated) return generated\n const legacyFileEntry =\n field.type === \"lookup\" && field.property?.displayType === \"json\"\n const display = configuredTypeRef(field.property?.displayType) ?? \"text\"\n if (field.type === \"lookup\" && field.property?.aggregate === \"values\") {\n const element =\n display === \"file\" || legacyFileEntry\n ? \"file-entry\"\n : display === \"relation\"\n ? \"row-id\"\n : display === \"multi-select\"\n ? \"select\"\n : typeof display === \"object\"\n ? display.element\n : display\n return { kind: \"list\", element: element as AtomicType }\n }\n if (legacyFileEntry) return \"file-entry\"\n return display\n }\n if (field.type === \"relation\") return \"relation\"\n if (field.type === \"multi-select\") return \"multi-select\"\n if (field.type === \"file\") return \"file\"\n return configuredTypeRef(field.type) ?? \"text\"\n}\n\n/**\n * Canonical query capability policy for Runtime validation and UI affordances.\n * It intentionally describes implemented behavior, not SQLite storage classes.\n */\nexport function eidosFileTypeRefQueryCapabilities(\n type: TypeRef,\n context: {\n isRecordLabel?: boolean\n contextualRowId?: boolean\n } = {}\n): EidosFileFieldQueryCapabilities {\n const listElement =\n typeof type === \"object\"\n ? type.element\n : type === \"multi-select\"\n ? \"select\"\n : type === \"relation\"\n ? \"row-id\"\n : type === \"file\"\n ? \"file-entry\"\n : null\n const list = listElement !== null\n const fileValue = type === \"file-entry\" || listElement === \"file-entry\"\n const ordered =\n typeof type === \"string\" &&\n [\n \"text\",\n \"number\",\n \"integer\",\n \"checkbox\",\n \"date\",\n \"datetime\",\n \"url\",\n \"select\",\n \"row-id\",\n ].includes(type)\n const stringMatch =\n typeof type === \"string\" &&\n [\"text\", \"url\", \"select\", \"row-id\"].includes(type)\n const searchableList =\n listElement !== null &&\n [\"text\", \"url\", \"select\", \"file-entry\"].includes(listElement)\n const recordLabelSearchable =\n context.isRecordLabel === true &&\n typeof type === \"string\" &&\n [\n \"text\",\n \"url\",\n \"select\",\n \"number\",\n \"integer\",\n \"checkbox\",\n \"date\",\n \"datetime\",\n \"row-id\",\n ].includes(type)\n const contextualRowId =\n context.contextualRowId === true &&\n typeof type === \"object\" &&\n type.element === \"row-id\"\n const searchable =\n stringMatch ||\n searchableList ||\n type === \"file-entry\" ||\n type === \"relation\" ||\n recordLabelSearchable ||\n contextualRowId\n const sortPosition: EidosFileSortPosition = !ordered\n ? null\n : type === \"row-id\"\n ? \"last\"\n : \"any\"\n\n let filterOperators: readonly EidosFileFilterOperator[]\n if (fileValue) filterOperators = FILE_OPERATORS\n else if (list) filterOperators = LIST_OPERATORS\n else if (type === \"checkbox\") filterOperators = CHECKBOX_OPERATORS\n else if (type === \"date\" || type === \"datetime\") {\n filterOperators = TEMPORAL_OPERATORS\n } else if (type === \"number\" || type === \"integer\") {\n filterOperators = ORDERED_OPERATORS\n } else if (stringMatch) filterOperators = STRING_OPERATORS\n else filterOperators = EMPTY_OPERATORS\n\n return {\n filterOperators,\n ordered,\n membership: list,\n stringMatch,\n searchable,\n sortable: sortPosition !== null,\n sortPosition,\n groupable: ordered,\n }\n}\n\nexport function eidosFileFieldQueryCapabilities(\n field: Pick<\n EidosFileFieldInfo,\n \"type\" | \"systemRole\" | \"property\" | \"storageCodec\" | \"isRecordLabel\"\n >\n): EidosFileFieldQueryCapabilities {\n const type = eidosFileFieldValueType(field)\n const contextualRowIdLookup =\n field.type === \"lookup\" &&\n typeof type === \"object\" &&\n type.element === \"row-id\" &&\n typeof field.property?.relationField === \"string\"\n return eidosFileTypeRefQueryCapabilities(type, {\n isRecordLabel: field.isRecordLabel,\n contextualRowId: contextualRowIdLookup,\n })\n}\n","import { EidosFileError } from \"./errors\"\nimport { quoteIdentifier } from \"./identifiers\"\nimport type { EidosFileConnection } from \"./connection\"\nimport type { EidosFileFieldInfo } from \"./types\"\n\nexport interface EidosFileFormulaReference {\n fieldName: string\n start: number\n end: number\n}\n\nexport interface CompiledEidosFileFormula {\n field: EidosFileFieldInfo\n expression: string\n /** Physical/logical projection aliases retained for query planning. */\n dependencies: string[]\n /** Stable structural dependencies used by the file-wide DAG. */\n dependencyFieldIds: string[]\n references: EidosFileFormulaReference[]\n}\n\n/** Eidos File 1.0 has no prop()/props() reference syntax. */\nexport const EIDOS_FILE_FORMULA_FIELD_FUNCTION_NAMES = [] as const\n\nexport const EIDOS_FILE_FORMULA_PROFILE = \"sqlite-3.45\" as const\n\nexport const EIDOS_FILE_FORMULA_FUNCTION_NAMES = [\n \"abs\",\n \"ceil\",\n \"ceiling\",\n \"char\",\n \"coalesce\",\n \"concat\",\n \"concat_ws\",\n \"date\",\n \"datetime\",\n \"floor\",\n \"format\",\n \"glob\",\n \"hex\",\n \"ifnull\",\n \"iif\",\n \"instr\",\n \"julianday\",\n \"length\",\n \"like\",\n \"lower\",\n \"ltrim\",\n \"max\",\n \"min\",\n \"nullif\",\n \"octet_length\",\n \"printf\",\n \"quote\",\n \"replace\",\n \"round\",\n \"rtrim\",\n \"sign\",\n \"strftime\",\n \"substr\",\n \"substring\",\n \"time\",\n \"timediff\",\n \"trim\",\n \"typeof\",\n \"unicode\",\n \"unixepoch\",\n \"upper\",\n] as const\n\nconst ALLOWED_FUNCTIONS = new Set<string>(EIDOS_FILE_FORMULA_FUNCTION_NAMES)\nconst ALLOWED_KEYWORDS = new Set([\n \"and\",\n \"as\",\n \"case\",\n \"cast\",\n \"else\",\n \"end\",\n \"false\",\n \"integer\",\n \"is\",\n \"not\",\n \"null\",\n \"or\",\n \"real\",\n \"text\",\n \"then\",\n \"true\",\n \"when\",\n])\nconst MAX_FORMULA_BYTES = 4_096\nconst MAX_FORMULA_NODES = 10_000\nconst MAX_FORMULA_DEPTH = 256\n\n/** Fails fast when a Host SQLite build cannot execute the fixed 1.0 profile. */\nexport function assertEidosFileFormulaProfile(\n connection: EidosFileConnection\n): void {\n try {\n connection.get(`SELECT\n abs(-1), ceil(1.5), ceiling(1.5), char(65), coalesce(NULL, 1),\n concat(1, NULL, 'x'), concat_ws('-', 1, NULL, 2),\n date('2026-01-01'), datetime('2026-01-01'), floor(1.5),\n format('%d', 1), glob('a*', 'abc'), hex('A'), ifnull(NULL, 1),\n iif(1, 1, 0), instr('abc', 'b'), julianday('2026-01-01'),\n length('abc'), like('a%', 'abc'), lower('A'), ltrim(' x'),\n max(1, 2), min(1, 2), nullif(1, 2), octet_length('😀'),\n printf('%d', 1), quote('x'), replace('abc', 'b', 'x'), round(1.5),\n rtrim('x '), sign(-1), strftime('%Y', '2026-01-01'),\n substr('abc', 1, 2), substring('abc', 1, 2),\n time('2026-01-01T12:00:00Z'),\n timediff('2026-01-02', '2026-01-01'), trim(' x '), typeof(1),\n unicode('A'), unixepoch('2026-01-01'), upper('a')`)\n } catch (error) {\n throw new EidosFileError(\n \"unsupported-feature\",\n `SQLite build does not satisfy the Eidos Formula 1.0 function profile: ${error instanceof Error ? error.message : String(error)}`\n )\n }\n}\n\nfunction nextNonWhitespace(source: string, index: number): string | undefined {\n while (index < source.length && /\\s/u.test(source[index]!)) index += 1\n return source[index]\n}\n\n/**\n * Scans canonical Formula source. Only double-quoted tokens can be Field\n * references; single-quoted string literals are skipped byte-for-byte.\n */\nexport function eidosFileFormulaReferences(\n source: string\n): EidosFileFormulaReference[] {\n if (new TextEncoder().encode(source).byteLength > MAX_FORMULA_BYTES) {\n throw new EidosFileError(\"resource-limit\", \"Eidos File formula is too long\")\n }\n if (source.trim().length === 0) {\n throw new EidosFileError(\"invalid-schema\", \"Formula source cannot be empty\")\n }\n const references: EidosFileFormulaReference[] = []\n let index = 0\n while (index < source.length) {\n const character = source[index]!\n if (/\\s/u.test(character)) {\n index += 1\n continue\n }\n if (character === \"'\") {\n index += 1\n let closed = false\n while (index < source.length) {\n if (source[index] !== \"'\") {\n index += 1\n continue\n }\n if (source[index + 1] === \"'\") {\n index += 2\n continue\n }\n index += 1\n closed = true\n break\n }\n if (!closed) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Unterminated string literal\"\n )\n }\n continue\n }\n if (character === '\"') {\n const start = index\n index += 1\n let name = \"\"\n let closed = false\n while (index < source.length) {\n if (source[index] !== '\"') {\n name += source[index]\n index += 1\n continue\n }\n if (source[index + 1] === '\"') {\n name += '\"'\n index += 2\n continue\n }\n index += 1\n closed = true\n break\n }\n if (!closed) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Unterminated Field reference\"\n )\n }\n references.push({ fieldName: name, start, end: index })\n continue\n }\n if (/[A-Za-z_]/.test(character)) {\n const start = index\n index += 1\n while (index < source.length && /[A-Za-z0-9_]/.test(source[index]!)) {\n index += 1\n }\n const token = source.slice(start, index).toLowerCase()\n if (nextNonWhitespace(source, index) === \"(\" && token !== \"cast\") {\n if (!ALLOWED_FUNCTIONS.has(token)) {\n throw new EidosFileError(\n \"invalid-schema\",\n `Unsupported Eidos File formula function: ${token}`\n )\n }\n } else if (!ALLOWED_KEYWORDS.has(token)) {\n throw new EidosFileError(\n \"invalid-schema\",\n `Field references must be double-quoted: ${source.slice(start, index)}`\n )\n }\n continue\n }\n if (/[0-9]/.test(character)) {\n index += 1\n while (index < source.length && /[0-9.eE+-]/.test(source[index]!)) {\n const current = source[index]!\n if (\n (current === \"+\" || current === \"-\") &&\n !/[eE]/.test(source[index - 1]!)\n ) {\n break\n }\n index += 1\n }\n continue\n }\n if (\"()+-*/%<>=!|,\".includes(character)) {\n index += 1\n continue\n }\n throw new EidosFileError(\n \"invalid-schema\",\n `Unsupported token in Eidos File formula: ${character}`\n )\n }\n return references\n}\n\nfunction formulaText(field: EidosFileFieldInfo): string {\n const value = field.property?.formula\n if (typeof value !== \"string\") {\n throw new EidosFileError(\n \"invalid-schema\",\n `Formula Field “${field.name}” requires an expression`\n )\n }\n return value\n}\n\ntype FormulaStaticType =\n | \"text\"\n | \"number\"\n | \"integer\"\n | \"checkbox\"\n | \"date\"\n | \"datetime\"\n | \"url\"\n\ninterface ExactFormulaNode {\n type: string\n op?: string\n value?: unknown\n name?: string\n left?: ExactFormulaNode\n right?: ExactFormulaNode\n operand?: ExactFormulaNode\n args?: ExactFormulaNode[]\n function?: { name?: string }\n inferred?: FormulaStaticType\n literal?: ExactNumberLiteral\n}\n\ninterface ExactNumberLiteral {\n raw: string\n type: \"integer\" | \"number\"\n sql: string\n}\n\ninterface ParsedExactFormula {\n root: ExactFormulaNode\n numbers: ExactNumberLiteral[]\n}\n\ninterface FormulaToken {\n kind:\n | \"word\"\n | \"number\"\n | \"string\"\n | \"field\"\n | \"operator\"\n | \"left\"\n | \"right\"\n | \"comma\"\n | \"end\"\n text: string\n value?: string\n literal?: ExactNumberLiteral\n}\n\nfunction parseExactFormula(source: string): ParsedExactFormula {\n if (new TextEncoder().encode(source).byteLength > MAX_FORMULA_BYTES) {\n throw new EidosFileError(\"resource-limit\", \"Eidos File formula is too long\")\n }\n for (let index = 0; index < source.length; index += 1) {\n const code = source.charCodeAt(index)\n if (code >= 0xd800 && code <= 0xdbff) {\n if (index + 1 >= source.length)\n throw new EidosFileError(\n \"invalid-formula\",\n \"Formula source contains an unpaired surrogate\"\n )\n const next = source.charCodeAt(index + 1)\n if (next < 0xdc00 || next > 0xdfff)\n throw new EidosFileError(\n \"invalid-formula\",\n \"Formula source contains an unpaired surrogate\"\n )\n index += 1\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n throw new EidosFileError(\n \"invalid-formula\",\n \"Formula source contains an unpaired surrogate\"\n )\n }\n }\n const tokens: FormulaToken[] = []\n let index = 0\n while (index < source.length) {\n const character = source[index]!\n if (\n character === \" \" ||\n character === \"\\t\" ||\n character === \"\\r\" ||\n character === \"\\n\"\n ) {\n index += 1\n continue\n }\n if (character === \"'\" || character === '\"') {\n const quote = character\n index += 1\n let value = \"\"\n let closed = false\n while (index < source.length) {\n if (source[index] !== quote) {\n value += source[index]\n index += 1\n } else if (source[index + 1] === quote) {\n value += quote\n index += 2\n } else {\n index += 1\n closed = true\n break\n }\n }\n if (!closed)\n throw new EidosFileError(\n \"invalid-formula\",\n \"Unterminated Formula token\"\n )\n tokens.push({\n kind: quote === \"'\" ? \"string\" : \"field\",\n text: value,\n value,\n })\n continue\n }\n if (/[0-9]/.test(character)) {\n const match = /^(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/.exec(\n source.slice(index)\n )\n if (!match)\n throw new EidosFileError(\"invalid-formula\", \"Invalid number literal\")\n const raw = match[0]\n const next = source[index + raw.length]\n if (next && /[0-9A-Za-z_.]/.test(next)) {\n throw new EidosFileError(\n \"invalid-formula\",\n \"Invalid number literal boundary\"\n )\n }\n const integerToken = !/[.eE]/.test(raw)\n const integer = integerToken ? BigInt(raw) : null\n let literal: ExactNumberLiteral\n if (integer !== null && integer <= 9_223_372_036_854_775_807n) {\n literal = { raw, type: \"integer\", sql: raw }\n } else {\n const value = Number(raw)\n if (!Number.isFinite(value)) {\n throw new EidosFileError(\n \"invalid-formula\",\n \"Number literal is non-finite\"\n )\n }\n let sql = Object.is(value, -0) ? \"0.0\" : value.toString()\n if (/^-?(?:0|[1-9][0-9]*)$/.test(sql)) sql += \".0\"\n literal = { raw, type: \"number\", sql }\n }\n tokens.push({ kind: \"number\", text: raw, literal })\n index += raw.length\n continue\n }\n if (/[A-Za-z]/.test(character)) {\n const start = index++\n while (index < source.length && /[A-Za-z0-9_]/.test(source[index]!))\n index += 1\n const token = source.slice(start, index)\n tokens.push({ kind: \"word\", text: token })\n continue\n }\n if (character === \"(\") {\n tokens.push({ kind: \"left\", text: character })\n index += 1\n continue\n }\n if (character === \")\") {\n tokens.push({ kind: \"right\", text: character })\n index += 1\n continue\n }\n if (character === \",\") {\n tokens.push({ kind: \"comma\", text: character })\n index += 1\n continue\n }\n const pair = source.slice(index, index + 2)\n if ([\"!=\", \"<=\", \">=\", \"==\", \"<>\", \"||\"].includes(pair)) {\n tokens.push({ kind: \"operator\", text: pair })\n index += 2\n continue\n }\n if (\"+-*/%<>=|\".includes(character)) {\n tokens.push({ kind: \"operator\", text: character })\n index += 1\n continue\n }\n throw new EidosFileError(\n \"invalid-formula\",\n `Unsupported token in Eidos File formula: ${character}`\n )\n }\n tokens.push({ kind: \"end\", text: \"\" })\n let cursor = 0\n const peek = () => tokens[cursor]!\n const take = () => tokens[cursor++]!\n const word = (value: string) =>\n peek().kind === \"word\" && peek().text.toUpperCase() === value\n const operator = (...values: string[]) =>\n peek().kind === \"operator\" && values.includes(peek().text)\n const binary = (\n lower: () => ExactFormulaNode,\n operators: string[]\n ): ExactFormulaNode => {\n let node = lower()\n while (\n (peek().kind === \"operator\" && operators.includes(peek().text)) ||\n (peek().kind === \"word\" && operators.includes(peek().text.toUpperCase()))\n ) {\n const op = take().text.toUpperCase()\n node = { type: \"binary\", op, left: node, right: lower() }\n }\n return node\n }\n let expression: () => ExactFormulaNode\n const primary = (): ExactFormulaNode => {\n const token = take()\n if (token.kind === \"number\")\n return { type: \"number\", literal: token.literal }\n if (token.kind === \"string\") return { type: \"string\", value: token.value }\n if (token.kind === \"field\") return { type: \"ref\", name: token.value }\n if (token.kind === \"word\") {\n const canonical = token.text.toUpperCase()\n if (canonical === \"NULL\") return { type: \"null\" }\n if (canonical === \"TRUE\" || canonical === \"FALSE\")\n return { type: \"boolean\", value: canonical === \"TRUE\" }\n if (canonical === \"CAST\") {\n if (take().kind !== \"left\")\n throw new EidosFileError(\n \"invalid-formula\",\n \"CAST requires an opening parenthesis\"\n )\n const operand = expression()\n if (!word(\"AS\"))\n throw new EidosFileError(\"invalid-formula\", \"CAST requires AS\")\n take()\n const target = take()\n const targetName = target.text.toUpperCase()\n if (\n target.kind !== \"word\" ||\n ![\"TEXT\", \"INTEGER\", \"REAL\"].includes(targetName)\n ) {\n throw new EidosFileError(\n \"invalid-formula\",\n \"CAST target must be TEXT, INTEGER, or REAL\"\n )\n }\n if (take().kind !== \"right\")\n throw new EidosFileError(\"invalid-formula\", \"CAST is missing “)”\")\n return {\n type: \"cast\",\n name: targetName.toLowerCase(),\n operand,\n }\n }\n if (canonical === \"CASE\") {\n const args: ExactFormulaNode[] = []\n while (word(\"WHEN\")) {\n take()\n args.push(expression())\n if (!word(\"THEN\"))\n throw new EidosFileError(\n \"invalid-formula\",\n \"CASE WHEN requires THEN\"\n )\n take()\n args.push(expression())\n }\n if (args.length === 0)\n throw new EidosFileError(\n \"invalid-formula\",\n \"CASE requires at least one WHEN\"\n )\n let hasElse = false\n if (word(\"ELSE\")) {\n take()\n args.push(expression())\n hasElse = true\n }\n if (!word(\"END\"))\n throw new EidosFileError(\"invalid-formula\", \"CASE requires END\")\n take()\n return { type: \"case\", value: hasElse, args }\n }\n if (peek().kind !== \"left\") {\n throw new EidosFileError(\n \"invalid-formula\",\n `Field references must be double-quoted: ${token.text}`\n )\n }\n if (!ALLOWED_FUNCTIONS.has(token.text.toLowerCase())) {\n throw new EidosFileError(\n \"invalid-formula\",\n `Unsupported Formula function: ${token.text}`\n )\n }\n take()\n const args: ExactFormulaNode[] = []\n if (peek().kind !== \"right\") {\n args.push(expression())\n while (peek().kind === \"comma\") {\n take()\n args.push(expression())\n }\n }\n if (take().kind !== \"right\")\n throw new EidosFileError(\n \"invalid-formula\",\n `Formula function ${token.text} is missing “)”`\n )\n return {\n type: \"call\",\n function: { name: token.text.toLowerCase() },\n args,\n }\n }\n if (token.kind === \"left\") {\n const node = expression()\n if (take().kind !== \"right\")\n throw new EidosFileError(\"invalid-formula\", \"Formula is missing “)”\")\n return node\n }\n throw new EidosFileError(\"invalid-formula\", \"Expected Formula expression\")\n }\n const unary = (): ExactFormulaNode => {\n if (operator(\"+\", \"-\")) {\n const op = take().text\n return { type: \"unary\", op, operand: primary() }\n }\n return primary()\n }\n const multiplicative = () => binary(unary, [\"*\", \"/\", \"%\"])\n const additive = () => binary(multiplicative, [\"+\", \"-\"])\n const concatenation = () => binary(additive, [\"||\"])\n const comparison = (): ExactFormulaNode => {\n const left = concatenation()\n if (word(\"IS\")) {\n take()\n const negate = word(\"NOT\")\n if (negate) take()\n if (!word(\"NULL\"))\n throw new EidosFileError(\n \"invalid-formula\",\n \"Formula IS only supports IS NULL and IS NOT NULL\"\n )\n take()\n return {\n type: \"is-null\",\n op: negate ? \"IS NOT NULL\" : \"IS NULL\",\n operand: left,\n }\n }\n if (!operator(\"=\", \"==\", \"!=\", \"<>\", \"<\", \"<=\", \">\", \">=\")) return left\n const op = take().text\n return { type: \"binary\", op, left, right: concatenation() }\n }\n const notExpression = (): ExactFormulaNode =>\n word(\"NOT\")\n ? (take(), { type: \"unary\", op: \"NOT\", operand: comparison() })\n : comparison()\n const andExpression = () => binary(notExpression, [\"AND\"])\n const orExpression = () => binary(andExpression, [\"OR\"])\n expression = orExpression\n if (tokens.length === 1)\n throw new EidosFileError(\n \"invalid-formula\",\n \"Formula source cannot be empty\"\n )\n const root = expression()\n if (peek().kind !== \"end\")\n throw new EidosFileError(\n \"invalid-formula\",\n `Unexpected Formula token: ${peek().text}`\n )\n assertExactFormulaAst(root)\n return { root, numbers: [] }\n}\n\nfunction assertExactFormulaAst(root: ExactFormulaNode): void {\n let nodes = 0\n let maximumDepth = 0\n const visit = (node: ExactFormulaNode, depth: number): void => {\n nodes += 1\n maximumDepth = Math.max(maximumDepth, depth)\n if (node.left) visit(node.left, depth + 1)\n if (node.right) visit(node.right, depth + 1)\n if (node.operand) visit(node.operand, depth + 1)\n for (const argument of node.args ?? []) visit(argument, depth + 1)\n }\n visit(root, 1)\n if (nodes > MAX_FORMULA_NODES || maximumDepth > MAX_FORMULA_DEPTH) {\n throw new EidosFileError(\n \"resource-limit\",\n \"Eidos File formula exceeds the AST complexity limit\"\n )\n }\n}\n\nfunction formulaOperandType(field: EidosFileFieldInfo): FormulaStaticType {\n let type: unknown\n if (field.systemRole === \"row-id\" || field.type === \"row-id\") type = \"text\"\n else if (field.type === \"rating\") type = \"integer\"\n else if (\n field.systemRole === \"created-time\" ||\n field.systemRole === \"updated-time\" ||\n field.type === \"created-time\" ||\n field.type === \"last-edited-time\"\n )\n type = \"datetime\"\n else if (field.type === \"select\") type = \"text\"\n else if (field.type === \"lookup\" && field.property?.aggregate === \"values\") {\n type = undefined\n } else if (field.type === \"formula\" || field.type === \"lookup\") {\n const valueType = field.property?.valueType\n type =\n valueType === \"row-id\" || valueType === \"select\"\n ? \"text\"\n : typeof valueType === \"string\"\n ? valueType\n : field.property?.displayType\n } else type = field.type\n if (\n ![\n \"text\",\n \"number\",\n \"integer\",\n \"checkbox\",\n \"date\",\n \"datetime\",\n \"url\",\n ].includes(String(type))\n ) {\n throw new EidosFileError(\n \"invalid-schema\",\n `Field “${field.name}” is not a Formula scalar operand`\n )\n }\n return type as FormulaStaticType\n}\n\nfunction exactFormulaType(\n node: ExactFormulaNode,\n fields: Map<string, EidosFileFieldInfo>,\n numbers: ExactNumberLiteral[],\n expected?: FormulaStaticType | \"any\"\n): FormulaStaticType | null {\n const infer = (child: ExactFormulaNode, type?: FormulaStaticType | \"any\") =>\n exactFormulaType(child, fields, numbers, type)\n if (node.literal) return setFormulaType(node, node.literal.type)\n if (node.type === \"null\")\n return expected === \"any\" ? null : (expected ?? null)\n if (node.type === \"boolean\") return setFormulaType(node, \"checkbox\")\n if (node.type === \"string\") return setFormulaType(node, \"text\")\n if (node.type === \"ref\") {\n const field = fields.get(String(node.name))\n if (!field)\n throw new EidosFileError(\n \"field-not-found\",\n `Formula Field not found: ${node.name}`\n )\n return setFormulaType(node, formulaOperandType(field))\n }\n if (\n node.type === \"call\" &&\n String(node.function?.name).startsWith(\"eidos_literal_\")\n ) {\n const literalIndex = Number(\n String(node.function?.name).slice(\"eidos_literal_\".length)\n )\n const literal = numbers[literalIndex]\n if (!literal)\n throw new EidosFileError(\n \"invalid-schema\",\n \"Invalid Formula number literal\"\n )\n node.literal = literal\n return setFormulaType(node, literal.type)\n }\n if (node.type === \"cast\") {\n if (!node.operand)\n throw new EidosFileError(\"invalid-schema\", \"CAST requires an operand\")\n infer(node.operand, \"any\")\n const result = {\n text: \"text\",\n integer: \"integer\",\n real: \"number\",\n }[String(node.name)] as FormulaStaticType | undefined\n if (!result)\n throw new EidosFileError(\"invalid-schema\", \"Invalid CAST target\")\n return setFormulaType(node, result)\n }\n if (node.type === \"is-null\") {\n if (!node.operand)\n throw new EidosFileError(\"invalid-schema\", \"IS NULL requires an operand\")\n infer(node.operand, \"any\")\n return setFormulaType(node, \"checkbox\")\n }\n if (node.type === \"case\") {\n const args = node.args ?? []\n const hasElse = node.value === true\n const branchNodes: ExactFormulaNode[] = []\n const pairLength = hasElse ? args.length - 1 : args.length\n for (let index = 0; index < pairLength; index += 2) {\n requireFormulaType(infer(args[index]!, \"checkbox\"), \"checkbox\", \"CASE\")\n branchNodes.push(args[index + 1]!)\n }\n if (hasElse) branchNodes.push(args[args.length - 1]!)\n else branchNodes.push({ type: \"null\" })\n const result = inferFormulaSequence(branchNodes, fields, numbers, expected)\n return setFormulaType(node, result)\n }\n if (node.type === \"unary\") {\n if (!node.operand || ![\"+\", \"-\", \"NOT\"].includes(String(node.op))) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Invalid unary Formula operator\"\n )\n }\n if (node.op === \"NOT\") {\n requireFormulaType(infer(node.operand, \"checkbox\"), \"checkbox\", \"NOT\")\n return setFormulaType(node, \"checkbox\")\n }\n const specialMinimum =\n node.op === \"-\" && node.operand.literal?.raw === \"9223372036854775808\"\n if (specialMinimum) {\n node.literal = {\n raw: \"-9223372036854775808\",\n type: \"integer\",\n sql: \"-9223372036854775808\",\n }\n return setFormulaType(node, \"integer\")\n }\n const operand = infer(node.operand, expected)\n if (operand !== \"integer\" && operand !== \"number\") {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Unary sign requires a numeric operand\"\n )\n }\n return setFormulaType(node, operand)\n }\n if (node.type === \"binary\") {\n if (!node.left || !node.right)\n throw new EidosFileError(\"invalid-schema\", \"Invalid binary Formula\")\n const op = String(node.op).toUpperCase()\n if (op === \"AND\" || op === \"OR\") {\n requireFormulaType(infer(node.left, \"checkbox\"), \"checkbox\", op)\n requireFormulaType(infer(node.right, \"checkbox\"), \"checkbox\", op)\n return setFormulaType(node, \"checkbox\")\n }\n if (op === \"||\") {\n infer(node.left, \"any\")\n infer(node.right, \"any\")\n return setFormulaType(node, \"text\")\n }\n if ([\"+\", \"-\", \"*\", \"/\", \"%\"].includes(op)) {\n const forced = op === \"%\" ? \"integer\" : op === \"/\" ? \"number\" : expected\n const pair = inferFormulaPair(\n node.left,\n node.right,\n fields,\n numbers,\n forced\n )\n if (\n !isNumericFormulaType(pair.left) ||\n !isNumericFormulaType(pair.right)\n ) {\n throw new EidosFileError(\n \"invalid-schema\",\n `${op} requires numeric operands`\n )\n }\n if (op === \"%\" && (pair.left !== \"integer\" || pair.right !== \"integer\")) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"% requires Integer operands\"\n )\n }\n const result =\n op === \"/\" || pair.left === \"number\" || pair.right === \"number\"\n ? \"number\"\n : \"integer\"\n return setFormulaType(node, result)\n }\n if ([\"=\", \"==\", \"!=\", \"<>\", \"<\", \"<=\", \">\", \">=\"].includes(op)) {\n const pair = inferFormulaPair(node.left, node.right, fields, numbers)\n if (\n !pair.left ||\n !pair.right ||\n !formulaTypesComparable(pair.left, pair.right)\n ) {\n throw new EidosFileError(\n \"invalid-schema\",\n `${op} operands have incompatible types`\n )\n }\n return setFormulaType(node, \"checkbox\")\n }\n throw new EidosFileError(\n \"invalid-schema\",\n `Unsupported Formula operator: ${op}`\n )\n }\n if (node.type === \"call\") {\n const name = String(node.function?.name).toLowerCase()\n const args = node.args ?? []\n const arity = (minimum: number, maximum = minimum) => {\n if (args.length < minimum || args.length > maximum) {\n throw new EidosFileError(\n \"invalid-schema\",\n `${name} expects ${minimum === maximum ? minimum : `${minimum}–${maximum}`} arguments`\n )\n }\n }\n if (name === \"iif\") {\n arity(3)\n requireFormulaType(infer(args[0]!, \"checkbox\"), \"checkbox\", \"IIF\")\n const pair = inferFormulaPair(\n args[1]!,\n args[2]!,\n fields,\n numbers,\n expected\n )\n if (!pair.left || !pair.right || pair.left !== pair.right) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"IIF branches require one exact type\"\n )\n }\n return setFormulaType(node, pair.left)\n }\n if (name === \"coalesce\" || name === \"ifnull\") {\n if (name === \"ifnull\") arity(2)\n else arity(2, 16)\n const type = inferFormulaSequence(args, fields, numbers, expected)\n return setFormulaType(node, type)\n }\n if (name === \"nullif\") {\n arity(2)\n const pair = inferFormulaPair(\n args[0]!,\n args[1]!,\n fields,\n numbers,\n expected\n )\n if (\n !pair.left ||\n !pair.right ||\n !formulaTypesComparable(pair.left, pair.right)\n ) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"NULLIF arguments have incompatible types\"\n )\n }\n return setFormulaType(node, pair.left)\n }\n if ([\"abs\", \"ceil\", \"ceiling\", \"floor\"].includes(name)) {\n arity(1)\n const type = infer(args[0]!, expected)\n if (!isNumericFormulaType(type))\n throw new EidosFileError(\n \"invalid-schema\",\n `${name.toUpperCase()} requires numeric input`\n )\n return setFormulaType(node, type)\n }\n if (name === \"round\") {\n arity(1, 2)\n const type = infer(args[0]!, \"number\")\n if (!isNumericFormulaType(type))\n throw new EidosFileError(\n \"invalid-schema\",\n \"ROUND requires numeric input\"\n )\n if (args[1])\n requireFormulaType(infer(args[1], \"integer\"), \"integer\", \"ROUND\")\n return setFormulaType(node, \"number\")\n }\n if (name === \"sign\") {\n arity(1)\n const type = infer(args[0]!, \"integer\")\n if (!isNumericFormulaType(type))\n throw new EidosFileError(\n \"invalid-schema\",\n \"SIGN requires numeric input\"\n )\n return setFormulaType(node, \"integer\")\n }\n if (name === \"min\" || name === \"max\") {\n arity(2, 16)\n const type = inferFormulaSequence(args, fields, numbers, expected)\n return setFormulaType(node, type)\n }\n if (name === \"concat\") {\n arity(1, 16)\n for (const argument of args) infer(argument, \"any\")\n return setFormulaType(node, \"text\")\n }\n if (name === \"concat_ws\") {\n arity(2, 16)\n requireFormulaType(infer(args[0]!, \"text\"), \"text\", \"CONCAT_WS\")\n for (const argument of args.slice(1)) infer(argument, \"any\")\n return setFormulaType(node, \"text\")\n }\n if (name === \"format\" || name === \"printf\") {\n arity(1, 16)\n requireFormulaType(infer(args[0]!, \"text\"), \"text\", name)\n for (const argument of args.slice(1)) infer(argument, \"any\")\n return setFormulaType(node, \"text\")\n }\n if (name === \"char\") {\n arity(1, 16)\n for (const argument of args)\n requireFormulaType(infer(argument, \"integer\"), \"integer\", \"CHAR\")\n return setFormulaType(node, \"text\")\n }\n const fixedSignatures: Record<\n string,\n {\n args: FormulaStaticType[]\n result: FormulaStaticType\n optionalLast?: boolean\n }\n > = {\n glob: { args: [\"text\", \"text\"], result: \"checkbox\" },\n instr: { args: [\"text\", \"text\"], result: \"integer\" },\n length: { args: [\"text\"], result: \"integer\" },\n like: {\n args: [\"text\", \"text\", \"text\"],\n result: \"checkbox\",\n optionalLast: true,\n },\n lower: { args: [\"text\"], result: \"text\" },\n ltrim: { args: [\"text\", \"text\"], result: \"text\", optionalLast: true },\n octet_length: { args: [\"text\"], result: \"integer\" },\n replace: { args: [\"text\", \"text\", \"text\"], result: \"text\" },\n rtrim: { args: [\"text\", \"text\"], result: \"text\", optionalLast: true },\n substr: {\n args: [\"text\", \"integer\", \"integer\"],\n result: \"text\",\n optionalLast: true,\n },\n substring: {\n args: [\"text\", \"integer\", \"integer\"],\n result: \"text\",\n optionalLast: true,\n },\n trim: { args: [\"text\", \"text\"], result: \"text\", optionalLast: true },\n unicode: { args: [\"text\"], result: \"integer\" },\n upper: { args: [\"text\"], result: \"text\" },\n }\n const fixedSignature = fixedSignatures[name]\n if (fixedSignature) {\n arity(\n fixedSignature.optionalLast\n ? fixedSignature.args.length - 1\n : fixedSignature.args.length,\n fixedSignature.args.length\n )\n args.forEach((argument, index) =>\n requireFormulaType(\n infer(argument, fixedSignature.args[index]!),\n fixedSignature.args[index]!,\n name\n )\n )\n return setFormulaType(node, fixedSignature.result)\n }\n if ([\"hex\", \"quote\", \"typeof\"].includes(name)) {\n arity(1)\n infer(args[0]!, \"any\")\n return setFormulaType(node, \"text\")\n }\n if (\n [\n \"date\",\n \"datetime\",\n \"julianday\",\n \"strftime\",\n \"time\",\n \"timediff\",\n \"unixepoch\",\n ].includes(name)\n ) {\n const timeValue = (argument: ExactFormulaNode): void => {\n if (argument.type === \"string\") {\n if (String(argument.value).toLowerCase() === \"now\")\n throw new EidosFileError(\n \"invalid-formula\",\n `${name.toUpperCase()} does not allow the current-time literal`\n )\n return\n }\n const type = infer(argument, \"date\")\n if (type !== \"date\" && type !== \"datetime\")\n throw new EidosFileError(\n \"invalid-schema\",\n `${name.toUpperCase()} requires a date or datetime time value`\n )\n }\n const modifier = (argument: ExactFormulaNode): void => {\n if (argument.type !== \"string\")\n throw new EidosFileError(\n \"invalid-formula\",\n `${name.toUpperCase()} modifiers must be string literals`\n )\n const value = String(argument.value).toLowerCase()\n if (\n [\"localtime\", \"utc\", \"auto\"].includes(value) ||\n (name === \"unixepoch\" && [\"subsec\", \"subsecond\"].includes(value))\n )\n throw new EidosFileError(\n \"invalid-formula\",\n `${name.toUpperCase()} modifier is not deterministic`\n )\n }\n if (name === \"timediff\") {\n arity(2)\n timeValue(args[0]!)\n timeValue(args[1]!)\n return setFormulaType(node, \"text\")\n }\n const firstTimeValue = name === \"strftime\" ? 1 : 0\n arity(name === \"strftime\" ? 2 : 1, 9)\n if (name === \"strftime\" && args[0]?.type !== \"string\")\n throw new EidosFileError(\n \"invalid-formula\",\n \"STRFTIME format must be a string literal\"\n )\n timeValue(args[firstTimeValue]!)\n for (const argument of args.slice(firstTimeValue + 1)) modifier(argument)\n return setFormulaType(\n node,\n name === \"date\"\n ? \"date\"\n : name === \"datetime\"\n ? \"datetime\"\n : name === \"julianday\"\n ? \"number\"\n : name === \"unixepoch\"\n ? \"integer\"\n : \"text\"\n )\n }\n throw new EidosFileError(\n \"invalid-schema\",\n `Unsupported Formula function: ${name}`\n )\n }\n throw new EidosFileError(\n \"invalid-schema\",\n `Unsupported Formula AST node: ${node.type}`\n )\n}\n\nfunction inferFormulaPair(\n leftNode: ExactFormulaNode,\n rightNode: ExactFormulaNode,\n fields: Map<string, EidosFileFieldInfo>,\n numbers: ExactNumberLiteral[],\n expected?: FormulaStaticType | \"any\"\n): { left: FormulaStaticType | null; right: FormulaStaticType | null } {\n let left = exactFormulaType(leftNode, fields, numbers, expected)\n let right = exactFormulaType(rightNode, fields, numbers, left ?? expected)\n if (left === null && right !== null)\n left = exactFormulaType(leftNode, fields, numbers, right)\n if (right === null && left !== null)\n right = exactFormulaType(rightNode, fields, numbers, left)\n return { left, right }\n}\n\nfunction inferFormulaSequence(\n nodes: ExactFormulaNode[],\n fields: Map<string, EidosFileFieldInfo>,\n numbers: ExactNumberLiteral[],\n expected?: FormulaStaticType | \"any\",\n allowMixedNumeric = false\n): FormulaStaticType {\n const types = nodes.map((node) =>\n exactFormulaType(node, fields, numbers, expected)\n )\n let selected = types.find((type): type is FormulaStaticType => type !== null)\n if (!selected && expected && expected !== \"any\") selected = expected\n if (!selected)\n throw new EidosFileError(\n \"invalid-schema\",\n \"Formula type cannot be inferred from NULL\"\n )\n for (let index = 0; index < nodes.length; index += 1) {\n let resolvedType: FormulaStaticType | null = types[index] ?? null\n if (resolvedType === null)\n resolvedType = exactFormulaType(nodes[index]!, fields, numbers, selected)\n if (resolvedType === null)\n throw new EidosFileError(\n \"invalid-schema\",\n \"Formula type cannot be inferred from NULL\"\n )\n if (resolvedType === selected) continue\n if (\n allowMixedNumeric &&\n isNumericFormulaType(resolvedType) &&\n isNumericFormulaType(selected)\n ) {\n selected = \"number\"\n continue\n }\n throw new EidosFileError(\n \"invalid-schema\",\n \"Formula arguments require one exact type\"\n )\n }\n return selected\n}\n\nfunction setFormulaType(\n node: ExactFormulaNode,\n type: FormulaStaticType\n): FormulaStaticType {\n node.inferred = type\n return type\n}\n\nfunction requireFormulaType(\n actual: FormulaStaticType | null,\n expected: FormulaStaticType,\n operation: string\n): void {\n if (actual !== expected)\n throw new EidosFileError(\n \"invalid-schema\",\n `${operation} requires ${expected}`\n )\n}\n\nfunction isNumericFormulaType(\n type: FormulaStaticType | null\n): type is \"integer\" | \"number\" {\n return type === \"integer\" || type === \"number\"\n}\n\nfunction formulaTypesComparable(\n left: FormulaStaticType,\n right: FormulaStaticType\n): boolean {\n if (isNumericFormulaType(left) && isNumericFormulaType(right)) return true\n if (left !== right) return false\n return true\n}\n\nfunction compileExactFormulaNode(\n node: ExactFormulaNode,\n fields: Map<string, EidosFileFieldInfo>,\n resolve: (field: EidosFileFieldInfo) => string\n): string {\n const compile = (child: ExactFormulaNode) =>\n compileExactFormulaNode(child, fields, resolve)\n if (node.literal) return node.literal.sql\n if (node.type === \"null\") return \"NULL\"\n if (node.type === \"boolean\") return node.value === true ? \"1\" : \"0\"\n if (node.type === \"string\") {\n const bytes = new TextEncoder().encode(String(node.value))\n const hex = Array.from(bytes, (byte) =>\n byte.toString(16).padStart(2, \"0\")\n ).join(\"\")\n return `CAST(X'${hex}' AS TEXT)`\n }\n if (node.type === \"ref\") {\n const field = fields.get(String(node.name))\n if (!field)\n throw new EidosFileError(\n \"field-not-found\",\n `Formula Field not found: ${node.name}`\n )\n return `(${resolve(field)})`\n }\n if (node.type === \"cast\")\n return `CAST((${compile(node.operand!)}) AS ${String(node.name).toUpperCase()})`\n if (node.type === \"is-null\")\n return `((${compile(node.operand!)}) ${String(node.op).toUpperCase()})`\n if (node.type === \"case\") {\n const args = node.args ?? []\n const hasElse = node.value === true\n const pairLength = hasElse ? args.length - 1 : args.length\n const clauses: string[] = []\n for (let index = 0; index < pairLength; index += 2) {\n clauses.push(\n `WHEN (${compile(args[index]!)}) THEN (${compile(args[index + 1]!)})`\n )\n }\n if (hasElse) clauses.push(`ELSE (${compile(args[args.length - 1]!)})`)\n return `(CASE ${clauses.join(\" \")} END)`\n }\n if (node.type === \"unary\") {\n const operand = compile(node.operand!)\n if (node.op === \"NOT\") return `(NOT (${operand}))`\n if (node.op === \"+\") return `(${operand})`\n return node.inferred === \"integer\"\n ? `eidos_formula_int_neg(${operand})`\n : `eidos_formula_num_neg(${operand})`\n }\n if (node.type === \"binary\") {\n const left = compile(node.left!)\n const right = compile(node.right!)\n const op = String(node.op).toUpperCase()\n if (op === \"AND\" || op === \"OR\") return `((${left}) ${op} (${right}))`\n if (op === \"||\") return `((${left}) || (${right}))`\n if ([\"+\", \"-\", \"*\"].includes(op)) {\n const suffix = op === \"+\" ? \"add\" : op === \"-\" ? \"sub\" : \"mul\"\n return `eidos_formula_${node.inferred === \"integer\" ? \"int\" : \"num\"}_${suffix}(${left}, ${right})`\n }\n if (op === \"/\") return `eidos_formula_num_div(${left}, ${right})`\n if (op === \"%\") return `eidos_formula_int_mod(${left}, ${right})`\n const normalizedOp = op === \"==\" ? \"=\" : op === \"<>\" ? \"!=\" : op\n const leftType = node.left!.inferred!\n const rightType = node.right!.inferred!\n if (\n isNumericFormulaType(leftType) &&\n isNumericFormulaType(rightType) &&\n (leftType !== rightType || leftType === \"number\")\n ) {\n const suffix = {\n \"=\": \"eq\",\n \"!=\": \"ne\",\n \"<\": \"lt\",\n \"<=\": \"lte\",\n \">\": \"gt\",\n \">=\": \"gte\",\n }[normalizedOp]\n return `eidos_formula_numeric_${suffix}(${left}, ${right})`\n }\n return `((${left}) COLLATE BINARY ${normalizedOp} (${right}) COLLATE BINARY)`\n }\n if (node.type === \"call\") {\n const name = String(node.function?.name).toLowerCase()\n const args = (node.args ?? []).map(compile)\n return `${name}(${args.join(\", \")})`\n }\n throw new EidosFileError(\n \"invalid-schema\",\n `Unsupported Formula AST node: ${node.type}`\n )\n}\n\nfunction exactFormulaLiteral(\n node: ExactFormulaNode,\n numbers: ExactNumberLiteral[]\n): ExactNumberLiteral | undefined {\n if (node.literal) return node.literal\n if (\n node.type !== \"call\" ||\n !String(node.function?.name).startsWith(\"eidos_literal_\")\n )\n return undefined\n return numbers[Number(String(node.function?.name).slice(14))]\n}\n\nfunction exactFormulaPrecedence(node: ExactFormulaNode): number {\n if (node.type === \"binary\") {\n const op = String(node.op).toUpperCase()\n if (op === \"OR\") return 1\n if (op === \"AND\") return 2\n if ([\"=\", \"==\", \"!=\", \"<>\", \"<\", \"<=\", \">\", \">=\"].includes(op)) return 4\n if (op === \"||\") return 5\n if (op === \"+\" || op === \"-\") return 6\n return 7\n }\n if (node.type === \"is-null\") return 4\n if (node.type === \"unary\") return node.op === \"NOT\" ? 3 : 8\n return 9\n}\n\nfunction serializeExactFormulaNode(\n node: ExactFormulaNode,\n numbers: ExactNumberLiteral[]\n): string {\n const literal = exactFormulaLiteral(node, numbers)\n if (literal) return literal.sql\n if (node.type === \"null\") return \"NULL\"\n if (node.type === \"boolean\") return node.value === true ? \"TRUE\" : \"FALSE\"\n if (node.type === \"string\")\n return `'${String(node.value).replace(/'/g, \"''\")}'`\n if (node.type === \"ref\") return quoteIdentifier(String(node.name))\n if (node.type === \"cast\")\n return `CAST(${serializeExactFormulaNode(node.operand!, numbers)} AS ${String(node.name).toUpperCase()})`\n if (node.type === \"is-null\") {\n const operand = node.operand!\n let serialized = serializeExactFormulaNode(operand, numbers)\n if (exactFormulaPrecedence(operand) < 5) serialized = `(${serialized})`\n return `${serialized} ${String(node.op).toUpperCase()}`\n }\n if (node.type === \"case\") {\n const args = node.args ?? []\n const hasElse = node.value === true\n const pairLength = hasElse ? args.length - 1 : args.length\n const clauses: string[] = []\n for (let index = 0; index < pairLength; index += 2) {\n clauses.push(\n `WHEN ${serializeExactFormulaNode(args[index]!, numbers)} THEN ${serializeExactFormulaNode(args[index + 1]!, numbers)}`\n )\n }\n if (hasElse)\n clauses.push(\n `ELSE ${serializeExactFormulaNode(args[args.length - 1]!, numbers)}`\n )\n return `CASE ${clauses.join(\" \")} END`\n }\n if (node.type === \"unary\") {\n const operand = node.operand!\n const specialMinimum =\n node.op === \"-\" &&\n exactFormulaLiteral(operand, numbers)?.raw === \"9223372036854775808\"\n if (specialMinimum) return \"-9223372036854775808\"\n let serialized = serializeExactFormulaNode(operand, numbers)\n if (\n exactFormulaPrecedence(operand) < exactFormulaPrecedence(node) ||\n operand.type === \"unary\"\n )\n serialized = `(${serialized})`\n return `${String(node.op).toUpperCase()}${node.op === \"NOT\" ? \" \" : \"\"}${serialized}`\n }\n if (node.type === \"binary\") {\n const op = String(node.op).toUpperCase()\n const serializedOp = op === \"==\" ? \"=\" : op === \"<>\" ? \"!=\" : op\n const precedence = exactFormulaPrecedence(node)\n const comparison = [\"=\", \"==\", \"!=\", \"<>\", \"<\", \"<=\", \">\", \">=\"].includes(\n op\n )\n const child = (value: ExactFormulaNode, right: boolean): string => {\n let serialized = serializeExactFormulaNode(value, numbers)\n const childPrecedence = exactFormulaPrecedence(value)\n if (\n childPrecedence < precedence ||\n (right && childPrecedence === precedence) ||\n (comparison && value.type === \"binary\" && childPrecedence === 4)\n )\n serialized = `(${serialized})`\n return serialized\n }\n return `${child(node.left!, false)} ${serializedOp} ${child(node.right!, true)}`\n }\n if (node.type === \"call\") {\n const name = String(node.function?.name).toUpperCase()\n return `${name}(${(node.args ?? [])\n .map((argument) => serializeExactFormulaNode(argument, numbers))\n .join(\", \")})`\n }\n throw new EidosFileError(\n \"invalid-formula\",\n `Unsupported Formula AST node: ${node.type}`\n )\n}\n\nfunction rewriteExactFormulaReferences(\n node: ExactFormulaNode,\n oldFieldName: string,\n newFieldName: string\n): void {\n if (node.type === \"ref\" && node.name === oldFieldName)\n node.name = newFieldName\n if (node.left)\n rewriteExactFormulaReferences(node.left, oldFieldName, newFieldName)\n if (node.right)\n rewriteExactFormulaReferences(node.right, oldFieldName, newFieldName)\n if (node.operand)\n rewriteExactFormulaReferences(node.operand, oldFieldName, newFieldName)\n for (const argument of node.args ?? [])\n rewriteExactFormulaReferences(argument, oldFieldName, newFieldName)\n}\n\n/** Compiles canonical source while allowing the Runtime to inline projections. */\nexport function compileEidosFileFormulaSource(\n source: string,\n fields: EidosFileFieldInfo[],\n resolve: (field: EidosFileFieldInfo) => string,\n declaredResultType?: string\n): { expression: string; dependencyFieldIds: string[] } {\n const references = eidosFileFormulaReferences(source)\n const fieldsByExactName = new Map(fields.map((field) => [field.name, field]))\n const dependencyFieldIds: string[] = []\n for (const reference of references) {\n const field = fieldsByExactName.get(reference.fieldName)\n if (!field) {\n throw new EidosFileError(\n \"field-not-found\",\n `Formula Field not found by exact name: ${reference.fieldName}`\n )\n }\n if (!dependencyFieldIds.includes(field.id))\n dependencyFieldIds.push(field.id)\n }\n const parsed = parseExactFormula(source)\n const expected = declaredResultType as FormulaStaticType | undefined\n const inferred = exactFormulaType(\n parsed.root,\n fieldsByExactName,\n parsed.numbers,\n expected\n )\n if (!inferred || (expected !== undefined && inferred !== expected)) {\n throw new EidosFileError(\n \"invalid-schema\",\n `Formula inferred ${inferred ?? \"no type\"}, expected ${expected ?? \"a concrete type\"}`\n )\n }\n return {\n expression: compileExactFormulaNode(\n parsed.root,\n fieldsByExactName,\n resolve\n ),\n dependencyFieldIds,\n }\n}\n\nexport function rewriteEidosFileFormulaFieldReferences(\n source: string,\n oldFieldName: string,\n newFieldName: string\n): string {\n if (\n !eidosFileFormulaReferences(source).some(\n (reference) => reference.fieldName === oldFieldName\n )\n ) {\n return source\n }\n const parsed = parseExactFormula(source)\n rewriteExactFormulaReferences(parsed.root, oldFieldName, newFieldName)\n return serializeExactFormulaNode(parsed.root, parsed.numbers)\n}\n\nexport function compileEidosFileFormula(\n field: EidosFileFieldInfo,\n fields: EidosFileFieldInfo[]\n): CompiledEidosFileFormula {\n const source = formulaText(field)\n const references = eidosFileFormulaReferences(source)\n const fieldsByExactName = new Map(\n fields.map((candidate) => [candidate.name, candidate])\n )\n const dependencies: string[] = []\n const dependencyFieldIds: string[] = []\n const resolved = new Map<EidosFileFormulaReference, EidosFileFieldInfo>()\n for (const reference of references) {\n const dependency = fieldsByExactName.get(reference.fieldName)\n if (!dependency) {\n throw new EidosFileError(\n \"field-not-found\",\n `Formula Field not found by exact name: ${reference.fieldName}`\n )\n }\n resolved.set(reference, dependency)\n const projectionName = dependency.physicalName ?? dependency.tableColumnName\n if (!dependencies.includes(projectionName))\n dependencies.push(projectionName)\n const dependencyId = dependency.id\n if (!dependencyFieldIds.includes(dependencyId)) {\n dependencyFieldIds.push(dependencyId)\n }\n }\n const { expression } = compileEidosFileFormulaSource(\n source,\n fields,\n (dependency) =>\n quoteIdentifier(dependency.physicalName ?? dependency.tableColumnName),\n String(field.property?.displayType ?? \"text\")\n )\n return {\n field,\n expression,\n dependencies,\n dependencyFieldIds,\n references,\n }\n}\n\nexport function compileEidosFileFormulaFields(\n fields: EidosFileFieldInfo[]\n): CompiledEidosFileFormula[] {\n const formulaFields = fields.filter((field) => field.type === \"formula\")\n const compiled = new Map(\n formulaFields.map((field) => [\n field.id,\n compileEidosFileFormula(field, fields),\n ])\n )\n const ordered: CompiledEidosFileFormula[] = []\n const visiting = new Set<string>()\n const visited = new Set<string>()\n const visit = (fieldId: string, path: string[]): void => {\n if (visited.has(fieldId)) return\n if (visiting.has(fieldId)) {\n const cycle = [...path.slice(path.indexOf(fieldId)), fieldId]\n .map((id) => compiled.get(id)?.field.name ?? id)\n .join(\" → \")\n throw new EidosFileError(\n \"dependency-cycle\",\n `Circular Eidos File Formula dependency: ${cycle}`\n )\n }\n const formula = compiled.get(fieldId)\n if (!formula) return\n visiting.add(fieldId)\n for (const dependencyId of formula.dependencyFieldIds) {\n if (compiled.has(dependencyId)) visit(dependencyId, [...path, fieldId])\n }\n visiting.delete(fieldId)\n visited.add(fieldId)\n ordered.push(formula)\n }\n for (const fieldId of compiled.keys()) visit(fieldId, [])\n return ordered\n}\n","import type {\n EidosFileFieldInfo,\n EidosFileFieldType,\n EidosFileFormulaDisplayType,\n EidosFileLookupAggregate,\n EidosFileStorageCodec,\n} from \"./types\"\nimport type { AtomicType, TypeRef } from \"./runtime-contract\"\n\nexport type EidosFileLookupTarget = Pick<EidosFileFieldInfo, \"type\"> &\n Partial<Pick<EidosFileFieldInfo, \"property\">>\n\nconst NUMERIC_LOOKUP_AGGREGATES = new Set<EidosFileLookupAggregate>([\n \"sum\",\n \"average\",\n])\n\nexport function eidosFileLookupStorageCodec(\n aggregate: EidosFileLookupAggregate\n): EidosFileStorageCodec {\n return aggregate === \"values\" ? \"json_array\" : \"scalar\"\n}\n\nexport function eidosFileLookupAggregateSupportsTarget(\n aggregate: EidosFileLookupAggregate,\n target: EidosFileFieldType | EidosFileLookupTarget\n): boolean {\n const element = eidosFileLookupElementType(target)\n if (NUMERIC_LOOKUP_AGGREGATES.has(aggregate))\n return element === \"number\" || element === \"integer\"\n if (aggregate === \"min\" || aggregate === \"max\")\n return LOOKUP_SORTABLE_TYPES.has(element)\n return true\n}\n\nconst LOOKUP_SORTABLE_TYPES = new Set<AtomicType>([\n \"text\",\n \"url\",\n \"select\",\n \"row-id\",\n \"integer\",\n \"number\",\n \"checkbox\",\n \"date\",\n \"datetime\",\n])\n\nexport function eidosFileLookupTargetValueType(\n target: EidosFileFieldType | EidosFileLookupTarget\n): TypeRef {\n const type = typeof target === \"string\" ? target : target.type\n const generated =\n typeof target === \"string\" ? undefined : target.property?.valueType\n const generatedObject =\n generated && typeof generated === \"object\"\n ? (generated as Record<string, unknown>)\n : undefined\n if (typeof generated === \"string\") {\n if (generated === \"json\") return type === \"lookup\" ? \"file-entry\" : \"text\"\n return generated as TypeRef\n }\n if (\n generatedObject?.kind === \"list\" &&\n typeof generatedObject.element === \"string\"\n ) {\n return generated as TypeRef\n }\n if (type === \"row-id\") return \"row-id\"\n if (type === \"created-time\" || type === \"last-edited-time\") return \"datetime\"\n if (type === \"multi-select\") return \"multi-select\"\n if (type === \"file\") return \"file\"\n if (type === \"relation\") return \"relation\"\n if (type === \"select\") return \"select\"\n if (type === \"rating\") return \"number\"\n if (type === \"formula\" || type === \"lookup\") {\n if (\n type === \"lookup\" &&\n typeof target !== \"string\" &&\n target.property?.displayType === \"json\"\n ) {\n return \"file-entry\"\n }\n const displayType = eidosFileLookupTargetDisplayType(target)\n return displayType\n }\n return type as AtomicType\n}\n\nexport function eidosFileLookupElementType(\n target: EidosFileFieldType | EidosFileLookupTarget\n): AtomicType {\n const type = eidosFileLookupTargetValueType(target)\n if (typeof type === \"object\") return type.element\n if (type === \"multi-select\") return \"select\"\n if (type === \"file\") return \"file-entry\"\n if (type === \"relation\") return \"row-id\"\n return type as AtomicType\n}\n\nexport function eidosFileLookupValueType(\n aggregate: EidosFileLookupAggregate,\n target: EidosFileFieldType | EidosFileLookupTarget\n): TypeRef {\n const element = eidosFileLookupElementType(target)\n if (aggregate === \"values\") return { kind: \"list\", element }\n if (aggregate === \"count\") return \"integer\"\n if (aggregate === \"average\") return \"number\"\n if (aggregate === \"sum\") return element === \"integer\" ? \"integer\" : \"number\"\n return element\n}\n\nexport function eidosFileLookupTargetDisplayType(\n target: EidosFileFieldType | EidosFileLookupTarget\n): EidosFileFormulaDisplayType {\n const type = typeof target === \"string\" ? target : target.type\n const configuredDisplayType =\n typeof target === \"string\" ? undefined : target.property?.displayType\n if (\n (type === \"formula\" || type === \"lookup\") &&\n (configuredDisplayType === \"text\" ||\n configuredDisplayType === \"number\" ||\n configuredDisplayType === \"integer\" ||\n configuredDisplayType === \"checkbox\" ||\n configuredDisplayType === \"date\" ||\n configuredDisplayType === \"datetime\" ||\n configuredDisplayType === \"url\")\n ) {\n return configuredDisplayType\n }\n if (type === \"number\" || type === \"rating\") return \"number\"\n if (type === \"integer\") return \"integer\"\n if (type === \"checkbox\") return \"checkbox\"\n if (type === \"date\") return \"date\"\n if (type === \"datetime\") return \"datetime\"\n if (type === \"url\") return \"url\"\n if (type === \"file\") return \"text\"\n return \"text\"\n}\n\nexport function eidosFileLookupDisplayType(\n aggregate: EidosFileLookupAggregate,\n target: EidosFileFieldType | EidosFileLookupTarget\n): EidosFileFormulaDisplayType {\n const valueType = eidosFileLookupValueType(aggregate, target)\n const atom = typeof valueType === \"object\" ? valueType.element : valueType\n if (atom === \"row-id\" || atom === \"select\") return \"text\"\n if (atom === \"file-entry\") return \"text\"\n return atom as EidosFileFormulaDisplayType\n}\n\nexport function eidosFileFieldStoresJsonArray(\n field: Pick<EidosFileFieldInfo, \"storageCodec\">\n): boolean {\n return (\n field.storageCodec === \"json_array\" || field.storageCodec === \"relation\"\n )\n}\n","import type { EidosFileSqlParams, EidosFileSqlPrimitive } from \"./connection\"\nimport { canonicalizeEidosFileJson } from \"./canonical-json\"\nimport { EidosFileError } from \"./errors\"\nimport {\n eidosFileFieldQueryCapabilities,\n eidosFileFieldValueType,\n} from \"./field-query-capabilities\"\nimport { quoteIdentifier } from \"./identifiers\"\nimport {\n currentEidosFileInstant,\n normalizeEidosFileDate,\n normalizeEidosFileInstant,\n} from \"./temporal\"\nimport type {\n EidosFileFieldInfo,\n EidosFileFilterGroup,\n EidosFileFilterOperator,\n EidosFileFilterRuleValue,\n EidosFileRelativeDateValue,\n EidosFileFilterRule,\n EidosFileFilterValue,\n EidosFileRowQuery,\n EidosFileSort,\n} from \"./types\"\n\nconst FILTER_OPERATORS = new Set<EidosFileFilterRule[\"operator\"]>([\n \"equals\",\n \"not-equals\",\n \"contains\",\n \"not-contains\",\n \"starts-with\",\n \"ends-with\",\n \"greater-than\",\n \"greater-than-or-equal\",\n \"less-than\",\n \"less-than-or-equal\",\n \"is-empty\",\n \"is-not-empty\",\n \"is-any-of\",\n \"is-all-of\",\n \"is-none-of\",\n \"is-between\",\n \"is-relative-to-today\",\n])\n\n/** Returns whether a persisted compatibility filter operator is executable. */\nexport function isEidosFileFilterOperator(\n value: unknown\n): value is EidosFileFilterRule[\"operator\"] {\n return FILTER_OPERATORS.has(value as EidosFileFilterRule[\"operator\"])\n}\n\nconst MAX_QUERY_DEPTH = 8\nconst MAX_QUERY_FILTER_NODES = 100\nconst MAX_QUERY_SORTS = 32\nconst MAX_QUERY_SEARCH_LENGTH = 1_000\n\n/** Rejects malformed or over-budget public query documents before normalization. */\nexport function assertEidosFileRowQuery(value: unknown): void {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new EidosFileError(\"invalid-query\", \"Row query must be an object\")\n }\n const query = value as Record<string, unknown>\n if (\n query.search !== undefined &&\n (typeof query.search !== \"string\" ||\n query.search.length > MAX_QUERY_SEARCH_LENGTH)\n ) {\n throw new EidosFileError(\n \"query-limit\",\n \"Search text exceeds the 1000-character limit\"\n )\n }\n if (query.sorts !== undefined) {\n if (!Array.isArray(query.sorts) || query.sorts.length > MAX_QUERY_SORTS) {\n throw new EidosFileError(\n \"query-limit\",\n \"A query may contain at most 32 sort keys\"\n )\n }\n for (const sort of query.sorts) {\n if (\n !sort ||\n typeof sort !== \"object\" ||\n Array.isArray(sort) ||\n typeof (sort as { field?: unknown }).field !== \"string\" ||\n ![\"asc\", \"desc\"].includes(\n String((sort as { direction?: unknown }).direction ?? \"asc\")\n ) ||\n ((sort as { nulls?: unknown }).nulls !== undefined &&\n ![\"first\", \"last\"].includes(\n String((sort as { nulls?: unknown }).nulls)\n ))\n ) {\n throw new EidosFileError(\"invalid-query\", \"Invalid sort document\")\n }\n }\n }\n let nodeCount = 0\n const visit = (node: unknown, depth: number): void => {\n nodeCount += 1\n if (depth > MAX_QUERY_DEPTH || nodeCount > MAX_QUERY_FILTER_NODES) {\n throw new EidosFileError(\n \"query-limit\",\n \"Filter exceeds the query complexity limit\"\n )\n }\n if (!node || typeof node !== \"object\" || Array.isArray(node)) {\n throw new EidosFileError(\"invalid-query\", \"Filter nodes must be objects\")\n }\n const filter = node as Record<string, unknown>\n if (filter.type === \"group\") {\n if (\n ![\"and\", \"or\"].includes(String(filter.conjunction)) ||\n !Array.isArray(filter.children)\n ) {\n throw new EidosFileError(\"invalid-query\", \"Invalid filter group\")\n }\n filter.children.forEach((child) => visit(child, depth + 1))\n return\n }\n if (\n filter.type !== \"rule\" ||\n typeof filter.field !== \"string\" ||\n !isEidosFileFilterOperator(filter.operator)\n ) {\n throw new EidosFileError(\"invalid-query\", \"Invalid filter rule\")\n }\n if (filter.operator === \"is-relative-to-today\") {\n if (!isRelativeDateValue(filter.value)) {\n throw new EidosFileError(\n \"invalid-query\",\n \"Relative date filter value is invalid\"\n )\n }\n return\n }\n const values = Array.isArray(filter.value) ? filter.value : [filter.value]\n if (\n values.length > 500 ||\n values.some(\n (entry) =>\n entry !== undefined &&\n entry !== null &&\n typeof entry !== \"string\" &&\n typeof entry !== \"number\" &&\n typeof entry !== \"boolean\"\n )\n ) {\n throw new EidosFileError(\n \"query-limit\",\n \"Filter values exceed the query limit\"\n )\n }\n if (filter.operator === \"is-between\" && values.length !== 2) {\n throw new EidosFileError(\n \"invalid-query\",\n \"Between filter requires exactly two values\"\n )\n }\n }\n if (query.filter !== undefined && query.filter !== null)\n visit(query.filter, 0)\n}\n\nexport interface CompiledEidosFileRowQuery {\n whereSql: string\n orderSql: string\n params: EidosFileSqlParams\n}\n\nfunction filterValue(value: unknown): EidosFileFilterValue | undefined {\n return value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ? value\n : undefined\n}\n\nfunction isRelativeDateValue(\n value: unknown\n): value is EidosFileRelativeDateValue {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false\n const candidate = value as Record<string, unknown>\n return (\n [\"past\", \"next\", \"this\"].includes(String(candidate.direction)) &&\n [\"day\", \"week\", \"month\", \"year\"].includes(String(candidate.unit))\n )\n}\n\nfunction normalizeFilterNode(\n value: unknown,\n depth: number\n): EidosFileFilterRule | EidosFileFilterGroup | null {\n if (depth > MAX_QUERY_DEPTH || typeof value !== \"object\" || value === null)\n return null\n const candidate = value as Record<string, unknown>\n if (candidate.type === \"rule\") {\n if (\n typeof candidate.field !== \"string\" ||\n !isEidosFileFilterOperator(candidate.operator)\n ) {\n return null\n }\n const values: EidosFileFilterRuleValue | undefined =\n candidate.operator === \"is-relative-to-today\" &&\n isRelativeDateValue(candidate.value)\n ? {\n direction: candidate.value.direction,\n unit: candidate.value.unit,\n }\n : Array.isArray(candidate.value)\n ? candidate.value.flatMap((entry) => {\n const normalized = filterValue(entry)\n return normalized === undefined ? [] : [normalized]\n })\n : filterValue(candidate.value)\n return {\n type: \"rule\",\n field: candidate.field,\n operator: candidate.operator as EidosFileFilterRule[\"operator\"],\n ...(values === undefined ? {} : { value: values }),\n }\n }\n if (candidate.type !== \"group\" || !Array.isArray(candidate.children)) {\n return null\n }\n return {\n type: \"group\",\n conjunction: candidate.conjunction === \"or\" ? \"or\" : \"and\",\n ...(candidate.negated === true ? { negated: true } : {}),\n children: candidate.children.flatMap((child) => {\n const normalized = normalizeFilterNode(child, depth + 1)\n return normalized ? [normalized] : []\n }),\n }\n}\n\nexport function normalizeEidosFileFilter(\n value: unknown\n): EidosFileFilterGroup | null {\n const normalized = normalizeFilterNode(value, 0)\n return normalized?.type === \"group\" ? normalized : null\n}\n\nexport function removeEidosFileFilterField(\n group: EidosFileFilterGroup | null,\n field: string\n): EidosFileFilterGroup | null {\n if (!group) return null\n const children: EidosFileFilterGroup[\"children\"] = []\n for (const child of group.children) {\n if (child.type === \"rule\") {\n if (child.field !== field) children.push(child)\n continue\n }\n const nested = removeEidosFileFilterField(child, field)\n if (nested && nested.children.length > 0) children.push(nested)\n }\n return {\n ...group,\n children,\n }\n}\n\nexport function normalizeEidosFileSorts(value: unknown): EidosFileSort[] {\n if (!Array.isArray(value)) return []\n return value.flatMap((entry) => {\n if (\n typeof entry !== \"object\" ||\n entry === null ||\n typeof (entry as { field?: unknown }).field !== \"string\"\n ) {\n return []\n }\n return [\n {\n field: (entry as { field: string }).field,\n direction:\n (entry as { direction?: unknown }).direction === \"desc\"\n ? (\"desc\" as const)\n : (\"asc\" as const),\n nulls:\n (entry as { nulls?: unknown }).nulls === \"first\"\n ? (\"first\" as const)\n : (\"last\" as const),\n },\n ]\n })\n}\n\nexport function normalizeEidosFileRowQuery(value: unknown): EidosFileRowQuery {\n if (typeof value !== \"object\" || value === null) return {}\n const candidate = value as Record<string, unknown>\n return {\n ...(typeof candidate.search === \"string\"\n ? { search: candidate.search }\n : {}),\n ...(Array.isArray(candidate.searchFields) &&\n candidate.searchFields.every((field) => typeof field === \"string\")\n ? { searchFields: [...candidate.searchFields] as string[] }\n : {}),\n filter: normalizeEidosFileFilter(candidate.filter),\n sorts: normalizeEidosFileSorts(candidate.sorts),\n }\n}\n\nfunction escapeLike(value: string): string {\n return value.replace(/[\\\\%_]/g, \"\\\\$&\")\n}\n\nfunction requiresUnicodeCasefold(value: string): boolean {\n const nonAscii = value.replace(/[\\x00-\\x7f]/g, \"\")\n return nonAscii.toUpperCase() !== nonAscii.toLowerCase()\n}\n\nfunction caseInsensitiveLike(\n expression: string,\n pattern: string,\n searchText: string,\n params: EidosFileSqlPrimitive[]\n): string {\n params.push(pattern)\n return requiresUnicodeCasefold(searchText)\n ? `eidos_casefold(COALESCE(CAST(${expression} AS TEXT), ''))\n LIKE eidos_casefold(?) ESCAPE '\\\\'`\n : `COALESCE(CAST(${expression} AS TEXT), '')\n LIKE ? COLLATE NOCASE ESCAPE '\\\\'`\n}\n\nfunction searchExpression(\n field: EidosFileFieldInfo,\n pattern: string,\n searchText: string,\n params: EidosFileSqlPrimitive[]\n): string {\n const column = quoteIdentifier(field.tableColumnName)\n const type = eidosFileFieldValueType(field)\n if (field.isRecordLabel && typeof type === \"string\") {\n const expression =\n type === \"checkbox\"\n ? `CASE ${column} WHEN 1 THEN 'true' WHEN 0 THEN 'false' ELSE NULL END`\n : type === \"number\"\n ? `eidos_canonical_number(${column})`\n : column\n return caseInsensitiveLike(expression, pattern, searchText, params)\n }\n const contextualRowIdLookup =\n field.type === \"lookup\" &&\n typeof type === \"object\" &&\n type.element === \"row-id\" &&\n typeof field.property?.relationField === \"string\"\n if (type === \"relation\" || contextualRowIdLookup) {\n const fragments = quoteIdentifier(`${field.tableColumnName}__search`)\n return `EXISTS (\n SELECT 1\n FROM json_each(\n CASE\n WHEN json_valid(${fragments}) AND json_type(${fragments}) = 'array'\n THEN ${fragments}\n ELSE '[]'\n END\n ) item\n WHERE ${caseInsensitiveLike(\"item.value\", pattern, searchText, params)}\n )`\n }\n const listElement =\n typeof type === \"object\"\n ? type.element\n : type === \"multi-select\"\n ? \"select\"\n : type === \"file\"\n ? \"file-entry\"\n : null\n const fileEntryPredicate = (entry: string): string => {\n const name = `json_extract(${entry}, '$.name')`\n const mediaType = `json_extract(${entry}, '$.mediaType')`\n const uri = `json_extract(${entry}, '$.uri')`\n return `(\n ${caseInsensitiveLike(name, pattern, searchText, params)}\n OR ${caseInsensitiveLike(mediaType, pattern, searchText, params)}\n OR (\n lower(COALESCE(CAST(${uri} AS TEXT), '')) NOT LIKE 'data:%'\n AND ${caseInsensitiveLike(uri, pattern, searchText, params)}\n )\n )`\n }\n if (type === \"file-entry\") {\n const entry = `CASE WHEN json_valid(${column}) THEN ${column} ELSE '{}' END`\n return fileEntryPredicate(entry)\n }\n if (listElement === null) {\n return caseInsensitiveLike(column, pattern, searchText, params)\n }\n return `EXISTS (\n SELECT 1\n FROM json_each(\n CASE\n WHEN json_valid(${column}) AND json_type(${column}) = 'array'\n THEN ${column}\n ELSE '[]'\n END\n ) item\n WHERE ${\n listElement === \"file-entry\"\n ? fileEntryPredicate(\n \"CASE WHEN item.type = 'object' THEN item.value ELSE '{}' END\"\n )\n : caseInsensitiveLike(\"item.value\", pattern, searchText, params)\n }\n )`\n}\n\nfunction searchableFields(\n fields: EidosFileFieldInfo[],\n selected?: readonly string[]\n): EidosFileFieldInfo[] {\n const selection = selected ? new Set(selected) : null\n return fields.filter(\n (field) =>\n (!selection || (!!field.id && selection.has(field.id))) &&\n (!field.isHidden || selection !== null) &&\n eidosFileFieldQueryCapabilities(field).searchable &&\n (field.isRecordLabel ||\n field.valueKind === \"source\" ||\n field.valueKind === \"materialized\" ||\n field.valueKind === \"derived\" ||\n field.valueKind === \"relation\" ||\n (selection !== null && field.valueKind === \"system\"))\n )\n}\n\nexport function eidosFileRowQuerySearchFields(\n fields: EidosFileFieldInfo[],\n query: EidosFileRowQuery\n): EidosFileFieldInfo[] {\n const normalized = normalizeEidosFileRowQuery(query)\n return normalized.search === undefined || normalized.search === \"\"\n ? []\n : searchableFields(fields, normalized.searchFields)\n}\n\nfunction collectFilterFields(\n filter: EidosFileFilterGroup | null | undefined,\n target: Set<string>\n): void {\n if (!filter) return\n for (const child of filter.children) {\n if (child.type === \"group\") {\n collectFilterFields(child, target)\n } else {\n target.add(child.field)\n }\n }\n}\n\n/**\n * Returns the columns whose values can affect whether a row matches a query.\n * Sort-only fields are intentionally excluded because counts do not depend on\n * row order. Consumers can add projected/grouped columns before building a\n * pruned derived-field source.\n */\nexport function eidosFileRowQueryPredicateColumns(\n fields: EidosFileFieldInfo[],\n query: EidosFileRowQuery\n): Set<string> {\n const normalized = normalizeEidosFileRowQuery(query)\n const columns = new Set<string>()\n if (normalized.search !== undefined && normalized.search !== \"\") {\n for (const field of searchableFields(fields, normalized.searchFields)) {\n columns.add(field.tableColumnName)\n }\n }\n collectFilterFields(normalized.filter, columns)\n return columns\n}\n\n/**\n * Returns whether changing the supplied columns can alter the rows or ordering\n * produced by a query. Derived-field dependencies are followed transitively so\n * renderers do not need to duplicate Eidos File query semantics.\n */\nexport function eidosFileRowQueryAffectedByFieldChanges(\n fields: EidosFileFieldInfo[],\n query: EidosFileRowQuery,\n changedColumns: Iterable<string>\n): boolean {\n const changed = new Set(changedColumns)\n if (changed.size === 0) return false\n\n const normalized = normalizeEidosFileRowQuery(query)\n const queriedColumns = eidosFileRowQueryPredicateColumns(fields, normalized)\n for (const sort of normalized.sorts ?? []) queriedColumns.add(sort.field)\n if (queriedColumns.size === 0) return false\n\n const fieldsByColumn = new Map(\n fields.map((field) => [field.tableColumnName, field])\n )\n const affected = (columnName: string, visiting: Set<string>): boolean => {\n if (changed.has(columnName)) return true\n if (visiting.has(columnName)) return false\n const field = fieldsByColumn.get(columnName)\n if (!field) return false\n\n const dependencies = new Set<string>()\n if (typeof field.sourceTableColumnName === \"string\") {\n dependencies.add(field.sourceTableColumnName)\n }\n if (Array.isArray(field.dependsOn)) {\n for (const dependency of field.dependsOn) {\n if (typeof dependency === \"string\") dependencies.add(dependency)\n }\n }\n if (dependencies.size === 0) return false\n\n const nextVisiting = new Set(visiting)\n nextVisiting.add(columnName)\n for (const dependency of dependencies) {\n if (affected(dependency, nextVisiting)) return true\n }\n return false\n }\n\n for (const columnName of queriedColumns) {\n if (affected(columnName, new Set())) return true\n }\n return false\n}\n\nfunction requireField(\n fields: Map<string, EidosFileFieldInfo>,\n columnName: string\n): EidosFileFieldInfo {\n const field = fields.get(columnName)\n if (!field) {\n throw new EidosFileError(\n \"field-not-found\",\n `Eidos File field not found: ${columnName}`\n )\n }\n return field\n}\n\nfunction sqlValue(value: EidosFileFilterValue): EidosFileSqlPrimitive {\n return typeof value === \"boolean\" ? (value ? 1 : 0) : value\n}\n\nfunction sqlFieldValue(\n field: EidosFileFieldInfo,\n value: EidosFileFilterValue\n): EidosFileSqlPrimitive {\n if (value === null) return null\n const type =\n (field.type === \"formula\" || field.type === \"lookup\") &&\n typeof field.property?.displayType === \"string\"\n ? field.property.displayType\n : field.type\n if (type === \"date\") {\n if (typeof value !== \"string\") {\n throw new EidosFileError(\n \"invalid-query\",\n `${field.name} filter values must use canonical YYYY-MM-DD text`\n )\n }\n return normalizeEidosFileDate(value, `${field.name} filter`)\n }\n if (\n type === \"datetime\" ||\n type === \"created-time\" ||\n type === \"last-edited-time\"\n ) {\n if (typeof value !== \"string\") {\n throw new EidosFileError(\n \"invalid-query\",\n `${field.name} filter values must be RFC 3339 text`\n )\n }\n return normalizeEidosFileInstant(value, `${field.name} filter`)\n }\n if (type === \"integer\") {\n if (\n typeof value !== \"string\" ||\n !/^(?:0|-[1-9][0-9]*|[1-9][0-9]*)$/u.test(value) ||\n value === \"-0\"\n ) {\n throw new EidosFileError(\n \"invalid-query\",\n `${field.name} filter values must be canonical signed int64 decimal text`\n )\n }\n const integer = BigInt(value)\n if (\n integer < -9_223_372_036_854_775_808n ||\n integer > 9_223_372_036_854_775_807n\n ) {\n throw new EidosFileError(\n \"invalid-query\",\n `${field.name} filter value is outside signed int64`\n )\n }\n return integer\n }\n return sqlValue(value)\n}\n\nfunction temporalFieldType(\n field: EidosFileFieldInfo\n): \"date\" | \"datetime\" | null {\n const type =\n (field.type === \"formula\" || field.type === \"lookup\") &&\n typeof field.property?.displayType === \"string\"\n ? field.property.displayType\n : field.type\n if (type === \"date\") return \"date\"\n if (\n type === \"datetime\" ||\n type === \"created-time\" ||\n type === \"last-edited-time\"\n ) {\n return \"datetime\"\n }\n return null\n}\n\nfunction shiftUtcMonth(instant: Date, amount: -1 | 1): Date {\n const result = new Date(instant.getTime())\n const day = result.getUTCDate()\n result.setUTCDate(1)\n result.setUTCMonth(result.getUTCMonth() + amount)\n const endOfTargetMonth = new Date(\n Date.UTC(result.getUTCFullYear(), result.getUTCMonth() + 1, 0)\n ).getUTCDate()\n result.setUTCDate(Math.min(day, endOfTargetMonth))\n return result\n}\n\nfunction shiftUtcYear(instant: Date, amount: -1 | 1): Date {\n const result = new Date(instant.getTime())\n const month = result.getUTCMonth()\n const day = result.getUTCDate()\n result.setUTCDate(1)\n result.setUTCFullYear(result.getUTCFullYear() + amount)\n result.setUTCMonth(month)\n const endOfTargetMonth = new Date(\n Date.UTC(result.getUTCFullYear(), month + 1, 0)\n ).getUTCDate()\n result.setUTCDate(Math.min(day, endOfTargetMonth))\n return result\n}\n\nfunction shiftUtcUnit(\n instant: Date,\n unit: EidosFileRelativeDateValue[\"unit\"],\n amount: -1 | 1\n): Date {\n if (unit === \"day\" || unit === \"week\") {\n const days = unit === \"day\" ? 1 : 7\n return new Date(instant.getTime() + amount * days * 86_400_000)\n }\n return unit === \"month\"\n ? shiftUtcMonth(instant, amount)\n : shiftUtcYear(instant, amount)\n}\n\nfunction utcPeriodStart(\n instant: Date,\n unit: EidosFileRelativeDateValue[\"unit\"]\n): Date {\n const year = instant.getUTCFullYear()\n const month = instant.getUTCMonth()\n const day = instant.getUTCDate()\n if (unit === \"year\") return new Date(Date.UTC(year, 0, 1))\n if (unit === \"month\") return new Date(Date.UTC(year, month, 1))\n const start = new Date(Date.UTC(year, month, day))\n if (unit === \"week\") {\n const daysSinceMonday = (start.getUTCDay() + 6) % 7\n start.setUTCDate(start.getUTCDate() - daysSinceMonday)\n }\n return start\n}\n\nfunction relativeTemporalBounds(\n relative: EidosFileRelativeDateValue,\n referenceInstant: string,\n type: \"date\" | \"datetime\"\n): [string, string] {\n const reference = new Date(\n normalizeEidosFileInstant(referenceInstant, \"Relative filter reference\")\n )\n const ordered = (() => {\n if (relative.direction === \"this\") {\n const start = utcPeriodStart(reference, relative.unit)\n const nextStart =\n relative.unit === \"day\" || relative.unit === \"week\"\n ? new Date(\n start.getTime() + (relative.unit === \"day\" ? 1 : 7) * 86_400_000\n )\n : shiftUtcUnit(start, relative.unit, 1)\n return [start, new Date(nextStart.getTime() - 1)]\n }\n const past = relative.direction === \"past\"\n const boundary = shiftUtcUnit(reference, relative.unit, past ? -1 : 1)\n return past ? [boundary, reference] : [reference, boundary]\n })()\n return ordered.map((value) =>\n type === \"date\" ? value.toISOString().slice(0, 10) : value.toISOString()\n ) as [string, string]\n}\n\nfunction likeExpression(\n field: EidosFileFieldInfo,\n operator: EidosFileFilterRule[\"operator\"],\n value: string,\n params: EidosFileSqlPrimitive[]\n): string {\n const column = quoteIdentifier(field.tableColumnName)\n const escaped = escapeLike(value)\n const pattern =\n operator === \"starts-with\"\n ? `${escaped}%`\n : operator === \"ends-with\"\n ? `%${escaped}`\n : `%${escaped}%`\n const arrayCodec =\n field.storageCodec === \"json_array\" || field.storageCodec === \"relation\"\n if (arrayCodec && (operator === \"contains\" || operator === \"not-contains\")) {\n params.push(value)\n const expression = `EXISTS (\n SELECT 1 FROM json_each(${column}) item\n WHERE item.type = 'text' AND item.value = ?\n )`\n return operator === \"not-contains\" ? `NOT (${expression})` : expression\n }\n const expression = arrayCodec\n ? `EXISTS (\n SELECT 1\n FROM json_each(\n CASE\n WHEN json_valid(${column}) AND json_type(${column}) = 'array'\n THEN ${column}\n ELSE '[]'\n END\n )\n WHERE ${caseInsensitiveLike(\"value\", pattern, value, params)}\n )`\n : `COALESCE(${caseInsensitiveLike(column, pattern, value, params)}, 0)`\n return operator === \"not-contains\" ? `NOT (${expression})` : expression\n}\n\nfunction compileRule(\n rule: EidosFileFilterRule,\n fields: Map<string, EidosFileFieldInfo>,\n params: EidosFileSqlPrimitive[],\n referenceInstant: string\n): string {\n const field = requireField(fields, rule.field)\n const column = quoteIdentifier(field.tableColumnName)\n const arrayCodec =\n field.storageCodec === \"json_array\" || field.storageCodec === \"relation\"\n const empty = arrayCodec\n ? `(${column} IS NULL OR (json_valid(${column}) AND json_type(${column}) = 'array' AND json_array_length(${column}) = 0))`\n : `(${column} IS NULL)`\n\n if (rule.operator === \"is-empty\") {\n return empty\n }\n if (rule.operator === \"is-not-empty\") {\n return `NOT ${empty}`\n }\n\n if (rule.operator === \"is-relative-to-today\") {\n const type = temporalFieldType(field)\n if (!type) {\n throw new EidosFileError(\n \"invalid-query\",\n `${field.name} does not support relative date filters`\n )\n }\n if (!isRelativeDateValue(rule.value)) {\n throw new EidosFileError(\n \"invalid-query\",\n `${field.name} relative date filter is invalid`\n )\n }\n const [lower, upper] = relativeTemporalBounds(\n rule.value,\n referenceInstant,\n type\n )\n params.push(lower, upper)\n return `COALESCE(${column} >= ? AND ${column} <= ?, 0)`\n }\n\n if (rule.operator === \"is-between\") {\n if (!Array.isArray(rule.value) || rule.value.length !== 2) {\n throw new EidosFileError(\n \"invalid-query\",\n `${field.name} between filter requires two values`\n )\n }\n const [lower, upper] = rule.value\n if (lower === null || upper === null) {\n throw new EidosFileError(\n \"invalid-query\",\n `${field.name} between filter values cannot be null`\n )\n }\n params.push(sqlFieldValue(field, lower), sqlFieldValue(field, upper))\n return `COALESCE(${column} >= ? AND ${column} <= ?, 0)`\n }\n\n if (\n rule.operator === \"is-any-of\" ||\n rule.operator === \"is-all-of\" ||\n rule.operator === \"is-none-of\"\n ) {\n const values = Array.isArray(rule.value) ? rule.value : []\n if (values.length === 0) return rule.operator === \"is-any-of\" ? \"0\" : \"1\"\n if (\n field.storageCodec === \"relation\" ||\n field.storageCodec === \"json_array\"\n ) {\n const expressions = values.map((entry) => {\n params.push(sqlValue(entry))\n const typePredicate =\n typeof entry === \"boolean\"\n ? `type = '${entry ? \"true\" : \"false\"}'`\n : typeof entry === \"number\"\n ? \"type IN ('integer', 'real')\"\n : entry === null\n ? \"type = 'null'\"\n : \"type = 'text'\"\n return `EXISTS (\n SELECT 1\n FROM json_each(\n CASE\n WHEN json_valid(${column}) AND json_type(${column}) = 'array'\n THEN ${column}\n ELSE '[]'\n END\n )\n WHERE ${typePredicate} AND value IS ?\n )`\n })\n const expression = `(${expressions.join(\n rule.operator === \"is-all-of\" ? \" AND \" : \" OR \"\n )})`\n return rule.operator === \"is-none-of\" ? `NOT (${expression})` : expression\n }\n params.push(...values.map((entry) => sqlFieldValue(field, entry)))\n if (rule.operator === \"is-all-of\") return \"0\"\n const expression = `COALESCE(${column} IN (${values.map(() => \"?\").join(\", \")}), 0)`\n return rule.operator === \"is-none-of\" ? `NOT (${expression})` : expression\n }\n\n const value = Array.isArray(rule.value) ? rule.value[0] : rule.value\n if (value !== null && typeof value === \"object\") {\n throw new EidosFileError(\n \"invalid-query\",\n `${field.name} filter has an invalid structured operand`\n )\n }\n if (rule.operator === \"equals\" || rule.operator === \"not-equals\") {\n if (arrayCodec && Array.isArray(rule.value)) {\n params.push(canonicalizeEidosFileJson(rule.value))\n return rule.operator === \"not-equals\"\n ? `${column} IS NOT ?`\n : `${column} IS ?`\n }\n if (value === null || value === undefined) {\n return `${column} IS ${rule.operator === \"not-equals\" ? \"NOT \" : \"\"}NULL`\n }\n params.push(sqlFieldValue(field, value))\n return rule.operator === \"not-equals\"\n ? `${column} IS NOT ?`\n : `${column} IS ?`\n }\n\n if (\n rule.operator === \"contains\" ||\n rule.operator === \"not-contains\" ||\n rule.operator === \"starts-with\" ||\n rule.operator === \"ends-with\"\n ) {\n return likeExpression(field, rule.operator, String(value ?? \"\"), params)\n }\n\n if (value === null || value === undefined) return \"0\"\n const comparisons: Partial<Record<EidosFileFilterOperator, string>> = {\n \"greater-than\": \">\",\n \"greater-than-or-equal\": \">=\",\n \"less-than\": \"<\",\n \"less-than-or-equal\": \"<=\",\n }\n const comparison = comparisons[rule.operator]\n if (!comparison) return \"0\"\n params.push(sqlFieldValue(field, value))\n return `COALESCE(${column} ${comparison} ?, 0)`\n}\n\nfunction compileGroup(\n group: EidosFileFilterGroup,\n fields: Map<string, EidosFileFieldInfo>,\n params: EidosFileSqlPrimitive[],\n referenceInstant: string\n): string {\n const children = group.children.map((child) =>\n child.type === \"group\"\n ? compileGroup(child, fields, params, referenceInstant)\n : compileRule(child, fields, params, referenceInstant)\n )\n const expression =\n children.length === 0\n ? group.conjunction === \"or\"\n ? \"0\"\n : \"1\"\n : `(${children.join(group.conjunction === \"or\" ? \" OR \" : \" AND \")})`\n return group.negated ? `NOT (${expression})` : expression\n}\n\nexport function eidosFileSortExpression(field: EidosFileFieldInfo): string {\n if (!eidosFileFieldQueryCapabilities(field).sortable) {\n throw new EidosFileError(\n \"invalid-query\",\n `${field.name} does not support sorting`\n )\n }\n return quoteIdentifier(field.tableColumnName)\n}\n\nfunction compileSorts(\n sorts: EidosFileSort[] | undefined,\n fields: Map<string, EidosFileFieldInfo>\n): string {\n const seen = new Set<string>()\n const clauses: string[] = []\n const uniqueSorts = (sorts ?? []).filter((sort) => {\n if (seen.has(sort.field)) return false\n seen.add(sort.field)\n return true\n })\n for (const [index, sort] of uniqueSorts.entries()) {\n const field = requireField(fields, sort.field)\n const capabilities = eidosFileFieldQueryCapabilities(field)\n if (\n !capabilities.sortable ||\n (capabilities.sortPosition === \"last\" && index < uniqueSorts.length - 1)\n ) {\n throw new EidosFileError(\n \"invalid-query\",\n `${field.name} does not support this sort position`\n )\n }\n const expression = eidosFileSortExpression(field)\n clauses.push(\n `${expression} ${\n sort.direction === \"desc\" ? \"DESC\" : \"ASC\"\n } NULLS ${sort.nulls === \"first\" ? \"FIRST\" : \"LAST\"}`\n )\n }\n clauses.push('\"__base_rowid\" ASC')\n return `ORDER BY ${clauses.join(\", \")}`\n}\n\nexport function compileEidosFileRowQuery(\n fields: EidosFileFieldInfo[],\n query: EidosFileRowQuery = {},\n context: { referenceInstant?: string } = {}\n): CompiledEidosFileRowQuery {\n query = normalizeEidosFileRowQuery(query)\n const byColumn = new Map(\n fields.map((field) => [field.tableColumnName, field])\n )\n const params: EidosFileSqlPrimitive[] = []\n const where: string[] = []\n const search = query.search\n if (search !== undefined && search !== \"\") {\n const pattern = `%${escapeLike(search)}%`\n const searchClauses = eidosFileRowQuerySearchFields(fields, query).map(\n (field) => searchExpression(field, pattern, search, params)\n )\n if (searchClauses.length > 0) where.push(`(${searchClauses.join(\" OR \")})`)\n }\n if (query.filter) {\n where.push(\n compileGroup(\n query.filter,\n byColumn,\n params,\n context.referenceInstant ?? currentEidosFileInstant()\n )\n )\n }\n return {\n whereSql: where.length > 0 ? `WHERE ${where.join(\" AND \")}` : \"\",\n orderSql: compileSorts(query.sorts, byColumn),\n params,\n }\n}\n","/** JSON values accepted by the Eidos 1.0 public protocols. */\nexport interface JsonObject {\n [key: string]: JsonValue\n}\n\nexport type JsonValue =\n | null\n | boolean\n | number\n | string\n | JsonValue[]\n | JsonObject\n\n/**\n * An immutable, independently owned octet sequence at a public boundary.\n * Implementations copy on ingress/egress; callers must treat this value as\n * immutable even though JavaScript's Uint8Array type itself is mutable.\n */\nexport type OwnedBytes = Uint8Array\n\nexport interface CancellationSignal {\n readonly aborted: boolean\n onAbort(callback: () => void): () => void\n}\n\nexport interface CancellationPort {\n cancelled(): boolean\n onCancel(callback: () => void): () => void\n}\n\nexport interface RequestContext {\n requestId: string\n deadlineMilliseconds?: number\n signal?: CancellationSignal\n}\n\nexport interface PublicationContext {\n cancellation: CancellationPort\n deadlineMilliseconds?: number\n}\n\nexport interface ByteSource {\n size: string\n read(\n offset: string,\n length: number,\n context: PublicationContext\n ): Promise<OwnedBytes>\n}\n\nexport interface ClockPort {\n nowInstant(): string\n nowMilliseconds(): number\n}\n\nexport interface EntropyPort {\n randomBytes(length: number): OwnedBytes\n}\n\nexport function cancellationPortFromSignal(\n signal?: CancellationSignal\n): CancellationPort {\n return {\n cancelled: () => signal?.aborted === true,\n onCancel: (callback) => signal?.onAbort(callback) ?? (() => undefined),\n }\n}\n\nexport class MemoryByteSource implements ByteSource {\n readonly size: string\n private released = false\n private readonly bytes: Uint8Array\n\n constructor(bytes: Uint8Array | ArrayBuffer) {\n this.bytes = new Uint8Array(\n bytes instanceof Uint8Array ? bytes.slice().buffer : bytes.slice(0)\n )\n this.size = String(this.bytes.byteLength)\n }\n\n async read(\n offset: string,\n length: number,\n context: PublicationContext\n ): Promise<OwnedBytes> {\n if (this.released) {\n throw byteSourceError(\n \"adapter-closed\",\n \"ByteSource was released\",\n false,\n true\n )\n }\n if (\n context.deadlineMilliseconds !== undefined &&\n (!Number.isSafeInteger(context.deadlineMilliseconds) ||\n context.deadlineMilliseconds < 1)\n ) {\n throw byteSourceError(\n \"invalid-argument\",\n \"deadlineMilliseconds must be a positive safe integer\"\n )\n }\n if (context.cancellation.cancelled()) {\n throw byteSourceError(\"cancelled\", \"ByteSource read was cancelled\")\n }\n let start: bigint\n try {\n start = parseNonNegativeInt64(offset, \"offset\")\n } catch (error) {\n throw byteSourceError(\n \"invalid-argument\",\n error instanceof Error ? error.message : \"Invalid ByteSource offset\"\n )\n }\n if (!Number.isSafeInteger(length) || length < 0) {\n throw byteSourceError(\n \"invalid-argument\",\n \"length must be a non-negative safe integer\"\n )\n }\n if (start > BigInt(this.bytes.byteLength)) {\n throw byteSourceError(\n \"invalid-argument\",\n \"offset exceeds ByteSource size\"\n )\n }\n const available = BigInt(this.bytes.byteLength) - start\n const count = Number(\n available < BigInt(length) ? available : BigInt(length)\n )\n return this.bytes.slice(Number(start), Number(start) + count)\n }\n\n release(): void {\n this.released = true\n }\n}\n\nfunction byteSourceError(\n code: \"adapter-closed\" | \"invalid-argument\" | \"cancelled\",\n message: string,\n retryable = false,\n fatal = false\n): Error & {\n code: typeof code\n retryable: boolean\n fatal: boolean\n} {\n return Object.assign(new Error(message), {\n name: \"EidosAdapterError\",\n code,\n retryable,\n fatal,\n })\n}\n\nexport function parseNonNegativeInt64(value: string, label: string): bigint {\n if (!/^(?:0|[1-9][0-9]*)$/.test(value)) {\n throw new RangeError(`${label} must be a canonical non-negative int64`)\n }\n const parsed = BigInt(value)\n if (parsed > 9_223_372_036_854_775_807n) {\n throw new RangeError(`${label} exceeds int64`)\n }\n return parsed\n}\n","import { EidosFileError } from \"./errors\"\nimport { isEidosFileUuid } from \"./identifiers\"\nimport type { EidosFileRelationValue, EidosFileRowValue } from \"./types\"\n\nconst MAX_RELATION_VALUES = 10_000\n\nfunction parseRelationIds(\n value: EidosFileRowValue | undefined\n): unknown[] | null {\n if (typeof value !== \"string\") return null\n try {\n const parsed: unknown = JSON.parse(value)\n return Array.isArray(parsed) ? parsed : null\n } catch {\n return null\n }\n}\n\nexport function decodeEidosFileRelationIds(\n value: EidosFileRowValue | undefined\n): string[] {\n if (value === undefined || value === null) return []\n const parsed = parseRelationIds(value)\n if (!parsed) {\n throw new EidosFileError(\n \"invalid-value\",\n \"Relation value must be a JSON array\"\n )\n }\n if (parsed.length > MAX_RELATION_VALUES) {\n throw new EidosFileError(\n \"resource-limit\",\n \"Relation contains too many targets\"\n )\n }\n if (!parsed.every(isEidosFileUuid)) {\n throw new EidosFileError(\n \"invalid-value\",\n \"Relation values must be lowercase hyphenated UUIDv7 strings\"\n )\n }\n if (new Set(parsed).size !== parsed.length) {\n throw new EidosFileError(\n \"invalid-value\",\n \"Relation target Row IDs must be unique\"\n )\n }\n return parsed as string[]\n}\n\nexport function encodeEidosFileRelationIds(ids: readonly string[]): string {\n if (ids.length > MAX_RELATION_VALUES) {\n throw new EidosFileError(\n \"resource-limit\",\n \"Relation contains too many targets\"\n )\n }\n if (!ids.every(isEidosFileUuid)) {\n throw new EidosFileError(\n \"invalid-value\",\n \"Relation values must be lowercase hyphenated UUIDv7 strings\"\n )\n }\n if (new Set(ids).size !== ids.length) {\n throw new EidosFileError(\n \"invalid-value\",\n \"Relation target Row IDs must be unique\"\n )\n }\n return JSON.stringify(ids)\n}\n\n/** Reads generated Relation presentation values, never canonical cells. */\nexport function decodeEidosFileRelationDisplay(\n value: EidosFileRowValue | undefined\n): EidosFileRelationValue[] {\n if (typeof value !== \"string\" || value.length === 0) return []\n try {\n const parsed: unknown = JSON.parse(value)\n if (!Array.isArray(parsed)) return []\n return parsed.slice(0, MAX_RELATION_VALUES).flatMap((entry) => {\n if (\n typeof entry !== \"object\" ||\n entry === null ||\n !(\"id\" in entry) ||\n !(\"title\" in entry) ||\n !isEidosFileUuid(entry.id) ||\n typeof entry.title !== \"string\"\n ) {\n return []\n }\n return [{ id: entry.id, title: entry.title }]\n })\n } catch {\n return []\n }\n}\n","import type { EidosFileConnection, EidosFileSqlPrimitive } from \"./connection\"\n\nconst INT64_MIN = -9_223_372_036_854_775_808n\nconst INT64_MAX = 9_223_372_036_854_775_807n\n\nexport function registerEidosFormulaFunctions(\n connection: EidosFileConnection\n): void {\n const fixed = (\n name: string,\n arity: number,\n operation: (...values: EidosFileSqlPrimitive[]) => EidosFileSqlPrimitive\n ) => connection.registerFunction(name, operation, arity)\n const fixedWhenMissing = (\n name: string,\n arity: number,\n operation: (...values: EidosFileSqlPrimitive[]) => EidosFileSqlPrimitive\n ) => {\n try {\n connection.get(`SELECT ${name}(1.5) AS value`)\n } catch {\n fixed(name, arity, operation)\n }\n }\n fixedWhenMissing(\"floor\", 1, (value) =>\n sqliteIntegralBoundary(value, Math.floor)\n )\n fixedWhenMissing(\"ceil\", 1, (value) =>\n sqliteIntegralBoundary(value, Math.ceil)\n )\n fixedWhenMissing(\"ceiling\", 1, (value) =>\n sqliteIntegralBoundary(value, Math.ceil)\n )\n fixedWhenMissing(\"sign\", 1, sqliteSign)\n fixed(\"eidos_formula_int_add\", 2, (a, b) => intBinary(a, b, (x, y) => x + y))\n fixed(\"eidos_formula_int_sub\", 2, (a, b) => intBinary(a, b, (x, y) => x - y))\n fixed(\"eidos_formula_int_mul\", 2, (a, b) => intBinary(a, b, (x, y) => x * y))\n fixed(\"eidos_formula_int_mod\", 2, (a, b) => {\n if (a === null || b === null) return null\n const left = asInteger(a)\n const right = asInteger(b)\n return right === 0n ? null : left % right\n })\n fixed(\"eidos_formula_int_neg\", 1, (value) => {\n if (value === null) return null\n const integer = asInteger(value)\n return integer === INT64_MIN ? null : -integer\n })\n fixed(\"eidos_formula_num_add\", 2, (a, b) =>\n numberBinary(a, b, (x, y) => x + y)\n )\n fixed(\"eidos_formula_num_sub\", 2, (a, b) =>\n numberBinary(a, b, (x, y) => x - y)\n )\n fixed(\"eidos_formula_num_mul\", 2, (a, b) =>\n numberBinary(a, b, (x, y) => x * y)\n )\n fixed(\"eidos_formula_num_div\", 2, (a, b) =>\n numberBinary(a, b, (x, y) => x / y)\n )\n fixed(\"eidos_formula_num_neg\", 1, (value) => {\n if (value === null) return null\n return finiteNumber(-asNumber(value))\n })\n for (const [suffix, predicate] of [\n [\"eq\", (order: number) => order === 0],\n [\"ne\", (order: number) => order !== 0],\n [\"lt\", (order: number) => order < 0],\n [\"lte\", (order: number) => order <= 0],\n [\"gt\", (order: number) => order > 0],\n [\"gte\", (order: number) => order >= 0],\n ] as const) {\n fixed(`eidos_formula_numeric_${suffix}`, 2, (a, b) => {\n if (a === null || b === null) return null\n return predicate(compareNumeric(a, b)) ? 1n : 0n\n })\n }\n}\n\nfunction sqliteIntegralBoundary(\n value: EidosFileSqlPrimitive,\n operation: (value: number) => number\n): bigint | number | null {\n if (value === null) return null\n if (typeof value === \"bigint\") return value\n if (typeof value !== \"number\" || !Number.isFinite(value))\n throw new TypeError(\"SQLite math function expected numeric input\")\n return operation(value)\n}\n\nfunction sqliteSign(value: EidosFileSqlPrimitive): bigint | null {\n if (value === null) return null\n if (typeof value === \"bigint\") return value < 0n ? -1n : value > 0n ? 1n : 0n\n if (typeof value !== \"number\" || !Number.isFinite(value))\n throw new TypeError(\"SQLite SIGN expected numeric input\")\n return value < 0 ? -1n : value > 0 ? 1n : 0n\n}\n\nfunction asInteger(value: EidosFileSqlPrimitive): bigint {\n if (typeof value === \"bigint\") return value\n if (typeof value === \"number\" && Number.isSafeInteger(value))\n return BigInt(value)\n throw new TypeError(\"Formula expected an Integer\")\n}\n\nfunction asNumber(value: EidosFileSqlPrimitive): number {\n if (typeof value === \"bigint\") return Number(value)\n if (typeof value === \"number\" && Number.isFinite(value)) return value\n throw new TypeError(\"Formula expected a Number\")\n}\n\nfunction boundedInteger(value: bigint): bigint | null {\n return value < INT64_MIN || value > INT64_MAX ? null : value\n}\n\nfunction intBinary(\n left: EidosFileSqlPrimitive,\n right: EidosFileSqlPrimitive,\n operation: (left: bigint, right: bigint) => bigint\n): bigint | null {\n if (left === null || right === null) return null\n return boundedInteger(operation(asInteger(left), asInteger(right)))\n}\n\nfunction finiteNumber(value: number): number | null {\n if (!Number.isFinite(value)) return null\n return Object.is(value, -0) ? 0 : value\n}\n\nfunction numberBinary(\n left: EidosFileSqlPrimitive,\n right: EidosFileSqlPrimitive,\n operation: (left: number, right: number) => number\n): number | null {\n if (left === null || right === null) return null\n return finiteNumber(operation(asNumber(left), asNumber(right)))\n}\n\nfunction compareNumeric(\n left: EidosFileSqlPrimitive,\n right: EidosFileSqlPrimitive\n): number {\n if (typeof left === \"bigint\" && typeof right === \"bigint\") {\n return left < right ? -1 : left > right ? 1 : 0\n }\n if (typeof left === \"number\" && typeof right === \"number\") {\n return left < right ? -1 : left > right ? 1 : 0\n }\n if (typeof left === \"bigint\" && typeof right === \"number\") {\n return compareIntegerAndNumber(left, right)\n }\n if (typeof left === \"number\" && typeof right === \"bigint\") {\n return -compareIntegerAndNumber(right, left)\n }\n throw new TypeError(\"Formula expected numeric operands\")\n}\n\nfunction compareIntegerAndNumber(integer: bigint, number: number): number {\n if (!Number.isFinite(number))\n throw new TypeError(\"Formula Number is non-finite\")\n const { numerator, denominator } = binary64Rational(number)\n const scaled = integer * denominator\n return scaled < numerator ? -1 : scaled > numerator ? 1 : 0\n}\n\nfunction binary64Rational(value: number): {\n numerator: bigint\n denominator: bigint\n} {\n if (value === 0) return { numerator: 0n, denominator: 1n }\n const bytes = new ArrayBuffer(8)\n const view = new DataView(bytes)\n view.setFloat64(0, value, false)\n const bits = view.getBigUint64(0, false)\n const negative = bits >> 63n === 1n\n const exponentBits = Number((bits >> 52n) & 0x7ffn)\n const fraction = bits & ((1n << 52n) - 1n)\n const significand = exponentBits === 0 ? fraction : (1n << 52n) | fraction\n const exponent = (exponentBits === 0 ? -1022 : exponentBits - 1023) - 52\n const signed = negative ? -significand : significand\n return exponent >= 0\n ? { numerator: signed << BigInt(exponent), denominator: 1n }\n : { numerator: signed, denominator: 1n << BigInt(-exponent) }\n}\n","import { canonicalizeEidosFileJson } from \"./canonical-json\"\nimport type { EidosFileConnection, EidosFileSqlPrimitive } from \"./connection\"\n\nconst INT64_MIN = -9_223_372_036_854_775_808n\nconst INT64_MAX = 9_223_372_036_854_775_807n\n\ntype LookupAtom =\n | null\n | bigint\n | number\n | boolean\n | string\n | Record<string, unknown>\n\nexport function registerEidosLookupFunctions(\n connection: EidosFileConnection\n): void {\n connection.registerFunction(\n \"eidos_lookup_aggregate\",\n (payload, aggregate, distinct, elementType) =>\n lookupAggregate(payload, aggregate, distinct, elementType),\n 4\n )\n}\n\nfunction lookupAggregate(\n payloadValue: EidosFileSqlPrimitive,\n aggregateValue: EidosFileSqlPrimitive,\n distinctValue: EidosFileSqlPrimitive,\n elementTypeValue: EidosFileSqlPrimitive\n): EidosFileSqlPrimitive {\n if (\n typeof payloadValue !== \"string\" ||\n typeof aggregateValue !== \"string\" ||\n typeof elementTypeValue !== \"string\"\n )\n return null\n try {\n const parsed = JSON.parse(payloadValue) as Array<{ v: unknown }>\n if (!Array.isArray(parsed)) return null\n let values = parsed.map((entry) =>\n decodeLookupAtom(entry?.v, elementTypeValue)\n )\n if (distinctValue === 1 || distinctValue === 1n) {\n const seen = new Set<string>()\n values = values.filter((value) => {\n const key = lookupAtomKey(value, elementTypeValue)\n if (seen.has(key)) return false\n seen.add(key)\n return true\n })\n }\n if (aggregateValue === \"values\") {\n return canonicalizeEidosFileJson(\n values.map((value) => publicLookupAtom(value, elementTypeValue))\n )\n }\n if (aggregateValue === \"first\")\n return values.length === 0\n ? null\n : sqlLookupAtom(values[0]!, elementTypeValue)\n const nonNull = values.filter(\n (value): value is Exclude<LookupAtom, null> => value !== null\n )\n if (aggregateValue === \"count\") return BigInt(nonNull.length)\n if (aggregateValue === \"sum\") {\n if (nonNull.length === 0) return null\n if (elementTypeValue === \"integer\") {\n const result = nonNull.reduce<bigint>(\n (sum, value) => sum + (value as bigint),\n 0n\n )\n return boundedInteger(result)\n }\n return finiteNumber(pairwiseBinary64(nonNull as number[]))\n }\n if (aggregateValue === \"average\") {\n if (nonNull.length === 0) return null\n const result =\n elementTypeValue === \"integer\"\n ? rationalToBinary64(\n nonNull.reduce<bigint>(\n (sum, value) => sum + (value as bigint),\n 0n\n ),\n BigInt(nonNull.length)\n )\n : pairwiseBinary64(nonNull as number[]) / nonNull.length\n return finiteNumber(result)\n }\n if (aggregateValue === \"min\" || aggregateValue === \"max\") {\n if (nonNull.length === 0) return null\n let selected = nonNull[0]!\n for (const candidate of nonNull.slice(1)) {\n const order = compareLookupAtoms(candidate, selected, elementTypeValue)\n if (\n (aggregateValue === \"min\" && order < 0) ||\n (aggregateValue === \"max\" && order > 0)\n )\n selected = candidate\n }\n return sqlLookupAtom(selected, elementTypeValue)\n }\n return null\n } catch {\n return null\n }\n}\n\nfunction decodeLookupAtom(value: unknown, type: string): LookupAtom {\n if (value === null) return null\n if (type === \"integer\") return BigInt(String(value))\n if (type === \"number\") {\n const number = Number(value)\n if (!Number.isFinite(number)) throw new TypeError(\"Invalid Number\")\n return Object.is(number, -0) ? 0 : number\n }\n if (type === \"checkbox\") return value === true || value === 1\n if (type === \"file-entry\") {\n const object =\n typeof value === \"string\" ? (JSON.parse(value) as unknown) : value\n if (!object || typeof object !== \"object\" || Array.isArray(object))\n throw new TypeError(\"Invalid File entry\")\n return JSON.parse(canonicalizeEidosFileJson(object)) as Record<\n string,\n unknown\n >\n }\n if (typeof value !== \"string\") throw new TypeError(\"Invalid text atom\")\n return value\n}\n\nfunction publicLookupAtom(value: LookupAtom, type: string): unknown {\n if (value === null) return null\n if (type === \"integer\") return String(value)\n return value\n}\n\nfunction sqlLookupAtom(value: LookupAtom, type: string): EidosFileSqlPrimitive {\n if (value === null) return null\n if (type === \"checkbox\") return value === true ? 1n : 0n\n if (type === \"file-entry\") return canonicalizeEidosFileJson(value)\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\"\n )\n return value\n return null\n}\n\nfunction lookupAtomKey(value: LookupAtom, type: string): string {\n if (value === null) return \"null\"\n if (type === \"number\") return `number:${numberKey(value as number)}`\n if (type === \"integer\") return `integer:${String(value)}`\n if (type === \"checkbox\") return `checkbox:${value === true ? 1 : 0}`\n if (type === \"file-entry\")\n return `file-entry:${canonicalizeEidosFileJson(value)}`\n return `${type}:${String(value)}`\n}\n\nfunction numberKey(value: number): string {\n const normalized = Object.is(value, -0) ? 0 : value\n const buffer = new ArrayBuffer(8)\n const view = new DataView(buffer)\n view.setFloat64(0, normalized, false)\n return view.getBigUint64(0, false).toString(16).padStart(16, \"0\")\n}\n\nfunction compareLookupAtoms(\n left: Exclude<LookupAtom, null>,\n right: Exclude<LookupAtom, null>,\n type: string\n): number {\n if (type === \"integer\" || type === \"number\")\n return left < right ? -1 : left > right ? 1 : 0\n if (type === \"checkbox\") return left === right ? 0 : left ? 1 : -1\n return compareUtf8(String(left), String(right))\n}\n\nfunction compareUtf8(left: string, right: string): number {\n const encoder = new TextEncoder()\n const a = encoder.encode(left)\n const b = encoder.encode(right)\n const length = Math.min(a.length, b.length)\n for (let index = 0; index < length; index += 1) {\n if (a[index] !== b[index]) return a[index]! < b[index]! ? -1 : 1\n }\n return a.length < b.length ? -1 : a.length > b.length ? 1 : 0\n}\n\nfunction boundedInteger(value: bigint): bigint | null {\n return value < INT64_MIN || value > INT64_MAX ? null : value\n}\n\nfunction finiteNumber(value: number): number | null {\n if (!Number.isFinite(value)) return null\n return Object.is(value, -0) ? 0 : value\n}\n\nfunction pairwiseBinary64(values: number[]): number {\n let level = values.slice()\n while (level.length > 1) {\n const next: number[] = []\n for (let index = 0; index < level.length; index += 2) {\n next.push(\n index + 1 < level.length\n ? level[index]! + level[index + 1]!\n : level[index]!\n )\n }\n level = next\n }\n return level[0] ?? 0\n}\n\nfunction rationalToBinary64(numerator: bigint, denominator: bigint): number {\n if (numerator === 0n) return 0\n const negative = numerator < 0n\n const absolute = negative ? -numerator : numerator\n let exponent = bitLength(absolute) - bitLength(denominator)\n if (exponent >= 0) {\n if (absolute < denominator << BigInt(exponent)) exponent -= 1\n } else if (absolute << BigInt(-exponent) < denominator) exponent -= 1\n let result: number\n if (exponent >= -1022) {\n const shift = 52 - exponent\n const scaledNumerator = shift >= 0 ? absolute << BigInt(shift) : absolute\n const scaledDenominator =\n shift >= 0 ? denominator : denominator << BigInt(-shift)\n let significand = divideRoundTiesEven(scaledNumerator, scaledDenominator)\n if (significand === 9_007_199_254_740_992n) {\n significand >>= 1n\n exponent += 1\n }\n result = Number(significand) * 2 ** (exponent - 52)\n } else {\n result =\n Number(divideRoundTiesEven(absolute << 1074n, denominator)) * 2 ** -1074\n }\n return negative ? -result : result\n}\n\nfunction bitLength(value: bigint): number {\n return value.toString(2).length\n}\n\nfunction divideRoundTiesEven(numerator: bigint, denominator: bigint): bigint {\n const quotient = numerator / denominator\n const remainder = numerator % denominator\n const doubled = remainder * 2n\n return doubled > denominator ||\n (doubled === denominator && quotient % 2n !== 0n)\n ? quotient + 1n\n : quotient\n}\n","import type { EidosFileConnection } from \"./connection\"\nimport {\n EIDOS_FILE_APPLICATION_ID,\n EIDOS_FILE_FORMAT_VERSION,\n EIDOS_FILE_SCHEMA_VERSION,\n} from \"./constants\"\nimport { EidosFileError } from \"./errors\"\nimport {\n assertEidosFileDisplayName,\n assertEidosFileUuid,\n createEidosFileUuid,\n} from \"./identifiers\"\nimport { currentEidosFileInstant, normalizeEidosFileInstant } from \"./temporal\"\nimport type { CreateEidosFileOptions } from \"./types\"\n\n/**\n * Canonical metadata DDL from Eidos File Format 1.0 section 7.\n *\n * Keep this definition format-owned. Runtime, Adapter, and UI code must not\n * introduce alternate metadata columns or duplicate semantic state.\n */\nexport const EIDOS_FILE_SCHEMA_SQL = `\nCREATE TABLE eidos__tables(\n id TEXT PRIMARY KEY COLLATE BINARY\n CHECK(length(CAST(id AS BLOB))=36 AND instr(id,char(0))=0\n AND substr(id,9,1)='-' AND substr(id,14,1)='-'\n AND substr(id,15,1)='7' AND substr(id,19,1)='-'\n AND substr(id,20,1) IN ('8','9','a','b') AND substr(id,24,1)='-'\n AND lower(id)=id AND length(CAST(replace(id,'-','') AS BLOB))=32\n AND replace(id,'-','') NOT GLOB '*[^0-9a-f]*'),\n name TEXT NOT NULL COLLATE NOCASE UNIQUE\n CHECK(length(CAST(name AS BLOB)) BETWEEN 1 AND 1024\n AND instr(name,char(0))=0\n AND lower(substr(name,1,7)) NOT IN ('sqlite_','eidos__')),\n physical_name TEXT NOT NULL COLLATE NOCASE UNIQUE\n CHECK(length(CAST(physical_name AS BLOB)) BETWEEN 1 AND 1024\n AND instr(physical_name,char(0))=0\n AND physical_name COLLATE BINARY = name COLLATE BINARY),\n label_field_id TEXT NOT NULL COLLATE BINARY,\n position INTEGER NOT NULL DEFAULT 0,\n settings_json TEXT NOT NULL DEFAULT '{}'\n CHECK(json_valid(settings_json) AND json_type(settings_json)='object'),\n created_at TEXT NOT NULL\n CHECK(length(CAST(created_at AS BLOB))=24\n AND created_at GLOB\n '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'\n AND substr(created_at,1,4)<>'0000'\n AND coalesce(\n strftime('%Y-%m-%dT%H:%M:%fZ',created_at,'+0 seconds')=created_at,0)),\n updated_at TEXT NOT NULL\n CHECK(length(CAST(updated_at AS BLOB))=24\n AND updated_at GLOB\n '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'\n AND substr(updated_at,1,4)<>'0000'\n AND coalesce(\n strftime('%Y-%m-%dT%H:%M:%fZ',updated_at,'+0 seconds')=updated_at,0)),\n FOREIGN KEY(label_field_id) REFERENCES eidos__fields(id)\n DEFERRABLE INITIALLY DEFERRED\n) STRICT, WITHOUT ROWID;\n\nCREATE TABLE eidos__fields(\n id TEXT PRIMARY KEY COLLATE BINARY\n CHECK(length(CAST(id AS BLOB))=36 AND instr(id,char(0))=0\n AND substr(id,9,1)='-' AND substr(id,14,1)='-'\n AND substr(id,15,1)='7' AND substr(id,19,1)='-'\n AND substr(id,20,1) IN ('8','9','a','b') AND substr(id,24,1)='-'\n AND lower(id)=id AND length(CAST(replace(id,'-','') AS BLOB))=32\n AND replace(id,'-','') NOT GLOB '*[^0-9a-f]*'),\n table_id TEXT NOT NULL COLLATE BINARY\n REFERENCES eidos__tables(id) ON DELETE CASCADE,\n name TEXT NOT NULL\n CHECK(length(CAST(name AS BLOB)) BETWEEN 1 AND 1024 AND instr(name,char(0))=0),\n physical_name TEXT COLLATE NOCASE\n CHECK(physical_name IS NULL OR\n (length(CAST(physical_name AS BLOB)) BETWEEN 1 AND 1024\n AND instr(physical_name,char(0))=0\n AND physical_name COLLATE BINARY = name COLLATE BINARY)),\n type TEXT NOT NULL CHECK(type IN (\n 'text','number','integer','checkbox','date','datetime','url',\n 'select','multi-select','file','relation','formula','lookup'\n )),\n system_role TEXT CHECK(system_role IN ('row-id','created-time','updated-time')),\n nullable INTEGER NOT NULL DEFAULT 1 CHECK(nullable IN (0,1)),\n position INTEGER NOT NULL DEFAULT 0,\n settings_json TEXT NOT NULL DEFAULT '{}'\n CHECK(json_valid(settings_json) AND json_type(settings_json)='object'),\n created_at TEXT NOT NULL\n CHECK(length(CAST(created_at AS BLOB))=24\n AND created_at GLOB\n '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'\n AND substr(created_at,1,4)<>'0000'\n AND coalesce(\n strftime('%Y-%m-%dT%H:%M:%fZ',created_at,'+0 seconds')=created_at,0)),\n updated_at TEXT NOT NULL\n CHECK(length(CAST(updated_at AS BLOB))=24\n AND updated_at GLOB\n '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'\n AND substr(updated_at,1,4)<>'0000'\n AND coalesce(\n strftime('%Y-%m-%dT%H:%M:%fZ',updated_at,'+0 seconds')=updated_at,0)),\n UNIQUE(table_id,name COLLATE NOCASE),\n UNIQUE(table_id,physical_name COLLATE NOCASE),\n CHECK(physical_name IS NOT NULL OR type IN ('relation','formula','lookup')),\n CHECK(system_role IS NULL OR\n (system_role='row-id' AND type='text' AND physical_name='_id' AND nullable=0) OR\n (system_role='created-time' AND type='datetime'\n AND physical_name='_created_at' AND nullable=0) OR\n (system_role='updated-time' AND type='datetime'\n AND physical_name='_updated_at' AND nullable=0))\n) STRICT, WITHOUT ROWID;\n\nCREATE UNIQUE INDEX eidos__fields_one_system_role\n ON eidos__fields(table_id,system_role) WHERE system_role IS NOT NULL;\n\nCREATE TABLE eidos__meta(\n singleton INTEGER PRIMARY KEY CHECK(singleton=1),\n format_major INTEGER NOT NULL CHECK(format_major=1),\n format_minor INTEGER NOT NULL CHECK(format_minor=0),\n file_id TEXT NOT NULL UNIQUE COLLATE BINARY\n CHECK(length(CAST(file_id AS BLOB))=36 AND instr(file_id,char(0))=0\n AND substr(file_id,9,1)='-' AND substr(file_id,14,1)='-'\n AND substr(file_id,15,1)='7' AND substr(file_id,19,1)='-'\n AND substr(file_id,20,1) IN ('8','9','a','b') AND substr(file_id,24,1)='-'\n AND lower(file_id)=file_id\n AND length(CAST(replace(file_id,'-','') AS BLOB))=32\n AND replace(file_id,'-','') NOT GLOB '*[^0-9a-f]*'),\n title TEXT NOT NULL\n CHECK(length(CAST(title AS BLOB)) BETWEEN 1 AND 1024 AND instr(title,char(0))=0),\n default_table_id TEXT COLLATE BINARY\n REFERENCES eidos__tables(id) DEFERRABLE INITIALLY DEFERRED,\n revision INTEGER NOT NULL DEFAULT 0 CHECK(revision>=0),\n created_at TEXT NOT NULL\n CHECK(length(CAST(created_at AS BLOB))=24\n AND created_at GLOB\n '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'\n AND substr(created_at,1,4)<>'0000'\n AND coalesce(\n strftime('%Y-%m-%dT%H:%M:%fZ',created_at,'+0 seconds')=created_at,0)),\n updated_at TEXT NOT NULL\n CHECK(length(CAST(updated_at AS BLOB))=24\n AND updated_at GLOB\n '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'\n AND substr(updated_at,1,4)<>'0000'\n AND coalesce(\n strftime('%Y-%m-%dT%H:%M:%fZ',updated_at,'+0 seconds')=updated_at,0))\n) STRICT, WITHOUT ROWID;\n\nCREATE TRIGGER eidos__meta_no_delete BEFORE DELETE ON eidos__meta\nBEGIN SELECT RAISE(ABORT,'eidos_meta_required'); END;\n\nCREATE TRIGGER eidos__meta_no_key_update BEFORE UPDATE OF singleton ON eidos__meta\nBEGIN SELECT RAISE(ABORT,'eidos_meta_singleton'); END;\n\nCREATE TABLE eidos__features(\n name TEXT PRIMARY KEY COLLATE BINARY\n CHECK(length(CAST(name AS BLOB)) BETWEEN 1 AND 255 AND instr(name,char(0))=0),\n version TEXT NOT NULL\n CHECK(length(CAST(version AS BLOB)) BETWEEN 1 AND 64 AND instr(version,char(0))=0),\n required INTEGER NOT NULL DEFAULT 0 CHECK(required IN (0,1)),\n config_json TEXT NOT NULL DEFAULT '{}'\n CHECK(json_valid(config_json) AND json_type(config_json)='object')\n) STRICT, WITHOUT ROWID;\n\nCREATE TABLE eidos__relation_fields(\n field_id TEXT PRIMARY KEY COLLATE BINARY\n REFERENCES eidos__fields(id) ON DELETE CASCADE,\n direction TEXT NOT NULL CHECK(direction IN ('forward','inverse')),\n target_table_id TEXT NOT NULL COLLATE BINARY REFERENCES eidos__tables(id),\n cardinality TEXT NOT NULL CHECK(cardinality IN ('one','many')),\n inverse_of_field_id TEXT COLLATE BINARY\n REFERENCES eidos__fields(id) ON DELETE RESTRICT,\n on_delete TEXT DEFAULT 'restrict'\n CHECK(on_delete IN ('restrict','detach','preserve')),\n CHECK((direction='forward' AND inverse_of_field_id IS NULL AND on_delete IS NOT NULL)\n OR (direction='inverse' AND inverse_of_field_id IS NOT NULL\n AND cardinality='many' AND on_delete IS NULL))\n) STRICT, WITHOUT ROWID;\n\nCREATE UNIQUE INDEX eidos__relation_one_inverse\n ON eidos__relation_fields(inverse_of_field_id)\n WHERE inverse_of_field_id IS NOT NULL;\n\nCREATE TABLE eidos__formula_fields(\n field_id TEXT PRIMARY KEY COLLATE BINARY\n REFERENCES eidos__fields(id) ON DELETE CASCADE,\n source_text TEXT NOT NULL\n CHECK(length(CAST(source_text AS BLOB)) BETWEEN 1 AND 4096),\n result_type TEXT NOT NULL\n CHECK(result_type IN ('text','number','integer','checkbox','date','datetime','url'))\n) STRICT, WITHOUT ROWID;\n\nCREATE TABLE eidos__lookup_fields(\n field_id TEXT PRIMARY KEY COLLATE BINARY\n REFERENCES eidos__fields(id) ON DELETE CASCADE,\n relation_field_id TEXT NOT NULL COLLATE BINARY REFERENCES eidos__fields(id),\n target_field_id TEXT NOT NULL COLLATE BINARY REFERENCES eidos__fields(id),\n aggregate TEXT NOT NULL\n CHECK(aggregate IN ('values','first','count','sum','average','min','max')),\n distinct_values INTEGER NOT NULL DEFAULT 0 CHECK(distinct_values IN (0,1))\n) STRICT, WITHOUT ROWID;\n\nCREATE TABLE eidos__views(\n id TEXT PRIMARY KEY COLLATE BINARY\n CHECK(length(CAST(id AS BLOB))=36 AND instr(id,char(0))=0\n AND substr(id,9,1)='-' AND substr(id,14,1)='-'\n AND substr(id,15,1)='7' AND substr(id,19,1)='-'\n AND substr(id,20,1) IN ('8','9','a','b') AND substr(id,24,1)='-'\n AND lower(id)=id AND length(CAST(replace(id,'-','') AS BLOB))=32\n AND replace(id,'-','') NOT GLOB '*[^0-9a-f]*'),\n table_id TEXT NOT NULL COLLATE BINARY\n REFERENCES eidos__tables(id) ON DELETE CASCADE,\n name TEXT NOT NULL\n CHECK(length(CAST(name AS BLOB)) BETWEEN 1 AND 1024 AND instr(name,char(0))=0),\n type TEXT NOT NULL\n CHECK(length(CAST(type AS BLOB)) BETWEEN 1 AND 64 AND instr(type,char(0))=0),\n query_json TEXT NOT NULL DEFAULT '{}'\n CHECK(json_valid(query_json) AND json_type(query_json)='object'),\n layout_json TEXT NOT NULL DEFAULT '{}'\n CHECK(json_valid(layout_json) AND json_type(layout_json)='object'),\n position INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL\n CHECK(length(CAST(created_at AS BLOB))=24\n AND created_at GLOB\n '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'\n AND substr(created_at,1,4)<>'0000'\n AND coalesce(\n strftime('%Y-%m-%dT%H:%M:%fZ',created_at,'+0 seconds')=created_at,0)),\n updated_at TEXT NOT NULL\n CHECK(length(CAST(updated_at AS BLOB))=24\n AND updated_at GLOB\n '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'\n AND substr(updated_at,1,4)<>'0000'\n AND coalesce(\n strftime('%Y-%m-%dT%H:%M:%fZ',updated_at,'+0 seconds')=updated_at,0)),\n UNIQUE(table_id,name COLLATE NOCASE)\n) STRICT, WITHOUT ROWID;\n`\n\nfunction creationInstant(value: CreateEidosFileOptions[\"createdAt\"]): string {\n return value === undefined\n ? currentEidosFileInstant()\n : normalizeEidosFileInstant(value, \"createdAt\")\n}\n\nexport function configureEidosFileConnection(\n connection: EidosFileConnection\n): void {\n connection.exec(\n \"PRAGMA foreign_keys = ON; PRAGMA trusted_schema = OFF; PRAGMA legacy_alter_table = OFF;\"\n )\n}\n\nexport function initializeEidosFileSchema(\n connection: EidosFileConnection,\n options: CreateEidosFileOptions = {},\n transaction = true\n): void {\n const timestamp = creationInstant(options.createdAt)\n const fileId = assertEidosFileUuid(\n options.fileId ?? createEidosFileUuid(Date.parse(timestamp)),\n \"File ID\"\n )\n const title = assertEidosFileDisplayName(\n options.title ?? \"Untitled\",\n \"File title\"\n )\n configureEidosFileConnection(connection)\n const install = () => {\n connection.exec(\n `PRAGMA encoding = 'UTF-8'; PRAGMA application_id = ${EIDOS_FILE_APPLICATION_ID}; PRAGMA user_version = ${EIDOS_FILE_SCHEMA_VERSION};`\n )\n connection.exec(EIDOS_FILE_SCHEMA_SQL)\n connection.run(\n `INSERT INTO eidos__meta(\n singleton,format_major,format_minor,file_id,title,revision,created_at,updated_at\n ) VALUES(1,1,0,?,?,0,?,?)`,\n [fileId, title, timestamp, timestamp]\n )\n }\n if (transaction) connection.transaction(install)\n else install()\n}\n\nexport function incrementEidosFileRevision(\n connection: EidosFileConnection,\n updatedAt = currentEidosFileInstant()\n): number {\n const current = connection.get<{ revision: number | bigint }>(\n \"SELECT revision FROM eidos__meta WHERE singleton=1\"\n )?.revision\n if (current === undefined || BigInt(current) >= 9_223_372_036_854_775_807n) {\n throw new EidosFileError(\n \"resource-limit\",\n \"Eidos File revision has reached the signed int64 maximum\"\n )\n }\n connection.run(\n \"UPDATE eidos__meta SET revision=revision+1, updated_at=? WHERE singleton=1\",\n [normalizeEidosFileInstant(updatedAt, \"updatedAt\")]\n )\n const next = connection.get<{ revision: number | bigint }>(\n \"SELECT revision FROM eidos__meta WHERE singleton=1\"\n )?.revision\n return Number(next ?? 0)\n}\n\n/** Updates only metadata owned by Eidos File Format 1.0. */\nexport function setEidosFileMetadata(\n connection: EidosFileConnection,\n entries: Record<string, string | undefined>\n): void {\n const assignments: string[] = []\n const params: Array<string | null> = []\n if (entries.title !== undefined) {\n assignments.push(\"title=?\")\n params.push(assertEidosFileDisplayName(entries.title, \"File title\"))\n }\n if (entries.default_table_id !== undefined) {\n assignments.push(\"default_table_id=?\")\n params.push(\n entries.default_table_id === \"\"\n ? null\n : assertEidosFileUuid(entries.default_table_id, \"Default Table ID\")\n )\n }\n if (assignments.length === 0) return\n connection.transaction(() => {\n const before = connection.get<Record<string, string | null>>(\n \"SELECT title,default_table_id FROM eidos__meta WHERE singleton=1\"\n )\n const changed = assignments.some((assignment, index) => {\n const column = assignment.slice(0, assignment.indexOf(\"=\"))\n return before?.[column] !== params[index]\n })\n if (!changed) return\n connection.run(\n `UPDATE eidos__meta SET ${assignments.join(\",\")} WHERE singleton=1`,\n params\n )\n incrementEidosFileRevision(connection)\n })\n}\n\n/** Compatibility constant retained for existing callers. */\nexport const EIDOS_FILE_FORMAT_VERSION_TEXT = EIDOS_FILE_FORMAT_VERSION\n","import type { EidosFileConnection } from \"./connection\"\n\nconst DEFAULT_STABLE_ROW_PAGE_SIZE = 256\n\nfunction isQueryResultLimit(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error.code === \"resource-limit\" &&\n \"message\" in error &&\n typeof error.message === \"string\" &&\n /Query result exceeds maxResult(?:Rows|Bytes)/.test(error.message)\n )\n}\n\n/**\n * Reads a whole user Table without asking an Adapter to materialize the whole\n * result at once. Pages follow the canonical binary Row-ID order, and shrink\n * automatically when a page is still too large for the active Adapter.\n */\nexport function scanStableRowPages<T extends object>(\n connection: EidosFileConnection,\n options: {\n columnsSql: string\n tableSql: string\n rowIdSql: string\n rowIdKey: keyof T & string\n pageSize?: number\n },\n visit: (rows: T[]) => void\n): void {\n let afterRowId: string | null = null\n let pageSize = Math.max(\n 1,\n Math.floor(options.pageSize ?? DEFAULT_STABLE_ROW_PAGE_SIZE)\n )\n\n while (true) {\n let page: T[]\n while (true) {\n const where =\n afterRowId === null\n ? \"\"\n : ` WHERE ${options.rowIdSql} COLLATE BINARY > ?`\n const bindings = afterRowId === null ? [pageSize] : [afterRowId, pageSize]\n try {\n page = connection.query<T>(\n `SELECT ${options.columnsSql} FROM ${options.tableSql}${where} ORDER BY ${options.rowIdSql} COLLATE BINARY LIMIT ?`,\n bindings\n )\n break\n } catch (error) {\n if (!isQueryResultLimit(error) || pageSize === 1) throw error\n pageSize = Math.max(1, Math.floor(pageSize / 2))\n }\n }\n\n if (page.length === 0) return\n visit(page)\n const nextRowId = page.at(-1)?.[options.rowIdKey]\n if (typeof nextRowId !== \"string\" || nextRowId === afterRowId) {\n throw new Error(\"Stable row scan requires unique text Row IDs\")\n }\n afterRowId = nextRowId\n if (page.length < pageSize) return\n }\n}\n","/** Returns the globally smallest normalized simple directed cycle. */\nexport function smallestDependencyCycle(\n graph: Map<string, Set<string>>\n): string[] | undefined {\n const compare = (left: string, right: string) =>\n left < right ? -1 : left > right ? 1 : 0\n const nodes = Array.from(graph.keys()).sort(compare)\n for (const start of nodes) {\n const visited = new Set([start])\n const search = (current: string, path: string[]): string[] | undefined => {\n const neighbors = Array.from(graph.get(current) ?? []).sort(compare)\n for (const next of neighbors) {\n if (compare(next, start) < 0) continue\n if (next === start) return [...path, start]\n if (visited.has(next)) continue\n visited.add(next)\n const found = search(next, [...path, next])\n visited.delete(next)\n if (found) return found\n }\n return undefined\n }\n const found = search(start, [start])\n if (found) return found\n }\n return undefined\n}\n","import type { EidosFileConnection, EidosFileSqlPrimitive } from \"./connection\"\nimport { isEidosFileUriReference } from \"./canonical-conversion\"\nimport {\n EIDOS_FILE_APPLICATION_ID,\n EIDOS_FILE_FEATURES_TABLE,\n EIDOS_FILE_FIELDS_TABLE,\n EIDOS_FILE_FORMAT,\n EIDOS_FILE_FORMAT_VERSION,\n EIDOS_FILE_FORMULA_FIELDS_TABLE,\n EIDOS_FILE_LOOKUP_FIELDS_TABLE,\n EIDOS_FILE_META_TABLE,\n EIDOS_FILE_RELATION_FIELDS_TABLE,\n EIDOS_FILE_REQUIRED_TABLES,\n EIDOS_FILE_SCHEMA_VERSION,\n EIDOS_FILE_TABLES_TABLE,\n EIDOS_FILE_VIEWS_TABLE,\n} from \"./constants\"\nimport { compileEidosFileFormula } from \"./formula\"\nimport { smallestDependencyCycle } from \"./dependency-graph\"\nimport { decodeEidosFileValues } from \"./file-values\"\nimport {\n assertEidosFileDisplayName,\n isEidosFileReservedTableName,\n isEidosFileUuid,\n quoteIdentifier,\n} from \"./identifiers\"\nimport { isCanonicalEidosFileJson, parseEidosFileJson } from \"./canonical-json\"\nimport {\n assertEidosFileMultiSelectHasNoDefaultOption,\n assertEidosFileSelectDefaultOption,\n assertEidosFileSelectOptions,\n} from \"./select-options\"\nimport {\n isCanonicalEidosFileDate,\n isCanonicalEidosFileInstant,\n} from \"./temporal\"\nimport type {\n EidosFileFieldInfo,\n EidosFileFieldType,\n EidosFileMetadata,\n EidosFileStorageCodec,\n EidosFileTableInfo,\n EidosFileValidationIssue,\n EidosFileValidationResult,\n EidosFileValueKind,\n} from \"./types\"\n\nexport type EidosFileValidationLevel =\n | \"identity\"\n | \"structural\"\n | \"content\"\n | \"semantic\"\n | \"full\"\n\ninterface MetaRow {\n singleton: number\n format_major: number\n format_minor: number\n file_id: string\n revision: number | bigint\n title: string\n default_table_id: string | null\n created_at: string\n updated_at: string\n}\n\ninterface TableRow {\n id: string\n name: string\n physical_name: string\n label_field_id: string\n position: number\n settings_json: string\n created_at: string\n updated_at: string\n}\n\ninterface FieldRow {\n id: string\n table_id: string\n name: string\n physical_name: string | null\n type: string\n system_role: \"row-id\" | \"created-time\" | \"updated-time\" | null\n nullable: number\n position: number\n settings_json: string\n created_at: string\n updated_at: string\n}\n\ninterface RelationRow {\n field_id: string\n direction: \"forward\" | \"inverse\"\n inverse_of_field_id: string | null\n target_table_id: string\n cardinality: \"one\" | \"many\"\n on_delete: \"restrict\" | \"detach\" | \"preserve\" | null\n}\n\ninterface FormulaRow {\n field_id: string\n source_text: string\n result_type: string\n}\n\ninterface LookupRow {\n field_id: string\n relation_field_id: string\n target_field_id: string\n aggregate: \"first\" | \"values\" | \"count\" | \"sum\" | \"average\" | \"min\" | \"max\"\n distinct_values: number\n}\n\nconst REQUIRED_COLUMNS: Record<string, readonly string[]> = {\n [EIDOS_FILE_META_TABLE]: [\n \"singleton\",\n \"format_major\",\n \"format_minor\",\n \"file_id\",\n \"revision\",\n \"title\",\n \"default_table_id\",\n \"created_at\",\n \"updated_at\",\n ],\n [EIDOS_FILE_FEATURES_TABLE]: [\"name\", \"version\", \"required\", \"config_json\"],\n [EIDOS_FILE_TABLES_TABLE]: [\n \"id\",\n \"name\",\n \"physical_name\",\n \"label_field_id\",\n \"position\",\n \"settings_json\",\n \"created_at\",\n \"updated_at\",\n ],\n [EIDOS_FILE_FIELDS_TABLE]: [\n \"id\",\n \"table_id\",\n \"name\",\n \"physical_name\",\n \"type\",\n \"system_role\",\n \"nullable\",\n \"position\",\n \"settings_json\",\n \"created_at\",\n \"updated_at\",\n ],\n [EIDOS_FILE_RELATION_FIELDS_TABLE]: [\n \"field_id\",\n \"direction\",\n \"inverse_of_field_id\",\n \"target_table_id\",\n \"cardinality\",\n \"on_delete\",\n ],\n [EIDOS_FILE_FORMULA_FIELDS_TABLE]: [\"field_id\", \"source_text\", \"result_type\"],\n [EIDOS_FILE_LOOKUP_FIELDS_TABLE]: [\n \"field_id\",\n \"relation_field_id\",\n \"target_field_id\",\n \"aggregate\",\n \"distinct_values\",\n ],\n [EIDOS_FILE_VIEWS_TABLE]: [\n \"id\",\n \"table_id\",\n \"name\",\n \"type\",\n \"query_json\",\n \"layout_json\",\n \"position\",\n \"created_at\",\n \"updated_at\",\n ],\n}\n\nconst ID_COLUMNS: Record<string, readonly string[]> = {\n [EIDOS_FILE_META_TABLE]: [\"file_id\", \"default_table_id\"],\n [EIDOS_FILE_TABLES_TABLE]: [\"id\"],\n [EIDOS_FILE_FIELDS_TABLE]: [\"id\", \"table_id\"],\n [EIDOS_FILE_RELATION_FIELDS_TABLE]: [\n \"field_id\",\n \"inverse_of_field_id\",\n \"target_table_id\",\n ],\n [EIDOS_FILE_FORMULA_FIELDS_TABLE]: [\"field_id\"],\n [EIDOS_FILE_LOOKUP_FIELDS_TABLE]: [\n \"field_id\",\n \"relation_field_id\",\n \"target_field_id\",\n ],\n [EIDOS_FILE_VIEWS_TABLE]: [\"id\", \"table_id\"],\n}\n\nconst REQUIRED_INDEXES = new Set([\n \"eidos__fields_one_system_role\",\n \"eidos__relation_one_inverse\",\n])\n\nconst REQUIRED_TRIGGERS = new Set([\n \"eidos__meta_no_delete\",\n \"eidos__meta_no_key_update\",\n])\n\nconst DYNAMIC_TRIGGER_NAME =\n /^eidos__(?:row_id_immutable|relation_(?:validate_(?:insert|update)|restrict|detach))__[0-9a-f]{32}$/\nconst DYNAMIC_FIELD_INDEX_NAME = /^eidos__index__([0-9a-f]{32})$/\n\nconst FIELD_TYPES = new Set<EidosFileFieldType>([\n \"text\",\n \"number\",\n \"integer\",\n \"checkbox\",\n \"date\",\n \"datetime\",\n \"url\",\n \"file\",\n \"select\",\n \"multi-select\",\n \"relation\",\n \"formula\",\n \"lookup\",\n])\n\nconst LABEL_SCALAR_TYPES = new Set([\n \"text\",\n \"number\",\n \"integer\",\n \"checkbox\",\n \"date\",\n \"datetime\",\n \"url\",\n \"select\",\n])\n\nconst FORMULA_RESULT_TYPES = new Set([\n \"text\",\n \"number\",\n \"integer\",\n \"checkbox\",\n \"date\",\n \"datetime\",\n \"url\",\n])\n\nconst NUMERIC_LOOKUP_TYPES = new Set([\"number\", \"integer\"])\nconst INDEXABLE_FIELD_TYPES = new Set([\n \"text\",\n \"number\",\n \"integer\",\n \"checkbox\",\n \"date\",\n \"datetime\",\n \"url\",\n \"select\",\n])\nconst FILTER_OPERATORS = new Set([\n \"equals\",\n \"not-equals\",\n \"contains\",\n \"not-contains\",\n \"starts-with\",\n \"ends-with\",\n \"greater-than\",\n \"greater-than-or-equal\",\n \"less-than\",\n \"less-than-or-equal\",\n \"is-empty\",\n \"is-not-empty\",\n \"is-any-of\",\n \"is-all-of\",\n \"is-none-of\",\n \"is-between\",\n \"is-relative-to-today\",\n])\nconst RUNTIME_FILTER_OPERATORS = new Set([\n \"is-null\",\n \"is-not-null\",\n \"eq\",\n \"ne\",\n \"lt\",\n \"lte\",\n \"gt\",\n \"gte\",\n \"between\",\n \"in\",\n \"contains\",\n \"starts-with\",\n \"ends-with\",\n \"has-any\",\n \"has-all\",\n \"relation-has\",\n \"relative-date\",\n])\n\nconst LEVELS: Record<EidosFileValidationLevel, number> = {\n identity: 0,\n structural: 1,\n content: 2,\n semantic: 3,\n full: 4,\n}\n\nfunction uuid(value: unknown, label: string): string {\n if (!isEidosFileUuid(value)) {\n throw new Error(`${label} is not canonical lowercase UUIDv7 TEXT`)\n }\n return value\n}\n\nfunction subtypeMap<T extends { field_id: string }>(rows: T[]): Map<string, T> {\n return new Map(rows.map((row) => [uuid(row.field_id, \"Field ID\"), row]))\n}\n\nfunction storageCodec(\n field: FieldRow,\n relation?: RelationRow\n): EidosFileStorageCodec {\n if (field.type === \"relation\" && relation?.direction === \"forward\")\n return \"relation\"\n if (field.type === \"file\" || field.type === \"multi-select\")\n return \"json_array\"\n return \"scalar\"\n}\n\nfunction valueKind(\n field: FieldRow,\n relation?: RelationRow\n): EidosFileValueKind {\n if (field.system_role !== null) return \"system\"\n if (field.type === \"formula\" || field.type === \"lookup\") return \"derived\"\n if (field.type === \"relation\") {\n return relation?.direction === \"inverse\" ? \"derived\" : \"relation\"\n }\n return \"source\"\n}\n\nfunction validPhysicalMapping(\n kind: \"table\" | \"field\",\n name: string,\n physicalName: string\n): boolean {\n return (\n physicalName === name &&\n (kind === \"field\" || !isEidosFileReservedTableName(name))\n )\n}\n\nfunction expectedColumnType(type: string): string | null {\n if (\n [\n \"text\",\n \"url\",\n \"select\",\n \"date\",\n \"datetime\",\n \"file\",\n \"multi-select\",\n \"relation\",\n ].includes(type)\n ) {\n return \"TEXT\"\n }\n if ([\"integer\", \"checkbox\"].includes(type)) {\n return \"INTEGER\"\n }\n if (type === \"number\") return \"REAL\"\n return null\n}\n\nfunction relationIds(value: EidosFileSqlPrimitive): string[] | null {\n if (typeof value !== \"string\" || !isCanonicalEidosFileJson(value)) return null\n const parsed = parseEidosFileJson(value)\n if (!Array.isArray(parsed) || !parsed.every(isEidosFileUuid)) return null\n if (new Set(parsed).size !== parsed.length) return null\n return parsed\n}\n\nfunction declaresBinaryText(sql: string | null, column: string): boolean {\n if (!sql) return false\n const escaped = column.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n const identifier = `(?:\"${escaped}\"|\\\\[${escaped}\\\\]|\\`${escaped}\\`|${escaped})`\n return new RegExp(\n `(?:\\\\(|,)\\\\s*${identifier}\\\\s+TEXT\\\\b[^,)]*\\\\bCOLLATE\\\\s+BINARY\\\\b`,\n \"i\"\n ).test(sql)\n}\n\nfunction readSqliteIdentifier(\n source: string,\n offset = 0\n): { value: string; end: number } | null {\n let start = offset\n while (/\\s/.test(source[start] ?? \"\")) start += 1\n const opener = source[start]\n const closer = opener === \"[\" ? \"]\" : opener\n if (opener === '\"' || opener === \"`\" || opener === \"[\") {\n let value = \"\"\n for (let index = start + 1; index < source.length; index += 1) {\n const character = source[index]!\n if (character !== closer) {\n value += character\n continue\n }\n if (closer !== \"]\" && source[index + 1] === closer) {\n value += closer\n index += 1\n continue\n }\n return { value, end: index + 1 }\n }\n return null\n }\n let end = start\n while (end < source.length && !/[\\s(),]/.test(source[end]!)) end += 1\n return end === start ? null : { value: source.slice(start, end), end }\n}\n\nfunction sqliteTableDefinitions(sql: string): string[] {\n let quote: '\"' | \"'\" | \"`\" | \"]\" | null = null\n let open = -1\n for (let index = 0; index < sql.length; index += 1) {\n const character = sql[index]!\n if (quote) {\n if (character !== quote) continue\n if (quote !== \"]\" && sql[index + 1] === quote) {\n index += 1\n } else {\n quote = null\n }\n continue\n }\n if (character === '\"' || character === \"'\" || character === \"`\") {\n quote = character\n continue\n }\n if (character === \"[\") {\n quote = \"]\"\n continue\n }\n if (character === \"(\") {\n open = index\n break\n }\n }\n if (open === -1) return []\n\n const definitions: string[] = []\n let depth = 1\n let start = open + 1\n quote = null\n for (let index = start; index < sql.length; index += 1) {\n const character = sql[index]!\n if (quote) {\n if (character !== quote) continue\n if (quote !== \"]\" && sql[index + 1] === quote) {\n index += 1\n } else {\n quote = null\n }\n continue\n }\n if (character === '\"' || character === \"'\" || character === \"`\") {\n quote = character\n continue\n }\n if (character === \"[\") {\n quote = \"]\"\n continue\n }\n if (character === \"(\") {\n depth += 1\n continue\n }\n if (character === \")\") {\n depth -= 1\n if (depth === 0) {\n definitions.push(sql.slice(start, index).trim())\n break\n }\n continue\n }\n if (character === \",\" && depth === 1) {\n definitions.push(sql.slice(start, index).trim())\n start = index + 1\n }\n }\n return definitions\n}\n\nfunction declaredColumnCollation(\n tableSql: string | null,\n column: string\n): string | null {\n if (!tableSql) return null\n const definition = sqliteTableDefinitions(tableSql).find(\n (candidate) => readSqliteIdentifier(candidate)?.value === column\n )\n if (!definition) return null\n const leading = readSqliteIdentifier(definition)!\n let depth = 0\n let quote: \"'\" | '\"' | \"`\" | \"]\" | null = null\n for (let index = leading.end; index < definition.length; index += 1) {\n const character = definition[index]!\n if (quote) {\n if (character !== quote) continue\n if (quote !== \"]\" && definition[index + 1] === quote) {\n index += 1\n } else {\n quote = null\n }\n continue\n }\n if (character === '\"' || character === \"'\" || character === \"`\") {\n quote = character\n continue\n }\n if (character === \"[\") {\n quote = \"]\"\n continue\n }\n if (character === \"(\") {\n depth += 1\n continue\n }\n if (character === \")\") {\n depth -= 1\n continue\n }\n if (depth !== 0 || !/[A-Za-z_]/.test(character)) continue\n let end = index + 1\n while (/[A-Za-z0-9_$]/.test(definition[end] ?? \"\")) end += 1\n if (definition.slice(index, end).toLowerCase() !== \"collate\") {\n index = end - 1\n continue\n }\n return readSqliteIdentifier(definition, end)?.value ?? null\n }\n return \"BINARY\"\n}\n\nexport function validateEidosFile(\n connection: EidosFileConnection,\n options: { level?: EidosFileValidationLevel } = {}\n): EidosFileValidationResult {\n const level = options.level ?? \"full\"\n const errors: EidosFileValidationIssue[] = []\n const warnings: EidosFileValidationIssue[] = []\n const add = (\n target: EidosFileValidationIssue[],\n code: string,\n message: string,\n table?: string\n ): void => {\n target.push({ code, message, ...(table ? { table } : {}) })\n }\n\n const applicationId = connection.get<{ application_id: number }>(\n \"PRAGMA application_id\"\n )?.application_id\n const userVersion = connection.get<{ user_version: number }>(\n \"PRAGMA user_version\"\n )?.user_version\n if (applicationId !== EIDOS_FILE_APPLICATION_ID) {\n add(errors, \"not-eidos-file\", \"SQLite application_id is not EIDS\")\n }\n if (userVersion !== EIDOS_FILE_SCHEMA_VERSION) {\n add(\n errors,\n \"unsupported-version\",\n `Unsupported Eidos File schema revision: ${userVersion ?? \"missing\"}`\n )\n }\n\n const sqliteObjects = connection.query<{\n name: string\n type: string\n tbl_name: string\n sql: string | null\n }>(\"SELECT name, type, tbl_name, sql FROM sqlite_master\")\n const sqliteTables = new Map(\n sqliteObjects\n .filter((object) => object.type === \"table\")\n .map((object) => [object.name, object])\n )\n for (const tableName of EIDOS_FILE_REQUIRED_TABLES) {\n if (!sqliteTables.has(tableName)) {\n add(\n errors,\n \"invalid-schema\",\n `Missing required metadata table: ${tableName}`,\n tableName\n )\n }\n }\n const allowedStaticObjects = new Set([\n ...EIDOS_FILE_REQUIRED_TABLES,\n ...REQUIRED_INDEXES,\n ...REQUIRED_TRIGGERS,\n ])\n for (const object of sqliteObjects) {\n if (\n object.name\n .replace(/[A-Z]/g, (character) => character.toLowerCase())\n .startsWith(\"eidos__\") &&\n !allowedStaticObjects.has(object.name) &&\n !DYNAMIC_TRIGGER_NAME.test(object.name) &&\n !(object.type === \"index\" && DYNAMIC_FIELD_INDEX_NAME.test(object.name))\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Undeclared reserved SQLite object: ${object.type} ${object.name}`,\n object.name\n )\n }\n }\n const indexes = new Set(\n sqliteObjects\n .filter((object) => object.type === \"index\")\n .map((object) => object.name)\n )\n for (const indexName of REQUIRED_INDEXES) {\n if (!indexes.has(indexName)) {\n add(\n errors,\n \"invalid-schema\",\n `Missing required metadata index: ${indexName}`\n )\n }\n }\n const triggers = new Set(\n sqliteObjects\n .filter((object) => object.type === \"trigger\")\n .map((object) => object.name)\n )\n for (const triggerName of REQUIRED_TRIGGERS) {\n if (!triggers.has(triggerName)) {\n add(errors, \"invalid-schema\", `Missing required trigger: ${triggerName}`)\n }\n }\n if (!sqliteTables.has(EIDOS_FILE_META_TABLE)) {\n return { valid: false, metadata: null, tables: [], errors, warnings }\n }\n\n let meta: MetaRow | undefined\n try {\n const metaRows = connection.query<MetaRow>(\n `SELECT * FROM ${EIDOS_FILE_META_TABLE}`\n )\n if (metaRows.length !== 1 || metaRows[0]?.singleton !== 1) {\n add(\n errors,\n \"invalid-schema\",\n \"eidos__meta must contain exactly singleton row 1\"\n )\n } else {\n meta = metaRows[0]\n }\n } catch {\n add(\n errors,\n \"invalid-schema\",\n \"Unable to read the canonical metadata singleton\"\n )\n }\n\n let metadata: EidosFileMetadata | null = null\n if (meta) {\n try {\n const fileId = uuid(meta.file_id, \"File ID\")\n const defaultTableId = meta.default_table_id\n ? uuid(meta.default_table_id, \"Default Table ID\")\n : undefined\n if (meta.format_major !== 1 || meta.format_minor !== 0) {\n add(\n errors,\n \"unsupported-version\",\n `Unsupported Eidos File format: ${meta.format_major}.${meta.format_minor}`\n )\n }\n if (\n (typeof meta.revision !== \"number\" &&\n typeof meta.revision !== \"bigint\") ||\n (typeof meta.revision === \"number\" &&\n !Number.isSafeInteger(meta.revision)) ||\n BigInt(meta.revision) < 0n\n ) {\n add(\n errors,\n \"invalid-schema\",\n \"File revision must be a non-negative integer\"\n )\n }\n if (\n !isCanonicalEidosFileInstant(meta.created_at) ||\n !isCanonicalEidosFileInstant(meta.updated_at)\n ) {\n add(\n errors,\n \"invalid-schema\",\n \"File metadata timestamps must be canonical UTC millisecond text\"\n )\n }\n metadata = {\n format: EIDOS_FILE_FORMAT,\n fileId,\n formatVersion: EIDOS_FILE_FORMAT_VERSION,\n schemaVersion: EIDOS_FILE_SCHEMA_VERSION,\n revision: meta.revision,\n createdAt: meta.created_at,\n updatedAt: meta.updated_at,\n title: meta.title,\n ...(defaultTableId ? { defaultTableId } : {}),\n }\n } catch (error) {\n add(\n errors,\n \"invalid-schema\",\n error instanceof Error ? error.message : \"Invalid metadata ID\"\n )\n }\n }\n\n if (LEVELS[level] === LEVELS.identity) {\n return {\n valid: errors.length === 0,\n metadata,\n tables: [],\n errors,\n warnings,\n }\n }\n\n for (const [tableName, requiredColumns] of Object.entries(REQUIRED_COLUMNS)) {\n if (!sqliteTables.has(tableName)) continue\n const columns = new Map(\n connection\n .query<{ name: string; type: string }>(\n `PRAGMA table_xinfo(${quoteIdentifier(tableName)})`\n )\n .map((column) => [column.name, column.type.toUpperCase()])\n )\n for (const column of requiredColumns) {\n if (!columns.has(column)) {\n add(\n errors,\n \"invalid-schema\",\n `Missing required column ${tableName}.${column}`,\n tableName\n )\n }\n }\n for (const column of ID_COLUMNS[tableName] ?? []) {\n if (\n columns.get(column) !== \"TEXT\" ||\n !declaresBinaryText(sqliteTables.get(tableName)?.sql ?? null, column)\n ) {\n add(\n errors,\n \"invalid-schema\",\n `${tableName}.${column} must use canonical UUIDv7 TEXT COLLATE BINARY`,\n tableName\n )\n }\n }\n if (\n new Set<string>([\n EIDOS_FILE_META_TABLE,\n EIDOS_FILE_TABLES_TABLE,\n EIDOS_FILE_FIELDS_TABLE,\n EIDOS_FILE_VIEWS_TABLE,\n ]).has(tableName)\n ) {\n for (const column of [\"created_at\", \"updated_at\"]) {\n if (columns.get(column) !== \"TEXT\") {\n add(\n errors,\n \"invalid-schema\",\n `${tableName}.${column} must use SQLite TEXT`,\n tableName\n )\n }\n }\n }\n }\n\n const tableModes = new Map(\n connection\n .query<{ name: string; wr: number; strict: number }>(\"PRAGMA table_list\")\n .map((row) => [row.name, row])\n )\n for (const tableName of EIDOS_FILE_REQUIRED_TABLES) {\n const mode = tableModes.get(tableName)\n if (!mode) continue\n if (mode.strict !== 1) {\n add(errors, \"invalid-schema\", `${tableName} must be STRICT`, tableName)\n }\n if (mode.wr !== 1) {\n add(\n errors,\n \"invalid-schema\",\n `${tableName} has the wrong WITHOUT ROWID mode`,\n tableName\n )\n }\n }\n\n if (sqliteTables.has(EIDOS_FILE_FEATURES_TABLE)) {\n for (const feature of connection.query<{\n name: string\n required: number\n config_json: string\n }>(\n `SELECT name, required, config_json FROM ${EIDOS_FILE_FEATURES_TABLE}`\n )) {\n if (!isCanonicalEidosFileJson(feature.config_json)) {\n add(\n errors,\n \"invalid-schema\",\n `Feature ${feature.name} has non-canonical config_json`\n )\n }\n if (feature.required === 1) {\n add(\n errors,\n \"unsupported-feature\",\n `Unknown required feature: ${feature.name}`\n )\n }\n }\n }\n\n const tableRows = sqliteTables.has(EIDOS_FILE_TABLES_TABLE)\n ? connection.query<TableRow>(\n `SELECT * FROM ${EIDOS_FILE_TABLES_TABLE} ORDER BY position, id`\n )\n : []\n const tables: EidosFileTableInfo[] = []\n const tableRowsById = new Map<string, TableRow>()\n const tableSettingsById = new Map<string, Record<string, unknown>>()\n const tableNames = new Set<string>()\n for (const row of tableRows) {\n try {\n const id = uuid(row.id, \"Table ID\")\n tableRowsById.set(id, row)\n const tableSettings = isCanonicalEidosFileJson(row.settings_json)\n ? parseEidosFileJson(row.settings_json)\n : null\n const settings =\n tableSettings &&\n !Array.isArray(tableSettings) &&\n typeof tableSettings === \"object\"\n ? tableSettings\n : {}\n tableSettingsById.set(id, settings)\n if (\n settings.contentFieldId !== undefined &&\n typeof settings.contentFieldId !== \"string\"\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Table ${row.name} contentFieldId must be a Field ID string`,\n row.physical_name\n )\n }\n tables.push({\n id,\n name: row.name,\n physicalName: row.physical_name,\n rawTableName: row.physical_name,\n position: row.position,\n icon: typeof settings.icon === \"string\" ? settings.icon : null,\n description:\n typeof settings.description === \"string\"\n ? settings.description\n : null,\n contentFieldId:\n typeof settings.contentFieldId === \"string\"\n ? settings.contentFieldId\n : null,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n })\n if (\n !isCanonicalEidosFileInstant(row.created_at) ||\n !isCanonicalEidosFileInstant(row.updated_at)\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Table ${row.name} metadata timestamps are not canonical instants`,\n row.physical_name\n )\n }\n if (!isCanonicalEidosFileJson(row.settings_json)) {\n add(\n errors,\n \"invalid-schema\",\n `Table ${row.name} has non-canonical settings_json`,\n row.physical_name\n )\n }\n const foldedTableName = row.name.replace(/[A-Z]/g, (character) =>\n character.toLowerCase()\n )\n if (tableNames.has(foldedTableName)) {\n add(\n errors,\n \"invalid-schema\",\n `Duplicate Table name under SQLite NOCASE: ${row.name}`,\n row.physical_name\n )\n }\n tableNames.add(foldedTableName)\n if (!validPhysicalMapping(\"table\", row.name, row.physical_name)) {\n add(\n errors,\n \"invalid-schema\",\n `Table ${row.name} has an invalid physical name`,\n row.physical_name\n )\n }\n const tableObject = sqliteTables.get(row.physical_name)\n if (!tableObject) {\n add(\n errors,\n \"invalid-schema\",\n `Missing user table ${row.physical_name}`,\n row.physical_name\n )\n } else if (!/\\bSTRICT\\b/i.test(tableObject.sql ?? \"\")) {\n add(\n errors,\n \"invalid-schema\",\n `User table ${row.physical_name} must be STRICT`,\n row.physical_name\n )\n }\n } catch (error) {\n add(\n errors,\n \"invalid-schema\",\n error instanceof Error ? error.message : \"Invalid Table ID\"\n )\n }\n }\n if (metadata?.defaultTableId && !tableRowsById.has(metadata.defaultTableId)) {\n add(\n errors,\n \"invalid-schema\",\n \"default_table_id does not reference a registered Table\"\n )\n }\n\n const relationRows = sqliteTables.has(EIDOS_FILE_RELATION_FIELDS_TABLE)\n ? connection.query<RelationRow>(\n `SELECT * FROM ${EIDOS_FILE_RELATION_FIELDS_TABLE}`\n )\n : []\n const formulaRows = sqliteTables.has(EIDOS_FILE_FORMULA_FIELDS_TABLE)\n ? connection.query<FormulaRow>(\n `SELECT * FROM ${EIDOS_FILE_FORMULA_FIELDS_TABLE}`\n )\n : []\n const lookupRows = sqliteTables.has(EIDOS_FILE_LOOKUP_FIELDS_TABLE)\n ? connection.query<LookupRow>(\n `SELECT * FROM ${EIDOS_FILE_LOOKUP_FIELDS_TABLE}`\n )\n : []\n const relations = subtypeMap(relationRows)\n const formulas = subtypeMap(formulaRows)\n const lookups = subtypeMap(lookupRows)\n\n const fieldRows = sqliteTables.has(EIDOS_FILE_FIELDS_TABLE)\n ? connection.query<FieldRow>(\n `SELECT * FROM ${EIDOS_FILE_FIELDS_TABLE} ORDER BY table_id, position, id`\n )\n : []\n const fieldRowsById = new Map<string, FieldRow>()\n const fieldRowsByHexId = new Map<string, FieldRow>()\n const fieldsByTable = new Map<string, EidosFileFieldInfo[]>()\n for (const row of fieldRows) {\n try {\n const id = uuid(row.id, \"Field ID\")\n const tableId = uuid(row.table_id, \"Field Table ID\")\n const table = tableRowsById.get(tableId)\n fieldRowsById.set(id, row)\n fieldRowsByHexId.set(id.replace(/-/g, \"\"), row)\n if (!table) {\n add(errors, \"invalid-schema\", `Field ${id} references an unknown Table`)\n continue\n }\n if (!FIELD_TYPES.has(row.type as EidosFileFieldType)) {\n add(\n errors,\n \"invalid-schema\",\n `Field ${row.name} has unsupported type ${row.type}`\n )\n }\n if (\n !isCanonicalEidosFileInstant(row.created_at) ||\n !isCanonicalEidosFileInstant(row.updated_at)\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Field ${row.name} metadata timestamps are not canonical instants`\n )\n }\n if (!isCanonicalEidosFileJson(row.settings_json)) {\n add(\n errors,\n \"invalid-schema\",\n `Field ${row.name} has non-canonical settings_json`\n )\n }\n let settings: Record<string, unknown> = {}\n try {\n const parsed = parseEidosFileJson(row.settings_json)\n if (\n Array.isArray(parsed) ||\n parsed === null ||\n typeof parsed !== \"object\"\n ) {\n throw new Error(\"settings_json must be an object\")\n }\n settings = parsed\n } catch (error) {\n add(\n errors,\n \"invalid-schema\",\n `Field ${row.name}: ${error instanceof Error ? error.message : \"invalid settings\"}`\n )\n }\n if (row.type === \"select\" || row.type === \"multi-select\") {\n try {\n assertEidosFileSelectOptions(settings)\n if (row.type === \"select\") {\n assertEidosFileSelectDefaultOption(settings)\n } else {\n assertEidosFileMultiSelectHasNoDefaultOption(settings)\n }\n } catch (error) {\n add(\n errors,\n \"invalid-schema\",\n error instanceof Error ? error.message : \"Invalid Select catalog\"\n )\n }\n }\n const relation = relations.get(id)\n const virtual =\n row.type === \"formula\" ||\n row.type === \"lookup\" ||\n (row.type === \"relation\" && relation?.direction === \"inverse\")\n const requiresNonNull =\n row.system_role !== null ||\n row.type === \"file\" ||\n row.type === \"multi-select\" ||\n row.type === \"relation\"\n const requiresNullable = row.type === \"formula\" || row.type === \"lookup\"\n if (\n (requiresNonNull && row.nullable !== 0) ||\n (requiresNullable && row.nullable !== 1)\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Field ${row.name} has invalid nullable metadata for ${row.type}`\n )\n }\n if (virtual && row.physical_name !== null) {\n add(\n errors,\n \"invalid-schema\",\n `Virtual Field ${row.name} must not have a physical column`\n )\n }\n if (!virtual && row.physical_name === null) {\n add(\n errors,\n \"invalid-schema\",\n `Stored Field ${row.name} requires a physical column`\n )\n }\n if (\n row.physical_name &&\n !validPhysicalMapping(\"field\", row.name, row.physical_name)\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Field ${row.name} has an invalid physical name`\n )\n }\n\n const formula = formulas.get(id)\n const lookup = lookups.get(id)\n const property: Record<string, unknown> | null = formula\n ? { formula: formula.source_text, displayType: formula.result_type }\n : lookup\n ? {\n relationField: uuid(\n lookup.relation_field_id,\n \"Lookup Relation Field ID\"\n ),\n targetField: uuid(\n lookup.target_field_id,\n \"Lookup Target Field ID\"\n ),\n aggregate: lookup.aggregate,\n displayType: \"text\",\n }\n : relation\n ? {\n targetTableId: uuid(\n relation.target_table_id,\n \"Relation Target Table ID\"\n ),\n direction: relation.direction,\n sourceFieldId: relation.inverse_of_field_id\n ? uuid(\n relation.inverse_of_field_id,\n \"Relation inverse Field ID\"\n )\n : undefined,\n cardinality: relation.cardinality,\n onDelete: relation.on_delete,\n }\n : settings\n const field: EidosFileFieldInfo = {\n id,\n tableId,\n name: row.name,\n type:\n row.system_role === \"row-id\"\n ? \"row-id\"\n : row.system_role === \"created-time\"\n ? \"created-time\"\n : row.system_role === \"updated-time\"\n ? \"last-edited-time\"\n : (row.type as EidosFileFieldType),\n tableName: table.physical_name,\n tableColumnName: row.physical_name ?? id,\n physicalName: row.physical_name,\n systemRole: row.system_role,\n nullable: row.nullable === 1,\n isRecordLabel: table.label_field_id === id,\n position: row.position,\n settings,\n property,\n storageCodec: storageCodec(row, relation),\n valueKind: valueKind(row, relation),\n isHidden: row.system_role !== null,\n isDerived: virtual,\n sourceTableColumnName:\n relation?.direction === \"inverse\" && relation.inverse_of_field_id\n ? uuid(relation.inverse_of_field_id, \"Inverse source Field ID\")\n : null,\n dependsOn: null,\n }\n const fields = fieldsByTable.get(tableId) ?? []\n fields.push(field)\n fieldsByTable.set(tableId, fields)\n } catch (error) {\n add(\n errors,\n \"invalid-schema\",\n error instanceof Error ? error.message : \"Invalid Field metadata\"\n )\n }\n }\n\n for (const indexObject of sqliteObjects.filter(\n (object) =>\n object.type === \"index\" && DYNAMIC_FIELD_INDEX_NAME.test(object.name)\n )) {\n const fieldHex = DYNAMIC_FIELD_INDEX_NAME.exec(indexObject.name)![1]!\n const field = fieldRowsByHexId.get(fieldHex)\n if (!field) {\n add(\n errors,\n \"invalid-schema\",\n `Reserved Field index ${indexObject.name} references an unknown Field`,\n indexObject.name\n )\n continue\n }\n if (!field.physical_name || !INDEXABLE_FIELD_TYPES.has(field.type)) {\n add(\n errors,\n \"invalid-schema\",\n `Reserved Field index ${indexObject.name} must reference a stored scalar Field`,\n indexObject.name\n )\n continue\n }\n const table = tableRowsById.get(field.table_id)\n if (!table || indexObject.tbl_name !== table.physical_name) {\n add(\n errors,\n \"invalid-schema\",\n `Reserved Field index ${indexObject.name} is attached to the wrong Table`,\n indexObject.name\n )\n continue\n }\n const indexList = connection.query<{\n name: string\n unique: number\n origin: string\n partial: number\n }>(`PRAGMA index_list(${quoteIdentifier(table.physical_name)})`)\n const listedIndex = indexList.find(\n (index) => index.name === indexObject.name\n )\n const keyColumns = connection\n .query<{\n cid: number\n name: string | null\n coll: string | null\n key: number\n }>(`PRAGMA index_xinfo(${quoteIdentifier(indexObject.name)})`)\n .filter((column) => column.key === 1)\n const keyColumn = keyColumns[0]\n const declaredCollation = declaredColumnCollation(\n sqliteTables.get(table.physical_name)?.sql ?? null,\n field.physical_name\n )\n if (\n !listedIndex ||\n listedIndex.unique !== 0 ||\n listedIndex.partial !== 0 ||\n listedIndex.origin !== \"c\" ||\n indexObject.sql === null ||\n keyColumns.length !== 1 ||\n !keyColumn ||\n keyColumn.cid < 0 ||\n keyColumn.name !== field.physical_name ||\n !declaredCollation ||\n keyColumn.coll?.toLowerCase() !== declaredCollation.toLowerCase()\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Reserved Field index ${indexObject.name} has an invalid definition`,\n indexObject.name\n )\n }\n }\n\n for (const [tableId, fields] of fieldsByTable) {\n const table = tableRowsById.get(tableId)\n if (!table) continue\n const requiredSystemFields = [\n [\"row-id\", \"_id\"],\n [\"created-time\", \"_created_at\"],\n [\"last-edited-time\", \"_updated_at\"],\n ] as const\n for (const [type, physicalName] of requiredSystemFields) {\n const matches = fields.filter(\n (field) => field.type === type && field.physicalName === physicalName\n )\n if (matches.length !== 1) {\n add(\n errors,\n \"invalid-schema\",\n `Table ${table.name} must register exactly one ${type} Field mapped to ${physicalName}`\n )\n }\n }\n const mappedNames = fields.flatMap((field) =>\n field.physicalName ? [field.physicalName] : []\n )\n const displayNames = fields.map((field) => field.name)\n if (\n new Set(\n displayNames.map((name) =>\n name.replace(/[A-Z]/g, (character) => character.toLowerCase())\n )\n ).size !== displayNames.length\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Table ${table.name} contains duplicate Field names under SQLite NOCASE`\n )\n }\n if (\n new Set(\n mappedNames.map((name) =>\n name.replace(/[A-Z]/g, (character) => character.toLowerCase())\n )\n ).size !== mappedNames.length\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Table ${table.name} maps more than one Field to a physical column`\n )\n }\n }\n\n if (sqliteTables.has(EIDOS_FILE_VIEWS_TABLE)) {\n const viewNamesByTable = new Map<string, Set<string>>()\n for (const view of connection.query<{\n id: string\n table_id: string\n name: string\n }>(`SELECT id, table_id, name FROM ${EIDOS_FILE_VIEWS_TABLE}`)) {\n try {\n uuid(view.id, \"View ID\")\n const tableId = uuid(view.table_id, \"View Table ID\")\n assertEidosFileDisplayName(view.name, \"View name\")\n if (!tableRowsById.has(tableId)) {\n throw new Error(\"View references an unknown Table\")\n }\n const foldedName = view.name.replace(/[A-Z]/g, (character) =>\n character.toLowerCase()\n )\n const names = viewNamesByTable.get(tableId) ?? new Set<string>()\n if (names.has(foldedName)) {\n add(\n errors,\n \"invalid-schema\",\n `Table ${tableRowsById.get(tableId)!.name} contains duplicate View names under SQLite NOCASE`\n )\n }\n names.add(foldedName)\n viewNamesByTable.set(tableId, names)\n } catch (error) {\n add(\n errors,\n \"invalid-schema\",\n error instanceof Error ? error.message : \"Invalid View metadata\"\n )\n }\n }\n }\n\n const triggerObjects = new Map(\n sqliteObjects\n .filter((object) => object.type === \"trigger\")\n .map((object) => [object.name, object])\n )\n const expectedTriggers = new Map<\n string,\n { table: string; fragments: string[] }\n >()\n for (const [tableId, table] of tableRowsById) {\n expectedTriggers.set(\n `eidos__row_id_immutable__${tableId.replace(/-/g, \"\")}`,\n {\n table: table.physical_name,\n fragments: [\"before update of\", \"_id\", \"eidos_row_id_immutable\"],\n }\n )\n }\n for (const [fieldId, relation] of relations) {\n if (relation.direction !== \"forward\") continue\n const field = fieldRowsById.get(fieldId)\n if (!field) continue\n try {\n const sourceTable = tableRowsById.get(\n uuid(field.table_id, \"Relation owner Table ID\")\n )\n const targetTable = tableRowsById.get(\n uuid(relation.target_table_id, \"Relation target Table ID\")\n )\n if (!sourceTable || !targetTable) continue\n const hex = fieldId.replace(/-/g, \"\")\n expectedTriggers.set(`eidos__relation_validate_insert__${hex}`, {\n table: sourceTable.physical_name,\n fragments: [\"before insert\", \"eidos_invalid_relation_value\"],\n })\n expectedTriggers.set(`eidos__relation_validate_update__${hex}`, {\n table: sourceTable.physical_name,\n fragments: [\"before update\", \"eidos_invalid_relation_value\"],\n })\n if (\n relation.on_delete === \"restrict\" ||\n relation.on_delete === \"detach\"\n ) {\n expectedTriggers.set(`eidos__relation_${relation.on_delete}__${hex}`, {\n table: targetTable.physical_name,\n fragments:\n relation.on_delete === \"restrict\"\n ? [\n \"before delete\",\n \"eidos_relation_restrict\",\n \"item.value\",\n 'old.\"_id\"',\n ]\n : [\n \"before delete\",\n \"update\",\n \"json_each\",\n \"json_group_array\",\n \"order by\",\n 'old.\"_id\"',\n \"_updated_at\",\n \"strftime\",\n ],\n })\n }\n } catch (error) {\n add(\n errors,\n \"invalid-schema\",\n error instanceof Error\n ? error.message\n : \"Invalid Relation trigger identity\"\n )\n }\n }\n for (const [name, expected] of expectedTriggers) {\n const trigger = triggerObjects.get(name)\n if (!trigger) {\n add(\n errors,\n \"invalid-schema\",\n `Missing required portable trigger: ${name}`\n )\n continue\n }\n const sql = (trigger.sql ?? \"\").toLowerCase()\n // Older CLI writers used the format-spec marker while the Runtime writer\n // uses the newer explicit marker. Both are behaviorally equivalent safety\n // triggers and must remain readable for existing Files.\n const validFragments = expected.fragments.every((fragment) =>\n fragment === \"eidos_invalid_relation_value\"\n ? sql.includes(\"eidos_invalid_relation_value\") ||\n sql.includes(\"eidos_relation_invalid\")\n : sql.includes(fragment)\n )\n if (\n trigger.tbl_name !== expected.table ||\n sql.includes(\"hex(\") ||\n !validFragments\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Portable trigger ${name} has an invalid definition`\n )\n }\n }\n for (const name of triggerObjects.keys()) {\n if (DYNAMIC_TRIGGER_NAME.test(name) && !expectedTriggers.has(name)) {\n add(\n errors,\n \"invalid-schema\",\n `Undeclared or stale portable trigger: ${name}`\n )\n }\n }\n\n if (LEVELS[level] === LEVELS.structural) {\n return { valid: errors.length === 0, metadata, tables, errors, warnings }\n }\n\n if (level === \"semantic\" || level === \"full\") {\n const dependencyGraph = new Map<string, string[]>()\n for (const [fieldId] of relations) {\n if (fieldRowsById.get(fieldId)?.type !== \"relation\") {\n add(\n errors,\n \"invalid-schema\",\n `Relation subtype ${fieldId} does not belong to a Relation Field`\n )\n }\n }\n for (const [fieldId] of formulas) {\n if (fieldRowsById.get(fieldId)?.type !== \"formula\") {\n add(\n errors,\n \"invalid-schema\",\n `Formula subtype ${fieldId} does not belong to a Formula Field`\n )\n }\n }\n for (const [fieldId] of lookups) {\n if (fieldRowsById.get(fieldId)?.type !== \"lookup\") {\n add(\n errors,\n \"invalid-schema\",\n `Lookup subtype ${fieldId} does not belong to a Lookup Field`\n )\n }\n }\n\n const logicalType = (\n fieldId: string,\n visiting = new Set<string>()\n ): string => {\n if (visiting.has(fieldId)) return \"invalid\"\n const row = fieldRowsById.get(fieldId)\n if (!row) return \"invalid\"\n if (row.type === \"formula\")\n return formulas.get(fieldId)?.result_type ?? \"invalid\"\n if (row.type !== \"lookup\") {\n if (row.system_role === \"row-id\") return \"row-id\"\n return row.type\n }\n const lookup = lookups.get(fieldId)\n if (!lookup) return \"invalid\"\n const element = lookupElementType(\n uuid(lookup.target_field_id, \"Lookup Target Field ID\"),\n new Set([...visiting, fieldId])\n )\n if (lookup.aggregate === \"values\") return `list:${element}`\n if (lookup.aggregate === \"count\") return \"integer\"\n if (lookup.aggregate === \"average\") return \"number\"\n if (lookup.aggregate === \"sum\")\n return element === \"integer\" ? \"integer\" : \"number\"\n return element\n }\n const lookupElementType = (\n fieldId: string,\n visiting = new Set<string>()\n ) => {\n const type = logicalType(fieldId, visiting)\n if (type.startsWith(\"list:\")) return type.slice(5)\n if (type === \"multi-select\") return \"select\"\n if (type === \"file\") return \"file-entry\"\n if (type === \"relation\") return \"row-id\"\n return type\n }\n for (const fields of fieldsByTable.values()) {\n for (const field of fields) {\n if (field.type !== \"lookup\" || !field.property) continue\n const valueType = logicalType(field.id!)\n field.property.valueType = valueType.startsWith(\"list:\")\n ? { kind: \"list\", element: valueType.slice(5) }\n : valueType\n const atom = valueType.startsWith(\"list:\")\n ? valueType.slice(5)\n : valueType\n field.property.displayType =\n atom === \"row-id\" || atom === \"select\"\n ? \"text\"\n : atom === \"file-entry\"\n ? \"text\"\n : atom\n }\n }\n for (const [tableId, fields] of fieldsByTable) {\n const table = tableRowsById.get(tableId)!\n const contentFieldId = tableSettingsById.get(tableId)?.contentFieldId\n if (typeof contentFieldId === \"string\") {\n const contentField = fields.find((field) => field.id === contentFieldId)\n if (\n !contentField ||\n contentField.type !== \"text\" ||\n contentField.valueKind !== \"source\" ||\n contentField.systemRole != null ||\n !contentField.physicalName\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Table ${table.name} Content Field must reference an ordinary Text Field in the same Table`\n )\n }\n }\n const labels = fields.filter((field) => field.isRecordLabel)\n if (labels.length !== 1) {\n add(\n errors,\n \"invalid-schema\",\n `Table ${table.name} must have exactly one Record Label Field`\n )\n }\n for (const label of labels) {\n const resultType = logicalType(label.id!)\n if (label.type === \"lookup\" || !LABEL_SCALAR_TYPES.has(resultType)) {\n add(\n errors,\n \"invalid-schema\",\n `Record Label Field ${label.name} is not scalar`\n )\n }\n }\n\n const physicalColumnRows = connection.query<{\n name: string\n type: string\n notnull: number\n }>(`PRAGMA table_xinfo(${quoteIdentifier(table.physical_name)})`)\n const physicalColumns = new Map(\n physicalColumnRows.map((column) => [\n column.name,\n column.type.toUpperCase(),\n ])\n )\n const physicalNullability = new Map(\n physicalColumnRows.map((column) => [column.name, column.notnull === 0])\n )\n for (const required of [\"_id\", \"_created_at\", \"_updated_at\"]) {\n if (!physicalColumns.has(required)) {\n add(\n errors,\n \"invalid-schema\",\n `User table ${table.name} is missing ${required}`\n )\n }\n }\n if (\n physicalColumns.get(\"_id\") !== \"TEXT\" ||\n !declaresBinaryText(\n sqliteTables.get(table.physical_name)?.sql ?? null,\n \"_id\"\n )\n ) {\n add(\n errors,\n \"invalid-schema\",\n `User table ${table.name}._id must use canonical UUIDv7 TEXT COLLATE BINARY`\n )\n }\n for (const field of fields) {\n const fieldId = field.id!\n if (field.physicalName) {\n const actualType = physicalColumns.get(field.physicalName)\n const expected = expectedColumnType(field.type)\n if (!actualType) {\n add(\n errors,\n \"invalid-schema\",\n `Stored Field ${field.name} has no physical column`\n )\n } else if (expected && actualType !== expected) {\n add(\n errors,\n \"invalid-schema\",\n `Field ${field.name} must use SQLite ${expected}, found ${actualType}`\n )\n }\n if (\n ![\"row-id\", \"created-time\", \"last-edited-time\"].includes(\n field.type\n ) &&\n physicalNullability.get(field.physicalName) !== field.nullable\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Field ${field.name} nullable metadata does not match its physical column`\n )\n }\n }\n if (field.type === \"formula\") {\n if (!formulas.has(fieldId)) {\n add(\n errors,\n \"invalid-schema\",\n `Formula Field ${field.name} is missing subtype metadata`\n )\n } else {\n if (!FORMULA_RESULT_TYPES.has(formulas.get(fieldId)!.result_type)) {\n add(\n errors,\n \"invalid-schema\",\n `Formula Field ${field.name} has an invalid result type`\n )\n }\n try {\n const compiled = compileEidosFileFormula(field, fields)\n dependencyGraph.set(fieldId, compiled.dependencyFieldIds)\n } catch (error) {\n add(\n errors,\n \"invalid-schema\",\n error instanceof Error ? error.message : \"Invalid Formula\"\n )\n }\n }\n } else if (field.type === \"lookup\") {\n const lookup = lookups.get(fieldId)\n if (!lookup) {\n add(\n errors,\n \"invalid-schema\",\n `Lookup Field ${field.name} is missing subtype metadata`\n )\n } else {\n const relationFieldId = uuid(\n lookup.relation_field_id,\n \"Lookup Relation Field ID\"\n )\n const targetFieldId = uuid(\n lookup.target_field_id,\n \"Lookup Target Field ID\"\n )\n const relationField = fieldRowsById.get(relationFieldId)\n const relation = relations.get(relationFieldId)\n const targetField = fieldRowsById.get(targetFieldId)\n if (\n !relationField ||\n !relation ||\n relationField.type !== \"relation\"\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Lookup ${field.name} does not reference a Relation Field`\n )\n } else {\n const relationOwner = uuid(\n relationField.table_id,\n \"Relation owner Table ID\"\n )\n const logicalTarget = uuid(\n relation.target_table_id,\n \"Relation target Table ID\"\n )\n const targetOwner = targetField\n ? uuid(targetField.table_id, \"Lookup target owner Table ID\")\n : \"\"\n if (relationOwner !== tableId) {\n add(\n errors,\n \"invalid-schema\",\n `Lookup ${field.name} Relation belongs to another Table`\n )\n }\n if (!targetField || targetOwner !== logicalTarget) {\n add(\n errors,\n \"invalid-schema\",\n `Lookup ${field.name} target is outside the Relation target Table`\n )\n }\n }\n const targetType = lookupElementType(targetFieldId)\n if (\n (lookup.aggregate === \"sum\" || lookup.aggregate === \"average\") &&\n !NUMERIC_LOOKUP_TYPES.has(targetType)\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Lookup ${field.name} ${lookup.aggregate} requires a numeric target`\n )\n }\n if (\n (lookup.aggregate === \"min\" || lookup.aggregate === \"max\") &&\n ![\n \"text\",\n \"url\",\n \"select\",\n \"row-id\",\n \"integer\",\n \"number\",\n \"checkbox\",\n \"date\",\n \"datetime\",\n ].includes(targetType)\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Lookup ${field.name} ${lookup.aggregate} requires a scalar target`\n )\n }\n dependencyGraph.set(fieldId, [relationFieldId, targetFieldId])\n }\n } else if (field.type === \"relation\") {\n const relation = relations.get(fieldId)\n if (!relation) {\n add(\n errors,\n \"invalid-schema\",\n `Relation Field ${field.name} is missing subtype metadata`\n )\n } else if (\n relation.direction === \"inverse\" &&\n relation.inverse_of_field_id\n ) {\n const sourceFieldId = uuid(\n relation.inverse_of_field_id,\n \"Inverse source Field ID\"\n )\n const sourceField = fieldRowsById.get(sourceFieldId)\n const sourceRelation = relations.get(sourceFieldId)\n const sourceTableId = sourceField\n ? uuid(sourceField.table_id, \"Forward Relation owner Table ID\")\n : \"\"\n if (\n !sourceField ||\n !sourceRelation ||\n sourceRelation.direction !== \"forward\" ||\n uuid(\n sourceRelation.target_table_id,\n \"Forward Relation target Table ID\"\n ) !== tableId ||\n uuid(\n relation.target_table_id,\n \"Inverse Relation target Table ID\"\n ) !== sourceTableId ||\n relation.cardinality !== \"many\"\n ) {\n add(\n errors,\n \"invalid-schema\",\n `Inverse Relation ${field.name} has inconsistent endpoints`\n )\n }\n dependencyGraph.set(fieldId, [sourceFieldId])\n } else if (relation.direction === \"forward\") {\n const targetTableId = uuid(\n relation.target_table_id,\n \"Relation target Table ID\"\n )\n if (!tableRowsById.has(targetTableId)) {\n add(\n errors,\n \"invalid-schema\",\n `Relation ${field.name} targets a missing Table`\n )\n }\n }\n }\n }\n }\n\n for (const id of fieldRowsById.keys())\n dependencyGraph.set(id, dependencyGraph.get(id) ?? [])\n const canonicalGraph = new Map<string, Set<string>>(\n Array.from(fieldRowsById.keys(), (id) => [id, new Set<string>()])\n )\n for (const [dependent, dependencies] of dependencyGraph) {\n for (const dependency of dependencies) {\n if (!fieldRowsById.has(dependency)) {\n add(\n errors,\n \"invalid-schema\",\n `Field ${dependent} depends on missing Field ${dependency}`\n )\n } else {\n canonicalGraph.get(dependency)!.add(dependent)\n }\n }\n }\n const dependencyCycle = smallestDependencyCycle(canonicalGraph)\n if (dependencyCycle) {\n const cycle = dependencyCycle\n .map((fieldId) => {\n const field = fieldRowsById.get(fieldId)\n return field ? `${field.name} (${fieldId})` : fieldId\n })\n .join(\" → \")\n add(errors, \"dependency-cycle\", `Eidos File dependency cycle: ${cycle}`)\n }\n\n if (sqliteTables.has(EIDOS_FILE_VIEWS_TABLE)) {\n for (const view of connection.query<{\n id: string\n table_id: string\n query_json: string\n layout_json: string\n created_at: string\n updated_at: string\n }>(\n `SELECT id, table_id, query_json, layout_json, created_at, updated_at FROM ${EIDOS_FILE_VIEWS_TABLE}`\n )) {\n try {\n uuid(view.id, \"View ID\")\n const tableId = uuid(view.table_id, \"View Table ID\")\n if (!tableRowsById.has(tableId))\n throw new Error(\"View references an unknown Table\")\n if (\n !isCanonicalEidosFileInstant(view.created_at) ||\n !isCanonicalEidosFileInstant(view.updated_at)\n ) {\n throw new Error(\"View timestamps must be canonical instants\")\n }\n if (\n !isCanonicalEidosFileJson(view.query_json) ||\n !isCanonicalEidosFileJson(view.layout_json)\n ) {\n throw new Error(\n \"View query_json and layout_json must be canonical JSON\"\n )\n }\n const viewFields = fieldsByTable.get(tableId) ?? []\n const fieldsById = new Map(\n viewFields.map((field) => [field.id!, field])\n )\n const fieldIds = new Set(fieldsById.keys())\n const query = parseEidosFileJson(view.query_json)\n const layout = parseEidosFileJson(view.layout_json)\n if (!query || Array.isArray(query) || typeof query !== \"object\") {\n throw new Error(\"View query_json must be an object\")\n }\n if (!layout || Array.isArray(layout) || typeof layout !== \"object\") {\n throw new Error(\"View layout_json must be an object\")\n }\n let unsupportedQuery = Object.keys(query).some(\n (key) => key !== \"filter\" && key !== \"sort\"\n )\n const hasOnlyKeys = (\n value: Record<string, unknown>,\n keys: string[]\n ): boolean => Object.keys(value).every((key) => keys.includes(key))\n const checkFilter = (value: unknown): void => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\"View filter nodes must be objects\")\n }\n const node = value as Record<string, unknown>\n if (node.op === \"and\" || node.op === \"or\") {\n if (!Array.isArray(node.args))\n throw new Error(\"View filter group must contain args\")\n if (!hasOnlyKeys(node, [\"op\", \"args\"])) unsupportedQuery = true\n node.args.forEach(checkFilter)\n return\n }\n if (node.op === \"not\") {\n if (!(\"arg\" in node))\n throw new Error(\"View filter negation must contain an arg\")\n if (!hasOnlyKeys(node, [\"op\", \"arg\"])) unsupportedQuery = true\n checkFilter(node.arg)\n return\n }\n if (typeof node.op !== \"string\") {\n throw new Error(\"View filter rule has an invalid operator\")\n }\n\n if (\"fieldId\" in node) {\n if (\n typeof node.fieldId !== \"string\" ||\n !fieldIds.has(node.fieldId)\n ) {\n throw new Error(\"View filter references an unknown Field ID\")\n }\n if (!RUNTIME_FILTER_OPERATORS.has(node.op)) {\n unsupportedQuery = true\n return\n }\n const field = fieldsById.get(node.fieldId)!\n const list =\n field.storageCodec === \"json_array\" ||\n field.storageCodec === \"relation\"\n if (\n list &&\n [\"lt\", \"lte\", \"gt\", \"gte\", \"starts-with\", \"ends-with\"].includes(\n node.op\n )\n ) {\n throw new Error(\n \"View filter uses a scalar comparison on a list Field\"\n )\n }\n if (node.op === \"is-null\" || node.op === \"is-not-null\") {\n if (!hasOnlyKeys(node, [\"op\", \"fieldId\"]))\n unsupportedQuery = true\n return\n }\n if ([\"eq\", \"ne\", \"lt\", \"lte\", \"gt\", \"gte\"].includes(node.op)) {\n if (!(\"value\" in node) || node.value === null)\n throw new Error(\"View filter operand must be non-null\")\n if (!hasOnlyKeys(node, [\"op\", \"fieldId\", \"value\"]))\n unsupportedQuery = true\n if (\n field.type === \"relation\" &&\n (!Array.isArray(node.value) ||\n !node.value.every(isEidosFileUuid))\n ) {\n throw new Error(\n \"View Relation filter values must be canonical Row IDs\"\n )\n }\n return\n }\n if (node.op === \"between\") {\n if (!(\"lower\" in node) || !(\"upper\" in node))\n throw new Error(\"View between filter is missing an operand\")\n if (node.lower === null || node.upper === null)\n throw new Error(\"View between operands must be non-null\")\n if (!hasOnlyKeys(node, [\"op\", \"fieldId\", \"lower\", \"upper\"]))\n unsupportedQuery = true\n return\n }\n if ([\"in\", \"has-any\", \"has-all\"].includes(node.op)) {\n if (\n !Array.isArray(node.values) ||\n node.values.some((entry) => entry === null)\n ) {\n throw new Error(\n \"View membership filter values must be a non-null array\"\n )\n }\n if (!hasOnlyKeys(node, [\"op\", \"fieldId\", \"values\"]))\n unsupportedQuery = true\n if (\n field.type === \"relation\" &&\n !(node.op === \"in\"\n ? node.values.every(\n (value) =>\n Array.isArray(value) && value.every(isEidosFileUuid)\n )\n : node.values.every(isEidosFileUuid))\n ) {\n throw new Error(\n \"View Relation filter values must be canonical Row IDs\"\n )\n }\n return\n }\n if ([\"contains\", \"starts-with\", \"ends-with\"].includes(node.op)) {\n if (typeof node.value !== \"string\")\n throw new Error(\"View text filter value must be a string\")\n if (!hasOnlyKeys(node, [\"op\", \"fieldId\", \"value\"]))\n unsupportedQuery = true\n return\n }\n if (node.op === \"relation-has\") {\n if (field.type !== \"relation\" || !isEidosFileUuid(node.rowId)) {\n throw new Error(\n \"View Relation filter must reference a canonical Row ID\"\n )\n }\n if (!hasOnlyKeys(node, [\"op\", \"fieldId\", \"rowId\"]))\n unsupportedQuery = true\n return\n }\n if (node.op === \"relative-date\") {\n if (\n field.type !== \"date\" &&\n field.type !== \"datetime\" &&\n field.type !== \"created-time\" &&\n field.type !== \"last-edited-time\"\n ) {\n throw new Error(\n \"View relative filter requires a Date or Datetime Field\"\n )\n }\n if (\n ![\"past\", \"next\", \"this\"].includes(String(node.direction)) ||\n ![\"day\", \"week\", \"month\", \"year\"].includes(String(node.unit))\n ) {\n throw new Error(\"View relative filter value is invalid\")\n }\n if (\n !hasOnlyKeys(node, [\"op\", \"fieldId\", \"direction\", \"unit\"])\n ) {\n unsupportedQuery = true\n }\n return\n }\n }\n\n if (typeof node.field !== \"string\" || !fieldIds.has(node.field)) {\n throw new Error(\"View filter references an unknown Field ID\")\n }\n if (!FILTER_OPERATORS.has(node.op)) {\n unsupportedQuery = true\n return\n }\n if (\n Object.keys(node).some(\n (key) => key !== \"field\" && key !== \"op\" && key !== \"value\"\n )\n ) {\n unsupportedQuery = true\n }\n const field = fieldsById.get(node.field)!\n const list =\n field.storageCodec === \"json_array\" ||\n field.storageCodec === \"relation\"\n if (\n list &&\n [\n \"greater-than\",\n \"greater-than-or-equal\",\n \"less-than\",\n \"less-than-or-equal\",\n \"starts-with\",\n \"ends-with\",\n ].includes(node.op)\n ) {\n throw new Error(\n \"View filter uses a scalar comparison on a list Field\"\n )\n }\n if (field.type === \"relation\" && \"value\" in node) {\n const values = Array.isArray(node.value)\n ? node.value\n : [node.value]\n if (\n !values.every(\n (entry) => entry === null || isEidosFileUuid(entry)\n )\n ) {\n throw new Error(\n \"View Relation filter values must be canonical Row IDs\"\n )\n }\n }\n if (node.op === \"is-between\") {\n if (!Array.isArray(node.value) || node.value.length !== 2) {\n throw new Error(\n \"View between filter must contain exactly two values\"\n )\n }\n }\n if (node.op === \"is-relative-to-today\") {\n if (\n field.type !== \"date\" &&\n field.type !== \"datetime\" &&\n field.type !== \"created-time\" &&\n field.type !== \"last-edited-time\"\n ) {\n throw new Error(\n \"View relative filter requires a Date or Datetime Field\"\n )\n }\n const relative = node.value\n if (\n !relative ||\n typeof relative !== \"object\" ||\n Array.isArray(relative)\n ) {\n throw new Error(\"View relative filter value is invalid\")\n }\n const relativeValue = relative as Record<string, unknown>\n if (\n typeof relativeValue.direction !== \"string\" ||\n typeof relativeValue.unit !== \"string\"\n ) {\n throw new Error(\"View relative filter value is invalid\")\n }\n if (\n ![\"past\", \"next\", \"this\"].includes(relativeValue.direction) ||\n ![\"day\", \"week\", \"month\", \"year\"].includes(\n relativeValue.unit\n ) ||\n Object.keys(relativeValue).some(\n (key) => key !== \"direction\" && key !== \"unit\"\n )\n ) {\n unsupportedQuery = true\n }\n }\n }\n if (\"filter\" in query) checkFilter(query.filter)\n if (\"sort\" in query) {\n if (!Array.isArray(query.sort))\n throw new Error(\"View sort must be an array\")\n for (const item of query.sort) {\n const fieldId =\n item && !Array.isArray(item) && typeof item === \"object\"\n ? typeof item.fieldId === \"string\"\n ? item.fieldId\n : item.field\n : undefined\n if (\n !item ||\n Array.isArray(item) ||\n typeof item !== \"object\" ||\n typeof fieldId !== \"string\" ||\n !fieldIds.has(fieldId)\n ) {\n throw new Error(\n \"View sort contains an invalid Field reference or direction\"\n )\n }\n if (\n (item.direction !== \"asc\" && item.direction !== \"desc\") ||\n (item.nulls !== undefined &&\n item.nulls !== \"first\" &&\n item.nulls !== \"last\") ||\n Object.keys(item).some(\n (key) =>\n key !== \"field\" &&\n key !== \"fieldId\" &&\n key !== \"direction\" &&\n key !== \"nulls\"\n )\n ) {\n unsupportedQuery = true\n }\n }\n }\n if (unsupportedQuery) {\n add(\n warnings,\n \"view-query-unsupported\",\n `View ${view.id} uses query semantics from a newer Eidos version`\n )\n }\n for (const key of [\n \"cardFields\",\n \"fieldOrder\",\n \"hiddenFields\",\n ] as const) {\n const value = layout[key]\n if (\n value !== undefined &&\n (!Array.isArray(value) ||\n !value.every(\n (fieldId) =>\n typeof fieldId === \"string\" && fieldIds.has(fieldId)\n ))\n ) {\n throw new Error(\n `View ${key} must contain Field IDs from its Table`\n )\n }\n }\n for (const key of [\n \"coverField\",\n \"groupField\",\n \"dateField\",\n ] as const) {\n const value = layout[key]\n if (\n value !== undefined &&\n value !== null &&\n (typeof value !== \"string\" || !fieldIds.has(value))\n ) {\n throw new Error(\n `View ${key} must be null or a Field ID from its Table`\n )\n }\n }\n if (layout.fieldWidths !== undefined) {\n if (\n !layout.fieldWidths ||\n Array.isArray(layout.fieldWidths) ||\n typeof layout.fieldWidths !== \"object\" ||\n Object.keys(layout.fieldWidths).some(\n (fieldId) => !fieldIds.has(fieldId)\n )\n ) {\n throw new Error(\n \"View fieldWidths keys must be Field IDs from its Table\"\n )\n }\n }\n } catch (error) {\n add(\n errors,\n \"invalid-schema\",\n error instanceof Error ? error.message : \"Invalid View\"\n )\n }\n }\n }\n\n const foreignKeyRows = connection.query<{ table: string; rowid: number }>(\n \"PRAGMA foreign_key_check\"\n )\n for (const violation of foreignKeyRows) {\n add(\n errors,\n \"invalid-schema\",\n `Foreign-key violation in ${violation.table}`,\n violation.table\n )\n }\n }\n\n if (level === \"content\" || level === \"full\") {\n const quickCheck = connection.get<{ quick_check: string }>(\n \"PRAGMA quick_check\"\n )\n if (quickCheck?.quick_check !== \"ok\") {\n add(\n errors,\n \"invalid-schema\",\n `SQLite quick_check failed: ${quickCheck?.quick_check ?? \"unknown\"}`\n )\n }\n for (const [tableId, fields] of fieldsByTable) {\n const table = tableRowsById.get(tableId)!\n const stored = fields.filter((field) => field.physicalName)\n if (stored.length === 0) continue\n const selection = stored\n .map((field) => quoteIdentifier(field.physicalName!))\n .join(\", \")\n for (const row of connection.query<Record<string, EidosFileSqlPrimitive>>(\n `SELECT ${selection} FROM ${quoteIdentifier(table.physical_name)}`\n )) {\n for (const field of stored) {\n const value = row[field.physicalName!]\n if (value === null || value === undefined) continue\n if (field.type === \"row-id\") {\n if (!isEidosFileUuid(value)) {\n add(\n errors,\n \"invalid-value\",\n `${table.name}._id must be canonical lowercase UUIDv7 TEXT`\n )\n }\n }\n if (\n field.type === \"number\" &&\n (typeof value !== \"number\" || !Number.isFinite(value))\n ) {\n add(\n errors,\n \"invalid-value\",\n `${table.name}.${field.name} must be finite REAL`\n )\n }\n if (field.type === \"checkbox\" && value !== 0 && value !== 1) {\n add(\n errors,\n \"invalid-value\",\n `${table.name}.${field.name} must be 0, 1, or NULL`\n )\n }\n if (field.type === \"date\" && !isCanonicalEidosFileDate(value)) {\n add(\n errors,\n \"invalid-value\",\n `${table.name}.${field.name} must be canonical YYYY-MM-DD text`\n )\n }\n if (field.type === \"url\" && !isEidosFileUriReference(value)) {\n add(\n errors,\n \"invalid-value\",\n `${table.name}.${field.name} must be a valid URI-reference`\n )\n }\n if (\n [\"datetime\", \"created-time\", \"last-edited-time\"].includes(\n field.type\n ) &&\n !isCanonicalEidosFileInstant(value)\n ) {\n add(\n errors,\n \"invalid-value\",\n `${table.name}.${field.name} must be canonical UTC millisecond text`\n )\n }\n if ([\"multi-select\", \"file\"].includes(field.type)) {\n let parsed: unknown = null\n if (field.type === \"file\" && typeof value === \"string\") {\n try {\n parsed = decodeEidosFileValues(value)\n } catch (error) {\n add(\n errors,\n \"invalid-value\",\n `${table.name}.${field.name}: ${error instanceof Error ? error.message : \"invalid File value\"}`\n )\n }\n } else if (\n typeof value === \"string\" &&\n isCanonicalEidosFileJson(value)\n ) {\n parsed = parseEidosFileJson(value)\n }\n if (!Array.isArray(parsed)) {\n add(\n errors,\n \"invalid-value\",\n `${table.name}.${field.name} must be a canonical JSON array`\n )\n }\n if (\n field.type === \"multi-select\" &&\n Array.isArray(parsed) &&\n (!parsed.every((entry) => typeof entry === \"string\") ||\n new Set(parsed).size !== parsed.length)\n ) {\n add(\n errors,\n \"invalid-value\",\n `${table.name}.${field.name} must be a unique string array`\n )\n }\n }\n if (field.type === \"relation\") {\n const ids = relationIds(value)\n const relation = relations.get(field.id!)\n if (!ids || relation?.direction !== \"forward\") {\n add(\n errors,\n \"invalid-value\",\n `${table.name}.${field.name} must be a canonical UUID array`\n )\n } else if (relation.cardinality === \"one\" && ids.length > 1) {\n add(\n errors,\n \"invalid-value\",\n `${table.name}.${field.name} exceeds cardinality one`\n )\n }\n }\n }\n }\n for (const field of fields) {\n const relation = field.id ? relations.get(field.id) : undefined\n if (\n field.type !== \"relation\" ||\n relation?.direction !== \"forward\" ||\n !field.physicalName\n ) {\n continue\n }\n const targetTable = tableRowsById.get(\n uuid(relation.target_table_id, \"Relation target Table ID\")\n )\n if (!targetTable) continue\n const missing =\n connection.get<{ total: number }>(\n `SELECT count(*) AS total\n FROM ${quoteIdentifier(table.physical_name)} source,\n json_each(CASE\n WHEN json_valid(source.${quoteIdentifier(field.physicalName)})\n AND json_type(source.${quoteIdentifier(field.physicalName)}) = 'array'\n THEN source.${quoteIdentifier(field.physicalName)} ELSE '[]' END\n ) item\n WHERE NOT EXISTS (\n SELECT 1 FROM ${quoteIdentifier(targetTable.physical_name)} target\n WHERE item.value = target.\"_id\"\n )`\n )?.total ?? 0\n if (missing > 0) {\n add(\n warnings,\n \"unresolved-relation\",\n `${table.name}.${field.name} contains ${missing} unresolved Relation value${missing === 1 ? \"\" : \"s\"}`,\n table.physical_name\n )\n }\n }\n }\n }\n\n return {\n valid: errors.length === 0,\n metadata,\n tables,\n errors,\n warnings,\n }\n}\n","import { canonicalizeEidosFileJson, parseEidosFileJson } from \"./canonical-json\"\nimport { isEidosFileUriReference } from \"./canonical-conversion\"\nimport { normalizeEidosFileColumnStatConfigs } from \"./column-stats\"\nimport type { EidosFileConnection, EidosFileSqlPrimitive } from \"./connection\"\nimport type { RecordNeighbors } from \"./runtime-contract\"\nimport {\n EIDOS_FILE_FIELDS_TABLE,\n EIDOS_FILE_FORMULA_FIELDS_TABLE,\n EIDOS_FILE_LOOKUP_FIELDS_TABLE,\n EIDOS_FILE_META_TABLE,\n EIDOS_FILE_RELATION_FIELDS_TABLE,\n EIDOS_FILE_TABLES_TABLE,\n EIDOS_FILE_VIEWS_TABLE,\n} from \"./constants\"\nimport { EidosFileError } from \"./errors\"\nimport {\n configuredTypeRef,\n eidosFileFieldValueType,\n} from \"./field-query-capabilities\"\nimport { assertEidosFileValues, decodeEidosFileValues } from \"./file-values\"\nimport { registerEidosFormulaFunctions } from \"./formula-functions\"\nimport {\n assertEidosFileFormulaProfile,\n compileEidosFileFormula,\n compileEidosFileFormulaSource,\n rewriteEidosFileFormulaFieldReferences,\n} from \"./formula\"\nimport {\n assertEidosFileDisplayName,\n assertEidosFileTableName,\n assertEidosFileUuid,\n createEidosFileUuid,\n quoteIdentifier,\n} from \"./identifiers\"\nimport {\n eidosFileLookupDisplayType,\n eidosFileLookupElementType,\n eidosFileLookupStorageCodec,\n eidosFileLookupTargetDisplayType,\n eidosFileLookupValueType,\n} from \"./lookup\"\nimport { registerEidosLookupFunctions } from \"./lookup-functions\"\nimport {\n assertEidosFileRowQuery,\n compileEidosFileRowQuery,\n eidosFileRowQuerySearchFields,\n eidosFileSortExpression,\n isEidosFileFilterOperator,\n normalizeEidosFileFilter,\n normalizeEidosFileRowQuery,\n normalizeEidosFileSorts,\n} from \"./query\"\nimport {\n decodeEidosFileRelationIds,\n encodeEidosFileRelationIds,\n} from \"./relation-values\"\nimport { incrementEidosFileRevision } from \"./schema\"\nimport {\n assertEidosFileMultiSelectHasNoDefaultOption,\n assertEidosFileSelectDefaultOption,\n assertEidosFileSelectOptions,\n parseEidosFileSelectDefaultOption,\n} from \"./select-options\"\nimport { scanStableRowPages } from \"./stable-row-scan\"\nimport {\n currentEidosFileInstant,\n eidosFileDateSqlCheck,\n eidosFileInstantSqlCheck,\n normalizeEidosFileDate,\n normalizeEidosFileInstant,\n} from \"./temporal\"\nimport type {\n CreateEidosFileFieldInput,\n CreateEidosFileTableInput,\n CreateEidosFileViewInput,\n EidosFileColumnStatConfig,\n EidosFileColumnStatResult,\n EidosFileFieldInfo,\n EidosFileFieldPlacement,\n EidosFileFieldType,\n EidosFileFilterGroup,\n EidosFileFilterRule,\n EidosFileFormulaPreview,\n EidosFileFormulaPreviewInput,\n EidosFileLogicalRow,\n EidosFileLogicalValue,\n EidosFileLookupAggregate,\n EidosFileMetadata,\n EidosFileRow,\n EidosFileRowGroupCount,\n EidosFileRowPage,\n EidosFileRowPageProjection,\n EidosFileRowQuery,\n EidosFileRowRange,\n EidosFileRowUpdate,\n EidosFileRowsMutation,\n EidosFileSchemaMutation,\n EidosFileSourceFieldType,\n EidosFileSort,\n EidosFileTableInfo,\n EidosFileViewInfo,\n ImportEidosFileFieldInput,\n UpdateEidosFileFieldInput,\n UpdateEidosFileTableInput,\n UpdateEidosFileViewInput,\n} from \"./types\"\nimport { validateEidosFile } from \"./validation\"\n\ninterface TableRow {\n id: string\n name: string\n physical_name: string\n label_field_id: string\n position: number\n settings_json: string\n created_at: string\n updated_at: string\n}\n\ninterface FieldRow {\n id: string\n table_id: string\n name: string\n physical_name: string | null\n type: EidosFileFieldType\n system_role: \"row-id\" | \"created-time\" | \"updated-time\" | null\n nullable: number\n position: number\n settings_json: string\n created_at: string\n updated_at: string\n}\n\ninterface RelationRow {\n field_id: string\n direction: \"forward\" | \"inverse\"\n inverse_of_field_id: string | null\n target_table_id: string\n cardinality: \"one\" | \"many\"\n on_delete: \"restrict\" | \"detach\" | \"preserve\" | null\n}\n\ninterface DeletedPhysicalRowState {\n tableId: string\n physicalTable: string\n row: Record<string, EidosFileSqlPrimitive>\n}\n\ninterface DetachedRelationState {\n tableId: string\n physicalTable: string\n physicalColumn: string\n rowId: string\n value: EidosFileSqlPrimitive\n detachedValue: EidosFileSqlPrimitive\n}\n\ninterface RowDeletionUndoState {\n tableId: string\n rowIds: string[]\n rows: DeletedPhysicalRowState[]\n detachedRelations: DetachedRelationState[]\n}\n\ntype RowMutationUndoEntry =\n | { kind: \"restore-delete\"; state: RowDeletionUndoState }\n | { kind: \"repeat-delete\"; state: RowDeletionUndoState }\n\ninterface RetainedRowMutationUndoEntry {\n entry: RowMutationUndoEntry\n bytes: number\n}\n\ninterface PreparedRowMutationUndoEntry {\n token: string\n retained: RetainedRowMutationUndoEntry\n}\n\nconst ROW_MUTATION_UNDO_ENTRIES_MAX = 50\nconst ROW_MUTATION_UNDO_BYTES_MAX = 64 * 1024 * 1024\n\ninterface FormulaRow {\n field_id: string\n source_text: string\n result_type: string\n}\n\ninterface LookupRow {\n field_id: string\n relation_field_id: string\n target_field_id: string\n aggregate: EidosFileLookupAggregate\n distinct_values: number\n}\n\nfunction sameSqlValue(\n left: EidosFileSqlPrimitive | undefined,\n right: EidosFileSqlPrimitive\n): boolean {\n if (left instanceof Uint8Array && right instanceof Uint8Array) {\n return (\n left.byteLength === right.byteLength &&\n left.every((value, index) => value === right[index])\n )\n }\n if (\n (typeof left === \"number\" || typeof left === \"bigint\") &&\n (typeof right === \"number\" || typeof right === \"bigint\") &&\n (typeof left === \"bigint\" || Number.isInteger(left)) &&\n (typeof right === \"bigint\" || Number.isInteger(right))\n ) {\n return BigInt(left) === BigInt(right)\n }\n return Object.is(left, right)\n}\n\ninterface ViewRow {\n id: string\n table_id: string\n name: string\n type: string\n query_json: string\n layout_json: string\n position: number\n created_at: string\n updated_at: string\n}\n\ninterface RuntimeSchema {\n tables: Map<string, TableRow>\n fields: Map<string, EidosFileFieldInfo>\n fieldsByTable: Map<string, EidosFileFieldInfo[]>\n relations: Map<string, RelationRow>\n formulas: Map<string, FormulaRow>\n lookups: Map<string, LookupRow>\n}\n\ninterface PreparedField {\n id: string\n name: string\n type: EidosFileFieldType\n physicalName: string | null\n settings: Record<string, unknown>\n input?: CreateEidosFileFieldInput\n isRecordLabel: boolean\n systemRole: \"row-id\" | \"created-time\" | \"updated-time\" | null\n nullable: boolean\n}\n\nfunction systemFieldsLast<T extends { systemRole?: string | null }>(\n fields: readonly T[]\n): T[] {\n return [\n ...fields.filter(\n (field) => field.systemRole === null || field.systemRole === undefined\n ),\n ...fields.filter(\n (field) => field.systemRole !== null && field.systemRole !== undefined\n ),\n ]\n}\n\nconst SYSTEM_FIELD_NAMES = {\n \"row-id\": \"_id\",\n \"created-time\": \"_created_at\",\n \"last-edited-time\": \"_updated_at\",\n} as const\n\nconst SYSTEM_FIELD_PHYSICAL_NAMES = {\n \"row-id\": \"_id\",\n \"created-time\": \"_created_at\",\n \"last-edited-time\": \"_updated_at\",\n} as const\n\nconst LABEL_TYPES = new Set<EidosFileFieldType>([\n \"row-id\",\n \"created-time\",\n \"last-edited-time\",\n \"text\",\n \"number\",\n \"integer\",\n \"checkbox\",\n \"date\",\n \"datetime\",\n \"url\",\n \"rating\",\n \"select\",\n \"formula\",\n \"lookup\",\n])\n\nfunction uuid(value: string): string {\n return assertEidosFileUuid(value)\n}\n\nfunction jsonObject(value: string): Record<string, unknown> {\n try {\n const parsed = parseEidosFileJson(value)\n return parsed && !Array.isArray(parsed) && typeof parsed === \"object\"\n ? parsed\n : {}\n } catch {\n return {}\n }\n}\n\nfunction canonicalFieldType(input: {\n type: EidosFileFieldType\n}): EidosFileFieldType {\n return input.type === \"rating\" ? \"integer\" : input.type\n}\n\nfunction persistedFieldType(type: EidosFileFieldType): EidosFileFieldType {\n if (type === \"row-id\") return \"text\"\n if (type === \"created-time\" || type === \"last-edited-time\") return \"datetime\"\n if (type === \"rating\") return \"integer\"\n return type\n}\n\nfunction canonicalTemporalProjection(expression: string, type: string): string {\n if (type === \"date\") {\n return `CASE WHEN (${expression}) IS NULL THEN NULL\n ELSE strftime('%Y-%m-%d', (${expression}), '+0 days') END`\n }\n if (type === \"datetime\") {\n return `CASE WHEN (${expression}) IS NULL THEN NULL\n ELSE strftime('%Y-%m-%dT%H:%M:%fZ', (${expression})) END`\n }\n return expression\n}\n\nfunction isVirtualField(\n type: EidosFileFieldType,\n input?: CreateEidosFileFieldInput\n): boolean {\n if (type === \"formula\" || type === \"lookup\") return true\n return (\n type === \"relation\" &&\n input !== undefined &&\n input.type === \"relation\" &&\n input.property.direction === \"inverse\"\n )\n}\n\nfunction fieldColumnSql(field: PreparedField): string | null {\n if (!field.physicalName) return null\n const column = quoteIdentifier(field.physicalName)\n switch (field.type) {\n case \"row-id\":\n return `${column} TEXT PRIMARY KEY COLLATE BINARY\n CHECK(length(CAST(${column} AS BLOB))=36 AND instr(${column},char(0))=0\n AND substr(${column},9,1)='-' AND substr(${column},14,1)='-'\n AND substr(${column},15,1)='7' AND substr(${column},19,1)='-'\n AND substr(${column},20,1) IN ('8','9','a','b') AND substr(${column},24,1)='-'\n AND lower(${column})=${column}\n AND length(CAST(replace(${column},'-','') AS BLOB))=32\n AND replace(${column},'-','') NOT GLOB '*[^0-9a-f]*')`\n case \"created-time\":\n case \"last-edited-time\":\n return `${column} TEXT NOT NULL CHECK(${eidosFileInstantSqlCheck(column)})`\n case \"text\":\n case \"url\":\n case \"select\":\n return `${column} TEXT${field.nullable ? \"\" : \" NOT NULL\"}`\n case \"number\":\n return `${column} REAL${field.nullable ? \"\" : \" NOT NULL\"}`\n case \"integer\":\n return `${column} INTEGER${field.nullable ? \"\" : \" NOT NULL\"}`\n case \"date\":\n return `${column} TEXT${field.nullable ? \"\" : \" NOT NULL\"} CHECK(${eidosFileDateSqlCheck(column)})`\n case \"datetime\":\n return `${column} TEXT${field.nullable ? \"\" : \" NOT NULL\"} CHECK(${eidosFileInstantSqlCheck(column)})`\n case \"rating\":\n return `${column} INTEGER`\n case \"checkbox\":\n return `${column} INTEGER${field.nullable ? \"\" : \" NOT NULL\"} CHECK(${column} IS NULL OR ${column} IN (0, 1))`\n case \"file\":\n case \"multi-select\":\n case \"relation\":\n return `${column} TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(${column}) AND json_type(${column}) = 'array')`\n default:\n return null\n }\n}\n\nfunction stablePosition(\n value: number | null | undefined,\n fallback: number\n): number {\n return typeof value === \"number\" && Number.isFinite(value)\n ? Math.max(0, Math.trunc(value))\n : fallback\n}\n\nfunction presentationSettingsObject(\n source: Record<string, unknown> | null | undefined\n): Record<string, unknown> {\n const property = source ? { ...source } : {}\n for (const key of [\n \"formula\",\n \"displayType\",\n \"targetTableId\",\n \"targetField\",\n \"multiple\",\n \"direction\",\n \"sourceFieldId\",\n \"cardinality\",\n \"onDelete\",\n \"relationField\",\n \"aggregate\",\n \"distinct\",\n ]) {\n delete property[key]\n }\n return property\n}\n\nfunction assertedRawSelectOptions(\n property: Record<string, unknown> | null | undefined\n): Array<Record<string, unknown>> {\n assertEidosFileSelectOptions(property)\n return Array.isArray(property?.options)\n ? property.options.map((option) => ({\n ...(option as Record<string, unknown>),\n }))\n : []\n}\n\nfunction presentationSettings(\n input: CreateEidosFileFieldInput\n): Record<string, unknown> {\n const property = presentationSettingsObject(\n \"property\" in input ? input.property : undefined\n )\n if (input.type === \"select\" || input.type === \"multi-select\") {\n property.options = assertedRawSelectOptions(\n \"property\" in input ? input.property : undefined\n )\n if (input.type === \"select\") {\n const defaultOption = assertEidosFileSelectDefaultOption(property)\n if (defaultOption === null) delete property.defaultOption\n else property.defaultOption = defaultOption\n } else {\n assertEidosFileMultiSelectHasNoDefaultOption(property)\n }\n }\n return property\n}\n\nfunction transformOptionValue(\n value: unknown,\n fieldId: string,\n changes: Map<string, string>\n): unknown {\n if (Array.isArray(value)) {\n return value.map((entry) => transformOptionValue(entry, fieldId, changes))\n }\n if (!value || typeof value !== \"object\") return value\n const object = value as Record<string, unknown>\n const referencesField = object.fieldId === fieldId || object.field === fieldId\n const next: Record<string, unknown> = {}\n for (const [key, entry] of Object.entries(object)) {\n if (\n referencesField &&\n (key === \"value\" ||\n key === \"values\" ||\n key === \"lower\" ||\n key === \"upper\")\n ) {\n next[key] = Array.isArray(entry)\n ? entry.map((item) =>\n typeof item === \"string\" ? (changes.get(item) ?? item) : item\n )\n : typeof entry === \"string\"\n ? (changes.get(entry) ?? entry)\n : entry\n } else {\n next[key] = transformOptionValue(entry, fieldId, changes)\n }\n }\n return next\n}\n\nfunction rowValue(value: EidosFileSqlPrimitive): EidosFileRow[string] {\n return value\n}\n\nfunction cursorSortValue(\n row: Record<string, EidosFileSqlPrimitive>,\n field: EidosFileFieldInfo\n): EidosFileSqlPrimitive {\n const value = row[field.tableColumnName] ?? null\n if (\n typeof value === \"string\" &&\n (field.storageCodec === \"json_array\" || field.storageCodec === \"relation\")\n ) {\n try {\n const parsed = parseEidosFileJson(value)\n if (Array.isArray(parsed)) {\n const first = parsed.find((entry) => entry !== null)\n return typeof first === \"string\" ||\n typeof first === \"number\" ||\n typeof first === \"boolean\" ||\n first === null ||\n first === undefined\n ? first === true\n ? 1\n : first === false\n ? 0\n : (first ?? null)\n : canonicalizeEidosFileJson(first)\n }\n } catch {\n return null\n }\n }\n return value\n}\n\nfunction encodeCursorSqlValue(value: EidosFileSqlPrimitive): unknown {\n if (typeof value === \"bigint\") return { integer: value.toString() }\n if (\n value === null ||\n typeof value === \"string\" ||\n (typeof value === \"number\" && Number.isFinite(value))\n ) {\n return value\n }\n throw new EidosFileError(\n \"invalid-query\",\n \"Sort boundary is not a scalar JSON cursor value\"\n )\n}\n\nfunction decodeCursorSqlValue(value: unknown): EidosFileSqlPrimitive {\n if (\n value === null ||\n typeof value === \"string\" ||\n (typeof value === \"number\" && Number.isFinite(value))\n ) {\n return value\n }\n if (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.keys(value).length === 1 &&\n \"integer\" in value &&\n typeof value.integer === \"string\" &&\n /^-?(?:0|[1-9][0-9]*)$/.test(value.integer)\n ) {\n const integer = BigInt(value.integer)\n if (\n integer >= -9_223_372_036_854_775_808n &&\n integer <= 9_223_372_036_854_775_807n\n ) {\n return integer\n }\n }\n throw new EidosFileError(\"invalid-query\", \"Cursor sort value is invalid\")\n}\n\nfunction uniqueSortFields(\n fields: EidosFileFieldInfo[],\n sorts: EidosFileSort[] | undefined\n): Array<{ field: EidosFileFieldInfo; sort: EidosFileSort }> {\n const byColumn = new Map(\n fields.map((field) => [field.tableColumnName, field])\n )\n const seen = new Set<string>()\n return (sorts ?? []).flatMap((sort) => {\n if (seen.has(sort.field)) return []\n const field = byColumn.get(sort.field)\n if (!field) return []\n seen.add(sort.field)\n return [{ field, sort }]\n })\n}\n\nfunction compileKeysetAfter(\n sorts: Array<{ field: EidosFileFieldInfo; sort: EidosFileSort }>,\n values: EidosFileSqlPrimitive[],\n lastId: string\n): { sql: string; params: EidosFileSqlPrimitive[] } {\n if (values.length !== sorts.length) {\n throw new EidosFileError(\"invalid-query\", \"Cursor sort tuple is invalid\")\n }\n const params: EidosFileSqlPrimitive[] = []\n const branches: string[] = []\n // Equality placeholders occur in every later branch, so construct the\n // parameter list in the same branch order instead of sharing SQL prefixes.\n sorts.forEach(({ field, sort }, index) => {\n const expression = eidosFileSortExpression(field)\n const value = values[index] ?? null\n let after: string\n if (value === null) {\n after = sort.nulls === \"first\" ? `${expression} IS NOT NULL` : \"0\"\n } else {\n const comparison = sort.direction === \"desc\" ? \"<\" : \">\"\n after =\n sort.nulls === \"last\"\n ? `(${expression} ${comparison} ? OR ${expression} IS NULL)`\n : `${expression} ${comparison} ?`\n }\n if (after !== \"0\") {\n const parts: string[] = []\n for (let prefixIndex = 0; prefixIndex < index; prefixIndex += 1) {\n const prefixExpression = eidosFileSortExpression(\n sorts[prefixIndex]!.field\n )\n const prefixValue = values[prefixIndex] ?? null\n if (prefixValue === null) parts.push(`${prefixExpression} IS NULL`)\n else {\n parts.push(`${prefixExpression} IS ?`)\n params.push(prefixValue)\n }\n }\n parts.push(after)\n if (value !== null) params.push(value)\n branches.push(`(${parts.join(\" AND \")})`)\n }\n })\n const finalParts: string[] = []\n sorts.forEach(({ field }, index) => {\n const expression = eidosFileSortExpression(field)\n const value = values[index] ?? null\n if (value === null) finalParts.push(`${expression} IS NULL`)\n else {\n finalParts.push(`${expression} IS ?`)\n params.push(value)\n }\n })\n finalParts.push('\"__base_rowid\" > ?')\n params.push(assertEidosFileUuid(lastId, \"Cursor Row ID\"))\n branches.push(`(${finalParts.join(\" AND \")})`)\n return { sql: `(${branches.join(\" OR \")})`, params }\n}\n\nfunction compileKeysetBefore(\n sorts: Array<{ field: EidosFileFieldInfo; sort: EidosFileSort }>,\n values: EidosFileSqlPrimitive[],\n firstId: string\n): { sql: string; params: EidosFileSqlPrimitive[] } {\n if (values.length !== sorts.length) {\n throw new EidosFileError(\"invalid-query\", \"Sort boundary is invalid\")\n }\n const params: EidosFileSqlPrimitive[] = []\n const branches: string[] = []\n sorts.forEach(({ field, sort }, index) => {\n const expression = eidosFileSortExpression(field)\n const value = values[index] ?? null\n let before: string\n if (value === null) {\n before = sort.nulls === \"last\" ? `${expression} IS NOT NULL` : \"0\"\n } else {\n const comparison = sort.direction === \"desc\" ? \">\" : \"<\"\n before =\n sort.nulls === \"first\"\n ? `(${expression} ${comparison} ? OR ${expression} IS NULL)`\n : `${expression} ${comparison} ?`\n }\n if (before !== \"0\") {\n const parts: string[] = []\n for (let prefixIndex = 0; prefixIndex < index; prefixIndex += 1) {\n const prefixExpression = eidosFileSortExpression(\n sorts[prefixIndex]!.field\n )\n const prefixValue = values[prefixIndex] ?? null\n if (prefixValue === null) parts.push(`${prefixExpression} IS NULL`)\n else {\n parts.push(`${prefixExpression} IS ?`)\n params.push(prefixValue)\n }\n }\n parts.push(before)\n if (value !== null) params.push(value)\n branches.push(`(${parts.join(\" AND \")})`)\n }\n })\n const finalParts: string[] = []\n sorts.forEach(({ field }, index) => {\n const expression = eidosFileSortExpression(field)\n const value = values[index] ?? null\n if (value === null) finalParts.push(`${expression} IS NULL`)\n else {\n finalParts.push(`${expression} IS ?`)\n params.push(value)\n }\n })\n finalParts.push('\"__base_rowid\" < ?')\n params.push(assertEidosFileUuid(firstId, \"Row ID\"))\n branches.push(`(${finalParts.join(\" AND \")})`)\n return { sql: `(${branches.join(\" OR \")})`, params }\n}\n\nfunction filterToStorage(\n filter: EidosFileFilterGroup | null | undefined,\n fields: EidosFileFieldInfo[]\n): Record<string, unknown> | null {\n const normalized = normalizeEidosFileFilter(filter)\n if (!normalized) return null\n const byKey = new Map<string, EidosFileFieldInfo>()\n for (const field of fields) {\n if (field.id) {\n byKey.set(field.id, field)\n byKey.set(field.tableColumnName, field)\n byKey.set(field.name, field)\n }\n }\n const convertRule = (\n rule: EidosFileFilterRule\n ): Record<string, unknown> | null => {\n const field = byKey.get(rule.field)\n if (!field?.id) return null\n const fieldId = field.id\n const list =\n field.storageCodec === \"json_array\" || field.storageCodec === \"relation\"\n const values = Array.isArray(rule.value) ? rule.value : [rule.value ?? null]\n const scalar = values[0] ?? null\n const equalityValue =\n list && Array.isArray(rule.value) ? rule.value : scalar\n const requireValue = () => {\n if (scalar === null) {\n throw new EidosFileError(\n \"invalid-query\",\n `Saved View filter ${rule.operator} requires an operand`\n )\n }\n return scalar\n }\n const requireValues = () => {\n if (values.some((value) => value === null)) {\n throw new EidosFileError(\n \"invalid-query\",\n `Saved View filter ${rule.operator} requires non-null operands`\n )\n }\n return values\n }\n const membership = (): Record<string, unknown> =>\n list\n ? { fieldId, op: \"has-any\", values: requireValues() }\n : { fieldId, op: \"in\", values: requireValues() }\n\n if (rule.operator === \"is-relative-to-today\") {\n const relative = rule.value\n if (\n !relative ||\n typeof relative !== \"object\" ||\n Array.isArray(relative) ||\n !(\"direction\" in relative) ||\n !(\"unit\" in relative) ||\n ![\"past\", \"next\", \"this\"].includes(String(relative.direction)) ||\n ![\"day\", \"week\", \"month\", \"year\"].includes(String(relative.unit))\n ) {\n throw new EidosFileError(\n \"invalid-query\",\n \"Saved View relative date filter is invalid\"\n )\n }\n return {\n direction: relative.direction,\n fieldId,\n op: \"relative-date\",\n unit: relative.unit,\n }\n }\n if (rule.operator === \"is-between\") {\n if (\n !Array.isArray(rule.value) ||\n rule.value.length !== 2 ||\n rule.value.some((value) => value === null)\n ) {\n throw new EidosFileError(\n \"invalid-query\",\n \"Saved View between filter is invalid\"\n )\n }\n return {\n fieldId,\n lower: rule.value[0],\n op: \"between\",\n upper: rule.value[1],\n }\n }\n switch (rule.operator) {\n case \"is-empty\":\n return list\n ? { fieldId, op: \"eq\", value: [] }\n : { fieldId, op: \"is-null\" }\n case \"is-not-empty\":\n return list\n ? { fieldId, op: \"ne\", value: [] }\n : { fieldId, op: \"is-not-null\" }\n case \"equals\":\n return equalityValue === null\n ? { fieldId, op: \"is-null\" }\n : { fieldId, op: \"eq\", value: equalityValue }\n case \"not-equals\":\n return equalityValue === null\n ? { fieldId, op: \"is-not-null\" }\n : { fieldId, op: \"ne\", value: equalityValue }\n case \"less-than\":\n return { fieldId, op: \"lt\", value: requireValue() }\n case \"less-than-or-equal\":\n return { fieldId, op: \"lte\", value: requireValue() }\n case \"greater-than\":\n return { fieldId, op: \"gt\", value: requireValue() }\n case \"greater-than-or-equal\":\n return { fieldId, op: \"gte\", value: requireValue() }\n case \"contains\":\n return list\n ? membership()\n : { fieldId, op: \"contains\", value: String(requireValue()) }\n case \"not-contains\":\n return {\n arg: list\n ? membership()\n : { fieldId, op: \"contains\", value: String(requireValue()) },\n op: \"not\",\n }\n case \"starts-with\":\n return { fieldId, op: \"starts-with\", value: String(requireValue()) }\n case \"ends-with\":\n return { fieldId, op: \"ends-with\", value: String(requireValue()) }\n case \"is-any-of\":\n return membership()\n case \"is-all-of\":\n return { fieldId, op: \"has-all\", values: requireValues() }\n case \"is-none-of\":\n return { arg: membership(), op: \"not\" }\n }\n }\n const convertGroup = (\n group: EidosFileFilterGroup\n ): Record<string, unknown> => {\n const node: Record<string, unknown> = {\n args: group.children.flatMap((child) => {\n const converted =\n child.type === \"group\" ? convertGroup(child) : convertRule(child)\n return converted ? [converted] : []\n }),\n op: group.conjunction,\n }\n return group.negated ? { arg: node, op: \"not\" } : node\n }\n return convertGroup(normalized)\n}\n\nfunction filterFromStorage(\n value: unknown,\n fields: EidosFileFieldInfo[]\n): EidosFileFilterGroup | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null\n const ids = new Set(fields.flatMap((field) => (field.id ? [field.id] : [])))\n const convert = (input: unknown): EidosFileFilterGroup | null => {\n if (!input || typeof input !== \"object\" || Array.isArray(input)) return null\n const group = input as Record<string, unknown>\n if (!Array.isArray(group.args)) return null\n const children: EidosFileFilterGroup[\"children\"] = []\n for (const child of group.args) {\n if (!child || typeof child !== \"object\" || Array.isArray(child)) continue\n const object = child as Record<string, unknown>\n if (Array.isArray(object.args)) {\n const nested = convert(object)\n if (nested) children.push(nested)\n } else if (\n typeof object.field === \"string\" &&\n typeof object.op === \"string\"\n ) {\n if (ids.has(object.field)) {\n children.push({\n type: \"rule\",\n field: object.field,\n operator: object.op as EidosFileFilterRule[\"operator\"],\n ...(\"value\" in object ? { value: object.value as never } : {}),\n } as EidosFileFilterGroup[\"children\"][number])\n }\n }\n }\n return {\n type: \"group\",\n conjunction: group.op === \"or\" ? \"or\" : \"and\",\n children,\n }\n }\n const runtimeGroup = (\n conjunction: \"and\" | \"or\",\n children: EidosFileFilterGroup[\"children\"]\n ): EidosFileFilterGroup => ({ type: \"group\", conjunction, children })\n const convertRuntime = (\n input: unknown\n ): EidosFileFilterGroup[\"children\"][number] | null => {\n if (!input || typeof input !== \"object\" || Array.isArray(input)) return null\n const node = input as Record<string, unknown>\n if ((node.op === \"and\" || node.op === \"or\") && Array.isArray(node.args)) {\n return runtimeGroup(\n node.op,\n node.args.flatMap((child) => {\n const converted = convertRuntime(child)\n return converted ? [converted] : []\n })\n )\n }\n if (node.op === \"not\" && node.arg !== undefined) {\n const child = convertRuntime(node.arg)\n if (!child) return null\n const nested =\n child.type === \"group\" ? child : runtimeGroup(\"and\", [child])\n return { ...nested, negated: nested.negated !== true }\n }\n if (\n typeof node.fieldId !== \"string\" ||\n !ids.has(node.fieldId) ||\n typeof node.op !== \"string\"\n ) {\n return null\n }\n const field = node.fieldId\n if (node.op === \"between\") {\n return {\n type: \"rule\",\n field,\n operator: \"is-between\",\n value: [node.lower, node.upper] as never,\n }\n }\n if (node.op === \"relative-date\") {\n return {\n type: \"rule\",\n field,\n operator: \"is-relative-to-today\",\n value: { direction: node.direction, unit: node.unit } as never,\n }\n }\n if (node.op === \"has-all\") {\n return {\n type: \"rule\",\n field,\n operator: \"is-all-of\",\n value: node.values as never,\n }\n }\n if (node.op === \"in\") {\n return runtimeGroup(\n \"or\",\n (node.values as unknown[]).map((entry) => ({\n type: \"rule\" as const,\n field,\n operator: \"equals\" as const,\n value: entry as never,\n }))\n )\n }\n if (node.op === \"is-null\" || node.op === \"is-not-null\") {\n return {\n type: \"rule\",\n field,\n operator: node.op === \"is-null\" ? \"equals\" : \"not-equals\",\n value: null,\n }\n }\n const operator = RUNTIME_TO_COMPATIBILITY_OPERATOR[node.op]\n if (!operator) return null\n return {\n type: \"rule\",\n field,\n operator,\n ...(node.op === \"has-any\"\n ? { value: node.values as never }\n : node.op === \"relation-has\"\n ? { value: [node.rowId] as never }\n : \"value\" in node\n ? { value: node.value as never }\n : {}),\n }\n }\n const containsRuntimeField = (input: unknown): boolean => {\n if (!input || typeof input !== \"object\") return false\n if (Array.isArray(input)) return input.some(containsRuntimeField)\n const node = input as Record<string, unknown>\n return (\n typeof node.fieldId === \"string\" ||\n Object.values(node).some(containsRuntimeField)\n )\n }\n if (!containsRuntimeField(value)) {\n return normalizeEidosFileFilter(convert(value))\n }\n const converted = convertRuntime(value)\n return normalizeEidosFileFilter(\n converted?.type === \"group\"\n ? converted\n : converted\n ? runtimeGroup(\"and\", [converted])\n : null\n )\n}\n\nconst RUNTIME_TO_COMPATIBILITY_OPERATOR: Record<\n string,\n EidosFileFilterRule[\"operator\"] | undefined\n> = {\n eq: \"equals\",\n ne: \"not-equals\",\n lt: \"less-than\",\n lte: \"less-than-or-equal\",\n gt: \"greater-than\",\n gte: \"greater-than-or-equal\",\n contains: \"contains\",\n \"starts-with\": \"starts-with\",\n \"ends-with\": \"ends-with\",\n \"has-any\": \"is-any-of\",\n \"relation-has\": \"is-any-of\",\n}\n\nconst RUNTIME_FILTER_OPERATORS = new Set([\n \"is-null\",\n \"is-not-null\",\n \"eq\",\n \"ne\",\n \"lt\",\n \"lte\",\n \"gt\",\n \"gte\",\n \"between\",\n \"in\",\n \"contains\",\n \"starts-with\",\n \"ends-with\",\n \"has-any\",\n \"has-all\",\n \"relation-has\",\n \"relative-date\",\n])\n\nfunction sortsFromStorage(value: unknown): EidosFileSort[] {\n if (!Array.isArray(value)) return []\n return value.flatMap((entry) => {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) return []\n const sort = entry as Record<string, unknown>\n const field =\n typeof sort.fieldId === \"string\"\n ? sort.fieldId\n : typeof sort.field === \"string\"\n ? sort.field\n : null\n if (!field) return []\n return [\n {\n field,\n direction:\n sort.direction === \"desc\" ? (\"desc\" as const) : (\"asc\" as const),\n nulls: sort.nulls === \"first\" ? (\"first\" as const) : (\"last\" as const),\n },\n ]\n })\n}\n\nfunction sortsToStorage(sorts: EidosFileSort[]): Record<string, unknown>[] {\n return sorts.map((sort) => ({\n direction: sort.direction,\n fieldId: sort.field,\n ...(sort.nulls === \"first\" ? { nulls: \"first\" } : {}),\n }))\n}\n\nfunction storedViewQueryStatus(\n query: Record<string, unknown>,\n fields: EidosFileFieldInfo[]\n): \"supported\" | \"unsupported\" {\n const fieldIds = new Set(\n fields.flatMap((field) => (field.id ? [field.id] : []))\n )\n if (Object.keys(query).some((key) => key !== \"filter\" && key !== \"sort\")) {\n return \"unsupported\"\n }\n const supportedScalar = (value: unknown): boolean =>\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n const supportedRuleValue = (\n operator: EidosFileFilterRule[\"operator\"],\n value: unknown\n ): boolean => {\n if (operator === \"is-relative-to-today\") {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false\n }\n const relative = value as Record<string, unknown>\n return (\n Object.keys(relative).every(\n (key) => key === \"direction\" || key === \"unit\"\n ) &&\n [\"past\", \"next\", \"this\"].includes(String(relative.direction)) &&\n [\"day\", \"week\", \"month\", \"year\"].includes(String(relative.unit))\n )\n }\n if (operator === \"is-between\") {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n value.every(supportedScalar)\n )\n }\n return (\n value === undefined ||\n supportedScalar(value) ||\n (Array.isArray(value) && value.every(supportedScalar))\n )\n }\n const filterSupported = (value: unknown): boolean => {\n if (!value || typeof value !== \"object\" || Array.isArray(value))\n return false\n const node = value as Record<string, unknown>\n if ((node.op === \"and\" || node.op === \"or\") && Array.isArray(node.args)) {\n return (\n Object.keys(node).every((key) => key === \"op\" || key === \"args\") &&\n node.args.every(filterSupported)\n )\n }\n if (node.op === \"not\") {\n return (\n Object.keys(node).every((key) => key === \"op\" || key === \"arg\") &&\n filterSupported(node.arg)\n )\n }\n if (typeof node.fieldId === \"string\") {\n if (\n !fieldIds.has(node.fieldId) ||\n typeof node.op !== \"string\" ||\n !RUNTIME_FILTER_OPERATORS.has(node.op)\n ) {\n return false\n }\n const allowed = new Set([\"fieldId\", \"op\"])\n if (\n [\n \"eq\",\n \"ne\",\n \"lt\",\n \"lte\",\n \"gt\",\n \"gte\",\n \"contains\",\n \"starts-with\",\n \"ends-with\",\n ].includes(node.op)\n ) {\n allowed.add(\"value\")\n if (!(\"value\" in node) || node.value === null) return false\n } else if ([\"in\", \"has-any\", \"has-all\"].includes(node.op)) {\n allowed.add(\"values\")\n if (!Array.isArray(node.values)) return false\n } else if (node.op === \"between\") {\n allowed.add(\"lower\")\n allowed.add(\"upper\")\n if (\n !(\"lower\" in node) ||\n !(\"upper\" in node) ||\n node.lower === null ||\n node.upper === null\n ) {\n return false\n }\n } else if (node.op === \"relation-has\") {\n allowed.add(\"rowId\")\n if (typeof node.rowId !== \"string\") return false\n } else if (node.op === \"relative-date\") {\n allowed.add(\"direction\")\n allowed.add(\"unit\")\n if (\n ![\"past\", \"next\", \"this\"].includes(String(node.direction)) ||\n ![\"day\", \"week\", \"month\", \"year\"].includes(String(node.unit))\n ) {\n return false\n }\n }\n return Object.keys(node).every((key) => allowed.has(key))\n }\n if (\n typeof node.field !== \"string\" ||\n !fieldIds.has(node.field) ||\n !isEidosFileFilterOperator(node.op) ||\n Object.keys(node).some(\n (key) => key !== \"field\" && key !== \"op\" && key !== \"value\"\n )\n ) {\n return false\n }\n return supportedRuleValue(node.op, node.value)\n }\n if (\"filter\" in query && !filterSupported(query.filter)) {\n return \"unsupported\"\n }\n if (\"sort\" in query) {\n if (!Array.isArray(query.sort)) return \"unsupported\"\n for (const value of query.sort) {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return \"unsupported\"\n }\n const sort = value as Record<string, unknown>\n const field =\n typeof sort.fieldId === \"string\"\n ? sort.fieldId\n : typeof sort.field === \"string\"\n ? sort.field\n : null\n const fieldKey = typeof sort.fieldId === \"string\" ? \"fieldId\" : \"field\"\n if (\n !field ||\n !fieldIds.has(field) ||\n (sort.direction !== \"asc\" && sort.direction !== \"desc\") ||\n (sort.nulls !== undefined &&\n sort.nulls !== \"first\" &&\n sort.nulls !== \"last\") ||\n Object.keys(sort).some(\n (key) => key !== fieldKey && key !== \"direction\" && key !== \"nulls\"\n )\n ) {\n return \"unsupported\"\n }\n }\n }\n return \"supported\"\n}\n\nexport class EidosFileRuntime {\n private mutationDepth = 0\n private mutationInstant: string | null = null\n private readonly rowMutationUndoEntries = new Map<\n string,\n RetainedRowMutationUndoEntry\n >()\n private rowMutationUndoBytes = 0\n private nestedMutationInvalidatesRowUndo = false\n private schemaCache:\n | { dataVersion: number; schema: RuntimeSchema }\n | undefined\n private readonly nowInstant: () => string\n private readonly allocateId: () => string\n\n constructor(\n readonly connection: EidosFileConnection,\n private readonly ownsConnection = false,\n environment: {\n nowInstant?: () => string\n allocateId?: () => string\n } = {}\n ) {\n this.nowInstant = environment.nowInstant ?? currentEidosFileInstant\n this.allocateId = environment.allocateId ?? (() => createEidosFileUuid())\n connection.exec(\"PRAGMA foreign_keys = ON; PRAGMA trusted_schema = OFF;\")\n connection.registerFunction(\"eidos_casefold\", (value) =>\n value === null ? null : String(value).toUpperCase().toLowerCase()\n )\n connection.registerFunction(\n \"eidos_canonical_number\",\n (value) => {\n if (value === null) return null\n const number = Number(value)\n return Number.isFinite(number)\n ? canonicalizeEidosFileJson(Object.is(number, -0) ? 0 : number)\n : null\n },\n 1\n )\n registerEidosFormulaFunctions(connection)\n assertEidosFileFormulaProfile(connection)\n registerEidosLookupFunctions(connection)\n }\n\n close(): void {\n this.clearRowMutationUndoEntries()\n if (this.ownsConnection) this.connection.close?.()\n }\n\n inspect() {\n return validateEidosFile(this.connection)\n }\n\n validate(\n options: {\n level?: \"identity\" | \"structural\" | \"content\" | \"semantic\" | \"full\"\n } = {}\n ) {\n return validateEidosFile(this.connection, options)\n }\n\n info(): EidosFileMetadata {\n const result = validateEidosFile(this.connection, { level: \"identity\" })\n if (!result.metadata || !result.valid) {\n throw new EidosFileError(\n \"not-eidos-file\",\n result.errors.map((issue) => issue.message).join(\"; \")\n )\n }\n return result.metadata\n }\n\n metadata(): EidosFileMetadata {\n return this.info()\n }\n\n private tableRow(tableId: string): TableRow {\n const row = this.allSchema().tables.get(\n assertEidosFileUuid(tableId, \"Table ID\")\n )\n if (!row) {\n throw new EidosFileError(\n \"table-not-found\",\n `Eidos File Table not found: ${tableId}`\n )\n }\n return row\n }\n\n private fieldRows(tableId: string): FieldRow[] {\n return this.connection.query<FieldRow>(\n `SELECT * FROM ${EIDOS_FILE_FIELDS_TABLE}\n WHERE table_id = ? ORDER BY position, id`,\n [assertEidosFileUuid(tableId, \"Table ID\")]\n )\n }\n\n private allSchema(): RuntimeSchema {\n const dataVersion = this.connection.dataVersion()\n if (\n this.mutationDepth === 0 &&\n this.schemaCache?.dataVersion === dataVersion\n ) {\n return this.schemaCache.schema\n }\n const tableRows = this.connection.query<TableRow>(\n `SELECT * FROM ${EIDOS_FILE_TABLES_TABLE}`\n )\n const tables = new Map(tableRows.map((table) => [uuid(table.id), table]))\n const relationRows = this.connection.query<RelationRow>(\n `SELECT * FROM ${EIDOS_FILE_RELATION_FIELDS_TABLE}`\n )\n const formulaRows = this.connection.query<FormulaRow>(\n `SELECT * FROM ${EIDOS_FILE_FORMULA_FIELDS_TABLE}`\n )\n const lookupRows = this.connection.query<LookupRow>(\n `SELECT * FROM ${EIDOS_FILE_LOOKUP_FIELDS_TABLE}`\n )\n const relations = new Map(\n relationRows.map((row) => [uuid(row.field_id), row])\n )\n const formulas = new Map(\n formulaRows.map((row) => [uuid(row.field_id), row])\n )\n const lookups = new Map(lookupRows.map((row) => [uuid(row.field_id), row]))\n const fields = new Map<string, EidosFileFieldInfo>()\n const fieldsByTable = new Map<string, EidosFileFieldInfo[]>()\n for (const row of this.connection.query<FieldRow>(\n `SELECT * FROM ${EIDOS_FILE_FIELDS_TABLE} ORDER BY table_id, position, id`\n )) {\n const id = uuid(row.id)\n const tableId = uuid(row.table_id)\n const table = tables.get(tableId)\n if (!table) continue\n const relation = relations.get(id)\n const formula = formulas.get(id)\n const lookup = lookups.get(id)\n const settings = jsonObject(row.settings_json)\n const type: EidosFileFieldType =\n row.system_role === \"row-id\"\n ? \"row-id\"\n : row.system_role === \"created-time\"\n ? \"created-time\"\n : row.system_role === \"updated-time\"\n ? \"last-edited-time\"\n : row.type\n const virtual =\n type === \"formula\" ||\n type === \"lookup\" ||\n (type === \"relation\" && relation?.direction === \"inverse\")\n let property: Record<string, unknown> | null = settings\n if (relation) {\n property = {\n ...settings,\n targetTableId: uuid(relation.target_table_id),\n targetField: \"\",\n multiple: relation.cardinality === \"many\",\n direction: relation.direction,\n sourceFieldId: relation.inverse_of_field_id\n ? uuid(relation.inverse_of_field_id)\n : undefined,\n cardinality: relation.cardinality,\n onDelete: relation.on_delete,\n }\n } else if (formula) {\n property = {\n ...settings,\n formula: formula.source_text,\n displayType: formula.result_type,\n }\n } else if (lookup) {\n const target = fields.get(uuid(lookup.target_field_id))\n property = {\n ...settings,\n relationField: uuid(lookup.relation_field_id),\n targetField: uuid(lookup.target_field_id),\n aggregate: lookup.aggregate,\n displayType: target\n ? eidosFileLookupDisplayType(lookup.aggregate, target)\n : lookup.aggregate === \"count\"\n ? \"number\"\n : \"text\",\n distinct: lookup.distinct_values === 1,\n }\n }\n const field: EidosFileFieldInfo = {\n id,\n tableId,\n name: row.name,\n type,\n tableName: table.physical_name,\n tableColumnName: row.physical_name ?? id,\n physicalName: row.physical_name,\n systemRole: row.system_role,\n nullable: row.nullable === 1,\n isRecordLabel: table.label_field_id === id,\n position: row.position,\n settings,\n property,\n storageCodec:\n type === \"relation\" && relation?.direction === \"forward\"\n ? \"relation\"\n : type === \"file\" ||\n type === \"multi-select\" ||\n (type === \"lookup\" && lookup?.aggregate === \"values\")\n ? \"json_array\"\n : \"scalar\",\n valueKind: [\"row-id\", \"created-time\", \"last-edited-time\"].includes(type)\n ? \"system\"\n : virtual\n ? \"derived\"\n : type === \"relation\"\n ? \"relation\"\n : \"source\",\n isHidden: [\"row-id\", \"created-time\", \"last-edited-time\"].includes(type),\n isDerived: virtual,\n sourceTableColumnName:\n relation?.direction === \"inverse\" && relation.inverse_of_field_id\n ? uuid(relation.inverse_of_field_id)\n : null,\n dependsOn: formula\n ? []\n : lookup\n ? [uuid(lookup.relation_field_id), uuid(lookup.target_field_id)]\n : null,\n }\n fields.set(id, field)\n const ownerFields = fieldsByTable.get(tableId) ?? []\n ownerFields.push(field)\n fieldsByTable.set(tableId, ownerFields)\n }\n // Resolve nested Lookup result TypeRefs after every Field is known.\n for (let pass = 0; pass < fields.size; pass += 1) {\n let changed = false\n for (const [id, lookup] of lookups) {\n const field = fields.get(id)\n const target = fields.get(uuid(lookup.target_field_id))\n if (field?.property && target) {\n const valueType = eidosFileLookupValueType(lookup.aggregate, target)\n const displayType = eidosFileLookupDisplayType(\n lookup.aggregate,\n target\n )\n if (\n JSON.stringify(field.property.valueType) !==\n JSON.stringify(valueType) ||\n field.property.displayType !== displayType\n ) {\n field.property.valueType = valueType\n field.property.displayType = displayType\n changed = true\n }\n }\n }\n if (!changed) break\n }\n const schema = {\n tables,\n fields,\n fieldsByTable,\n relations,\n formulas,\n lookups,\n }\n if (this.mutationDepth === 0) this.schemaCache = { dataVersion, schema }\n return schema\n }\n\n listTables(): EidosFileTableInfo[] {\n return Array.from(this.allSchema().tables.values())\n .sort(\n (left, right) =>\n left.position - right.position ||\n uuid(left.id).localeCompare(uuid(right.id))\n )\n .map((row) => ({\n ...(() => {\n const settings = jsonObject(row.settings_json)\n return {\n icon: typeof settings.icon === \"string\" ? settings.icon : null,\n description:\n typeof settings.description === \"string\"\n ? settings.description\n : null,\n contentFieldId:\n typeof settings.contentFieldId === \"string\"\n ? settings.contentFieldId\n : null,\n }\n })(),\n id: uuid(row.id),\n name: row.name,\n physicalName: row.physical_name,\n rawTableName: row.physical_name,\n position: row.position,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n }))\n }\n\n getTable(tableId: string): EidosFileTableInfo {\n const row = this.tableRow(tableId)\n const settings = jsonObject(row.settings_json)\n return {\n id: uuid(row.id),\n name: row.name,\n physicalName: row.physical_name,\n rawTableName: row.physical_name,\n position: row.position,\n icon: typeof settings.icon === \"string\" ? settings.icon : null,\n description:\n typeof settings.description === \"string\" ? settings.description : null,\n contentFieldId:\n typeof settings.contentFieldId === \"string\"\n ? settings.contentFieldId\n : null,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n }\n }\n\n listFields(tableId: string): EidosFileFieldInfo[] {\n this.tableRow(tableId)\n return this.allSchema().fieldsByTable.get(tableId) ?? []\n }\n\n private fieldByKey(tableId: string, key: string): EidosFileFieldInfo {\n const fields = this.listFields(tableId)\n const field = fields.find(\n (candidate) =>\n candidate.id === key ||\n candidate.tableColumnName === key ||\n candidate.physicalName === key ||\n candidate.name === key\n )\n if (!field) {\n throw new EidosFileError(\n \"field-not-found\",\n `Eidos File Field not found: ${key}`\n )\n }\n return field\n }\n\n /** @internal Exact Runtime service transaction composition hook. */\n applyCanonicalMutation<T>(\n operation: (instant: string) => T,\n expectedRevision?: number | bigint\n ): T {\n return this.mutate(\n () => operation(this.operationInstant()),\n expectedRevision\n )\n }\n\n private mutate<T>(\n operation: () => T,\n expectedRevision?: number | bigint,\n invalidatesRowUndo = false\n ): T {\n if (this.mutationDepth > 0) {\n const result = operation()\n if (invalidatesRowUndo) this.nestedMutationInvalidatesRowUndo = true\n return result\n }\n const previousInvalidation = this.nestedMutationInvalidatesRowUndo\n this.nestedMutationInvalidatesRowUndo = false\n let clearRowUndoAfterCommit = false\n try {\n const result = this.connection.transaction(() => {\n this.schemaCache = undefined\n const revision = this.info().revision ?? 0\n if (\n expectedRevision !== undefined &&\n BigInt(revision) !== BigInt(expectedRevision)\n ) {\n throw new EidosFileError(\n \"stale-revision\",\n `Expected revision ${expectedRevision}, found ${revision}`\n )\n }\n const totalChangesBefore =\n this.connection.get<{ total: number | bigint }>(\n \"SELECT total_changes() AS total\"\n )?.total ?? 0\n this.mutationInstant = this.nowInstant()\n this.mutationDepth += 1\n try {\n const operationResult = operation()\n const totalChangesAfter =\n this.connection.get<{ total: number | bigint }>(\n \"SELECT total_changes() AS total\"\n )?.total ?? totalChangesBefore\n if (BigInt(totalChangesAfter) === BigInt(totalChangesBefore)) {\n return operationResult\n }\n const validation = validateEidosFile(this.connection, {\n level: \"semantic\",\n })\n if (!validation.valid) {\n throw new EidosFileError(\n \"invalid-schema\",\n validation.errors.map((issue) => issue.message).join(\"; \")\n )\n }\n incrementEidosFileRevision(this.connection, this.operationInstant())\n clearRowUndoAfterCommit =\n invalidatesRowUndo || this.nestedMutationInvalidatesRowUndo\n return operationResult\n } finally {\n this.mutationDepth -= 1\n this.mutationInstant = null\n this.schemaCache = undefined\n }\n })\n if (clearRowUndoAfterCommit) this.clearRowMutationUndoEntries()\n return result\n } finally {\n this.nestedMutationInvalidatesRowUndo = previousInvalidation\n }\n }\n\n private mutateSchemaState<T>(operation: () => T): T {\n return this.mutate(operation, undefined, true)\n }\n\n private operationInstant(): string {\n return this.mutationInstant ?? this.nowInstant()\n }\n\n private prepareFields(input: CreateEidosFileTableInput): PreparedField[] {\n const systemIds = [this.allocateId(), this.allocateId(), this.allocateId()]\n const userFields: PreparedField[] = (input.fields ?? []).map((field) => {\n const id = field.id ?? this.allocateId()\n assertEidosFileUuid(id, \"Field ID\")\n assertEidosFileDisplayName(field.name, \"Field name\")\n return {\n id,\n name: field.name,\n type: canonicalFieldType(field),\n physicalName: null,\n settings: {\n ...presentationSettings(field),\n ...(field.type === \"rating\" ? { display: { kind: \"rating\" } } : {}),\n },\n input: field,\n isRecordLabel: \"isRecordLabel\" in field && field.isRecordLabel === true,\n systemRole: null,\n nullable:\n field.type === \"formula\" || field.type === \"lookup\"\n ? true\n : field.type === \"file\" ||\n field.type === \"multi-select\" ||\n field.type === \"relation\"\n ? false\n : \"nullable\" in field\n ? field.nullable !== false\n : true,\n } satisfies PreparedField\n })\n const names = new Set<string>(\n Object.values(SYSTEM_FIELD_NAMES).map((name) =>\n name.replace(/[A-Z]/g, (character) => character.toLowerCase())\n )\n )\n if (userFields.filter((field) => field.isRecordLabel).length > 1) {\n throw new EidosFileError(\n \"constraint-conflict\",\n \"A Table can declare only one Record Label Field\"\n )\n }\n for (const field of userFields) {\n const folded = field.name.replace(/[A-Z]/g, (character) =>\n character.toLowerCase()\n )\n if (names.has(folded)) {\n throw new EidosFileError(\n \"constraint-conflict\",\n `Field names must be unique under SQLite NOCASE: ${field.name}`\n )\n }\n names.add(folded)\n }\n const systemTypes = [\"row-id\", \"created-time\", \"last-edited-time\"] as const\n const system = systemTypes.map(\n (type, index) =>\n ({\n id: systemIds[index]!,\n name: SYSTEM_FIELD_NAMES[type],\n type,\n physicalName: SYSTEM_FIELD_PHYSICAL_NAMES[type],\n settings: {},\n isRecordLabel: false,\n systemRole: type === \"last-edited-time\" ? \"updated-time\" : type,\n nullable: false,\n }) satisfies PreparedField\n )\n if (!userFields.some((field) => field.isRecordLabel)) {\n const firstScalar = userFields.find(\n (field) =>\n LABEL_TYPES.has(field.type) &&\n !isVirtualField(field.type, field.input)\n )\n ;(firstScalar ?? system[0]!).isRecordLabel = true\n }\n for (const field of userFields) {\n if (isVirtualField(field.type, field.input)) continue\n field.physicalName = field.name\n }\n return [...system, ...userFields]\n }\n\n createTable(input: CreateEidosFileTableInput): EidosFileTableInfo {\n const physicalName = assertEidosFileTableName(input.name)\n if (\n this.listTables().some(\n (table) =>\n table.name.replace(/[A-Z]/g, (character) =>\n character.toLowerCase()\n ) ===\n input.name.replace(/[A-Z]/g, (character) => character.toLowerCase())\n )\n ) {\n throw new EidosFileError(\n \"constraint-conflict\",\n `Duplicate Table name: ${input.name}`\n )\n }\n const tableId = input.id ?? this.allocateId()\n assertEidosFileUuid(tableId, \"Table ID\")\n const fields = this.prepareFields(input)\n const position = this.listTables().length\n return this.mutateSchemaState(() => {\n const now = this.operationInstant()\n const definitions = fields.flatMap((field) => {\n const definition = fieldColumnSql(field)\n return definition ? [definition] : []\n })\n this.connection.exec(\n `CREATE TABLE ${quoteIdentifier(physicalName)} (${definitions.join(\", \")}) STRICT, WITHOUT ROWID`\n )\n const labelField = fields.find((field) => field.isRecordLabel)\n if (!labelField) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"A Table requires exactly one Record Label Field\"\n )\n }\n const tableSettings = canonicalizeEidosFileJson({\n ...(input.icon === undefined ? {} : { icon: input.icon }),\n ...(input.description === undefined\n ? {}\n : { description: input.description }),\n })\n this.connection.run(\n `INSERT INTO ${EIDOS_FILE_TABLES_TABLE}\n (id, name, physical_name, label_field_id, position, settings_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n [\n tableId,\n input.name,\n physicalName,\n labelField.id,\n position,\n tableSettings,\n now,\n now,\n ]\n )\n // Insert every base Field first. Lookup and inverse definitions may\n // reference siblings whose position is later in the input list.\n fields.forEach((field, fieldPosition) => {\n const position =\n field.systemRole === \"row-id\"\n ? -3\n : field.systemRole === \"created-time\"\n ? -2\n : field.systemRole === \"updated-time\"\n ? -1\n : fieldPosition - 3\n this.insertFieldMetadata(tableId, field, position, now)\n })\n fields.forEach((field) => {\n this.insertFieldSubtypeMetadata(tableId, field)\n })\n this.installRowIdTrigger(tableId, physicalName)\n for (const field of fields) {\n if (field.type === \"relation\" && field.input) {\n this.installRelationTriggers(field.id)\n }\n }\n if (input.createDefaultView !== false) {\n const viewId = this.allocateId()\n const fieldOrder = systemFieldsLast(fields).map((field) => field.id)\n this.connection.run(\n `INSERT INTO ${EIDOS_FILE_VIEWS_TABLE}\n (id, table_id, name, type, query_json, layout_json, position, created_at, updated_at)\n VALUES (?, ?, ?, 'grid', '{}', ?, 0, ?, ?)`,\n [\n viewId,\n tableId,\n \"Grid\",\n canonicalizeEidosFileJson({\n cardFields: [],\n coverField: null,\n fieldOrder,\n fieldWidths: {},\n groupField: null,\n hiddenFields: fields\n .filter(\n (field) =>\n !field.isRecordLabel &&\n [\"row-id\", \"created-time\", \"last-edited-time\"].includes(\n field.type\n )\n )\n .map((field) => field.id),\n }),\n now,\n now,\n ]\n )\n }\n return {\n id: tableId,\n name: input.name,\n physicalName,\n rawTableName: physicalName,\n position,\n icon: input.icon ?? null,\n description: input.description ?? null,\n contentFieldId: null,\n createdAt: now,\n updatedAt: now,\n }\n })\n }\n\n private insertFieldMetadata(\n tableId: string,\n field: PreparedField,\n position: number,\n now: string\n ): void {\n this.connection.run(\n `INSERT INTO ${EIDOS_FILE_FIELDS_TABLE}\n (id, table_id, name, physical_name, type, system_role, nullable, position,\n settings_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n [\n field.id,\n tableId,\n field.name,\n field.physicalName,\n persistedFieldType(field.type),\n field.systemRole,\n field.nullable ? 1 : 0,\n position,\n canonicalizeEidosFileJson(field.settings),\n now,\n now,\n ]\n )\n }\n\n private insertFieldSubtypeMetadata(\n tableId: string,\n field: PreparedField\n ): void {\n const input = field.input\n if (!input) return\n if (field.type === \"formula\" && input.type === \"formula\") {\n this.connection.run(\n `INSERT INTO ${EIDOS_FILE_FORMULA_FIELDS_TABLE}\n (field_id, source_text, result_type) VALUES (?, ?, ?)`,\n [field.id, input.property.formula, input.property.displayType]\n )\n }\n if (field.type === \"relation\" && input.type === \"relation\") {\n const direction = input.property.direction ?? \"forward\"\n const sourceFieldId = input.property.sourceFieldId ?? null\n const cardinality =\n direction === \"inverse\"\n ? \"many\"\n : (input.property.cardinality ??\n (input.property.multiple ? \"many\" : \"one\"))\n this.connection.run(\n `INSERT INTO ${EIDOS_FILE_RELATION_FIELDS_TABLE}\n (field_id, direction, inverse_of_field_id, target_table_id, cardinality, on_delete)\n VALUES (?, ?, ?, ?, ?, ?)`,\n [\n field.id,\n direction,\n sourceFieldId\n ? assertEidosFileUuid(sourceFieldId, \"Source Field ID\")\n : null,\n assertEidosFileUuid(input.property.targetTableId, \"Target Table ID\"),\n cardinality,\n direction === \"forward\"\n ? (input.property.onDelete ?? \"restrict\")\n : null,\n ]\n )\n }\n if (field.type === \"lookup\" && input.type === \"lookup\") {\n const relation = this.fieldByKey(tableId, input.property.relationField)\n const schema = this.allSchema()\n const relationDefinition = schema.relations.get(relation.id!)\n if (!relationDefinition) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Lookup requires a Relation Field\"\n )\n }\n const targetTableId = uuid(relationDefinition.target_table_id)\n const target = this.fieldByKey(targetTableId, input.property.targetField)\n this.connection.run(\n `INSERT INTO ${EIDOS_FILE_LOOKUP_FIELDS_TABLE}\n (field_id, relation_field_id, target_field_id, aggregate, distinct_values)\n VALUES (?, ?, ?, ?, ?)`,\n [\n field.id,\n relation.id!,\n target.id!,\n input.property.aggregate,\n input.property.distinct === true ? 1 : 0,\n ]\n )\n }\n }\n\n private installRowIdTrigger(tableId: string, physicalName: string): void {\n const trigger = `eidos__row_id_immutable__${tableId.replace(/-/g, \"\")}`\n this.connection.exec(`\n CREATE TRIGGER ${quoteIdentifier(trigger)}\n BEFORE UPDATE OF \"_id\" ON ${quoteIdentifier(physicalName)}\n WHEN NEW.\"_id\" IS NOT OLD.\"_id\"\n BEGIN SELECT RAISE(ABORT, 'EIDOS_ROW_ID_IMMUTABLE'); END;\n `)\n }\n\n private installRelationTriggers(fieldId: string): void {\n const schema = this.allSchema()\n const field = schema.fields.get(fieldId)\n const relation = schema.relations.get(fieldId)\n if (\n !field ||\n !relation ||\n relation.direction !== \"forward\" ||\n !field.physicalName\n )\n return\n const sourceTable = schema.tables.get(field.tableId!)!\n const targetTable = schema.tables.get(uuid(relation.target_table_id))!\n const hex = fieldId.replace(/-/g, \"\")\n const column = quoteIdentifier(field.physicalName)\n const invalidUuid = `(typeof(item.value) <> 'text' OR length(item.value) <> 36\n OR substr(item.value, 9, 1) <> '-' OR substr(item.value, 14, 1) <> '-'\n OR substr(item.value, 19, 1) <> '-' OR substr(item.value, 24, 1) <> '-'\n OR substr(item.value, 15, 1) <> '7'\n OR substr(item.value, 20, 1) NOT IN ('8','9','a','b')\n OR replace(item.value, '-', '') GLOB '*[^0-9a-f]*')`\n for (const event of [\"INSERT\", \"UPDATE\"] as const) {\n const triggerName = `eidos__relation_validate_${event.toLowerCase()}__${hex}`\n const newValue = `NEW.${column}`\n const safeArray = `CASE WHEN json_valid(${newValue}) AND json_type(${newValue}) = 'array' THEN ${newValue} ELSE '[]' END`\n const updateOf = event === \"UPDATE\" ? ` OF ${column}` : \"\"\n this.connection.exec(`\n CREATE TRIGGER ${quoteIdentifier(triggerName)}\n BEFORE ${event}${updateOf} ON ${quoteIdentifier(sourceTable.physical_name)}\n WHEN NOT json_valid(${newValue})\n OR json_type(${newValue}) <> 'array'\n OR EXISTS (SELECT 1 FROM json_each(${safeArray}) item WHERE ${invalidUuid})\n OR (SELECT count(*) FROM json_each(${safeArray})) <>\n (SELECT count(DISTINCT value) FROM json_each(${safeArray}))\n ${relation.cardinality === \"one\" ? `OR json_array_length(${safeArray}) > 1` : \"\"}\n BEGIN SELECT RAISE(ABORT, 'EIDOS_INVALID_RELATION_VALUE'); END;\n `)\n }\n if (relation.on_delete === \"preserve\") return\n const targetUuid = `OLD.\"_id\"`\n const triggerName = `eidos__relation_${relation.on_delete}__${hex}`\n if (relation.on_delete === \"restrict\") {\n this.connection.exec(`\n CREATE TRIGGER ${quoteIdentifier(triggerName)}\n BEFORE DELETE ON ${quoteIdentifier(targetTable.physical_name)}\n WHEN EXISTS (\n SELECT 1 FROM ${quoteIdentifier(sourceTable.physical_name)} source,\n json_each(source.${column}) item WHERE item.value = ${targetUuid}\n )\n BEGIN SELECT RAISE(ABORT, 'EIDOS_RELATION_RESTRICT'); END;\n `)\n } else {\n this.connection.exec(`\n CREATE TRIGGER ${quoteIdentifier(triggerName)}\n BEFORE DELETE ON ${quoteIdentifier(targetTable.physical_name)}\n WHEN EXISTS (\n SELECT 1 FROM ${quoteIdentifier(sourceTable.physical_name)} source,\n json_each(source.${column}) item WHERE item.value = ${targetUuid}\n )\n BEGIN\n UPDATE ${quoteIdentifier(sourceTable.physical_name)}\n SET ${column} = (\n SELECT coalesce(json_group_array(value), '[]') FROM (\n SELECT item.value AS value FROM json_each(${column}) item\n WHERE item.value <> ${targetUuid} ORDER BY CAST(item.key AS INTEGER)\n )\n ), \"_updated_at\" = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')\n WHERE EXISTS (SELECT 1 FROM json_each(${column}) item WHERE item.value = ${targetUuid});\n END;\n `)\n }\n }\n\n private dropRelationTriggers(fieldId: string): void {\n const hex = fieldId.replace(/-/g, \"\")\n for (const name of [\n `eidos__relation_validate_insert__${hex}`,\n `eidos__relation_validate_update__${hex}`,\n `eidos__relation_restrict__${hex}`,\n `eidos__relation_detach__${hex}`,\n `eidos__relation_preserve__${hex}`,\n ]) {\n this.connection.exec(`DROP TRIGGER IF EXISTS ${quoteIdentifier(name)}`)\n }\n }\n\n updateTable(\n tableId: string,\n changes: UpdateEidosFileTableInput\n ): EidosFileTableInfo {\n const table = this.getTable(tableId)\n const persistedSettings = jsonObject(this.tableRow(tableId).settings_json)\n return this.mutateSchemaState(() => {\n let name = table.name\n let physicalName = table.physicalName ?? table.rawTableName\n if (changes.name !== undefined && changes.name !== table.name) {\n name = assertEidosFileTableName(changes.name)\n if (\n this.listTables().some(\n (candidate) =>\n candidate.id !== tableId &&\n candidate.name.replace(/[A-Z]/g, (character) =>\n character.toLowerCase()\n ) ===\n name.replace(/[A-Z]/g, (character) => character.toLowerCase())\n )\n ) {\n throw new EidosFileError(\n \"constraint-conflict\",\n `Duplicate Table name: ${name}`\n )\n }\n physicalName = name\n if (physicalName !== (table.physicalName ?? table.rawTableName)) {\n const previousPhysicalName = table.physicalName ?? table.rawTableName\n if (\n previousPhysicalName !== physicalName &&\n previousPhysicalName.replace(/[A-Z]/g, (character) =>\n character.toLowerCase()\n ) ===\n physicalName.replace(/[A-Z]/g, (character) =>\n character.toLowerCase()\n )\n ) {\n const baseTemporary = `eidos__rename_table__${tableId.replace(/-/g, \"\")}`\n let temporary = baseTemporary\n let suffix = 0\n const occupied = new Set(\n this.connection\n .query<{ name: string }>(\"SELECT name FROM sqlite_schema\")\n .map((object) =>\n object.name.replace(/[A-Z]/g, (character) =>\n character.toLowerCase()\n )\n )\n )\n while (occupied.has(temporary.toLowerCase())) {\n suffix += 1\n temporary = `${baseTemporary}__${suffix}`\n }\n this.connection.exec(\n `ALTER TABLE ${quoteIdentifier(previousPhysicalName)} RENAME TO ${quoteIdentifier(temporary)}`\n )\n this.connection.exec(\n `ALTER TABLE ${quoteIdentifier(temporary)} RENAME TO ${quoteIdentifier(physicalName)}`\n )\n } else {\n this.connection.exec(\n `ALTER TABLE ${quoteIdentifier(previousPhysicalName)} RENAME TO ${quoteIdentifier(physicalName)}`\n )\n }\n }\n }\n const now = this.operationInstant()\n const nextSettings = { ...persistedSettings }\n if (changes.icon !== undefined) {\n if (changes.icon === null) delete nextSettings.icon\n else nextSettings.icon = changes.icon\n }\n if (changes.description !== undefined) {\n if (changes.description === null) delete nextSettings.description\n else nextSettings.description = changes.description\n }\n if (changes.contentFieldId !== undefined) {\n if (changes.contentFieldId === null) {\n delete nextSettings.contentFieldId\n } else {\n const contentField = this.fieldByKey(tableId, changes.contentFieldId)\n if (\n contentField.type !== \"text\" ||\n contentField.valueKind !== \"source\" ||\n contentField.systemRole != null ||\n !contentField.physicalName\n ) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"The Content Field must be an ordinary Text Field in the same Table\"\n )\n }\n nextSettings.contentFieldId = contentField.id\n }\n }\n let recordLabelFieldId = this.tableRow(tableId).label_field_id\n if (changes.recordLabelFieldId !== undefined) {\n const labelField = this.fieldByKey(tableId, changes.recordLabelFieldId)\n if (labelField.type === \"lookup\" || !LABEL_TYPES.has(labelField.type)) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"The Record Label Field must be a scalar Field in the same Table\"\n )\n }\n recordLabelFieldId = labelField.id\n }\n const settings = canonicalizeEidosFileJson(nextSettings)\n this.connection.run(\n `UPDATE ${EIDOS_FILE_TABLES_TABLE}\n SET name = ?, physical_name = ?, label_field_id = ?, settings_json = ?, updated_at = ?\n WHERE id = ?`,\n [name, physicalName, recordLabelFieldId, settings, now, tableId]\n )\n return this.getTable(tableId)\n })\n }\n\n deleteTable(tableId: string): boolean {\n const table = this.getTable(tableId)\n return this.mutateSchemaState(() => {\n this.connection.exec(\n `DROP TABLE ${quoteIdentifier(table.physicalName ?? table.rawTableName)}`\n )\n const result = this.connection.run(\n `DELETE FROM ${EIDOS_FILE_TABLES_TABLE} WHERE id = ?`,\n [tableId]\n )\n return result.changes > 0\n })\n }\n\n addField(\n tableId: string,\n input: CreateEidosFileFieldInput,\n placement?: EidosFileFieldPlacement\n ): EidosFileFieldInfo {\n const table = this.getTable(tableId)\n assertEidosFileDisplayName(input.name, \"Field name\")\n const id = input.id ?? this.allocateId()\n assertEidosFileUuid(id, \"Field ID\")\n const type = canonicalFieldType(input)\n const fields = this.listFields(tableId)\n if (\n fields.some(\n (field) =>\n field.name.replace(/[A-Z]/g, (character) =>\n character.toLowerCase()\n ) ===\n input.name.replace(/[A-Z]/g, (character) => character.toLowerCase())\n )\n ) {\n throw new EidosFileError(\n \"constraint-conflict\",\n `Duplicate Field name: ${input.name}`\n )\n }\n const physicalName = isVirtualField(type, input) ? null : input.name\n const prepared: PreparedField = {\n id,\n name: input.name,\n type,\n physicalName,\n settings: {\n ...presentationSettings(input),\n ...(input.type === \"rating\" ? { display: { kind: \"rating\" } } : {}),\n },\n input,\n isRecordLabel: \"isRecordLabel\" in input && input.isRecordLabel === true,\n systemRole: null,\n nullable:\n input.type === \"formula\" || input.type === \"lookup\"\n ? true\n : input.type === \"file\" ||\n input.type === \"multi-select\" ||\n input.type === \"relation\"\n ? false\n : \"nullable\" in input\n ? input.nullable !== false\n : true,\n }\n if (\n prepared.physicalName &&\n !prepared.nullable &&\n ![\"file\", \"multi-select\", \"relation\"].includes(prepared.type) &&\n this.countRows(tableId) > 0\n ) {\n throw new EidosFileError(\n \"constraint-conflict\",\n \"A populated Table cannot add a non-null scalar Field without a default\"\n )\n }\n return this.mutateSchemaState(() => {\n if (prepared.isRecordLabel && prepared.type === \"lookup\") {\n throw new EidosFileError(\n \"invalid-schema\",\n \"A Lookup cannot be the Record Label Field in Eidos File 1.0\"\n )\n }\n const definition = fieldColumnSql(prepared)\n if (definition) {\n this.connection.exec(\n `ALTER TABLE ${quoteIdentifier(table.physicalName ?? table.rawTableName)} ADD COLUMN ${definition}`\n )\n }\n this.insertFieldMetadata(\n tableId,\n prepared,\n fields.length,\n this.operationInstant()\n )\n this.insertFieldSubtypeMetadata(tableId, prepared)\n if (prepared.isRecordLabel) {\n this.connection.run(\n `UPDATE ${EIDOS_FILE_TABLES_TABLE}\n SET label_field_id = ?, updated_at = ? WHERE id = ?`,\n [id, this.operationInstant(), tableId]\n )\n }\n if (type === \"relation\") this.installRelationTriggers(id)\n if (placement) {\n const view = this.viewRow(placement.viewId)\n const layout = jsonObject(view.layout_json)\n const order = Array.isArray(layout.fieldOrder)\n ? layout.fieldOrder.filter(\n (value): value is string => typeof value === \"string\"\n )\n : fields.flatMap((field) => (field.id ? [field.id] : []))\n order.splice(\n Math.max(0, Math.min(placement.index, order.length)),\n 0,\n id\n )\n layout.fieldOrder = order\n this.connection.run(\n `UPDATE ${EIDOS_FILE_VIEWS_TABLE} SET layout_json = ?, updated_at = ? WHERE id = ?`,\n [canonicalizeEidosFileJson(layout), this.operationInstant(), view.id]\n )\n }\n return this.fieldByKey(tableId, id)\n })\n }\n\n importField(\n tableId: string,\n input: ImportEidosFileFieldInput\n ): EidosFileFieldInfo {\n if (\n input.type === \"formula\" ||\n input.type === \"lookup\" ||\n input.type === \"relation\"\n ) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Import derived and Relation Fields through canonical subtype definitions\"\n )\n }\n return this.addField(tableId, {\n name: input.name,\n columnName: input.columnName,\n type: input.type as EidosFileSourceFieldType,\n property: input.property ?? undefined,\n storageCodec: input.storageCodec,\n })\n }\n\n updateField(\n tableId: string,\n fieldKey: string,\n changes: UpdateEidosFileFieldInput\n ): EidosFileFieldInfo {\n const table = this.getTable(tableId)\n const field = this.fieldByKey(tableId, fieldKey)\n const fieldId = field.id\n if (\n changes.type !== undefined &&\n canonicalFieldType({\n type: changes.type,\n } as CreateEidosFileFieldInput) !== field.type\n ) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Field type conversion requires an explicit canonical conversion operation\"\n )\n }\n return this.mutateSchemaState(() => {\n let name = field.name\n let physicalName: string | null = field.physicalName ?? null\n if (changes.name !== undefined && changes.name !== field.name) {\n name = assertEidosFileDisplayName(changes.name, \"Field name\")\n const fields = this.listFields(tableId)\n if (\n fields.some(\n (candidate) =>\n candidate.id !== field.id &&\n candidate.name.replace(/[A-Z]/g, (character) =>\n character.toLowerCase()\n ) ===\n name.replace(/[A-Z]/g, (character) => character.toLowerCase())\n )\n ) {\n throw new EidosFileError(\n \"constraint-conflict\",\n `Duplicate Field name: ${name}`\n )\n }\n if (field.physicalName) {\n physicalName = name\n if (physicalName !== field.physicalName) {\n this.connection.exec(\n `ALTER TABLE ${quoteIdentifier(table.physicalName ?? table.rawTableName)} RENAME COLUMN ${quoteIdentifier(field.physicalName)} TO ${quoteIdentifier(physicalName)}`\n )\n }\n }\n const formulaRows = this.connection.query<{\n field_id: string\n source_text: string\n }>(\n `SELECT formula.field_id, formula.source_text\n FROM ${EIDOS_FILE_FORMULA_FIELDS_TABLE} formula\n JOIN ${EIDOS_FILE_FIELDS_TABLE} owner ON owner.id = formula.field_id\n WHERE owner.table_id = ?`,\n [tableId]\n )\n for (const formula of formulaRows) {\n const expression = rewriteEidosFileFormulaFieldReferences(\n formula.source_text,\n field.name,\n name\n )\n if (expression !== formula.source_text) {\n this.connection.run(\n `UPDATE ${EIDOS_FILE_FORMULA_FIELDS_TABLE} SET source_text = ? WHERE field_id = ?`,\n [expression, formula.field_id]\n )\n }\n }\n }\n\n let settings = field.settings ?? {}\n if (changes.property !== undefined) {\n settings = presentationSettingsObject(changes.property)\n }\n if (changes.optionValueChanges && changes.optionValueChanges.length > 0) {\n if (field.type !== \"select\" && field.type !== \"multi-select\") {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Only Select Fields have option values\"\n )\n }\n const replacements = new Map(\n changes.optionValueChanges.map((change) => [change.from, change.to])\n )\n const options = assertedRawSelectOptions(settings)\n const existingNames = new Set(\n options.map((option) => option.name as string)\n )\n settings.options = options.flatMap((option) => {\n const replacement = replacements.get(option.name as string)\n if (replacement === undefined) return [option]\n if (existingNames.has(replacement)) return []\n return [{ ...option, name: replacement }]\n })\n if (\n field.type === \"select\" &&\n typeof settings.defaultOption === \"string\"\n ) {\n settings.defaultOption =\n replacements.get(settings.defaultOption) ?? settings.defaultOption\n }\n }\n if (field.type === \"select\" || field.type === \"multi-select\") {\n settings.options = assertedRawSelectOptions(settings)\n if (field.type === \"select\") {\n const defaultOption = assertEidosFileSelectDefaultOption(settings)\n if (defaultOption === null) delete settings.defaultOption\n else settings.defaultOption = defaultOption\n } else {\n assertEidosFileMultiSelectHasNoDefaultOption(settings)\n }\n }\n if (changes.optionValueChanges && changes.optionValueChanges.length > 0) {\n const replacements = new Map(\n changes.optionValueChanges.map((change) => [change.from, change.to])\n )\n for (const [from, to] of replacements) {\n if (field.type === \"select\") {\n this.connection.run(\n `UPDATE ${quoteIdentifier(table.physicalName ?? table.rawTableName)}\n SET ${quoteIdentifier(field.physicalName!)} = ?, \"_updated_at\" = ?\n WHERE ${quoteIdentifier(field.physicalName!)} = ?`,\n [to, this.operationInstant(), from]\n )\n } else {\n this.connection.run(\n `UPDATE ${quoteIdentifier(table.physicalName ?? table.rawTableName)}\n SET ${quoteIdentifier(field.physicalName!)} = (\n SELECT json_group_array(value) FROM (\n SELECT value FROM (\n SELECT CASE WHEN value = ? THEN ? ELSE value END AS value,\n CAST(key AS INTEGER) AS position\n FROM json_each(${quoteIdentifier(field.physicalName!)})\n ) GROUP BY value ORDER BY min(position)\n )\n ), \"_updated_at\" = ?\n WHERE EXISTS (\n SELECT 1 FROM json_each(${quoteIdentifier(field.physicalName!)}) WHERE value = ?\n )`,\n [from, to, this.operationInstant(), from]\n )\n }\n }\n for (const view of this.connection.query<ViewRow>(\n `SELECT * FROM ${EIDOS_FILE_VIEWS_TABLE}`\n )) {\n const query = transformOptionValue(\n parseEidosFileJson(view.query_json),\n fieldId,\n replacements\n )\n const layout = transformOptionValue(\n parseEidosFileJson(view.layout_json),\n fieldId,\n replacements\n )\n this.connection.run(\n `UPDATE ${EIDOS_FILE_VIEWS_TABLE} SET query_json = ?, layout_json = ?, updated_at = ? WHERE id = ?`,\n [\n canonicalizeEidosFileJson(query),\n canonicalizeEidosFileJson(layout),\n this.operationInstant(),\n view.id,\n ]\n )\n }\n }\n\n if (field.type === \"formula\" && changes.property) {\n const expression = changes.property.formula\n const resultType = changes.property.displayType\n if (typeof expression !== \"string\" || typeof resultType !== \"string\") {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Formula requires expression and result type\"\n )\n }\n const draft: EidosFileFieldInfo = {\n ...field,\n name,\n physicalName,\n property: {\n ...changes.property,\n formula: expression,\n displayType: resultType,\n },\n }\n compileEidosFileFormula(\n draft,\n this.listFields(tableId).map((candidate) =>\n candidate.id === fieldId ? draft : candidate\n )\n )\n this.connection.run(\n `UPDATE ${EIDOS_FILE_FORMULA_FIELDS_TABLE}\n SET source_text = ?, result_type = ? WHERE field_id = ?`,\n [expression, resultType, fieldId]\n )\n }\n\n if (field.type === \"lookup\" && changes.property) {\n const relationKey = changes.property.relationField\n const targetKey = changes.property.targetField\n const aggregate = changes.property.aggregate\n if (\n typeof relationKey !== \"string\" ||\n typeof targetKey !== \"string\" ||\n ![\n \"first\",\n \"values\",\n \"count\",\n \"sum\",\n \"average\",\n \"min\",\n \"max\",\n ].includes(String(aggregate))\n ) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Lookup requires Relation and target Field IDs\"\n )\n }\n const relationField = this.fieldByKey(tableId, relationKey)\n const relation = this.allSchema().relations.get(relationField.id!)\n if (!relation)\n throw new EidosFileError(\n \"invalid-schema\",\n \"Lookup requires a Relation Field\"\n )\n const targetField = this.fieldByKey(\n uuid(relation.target_table_id),\n targetKey\n )\n this.connection.run(\n `UPDATE ${EIDOS_FILE_LOOKUP_FIELDS_TABLE}\n SET relation_field_id = ?, target_field_id = ?, aggregate = ?, distinct_values = ?\n WHERE field_id = ?`,\n [\n relationField.id!,\n targetField.id!,\n String(aggregate),\n changes.property.distinct === true ? 1 : 0,\n fieldId,\n ]\n )\n }\n\n if (field.type === \"relation\" && changes.property) {\n const current = this.allSchema().relations.get(fieldId)\n if (!current)\n throw new EidosFileError(\n \"invalid-schema\",\n \"Relation subtype is missing\"\n )\n const direction = changes.property.direction ?? current.direction\n if (direction !== current.direction) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Changing Relation direction in place is not supported; create the inverse Field explicitly\"\n )\n }\n const targetTableId =\n changes.property.targetTableId ?? uuid(current.target_table_id)\n const sourceFieldId =\n changes.property.sourceFieldId ??\n (current.inverse_of_field_id\n ? uuid(current.inverse_of_field_id)\n : null)\n const cardinality =\n direction === \"inverse\"\n ? \"many\"\n : (changes.property.cardinality ?? current.cardinality)\n const onDelete =\n direction === \"forward\"\n ? (changes.property.onDelete ?? current.on_delete ?? \"restrict\")\n : null\n if (\n (direction !== \"forward\" && direction !== \"inverse\") ||\n typeof targetTableId !== \"string\" ||\n (cardinality !== \"one\" && cardinality !== \"many\") ||\n (onDelete !== null &&\n ![\"restrict\", \"detach\", \"preserve\"].includes(String(onDelete)))\n ) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Invalid Relation definition\"\n )\n }\n this.dropRelationTriggers(fieldId)\n this.connection.run(\n `UPDATE ${EIDOS_FILE_RELATION_FIELDS_TABLE}\n SET direction = ?, inverse_of_field_id = ?, target_table_id = ?, cardinality = ?, on_delete = ?\n WHERE field_id = ?`,\n [\n direction,\n sourceFieldId\n ? assertEidosFileUuid(String(sourceFieldId), \"Source Field ID\")\n : null,\n assertEidosFileUuid(String(targetTableId), \"Target Table ID\"),\n cardinality,\n onDelete === null ? null : String(onDelete),\n fieldId,\n ]\n )\n this.installRelationTriggers(fieldId)\n }\n\n const now = this.operationInstant()\n this.connection.run(\n `UPDATE ${EIDOS_FILE_FIELDS_TABLE}\n SET name = ?, physical_name = ?, settings_json = ?, updated_at = ?\n WHERE id = ?`,\n [name, physicalName, canonicalizeEidosFileJson(settings), now, fieldId]\n )\n if (changes.isRecordLabel === true) {\n if (field.type === \"lookup\") {\n throw new EidosFileError(\n \"invalid-schema\",\n \"A Lookup cannot be the Record Label Field in Eidos File 1.0\"\n )\n }\n this.connection.run(\n `UPDATE ${EIDOS_FILE_TABLES_TABLE}\n SET label_field_id = ?, updated_at = ? WHERE id = ?`,\n [fieldId, now, tableId]\n )\n }\n return this.fieldByKey(tableId, fieldId)\n })\n }\n\n setFieldNullable(fieldId: string, nullable: boolean): EidosFileFieldInfo {\n const field = Array.from(this.allSchema().fields.values()).find(\n (candidate) => candidate.id === fieldId\n )\n if (!field) {\n throw new EidosFileError(\n \"field-not-found\",\n \"Eidos File Field not found: \" + fieldId\n )\n }\n if (\n field.systemRole ||\n !field.physicalName ||\n [\"file\", \"multi-select\", \"relation\", \"formula\", \"lookup\"].includes(\n field.type\n )\n ) {\n throw new EidosFileError(\n \"protected-field\",\n \"Only stored scalar and JSON Fields have configurable nullability\"\n )\n }\n if ((field.nullable ?? true) === nullable) return field\n return this.mutateSchemaState(() => {\n const table = this.getTable(field.tableId)\n if (!nullable) {\n const nulls =\n this.connection.get<{ count: number | bigint }>(\n \"SELECT count(*) AS count FROM \" +\n quoteIdentifier(table.physicalName ?? table.rawTableName) +\n \" WHERE \" +\n quoteIdentifier(field.physicalName!) +\n \" IS NULL\"\n )?.count ?? 0\n if (BigInt(nulls) > 0n) {\n throw new EidosFileError(\n \"constraint-conflict\",\n \"Existing SQL NULL values block non-nullability\"\n )\n }\n }\n this.connection.run(\n \"UPDATE \" + EIDOS_FILE_FIELDS_TABLE + \" SET nullable=? WHERE id=?\",\n [nullable ? 1 : 0, fieldId]\n )\n this.rebuildUserTable(field.tableId)\n return this.fieldByKey(field.tableId, fieldId)\n })\n }\n\n /** @internal Applies a preflighted Runtime 1.0 stored-type conversion. */\n convertStoredFieldMetadataOnly(\n fieldId: string,\n targetType: \"text\" | \"select\" | \"url\",\n nullable: boolean\n ): EidosFileFieldInfo {\n const field = Array.from(this.allSchema().fields.values()).find(\n (candidate) => candidate.id === fieldId\n )\n if (\n !field ||\n !field.physicalName ||\n ![\"text\", \"select\", \"url\"].includes(field.type) ||\n (field.nullable ?? false) !== nullable\n ) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Metadata-only conversion requires an unchanged Text, Select, or URL storage shape\"\n )\n }\n return this.mutateSchemaState(() => {\n this.connection.run(\n `UPDATE ${EIDOS_FILE_FIELDS_TABLE} SET type = ? WHERE id = ?`,\n [targetType, fieldId]\n )\n this.connection.run(\n `UPDATE ${EIDOS_FILE_TABLES_TABLE} SET updated_at = ? WHERE id = ?`,\n [this.operationInstant(), field.tableId]\n )\n this.schemaCache = undefined\n return this.fieldByKey(field.tableId, fieldId)\n })\n }\n\n /** @internal Applies a preflighted Runtime 1.0 stored-type conversion. */\n convertStoredField(\n fieldId: string,\n targetType: EidosFileFieldType,\n nullable: boolean,\n rows: readonly {\n id: string\n value: EidosFileSqlPrimitive\n changed: boolean\n }[],\n relation?: {\n targetTableId: string\n cardinality: \"one\" | \"many\"\n onDelete: \"restrict\" | \"detach\" | \"preserve\"\n }\n ): EidosFileFieldInfo {\n const field = Array.from(this.allSchema().fields.values()).find(\n (candidate) => candidate.id === fieldId\n )\n if (\n !field ||\n field.systemRole ||\n !field.physicalName ||\n [\"formula\", \"lookup\"].includes(field.type) ||\n [\n \"formula\",\n \"lookup\",\n \"row-id\",\n \"created-time\",\n \"last-edited-time\",\n ].includes(targetType)\n ) {\n throw new EidosFileError(\n \"protected-field\",\n \"Stored-type conversion requires a writable stored Field\"\n )\n }\n if (targetType === \"relation\" && !relation) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Relation conversion requires a forward Relation definition\"\n )\n }\n const expectedRows = this.countRows(field.tableId)\n if (\n rows.length !== expectedRows ||\n new Set(rows.map((row) => row.id)).size !== rows.length\n ) {\n throw new EidosFileError(\n \"stale-revision\",\n \"Conversion rows no longer match the Table\"\n )\n }\n return this.mutateSchemaState(() => {\n const relationFieldIdsBefore = Array.from(\n this.allSchema().relations.keys()\n )\n for (const relationFieldId of relationFieldIdsBefore) {\n this.dropRelationTriggers(relationFieldId)\n }\n this.connection.run(\n `DELETE FROM ${EIDOS_FILE_RELATION_FIELDS_TABLE} WHERE field_id = ?`,\n [fieldId]\n )\n this.connection.run(\n `UPDATE ${EIDOS_FILE_FIELDS_TABLE}\n SET type = ?, nullable = ? WHERE id = ?`,\n [\n targetType,\n targetType === \"file\" ||\n targetType === \"multi-select\" ||\n targetType === \"relation\"\n ? 0\n : nullable\n ? 1\n : 0,\n fieldId,\n ]\n )\n if (targetType === \"relation\" && relation) {\n this.connection.run(\n `INSERT INTO ${EIDOS_FILE_RELATION_FIELDS_TABLE}\n (field_id, direction, target_table_id, cardinality, inverse_of_field_id, on_delete)\n VALUES (?, 'forward', ?, ?, NULL, ?)`,\n [\n fieldId,\n assertEidosFileUuid(relation.targetTableId, \"Target Table ID\"),\n relation.cardinality,\n relation.onDelete,\n ]\n )\n }\n this.schemaCache = undefined\n this.rebuildUserTable(\n field.tableId,\n {\n fieldId,\n rows: new Map(rows.map((row) => [row.id, row])),\n },\n relationFieldIdsBefore\n )\n this.connection.run(\n `UPDATE ${EIDOS_FILE_TABLES_TABLE} SET updated_at = ? WHERE id = ?`,\n [this.operationInstant(), field.tableId]\n )\n return this.fieldByKey(field.tableId, fieldId)\n })\n }\n\n private rebuildUserTable(\n tableId: string,\n transformed?: {\n fieldId: string\n rows: Map<\n string,\n { id: string; value: EidosFileSqlPrimitive; changed: boolean }\n >\n },\n relationFieldIdsBefore?: string[]\n ): void {\n this.schemaCache = undefined\n const table = this.getTable(tableId)\n const physicalName = table.physicalName ?? table.rawTableName\n const fields = this.listFields(tableId)\n const stored = fields.filter((field) => field.physicalName)\n const definitions = stored.map(\n (field) =>\n fieldColumnSql({\n id: field.id!,\n name: field.name,\n type: field.type,\n physicalName: field.physicalName!,\n settings: field.settings ?? {},\n isRecordLabel: field.isRecordLabel === true,\n systemRole: field.systemRole ?? null,\n nullable: field.nullable ?? false,\n })!\n )\n const temporary = this.transientTableName(\n \"eidos__rebuild_table__\" + tableId.replace(/-/g, \"\")\n )\n const staging = this.transientTableName(\n \"eidos__rebuild_old_table__\" + tableId.replace(/-/g, \"\")\n )\n const relationFieldIds = Array.from(\n new Set([\n ...(relationFieldIdsBefore ?? []),\n ...Array.from(this.allSchema().relations.keys()),\n ])\n )\n for (const relationFieldId of relationFieldIds) {\n this.dropRelationTriggers(relationFieldId)\n }\n const organization = this.connection.get<{ sql: string }>(\n \"SELECT sql FROM sqlite_schema WHERE type='table' AND name=?\",\n [physicalName]\n )?.sql\n const withoutRowid = /\\bWITHOUT\\s+ROWID\\b/i.test(organization ?? \"\")\n this.connection.exec(\n \"CREATE TABLE \" +\n quoteIdentifier(temporary) +\n \" (\" +\n definitions.join(\", \") +\n `) STRICT${withoutRowid ? \", WITHOUT ROWID\" : \"\"}`\n )\n const columns = stored.map((field) => quoteIdentifier(field.physicalName!))\n if (transformed) {\n const placeholders = columns.map(() => \"?\").join(\", \")\n const sql = `INSERT INTO ${quoteIdentifier(temporary)} (${columns.join(\", \")}) VALUES (${placeholders})`\n scanStableRowPages<Record<string, EidosFileSqlPrimitive>>(\n this.connection,\n {\n columnsSql: \"*\",\n tableSql: quoteIdentifier(physicalName),\n rowIdSql: `\"_id\"`,\n rowIdKey: \"_id\",\n },\n (sourceRows) => {\n const parameterSets = sourceRows.map((row) => {\n const rowId = String(row._id)\n const conversion = transformed.rows.get(rowId)\n if (!conversion) {\n throw new EidosFileError(\n \"stale-revision\",\n \"Conversion row set changed before apply\"\n )\n }\n return stored.map((storedField) => {\n if (storedField.id === transformed.fieldId)\n return conversion.value\n if (\n storedField.systemRole === \"updated-time\" &&\n conversion.changed\n ) {\n return this.operationInstant()\n }\n return row[storedField.physicalName!]\n })\n })\n if (this.connection.runMany)\n this.connection.runMany(sql, parameterSets)\n else\n for (const parameters of parameterSets)\n this.connection.run(sql, parameters)\n }\n )\n } else {\n this.connection.exec(\n \"INSERT INTO \" +\n quoteIdentifier(temporary) +\n \" (\" +\n columns.join(\", \") +\n \") SELECT \" +\n columns.join(\", \") +\n \" FROM \" +\n quoteIdentifier(physicalName)\n )\n }\n this.connection.exec(\n `DROP TRIGGER IF EXISTS ${quoteIdentifier(\n `eidos__row_id_immutable__${tableId.replace(/-/g, \"\")}`\n )}`\n )\n this.connection.exec(\n `ALTER TABLE ${quoteIdentifier(physicalName)} RENAME TO ${quoteIdentifier(staging)}`\n )\n this.connection.exec(\n \"ALTER TABLE \" +\n quoteIdentifier(temporary) +\n \" RENAME TO \" +\n quoteIdentifier(physicalName)\n )\n this.connection.exec(\"DROP TABLE \" + quoteIdentifier(staging))\n this.installRowIdTrigger(tableId, physicalName)\n for (const relationFieldId of relationFieldIds) {\n this.installRelationTriggers(relationFieldId)\n }\n this.schemaCache = undefined\n }\n\n private transientTableName(base: string): string {\n const names = new Set(\n this.connection\n .query<{ name: string }>(\"SELECT name FROM sqlite_schema\")\n .map((row) => row.name)\n )\n if (!names.has(base)) return base\n for (let suffix = 1; suffix < Number.MAX_SAFE_INTEGER; suffix += 1) {\n const candidate = `${base}__${suffix}`\n if (!names.has(candidate)) return candidate\n }\n throw new EidosFileError(\n \"resource-limit\",\n \"No collision-free rebuild Table name is available\"\n )\n }\n\n private removeFieldFromViewLayouts(tableId: string, fieldId: string): void {\n const views = this.connection.query<{\n id: string\n layout_json: string\n }>(\n `SELECT id, layout_json FROM ${EIDOS_FILE_VIEWS_TABLE} WHERE table_id = ?`,\n [tableId]\n )\n for (const view of views) {\n const layout = jsonObject(view.layout_json)\n for (const key of [\"cardFields\", \"fieldOrder\", \"hiddenFields\"] as const) {\n if (Array.isArray(layout[key])) {\n layout[key] = layout[key].filter((value) => value !== fieldId)\n }\n }\n for (const key of [\"coverField\", \"groupField\", \"dateField\"] as const) {\n if (layout[key] === fieldId) layout[key] = null\n }\n if (\n layout.fieldWidths &&\n typeof layout.fieldWidths === \"object\" &&\n !Array.isArray(layout.fieldWidths)\n ) {\n const fieldWidths = {\n ...(layout.fieldWidths as Record<string, unknown>),\n }\n delete fieldWidths[fieldId]\n layout.fieldWidths = fieldWidths\n }\n const next = canonicalizeEidosFileJson(layout)\n if (next === view.layout_json) continue\n this.connection.run(\n `UPDATE ${EIDOS_FILE_VIEWS_TABLE}\n SET layout_json = ?, updated_at = ? WHERE id = ?`,\n [next, this.operationInstant(), view.id]\n )\n }\n }\n\n deleteField(\n tableId: string,\n fieldKey: string,\n replacementRecordLabelFieldId?: string\n ): boolean {\n const table = this.getTable(tableId)\n const field = this.fieldByKey(tableId, fieldKey)\n if (!field.id) return false\n if (field.valueKind === \"system\") {\n throw new EidosFileError(\n \"protected-field\",\n \"System Fields cannot be deleted\"\n )\n }\n if (field.isRecordLabel && !replacementRecordLabelFieldId) {\n throw new EidosFileError(\n \"constraint-conflict\",\n \"Deleting the Record Label Field requires a replacement Field ID\"\n )\n }\n const replacement = replacementRecordLabelFieldId\n ? this.fieldByKey(tableId, replacementRecordLabelFieldId)\n : undefined\n if (replacement?.id === field.id) {\n throw new EidosFileError(\n \"constraint-conflict\",\n \"The replacement Record Label Field must be a different Field\"\n )\n }\n return this.mutateSchemaState(() => {\n if (table.contentFieldId === field.id) {\n const settings = jsonObject(this.tableRow(tableId).settings_json)\n delete settings.contentFieldId\n this.connection.run(\n `UPDATE ${EIDOS_FILE_TABLES_TABLE}\n SET settings_json = ?, updated_at = ? WHERE id = ?`,\n [\n canonicalizeEidosFileJson(settings),\n this.operationInstant(),\n tableId,\n ]\n )\n }\n if (field.isRecordLabel && replacement?.id) {\n this.connection.run(\n `UPDATE ${EIDOS_FILE_TABLES_TABLE}\n SET label_field_id = ?, updated_at = ? WHERE id = ?`,\n [replacement.id, this.operationInstant(), tableId]\n )\n }\n const dependentLookup = this.connection.get<{ field_id: string }>(\n `SELECT field_id FROM ${EIDOS_FILE_LOOKUP_FIELDS_TABLE}\n WHERE relation_field_id = ? OR target_field_id = ? LIMIT 1`,\n [field.id!, field.id!]\n )\n const dependentInverse = this.connection.get<{ field_id: string }>(\n `SELECT field_id FROM ${EIDOS_FILE_RELATION_FIELDS_TABLE}\n WHERE inverse_of_field_id = ? LIMIT 1`,\n [field.id!]\n )\n if (dependentLookup || dependentInverse) {\n throw new EidosFileError(\n \"constraint-conflict\",\n `Field ${field.name} has structural dependents`\n )\n }\n for (const formula of this.listFields(tableId).filter(\n (candidate) => candidate.type === \"formula\"\n )) {\n const compiled = compileEidosFileFormula(\n formula,\n this.listFields(tableId)\n )\n if (compiled.dependencyFieldIds.includes(field.id!)) {\n throw new EidosFileError(\n \"formula-in-use\",\n `Formula ${formula.name} depends on ${field.name}`\n )\n }\n }\n this.removeFieldFromViewLayouts(tableId, field.id!)\n if (field.type === \"relation\") this.dropRelationTriggers(field.id!)\n if (field.physicalName) {\n this.connection.exec(\n `ALTER TABLE ${quoteIdentifier(table.physicalName ?? table.rawTableName)} DROP COLUMN ${quoteIdentifier(field.physicalName)}`\n )\n }\n const result = this.connection.run(\n `DELETE FROM ${EIDOS_FILE_FIELDS_TABLE} WHERE id = ?`,\n [field.id!]\n )\n return result.changes > 0\n })\n }\n\n private viewRow(viewId: string): ViewRow {\n const row = this.connection.get<ViewRow>(\n `SELECT * FROM ${EIDOS_FILE_VIEWS_TABLE} WHERE id = ?`,\n [assertEidosFileUuid(viewId, \"View ID\")]\n )\n if (!row)\n throw new EidosFileError(\n \"view-not-found\",\n `Eidos File View not found: ${viewId}`\n )\n return row\n }\n\n private mapView(row: ViewRow): EidosFileViewInfo {\n const tableId = uuid(row.table_id)\n const fields = this.listFields(tableId)\n const query = jsonObject(row.query_json)\n const layout = jsonObject(row.layout_json)\n const queryStatus = storedViewQueryStatus(query, fields)\n const storedSorts = sortsFromStorage(query.sort)\n const fieldIds = new Set(\n fields.flatMap((field) => (field.id ? [field.id] : []))\n )\n const fieldOrder = Array.isArray(layout.fieldOrder)\n ? layout.fieldOrder.flatMap((value) =>\n typeof value === \"string\" && fieldIds.has(value) ? [value] : []\n )\n : []\n const properties = { ...layout }\n return {\n id: uuid(row.id),\n name: row.name,\n type: row.type,\n tableId,\n queryStatus,\n query: row.query_json,\n properties,\n filter:\n queryStatus === \"supported\"\n ? filterFromStorage(query.filter, fields)\n : null,\n sorts:\n queryStatus === \"supported\"\n ? storedSorts.filter((sort) => fieldIds.has(sort.field))\n : [],\n orderMap: Object.fromEntries(\n fieldOrder.map((fieldId, index) => [fieldId, index])\n ),\n hiddenFields: Array.isArray(layout.hiddenFields)\n ? layout.hiddenFields.flatMap((value) =>\n typeof value === \"string\" && fieldIds.has(value) ? [value] : []\n )\n : [],\n position: row.position,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n }\n }\n\n listViews(tableId: string): EidosFileViewInfo[] {\n this.tableRow(tableId)\n return this.connection\n .query<ViewRow>(\n `SELECT * FROM ${EIDOS_FILE_VIEWS_TABLE}\n WHERE table_id = ? ORDER BY position, id`,\n [tableId]\n )\n .map((row) => this.mapView(row))\n }\n\n createView(\n tableId: string,\n input: CreateEidosFileViewInput\n ): EidosFileViewInfo {\n const fields = this.listFields(tableId)\n const name = assertEidosFileDisplayName(input.name, \"View name\")\n const foldedName = name.replace(/[A-Z]/g, (character) =>\n character.toLowerCase()\n )\n if (\n this.listViews(tableId).some(\n (view) =>\n view.name.replace(/[A-Z]/g, (character) =>\n character.toLowerCase()\n ) === foldedName\n )\n ) {\n throw new EidosFileError(\n \"constraint-conflict\",\n `Duplicate View name: ${name}`\n )\n }\n const id = input.id ?? this.allocateId()\n const now = this.operationInstant()\n const fieldByKey = new Map<string, string>()\n for (const field of fields) {\n if (!field.id) continue\n fieldByKey.set(field.id, field.id)\n fieldByKey.set(field.tableColumnName, field.id)\n }\n const sorts = normalizeEidosFileSorts(input.sorts).flatMap((sort) => {\n const field = fieldByKey.get(sort.field)\n return field ? [{ ...sort, field }] : []\n })\n const properties = input.properties ?? {}\n const mapFieldList = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.flatMap((key) => {\n const fieldId =\n typeof key === \"string\" ? fieldByKey.get(key) : undefined\n return fieldId ? [fieldId] : []\n })\n : []\n const hiddenFields = (\n input.hiddenFields ?? mapFieldList(properties.hiddenFields)\n ).flatMap((key) => {\n const id = fieldByKey.get(key)\n return id ? [id] : []\n })\n const orderSource = input.orderMap\n ? Object.entries(input.orderMap)\n .sort((left, right) => left[1] - right[1])\n .map(([key]) => key)\n : Array.isArray(properties.fieldOrder)\n ? properties.fieldOrder.flatMap((key) =>\n typeof key === \"string\" ? [key] : []\n )\n : systemFieldsLast(fields).flatMap((field) =>\n field.id ? [field.id] : []\n )\n const fieldOrder = orderSource.flatMap((key) => {\n const id = fieldByKey.get(key)\n return id ? [id] : []\n })\n const fieldWidths =\n properties.fieldWidths &&\n typeof properties.fieldWidths === \"object\" &&\n !Array.isArray(properties.fieldWidths)\n ? Object.fromEntries(\n Object.entries(properties.fieldWidths).flatMap(([key, value]) => {\n const fieldId = fieldByKey.get(key)\n return fieldId &&\n typeof value === \"number\" &&\n Number.isFinite(value)\n ? [[fieldId, value]]\n : []\n })\n )\n : {}\n const mappedLayoutField = (value: unknown): string | null =>\n typeof value === \"string\" ? (fieldByKey.get(value) ?? null) : null\n return this.mutate(() => {\n this.connection.run(\n `INSERT INTO ${EIDOS_FILE_VIEWS_TABLE}\n (id, table_id, name, type, query_json, layout_json, position, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n [\n assertEidosFileUuid(id, \"View ID\"),\n assertEidosFileUuid(tableId, \"Table ID\"),\n name,\n input.type,\n canonicalizeEidosFileJson({\n ...(filterToStorage(input.filter, fields)\n ? { filter: filterToStorage(input.filter, fields) }\n : {}),\n ...(sorts.length > 0 ? { sort: sortsToStorage(sorts) } : {}),\n }),\n canonicalizeEidosFileJson({\n ...properties,\n cardFields: mapFieldList(properties.cardFields),\n coverField: mappedLayoutField(properties.coverField),\n dateField: mappedLayoutField(properties.dateField),\n fieldOrder,\n fieldWidths,\n groupField: mappedLayoutField(properties.groupField),\n hiddenFields,\n }),\n stablePosition(input.position, this.listViews(tableId).length),\n now,\n now,\n ]\n )\n const view = this.mapView(this.viewRow(id))\n this.optimizeViewQueries()\n return view\n })\n }\n\n updateView(\n viewId: string,\n changes: UpdateEidosFileViewInput\n ): EidosFileViewInfo {\n const currentRow = this.viewRow(viewId)\n const current = this.mapView(currentRow)\n const fields = this.listFields(current.tableId)\n const name = assertEidosFileDisplayName(\n changes.name ?? current.name,\n \"View name\"\n )\n const foldedName = name.replace(/[A-Z]/g, (character) =>\n character.toLowerCase()\n )\n if (\n this.listViews(current.tableId).some(\n (view) =>\n view.id !== viewId &&\n view.name.replace(/[A-Z]/g, (character) =>\n character.toLowerCase()\n ) === foldedName\n )\n ) {\n throw new EidosFileError(\n \"constraint-conflict\",\n `Duplicate View name: ${name}`\n )\n }\n const next: CreateEidosFileViewInput = {\n name,\n type: changes.type ?? current.type,\n position: changes.position ?? current.position,\n properties:\n changes.properties === undefined\n ? current.properties\n : changes.properties,\n filter: changes.filter === undefined ? current.filter : changes.filter,\n sorts: changes.sorts === undefined ? current.sorts : changes.sorts,\n orderMap:\n changes.orderMap === undefined ? current.orderMap : changes.orderMap,\n hiddenFields:\n changes.hiddenFields === undefined\n ? current.hiddenFields\n : changes.hiddenFields,\n }\n const queryChanged =\n changes.filter !== undefined || changes.sorts !== undefined\n const layoutChanged =\n changes.properties !== undefined ||\n changes.orderMap !== undefined ||\n changes.hiddenFields !== undefined\n return this.mutate(() => {\n const fieldByKey = new Map(\n fields.flatMap((field) =>\n field.id\n ? [\n [field.tableColumnName, field.id],\n [field.id, field.id],\n ]\n : []\n )\n )\n const sorts = normalizeEidosFileSorts(next.sorts).flatMap((sort) => {\n const id = fieldByKey.get(sort.field)\n return id ? [{ ...sort, field: id }] : []\n })\n const hiddenFields = (next.hiddenFields ?? []).flatMap((key) => {\n const id = fieldByKey.get(key)\n return id ? [id] : []\n })\n const fieldOrder = next.orderMap\n ? Object.entries(next.orderMap)\n .sort((left, right) => left[1] - right[1])\n .flatMap(([key]) => {\n const id = fieldByKey.get(key)\n return id ? [id] : []\n })\n : systemFieldsLast(fields).flatMap((field) =>\n field.id ? [field.id] : []\n )\n const layout = {\n ...(next.properties ?? {}),\n fieldOrder,\n hiddenFields,\n }\n this.connection.run(\n `UPDATE ${EIDOS_FILE_VIEWS_TABLE}\n SET name = ?, type = ?, query_json = ?, layout_json = ?, position = ?, updated_at = ?\n WHERE id = ?`,\n [\n next.name,\n next.type,\n queryChanged\n ? canonicalizeEidosFileJson({\n ...(filterToStorage(next.filter, fields)\n ? { filter: filterToStorage(next.filter, fields) }\n : {}),\n ...(sorts.length ? { sort: sortsToStorage(sorts) } : {}),\n })\n : currentRow.query_json,\n layoutChanged\n ? canonicalizeEidosFileJson(layout)\n : currentRow.layout_json,\n stablePosition(next.position, current.position ?? 0),\n this.operationInstant(),\n viewId,\n ]\n )\n const view = this.mapView(this.viewRow(viewId))\n this.optimizeViewQueries()\n return view\n })\n }\n\n duplicateView(viewId: string, name?: string): EidosFileViewInfo {\n const view = this.mapView(this.viewRow(viewId))\n if (view.queryStatus === \"unsupported\") {\n throw new EidosFileError(\n \"unsupported-feature\",\n \"This View uses a saved query from a newer Eidos version\"\n )\n }\n return this.createView(view.tableId, {\n name: name ?? `${view.name} copy`,\n type: view.type,\n properties: view.properties,\n filter: view.filter,\n sorts: view.sorts,\n orderMap: view.orderMap,\n hiddenFields: view.hiddenFields,\n })\n }\n\n deleteView(viewId: string): boolean {\n const view = this.mapView(this.viewRow(viewId))\n if (this.listViews(view.tableId).length <= 1) {\n throw new EidosFileError(\n \"protected-view\",\n \"A Table must retain at least one View\"\n )\n }\n return this.mutate(\n () =>\n this.connection.run(\n `DELETE FROM ${EIDOS_FILE_VIEWS_TABLE} WHERE id = ?`,\n [viewId]\n ).changes > 0\n )\n }\n\n reorderViews(tableId: string, viewIds: string[]): EidosFileViewInfo[] {\n const current = this.listViews(tableId).map((view) => view.id)\n if (\n current.length !== viewIds.length ||\n current.some((id) => !viewIds.includes(id))\n ) {\n throw new EidosFileError(\n \"invalid-value\",\n \"View reorder must contain every View exactly once\"\n )\n }\n this.mutate(() => {\n viewIds.forEach((id, position) => {\n this.connection.run(\n `UPDATE ${EIDOS_FILE_VIEWS_TABLE} SET position = ?, updated_at = ? WHERE id = ?`,\n [position, this.operationInstant(), id]\n )\n })\n })\n return this.listViews(tableId)\n }\n\n private fieldExpression(\n field: EidosFileFieldInfo,\n rowAlias: string,\n schema: RuntimeSchema,\n stack: string[] = []\n ): string {\n if (!field.id) throw new EidosFileError(\"invalid-schema\", \"Field has no ID\")\n if (stack.includes(field.id)) {\n throw new EidosFileError(\n \"dependency-cycle\",\n `Dependency cycle: ${[...stack, field.id].join(\" → \")}`\n )\n }\n if (field.type === \"row-id\") return `${rowAlias}.\"_id\"`\n if (field.physicalName)\n return `${rowAlias}.${quoteIdentifier(field.physicalName)}`\n const nextStack = [...stack, field.id]\n const formula = schema.formulas.get(field.id)\n if (formula) {\n const ownerFields = schema.fieldsByTable.get(field.tableId!) ?? []\n const expression = compileEidosFileFormulaSource(\n formula.source_text,\n ownerFields,\n (dependency) =>\n this.fieldExpression(dependency, rowAlias, schema, nextStack),\n formula.result_type\n ).expression\n return canonicalTemporalProjection(expression, formula.result_type)\n }\n const relation = schema.relations.get(field.id)\n if (relation?.direction === \"inverse\" && relation.inverse_of_field_id) {\n const sourceField = schema.fields.get(uuid(relation.inverse_of_field_id))\n if (!sourceField?.physicalName)\n throw new EidosFileError(\n \"invalid-schema\",\n \"Inverse Relation source is invalid\"\n )\n const sourceTable = schema.tables.get(sourceField.tableId!)!\n return `coalesce((\n SELECT json_group_array(source_id) FROM (\n SELECT source.\"_id\" AS source_id\n FROM ${quoteIdentifier(sourceTable.physical_name)} source,\n json_each(source.${quoteIdentifier(sourceField.physicalName)}) item\n WHERE item.value = ${rowAlias}.\"_id\"\n ORDER BY source.\"_id\"\n )\n ), '[]')`\n }\n const lookup = schema.lookups.get(field.id)\n if (lookup)\n return this.lookupExpression(lookup, rowAlias, schema, nextStack)\n throw new EidosFileError(\n \"invalid-schema\",\n `No logical projection for Field ${field.name}`\n )\n }\n\n private lookupExpression(\n lookup: LookupRow,\n rowAlias: string,\n schema: RuntimeSchema,\n stack: string[]\n ): string {\n const relationField = schema.fields.get(uuid(lookup.relation_field_id))\n const targetField = schema.fields.get(uuid(lookup.target_field_id))\n if (!relationField || !targetField) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Lookup references a missing Field\"\n )\n }\n const relation = schema.relations.get(relationField.id!)\n if (!relation)\n throw new EidosFileError(\"invalid-schema\", \"Lookup relation is invalid\")\n const targetTableId = uuid(relation.target_table_id)\n const targetTable = schema.tables.get(targetTableId)\n if (!targetTable || targetField.tableId !== targetTableId) {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Lookup target does not belong to the Relation target Table\"\n )\n }\n const targetAlias = `lookup_${stack.length}`\n const relationExpression = this.fieldExpression(\n relationField,\n rowAlias,\n schema,\n stack\n )\n const targetExpression = this.fieldExpression(\n targetField,\n targetAlias,\n schema,\n stack\n )\n const targetIsList =\n targetField.type === \"relation\" ||\n targetField.type === \"multi-select\" ||\n targetField.type === \"file\" ||\n (targetField.type === \"lookup\" &&\n targetField.property?.aggregate === \"values\")\n const targetResultType = eidosFileLookupElementType(targetField)\n const base = `\n SELECT CAST(item.key AS INTEGER) AS relation_order,\n ${targetExpression} AS value,\n ${targetExpression} AS typed_value\n FROM json_each(${relationExpression}) item\n JOIN ${quoteIdentifier(targetTable.physical_name)} ${targetAlias}\n ON item.value = ${targetAlias}.\"_id\"\n `\n const flattened = targetIsList\n ? `SELECT relation_order, CAST(flat.key AS INTEGER) AS nested_order,\n flat.value AS value\n FROM (${base}) valueset,\n json_each(CASE WHEN json_valid(valueset.typed_value) THEN valueset.typed_value ELSE '[]' END) flat`\n : `SELECT relation_order, 0 AS nested_order, typed_value AS value FROM (${base})`\n const encoded =\n targetResultType === \"integer\"\n ? \"CASE WHEN value IS NULL THEN NULL ELSE CAST(value AS TEXT) END\"\n : targetResultType === \"file-entry\"\n ? \"CASE WHEN value IS NULL THEN NULL ELSE json(value) END\"\n : \"value\"\n const payload = `(SELECT coalesce(\n json_group_array(\n json_object('v', ${encoded})\n ORDER BY relation_order, nested_order\n ),\n '[]'\n ) FROM (${flattened}))`\n return `eidos_lookup_aggregate(\n ${payload},\n '${lookup.aggregate}',\n ${lookup.distinct_values === 1 ? 1 : 0},\n '${targetResultType}'\n )`\n }\n\n private relationDisplayExpression(\n field: EidosFileFieldInfo,\n rowAlias: string,\n schema: RuntimeSchema\n ): string {\n const relation = schema.relations.get(field.id!)\n if (!relation) return \"'[]'\"\n const targetTableId = uuid(relation.target_table_id)\n const targetTable = schema.tables.get(targetTableId)!\n const label = (schema.fieldsByTable.get(targetTableId) ?? []).find(\n (candidate) => candidate.isRecordLabel\n )\n if (!label) return \"'[]'\"\n const ids = this.fieldExpression(field, rowAlias, schema)\n const labelExpression = this.fieldExpression(\n label,\n \"relation_target\",\n schema\n )\n return `coalesce((\n SELECT json_group_array(json_object('id', id, 'title', label)) FROM (\n SELECT item.value AS id, ${labelExpression} AS label\n FROM json_each(${ids}) item\n JOIN ${quoteIdentifier(targetTable.physical_name)} relation_target\n ON item.value = relation_target.\"_id\"\n ORDER BY CAST(item.key AS INTEGER)\n )\n ), '[]')`\n }\n\n private rowIdSearchTargetTableId(\n field: EidosFileFieldInfo,\n schema: RuntimeSchema,\n visiting = new Set<string>()\n ): string | null {\n if (!field.id || visiting.has(field.id)) return null\n const nextVisiting = new Set(visiting)\n nextVisiting.add(field.id)\n if (field.type === \"row-id\") return field.tableId ?? null\n const relation = schema.relations.get(field.id)\n if (relation) return uuid(relation.target_table_id)\n const lookup = schema.lookups.get(field.id)\n if (!lookup) return null\n const target = schema.fields.get(uuid(lookup.target_field_id))\n return target\n ? this.rowIdSearchTargetTableId(target, schema, nextVisiting)\n : null\n }\n\n private recordLabelSearchExpression(\n field: EidosFileFieldInfo,\n rowAlias: string,\n schema: RuntimeSchema\n ): string {\n const expression = this.fieldExpression(field, rowAlias, schema)\n const type = eidosFileFieldValueType(field)\n if (typeof type !== \"string\") return \"NULL\"\n if (type === \"checkbox\") {\n return `CASE ${expression} WHEN 1 THEN 'true' WHEN 0 THEN 'false' ELSE NULL END`\n }\n if (type === \"number\") return `eidos_canonical_number(${expression})`\n return `CAST(${expression} AS TEXT)`\n }\n\n private rowIdSearchFragmentsExpression(\n field: EidosFileFieldInfo,\n rowAlias: string,\n schema: RuntimeSchema\n ): string | null {\n const targetTableId = this.rowIdSearchTargetTableId(field, schema)\n if (!targetTableId) return null\n const targetTable = schema.tables.get(targetTableId)\n const label = (schema.fieldsByTable.get(targetTableId) ?? []).find(\n (candidate) => candidate.isRecordLabel\n )\n if (!targetTable || !label) return null\n const ids = this.fieldExpression(field, rowAlias, schema)\n const labelSearch = this.recordLabelSearchExpression(\n label,\n \"search_target\",\n schema\n )\n return `coalesce((\n SELECT json_group_array(fragment) FROM (\n SELECT CASE\n WHEN search_target.\"_id\" IS NULL THEN CAST(item.value AS TEXT)\n ELSE ${labelSearch}\n END AS fragment\n FROM json_each(${ids}) item\n LEFT JOIN ${quoteIdentifier(targetTable.physical_name)} search_target\n ON item.value = search_target.\"_id\"\n ORDER BY CAST(item.key AS INTEGER)\n )\n ), '[]')`\n }\n\n private querySearchFragmentFieldIds(\n fields: EidosFileFieldInfo[],\n query: EidosFileRowQuery\n ): Set<string> {\n return new Set(\n eidosFileRowQuerySearchFields(fields, query).flatMap((field) => {\n const type = eidosFileFieldValueType(field)\n return field.id &&\n (type === \"relation\" ||\n (field.type === \"lookup\" &&\n typeof type === \"object\" &&\n type.element === \"row-id\"))\n ? [field.id]\n : []\n })\n )\n }\n\n private requiredQueryFieldKeys(\n fields: EidosFileFieldInfo[],\n query: EidosFileRowQuery\n ): Set<string> {\n const required = new Set<string>()\n const collectFilter = (\n group: EidosFileFilterGroup | null | undefined\n ): void => {\n if (!group) return\n for (const child of group.children) {\n if (child.type === \"group\") collectFilter(child)\n else required.add(child.field)\n }\n }\n collectFilter(query.filter)\n for (const sort of query.sorts ?? []) required.add(sort.field)\n for (const field of eidosFileRowQuerySearchFields(fields, query)) {\n if (field.id) required.add(field.id)\n }\n return required\n }\n\n private logicalSource(\n tableId: string,\n requestedKeys?: Iterable<string>,\n includeRecordLabel = true,\n includeRelationDisplays = true,\n searchFragmentFieldIds: ReadonlySet<string> = new Set()\n ): {\n sql: string\n fields: EidosFileFieldInfo[]\n schema: RuntimeSchema\n } {\n const schema = this.allSchema()\n const table = schema.tables.get(tableId)\n if (!table)\n throw new EidosFileError(\"table-not-found\", `Table not found: ${tableId}`)\n const fields = schema.fieldsByTable.get(tableId) ?? []\n const byKey = new Map<string, EidosFileFieldInfo>()\n for (const field of fields) {\n byKey.set(field.id!, field)\n byKey.set(field.tableColumnName, field)\n byKey.set(field.name, field)\n }\n const projected = requestedKeys\n ? new Set(\n [...requestedKeys].flatMap((key) => {\n const field = byKey.get(key)\n return field?.id ? [field.id] : []\n })\n )\n : new Set(fields.flatMap((field) => (field.id ? [field.id] : [])))\n const rowId = fields.find((field) => field.type === \"row-id\")\n const label = fields.find((field) => field.isRecordLabel)\n if (rowId?.id) projected.add(rowId.id)\n if (includeRecordLabel && label?.id) projected.add(label.id)\n const projections = fields\n .filter((field) => projected.has(field.id!))\n .flatMap((field) => {\n const expression = this.fieldExpression(field, \"base\", schema)\n const result = [\n `${expression} AS ${quoteIdentifier(field.tableColumnName)}`,\n ]\n if (includeRelationDisplays && field.type === \"relation\") {\n result.push(\n `${this.relationDisplayExpression(field, \"base\", schema)} AS ${quoteIdentifier(`${field.tableColumnName}__display`)}`\n )\n }\n if (searchFragmentFieldIds.has(field.id!)) {\n const fragments = this.rowIdSearchFragmentsExpression(\n field,\n \"base\",\n schema\n )\n if (fragments) {\n result.push(\n `${fragments} AS ${quoteIdentifier(`${field.tableColumnName}__search`)}`\n )\n }\n }\n return result\n })\n return {\n sql: `SELECT base.\"_id\" AS \"__base_rowid\", ${projections.join(\", \")}\n FROM ${quoteIdentifier(table.physical_name)} base`,\n fields,\n schema,\n }\n }\n\n private compatibilityQuery(\n tableId: string,\n query: EidosFileRowQuery\n ): EidosFileRowQuery {\n assertEidosFileRowQuery(query)\n const fields = this.listFields(tableId)\n const byKey = new Map<string, string>()\n for (const field of fields) {\n byKey.set(field.tableColumnName, field.tableColumnName)\n byKey.set(field.name, field.tableColumnName)\n if (field.id) byKey.set(field.id, field.tableColumnName)\n }\n const normalized = normalizeEidosFileRowQuery(query)\n const convertFilter = (\n group: EidosFileFilterGroup | null | undefined\n ): EidosFileFilterGroup | null => {\n if (!group) return null\n const children: EidosFileFilterGroup[\"children\"] = []\n for (const child of group.children) {\n if (child.type === \"group\") {\n const nested = convertFilter(child)\n if (nested) children.push(nested)\n } else {\n const field = byKey.get(child.field)\n if (field) children.push({ ...child, field })\n }\n }\n return { ...group, children }\n }\n return {\n ...normalized,\n filter: convertFilter(normalized.filter),\n sorts: normalized.sorts?.flatMap((sort) => {\n const field = byKey.get(sort.field)\n return field ? [{ ...sort, field }] : []\n }),\n }\n }\n\n listRows(\n tableId: string,\n options?: { offset?: number; limit?: number; query?: EidosFileRowQuery }\n ): EidosFileRow[]\n listRows(\n tableId: string,\n limit?: number,\n offset?: number,\n query?: EidosFileRowQuery\n ): EidosFileRow[]\n listRows(\n tableId: string,\n optionsOrLimit:\n | { offset?: number; limit?: number; query?: EidosFileRowQuery }\n | number = {},\n legacyOffset = 0,\n legacyQuery: EidosFileRowQuery = {}\n ): EidosFileRow[] {\n const options =\n typeof optionsOrLimit === \"number\"\n ? { limit: optionsOrLimit, offset: legacyOffset, query: legacyQuery }\n : optionsOrLimit\n return this.getRowPage(\n tableId,\n options.offset ?? 0,\n options.limit ?? 100,\n options.query ?? {}\n ).rows\n }\n\n getRowPage(\n tableId: string,\n offset: number,\n limit: number,\n query: EidosFileRowQuery = {},\n totalHint?: number,\n cursor?: string,\n projection?: EidosFileRowPageProjection\n ): EidosFileRowPage {\n if (\n !Number.isSafeInteger(offset) ||\n offset < 0 ||\n !Number.isSafeInteger(limit) ||\n limit < 1 ||\n limit > 10_000\n ) {\n throw new EidosFileError(\"query-limit\", \"Invalid Eidos File page bounds\")\n }\n const compatibleQuery = this.compatibilityQuery(tableId, query)\n const fields = this.listFields(tableId)\n const requested = projection\n ? new Set([\n ...projection.columns,\n ...(projection.preservedColumns ?? []),\n ...this.requiredQueryFieldKeys(fields, compatibleQuery),\n ])\n : undefined\n const source = this.logicalSource(\n tableId,\n requested,\n projection?.includeRecordLabel !== false,\n projection?.includeRelationDisplays !== false,\n this.querySearchFragmentFieldIds(fields, compatibleQuery)\n )\n const querySignature = canonicalizeEidosFileJson(compatibleQuery)\n const sorts = uniqueSortFields(source.fields, compatibleQuery.sorts)\n const revision = String(this.info().revision ?? 0)\n let effectiveOffset = offset\n let cursorWhere = \"\"\n let cursorParams: EidosFileSqlPrimitive[] = []\n let referenceInstant = this.nowInstant()\n if (cursor) {\n try {\n const payload = JSON.parse(decodeURIComponent(cursor)) as {\n version: number\n revision: string\n tableId: string\n query: string\n offset: number\n values: unknown[]\n lastId: string\n direction: \"forward\"\n referenceInstant?: string\n }\n if (\n payload.version !== 1 ||\n payload.direction !== \"forward\" ||\n payload.revision !== revision ||\n payload.tableId !== tableId ||\n payload.query !== querySignature ||\n !Array.isArray(payload.values)\n ) {\n throw new Error(\"cursor binding mismatch\")\n }\n effectiveOffset = payload.offset\n if (payload.referenceInstant !== undefined) {\n referenceInstant = normalizeEidosFileInstant(\n payload.referenceInstant,\n \"Cursor reference instant\"\n )\n }\n const keyset = compileKeysetAfter(\n sorts,\n payload.values.map(decodeCursorSqlValue),\n payload.lastId\n )\n cursorWhere = keyset.sql\n cursorParams = keyset.params\n } catch {\n throw new EidosFileError(\n \"invalid-query\",\n \"Invalid or stale Eidos File cursor\"\n )\n }\n }\n const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, {\n referenceInstant,\n })\n const whereSql = cursorWhere\n ? compiled.whereSql\n ? `${compiled.whereSql} AND ${cursorWhere}`\n : `WHERE ${cursorWhere}`\n : compiled.whereSql\n const rawRows = this.connection.query<\n Record<string, EidosFileSqlPrimitive>\n >(\n `WITH logical AS (${source.sql})\n SELECT * FROM logical ${whereSql} ${compiled.orderSql}\n LIMIT ?${cursor ? \"\" : \" OFFSET ?\"}`,\n cursor\n ? [...compiled.params, ...cursorParams, limit]\n : [...compiled.params, limit, effectiveOffset]\n )\n const rows = rawRows.map((row) => {\n const mapped: EidosFileRow = {}\n for (const [key, value] of Object.entries(row)) {\n if (key !== \"__base_rowid\") mapped[key] = rowValue(value)\n }\n if (!projection) return mapped\n const preserved = new Set([\"_id\", ...(projection.preservedColumns ?? [])])\n const candidates = projection.columns\n const selected = new Set<string>(preserved)\n let count = 0\n for (const key of candidates) {\n const value = mapped[key]\n if (\n projection.omitEmptyFields &&\n (value === null ||\n value === undefined ||\n value === \"\" ||\n value === \"[]\")\n )\n continue\n if (\n projection.fieldLimit !== undefined &&\n count >= projection.fieldLimit\n )\n break\n selected.add(key)\n if (`${key}__display` in mapped) selected.add(`${key}__display`)\n count += 1\n }\n return Object.fromEntries(\n Object.entries(mapped).filter(([key]) => selected.has(key))\n )\n })\n const total = totalHint ?? this.countRows(tableId, query, referenceInstant)\n const nextOffset = effectiveOffset + rawRows.length\n const lastRawRow = rawRows.at(-1)\n const nextCursor =\n lastRawRow && rawRows.length === limit && nextOffset < total\n ? encodeURIComponent(\n JSON.stringify({\n version: 1,\n revision,\n tableId,\n query: querySignature,\n offset: nextOffset,\n values: sorts.map(({ field }) =>\n encodeCursorSqlValue(cursorSortValue(lastRawRow, field))\n ),\n lastId: String(lastRawRow.__base_rowid),\n direction: \"forward\",\n referenceInstant,\n })\n )\n : undefined\n return {\n tableId,\n offset: effectiveOffset,\n limit,\n total,\n rows,\n ...(nextCursor ? { nextCursor } : {}),\n }\n }\n\n /** Returns the zero-based position of a Row ID in a filtered/sorted query. */\n getRowIndex(\n tableId: string,\n rowId: string,\n query: EidosFileRowQuery = {}\n ): number | null {\n const id = assertEidosFileUuid(rowId, \"Row ID\")\n const compatibleQuery = this.compatibilityQuery(tableId, query)\n const fields = this.listFields(tableId)\n const source = this.logicalSource(\n tableId,\n this.requiredQueryFieldKeys(fields, compatibleQuery),\n false,\n false,\n this.querySearchFragmentFieldIds(fields, compatibleQuery)\n )\n const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, {\n referenceInstant: this.nowInstant(),\n })\n const sorts = uniqueSortFields(source.fields, compatibleQuery.sorts)\n const targetWhere = compiled.whereSql\n ? `${compiled.whereSql} AND \"__base_rowid\" = ?`\n : 'WHERE \"__base_rowid\" = ?'\n const target = this.connection.get<Record<string, EidosFileSqlPrimitive>>(\n `WITH logical AS (${source.sql})\n SELECT * FROM logical ${targetWhere} LIMIT 1`,\n [...compiled.params, id]\n )\n if (!target) return null\n\n const before = compileKeysetBefore(\n sorts,\n sorts.map(({ field }) => cursorSortValue(target, field)),\n id\n )\n const beforeWhere = compiled.whereSql\n ? `${compiled.whereSql} AND ${before.sql}`\n : `WHERE ${before.sql}`\n const result = this.connection.get<{ count: number | bigint }>(\n `WITH logical AS (${source.sql})\n SELECT COUNT(*) AS count FROM logical ${beforeWhere}`,\n [...compiled.params, ...before.params]\n )\n return Number(result?.count ?? 0)\n }\n\n getRecordNeighbors(\n tableId: string,\n rowId: string,\n query: EidosFileRowQuery = {}\n ): RecordNeighbors {\n const id = assertEidosFileUuid(rowId, \"Row ID\")\n const compatibleQuery = this.compatibilityQuery(tableId, query)\n const fields = this.listFields(tableId)\n const source = this.logicalSource(\n tableId,\n this.requiredQueryFieldKeys(fields, compatibleQuery),\n false,\n false,\n this.querySearchFragmentFieldIds(fields, compatibleQuery)\n )\n const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, {\n referenceInstant: this.nowInstant(),\n })\n const targetWhere = compiled.whereSql\n ? `${compiled.whereSql} AND \"__base_rowid\" = ?`\n : 'WHERE \"__base_rowid\" = ?'\n const target = this.connection.get<Record<string, EidosFileSqlPrimitive>>(\n `WITH logical AS (${source.sql}) SELECT * FROM logical ${targetWhere} LIMIT 1`,\n [...compiled.params, id]\n )\n if (!target) return { found: false }\n const sorts = uniqueSortFields(source.fields, compatibleQuery.sorts)\n const values = sorts.map(({ field }) => cursorSortValue(target, field))\n const reverseOrder = [\n ...sorts.map(\n ({ field, sort }) =>\n `${eidosFileSortExpression(field)} ${sort.direction === \"desc\" ? \"ASC\" : \"DESC\"} NULLS ${sort.nulls === \"first\" ? \"LAST\" : \"FIRST\"}`\n ),\n '\"__base_rowid\" DESC',\n ].join(\", \")\n const neighbor = (previous: boolean): string | null => {\n const boundary = (previous ? compileKeysetBefore : compileKeysetAfter)(\n sorts,\n values,\n id\n )\n const where = compiled.whereSql\n ? `${compiled.whereSql} AND ${boundary.sql}`\n : `WHERE ${boundary.sql}`\n const row = this.connection.get<{ id: string }>(\n `WITH logical AS (${source.sql}) SELECT \"__base_rowid\" AS id FROM logical ${where} ${previous ? `ORDER BY ${reverseOrder}` : compiled.orderSql} LIMIT 1`,\n [...compiled.params, ...boundary.params]\n )\n return row?.id ?? null\n }\n return { found: true, previousId: neighbor(true), nextId: neighbor(false) }\n }\n\n getRow(tableId: string, rowId: string): EidosFileRow | null {\n const source = this.logicalSource(tableId)\n const row = this.connection.get<Record<string, EidosFileSqlPrimitive>>(\n `WITH logical AS (${source.sql}) SELECT * FROM logical WHERE \"__base_rowid\" = ?`,\n [assertEidosFileUuid(rowId, \"Row ID\")]\n )\n if (!row) return null\n return Object.fromEntries(\n Object.entries(row).flatMap(([key, value]) =>\n key === \"__base_rowid\" ? [] : [[key, rowValue(value)]]\n )\n )\n }\n\n queryRows(\n tableId: string,\n options: {\n fields?: string[]\n query?: EidosFileRowQuery\n limit?: number\n offset?: number\n cursor?: string\n resolveRelations?: boolean\n } = {}\n ): { rows: EidosFileLogicalRow[]; nextCursor?: string } {\n const fields = this.listFields(tableId)\n const requested = options.fields\n ? options.fields.map((id) => this.fieldByKey(tableId, id))\n : fields\n const rowIdField = fields.find((field) => field.type === \"row-id\")!\n const page = this.getRowPage(\n tableId,\n options.offset ?? 0,\n options.limit ?? 100,\n options.query ?? {},\n undefined,\n options.cursor,\n {\n columns: requested.map((field) => field.tableColumnName),\n preservedColumns: [rowIdField.tableColumnName],\n fieldLimit: requested.length,\n includeRecordLabel: false,\n includeRelationDisplays: options.resolveRelations === true,\n }\n )\n const rows = this.logicalRows(\n rowIdField,\n requested,\n page.rows,\n options.resolveRelations === true\n )\n return { rows, ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}) }\n }\n\n /** @internal Exact primary-key lookup without page totals or cursor work. */\n getLogicalRowsByIds(\n tableId: string,\n rowIds: string[],\n options: { fields?: string[]; resolveRelations?: boolean } = {}\n ): EidosFileLogicalRow[] {\n if (rowIds.length === 0) return []\n if (rowIds.length > 500) {\n throw new EidosFileError(\n \"resource-limit\",\n \"getLogicalRowsByIds accepts at most 500 Row IDs\"\n )\n }\n const ids = rowIds.map((rowId) => assertEidosFileUuid(rowId, \"Row ID\"))\n const fields = this.listFields(tableId)\n const requested = options.fields\n ? options.fields.map((id) => this.fieldByKey(tableId, id))\n : fields\n const rowIdField = fields.find((field) => field.type === \"row-id\")!\n const source = this.logicalSource(\n tableId,\n requested.map((field) => field.id!),\n false,\n options.resolveRelations === true\n )\n const rawRows = this.connection.query<\n Record<string, EidosFileSqlPrimitive>\n >(\n `WITH logical AS (${source.sql})\n SELECT * FROM logical\n WHERE \"__base_rowid\" IN (${ids.map(() => \"?\").join(\", \")})`,\n ids\n )\n const logicalRows = this.logicalRows(\n rowIdField,\n requested,\n rawRows.map((row) =>\n Object.fromEntries(\n Object.entries(row).flatMap(([key, value]) =>\n key === \"__base_rowid\" ? [] : [[key, rowValue(value)]]\n )\n )\n ),\n options.resolveRelations === true\n )\n const byId = new Map(logicalRows.map((row) => [row.id, row]))\n return ids.flatMap((rowId) => {\n const row = byId.get(rowId)\n return row ? [row] : []\n })\n }\n\n private logicalRows(\n rowIdField: EidosFileFieldInfo,\n requested: EidosFileFieldInfo[],\n rows: EidosFileRow[],\n resolveRelations: boolean\n ): EidosFileLogicalRow[] {\n return rows.map((row) => {\n const logicalFields = Object.fromEntries(\n requested.map((field) => {\n const raw = row[field.tableColumnName]\n let value: EidosFileLogicalValue = raw ?? null\n const resultType =\n field.type === \"formula\" || field.type === \"lookup\"\n ? String(field.property?.displayType ?? field.type)\n : field.type\n if (\n typeof raw === \"string\" &&\n (field.type === \"file\" ||\n field.type === \"multi-select\" ||\n field.type === \"relation\" ||\n (field.type === \"lookup\" &&\n field.property?.aggregate === \"values\"))\n ) {\n if (field.type === \"file\") {\n try {\n value = decodeEidosFileValues(raw)\n } catch {\n throw new EidosFileError(\n \"invalid-sqlite\",\n `${field.name} contains an invalid stored File value`\n )\n }\n } else {\n value = parseEidosFileJson(raw)\n }\n } else if (resultType === \"checkbox\" && typeof raw === \"number\") {\n value = raw === 1\n }\n return [field.id!, value]\n })\n )\n const resolved = resolveRelations\n ? Object.fromEntries(\n requested.flatMap((field) => {\n if (field.type !== \"relation\") return []\n const display = row[`${field.tableColumnName}__display`]\n if (typeof display !== \"string\") return [[field.id!, []]]\n const parsed = parseEidosFileJson(display)\n if (!Array.isArray(parsed)) return [[field.id!, []]]\n return [\n [\n field.id!,\n parsed.flatMap((entry) =>\n entry &&\n !Array.isArray(entry) &&\n typeof entry === \"object\" &&\n typeof entry.id === \"string\"\n ? [{ id: entry.id, label: entry.title ?? null }]\n : []\n ),\n ],\n ]\n })\n )\n : undefined\n return {\n id: String(row[rowIdField.tableColumnName]),\n fields: logicalFields,\n ...(resolved && Object.keys(resolved).length > 0 ? { resolved } : {}),\n }\n })\n }\n\n /**\n * @internal Exact Runtime aggregate/group scan. One set-based SQL statement\n * returns typed logical inputs in effective query order; the public Runtime\n * remains responsible for aggregate arithmetic and response bounds.\n */\n runtimeScanLogicalRows(\n tableId: string,\n fieldIds: string[],\n query: EidosFileRowQuery\n ): EidosFileLogicalRow[] {\n const compatibleQuery = this.compatibilityQuery(tableId, query)\n const fields = this.listFields(tableId)\n const source = this.logicalSource(\n tableId,\n [...fieldIds, ...this.requiredQueryFieldKeys(fields, compatibleQuery)],\n false,\n false,\n this.querySearchFragmentFieldIds(fields, compatibleQuery)\n )\n const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, {\n referenceInstant: this.nowInstant(),\n })\n const selectedFields = fieldIds.map((fieldId) =>\n this.fieldByKey(tableId, fieldId)\n )\n const encodedValues = selectedFields.map((field) => {\n const column = quoteIdentifier(field.tableColumnName)\n return `json_object(\n 'storage', typeof(${column}),\n 'value', CASE WHEN typeof(${column})='integer'\n THEN CAST(${column} AS TEXT) ELSE ${column} END\n )`\n })\n const payload = this.connection.get<{ payload: string }>(\n `WITH logical AS (${source.sql}), ordered AS (\n SELECT * FROM logical ${compiled.whereSql} ${compiled.orderSql}\n LIMIT -1\n )\n SELECT coalesce(\n json_group_array(\n json_object(\n 'id', \"__base_rowid\",\n 'values', json_array(${encodedValues.join(\", \")})\n )\n ),\n '[]'\n ) AS payload\n FROM ordered`,\n compiled.params\n )?.payload\n const parsed = parseEidosFileJson(payload ?? \"[]\")\n if (!Array.isArray(parsed)) {\n throw new EidosFileError(\n \"invalid-value\",\n \"Logical aggregate scan returned an invalid payload\"\n )\n }\n return parsed.map((entry) => {\n if (!entry || Array.isArray(entry) || typeof entry !== \"object\") {\n throw new EidosFileError(\n \"invalid-value\",\n \"Logical aggregate scan returned an invalid row\"\n )\n }\n const rowId = entry.id\n const rowValues = entry.values\n if (\n typeof rowId !== \"string\" ||\n !Array.isArray(rowValues) ||\n rowValues.length !== selectedFields.length\n ) {\n throw new EidosFileError(\n \"invalid-value\",\n \"Logical aggregate scan returned an invalid row\"\n )\n }\n return {\n id: rowId,\n fields: Object.fromEntries(\n selectedFields.map((field, index) => {\n const wrapped = rowValues[index]\n if (\n !wrapped ||\n Array.isArray(wrapped) ||\n typeof wrapped !== \"object\"\n ) {\n throw new EidosFileError(\n \"invalid-value\",\n \"Logical aggregate scan returned an invalid value\"\n )\n }\n const storage = wrapped.storage\n const value = wrapped.value\n if (storage === \"null\") return [field.id!, null]\n if (storage === \"integer\") {\n if (typeof value !== \"string\") {\n throw new EidosFileError(\n \"invalid-value\",\n \"Logical aggregate INTEGER lost precision\"\n )\n }\n return [\n field.id!,\n fieldValueTypeForScan(field) === \"checkbox\"\n ? value === \"1\"\n : fieldValueTypeForScan(field) === \"integer\"\n ? BigInt(value)\n : Number(value),\n ]\n }\n if (storage === \"real\") return [field.id!, Number(value)]\n if (storage === \"text\") {\n const logicalType = fieldValueTypeForScan(field)\n if (\n logicalType === \"file\" ||\n logicalType === \"multi-select\" ||\n logicalType === \"relation\" ||\n logicalType === \"file-entry\" ||\n typeof logicalType === \"object\"\n ) {\n return [field.id!, parseEidosFileJson(String(value))]\n }\n return [field.id!, String(value)]\n }\n throw new EidosFileError(\n \"invalid-value\",\n \"Logical aggregate scan returned an unsupported storage class\"\n )\n })\n ),\n }\n })\n }\n\n /** @internal Builds the keyset boundary used by the exact Runtime service. */\n createRowCursor(\n tableId: string,\n query: EidosFileRowQuery,\n row: EidosFileLogicalRow\n ): string {\n const compatibleQuery = this.compatibilityQuery(tableId, query)\n const fields = this.listFields(tableId)\n const sorts = uniqueSortFields(fields, compatibleQuery.sorts)\n const values = sorts.map(({ field }) => {\n const value = row.fields[field.id!] ?? null\n return typeof value === \"boolean\" ? (value ? 1 : 0) : value\n })\n if (\n values.some(\n (value) =>\n value !== null &&\n typeof value !== \"string\" &&\n typeof value !== \"number\" &&\n typeof value !== \"bigint\" &&\n !(value instanceof Uint8Array)\n )\n ) {\n throw new EidosFileError(\n \"invalid-query\",\n \"Sort boundary is not a scalar SQLite value\"\n )\n }\n return encodeURIComponent(\n JSON.stringify({\n version: 1,\n revision: String(this.info().revision ?? 0),\n tableId,\n query: canonicalizeEidosFileJson(compatibleQuery),\n offset: 0,\n values: values.map((value) =>\n encodeCursorSqlValue(value as EidosFileSqlPrimitive)\n ),\n lastId: row.id,\n direction: \"forward\",\n referenceInstant: this.nowInstant(),\n })\n )\n }\n\n countRows(\n tableId: string,\n query: EidosFileRowQuery = {},\n referenceInstant = this.nowInstant()\n ): number {\n const compatibleQuery = this.compatibilityQuery(tableId, query)\n const fields = this.listFields(tableId)\n const source = this.logicalSource(\n tableId,\n this.requiredQueryFieldKeys(fields, compatibleQuery),\n false,\n false,\n this.querySearchFragmentFieldIds(fields, compatibleQuery)\n )\n const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, {\n referenceInstant,\n })\n return (\n this.connection.get<{ count: number }>(\n `WITH logical AS (${source.sql}) SELECT count(*) AS count FROM logical ${compiled.whereSql}`,\n compiled.params\n )?.count ?? 0\n )\n }\n\n countRowsByField(\n tableId: string,\n fieldKey: string,\n query: EidosFileRowQuery = {}\n ): EidosFileRowGroupCount[] {\n const field = this.fieldByKey(tableId, fieldKey)\n const compatibleQuery = this.compatibilityQuery(tableId, query)\n const fields = this.listFields(tableId)\n const source = this.logicalSource(\n tableId,\n [field.id!, ...this.requiredQueryFieldKeys(fields, compatibleQuery)],\n false,\n false,\n this.querySearchFragmentFieldIds(fields, compatibleQuery)\n )\n const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, {\n referenceInstant: this.nowInstant(),\n })\n const column = quoteIdentifier(field.tableColumnName)\n if (\n field.storageCodec === \"json_array\" ||\n field.storageCodec === \"relation\"\n ) {\n return this.connection.query<{\n value: EidosFileSqlPrimitive\n total: number\n }>(\n `WITH logical AS (${source.sql}), filtered AS (\n SELECT * FROM logical ${compiled.whereSql}\n )\n SELECT item.value AS value, count(*) AS total\n FROM filtered, json_each(filtered.${column}) item\n GROUP BY item.value ORDER BY total DESC, item.value`,\n compiled.params\n )\n }\n return this.connection.query<{\n value: EidosFileSqlPrimitive\n total: number\n }>(\n `WITH logical AS (${source.sql})\n SELECT ${column} AS value, count(*) AS total FROM logical\n ${compiled.whereSql} GROUP BY ${column} ORDER BY total DESC, ${column}`,\n compiled.params\n )\n }\n\n calculateColumnStats(\n tableId: string,\n configs: EidosFileColumnStatConfig[],\n query: EidosFileRowQuery = {}\n ): EidosFileColumnStatResult[] {\n const compatibleQuery = this.compatibilityQuery(tableId, query)\n const fields = this.listFields(tableId)\n configs = normalizeEidosFileColumnStatConfigs(configs, fields)\n const source = this.logicalSource(\n tableId,\n [\n ...configs.map((config) => config.fieldId),\n ...this.requiredQueryFieldKeys(fields, compatibleQuery),\n ],\n false,\n false,\n this.querySearchFragmentFieldIds(fields, compatibleQuery)\n )\n const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, {\n referenceInstant: this.nowInstant(),\n })\n return configs.map((config) => {\n const field = this.fieldByKey(tableId, config.fieldId)\n const column = quoteIdentifier(field.tableColumnName)\n const list =\n field.storageCodec === \"json_array\" || field.storageCodec === \"relation\"\n if (config.type.startsWith(\"relation-\") && field.type !== \"relation\") {\n throw new EidosFileError(\n \"invalid-query\",\n `${config.type} requires a Relation Field`\n )\n }\n const flattened = `(SELECT item.value AS value, item.type AS value_type\n FROM filtered, json_each(filtered.${column}) item\n WHERE item.value IS NOT NULL)`\n const expression = {\n \"count-all\": \"count(*)\",\n \"count-non-null\": list ? \"count(*)\" : `count(${column})`,\n \"count-empty\": `sum(CASE WHEN ${column} IS NULL${list ? ` OR json_array_length(${column}) = 0` : \"\"} THEN 1 ELSE 0 END)`,\n \"percent-checked\": `CASE WHEN count(*) = 0 THEN 0 ELSE round(100.0 * sum(CASE WHEN ${column} = 1 THEN 1 ELSE 0 END) / count(*), 2) END`,\n \"percent-unchecked\": `CASE WHEN count(*) = 0 THEN 0 ELSE round(100.0 * sum(CASE WHEN ${column} = 1 THEN 0 ELSE 1 END) / count(*), 2) END`,\n \"count-distinct\": list\n ? `(SELECT count(DISTINCT value_type || ':' || json_quote(value)) FROM ${flattened})`\n : `count(DISTINCT ${column})`,\n sum: list\n ? `(SELECT sum(value) FROM ${flattened} WHERE value_type IN ('integer','real'))`\n : `sum(${column})`,\n average: list\n ? `(SELECT avg(value) FROM ${flattened} WHERE value_type IN ('integer','real'))`\n : `avg(${column})`,\n min: list ? `(SELECT min(value) FROM ${flattened})` : `min(${column})`,\n max: list ? `(SELECT max(value) FROM ${flattened})` : `max(${column})`,\n \"relation-value-count\": `sum(json_array_length(${column}))`,\n \"relation-row-count\": `sum(CASE WHEN json_array_length(${column}) > 0 THEN 1 ELSE 0 END)`,\n \"relation-distinct-target-count\": `(SELECT count(DISTINCT value) FROM ${flattened} WHERE value_type = 'text')`,\n }[config.type]\n if (!expression) {\n throw new EidosFileError(\n \"invalid-query\",\n `Unsupported statistic: ${config.type}`\n )\n }\n const rawValue =\n this.connection.get<{ value: EidosFileSqlPrimitive }>(\n `WITH logical AS (${source.sql}), filtered AS (\n SELECT * FROM logical ${compiled.whereSql}\n ) SELECT ${expression} AS value FROM filtered`,\n compiled.params\n )?.value ?? null\n const value = typeof rawValue === \"bigint\" ? String(rawValue) : rawValue\n if (value instanceof Uint8Array) {\n throw new EidosFileError(\n \"invalid-query\",\n `Statistic ${config.type} returned an invalid binary value`\n )\n }\n return { ...config, value }\n })\n }\n\n aggregate(\n tableId: string,\n configs: EidosFileColumnStatConfig[],\n query: EidosFileRowQuery = {}\n ): EidosFileColumnStatResult[] {\n return this.calculateColumnStats(tableId, configs, query)\n }\n\n private normalizeStoredValue(\n field: EidosFileFieldInfo,\n value: EidosFileRow[string],\n allowUnresolvedRelations: boolean\n ): EidosFileSqlPrimitive {\n if (value === null || value === undefined) {\n if (\n field.type === \"file\" ||\n field.type === \"multi-select\" ||\n field.type === \"relation\"\n )\n return \"[]\"\n return null\n }\n if (field.type === \"checkbox\") {\n if (value === true || value === 1) return 1\n if (value === false || value === 0) return 0\n throw new EidosFileError(\n \"invalid-value\",\n `${field.name} must be boolean or NULL`\n )\n }\n if (field.type === \"number\") {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new EidosFileError(\n \"invalid-value\",\n `${field.name} must be finite number or NULL`\n )\n }\n return value\n }\n if (field.type === \"date\") {\n if (typeof value !== \"string\") {\n throw new EidosFileError(\n \"invalid-value\",\n `${field.name} must be canonical YYYY-MM-DD text or NULL`\n )\n }\n return normalizeEidosFileDate(value, field.name)\n }\n if (field.type === \"datetime\") {\n if (typeof value !== \"string\") {\n throw new EidosFileError(\n \"invalid-value\",\n `${field.name} must be RFC 3339 text or NULL`\n )\n }\n return normalizeEidosFileInstant(value, field.name)\n }\n if ([\"integer\", \"rating\"].includes(field.type)) {\n if (typeof value !== \"number\" && typeof value !== \"bigint\") {\n throw new EidosFileError(\n \"invalid-value\",\n `${field.name} must be an integer or NULL`\n )\n }\n const integer =\n typeof value === \"bigint\"\n ? value >= -9_223_372_036_854_775_808n &&\n value <= 9_223_372_036_854_775_807n\n : typeof value === \"number\" && Number.isSafeInteger(value)\n if (!integer) {\n throw new EidosFileError(\n \"invalid-value\",\n `${field.name} must be an integer or NULL`\n )\n }\n if (field.type === \"rating\") {\n const maximum =\n typeof field.settings?.max === \"number\" ? field.settings.max : 5\n if (typeof value !== \"number\" || value < 0 || value > maximum) {\n throw new EidosFileError(\n \"invalid-value\",\n `${field.name} must be between 0 and ${maximum}`\n )\n }\n }\n return value\n }\n if (\n field.type === \"select\" ||\n field.type === \"text\" ||\n field.type === \"url\"\n ) {\n if (typeof value !== \"string\") {\n throw new EidosFileError(\n \"invalid-value\",\n `${field.name} must be text or NULL`\n )\n }\n if (field.type === \"url\" && !isEidosFileUriReference(value)) {\n throw new EidosFileError(\n \"invalid-value\",\n `${field.name} contains an invalid URI-reference`\n )\n }\n return value\n }\n if (field.type === \"multi-select\") {\n const parsed =\n typeof value === \"string\" ? parseEidosFileJson(value) : value\n if (\n !Array.isArray(parsed) ||\n !parsed.every((entry) => typeof entry === \"string\") ||\n new Set(parsed).size !== parsed.length\n ) {\n throw new EidosFileError(\n \"invalid-value\",\n `${field.name} must be a unique string array`\n )\n }\n return canonicalizeEidosFileJson(parsed)\n }\n if (field.type === \"file\") {\n return typeof value === \"string\"\n ? canonicalizeEidosFileJson(decodeEidosFileValues(value))\n : canonicalizeEidosFileJson(assertEidosFileValues(value))\n }\n if (field.type === \"relation\") {\n const ids = Array.isArray(value)\n ? value.map(String)\n : decodeEidosFileRelationIds(\n typeof value === \"string\" ? value : undefined\n )\n const encoded = encodeEidosFileRelationIds(ids)\n const schema = this.allSchema()\n const relation = schema.relations.get(field.id!)\n if (!relation || relation.direction !== \"forward\") {\n throw new EidosFileError(\n \"invalid-value\",\n \"Inverse Relations are read-only\"\n )\n }\n if (relation.cardinality === \"one\" && ids.length > 1) {\n throw new EidosFileError(\n \"invalid-value\",\n `${field.name} accepts at most one target`\n )\n }\n if (!allowUnresolvedRelations && ids.length > 0) {\n const target = schema.tables.get(uuid(relation.target_table_id))!\n const placeholders = ids.map(() => \"?\").join(\", \")\n const count =\n this.connection.get<{ count: number }>(\n `SELECT count(*) AS count FROM ${quoteIdentifier(target.physical_name)}\n WHERE \"_id\" IN (${placeholders})`,\n ids\n )?.count ?? 0\n if (count !== ids.length) {\n throw new EidosFileError(\n \"invalid-value\",\n `${field.name} contains a missing target Row ID`\n )\n }\n }\n return encoded\n }\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\"\n ) {\n return value\n }\n throw new EidosFileError(\n \"invalid-value\",\n `Unsupported value for ${field.name}`\n )\n }\n\n private rowChanges(\n tableId: string,\n row: EidosFileRow,\n allowUnresolvedRelations: boolean,\n applyCreateDefaults = false\n ): Array<{ field: EidosFileFieldInfo; value: EidosFileSqlPrimitive }> {\n const changes: Array<{\n field: EidosFileFieldInfo\n value: EidosFileSqlPrimitive\n }> = []\n for (const [key, value] of Object.entries(row)) {\n if (key === \"_id\" || key === \"id\" || key.endsWith(\"__display\")) continue\n const field = this.fieldByKey(tableId, key)\n if (!field.physicalName || field.valueKind === \"system\") {\n throw new EidosFileError(\n \"protected-field\",\n `Field ${field.name} is read-only`\n )\n }\n changes.push({\n field,\n value: this.normalizeStoredValue(\n field,\n value,\n allowUnresolvedRelations\n ),\n })\n }\n if (applyCreateDefaults) {\n const suppliedFieldIds = new Set(changes.map((change) => change.field.id))\n for (const field of this.listFields(tableId)) {\n if (\n field.type !== \"select\" ||\n !field.id ||\n !field.physicalName ||\n suppliedFieldIds.has(field.id)\n ) {\n continue\n }\n const defaultOption = parseEidosFileSelectDefaultOption(field.settings)\n if (defaultOption === null) continue\n changes.push({\n field,\n value: this.normalizeStoredValue(\n field,\n defaultOption,\n allowUnresolvedRelations\n ),\n })\n }\n }\n return changes\n }\n\n private insertRowInTransaction(\n tableId: string,\n row: EidosFileRow,\n allowUnresolvedRelations: boolean,\n applyCreateDefaults: boolean\n ): string {\n const table = this.getTable(tableId)\n const requestedId = row._id ?? row.id\n const rowId =\n typeof requestedId === \"string\"\n ? assertEidosFileUuid(requestedId, \"Row ID\")\n : this.allocateId()\n const now = this.operationInstant()\n const changes = this.rowChanges(\n tableId,\n row,\n allowUnresolvedRelations,\n applyCreateDefaults\n )\n const columns = [\n \"_id\",\n \"_created_at\",\n \"_updated_at\",\n ...changes.map((change) => change.field.physicalName!),\n ]\n const values: EidosFileSqlPrimitive[] = [\n rowId,\n now,\n now,\n ...changes.map((change) => change.value),\n ]\n this.connection.run(\n `INSERT INTO ${quoteIdentifier(table.physicalName ?? table.rawTableName)}\n (${columns.map(quoteIdentifier).join(\", \")})\n VALUES (${values.map(() => \"?\").join(\", \")})`,\n values\n )\n return rowId\n }\n\n private insertImportedRowsInTransaction(\n tableId: string,\n rows: readonly EidosFileRow[]\n ): string[] {\n if (rows.length === 0) return []\n const table = this.getTable(tableId)\n const fields = this.listFields(tableId)\n const fieldByKey = new Map<string, EidosFileFieldInfo>()\n for (const field of fields) {\n for (const key of [\n field.id,\n field.tableColumnName,\n field.physicalName,\n field.name,\n ]) {\n if (key && !fieldByKey.has(key)) fieldByKey.set(key, field)\n }\n }\n const tableName = table.physicalName ?? table.rawTableName\n const plans = new Map<\n string,\n {\n keys: string[]\n fields: EidosFileFieldInfo[]\n sql: string\n parameterSets: EidosFileSqlPrimitive[][]\n }\n >()\n const now = this.operationInstant()\n const ids = rows.map((row) => {\n const requestedId = row._id ?? row.id\n const rowId =\n typeof requestedId === \"string\"\n ? assertEidosFileUuid(requestedId, \"Row ID\")\n : this.allocateId()\n const keys = Object.keys(row).filter(\n (key) => key !== \"_id\" && key !== \"id\" && !key.endsWith(\"__display\")\n )\n const signature = JSON.stringify(keys)\n let plan = plans.get(signature)\n if (!plan) {\n const plannedFields = keys.map((key) => {\n const field = fieldByKey.get(key)\n if (!field) {\n throw new EidosFileError(\n \"field-not-found\",\n `Eidos File Field not found: ${key}`\n )\n }\n if (!field.physicalName || field.valueKind === \"system\") {\n throw new EidosFileError(\n \"protected-field\",\n `Field ${field.name} is read-only`\n )\n }\n return field\n })\n const columns = [\n \"_id\",\n \"_created_at\",\n \"_updated_at\",\n ...plannedFields.map((field) => field.physicalName!),\n ]\n plan = {\n keys,\n fields: plannedFields,\n sql: `INSERT INTO ${quoteIdentifier(tableName)}\n (${columns.map(quoteIdentifier).join(\", \")})\n VALUES (${columns.map(() => \"?\").join(\", \")})`,\n parameterSets: [],\n }\n plans.set(signature, plan)\n }\n const values: EidosFileSqlPrimitive[] = [\n rowId,\n now,\n now,\n ...plan.keys.map((key, index) =>\n this.normalizeStoredValue(plan.fields[index]!, row[key], true)\n ),\n ]\n plan.parameterSets.push(values)\n return rowId\n })\n for (const plan of plans.values()) {\n if (this.connection.runMany) {\n this.connection.runMany(plan.sql, plan.parameterSets)\n } else {\n for (const values of plan.parameterSets) {\n this.connection.run(plan.sql, values)\n }\n }\n }\n return ids\n }\n\n insertRow(tableId: string, row: EidosFileRow): EidosFileRow {\n const id = this.mutate(() =>\n this.insertRowInTransaction(tableId, row, true, true)\n )\n return this.getRow(tableId, id)!\n }\n\n insertImportedRow(tableId: string, row: EidosFileRow): EidosFileRow {\n const id = this.mutate(() =>\n this.insertRowInTransaction(tableId, row, true, false)\n )\n return this.getRow(tableId, id)!\n }\n\n insertImportedRows(tableId: string, rows: EidosFileRow[]): EidosFileRow[] {\n const ids = this.mutate(() =>\n this.insertImportedRowsInTransaction(tableId, rows)\n )\n return ids.map((id) => this.getRow(tableId, id)!)\n }\n\n /** @internal Appends rows inside a caller-owned import transaction. */\n appendImportedRows(tableId: string, rows: EidosFileRow[]): void {\n this.insertImportedRowsInTransaction(tableId, rows)\n }\n\n /** @internal Used by the transactional CSV interchange layer. */\n importTable(\n table: CreateEidosFileTableInput,\n rows: EidosFileRow[]\n ): EidosFileTableInfo {\n return this.mutate(() => {\n const created = this.createTable(table)\n this.insertImportedRowsInTransaction(created.id, rows)\n return created\n })\n }\n\n updateRow(\n tableId: string,\n rowId: string,\n changes: EidosFileRow\n ): EidosFileRow {\n return this.updateRows(tableId, [{ rowId, changes }])[0]!\n }\n\n updateRows(tableId: string, updates: EidosFileRowUpdate[]): EidosFileRow[] {\n const table = this.getTable(tableId)\n const ids = this.mutate(() => {\n for (const update of updates) {\n const rowId = assertEidosFileUuid(update.rowId, \"Row ID\")\n const changes = this.rowChanges(tableId, update.changes, true)\n if (changes.length === 0) continue\n const assignments = [\n ...changes.map(\n (change) => `${quoteIdentifier(change.field.physicalName!)} = ?`\n ),\n `\"_updated_at\" = ?`,\n ]\n const result = this.connection.run(\n `UPDATE ${quoteIdentifier(table.physicalName ?? table.rawTableName)}\n SET ${assignments.join(\", \")} WHERE \"_id\" = ?`,\n [\n ...changes.map((change) => change.value),\n this.operationInstant(),\n rowId,\n ]\n )\n if (result.changes === 0) {\n throw new EidosFileError(\n \"row-not-found\",\n `Eidos File Row not found: ${rowId}`\n )\n }\n }\n return updates.map((update) => update.rowId)\n })\n return ids.map((id) => this.getRow(tableId, id)!)\n }\n\n private rowMutationUndoEntryBytes(entry: RowMutationUndoEntry): number {\n const json = JSON.stringify(entry, (_key, value: unknown) => {\n if (typeof value === \"bigint\") {\n return { $int64: value.toString() }\n }\n if (value instanceof Uint8Array) {\n return { $blob: Array.from(value) }\n }\n return value\n })\n return new TextEncoder().encode(json).byteLength\n }\n\n private prepareRowMutationUndo(\n entry: RowMutationUndoEntry\n ): PreparedRowMutationUndoEntry {\n const bytes = this.rowMutationUndoEntryBytes(entry)\n if (bytes > ROW_MUTATION_UNDO_BYTES_MAX) {\n throw new EidosFileError(\n \"resource-limit\",\n \"This deletion is too large to retain for undo\"\n )\n }\n const base = `row-undo:${this.allocateId()}`\n let token = base\n let suffix = 1\n while (this.rowMutationUndoEntries.has(token)) {\n token = `${base}:${suffix}`\n suffix += 1\n }\n return { token, retained: { entry, bytes } }\n }\n\n private deleteRowMutationUndoEntry(token: string): boolean {\n const retained = this.rowMutationUndoEntries.get(token)\n if (!retained) return false\n this.rowMutationUndoEntries.delete(token)\n this.rowMutationUndoBytes = Math.max(\n 0,\n this.rowMutationUndoBytes - retained.bytes\n )\n return true\n }\n\n private clearRowMutationUndoEntries(): void {\n this.rowMutationUndoEntries.clear()\n this.rowMutationUndoBytes = 0\n }\n\n private commitRowMutationUndo(\n prepared: PreparedRowMutationUndoEntry,\n consumedToken?: string\n ): string {\n if (consumedToken) this.deleteRowMutationUndoEntry(consumedToken)\n this.rowMutationUndoEntries.set(prepared.token, prepared.retained)\n this.rowMutationUndoBytes += prepared.retained.bytes\n while (\n this.rowMutationUndoEntries.size > ROW_MUTATION_UNDO_ENTRIES_MAX ||\n this.rowMutationUndoBytes > ROW_MUTATION_UNDO_BYTES_MAX\n ) {\n // A new edit clears the UI redo stack. Prefer dropping those stale redo\n // tokens before an older undo token that the UI may still expose.\n const redoToken = Array.from(this.rowMutationUndoEntries).find(\n ([token, retained]) =>\n token !== prepared.token && retained.entry.kind === \"repeat-delete\"\n )?.[0]\n const oldestToken = this.rowMutationUndoEntries.keys().next().value\n const token = redoToken ?? oldestToken\n if (typeof token !== \"string\" || token === prepared.token) break\n this.deleteRowMutationUndoEntry(token)\n }\n return prepared.token\n }\n\n private captureRowDeletionUndoState(\n tableId: string,\n rowIds: string[]\n ): RowDeletionUndoState {\n const ids = Array.from(\n new Set(rowIds.map((id) => assertEidosFileUuid(id, \"Row ID\")))\n )\n const table = this.getTable(tableId)\n const physicalTable = table.physicalName ?? table.rawTableName\n const rawRows =\n ids.length === 0\n ? []\n : this.connection.query<Record<string, EidosFileSqlPrimitive>>(\n `SELECT * FROM ${quoteIdentifier(physicalTable)} WHERE \"_id\" IN (${ids.map(() => \"?\").join(\", \")})`,\n ids\n )\n const rawById = new Map(\n rawRows.flatMap((row) =>\n typeof row._id === \"string\" ? [[row._id, row] as const] : []\n )\n )\n for (const rowId of ids) {\n if (!rawById.has(rowId)) {\n throw new EidosFileError(\"row-not-found\", `Row not found: ${rowId}`)\n }\n }\n\n const deleteSet = new Set(ids)\n const detachedRelations: DetachedRelationState[] = []\n const schema = this.allSchema()\n for (const [fieldId, relation] of schema.relations) {\n if (\n relation.direction !== \"forward\" ||\n relation.on_delete !== \"detach\" ||\n uuid(relation.target_table_id) !== tableId\n ) {\n continue\n }\n const field = Array.from(schema.fieldsByTable.values())\n .flat()\n .find((candidate) => candidate.id === fieldId)\n if (!field?.tableId || !field.physicalName) continue\n const sourceTable = schema.tables.get(field.tableId)\n if (!sourceTable) continue\n const sourceRows = this.connection.query<{\n _id: string\n relation_value: EidosFileSqlPrimitive\n }>(\n `SELECT \"_id\", ${quoteIdentifier(field.physicalName)} AS relation_value FROM ${quoteIdentifier(sourceTable.physical_name)} ORDER BY \"_id\" COLLATE BINARY`\n )\n for (const sourceRow of sourceRows) {\n if (field.tableId === tableId && deleteSet.has(sourceRow._id)) continue\n if (typeof sourceRow.relation_value !== \"string\") {\n throw new EidosFileError(\n \"invalid-value\",\n `Relation ${fieldId} has a non-text stored value`\n )\n }\n const parsed = parseEidosFileJson(sourceRow.relation_value)\n if (!Array.isArray(parsed)) {\n throw new EidosFileError(\n \"invalid-value\",\n `Relation ${fieldId} has a non-array stored value`\n )\n }\n if (\n !parsed.some(\n (entry) => typeof entry === \"string\" && deleteSet.has(entry)\n )\n ) {\n continue\n }\n const survivors = parsed.filter(\n (entry) => typeof entry !== \"string\" || !deleteSet.has(entry)\n )\n detachedRelations.push({\n tableId: field.tableId,\n physicalTable: sourceTable.physical_name,\n physicalColumn: field.physicalName,\n rowId: sourceRow._id,\n value: sourceRow.relation_value,\n detachedValue: canonicalizeEidosFileJson(survivors),\n })\n }\n }\n\n return {\n tableId,\n rowIds: ids,\n rows: ids.map((rowId) => ({\n tableId,\n physicalTable,\n row: rawById.get(rowId)!,\n })),\n detachedRelations,\n }\n }\n\n private sameUndoPhysicalRow(\n left: Record<string, EidosFileSqlPrimitive>,\n right: Record<string, EidosFileSqlPrimitive>\n ): boolean {\n const leftKeys = Object.keys(left)\n .filter((key) => key !== \"_updated_at\")\n .sort()\n const rightKeys = Object.keys(right)\n .filter((key) => key !== \"_updated_at\")\n .sort()\n return (\n leftKeys.length === rightKeys.length &&\n leftKeys.every(\n (key, index) =>\n key === rightKeys[index] && sameSqlValue(left[key], right[key]!)\n )\n )\n }\n\n private assertRepeatRowDeletionApplicable(state: RowDeletionUndoState): void {\n const current = this.captureRowDeletionUndoState(\n state.tableId,\n state.rowIds\n )\n if (\n current.rows.length !== state.rows.length ||\n current.rows.some((entry, index) => {\n const expected = state.rows[index]\n return (\n !expected ||\n entry.physicalTable !== expected.physicalTable ||\n !this.sameUndoPhysicalRow(entry.row, expected.row)\n )\n })\n ) {\n throw new EidosFileError(\n \"file-conflict\",\n \"The restored records changed and cannot be redone\"\n )\n }\n const relationKey = (entry: DetachedRelationState) =>\n `${entry.tableId}\\u0000${entry.rowId}\\u0000${entry.physicalColumn}`\n const expectedRelations = new Map(\n state.detachedRelations.map((entry) => [relationKey(entry), entry])\n )\n if (\n current.detachedRelations.length !== expectedRelations.size ||\n current.detachedRelations.some((entry) => {\n const expected = expectedRelations.get(relationKey(entry))\n return !expected || !sameSqlValue(entry.value, expected.value)\n })\n ) {\n throw new EidosFileError(\n \"file-conflict\",\n \"Related records changed and this deletion cannot be redone\"\n )\n }\n }\n\n private restoreRowDeletionUndoState(state: RowDeletionUndoState): Array<{\n tableId: string\n rowId: string\n }> {\n return this.mutate(() => {\n const table = this.getTable(state.tableId)\n const physicalTable = table.physicalName ?? table.rawTableName\n if (state.rows.some((entry) => entry.physicalTable !== physicalTable)) {\n throw new EidosFileError(\n \"stale-revision\",\n \"The table changed after these rows were deleted\"\n )\n }\n if (state.rowIds.length > 0) {\n const existing = this.connection.get<{ count: number }>(\n `SELECT count(*) AS count FROM ${quoteIdentifier(physicalTable)} WHERE \"_id\" IN (${state.rowIds.map(() => \"?\").join(\", \")})`,\n state.rowIds\n )?.count\n if (Number(existing ?? 0) !== 0) {\n throw new EidosFileError(\n \"file-conflict\",\n \"A deleted Row ID is already in use\"\n )\n }\n }\n for (const relation of state.detachedRelations) {\n const current = this.connection.get<{\n value: EidosFileSqlPrimitive\n }>(\n `SELECT ${quoteIdentifier(relation.physicalColumn)} AS value FROM ${quoteIdentifier(relation.physicalTable)} WHERE \"_id\" = ?`,\n [relation.rowId]\n )\n if (!current || !sameSqlValue(current.value, relation.detachedValue)) {\n throw new EidosFileError(\n \"file-conflict\",\n `Related Row ${relation.rowId} changed after the deletion`\n )\n }\n }\n const schema = this.allSchema()\n const outgoingRelationColumns = new Set(\n (schema.fieldsByTable.get(state.tableId) ?? []).flatMap((field) => {\n const relation = field.id ? schema.relations.get(field.id) : undefined\n return relation?.direction === \"forward\" && field.physicalName\n ? [field.physicalName]\n : []\n })\n )\n\n // Insert every deleted identity first with empty outgoing relations. This\n // lets records that referenced one another be restored without depending\n // on insertion order or weakening the relation safety triggers.\n for (const entry of state.rows) {\n const keys = Object.keys(entry.row)\n const values = keys.map((key) =>\n outgoingRelationColumns.has(key) ? \"[]\" : entry.row[key]!\n )\n this.connection.run(\n `INSERT INTO ${quoteIdentifier(physicalTable)} (${keys.map(quoteIdentifier).join(\", \")}) VALUES (${keys.map(() => \"?\").join(\", \")})`,\n values\n )\n }\n for (const entry of state.rows) {\n const rowId = entry.row._id\n if (typeof rowId !== \"string\") {\n throw new EidosFileError(\n \"invalid-schema\",\n \"Deleted row state is missing its Row ID\"\n )\n }\n const keys = Object.keys(entry.row).filter((key) => key !== \"_id\")\n if (keys.length > 0) {\n const response = this.connection.run(\n `UPDATE ${quoteIdentifier(physicalTable)} SET ${keys.map((key) => `${quoteIdentifier(key)} = ?`).join(\", \")} WHERE \"_id\" = ?`,\n [\n ...keys.map((key) =>\n key === \"_updated_at\"\n ? this.operationInstant()\n : entry.row[key]!\n ),\n rowId,\n ]\n )\n if (response.changes === 0) {\n throw new EidosFileError(\n \"stale-revision\",\n `Could not restore Row ${rowId}`\n )\n }\n }\n }\n for (const relation of state.detachedRelations) {\n const response = this.connection.run(\n `UPDATE ${quoteIdentifier(relation.physicalTable)} SET ${quoteIdentifier(relation.physicalColumn)} = ?, \"_updated_at\" = ? WHERE \"_id\" = ?`,\n [relation.value, this.operationInstant(), relation.rowId]\n )\n if (response.changes === 0) {\n throw new EidosFileError(\n \"stale-revision\",\n `Could not restore Relation on Row ${relation.rowId}`\n )\n }\n }\n return [\n ...state.rows.map((entry) => ({\n tableId: entry.tableId,\n rowId: String(entry.row._id),\n })),\n ...state.detachedRelations.map((entry) => ({\n tableId: entry.tableId,\n rowId: entry.rowId,\n })),\n ]\n })\n }\n\n deleteRowsReversible(\n tableId: string,\n rowIds: string[],\n expectedRevision?: number | bigint,\n consumedUndoToken?: string\n ): {\n revision: number | bigint\n deleted: string[]\n affected: Array<{ tableId: string; rowId: string }>\n rowCount: number\n undoToken?: string\n } {\n if (rowIds.length === 0) {\n return {\n revision: this.info().revision ?? 0,\n deleted: [],\n affected: [],\n rowCount: this.countRows(tableId),\n }\n }\n const rowCountBefore = this.countRows(tableId)\n const state = this.captureRowDeletionUndoState(tableId, rowIds)\n const preparedUndo = this.prepareRowMutationUndo({\n kind: \"restore-delete\",\n state,\n })\n const result = this.mutateRows({\n tableId,\n delete: state.rowIds,\n expectedRevision,\n })\n const undoToken = this.commitRowMutationUndo(\n preparedUndo,\n consumedUndoToken\n )\n return {\n revision: result.revision,\n deleted: result.deleted,\n affected: result.affected ?? [],\n rowCount: rowCountBefore - result.deleted.length,\n undoToken,\n }\n }\n\n revertRowMutation(undoToken: string): {\n revision: number | bigint\n affected: Array<{ tableId: string; rowId: string }>\n rowCount: number\n undoToken?: string\n } {\n const retained = this.rowMutationUndoEntries.get(undoToken)\n if (!retained) {\n throw new EidosFileError(\n \"stale-revision\",\n \"This row change can no longer be undone\"\n )\n }\n const entry = retained.entry\n if (entry.kind === \"restore-delete\") {\n const rowCount =\n this.countRows(entry.state.tableId) + entry.state.rowIds.length\n const preparedUndo = this.prepareRowMutationUndo({\n kind: \"repeat-delete\",\n state: entry.state,\n })\n const affected = this.restoreRowDeletionUndoState(entry.state)\n return {\n revision: this.info().revision ?? 0,\n affected,\n rowCount,\n undoToken: this.commitRowMutationUndo(preparedUndo, undoToken),\n }\n }\n this.assertRepeatRowDeletionApplicable(entry.state)\n const result = this.deleteRowsReversible(\n entry.state.tableId,\n entry.state.rowIds,\n undefined,\n undoToken\n )\n return {\n revision: result.revision,\n affected: result.affected,\n rowCount: result.rowCount,\n undoToken: result.undoToken,\n }\n }\n\n deleteRow(tableId: string, rowId: string): boolean {\n return this.deleteRows(tableId, [rowId]).length === 1\n }\n\n deleteRows(tableId: string, rowIds: string[]): string[] {\n if (rowIds.length === 0) return []\n const ids = Array.from(\n new Set(rowIds.map((id) => assertEidosFileUuid(id, \"Row ID\")))\n )\n if (ids.length > 500) {\n throw new EidosFileError(\n \"resource-limit\",\n \"deleteRows accepts at most 500 Row IDs\"\n )\n }\n return this.mutateRows({ tableId, delete: ids }).deleted\n }\n\n private rowIdsForRanges(\n tableId: string,\n ranges: EidosFileRowRange[],\n query: EidosFileRowQuery\n ): string[] {\n const rowIdField = this.listFields(tableId).find(\n (field) => field.type === \"row-id\"\n )!\n return ranges.flatMap((range) => {\n const start = Math.max(0, Math.trunc(range.startIndex))\n const end = Math.max(start, Math.trunc(range.endIndex))\n if (end === start) return []\n return this.getRowPage(tableId, start, end - start, query).rows.flatMap(\n (row) => {\n const id = row[rowIdField.tableColumnName]\n return typeof id === \"string\" ? [id] : []\n }\n )\n })\n }\n\n deleteRowRanges(\n tableId: string,\n ranges: EidosFileRowRange[],\n query: EidosFileRowQuery = {}\n ): number {\n const ids = this.rowIdsForRanges(tableId, ranges, query)\n return this.deleteRows(tableId, ids).length\n }\n\n deleteRowRangesReversible(\n tableId: string,\n ranges: EidosFileRowRange[],\n query: EidosFileRowQuery = {}\n ) {\n return this.deleteRowsReversible(\n tableId,\n this.rowIdsForRanges(tableId, ranges, query)\n )\n }\n\n previewFormula(\n tableId: string,\n input: EidosFileFormulaPreviewInput\n ): EidosFileFormulaPreview {\n const fields = this.listFields(tableId)\n const draft: EidosFileFieldInfo = {\n id: this.allocateId(),\n tableId,\n name: input.name,\n type: \"formula\",\n tableName: this.getTable(tableId).rawTableName,\n tableColumnName: input.columnName,\n physicalName: null,\n isRecordLabel: false,\n position: fields.length,\n settings: {},\n property: { formula: input.formula, displayType: input.displayType },\n storageCodec: \"scalar\",\n valueKind: \"derived\",\n isHidden: false,\n isDerived: true,\n sourceTableColumnName: null,\n dependsOn: null,\n }\n const compiled = compileEidosFileFormula(draft, fields)\n const schema = this.allSchema()\n const expression = compileEidosFileFormulaSource(\n input.formula,\n fields,\n (dependency) => this.fieldExpression(dependency, \"base\", schema),\n input.displayType\n ).expression\n const sampleExpression = canonicalTemporalProjection(\n expression,\n input.displayType\n )\n const table = this.getTable(tableId)\n const label = fields.find((field) => field.isRecordLabel)!\n const previewRowIds =\n input.rowIds === undefined\n ? undefined\n : Array.from(\n new Set(\n input.rowIds.map((rowId) =>\n assertEidosFileUuid(rowId, \"Formula preview Row ID\")\n )\n )\n ).slice(0, 100)\n const rowFilter =\n previewRowIds === undefined\n ? \"\"\n : previewRowIds.length === 0\n ? \"WHERE 0\"\n : `WHERE base.\"_id\" IN (${previewRowIds.map(() => \"?\").join(\", \")})`\n const samples = this.connection.query<{\n row_id: string\n title: EidosFileSqlPrimitive\n value: EidosFileSqlPrimitive\n }>(\n `SELECT base.\"_id\" AS row_id,\n ${this.fieldExpression(label, \"base\", schema)} AS title,\n ${sampleExpression} AS value\n FROM ${quoteIdentifier(table.physicalName ?? table.rawTableName)} base\n ${rowFilter}\n ORDER BY base.\"_id\" LIMIT ${previewRowIds?.length || 5}`,\n previewRowIds ?? []\n )\n return {\n expression,\n dependencies: compiled.dependencyFieldIds.map((id) => {\n const field = fields.find((candidate) => candidate.id === id)!\n return { name: field.name, columnName: field.tableColumnName }\n }),\n samples: samples.map((sample) => ({\n rowId: sample.row_id,\n title: sample.title === null ? null : String(sample.title),\n value: rowValue(sample.value),\n })),\n }\n }\n\n optimizeViewQueries(): void {\n const indexedFields = new Set<string>()\n for (const table of this.listTables()) {\n const fields = this.listFields(table.id)\n for (const view of this.listViews(table.id)) {\n if (view.type !== \"calendar\") continue\n const dateField = view.properties?.dateField\n if (typeof dateField !== \"string\") continue\n const field = fields.find(\n (candidate) =>\n candidate.id === dateField ||\n candidate.tableColumnName === dateField\n )\n if (\n !field?.id ||\n !field.physicalName ||\n field.isDerived ||\n field.storageCodec !== \"scalar\" ||\n ![\"date\", \"datetime\", \"created-time\", \"last-edited-time\"].includes(\n field.type\n ) ||\n indexedFields.has(field.id)\n ) {\n continue\n }\n indexedFields.add(field.id)\n const indexName = `idx_eidos_calendar_${field.id.replace(/-/g, \"\")}`\n this.connection.exec(\n `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(indexName)}\n ON ${quoteIdentifier(table.physicalName ?? table.rawTableName)}\n (${quoteIdentifier(field.physicalName)} COLLATE BINARY)`\n )\n }\n }\n }\n\n schema(tableId?: string) {\n const tables = tableId ? [this.getTable(tableId)] : this.listTables()\n return tables.map((table) => ({\n table,\n fields: this.listFields(table.id),\n views: this.listViews(table.id),\n }))\n }\n\n mutateSchema(\n operations: EidosFileSchemaMutation[],\n expectedRevision?: number | bigint\n ): { revision: number | bigint; results: unknown[] } {\n if (operations.length === 0) {\n throw new EidosFileError(\n \"invalid-value\",\n \"mutateSchema requires at least one operation\"\n )\n }\n const results = this.mutate(\n () =>\n operations.map((operation) => {\n switch (operation.type) {\n case \"create-table\":\n return this.createTable(operation.table)\n case \"update-table\":\n return this.updateTable(operation.tableId, operation.changes)\n case \"delete-table\":\n return this.deleteTable(operation.tableId)\n case \"add-field\":\n return this.addField(operation.tableId, operation.field)\n case \"update-field\":\n return this.updateField(\n operation.tableId,\n operation.fieldId,\n operation.changes\n )\n case \"delete-field\":\n return this.deleteField(operation.tableId, operation.fieldId)\n case \"create-view\":\n return this.createView(operation.tableId, operation.view)\n case \"update-view\":\n return this.updateView(operation.viewId, operation.changes)\n case \"delete-view\":\n return this.deleteView(operation.viewId)\n }\n }),\n expectedRevision\n )\n return { revision: this.info().revision ?? 0, results }\n }\n\n private logicalMutationFields(\n tableId: string,\n fields: Record<string, EidosFileLogicalValue>,\n id?: string\n ): EidosFileRow {\n const row: Record<string, EidosFileLogicalValue> = id ? { _id: id } : {}\n for (const [fieldId, value] of Object.entries(fields)) {\n const field = this.fieldByKey(tableId, fieldId)\n if (\n field.isDerived ||\n (field.valueKind === \"system\" && field.type !== \"row-id\")\n ) {\n throw new EidosFileError(\n \"invalid-value\",\n `Field ${field.name} is read-only`\n )\n }\n row[field.id!] = value\n }\n return row as unknown as EidosFileRow\n }\n\n mutateRows(input: EidosFileRowsMutation): {\n revision: number | bigint\n rows: EidosFileLogicalRow[]\n deleted: string[]\n /** @internal Exact Runtime affected-row composition, including detach. */\n affected?: Array<{ tableId: string; rowId: string }>\n } {\n const operationCount =\n (input.insert?.length ?? 0) +\n (input.update?.length ?? 0) +\n (input.delete?.length ?? 0)\n if (operationCount === 0) {\n throw new EidosFileError(\n \"invalid-value\",\n \"mutateRows requires at least one operation\"\n )\n }\n if (operationCount > 500) {\n throw new EidosFileError(\n \"resource-limit\",\n \"mutateRows accepts at most 500 row operations per atomic batch\"\n )\n }\n const table = this.getTable(input.tableId)\n const result = this.mutate(() => {\n const operationInstant = this.operationInstant()\n const deleteIds = (input.delete ?? []).map((id) =>\n assertEidosFileUuid(id, \"Row ID\")\n )\n const deleteSet = new Set(deleteIds)\n if (deleteSet.size !== deleteIds.length) {\n throw new EidosFileError(\n \"invalid-value\",\n \"A Row ID may occur only once in one mutation\"\n )\n }\n for (const rowId of deleteIds) {\n const exists = this.connection.get<{ present: number }>(\n `SELECT 1 AS present FROM ${quoteIdentifier(table.physicalName ?? table.rawTableName)} WHERE \"_id\" = ?`,\n [rowId]\n )\n if (!exists) {\n throw new EidosFileError(\"row-not-found\", `Row not found: ${rowId}`)\n }\n }\n\n const preparedUpdates = (input.update ?? []).map((update) => {\n const rowId = assertEidosFileUuid(update.id, \"Row ID\")\n const requestedChanges = this.rowChanges(\n input.tableId,\n this.logicalMutationFields(input.tableId, update.fields),\n false\n )\n const current = this.connection.get<\n Record<string, EidosFileSqlPrimitive>\n >(\n `SELECT * FROM ${quoteIdentifier(table.physicalName ?? table.rawTableName)} WHERE \"_id\" = ?`,\n [rowId]\n )\n if (!current) {\n throw new EidosFileError(\"row-not-found\", `Row not found: ${rowId}`)\n }\n const changes = requestedChanges.filter(\n (change) =>\n !sameSqlValue(current[change.field.physicalName!], change.value)\n )\n return { rowId, requestedChanges, changes }\n })\n\n type DetachAction = {\n tableId: string\n physicalTable: string\n physicalColumn: string\n rowId: string\n value: string\n }\n const detachActions: DetachAction[] = []\n if (deleteSet.size > 0) {\n const schema = this.allSchema()\n const proposedRelationValues = new Map<string, EidosFileSqlPrimitive>()\n for (const update of preparedUpdates) {\n for (const change of update.requestedChanges) {\n if (change.field.type === \"relation\") {\n proposedRelationValues.set(\n `${update.rowId}\\u0000${change.field.id}`,\n change.value\n )\n }\n }\n }\n for (const [fieldId, relation] of schema.relations) {\n if (\n relation.direction !== \"forward\" ||\n uuid(relation.target_table_id) !== input.tableId ||\n relation.on_delete === \"preserve\"\n ) {\n continue\n }\n const field = Array.from(schema.fieldsByTable.values())\n .flat()\n .find((candidate) => candidate.id === fieldId)\n if (!field?.tableId || !field.physicalName) continue\n const sourceTable = schema.tables.get(field.tableId)\n if (!sourceTable) continue\n const sourceRows = this.connection.query<{\n _id: string\n relation_value: string\n }>(\n `SELECT \"_id\", ${quoteIdentifier(field.physicalName)} AS relation_value FROM ${quoteIdentifier(sourceTable.physical_name)} ORDER BY \"_id\" COLLATE BINARY`\n )\n for (const sourceRow of sourceRows) {\n if (\n field.tableId === input.tableId &&\n deleteSet.has(sourceRow._id)\n ) {\n continue\n }\n const proposed = proposedRelationValues.get(\n `${sourceRow._id}\\u0000${fieldId}`\n )\n const raw = proposed ?? sourceRow.relation_value\n if (typeof raw !== \"string\") {\n throw new EidosFileError(\n \"invalid-value\",\n `Relation ${fieldId} has a non-text stored value`\n )\n }\n const parsed = parseEidosFileJson(raw)\n if (!Array.isArray(parsed)) {\n throw new EidosFileError(\n \"invalid-value\",\n `Relation ${fieldId} has a non-array stored value`\n )\n }\n const referenced = parsed.some(\n (entry) => typeof entry === \"string\" && deleteSet.has(entry)\n )\n if (!referenced) continue\n if (relation.on_delete === \"restrict\") {\n throw new EidosFileError(\n \"constraint-conflict\",\n `Relation ${fieldId} restricts deletion of a referenced Row`\n )\n }\n const survivors = parsed.filter(\n (entry) => typeof entry !== \"string\" || !deleteSet.has(entry)\n )\n detachActions.push({\n tableId: field.tableId,\n physicalTable: sourceTable.physical_name,\n physicalColumn: field.physicalName,\n rowId: sourceRow._id,\n value: canonicalizeEidosFileJson(survivors),\n })\n }\n }\n }\n\n const inserted = (input.insert ?? []).map((row) =>\n this.insertRowInTransaction(\n input.tableId,\n this.logicalMutationFields(input.tableId, row.fields, row.id),\n false,\n true\n )\n )\n const changedUpdates: string[] = []\n for (const { rowId, changes } of preparedUpdates) {\n if (changes.length === 0) continue\n const response = this.connection.run(\n `UPDATE ${quoteIdentifier(table.physicalName ?? table.rawTableName)}\n SET ${changes.map((change) => `${quoteIdentifier(change.field.physicalName!)} = ?`).join(\", \")},\n \"_updated_at\" = ?\n WHERE \"_id\" = ?`,\n [...changes.map((change) => change.value), operationInstant, rowId]\n )\n if (response.changes === 0)\n throw new EidosFileError(\"row-not-found\", `Row not found: ${rowId}`)\n changedUpdates.push(rowId)\n }\n for (const detach of detachActions) {\n const response = this.connection.run(\n `UPDATE ${quoteIdentifier(detach.physicalTable)}\n SET ${quoteIdentifier(detach.physicalColumn)} = ?, \"_updated_at\" = ?\n WHERE \"_id\" = ? AND ${quoteIdentifier(detach.physicalColumn)} IS NOT ?`,\n [detach.value, operationInstant, detach.rowId, detach.value]\n )\n if (response.changes === 0) {\n throw new EidosFileError(\n \"stale-revision\",\n \"Relation source changed during composed delete\"\n )\n }\n }\n\n // Deleted source rows are excluded from incoming policy checks. Clearing\n // their outgoing arrays prevents the portable single-row safety triggers\n // from reintroducing order-dependent behavior during the physical delete.\n if (deleteSet.size > 0) {\n const schema = this.allSchema()\n const outgoing = (schema.fieldsByTable.get(input.tableId) ?? []).filter(\n (field) =>\n field.type === \"relation\" &&\n field.physicalName &&\n schema.relations.get(field.id!)?.direction === \"forward\"\n )\n for (const field of outgoing) {\n this.connection.run(\n `UPDATE ${quoteIdentifier(table.physicalName ?? table.rawTableName)} SET ${quoteIdentifier(field.physicalName!)} = '[]' WHERE \"_id\" IN (${deleteIds.map(() => \"?\").join(\",\")})`,\n deleteIds\n )\n }\n }\n const deleted: string[] = []\n for (const rowId of deleteIds) {\n const response = this.connection.run(\n `DELETE FROM ${quoteIdentifier(table.physicalName ?? table.rawTableName)} WHERE \"_id\" = ?`,\n [rowId]\n )\n if (response.changes) deleted.push(rowId)\n }\n return {\n inserted,\n updated: preparedUpdates.map(({ rowId }) => rowId),\n deleted,\n affected: [\n ...inserted.map((rowId) => ({ tableId: input.tableId, rowId })),\n ...changedUpdates.map((rowId) => ({ tableId: input.tableId, rowId })),\n ...deleted.map((rowId) => ({ tableId: input.tableId, rowId })),\n ...detachActions.map(({ tableId, rowId }) => ({ tableId, rowId })),\n ],\n }\n }, input.expectedRevision)\n const requestedIds = [...new Set([...result.inserted, ...result.updated])]\n const queried = this.getLogicalRowsByIds(input.tableId, requestedIds)\n const rowsById = new Map(queried.map((row) => [row.id, row]))\n return {\n revision: this.info().revision ?? 0,\n rows: requestedIds.flatMap((id) => {\n const row = rowsById.get(id)\n return row ? [row] : []\n }),\n deleted: result.deleted,\n affected: Array.from(\n new Map(\n result.affected.map((entry) => [\n `${entry.tableId}\\u0000${entry.rowId}`,\n entry,\n ])\n ).values()\n ).sort((left, right) =>\n left.tableId === right.tableId\n ? left.rowId < right.rowId\n ? -1\n : left.rowId > right.rowId\n ? 1\n : 0\n : left.tableId < right.tableId\n ? -1\n : 1\n ),\n }\n }\n}\n\nfunction fieldValueTypeForScan(\n field: EidosFileFieldInfo\n): string | { kind: \"list\"; element: string } {\n if (field.systemRole === \"row-id\") return \"row-id\"\n if (\n field.systemRole === \"created-time\" ||\n field.systemRole === \"updated-time\"\n ) {\n return \"datetime\"\n }\n const configured = configuredTypeRef(field.property?.valueType)\n if (configured) return configured\n if (field.type === \"lookup\" && field.property?.aggregate === \"values\") {\n const display = String(field.property?.displayType ?? \"text\")\n return {\n kind: \"list\",\n element:\n display === \"file\"\n ? \"file-entry\"\n : display === \"relation\"\n ? \"row-id\"\n : display === \"multi-select\"\n ? \"select\"\n : display,\n }\n }\n if (field.type === \"formula\" || field.type === \"lookup\") {\n const display = String(field.property?.displayType ?? \"text\")\n return display === \"file\" ? \"file-entry\" : display\n }\n return field.type\n}\n"],"mappings":";;AAQA,MAAMA,cAAY,CAA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EACA;EACA;EACA;EACA;EACA;EACA;EACD;CACF;AAED,MAAM,aAAgD;EACnD,wBAAwB,CAAC,WAAW,mBAAmB;EACvD,0BAA0B,CAAC,KAAK;EAChC,0BAA0B,CAAC,MAAM,WAAW;EAC5C,mCAAmC;EAClC;EACA;EACA;EACD;EACA,kCAAkC,CAAC,WAAW;EAC9C,iCAAiC;EAChC;EACA;EACA;EACD;EACA,yBAAyB,CAAC,MAAM,WAAW;CAC7C;AAED,MAAM,mBAAmB,IAAI,IAAI,CAC/B,iCACA,8BACD,CAAC;AAEF,MAAM,oBAAoB,IAAI,IAAI,CAChC,yBACA,4BACD,CAAC;AAEF,MAAM,uBACJ;AACF,MAAM,2BAA2B;AAEjC,MAAM,cAAc,IAAI,IAAwB;CAC9C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,MAAM,qBAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,MAAM,uBAAuB,IAAI,IAAI;CACnC;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,MAAM,uBAAuB,IAAI,IAAI,CAAC,UAAU,UAAU,CAAC;AAC3D,MAAM,wBAAwB,IAAI,IAAI;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AACF,MAAM,mBAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AACF,MAAME,6BAA2B,IAAI,IAAI;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,MAAM,SAAmD;CACvD,UAAU;CACV,YAAY;CACZ,SAAS;CACT,UAAU;CACV,MAAM;CACP;AAED,SAASC,OAAK,OAAgB,OAAuB;AACnD,KAAI,CAAC,gB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