express-file-cluster 0.8.0 → 0.9.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 (50) hide show
  1. package/README.md +1 -1
  2. package/dist/auth/index.cjs +3 -3
  3. package/dist/auth/index.d.cts +1 -1
  4. package/dist/auth/index.d.ts +1 -1
  5. package/dist/auth/index.js +2 -2
  6. package/dist/{chunk-ZDM5JHVK.cjs → chunk-2J3HHQKP.cjs} +3 -3
  7. package/dist/{chunk-ZDM5JHVK.cjs.map → chunk-2J3HHQKP.cjs.map} +1 -1
  8. package/dist/{chunk-OSES7ZQ5.js → chunk-2PBMLMO4.js} +2 -2
  9. package/dist/{chunk-75O3WQKR.cjs → chunk-66R7S7J3.cjs} +5 -5
  10. package/dist/{chunk-75O3WQKR.cjs.map → chunk-66R7S7J3.cjs.map} +1 -1
  11. package/dist/{chunk-B2I7SYQ3.js → chunk-6QNLN6AI.js} +20 -7
  12. package/dist/chunk-6QNLN6AI.js.map +1 -0
  13. package/dist/{chunk-BUBXO7WU.js → chunk-HXV543HZ.js} +10 -3
  14. package/dist/chunk-HXV543HZ.js.map +1 -0
  15. package/dist/{chunk-FQFKHPLR.cjs → chunk-RGTENTDN.cjs} +121 -108
  16. package/dist/chunk-RGTENTDN.cjs.map +1 -0
  17. package/dist/{chunk-TRC4DUZB.js → chunk-RSZB7VAO.js} +2 -2
  18. package/dist/{chunk-MGH4VDV3.cjs → chunk-VQSWSYK6.cjs} +10 -3
  19. package/dist/chunk-VQSWSYK6.cjs.map +1 -0
  20. package/dist/cli/db-runner.cjs +19 -19
  21. package/dist/cli/db-runner.js +3 -3
  22. package/dist/cli/index.cjs +3 -3
  23. package/dist/cli/index.js +2 -2
  24. package/dist/docs/api-reference/ignite.md +19 -0
  25. package/dist/docs/api-reference/table.md +3 -0
  26. package/dist/docs/cli/add.md +1 -1
  27. package/dist/docs/guides/database.md +2 -0
  28. package/dist/docs/guides/relations.md +147 -0
  29. package/dist/docs/guides/which-api.md +50 -0
  30. package/dist/docs/index.md +3 -1
  31. package/dist/docs/skills/SKILL.md +1 -1
  32. package/dist/docs/skills/api-surface.md +1 -0
  33. package/dist/index.cjs +19 -19
  34. package/dist/index.cjs.map +1 -1
  35. package/dist/index.d.cts +2 -2
  36. package/dist/index.d.ts +2 -2
  37. package/dist/index.js +6 -6
  38. package/dist/index.js.map +1 -1
  39. package/dist/registry/index.json +1 -1
  40. package/dist/tasks/index.d.cts +1 -1
  41. package/dist/tasks/index.d.ts +1 -1
  42. package/dist/{types-B1tJoI4g.d.ts → types-gyvA7BtO.d.cts} +12 -1
  43. package/dist/{types-B1tJoI4g.d.cts → types-gyvA7BtO.d.ts} +12 -1
  44. package/package.json +1 -1
  45. package/dist/chunk-B2I7SYQ3.js.map +0 -1
  46. package/dist/chunk-BUBXO7WU.js.map +0 -1
  47. package/dist/chunk-FQFKHPLR.cjs.map +0 -1
  48. package/dist/chunk-MGH4VDV3.cjs.map +0 -1
  49. /package/dist/{chunk-OSES7ZQ5.js.map → chunk-2PBMLMO4.js.map} +0 -0
  50. /package/dist/{chunk-TRC4DUZB.js.map → chunk-RSZB7VAO.js.map} +0 -0
@@ -18,7 +18,7 @@
18
18
 
19
19
 
20
20
 
21
- var _chunk75O3WQKRcjs = require('./chunk-75O3WQKR.cjs');
21
+ var _chunk66R7S7J3cjs = require('./chunk-66R7S7J3.cjs');
22
22
 
23
23
 
24
24
 
@@ -26,7 +26,7 @@ var _chunk75O3WQKRcjs = require('./chunk-75O3WQKR.cjs');
26
26
 
27
27
 
28
28
 
29
- var _chunkMGH4VDV3cjs = require('./chunk-MGH4VDV3.cjs');
29
+ var _chunkVQSWSYK6cjs = require('./chunk-VQSWSYK6.cjs');
30
30
 
31
31
 
32
32
  var _chunkYL37D6KMcjs = require('./chunk-YL37D6KM.cjs');
@@ -35,11 +35,11 @@ var _chunkYL37D6KMcjs = require('./chunk-YL37D6KM.cjs');
35
35
  var mongoosePromise;
36
36
  function loadMongoose() {
37
37
  mongoosePromise ??= Promise.resolve().then(() => _interopRequireWildcard(require("mongoose"))).then((mod) => _nullishCoalesce(mod.default, () => ( mod))).then((mg) => {
38
- _chunkMGH4VDV3cjs.whenQueryTracking.call(void 0, () => mg.set("debug", _chunkMGH4VDV3cjs.countStatement));
38
+ _chunkVQSWSYK6cjs.whenQueryTracking.call(void 0, () => mg.set("debug", _chunkVQSWSYK6cjs.countStatement));
39
39
  return mg;
40
40
  }).catch((err) => {
41
41
  mongoosePromise = void 0;
42
- throw _chunkMGH4VDV3cjs.notInstalled.call(void 0, err, "mongoose", "npm install mongoose");
42
+ throw _chunkVQSWSYK6cjs.notInstalled.call(void 0, err, "mongoose", "npm install mongoose");
43
43
  });
44
44
  return mongoosePromise;
45
45
  }
