@eidos.space/eidos-file 1.0.0 → 2.0.2

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 (47) hide show
  1. package/DEVELOPER_PLATFORM.md +17 -11
  2. package/FIELD-CONVERSION.md +75 -0
  3. package/README.md +18 -2
  4. package/dist/{adapter-contract-B3p-48Yb.d.mts → adapter-contract-CPhqAl4b.d.mts} +46 -65
  5. package/dist/adapter-contract-CPhqAl4b.d.mts.map +1 -0
  6. package/dist/better-sqlite3.d.mts +2 -2
  7. package/dist/better-sqlite3.d.mts.map +1 -1
  8. package/dist/better-sqlite3.mjs +13 -5
  9. package/dist/better-sqlite3.mjs.map +1 -1
  10. package/dist/browser.d.mts +4 -4
  11. package/dist/browser.mjs +3 -3
  12. package/dist/browser.mjs.map +1 -1
  13. package/dist/{csv-WEud-i_H.mjs → csv-CvzHNNGW.mjs} +48 -11
  14. package/dist/csv-CvzHNNGW.mjs.map +1 -0
  15. package/dist/csv.d.mts +4 -2
  16. package/dist/csv.d.mts.map +1 -1
  17. package/dist/csv.mjs +1 -1
  18. package/dist/index.d.mts +40 -14
  19. package/dist/index.d.mts.map +1 -1
  20. package/dist/index.mjs +578 -200
  21. package/dist/index.mjs.map +1 -1
  22. package/dist/node-sqlite.d.mts +111 -0
  23. package/dist/node-sqlite.d.mts.map +1 -0
  24. package/dist/node-sqlite.mjs +708 -0
  25. package/dist/node-sqlite.mjs.map +1 -0
  26. package/dist/{runtime-DCo5E0Kr.d.mts → runtime-CkL1OOJT.d.mts} +129 -7
  27. package/dist/runtime-CkL1OOJT.d.mts.map +1 -0
  28. package/dist/{runtime-CMdfE7Gx.mjs → runtime-qbuZMbV4.mjs} +674 -198
  29. package/dist/runtime-qbuZMbV4.mjs.map +1 -0
  30. package/dist/{select-options-DihMTuoa.mjs → select-options-Dr8XCYOS.mjs} +145 -80
  31. package/dist/select-options-Dr8XCYOS.mjs.map +1 -0
  32. package/dist/{sqlite-wasm-B86yaLG6.mjs → sqlite-wasm-fT8Z-5Ww.mjs} +34 -13
  33. package/dist/sqlite-wasm-fT8Z-5Ww.mjs.map +1 -0
  34. package/dist/system-metadata-merge-BaX38cp-.d.mts +77 -0
  35. package/dist/system-metadata-merge-BaX38cp-.d.mts.map +1 -0
  36. package/dist/system-metadata-merge-CjTqAwCi.mjs +819 -0
  37. package/dist/system-metadata-merge-CjTqAwCi.mjs.map +1 -0
  38. package/dist/{temporal-CVzLU63l.d.mts → temporal-ysCLNSub.d.mts} +8 -3
  39. package/dist/temporal-ysCLNSub.d.mts.map +1 -0
  40. package/package.json +10 -2
  41. package/dist/adapter-contract-B3p-48Yb.d.mts.map +0 -1
  42. package/dist/csv-WEud-i_H.mjs.map +0 -1
  43. package/dist/runtime-CMdfE7Gx.mjs.map +0 -1
  44. package/dist/runtime-DCo5E0Kr.d.mts.map +0 -1
  45. package/dist/select-options-DihMTuoa.mjs.map +0 -1
  46. package/dist/sqlite-wasm-B86yaLG6.mjs.map +0 -1
  47. package/dist/temporal-CVzLU63l.d.mts.map +0 -1
