express-file-cluster 0.9.0 → 0.9.1

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/dist/auth/index.d.cts +1 -1
  2. package/dist/auth/index.d.ts +1 -1
  3. package/dist/{chunk-2PBMLMO4.js → chunk-QKQZF573.js} +26 -4
  4. package/dist/chunk-QKQZF573.js.map +1 -0
  5. package/dist/{chunk-6QNLN6AI.js → chunk-RRQ2RK5M.js} +353 -3
  6. package/dist/chunk-RRQ2RK5M.js.map +1 -0
  7. package/dist/{chunk-RGTENTDN.cjs → chunk-RTF7PHS2.cjs} +432 -82
  8. package/dist/chunk-RTF7PHS2.cjs.map +1 -0
  9. package/dist/{chunk-66R7S7J3.cjs → chunk-X2US4RAM.cjs} +26 -4
  10. package/dist/chunk-X2US4RAM.cjs.map +1 -0
  11. package/dist/cli/db-runner.cjs +17 -17
  12. package/dist/cli/db-runner.js +2 -2
  13. package/dist/cli/index.cjs +363 -26
  14. package/dist/cli/index.cjs.map +1 -1
  15. package/dist/cli/index.js +343 -6
  16. package/dist/cli/index.js.map +1 -1
  17. package/dist/docs/api-reference/collection.md +155 -0
  18. package/dist/docs/cli/add.md +35 -6
  19. package/dist/docs/guides/authentication.md +50 -0
  20. package/dist/docs/guides/coming-from-mongoose.md +60 -0
  21. package/dist/docs/guides/which-api.md +21 -12
  22. package/dist/docs/index.md +3 -1
  23. package/dist/docs/skills/SKILL.md +2 -2
  24. package/dist/docs/skills/api-surface.md +8 -0
  25. package/dist/docs/skills/what-not-to-invent.md +3 -2
  26. package/dist/index.cjs +11 -9
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +193 -3
  29. package/dist/index.d.ts +193 -3
  30. package/dist/index.js +4 -2
  31. package/dist/index.js.map +1 -1
  32. package/dist/registry/index.json +1 -1
  33. package/dist/tasks/index.d.cts +1 -1
  34. package/dist/tasks/index.d.ts +1 -1
  35. package/dist/{types-gyvA7BtO.d.cts → types-BY-ObnZH.d.cts} +36 -7
  36. package/dist/{types-gyvA7BtO.d.ts → types-BY-ObnZH.d.ts} +36 -7
  37. package/package.json +1 -1
  38. package/dist/chunk-2PBMLMO4.js.map +0 -1
  39. package/dist/chunk-66R7S7J3.cjs.map +0 -1
  40. package/dist/chunk-6QNLN6AI.js.map +0 -1
  41. package/dist/chunk-RGTENTDN.cjs.map +0 -1
@@ -18,7 +18,7 @@
18
18
 
19
19
 
20
20
 
21
- var _chunk66R7S7J3cjs = require('./chunk-66R7S7J3.cjs');
21
+ var _chunkX2US4RAMcjs = require('./chunk-X2US4RAM.cjs');
22
22
 
23
23
 
24
24
 
@@ -55,6 +55,29 @@ function ctor(type, mg) {
55
55
  return Date;
56
56
  case "objectId":
57
57
  return mg.Schema.Types.ObjectId;
58
+ // defineCollection only:
59
+ case "decimal128":
60
+ return mg.Schema.Types.Decimal128;
61
+ case "long":
62
+ return BigInt;
63
+ // stored as a BSON Long (int64)
64
+ case "binary":
65
+ return Buffer;
66
+ case "geoPoint":
67
+ return new mg.Schema(
68
+ {
69
+ type: { type: String, enum: ["Point"], required: true },
70
+ coordinates: {
71
+ type: [Number],
72
+ required: true,
73
+ validate: {
74
+ validator: (c) => c.length === 2 && Math.abs(c[0]) <= 180 && Math.abs(c[1]) <= 90,
75
+ message: "must be [longitude, latitude]"
76
+ }
77
+ }
78
+ },
79
+ { _id: false }
80
+ );
58
81
  }
59
82
  return mg.Schema.Types.Mixed;
60
83
  }
