@eidos.space/eidos-file 3.6.0 → 4.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 (41) hide show
  1. package/FIELD-CONVERSION.md +6 -2
  2. package/dist/{adapter-contract-DLze8O3C.d.mts → adapter-contract-CSbe2Wbp.d.mts} +2 -2
  3. package/dist/{adapter-contract-DLze8O3C.d.mts.map → adapter-contract-CSbe2Wbp.d.mts.map} +1 -1
  4. package/dist/better-sqlite3.d.mts +2 -2
  5. package/dist/better-sqlite3.mjs +1 -1
  6. package/dist/browser.d.mts +4 -4
  7. package/dist/browser.d.mts.map +1 -1
  8. package/dist/browser.mjs +3 -3
  9. package/dist/browser.mjs.map +1 -1
  10. package/dist/{csv-NK8Rti5O.mjs → csv-DSZ72Fkf.mjs} +18 -6
  11. package/dist/csv-DSZ72Fkf.mjs.map +1 -0
  12. package/dist/csv.d.mts +5 -1
  13. package/dist/csv.d.mts.map +1 -1
  14. package/dist/csv.mjs +1 -1
  15. package/dist/index.d.mts +38 -5
  16. package/dist/index.d.mts.map +1 -1
  17. package/dist/index.mjs +400 -44
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/node-sqlite.d.mts +9 -4
  20. package/dist/node-sqlite.d.mts.map +1 -1
  21. package/dist/node-sqlite.mjs +40 -3
  22. package/dist/node-sqlite.mjs.map +1 -1
  23. package/dist/{runtime-WzTMDrCe.d.mts → runtime-CB1g73FF.d.mts} +206 -14
  24. package/dist/runtime-CB1g73FF.d.mts.map +1 -0
  25. package/dist/{runtime-CTUCLd5Z.mjs → runtime-CpJ2VAXw.mjs} +1225 -178
  26. package/dist/runtime-CpJ2VAXw.mjs.map +1 -0
  27. package/dist/{sqlite-wasm-LbUUazaL.mjs → sqlite-wasm-Can22vNb.mjs} +8 -3
  28. package/dist/sqlite-wasm-Can22vNb.mjs.map +1 -0
  29. package/dist/{system-metadata-merge-D1jeYLZa.mjs → system-metadata-merge-BMBzxVo0.mjs} +123 -3
  30. package/dist/system-metadata-merge-BMBzxVo0.mjs.map +1 -0
  31. package/dist/{system-metadata-merge-CzWtCvqE.d.mts → system-metadata-merge-BNLOu74_.d.mts} +32 -3
  32. package/dist/{system-metadata-merge-CzWtCvqE.d.mts.map → system-metadata-merge-BNLOu74_.d.mts.map} +1 -1
  33. package/dist/{temporal-C-RGZNiQ.d.mts → temporal-DL3k3udh.d.mts} +6 -5
  34. package/dist/temporal-DL3k3udh.d.mts.map +1 -0
  35. package/package.json +4 -2
  36. package/dist/csv-NK8Rti5O.mjs.map +0 -1
  37. package/dist/runtime-CTUCLd5Z.mjs.map +0 -1
  38. package/dist/runtime-WzTMDrCe.d.mts.map +0 -1
  39. package/dist/sqlite-wasm-LbUUazaL.mjs.map +0 -1
  40. package/dist/system-metadata-merge-D1jeYLZa.mjs.map +0 -1
  41. package/dist/temporal-C-RGZNiQ.d.mts.map +0 -1
@@ -1,4 +1,5 @@
1
- import { A as isEidosFileUuid, C as assertEidosFileDisplayName, E as assertEidosFileUuid, F as EidosFileError, M as canonicalizeEidosFileJson, N as isCanonicalEidosFileJson, O as createEidosFileUuid, P as parseEidosFileJson, T as assertEidosFileTableName, c as eidosFileInstantSqlCheck, d as normalizeEidosFileDate, f as normalizeEidosFileInstant, h as decodeEidosFileValues, i as parseEidosFileSelectDefaultOption, j as quoteIdentifier, k as isEidosFileReservedTableName, l as isCanonicalEidosFileDate, n as assertEidosFileSelectDefaultOption, o as currentEidosFileInstant, p as assertEidosFileValues, r as assertEidosFileSelectOptions, s as eidosFileDateSqlCheck, t as assertEidosFileMultiSelectHasNoDefaultOption, u as isCanonicalEidosFileInstant } from "./select-options-DSzDn3qm.mjs";
1
+ import { A as isEidosFileUuid, C as assertEidosFileDisplayName, E as assertEidosFileUuid, F as EidosFileError, M as canonicalizeEidosFileJson, N as isCanonicalEidosFileJson, O as createEidosFileUuid, P as parseEidosFileJson, T as assertEidosFileTableName, a as parseEidosFileSelectOptions, c as eidosFileInstantSqlCheck, d as normalizeEidosFileDate, f as normalizeEidosFileInstant, h as decodeEidosFileValues, i as parseEidosFileSelectDefaultOption, j as quoteIdentifier, k as isEidosFileReservedTableName, l as isCanonicalEidosFileDate, n as assertEidosFileSelectDefaultOption, o as currentEidosFileInstant, p as assertEidosFileValues, r as assertEidosFileSelectOptions, s as eidosFileDateSqlCheck, t as assertEidosFileMultiSelectHasNoDefaultOption, u as isCanonicalEidosFileInstant } from "./select-options-DSzDn3qm.mjs";
2
+ import moment from "moment-timezone";
2
3
  //#region src/connection-port.ts
3
4
  const INT64_MIN$3 = -9223372036854775808n;
4
5
  const INT64_MAX$3 = 9223372036854775807n;
@@ -297,10 +298,12 @@ function recommendedEidosFileConversionPolicies(from, to) {
297
298
  if (from === "datetime" && to === "date") policies.push("utc-date");
298
299
  if (from === "multi-select" && to === "select") policies.push("first");
299
300
  if (!LIST_TYPES.has(from) && LIST_TYPES.has(to)) policies.push("null-to-empty-list");
301
+ if (to === "checkbox") policies.push("null-to-false");
300
302
  return policies;
301
303
  }
302
304
  /** Returns the nullable shape used by editor-initiated conversions. */
