@eidos.space/eidos-file 1.0.0 → 2.0.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 (42) hide show
  1. package/DEVELOPER_PLATFORM.md +17 -11
  2. package/FIELD-CONVERSION.md +75 -0
  3. package/README.md +18 -2
  4. package/dist/{adapter-contract-B3p-48Yb.d.mts → adapter-contract-BRKKEulb.d.mts} +26 -65
  5. package/dist/adapter-contract-BRKKEulb.d.mts.map +1 -0
  6. package/dist/better-sqlite3.d.mts +2 -2
  7. package/dist/better-sqlite3.d.mts.map +1 -1
  8. package/dist/better-sqlite3.mjs +13 -5
  9. package/dist/better-sqlite3.mjs.map +1 -1
  10. package/dist/browser.d.mts +4 -4
  11. package/dist/browser.mjs +3 -3
  12. package/dist/browser.mjs.map +1 -1
  13. package/dist/{csv-WEud-i_H.mjs → csv-BQPkzC5Y.mjs} +18 -8
  14. package/dist/csv-BQPkzC5Y.mjs.map +1 -0
  15. package/dist/csv.d.mts +4 -2
  16. package/dist/csv.d.mts.map +1 -1
  17. package/dist/csv.mjs +1 -1
  18. package/dist/index.d.mts +29 -14
  19. package/dist/index.d.mts.map +1 -1
  20. package/dist/index.mjs +493 -175
  21. package/dist/index.mjs.map +1 -1
  22. package/dist/node-sqlite.d.mts +98 -0
  23. package/dist/node-sqlite.d.mts.map +1 -0
  24. package/dist/node-sqlite.mjs +684 -0
  25. package/dist/node-sqlite.mjs.map +1 -0
  26. package/dist/{runtime-CMdfE7Gx.mjs → runtime-9_adwQ0y.mjs} +287 -126
  27. package/dist/runtime-9_adwQ0y.mjs.map +1 -0
  28. package/dist/{runtime-DCo5E0Kr.d.mts → runtime-C9IcEeTi.d.mts} +67 -7
  29. package/dist/runtime-C9IcEeTi.d.mts.map +1 -0
  30. package/dist/{select-options-DihMTuoa.mjs → select-options-CfNwfc_a.mjs} +123 -80
  31. package/dist/select-options-CfNwfc_a.mjs.map +1 -0
  32. package/dist/{sqlite-wasm-B86yaLG6.mjs → sqlite-wasm-BM6hsxH8.mjs} +14 -7
  33. package/dist/sqlite-wasm-BM6hsxH8.mjs.map +1 -0
  34. package/dist/{temporal-CVzLU63l.d.mts → temporal-fyRCzJjy.d.mts} +3 -3
  35. package/dist/{temporal-CVzLU63l.d.mts.map → temporal-fyRCzJjy.d.mts.map} +1 -1
  36. package/package.json +10 -2
  37. package/dist/adapter-contract-B3p-48Yb.d.mts.map +0 -1
  38. package/dist/csv-WEud-i_H.mjs.map +0 -1
  39. package/dist/runtime-CMdfE7Gx.mjs.map +0 -1
  40. package/dist/runtime-DCo5E0Kr.d.mts.map +0 -1
  41. package/dist/select-options-DihMTuoa.mjs.map +0 -1
  42. package/dist/sqlite-wasm-B86yaLG6.mjs.map +0 -1
@@ -1,4 +1,4 @@
1
- import { A as parseEidosFileJson, C as createEidosFileUuid, E as quoteIdentifier, O as canonicalizeEidosFileJson, T as isEidosFileUuid, a as eidosFileInstantSqlCheck, c as normalizeEidosFileDate, i as eidosFileDateSqlCheck, j as EidosFileError, k as isCanonicalEidosFileJson, l as normalizeEidosFileInstant, o as isCanonicalEidosFileDate, r as currentEidosFileInstant, s as isCanonicalEidosFileInstant, t as assertEidosFileSelectOptions, u as assertEidosFileValues, w as eidosFilePhysicalName, x as assertEidosFileUuid, y as assertEidosFileDisplayName } from "./select-options-DihMTuoa.mjs";
1
+ import { A as isCanonicalEidosFileJson, C as assertEidosFileUuid, D as isEidosFileUuid, E as isEidosFileReservedTableName, M as EidosFileError, O as quoteIdentifier, S as assertEidosFileTableName, T as createEidosFileUuid, a as eidosFileInstantSqlCheck, b as assertEidosFileDisplayName, c as normalizeEidosFileDate, f as decodeEidosFileValues, i as eidosFileDateSqlCheck, j as parseEidosFileJson, k as canonicalizeEidosFileJson, l as normalizeEidosFileInstant, o as isCanonicalEidosFileDate, r as currentEidosFileInstant, s as isCanonicalEidosFileInstant, t as assertEidosFileSelectOptions, u as assertEidosFileValues } from "./select-options-CfNwfc_a.mjs";
2
2
  //#region src/connection-port.ts
3
3
  const INT64_MIN$2 = -9223372036854775808n;
4
4
  const INT64_MAX$2 = 9223372036854775807n;
@@ -157,14 +157,22 @@ function nativeToSqlValue(value) {
157
157
  tag: "text",
158
158
  value: assertUnicodeString(value)
159
159
  };
160
- if (value instanceof Uint8Array) return {
161
- tag: "blob",
162
- value: new Uint8Array(value)
163
- };
164
- if (value instanceof ArrayBuffer) return {
165
- tag: "blob",
166
- value: new Uint8Array(value.slice(0))
167
- };
160
+ if (ArrayBuffer.isView(value) && Object.prototype.toString.call(value) === "[object Uint8Array]") {
161
+ const view = value;
162
+ const bytes = new Uint8Array(view.byteLength);
163
+ bytes.set(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));
164
+ return {
165
+ tag: "blob",
166
+ value: bytes
167
+ };
168
+ }
169
+ if (Object.prototype.toString.call(value) === "[object ArrayBuffer]") {
170
+ const source = new Uint8Array(value);
171
+ return {
172
+ tag: "blob",
173
+ value: new Uint8Array(source)
174
+ };
175
+ }
168
176
  throw new EidosAdapterError("invalid-sql-value", "Unsupported SQLite storage value: " + typeof value, false, true);
169
177
  }