@@ -65,7 +65,7 @@ function rules(node, mg) {
65
65
  if (d.unique !== void 0) entry["unique"] = d.unique;
66
66
  if (d.index !== void 0) entry["index"] = d.index;
67
67
  if (d.default !== void 0)
68
- entry["default"] = _chunk75O3WQKRcjs.resolveDefault.call(void 0, d.default, () => new mg.Types.ObjectId());
68
+ entry["default"] = _chunk66R7S7J3cjs.resolveDefault.call(void 0, d.default, () => new mg.Types.ObjectId());
69
69
  if (d.enum !== void 0) entry["enum"] = d.enum;
70
70
  if (d.min !== void 0) entry["min"] = d.min;
71
71
  if (d.max !== void 0) entry["max"] = d.max;
@@ -139,7 +139,7 @@ function normalise(value) {
139
139
  function translateError(model, err) {
140
140
  const e = err;
141
141
  if (_optionalChain([e, 'optionalAccess', _ => _.name]) === "ValidationError" && e.errors) {
142
- throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(
142
+ throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(
143
143
  model,
144
144
  Object.entries(e.errors).map(([path, v]) => ({
145
145
  path,
@@ -151,13 +151,13 @@ function translateError(model, err) {
151
151
  );
152
152
  }
153
153
  if (_optionalChain([e, 'optionalAccess', _2 => _2.name]) === "CastError") {
154
- throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(model, [
154
+ throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(model, [
155
155
  { path: _nullishCoalesce(e.path, () => ( "")), message: _nullishCoalesce(e.message, () => ( "invalid value")) }
156
156
  ]);
157
157
  }
158
158
  if (_optionalChain([e, 'optionalAccess', _3 => _3.code]) === 11e3) {
159
159
  const field = _nullishCoalesce(Object.keys(_nullishCoalesce(e.keyValue, () => ( {})))[0], () => ( "field"));
160
- throw new (0, _chunk75O3WQKRcjs.HttpError)(409, `${model} with this ${field} already exists`);
160
+ throw new (0, _chunk66R7S7J3cjs.HttpError)(409, `${model} with this ${field} already exists`);
161
161
  }
162
162
  throw err;
163
163
  }
@@ -183,14 +183,14 @@ function mapSort(sort) {
183
183
  }
184
184
  function mongoModel(name, tree, options) {
185
185
  let compiled;
186
- const model = () => compiled ??= _chunkMGH4VDV3cjs.untracked.call(void 0,
186
+ const model = () => compiled ??= _chunkVQSWSYK6cjs.untracked.call(void 0,
187
187
  () => loadMongoose().then(async (mg) => {
188
188
  if (mg.models[name]) return mg.models[name];
189
189
  const schema = new mg.Schema(buildTree(tree, mg), {
190
190
  timestamps: _nullishCoalesce(options.timestamps, () => ( true)),
191
191
  // autoSync: false hands collection and index creation to migrations, on MongoDB too.
192
- autoIndex: _chunk75O3WQKRcjs.isAutoSync.call(void 0, ),
193
- autoCreate: _chunk75O3WQKRcjs.isAutoSync.call(void 0, ),
192
+ autoIndex: _chunk66R7S7J3cjs.isAutoSync.call(void 0, ),
193
+ autoCreate: _chunk66R7S7J3cjs.isAutoSync.call(void 0, ),
194
194
  ...options.collection !== void 0 && { collection: options.collection }
195
195
  });
196
196
  for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
@@ -202,7 +202,7 @@ function mongoModel(name, tree, options) {
202
202
  ...idx.name !== void 0 && { name: idx.name }
203
203
  });
204
204
  }
205
- const sequences = _chunk75O3WQKRcjs.sequenceFields.call(void 0, name, tree);
205
+ const sequences = _chunk66R7S7J3cjs.sequenceFields.call(void 0, name, tree);
206
206
  if (sequences.length > 0) {
207
207
  schema.pre("validate", async function() {
208
208
  if (!this.isNew) return;
@@ -212,7 +212,7 @@ function mongoModel(name, tree, options) {
212
212
  });
213
213
  }
214
214
  const M = mg.model(name, schema);
215
- if (_chunk75O3WQKRcjs.isAutoSync.call(void 0, )) {
215
+ if (_chunk66R7S7J3cjs.isAutoSync.call(void 0, )) {
216
216
  await M.init().catch((err) => {
217
217
  _chunkYL37D6KMcjs.getLogger.call(void 0, ).warn(
218
218
  { model: name, err: err.message },
@@ -224,7 +224,7 @@ function mongoModel(name, tree, options) {
224
224
  })
225
225
  );
226
226
  const session = () => {
227
- const tx = _chunk75O3WQKRcjs.currentTx.call(void 0, );
227
+ const tx = _chunk66R7S7J3cjs.currentTx.call(void 0, );
228
228
  return _optionalChain([tx, 'optionalAccess', _5 => _5.engine]) === "mongodb" ? { session: tx.session } : {};
229
229
  };
230
230
  const applyQueryOptions = (q2, opts) => {
@@ -358,7 +358,7 @@ function mongoModel(name, tree, options) {
358
358
  }),
359
359
  raw: () => model(),
360
360
  async sync(opts) {
361
- if (_chunk75O3WQKRcjs.isSyncSuppressed.call(void 0, )) return [];
361
+ if (_chunk66R7S7J3cjs.isSyncSuppressed.call(void 0, )) return [];
362
362
  const M = await model();
363
363
  const changes = [];
364
364
  const exists = (await M.db.db.listCollections({ name: M.collection.collectionName }).toArray()).length > 0;
@@ -444,16 +444,23 @@ function mongoModel(name, tree, options) {
444
444
  }
445
445
 
446
446
  // src/db/mongo.ts
447
- async function connectMongo(url) {
447
+ async function connectMongo(url, pool = {}) {
448
448
  const mg = await loadMongoose();
449
- await mg.connect(url);
449
+ await mg.connect(url, {
450
+ ...pool.max !== void 0 && { maxPoolSize: pool.max },
451
+ ...pool.idleTimeoutMs !== void 0 && { maxIdleTimeMS: pool.idleTimeoutMs },
452
+ ...pool.connectionTimeoutMs !== void 0 && {
453
+ serverSelectionTimeoutMS: pool.connectionTimeoutMs,
454
+ waitQueueTimeoutMS: pool.connectionTimeoutMs
455
+ }
456
+ });
450
457
  _chunkYL37D6KMcjs.getLogger.call(void 0, ).info("MongoDB connected");
451
458
  return mg.connection;
452
459
  }
453
460
 
454
461
  // src/db/pg-model.ts
455
462
  function pgModel(name, tree, options) {
456
- const tbl = _chunk75O3WQKRcjs.pgTable.call(void 0, name, tree, options, { native: false, api: "defineModel" });
463
+ const tbl = _chunk66R7S7J3cjs.pgTable.call(void 0, name, tree, options, { native: false, api: "defineModel" });
457
464
  const { columns, ts, refs, ready, compile, client, columnFor, toDb, fromRow, validate, guard } = tbl;
458
465
  const kindOf = (field) => _optionalChain([columns, 'access', _15 => _15.get, 'call', _16 => _16(field), 'optionalAccess', _17 => _17.kind]);
459
466
  function missingField(sql, cond) {
@@ -553,7 +560,7 @@ function pgModel(name, tree, options) {
553
560
  break;
554
561
  }
555
562
  default:
556
- throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(name, [
563
+ throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(name, [
557
564
  { path, message: `operator ${op} is not supported on PostgreSQL` }
558
565
  ]);
559
566
  }
@@ -584,8 +591,8 @@ function pgModel(name, tree, options) {
584
591
  for (const path of Array.isArray(paths) ? paths : [paths]) {
585
592
  const ref = refs.get(path);
586
593
  if (!ref)
587
- throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(name, [{ path, message: "is not a populatable ref field" }]);
588
- const target = _chunk75O3WQKRcjs.getRegisteredModel.call(void 0, ref.model);
594
+ throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(name, [{ path, message: "is not a populatable ref field" }]);
595
+ const target = _chunk66R7S7J3cjs.getRegisteredModel.call(void 0, ref.model);
589
596
  if (!target) throw new Error(`[EFC] populate: model "${ref.model}" is not defined`);
590
597
  const ids = [
591
598
  ...new Set(
@@ -628,7 +635,7 @@ function pgModel(name, tree, options) {
628
635
  return populate(rows, _optionalChain([opts, 'optionalAccess', _22 => _22.populate]));
629
636
  }
630
637
  const strictUpdate = (update) => {
631
- const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || _chunk75O3WQKRcjs.nodeAt.call(void 0, tree, path.split(".")) !== void 0);
638
+ const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || _chunk66R7S7J3cjs.nodeAt.call(void 0, tree, path.split(".")) !== void 0);
632
639
  const out = {};
633
640
  for (const [k, v] of Object.entries(update)) {
634
641
  if (k.startsWith("$") && v !== null && typeof v === "object") {
@@ -643,7 +650,7 @@ function pgModel(name, tree, options) {
643
650
  const ops = update;
644
651
  for (const op of Object.keys(update).filter((k) => k.startsWith("$"))) {
645
652
  if (!["$set", "$unset", "$inc", "$push", "$pull"].includes(op)) {
646
- throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(name, [
653
+ throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(name, [
647
654
  { path: op, message: "update operator is not supported on PostgreSQL" }
648
655
  ]);
649
656
  }
@@ -656,25 +663,25 @@ function pgModel(name, tree, options) {
656
663
  for (const [k, v] of Object.entries($set)) if (!k.includes(".")) topLevel[k] = v;
657
664
  for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) if (!k.includes(".")) topLevel[k] = null;
658
665
  for (const [k, v] of Object.entries($set))
659
- if (k.includes(".")) await _chunk75O3WQKRcjs.validateAtPath.call(void 0, tree, k, v, issues);
666
+ if (k.includes(".")) await _chunk66R7S7J3cjs.validateAtPath.call(void 0, tree, k, v, issues);
660
667
  for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) {
661
- if (k.includes(".")) await _chunk75O3WQKRcjs.validateAtPath.call(void 0, tree, k, null, issues);
668
+ if (k.includes(".")) await _chunk66R7S7J3cjs.validateAtPath.call(void 0, tree, k, null, issues);
662
669
  }
663
670
  for (const [k, by] of Object.entries(_nullishCoalesce(ops["$inc"], () => ( {})))) {
664
671
  if (typeof by !== "number") issues.push({ path: k, message: "$inc needs a number" });
665
- const node = k.includes(".") ? _chunk75O3WQKRcjs.nodeAt.call(void 0, tree, k.split(".")) : tree[k];
672
+ const node = k.includes(".") ? _chunk66R7S7J3cjs.nodeAt.call(void 0, tree, k.split(".")) : tree[k];
666
673
  if (node && !(node.kind === "scalar" && node.type === "number") && node.kind !== "json") {
667
674
  issues.push({ path: k, message: "$inc only applies to number fields" });
668
675
  }
669
676
  }
670
- if (issues.length) throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(name, issues);
677
+ if (issues.length) throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(name, issues);
671
678
  await validate(topLevel, true);
672
679
  const set = {};
673
680
  const nested = /* @__PURE__ */ new Map();
674
681
  const touchedTop = /* @__PURE__ */ new Set();
675
682
  const acc = (field) => _nullishCoalesce(nested.get(field), () => ( columnFor(t, field)));
676
683
  const conflict = (path) => {
677
- throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(name, [{ path, message: "conflicting update paths" }]);
684
+ throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(name, [{ path, message: "conflicting update paths" }]);
678
685
  };
679
686
  const top = (field, value) => {
680
687
  if (touchedTop.has(field) || nested.has(field)) conflict(field);
@@ -845,7 +852,7 @@ function defineModel(name, schema, options) {
845
852
  return createModel(name, schema, _nullishCoalesce(options, () => ( {})));
846
853
  }
847
854
  function distinctFields(tree, options) {
848
- const ts = _chunk75O3WQKRcjs.timestampFields.call(void 0, options);
855
+ const ts = _chunk66R7S7J3cjs.timestampFields.call(void 0, options);
849
856
  const fields = /* @__PURE__ */ new Set(["id", ...Object.values(ts)]);
850
857
  for (const [key, node] of Object.entries(tree)) if (node.kind === "scalar") fields.add(key);
851
858
  return fields;
@@ -870,11 +877,11 @@ var MODEL_OPS = [
870
877
  ];
871
878
  var sortKey = (v) => v instanceof Date ? v.getTime() : v;
872
879
  function createModel(name, schema, options, native) {
873
- const tree = _chunk75O3WQKRcjs.normalizeSchema.call(void 0, schema, "model", name);
880
+ const tree = _chunk66R7S7J3cjs.normalizeSchema.call(void 0, schema, "model", name);
874
881
  let engineModel;
875
882
  const impl = () => {
876
883
  if (engineModel) return engineModel;
877
- const engine = _chunk75O3WQKRcjs.getDbEngine.call(void 0, );
884
+ const engine = _chunk66R7S7J3cjs.getDbEngine.call(void 0, );
878
885
  if (native && native.engine !== engine) {
879
886
  throw new Error(
880
887
  `[EFC] ${name} is a ${ENGINE_LABEL[native.engine]} ${native.kind} (${native.api}) but the app is connected to ${ENGINE_LABEL[engine]} \u2014 check DATABASE_URL / config.database, or use defineModel for a model that runs on both`
@@ -916,7 +923,7 @@ function createModel(name, schema, options, native) {
916
923
  try {
917
924
  return await m.create(create);
918
925
  } catch (err) {
919
- if (_chunk75O3WQKRcjs.isHttpError.call(void 0, err) && err.statusCode === 409 && !_chunk75O3WQKRcjs.currentTx.call(void 0, )) {
926
+ if (_chunk66R7S7J3cjs.isHttpError.call(void 0, err) && err.statusCode === 409 && !_chunk66R7S7J3cjs.currentTx.call(void 0, )) {
920
927
  const retried = await m.updateOne(filter, update);
921
928
  if (retried) return retried;
922
929
  }
@@ -932,26 +939,26 @@ function createModel(name, schema, options, native) {
932
939
  sync: (opts) => call((m) => m.sync(opts)),
933
940
  drop: () => call((m) => m.drop())
934
941
  };
935
- _chunkMGH4VDV3cjs.traceOps.call(void 0, name, model, MODEL_OPS);
936
- _chunk75O3WQKRcjs.registerModel.call(void 0, {
942
+ _chunkVQSWSYK6cjs.traceOps.call(void 0, name, model, MODEL_OPS);
943
+ _chunk66R7S7J3cjs.registerModel.call(void 0, {
937
944
  name,
938
945
  sync: model.sync,
939
946
  plan: (opts) => call((m) => m.plan(opts)),
940
947
  drop: model.drop,
941
948
  findByIds: (ids) => model.find({ id: { $in: ids } }),
942
- pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => ( _chunk75O3WQKRcjs.tableNameFor.call(void 0, name))), idKind: "uuid" })
949
+ pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => ( _chunk66R7S7J3cjs.tableNameFor.call(void 0, name))), idKind: "uuid" })
943
950
  });
944
951
  return model;
945
952
  }
946
953
 
947
954
  // src/db/transaction.ts
948
955
  async function transaction(fn) {
949
- if (_chunk75O3WQKRcjs.currentTx.call(void 0, )) return fn();
950
- if (_chunk75O3WQKRcjs.getDbEngine.call(void 0, ) === "postgresql") {
956
+ if (_chunk66R7S7J3cjs.currentTx.call(void 0, )) return fn();
957
+ if (_chunk66R7S7J3cjs.getDbEngine.call(void 0, ) === "postgresql") {
951
958
  let result;
952
959
  const afterCommit = [];
953
- await _chunkMGH4VDV3cjs.getOrm.call(void 0, ).transaction(async (tx) => {
954
- result = await _chunk75O3WQKRcjs.runInTx.call(void 0, { engine: "postgresql", tx, afterCommit }, fn);
960
+ await _chunkVQSWSYK6cjs.getOrm.call(void 0, ).transaction(async (tx) => {
961
+ result = await _chunk66R7S7J3cjs.runInTx.call(void 0, { engine: "postgresql", tx, afterCommit }, fn);
955
962
  });
956
963
  for (const run of afterCommit) run();
957
964
  return result;
@@ -961,7 +968,7 @@ async function transaction(fn) {
961
968
  try {
962
969
  let result;
963
970
  await session.withTransaction(async () => {
964
- result = await _chunk75O3WQKRcjs.runInTx.call(void 0, { engine: "mongodb", session }, fn);
971
+ result = await _chunk66R7S7J3cjs.runInTx.call(void 0, { engine: "mongodb", session }, fn);
965
972
  });
966
973
  return result;
967
974
  } finally {
@@ -1007,8 +1014,8 @@ var TableRuntime = (_class = class {
1007
1014
  constructor(name, schema, options) {;_class.prototype.__init.call(this);
1008
1015
  this.name = name;
1009
1016
  this.options = options;
1010
- const tree = _chunk75O3WQKRcjs.normalizeSchema.call(void 0, schema, "table", name);
1011
- this.tbl = _chunk75O3WQKRcjs.pgTable.call(void 0, name, tree, options, { native: true, api: "defineTable" });
1017
+ const tree = _chunk66R7S7J3cjs.normalizeSchema.call(void 0, schema, "table", name);
1018
+ this.tbl = _chunk66R7S7J3cjs.pgTable.call(void 0, name, tree, options, { native: true, api: "defineTable" });
1012
1019
  this.uniqueSets = [["id"]];
1013
1020
  for (const spec of this.tbl.columns.values()) {
1014
1021
  if (_optionalChain([spec, 'access', _25 => _25.node, 'optionalAccess', _26 => _26.def, 'access', _27 => _27.unique])) this.uniqueSets.push([spec.field]);
@@ -1035,7 +1042,7 @@ var TableRuntime = (_class = class {
1035
1042
  /** Many-to-many fields as list columns, so filters and projections treat them alike. */
1036
1043
  __init() {this.joinSpecs = /* @__PURE__ */ new Map()}
1037
1044
  fail(path, message) {
1038
- throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(this.name, [{ path, message }]);
1045
+ throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(this.name, [{ path, message }]);
1039
1046
  }
1040
1047
  spec(field) {
1041
1048
  return _nullishCoalesce(this.tbl.columns.get(field), () => ( this.joinSpecs.get(field)));
@@ -1046,18 +1053,18 @@ var TableRuntime = (_class = class {
1046
1053
  /** A many-to-many field's ids, in order, for the row `owner` (a table name or alias). */
1047
1054
  joinExpr(sql, join, owner) {
1048
1055
  return sql.raw(
1049
- `coalesce((select array_agg(efc_j.ref_id order by efc_j.position) from ${_chunk75O3WQKRcjs.q.call(void 0, join.table)} efc_j where efc_j.owner_id = ${owner}.${_chunk75O3WQKRcjs.q.call(void 0, "id")}), '{}'::${join.ddl})`
1056
+ `coalesce((select array_agg(efc_j.ref_id order by efc_j.position) from ${_chunk66R7S7J3cjs.q.call(void 0, join.table)} efc_j where efc_j.owner_id = ${owner}.${_chunk66R7S7J3cjs.q.call(void 0, "id")}), '{}'::${join.ddl})`
1050
1057
  );
1051
1058
  }
1052
1059
  col(sql, field, alias) {
1053
1060
  const join = this.join(field);
1054
- if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => ( _chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))));
1061
+ if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => ( _chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))));
1055
1062
  const spec = this.spec(field);
1056
- return sql.raw(alias ? `${alias}.${_chunk75O3WQKRcjs.q.call(void 0, spec.column)}` : _chunk75O3WQKRcjs.q.call(void 0, spec.column));
1063
+ return sql.raw(alias ? `${alias}.${_chunk66R7S7J3cjs.q.call(void 0, spec.column)}` : _chunk66R7S7J3cjs.q.call(void 0, spec.column));
1057
1064
  }
1058
1065
  /** SELECT items for the many-to-many fields among `fields`, as text arrays. */
1059
1066
  joinColumns(sql, fields, owner) {
1060
- return fields.filter((f) => this.join(f)).map((f) => sql`${this.col(sql, f, owner)}::text[] as ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, relAlias(f)))}`);
1067
+ return fields.filter((f) => this.join(f)).map((f) => sql`${this.col(sql, f, owner)}::text[] as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, relAlias(f)))}`);
1061
1068
  }
1062
1069
  /** `col` for SELECT lists: many-to-many fields come back as text arrays under an alias. */
1063
1070
  selectCols(sql, fields, owner) {
@@ -1349,7 +1356,7 @@ var TableRuntime = (_class = class {
1349
1356
  if (args["cursor"]) {
1350
1357
  this.uniqueKey(args["cursor"], "cursor");
1351
1358
  const cw = this.where(sql, t, args["cursor"]);
1352
- const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} where ${cw})`;
1359
+ const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${cw})`;
1353
1360
  const ors = [];
1354
1361
  const same = (o) => sql`${this.col(sql, o.field)} is not distinct from ${at(o.field)}`;
1355
1362
  for (let i = 0; i < order.length; i++) {
@@ -1362,7 +1369,7 @@ var TableRuntime = (_class = class {
1362
1369
  ors.push(eqs.length ? sql`(${sql.join([...eqs, after], sql` and `)})` : after);
1363
1370
  }
1364
1371
  ors.push(sql`(${sql.join(order.map(same), sql` and `)})`);
1365
- parts.push(sql`exists (select 1 from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} where ${cw})`);
1372
+ parts.push(sql`exists (select 1 from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${cw})`);
1366
1373
  parts.push(sql`(${sql.join(ors, sql` or `)})`);
1367
1374
  }
1368
1375
  return parts.length ? sql.join(parts, sql` and `) : sql`true`;
@@ -1387,7 +1394,7 @@ var TableRuntime = (_class = class {
1387
1394
  const offset = args["skip"] ? sql` offset ${sql.param(args["skip"])}` : sql``;
1388
1395
  const orderBy = order.length ? sql` order by ${this.orderSql(sql, order)}` : sql``;
1389
1396
  const where = this.readWhere(sql, t, args, order);
1390
- const from = sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table));
1397
+ const from = sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table));
1391
1398
  const distinct = _optionalChain([args, 'access', _29 => _29["distinct"], 'optionalAccess', _30 => _30.filter, 'call', _31 => _31((f) => this.spec(f))]);
1392
1399
  if (_optionalChain([distinct, 'optionalAccess', _32 => _32.length])) {
1393
1400
  const dcols = sql.join(
@@ -1417,7 +1424,7 @@ var TableRuntime = (_class = class {
1417
1424
  distinct ? "efc_distinct" : void 0
1418
1425
  );
1419
1426
  const include = this.includeArg(args);
1420
- const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : _chunk75O3WQKRcjs.q.call(void 0, this.tbl.table), 1) : [];
1427
+ const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : _chunk66R7S7J3cjs.q.call(void 0, this.tbl.table), 1) : [];
1421
1428
  const { query, reversed } = this.readQuery(
1422
1429
  sql,
1423
1430
  t,
@@ -1492,7 +1499,7 @@ var TableRuntime = (_class = class {
1492
1499
  for (const [name, arg] of Object.entries(include)) {
1493
1500
  if (!arg) continue;
1494
1501
  const expr = await this.relationExpr(sql, this.relation(name), relArgs(arg), owner, depth);
1495
- out.push(sql`${expr} as ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, incAlias(name)))}`);
1502
+ out.push(sql`${expr} as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, incAlias(name)))}`);
1496
1503
  }
1497
1504
  return out;
1498
1505
  }
@@ -1526,21 +1533,21 @@ var TableRuntime = (_class = class {
1526
1533
  */
1527
1534
  relationSource(rel, owner, a, j) {
1528
1535
  const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
1529
- const target = `${_chunk75O3WQKRcjs.q.call(void 0, T.tbl.table)} ${a}`;
1530
- const ownerId = `${owner}.${_chunk75O3WQKRcjs.q.call(void 0, "id")}`;
1536
+ const target = `${_chunk66R7S7J3cjs.q.call(void 0, T.tbl.table)} ${a}`;
1537
+ const ownerId = `${owner}.${_chunk66R7S7J3cjs.q.call(void 0, "id")}`;
1531
1538
  if (rel.via === "fk") {
1532
1539
  return {
1533
1540
  T,
1534
1541
  from: target,
1535
- cond: `${a}.${_chunk75O3WQKRcjs.q.call(void 0, "id")} = ${owner}.${_chunk75O3WQKRcjs.q.call(void 0, rel.column)}`,
1536
- defaultOrder: `${a}.${_chunk75O3WQKRcjs.q.call(void 0, "id")}`
1542
+ cond: `${a}.${_chunk66R7S7J3cjs.q.call(void 0, "id")} = ${owner}.${_chunk66R7S7J3cjs.q.call(void 0, rel.column)}`,
1543
+ defaultOrder: `${a}.${_chunk66R7S7J3cjs.q.call(void 0, "id")}`
1537
1544
  };
1538
1545
  }
1539
1546
  let from;
1540
1547
  let cond;
1541
1548
  let defaultOrder;
1542
1549
  if (rel.via === "join") {
1543
- from = `${_chunk75O3WQKRcjs.q.call(void 0, rel.join.table)} ${j} join ${target} on ${a}.${_chunk75O3WQKRcjs.q.call(void 0, "id")} = ${j}.ref_id`;
1550
+ from = `${_chunk66R7S7J3cjs.q.call(void 0, rel.join.table)} ${j} join ${target} on ${a}.${_chunk66R7S7J3cjs.q.call(void 0, "id")} = ${j}.ref_id`;
1544
1551
  cond = `${j}.owner_id = ${ownerId}`;
1545
1552
  defaultOrder = `${j}.position`;
1546
1553
  } else {
@@ -1558,7 +1565,7 @@ var TableRuntime = (_class = class {
1558
1565
  `[EFC] ${this.name}.${rel.name}: ${rel.target}.${rel.foreignKey} is many-to-many \u2014 use hasMany`
1559
1566
  );
1560
1567
  }
1561
- from = `${_chunk75O3WQKRcjs.q.call(void 0, join.table)} ${j} join ${target} on ${a}.${_chunk75O3WQKRcjs.q.call(void 0, "id")} = ${j}.owner_id`;
1568
+ from = `${_chunk66R7S7J3cjs.q.call(void 0, join.table)} ${j} join ${target} on ${a}.${_chunk66R7S7J3cjs.q.call(void 0, "id")} = ${j}.owner_id`;
1562
1569
  cond = `${j}.ref_id = ${ownerId}`;
1563
1570
  } else {
1564
1571
  if (rel.kind === "one" && !column.node.def.unique) {
@@ -1567,9 +1574,9 @@ var TableRuntime = (_class = class {
1567
1574
  );
1568
1575
  }
1569
1576
  from = target;
1570
- cond = `${a}.${_chunk75O3WQKRcjs.q.call(void 0, column.column)} = ${ownerId}`;
1577
+ cond = `${a}.${_chunk66R7S7J3cjs.q.call(void 0, column.column)} = ${ownerId}`;
1571
1578
  }
1572
- defaultOrder = `${a}.${_chunk75O3WQKRcjs.q.call(void 0, "id")}`;
1579
+ defaultOrder = `${a}.${_chunk66R7S7J3cjs.q.call(void 0, "id")}`;
1573
1580
  }
1574
1581
  return { T, from, cond, defaultOrder };
1575
1582
  }
@@ -1594,7 +1601,7 @@ var TableRuntime = (_class = class {
1594
1601
  const where = isPlainObject(w) ? w : { id: w };
1595
1602
  const found = await T.findUnique({ where, select: { id: true } });
1596
1603
  if (!found) {
1597
- throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(this.name, [
1604
+ throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(this.name, [
1598
1605
  { path, message: `no ${rel.target} matches ${JSON.stringify(where, idJson)}` }
1599
1606
  ]);
1600
1607
  }
@@ -1686,8 +1693,8 @@ var TableRuntime = (_class = class {
1686
1693
  try {
1687
1694
  await T.updateNested({ where: whereOf(w), data: { [fk]: owner } });
1688
1695
  } catch (err) {
1689
- if (_chunk75O3WQKRcjs.isHttpError.call(void 0, err) && err.statusCode === 404) {
1690
- throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(this.name, [
1696
+ if (_chunk66R7S7J3cjs.isHttpError.call(void 0, err) && err.statusCode === 404) {
1697
+ throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(this.name, [
1691
1698
  {
1692
1699
  path: key,
1693
1700
  message: `no ${rel.target} matches ${JSON.stringify(whereOf(w), idJson)}`
@@ -1708,29 +1715,35 @@ var TableRuntime = (_class = class {
1708
1715
  };
1709
1716
  after.push(async (owner) => {
1710
1717
  if (rel.kind === "one") {
1711
- if (mode === "update" && (_optionalChain([ops, 'optionalAccess', _40 => _40["create"]]) || _optionalChain([ops, 'optionalAccess', _41 => _41["connect"]]) || _optionalChain([ops, 'optionalAccess', _42 => _42["disconnect"]]))) {
1712
- await unlink(owner);
1718
+ if (_optionalChain([ops, 'optionalAccess', _40 => _40["delete"]])) await T.deleteMany({ where: mine(owner) });
1719
+ if (mode === "update" && (_optionalChain([ops, 'optionalAccess', _41 => _41["create"]]) || _optionalChain([ops, 'optionalAccess', _42 => _42["connect"]]) || _optionalChain([ops, 'optionalAccess', _43 => _43["disconnect"]]))) {
1720
+ if (!_optionalChain([T, 'access', _44 => _44.tbl, 'access', _45 => _45.columns, 'access', _46 => _46.get, 'call', _47 => _47(fk), 'optionalAccess', _48 => _48.node, 'optionalAccess', _49 => _49.def, 'access', _50 => _50.required])) await unlink(owner);
1721
+ else if ((await T.findMany({ where: mine(owner), select: { id: true }, take: 1 })).length) {
1722
+ this.fail(
1723
+ key,
1724
+ `${rel.target}.${fk} is required, so the current ${rel.target} can't be unlinked \u2014 add delete: true to replace it`
1725
+ );
1726
+ }
1713
1727
  }
1714
- if (_optionalChain([ops, 'optionalAccess', _43 => _43["delete"]])) await T.deleteMany({ where: mine(owner) });
1715
- if (_optionalChain([ops, 'optionalAccess', _44 => _44["connect"]]) !== void 0) await link(owner, ops["connect"]);
1716
- if (_optionalChain([ops, 'optionalAccess', _45 => _45["create"]]) !== void 0) await createChild(owner, ops["create"]);
1728
+ if (_optionalChain([ops, 'optionalAccess', _51 => _51["connect"]]) !== void 0) await link(owner, ops["connect"]);
1729
+ if (_optionalChain([ops, 'optionalAccess', _52 => _52["create"]]) !== void 0) await createChild(owner, ops["create"]);
1717
1730
  return;
1718
1731
  }
1719
- if (_optionalChain([ops, 'optionalAccess', _46 => _46["set"]]) !== void 0) {
1732
+ if (_optionalChain([ops, 'optionalAccess', _53 => _53["set"]]) !== void 0) {
1720
1733
  const keep = list(ops["set"]).map(whereOf);
1721
1734
  await unlink(owner, keep.length ? { NOT: { OR: keep } } : void 0);
1722
1735
  for (const w of keep) await link(owner, w);
1723
1736
  }
1724
- for (const w of list(_optionalChain([ops, 'optionalAccess', _47 => _47["disconnect"]]))) await unlink(owner, whereOf(w));
1725
- for (const w of list(_optionalChain([ops, 'optionalAccess', _48 => _48["delete"]])))
1737
+ for (const w of list(_optionalChain([ops, 'optionalAccess', _54 => _54["disconnect"]]))) await unlink(owner, whereOf(w));
1738
+ for (const w of list(_optionalChain([ops, 'optionalAccess', _55 => _55["delete"]])))
1726
1739
  await T.deleteMany({ where: { AND: [mine(owner), whereOf(w)] } });
1727
- if (_optionalChain([ops, 'optionalAccess', _49 => _49["deleteMany"]]) !== void 0) {
1740
+ if (_optionalChain([ops, 'optionalAccess', _56 => _56["deleteMany"]]) !== void 0) {
1728
1741
  for (const w of list(ops["deleteMany"])) {
1729
1742
  await T.deleteMany({ where: { AND: [mine(owner), ...isPlainObject(w) ? [w] : []] } });
1730
1743
  }
1731
1744
  }
1732
- for (const w of list(_optionalChain([ops, 'optionalAccess', _50 => _50["connect"]]))) await link(owner, w);
1733
- for (const c of list(_optionalChain([ops, 'optionalAccess', _51 => _51["create"]]))) await createChild(owner, c);
1745
+ for (const w of list(_optionalChain([ops, 'optionalAccess', _57 => _57["connect"]]))) await link(owner, w);
1746
+ for (const c of list(_optionalChain([ops, 'optionalAccess', _58 => _58["create"]]))) await createChild(owner, c);
1734
1747
  });
1735
1748
  }
1736
1749
  return { data: out, after };
@@ -1832,7 +1845,7 @@ var TableRuntime = (_class = class {
1832
1845
  const a = `efc_f${++aliasSeq}`;
1833
1846
  const { T, from, cond } = this.relationSource(
1834
1847
  rel,
1835
- _nullishCoalesce(owner, () => ( _chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))),
1848
+ _nullishCoalesce(owner, () => ( _chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))),
1836
1849
  a,
1837
1850
  `efc_fj${aliasSeq}`
1838
1851
  );
@@ -1874,7 +1887,7 @@ var TableRuntime = (_class = class {
1874
1887
  const include = this.includeArg(args);
1875
1888
  const pairs = [];
1876
1889
  for (const f of this.projection(args)) {
1877
- if (_optionalChain([include, 'optionalAccess', _52 => _52[f]])) continue;
1890
+ if (_optionalChain([include, 'optionalAccess', _59 => _59[f]])) continue;
1878
1891
  pairs.push(sql`${sql.raw(literal(f))}, ${this.jsonValue(sql, f, alias)}`);
1879
1892
  }
1880
1893
  for (const [name, arg] of Object.entries(_nullishCoalesce(include, () => ( {})))) {
@@ -1905,7 +1918,7 @@ var TableRuntime = (_class = class {
1905
1918
  const include = this.includeArg(args);
1906
1919
  const keyed = {};
1907
1920
  for (const f of this.projection(args)) {
1908
- if (_optionalChain([include, 'optionalAccess', _53 => _53[f]])) continue;
1921
+ if (_optionalChain([include, 'optionalAccess', _60 => _60[f]])) continue;
1909
1922
  const v = json[f];
1910
1923
  const join = this.join(f);
1911
1924
  if (v == null || join) {
@@ -1973,7 +1986,7 @@ var TableRuntime = (_class = class {
1973
1986
  }
1974
1987
  async orThrow(p) {
1975
1988
  const r = await p;
1976
- if (r === null) throw new (0, _chunk75O3WQKRcjs.HttpError)(404, `${this.name} not found`);
1989
+ if (r === null) throw new (0, _chunk66R7S7J3cjs.HttpError)(404, `${this.name} not found`);
1977
1990
  return r;
1978
1991
  }
1979
1992
  async count(args = {}) {
@@ -1983,7 +1996,7 @@ var TableRuntime = (_class = class {
1983
1996
  const counted = select ? Object.entries(select).filter(([f, on]) => on && (f === "_all" || this.spec(f))) : [["_all", true]];
1984
1997
  const exprs = sql.join(
1985
1998
  counted.map(
1986
- ([f]) => f === "_all" ? sql`count(*)::int as ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, "_all"))}` : sql`count(${this.col(sql, f, "efc_rows")})::int as ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, f))}`
1999
+ ([f]) => f === "_all" ? sql`count(*)::int as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, "_all"))}` : sql`count(${this.col(sql, f, "efc_rows")})::int as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, f))}`
1987
2000
  ),
1988
2001
  sql`, `
1989
2002
  );
@@ -2058,7 +2071,7 @@ var TableRuntime = (_class = class {
2058
2071
  const specs = this.aggregateSpec(args);
2059
2072
  if (specs.length === 0) return {};
2060
2073
  const exprs = sql.join(
2061
- specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, s.alias))}`),
2074
+ specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, s.alias))}`),
2062
2075
  sql`, `
2063
2076
  );
2064
2077
  const { query } = this.readQuery(sql, t, { ...args, select: void 0 }, sql`*`);
@@ -2116,7 +2129,7 @@ var TableRuntime = (_class = class {
2116
2129
  [
2117
2130
  ...by.map((f) => this.col(sql, f)),
2118
2131
  ...specs.map(
2119
- (s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, s.alias))}`
2132
+ (s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, s.alias))}`
2120
2133
  )
2121
2134
  ],
2122
2135
  sql`, `
@@ -2140,7 +2153,7 @@ var TableRuntime = (_class = class {
2140
2153
  }
2141
2154
  }
2142
2155
  }
2143
- const query = sql`select ${select} from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))}${where ? sql` where ${where}` : sql``} group by ${sql.join(
2156
+ const query = sql`select ${select} from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))}${where ? sql` where ${where}` : sql``} group by ${sql.join(
2144
2157
  by.map((f) => this.col(sql, f)),
2145
2158
  sql`, `
2146
2159
  )}${having ? sql` having ${having}` : sql``}${orders.length ? sql` order by ${sql.join(orders, sql`, `)}` : sql``}${args["take"] !== void 0 ? sql` limit ${sql.param(args["take"])}` : sql``}${args["skip"] ? sql` offset ${sql.param(args["skip"])}` : sql``}`;
@@ -2218,7 +2231,7 @@ var TableRuntime = (_class = class {
2218
2231
  }
2219
2232
  }
2220
2233
  }
2221
- if (issues.length) throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(this.name, issues);
2234
+ if (issues.length) throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(this.name, issues);
2222
2235
  await this.tbl.validate(plain, true);
2223
2236
  for (const [field, v] of Object.entries(plain)) {
2224
2237
  sets.push(
@@ -2260,7 +2273,7 @@ var TableRuntime = (_class = class {
2260
2273
  }
2261
2274
  for (const [field, entries] of byField) {
2262
2275
  const join = this.join(field);
2263
- const jt = sql.raw(_chunk75O3WQKRcjs.q.call(void 0, join.table));
2276
+ const jt = sql.raw(_chunk66R7S7J3cjs.q.call(void 0, join.table));
2264
2277
  const sets = entries.filter((e) => e.op.mode === "set");
2265
2278
  if (sets.length) {
2266
2279
  const owners2 = sets.map((e) => idText(e.id));
@@ -2307,7 +2320,7 @@ var TableRuntime = (_class = class {
2307
2320
  const idDdl = this.tbl.columns.get("id").ddl;
2308
2321
  const owners = sql`${sql.param(ids.map(idText))}::${sql.raw(idDdl)}[]`;
2309
2322
  const parts = joins.map(
2310
- (j) => sql`select ${sql.param(j.field)}::text as f, owner_id::text as o, array_agg(ref_id::text order by position) as ids from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, j.table))} where owner_id = any(${owners}) group by owner_id`
2323
+ (j) => sql`select ${sql.param(j.field)}::text as f, owner_id::text as o, array_agg(ref_id::text order by position) as ids from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, j.table))} where owner_id = any(${owners}) group by owner_id`
2311
2324
  );
2312
2325
  const { rows } = await this.exec(sql.join(parts, sql` union all `));
2313
2326
  for (const j of joins) out.set(j.field, /* @__PURE__ */ new Map());
@@ -2329,7 +2342,7 @@ var TableRuntime = (_class = class {
2329
2342
  }
2330
2343
  insertSql(sql, t, rows) {
2331
2344
  const fields = [...new Set(rows.flatMap((r) => Object.keys(r)))];
2332
- const head = sql`insert into ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} (${sql.join(
2345
+ const head = sql`insert into ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} (${sql.join(
2333
2346
  fields.map((f) => this.col(sql, f)),
2334
2347
  sql`, `
2335
2348
  )})`;
@@ -2408,7 +2421,7 @@ var TableRuntime = (_class = class {
2408
2421
  const ops = new Map(split.map((x) => [String(x.row["id"]), x.ops]));
2409
2422
  for (const record of records) {
2410
2423
  for (const join of this.tbl.joins.values()) {
2411
- const op = _optionalChain([ops, 'access', _54 => _54.get, 'call', _55 => _55(String(record["id"])), 'optionalAccess', _56 => _56.find, 'call', _57 => _57((o) => o.field === join.field)]);
2424
+ const op = _optionalChain([ops, 'access', _61 => _61.get, 'call', _62 => _62(String(record["id"])), 'optionalAccess', _63 => _63.find, 'call', _64 => _64((o) => o.field === join.field)]);
2412
2425
  record[join.field] = this.joinValues(join, op ? dedupe(op.items).map(idText) : []);
2413
2426
  }
2414
2427
  }
@@ -2426,7 +2439,7 @@ var TableRuntime = (_class = class {
2426
2439
  return;
2427
2440
  }
2428
2441
  const { rows: ids } = await this.exec(
2429
- sql`select nextval(pg_get_serial_sequence(${sql.param(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))}, 'id'))::text as id from generate_series(1, ${sql.param(missing.length)})`
2442
+ sql`select nextval(pg_get_serial_sequence(${sql.param(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))}, 'id'))::text as id from generate_series(1, ${sql.param(missing.length)})`
2430
2443
  );
2431
2444
  missing.forEach((r, i) => {
2432
2445
  const id = ids[i]["id"];
@@ -2455,9 +2468,9 @@ var TableRuntime = (_class = class {
2455
2468
  const where = this.where(sql, t, args["where"]);
2456
2469
  const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
2457
2470
  const extra = links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``;
2458
- const query = sets.length ? sql`update ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *${extra}` : sql`select *${extra} from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} where ${where} limit 1`;
2471
+ const query = sets.length ? sql`update ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *${extra}` : sql`select *${extra} from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${where} limit 1`;
2459
2472
  const [row] = (await this.exec(query)).rows;
2460
- if (!row) throw new (0, _chunk75O3WQKRcjs.HttpError)(404, `${this.name} not found`);
2473
+ if (!row) throw new (0, _chunk66R7S7J3cjs.HttpError)(404, `${this.name} not found`);
2461
2474
  const record = this.fromRaw(t, row);
2462
2475
  await this.applyJoins(sql, [{ id: record["id"], ops: joinOps }]);
2463
2476
  await this.refreshJoins(sql, [record], joinOps);
@@ -2478,7 +2491,7 @@ var TableRuntime = (_class = class {
2478
2491
  const links = returning ? this.joinColumns(sql, [...this.tbl.joins.keys()]) : [];
2479
2492
  const list = returning ? sql` returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : joinOps.length ? sql` returning ${this.col(sql, "id")}` : sql``;
2480
2493
  const result = await this.exec(
2481
- sets.length ? sql`update ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where}${list}` : sql`select ${returning ? sql`*${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : this.col(sql, "id")} from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} where ${where}`
2494
+ sets.length ? sql`update ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where}${list}` : sql`select ${returning ? sql`*${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : this.col(sql, "id")} from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${where}`
2482
2495
  );
2483
2496
  const records = result.rows.map((r) => returning ? this.fromRaw(t, r) : r);
2484
2497
  await this.applyJoins(
@@ -2502,7 +2515,7 @@ var TableRuntime = (_class = class {
2502
2515
  if (row[f] === void 0) row[f] = this.tbl.toDb(f, args["where"][f]);
2503
2516
  }
2504
2517
  const { head, values } = this.insertSql(sql, t, [row]);
2505
- const table = _chunk75O3WQKRcjs.q.call(void 0, this.tbl.table);
2518
+ const table = _chunk66R7S7J3cjs.q.call(void 0, this.tbl.table);
2506
2519
  const update = await this.setList(sql, t, _nullishCoalesce(args["update"], () => ( {})), table);
2507
2520
  const { joinOps } = update;
2508
2521
  let { sets } = update;
@@ -2523,7 +2536,7 @@ var TableRuntime = (_class = class {
2523
2536
  const [out] = (await this.exec(
2524
2537
  sql`${head} values ${values} on conflict (${target}) do update set ${sql.join(sets, sql`, `)}${cond}${returning}`
2525
2538
  )).rows;
2526
- if (!out) throw new (0, _chunk75O3WQKRcjs.HttpError)(404, `${this.name} not found`);
2539
+ if (!out) throw new (0, _chunk66R7S7J3cjs.HttpError)(404, `${this.name} not found`);
2527
2540
  const record = this.fromRaw(t, out);
2528
2541
  if (linked) {
2529
2542
  const ops = out["efc_inserted"] ? createOps.filter((o) => o.items.length) : joinOps;
@@ -2542,9 +2555,9 @@ var TableRuntime = (_class = class {
2542
2555
  const where = this.where(sql, t, args["where"]);
2543
2556
  const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
2544
2557
  const [row] = (await this.exec(
2545
- sql`delete from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} where ${where} returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}`
2558
+ sql`delete from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${where} returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}`
2546
2559
  )).rows;
2547
- if (!row) throw new (0, _chunk75O3WQKRcjs.HttpError)(404, `${this.name} not found`);
2560
+ if (!row) throw new (0, _chunk66R7S7J3cjs.HttpError)(404, `${this.name} not found`);
2548
2561
  return this.project(this.fromRaw(t, row), this.projection(args));
2549
2562
  });
2550
2563
  }
@@ -2552,7 +2565,7 @@ var TableRuntime = (_class = class {
2552
2565
  const { t, sql } = await this.ready(args["where"]);
2553
2566
  return this.tbl.guard(async () => {
2554
2567
  const where = _nullishCoalesce(this.where(sql, t, args["where"]), () => ( sql`true`));
2555
- const result = await this.tbl.client().execute(sql`delete from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} where ${where}`);
2568
+ const result = await this.tbl.client().execute(sql`delete from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${where}`);
2556
2569
  return { count: _nullishCoalesce(result.rowCount, () => ( 0)) };
2557
2570
  });
2558
2571
  }
@@ -2561,10 +2574,10 @@ function relArgs(arg) {
2561
2574
  return isPlainObject(arg) ? arg : {};
2562
2575
  }
2563
2576
  function runtimeOf(name, from) {
2564
- const runtime = _optionalChain([_chunk75O3WQKRcjs.getRegisteredModel.call(void 0, name), 'optionalAccess', _58 => _58.tableRuntime, 'optionalCall', _59 => _59()]);
2577
+ const runtime = _optionalChain([_chunk66R7S7J3cjs.getRegisteredModel.call(void 0, name), 'optionalAccess', _65 => _65.tableRuntime, 'optionalCall', _66 => _66()]);
2565
2578
  if (!runtime) {
2566
2579
  throw new Error(
2567
- _chunk75O3WQKRcjs.getRegisteredModel.call(void 0, name) ? `[EFC] ${from}: include needs ${name} to be a defineTable model` : `[EFC] ${from}: "${name}" is not defined \u2014 import that model before including it`
2580
+ _chunk66R7S7J3cjs.getRegisteredModel.call(void 0, name) ? `[EFC] ${from}: include needs ${name} to be a defineTable model` : `[EFC] ${from}: "${name}" is not defined \u2014 import that model before including it`
2568
2581
  );
2569
2582
  }
2570
2583
  return runtime;
@@ -2584,7 +2597,7 @@ var JSON_OPS = /* @__PURE__ */ new Set([
2584
2597
  "mode"
2585
2598
  ]);
2586
2599
  function createTable(name, schema, options = {}) {
2587
- _chunk75O3WQKRcjs.normalizeSchema.call(void 0, schema, "table", name);
2600
+ _chunk66R7S7J3cjs.normalizeSchema.call(void 0, schema, "table", name);
2588
2601
  for (const [rel, def] of Object.entries(_nullishCoalesce(options.relations, () => ( {})))) {
2589
2602
  const where = `[EFC] ${name}.relations.${rel}`;
2590
2603
  if (rel in schema) throw new Error(`${where}: a field already has this name`);
@@ -2599,7 +2612,7 @@ function createTable(name, schema, options = {}) {
2599
2612
  }
2600
2613
  let runtime;
2601
2614
  const rt = () => {
2602
- const engine = _chunk75O3WQKRcjs.getDbEngine.call(void 0, );
2615
+ const engine = _chunk66R7S7J3cjs.getDbEngine.call(void 0, );
2603
2616
  if (engine !== "postgresql") {
2604
2617
  throw new Error(
2605
2618
  `[EFC] ${name} is a PostgreSQL table (defineTable) but the app is connected to MongoDB \u2014 check DATABASE_URL / config.database, or use defineModel for a model that runs on both`
@@ -2619,24 +2632,24 @@ function createTable(name, schema, options = {}) {
2619
2632
  aggregate: (args) => call((r) => r.aggregate(args)),
2620
2633
  groupBy: (args) => call((r) => r.groupBy(args)),
2621
2634
  create: (args) => call((r) => r.withInclude(args, (a) => r.createNested(a))),
2622
- createMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _60 => _60["data"]]), "createMany"), r.createMany(args, false))),
2623
- createManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _61 => _61["data"]]), "createMany"), r.createMany(args, true))),
2635
+ createMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _67 => _67["data"]]), "createMany"), r.createMany(args, false))),
2636
+ createManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _68 => _68["data"]]), "createMany"), r.createMany(args, true))),
2624
2637
  update: (args) => call((r) => r.withInclude(args, (a) => r.updateNested(a))),
2625
- updateMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _62 => _62["data"]]), "updateMany"), r.updateMany(args, false))),
2626
- updateManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _63 => _63["data"]]), "updateMany"), r.updateMany(args, true))),
2638
+ updateMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _69 => _69["data"]]), "updateMany"), r.updateMany(args, false))),
2639
+ updateManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _70 => _70["data"]]), "updateMany"), r.updateMany(args, true))),
2627
2640
  upsert: (args) => call((r) => r.withInclude(args, (a) => r.upsertNested(a))),
2628
2641
  delete: (args) => call((r) => r.deleteWithInclude(args)),
2629
2642
  deleteMany: (args) => call((r) => r.deleteMany(args)),
2630
2643
  raw: () => call(async (r) => (await r.tbl.compile()).t),
2631
- sync: (opts) => call((r) => r.tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _64 => _64.dryRun]), () => ( false)))),
2644
+ sync: (opts) => call((r) => r.tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _71 => _71.dryRun]), () => ( false)))),
2632
2645
  drop: () => call((r) => r.tbl.drop())
2633
2646
  };
2634
- _chunkMGH4VDV3cjs.traceOps.call(void 0,
2647
+ _chunkVQSWSYK6cjs.traceOps.call(void 0,
2635
2648
  name,
2636
2649
  model,
2637
2650
  Object.keys(model).filter((op) => !["name", "raw", "sync", "drop"].includes(op))
2638
2651
  );
2639
- _chunk75O3WQKRcjs.registerModel.call(void 0, {
2652
+ _chunk66R7S7J3cjs.registerModel.call(void 0, {
2640
2653
  name,
2641
2654
  sync: model.sync,
2642
2655
  plan: (opts) => call((r) => r.tbl.plan(opts)),
@@ -2683,4 +2696,4 @@ var db = new Proxy({}, {
2683
2696
 
2684
2697
 
2685
2698
  exports.connectMongo = connectMongo; exports.defineModel = defineModel; exports.transaction = transaction; exports.defineTable = defineTable; exports.setDbClient = setDbClient; exports.getDbClient = getDbClient; exports.db = db;
2686
- //# sourceMappingURL=chunk-FQFKHPLR.cjs.map
2699
+ //# sourceMappingURL=chunk-RGTENTDN.cjs.map