@@ -65,7 +88,7 @@ function rules(node, mg) {
65
88
  if (d.unique !== void 0) entry["unique"] = d.unique;
66
89
  if (d.index !== void 0) entry["index"] = d.index;
67
90
  if (d.default !== void 0)
68
- entry["default"] = _chunk66R7S7J3cjs.resolveDefault.call(void 0, d.default, () => new mg.Types.ObjectId());
91
+ entry["default"] = _chunkX2US4RAMcjs.resolveDefault.call(void 0, d.default, () => new mg.Types.ObjectId());
69
92
  if (d.enum !== void 0) entry["enum"] = d.enum;
70
93
  if (d.min !== void 0) entry["min"] = d.min;
71
94
  if (d.max !== void 0) entry["max"] = d.max;
@@ -139,7 +162,7 @@ function normalise(value) {
139
162
  function translateError(model, err) {
140
163
  const e = err;
141
164
  if (_optionalChain([e, 'optionalAccess', _ => _.name]) === "ValidationError" && e.errors) {
142
- throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(
165
+ throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(
143
166
  model,
144
167
  Object.entries(e.errors).map(([path, v]) => ({
145
168
  path,
@@ -151,13 +174,13 @@ function translateError(model, err) {
151
174
  );
152
175
  }
153
176
  if (_optionalChain([e, 'optionalAccess', _2 => _2.name]) === "CastError") {
154
- throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(model, [
177
+ throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(model, [
155
178
  { path: _nullishCoalesce(e.path, () => ( "")), message: _nullishCoalesce(e.message, () => ( "invalid value")) }
156
179
  ]);
157
180
  }
158
181
  if (_optionalChain([e, 'optionalAccess', _3 => _3.code]) === 11e3) {
159
182
  const field = _nullishCoalesce(Object.keys(_nullishCoalesce(e.keyValue, () => ( {})))[0], () => ( "field"));
160
- throw new (0, _chunk66R7S7J3cjs.HttpError)(409, `${model} with this ${field} already exists`);
183
+ throw new (0, _chunkX2US4RAMcjs.HttpError)(409, `${model} with this ${field} already exists`);
161
184
  }
162
185
  throw err;
163
186
  }
@@ -189,8 +212,8 @@ function mongoModel(name, tree, options) {
189
212
  const schema = new mg.Schema(buildTree(tree, mg), {
190
213
  timestamps: _nullishCoalesce(options.timestamps, () => ( true)),
191
214
  // autoSync: false hands collection and index creation to migrations, on MongoDB too.
192
- autoIndex: _chunk66R7S7J3cjs.isAutoSync.call(void 0, ),
193
- autoCreate: _chunk66R7S7J3cjs.isAutoSync.call(void 0, ),
215
+ autoIndex: _chunkX2US4RAMcjs.isAutoSync.call(void 0, ),
216
+ autoCreate: _chunkX2US4RAMcjs.isAutoSync.call(void 0, ),
194
217
  ...options.collection !== void 0 && { collection: options.collection }
195
218
  });
196
219
  for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
@@ -199,10 +222,13 @@ function mongoModel(name, tree, options) {
199
222
  ...idx.expireAfterSeconds !== void 0 && {
200
223
  expireAfterSeconds: idx.expireAfterSeconds
201
224
  },
202
- ...idx.name !== void 0 && { name: idx.name }
225
+ ...idx.name !== void 0 && { name: idx.name },
226
+ ...idx.partialFilterExpression !== void 0 && {
227
+ partialFilterExpression: idx.partialFilterExpression
228
+ }
203
229
  });
204
230
  }
205
- const sequences = _chunk66R7S7J3cjs.sequenceFields.call(void 0, name, tree);
231
+ const sequences = _chunkX2US4RAMcjs.sequenceFields.call(void 0, name, tree);
206
232
  if (sequences.length > 0) {
207
233
  schema.pre("validate", async function() {
208
234
  if (!this.isNew) return;
@@ -212,7 +238,7 @@ function mongoModel(name, tree, options) {
212
238
  });
213
239
  }
214
240
  const M = mg.model(name, schema);
215
- if (_chunk66R7S7J3cjs.isAutoSync.call(void 0, )) {
241
+ if (_chunkX2US4RAMcjs.isAutoSync.call(void 0, )) {
216
242
  await M.init().catch((err) => {
217
243
  _chunkYL37D6KMcjs.getLogger.call(void 0, ).warn(
218
244
  { model: name, err: err.message },
@@ -224,7 +250,7 @@ function mongoModel(name, tree, options) {
224
250
  })
225
251
  );
226
252
  const session = () => {
227
- const tx = _chunk66R7S7J3cjs.currentTx.call(void 0, );
253
+ const tx = _chunkX2US4RAMcjs.currentTx.call(void 0, );
228
254
  return _optionalChain([tx, 'optionalAccess', _5 => _5.engine]) === "mongodb" ? { session: tx.session } : {};
229
255
  };
230
256
  const applyQueryOptions = (q2, opts) => {
@@ -358,7 +384,7 @@ function mongoModel(name, tree, options) {
358
384
  }),
359
385
  raw: () => model(),
360
386
  async sync(opts) {
361
- if (_chunk66R7S7J3cjs.isSyncSuppressed.call(void 0, )) return [];
387
+ if (_chunkX2US4RAMcjs.isSyncSuppressed.call(void 0, )) return [];
362
388
  const M = await model();
363
389
  const changes = [];
364
390
  const exists = (await M.db.db.listCollections({ name: M.collection.collectionName }).toArray()).length > 0;
@@ -460,7 +486,7 @@ async function connectMongo(url, pool = {}) {
460
486
 
461
487
  // src/db/pg-model.ts
462
488
  function pgModel(name, tree, options) {
463
- const tbl = _chunk66R7S7J3cjs.pgTable.call(void 0, name, tree, options, { native: false, api: "defineModel" });
489
+ const tbl = _chunkX2US4RAMcjs.pgTable.call(void 0, name, tree, options, { native: false, api: "defineModel" });
464
490
  const { columns, ts, refs, ready, compile, client, columnFor, toDb, fromRow, validate, guard } = tbl;
465
491
  const kindOf = (field) => _optionalChain([columns, 'access', _15 => _15.get, 'call', _16 => _16(field), 'optionalAccess', _17 => _17.kind]);
466
492
  function missingField(sql, cond) {
@@ -560,7 +586,7 @@ function pgModel(name, tree, options) {
560
586
  break;
561
587
  }
562
588
  default:
563
- throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(name, [
589
+ throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(name, [
564
590
  { path, message: `operator ${op} is not supported on PostgreSQL` }
565
591
  ]);
566
592
  }
@@ -591,8 +617,8 @@ function pgModel(name, tree, options) {
591
617
  for (const path of Array.isArray(paths) ? paths : [paths]) {
592
618
  const ref = refs.get(path);
593
619
  if (!ref)
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);
620
+ throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(name, [{ path, message: "is not a populatable ref field" }]);
621
+ const target = _chunkX2US4RAMcjs.getRegisteredModel.call(void 0, ref.model);
596
622
  if (!target) throw new Error(`[EFC] populate: model "${ref.model}" is not defined`);
597
623
  const ids = [
598
624
  ...new Set(
@@ -635,7 +661,7 @@ function pgModel(name, tree, options) {
635
661
  return populate(rows, _optionalChain([opts, 'optionalAccess', _22 => _22.populate]));
636
662
  }
637
663
  const strictUpdate = (update) => {
638
- const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || _chunk66R7S7J3cjs.nodeAt.call(void 0, tree, path.split(".")) !== void 0);
664
+ const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || _chunkX2US4RAMcjs.nodeAt.call(void 0, tree, path.split(".")) !== void 0);
639
665
  const out = {};
640
666
  for (const [k, v] of Object.entries(update)) {
641
667
  if (k.startsWith("$") && v !== null && typeof v === "object") {
@@ -650,7 +676,7 @@ function pgModel(name, tree, options) {
650
676
  const ops = update;
651
677
  for (const op of Object.keys(update).filter((k) => k.startsWith("$"))) {
652
678
  if (!["$set", "$unset", "$inc", "$push", "$pull"].includes(op)) {
653
- throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(name, [
679
+ throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(name, [
654
680
  { path: op, message: "update operator is not supported on PostgreSQL" }
655
681
  ]);
656
682
  }
@@ -663,25 +689,25 @@ function pgModel(name, tree, options) {
663
689
  for (const [k, v] of Object.entries($set)) if (!k.includes(".")) topLevel[k] = v;
664
690
  for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) if (!k.includes(".")) topLevel[k] = null;
665
691
  for (const [k, v] of Object.entries($set))
666
- if (k.includes(".")) await _chunk66R7S7J3cjs.validateAtPath.call(void 0, tree, k, v, issues);
692
+ if (k.includes(".")) await _chunkX2US4RAMcjs.validateAtPath.call(void 0, tree, k, v, issues);
667
693
  for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) {
668
- if (k.includes(".")) await _chunk66R7S7J3cjs.validateAtPath.call(void 0, tree, k, null, issues);
694
+ if (k.includes(".")) await _chunkX2US4RAMcjs.validateAtPath.call(void 0, tree, k, null, issues);
669
695
  }
670
696
  for (const [k, by] of Object.entries(_nullishCoalesce(ops["$inc"], () => ( {})))) {
671
697
  if (typeof by !== "number") issues.push({ path: k, message: "$inc needs a number" });
672
- const node = k.includes(".") ? _chunk66R7S7J3cjs.nodeAt.call(void 0, tree, k.split(".")) : tree[k];
698
+ const node = k.includes(".") ? _chunkX2US4RAMcjs.nodeAt.call(void 0, tree, k.split(".")) : tree[k];
673
699
  if (node && !(node.kind === "scalar" && node.type === "number") && node.kind !== "json") {
674
700
  issues.push({ path: k, message: "$inc only applies to number fields" });
675
701
  }
676
702
  }
677
- if (issues.length) throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(name, issues);
703
+ if (issues.length) throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(name, issues);
678
704
  await validate(topLevel, true);
679
705
  const set = {};
680
706
  const nested = /* @__PURE__ */ new Map();
681
707
  const touchedTop = /* @__PURE__ */ new Set();
682
708
  const acc = (field) => _nullishCoalesce(nested.get(field), () => ( columnFor(t, field)));
683
709
  const conflict = (path) => {
684
- throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(name, [{ path, message: "conflicting update paths" }]);
710
+ throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(name, [{ path, message: "conflicting update paths" }]);
685
711
  };
686
712
  const top = (field, value) => {
687
713
  if (touchedTop.has(field) || nested.has(field)) conflict(field);
@@ -852,7 +878,7 @@ function defineModel(name, schema, options) {
852
878
  return createModel(name, schema, _nullishCoalesce(options, () => ( {})));
853
879
  }
854
880
  function distinctFields(tree, options) {
855
- const ts = _chunk66R7S7J3cjs.timestampFields.call(void 0, options);
881
+ const ts = _chunkX2US4RAMcjs.timestampFields.call(void 0, options);
856
882
  const fields = /* @__PURE__ */ new Set(["id", ...Object.values(ts)]);
857
883
  for (const [key, node] of Object.entries(tree)) if (node.kind === "scalar") fields.add(key);
858
884
  return fields;
@@ -877,11 +903,11 @@ var MODEL_OPS = [
877
903
  ];
878
904
  var sortKey = (v) => v instanceof Date ? v.getTime() : v;
879
905
  function createModel(name, schema, options, native) {
880
- const tree = _chunk66R7S7J3cjs.normalizeSchema.call(void 0, schema, "model", name);
906
+ const tree = _chunkX2US4RAMcjs.normalizeSchema.call(void 0, schema, "model", name);
881
907
  let engineModel;
882
908
  const impl = () => {
883
909
  if (engineModel) return engineModel;
884
- const engine = _chunk66R7S7J3cjs.getDbEngine.call(void 0, );
910
+ const engine = _chunkX2US4RAMcjs.getDbEngine.call(void 0, );
885
911
  if (native && native.engine !== engine) {
886
912
  throw new Error(
887
913
  `[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`
@@ -923,7 +949,7 @@ function createModel(name, schema, options, native) {
923
949
  try {
924
950
  return await m.create(create);
925
951
  } catch (err) {
926
- if (_chunk66R7S7J3cjs.isHttpError.call(void 0, err) && err.statusCode === 409 && !_chunk66R7S7J3cjs.currentTx.call(void 0, )) {
952
+ if (_chunkX2US4RAMcjs.isHttpError.call(void 0, err) && err.statusCode === 409 && !_chunkX2US4RAMcjs.currentTx.call(void 0, )) {
927
953
  const retried = await m.updateOne(filter, update);
928
954
  if (retried) return retried;
929
955
  }
@@ -940,25 +966,25 @@ function createModel(name, schema, options, native) {
940
966
  drop: () => call((m) => m.drop())
941
967
  };
942
968
  _chunkVQSWSYK6cjs.traceOps.call(void 0, name, model, MODEL_OPS);
943
- _chunk66R7S7J3cjs.registerModel.call(void 0, {
969
+ _chunkX2US4RAMcjs.registerModel.call(void 0, {
944
970
  name,
945
971
  sync: model.sync,
946
972
  plan: (opts) => call((m) => m.plan(opts)),
947
973
  drop: model.drop,
948
974
  findByIds: (ids) => model.find({ id: { $in: ids } }),
949
- pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => ( _chunk66R7S7J3cjs.tableNameFor.call(void 0, name))), idKind: "uuid" })
975
+ pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => ( _chunkX2US4RAMcjs.tableNameFor.call(void 0, name))), idKind: "uuid" })
950
976
  });
951
977
  return model;
952
978
  }
953
979
 
954
980
  // src/db/transaction.ts
955
981
  async function transaction(fn) {
956
- if (_chunk66R7S7J3cjs.currentTx.call(void 0, )) return fn();
957
- if (_chunk66R7S7J3cjs.getDbEngine.call(void 0, ) === "postgresql") {
982
+ if (_chunkX2US4RAMcjs.currentTx.call(void 0, )) return fn();
983
+ if (_chunkX2US4RAMcjs.getDbEngine.call(void 0, ) === "postgresql") {
958
984
  let result;
959
985
  const afterCommit = [];
960
986
  await _chunkVQSWSYK6cjs.getOrm.call(void 0, ).transaction(async (tx) => {
961
- result = await _chunk66R7S7J3cjs.runInTx.call(void 0, { engine: "postgresql", tx, afterCommit }, fn);
987
+ result = await _chunkX2US4RAMcjs.runInTx.call(void 0, { engine: "postgresql", tx, afterCommit }, fn);
962
988
  });
963
989
  for (const run of afterCommit) run();
964
990
  return result;
@@ -968,7 +994,7 @@ async function transaction(fn) {
968
994
  try {
969
995
  let result;
970
996
  await session.withTransaction(async () => {
971
- result = await _chunk66R7S7J3cjs.runInTx.call(void 0, { engine: "mongodb", session }, fn);
997
+ result = await _chunkX2US4RAMcjs.runInTx.call(void 0, { engine: "mongodb", session }, fn);
972
998
  });
973
999
  return result;
974
1000
  } finally {
@@ -1014,8 +1040,8 @@ var TableRuntime = (_class = class {
1014
1040
  constructor(name, schema, options) {;_class.prototype.__init.call(this);
1015
1041
  this.name = name;
1016
1042
  this.options = options;
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" });
1043
+ const tree = _chunkX2US4RAMcjs.normalizeSchema.call(void 0, schema, "table", name);
1044
+ this.tbl = _chunkX2US4RAMcjs.pgTable.call(void 0, name, tree, options, { native: true, api: "defineTable" });
1019
1045
  this.uniqueSets = [["id"]];
1020
1046
  for (const spec of this.tbl.columns.values()) {
1021
1047
  if (_optionalChain([spec, 'access', _25 => _25.node, 'optionalAccess', _26 => _26.def, 'access', _27 => _27.unique])) this.uniqueSets.push([spec.field]);
@@ -1042,7 +1068,7 @@ var TableRuntime = (_class = class {
1042
1068
  /** Many-to-many fields as list columns, so filters and projections treat them alike. */
1043
1069
  __init() {this.joinSpecs = /* @__PURE__ */ new Map()}
1044
1070
  fail(path, message) {
1045
- throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(this.name, [{ path, message }]);
1071
+ throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(this.name, [{ path, message }]);
1046
1072
  }
1047
1073
  spec(field) {
1048
1074
  return _nullishCoalesce(this.tbl.columns.get(field), () => ( this.joinSpecs.get(field)));
@@ -1053,18 +1079,18 @@ var TableRuntime = (_class = class {
1053
1079
  /** A many-to-many field's ids, in order, for the row `owner` (a table name or alias). */
1054
1080
  joinExpr(sql, join, owner) {
1055
1081
  return sql.raw(
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})`
1082
+ `coalesce((select array_agg(efc_j.ref_id order by efc_j.position) from ${_chunkX2US4RAMcjs.q.call(void 0, join.table)} efc_j where efc_j.owner_id = ${owner}.${_chunkX2US4RAMcjs.q.call(void 0, "id")}), '{}'::${join.ddl})`
1057
1083
  );
1058
1084
  }
1059
1085
  col(sql, field, alias) {
1060
1086
  const join = this.join(field);
1061
- if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => ( _chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))));
1087
+ if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => ( _chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))));
1062
1088
  const spec = this.spec(field);
1063
- return sql.raw(alias ? `${alias}.${_chunk66R7S7J3cjs.q.call(void 0, spec.column)}` : _chunk66R7S7J3cjs.q.call(void 0, spec.column));
1089
+ return sql.raw(alias ? `${alias}.${_chunkX2US4RAMcjs.q.call(void 0, spec.column)}` : _chunkX2US4RAMcjs.q.call(void 0, spec.column));
1064
1090
  }
1065
1091
  /** SELECT items for the many-to-many fields among `fields`, as text arrays. */
1066
1092
  joinColumns(sql, fields, owner) {
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)))}`);
1093
+ return fields.filter((f) => this.join(f)).map((f) => sql`${this.col(sql, f, owner)}::text[] as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, relAlias(f)))}`);
1068
1094
  }
1069
1095
  /** `col` for SELECT lists: many-to-many fields come back as text arrays under an alias. */
1070
1096
  selectCols(sql, fields, owner) {
@@ -1356,7 +1382,7 @@ var TableRuntime = (_class = class {
1356
1382
  if (args["cursor"]) {
1357
1383
  this.uniqueKey(args["cursor"], "cursor");
1358
1384
  const cw = this.where(sql, t, args["cursor"]);
1359
- const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${cw})`;
1385
+ const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${cw})`;
1360
1386
  const ors = [];
1361
1387
  const same = (o) => sql`${this.col(sql, o.field)} is not distinct from ${at(o.field)}`;
1362
1388
  for (let i = 0; i < order.length; i++) {
@@ -1369,7 +1395,7 @@ var TableRuntime = (_class = class {
1369
1395
  ors.push(eqs.length ? sql`(${sql.join([...eqs, after], sql` and `)})` : after);
1370
1396
  }
1371
1397
  ors.push(sql`(${sql.join(order.map(same), sql` and `)})`);
1372
- parts.push(sql`exists (select 1 from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${cw})`);
1398
+ parts.push(sql`exists (select 1 from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${cw})`);
1373
1399
  parts.push(sql`(${sql.join(ors, sql` or `)})`);
1374
1400
  }
1375
1401
  return parts.length ? sql.join(parts, sql` and `) : sql`true`;
@@ -1394,7 +1420,7 @@ var TableRuntime = (_class = class {
1394
1420
  const offset = args["skip"] ? sql` offset ${sql.param(args["skip"])}` : sql``;
1395
1421
  const orderBy = order.length ? sql` order by ${this.orderSql(sql, order)}` : sql``;
1396
1422
  const where = this.readWhere(sql, t, args, order);
1397
- const from = sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table));
1423
+ const from = sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table));
1398
1424
  const distinct = _optionalChain([args, 'access', _29 => _29["distinct"], 'optionalAccess', _30 => _30.filter, 'call', _31 => _31((f) => this.spec(f))]);
1399
1425
  if (_optionalChain([distinct, 'optionalAccess', _32 => _32.length])) {
1400
1426
  const dcols = sql.join(
@@ -1424,7 +1450,7 @@ var TableRuntime = (_class = class {
1424
1450
  distinct ? "efc_distinct" : void 0
1425
1451
  );
1426
1452
  const include = this.includeArg(args);
1427
- const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : _chunk66R7S7J3cjs.q.call(void 0, this.tbl.table), 1) : [];
1453
+ const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : _chunkX2US4RAMcjs.q.call(void 0, this.tbl.table), 1) : [];
1428
1454
  const { query, reversed } = this.readQuery(
1429
1455
  sql,
1430
1456
  t,
@@ -1499,7 +1525,7 @@ var TableRuntime = (_class = class {
1499
1525
  for (const [name, arg] of Object.entries(include)) {
1500
1526
  if (!arg) continue;
1501
1527
  const expr = await this.relationExpr(sql, this.relation(name), relArgs(arg), owner, depth);
1502
- out.push(sql`${expr} as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, incAlias(name)))}`);
1528
+ out.push(sql`${expr} as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, incAlias(name)))}`);
1503
1529
  }
1504
1530
  return out;
1505
1531
  }
@@ -1533,21 +1559,21 @@ var TableRuntime = (_class = class {
1533
1559
  */
1534
1560
  relationSource(rel, owner, a, j) {
1535
1561
  const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
1536
- const target = `${_chunk66R7S7J3cjs.q.call(void 0, T.tbl.table)} ${a}`;
1537
- const ownerId = `${owner}.${_chunk66R7S7J3cjs.q.call(void 0, "id")}`;
1562
+ const target = `${_chunkX2US4RAMcjs.q.call(void 0, T.tbl.table)} ${a}`;
1563
+ const ownerId = `${owner}.${_chunkX2US4RAMcjs.q.call(void 0, "id")}`;
1538
1564
  if (rel.via === "fk") {
1539
1565
  return {
1540
1566
  T,
1541
1567
  from: target,
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")}`
1568
+ cond: `${a}.${_chunkX2US4RAMcjs.q.call(void 0, "id")} = ${owner}.${_chunkX2US4RAMcjs.q.call(void 0, rel.column)}`,
1569
+ defaultOrder: `${a}.${_chunkX2US4RAMcjs.q.call(void 0, "id")}`
1544
1570
  };
1545
1571
  }
1546
1572
  let from;
1547
1573
  let cond;
1548
1574
  let defaultOrder;
1549
1575
  if (rel.via === "join") {
1550
- from = `${_chunk66R7S7J3cjs.q.call(void 0, rel.join.table)} ${j} join ${target} on ${a}.${_chunk66R7S7J3cjs.q.call(void 0, "id")} = ${j}.ref_id`;
1576
+ from = `${_chunkX2US4RAMcjs.q.call(void 0, rel.join.table)} ${j} join ${target} on ${a}.${_chunkX2US4RAMcjs.q.call(void 0, "id")} = ${j}.ref_id`;
1551
1577
  cond = `${j}.owner_id = ${ownerId}`;
1552
1578
  defaultOrder = `${j}.position`;
1553
1579
  } else {
@@ -1565,7 +1591,7 @@ var TableRuntime = (_class = class {
1565
1591
  `[EFC] ${this.name}.${rel.name}: ${rel.target}.${rel.foreignKey} is many-to-many \u2014 use hasMany`
1566
1592
  );
1567
1593
  }
1568
- from = `${_chunk66R7S7J3cjs.q.call(void 0, join.table)} ${j} join ${target} on ${a}.${_chunk66R7S7J3cjs.q.call(void 0, "id")} = ${j}.owner_id`;
1594
+ from = `${_chunkX2US4RAMcjs.q.call(void 0, join.table)} ${j} join ${target} on ${a}.${_chunkX2US4RAMcjs.q.call(void 0, "id")} = ${j}.owner_id`;
1569
1595
  cond = `${j}.ref_id = ${ownerId}`;
1570
1596
  } else {
1571
1597
  if (rel.kind === "one" && !column.node.def.unique) {
@@ -1574,9 +1600,9 @@ var TableRuntime = (_class = class {
1574
1600
  );
1575
1601
  }
1576
1602
  from = target;
1577
- cond = `${a}.${_chunk66R7S7J3cjs.q.call(void 0, column.column)} = ${ownerId}`;
1603
+ cond = `${a}.${_chunkX2US4RAMcjs.q.call(void 0, column.column)} = ${ownerId}`;
1578
1604
  }
1579
- defaultOrder = `${a}.${_chunk66R7S7J3cjs.q.call(void 0, "id")}`;
1605
+ defaultOrder = `${a}.${_chunkX2US4RAMcjs.q.call(void 0, "id")}`;
1580
1606
  }
1581
1607
  return { T, from, cond, defaultOrder };
1582
1608
  }
@@ -1601,7 +1627,7 @@ var TableRuntime = (_class = class {
1601
1627
  const where = isPlainObject(w) ? w : { id: w };
1602
1628
  const found = await T.findUnique({ where, select: { id: true } });
1603
1629
  if (!found) {
1604
- throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(this.name, [
1630
+ throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(this.name, [
1605
1631
  { path, message: `no ${rel.target} matches ${JSON.stringify(where, idJson)}` }
1606
1632
  ]);
1607
1633
  }
@@ -1693,8 +1719,8 @@ var TableRuntime = (_class = class {
1693
1719
  try {
1694
1720
  await T.updateNested({ where: whereOf(w), data: { [fk]: owner } });
1695
1721
  } catch (err) {
1696
- if (_chunk66R7S7J3cjs.isHttpError.call(void 0, err) && err.statusCode === 404) {
1697
- throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(this.name, [
1722
+ if (_chunkX2US4RAMcjs.isHttpError.call(void 0, err) && err.statusCode === 404) {
1723
+ throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(this.name, [
1698
1724
  {
1699
1725
  path: key,
1700
1726
  message: `no ${rel.target} matches ${JSON.stringify(whereOf(w), idJson)}`
@@ -1845,7 +1871,7 @@ var TableRuntime = (_class = class {
1845
1871
  const a = `efc_f${++aliasSeq}`;
1846
1872
  const { T, from, cond } = this.relationSource(
1847
1873
  rel,
1848
- _nullishCoalesce(owner, () => ( _chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))),
1874
+ _nullishCoalesce(owner, () => ( _chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))),
1849
1875
  a,
1850
1876
  `efc_fj${aliasSeq}`
1851
1877
  );
@@ -1986,7 +2012,7 @@ var TableRuntime = (_class = class {
1986
2012
  }
1987
2013
  async orThrow(p) {
1988
2014
  const r = await p;
1989
- if (r === null) throw new (0, _chunk66R7S7J3cjs.HttpError)(404, `${this.name} not found`);
2015
+ if (r === null) throw new (0, _chunkX2US4RAMcjs.HttpError)(404, `${this.name} not found`);
1990
2016
  return r;
1991
2017
  }
1992
2018
  async count(args = {}) {
@@ -1996,7 +2022,7 @@ var TableRuntime = (_class = class {
1996
2022
  const counted = select ? Object.entries(select).filter(([f, on]) => on && (f === "_all" || this.spec(f))) : [["_all", true]];
1997
2023
  const exprs = sql.join(
1998
2024
  counted.map(
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))}`
2025
+ ([f]) => f === "_all" ? sql`count(*)::int as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, "_all"))}` : sql`count(${this.col(sql, f, "efc_rows")})::int as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, f))}`
2000
2026
  ),
2001
2027
  sql`, `
2002
2028
  );
@@ -2071,7 +2097,7 @@ var TableRuntime = (_class = class {
2071
2097
  const specs = this.aggregateSpec(args);
2072
2098
  if (specs.length === 0) return {};
2073
2099
  const exprs = sql.join(
2074
- specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, s.alias))}`),
2100
+ specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, s.alias))}`),
2075
2101
  sql`, `
2076
2102
  );
2077
2103
  const { query } = this.readQuery(sql, t, { ...args, select: void 0 }, sql`*`);
@@ -2129,7 +2155,7 @@ var TableRuntime = (_class = class {
2129
2155
  [
2130
2156
  ...by.map((f) => this.col(sql, f)),
2131
2157
  ...specs.map(
2132
- (s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, s.alias))}`
2158
+ (s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, s.alias))}`
2133
2159
  )
2134
2160
  ],
2135
2161
  sql`, `
@@ -2153,7 +2179,7 @@ var TableRuntime = (_class = class {
2153
2179
  }
2154
2180
  }
2155
2181
  }
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(
2182
+ const query = sql`select ${select} from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))}${where ? sql` where ${where}` : sql``} group by ${sql.join(
2157
2183
  by.map((f) => this.col(sql, f)),
2158
2184
  sql`, `
2159
2185
  )}${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``}`;
@@ -2231,7 +2257,7 @@ var TableRuntime = (_class = class {
2231
2257
  }
2232
2258
  }
2233
2259
  }
2234
- if (issues.length) throw new (0, _chunk66R7S7J3cjs.ModelValidationError)(this.name, issues);
2260
+ if (issues.length) throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(this.name, issues);
2235
2261
  await this.tbl.validate(plain, true);
2236
2262
  for (const [field, v] of Object.entries(plain)) {
2237
2263
  sets.push(
@@ -2273,7 +2299,7 @@ var TableRuntime = (_class = class {
2273
2299
  }
2274
2300
  for (const [field, entries] of byField) {
2275
2301
  const join = this.join(field);
2276
- const jt = sql.raw(_chunk66R7S7J3cjs.q.call(void 0, join.table));
2302
+ const jt = sql.raw(_chunkX2US4RAMcjs.q.call(void 0, join.table));
2277
2303
  const sets = entries.filter((e) => e.op.mode === "set");
2278
2304
  if (sets.length) {
2279
2305
  const owners2 = sets.map((e) => idText(e.id));
@@ -2320,7 +2346,7 @@ var TableRuntime = (_class = class {
2320
2346
  const idDdl = this.tbl.columns.get("id").ddl;
2321
2347
  const owners = sql`${sql.param(ids.map(idText))}::${sql.raw(idDdl)}[]`;
2322
2348
  const parts = joins.map(
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`
2349
+ (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(_chunkX2US4RAMcjs.q.call(void 0, j.table))} where owner_id = any(${owners}) group by owner_id`
2324
2350
  );
2325
2351
  const { rows } = await this.exec(sql.join(parts, sql` union all `));
2326
2352
  for (const j of joins) out.set(j.field, /* @__PURE__ */ new Map());
@@ -2342,7 +2368,7 @@ var TableRuntime = (_class = class {
2342
2368
  }
2343
2369
  insertSql(sql, t, rows) {
2344
2370
  const fields = [...new Set(rows.flatMap((r) => Object.keys(r)))];
2345
- const head = sql`insert into ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} (${sql.join(
2371
+ const head = sql`insert into ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} (${sql.join(
2346
2372
  fields.map((f) => this.col(sql, f)),
2347
2373
  sql`, `
2348
2374
  )})`;
@@ -2439,7 +2465,7 @@ var TableRuntime = (_class = class {
2439
2465
  return;
2440
2466
  }
2441
2467
  const { rows: ids } = await this.exec(
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)})`
2468
+ sql`select nextval(pg_get_serial_sequence(${sql.param(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))}, 'id'))::text as id from generate_series(1, ${sql.param(missing.length)})`
2443
2469
  );
2444
2470
  missing.forEach((r, i) => {
2445
2471
  const id = ids[i]["id"];
@@ -2468,9 +2494,9 @@ var TableRuntime = (_class = class {
2468
2494
  const where = this.where(sql, t, args["where"]);
2469
2495
  const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
2470
2496
  const extra = links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``;
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`;
2497
+ const query = sets.length ? sql`update ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *${extra}` : sql`select *${extra} from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${where} limit 1`;
2472
2498
  const [row] = (await this.exec(query)).rows;
2473
- if (!row) throw new (0, _chunk66R7S7J3cjs.HttpError)(404, `${this.name} not found`);
2499
+ if (!row) throw new (0, _chunkX2US4RAMcjs.HttpError)(404, `${this.name} not found`);
2474
2500
  const record = this.fromRaw(t, row);
2475
2501
  await this.applyJoins(sql, [{ id: record["id"], ops: joinOps }]);
2476
2502
  await this.refreshJoins(sql, [record], joinOps);
@@ -2491,7 +2517,7 @@ var TableRuntime = (_class = class {
2491
2517
  const links = returning ? this.joinColumns(sql, [...this.tbl.joins.keys()]) : [];
2492
2518
  const list = returning ? sql` returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : joinOps.length ? sql` returning ${this.col(sql, "id")}` : sql``;
2493
2519
  const result = await this.exec(
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}`
2520
+ sets.length ? sql`update ${sql.raw(_chunkX2US4RAMcjs.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(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${where}`
2495
2521
  );
2496
2522
  const records = result.rows.map((r) => returning ? this.fromRaw(t, r) : r);
2497
2523
  await this.applyJoins(
@@ -2515,7 +2541,7 @@ var TableRuntime = (_class = class {
2515
2541
  if (row[f] === void 0) row[f] = this.tbl.toDb(f, args["where"][f]);
2516
2542
  }
2517
2543
  const { head, values } = this.insertSql(sql, t, [row]);
2518
- const table = _chunk66R7S7J3cjs.q.call(void 0, this.tbl.table);
2544
+ const table = _chunkX2US4RAMcjs.q.call(void 0, this.tbl.table);
2519
2545
  const update = await this.setList(sql, t, _nullishCoalesce(args["update"], () => ( {})), table);
2520
2546
  const { joinOps } = update;
2521
2547
  let { sets } = update;
@@ -2536,7 +2562,7 @@ var TableRuntime = (_class = class {
2536
2562
  const [out] = (await this.exec(
2537
2563
  sql`${head} values ${values} on conflict (${target}) do update set ${sql.join(sets, sql`, `)}${cond}${returning}`
2538
2564
  )).rows;
2539
- if (!out) throw new (0, _chunk66R7S7J3cjs.HttpError)(404, `${this.name} not found`);
2565
+ if (!out) throw new (0, _chunkX2US4RAMcjs.HttpError)(404, `${this.name} not found`);
2540
2566
  const record = this.fromRaw(t, out);
2541
2567
  if (linked) {
2542
2568
  const ops = out["efc_inserted"] ? createOps.filter((o) => o.items.length) : joinOps;
@@ -2555,9 +2581,9 @@ var TableRuntime = (_class = class {
2555
2581
  const where = this.where(sql, t, args["where"]);
2556
2582
  const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
2557
2583
  const [row] = (await this.exec(
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``}`
2584
+ sql`delete from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${where} returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}`
2559
2585
  )).rows;
2560
- if (!row) throw new (0, _chunk66R7S7J3cjs.HttpError)(404, `${this.name} not found`);
2586
+ if (!row) throw new (0, _chunkX2US4RAMcjs.HttpError)(404, `${this.name} not found`);
2561
2587
  return this.project(this.fromRaw(t, row), this.projection(args));
2562
2588
  });
2563
2589
  }
@@ -2565,7 +2591,7 @@ var TableRuntime = (_class = class {
2565
2591
  const { t, sql } = await this.ready(args["where"]);
2566
2592
  return this.tbl.guard(async () => {
2567
2593
  const where = _nullishCoalesce(this.where(sql, t, args["where"]), () => ( sql`true`));
2568
- const result = await this.tbl.client().execute(sql`delete from ${sql.raw(_chunk66R7S7J3cjs.q.call(void 0, this.tbl.table))} where ${where}`);
2594
+ const result = await this.tbl.client().execute(sql`delete from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${where}`);
2569
2595
  return { count: _nullishCoalesce(result.rowCount, () => ( 0)) };
2570
2596
  });
2571
2597
  }
@@ -2574,10 +2600,10 @@ function relArgs(arg) {
2574
2600
  return isPlainObject(arg) ? arg : {};
2575
2601
  }
2576
2602
  function runtimeOf(name, from) {
2577
- const runtime = _optionalChain([_chunk66R7S7J3cjs.getRegisteredModel.call(void 0, name), 'optionalAccess', _65 => _65.tableRuntime, 'optionalCall', _66 => _66()]);
2603
+ const runtime = _optionalChain([_chunkX2US4RAMcjs.getRegisteredModel.call(void 0, name), 'optionalAccess', _65 => _65.tableRuntime, 'optionalCall', _66 => _66()]);
2578
2604
  if (!runtime) {
2579
2605
  throw new Error(
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`
2606
+ _chunkX2US4RAMcjs.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`
2581
2607
  );
2582
2608
  }
2583
2609
  return runtime;
@@ -2597,7 +2623,7 @@ var JSON_OPS = /* @__PURE__ */ new Set([
2597
2623
  "mode"
2598
2624
  ]);
2599
2625
  function createTable(name, schema, options = {}) {
2600
- _chunk66R7S7J3cjs.normalizeSchema.call(void 0, schema, "table", name);
2626
+ _chunkX2US4RAMcjs.normalizeSchema.call(void 0, schema, "table", name);
2601
2627
  for (const [rel, def] of Object.entries(_nullishCoalesce(options.relations, () => ( {})))) {
2602
2628
  const where = `[EFC] ${name}.relations.${rel}`;
2603
2629
  if (rel in schema) throw new Error(`${where}: a field already has this name`);
@@ -2612,7 +2638,7 @@ function createTable(name, schema, options = {}) {
2612
2638
  }
2613
2639
  let runtime;
2614
2640
  const rt = () => {
2615
- const engine = _chunk66R7S7J3cjs.getDbEngine.call(void 0, );
2641
+ const engine = _chunkX2US4RAMcjs.getDbEngine.call(void 0, );
2616
2642
  if (engine !== "postgresql") {
2617
2643
  throw new Error(
2618
2644
  `[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`
@@ -2649,7 +2675,7 @@ function createTable(name, schema, options = {}) {
2649
2675
  model,
2650
2676
  Object.keys(model).filter((op) => !["name", "raw", "sync", "drop"].includes(op))
2651
2677
  );
2652
- _chunk66R7S7J3cjs.registerModel.call(void 0, {
2678
+ _chunkX2US4RAMcjs.registerModel.call(void 0, {
2653
2679
  name,
2654
2680
  sync: model.sync,
2655
2681
  plan: (opts) => call((r) => r.tbl.plan(opts)),
@@ -2664,6 +2690,329 @@ function defineTable(name, schema, options) {
2664
2690
  return createTable(name, schema, _nullishCoalesce(options, () => ( {})));
2665
2691
  }
2666
2692
 
2693
+ // src/db/collection-model.ts
2694
+ function fromBson(value) {
2695
+ if (Array.isArray(value)) return value.map(fromBson);
2696
+ if (value == null || typeof value !== "object") return value;
2697
+ switch (value._bsontype) {
2698
+ case "Decimal128":
2699
+ return String(value);
2700
+ case "Long":
2701
+ return BigInt(String(value));
2702
+ case "Binary":
2703
+ return Buffer.from(value.buffer);
2704
+ case void 0:
2705
+ break;
2706
+ default:
2707
+ return value;
2708
+ }
2709
+ if (Object.getPrototypeOf(value) !== Object.prototype) return value;
2710
+ const out = {};
2711
+ for (const [k, v] of Object.entries(value)) out[k] = fromBson(v);
2712
+ return out;
2713
+ }
2714
+ function castLongs(value, node) {
2715
+ if (value == null) return value;
2716
+ if (node.kind === "scalar") {
2717
+ return node.type === "long" && typeof value === "number" ? BigInt(value) : value;
2718
+ }
2719
+ if (node.kind === "array" && Array.isArray(value))
2720
+ return value.map((v) => castLongs(v, node.item));
2721
+ if (node.kind === "object" && typeof value === "object") {
2722
+ castTree(value, node.fields);
2723
+ }
2724
+ return value;
2725
+ }
2726
+ function castTree(doc, tree) {
2727
+ for (const [key, node] of Object.entries(tree)) {
2728
+ if (key in doc) doc[key] = castLongs(doc[key], node);
2729
+ }
2730
+ return doc;
2731
+ }
2732
+ function hasLong(tree) {
2733
+ const walk = (n) => n.kind === "scalar" ? n.type === "long" : n.kind === "array" ? walk(n.item) : n.kind === "object" ? hasLong(n.fields) : false;
2734
+ return Object.values(tree).some(walk);
2735
+ }
2736
+ function writeResult(r) {
2737
+ return {
2738
+ matchedCount: _nullishCoalesce(r.matchedCount, () => ( 0)),
2739
+ modifiedCount: _nullishCoalesce(r.modifiedCount, () => ( 0)),
2740
+ upsertedCount: _nullishCoalesce(r.upsertedCount, () => ( 0)),
2741
+ upsertedId: r.upsertedId == null ? null : String(r.upsertedId)
2742
+ };
2743
+ }
2744
+ function mapBulkOp(op) {
2745
+ const [kind, body] = _nullishCoalesce(Object.entries(op)[0], () => ( []));
2746
+ if (!kind || body == null || typeof body !== "object") return op;
2747
+ const b = { ...body };
2748
+ if (b["filter"]) b["filter"] = mapFilter(b["filter"]);
2749
+ return { [kind]: b };
2750
+ }
2751
+ function createCollection(name, schema, options) {
2752
+ const tree = _chunkX2US4RAMcjs.normalizeSchema.call(void 0, schema, "collection", name);
2753
+ const base = mongoModel(name, tree, options);
2754
+ const longs = hasLong(tree);
2755
+ const toRecord = (doc) => {
2756
+ if (doc == null) return null;
2757
+ const rec = normalise(fromBson(doc));
2758
+ return longs ? castTree(rec, tree) : rec;
2759
+ };
2760
+ const model = async () => {
2761
+ const engine = _chunkX2US4RAMcjs.getDbEngine.call(void 0, );
2762
+ if (engine !== "mongodb") {
2763
+ throw new Error(
2764
+ `[EFC] ${name} is a MongoDB collection (defineCollection) but the app is connected to PostgreSQL \u2014 check DATABASE_URL / config.database, or use defineModel for a model that runs on both`
2765
+ );
2766
+ }
2767
+ return await base.raw();
2768
+ };
2769
+ const session = () => {
2770
+ const tx = _chunkX2US4RAMcjs.currentTx.call(void 0, );
2771
+ return _optionalChain([tx, 'optionalAccess', _72 => _72.engine]) === "mongodb" ? tx.session : null;
2772
+ };
2773
+ const sess = () => {
2774
+ const s = session();
2775
+ return s ? { session: s } : {};
2776
+ };
2777
+ const guard = async (fn) => {
2778
+ const M = await model();
2779
+ try {
2780
+ return await fn(M);
2781
+ } catch (err) {
2782
+ return translateError(name, err);
2783
+ }
2784
+ };
2785
+ const findOpts = (q2, opts) => {
2786
+ if (_optionalChain([opts, 'optionalAccess', _73 => _73.projection])) q2.select(opts.projection);
2787
+ if (_optionalChain([opts, 'optionalAccess', _74 => _74.sort])) {
2788
+ const meta = Object.values(opts.sort).some((v) => typeof v === "object");
2789
+ q2.sort(meta ? opts.sort : mapSort(opts.sort));
2790
+ }
2791
+ if (_optionalChain([opts, 'optionalAccess', _75 => _75.skip]) !== void 0) q2.skip(opts.skip);
2792
+ if (_optionalChain([opts, 'optionalAccess', _76 => _76.limit]) !== void 0) q2.limit(opts.limit);
2793
+ if (_optionalChain([opts, 'optionalAccess', _77 => _77.populate])) q2.populate(opts.populate);
2794
+ const collation = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _78 => _78.collation]), () => ( options.collation));
2795
+ if (collation) q2.collation(collation);
2796
+ q2.session(session());
2797
+ return q2;
2798
+ };
2799
+ const isBadId = (err) => {
2800
+ const e = err;
2801
+ return _optionalChain([e, 'optionalAccess', _79 => _79.name]) === "CastError" && e.path === "_id";
2802
+ };
2803
+ const model$ = {
2804
+ name,
2805
+ find: (filter, opts) => guard(async (M) => {
2806
+ const docs = await findOpts(M.find(mapFilter(filter)), opts).lean();
2807
+ return docs.map(toRecord);
2808
+ }),
2809
+ findOne: (filter, opts) => guard(async (M) => toRecord(await findOpts(M.findOne(mapFilter(filter)), opts).lean())),
2810
+ findById: (id, opts) => guard(async (M) => {
2811
+ try {
2812
+ return toRecord(await findOpts(M.findById(id), opts).lean());
2813
+ } catch (err) {
2814
+ if (isBadId(err)) return null;
2815
+ throw err;
2816
+ }
2817
+ }),
2818
+ exists: (filter) => guard(async (M) => await M.exists(mapFilter(filter)).session(session()) !== null),
2819
+ countDocuments: (filter) => guard((M) => M.countDocuments(mapFilter(filter)).session(session()).exec()),
2820
+ estimatedDocumentCount: () => guard((M) => M.estimatedDocumentCount().exec()),
2821
+ distinct: (field, filter) => guard(async (M) => {
2822
+ const values = await M.distinct(field === "id" ? "_id" : field, mapFilter(filter)).session(
2823
+ session()
2824
+ );
2825
+ return values.map(
2826
+ (v) => v != null && v._bsontype === "ObjectId" ? String(v) : fromBson(v)
2827
+ );
2828
+ }),
2829
+ create: (data) => guard(async (M) => {
2830
+ const [doc] = await M.create([data], sess());
2831
+ return toRecord(doc.toObject({ flattenMaps: true }));
2832
+ }),
2833
+ insertMany: (data) => guard(async (M) => {
2834
+ if (data.length === 0) return [];
2835
+ const docs = await M.create(data, { ...sess(), ordered: true });
2836
+ return docs.map((d) => toRecord(d.toObject({ flattenMaps: true })));
2837
+ }),
2838
+ updateOne: (filter, update, opts) => guard(
2839
+ async (M) => writeResult(
2840
+ await M.updateOne(mapFilter(filter), update, {
2841
+ runValidators: true,
2842
+ upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _80 => _80.upsert]), () => ( false)),
2843
+ ...sess()
2844
+ })
2845
+ )
2846
+ ),
2847
+ updateMany: (filter, update, opts) => guard(
2848
+ async (M) => writeResult(
2849
+ await M.updateMany(mapFilter(filter), update, {
2850
+ runValidators: true,
2851
+ upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _81 => _81.upsert]), () => ( false)),
2852
+ ...sess()
2853
+ })
2854
+ )
2855
+ ),
2856
+ replaceOne: (filter, replacement, opts) => guard(
2857
+ async (M) => writeResult(
2858
+ await M.replaceOne(mapFilter(filter), replacement, {
2859
+ runValidators: true,
2860
+ upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _82 => _82.upsert]), () => ( false)),
2861
+ ...sess()
2862
+ })
2863
+ )
2864
+ ),
2865
+ findOneAndUpdate: (filter, update, opts) => guard(
2866
+ async (M) => toRecord(
2867
+ await M.findOneAndUpdate(mapFilter(filter), update, {
2868
+ runValidators: true,
2869
+ upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _83 => _83.upsert]), () => ( false)),
2870
+ returnDocument: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _84 => _84.returnDocument]), () => ( "before")),
2871
+ ..._optionalChain([opts, 'optionalAccess', _85 => _85.projection]) && { projection: opts.projection },
2872
+ ..._optionalChain([opts, 'optionalAccess', _86 => _86.sort]) && { sort: opts.sort },
2873
+ ...sess()
2874
+ }).lean()
2875
+ )
2876
+ ),
2877
+ findByIdAndUpdate: (id, update, opts) => guard(async (M) => {
2878
+ try {
2879
+ return toRecord(
2880
+ await M.findByIdAndUpdate(id, update, {
2881
+ runValidators: true,
2882
+ returnDocument: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _87 => _87.returnDocument]), () => ( "before")),
2883
+ ...sess()
2884
+ }).lean()
2885
+ );
2886
+ } catch (err) {
2887
+ if (isBadId(err)) return null;
2888
+ throw err;
2889
+ }
2890
+ }),
2891
+ findOneAndDelete: (filter, opts) => guard(
2892
+ async (M) => toRecord(
2893
+ await M.findOneAndDelete(mapFilter(filter), {
2894
+ ..._optionalChain([opts, 'optionalAccess', _88 => _88.sort]) && { sort: opts.sort },
2895
+ ...sess()
2896
+ }).lean()
2897
+ )
2898
+ ),
2899
+ findByIdAndDelete: (id) => guard(async (M) => {
2900
+ try {
2901
+ return toRecord(await M.findByIdAndDelete(id, sess()).lean());
2902
+ } catch (err) {
2903
+ if (isBadId(err)) return null;
2904
+ throw err;
2905
+ }
2906
+ }),
2907
+ deleteOne: (filter) => guard(async (M) => ({
2908
+ deletedCount: (await M.deleteOne(mapFilter(filter), sess())).deletedCount
2909
+ })),
2910
+ deleteMany: (filter) => guard(async (M) => ({
2911
+ deletedCount: (await M.deleteMany(mapFilter(filter), sess())).deletedCount
2912
+ })),
2913
+ aggregate: (pipeline) => guard(async (M) => {
2914
+ const agg = M.aggregate(pipeline);
2915
+ const s = session();
2916
+ if (s) agg.session(s);
2917
+ if (options.collation)
2918
+ agg.collation(options.collation);
2919
+ return (await agg).map(toRecord);
2920
+ }),
2921
+ bulkWrite: (ops, opts) => guard(async (M) => {
2922
+ if (ops.length === 0) {
2923
+ return {
2924
+ insertedCount: 0,
2925
+ matchedCount: 0,
2926
+ modifiedCount: 0,
2927
+ deletedCount: 0,
2928
+ upsertedCount: 0
2929
+ };
2930
+ }
2931
+ const r = await M.bulkWrite(
2932
+ ops.map(mapBulkOp),
2933
+ {
2934
+ ordered: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _89 => _89.ordered]), () => ( true)),
2935
+ runValidators: true,
2936
+ ...sess()
2937
+ }
2938
+ );
2939
+ return {
2940
+ insertedCount: r.insertedCount,
2941
+ matchedCount: r.matchedCount,
2942
+ modifiedCount: r.modifiedCount,
2943
+ deletedCount: r.deletedCount,
2944
+ upsertedCount: r.upsertedCount
2945
+ };
2946
+ }),
2947
+ watch: (pipeline = [], opts) => {
2948
+ let stream;
2949
+ let closed = false;
2950
+ const open = async () => {
2951
+ const M = await model();
2952
+ stream ??= M.watch(pipeline, {
2953
+ ..._optionalChain([opts, 'optionalAccess', _90 => _90.fullDocument]) && { fullDocument: opts.fullDocument }
2954
+ });
2955
+ return stream;
2956
+ };
2957
+ const close = async () => {
2958
+ closed = true;
2959
+ await _optionalChain([stream, 'optionalAccess', _91 => _91.close, 'call', _92 => _92()]);
2960
+ };
2961
+ return {
2962
+ close,
2963
+ async *[Symbol.asyncIterator]() {
2964
+ const s = await open();
2965
+ try {
2966
+ while (!closed) {
2967
+ const change = await s.next().catch((err) => {
2968
+ if (closed) return null;
2969
+ throw err;
2970
+ });
2971
+ if (!change) return;
2972
+ const key = change["documentKey"];
2973
+ yield {
2974
+ operationType: String(change["operationType"]),
2975
+ id: _optionalChain([key, 'optionalAccess', _93 => _93._id]) == null ? void 0 : String(key._id),
2976
+ ...change["fullDocument"] != null && {
2977
+ fullDocument: toRecord(change["fullDocument"])
2978
+ },
2979
+ ...change["updateDescription"] != null && {
2980
+ updateDescription: fromBson(change["updateDescription"])
2981
+ },
2982
+ raw: change
2983
+ };
2984
+ }
2985
+ } finally {
2986
+ await close();
2987
+ }
2988
+ }
2989
+ };
2990
+ },
2991
+ raw: () => model(),
2992
+ sync: (opts) => model().then(() => base.sync(opts)),
2993
+ drop: () => model().then(() => base.drop())
2994
+ };
2995
+ _chunkVQSWSYK6cjs.traceOps.call(void 0,
2996
+ name,
2997
+ model$,
2998
+ Object.keys(model$).filter((op) => !["name", "raw", "sync", "drop", "watch"].includes(op))
2999
+ );
3000
+ _chunkX2US4RAMcjs.registerModel.call(void 0, {
3001
+ name,
3002
+ sync: model$.sync,
3003
+ plan: (opts) => model().then(() => base.plan(opts)),
3004
+ drop: model$.drop,
3005
+ findByIds: (ids) => model$.find({ _id: { $in: ids } }),
3006
+ pgTarget: () => {
3007
+ throw new Error(`[EFC] ${name} is a MongoDB collection (defineCollection)`);
3008
+ }
3009
+ });
3010
+ return model$;
3011
+ }
3012
+ function defineCollection(name, schema, options) {
3013
+ return createCollection(name, schema, _nullishCoalesce(options, () => ( {})));
3014
+ }
3015
+
2667
3016
  // src/db/index.ts
2668
3017
  var _client = null;
2669
3018
  function setDbClient(client) {
@@ -2695,5 +3044,6 @@ var db = new Proxy({}, {
2695
3044
 
2696
3045
 
2697
3046
 
2698
- exports.connectMongo = connectMongo; exports.defineModel = defineModel; exports.transaction = transaction; exports.defineTable = defineTable; exports.setDbClient = setDbClient; exports.getDbClient = getDbClient; exports.db = db;
2699
- //# sourceMappingURL=chunk-RGTENTDN.cjs.map
3047
+
3048
+ exports.connectMongo = connectMongo; exports.defineModel = defineModel; exports.transaction = transaction; exports.defineTable = defineTable; exports.defineCollection = defineCollection; exports.setDbClient = setDbClient; exports.getDbClient = getDbClient; exports.db = db;
3049
+ //# sourceMappingURL=chunk-RTF7PHS2.cjs.map