170
178
  /**
@@ -186,6 +194,7 @@ var ConnectionPortEidosFileConnection = class {
186
194
  };
187
195
  }
188
196
  exec(sql) {
197
+ if (sql.trim() === "PRAGMA foreign_keys = ON; PRAGMA trusted_schema = OFF;") return;
189
198
  this.port.execSchema(sql);
190
199
  }
191
200
  query(sql, params = []) {
@@ -291,7 +300,11 @@ const DATE_STATS = [
291
300
  "min",
292
301
  "max"
293
302
  ];
294
- const CHECKBOX_STATS = COMMON_STATS;
303
+ const CHECKBOX_STATS = [
304
+ ...COMMON_STATS,
305
+ "percent-checked",
306
+ "percent-unchecked"
307
+ ];
295
308
  const MULTI_VALUE_STATS = [...COMMON_STATS];
296
309
  const RELATION_STATS = [
297
310
  ...MULTI_VALUE_STATS,
@@ -304,6 +317,8 @@ const LABELS = {
304
317
  "count-non-null": "Count non-null",
305
318
  "count-distinct": "Count distinct",
306
319
  "count-empty": "Count empty",
320
+ "percent-checked": "Percent checked",
321
+ "percent-unchecked": "Percent unchecked",
307
322
  sum: "Sum",
308
323
  average: "Average",
309
324
  min: "Minimum",
@@ -773,6 +788,7 @@ function assertExactFormulaAst(root) {
773
788
  function formulaOperandType(field) {
774
789
  let type;
775
790
  if (field.systemRole === "row-id" || field.type === "row-id") type = "text";
791
+ else if (field.type === "rating") type = "integer";
776
792
  else if (field.systemRole === "created-time" || field.systemRole === "updated-time" || field.type === "created-time" || field.type === "last-edited-time") type = "datetime";
777
793
  else if (field.type === "select") type = "text";
778
794
  else if (field.type === "lookup" && field.property?.aggregate === "values") type = void 0;
@@ -1283,7 +1299,7 @@ function eidosFileLookupTargetDisplayType(target) {
1283
1299
  if (type === "date") return "date";
1284
1300
  if (type === "datetime") return "datetime";
1285
1301
  if (type === "url") return "url";
1286
- if (type === "json" || type === "file") return "json";
1302
+ if (type === "file") return "json";
1287
1303
  return "text";
1288
1304
  }
1289
1305
  function eidosFileLookupDisplayType(aggregate, target) {
@@ -1419,6 +1435,16 @@ function normalizeEidosFileRowQuery(value) {
1419
1435
  function escapeLike(value) {
1420
1436
  return value.replace(/[\\%_]/g, "\\$&");
1421
1437
  }
1438
+ function requiresUnicodeCasefold(value) {
1439
+ const nonAscii = value.replace(/[\x00-\x7f]/g, "");
1440
+ return nonAscii.toUpperCase() !== nonAscii.toLowerCase();
1441
+ }
1442
+ function caseInsensitiveLike(expression, pattern, searchText, params) {
1443
+ params.push(pattern);
1444
+ return requiresUnicodeCasefold(searchText) ? `eidos_casefold(COALESCE(CAST(${expression} AS TEXT), ''))
1445
+ LIKE eidos_casefold(?) ESCAPE '\\'` : `COALESCE(CAST(${expression} AS TEXT), '')
1446
+ LIKE ? COLLATE NOCASE ESCAPE '\\'`;
1447
+ }
1422
1448
  function searchableFields(fields, selected) {
1423
1449
  const selection = selected ? new Set(selected) : null;
1424
1450
  return fields.filter((field) => (!selection || !!field.id && selection.has(field.id)) && !field.isHidden && (field.isRecordLabel || field.valueKind === "source" || field.valueKind === "materialized" || field.valueKind === "derived"));
@@ -1522,18 +1548,15 @@ function likeExpression(field, operator, value, params) {
1522
1548
  ELSE '[]'
1523
1549
  END
1524
1550
  )
1525
- WHERE eidos_casefold(COALESCE(CAST(value AS TEXT), ''))
1526
- LIKE eidos_casefold(?) ESCAPE '\\'
1527
- )` : `eidos_casefold(COALESCE(CAST(${column} AS TEXT), ''))
1528
- LIKE eidos_casefold(?) ESCAPE '\\'`;
1529
- params.push(pattern);
1551
+ WHERE ${caseInsensitiveLike("value", pattern, value, params)}
1552
+ )` : `COALESCE(${caseInsensitiveLike(column, pattern, value, params)}, 0)`;
1530
1553
  return operator === "not-contains" ? `NOT (${expression})` : expression;
1531
1554
  }
1532
1555
  function compileRule(rule, fields, params) {
1533
1556
  const field = requireField(fields, rule.field);
1534
1557
  const column = quoteIdentifier(field.tableColumnName);
1535
1558
  const arrayCodec = field.storageCodec === "json_array" || field.storageCodec === "relation";
1536
- const empty = arrayCodec ? `(json_valid(${column}) AND json_type(${column}) = 'array' AND json_array_length(${column}) = 0)` : `(${column} IS NULL)`;
1559
+ const empty = arrayCodec ? `(${column} IS NULL OR (json_valid(${column}) AND json_type(${column}) = 'array' AND json_array_length(${column}) = 0))` : `(${column} IS NULL)`;
1537
1560
  if (rule.operator === "is-empty") return empty;
1538
1561
  if (rule.operator === "is-not-empty") return `NOT ${empty}`;
1539
1562
  if (rule.operator === "is-any-of" || rule.operator === "is-all-of" || rule.operator === "is-none-of") {
@@ -1558,18 +1581,18 @@ function compileRule(rule, fields, params) {
1558
1581
  }
1559
1582
  params.push(...values.map((entry) => sqlFieldValue(field, entry)));
1560
1583
  if (rule.operator === "is-all-of") return "0";
1561
- const expression = `${column} IN (${values.map(() => "?").join(", ")})`;
1584
+ const expression = `COALESCE(${column} IN (${values.map(() => "?").join(", ")}), 0)`;
1562
1585
  return rule.operator === "is-none-of" ? `NOT (${expression})` : expression;
1563
1586
  }
1564
1587
  const value = Array.isArray(rule.value) ? rule.value[0] : rule.value;
1565
1588
  if (rule.operator === "equals" || rule.operator === "not-equals") {
1566
1589
  if (arrayCodec && Array.isArray(rule.value)) {
1567
- params.push(JSON.stringify(rule.value.map(sqlValue)));
1568
- return rule.operator === "not-equals" ? `${column} <> ?` : `${column} = ?`;
1590
+ params.push(canonicalizeEidosFileJson(rule.value));
1591
+ return rule.operator === "not-equals" ? `${column} IS NOT ?` : `${column} IS ?`;
1569
1592
  }
1570
1593
  if (value === null || value === void 0) return `${column} IS ${rule.operator === "not-equals" ? "NOT " : ""}NULL`;
1571
1594
  params.push(sqlFieldValue(field, value));
1572
- return rule.operator === "not-equals" ? `${column} <> ?` : `${column} = ?`;
1595
+ return rule.operator === "not-equals" ? `${column} IS NOT ?` : `${column} IS ?`;
1573
1596
  }
1574
1597
  if (rule.operator === "contains" || rule.operator === "not-contains" || rule.operator === "starts-with" || rule.operator === "ends-with") return likeExpression(field, rule.operator, String(value ?? ""), params);
1575
1598
  if (value === null || value === void 0) return "0";
@@ -1581,7 +1604,7 @@ function compileRule(rule, fields, params) {
1581
1604
  }[rule.operator];
1582
1605
  if (!comparison) return "0";
1583
1606
  params.push(sqlFieldValue(field, value));
1584
- return `${column} ${comparison} ?`;
1607
+ return `COALESCE(${column} ${comparison} ?, 0)`;
1585
1608
  }
1586
1609
  function compileGroup(group, fields, params) {
1587
1610
  const children = group.children.map((child) => child.type === "group" ? compileGroup(child, fields, params) : compileRule(child, fields, params));
@@ -1614,11 +1637,7 @@ function compileEidosFileRowQuery(fields, query = {}) {
1614
1637
  const search = query.search;
1615
1638
  if (search !== void 0 && search !== "") {
1616
1639
  const pattern = `%${escapeLike(search)}%`;
1617
- const searchClauses = searchableFields(fields, query.searchFields).map((field) => {
1618
- params.push(pattern);
1619
- return `eidos_casefold(COALESCE(CAST(${quoteIdentifier(field.tableColumnName)} AS TEXT), ''))
1620
- LIKE eidos_casefold(?) ESCAPE '\\'`;
1621
- });
1640
+ const searchClauses = searchableFields(fields, query.searchFields).map((field) => caseInsensitiveLike(quoteIdentifier(field.tableColumnName), pattern, search, params));
1622
1641
  if (searchClauses.length > 0) where.push(`(${searchClauses.join(" OR ")})`);
1623
1642
  }
1624
1643
  if (query.filter) where.push(compileGroup(query.filter, byColumn, params));
@@ -2034,10 +2053,6 @@ function decodeLookupAtom(value, type) {
2034
2053
  return Object.is(number, -0) ? 0 : number;
2035
2054
  }
2036
2055
  if (type === "checkbox") return value === true || value === 1;
2037
- if (type === "json") {
2038
- const source = typeof value === "string" ? value : JSON.stringify(value);
2039
- return canonicalizeEidosFileJson(JSON.parse(source));
2040
- }
2041
2056
  if (type === "file-entry") {
2042
2057
  const object = typeof value === "string" ? JSON.parse(value) : value;
2043
2058
  if (!object || typeof object !== "object" || Array.isArray(object)) throw new TypeError("Invalid File entry");
@@ -2049,7 +2064,6 @@ function decodeLookupAtom(value, type) {
2049
2064
  function publicLookupAtom(value, type) {
2050
2065
  if (value === null) return null;
2051
2066
  if (type === "integer") return String(value);
2052
- if (type === "json") return String(value);
2053
2067
  return value;
2054
2068
  }
2055
2069
  function sqlLookupAtom(value, type) {
@@ -2147,11 +2161,14 @@ CREATE TABLE eidos__tables(
2147
2161
  AND substr(id,20,1) IN ('8','9','a','b') AND substr(id,24,1)='-'
2148
2162
  AND lower(id)=id AND length(CAST(replace(id,'-','') AS BLOB))=32
2149
2163
  AND replace(id,'-','') NOT GLOB '*[^0-9a-f]*'),
2150
- name TEXT NOT NULL
2151
- CHECK(length(CAST(name AS BLOB)) BETWEEN 1 AND 1024 AND instr(name,char(0))=0),
2164
+ name TEXT NOT NULL COLLATE NOCASE UNIQUE
2165
+ CHECK(length(CAST(name AS BLOB)) BETWEEN 1 AND 1024
2166
+ AND instr(name,char(0))=0
2167
+ AND lower(substr(name,1,7)) NOT IN ('sqlite_','eidos__')),
2152
2168
  physical_name TEXT NOT NULL COLLATE NOCASE UNIQUE
2153
2169
  CHECK(length(CAST(physical_name AS BLOB)) BETWEEN 1 AND 1024
2154
- AND instr(physical_name,char(0))=0),
2170
+ AND instr(physical_name,char(0))=0
2171
+ AND physical_name COLLATE BINARY = name COLLATE BINARY),
2155
2172
  label_field_id TEXT NOT NULL COLLATE BINARY,
2156
2173
  position INTEGER NOT NULL DEFAULT 0,
2157
2174
  settings_json TEXT NOT NULL DEFAULT '{}'
@@ -2189,7 +2206,8 @@ CREATE TABLE eidos__fields(
2189
2206
  physical_name TEXT COLLATE NOCASE
2190
2207
  CHECK(physical_name IS NULL OR
2191
2208
  (length(CAST(physical_name AS BLOB)) BETWEEN 1 AND 1024
2192
- AND instr(physical_name,char(0))=0)),
2209
+ AND instr(physical_name,char(0))=0
2210
+ AND physical_name COLLATE BINARY = name COLLATE BINARY)),
2193
2211
  type TEXT NOT NULL CHECK(type IN (
2194
2212
  'text','number','integer','checkbox','date','datetime','url','json',
2195
2213
  'select','multi-select','file','relation','formula','lookup'
@@ -2409,6 +2427,41 @@ function setEidosFileMetadata(connection, entries) {
2409
2427
  /** Compatibility constant retained for existing callers. */