303
305
  function eidosFileConversionTargetNullable(from, to, sourceNullable) {
306
+ if (to === "checkbox") return false;
304
307
  if (LIST_TYPES.has(to)) return false;
305
308
  if (LIST_TYPES.has(from)) return true;
306
309
  return sourceNullable;
@@ -344,7 +347,31 @@ function eidosFileConversionCanReusePhysicalColumn(from, to, sourceNullable, tar
344
347
  return sourceNullable === targetNullable && SHARED_TEXT_COLUMN_TYPES.has(from) && SHARED_TEXT_COLUMN_TYPES.has(to);
345
348
  }
346
349
  function planCanonicalFieldConversion(input) {
350
+ const allowedPolicies = [
351
+ "round-binary64",
352
+ "truncate-toward-zero",
353
+ "round-ties-even",
354
+ "zero-false-nonzero-true",
355
+ "utc-date",
356
+ "first",
357
+ "null-to-empty-list",
358
+ "null-to-false"
359
+ ];
360
+ if (input.policies?.some((policy) => !allowedPolicies.includes(policy))) return {
361
+ classification: "forbidden",
362
+ rows: [],
363
+ affectedRows: "0",
364
+ valueChanges: [],
365
+ error: "Unknown conversion policy"
366
+ };
347
367
  const policies = new Set(input.policies ?? []);
368
+ if (policies.has("null-to-false") && (input.to !== "checkbox" || input.toNullable)) return {
369
+ classification: "forbidden",
370
+ rows: [],
371
+ affectedRows: "0",
372
+ valueChanges: [],
373
+ error: "null-to-false requires a non-null Checkbox destination"
374
+ };
348
375
  const sourceHasEmptyList = input.rows.some((row) => {
349
376
  if (row.value === null || typeof row.value !== "string") return false;
350
377
  return row.value === "[]";
@@ -394,6 +421,11 @@ function planCanonicalFieldConversion(input) {
394
421
  };
395
422
  }
396
423
  function convertNull(input, policies, sourceHasEmptyList) {
424
+ if (input.to === "checkbox" && !input.toNullable && policies.has("null-to-false")) return {
425
+ value: 0n,
426
+ class: 2,
427
+ code: "null-to-false"
428
+ };
397
429
  if (LIST_TYPES.has(input.to)) {
398
430
  if (!policies.has("null-to-empty-list")) throw new Error("SQL NULL requires null-to-empty-list for a list destination");
399
431
  return {
@@ -853,7 +885,8 @@ const ORDERED_OPERATORS = [
853
885
  const TEMPORAL_OPERATORS = [
854
886
  ...ORDERED_OPERATORS,
855
887
  "is-between",
856
- "is-relative-to-today"
888
+ "is-in-calendar-period",
889
+ "is-in-calendar-window"
857
890
  ];
858
891
  const LIST_OPERATORS = [
859
892
  "contains",
@@ -2191,6 +2224,251 @@ function eidosFileFieldStoresJsonArray(field) {
2191
2224
  return field.storageCodec === "json_array" || field.storageCodec === "relation";
2192
2225
  }
2193
2226
  //#endregion
2227
+ //#region src/calendar-day.ts
2228
+ /** Default portable calendar profile; selection never depends on array order. */
2229
+ const EIDOS_FILE_CALENDAR_TIME_ZONE_DATA = "2026f";
2230
+ const EIDOS_FILE_CALENDAR_MIN_YEAR = 1970;
2231
+ const EIDOS_FILE_CALENDAR_MAX_YEAR = 2499;
2232
+ const names = new Set(moment.tz.names());
2233
+ const DAY_MS = 864e5;
2234
+ function isEidosFileCalendarDayValue(value) {
2235
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2236
+ const item = value;
2237
+ return Object.keys(item).every((key) => [
2238
+ "day",
2239
+ "timeZone",
2240
+ "timeZoneData"
2241
+ ].includes(key)) && (item.day === "yesterday" || item.day === "today" || item.day === "tomorrow") && typeof item.timeZone === "string" && item.timeZone.length > 0 && typeof item.timeZoneData === "string" && item.timeZoneData.length > 0;
2242
+ }
2243
+ /** Exact names and aliases in this profile, including UTC. */
2244
+ function eidosFileCalendarTimeZones(timeZoneData) {
2245
+ assertProfile(timeZoneData);
2246
+ return [...names];
2247
+ }
2248
+ function supportsEidosFileCalendarProfile(timeZoneData) {
2249
+ return timeZoneData === "2026f" && moment.tz.dataVersion === timeZoneData;
2250
+ }
2251
+ function assertProfile(timeZoneData) {
2252
+ if (!supportsEidosFileCalendarProfile(timeZoneData)) throw new EidosFileError("unsupported-feature", `Calendar time-zone data ${timeZoneData} is unavailable`);
2253
+ }
2254
+ function zoneFor(timeZone, timeZoneData) {
2255
+ assertProfile(timeZoneData);
2256
+ if (!names.has(timeZone)) throw new EidosFileError("invalid-query", `Unknown calendar time zone: ${timeZone}`);
2257
+ return moment.tz.zone(timeZone);
2258
+ }
2259
+ /** Validates profile/name without evaluating a reference instant. */
2260
+ function assertEidosFileCalendarZone(timeZone, timeZoneData) {
2261
+ zoneFor(timeZone, timeZoneData);
2262
+ }
2263
+ /**
2264
+ * Project using portable rules only. Values outside the profile's local year
2265
+ * range return null: an ordinary stored value cannot fail an entire row page.
2266
+ */
2267
+ function projectEidosFileCalendarInstant(instant, timeZone, timeZoneData) {
2268
+ const zone = zoneFor(timeZone, timeZoneData);
2269
+ if (!isCanonicalEidosFileInstant(instant)) return null;
2270
+ const epoch = Date.parse(instant);
2271
+ const wall = /* @__PURE__ */ new Date(epoch - zone.utcOffset(epoch) * 6e4);
2272
+ const year = wall.getUTCFullYear();
2273
+ if (year < 1970 || year > 2499) return null;
2274
+ return {
2275
+ year,
2276
+ month: wall.getUTCMonth() + 1,
2277
+ day: wall.getUTCDate(),
2278
+ hour: wall.getUTCHours(),
2279
+ minute: wall.getUTCMinutes(),
2280
+ second: wall.getUTCSeconds(),
2281
+ millisecond: wall.getUTCMilliseconds()
2282
+ };
2283
+ }
2284
+ /** Reject gaps, folds, invalid calendar parts and range overflow. */
2285
+ function resolveEidosFileCalendarInstant(parts, timeZone, timeZoneData) {
2286
+ const zone = zoneFor(timeZone, timeZoneData);
2287
+ if (![
2288
+ parts.year,
2289
+ parts.month,
2290
+ parts.day,
2291
+ parts.hour,
2292
+ parts.minute,
2293
+ parts.second,
2294
+ parts.millisecond
2295
+ ].every(Number.isInteger) || parts.year < 1970 || parts.year > 2499 || parts.month < 1 || parts.month > 12 || parts.day < 1 || parts.day > 31 || parts.hour < 0 || parts.hour > 23 || parts.minute < 0 || parts.minute > 59 || parts.second < 0 || parts.second > 59 || parts.millisecond < 0 || parts.millisecond > 999) return null;
2296
+ const wall = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second, parts.millisecond);
2297
+ const matches = [...new Set(zone.offsets)].flatMap((offset) => {
2298
+ const candidate = new Date(wall + offset * 6e4).toISOString();
2299
+ const projected = projectEidosFileCalendarInstant(candidate, timeZone, timeZoneData);
2300
+ return projected && Object.keys(parts).every((key) => projected[key] === parts[key]) ? [candidate] : [];
2301
+ });
2302
+ return matches.length === 1 ? matches[0] : null;
2303
+ }
2304
+ /** The inverse image of one Gregorian date under piecewise-constant IANA offsets. */
2305
+ function eidosFileCalendarDayBounds(value, referenceInstant) {
2306
+ const reference = projectEidosFileCalendarInstant(referenceInstant, value.timeZone, value.timeZoneData);
2307
+ if (!reference) throw new EidosFileError("unsupported-feature", "Calendar reference is outside profile years 1970–2499");
2308
+ const delta = value.day === "yesterday" ? -1 : value.day === "tomorrow" ? 1 : 0;
2309
+ const start = Date.UTC(reference.year, reference.month - 1, reference.day) + delta * DAY_MS;
2310
+ const target = new Date(start);
2311
+ if (target.getUTCFullYear() < 1970 || target.getUTCFullYear() > 2499) throw new EidosFileError("unsupported-feature", "Calendar target is outside profile years 1970–2499");
2312
+ const date = target.toISOString().slice(0, 10);
2313
+ return {
2314
+ date,
2315
+ intervals: eidosFileCalendarDateRangeIntervals(date, new Date(start + DAY_MS).toISOString().slice(0, 10), value.timeZone, value.timeZoneData)
2316
+ };
2317
+ }
2318
+ /** Half-open local calendar range, suitable for Calendar's generated queries. */
2319
+ function eidosFileCalendarDateRangeIntervals(startDate, endDate, timeZone, timeZoneData) {
2320
+ const zone = zoneFor(timeZone, timeZoneData);
2321
+ const start = Date.parse(`${normalizeEidosFileDate(startDate)}T00:00:00.000Z`);
2322
+ const end = Date.parse(`${normalizeEidosFileDate(endDate)}T00:00:00.000Z`);
2323
+ if (start >= end) throw new EidosFileError("invalid-query", "Calendar range must be increasing");
2324
+ if (startDate < "1970-01-01" || endDate > "2500-01-01") throw new EidosFileError("unsupported-feature", "Calendar range is outside profile years 1970–2499");
2325
+ const spans = [];
2326
+ for (let index = 0; index < zone.untils.length; index++) {
2327
+ const lower = Math.max(start + zone.offsets[index] * 6e4, index === 0 ? -Infinity : zone.untils[index - 1]);
2328
+ const upper = Math.min(end + zone.offsets[index] * 6e4, zone.untils[index]);
2329
+ if (lower >= upper) continue;
2330
+ const previous = spans.at(-1);
2331
+ if (previous && previous[1] === lower) previous[1] = upper;
2332
+ else spans.push([lower, upper]);
2333
+ }
2334
+ return spans.map(([lower, upper]) => [new Date(lower).toISOString(), new Date(upper).toISOString()]);
2335
+ }
2336
+ //#endregion
2337
+ //#region src/calendar-period.ts
2338
+ /** Inspect period syntax without treating operand objects as predicates. */
2339
+ function hasEidosFileCalendarPeriodQuery(value) {
2340
+ return hasCalendarQuery(value, false);
2341
+ }
2342
+ /** Calendar context and root-R requirements apply to periods and windows. */
2343
+ function hasEidosFileCalendarQuery(value) {
2344
+ return hasCalendarQuery(value, true);
2345
+ }
2346
+ function hasCalendarQuery(value, windows) {
2347
+ if (!value || typeof value !== "object") return false;
2348
+ const visit = (value) => hasCalendarQuery(value, windows);
2349
+ if (Array.isArray(value)) return value.some(visit);
2350
+ const node = value;
2351
+ if (node.op === "calendar-period" || windows && node.op === "calendar-window" || node.type === "rule" && (node.operator === "is-in-calendar-period" || windows && node.operator === "is-in-calendar-window")) return true;
2352
+ return node.filter !== void 0 && visit(node.filter) || node.op === "not" && visit(node.arg) || (node.op === "and" || node.op === "or") && Array.isArray(node.args) && node.args.some(visit) || node.type === "group" && Array.isArray(node.children) && node.children.some(visit);
2353
+ }
2354
+ function isEidosFileCalendarPeriodValue(value) {
2355
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2356
+ const item = value;
2357
+ return Object.keys(item).every((key) => key === "unit" || key === "offset") && [
2358
+ "day",
2359
+ "week",
2360
+ "month",
2361
+ "year"
2362
+ ].includes(item.unit) && (item.offset === -1 || item.offset === 0 || item.offset === 1);
2363
+ }
2364
+ function assertEidosFileCalendarContext(value) {
2365
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new EidosFileError("invalid-query", "Calendar context is required");
2366
+ const item = value;
2367
+ if (Object.keys(item).some((key) => ![
2368
+ "timeZone",
2369
+ "timeZoneData",
2370
+ "weekStartsOn"
2371
+ ].includes(key)) || typeof item.timeZone !== "string" || typeof item.timeZoneData !== "string" || item.weekStartsOn !== 0 && item.weekStartsOn !== 1) throw new EidosFileError("invalid-query", "Calendar context is invalid");
2372
+ assertEidosFileCalendarZone(item.timeZone, item.timeZoneData);
2373
+ }
2374
+ /** Whole local calendar periods; never rolling durations or UTC projections. */
2375
+ function eidosFileCalendarPeriodBounds(value, context, referenceInstant) {
2376
+ if (!isEidosFileCalendarPeriodValue(value)) throw new EidosFileError("invalid-query", "Calendar period is invalid");
2377
+ assertEidosFileCalendarContext(context);
2378
+ const reference = projectEidosFileCalendarInstant(referenceInstant, context.timeZone, context.timeZoneData);
2379
+ if (!reference) throw new EidosFileError("unsupported-feature", "Calendar reference is outside profile years 1970–2499");
2380
+ let start;
2381
+ let end;
2382
+ const { year, month, day } = reference;
2383
+ if (value.unit === "year") {
2384
+ start = Date.UTC(year + value.offset, 0, 1);
2385
+ end = Date.UTC(year + value.offset + 1, 0, 1);
2386
+ } else if (value.unit === "month") {
2387
+ start = Date.UTC(year, month - 1 + value.offset, 1);
2388
+ end = Date.UTC(year, month + value.offset, 1);
2389
+ } else {
2390
+ const today = Date.UTC(year, month - 1, day);
2391
+ const weekOffset = (new Date(today).getUTCDay() - context.weekStartsOn + 7) % 7;
2392
+ const startDay = value.unit === "week" ? day - weekOffset + value.offset * 7 : day + value.offset;
2393
+ start = Date.UTC(year, month - 1, startDay);
2394
+ end = Date.UTC(year, month - 1, startDay + (value.unit === "week" ? 7 : 1));
2395
+ }
2396
+ if (new Date(start).getUTCFullYear() < 1970 || end > Date.UTC(2500, 0, 1)) throw new EidosFileError("unsupported-feature", "Calendar target is outside profile years 1970–2499");
2397
+ const startDate = new Date(start).toISOString().slice(0, 10);
2398
+ const endDate = new Date(end).toISOString().slice(0, 10);
2399
+ return {
2400
+ startDate,
2401
+ endDate,
2402
+ intervals: eidosFileCalendarDateRangeIntervals(startDate, endDate, context.timeZone, context.timeZoneData)
2403
+ };
2404
+ }
2405
+ //#endregion
2406
+ //#region src/calendar-window.ts
2407
+ /** Covers every possible date span within the advertised 1970–2499 profile. */
2408
+ const EIDOS_FILE_CALENDAR_WINDOW_COUNT_MAX = 1e6;
2409
+ function isEidosFileCalendarWindowValue(value) {
2410
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2411
+ const item = value;
2412
+ return Object.keys(item).every((key) => [
2413
+ "direction",
2414
+ "count",
2415
+ "unit"
2416
+ ].includes(key)) && (item.direction === "past" || item.direction === "next") && typeof item.count === "number" && Number.isSafeInteger(item.count) && item.count >= 1 && item.count <= 1e6 && [
2417
+ "day",
2418
+ "week",
2419
+ "month",
2420
+ "year"
2421
+ ].includes(item.unit);
2422
+ }
2423
+ function hasEidosFileCalendarWindowQuery(value) {
2424
+ if (!value || typeof value !== "object") return false;
2425
+ if (Array.isArray(value)) return value.some(hasEidosFileCalendarWindowQuery);
2426
+ const node = value;
2427
+ if (node.op === "calendar-window" || node.type === "rule" && node.operator === "is-in-calendar-window") return true;
2428
+ return node.filter !== void 0 && hasEidosFileCalendarWindowQuery(node.filter) || node.op === "not" && hasEidosFileCalendarWindowQuery(node.arg) || (node.op === "and" || node.op === "or") && Array.isArray(node.args) && node.args.some(hasEidosFileCalendarWindowQuery) || node.type === "group" && Array.isArray(node.children) && node.children.some(hasEidosFileCalendarWindowQuery);
2429
+ }
2430
+ /** A relative-to-today date window includes both the shifted date and today. */
2431
+ function eidosFileCalendarWindowBounds(value, context, referenceInstant) {
2432
+ if (!isEidosFileCalendarWindowValue(value)) throw new EidosFileError("invalid-query", "Calendar window is invalid");
2433
+ assertEidosFileCalendarContext(context);
2434
+ const reference = projectEidosFileCalendarInstant(referenceInstant, context.timeZone, context.timeZoneData);
2435
+ if (!reference) throw new EidosFileError("unsupported-feature", "Calendar reference is outside profile years 1970–2499");
2436
+ const today = Date.UTC(reference.year, reference.month - 1, reference.day);
2437
+ const amount = value.count * (value.direction === "past" ? -1 : 1);
2438
+ let target;
2439
+ if (value.unit === "day" || value.unit === "week") target = today + amount * (value.unit === "week" ? 7 : 1) * 864e5;
2440
+ else {
2441
+ const monthIndex = reference.year * 12 + reference.month - 1 + amount * (value.unit === "year" ? 12 : 1);
2442
+ const year = Math.floor(monthIndex / 12);
2443
+ if (year < 1970 || year > 2499) throw new EidosFileError("unsupported-feature", "Calendar window is outside profile years 1970–2499");
2444
+ const first = new Date(Date.UTC(year, monthIndex % 12, 1));
2445
+ const last = new Date(Date.UTC(first.getUTCFullYear(), first.getUTCMonth() + 1, 0)).getUTCDate();
2446
+ target = Date.UTC(first.getUTCFullYear(), first.getUTCMonth(), Math.min(reference.day, last));
2447
+ }
2448
+ const start = value.direction === "past" ? target : today;
2449
+ const end = (value.direction === "past" ? today : target) + 864e5;
2450
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start >= end || new Date(start).getUTCFullYear() < 1970 || end > Date.UTC(2500, 0, 1)) throw new EidosFileError("unsupported-feature", "Calendar window is outside profile years 1970–2499");
2451
+ const startDate = new Date(start).toISOString().slice(0, 10);
2452
+ const endDate = new Date(end).toISOString().slice(0, 10);
2453
+ return {
2454
+ startDate,
2455
+ endDate,
2456
+ intervals: eidosFileCalendarDateRangeIntervals(startDate, endDate, context.timeZone, context.timeZoneData)
2457
+ };
2458
+ }
2459
+ //#endregion
2460
+ //#region src/source-instant.ts
2461
+ /** Exact comparison key for external RFC 3339 source values, never API input. */
2462
+ function sourceInstantComparisonKey(value) {
2463
+ if (value === null) return null;
2464
+ if (typeof value !== "string") throw new EidosFileError("invalid-value", "Source timestamp must be RFC 3339 text");
2465
+ const parts = /^(\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2})(?:\.(\d+))?([Zz]|[+-]\d{2}:\d{2})$/.exec(value);
2466
+ if (!parts) throw new EidosFileError("invalid-value", "Source timestamp must be RFC 3339 text");
2467
+ const second = normalizeEidosFileInstant(`${parts[1]}.000${parts[3]}`, "Source timestamp");
2468
+ const fraction = (parts[2] ?? "").replace(/0+$/, "").padEnd(9, "0");
2469
+ return `${second.slice(0, 19)}.${fraction}`;
2470
+ }
2471
+ //#endregion
2194
2472
  //#region src/query.ts
2195
2473
  const FILTER_OPERATORS$1 = new Set([
2196
2474
  "equals",
@@ -2209,7 +2487,10 @@ const FILTER_OPERATORS$1 = new Set([
2209
2487
  "is-all-of",
2210
2488
  "is-none-of",
2211
2489
  "is-between",
2212
- "is-relative-to-today"
2490
+ "is-relative-to-today",
2491
+ "is-on-calendar-day",
2492
+ "is-in-calendar-period",
2493
+ "is-in-calendar-window"
2213
2494
  ]);
2214
2495
  /** Returns whether a persisted compatibility filter operator is executable. */
2215
2496
  function isEidosFileFilterOperator(value) {
@@ -2223,6 +2504,8 @@ const MAX_QUERY_SEARCH_LENGTH = 1e3;
2223
2504
  function assertEidosFileRowQuery(value) {
2224
2505
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new EidosFileError("invalid-query", "Row query must be an object");
2225
2506
  const query = value;
2507
+ if (query.calendar !== void 0) assertEidosFileCalendarContext(query.calendar);
2508
+ if (query.referenceInstant !== void 0 && !isCanonicalEidosFileInstant(query.referenceInstant)) throw new EidosFileError("invalid-query", "referenceInstant must be a canonical UTC instant");
2226
2509
  if (query.search !== void 0 && (typeof query.search !== "string" || query.search.length > MAX_QUERY_SEARCH_LENGTH)) throw new EidosFileError("query-limit", "Search text exceeds the 1000-character limit");
2227
2510
  if (query.sorts !== void 0) {
2228
2511
  if (!Array.isArray(query.sorts) || query.sorts.length > MAX_QUERY_SORTS) throw new EidosFileError("query-limit", "A query may contain at most 32 sort keys");
@@ -2240,6 +2523,18 @@ function assertEidosFileRowQuery(value) {
2240
2523
  return;
2241
2524
  }
2242
2525
  if (filter.type !== "rule" || typeof filter.field !== "string" || !isEidosFileFilterOperator(filter.operator)) throw new EidosFileError("invalid-query", "Invalid filter rule");
2526
+ if (filter.operator === "is-in-calendar-window") {
2527
+ if (!isEidosFileCalendarWindowValue(filter.value)) throw new EidosFileError("invalid-query", "Calendar window filter is invalid");
2528
+ return;
2529
+ }
2530
+ if (filter.operator === "is-in-calendar-period") {
2531
+ if (!isEidosFileCalendarPeriodValue(filter.value)) throw new EidosFileError("invalid-query", "Calendar period filter is invalid");
2532
+ return;
2533
+ }
2534
+ if (filter.operator === "is-on-calendar-day") {
2535
+ if (!isEidosFileCalendarDayValue(filter.value)) throw new EidosFileError("invalid-query", "Calendar day filter value is invalid");
2536
+ return;
2537
+ }
2243
2538
  if (filter.operator === "is-relative-to-today") {
2244
2539
  if (!isRelativeDateValue(filter.value)) throw new EidosFileError("invalid-query", "Relative date filter value is invalid");
2245
2540
  return;
@@ -2272,7 +2567,18 @@ function normalizeFilterNode(value, depth) {
2272
2567
  const candidate = value;
2273
2568
  if (candidate.type === "rule") {
2274
2569
  if (typeof candidate.field !== "string" || !isEidosFileFilterOperator(candidate.operator)) return null;
2275
- const values = candidate.operator === "is-relative-to-today" && isRelativeDateValue(candidate.value) ? {
2570
+ const values = candidate.operator === "is-in-calendar-window" && isEidosFileCalendarWindowValue(candidate.value) ? {
2571
+ direction: candidate.value.direction,
2572
+ count: candidate.value.count,
2573
+ unit: candidate.value.unit
2574
+ } : candidate.operator === "is-in-calendar-period" && isEidosFileCalendarPeriodValue(candidate.value) ? {
2575
+ unit: candidate.value.unit,
2576
+ offset: candidate.value.offset
2577
+ } : candidate.operator === "is-on-calendar-day" && isEidosFileCalendarDayValue(candidate.value) ? {
2578
+ day: candidate.value.day,
2579
+ timeZone: candidate.value.timeZone,
2580
+ timeZoneData: candidate.value.timeZoneData
2581
+ } : candidate.operator === "is-relative-to-today" && isRelativeDateValue(candidate.value) ? {
2276
2582
  direction: candidate.value.direction,
2277
2583
  unit: candidate.value.unit
2278
2584
  } : Array.isArray(candidate.value) ? candidate.value.flatMap((entry) => {
@@ -2332,6 +2638,8 @@ function normalizeEidosFileRowQuery(value) {
2332
2638
  if (typeof value !== "object" || value === null) return {};
2333
2639
  const candidate = value;
2334
2640
  return {
2641
+ ...candidate.calendar ? { calendar: candidate.calendar } : {},
2642
+ ...typeof candidate.referenceInstant === "string" ? { referenceInstant: candidate.referenceInstant } : {},
2335
2643
  ...typeof candidate.search === "string" ? { search: candidate.search } : {},
2336
2644
  ...Array.isArray(candidate.searchFields) && candidate.searchFields.every((field) => typeof field === "string") ? { searchFields: [...candidate.searchFields] } : {},
2337
2645
  filter: normalizeEidosFileFilter(candidate.filter),
@@ -2489,59 +2797,6 @@ function temporalFieldType(field) {
2489
2797
  if (type === "datetime" || type === "created-time" || type === "last-edited-time") return "datetime";
2490
2798
  return null;
2491
2799
  }
2492
- function shiftUtcMonth(instant, amount) {
2493
- const result = new Date(instant.getTime());
2494
- const day = result.getUTCDate();
2495
- result.setUTCDate(1);
2496
- result.setUTCMonth(result.getUTCMonth() + amount);
2497
- const endOfTargetMonth = new Date(Date.UTC(result.getUTCFullYear(), result.getUTCMonth() + 1, 0)).getUTCDate();
2498
- result.setUTCDate(Math.min(day, endOfTargetMonth));
2499
- return result;
2500
- }
2501
- function shiftUtcYear(instant, amount) {
2502
- const result = new Date(instant.getTime());
2503
- const month = result.getUTCMonth();
2504
- const day = result.getUTCDate();
2505
- result.setUTCDate(1);
2506
- result.setUTCFullYear(result.getUTCFullYear() + amount);
2507
- result.setUTCMonth(month);
2508
- const endOfTargetMonth = new Date(Date.UTC(result.getUTCFullYear(), month + 1, 0)).getUTCDate();
2509
- result.setUTCDate(Math.min(day, endOfTargetMonth));
2510
- return result;
2511
- }
2512
- function shiftUtcUnit(instant, unit, amount) {
2513
- if (unit === "day" || unit === "week") {
2514
- const days = unit === "day" ? 1 : 7;
2515
- return new Date(instant.getTime() + amount * days * 864e5);
2516
- }
2517
- return unit === "month" ? shiftUtcMonth(instant, amount) : shiftUtcYear(instant, amount);
2518
- }
2519
- function utcPeriodStart(instant, unit) {
2520
- const year = instant.getUTCFullYear();
2521
- const month = instant.getUTCMonth();
2522
- const day = instant.getUTCDate();
2523
- if (unit === "year") return new Date(Date.UTC(year, 0, 1));
2524
- if (unit === "month") return new Date(Date.UTC(year, month, 1));
2525
- const start = new Date(Date.UTC(year, month, day));
2526
- if (unit === "week") {
2527
- const daysSinceMonday = (start.getUTCDay() + 6) % 7;
2528
- start.setUTCDate(start.getUTCDate() - daysSinceMonday);
2529
- }
2530
- return start;
2531
- }
2532
- function relativeTemporalBounds(relative, referenceInstant, type) {
2533
- const reference = new Date(normalizeEidosFileInstant(referenceInstant, "Relative filter reference"));
2534
- return (() => {
2535
- if (relative.direction === "this") {
2536
- const start = utcPeriodStart(reference, relative.unit);
2537
- const nextStart = relative.unit === "day" || relative.unit === "week" ? new Date(start.getTime() + (relative.unit === "day" ? 1 : 7) * 864e5) : shiftUtcUnit(start, relative.unit, 1);
2538
- return [start, /* @__PURE__ */ new Date(nextStart.getTime() - 1)];
2539
- }
2540
- const past = relative.direction === "past";
2541
- const boundary = shiftUtcUnit(reference, relative.unit, past ? -1 : 1);
2542
- return past ? [boundary, reference] : [reference, boundary];
2543
- })().map((value) => type === "date" ? value.toISOString().slice(0, 10) : value.toISOString());
2544
- }
2545
2800
  function likeExpression(field, operator, value, params) {
2546
2801
  const column = quoteIdentifier(field.tableColumnName);
2547
2802
  const escaped = escapeLike(value);
@@ -2568,26 +2823,40 @@ function likeExpression(field, operator, value, params) {
2568
2823
  )` : `COALESCE(${caseInsensitiveLike(column, pattern, value, params)}, 0)`;
2569
2824
  return operator === "not-contains" ? `NOT (${expression})` : expression;
2570
2825
  }
2571
- function compileRule(rule, fields, params, referenceInstant) {
2826
+ function compileRule(rule, fields, params, referenceInstant, calendar, externalInstants = false) {
2572
2827
  const field = requireField(fields, rule.field);
2573
- const column = quoteIdentifier(field.tableColumnName);
2828
+ const sourceInstant = externalInstants && temporalFieldType(field) === "datetime";
2829
+ const column = sourceInstant ? `eidos_source_instant_key(${quoteIdentifier(field.tableColumnName)})` : quoteIdentifier(field.tableColumnName);
2830
+ const fieldValue = (value) => {
2831
+ const normalized = sqlFieldValue(field, value);
2832
+ return sourceInstant ? sourceInstantComparisonKey(normalized) : normalized;
2833
+ };
2574
2834
  const arrayCodec = field.storageCodec === "json_array" || field.storageCodec === "relation";
2575
2835
  const empty = arrayCodec ? `(${column} IS NULL OR (json_valid(${column}) AND json_type(${column}) = 'array' AND json_array_length(${column}) = 0))` : `(${column} IS NULL)`;
2576
2836
  if (rule.operator === "is-empty") return empty;
2577
2837
  if (rule.operator === "is-not-empty") return `NOT ${empty}`;
2578
- if (rule.operator === "is-relative-to-today") {
2838
+ if (rule.operator === "is-on-calendar-day" || rule.operator === "is-relative-to-today") throw new EidosFileError("unsupported-feature", "Retired date filter requires an explicit upgrade");
2839
+ if (rule.operator === "is-in-calendar-period" || rule.operator === "is-in-calendar-window") {
2579
2840
  const type = temporalFieldType(field);
2580
- if (!type) throw new EidosFileError("invalid-query", `${field.name} does not support relative date filters`);
2581
- if (!isRelativeDateValue(rule.value)) throw new EidosFileError("invalid-query", `${field.name} relative date filter is invalid`);
2582
- const [lower, upper] = relativeTemporalBounds(rule.value, referenceInstant, type);
2583
- params.push(lower, upper);
2584
- return `COALESCE(${column} >= ? AND ${column} <= ?, 0)`;
2841
+ const period = rule.operator === "is-in-calendar-period" && isEidosFileCalendarPeriodValue(rule.value) ? rule.value : null;
2842
+ const window = rule.operator === "is-in-calendar-window" && isEidosFileCalendarWindowValue(rule.value) ? rule.value : null;
2843
+ if (!type || !period && !window) throw new EidosFileError("invalid-query", "Calendar period requires a Date/Datetime Field");
2844
+ const bounds = window ? eidosFileCalendarWindowBounds(window, calendar, referenceInstant) : eidosFileCalendarPeriodBounds(period, calendar, referenceInstant);
2845
+ if (type === "date") {
2846
+ params.push(bounds.startDate, bounds.endDate);
2847
+ return `COALESCE(${column} >= ? AND ${column} < ?, 0)`;
2848
+ }
2849
+ const spans = bounds.intervals.map(([lower, upper]) => {
2850
+ params.push(sourceInstant ? sourceInstantComparisonKey(lower) : lower, sourceInstant ? sourceInstantComparisonKey(upper) : upper);
2851
+ return `(${column} >= ? AND ${column} < ?)`;
2852
+ });
2853
+ return spans.length ? `COALESCE((${spans.join(" OR ")}), 0)` : "0";
2585
2854
  }
2586
2855
  if (rule.operator === "is-between") {
2587
2856
  if (!Array.isArray(rule.value) || rule.value.length !== 2) throw new EidosFileError("invalid-query", `${field.name} between filter requires two values`);
2588
2857
  const [lower, upper] = rule.value;
2589
2858
  if (lower === null || upper === null) throw new EidosFileError("invalid-query", `${field.name} between filter values cannot be null`);
2590
- params.push(sqlFieldValue(field, lower), sqlFieldValue(field, upper));
2859
+ params.push(fieldValue(lower), fieldValue(upper));
2591
2860
  return `COALESCE(${column} >= ? AND ${column} <= ?, 0)`;
2592
2861
  }
2593
2862
  if (rule.operator === "is-any-of" || rule.operator === "is-all-of" || rule.operator === "is-none-of") {
@@ -2610,7 +2879,7 @@ function compileRule(rule, fields, params, referenceInstant) {
2610
2879
  }).join(rule.operator === "is-all-of" ? " AND " : " OR ")})`;
2611
2880
  return rule.operator === "is-none-of" ? `NOT (${expression})` : expression;
2612
2881
  }
2613
- params.push(...values.map((entry) => sqlFieldValue(field, entry)));
2882
+ params.push(...values.map(fieldValue));
2614
2883
  if (rule.operator === "is-all-of") return "0";
2615
2884
  const expression = `COALESCE(${column} IN (${values.map(() => "?").join(", ")}), 0)`;
2616
2885
  return rule.operator === "is-none-of" ? `NOT (${expression})` : expression;
@@ -2623,7 +2892,7 @@ function compileRule(rule, fields, params, referenceInstant) {
2623
2892
  return rule.operator === "not-equals" ? `${column} IS NOT ?` : `${column} IS ?`;
2624
2893
  }
2625
2894
  if (value === null || value === void 0) return `${column} IS ${rule.operator === "not-equals" ? "NOT " : ""}NULL`;
2626
- params.push(sqlFieldValue(field, value));
2895
+ params.push(fieldValue(value));
2627
2896
  return rule.operator === "not-equals" ? `${column} IS NOT ?` : `${column} IS ?`;
2628
2897
  }
2629
2898
  if (rule.operator === "contains" || rule.operator === "not-contains" || rule.operator === "starts-with" || rule.operator === "ends-with") return likeExpression(field, rule.operator, String(value ?? ""), params);
@@ -2635,11 +2904,11 @@ function compileRule(rule, fields, params, referenceInstant) {
2635
2904
  "less-than-or-equal": "<="
2636
2905
  }[rule.operator];
2637
2906
  if (!comparison) return "0";
2638
- params.push(sqlFieldValue(field, value));
2907
+ params.push(fieldValue(value));
2639
2908
  return `COALESCE(${column} ${comparison} ?, 0)`;
2640
2909
  }
2641
- function compileGroup(group, fields, params, referenceInstant) {
2642
- const children = group.children.map((child) => child.type === "group" ? compileGroup(child, fields, params, referenceInstant) : compileRule(child, fields, params, referenceInstant));
2910
+ function compileGroup(group, fields, params, referenceInstant, calendar, externalInstants = false) {
2911
+ const children = group.children.map((child) => child.type === "group" ? compileGroup(child, fields, params, referenceInstant, calendar, externalInstants) : compileRule(child, fields, params, referenceInstant, calendar, externalInstants));
2643
2912
  const expression = children.length === 0 ? group.conjunction === "or" ? "0" : "1" : `(${children.join(group.conjunction === "or" ? " OR " : " AND ")})`;
2644
2913
  return group.negated ? `NOT (${expression})` : expression;
2645
2914
  }
@@ -2666,6 +2935,7 @@ function compileSorts(sorts, fields) {
2666
2935
  return `ORDER BY ${clauses.join(", ")}`;
2667
2936
  }
2668
2937
  function compileEidosFileRowQuery(fields, query = {}, context = {}) {
2938
+ assertEidosFileRowQuery(query);
2669
2939
  query = normalizeEidosFileRowQuery(query);
2670
2940
  const byColumn = new Map(fields.map((field) => [field.tableColumnName, field]));
2671
2941
  const params = [];
@@ -2676,7 +2946,7 @@ function compileEidosFileRowQuery(fields, query = {}, context = {}) {
2676
2946
  const searchClauses = eidosFileRowQuerySearchFields(fields, query).map((field) => searchExpression(field, pattern, search, params));
2677
2947
  if (searchClauses.length > 0) where.push(`(${searchClauses.join(" OR ")})`);
2678
2948
  }
2679
- if (query.filter) where.push(compileGroup(query.filter, byColumn, params, context.referenceInstant ?? currentEidosFileInstant()));
2949
+ if (query.filter) where.push(compileGroup(query.filter, byColumn, params, context.referenceInstant ?? currentEidosFileInstant(), context.calendar ?? query.calendar, context.externalInstants));
2680
2950
  return {
2681
2951
  whereSql: where.length > 0 ? `WHERE ${where.join(" AND ")}` : "",
2682
2952
  orderSql: compileSorts(query.sorts, byColumn),
@@ -2778,6 +3048,75 @@ function decodeEidosFileRelationDisplay(value) {
2778
3048
  }
2779
3049
  }
2780
3050
  //#endregion
3051
+ //#region src/temporal-defaults.ts
3052
+ const EIDOS_FILE_TEMPORAL_DEFAULTS_FEATURE = "eidos:temporal-defaults";
3053
+ /** Absence/null disables the rule; only writable stored Date/Datetime support it. */
3054
+ function assertEidosFileTemporalDefault(type, settings, writable = true) {
3055
+ const value = settings?.defaultValue;
3056
+ if (value === void 0 || value === null) return null;
3057
+ if (value !== "now" || !writable || type !== "date" && type !== "datetime") throw new EidosFileError("invalid-schema", "defaultValue must be now on a writable stored Date or Datetime Field");
3058
+ return value;
3059
+ }
3060
+ function assertEidosFileCreationContext(context) {
3061
+ if (!context || typeof context !== "object" || Array.isArray(context) || Object.keys(context).some((key) => key !== "timeZone" && key !== "timeZoneData") || typeof context.timeZone !== "string" || typeof context.timeZoneData !== "string") throw new EidosFileError("invalid-value", "Invalid creation calendar context");
3062
+ assertEidosFileCalendarZone(context.timeZone, context.timeZoneData);
3063
+ }
3064
+ /** Shared by Runtime creation and unsaved UI previews. Never reads a host clock. */
3065
+ function eidosFileTemporalDefaultValue(type, settings, referenceInstant, context) {
3066
+ if (assertEidosFileTemporalDefault(type, settings) === null) return null;
3067
+ if (!isCanonicalEidosFileInstant(referenceInstant)) throw new EidosFileError("invalid-value", "Creation instant must be canonical UTC");
3068
+ if (context !== void 0) assertEidosFileCreationContext(context);
3069
+ if (type === "datetime") return referenceInstant;
3070
+ const parts = projectEidosFileCalendarInstant(referenceInstant, context?.timeZone ?? "UTC", context?.timeZoneData ?? "2026f");
3071
+ if (!parts) throw new EidosFileError("invalid-value", "Creation date is outside the calendar profile");
3072
+ return `${parts.year}-${String(parts.month).padStart(2, "0")}-${String(parts.day).padStart(2, "0")}`;
3073
+ }
3074
+ function hasTemporalDefaultsFeature(connection) {
3075
+ const row = connection.get("SELECT version, required, config_json FROM eidos__features WHERE name = ?", [EIDOS_FILE_TEMPORAL_DEFAULTS_FEATURE]);
3076
+ if (!row) return false;
3077
+ if (row.version !== "1" || row.required !== 1 || row.config_json !== "{}") throw new EidosFileError("unsupported-feature", "Unsupported temporal defaults feature declaration");
3078
+ return true;
3079
+ }
3080
+ /** Called within the schema transaction. Kept required after disabling defaults. */
3081
+ function enableTemporalDefaultsFeature(connection) {
3082
+ if (hasTemporalDefaultsFeature(connection)) return;
3083
+ connection.run("INSERT INTO eidos__features (name, version, required, config_json) VALUES (?, '1', 1, '{}')", [EIDOS_FILE_TEMPORAL_DEFAULTS_FEATURE]);
3084
+ }
3085
+ //#endregion
3086
+ //#region src/calendar-query-feature.ts
3087
+ const EIDOS_CALENDAR_QUERY_FEATURE = "eidos:calendar-query";
3088
+ const EIDOS_CALENDAR_WINDOW_FEATURE = "eidos:calendar-window";
3089
+ function hasCalendarWindowFeature(connection) {
3090
+ const row = connection.query("SELECT version, required, config_json FROM eidos__features WHERE name = ?", [EIDOS_CALENDAR_WINDOW_FEATURE])[0];
3091
+ if (!row) return false;
3092
+ if (row.version !== "1" || row.required !== 1 || row.config_json !== "{}") throw new EidosFileError("unsupported-feature", "Unsupported calendar window feature declaration");
3093
+ requireCalendarQueryFeature(connection);
3094
+ return true;
3095
+ }
3096
+ function requireCalendarWindowFeature(connection) {
3097
+ if (!hasCalendarWindowFeature(connection)) throw new EidosFileError("invalid-schema", "Calendar window Views require the calendar window feature");
3098
+ }
3099
+ /** Install both dependencies inside the View's existing revision transaction. */
3100
+ function enableCalendarWindowFeature(connection) {
3101
+ enableCalendarQueryFeature(connection);
3102
+ if (hasCalendarWindowFeature(connection)) return;
3103
+ connection.run("INSERT INTO eidos__features (name, version, required, config_json) VALUES (?, '1', 1, '{}')", [EIDOS_CALENDAR_WINDOW_FEATURE]);
3104
+ }
3105
+ function hasCalendarQueryFeature(connection) {
3106
+ const row = connection.query("SELECT version, required, config_json FROM eidos__features WHERE name = ?", [EIDOS_CALENDAR_QUERY_FEATURE])[0];
3107
+ if (!row) return false;
3108
+ if (row.version !== "2" || row.required !== 1 || row.config_json !== "{}") throw new EidosFileError("unsupported-feature", "Unsupported calendar query feature declaration");
3109
+ return true;
3110
+ }
3111
+ function requireCalendarQueryFeature(connection) {
3112
+ if (!hasCalendarQueryFeature(connection)) throw new EidosFileError("invalid-schema", "Calendar period Views require the calendar query feature");
3113
+ }
3114
+ /** Call only inside the transaction that persists the first new query. */
3115
+ function enableCalendarQueryFeature(connection) {
3116
+ if (hasCalendarQueryFeature(connection)) return;
3117
+ connection.run("INSERT INTO eidos__features (name, version, required, config_json) VALUES (?, '2', 1, '{}')", [EIDOS_CALENDAR_QUERY_FEATURE]);
3118
+ }
3119
+ //#endregion
2781
3120
  //#region src/formula-functions.ts
2782
3121
  const INT64_MIN$1 = -9223372036854775808n;
2783
3122
  const INT64_MAX$1 = 9223372036854775807n;
@@ -3367,6 +3706,200 @@ function scanStableRowPages(connection, options, visit) {
3367
3706
  }
3368
3707
  }
3369
3708
  //#endregion
3709
+ //#region src/calendar-query-upgrade.ts
3710
+ const EIDOS_FILE_DATE_QUERY_UPGRADE_RECEIPT = "space.eidos/date-query-upgrade";
3711
+ const EIDOS_FILE_DATE_QUERY_UPGRADE_RECEIPT_MAX_BYTES = 65536;
3712
+ function hasRetiredEidosFileDateQuery(value) {
3713
+ if (!value || typeof value !== "object") return false;
3714
+ if (Array.isArray(value)) return value.some(hasRetiredEidosFileDateQuery);
3715
+ const node = value;
3716
+ if ([
3717
+ "relative-date",
3718
+ "calendar-day",
3719
+ "is-relative-to-today",
3720
+ "is-on-calendar-day"
3721
+ ].includes(node.op)) return true;
3722
+ if (node.type === "rule" && ["is-relative-to-today", "is-on-calendar-day"].includes(node.operator)) return true;
3723
+ return node.filter !== void 0 && hasRetiredEidosFileDateQuery(node.filter) || node.op === "not" && hasRetiredEidosFileDateQuery(node.arg) || (node.op === "and" || node.op === "or") && Array.isArray(node.args) && node.args.some(hasRetiredEidosFileDateQuery) || node.type === "group" && Array.isArray(node.children) && node.children.some(hasRetiredEidosFileDateQuery);
3724
+ }
3725
+ /** Preview an explicit semantic upgrade. Unknown nodes fail the whole preview. */
3726
+ function upgradeEidosFileDateQuery(value) {
3727
+ const invalid = (message) => {
3728
+ throw new EidosFileError("invalid-query", message);
3729
+ };
3730
+ const object = (entry) => entry && typeof entry === "object" && !Array.isArray(entry) ? entry : invalid("Date query upgrade requires objects");
3731
+ const keys = (entry, allowed) => {
3732
+ if (Object.keys(entry).some((key) => !allowed.includes(key))) invalid("Query members do not match the operator's structure");
3733
+ };
3734
+ const source = object(value);
3735
+ keys(source, ["filter", "sort"]);
3736
+ const changes = [];
3737
+ let nodes = 0;
3738
+ const visit = (entry, depth) => {
3739
+ if (++nodes > 100 || depth > 8) invalid("Date query upgrade exceeds query limits");
3740
+ const node = object(entry);
3741
+ if (node.op === "and" || node.op === "or") {
3742
+ keys(node, ["op", "args"]);
3743
+ if (!Array.isArray(node.args)) invalid("Logical query args are invalid");
3744
+ return {
3745
+ ...node,
3746
+ args: node.args.map((child) => visit(child, depth + 1))
3747
+ };
3748
+ }
3749
+ if (node.op === "not") {
3750
+ keys(node, ["op", "arg"]);
3751
+ return {
3752
+ ...node,
3753
+ arg: visit(node.arg, depth + 1)
3754
+ };
3755
+ }
3756
+ if (typeof node.fieldId !== "string" || !node.fieldId) invalid("Query Field is required");
3757
+ if (node.op === "calendar-day") {
3758
+ keys(node, [
3759
+ "op",
3760
+ "fieldId",
3761
+ "day",
3762
+ "timeZone",
3763
+ "timeZoneData"
3764
+ ]);
3765
+ if (!isEidosFileCalendarDayValue({
3766
+ day: node.day,
3767
+ timeZone: node.timeZone,
3768
+ timeZoneData: node.timeZoneData
3769
+ })) invalid("Retired calendar day is invalid");
3770
+ assertEidosFileCalendarZone(node.timeZone, node.timeZoneData);
3771
+ const offset = node.day === "yesterday" ? -1 : node.day === "tomorrow" ? 1 : 0;
3772
+ changes.push({
3773
+ fieldId: node.fieldId,
3774
+ from: `calendar-day:${String(node.day)}`,
3775
+ unit: "day",
3776
+ offset
3777
+ });
3778
+ return {
3779
+ op: "calendar-period",
3780
+ fieldId: node.fieldId,
3781
+ unit: "day",
3782
+ offset
3783
+ };
3784
+ }
3785
+ if (node.op === "relative-date") {
3786
+ keys(node, [
3787
+ "op",
3788
+ "fieldId",
3789
+ "direction",
3790
+ "unit"
3791
+ ]);
3792
+ const offset = node.direction === "past" ? -1 : node.direction === "this" ? 0 : node.direction === "next" ? 1 : null;
3793
+ const candidate = {
3794
+ unit: node.unit,
3795
+ offset
3796
+ };
3797
+ if (!isEidosFileCalendarPeriodValue(candidate)) invalid("Retired relative date is invalid");
3798
+ const period = candidate;
3799
+ changes.push({
3800
+ fieldId: node.fieldId,
3801
+ from: `relative-date:${String(node.direction)}:${String(node.unit)}`,
3802
+ ...period
3803
+ });
3804
+ return {
3805
+ op: "calendar-period",
3806
+ fieldId: node.fieldId,
3807
+ ...period
3808
+ };
3809
+ }
3810
+ const expected = typeof node.op === "string" ? {
3811
+ "calendar-window": [
3812
+ "direction",
3813
+ "unit",
3814
+ "count"
3815
+ ],
3816
+ "calendar-period": ["unit", "offset"],
3817
+ "is-null": [],
3818
+ "is-not-null": [],
3819
+ eq: ["value"],
3820
+ ne: ["value"],
3821
+ lt: ["value"],
3822
+ lte: ["value"],
3823
+ gt: ["value"],
3824
+ gte: ["value"],
3825
+ between: ["lower", "upper"],
3826
+ in: ["values"],
3827
+ contains: ["value"],
3828
+ "starts-with": ["value"],
3829
+ "ends-with": ["value"],
3830
+ "has-any": ["values"],
3831
+ "has-all": ["values"],
3832
+ "relation-has": ["rowId"]
3833
+ }[node.op] : void 0;
3834
+ if (!expected) throw new EidosFileError("unsupported-feature", "Unknown query nodes cannot be upgraded safely");
3835
+ keys(node, [
3836
+ "op",
3837
+ "fieldId",
3838
+ ...expected
3839
+ ]);
3840
+ if (expected.some((key) => !(key in node))) invalid("Query operand is missing");
3841
+ if ([
3842
+ "eq",
3843
+ "ne",
3844
+ "lt",
3845
+ "lte",
3846
+ "gt",
3847
+ "gte"
3848
+ ].includes(node.op) && node.value === null) invalid("Query comparison requires a non-null operand");
3849
+ if (node.op === "between" && (node.lower === null || node.upper === null)) invalid("Between requires non-null operands");
3850
+ if ([
3851
+ "in",
3852
+ "has-any",
3853
+ "has-all"
3854
+ ].includes(node.op) && (!Array.isArray(node.values) || node.values.length > 500 || node.values.some((item) => item === null))) invalid("Query list operands are invalid");
3855
+ if ([
3856
+ "contains",
3857
+ "starts-with",
3858
+ "ends-with"
3859
+ ].includes(node.op) && typeof node.value !== "string") invalid("Query text operand is invalid");
3860
+ if (node.op === "relation-has" && typeof node.rowId !== "string") invalid("Query Relation operand is invalid");
3861
+ if (node.op === "calendar-window" && !isEidosFileCalendarWindowValue({
3862
+ direction: node.direction,
3863
+ unit: node.unit,
3864
+ count: node.count
3865
+ })) invalid("Calendar window is invalid");
3866
+ if (node.op === "calendar-period" && !isEidosFileCalendarPeriodValue({
3867
+ unit: node.unit,
3868
+ offset: node.offset
3869
+ })) invalid("Calendar period is invalid");
3870
+ return { ...node };
3871
+ };
3872
+ const query = {
3873
+ ...source.filter === void 0 ? {} : { filter: visit(source.filter, 0) },
3874
+ ...source.sort === void 0 ? {} : { sort: source.sort }
3875
+ };
3876
+ if (source.sort !== void 0) {
3877
+ if (!Array.isArray(source.sort)) invalid("Query sort is invalid");
3878
+ for (const entry of source.sort) {
3879
+ const sort = object(entry);
3880
+ keys(sort, [
3881
+ "fieldId",
3882
+ "direction",
3883
+ "nulls"
3884
+ ]);
3885
+ if (typeof sort.fieldId !== "string" || !["asc", "desc"].includes(sort.direction) || sort.nulls !== void 0 && sort.nulls !== "first" && sort.nulls !== "last") invalid("Query sort is invalid");
3886
+ }
3887
+ }
3888
+ return {
3889
+ query: JSON.parse(canonicalizeEidosFileJson(query)),
3890
+ changes
3891
+ };
3892
+ }
3893
+ function eidosFileDateQueryUpgradeReceipt(originalQuery, upgrade) {
3894
+ const receipt = JSON.parse(canonicalizeEidosFileJson({
3895
+ version: 2,
3896
+ originalQuery,
3897
+ changes: upgrade.changes
3898
+ }));
3899
+ if (new TextEncoder().encode(canonicalizeEidosFileJson(receipt)).byteLength > 65536) throw new EidosFileError("query-limit", "Date query recovery receipt exceeds 65536 bytes");
3900
+ return receipt;
3901
+ }
3902
+ //#endregion
3370
3903
  //#region src/dependency-graph.ts
3371
3904
  /** Returns the globally smallest normalized simple directed cycle. */
3372
3905
  function smallestDependencyCycle(graph) {
@@ -3549,7 +4082,10 @@ const FILTER_OPERATORS = new Set([
3549
4082
  "is-all-of",
3550
4083
  "is-none-of",
3551
4084
  "is-between",
3552
- "is-relative-to-today"
4085
+ "is-relative-to-today",
4086
+ "is-on-calendar-day",
4087
+ "is-in-calendar-period",
4088
+ "is-in-calendar-window"
3553
4089
  ]);
3554
4090
  const RUNTIME_FILTER_OPERATORS$1 = new Set([
3555
4091
  "is-null",
@@ -3568,7 +4104,10 @@ const RUNTIME_FILTER_OPERATORS$1 = new Set([
3568
4104
  "has-any",
3569
4105
  "has-all",
3570
4106
  "relation-has",
3571
- "relative-date"
4107
+ "relative-date",
4108
+ "calendar-day",
4109
+ "calendar-period",
4110
+ "calendar-window"
3572
4111
  ]);
3573
4112
  const LEVELS = {
3574
4113
  identity: 0,
@@ -3828,22 +4367,61 @@ function validateEidosFile(connection, options = {}) {
3828
4367
  } catch (error) {
3829
4368
  add(errors, "invalid-schema", error instanceof Error ? error.message : "Invalid metadata ID");
3830
4369
  }
3831
- if (LEVELS[level] === LEVELS.identity) return {
4370
+ if (sqliteTables.has("eidos__features")) {
4371
+ const loadedModules = new Set(connection.query("PRAGMA module_list").map((row) => row.name));
4372
+ scanStableRowPages(connection, {
4373
+ columnsSql: "name, required, config_json",
4374
+ tableSql: EIDOS_FILE_FEATURES_TABLE,
4375
+ rowIdSql: "name",
4376
+ rowIdKey: "name"
4377
+ }, (features) => {
4378
+ for (const feature of features) {
4379
+ if (feature.name === "eidos:temporal-defaults") {
4380
+ try {
4381
+ hasTemporalDefaultsFeature(connection);
4382
+ } catch (error) {
4383
+ add(errors, "unsupported-feature", error instanceof Error ? error.message : "Unsupported temporal defaults feature");
4384
+ }
4385
+ continue;
4386
+ }
4387
+ if (!isCanonicalEidosFileJson(feature.config_json)) add(errors, "invalid-schema", `Feature ${feature.name} has non-canonical config_json`);
4388
+ if (feature.name === "eidos:calendar-query" || feature.name === "eidos:calendar-window") {
4389
+ try {
4390
+ if (feature.name === "eidos:calendar-window") hasCalendarWindowFeature(connection);
4391
+ else hasCalendarQueryFeature(connection);
4392
+ } catch (error) {
4393
+ add(errors, "unsupported-feature", error instanceof Error ? error.message : "Unsupported calendar feature");
4394
+ }
4395
+ continue;
4396
+ }
4397
+ const moduleName = feature.name.startsWith("vtab:") ? feature.name.slice(5) : null;
4398
+ if (feature.required === 1 && (!moduleName || !SUPPORTED_VTAB_MODULES.has(moduleName) || !loadedModules.has(moduleName))) add(errors, "unsupported-feature", `Required feature is unavailable in this runtime: ${feature.name}`);
4399
+ }
4400
+ });
4401
+ }
4402
+ if (errors.some((issue) => issue.code === "unsupported-feature")) return {
3832
4403
  valid: errors.length === 0,
3833
4404
  metadata,
3834
4405
  tables: [],
3835
4406
  errors,
3836
4407
  warnings
3837
4408
  };
3838
- if (sqliteTables.has("eidos__features")) {
3839
- const loadedModules = new Set(connection.query("PRAGMA module_list").map((row) => row.name));
3840
- for (const feature of connection.query(`SELECT name, required, config_json FROM ${EIDOS_FILE_FEATURES_TABLE}`)) {
3841
- if (!isCanonicalEidosFileJson(feature.config_json)) add(errors, "invalid-schema", `Feature ${feature.name} has non-canonical config_json`);
3842
- const moduleName = feature.name.startsWith("vtab:") ? feature.name.slice(5) : null;
3843
- if (feature.required === 1 && (!moduleName || !SUPPORTED_VTAB_MODULES.has(moduleName) || !loadedModules.has(moduleName))) add(errors, "unsupported-feature", `Required feature is unavailable in this runtime: ${feature.name}`);
3844
- }
4409
+ if (sqliteTables.has("eidos__views") && (!sqliteTables.has("eidos__features") || !hasCalendarQueryFeature(connection) || !hasCalendarWindowFeature(connection))) try {
4410
+ scanStableRowPages(connection, {
4411
+ columnsSql: "id, query_json",
4412
+ tableSql: EIDOS_FILE_VIEWS_TABLE,
4413
+ rowIdSql: "id",
4414
+ rowIdKey: "id"
4415
+ }, (views) => {
4416
+ for (const view of views) {
4417
+ if (hasEidosFileCalendarWindowQuery(parseEidosFileJson(view.query_json))) requireCalendarWindowFeature(connection);
4418
+ if (hasEidosFileCalendarQuery(parseEidosFileJson(view.query_json))) requireCalendarQueryFeature(connection);
4419
+ }
4420
+ });
4421
+ } catch (error) {
4422
+ add(errors, "invalid-schema", error instanceof Error ? error.message : "Invalid calendar query feature");
3845
4423
  }
3846
- if (errors.some((issue) => issue.code === "unsupported-feature")) return {
4424
+ if (LEVELS[level] === LEVELS.identity) return {
3847
4425
  valid: errors.length === 0,
3848
4426
  metadata,
3849
4427
  tables: [],
@@ -3942,6 +4520,11 @@ function validateEidosFile(connection, options = {}) {
3942
4520
  } catch (error) {
3943
4521
  add(errors, "invalid-schema", `Field ${row.name}: ${error instanceof Error ? error.message : "invalid settings"}`);
3944
4522
  }
4523
+ try {
4524
+ if (assertEidosFileTemporalDefault(row.type, settings, row.system_role === null && row.physical_name !== null && settings.writable !== false && settings.readOnly !== true && settings.isSystem !== true) === "now" && !hasTemporalDefaultsFeature(connection)) throw new Error("Temporal defaults require the eidos:temporal-defaults feature");
4525
+ } catch (error) {
4526
+ add(errors, "invalid-schema", error instanceof Error ? error.message : "Invalid temporal default");
4527
+ }
3945
4528
  if (row.type === "select" || row.type === "multi-select") try {
3946
4529
  assertEidosFileSelectOptions(settings);
3947
4530
  if (row.type === "select") assertEidosFileSelectDefaultOption(settings);
@@ -4180,6 +4763,7 @@ function validateEidosFile(connection, options = {}) {
4180
4763
  const physicalColumnRows = connection.query(`PRAGMA table_xinfo(${quoteIdentifier(table.physical_name)})`);
4181
4764
  const physicalColumns = new Map(physicalColumnRows.map((column) => [column.name, column.type.toUpperCase()]));
4182
4765
  const physicalNullability = new Map(physicalColumnRows.map((column) => [column.name, column.notnull === 0]));
4766
+ const physicalDefaults = new Map(physicalColumnRows.map((column) => [column.name, column.dflt_value]));
4183
4767
  for (const required of [
4184
4768
  "_id",
4185
4769
  "_created_at",
@@ -4192,6 +4776,8 @@ function validateEidosFile(connection, options = {}) {
4192
4776
  for (const field of fields) {
4193
4777
  const fieldId = field.id;
4194
4778
  if (field.physicalName) {
4779
+ const columnDefault = physicalDefaults.get(field.physicalName);
4780
+ if (!isVirtual && field.type === "checkbox" && columnDefault != null && columnDefault !== "0") add(errors, "invalid-schema", `Checkbox Field ${field.name} must omit its legacy default or use DEFAULT 0`);
4195
4781
  const actualType = physicalColumns.get(field.physicalName);
4196
4782
  const expected = expectedColumnType(field.type);
4197
4783
  if (!actualType) add(errors, "invalid-schema", `Stored Field ${field.name} has no physical column`);
@@ -4280,6 +4866,8 @@ function validateEidosFile(connection, options = {}) {
4280
4866
  const fieldsById = new Map(viewFields.map((field) => [field.id, field]));
4281
4867
  const fieldIds = new Set(fieldsById.keys());
4282
4868
  const query = parseEidosFileJson(view.query_json);
4869
+ if (hasEidosFileCalendarQuery(query)) requireCalendarQueryFeature(connection);
4870
+ if (hasEidosFileCalendarWindowQuery(query)) requireCalendarWindowFeature(connection);
4283
4871
  const layout = parseEidosFileJson(view.layout_json);
4284
4872
  if (!query || Array.isArray(query) || typeof query !== "object") throw new Error("View query_json must be an object");
4285
4873
  if (!layout || Array.isArray(layout) || typeof layout !== "object") throw new Error("View layout_json must be an object");
@@ -4384,7 +4972,56 @@ function validateEidosFile(connection, options = {}) {
4384
4972
  ])) unsupportedQuery = true;
4385
4973
  return;
4386
4974
  }
4975
+ if (node.op === "calendar-window") {
4976
+ const type = eidosFileFieldValueType(field);
4977
+ if (type !== "date" && type !== "datetime" || !isEidosFileCalendarWindowValue({
4978
+ direction: node.direction,
4979
+ count: node.count,
4980
+ unit: node.unit
4981
+ }) || !hasOnlyKeys(node, [
4982
+ "op",
4983
+ "fieldId",
4984
+ "direction",
4985
+ "count",
4986
+ "unit"
4987
+ ])) throw new Error("View calendar window is invalid");
4988
+ return;
4989
+ }
4990
+ if (node.op === "calendar-period") {
4991
+ const type = eidosFileFieldValueType(field);
4992
+ if (type !== "date" && type !== "datetime" || !isEidosFileCalendarPeriodValue({
4993
+ unit: node.unit,
4994
+ offset: node.offset
4995
+ }) || !hasOnlyKeys(node, [
4996
+ "op",
4997
+ "fieldId",
4998
+ "unit",
4999
+ "offset"
5000
+ ])) throw new Error("View calendar period is invalid");
5001
+ return;
5002
+ }
5003
+ if (node.op === "calendar-day") {
5004
+ unsupportedQuery = true;
5005
+ const type = eidosFileFieldValueType(field);
5006
+ if (type !== "date" && type !== "datetime") throw new Error("View calendar filter requires a Date or Datetime Field");
5007
+ const value = {
5008
+ day: node.day,
5009
+ timeZone: node.timeZone,
5010
+ timeZoneData: node.timeZoneData
5011
+ };
5012
+ if (!isEidosFileCalendarDayValue(value)) throw new Error("View calendar day filter value is invalid");
5013
+ if (!hasOnlyKeys(node, [
5014
+ "op",
5015
+ "fieldId",
5016
+ "day",
5017
+ "timeZone",
5018
+ "timeZoneData"
5019
+ ]) || !supportsEidosFileCalendarProfile(value.timeZoneData)) unsupportedQuery = true;
5020
+ else assertEidosFileCalendarZone(value.timeZone, value.timeZoneData);
5021
+ return;
5022
+ }
4387
5023
  if (node.op === "relative-date") {
5024
+ unsupportedQuery = true;
4388
5025
  if (field.type !== "date" && field.type !== "datetime" && field.type !== "created-time" && field.type !== "last-edited-time") throw new Error("View relative filter requires a Date or Datetime Field");
4389
5026
  if (![
4390
5027
  "past",
@@ -4426,7 +5063,26 @@ function validateEidosFile(connection, options = {}) {
4426
5063
  if (node.op === "is-between") {
4427
5064
  if (!Array.isArray(node.value) || node.value.length !== 2) throw new Error("View between filter must contain exactly two values");
4428
5065
  }
5066
+ if (node.op === "is-in-calendar-window") {
5067
+ const type = eidosFileFieldValueType(field);
5068
+ if (type !== "date" && type !== "datetime" || !isEidosFileCalendarWindowValue(node.value)) throw new Error("View calendar window is invalid");
5069
+ return;
5070
+ }
5071
+ if (node.op === "is-in-calendar-period") {
5072
+ const type = eidosFileFieldValueType(field);
5073
+ if (type !== "date" && type !== "datetime" || !isEidosFileCalendarPeriodValue(node.value)) throw new Error("View calendar period is invalid");
5074
+ return;
5075
+ }
5076
+ if (node.op === "is-on-calendar-day") {
5077
+ unsupportedQuery = true;
5078
+ const type = eidosFileFieldValueType(field);
5079
+ if (type !== "date" && type !== "datetime" || !isEidosFileCalendarDayValue(node.value)) throw new Error("View calendar day filter value is invalid");
5080
+ if (!supportsEidosFileCalendarProfile(node.value.timeZoneData)) unsupportedQuery = true;
5081
+ else assertEidosFileCalendarZone(node.value.timeZone, node.value.timeZoneData);
5082
+ return;
5083
+ }
4429
5084
  if (node.op === "is-relative-to-today") {
5085
+ unsupportedQuery = true;
4430
5086
  if (field.type !== "date" && field.type !== "datetime" && field.type !== "created-time" && field.type !== "last-edited-time") throw new Error("View relative filter requires a Date or Datetime Field");
4431
5087
  const relative = node.value;
4432
5088
  if (!relative || typeof relative !== "object" || Array.isArray(relative)) throw new Error("View relative filter value is invalid");
@@ -4564,6 +5220,182 @@ function validateEidosFile(connection, options = {}) {
4564
5220
  };
4565
5221
  }
4566
5222
  //#endregion
5223
+ //#region src/creation-defaults.ts
5224
+ const MAX_BRANCHES = 32;
5225
+ function branches(node) {
5226
+ if (node.type === "rule") return [[node]];
5227
+ if (node.negated) return null;
5228
+ let result = node.conjunction === "and" ? [[]] : [];
5229
+ for (const child of node.children) {
5230
+ const next = branches(child);
5231
+ if (!next) return null;
5232
+ if (node.conjunction === "or") result.push(...next);
5233
+ else result = result.flatMap((left) => next.map((right) => [...left, ...right]));
5234
+ if (result.length > MAX_BRANCHES) return null;
5235
+ }
5236
+ return result;
5237
+ }
5238
+ function step(value, field, direction) {
5239
+ if (field.type === "rating") return Number(value) + direction;
5240
+ if (field.type === "integer") try {
5241
+ return BigInt(value) + BigInt(direction);
5242
+ } catch {
5243
+ return;
5244
+ }
5245
+ if (field.type === "number") return Number(value) + direction;
5246
+ if (field.type === "date" || field.type === "datetime") {
5247
+ const instant = Date.parse(String(value) + (field.type === "date" ? "T00:00:00.000Z" : ""));
5248
+ if (!Number.isFinite(instant)) return void 0;
5249
+ const date = new Date(instant + direction * (field.type === "date" ? 864e5 : 1));
5250
+ if (!Number.isFinite(date.getTime())) return void 0;
5251
+ return field.type === "date" ? date.toISOString().slice(0, 10) : date.toISOString();
5252
+ }
5253
+ }
5254
+ function adjacent(value, direction) {
5255
+ if (value === 0) return direction * Number.MIN_VALUE;
5256
+ const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
5257
+ view.setFloat64(0, value);
5258
+ view.setBigUint64(0, view.getBigUint64(0) + (Math.sign(value) === direction ? 1n : -1n));
5259
+ return view.getFloat64(0);
5260
+ }
5261
+ function seeds(field, rules, query, instant) {
5262
+ const result = [];
5263
+ const members = [], fragments = [], prefixes = [], suffixes = [];
5264
+ const options = parseEidosFileSelectOptions(field.settings ?? field.property).map((option) => option.name);
5265
+ for (const rule of rules) {
5266
+ const value = rule.value;
5267
+ if (rule.operator === "is-empty") result.push(field.storageCodec === "json_array" || field.storageCodec === "relation" ? "[]" : null);
5268
+ if (rule.operator === "equals") {
5269
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") result.push(typeof value === "boolean" ? Number(value) : value);
5270
+ }
5271
+ if (field.type === "multi-select") {
5272
+ if (rule.operator === "contains" && typeof value === "string") members.push(value);
5273
+ if (rule.operator === "is-all-of" && Array.isArray(value) && value.every((entry) => typeof entry === "string")) members.push(...value);
5274
+ if (rule.operator === "is-any-of" && Array.isArray(value) && value.length === 1 && typeof value[0] === "string") members.push(value[0]);
5275
+ }
5276
+ if (["text", "url"].includes(field.type) && typeof value === "string") {
5277
+ if (rule.operator === "contains") fragments.push(value);
5278
+ if (rule.operator === "starts-with") prefixes.push(value);
5279
+ if (rule.operator === "ends-with") suffixes.push(value);
5280
+ }
5281
+ if ([
5282
+ "number",
5283
+ "integer",
5284
+ "rating",
5285
+ "date",
5286
+ "datetime"
5287
+ ].includes(field.type)) {
5288
+ if (rule.operator === "is-between" && Array.isArray(value)) {
5289
+ for (const entry of value) if (typeof entry === "string" || typeof entry === "number") result.push(entry);
5290
+ }
5291
+ if (typeof value === "string" || typeof value === "number") {
5292
+ if (rule.operator === "greater-than-or-equal" || rule.operator === "less-than-or-equal") result.push(value);
5293
+ if (rule.operator === "greater-than" || rule.operator === "less-than") {
5294
+ const direction = rule.operator === "greater-than" ? 1 : -1;
5295
+ const next = step(value, field, direction);
5296
+ if (next !== void 0) result.push(next);
5297
+ if (field.type === "number") result.push(adjacent(Number(value), direction));
5298
+ }
5299
+ }
5300
+ if (query.calendar) {
5301
+ const bounds = rule.operator === "is-in-calendar-period" && isEidosFileCalendarPeriodValue(value) ? eidosFileCalendarPeriodBounds(value, query.calendar, instant) : rule.operator === "is-in-calendar-window" && isEidosFileCalendarWindowValue(value) ? eidosFileCalendarWindowBounds(value, query.calendar, instant) : null;
5302
+ if (bounds) if (field.type === "date") result.push(bounds.startDate);
5303
+ else for (const [start] of bounds.intervals) result.push(start);
5304
+ }
5305
+ }
5306
+ }
5307
+ if (members.length && members.every((member) => options.includes(member))) result.push(JSON.stringify([...new Set(members)]));
5308
+ if (fragments.length || prefixes.length || suffixes.length) {
5309
+ let text = prefixes.sort((a, b) => b.length - a.length)[0] ?? "";
5310
+ for (const fragment of fragments) if (!text.toLowerCase().includes(fragment.toLowerCase())) text += fragment;
5311
+ const suffix = suffixes.sort((a, b) => b.length - a.length)[0] ?? "";
5312
+ if (!text.toLowerCase().endsWith(suffix.toLowerCase())) text += suffix;
5313
+ result.push(text);
5314
+ }
5315
+ if (field.type === "checkbox" && rules.some((rule) => rule.operator === "equals" || rule.operator === "not-equals")) result.push(0, 1);
5316
+ if (field.type === "select") return [...new Set([...result, ...rules.some((rule) => [
5317
+ "equals",
5318
+ "contains",
5319
+ "starts-with",
5320
+ "ends-with"
5321
+ ].includes(rule.operator)) ? options : []])].filter((value) => value === null || options.includes(String(value)));
5322
+ if (["relation", "file"].includes(field.type)) return result.filter((value) => value === "[]" || value === null);
5323
+ if (field.type === "integer" || field.type === "rating") return [...new Set(result.flatMap((value) => {
5324
+ if (typeof value !== "string") return [value];
5325
+ try {
5326
+ return [field.type === "rating" ? Number(value) : BigInt(value)];
5327
+ } catch {
5328
+ return [];
5329
+ }
5330
+ }))];
5331
+ return [...new Set(result)];
5332
+ }
5333
+ /** Internal ordinary-create policy. Candidate acceptance uses the query compiler and adapter SQL. */
5334
+ function inferEidosFileCreationDefaults(connection, fields, query, explicit, defaults, instant, normalize) {
5335
+ assertEidosFileRowQuery(query);
5336
+ if (!query.filter) return {};
5337
+ compileEidosFileRowQuery(fields, {
5338
+ filter: query.filter,
5339
+ calendar: query.calendar
5340
+ }, { referenceInstant: instant });
5341
+ const alternatives = branches(query.filter);
5342
+ if (!alternatives?.length) return {};
5343
+ const plans = [];
5344
+ let evaluations = 0;
5345
+ for (const branch of alternatives) {
5346
+ const plan = {};
5347
+ let excluded = false;
5348
+ for (const field of fields) {
5349
+ const rules = branch.filter((rule) => rule.field === field.tableColumnName);
5350
+ if (!rules.length) continue;
5351
+ const key = field.tableColumnName;
5352
+ const compiled = compileEidosFileRowQuery([field], {
5353
+ filter: {
5354
+ type: "group",
5355
+ conjunction: "and",
5356
+ children: rules
5357
+ },
5358
+ calendar: query.calendar
5359
+ }, { referenceInstant: instant });
5360
+ const affinity = ["number"].includes(field.type) ? "REAL" : [
5361
+ "integer",
5362
+ "rating",
5363
+ "checkbox"
5364
+ ].includes(field.type) ? "INTEGER" : "TEXT";
5365
+ const accepts = (value) => {
5366
+ if (++evaluations > 2048) return false;
5367
+ return Boolean(connection.get(`SELECT 1 AS matched FROM (SELECT CAST(? AS ${affinity}) AS ${quoteIdentifier(key)}) ${compiled.whereSql}`, [typeof value === "boolean" ? Number(value) : value, ...compiled.params]));
5368
+ };
5369
+ if (Object.hasOwn(explicit, key)) {
5370
+ if (!accepts(explicit[key] ?? null)) excluded = true;
5371
+ continue;
5372
+ }
5373
+ if (field.systemRole || field.isDerived || !["source", "relation"].includes(field.valueKind) || field.writable === false || field.settings?.writable === false || field.settings?.readOnly === true || field.settings?.isSystem === true) continue;
5374
+ const base = defaults[key] ?? null;
5375
+ if ((base !== null || field.nullable !== false) && accepts(base)) {
5376
+ plan[key] = base;
5377
+ continue;
5378
+ }
5379
+ const candidates = seeds(field, rules, query, instant).flatMap((value) => {
5380
+ let normalized;
5381
+ try {
5382
+ normalized = normalize(field, value);
5383
+ } catch {
5384
+ return [];
5385
+ }
5386
+ if (normalized === null && field.nullable === false) return [];
5387
+ return accepts(normalized) ? [normalized] : [];
5388
+ });
5389
+ if (field.type === "select" && new Set(candidates).size > 1) continue;
5390
+ if (candidates.length) plan[key] = candidates[0];
5391
+ }
5392
+ if (evaluations > 2048) return {};
5393
+ if (!excluded) plans.push(plan);
5394
+ }
5395
+ if (!plans.length) return {};
5396
+ return Object.fromEntries(Object.entries(plans[0]).filter(([key, value]) => plans.every((plan) => Object.hasOwn(plan, key) && plan[key] === value)));
5397
+ }
5398
+ //#endregion
4567
5399
  //#region src/runtime.ts
4568
5400
  const ROW_MUTATION_UNDO_ENTRIES_MAX = 50;
4569
5401
  const ROW_MUTATION_UNDO_BYTES_MAX = 64 * 1024 * 1024;
@@ -4654,7 +5486,7 @@ function fieldColumnSql(field) {
4654
5486
  case "date": return `${column} TEXT${field.nullable ? "" : " NOT NULL"} CHECK(${eidosFileDateSqlCheck(column)})`;
4655
5487
  case "datetime": return `${column} TEXT${field.nullable ? "" : " NOT NULL"} CHECK(${eidosFileInstantSqlCheck(column)})`;
4656
5488
  case "rating": return `${column} INTEGER`;
4657
- case "checkbox": return `${column} INTEGER${field.nullable ? "" : " NOT NULL"} CHECK(${column} IS NULL OR ${column} IN (0, 1))`;
5489
+ case "checkbox": return `${column} INTEGER${field.nullable ? "" : " NOT NULL"} DEFAULT 0 CHECK(${column} IS NULL OR ${column} IN (0, 1))`;
4658
5490
  case "file":
4659
5491
  case "multi-select":
4660
5492
  case "relation": return `${column} TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(${column}) AND json_type(${column}) = 'array')`;
@@ -4688,6 +5520,7 @@ function assertedRawSelectOptions(property) {
4688
5520
  }
4689
5521
  function presentationSettings(input) {
4690
5522
  const property = presentationSettingsObject("property" in input ? input.property : void 0);
5523
+ assertEidosFileTemporalDefault(input.type, property);
4691
5524
  if (input.type === "select" || input.type === "multi-select") {
4692
5525
  property.options = assertedRawSelectOptions("property" in input ? input.property : void 0);
4693
5526
  if (input.type === "select") {
@@ -4875,6 +5708,7 @@ function compileKeysetBefore(sorts, values, firstId) {
4875
5708
  };
4876
5709
  }
4877
5710
  function filterToStorage(filter, fields) {
5711
+ if (filter) assertEidosFileRowQuery({ filter });
4878
5712
  const normalized = normalizeEidosFileFilter(filter);
4879
5713
  if (!normalized) return null;
4880
5714
  const byKey = /* @__PURE__ */ new Map();
@@ -4908,6 +5742,26 @@ function filterToStorage(filter, fields) {
4908
5742
  op: "in",
4909
5743
  values: requireValues()
4910
5744
  };
5745
+ if (rule.operator === "is-in-calendar-window") {
5746
+ if (!isEidosFileCalendarWindowValue(rule.value)) throw new EidosFileError("invalid-query", "Saved calendar window is invalid");
5747
+ return {
5748
+ op: "calendar-window",
5749
+ fieldId,
5750
+ ...rule.value
5751
+ };
5752
+ }
5753
+ if (rule.operator === "is-in-calendar-period") {
5754
+ if (!isEidosFileCalendarPeriodValue(rule.value)) throw new EidosFileError("invalid-query", "Saved calendar period is invalid");
5755
+ return {
5756
+ op: "calendar-period",
5757
+ fieldId,
5758
+ ...rule.value
5759
+ };
5760
+ }
5761
+ if (rule.operator === "is-on-calendar-day") {
5762
+ if (!isEidosFileCalendarDayValue(rule.value)) throw new EidosFileError("invalid-query", "Saved View calendar day filter is invalid");
5763
+ throw new EidosFileError("unsupported-feature", "Retired calendar-day query requires an explicit date filter upgrade");
5764
+ }
4911
5765
  if (rule.operator === "is-relative-to-today") {
4912
5766
  const relative = rule.value;
4913
5767
  if (!relative || typeof relative !== "object" || Array.isArray(relative) || !("direction" in relative) || !("unit" in relative) || ![
@@ -4920,12 +5774,7 @@ function filterToStorage(filter, fields) {
4920
5774
  "month",
4921
5775
  "year"
4922
5776
  ].includes(String(relative.unit))) throw new EidosFileError("invalid-query", "Saved View relative date filter is invalid");
4923
- return {
4924
- direction: relative.direction,
4925
- fieldId,
4926
- op: "relative-date",
4927
- unit: relative.unit
4928
- };
5777
+ throw new EidosFileError("unsupported-feature", "Retired relative-date query requires an explicit date filter upgrade");
4929
5778
  }
4930
5779
  if (rule.operator === "is-between") {
4931
5780
  if (!Array.isArray(rule.value) || rule.value.length !== 2 || rule.value.some((value) => value === null)) throw new EidosFileError("invalid-query", "Saved View between filter is invalid");
@@ -5097,6 +5946,35 @@ function filterFromStorage(value, fields) {
5097
5946
  operator: "is-between",
5098
5947
  value: [node.lower, node.upper]
5099
5948
  };
5949
+ if (node.op === "calendar-window") return {
5950
+ type: "rule",
5951
+ field,
5952
+ operator: "is-in-calendar-window",
5953
+ value: {
5954
+ direction: node.direction,
5955
+ unit: node.unit,
5956
+ count: node.count
5957
+ }
5958
+ };
5959
+ if (node.op === "calendar-period") return {
5960
+ type: "rule",
5961
+ field,
5962
+ operator: "is-in-calendar-period",
5963
+ value: {
5964
+ unit: node.unit,
5965
+ offset: node.offset
5966
+ }
5967
+ };
5968
+ if (node.op === "calendar-day") return {
5969
+ type: "rule",
5970
+ field,
5971
+ operator: "is-on-calendar-day",
5972
+ value: {
5973
+ day: node.day,
5974
+ timeZone: node.timeZone,
5975
+ timeZoneData: node.timeZoneData
5976
+ }
5977
+ };
5100
5978
  if (node.op === "relative-date") return {
5101
5979
  type: "rule",
5102
5980
  field,
@@ -5173,7 +6051,10 @@ const RUNTIME_FILTER_OPERATORS = new Set([
5173
6051
  "has-any",
5174
6052
  "has-all",
5175
6053
  "relation-has",
5176
- "relative-date"
6054
+ "relative-date",
6055
+ "calendar-day",
6056
+ "calendar-period",
6057
+ "calendar-window"
5177
6058
  ]);
5178
6059
  function sortsFromStorage(value) {
5179
6060
  if (!Array.isArray(value)) return [];
@@ -5201,20 +6082,9 @@ function storedViewQueryStatus(query, fields) {
5201
6082
  if (Object.keys(query).some((key) => key !== "filter" && key !== "sort")) return "unsupported";
5202
6083
  const supportedScalar = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
5203
6084
  const supportedRuleValue = (operator, value) => {
5204
- if (operator === "is-relative-to-today") {
5205
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
5206
- const relative = value;
5207
- return Object.keys(relative).every((key) => key === "direction" || key === "unit") && [
5208
- "past",
5209
- "next",
5210
- "this"
5211
- ].includes(String(relative.direction)) && [
5212
- "day",
5213
- "week",
5214
- "month",
5215
- "year"
5216
- ].includes(String(relative.unit));
5217
- }
6085
+ if (operator === "is-in-calendar-window") return isEidosFileCalendarWindowValue(value);
6086
+ if (operator === "is-in-calendar-period") return isEidosFileCalendarPeriodValue(value);
6087
+ if (operator === "is-on-calendar-day" || operator === "is-relative-to-today") return false;
5218
6088
  if (operator === "is-between") return Array.isArray(value) && value.length === 2 && value.every(supportedScalar);
5219
6089
  return value === void 0 || supportedScalar(value) || Array.isArray(value) && value.every(supportedScalar);
5220
6090
  };
@@ -5253,6 +6123,32 @@ function storedViewQueryStatus(query, fields) {
5253
6123
  } else if (node.op === "relation-has") {
5254
6124
  allowed.add("rowId");
5255
6125
  if (typeof node.rowId !== "string") return false;
6126
+ } else if (node.op === "calendar-window") {
6127
+ allowed.add("unit");
6128
+ allowed.add("direction");
6129
+ allowed.add("count");
6130
+ if (!isEidosFileCalendarWindowValue({
6131
+ unit: node.unit,
6132
+ direction: node.direction,
6133
+ count: node.count
6134
+ })) return false;
6135
+ } else if (node.op === "calendar-period") {
6136
+ allowed.add("unit");
6137
+ allowed.add("offset");
6138
+ if (!isEidosFileCalendarPeriodValue({
6139
+ unit: node.unit,
6140
+ offset: node.offset
6141
+ })) return false;
6142
+ } else if (node.op === "calendar-day" || node.op === "relative-date") return false;
6143
+ else if (node.op === "calendar-day") {
6144
+ allowed.add("day");
6145
+ allowed.add("timeZone");
6146
+ allowed.add("timeZoneData");
6147
+ if (!supportedRuleValue("is-on-calendar-day", {
6148
+ day: node.day,
6149
+ timeZone: node.timeZone,
6150
+ timeZoneData: node.timeZoneData
6151
+ })) return false;
5256
6152
  } else if (node.op === "relative-date") {
5257
6153
  allowed.add("direction");
5258
6154
  allowed.add("unit");
@@ -5294,14 +6190,18 @@ var EidosFileRuntime = class {
5294
6190
  nestedMutationInvalidatesRowUndo = false;
5295
6191
  schemaCache;
5296
6192
  nowInstant;
6193
+ requestInstant;
6194
+ batchQuerySequence = 0;
5297
6195
  allocateId;
5298
6196
  constructor(connection, ownsConnection = false, environment = {}) {
5299
6197
  this.connection = connection;
5300
6198
  this.ownsConnection = ownsConnection;
5301
- this.nowInstant = environment.nowInstant ?? currentEidosFileInstant;
6199
+ const clock = environment.nowInstant ?? currentEidosFileInstant;
6200
+ this.nowInstant = () => this.requestInstant ?? clock();
5302
6201
  this.allocateId = environment.allocateId ?? (() => createEidosFileUuid());
5303
6202
  connection.exec("PRAGMA foreign_keys = ON; PRAGMA trusted_schema = OFF;");
5304
6203
  connection.registerFunction("eidos_casefold", (value) => value === null ? null : String(value).toUpperCase().toLowerCase());
6204
+ connection.registerFunction("eidos_source_instant_key", sourceInstantComparisonKey, 1);
5305
6205
  connection.registerFunction("eidos_canonical_number", (value) => {
5306
6206
  if (value === null) return null;
5307
6207
  const number = Number(value);
@@ -5564,6 +6464,10 @@ var EidosFileRuntime = class {
5564
6464
  return field;
5565
6465
  }
5566
6466
  /** @internal Exact Runtime service transaction composition hook. */
6467
+ setRequestInstant(instant) {
6468
+ this.requestInstant = instant;
6469
+ }
6470
+ /** @internal Exact Runtime service transaction composition hook. */
5567
6471
  applyCanonicalMutation(operation, expectedRevision) {
5568
6472
  return this.mutate(() => operation(this.operationInstant()), expectedRevision);
5569
6473
  }
@@ -5638,7 +6542,7 @@ var EidosFileRuntime = class {
5638
6542
  input: field,
5639
6543
  isRecordLabel: "isRecordLabel" in field && field.isRecordLabel === true,
5640
6544
  systemRole: null,
5641
- nullable: field.type === "formula" || field.type === "lookup" ? true : field.type === "file" || field.type === "multi-select" || field.type === "relation" ? false : "nullable" in field ? field.nullable !== false : true
6545
+ nullable: field.type === "formula" || field.type === "lookup" ? true : field.type === "file" || field.type === "multi-select" || field.type === "relation" ? false : field.type === "checkbox" ? field.nullable === true : "nullable" in field ? field.nullable !== false : true
5642
6546
  };
5643
6547
  });
5644
6548
  const names = new Set(Object.values(SYSTEM_FIELD_NAMES).map((name) => name.replace(/[A-Z]/g, (character) => character.toLowerCase())));
@@ -5753,6 +6657,7 @@ var EidosFileRuntime = class {
5753
6657
  });
5754
6658
  }
5755
6659
  insertFieldMetadata(tableId, field, position, now) {
6660
+ if (assertEidosFileTemporalDefault(field.type, field.settings, !field.systemRole) === "now") enableTemporalDefaultsFeature(this.connection);
5756
6661
  this.connection.run(`INSERT INTO ${EIDOS_FILE_FIELDS_TABLE}
5757
6662
  (id, table_id, name, physical_name, type, system_role, nullable, position,
5758
6663
  settings_json, created_at, updated_at)
@@ -5981,9 +6886,10 @@ var EidosFileRuntime = class {
5981
6886
  input,
5982
6887
  isRecordLabel: "isRecordLabel" in input && input.isRecordLabel === true,
5983
6888
  systemRole: null,
5984
- nullable: input.type === "formula" || input.type === "lookup" ? true : input.type === "file" || input.type === "multi-select" || input.type === "relation" ? false : "nullable" in input ? input.nullable !== false : true
6889
+ nullable: input.type === "formula" || input.type === "lookup" ? true : input.type === "file" || input.type === "multi-select" || input.type === "relation" ? false : input.type === "checkbox" ? input.nullable === true : "nullable" in input ? input.nullable !== false : true
5985
6890
  };
5986
6891
  if (prepared.physicalName && !prepared.nullable && ![
6892
+ "checkbox",
5987
6893
  "file",
5988
6894
  "multi-select",
5989
6895
  "relation"
@@ -6213,6 +7119,7 @@ var EidosFileRuntime = class {
6213
7119
  now,
6214
7120
  fieldId
6215
7121
  ]);
7122
+ if (assertEidosFileTemporalDefault(field.type, settings, !field.systemRole && !!field.physicalName && settings.readOnly !== true && settings.writable !== false && settings.isSystem !== true) === "now") enableTemporalDefaultsFeature(this.connection);
6216
7123
  if (changes.isRecordLabel === true) {
6217
7124
  if (field.type === "lookup") throw new EidosFileError("invalid-schema", "A Lookup cannot be the Record Label Field in Eidos File 1.0");
6218
7125
  this.connection.run(`UPDATE ${EIDOS_FILE_TABLES_TABLE}
@@ -6280,6 +7187,11 @@ var EidosFileRuntime = class {
6280
7187
  const relationFieldIdsBefore = Array.from(this.allSchema().relations.keys());
6281
7188
  for (const relationFieldId of relationFieldIdsBefore) this.dropRelationTriggers(relationFieldId);
6282
7189
  this.connection.run(`DELETE FROM ${EIDOS_FILE_RELATION_FIELDS_TABLE} WHERE field_id = ?`, [fieldId]);
7190
+ if (targetType !== "date" && targetType !== "datetime" && field.settings?.defaultValue !== void 0) {
7191
+ const settings = { ...field.settings };
7192
+ delete settings.defaultValue;
7193
+ this.connection.run(`UPDATE ${EIDOS_FILE_FIELDS_TABLE} SET settings_json = ? WHERE id = ?`, [canonicalizeEidosFileJson(settings), fieldId]);
7194
+ }
6283
7195
  this.connection.run(`UPDATE ${EIDOS_FILE_FIELDS_TABLE}
6284
7196
  SET type = ?, nullable = ? WHERE id = ?`, [
6285
7197
  targetType,
@@ -6452,6 +7364,8 @@ var EidosFileRuntime = class {
6452
7364
  const tableId = uuid(row.table_id);
6453
7365
  const fields = this.listFields(tableId);
6454
7366
  const query = jsonObject(row.query_json);
7367
+ if (hasEidosFileCalendarQuery(query)) requireCalendarQueryFeature(this.connection);
7368
+ if (hasEidosFileCalendarWindowQuery(query)) requireCalendarWindowFeature(this.connection);
6455
7369
  const layout = jsonObject(row.layout_json);
6456
7370
  const queryStatus = storedViewQueryStatus(query, fields);
6457
7371
  const storedSorts = sortsFromStorage(query.sort);
@@ -6519,6 +7433,8 @@ var EidosFileRuntime = class {
6519
7433
  })) : {};
6520
7434
  const mappedLayoutField = (value) => typeof value === "string" ? fieldByKey.get(value) ?? null : null;
6521
7435
  return this.mutate(() => {
7436
+ if (hasEidosFileCalendarWindowQuery(input.filter)) enableCalendarWindowFeature(this.connection);
7437
+ if (hasEidosFileCalendarQuery({ filter: filterToStorage(input.filter, fields) })) enableCalendarQueryFeature(this.connection);
6522
7438
  this.connection.run(`INSERT INTO ${EIDOS_FILE_VIEWS_TABLE}
6523
7439
  (id, table_id, name, type, query_json, layout_json, position, created_at, updated_at)
6524
7440
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
@@ -6552,6 +7468,57 @@ var EidosFileRuntime = class {
6552
7468
  updateView(viewId, changes) {
6553
7469
  const currentRow = this.viewRow(viewId);
6554
7470
  const current = this.mapView(currentRow);
7471
+ if (changes.upgradeDateQuery || changes.restoreDateQuery) {
7472
+ if (Object.keys(changes).some((key) => key !== "upgradeDateQuery" && key !== "restoreDateQuery") || changes.upgradeDateQuery && changes.restoreDateQuery) throw new EidosFileError("invalid-value", "Date query upgrade/restore must be a separate View change");
7473
+ const source = parseEidosFileJson(currentRow.query_json);
7474
+ const layout = parseEidosFileJson(currentRow.layout_json);
7475
+ const retained = layout[EIDOS_FILE_DATE_QUERY_UPGRADE_RECEIPT];
7476
+ if (retained !== void 0) {
7477
+ if (!retained || typeof retained !== "object" || Array.isArray(retained) || Object.keys(retained).some((key) => ![
7478
+ "version",
7479
+ "originalQuery",
7480
+ "changes"
7481
+ ].includes(key))) throw new EidosFileError("invalid-value", "Existing date query recovery receipt is invalid");
7482
+ if (new TextEncoder().encode(canonicalizeEidosFileJson(retained)).byteLength > 65536) throw new EidosFileError("query-limit", "Date query recovery receipt exceeds 65536 bytes");
7483
+ }
7484
+ let target;
7485
+ let receipt = retained;
7486
+ if (changes.restoreDateQuery) {
7487
+ if (!retained || typeof retained !== "object" || Array.isArray(retained) || !("originalQuery" in retained) || !("version" in retained) || retained.version !== 2) throw new EidosFileError("invalid-value", "No date query recovery receipt is available");
7488
+ target = retained.originalQuery;
7489
+ const preview = upgradeEidosFileDateQuery(target);
7490
+ if (!preview.changes.length) throw new EidosFileError("invalid-value", "Recovery receipt has no retired date query");
7491
+ eidosFileDateQueryUpgradeReceipt(target, preview);
7492
+ } else {
7493
+ const preview = upgradeEidosFileDateQuery(source);
7494
+ if (!preview.changes.length) return current;
7495
+ target = preview.query;
7496
+ if (retained !== void 0) {
7497
+ if (!retained || typeof retained !== "object" || Array.isArray(retained) || !("version" in retained) || retained.version !== 2 || !("originalQuery" in retained)) throw new EidosFileError("invalid-value", "Existing date query recovery receipt is invalid");
7498
+ const original = upgradeEidosFileDateQuery(retained.originalQuery);
7499
+ if (!original.changes.length) throw new EidosFileError("invalid-value", "Recovery receipt has no retired date query");
7500
+ eidosFileDateQueryUpgradeReceipt(retained.originalQuery, original);
7501
+ }
7502
+ receipt ??= eidosFileDateQueryUpgradeReceipt(source, preview);
7503
+ }
7504
+ const queryJson = canonicalizeEidosFileJson(target);
7505
+ if (queryJson === currentRow.query_json && hasCalendarQueryFeature(this.connection)) return current;
7506
+ return this.mutate(() => {
7507
+ enableCalendarQueryFeature(this.connection);
7508
+ if (hasEidosFileCalendarWindowQuery(target)) enableCalendarWindowFeature(this.connection);
7509
+ this.connection.run(`UPDATE ${EIDOS_FILE_VIEWS_TABLE} SET query_json = ?, layout_json = ?, updated_at = ? WHERE id = ?`, [
7510
+ queryJson,
7511
+ canonicalizeEidosFileJson({
7512
+ ...layout,
7513
+ [EIDOS_FILE_DATE_QUERY_UPGRADE_RECEIPT]: receipt
7514
+ }),
7515
+ this.operationInstant(),
7516
+ viewId
7517
+ ]);
7518
+ return this.mapView(this.viewRow(viewId));
7519
+ });
7520
+ }
7521
+ if (current.queryStatus === "unsupported" && (changes.filter !== void 0 || changes.sorts !== void 0)) throw new EidosFileError("unsupported-feature", "Unsupported View query must be upgraded explicitly before editing");
6555
7522
  const fields = this.listFields(current.tableId);
6556
7523
  const name = assertEidosFileDisplayName(changes.name ?? current.name, "View name");
6557
7524
  const foldedName = name.replace(/[A-Z]/g, (character) => character.toLowerCase());
@@ -6560,7 +7527,10 @@ var EidosFileRuntime = class {
6560
7527
  name,
6561
7528
  type: changes.type ?? current.type,
6562
7529
  position: changes.position ?? current.position,
6563
- properties: changes.properties === void 0 ? current.properties : changes.properties,
7530
+ properties: changes.properties === void 0 ? current.properties : {
7531
+ ...changes.properties,
7532
+ ...current.properties?.["space.eidos/date-query-upgrade"] !== void 0 ? { [EIDOS_FILE_DATE_QUERY_UPGRADE_RECEIPT]: current.properties[EIDOS_FILE_DATE_QUERY_UPGRADE_RECEIPT] } : {}
7533
+ },
6564
7534
  filter: changes.filter === void 0 ? current.filter : changes.filter,
6565
7535
  sorts: changes.sorts === void 0 ? current.sorts : changes.sorts,
6566
7536
  orderMap: changes.orderMap === void 0 ? current.orderMap : changes.orderMap,
@@ -6569,6 +7539,8 @@ var EidosFileRuntime = class {
6569
7539
  const queryChanged = changes.filter !== void 0 || changes.sorts !== void 0;
6570
7540
  const layoutChanged = changes.properties !== void 0 || changes.orderMap !== void 0 || changes.hiddenFields !== void 0;
6571
7541
  return this.mutate(() => {
7542
+ if (queryChanged && hasEidosFileCalendarWindowQuery(next.filter)) enableCalendarWindowFeature(this.connection);
7543
+ if (queryChanged && hasEidosFileCalendarQuery({ filter: filterToStorage(next.filter, fields) })) enableCalendarQueryFeature(this.connection);
6572
7544
  const fieldByKey = new Map(fields.flatMap((field) => field.id ? [[field.tableColumnName, field.id], [field.id, field.id]] : []));
6573
7545
  const sorts = normalizeEidosFileSorts(next.sorts).flatMap((sort) => {
6574
7546
  const id = fieldByKey.get(sort.field);
@@ -6817,9 +7789,16 @@ var EidosFileRuntime = class {
6817
7789
  }).join(", ")}
6818
7790
  FROM ${quoteIdentifier(table.physical_name)} base`,
6819
7791
  fields,
6820
- schema
7792
+ schema,
7793
+ externalInstants: this.isVirtualTable(tableId)
6821
7794
  };
6822
7795
  }
7796
+ compileRowQuery(source, query, context) {
7797
+ return compileEidosFileRowQuery(source.fields, query, {
7798
+ ...context,
7799
+ externalInstants: source.externalInstants
7800
+ });
7801
+ }
6823
7802
  compatibilityQuery(tableId, query) {
6824
7803
  assertEidosFileRowQuery(query);
6825
7804
  const fields = this.listFields(tableId);
@@ -6869,6 +7848,31 @@ var EidosFileRuntime = class {
6869
7848
  return this.getRowPage(tableId, options.offset ?? 0, options.limit ?? 100, options.query ?? {}).rows;
6870
7849
  }
6871
7850
  getRowPage(tableId, offset, limit, query = {}, totalHint, cursor, projection) {
7851
+ const page = this.readRowPage(tableId, offset, limit, query, cursor, projection);
7852
+ const total = totalHint ?? this.countRows(tableId, query, page.referenceInstant);
7853
+ const nextOffset = page.effectiveOffset + page.rawRows.length;
7854
+ const lastRawRow = page.rawRows.at(-1);
7855
+ const nextCursor = lastRawRow && page.rawRows.length === limit && nextOffset < total ? encodeURIComponent(JSON.stringify({
7856
+ version: 1,
7857
+ revision: page.revision,
7858
+ tableId,
7859
+ query: page.querySignature,
7860
+ offset: nextOffset,
7861
+ values: page.sorts.map(({ field }) => encodeCursorSqlValue(cursorSortValue(lastRawRow, field))),
7862
+ lastId: String(lastRawRow.__base_rowid),
7863
+ direction: "forward",
7864
+ referenceInstant: page.referenceInstant
7865
+ })) : void 0;
7866
+ return {
7867
+ tableId,
7868
+ offset: page.effectiveOffset,
7869
+ limit,
7870
+ total,
7871
+ rows: page.rows,
7872
+ ...nextCursor ? { nextCursor } : {}
7873
+ };
7874
+ }
7875
+ readRowPage(tableId, offset, limit, query, cursor, projection) {
6872
7876
  if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 1e4) throw new EidosFileError("query-limit", "Invalid Eidos File page bounds");
6873
7877
  const compatibleQuery = this.compatibilityQuery(tableId, query);
6874
7878
  const fields = this.listFields(tableId);
@@ -6884,7 +7888,7 @@ var EidosFileRuntime = class {
6884
7888
  let effectiveOffset = offset;
6885
7889
  let cursorWhere = "";
6886
7890
  let cursorParams = [];
6887
- let referenceInstant = this.nowInstant();
7891
+ let referenceInstant = compatibleQuery.referenceInstant ?? this.nowInstant();
6888
7892
  if (cursor) try {
6889
7893
  const payload = JSON.parse(decodeURIComponent(cursor));
6890
7894
  if (payload.version !== 1 || payload.direction !== "forward" || payload.revision !== revision || payload.tableId !== tableId || payload.query !== querySignature || !Array.isArray(payload.values)) throw new Error("cursor binding mismatch");
@@ -6896,7 +7900,7 @@ var EidosFileRuntime = class {
6896
7900
  } catch {
6897
7901
  throw new EidosFileError("invalid-query", "Invalid or stale Eidos File cursor");
6898
7902
  }
6899
- const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, { referenceInstant });
7903
+ const compiled = this.compileRowQuery(source, compatibleQuery, { referenceInstant });
6900
7904
  const whereSql = cursorWhere ? compiled.whereSql ? `${compiled.whereSql} AND ${cursorWhere}` : `WHERE ${cursorWhere}` : compiled.whereSql;
6901
7905
  const rawRows = this.connection.query(`WITH logical AS (${source.sql})
6902
7906
  SELECT * FROM logical ${whereSql} ${compiled.orderSql}
@@ -6909,54 +7913,45 @@ var EidosFileRuntime = class {
6909
7913
  limit,
6910
7914
  effectiveOffset
6911
7915
  ]);
6912
- const rows = rawRows.map((row) => {
6913
- const mapped = {};
6914
- for (const [key, value] of Object.entries(row)) if (key !== "__base_rowid") mapped[key] = rowValue(value);
6915
- if (!projection) return mapped;
6916
- const preserved = new Set(["_id", ...projection.preservedColumns ?? []]);
6917
- const candidates = projection.columns;
6918
- const selected = new Set(preserved);
6919
- let count = 0;
6920
- for (const key of candidates) {
6921
- const value = mapped[key];
6922
- if (projection.omitEmptyFields && (value === null || value === void 0 || value === "" || value === "[]")) continue;
6923
- if (projection.fieldLimit !== void 0 && count >= projection.fieldLimit) break;
6924
- selected.add(key);
6925
- if (`${key}__display` in mapped) selected.add(`${key}__display`);
6926
- count += 1;
6927
- }
6928
- return Object.fromEntries(Object.entries(mapped).filter(([key]) => selected.has(key)));
6929
- });
6930
- const total = totalHint ?? this.countRows(tableId, query, referenceInstant);
6931
- const nextOffset = effectiveOffset + rawRows.length;
6932
- const lastRawRow = rawRows.at(-1);
6933
- const nextCursor = lastRawRow && rawRows.length === limit && nextOffset < total ? encodeURIComponent(JSON.stringify({
6934
- version: 1,
6935
- revision,
6936
- tableId,
6937
- query: querySignature,
6938
- offset: nextOffset,
6939
- values: sorts.map(({ field }) => encodeCursorSqlValue(cursorSortValue(lastRawRow, field))),
6940
- lastId: String(lastRawRow.__base_rowid),
6941
- direction: "forward",
6942
- referenceInstant
6943
- })) : void 0;
6944
7916
  return {
6945
- tableId,
6946
- offset: effectiveOffset,
6947
- limit,
6948
- total,
6949
- rows,
6950
- ...nextCursor ? { nextCursor } : {}
7917
+ rows: rawRows.map((row) => {
7918
+ const mapped = {};
7919
+ for (const [key, value] of Object.entries(row)) if (key !== "__base_rowid") mapped[key] = rowValue(value);
7920
+ if (!projection) return mapped;
7921
+ const preserved = new Set(["_id", ...projection.preservedColumns ?? []]);
7922
+ const candidates = projection.columns;
7923
+ const selected = new Set(preserved);
7924
+ let count = 0;
7925
+ for (const key of candidates) {
7926
+ const value = mapped[key];
7927
+ if (projection.omitEmptyFields && (value === null || value === void 0 || value === "" || value === "[]")) continue;
7928
+ if (projection.fieldLimit !== void 0 && count >= projection.fieldLimit) break;
7929
+ selected.add(key);
7930
+ if (`${key}__display` in mapped) selected.add(`${key}__display`);
7931
+ count += 1;
7932
+ }
7933
+ return Object.fromEntries(Object.entries(mapped).filter(([key]) => selected.has(key)));
7934
+ }),
7935
+ rawRows,
7936
+ effectiveOffset,
7937
+ referenceInstant,
7938
+ revision,
7939
+ querySignature,
7940
+ sorts
6951
7941
  };
6952
7942
  }
6953
7943
  /** Returns the zero-based position of a Row ID in a filtered/sorted query. */
6954
7944
  getRowIndex(tableId, rowId, query = {}) {
7945
+ const index = this.getRowIndexValue(tableId, rowId, query);
7946
+ return index === null ? null : Number(index);
7947
+ }
7948
+ /** @internal Exact scalar index for the asynchronous Runtime boundary. */
7949
+ getRowIndexValue(tableId, rowId, query = {}) {
6955
7950
  const id = this.assertRowId(tableId, rowId, "Row ID");
6956
7951
  const compatibleQuery = this.compatibilityQuery(tableId, query);
6957
7952
  const fields = this.listFields(tableId);
6958
7953
  const source = this.logicalSource(tableId, this.requiredQueryFieldKeys(fields, compatibleQuery), false, false, this.querySearchFragmentFieldIds(fields, compatibleQuery));
6959
- const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, { referenceInstant: this.nowInstant() });
7954
+ const compiled = this.compileRowQuery(source, compatibleQuery, { referenceInstant: query.referenceInstant ?? this.nowInstant() });
6960
7955
  const sorts = uniqueSortFields(source.fields, compatibleQuery.sorts);
6961
7956
  const targetWhere = compiled.whereSql ? `${compiled.whereSql} AND "__base_rowid" = ?` : "WHERE \"__base_rowid\" = ?";
6962
7957
  const target = this.connection.get(`WITH logical AS (${source.sql})
@@ -6966,14 +7961,14 @@ var EidosFileRuntime = class {
6966
7961
  const beforeWhere = compiled.whereSql ? `${compiled.whereSql} AND ${before.sql}` : `WHERE ${before.sql}`;
6967
7962
  const result = this.connection.get(`WITH logical AS (${source.sql})
6968
7963
  SELECT COUNT(*) AS count FROM logical ${beforeWhere}`, [...compiled.params, ...before.params]);
6969
- return Number(result?.count ?? 0);
7964
+ return String(result?.count ?? 0);
6970
7965
  }
6971
7966
  getRecordNeighbors(tableId, rowId, query = {}) {
6972
7967
  const id = this.assertRowId(tableId, rowId, "Row ID");
6973
7968
  const compatibleQuery = this.compatibilityQuery(tableId, query);
6974
7969
  const fields = this.listFields(tableId);
6975
7970
  const source = this.logicalSource(tableId, this.requiredQueryFieldKeys(fields, compatibleQuery), false, false, this.querySearchFragmentFieldIds(fields, compatibleQuery));
6976
- const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, { referenceInstant: this.nowInstant() });
7971
+ const compiled = this.compileRowQuery(source, compatibleQuery, { referenceInstant: query.referenceInstant ?? this.nowInstant() });
6977
7972
  const targetWhere = compiled.whereSql ? `${compiled.whereSql} AND "__base_rowid" = ?` : "WHERE \"__base_rowid\" = ?";
6978
7973
  const target = this.connection.get(`WITH logical AS (${source.sql}) SELECT * FROM logical ${targetWhere} LIMIT 1`, [...compiled.params, id]);
6979
7974
  if (!target) return { found: false };
@@ -7013,6 +8008,20 @@ var EidosFileRuntime = class {
7013
8008
  ...page.nextCursor ? { nextCursor: page.nextCursor } : {}
7014
8009
  };
7015
8010
  }
8011
+ /** @internal Bounded logical rows; the service owns sentinel paging and totals. */
8012
+ runtimeQueryRows(tableId, options) {
8013
+ const fields = this.listFields(tableId);
8014
+ const requested = options.fields.map((id) => this.fieldByKey(tableId, id));
8015
+ const rowIdField = fields.find((field) => field.type === "row-id");
8016
+ const page = this.readRowPage(tableId, options.offset ?? 0, options.limit, options.query, options.cursor, {
8017
+ columns: requested.map((field) => field.tableColumnName),
8018
+ preservedColumns: [rowIdField.tableColumnName],
8019
+ fieldLimit: requested.length,
8020
+ includeRecordLabel: false,
8021
+ includeRelationDisplays: options.resolveRelations
8022
+ });
8023
+ return this.logicalRows(rowIdField, requested, page.rows, options.resolveRelations);
8024
+ }
7016
8025
  /** @internal Bounded first pages sharing one materialized source scan. */
7017
8026
  runtimeQueryRowPages(tableId, queries, fieldIds, limit, resolveRelations) {
7018
8027
  if (queries.length === 0) return [];
@@ -7025,9 +8034,13 @@ var EidosFileRuntime = class {
7025
8034
  rowIdField.id,
7026
8035
  ...compatible.flatMap((query) => [...this.requiredQueryFieldKeys(fields, query)])
7027
8036
  ], false, resolveRelations, new Set(compatible.flatMap((query) => [...this.querySearchFragmentFieldIds(fields, query)])));
7028
- const referenceInstant = this.nowInstant();
7029
- const compiled = compatible.map((query) => compileEidosFileRowQuery(source.fields, query, { referenceInstant }));
7030
- const prefix = `__batch_${this.allocateId().replaceAll("-", "")}`;
8037
+ const referenceInstant = queries[0]?.referenceInstant ?? this.nowInstant();
8038
+ const compiled = compatible.map((query) => this.compileRowQuery(source, query, { referenceInstant }));
8039
+ const columnNames = new Set(source.fields.map((field) => field.tableColumnName));
8040
+ let prefix;
8041
+ do
8042
+ prefix = `__batch_${++this.batchQuerySequence}`;
8043
+ while (columnNames.has(`${prefix}_page`) || columnNames.has(`${prefix}_count`));
7031
8044
  const batchKey = `${prefix}_page`;
7032
8045
  const countKey = `${prefix}_count`;
7033
8046
  const params = [];
@@ -7108,7 +8121,7 @@ var EidosFileRuntime = class {
7108
8121
  const compatibleQuery = this.compatibilityQuery(tableId, query);
7109
8122
  const fields = this.listFields(tableId);
7110
8123
  const source = this.logicalSource(tableId, [...fieldIds, ...this.requiredQueryFieldKeys(fields, compatibleQuery)], false, false, this.querySearchFragmentFieldIds(fields, compatibleQuery));
7111
- const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, { referenceInstant: this.nowInstant() });
8124
+ const compiled = this.compileRowQuery(source, compatibleQuery, { referenceInstant: query.referenceInstant ?? this.nowInstant() });
7112
8125
  const selectedFields = fieldIds.map((fieldId) => this.fieldByKey(tableId, fieldId));
7113
8126
  const encodedValues = selectedFields.map((field) => {
7114
8127
  const column = quoteIdentifier(field.tableColumnName);
@@ -7179,14 +8192,14 @@ var EidosFileRuntime = class {
7179
8192
  values: values.map((value) => encodeCursorSqlValue(value)),
7180
8193
  lastId: row.id,
7181
8194
  direction: "forward",
7182
- referenceInstant: this.nowInstant()
8195
+ referenceInstant: query.referenceInstant ?? this.nowInstant()
7183
8196
  }));
7184
8197
  }
7185
- countRows(tableId, query = {}, referenceInstant = this.nowInstant()) {
8198
+ countRows(tableId, query = {}, referenceInstant = query.referenceInstant ?? this.nowInstant()) {
7186
8199
  const compatibleQuery = this.compatibilityQuery(tableId, query);
7187
8200
  const fields = this.listFields(tableId);
7188
8201
  const source = this.logicalSource(tableId, this.requiredQueryFieldKeys(fields, compatibleQuery), false, false, this.querySearchFragmentFieldIds(fields, compatibleQuery));
7189
- const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, { referenceInstant });
8202
+ const compiled = this.compileRowQuery(source, compatibleQuery, { referenceInstant });
7190
8203
  return this.connection.get(`WITH logical AS (${source.sql}) SELECT count(*) AS count FROM logical ${compiled.whereSql}`, compiled.params)?.count ?? 0;
7191
8204
  }
7192
8205
  countRowsByField(tableId, fieldKey, query = {}) {
@@ -7194,7 +8207,7 @@ var EidosFileRuntime = class {
7194
8207
  const compatibleQuery = this.compatibilityQuery(tableId, query);
7195
8208
  const fields = this.listFields(tableId);
7196
8209
  const source = this.logicalSource(tableId, [field.id, ...this.requiredQueryFieldKeys(fields, compatibleQuery)], false, false, this.querySearchFragmentFieldIds(fields, compatibleQuery));
7197
- const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, { referenceInstant: this.nowInstant() });
8210
+ const compiled = this.compileRowQuery(source, compatibleQuery, { referenceInstant: query.referenceInstant ?? this.nowInstant() });
7198
8211
  const column = quoteIdentifier(field.tableColumnName);
7199
8212
  if (field.storageCodec === "json_array" || field.storageCodec === "relation") return this.connection.query(`WITH logical AS (${source.sql}), filtered AS (
7200
8213
  SELECT * FROM logical ${compiled.whereSql}
@@ -7211,7 +8224,7 @@ var EidosFileRuntime = class {
7211
8224
  const fields = this.listFields(tableId);
7212
8225
  configs = normalizeEidosFileColumnStatConfigs(configs, fields);
7213
8226
  const source = this.logicalSource(tableId, [...configs.map((config) => config.fieldId), ...this.requiredQueryFieldKeys(fields, compatibleQuery)], false, false, this.querySearchFragmentFieldIds(fields, compatibleQuery));
7214
- const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, { referenceInstant: this.nowInstant() });
8227
+ const compiled = this.compileRowQuery(source, compatibleQuery, { referenceInstant: query.referenceInstant ?? this.nowInstant() });
7215
8228
  return configs.map((config) => {
7216
8229
  const field = this.fieldByKey(tableId, config.fieldId);
7217
8230
  const column = quoteIdentifier(field.tableColumnName);
@@ -7261,7 +8274,7 @@ var EidosFileRuntime = class {
7261
8274
  ...this.requiredQueryFieldKeys(fields, compatibleQuery)
7262
8275
  ];
7263
8276
  const source = this.logicalSource(tableId, requiredFieldIds, false, false, this.querySearchFragmentFieldIds(fields, compatibleQuery));
7264
- const compiled = compileEidosFileRowQuery(source.fields, compatibleQuery, { referenceInstant: this.nowInstant() });
8277
+ const compiled = this.compileRowQuery(source, compatibleQuery, { referenceInstant: query.referenceInstant ?? this.nowInstant() });
7265
8278
  let metricSql = "count(*)";
7266
8279
  if (options.metric.op === "count") metricSql = metricField ? `count(${quoteIdentifier(metricField.tableColumnName)})` : "count(*)";
7267
8280
  else if (metricField) {
@@ -7408,7 +8421,7 @@ var EidosFileRuntime = class {
7408
8421
  if (typeof value === "string" || typeof value === "number" || typeof value === "bigint") return value;
7409
8422
  throw new EidosFileError("invalid-value", `Unsupported value for ${field.name}`);
7410
8423
  }
7411
- rowChanges(tableId, row, allowUnresolvedRelations, applyCreateDefaults = false) {
8424
+ rowChanges(tableId, row, allowUnresolvedRelations, createMode, creationContext) {
7412
8425
  const changes = [];
7413
8426
  for (const [key, value] of Object.entries(row)) {
7414
8427
  if (key === "_id" || key === "id" || key.endsWith("__display")) continue;
@@ -7419,27 +8432,54 @@ var EidosFileRuntime = class {
7419
8432
  value: this.normalizeStoredValue(field, value, allowUnresolvedRelations)
7420
8433
  });
7421
8434
  }
7422
- if (applyCreateDefaults) {
8435
+ if (createMode) {
7423
8436
  const suppliedFieldIds = new Set(changes.map((change) => change.field.id));
7424
8437
  for (const field of this.listFields(tableId)) {
7425
- if (field.type !== "select" || !field.id || !field.physicalName || suppliedFieldIds.has(field.id)) continue;
7426
- const defaultOption = parseEidosFileSelectDefaultOption(field.settings);
7427
- if (defaultOption === null) continue;
8438
+ if (field.type !== "checkbox" && (createMode !== "ordinary" || ![
8439
+ "select",
8440
+ "date",
8441
+ "datetime"
8442
+ ].includes(field.type)) || !field.id || !field.physicalName || field.valueKind === "system" || field.settings?.writable === false || field.settings?.readOnly === true || field.settings?.isSystem === true || suppliedFieldIds.has(field.id)) continue;
8443
+ const defaultValue = field.type === "checkbox" ? false : field.type === "select" ? parseEidosFileSelectDefaultOption(field.settings) : eidosFileTemporalDefaultValue(field.type, field.settings, this.operationInstant(), creationContext);
8444
+ if (defaultValue === null) continue;
7428
8445
  changes.push({
7429
8446
  field,
7430
- value: this.normalizeStoredValue(field, defaultOption, allowUnresolvedRelations)
8447
+ value: this.normalizeStoredValue(field, defaultValue, allowUnresolvedRelations)
7431
8448
  });
7432
8449
  }
7433
8450
  }
7434
8451
  return changes;
7435
8452
  }
7436
- insertRowInTransaction(tableId, row, allowUnresolvedRelations, applyCreateDefaults) {
8453
+ insertRowInTransaction(tableId, row, allowUnresolvedRelations, applyCreateDefaults, creationContext, creationQuery) {
7437
8454
  if (!this.tableCapabilities(tableId).insert) throw new EidosFileError("table-mutation-not-supported", "Virtual table does not support row creation");
7438
8455
  const table = this.getTable(tableId);
7439
8456
  const requestedId = row._id ?? row.id;
7440
8457
  const rowId = typeof requestedId === "string" ? this.assertRowId(tableId, requestedId, "Row ID") : this.allocateId();
7441
8458
  const now = this.operationInstant();
7442
- const changes = this.rowChanges(tableId, row, allowUnresolvedRelations, applyCreateDefaults);
8459
+ let changes = this.rowChanges(tableId, row, allowUnresolvedRelations, applyCreateDefaults ? "ordinary" : "import", creationContext);
8460
+ if (applyCreateDefaults && creationQuery?.filter) {
8461
+ const checkFields = (group) => {
8462
+ for (const child of group.children) if (child.type === "group") checkFields(child);
8463
+ else this.fieldByKey(tableId, child.field);
8464
+ };
8465
+ assertEidosFileRowQuery(creationQuery);
8466
+ checkFields(creationQuery.filter);
8467
+ const fields = this.listFields(tableId);
8468
+ const explicit = Object.fromEntries(this.rowChanges(tableId, row, allowUnresolvedRelations).map(({ field, value }) => [field.tableColumnName, value]));
8469
+ const defaults = Object.fromEntries(changes.map(({ field, value }) => [field.tableColumnName, value]));
8470
+ for (const field of fields) if (!Object.hasOwn(defaults, field.tableColumnName) && field.nullable === false && ["json_array", "relation"].includes(field.storageCodec)) defaults[field.tableColumnName] = "[]";
8471
+ const inferred = inferEidosFileCreationDefaults(this.connection, fields, this.compatibilityQuery(tableId, creationQuery), explicit, defaults, now, (field, value) => this.normalizeStoredValue(field, value, false));
8472
+ changes = this.rowChanges(tableId, {
8473
+ ...inferred,
8474
+ ...row
8475
+ }, allowUnresolvedRelations, "ordinary", creationContext);
8476
+ const supplied = new Set(changes.map(({ field }) => field.id));
8477
+ for (const field of fields) if (field.nullable === false && field.valueKind === "source" && field.writable !== false && !supplied.has(field.id) && ![
8478
+ "file",
8479
+ "multi-select",
8480
+ "checkbox"
8481
+ ].includes(field.type)) throw new EidosFileError("invalid-value", `Required Field value is missing: ${field.name}`);
8482
+ }
7443
8483
  const columns = [
7444
8484
  "_id",
7445
8485
  "_created_at",
@@ -7486,15 +8526,19 @@ var EidosFileRuntime = class {
7486
8526
  if (!field.physicalName || field.valueKind === "system" || field.settings?.writable === false || field.settings?.readOnly === true || field.settings?.isSystem === true) throw new EidosFileError("protected-field", `Field ${field.name} is read-only`);
7487
8527
  return field;
7488
8528
  });
8529
+ const suppliedFieldIds = new Set(plannedFields.map((field) => field.id));
8530
+ const defaultCheckboxFields = fields.filter((field) => field.type === "checkbox" && field.physicalName && field.valueKind !== "system" && field.settings?.writable !== false && field.settings?.readOnly !== true && field.settings?.isSystem !== true && !suppliedFieldIds.has(field.id));
7489
8531
  const columns = [
7490
8532
  "_id",
7491
8533
  "_created_at",
7492
8534
  "_updated_at",
7493
- ...plannedFields.map((field) => field.physicalName)
8535
+ ...plannedFields.map((field) => field.physicalName),
8536
+ ...defaultCheckboxFields.map((field) => field.physicalName)
7494
8537
  ];
7495
8538
  plan = {
7496
8539
  keys,
7497
8540
  fields: plannedFields,
8541
+ defaultCheckboxCount: defaultCheckboxFields.length,
7498
8542
  sql: `INSERT INTO ${quoteIdentifier(tableName)}
7499
8543
  (${columns.map(quoteIdentifier).join(", ")})
7500
8544
  VALUES (${columns.map(() => "?").join(", ")})`,
@@ -7506,7 +8550,8 @@ var EidosFileRuntime = class {
7506
8550
  rowId,
7507
8551
  now,
7508
8552
  now,
7509
- ...plan.keys.map((key, index) => this.normalizeStoredValue(plan.fields[index], row[key], true))
8553
+ ...plan.keys.map((key, index) => this.normalizeStoredValue(plan.fields[index], row[key], true)),
8554
+ ...Array(plan.defaultCheckboxCount).fill(0)
7510
8555
  ];
7511
8556
  plan.parameterSets.push(values);
7512
8557
  return rowId;
@@ -7515,8 +8560,9 @@ var EidosFileRuntime = class {
7515
8560
  else for (const values of plan.parameterSets) this.connection.run(plan.sql, values);
7516
8561
  return ids;
7517
8562
  }
7518
- insertRow(tableId, row) {
7519
- const id = this.mutate(() => this.insertRowInTransaction(tableId, row, true, true));
8563
+ insertRow(tableId, row, creationContext) {
8564
+ if (creationContext !== void 0) assertEidosFileCreationContext(creationContext);
8565
+ const id = this.mutate(() => this.insertRowInTransaction(tableId, row, true, true, creationContext));
7520
8566
  return this.getRow(tableId, id);
7521
8567
  }
7522
8568
  insertImportedRow(tableId, row) {
@@ -7919,6 +8965,7 @@ var EidosFileRuntime = class {
7919
8965
  return row;
7920
8966
  }
7921
8967
  mutateRows(input) {
8968
+ if (input.creationContext !== void 0) assertEidosFileCreationContext(input.creationContext);
7922
8969
  const operationCount = (input.insert?.length ?? 0) + (input.update?.length ?? 0) + (input.delete?.length ?? 0);
7923
8970
  if (operationCount === 0) throw new EidosFileError("invalid-value", "mutateRows requires at least one operation");
7924
8971
  if (operationCount > 500) throw new EidosFileError("resource-limit", "mutateRows accepts at most 500 row operations per atomic batch");
@@ -7975,7 +9022,7 @@ var EidosFileRuntime = class {
7975
9022
  }
7976
9023
  }
7977
9024
  }
7978
- const inserted = (input.insert ?? []).map((row) => this.insertRowInTransaction(input.tableId, this.logicalMutationFields(input.tableId, row.fields, row.id), false, true));
9025
+ const inserted = (input.insert ?? []).map((row) => this.insertRowInTransaction(input.tableId, this.logicalMutationFields(input.tableId, row.fields, row.id), false, true, input.creationContext, input.creationQuery));
7979
9026
  const changedUpdates = [];
7980
9027
  for (const { rowId, changes } of preparedUpdates) {
7981
9028
  if (changes.length === 0) continue;
@@ -8061,6 +9108,6 @@ function fieldValueTypeForScan(field) {
8061
9108
  return field.type;
8062
9109
  }
8063
9110
  //#endregion
8064
- export { EIDOS_FILE_FORMAT as $, eidosFileLookupDisplayType as A, compileEidosFileFormula as B, isEidosFileFilterOperator as C, assertExactConnectionBindings as Ct, removeEidosFileFilterField as D, nativeToSqlValue as Dt, normalizeEidosFileSorts as E, exactConnectionBindingCount as Et, eidosFileLookupValueType as F, configuredTypeRef as G, compileEidosFileFormulaSource as H, EIDOS_FILE_FORMULA_FIELD_FUNCTION_NAMES as I, eidosFileTypeRefQueryCapabilities as J, eidosFileFieldQueryCapabilities as K, EIDOS_FILE_FORMULA_FUNCTION_NAMES as L, eidosFileLookupStorageCodec as M, eidosFileLookupTargetDisplayType as N, eidosFileFieldStoresJsonArray as O, sqlValueToNative as Ot, eidosFileLookupTargetValueType as P, EIDOS_FILE_FIELDS_TABLE as Q, EIDOS_FILE_FORMULA_PROFILE as R, eidosFileSortExpression as S, EidosAdapterError as St, normalizeEidosFileRowQuery as T, assertUnicodeString as Tt, eidosFileFormulaReferences as U, compileEidosFileFormulaFields as V, rewriteEidosFileFormulaFieldReferences as W, EIDOS_FILE_EXTENSION as X, EIDOS_FILE_APPLICATION_ID as Y, EIDOS_FILE_FEATURES_TABLE as Z, assertEidosFileRowQuery as _, eidosFileTextMultiSelectChoices as _t, EIDOS_FILE_FORMAT_VERSION_TEXT as a, EIDOS_FILE_RELATION_FIELDS_TABLE as at, eidosFileRowQueryPredicateColumns as b, recommendedEidosFileConversionPolicies as bt, incrementEidosFileRevision as c, EIDOS_FILE_SYSTEM_COLUMNS as ct, decodeEidosFileRelationDisplay as d, SQLITE_HEADER as dt, EIDOS_FILE_FORMAT_VERSION as et, decodeEidosFileRelationIds as f, hasEidosFileSqliteHeader as ft, parseNonNegativeInt64 as g, eidosFileConversionTargetNullable as gt, cancellationPortFromSignal as h, eidosFileConversionCanReusePhysicalColumn as ht, scanStableRowPages as i, EIDOS_FILE_MIME_TYPE as it, eidosFileLookupElementType as j, eidosFileLookupAggregateSupportsTarget as k, initializeEidosFileSchema as l, EIDOS_FILE_TABLES_TABLE as lt, MemoryByteSource as m, eidosFileColumnStatTypesForField as mt, validateEidosFile as n, EIDOS_FILE_LOOKUP_FIELDS_TABLE as nt, EIDOS_FILE_SCHEMA_SQL as o, EIDOS_FILE_REQUIRED_TABLES as ot, encodeEidosFileRelationIds as p, eidosFileColumnStatLabel as pt, eidosFileFieldValueType as q, smallestDependencyCycle as r, EIDOS_FILE_META_TABLE as rt, configureEidosFileConnection as s, EIDOS_FILE_SCHEMA_VERSION as st, EidosFileRuntime as t, EIDOS_FILE_FORMULA_FIELDS_TABLE as tt, setEidosFileMetadata as u, EIDOS_FILE_VIEWS_TABLE as ut, compileEidosFileRowQuery as v, isEidosFileUriReference as vt, normalizeEidosFileFilter as w, assertInt64Decimal as wt, eidosFileRowQuerySearchFields as x, ConnectionPortEidosFileConnection as xt, eidosFileRowQueryAffectedByFieldChanges as y, planCanonicalFieldConversion as yt, assertEidosFileFormulaProfile as z };
9111
+ export { isEidosFileCalendarDayValue as $, assertInt64Decimal as $t, eidosFileRowQuerySearchFields as A, EIDOS_FILE_FORMULA_FIELDS_TABLE as At, isEidosFileCalendarWindowValue as B, SQLITE_HEADER as Bt, MemoryByteSource as C, eidosFileTypeRefQueryCapabilities as Ct, compileEidosFileRowQuery as D, EIDOS_FILE_FIELDS_TABLE as Dt, assertEidosFileRowQuery as E, EIDOS_FILE_FEATURES_TABLE as Et, normalizeEidosFileSorts as F, EIDOS_FILE_REQUIRED_TABLES as Ft, isEidosFileCalendarPeriodValue as G, eidosFileConversionTargetNullable as Gt, eidosFileCalendarPeriodBounds as H, eidosFileColumnStatLabel as Ht, removeEidosFileFilterField as I, EIDOS_FILE_SCHEMA_VERSION as It, EIDOS_FILE_CALENDAR_TIME_ZONE_DATA as J, planCanonicalFieldConversion as Jt, EIDOS_FILE_CALENDAR_MAX_YEAR as K, eidosFileTextMultiSelectChoices as Kt, EIDOS_FILE_CALENDAR_WINDOW_COUNT_MAX as L, EIDOS_FILE_SYSTEM_COLUMNS as Lt, isEidosFileFilterOperator as M, EIDOS_FILE_META_TABLE as Mt, normalizeEidosFileFilter as N, EIDOS_FILE_MIME_TYPE as Nt, eidosFileRowQueryAffectedByFieldChanges as O, EIDOS_FILE_FORMAT as Ot, normalizeEidosFileRowQuery as P, EIDOS_FILE_RELATION_FIELDS_TABLE as Pt, eidosFileCalendarTimeZones as Q, assertExactConnectionBindings as Qt, eidosFileCalendarWindowBounds as R, EIDOS_FILE_TABLES_TABLE as Rt, encodeEidosFileRelationIds as S, eidosFileFieldValueType as St, parseNonNegativeInt64 as T, EIDOS_FILE_EXTENSION as Tt, hasEidosFileCalendarPeriodQuery as U, eidosFileColumnStatTypesForField as Ut, assertEidosFileCalendarContext as V, hasEidosFileSqliteHeader as Vt, hasEidosFileCalendarQuery as W, eidosFileConversionCanReusePhysicalColumn as Wt, eidosFileCalendarDateRangeIntervals as X, ConnectionPortEidosFileConnection as Xt, assertEidosFileCalendarZone as Y, recommendedEidosFileConversionPolicies as Yt, eidosFileCalendarDayBounds as Z, EidosAdapterError as Zt, assertEidosFileTemporalDefault as _, compileEidosFileFormulaSource as _t, EIDOS_FILE_DATE_QUERY_UPGRADE_RECEIPT_MAX_BYTES as a, eidosFileLookupDisplayType as at, decodeEidosFileRelationDisplay as b, configuredTypeRef as bt, upgradeEidosFileDateQuery as c, eidosFileLookupTargetDisplayType as ct, EIDOS_FILE_SCHEMA_SQL as d, EIDOS_FILE_FORMULA_FIELD_FUNCTION_NAMES as dt, assertUnicodeString as en, projectEidosFileCalendarInstant as et, configureEidosFileConnection as f, EIDOS_FILE_FORMULA_FUNCTION_NAMES as ft, assertEidosFileCreationContext as g, compileEidosFileFormulaFields as gt, setEidosFileMetadata as h, compileEidosFileFormula as ht, EIDOS_FILE_DATE_QUERY_UPGRADE_RECEIPT as i, eidosFileLookupAggregateSupportsTarget as it, eidosFileSortExpression as j, EIDOS_FILE_LOOKUP_FIELDS_TABLE as jt, eidosFileRowQueryPredicateColumns as k, EIDOS_FILE_FORMAT_VERSION as kt, scanStableRowPages as l, eidosFileLookupTargetValueType as lt, initializeEidosFileSchema as m, assertEidosFileFormulaProfile as mt, validateEidosFile as n, nativeToSqlValue as nn, supportsEidosFileCalendarProfile as nt, eidosFileDateQueryUpgradeReceipt as o, eidosFileLookupElementType as ot, incrementEidosFileRevision as p, EIDOS_FILE_FORMULA_PROFILE as pt, EIDOS_FILE_CALENDAR_MIN_YEAR as q, isEidosFileUriReference as qt, smallestDependencyCycle as r, sqlValueToNative as rn, eidosFileFieldStoresJsonArray as rt, hasRetiredEidosFileDateQuery as s, eidosFileLookupStorageCodec as st, EidosFileRuntime as t, exactConnectionBindingCount as tn, resolveEidosFileCalendarInstant as tt, EIDOS_FILE_FORMAT_VERSION_TEXT as u, eidosFileLookupValueType as ut, eidosFileTemporalDefaultValue as v, eidosFileFormulaReferences as vt, cancellationPortFromSignal as w, EIDOS_FILE_APPLICATION_ID as wt, decodeEidosFileRelationIds as x, eidosFileFieldQueryCapabilities as xt, enableTemporalDefaultsFeature as y, rewriteEidosFileFormulaFieldReferences as yt, hasEidosFileCalendarWindowQuery as z, EIDOS_FILE_VIEWS_TABLE as zt };
8065
9112
 
8066
- //# sourceMappingURL=runtime-CTUCLd5Z.mjs.map
9113
+ //# sourceMappingURL=runtime-CpJ2VAXw.mjs.map