@@ -0,0 +1,819 @@
1
+ import { s as isCanonicalEidosFileInstant } from "./select-options-Dr8XCYOS.mjs";
2
+ import { n as validateEidosFile } from "./runtime-qbuZMbV4.mjs";
3
+ //#region src/system-metadata-merge.ts
4
+ const PROFILE = "ER-System-Merge-1.0";
5
+ const MAX_INT64 = 9223372036854775807n;
6
+ const SIDE_KEY = /^[a-z0-9._~-]{1,128}$/;
7
+ const EIDOS_SYSTEM_METADATA_TABLES = [
8
+ "eidos__meta",
9
+ "eidos__tables",
10
+ "eidos__fields",
11
+ "eidos__features",
12
+ "eidos__relation_fields",
13
+ "eidos__formula_fields",
14
+ "eidos__lookup_fields",
15
+ "eidos__views"
16
+ ];
17
+ function mapRows(rows, key) {
18
+ return new Map(rows.map((row) => [key(row), row]));
19
+ }
20
+ function readSnapshot(connection) {
21
+ const meta = connection.get(`SELECT singleton,format_major,format_minor,file_id,title,default_table_id,
22
+ revision,created_at,updated_at FROM eidos__meta WHERE singleton=1`);
23
+ if (!meta) throw new Error("Missing eidos__meta singleton");
24
+ return {
25
+ meta,
26
+ tables: mapRows(connection.query(`SELECT id,name,physical_name,label_field_id,position,settings_json,created_at,updated_at
27
+ FROM eidos__tables ORDER BY id`), (row) => row.id),
28
+ fields: mapRows(connection.query(`SELECT id,table_id,name,physical_name,type,system_role,nullable,position,
29
+ settings_json,created_at,updated_at FROM eidos__fields ORDER BY id`), (row) => row.id),
30
+ relations: mapRows(connection.query(`SELECT field_id,direction,target_table_id,cardinality,inverse_of_field_id,on_delete
31
+ FROM eidos__relation_fields ORDER BY field_id`), (row) => row.field_id),
32
+ formulas: mapRows(connection.query(`SELECT field_id,source_text,result_type FROM eidos__formula_fields ORDER BY field_id`), (row) => row.field_id),
33
+ lookups: mapRows(connection.query(`SELECT field_id,relation_field_id,target_field_id,aggregate,distinct_values
34
+ FROM eidos__lookup_fields ORDER BY field_id`), (row) => row.field_id),
35
+ views: mapRows(connection.query(`SELECT id,table_id,name,type,query_json,layout_json,position,created_at,updated_at
36
+ FROM eidos__views ORDER BY id`), (row) => row.id),
37
+ features: mapRows(connection.query(`SELECT name,version,required,config_json FROM eidos__features ORDER BY name`), (row) => row.name)
38
+ };
39
+ }
40
+ function valueKey(value) {
41
+ if (typeof value === "bigint") return `bigint:${value.toString()}`;
42
+ if (Array.isArray(value)) return `[${value.map(valueKey).join(",")}]`;
43
+ if (value && typeof value === "object") return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => `${JSON.stringify(key)}:${valueKey(entry)}`).join(",")}}`;
44
+ return JSON.stringify(value);
45
+ }
46
+ function equal(left, right) {
47
+ return valueKey(left) === valueKey(right);
48
+ }
49
+ function ids(...maps) {
50
+ return [...new Set(maps.flatMap((map) => [...map.keys()]))].sort();
51
+ }
52
+ function rankWinner(ours, theirs) {
53
+ if (ours.clock !== theirs.clock) return ours.clock > theirs.clock ? "ours" : "theirs";
54
+ return ours.key > theirs.key ? "ours" : "theirs";
55
+ }
56
+ function changedGroups(base, row, groups) {
57
+ if (!base || !row) return [];
58
+ return Object.entries(groups).filter(([, columns]) => columns.some((column) => !equal(base[column], row[column]))).map(([group]) => group);
59
+ }
60
+ function summary(row, groups = []) {
61
+ return row ? {
62
+ state: "present",
63
+ ...groups.length ? { changedGroups: groups } : {}
64
+ } : { state: "absent" };
65
+ }
66
+ function conflict(code, objectKind, objectId, group, message, base, ours, theirs, groups, resolutionScope) {
67
+ return {
68
+ code,
69
+ objectKind,
70
+ objectId,
71
+ group,
72
+ message,
73
+ base: summary(base),
74
+ ours: summary(ours, changedGroups(base, ours, groups)),
75
+ theirs: summary(theirs, changedGroups(base, theirs, groups)),
76
+ resolutionScope
77
+ };
78
+ }
79
+ function resolveLwwGroup(options) {
80
+ const { base, ours, theirs, objectKind, objectId, group, oursRank, theirsRank, automaticResolutions } = options;
81
+ if (equal(ours, theirs)) return ours;
82
+ if (equal(ours, base)) return theirs;
83
+ if (equal(theirs, base)) return ours;
84
+ const selectedSide = rankWinner(oursRank, theirsRank);
85
+ automaticResolutions.push({
86
+ objectKind,
87
+ objectId,
88
+ group,
89
+ reason: "last-write-wins",
90
+ selectedSide
91
+ });
92
+ return selectedSide === "ours" ? ours : theirs;
93
+ }
94
+ function immutableMeta(meta) {
95
+ return [
96
+ meta.singleton,
97
+ meta.format_major,
98
+ meta.format_minor,
99
+ meta.file_id,
100
+ meta.created_at
101
+ ];
102
+ }
103
+ function sameSystemSnapshot(left, right) {
104
+ return equal(left.meta, right.meta) && equal([...left.tables], [...right.tables]) && equal([...left.fields], [...right.fields]) && equal([...left.relations], [...right.relations]) && equal([...left.formulas], [...right.formulas]) && equal([...left.lookups], [...right.lookups]) && equal([...left.views], [...right.views]) && equal([...left.features], [...right.features]);
105
+ }
106
+ function structuralTable(row) {
107
+ return [
108
+ row.id,
109
+ row.name,
110
+ row.physical_name,
111
+ row.created_at
112
+ ];
113
+ }
114
+ function structuralField(row) {
115
+ return [
116
+ row.id,
117
+ row.table_id,
118
+ row.name,
119
+ row.physical_name,
120
+ row.type,
121
+ row.system_role,
122
+ row.nullable,
123
+ row.created_at
124
+ ];
125
+ }
126
+ const TABLE_GROUPS = {
127
+ physicalIdentity: ["name", "physical_name"],
128
+ recordLabel: ["label_field_id"],
129
+ order: ["position"],
130
+ settings: ["settings_json"]
131
+ };
132
+ const FIELD_GROUPS = {
133
+ nameMapping: ["name", "physical_name"],
134
+ shape: [
135
+ "type",
136
+ "system_role",
137
+ "nullable"
138
+ ],
139
+ definition: ["settings_json"],
140
+ order: ["position"]
141
+ };
142
+ const VIEW_GROUPS = {
143
+ identityOwner: ["table_id", "created_at"],
144
+ name: ["name"],
145
+ query: ["query_json"],
146
+ presentation: ["type", "layout_json"],
147
+ order: ["position"]
148
+ };
149
+ const FEATURE_GROUPS = { declaration: [
150
+ "version",
151
+ "required",
152
+ "config_json"
153
+ ] };
154
+ function mergeExistingTables(base, ours, theirs, plan, oursKey, theirsKey, operationInstant) {
155
+ for (const id of ids(base.tables, ours.tables, theirs.tables)) {
156
+ const baseRow = base.tables.get(id);
157
+ const oursRow = ours.tables.get(id);
158
+ const theirsRow = theirs.tables.get(id);
159
+ if (!baseRow || !oursRow || !theirsRow) {
160
+ const code = baseRow && (!oursRow || !theirsRow) ? "delete-update" : "unsupported-schema-change";
161
+ plan.conflicts.push(conflict(code, "table", id, "physical-identity", code === "delete-update" ? "Table deletion cannot be combined without proving its schema and dependency effects." : "Table creation requires physical schema reconstruction and is not automatic in this implementation.", baseRow, oursRow, theirsRow, TABLE_GROUPS, "schema"));
162
+ continue;
163
+ }
164
+ if (!equal(structuralTable(baseRow), structuralTable(oursRow)) || !equal(structuralTable(baseRow), structuralTable(theirsRow))) {
165
+ const bothRenamed = !equal(baseRow.name, oursRow.name) && !equal(baseRow.name, theirsRow.name) && !equal(oursRow.name, theirsRow.name);
166
+ plan.conflicts.push(conflict(bothRenamed ? "table-rename-conflict" : "unsupported-schema-change", "table", id, "physical-identity", bothRenamed ? "The same Table received incompatible concurrent physical names." : "A Table physical identity change requires schema reconstruction before it can be merged.", baseRow, oursRow, theirsRow, TABLE_GROUPS, "schema"));
167
+ continue;
168
+ }
169
+ const oursRank = {
170
+ side: "ours",
171
+ clock: oursRow.updated_at,
172
+ key: oursKey
173
+ };
174
+ const theirsRank = {
175
+ side: "theirs",
176
+ clock: theirsRow.updated_at,
177
+ key: theirsKey
178
+ };
179
+ const merged = {
180
+ ...baseRow,
181
+ label_field_id: resolveLwwGroup({
182
+ base: baseRow.label_field_id,
183
+ ours: oursRow.label_field_id,
184
+ theirs: theirsRow.label_field_id,
185
+ objectKind: "table",
186
+ objectId: id,
187
+ group: "record-label",
188
+ oursRank,
189
+ theirsRank,
190
+ automaticResolutions: plan.automaticResolutions
191
+ }),
192
+ position: resolveLwwGroup({
193
+ base: baseRow.position,
194
+ ours: oursRow.position,
195
+ theirs: theirsRow.position,
196
+ objectKind: "table",
197
+ objectId: id,
198
+ group: "order",
199
+ oursRank,
200
+ theirsRank,
201
+ automaticResolutions: plan.automaticResolutions
202
+ }),
203
+ settings_json: resolveLwwGroup({
204
+ base: baseRow.settings_json,
205
+ ours: oursRow.settings_json,
206
+ theirs: theirsRow.settings_json,
207
+ objectKind: "table",
208
+ objectId: id,
209
+ group: "settings",
210
+ oursRank,
211
+ theirsRank,
212
+ automaticResolutions: plan.automaticResolutions
213
+ })
214
+ };
215
+ if (merged.label_field_id !== baseRow.label_field_id || merged.position !== baseRow.position || merged.settings_json !== baseRow.settings_json) merged.updated_at = operationInstant;
216
+ else merged.updated_at = baseRow.updated_at;
217
+ plan.tables.set(id, merged);
218
+ }
219
+ }
220
+ function fieldSubtype(snapshot, id) {
221
+ return snapshot.relations.get(id) ?? snapshot.formulas.get(id) ?? snapshot.lookups.get(id) ?? null;
222
+ }
223
+ function setFieldSubtype(plan, id, row) {
224
+ plan.relations.delete(id);
225
+ plan.formulas.delete(id);
226
+ plan.lookups.delete(id);
227
+ if (!row) return;
228
+ if ("direction" in row) plan.relations.set(id, row);
229
+ else if ("source_text" in row) plan.formulas.set(id, row);
230
+ else plan.lookups.set(id, row);
231
+ }
232
+ function mergeExistingFields(base, ours, theirs, plan, oursKey, theirsKey, operationInstant) {
233
+ for (const id of ids(base.fields, ours.fields, theirs.fields)) {
234
+ const baseRow = base.fields.get(id);
235
+ const oursRow = ours.fields.get(id);
236
+ const theirsRow = theirs.fields.get(id);
237
+ if (!baseRow || !oursRow || !theirsRow) {
238
+ const code = baseRow && (!oursRow || !theirsRow) ? "delete-update" : "unsupported-schema-change";
239
+ plan.conflicts.push(conflict(code, "field", id, "shape", code === "delete-update" ? "Field deletion cannot be combined without proving row, View, and dependency effects." : "Field creation requires physical schema reconstruction and is not automatic in this implementation.", baseRow, oursRow, theirsRow, FIELD_GROUPS, "schema"));
240
+ continue;
241
+ }
242
+ if (!equal(structuralField(baseRow), structuralField(oursRow)) || !equal(structuralField(baseRow), structuralField(theirsRow))) {
243
+ const oursRenamed = !equal([baseRow.name, baseRow.physical_name], [oursRow.name, oursRow.physical_name]);
244
+ const theirsRenamed = !equal([baseRow.name, baseRow.physical_name], [theirsRow.name, theirsRow.physical_name]);
245
+ const concurrentRename = oursRenamed && theirsRenamed && !equal([oursRow.name, oursRow.physical_name], [theirsRow.name, theirsRow.physical_name]);
246
+ const shapeChanged = !equal([
247
+ baseRow.type,
248
+ baseRow.system_role,
249
+ baseRow.nullable
250
+ ], [
251
+ oursRow.type,
252
+ oursRow.system_role,
253
+ oursRow.nullable
254
+ ]) || !equal([
255
+ baseRow.type,
256
+ baseRow.system_role,
257
+ baseRow.nullable
258
+ ], [
259
+ theirsRow.type,
260
+ theirsRow.system_role,
261
+ theirsRow.nullable
262
+ ]);
263
+ const code = concurrentRename ? "field-rename-conflict" : shapeChanged ? "field-conversion-conflict" : "unsupported-schema-change";
264
+ plan.conflicts.push(conflict(code, "field", id, shapeChanged ? "shape" : "name-mapping", code === "field-rename-conflict" ? "The same Field received incompatible concurrent names." : code === "field-conversion-conflict" ? "The Field shape changed without a proven lossless conversion projection." : "A Field mapping change requires schema reconstruction before it can be merged.", baseRow, oursRow, theirsRow, FIELD_GROUPS, "schema"));
265
+ continue;
266
+ }
267
+ const oursRank = {
268
+ side: "ours",
269
+ clock: oursRow.updated_at,
270
+ key: oursKey
271
+ };
272
+ const theirsRank = {
273
+ side: "theirs",
274
+ clock: theirsRow.updated_at,
275
+ key: theirsKey
276
+ };
277
+ const baseSubtype = fieldSubtype(base, id);
278
+ const oursSubtype = fieldSubtype(ours, id);
279
+ const theirsSubtype = fieldSubtype(theirs, id);
280
+ if (["select", "multi-select"].includes(baseRow.type) && !equal(oursRow.settings_json, baseRow.settings_json) && !equal(theirsRow.settings_json, baseRow.settings_json) && !equal(oursRow.settings_json, theirsRow.settings_json)) {
281
+ plan.conflicts.push(conflict("option-catalog-conflict", "field", id, "definition", "Concurrent option catalog changes cannot be combined without proving value and View rewrites.", baseRow, oursRow, theirsRow, FIELD_GROUPS, "group"));
282
+ continue;
283
+ }
284
+ const [mergedSettings, mergedSubtype] = resolveLwwGroup({
285
+ base: [baseRow.settings_json, baseSubtype],
286
+ ours: [oursRow.settings_json, oursSubtype],
287
+ theirs: [theirsRow.settings_json, theirsSubtype],
288
+ objectKind: "field",
289
+ objectId: id,
290
+ group: "definition",
291
+ oursRank,
292
+ theirsRank,
293
+ automaticResolutions: plan.automaticResolutions
294
+ });
295
+ const merged = {
296
+ ...baseRow,
297
+ position: resolveLwwGroup({
298
+ base: baseRow.position,
299
+ ours: oursRow.position,
300
+ theirs: theirsRow.position,
301
+ objectKind: "field",
302
+ objectId: id,
303
+ group: "order",
304
+ oursRank,
305
+ theirsRank,
306
+ automaticResolutions: plan.automaticResolutions
307
+ }),
308
+ settings_json: mergedSettings
309
+ };
310
+ merged.updated_at = merged.position !== baseRow.position || merged.settings_json !== baseRow.settings_json || !equal(mergedSubtype, baseSubtype) ? operationInstant : baseRow.updated_at;
311
+ plan.fields.set(id, merged);
312
+ setFieldSubtype(plan, id, mergedSubtype);
313
+ }
314
+ }
315
+ function mergeViews(base, ours, theirs, plan, oursKey, theirsKey, operationInstant) {
316
+ for (const id of ids(base.views, ours.views, theirs.views)) {
317
+ const baseRow = base.views.get(id);
318
+ const oursRow = ours.views.get(id);
319
+ const theirsRow = theirs.views.get(id);
320
+ if (!baseRow) {
321
+ if (!oursRow && theirsRow) plan.views.set(id, {
322
+ ...theirsRow,
323
+ updated_at: operationInstant
324
+ });
325
+ else if (oursRow && !theirsRow) plan.views.set(id, {
326
+ ...oursRow,
327
+ updated_at: operationInstant
328
+ });
329
+ else if (oursRow && theirsRow) if (equal({
330
+ ...oursRow,
331
+ updated_at: ""
332
+ }, {
333
+ ...theirsRow,
334
+ updated_at: ""
335
+ })) plan.views.set(id, {
336
+ ...oursRow,
337
+ updated_at: operationInstant
338
+ });
339
+ else plan.conflicts.push(conflict("identity-collision", "view", id, "identity", "The same View ID was independently created with unequal definitions.", void 0, oursRow, theirsRow, VIEW_GROUPS, "object"));
340
+ continue;
341
+ }
342
+ if (!oursRow && !theirsRow) {
343
+ plan.views.delete(id);
344
+ continue;
345
+ }
346
+ if (!oursRow || !theirsRow) {
347
+ const survivor = oursRow ?? theirsRow;
348
+ if (survivor && equal({
349
+ ...survivor,
350
+ updated_at: ""
351
+ }, {
352
+ ...baseRow,
353
+ updated_at: ""
354
+ })) plan.views.delete(id);
355
+ else plan.conflicts.push(conflict("delete-update", "view", id, "object", "One side deleted a View that the other side changed.", baseRow, oursRow, theirsRow, VIEW_GROUPS, "object"));
356
+ continue;
357
+ }
358
+ if (oursRow.table_id !== baseRow.table_id || theirsRow.table_id !== baseRow.table_id || oursRow.created_at !== baseRow.created_at || theirsRow.created_at !== baseRow.created_at) {
359
+ plan.conflicts.push(conflict("identity-collision", "view", id, "identity-owner", "A View owner or creation identity changed.", baseRow, oursRow, theirsRow, VIEW_GROUPS, "object"));
360
+ continue;
361
+ }
362
+ const oursRank = {
363
+ side: "ours",
364
+ clock: oursRow.updated_at,
365
+ key: oursKey
366
+ };
367
+ const theirsRank = {
368
+ side: "theirs",
369
+ clock: theirsRow.updated_at,
370
+ key: theirsKey
371
+ };
372
+ const merged = {
373
+ ...baseRow,
374
+ name: resolveLwwGroup({
375
+ base: baseRow.name,
376
+ ours: oursRow.name,
377
+ theirs: theirsRow.name,
378
+ objectKind: "view",
379
+ objectId: id,
380
+ group: "name",
381
+ oursRank,
382
+ theirsRank,
383
+ automaticResolutions: plan.automaticResolutions
384
+ }),
385
+ query_json: resolveLwwGroup({
386
+ base: baseRow.query_json,
387
+ ours: oursRow.query_json,
388
+ theirs: theirsRow.query_json,
389
+ objectKind: "view",
390
+ objectId: id,
391
+ group: "query",
392
+ oursRank,
393
+ theirsRank,
394
+ automaticResolutions: plan.automaticResolutions
395
+ }),
396
+ type: baseRow.type,
397
+ layout_json: "",
398
+ position: resolveLwwGroup({
399
+ base: baseRow.position,
400
+ ours: oursRow.position,
401
+ theirs: theirsRow.position,
402
+ objectKind: "view",
403
+ objectId: id,
404
+ group: "order",
405
+ oursRank,
406
+ theirsRank,
407
+ automaticResolutions: plan.automaticResolutions
408
+ })
409
+ };
410
+ const presentation = resolveLwwGroup({
411
+ base: [baseRow.type, baseRow.layout_json],
412
+ ours: [oursRow.type, oursRow.layout_json],
413
+ theirs: [theirsRow.type, theirsRow.layout_json],
414
+ objectKind: "view",
415
+ objectId: id,
416
+ group: "presentation",
417
+ oursRank,
418
+ theirsRank,
419
+ automaticResolutions: plan.automaticResolutions
420
+ });
421
+ merged.type = presentation[0];
422
+ merged.layout_json = presentation[1];
423
+ merged.updated_at = !equal([
424
+ merged.name,
425
+ merged.query_json,
426
+ merged.type,
427
+ merged.layout_json,
428
+ merged.position
429
+ ], [
430
+ baseRow.name,
431
+ baseRow.query_json,
432
+ baseRow.type,
433
+ baseRow.layout_json,
434
+ baseRow.position
435
+ ]) ? operationInstant : baseRow.updated_at;
436
+ plan.views.set(id, merged);
437
+ }
438
+ }
439
+ function mergeFeatures(base, ours, theirs, plan) {
440
+ for (const name of ids(base.features, ours.features, theirs.features)) {
441
+ const baseRow = base.features.get(name);
442
+ const oursRow = ours.features.get(name);
443
+ const theirsRow = theirs.features.get(name);
444
+ if (!baseRow) {
445
+ if (oursRow && theirsRow && !equal(oursRow, theirsRow)) plan.conflicts.push(conflict("feature-conflict", "feature", name, "declaration", "The same Feature was independently declared with unequal capabilities.", void 0, oursRow, theirsRow, FEATURE_GROUPS, "object"));
446
+ else if (oursRow || theirsRow) plan.features.set(name, oursRow ?? theirsRow);
447
+ continue;
448
+ }
449
+ if (!oursRow && !theirsRow) plan.features.delete(name);
450
+ else if (!oursRow || !theirsRow) {
451
+ const survivor = oursRow ?? theirsRow;
452
+ if (survivor && equal(survivor, baseRow)) plan.features.delete(name);
453
+ else plan.conflicts.push(conflict("delete-update", "feature", name, "declaration", "One side removed a Feature that the other side changed.", baseRow, oursRow, theirsRow, FEATURE_GROUPS, "object"));
454
+ } else if (equal(oursRow, theirsRow)) plan.features.set(name, oursRow);
455
+ else if (equal(oursRow, baseRow)) plan.features.set(name, theirsRow);
456
+ else if (equal(theirsRow, baseRow)) plan.features.set(name, oursRow);
457
+ else plan.conflicts.push(conflict("feature-conflict", "feature", name, "declaration", "Concurrent unequal Feature declarations have no canonical last-write clock.", baseRow, oursRow, theirsRow, FEATURE_GROUPS, "group"));
458
+ }
459
+ }
460
+ function viewNameConflicts(plan) {
461
+ const names = /* @__PURE__ */ new Map();
462
+ for (const view of plan.views.values()) {
463
+ const scope = `${view.table_id}\u001f${view.name.toLocaleLowerCase("en-US")}`;
464
+ const previous = names.get(scope);
465
+ if (previous && previous !== view.id) plan.conflicts.push({
466
+ code: "name-collision",
467
+ objectKind: "view",
468
+ objectId: view.id,
469
+ group: "name",
470
+ message: "Two Views in the same Table have the same case-insensitive final name.",
471
+ base: { state: "absent" },
472
+ ours: {
473
+ state: "present",
474
+ changedGroups: ["name"]
475
+ },
476
+ theirs: {
477
+ state: "present",
478
+ changedGroups: ["name"]
479
+ },
480
+ resolutionScope: "group"
481
+ });
482
+ else names.set(scope, view.id);
483
+ }
484
+ }
485
+ function buildPlan(base, ours, theirs, oursKey, theirsKey, operationInstant) {
486
+ const automaticResolutions = [];
487
+ const conflicts = [];
488
+ const oursRank = {
489
+ side: "ours",
490
+ clock: ours.meta.updated_at,
491
+ key: oursKey
492
+ };
493
+ const theirsRank = {
494
+ side: "theirs",
495
+ clock: theirs.meta.updated_at,
496
+ key: theirsKey
497
+ };
498
+ const revision = [
499
+ base.meta.revision,
500
+ ours.meta.revision,
501
+ theirs.meta.revision
502
+ ].map(BigInt).reduce((maximum, value) => value > maximum ? value : maximum);
503
+ if (revision >= MAX_INT64) return "revision-exhausted";
504
+ const meta = {
505
+ ...base.meta,
506
+ title: resolveLwwGroup({
507
+ base: base.meta.title,
508
+ ours: ours.meta.title,
509
+ theirs: theirs.meta.title,
510
+ objectKind: "file",
511
+ objectId: base.meta.file_id,
512
+ group: "title",
513
+ oursRank,
514
+ theirsRank,
515
+ automaticResolutions
516
+ }),
517
+ default_table_id: resolveLwwGroup({
518
+ base: base.meta.default_table_id,
519
+ ours: ours.meta.default_table_id,
520
+ theirs: theirs.meta.default_table_id,
521
+ objectKind: "file",
522
+ objectId: base.meta.file_id,
523
+ group: "default-table",
524
+ oursRank,
525
+ theirsRank,
526
+ automaticResolutions
527
+ }),
528
+ revision: revision + 1n,
529
+ updated_at: operationInstant
530
+ };
531
+ automaticResolutions.push({
532
+ objectKind: "file",
533
+ objectId: base.meta.file_id,
534
+ group: "revision-and-timestamp",
535
+ reason: "merge-finalization"
536
+ });
537
+ const plan = {
538
+ meta,
539
+ tables: new Map(base.tables),
540
+ fields: new Map(base.fields),
541
+ relations: new Map(base.relations),
542
+ formulas: new Map(base.formulas),
543
+ lookups: new Map(base.lookups),
544
+ views: new Map(base.views),
545
+ features: new Map(base.features),
546
+ automaticResolutions,
547
+ conflicts
548
+ };
549
+ mergeExistingTables(base, ours, theirs, plan, oursKey, theirsKey, operationInstant);
550
+ mergeExistingFields(base, ours, theirs, plan, oursKey, theirsKey, operationInstant);
551
+ mergeViews(base, ours, theirs, plan, oursKey, theirsKey, operationInstant);
552
+ mergeFeatures(base, ours, theirs, plan);
553
+ viewNameConflicts(plan);
554
+ if (plan.meta.default_table_id !== null && !plan.tables.has(plan.meta.default_table_id)) plan.conflicts.push({
555
+ code: "dependency-conflict",
556
+ objectKind: "file",
557
+ objectId: plan.meta.file_id,
558
+ group: "default-table",
559
+ message: "The merged default Table reference does not exist.",
560
+ base: summary(base.tables.get(plan.meta.default_table_id)),
561
+ ours: summary(ours.tables.get(plan.meta.default_table_id)),
562
+ theirs: summary(theirs.tables.get(plan.meta.default_table_id)),
563
+ resolutionScope: "dependency"
564
+ });
565
+ return plan;
566
+ }
567
+ function replaceRows(connection, table, keyColumn, columns, rows) {
568
+ const existing = connection.query(`SELECT ${keyColumn} FROM ${table}`);
569
+ for (const row of existing) {
570
+ const key = String(row[keyColumn]);
571
+ if (!rows.has(key)) connection.run(`DELETE FROM ${table} WHERE ${keyColumn}=?`, [key]);
572
+ }
573
+ const placeholders = columns.map(() => "?").join(",");
574
+ const updates = columns.filter((column) => column !== keyColumn).map((column) => `${column}=excluded.${column}`).join(",");
575
+ const sql = `INSERT INTO ${table}(${columns.join(",")}) VALUES(${placeholders})
576
+ ON CONFLICT(${keyColumn}) DO UPDATE SET ${updates}`;
577
+ for (const row of rows.values()) connection.run(sql, columns.map((column) => row[column]));
578
+ }
579
+ var CandidateValidationFailure = class extends Error {
580
+ constructor(validation) {
581
+ super("Merged Eidos system metadata candidate failed validation");
582
+ this.validation = validation;
583
+ }
584
+ };
585
+ function applyPlan(connection, plan) {
586
+ return connection.transaction(() => {
587
+ connection.exec("PRAGMA defer_foreign_keys = ON;");
588
+ replaceRows(connection, "eidos__tables", "id", [
589
+ "id",
590
+ "name",
591
+ "physical_name",
592
+ "label_field_id",
593
+ "position",
594
+ "settings_json",
595
+ "created_at",
596
+ "updated_at"
597
+ ], plan.tables);
598
+ replaceRows(connection, "eidos__fields", "id", [
599
+ "id",
600
+ "table_id",
601
+ "name",
602
+ "physical_name",
603
+ "type",
604
+ "system_role",
605
+ "nullable",
606
+ "position",
607
+ "settings_json",
608
+ "created_at",
609
+ "updated_at"
610
+ ], plan.fields);
611
+ replaceRows(connection, "eidos__relation_fields", "field_id", [
612
+ "field_id",
613
+ "direction",
614
+ "target_table_id",
615
+ "cardinality",
616
+ "inverse_of_field_id",
617
+ "on_delete"
618
+ ], plan.relations);
619
+ replaceRows(connection, "eidos__formula_fields", "field_id", [
620
+ "field_id",
621
+ "source_text",
622
+ "result_type"
623
+ ], plan.formulas);
624
+ replaceRows(connection, "eidos__lookup_fields", "field_id", [
625
+ "field_id",
626
+ "relation_field_id",
627
+ "target_field_id",
628
+ "aggregate",
629
+ "distinct_values"
630
+ ], plan.lookups);
631
+ replaceRows(connection, "eidos__views", "id", [
632
+ "id",
633
+ "table_id",
634
+ "name",
635
+ "type",
636
+ "query_json",
637
+ "layout_json",
638
+ "position",
639
+ "created_at",
640
+ "updated_at"
641
+ ], plan.views);
642
+ replaceRows(connection, "eidos__features", "name", [
643
+ "name",
644
+ "version",
645
+ "required",
646
+ "config_json"
647
+ ], plan.features);
648
+ connection.run(`UPDATE eidos__meta SET title=?,default_table_id=?,revision=?,updated_at=? WHERE singleton=1`, [
649
+ plan.meta.title,
650
+ plan.meta.default_table_id,
651
+ plan.meta.revision,
652
+ plan.meta.updated_at
653
+ ]);
654
+ const validation = validateEidosFile(connection, { level: "full" });
655
+ if (!validation.valid) throw new CandidateValidationFailure(validation);
656
+ return validation;
657
+ });
658
+ }
659
+ function validationIssues(input, validation) {
660
+ return validation.errors.map((issue) => ({
661
+ input,
662
+ code: issue.code,
663
+ message: issue.message
664
+ }));
665
+ }
666
+ /**
667
+ * Deterministically merges the canonical Eidos system metadata tables into a private candidate.
668
+ * The result connection must be an Ours-derived seed whose system rows are still byte-logically
669
+ * equal to Ours; a host may pre-merge only non-provider tables before this call.
670
+ */
671
+ function mergeEidosSystemMetadata(input) {
672
+ const requestIssues = [];
673
+ if (!SIDE_KEY.test(input.oursKey)) requestIssues.push({
674
+ input: "request",
675
+ code: "invalid-side-key",
676
+ message: "oursKey is not a stable lowercase ASCII side key"
677
+ });
678
+ if (!SIDE_KEY.test(input.theirsKey)) requestIssues.push({
679
+ input: "request",
680
+ code: "invalid-side-key",
681
+ message: "theirsKey is not a stable lowercase ASCII side key"
682
+ });
683
+ if (input.oursKey === input.theirsKey) requestIssues.push({
684
+ input: "request",
685
+ code: "duplicate-side-key",
686
+ message: "oursKey and theirsKey must be distinct"
687
+ });
688
+ if (!isCanonicalEidosFileInstant(input.operationInstant)) requestIssues.push({
689
+ input: "request",
690
+ code: "invalid-operation-instant",
691
+ message: "operationInstant is not a canonical Eidos File instant"
692
+ });
693
+ if (requestIssues.length) return {
694
+ outcome: "invalid-input",
695
+ issues: requestIssues
696
+ };
697
+ const connections = [
698
+ ["base", input.base],
699
+ ["ours", input.ours],
700
+ ["theirs", input.theirs],
701
+ ["result", input.result]
702
+ ];
703
+ const validationIssuesFound = [];
704
+ for (const [name, connection] of connections) try {
705
+ const validation = validateEidosFile(connection, { level: "structural" });
706
+ if (!validation.valid) validationIssuesFound.push(...validationIssues(name, validation));
707
+ } catch (error) {
708
+ validationIssuesFound.push({
709
+ input: name,
710
+ code: "invalid-merge-input",
711
+ message: error instanceof Error ? error.message : "Snapshot validation failed"
712
+ });
713
+ }
714
+ if (validationIssuesFound.length) return {
715
+ outcome: "invalid-input",
716
+ issues: validationIssuesFound
717
+ };
718
+ let base;
719
+ let ours;
720
+ let theirs;
721
+ let result;
722
+ try {
723
+ base = readSnapshot(input.base);
724
+ ours = readSnapshot(input.ours);
725
+ theirs = readSnapshot(input.theirs);
726
+ result = readSnapshot(input.result);
727
+ } catch (error) {
728
+ return {
729
+ outcome: "invalid-input",
730
+ issues: [{
731
+ input: "request",
732
+ code: "invalid-merge-input",
733
+ message: error instanceof Error ? error.message : "Could not read system metadata"
734
+ }]
735
+ };
736
+ }
737
+ if (!equal(immutableMeta(base.meta), immutableMeta(ours.meta)) || !equal(immutableMeta(base.meta), immutableMeta(theirs.meta))) return {
738
+ outcome: "invalid-input",
739
+ issues: [{
740
+ input: "request",
741
+ code: "identity-mismatch",
742
+ message: "Base, Ours, and Theirs do not describe the same immutable Eidos File identity"
743
+ }]
744
+ };
745
+ if (!sameSystemSnapshot(ours, result)) return {
746
+ outcome: "invalid-input",
747
+ issues: [{
748
+ input: "result",
749
+ code: "invalid-result-seed",
750
+ message: "The private result seed must preserve every Eidos system metadata row from Ours before Runtime merge"
751
+ }]
752
+ };
753
+ const latestInputClock = [
754
+ base.meta.updated_at,
755
+ ours.meta.updated_at,
756
+ theirs.meta.updated_at,
757
+ ...[
758
+ base,
759
+ ours,
760
+ theirs
761
+ ].flatMap((snapshot) => [
762
+ ...[...snapshot.tables.values()].map((row) => row.updated_at),
763
+ ...[...snapshot.fields.values()].map((row) => row.updated_at),
764
+ ...[...snapshot.views.values()].map((row) => row.updated_at)
765
+ ])
766
+ ].sort().at(-1);
767
+ if (input.operationInstant <= latestInputClock) return {
768
+ outcome: "failed",
769
+ code: "clock-not-after-input"
770
+ };
771
+ const plan = buildPlan(base, ours, theirs, input.oursKey, input.theirsKey, input.operationInstant);
772
+ if (plan === "revision-exhausted") return {
773
+ outcome: "failed",
774
+ code: plan
775
+ };
776
+ if (plan.conflicts.length) return {
777
+ outcome: "conflict",
778
+ conflicts: plan.conflicts,
779
+ automaticResolutions: plan.automaticResolutions
780
+ };
781
+ let validation;
782
+ try {
783
+ validation = applyPlan(input.result, plan);
784
+ } catch (error) {
785
+ if (error instanceof CandidateValidationFailure) return {
786
+ outcome: "conflict",
787
+ conflicts: [{
788
+ code: "validation-failed",
789
+ objectKind: "dependency",
790
+ objectId: base.meta.file_id,
791
+ group: "candidate",
792
+ message: error.validation.errors.map((issue) => issue.message).join("; "),
793
+ base: { state: "present" },
794
+ ours: { state: "present" },
795
+ theirs: { state: "present" },
796
+ resolutionScope: "dependency"
797
+ }],
798
+ automaticResolutions: plan.automaticResolutions
799
+ };
800
+ throw error;
801
+ }
802
+ return {
803
+ outcome: "merged",
804
+ automaticResolutions: plan.automaticResolutions,
805
+ validation: {
806
+ profile: PROFILE,
807
+ level: "full",
808
+ fileId: plan.meta.file_id,
809
+ revision: BigInt(plan.meta.revision).toString(),
810
+ operationInstant: input.operationInstant,
811
+ errors: validation.errors,
812
+ warnings: validation.warnings
813
+ }
814
+ };
815
+ }
816
+ //#endregion
817
+ export { mergeEidosSystemMetadata as n, EIDOS_SYSTEM_METADATA_TABLES as t };
818
+
819
+ //# sourceMappingURL=system-metadata-merge-CjTqAwCi.mjs.map