2410
2428
  const EIDOS_FILE_FORMAT_VERSION_TEXT = "1.0";
2411
2429
  //#endregion
2430
+ //#region src/stable-row-scan.ts
2431
+ const DEFAULT_STABLE_ROW_PAGE_SIZE = 256;
2432
+ function isQueryResultLimit(error) {
2433
+ return typeof error === "object" && error !== null && "code" in error && error.code === "resource-limit" && "message" in error && typeof error.message === "string" && /Query result exceeds maxResult(?:Rows|Bytes)/.test(error.message);
2434
+ }
2435
+ /**
2436
+ * Reads a whole user Table without asking an Adapter to materialize the whole
2437
+ * result at once. Pages follow the canonical binary Row-ID order, and shrink
2438
+ * automatically when a page is still too large for the active Adapter.
2439
+ */
2440
+ function scanStableRowPages(connection, options, visit) {
2441
+ let afterRowId = null;
2442
+ let pageSize = Math.max(1, Math.floor(options.pageSize ?? DEFAULT_STABLE_ROW_PAGE_SIZE));
2443
+ while (true) {
2444
+ let page;
2445
+ while (true) {
2446
+ const where = afterRowId === null ? "" : ` WHERE ${options.rowIdSql} COLLATE BINARY > ?`;
2447
+ const bindings = afterRowId === null ? [pageSize] : [afterRowId, pageSize];
2448
+ try {
2449
+ page = connection.query(`SELECT ${options.columnsSql} FROM ${options.tableSql}${where} ORDER BY ${options.rowIdSql} COLLATE BINARY LIMIT ?`, bindings);
2450
+ break;
2451
+ } catch (error) {
2452
+ if (!isQueryResultLimit(error) || pageSize === 1) throw error;
2453
+ pageSize = Math.max(1, Math.floor(pageSize / 2));
2454
+ }
2455
+ }
2456
+ if (page.length === 0) return;
2457
+ visit(page);
2458
+ const nextRowId = page.at(-1)?.[options.rowIdKey];
2459
+ if (typeof nextRowId !== "string" || nextRowId === afterRowId) throw new Error("Stable row scan requires unique text Row IDs");
2460
+ afterRowId = nextRowId;
2461
+ if (page.length < pageSize) return;
2462
+ }
2463
+ }
2464
+ //#endregion
2412
2465
  //#region src/dependency-graph.ts
2413
2466
  /** Returns the globally smallest normalized simple directed cycle. */
2414
2467
  function smallestDependencyCycle(graph) {
@@ -2536,7 +2589,6 @@ const FIELD_TYPES = new Set([
2536
2589
  "datetime",
2537
2590
  "url",
2538
2591
  "file",
2539
- "json",
2540
2592
  "select",
2541
2593
  "multi-select",
2542
2594
  "relation",
@@ -2560,8 +2612,7 @@ const FORMULA_RESULT_TYPES = new Set([
2560
2612
  "checkbox",
2561
2613
  "date",
2562
2614
  "datetime",
2563
- "url",
2564
- "json"
2615
+ "url"
2565
2616
  ]);
2566
2617
  const NUMERIC_LOOKUP_TYPES = new Set(["number", "integer"]);
2567
2618
  const FILTER_OPERATORS = new Set([
@@ -2605,32 +2656,8 @@ function valueKind(field, relation) {
2605
2656
  if (field.type === "relation") return relation?.direction === "inverse" ? "derived" : "relation";
2606
2657
  return "source";
2607
2658
  }
2608
- function validPhysicalMapping(kind, name, physicalName, id) {
2609
- const folded = name.replace(/[A-Z]/g, (character) => character.toLowerCase());
2610
- const reserved = kind === "table" ? [
2611
- "sqlite_",
2612
- "eidos__",
2613
- "x__"
2614
- ].some((prefix) => folded.startsWith(prefix)) : [
2615
- "_id",
2616
- "_created_at",
2617
- "_updated_at"
2618
- ].includes(folded);
2619
- const hex = id.replace(/-/g, "");
2620
- if (kind === "table" && reserved) return [
2621
- 8,
2622
- 12,
2623
- 32
2624
- ].some((length) => {
2625
- const prefix = `t__${hex.slice(0, length)}__`;
2626
- return physicalName.startsWith(prefix) && new TextEncoder().encode(physicalName).byteLength <= 1024;
2627
- });
2628
- if (physicalName === name) return !reserved;
2629
- return [
2630
- 8,
2631
- 12,
2632
- 32
2633
- ].some((length) => physicalName === `${name}__${hex.slice(0, length)}`);
2659
+ function validPhysicalMapping(kind, name, physicalName) {
2660
+ return physicalName === name && (kind === "field" || !isEidosFileReservedTableName(name));
2634
2661
  }
2635
2662
  function expectedColumnType(type) {
2636
2663
  if ([
@@ -2640,7 +2667,6 @@ function expectedColumnType(type) {
2640
2667
  "date",
2641
2668
  "datetime",
2642
2669
  "file",
2643
- "json",
2644
2670
  "multi-select",
2645
2671
  "relation"
2646
2672
  ].includes(type)) return "TEXT";
@@ -2760,6 +2786,7 @@ function validateEidosFile(connection, options = {}) {
2760
2786
  const tableRows = sqliteTables.has("eidos__tables") ? connection.query(`SELECT * FROM ${EIDOS_FILE_TABLES_TABLE} ORDER BY position, id`) : [];
2761
2787
  const tables = [];
2762
2788
  const tableRowsById = /* @__PURE__ */ new Map();
2789
+ const tableNames = /* @__PURE__ */ new Set();
2763
2790
  for (const row of tableRows) try {
2764
2791
  const id = uuid$1(row.id, "Table ID");
2765
2792
  tableRowsById.set(id, row);
@@ -2778,7 +2805,10 @@ function validateEidosFile(connection, options = {}) {
2778
2805
  });
2779
2806
  if (!isCanonicalEidosFileInstant(row.created_at) || !isCanonicalEidosFileInstant(row.updated_at)) add(errors, "invalid-schema", `Table ${row.name} metadata timestamps are not canonical instants`, row.physical_name);
2780
2807
  if (!isCanonicalEidosFileJson(row.settings_json)) add(errors, "invalid-schema", `Table ${row.name} has non-canonical settings_json`, row.physical_name);
2781
- if (!validPhysicalMapping("table", row.name, row.physical_name, id)) add(errors, "invalid-schema", `Table ${row.name} has an invalid physical name`, row.physical_name);
2808
+ const foldedTableName = row.name.replace(/[A-Z]/g, (character) => character.toLowerCase());
2809
+ if (tableNames.has(foldedTableName)) add(errors, "invalid-schema", `Duplicate Table name under SQLite NOCASE: ${row.name}`, row.physical_name);
2810
+ tableNames.add(foldedTableName);
2811
+ if (!validPhysicalMapping("table", row.name, row.physical_name)) add(errors, "invalid-schema", `Table ${row.name} has an invalid physical name`, row.physical_name);
2782
2812
  const tableObject = sqliteTables.get(row.physical_name);
2783
2813
  if (!tableObject) add(errors, "invalid-schema", `Missing user table ${row.physical_name}`, row.physical_name);
2784
2814
  else if (!/\bSTRICT\b/i.test(tableObject.sql ?? "")) add(errors, "invalid-schema", `User table ${row.physical_name} must be STRICT`, row.physical_name);
@@ -2827,8 +2857,7 @@ function validateEidosFile(connection, options = {}) {
2827
2857
  if (requiresNonNull && row.nullable !== 0 || requiresNullable && row.nullable !== 1) add(errors, "invalid-schema", `Field ${row.name} has invalid nullable metadata for ${row.type}`);
2828
2858
  if (virtual && row.physical_name !== null) add(errors, "invalid-schema", `Virtual Field ${row.name} must not have a physical column`);
2829
2859
  if (!virtual && row.physical_name === null) add(errors, "invalid-schema", `Stored Field ${row.name} requires a physical column`);
2830
- const systemMapping = row.system_role === "row-id" && row.type === "text" && row.physical_name === "_id" && row.nullable === 0 || row.system_role === "created-time" && row.type === "datetime" && row.physical_name === "_created_at" && row.nullable === 0 || row.system_role === "updated-time" && row.type === "datetime" && row.physical_name === "_updated_at" && row.nullable === 0;
2831
- if (row.physical_name && !systemMapping && !validPhysicalMapping("field", row.name, row.physical_name, id)) add(errors, "invalid-schema", `Field ${row.name} has an invalid physical name`);
2860
+ if (row.physical_name && !validPhysicalMapping("field", row.name, row.physical_name)) add(errors, "invalid-schema", `Field ${row.name} has an invalid physical name`);
2832
2861
  const formula = formulas.get(id);
2833
2862
  const lookup = lookups.get(id);
2834
2863
  const property = formula ? {
@@ -2882,8 +2911,26 @@ function validateEidosFile(connection, options = {}) {
2882
2911
  ["last-edited-time", "_updated_at"]
2883
2912
  ]) if (fields.filter((field) => field.type === type && field.physicalName === physicalName).length !== 1) add(errors, "invalid-schema", `Table ${table.name} must register exactly one ${type} Field mapped to ${physicalName}`);
2884
2913
  const mappedNames = fields.flatMap((field) => field.physicalName ? [field.physicalName] : []);
2914
+ const displayNames = fields.map((field) => field.name);
2915
+ if (new Set(displayNames.map((name) => name.replace(/[A-Z]/g, (character) => character.toLowerCase()))).size !== displayNames.length) add(errors, "invalid-schema", `Table ${table.name} contains duplicate Field names under SQLite NOCASE`);
2885
2916
  if (new Set(mappedNames.map((name) => name.replace(/[A-Z]/g, (character) => character.toLowerCase()))).size !== mappedNames.length) add(errors, "invalid-schema", `Table ${table.name} maps more than one Field to a physical column`);
2886
2917
  }
2918
+ if (sqliteTables.has("eidos__views")) {
2919
+ const viewNamesByTable = /* @__PURE__ */ new Map();
2920
+ for (const view of connection.query(`SELECT id, table_id, name FROM ${EIDOS_FILE_VIEWS_TABLE}`)) try {
2921
+ uuid$1(view.id, "View ID");
2922
+ const tableId = uuid$1(view.table_id, "View Table ID");
2923
+ assertEidosFileDisplayName(view.name, "View name");
2924
+ if (!tableRowsById.has(tableId)) throw new Error("View references an unknown Table");
2925
+ const foldedName = view.name.replace(/[A-Z]/g, (character) => character.toLowerCase());
2926
+ const names = viewNamesByTable.get(tableId) ?? /* @__PURE__ */ new Set();
2927
+ if (names.has(foldedName)) add(errors, "invalid-schema", `Table ${tableRowsById.get(tableId).name} contains duplicate View names under SQLite NOCASE`);
2928
+ names.add(foldedName);
2929
+ viewNamesByTable.set(tableId, names);
2930
+ } catch (error) {
2931
+ add(errors, "invalid-schema", error instanceof Error ? error.message : "Invalid View metadata");
2932
+ }
2933
+ }
2887
2934
  const triggerObjects = new Map(sqliteObjects.filter((object) => object.type === "trigger").map((object) => [object.name, object]));
2888
2935
  const expectedTriggers = /* @__PURE__ */ new Map();
2889
2936
  for (const [tableId, table] of tableRowsById) expectedTriggers.set(`eidos__row_id_immutable__${tableId.replace(/-/g, "")}`, {
@@ -3174,16 +3221,16 @@ function validateEidosFile(connection, options = {}) {
3174
3221
  "last-edited-time"
3175
3222
  ].includes(field.type) && !isCanonicalEidosFileInstant(value)) add(errors, "invalid-value", `${table.name}.${field.name} must be canonical UTC millisecond text`);
3176
3223
  if (["multi-select", "file"].includes(field.type)) {
3177
- const parsed = typeof value === "string" && isCanonicalEidosFileJson(value) ? parseEidosFileJson(value) : null;
3178
- if (!Array.isArray(parsed)) add(errors, "invalid-value", `${table.name}.${field.name} must be a canonical JSON array`);
3179
- if (field.type === "multi-select" && Array.isArray(parsed) && (!parsed.every((entry) => typeof entry === "string") || new Set(parsed).size !== parsed.length)) add(errors, "invalid-value", `${table.name}.${field.name} must be a unique string array`);
3180
- if (field.type === "file" && Array.isArray(parsed)) try {
3181
- assertEidosFileValues(parsed);
3224
+ let parsed = null;
3225
+ if (field.type === "file" && typeof value === "string") try {
3226
+ parsed = decodeEidosFileValues(value);
3182
3227
  } catch (error) {
3183
3228
  add(errors, "invalid-value", `${table.name}.${field.name}: ${error instanceof Error ? error.message : "invalid File value"}`);
3184
3229
  }
3230
+ else if (typeof value === "string" && isCanonicalEidosFileJson(value)) parsed = parseEidosFileJson(value);
3231
+ if (!Array.isArray(parsed)) add(errors, "invalid-value", `${table.name}.${field.name} must be a canonical JSON array`);
3232
+ if (field.type === "multi-select" && Array.isArray(parsed) && (!parsed.every((entry) => typeof entry === "string") || new Set(parsed).size !== parsed.length)) add(errors, "invalid-value", `${table.name}.${field.name} must be a unique string array`);
3185
3233
  }
3186
- if (field.type === "json" && (typeof value !== "string" || !isCanonicalEidosFileJson(value))) add(errors, "invalid-value", `${table.name}.${field.name} must be canonical JSON`);
3187
3234
  if (field.type === "relation") {
3188
3235
  const ids = relationIds(value);
3189
3236
  const relation = relations.get(field.id);
@@ -3226,6 +3273,9 @@ function sameSqlValue(left, right) {
3226
3273
  if ((typeof left === "number" || typeof left === "bigint") && (typeof right === "number" || typeof right === "bigint") && (typeof left === "bigint" || Number.isInteger(left)) && (typeof right === "bigint" || Number.isInteger(right))) return BigInt(left) === BigInt(right);
3227
3274
  return Object.is(left, right);
3228
3275
  }
3276
+ function systemFieldsLast(fields) {
3277
+ return [...fields.filter((field) => field.systemRole === null || field.systemRole === void 0), ...fields.filter((field) => field.systemRole !== null && field.systemRole !== void 0)];
3278
+ }
3229
3279
  const SYSTEM_FIELD_NAMES = {
3230
3280
  "row-id": "_id",
3231
3281
  "created-time": "_created_at",
@@ -3306,7 +3356,6 @@ function fieldColumnSql(field) {
3306
3356
  case "datetime": return `${column} TEXT${field.nullable ? "" : " NOT NULL"} CHECK(${eidosFileInstantSqlCheck(column)})`;
3307
3357
  case "rating": return `${column} INTEGER`;
3308
3358
  case "checkbox": return `${column} INTEGER${field.nullable ? "" : " NOT NULL"} CHECK(${column} IS NULL OR ${column} IN (0, 1))`;
3309
- case "json": return `${column} TEXT${field.nullable ? "" : " NOT NULL"} CHECK(${column} IS NULL OR json_valid(${column}))`;
3310
3359
  case "file":
3311
3360
  case "multi-select":
3312
3361
  case "relation": return `${column} TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(${column}) AND json_type(${column}) = 'array')`;
@@ -3780,20 +3829,17 @@ var EidosFileRuntime = class {
3780
3829
  const firstScalar = userFields.find((field) => LABEL_TYPES.has(field.type) && !isVirtualField(field.type, field.input));
3781
3830
  (firstScalar ?? system[0]).isRecordLabel = true;
3782
3831
  }
3783
- const existing = new Set(system.map((field) => field.physicalName));
3784
3832
  for (const field of userFields) {
3785
3833
  if (isVirtualField(field.type, field.input)) continue;
3786
- field.physicalName = eidosFilePhysicalName("field", field.name, field.id, existing);
3787
- existing.add(field.physicalName);
3834
+ field.physicalName = field.name;
3788
3835
  }
3789
3836
  return [...system, ...userFields];
3790
3837
  }
3791
3838
  createTable(input) {
3792
- assertEidosFileDisplayName(input.name, "Table name");
3839
+ const physicalName = assertEidosFileTableName(input.name);
3840
+ if (this.listTables().some((table) => table.name.replace(/[A-Z]/g, (character) => character.toLowerCase()) === input.name.replace(/[A-Z]/g, (character) => character.toLowerCase()))) throw new EidosFileError("constraint-conflict", `Duplicate Table name: ${input.name}`);
3793
3841
  const tableId = input.id ?? this.allocateId();
3794
3842
  assertEidosFileUuid(tableId, "Table ID");
3795
- const existing = this.listTables().map((table) => table.physicalName ?? table.rawTableName);
3796
- const physicalName = eidosFilePhysicalName("table", input.name, tableId, existing);
3797
3843
  const fields = this.prepareFields(input);
3798
3844
  const position = this.listTables().length;
3799
3845
  return this.mutate(() => {
@@ -3832,7 +3878,7 @@ var EidosFileRuntime = class {
3832
3878
  for (const field of fields) if (field.type === "relation" && field.input) this.installRelationTriggers(field.id);
3833
3879
  if (input.createDefaultView !== false) {
3834
3880
  const viewId = this.allocateId();
3835
- const fieldOrder = fields.map((field) => field.id);
3881
+ const fieldOrder = systemFieldsLast(fields).map((field) => field.id);
3836
3882
  this.connection.run(`INSERT INTO ${EIDOS_FILE_VIEWS_TABLE}
3837
3883
  (id, table_id, name, type, query_json, layout_json, position, created_at, updated_at)
3838
3884
  VALUES (?, ?, ?, 'grid', '{}', ?, 0, ?, ?)`, [
@@ -4015,15 +4061,16 @@ var EidosFileRuntime = class {
4015
4061
  let name = table.name;
4016
4062
  let physicalName = table.physicalName ?? table.rawTableName;
4017
4063
  if (changes.name !== void 0 && changes.name !== table.name) {
4018
- name = assertEidosFileDisplayName(changes.name, "Table name");
4019
- physicalName = eidosFilePhysicalName("table", name, tableId, this.listTables().filter((candidate) => candidate.id !== tableId).map((candidate) => candidate.physicalName ?? candidate.rawTableName));
4064
+ name = assertEidosFileTableName(changes.name);
4065
+ if (this.listTables().some((candidate) => candidate.id !== tableId && candidate.name.replace(/[A-Z]/g, (character) => character.toLowerCase()) === name.replace(/[A-Z]/g, (character) => character.toLowerCase()))) throw new EidosFileError("constraint-conflict", `Duplicate Table name: ${name}`);
4066
+ physicalName = name;
4020
4067
  if (physicalName !== (table.physicalName ?? table.rawTableName)) {
4021
4068
  const previousPhysicalName = table.physicalName ?? table.rawTableName;
4022
4069
  if (previousPhysicalName !== physicalName && previousPhysicalName.replace(/[A-Z]/g, (character) => character.toLowerCase()) === physicalName.replace(/[A-Z]/g, (character) => character.toLowerCase())) {
4023
- const baseTemporary = `t__rename__${tableId.replace(/-/g, "")}`;
4070
+ const baseTemporary = `eidos__rename_table__${tableId.replace(/-/g, "")}`;
4024
4071
  let temporary = baseTemporary;
4025
4072
  let suffix = 0;
4026
- const occupied = new Set(this.listTables().map((candidate) => (candidate.physicalName ?? candidate.rawTableName).replace(/[A-Z]/g, (character) => character.toLowerCase())));
4073
+ const occupied = new Set(this.connection.query("SELECT name FROM sqlite_schema").map((object) => object.name.replace(/[A-Z]/g, (character) => character.toLowerCase())));
4027
4074
  while (occupied.has(temporary.toLowerCase())) {
4028
4075
  suffix += 1;
4029
4076
  temporary = `${baseTemporary}__${suffix}`;
@@ -4065,7 +4112,7 @@ var EidosFileRuntime = class {
4065
4112
  const type = canonicalFieldType(input);
4066
4113
  const fields = this.listFields(tableId);
4067
4114
  if (fields.some((field) => field.name.replace(/[A-Z]/g, (character) => character.toLowerCase()) === input.name.replace(/[A-Z]/g, (character) => character.toLowerCase()))) throw new EidosFileError("constraint-conflict", `Duplicate Field name: ${input.name}`);
4068
- const physicalName = isVirtualField(type, input) ? null : eidosFilePhysicalName("field", input.name, id, fields.flatMap((field) => field.physicalName ? [field.physicalName] : []));
4115
+ const physicalName = isVirtualField(type, input) ? null : input.name;
4069
4116
  const prepared = {
4070
4117
  id,
4071
4118
  name: input.name,
@@ -4133,10 +4180,9 @@ var EidosFileRuntime = class {
4133
4180
  let physicalName = field.physicalName ?? null;
4134
4181
  if (changes.name !== void 0 && changes.name !== field.name) {
4135
4182
  name = assertEidosFileDisplayName(changes.name, "Field name");
4136
- const fields = this.listFields(tableId);
4137
- if (fields.some((candidate) => candidate.id !== field.id && candidate.name.replace(/[A-Z]/g, (character) => character.toLowerCase()) === name.replace(/[A-Z]/g, (character) => character.toLowerCase()))) throw new EidosFileError("constraint-conflict", `Duplicate Field name: ${name}`);
4183
+ if (this.listFields(tableId).some((candidate) => candidate.id !== field.id && candidate.name.replace(/[A-Z]/g, (character) => character.toLowerCase()) === name.replace(/[A-Z]/g, (character) => character.toLowerCase()))) throw new EidosFileError("constraint-conflict", `Duplicate Field name: ${name}`);
4138
4184
  if (field.physicalName) {
4139
- physicalName = eidosFilePhysicalName("field", name, fieldId, fields.filter((candidate) => candidate.id !== field.id).flatMap((candidate) => candidate.physicalName ? [candidate.physicalName] : []));
4185
+ physicalName = name;
4140
4186
  if (physicalName !== field.physicalName) this.connection.exec(`ALTER TABLE ${quoteIdentifier(table.physicalName ?? table.rawTableName)} RENAME COLUMN ${quoteIdentifier(field.physicalName)} TO ${quoteIdentifier(physicalName)}`);
4141
4187
  }
4142
4188
  const formulaRows = this.connection.query(`SELECT formula.field_id, formula.source_text
@@ -4314,6 +4360,21 @@ var EidosFileRuntime = class {
4314
4360
  });
4315
4361
  }
4316
4362
  /** @internal Applies a preflighted Runtime 1.0 stored-type conversion. */
4363
+ convertStoredFieldMetadataOnly(fieldId, targetType, nullable) {
4364
+ const field = Array.from(this.allSchema().fields.values()).find((candidate) => candidate.id === fieldId);
4365
+ if (!field || !field.physicalName || ![
4366
+ "text",
4367
+ "select",
4368
+ "url"
4369
+ ].includes(field.type) || (field.nullable ?? false) !== nullable) throw new EidosFileError("invalid-schema", "Metadata-only conversion requires an unchanged Text, Select, or URL storage shape");
4370
+ return this.mutate(() => {
4371
+ this.connection.run(`UPDATE ${EIDOS_FILE_FIELDS_TABLE} SET type = ? WHERE id = ?`, [targetType, fieldId]);
4372
+ this.connection.run(`UPDATE ${EIDOS_FILE_TABLES_TABLE} SET updated_at = ? WHERE id = ?`, [this.operationInstant(), field.tableId]);
4373
+ this.schemaCache = void 0;
4374
+ return this.fieldByKey(field.tableId, fieldId);
4375
+ });
4376
+ }
4377
+ /** @internal Applies a preflighted Runtime 1.0 stored-type conversion. */
4317
4378
  convertStoredField(fieldId, targetType, nullable, rows, relation) {
4318
4379
  const field = Array.from(this.allSchema().fields.values()).find((candidate) => candidate.id === fieldId);
4319
4380
  if (!field || field.systemRole || !field.physicalName || ["formula", "lookup"].includes(field.type) || [
@@ -4368,8 +4429,8 @@ var EidosFileRuntime = class {
4368
4429
  systemRole: field.systemRole ?? null,
4369
4430
  nullable: field.nullable ?? false
4370
4431
  }));
4371
- const temporary = this.transientTableName("t__rebuild__" + tableId.replace(/-/g, ""));
4372
- const staging = this.transientTableName("t__rebuild_old__" + tableId.replace(/-/g, ""));
4432
+ const temporary = this.transientTableName("eidos__rebuild_table__" + tableId.replace(/-/g, ""));
4433
+ const staging = this.transientTableName("eidos__rebuild_old_table__" + tableId.replace(/-/g, ""));
4373
4434
  const relationFieldIds = Array.from(new Set([...relationFieldIdsBefore ?? [], ...Array.from(this.allSchema().relations.keys())]));
4374
4435
  for (const relationFieldId of relationFieldIds) this.dropRelationTriggers(relationFieldId);
4375
4436
  const organization = this.connection.get("SELECT sql FROM sqlite_schema WHERE type='table' AND name=?", [physicalName])?.sql;
@@ -4377,20 +4438,27 @@ var EidosFileRuntime = class {
4377
4438
  this.connection.exec("CREATE TABLE " + quoteIdentifier(temporary) + " (" + definitions.join(", ") + `) STRICT${withoutRowid ? ", WITHOUT ROWID" : ""}`);
4378
4439
  const columns = stored.map((field) => quoteIdentifier(field.physicalName));
4379
4440
  if (transformed) {
4380
- const parameterSets = this.connection.query(`SELECT * FROM ${quoteIdentifier(physicalName)} ORDER BY "_id" COLLATE BINARY`).map((row) => {
4381
- const rowId = String(row._id);
4382
- const conversion = transformed.rows.get(rowId);
4383
- if (!conversion) throw new EidosFileError("stale-revision", "Conversion row set changed before apply");
4384
- return stored.map((storedField) => {
4385
- if (storedField.id === transformed.fieldId) return conversion.value;
4386
- if (storedField.systemRole === "updated-time" && conversion.changed) return this.operationInstant();
4387
- return row[storedField.physicalName];
4388
- });
4389
- });
4390
4441
  const placeholders = columns.map(() => "?").join(", ");
4391
4442
  const sql = `INSERT INTO ${quoteIdentifier(temporary)} (${columns.join(", ")}) VALUES (${placeholders})`;
4392
- if (this.connection.runMany) this.connection.runMany(sql, parameterSets);
4393
- else for (const parameters of parameterSets) this.connection.run(sql, parameters);
4443
+ scanStableRowPages(this.connection, {
4444
+ columnsSql: "*",
4445
+ tableSql: quoteIdentifier(physicalName),
4446
+ rowIdSql: `"_id"`,
4447
+ rowIdKey: "_id"
4448
+ }, (sourceRows) => {
4449
+ const parameterSets = sourceRows.map((row) => {
4450
+ const rowId = String(row._id);
4451
+ const conversion = transformed.rows.get(rowId);
4452
+ if (!conversion) throw new EidosFileError("stale-revision", "Conversion row set changed before apply");
4453
+ return stored.map((storedField) => {
4454
+ if (storedField.id === transformed.fieldId) return conversion.value;
4455
+ if (storedField.systemRole === "updated-time" && conversion.changed) return this.operationInstant();
4456
+ return row[storedField.physicalName];
4457
+ });
4458
+ });
4459
+ if (this.connection.runMany) this.connection.runMany(sql, parameterSets);
4460
+ else for (const parameters of parameterSets) this.connection.run(sql, parameters);
4461
+ });
4394
4462
  } else this.connection.exec("INSERT INTO " + quoteIdentifier(temporary) + " (" + columns.join(", ") + ") SELECT " + columns.join(", ") + " FROM " + quoteIdentifier(physicalName));
4395
4463
  this.connection.exec(`DROP TRIGGER IF EXISTS ${quoteIdentifier(`eidos__row_id_immutable__${tableId.replace(/-/g, "")}`)}`);
4396
4464
  this.connection.exec(`ALTER TABLE ${quoteIdentifier(physicalName)} RENAME TO ${quoteIdentifier(staging)}`);
@@ -4409,6 +4477,31 @@ var EidosFileRuntime = class {
4409
4477
  }
4410
4478
  throw new EidosFileError("resource-limit", "No collision-free rebuild Table name is available");
4411
4479
  }
4480
+ removeFieldFromViewLayouts(tableId, fieldId) {
4481
+ const views = this.connection.query(`SELECT id, layout_json FROM ${EIDOS_FILE_VIEWS_TABLE} WHERE table_id = ?`, [tableId]);
4482
+ for (const view of views) {
4483
+ const layout = jsonObject(view.layout_json);
4484
+ for (const key of [
4485
+ "cardFields",
4486
+ "fieldOrder",
4487
+ "hiddenFields"
4488
+ ]) if (Array.isArray(layout[key])) layout[key] = layout[key].filter((value) => value !== fieldId);
4489
+ for (const key of ["coverField", "groupField"]) if (layout[key] === fieldId) layout[key] = null;
4490
+ if (layout.fieldWidths && typeof layout.fieldWidths === "object" && !Array.isArray(layout.fieldWidths)) {
4491
+ const fieldWidths = { ...layout.fieldWidths };
4492
+ delete fieldWidths[fieldId];
4493
+ layout.fieldWidths = fieldWidths;
4494
+ }
4495
+ const next = canonicalizeEidosFileJson(layout);
4496
+ if (next === view.layout_json) continue;
4497
+ this.connection.run(`UPDATE ${EIDOS_FILE_VIEWS_TABLE}
4498
+ SET layout_json = ?, updated_at = ? WHERE id = ?`, [
4499
+ next,
4500
+ this.operationInstant(),
4501
+ view.id
4502
+ ]);
4503
+ }
4504
+ }
4412
4505
  deleteField(tableId, fieldKey, replacementRecordLabelFieldId) {
4413
4506
  const table = this.getTable(tableId);
4414
4507
  const field = this.fieldByKey(tableId, fieldKey);
@@ -4430,6 +4523,7 @@ var EidosFileRuntime = class {
4430
4523
  WHERE inverse_of_field_id = ? LIMIT 1`, [field.id]);
4431
4524
  if (dependentLookup || dependentInverse) throw new EidosFileError("constraint-conflict", `Field ${field.name} has structural dependents`);
4432
4525
  for (const formula of this.listFields(tableId).filter((candidate) => candidate.type === "formula")) if (compileEidosFileFormula(formula, this.listFields(tableId)).dependencyFieldIds.includes(field.id)) throw new EidosFileError("formula-in-use", `Formula ${formula.name} depends on ${field.name}`);
4526
+ this.removeFieldFromViewLayouts(tableId, field.id);
4433
4527
  if (field.type === "relation") this.dropRelationTriggers(field.id);
4434
4528
  if (field.physicalName) this.connection.exec(`ALTER TABLE ${quoteIdentifier(table.physicalName ?? table.rawTableName)} DROP COLUMN ${quoteIdentifier(field.physicalName)}`);
4435
4529
  return this.connection.run(`DELETE FROM ${EIDOS_FILE_FIELDS_TABLE} WHERE id = ?`, [field.id]).changes > 0;
@@ -4472,6 +4566,9 @@ var EidosFileRuntime = class {
4472
4566
  }
4473
4567
  createView(tableId, input) {
4474
4568
  const fields = this.listFields(tableId);
4569
+ const name = assertEidosFileDisplayName(input.name, "View name");
4570
+ const foldedName = name.replace(/[A-Z]/g, (character) => character.toLowerCase());
4571
+ if (this.listViews(tableId).some((view) => view.name.replace(/[A-Z]/g, (character) => character.toLowerCase()) === foldedName)) throw new EidosFileError("constraint-conflict", `Duplicate View name: ${name}`);
4475
4572
  const id = input.id ?? this.allocateId();
4476
4573
  const now = this.operationInstant();
4477
4574
  const fieldByKey = /* @__PURE__ */ new Map();
@@ -4496,7 +4593,7 @@ var EidosFileRuntime = class {
4496
4593
  const id = fieldByKey.get(key);
4497
4594
  return id ? [id] : [];
4498
4595
  });
4499
- const fieldOrder = (input.orderMap ? Object.entries(input.orderMap).sort((left, right) => left[1] - right[1]).map(([key]) => key) : Array.isArray(properties.fieldOrder) ? properties.fieldOrder.flatMap((key) => typeof key === "string" ? [key] : []) : fields.flatMap((field) => field.id ? [field.id] : [])).flatMap((key) => {
4596
+ const fieldOrder = (input.orderMap ? Object.entries(input.orderMap).sort((left, right) => left[1] - right[1]).map(([key]) => key) : Array.isArray(properties.fieldOrder) ? properties.fieldOrder.flatMap((key) => typeof key === "string" ? [key] : []) : systemFieldsLast(fields).flatMap((field) => field.id ? [field.id] : [])).flatMap((key) => {
4500
4597
  const id = fieldByKey.get(key);
4501
4598
  return id ? [id] : [];
4502
4599
  });
@@ -4511,7 +4608,7 @@ var EidosFileRuntime = class {
4511
4608
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
4512
4609
  assertEidosFileUuid(id, "View ID"),
4513
4610
  assertEidosFileUuid(tableId, "Table ID"),
4514
- input.name,
4611
+ name,
4515
4612
  input.type,
4516
4613
  canonicalizeEidosFileJson({
4517
4614
  ...filterToStorage(input.filter, fields) ? { filter: filterToStorage(input.filter, fields) } : {},
@@ -4536,8 +4633,11 @@ var EidosFileRuntime = class {
4536
4633
  updateView(viewId, changes) {
4537
4634
  const current = this.mapView(this.viewRow(viewId));
4538
4635
  const fields = this.listFields(current.tableId);
4636
+ const name = assertEidosFileDisplayName(changes.name ?? current.name, "View name");
4637
+ const foldedName = name.replace(/[A-Z]/g, (character) => character.toLowerCase());
4638
+ if (this.listViews(current.tableId).some((view) => view.id !== viewId && view.name.replace(/[A-Z]/g, (character) => character.toLowerCase()) === foldedName)) throw new EidosFileError("constraint-conflict", `Duplicate View name: ${name}`);
4539
4639
  const next = {
4540
- name: changes.name ?? current.name,
4640
+ name,
4541
4641
  type: changes.type ?? current.type,
4542
4642
  position: changes.position ?? current.position,
4543
4643
  properties: changes.properties === void 0 ? current.properties : changes.properties,
@@ -4562,7 +4662,7 @@ var EidosFileRuntime = class {
4562
4662
  const fieldOrder = next.orderMap ? Object.entries(next.orderMap).sort((left, right) => left[1] - right[1]).flatMap(([key]) => {
4563
4663
  const id = fieldByKey.get(key);
4564
4664
  return id ? [id] : [];
4565
- }) : fields.flatMap((field) => field.id ? [field.id] : []);
4665
+ }) : systemFieldsLast(fields).flatMap((field) => field.id ? [field.id] : []);
4566
4666
  const layout = {
4567
4667
  ...next.properties ?? {},
4568
4668
  fieldOrder,
@@ -4675,7 +4775,7 @@ var EidosFileRuntime = class {
4675
4775
  return `eidos_lookup_aggregate(
4676
4776
  ${`(SELECT coalesce(
4677
4777
  json_group_array(
4678
- json_object('v', ${targetResultType === "integer" ? "CASE WHEN value IS NULL THEN NULL ELSE CAST(value AS TEXT) END" : targetResultType === "json" || targetResultType === "file-entry" ? "CASE WHEN value IS NULL THEN NULL ELSE json(value) END" : "value"})
4778
+ json_object('v', ${targetResultType === "integer" ? "CASE WHEN value IS NULL THEN NULL ELSE CAST(value AS TEXT) END" : targetResultType === "file-entry" ? "CASE WHEN value IS NULL THEN NULL ELSE json(value) END" : "value"})
4679
4779
  ORDER BY relation_order, nested_order
4680
4780
  ),
4681
4781
  '[]'
@@ -4897,7 +4997,12 @@ var EidosFileRuntime = class {
4897
4997
  const raw = row[field.tableColumnName];
4898
4998
  let value = raw ?? null;
4899
4999
  const resultType = field.type === "formula" || field.type === "lookup" ? String(field.property?.displayType ?? field.type) : field.type;
4900
- if (typeof raw === "string" && (field.type === "file" || field.type === "multi-select" || field.type === "relation" || field.type === "lookup" && field.property?.aggregate === "values" || field.type === "json")) value = parseEidosFileJson(raw);
5000
+ if (typeof raw === "string" && (field.type === "file" || field.type === "multi-select" || field.type === "relation" || field.type === "lookup" && field.property?.aggregate === "values")) if (field.type === "file") try {
5001
+ value = decodeEidosFileValues(raw);
5002
+ } catch {
5003
+ throw new EidosFileError("invalid-sqlite", `${field.name} contains an invalid stored File value`);
5004
+ }
5005
+ else value = parseEidosFileJson(raw);
4901
5006
  else if (resultType === "checkbox" && typeof raw === "number") value = raw === 1;
4902
5007
  return [field.id, value];
4903
5008
  }));
@@ -5044,6 +5149,8 @@ var EidosFileRuntime = class {
5044
5149
  "count-all": "count(*)",
5045
5150
  "count-non-null": list ? "count(*)" : `count(${column})`,
5046
5151
  "count-empty": `sum(CASE WHEN ${column} IS NULL${list ? ` OR json_array_length(${column}) = 0` : ""} THEN 1 ELSE 0 END)`,
5152
+ "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`,
5153
+ "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`,
5047
5154
  "count-distinct": list ? `(SELECT count(DISTINCT value_type || ':' || json_quote(value)) FROM ${flattened})` : `count(DISTINCT ${column})`,
5048
5155
  sum: list ? `(SELECT sum(value) FROM ${flattened} WHERE value_type IN ('integer','real'))` : `sum(${column})`,
5049
5156
  average: list ? `(SELECT avg(value) FROM ${flattened} WHERE value_type IN ('integer','real'))` : `avg(${column})`,
@@ -5101,13 +5208,12 @@ var EidosFileRuntime = class {
5101
5208
  if (typeof value !== "string") throw new EidosFileError("invalid-value", `${field.name} must be text or NULL`);
5102
5209
  return value;
5103
5210
  }
5104
- if (field.type === "json") return canonicalizeEidosFileJson(parseEidosFileJson(typeof value === "string" ? value : canonicalizeEidosFileJson(value)));
5105
5211
  if (field.type === "multi-select") {
5106
5212
  const parsed = typeof value === "string" ? parseEidosFileJson(value) : value;
5107
5213
  if (!Array.isArray(parsed) || !parsed.every((entry) => typeof entry === "string") || new Set(parsed).size !== parsed.length) throw new EidosFileError("invalid-value", `${field.name} must be a unique string array`);
5108
5214
  return canonicalizeEidosFileJson(parsed);
5109
5215
  }
5110
- if (field.type === "file") return canonicalizeEidosFileJson(assertEidosFileValues(typeof value === "string" ? parseEidosFileJson(value) : value));
5216
+ if (field.type === "file") return typeof value === "string" ? canonicalizeEidosFileJson(decodeEidosFileValues(value)) : canonicalizeEidosFileJson(assertEidosFileValues(value));
5111
5217
  if (field.type === "relation") {
5112
5218
  const ids = Array.isArray(value) ? value.map(String) : decodeEidosFileRelationIds(typeof value === "string" ? value : void 0);
5113
5219
  const encoded = encodeEidosFileRelationIds(ids);
@@ -5162,6 +5268,62 @@ var EidosFileRuntime = class {
5162
5268
  VALUES (${values.map(() => "?").join(", ")})`, values);
5163
5269
  return rowId;
5164
5270
  }
5271
+ insertImportedRowsInTransaction(tableId, rows) {
5272
+ if (rows.length === 0) return [];
5273
+ const table = this.getTable(tableId);
5274
+ const fields = this.listFields(tableId);
5275
+ const fieldByKey = /* @__PURE__ */ new Map();
5276
+ for (const field of fields) for (const key of [
5277
+ field.id,
5278
+ field.tableColumnName,
5279
+ field.physicalName,
5280
+ field.name
5281
+ ]) if (key && !fieldByKey.has(key)) fieldByKey.set(key, field);
5282
+ const tableName = table.physicalName ?? table.rawTableName;
5283
+ const plans = /* @__PURE__ */ new Map();
5284
+ const now = this.operationInstant();
5285
+ const ids = rows.map((row) => {
5286
+ const requestedId = row._id ?? row.id;
5287
+ const rowId = typeof requestedId === "string" ? assertEidosFileUuid(requestedId, "Row ID") : this.allocateId();
5288
+ const keys = Object.keys(row).filter((key) => key !== "_id" && key !== "id" && !key.endsWith("__display"));
5289
+ const signature = JSON.stringify(keys);
5290
+ let plan = plans.get(signature);
5291
+ if (!plan) {
5292
+ const plannedFields = keys.map((key) => {
5293
+ const field = fieldByKey.get(key);
5294
+ if (!field) throw new EidosFileError("field-not-found", `Eidos File Field not found: ${key}`);
5295
+ if (!field.physicalName || field.valueKind === "system") throw new EidosFileError("protected-field", `Field ${field.name} is read-only`);
5296
+ return field;
5297
+ });
5298
+ const columns = [
5299
+ "_id",
5300
+ "_created_at",
5301
+ "_updated_at",
5302
+ ...plannedFields.map((field) => field.physicalName)
5303
+ ];
5304
+ plan = {
5305
+ keys,
5306
+ fields: plannedFields,
5307
+ sql: `INSERT INTO ${quoteIdentifier(tableName)}
5308
+ (${columns.map(quoteIdentifier).join(", ")})
5309
+ VALUES (${columns.map(() => "?").join(", ")})`,
5310
+ parameterSets: []
5311
+ };
5312
+ plans.set(signature, plan);
5313
+ }
5314
+ const values = [
5315
+ rowId,
5316
+ now,
5317
+ now,
5318
+ ...plan.keys.map((key, index) => this.normalizeStoredValue(plan.fields[index], row[key], true))
5319
+ ];
5320
+ plan.parameterSets.push(values);
5321
+ return rowId;
5322
+ });
5323
+ for (const plan of plans.values()) if (this.connection.runMany) this.connection.runMany(plan.sql, plan.parameterSets);
5324
+ else for (const values of plan.parameterSets) this.connection.run(plan.sql, values);
5325
+ return ids;
5326
+ }
5165
5327
  insertRow(tableId, row) {
5166
5328
  const id = this.mutate(() => this.insertRowInTransaction(tableId, row, true));
5167
5329
  return this.getRow(tableId, id);
@@ -5171,13 +5333,17 @@ var EidosFileRuntime = class {
5171
5333
  return this.getRow(tableId, id);
5172
5334
  }
5173
5335
  insertImportedRows(tableId, rows) {
5174
- return this.mutate(() => rows.map((row) => this.insertRowInTransaction(tableId, row, true))).map((id) => this.getRow(tableId, id));
5336
+ return this.mutate(() => this.insertImportedRowsInTransaction(tableId, rows)).map((id) => this.getRow(tableId, id));
5337
+ }
5338
+ /** @internal Appends rows inside a caller-owned import transaction. */
5339
+ appendImportedRows(tableId, rows) {
5340
+ this.insertImportedRowsInTransaction(tableId, rows);
5175
5341
  }
5176
5342
  /** @internal Used by the transactional CSV interchange layer. */
5177
5343
  importTable(table, rows) {
5178
5344
  return this.mutate(() => {
5179
5345
  const created = this.createTable(table);
5180
- rows.forEach((row) => this.insertRowInTransaction(created.id, row, true));
5346
+ this.insertImportedRowsInTransaction(created.id, rows);
5181
5347
  return created;
5182
5348
  });
5183
5349
  }
@@ -5210,17 +5376,12 @@ var EidosFileRuntime = class {
5210
5376
  }
5211
5377
  deleteRows(tableId, rowIds) {
5212
5378
  if (rowIds.length === 0) return [];
5213
- const table = this.getTable(tableId);
5214
5379
  const ids = Array.from(new Set(rowIds.map((id) => assertEidosFileUuid(id, "Row ID"))));
5215
5380
  if (ids.length > 500) throw new EidosFileError("resource-limit", "deleteRows accepts at most 500 Row IDs");
5216
- return this.mutate(() => {
5217
- const existing = this.connection.query(`SELECT "_id" AS id
5218
- FROM ${quoteIdentifier(table.physicalName ?? table.rawTableName)}
5219
- WHERE "_id" IN (${ids.map(() => "?").join(", ")})`, ids).map((row) => uuid(row.id));
5220
- if (existing.length > 0) this.connection.run(`DELETE FROM ${quoteIdentifier(table.physicalName ?? table.rawTableName)}
5221
- WHERE "_id" IN (${existing.map(() => "?").join(", ")})`, existing);
5222
- return existing;
5223
- });
5381
+ return this.mutateRows({
5382
+ tableId,
5383
+ delete: ids
5384
+ }).deleted;
5224
5385
  }
5225
5386
  deleteRowRanges(tableId, ranges, query = {}) {
5226
5387
  const rowIdField = this.listFields(tableId).find((field) => field.type === "row-id");
@@ -5471,6 +5632,6 @@ function fieldValueTypeForScan(field) {
5471
5632
  return field.type;
5472
5633
  }
5473
5634
  //#endregion
5474
- export { EIDOS_FILE_SYSTEM_COLUMNS as $, eidosFileLookupTargetDisplayType as A, EIDOS_FILE_APPLICATION_ID as B, normalizeEidosFileSorts as C, eidosFileLookupDisplayType as D, eidosFileLookupAggregateSupportsTarget as E, compileEidosFileFormula as F, EIDOS_FILE_FORMAT_VERSION as G, EIDOS_FILE_FEATURES_TABLE as H, compileEidosFileFormulaFields as I, EIDOS_FILE_META_TABLE as J, EIDOS_FILE_FORMULA_FIELDS_TABLE as K, compileEidosFileFormulaSource as L, eidosFileLookupValueType as M, EIDOS_FILE_FORMULA_FIELD_FUNCTION_NAMES as N, eidosFileLookupElementType as O, EIDOS_FILE_FORMULA_FUNCTION_NAMES as P, EIDOS_FILE_SCHEMA_VERSION as Q, eidosFileFormulaReferences as R, normalizeEidosFileRowQuery as S, eidosFileFieldStoresJsonArray as T, EIDOS_FILE_FIELDS_TABLE as U, EIDOS_FILE_EXTENSION as V, EIDOS_FILE_FORMAT as W, EIDOS_FILE_RELATION_FIELDS_TABLE as X, EIDOS_FILE_MIME_TYPE as Y, EIDOS_FILE_REQUIRED_TABLES as Z, compileEidosFileRowQuery as _, EIDOS_FILE_SCHEMA_SQL as a, eidosFileColumnStatTypesForField as at, eidosFileSortExpression as b, initializeEidosFileSchema as c, assertExactConnectionBindings as ct, decodeEidosFileRelationIds as d, exactConnectionBindingCount as dt, EIDOS_FILE_TABLES_TABLE as et, encodeEidosFileRelationIds as f, nativeToSqlValue as ft, assertEidosFileRowQuery as g, parseNonNegativeInt64 as h, EIDOS_FILE_FORMAT_VERSION_TEXT as i, eidosFileColumnStatLabel as it, eidosFileLookupTargetValueType as j, eidosFileLookupStorageCodec as k, setEidosFileMetadata as l, assertInt64Decimal as lt, cancellationPortFromSignal as m, validateEidosFile as n, SQLITE_HEADER as nt, configureEidosFileConnection as o, ConnectionPortEidosFileConnection as ot, MemoryByteSource as p, sqlValueToNative as pt, EIDOS_FILE_LOOKUP_FIELDS_TABLE as q, smallestDependencyCycle as r, hasEidosFileSqliteHeader as rt, incrementEidosFileRevision as s, EidosAdapterError as st, EidosFileRuntime as t, EIDOS_FILE_VIEWS_TABLE as tt, decodeEidosFileRelationDisplay as u, assertUnicodeString as ut, eidosFileRowQueryAffectedByFieldChanges as v, removeEidosFileFilterField as w, normalizeEidosFileFilter as x, eidosFileRowQueryPredicateColumns as y, rewriteEidosFileFormulaFieldReferences as z };
5635
+ export { EIDOS_FILE_SCHEMA_VERSION as $, eidosFileLookupStorageCodec as A, rewriteEidosFileFormulaFieldReferences as B, normalizeEidosFileRowQuery as C, eidosFileLookupAggregateSupportsTarget as D, eidosFileFieldStoresJsonArray as E, EIDOS_FILE_FORMULA_FUNCTION_NAMES as F, EIDOS_FILE_FORMAT as G, EIDOS_FILE_EXTENSION as H, compileEidosFileFormula as I, EIDOS_FILE_LOOKUP_FIELDS_TABLE as J, EIDOS_FILE_FORMAT_VERSION as K, compileEidosFileFormulaFields as L, eidosFileLookupTargetValueType as M, eidosFileLookupValueType as N, eidosFileLookupDisplayType as O, EIDOS_FILE_FORMULA_FIELD_FUNCTION_NAMES as P, EIDOS_FILE_REQUIRED_TABLES as Q, compileEidosFileFormulaSource as R, normalizeEidosFileFilter as S, removeEidosFileFilterField as T, EIDOS_FILE_FEATURES_TABLE as U, EIDOS_FILE_APPLICATION_ID as V, EIDOS_FILE_FIELDS_TABLE as W, EIDOS_FILE_MIME_TYPE as X, EIDOS_FILE_META_TABLE as Y, EIDOS_FILE_RELATION_FIELDS_TABLE as Z, assertEidosFileRowQuery as _, EIDOS_FILE_FORMAT_VERSION_TEXT as a, eidosFileColumnStatLabel as at, eidosFileRowQueryPredicateColumns as b, incrementEidosFileRevision as c, EidosAdapterError as ct, decodeEidosFileRelationDisplay as d, assertUnicodeString as dt, EIDOS_FILE_SYSTEM_COLUMNS as et, decodeEidosFileRelationIds as f, exactConnectionBindingCount as ft, parseNonNegativeInt64 as g, cancellationPortFromSignal as h, scanStableRowPages as i, hasEidosFileSqliteHeader as it, eidosFileLookupTargetDisplayType as j, eidosFileLookupElementType as k, initializeEidosFileSchema as l, assertExactConnectionBindings as lt, MemoryByteSource as m, sqlValueToNative as mt, validateEidosFile as n, EIDOS_FILE_VIEWS_TABLE as nt, EIDOS_FILE_SCHEMA_SQL as o, eidosFileColumnStatTypesForField as ot, encodeEidosFileRelationIds as p, nativeToSqlValue as pt, EIDOS_FILE_FORMULA_FIELDS_TABLE as q, smallestDependencyCycle as r, SQLITE_HEADER as rt, configureEidosFileConnection as s, ConnectionPortEidosFileConnection as st, EidosFileRuntime as t, EIDOS_FILE_TABLES_TABLE as tt, setEidosFileMetadata as u, assertInt64Decimal as ut, compileEidosFileRowQuery as v, normalizeEidosFileSorts as w, eidosFileSortExpression as x, eidosFileRowQueryAffectedByFieldChanges as y, eidosFileFormulaReferences as z };
5475
5636
 
5476
- //# sourceMappingURL=runtime-CMdfE7Gx.mjs.map
5637
+ //# sourceMappingURL=runtime-9_adwQ0y.mjs.map