express-file-cluster 0.9.3 → 0.10.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 (220) hide show
  1. package/dist/auth/index.cjs +6 -7
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +7 -2
  4. package/dist/auth/index.d.ts +7 -2
  5. package/dist/auth/index.js +5 -6
  6. package/dist/{chunk-QL6EWT4B.cjs → chunk-4DOHQU6I.cjs} +9 -7
  7. package/dist/chunk-4DOHQU6I.cjs.map +1 -0
  8. package/dist/chunk-73XJUT2S.js +366 -0
  9. package/dist/chunk-73XJUT2S.js.map +1 -0
  10. package/dist/{chunk-ATL4GYFU.js → chunk-7KC2H76D.js} +50 -8
  11. package/dist/chunk-7KC2H76D.js.map +1 -0
  12. package/dist/{chunk-TYR2GZZE.cjs → chunk-7KO4DJRJ.cjs} +19 -14
  13. package/dist/chunk-7KO4DJRJ.cjs.map +1 -0
  14. package/dist/{chunk-UBQYQPBU.js → chunk-ATVD2HGC.js} +4 -4
  15. package/dist/{chunk-R34R7QPD.cjs → chunk-DCJOWFVD.cjs} +3 -3
  16. package/dist/{chunk-R34R7QPD.cjs.map → chunk-DCJOWFVD.cjs.map} +1 -1
  17. package/dist/chunk-DUADUR6R.cjs +366 -0
  18. package/dist/chunk-DUADUR6R.cjs.map +1 -0
  19. package/dist/{chunk-BBSZLGZW.js → chunk-EGSSZUVO.js} +8 -6
  20. package/dist/chunk-EGSSZUVO.js.map +1 -0
  21. package/dist/{chunk-TI24L4XE.cjs → chunk-GBI77W5T.cjs} +6 -2
  22. package/dist/chunk-GBI77W5T.cjs.map +1 -0
  23. package/dist/{chunk-RTF7PHS2.cjs → chunk-HBCY7ILD.cjs} +306 -119
  24. package/dist/chunk-HBCY7ILD.cjs.map +1 -0
  25. package/dist/{chunk-ANUSWEAP.cjs → chunk-KFVFP2Q7.cjs} +59 -17
  26. package/dist/chunk-KFVFP2Q7.cjs.map +1 -0
  27. package/dist/{chunk-RS4MXCPW.js → chunk-NI2BNGGV.js} +2 -2
  28. package/dist/{chunk-X2US4RAM.cjs → chunk-NKLOE4AK.cjs} +11 -13
  29. package/dist/chunk-NKLOE4AK.cjs.map +1 -0
  30. package/dist/{chunk-RRQ2RK5M.js → chunk-PGJQK36V.js} +195 -8
  31. package/dist/chunk-PGJQK36V.js.map +1 -0
  32. package/dist/{chunk-QKQZF573.js → chunk-QDEDOHP7.js} +4 -6
  33. package/dist/chunk-QDEDOHP7.js.map +1 -0
  34. package/dist/{chunk-UTM4PEVG.js → chunk-R4XO4SVM.js} +10 -5
  35. package/dist/chunk-R4XO4SVM.js.map +1 -0
  36. package/dist/chunk-R52CUEGT.js +74 -0
  37. package/dist/chunk-R52CUEGT.js.map +1 -0
  38. package/dist/{chunk-HBYSKULC.js → chunk-RAB44UGX.js} +5 -1
  39. package/dist/chunk-RAB44UGX.js.map +1 -0
  40. package/dist/{chunk-7YEX4MQV.cjs → chunk-WBLUGOAG.cjs} +42 -6
  41. package/dist/chunk-WBLUGOAG.cjs.map +1 -0
  42. package/dist/{chunk-T4OHFU5T.cjs → chunk-YK4ZM3CA.cjs} +15 -15
  43. package/dist/{chunk-T4OHFU5T.cjs.map → chunk-YK4ZM3CA.cjs.map} +1 -1
  44. package/dist/cli/db-runner.cjs +2012 -120
  45. package/dist/cli/db-runner.cjs.map +1 -1
  46. package/dist/cli/db-runner.js +1989 -97
  47. package/dist/cli/db-runner.js.map +1 -1
  48. package/dist/cli/index.cjs +101 -43
  49. package/dist/cli/index.cjs.map +1 -1
  50. package/dist/cli/index.js +80 -22
  51. package/dist/cli/index.js.map +1 -1
  52. package/dist/docs/api-reference/auth.md +10 -8
  53. package/dist/docs/api-reference/collection.md +44 -1
  54. package/dist/docs/api-reference/ignite.md +22 -3
  55. package/dist/docs/api-reference/types.md +99 -0
  56. package/dist/docs/cli/add.md +1 -1
  57. package/dist/docs/cli/db.md +2 -2
  58. package/dist/docs/contributing/index.md +1 -1
  59. package/dist/docs/core-concepts/background-tasks.md +6 -3
  60. package/dist/docs/getting-started/index.md +3 -2
  61. package/dist/docs/guides/authentication.md +34 -24
  62. package/dist/docs/guides/caching.md +32 -1
  63. package/dist/docs/guides/database.md +14 -0
  64. package/dist/docs/guides/feature-matrix.md +58 -0
  65. package/dist/docs/guides/migrations.md +23 -2
  66. package/dist/docs/guides/oauth.md +15 -1
  67. package/dist/docs/guides/which-api.md +2 -2
  68. package/dist/docs/index.md +4 -1
  69. package/dist/docs/skills/SKILL.md +2 -2
  70. package/dist/docs/skills/api-surface.md +10 -4
  71. package/dist/docs/skills/auth-internals.md +3 -3
  72. package/dist/docs/skills/tasks-internals.md +4 -3
  73. package/dist/docs/skills/what-not-to-invent.md +4 -3
  74. package/dist/docs/versioning.md +42 -0
  75. package/dist/index.cjs +144 -51
  76. package/dist/index.cjs.map +1 -1
  77. package/dist/index.d.cts +204 -3
  78. package/dist/index.d.ts +204 -3
  79. package/dist/index.js +107 -14
  80. package/dist/index.js.map +1 -1
  81. package/dist/pgboss-backend-FW42SBSM.js +14 -0
  82. package/dist/pgboss-backend-RVHUBJTU.cjs +14 -0
  83. package/dist/{pgboss-backend-TCHI7CHM.cjs.map → pgboss-backend-RVHUBJTU.cjs.map} +1 -1
  84. package/dist/registry/index.json +34 -3
  85. package/dist/registry/js-mongo/account-security.json +1 -1
  86. package/dist/registry/js-mongo/admin-users.json +1 -1
  87. package/dist/registry/js-mongo/auth.json +1 -1
  88. package/dist/registry/js-mongo/auth@apple.json +1 -1
  89. package/dist/registry/js-mongo/auth@google.json +1 -1
  90. package/dist/registry/js-mongo/email-verification.json +1 -1
  91. package/dist/registry/js-mongo/forgot-password.json +1 -1
  92. package/dist/registry/js-mongo/user-profile.json +1 -1
  93. package/dist/registry/js-mongo-collection/_base.json +1 -0
  94. package/dist/registry/js-mongo-collection/account-security.json +1 -0
  95. package/dist/registry/js-mongo-collection/account-settings.json +1 -0
  96. package/dist/registry/js-mongo-collection/admin-admins.json +1 -0
  97. package/dist/registry/js-mongo-collection/admin-analytics.json +1 -0
  98. package/dist/registry/js-mongo-collection/admin-billing.json +1 -0
  99. package/dist/registry/js-mongo-collection/admin-content.json +1 -0
  100. package/dist/registry/js-mongo-collection/admin-logs.json +1 -0
  101. package/dist/registry/js-mongo-collection/admin-support.json +1 -0
  102. package/dist/registry/js-mongo-collection/admin-system.json +1 -0
  103. package/dist/registry/js-mongo-collection/admin-users.json +1 -0
  104. package/dist/registry/js-mongo-collection/admin.json +1 -0
  105. package/dist/registry/js-mongo-collection/auth.json +1 -0
  106. package/dist/registry/js-mongo-collection/auth@apple.json +1 -0
  107. package/dist/registry/js-mongo-collection/auth@google.json +1 -0
  108. package/dist/registry/js-mongo-collection/billing.json +1 -0
  109. package/dist/registry/js-mongo-collection/email-client.json +1 -0
  110. package/dist/registry/js-mongo-collection/email-verification.json +1 -0
  111. package/dist/registry/js-mongo-collection/files.json +1 -0
  112. package/dist/registry/js-mongo-collection/forgot-password.json +1 -0
  113. package/dist/registry/js-mongo-collection/notifications.json +1 -0
  114. package/dist/registry/js-mongo-collection/support.json +1 -0
  115. package/dist/registry/js-mongo-collection/user-profile.json +1 -0
  116. package/dist/registry/js-pg-model/account-security.json +1 -1
  117. package/dist/registry/js-pg-model/admin-users.json +1 -1
  118. package/dist/registry/js-pg-model/auth.json +1 -1
  119. package/dist/registry/js-pg-model/auth@apple.json +1 -1
  120. package/dist/registry/js-pg-model/auth@google.json +1 -1
  121. package/dist/registry/js-pg-model/email-verification.json +1 -1
  122. package/dist/registry/js-pg-model/forgot-password.json +1 -1
  123. package/dist/registry/js-pg-model/user-profile.json +1 -1
  124. package/dist/registry/js-pg-table/account-security.json +1 -1
  125. package/dist/registry/js-pg-table/admin-users.json +1 -1
  126. package/dist/registry/js-pg-table/auth.json +1 -1
  127. package/dist/registry/js-pg-table/auth@apple.json +1 -1
  128. package/dist/registry/js-pg-table/auth@google.json +1 -1
  129. package/dist/registry/js-pg-table/email-verification.json +1 -1
  130. package/dist/registry/js-pg-table/forgot-password.json +1 -1
  131. package/dist/registry/js-pg-table/user-profile.json +1 -1
  132. package/dist/registry/ts-mongo/account-security.json +1 -1
  133. package/dist/registry/ts-mongo/admin-users.json +1 -1
  134. package/dist/registry/ts-mongo/auth.json +1 -1
  135. package/dist/registry/ts-mongo/auth@apple.json +1 -1
  136. package/dist/registry/ts-mongo/auth@google.json +1 -1
  137. package/dist/registry/ts-mongo/email-verification.json +1 -1
  138. package/dist/registry/ts-mongo/forgot-password.json +1 -1
  139. package/dist/registry/ts-mongo/user-profile.json +1 -1
  140. package/dist/registry/ts-mongo-collection/_base.json +1 -0
  141. package/dist/registry/ts-mongo-collection/account-security.json +1 -0
  142. package/dist/registry/ts-mongo-collection/account-settings.json +1 -0
  143. package/dist/registry/ts-mongo-collection/admin-admins.json +1 -0
  144. package/dist/registry/ts-mongo-collection/admin-analytics.json +1 -0
  145. package/dist/registry/ts-mongo-collection/admin-billing.json +1 -0
  146. package/dist/registry/ts-mongo-collection/admin-content.json +1 -0
  147. package/dist/registry/ts-mongo-collection/admin-logs.json +1 -0
  148. package/dist/registry/ts-mongo-collection/admin-support.json +1 -0
  149. package/dist/registry/ts-mongo-collection/admin-system.json +1 -0
  150. package/dist/registry/ts-mongo-collection/admin-users.json +1 -0
  151. package/dist/registry/ts-mongo-collection/admin.json +1 -0
  152. package/dist/registry/ts-mongo-collection/auth.json +1 -0
  153. package/dist/registry/ts-mongo-collection/auth@apple.json +1 -0
  154. package/dist/registry/ts-mongo-collection/auth@google.json +1 -0
  155. package/dist/registry/ts-mongo-collection/billing.json +1 -0
  156. package/dist/registry/ts-mongo-collection/email-client.json +1 -0
  157. package/dist/registry/ts-mongo-collection/email-verification.json +1 -0
  158. package/dist/registry/ts-mongo-collection/files.json +1 -0
  159. package/dist/registry/ts-mongo-collection/forgot-password.json +1 -0
  160. package/dist/registry/ts-mongo-collection/notifications.json +1 -0
  161. package/dist/registry/ts-mongo-collection/support.json +1 -0
  162. package/dist/registry/ts-mongo-collection/user-profile.json +1 -0
  163. package/dist/registry/ts-pg-model/account-security.json +1 -1
  164. package/dist/registry/ts-pg-model/admin-users.json +1 -1
  165. package/dist/registry/ts-pg-model/auth.json +1 -1
  166. package/dist/registry/ts-pg-model/auth@apple.json +1 -1
  167. package/dist/registry/ts-pg-model/auth@google.json +1 -1
  168. package/dist/registry/ts-pg-model/email-verification.json +1 -1
  169. package/dist/registry/ts-pg-model/forgot-password.json +1 -1
  170. package/dist/registry/ts-pg-model/user-profile.json +1 -1
  171. package/dist/registry/ts-pg-table/account-security.json +1 -1
  172. package/dist/registry/ts-pg-table/admin-users.json +1 -1
  173. package/dist/registry/ts-pg-table/auth.json +1 -1
  174. package/dist/registry/ts-pg-table/auth@apple.json +1 -1
  175. package/dist/registry/ts-pg-table/auth@google.json +1 -1
  176. package/dist/registry/ts-pg-table/email-verification.json +1 -1
  177. package/dist/registry/ts-pg-table/forgot-password.json +1 -1
  178. package/dist/registry/ts-pg-table/user-profile.json +1 -1
  179. package/dist/tasks/index.cjs +4 -2
  180. package/dist/tasks/index.cjs.map +1 -1
  181. package/dist/tasks/index.d.cts +4 -2
  182. package/dist/tasks/index.d.ts +4 -2
  183. package/dist/tasks/index.js +3 -1
  184. package/dist/thread-runner.cjs +8 -0
  185. package/dist/thread-runner.cjs.map +1 -0
  186. package/dist/thread-runner.d.cts +3 -0
  187. package/dist/thread-runner.d.ts +3 -0
  188. package/dist/thread-runner.js +8 -0
  189. package/dist/thread-runner.js.map +1 -0
  190. package/dist/{types-BY-ObnZH.d.ts → types-Bnxvj3l0.d.cts} +14 -2
  191. package/dist/{types-BY-ObnZH.d.cts → types-Bnxvj3l0.d.ts} +14 -2
  192. package/package.json +1 -1
  193. package/dist/chunk-277BSYVH.js +0 -127
  194. package/dist/chunk-277BSYVH.js.map +0 -1
  195. package/dist/chunk-7YEX4MQV.cjs.map +0 -1
  196. package/dist/chunk-ANUSWEAP.cjs.map +0 -1
  197. package/dist/chunk-ATL4GYFU.js.map +0 -1
  198. package/dist/chunk-BBSZLGZW.js.map +0 -1
  199. package/dist/chunk-HBYSKULC.js.map +0 -1
  200. package/dist/chunk-HXV543HZ.js +0 -177
  201. package/dist/chunk-HXV543HZ.js.map +0 -1
  202. package/dist/chunk-LJNSJFOL.js +0 -38
  203. package/dist/chunk-LJNSJFOL.js.map +0 -1
  204. package/dist/chunk-QKQZF573.js.map +0 -1
  205. package/dist/chunk-QL6EWT4B.cjs.map +0 -1
  206. package/dist/chunk-RRQ2RK5M.js.map +0 -1
  207. package/dist/chunk-RTF7PHS2.cjs.map +0 -1
  208. package/dist/chunk-TI24L4XE.cjs.map +0 -1
  209. package/dist/chunk-TYR2GZZE.cjs.map +0 -1
  210. package/dist/chunk-UTM4PEVG.js.map +0 -1
  211. package/dist/chunk-VQSWSYK6.cjs +0 -177
  212. package/dist/chunk-VQSWSYK6.cjs.map +0 -1
  213. package/dist/chunk-X2US4RAM.cjs.map +0 -1
  214. package/dist/chunk-YL37D6KM.cjs +0 -127
  215. package/dist/chunk-YL37D6KM.cjs.map +0 -1
  216. package/dist/pgboss-backend-QKBXVJ6B.js +0 -14
  217. package/dist/pgboss-backend-TCHI7CHM.cjs +0 -14
  218. /package/dist/{chunk-UBQYQPBU.js.map → chunk-ATVD2HGC.js.map} +0 -0
  219. /package/dist/{chunk-RS4MXCPW.js.map → chunk-NI2BNGGV.js.map} +0 -0
  220. /package/dist/{pgboss-backend-QKBXVJ6B.js.map → pgboss-backend-FW42SBSM.js.map} +0 -0
@@ -18,7 +18,7 @@
18
18
 
19
19
 
20
20
 
21
- var _chunkX2US4RAMcjs = require('./chunk-X2US4RAM.cjs');
21
+ var _chunkNKLOE4AKcjs = require('./chunk-NKLOE4AK.cjs');
22
22
 
23
23
 
24
24
 
@@ -26,20 +26,18 @@ var _chunkX2US4RAMcjs = require('./chunk-X2US4RAM.cjs');
26
26
 
27
27
 
28
28
 
29
- var _chunkVQSWSYK6cjs = require('./chunk-VQSWSYK6.cjs');
30
29
 
31
-
32
- var _chunkYL37D6KMcjs = require('./chunk-YL37D6KM.cjs');
30
+ var _chunkDUADUR6Rcjs = require('./chunk-DUADUR6R.cjs');
33
31
 
34
32
  // src/db/mongo-model.ts
35
33
  var mongoosePromise;
36
34
  function loadMongoose() {
37
35
  mongoosePromise ??= Promise.resolve().then(() => _interopRequireWildcard(require("mongoose"))).then((mod) => _nullishCoalesce(mod.default, () => ( mod))).then((mg) => {
38
- _chunkVQSWSYK6cjs.whenQueryTracking.call(void 0, () => mg.set("debug", _chunkVQSWSYK6cjs.countStatement));
36
+ _chunkDUADUR6Rcjs.whenQueryTracking.call(void 0, () => mg.set("debug", _chunkDUADUR6Rcjs.countStatement));
39
37
  return mg;
40
38
  }).catch((err) => {
41
39
  mongoosePromise = void 0;
42
- throw _chunkVQSWSYK6cjs.notInstalled.call(void 0, err, "mongoose", "npm install mongoose");
40
+ throw _chunkDUADUR6Rcjs.notInstalled.call(void 0, err, "mongoose", "npm install mongoose");
43
41
  });
44
42
  return mongoosePromise;
45
43
  }
@@ -88,7 +86,7 @@ function rules(node, mg) {
88
86
  if (d.unique !== void 0) entry["unique"] = d.unique;
89
87
  if (d.index !== void 0) entry["index"] = d.index;
90
88
  if (d.default !== void 0)
91
- entry["default"] = _chunkX2US4RAMcjs.resolveDefault.call(void 0, d.default, () => new mg.Types.ObjectId());
89
+ entry["default"] = _chunkNKLOE4AKcjs.resolveDefault.call(void 0, d.default, () => new mg.Types.ObjectId());
92
90
  if (d.enum !== void 0) entry["enum"] = d.enum;
93
91
  if (d.min !== void 0) entry["min"] = d.min;
94
92
  if (d.max !== void 0) entry["max"] = d.max;
@@ -162,7 +160,7 @@ function normalise(value) {
162
160
  function translateError(model, err) {
163
161
  const e = err;
164
162
  if (_optionalChain([e, 'optionalAccess', _ => _.name]) === "ValidationError" && e.errors) {
165
- throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(
163
+ throw new (0, _chunkNKLOE4AKcjs.ModelValidationError)(
166
164
  model,
167
165
  Object.entries(e.errors).map(([path, v]) => ({
168
166
  path,
@@ -174,13 +172,13 @@ function translateError(model, err) {
174
172
  );
175
173
  }
176
174
  if (_optionalChain([e, 'optionalAccess', _2 => _2.name]) === "CastError") {
177
- throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(model, [
175
+ throw new (0, _chunkNKLOE4AKcjs.ModelValidationError)(model, [
178
176
  { path: _nullishCoalesce(e.path, () => ( "")), message: _nullishCoalesce(e.message, () => ( "invalid value")) }
179
177
  ]);
180
178
  }
181
179
  if (_optionalChain([e, 'optionalAccess', _3 => _3.code]) === 11e3) {
182
180
  const field = _nullishCoalesce(Object.keys(_nullishCoalesce(e.keyValue, () => ( {})))[0], () => ( "field"));
183
- throw new (0, _chunkX2US4RAMcjs.HttpError)(409, `${model} with this ${field} already exists`);
181
+ throw new (0, _chunkNKLOE4AKcjs.HttpError)(409, `${model} with this ${field} already exists`);
184
182
  }
185
183
  throw err;
186
184
  }
@@ -206,14 +204,14 @@ function mapSort(sort) {
206
204
  }
207
205
  function mongoModel(name, tree, options) {
208
206
  let compiled;
209
- const model = () => compiled ??= _chunkVQSWSYK6cjs.untracked.call(void 0,
207
+ const model = () => compiled ??= _chunkDUADUR6Rcjs.untracked.call(void 0,
210
208
  () => loadMongoose().then(async (mg) => {
211
209
  if (mg.models[name]) return mg.models[name];
212
210
  const schema = new mg.Schema(buildTree(tree, mg), {
213
211
  timestamps: _nullishCoalesce(options.timestamps, () => ( true)),
214
212
  // autoSync: false hands collection and index creation to migrations, on MongoDB too.
215
- autoIndex: _chunkX2US4RAMcjs.isAutoSync.call(void 0, ),
216
- autoCreate: _chunkX2US4RAMcjs.isAutoSync.call(void 0, ),
213
+ autoIndex: _chunkNKLOE4AKcjs.isAutoSync.call(void 0, ),
214
+ autoCreate: _chunkNKLOE4AKcjs.isAutoSync.call(void 0, ),
217
215
  ...options.collection !== void 0 && { collection: options.collection }
218
216
  });
219
217
  for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
@@ -228,7 +226,7 @@ function mongoModel(name, tree, options) {
228
226
  }
229
227
  });
230
228
  }
231
- const sequences = _chunkX2US4RAMcjs.sequenceFields.call(void 0, name, tree);
229
+ const sequences = _chunkNKLOE4AKcjs.sequenceFields.call(void 0, name, tree);
232
230
  if (sequences.length > 0) {
233
231
  schema.pre("validate", async function() {
234
232
  if (!this.isNew) return;
@@ -238,9 +236,9 @@ function mongoModel(name, tree, options) {
238
236
  });
239
237
  }
240
238
  const M = mg.model(name, schema);
241
- if (_chunkX2US4RAMcjs.isAutoSync.call(void 0, )) {
239
+ if (_chunkNKLOE4AKcjs.isAutoSync.call(void 0, )) {
242
240
  await M.init().catch((err) => {
243
- _chunkYL37D6KMcjs.getLogger.call(void 0, ).warn(
241
+ _chunkDUADUR6Rcjs.getLogger.call(void 0, ).warn(
244
242
  { model: name, err: err.message },
245
243
  `${name}: could not build its indexes \u2014 fix the data, then run efc db sync`
246
244
  );
@@ -250,7 +248,7 @@ function mongoModel(name, tree, options) {
250
248
  })
251
249
  );
252
250
  const session = () => {
253
- const tx = _chunkX2US4RAMcjs.currentTx.call(void 0, );
251
+ const tx = _chunkNKLOE4AKcjs.currentTx.call(void 0, );
254
252
  return _optionalChain([tx, 'optionalAccess', _5 => _5.engine]) === "mongodb" ? { session: tx.session } : {};
255
253
  };
256
254
  const applyQueryOptions = (q2, opts) => {
@@ -384,7 +382,7 @@ function mongoModel(name, tree, options) {
384
382
  }),
385
383
  raw: () => model(),
386
384
  async sync(opts) {
387
- if (_chunkX2US4RAMcjs.isSyncSuppressed.call(void 0, )) return [];
385
+ if (_chunkNKLOE4AKcjs.isSyncSuppressed.call(void 0, )) return [];
388
386
  const M = await model();
389
387
  const changes = [];
390
388
  const exists = (await M.db.db.listCollections({ name: M.collection.collectionName }).toArray()).length > 0;
@@ -479,14 +477,36 @@ async function connectMongo(url, pool = {}) {
479
477
  serverSelectionTimeoutMS: pool.connectionTimeoutMs,
480
478
  waitQueueTimeoutMS: pool.connectionTimeoutMs
481
479
  }
480
+ }).catch((err) => {
481
+ throw explainMongoError(err, url);
482
482
  });
483
- _chunkYL37D6KMcjs.getLogger.call(void 0, ).info("MongoDB connected");
483
+ _chunkDUADUR6Rcjs.getLogger.call(void 0, ).info("MongoDB connected");
484
484
  return mg.connection;
485
485
  }
486
+ function explainMongoError(err, url) {
487
+ const e = err;
488
+ let where = "(unparsable DATABASE_URL)";
489
+ let user = "(none)";
490
+ try {
491
+ const u = new URL(url);
492
+ where = u.host || "localhost";
493
+ user = decodeURIComponent(u.username) || "(none)";
494
+ } catch (e2) {
495
+ }
496
+ let text;
497
+ if (e.code === 18 || e.codeName === "AuthenticationFailed") {
498
+ text = `MongoDB rejected the login for user "${user}" at ${where}. Check the username and password in DATABASE_URL (special characters must be URL-encoded), and authSource if the user lives in another database.`;
499
+ } else if (e.name === "MongooseServerSelectionError" || e.name === "MongoServerSelectionError") {
500
+ text = `Could not reach MongoDB at ${where}. Is it running? On Atlas, add this machine's IP under Network Access.`;
501
+ } else if (e.name === "MongoParseError") {
502
+ text = `DATABASE_URL isn't a valid MongoDB connection string: ${_nullishCoalesce(e.message, () => ( ""))}`;
503
+ }
504
+ return text ? new Error(`[EFC] ${text}`, { cause: err }) : err;
505
+ }
486
506
 
487
507
  // src/db/pg-model.ts
488
508
  function pgModel(name, tree, options) {
489
- const tbl = _chunkX2US4RAMcjs.pgTable.call(void 0, name, tree, options, { native: false, api: "defineModel" });
509
+ const tbl = _chunkNKLOE4AKcjs.pgTable.call(void 0, name, tree, options, { native: false, api: "defineModel" });
490
510
  const { columns, ts, refs, ready, compile, client, columnFor, toDb, fromRow, validate, guard } = tbl;
491
511
  const kindOf = (field) => _optionalChain([columns, 'access', _15 => _15.get, 'call', _16 => _16(field), 'optionalAccess', _17 => _17.kind]);
492
512
  function missingField(sql, cond) {
@@ -586,7 +606,7 @@ function pgModel(name, tree, options) {
586
606
  break;
587
607
  }
588
608
  default:
589
- throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(name, [
609
+ throw new (0, _chunkNKLOE4AKcjs.ModelValidationError)(name, [
590
610
  { path, message: `operator ${op} is not supported on PostgreSQL` }
591
611
  ]);
592
612
  }
@@ -617,8 +637,8 @@ function pgModel(name, tree, options) {
617
637
  for (const path of Array.isArray(paths) ? paths : [paths]) {
618
638
  const ref = refs.get(path);
619
639
  if (!ref)
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);
640
+ throw new (0, _chunkNKLOE4AKcjs.ModelValidationError)(name, [{ path, message: "is not a populatable ref field" }]);
641
+ const target = _chunkNKLOE4AKcjs.getRegisteredModel.call(void 0, ref.model);
622
642
  if (!target) throw new Error(`[EFC] populate: model "${ref.model}" is not defined`);
623
643
  const ids = [
624
644
  ...new Set(
@@ -661,7 +681,7 @@ function pgModel(name, tree, options) {
661
681
  return populate(rows, _optionalChain([opts, 'optionalAccess', _22 => _22.populate]));
662
682
  }
663
683
  const strictUpdate = (update) => {
664
- const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || _chunkX2US4RAMcjs.nodeAt.call(void 0, tree, path.split(".")) !== void 0);
684
+ const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || _chunkNKLOE4AKcjs.nodeAt.call(void 0, tree, path.split(".")) !== void 0);
665
685
  const out = {};
666
686
  for (const [k, v] of Object.entries(update)) {
667
687
  if (k.startsWith("$") && v !== null && typeof v === "object") {
@@ -676,7 +696,7 @@ function pgModel(name, tree, options) {
676
696
  const ops = update;
677
697
  for (const op of Object.keys(update).filter((k) => k.startsWith("$"))) {
678
698
  if (!["$set", "$unset", "$inc", "$push", "$pull"].includes(op)) {
679
- throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(name, [
699
+ throw new (0, _chunkNKLOE4AKcjs.ModelValidationError)(name, [
680
700
  { path: op, message: "update operator is not supported on PostgreSQL" }
681
701
  ]);
682
702
  }
@@ -689,25 +709,25 @@ function pgModel(name, tree, options) {
689
709
  for (const [k, v] of Object.entries($set)) if (!k.includes(".")) topLevel[k] = v;
690
710
  for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) if (!k.includes(".")) topLevel[k] = null;
691
711
  for (const [k, v] of Object.entries($set))
692
- if (k.includes(".")) await _chunkX2US4RAMcjs.validateAtPath.call(void 0, tree, k, v, issues);
712
+ if (k.includes(".")) await _chunkNKLOE4AKcjs.validateAtPath.call(void 0, tree, k, v, issues);
693
713
  for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) {
694
- if (k.includes(".")) await _chunkX2US4RAMcjs.validateAtPath.call(void 0, tree, k, null, issues);
714
+ if (k.includes(".")) await _chunkNKLOE4AKcjs.validateAtPath.call(void 0, tree, k, null, issues);
695
715
  }
696
716
  for (const [k, by] of Object.entries(_nullishCoalesce(ops["$inc"], () => ( {})))) {
697
717
  if (typeof by !== "number") issues.push({ path: k, message: "$inc needs a number" });
698
- const node = k.includes(".") ? _chunkX2US4RAMcjs.nodeAt.call(void 0, tree, k.split(".")) : tree[k];
718
+ const node = k.includes(".") ? _chunkNKLOE4AKcjs.nodeAt.call(void 0, tree, k.split(".")) : tree[k];
699
719
  if (node && !(node.kind === "scalar" && node.type === "number") && node.kind !== "json") {
700
720
  issues.push({ path: k, message: "$inc only applies to number fields" });
701
721
  }
702
722
  }
703
- if (issues.length) throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(name, issues);
723
+ if (issues.length) throw new (0, _chunkNKLOE4AKcjs.ModelValidationError)(name, issues);
704
724
  await validate(topLevel, true);
705
725
  const set = {};
706
726
  const nested = /* @__PURE__ */ new Map();
707
727
  const touchedTop = /* @__PURE__ */ new Set();
708
728
  const acc = (field) => _nullishCoalesce(nested.get(field), () => ( columnFor(t, field)));
709
729
  const conflict = (path) => {
710
- throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(name, [{ path, message: "conflicting update paths" }]);
730
+ throw new (0, _chunkNKLOE4AKcjs.ModelValidationError)(name, [{ path, message: "conflicting update paths" }]);
711
731
  };
712
732
  const top = (field, value) => {
713
733
  if (touchedTop.has(field) || nested.has(field)) conflict(field);
@@ -878,7 +898,7 @@ function defineModel(name, schema, options) {
878
898
  return createModel(name, schema, _nullishCoalesce(options, () => ( {})));
879
899
  }
880
900
  function distinctFields(tree, options) {
881
- const ts = _chunkX2US4RAMcjs.timestampFields.call(void 0, options);
901
+ const ts = _chunkNKLOE4AKcjs.timestampFields.call(void 0, options);
882
902
  const fields = /* @__PURE__ */ new Set(["id", ...Object.values(ts)]);
883
903
  for (const [key, node] of Object.entries(tree)) if (node.kind === "scalar") fields.add(key);
884
904
  return fields;
@@ -903,11 +923,11 @@ var MODEL_OPS = [
903
923
  ];
904
924
  var sortKey = (v) => v instanceof Date ? v.getTime() : v;
905
925
  function createModel(name, schema, options, native) {
906
- const tree = _chunkX2US4RAMcjs.normalizeSchema.call(void 0, schema, "model", name);
926
+ const tree = _chunkNKLOE4AKcjs.normalizeSchema.call(void 0, schema, "model", name);
907
927
  let engineModel;
908
928
  const impl = () => {
909
929
  if (engineModel) return engineModel;
910
- const engine = _chunkX2US4RAMcjs.getDbEngine.call(void 0, );
930
+ const engine = _chunkNKLOE4AKcjs.getDbEngine.call(void 0, );
911
931
  if (native && native.engine !== engine) {
912
932
  throw new Error(
913
933
  `[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`
@@ -949,7 +969,7 @@ function createModel(name, schema, options, native) {
949
969
  try {
950
970
  return await m.create(create);
951
971
  } catch (err) {
952
- if (_chunkX2US4RAMcjs.isHttpError.call(void 0, err) && err.statusCode === 409 && !_chunkX2US4RAMcjs.currentTx.call(void 0, )) {
972
+ if (_chunkNKLOE4AKcjs.isHttpError.call(void 0, err) && err.statusCode === 409 && !_chunkNKLOE4AKcjs.currentTx.call(void 0, )) {
953
973
  const retried = await m.updateOne(filter, update);
954
974
  if (retried) return retried;
955
975
  }
@@ -965,26 +985,32 @@ function createModel(name, schema, options, native) {
965
985
  sync: (opts) => call((m) => m.sync(opts)),
966
986
  drop: () => call((m) => m.drop())
967
987
  };
968
- _chunkVQSWSYK6cjs.traceOps.call(void 0, name, model, MODEL_OPS);
969
- _chunkX2US4RAMcjs.registerModel.call(void 0, {
988
+ _chunkDUADUR6Rcjs.traceOps.call(void 0, name, model, MODEL_OPS);
989
+ _chunkNKLOE4AKcjs.registerModel.call(void 0, {
970
990
  name,
971
991
  sync: model.sync,
972
992
  plan: (opts) => call((m) => m.plan(opts)),
973
993
  drop: model.drop,
974
994
  findByIds: (ids) => model.find({ id: { $in: ids } }),
975
- pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => ( _chunkX2US4RAMcjs.tableNameFor.call(void 0, name))), idKind: "uuid" })
995
+ pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => ( _chunkNKLOE4AKcjs.tableNameFor.call(void 0, name))), idKind: "uuid" }),
996
+ studio: {
997
+ storage: async () => _chunkNKLOE4AKcjs.getDbEngine.call(void 0, ) === "mongodb" ? (await model.raw()).collection.collectionName : _nullishCoalesce(options.collection, () => ( _chunkNKLOE4AKcjs.tableNameFor.call(void 0, name))),
998
+ create: (data) => model.create(data),
999
+ update: (id, data) => model.update(id, data),
1000
+ delete: (id) => model.delete(id)
1001
+ }
976
1002
  });
977
1003
  return model;
978
1004
  }
979
1005
 
980
1006
  // src/db/transaction.ts
981
1007
  async function transaction(fn) {
982
- if (_chunkX2US4RAMcjs.currentTx.call(void 0, )) return fn();
983
- if (_chunkX2US4RAMcjs.getDbEngine.call(void 0, ) === "postgresql") {
1008
+ if (_chunkNKLOE4AKcjs.currentTx.call(void 0, )) return fn();
1009
+ if (_chunkNKLOE4AKcjs.getDbEngine.call(void 0, ) === "postgresql") {
984
1010
  let result;
985
1011
  const afterCommit = [];
986
- await _chunkVQSWSYK6cjs.getOrm.call(void 0, ).transaction(async (tx) => {
987
- result = await _chunkX2US4RAMcjs.runInTx.call(void 0, { engine: "postgresql", tx, afterCommit }, fn);
1012
+ await _chunkDUADUR6Rcjs.getOrm.call(void 0, ).transaction(async (tx) => {
1013
+ result = await _chunkNKLOE4AKcjs.runInTx.call(void 0, { engine: "postgresql", tx, afterCommit }, fn);
988
1014
  });
989
1015
  for (const run of afterCommit) run();
990
1016
  return result;
@@ -994,7 +1020,7 @@ async function transaction(fn) {
994
1020
  try {
995
1021
  let result;
996
1022
  await session.withTransaction(async () => {
997
- result = await _chunkX2US4RAMcjs.runInTx.call(void 0, { engine: "mongodb", session }, fn);
1023
+ result = await _chunkNKLOE4AKcjs.runInTx.call(void 0, { engine: "mongodb", session }, fn);
998
1024
  });
999
1025
  return result;
1000
1026
  } finally {
@@ -1040,8 +1066,8 @@ var TableRuntime = (_class = class {
1040
1066
  constructor(name, schema, options) {;_class.prototype.__init.call(this);
1041
1067
  this.name = name;
1042
1068
  this.options = options;
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" });
1069
+ const tree = _chunkNKLOE4AKcjs.normalizeSchema.call(void 0, schema, "table", name);
1070
+ this.tbl = _chunkNKLOE4AKcjs.pgTable.call(void 0, name, tree, options, { native: true, api: "defineTable" });
1045
1071
  this.uniqueSets = [["id"]];
1046
1072
  for (const spec of this.tbl.columns.values()) {
1047
1073
  if (_optionalChain([spec, 'access', _25 => _25.node, 'optionalAccess', _26 => _26.def, 'access', _27 => _27.unique])) this.uniqueSets.push([spec.field]);
@@ -1068,7 +1094,7 @@ var TableRuntime = (_class = class {
1068
1094
  /** Many-to-many fields as list columns, so filters and projections treat them alike. */
1069
1095
  __init() {this.joinSpecs = /* @__PURE__ */ new Map()}
1070
1096
  fail(path, message) {
1071
- throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(this.name, [{ path, message }]);
1097
+ throw new (0, _chunkNKLOE4AKcjs.ModelValidationError)(this.name, [{ path, message }]);
1072
1098
  }
1073
1099
  spec(field) {
1074
1100
  return _nullishCoalesce(this.tbl.columns.get(field), () => ( this.joinSpecs.get(field)));
@@ -1079,18 +1105,18 @@ var TableRuntime = (_class = class {
1079
1105
  /** A many-to-many field's ids, in order, for the row `owner` (a table name or alias). */
1080
1106
  joinExpr(sql, join, owner) {
1081
1107
  return sql.raw(
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})`
1108
+ `coalesce((select array_agg(efc_j.ref_id order by efc_j.position) from ${_chunkNKLOE4AKcjs.q.call(void 0, join.table)} efc_j where efc_j.owner_id = ${owner}.${_chunkNKLOE4AKcjs.q.call(void 0, "id")}), '{}'::${join.ddl})`
1083
1109
  );
1084
1110
  }
1085
1111
  col(sql, field, alias) {
1086
1112
  const join = this.join(field);
1087
- if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => ( _chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))));
1113
+ if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => ( _chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table))));
1088
1114
  const spec = this.spec(field);
1089
- return sql.raw(alias ? `${alias}.${_chunkX2US4RAMcjs.q.call(void 0, spec.column)}` : _chunkX2US4RAMcjs.q.call(void 0, spec.column));
1115
+ return sql.raw(alias ? `${alias}.${_chunkNKLOE4AKcjs.q.call(void 0, spec.column)}` : _chunkNKLOE4AKcjs.q.call(void 0, spec.column));
1090
1116
  }
1091
1117
  /** SELECT items for the many-to-many fields among `fields`, as text arrays. */
1092
1118
  joinColumns(sql, fields, owner) {
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)))}`);
1119
+ return fields.filter((f) => this.join(f)).map((f) => sql`${this.col(sql, f, owner)}::text[] as ${sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, relAlias(f)))}`);
1094
1120
  }
1095
1121
  /** `col` for SELECT lists: many-to-many fields come back as text arrays under an alias. */
1096
1122
  selectCols(sql, fields, owner) {
@@ -1382,7 +1408,7 @@ var TableRuntime = (_class = class {
1382
1408
  if (args["cursor"]) {
1383
1409
  this.uniqueKey(args["cursor"], "cursor");
1384
1410
  const cw = this.where(sql, t, args["cursor"]);
1385
- const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${cw})`;
1411
+ const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table))} where ${cw})`;
1386
1412
  const ors = [];
1387
1413
  const same = (o) => sql`${this.col(sql, o.field)} is not distinct from ${at(o.field)}`;
1388
1414
  for (let i = 0; i < order.length; i++) {
@@ -1395,7 +1421,7 @@ var TableRuntime = (_class = class {
1395
1421
  ors.push(eqs.length ? sql`(${sql.join([...eqs, after], sql` and `)})` : after);
1396
1422
  }
1397
1423
  ors.push(sql`(${sql.join(order.map(same), sql` and `)})`);
1398
- parts.push(sql`exists (select 1 from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${cw})`);
1424
+ parts.push(sql`exists (select 1 from ${sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table))} where ${cw})`);
1399
1425
  parts.push(sql`(${sql.join(ors, sql` or `)})`);
1400
1426
  }
1401
1427
  return parts.length ? sql.join(parts, sql` and `) : sql`true`;
@@ -1420,7 +1446,7 @@ var TableRuntime = (_class = class {
1420
1446
  const offset = args["skip"] ? sql` offset ${sql.param(args["skip"])}` : sql``;
1421
1447
  const orderBy = order.length ? sql` order by ${this.orderSql(sql, order)}` : sql``;
1422
1448
  const where = this.readWhere(sql, t, args, order);
1423
- const from = sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table));
1449
+ const from = sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table));
1424
1450
  const distinct = _optionalChain([args, 'access', _29 => _29["distinct"], 'optionalAccess', _30 => _30.filter, 'call', _31 => _31((f) => this.spec(f))]);
1425
1451
  if (_optionalChain([distinct, 'optionalAccess', _32 => _32.length])) {
1426
1452
  const dcols = sql.join(
@@ -1450,7 +1476,7 @@ var TableRuntime = (_class = class {
1450
1476
  distinct ? "efc_distinct" : void 0
1451
1477
  );
1452
1478
  const include = this.includeArg(args);
1453
- const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : _chunkX2US4RAMcjs.q.call(void 0, this.tbl.table), 1) : [];
1479
+ const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : _chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table), 1) : [];
1454
1480
  const { query, reversed } = this.readQuery(
1455
1481
  sql,
1456
1482
  t,
@@ -1525,7 +1551,7 @@ var TableRuntime = (_class = class {
1525
1551
  for (const [name, arg] of Object.entries(include)) {
1526
1552
  if (!arg) continue;
1527
1553
  const expr = await this.relationExpr(sql, this.relation(name), relArgs(arg), owner, depth);
1528
- out.push(sql`${expr} as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, incAlias(name)))}`);
1554
+ out.push(sql`${expr} as ${sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, incAlias(name)))}`);
1529
1555
  }
1530
1556
  return out;
1531
1557
  }
@@ -1559,21 +1585,21 @@ var TableRuntime = (_class = class {
1559
1585
  */
1560
1586
  relationSource(rel, owner, a, j) {
1561
1587
  const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
1562
- const target = `${_chunkX2US4RAMcjs.q.call(void 0, T.tbl.table)} ${a}`;
1563
- const ownerId = `${owner}.${_chunkX2US4RAMcjs.q.call(void 0, "id")}`;
1588
+ const target = `${_chunkNKLOE4AKcjs.q.call(void 0, T.tbl.table)} ${a}`;
1589
+ const ownerId = `${owner}.${_chunkNKLOE4AKcjs.q.call(void 0, "id")}`;
1564
1590
  if (rel.via === "fk") {
1565
1591
  return {
1566
1592
  T,
1567
1593
  from: target,
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")}`
1594
+ cond: `${a}.${_chunkNKLOE4AKcjs.q.call(void 0, "id")} = ${owner}.${_chunkNKLOE4AKcjs.q.call(void 0, rel.column)}`,
1595
+ defaultOrder: `${a}.${_chunkNKLOE4AKcjs.q.call(void 0, "id")}`
1570
1596
  };
1571
1597
  }
1572
1598
  let from;
1573
1599
  let cond;
1574
1600
  let defaultOrder;
1575
1601
  if (rel.via === "join") {
1576
- from = `${_chunkX2US4RAMcjs.q.call(void 0, rel.join.table)} ${j} join ${target} on ${a}.${_chunkX2US4RAMcjs.q.call(void 0, "id")} = ${j}.ref_id`;
1602
+ from = `${_chunkNKLOE4AKcjs.q.call(void 0, rel.join.table)} ${j} join ${target} on ${a}.${_chunkNKLOE4AKcjs.q.call(void 0, "id")} = ${j}.ref_id`;
1577
1603
  cond = `${j}.owner_id = ${ownerId}`;
1578
1604
  defaultOrder = `${j}.position`;
1579
1605
  } else {
@@ -1591,7 +1617,7 @@ var TableRuntime = (_class = class {
1591
1617
  `[EFC] ${this.name}.${rel.name}: ${rel.target}.${rel.foreignKey} is many-to-many \u2014 use hasMany`
1592
1618
  );
1593
1619
  }
1594
- from = `${_chunkX2US4RAMcjs.q.call(void 0, join.table)} ${j} join ${target} on ${a}.${_chunkX2US4RAMcjs.q.call(void 0, "id")} = ${j}.owner_id`;
1620
+ from = `${_chunkNKLOE4AKcjs.q.call(void 0, join.table)} ${j} join ${target} on ${a}.${_chunkNKLOE4AKcjs.q.call(void 0, "id")} = ${j}.owner_id`;
1595
1621
  cond = `${j}.ref_id = ${ownerId}`;
1596
1622
  } else {
1597
1623
  if (rel.kind === "one" && !column.node.def.unique) {
@@ -1600,9 +1626,9 @@ var TableRuntime = (_class = class {
1600
1626
  );
1601
1627
  }
1602
1628
  from = target;
1603
- cond = `${a}.${_chunkX2US4RAMcjs.q.call(void 0, column.column)} = ${ownerId}`;
1629
+ cond = `${a}.${_chunkNKLOE4AKcjs.q.call(void 0, column.column)} = ${ownerId}`;
1604
1630
  }
1605
- defaultOrder = `${a}.${_chunkX2US4RAMcjs.q.call(void 0, "id")}`;
1631
+ defaultOrder = `${a}.${_chunkNKLOE4AKcjs.q.call(void 0, "id")}`;
1606
1632
  }
1607
1633
  return { T, from, cond, defaultOrder };
1608
1634
  }
@@ -1627,7 +1653,7 @@ var TableRuntime = (_class = class {
1627
1653
  const where = isPlainObject(w) ? w : { id: w };
1628
1654
  const found = await T.findUnique({ where, select: { id: true } });
1629
1655
  if (!found) {
1630
- throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(this.name, [
1656
+ throw new (0, _chunkNKLOE4AKcjs.ModelValidationError)(this.name, [
1631
1657
  { path, message: `no ${rel.target} matches ${JSON.stringify(where, idJson)}` }
1632
1658
  ]);
1633
1659
  }
@@ -1719,8 +1745,8 @@ var TableRuntime = (_class = class {
1719
1745
  try {
1720
1746
  await T.updateNested({ where: whereOf(w), data: { [fk]: owner } });
1721
1747
  } catch (err) {
1722
- if (_chunkX2US4RAMcjs.isHttpError.call(void 0, err) && err.statusCode === 404) {
1723
- throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(this.name, [
1748
+ if (_chunkNKLOE4AKcjs.isHttpError.call(void 0, err) && err.statusCode === 404) {
1749
+ throw new (0, _chunkNKLOE4AKcjs.ModelValidationError)(this.name, [
1724
1750
  {
1725
1751
  path: key,
1726
1752
  message: `no ${rel.target} matches ${JSON.stringify(whereOf(w), idJson)}`
@@ -1871,7 +1897,7 @@ var TableRuntime = (_class = class {
1871
1897
  const a = `efc_f${++aliasSeq}`;
1872
1898
  const { T, from, cond } = this.relationSource(
1873
1899
  rel,
1874
- _nullishCoalesce(owner, () => ( _chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))),
1900
+ _nullishCoalesce(owner, () => ( _chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table))),
1875
1901
  a,
1876
1902
  `efc_fj${aliasSeq}`
1877
1903
  );
@@ -2012,7 +2038,7 @@ var TableRuntime = (_class = class {
2012
2038
  }
2013
2039
  async orThrow(p) {
2014
2040
  const r = await p;
2015
- if (r === null) throw new (0, _chunkX2US4RAMcjs.HttpError)(404, `${this.name} not found`);
2041
+ if (r === null) throw new (0, _chunkNKLOE4AKcjs.HttpError)(404, `${this.name} not found`);
2016
2042
  return r;
2017
2043
  }
2018
2044
  async count(args = {}) {
@@ -2022,7 +2048,7 @@ var TableRuntime = (_class = class {
2022
2048
  const counted = select ? Object.entries(select).filter(([f, on]) => on && (f === "_all" || this.spec(f))) : [["_all", true]];
2023
2049
  const exprs = sql.join(
2024
2050
  counted.map(
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))}`
2051
+ ([f]) => f === "_all" ? sql`count(*)::int as ${sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, "_all"))}` : sql`count(${this.col(sql, f, "efc_rows")})::int as ${sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, f))}`
2026
2052
  ),
2027
2053
  sql`, `
2028
2054
  );
@@ -2097,7 +2123,7 @@ var TableRuntime = (_class = class {
2097
2123
  const specs = this.aggregateSpec(args);
2098
2124
  if (specs.length === 0) return {};
2099
2125
  const exprs = sql.join(
2100
- specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, s.alias))}`),
2126
+ specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, s.alias))}`),
2101
2127
  sql`, `
2102
2128
  );
2103
2129
  const { query } = this.readQuery(sql, t, { ...args, select: void 0 }, sql`*`);
@@ -2155,7 +2181,7 @@ var TableRuntime = (_class = class {
2155
2181
  [
2156
2182
  ...by.map((f) => this.col(sql, f)),
2157
2183
  ...specs.map(
2158
- (s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, s.alias))}`
2184
+ (s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, s.alias))}`
2159
2185
  )
2160
2186
  ],
2161
2187
  sql`, `
@@ -2179,7 +2205,7 @@ var TableRuntime = (_class = class {
2179
2205
  }
2180
2206
  }
2181
2207
  }
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(
2208
+ const query = sql`select ${select} from ${sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table))}${where ? sql` where ${where}` : sql``} group by ${sql.join(
2183
2209
  by.map((f) => this.col(sql, f)),
2184
2210
  sql`, `
2185
2211
  )}${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``}`;
@@ -2257,7 +2283,7 @@ var TableRuntime = (_class = class {
2257
2283
  }
2258
2284
  }
2259
2285
  }
2260
- if (issues.length) throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(this.name, issues);
2286
+ if (issues.length) throw new (0, _chunkNKLOE4AKcjs.ModelValidationError)(this.name, issues);
2261
2287
  await this.tbl.validate(plain, true);
2262
2288
  for (const [field, v] of Object.entries(plain)) {
2263
2289
  sets.push(
@@ -2299,7 +2325,7 @@ var TableRuntime = (_class = class {
2299
2325
  }
2300
2326
  for (const [field, entries] of byField) {
2301
2327
  const join = this.join(field);
2302
- const jt = sql.raw(_chunkX2US4RAMcjs.q.call(void 0, join.table));
2328
+ const jt = sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, join.table));
2303
2329
  const sets = entries.filter((e) => e.op.mode === "set");
2304
2330
  if (sets.length) {
2305
2331
  const owners2 = sets.map((e) => idText(e.id));
@@ -2346,7 +2372,7 @@ var TableRuntime = (_class = class {
2346
2372
  const idDdl = this.tbl.columns.get("id").ddl;
2347
2373
  const owners = sql`${sql.param(ids.map(idText))}::${sql.raw(idDdl)}[]`;
2348
2374
  const parts = joins.map(
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`
2375
+ (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(_chunkNKLOE4AKcjs.q.call(void 0, j.table))} where owner_id = any(${owners}) group by owner_id`
2350
2376
  );
2351
2377
  const { rows } = await this.exec(sql.join(parts, sql` union all `));
2352
2378
  for (const j of joins) out.set(j.field, /* @__PURE__ */ new Map());
@@ -2368,7 +2394,7 @@ var TableRuntime = (_class = class {
2368
2394
  }
2369
2395
  insertSql(sql, t, rows) {
2370
2396
  const fields = [...new Set(rows.flatMap((r) => Object.keys(r)))];
2371
- const head = sql`insert into ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} (${sql.join(
2397
+ const head = sql`insert into ${sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table))} (${sql.join(
2372
2398
  fields.map((f) => this.col(sql, f)),
2373
2399
  sql`, `
2374
2400
  )})`;
@@ -2465,7 +2491,7 @@ var TableRuntime = (_class = class {
2465
2491
  return;
2466
2492
  }
2467
2493
  const { rows: ids } = await this.exec(
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)})`
2494
+ sql`select nextval(pg_get_serial_sequence(${sql.param(_chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table))}, 'id'))::text as id from generate_series(1, ${sql.param(missing.length)})`
2469
2495
  );
2470
2496
  missing.forEach((r, i) => {
2471
2497
  const id = ids[i]["id"];
@@ -2494,9 +2520,9 @@ var TableRuntime = (_class = class {
2494
2520
  const where = this.where(sql, t, args["where"]);
2495
2521
  const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
2496
2522
  const extra = links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``;
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`;
2523
+ const query = sets.length ? sql`update ${sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *${extra}` : sql`select *${extra} from ${sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table))} where ${where} limit 1`;
2498
2524
  const [row] = (await this.exec(query)).rows;
2499
- if (!row) throw new (0, _chunkX2US4RAMcjs.HttpError)(404, `${this.name} not found`);
2525
+ if (!row) throw new (0, _chunkNKLOE4AKcjs.HttpError)(404, `${this.name} not found`);
2500
2526
  const record = this.fromRaw(t, row);
2501
2527
  await this.applyJoins(sql, [{ id: record["id"], ops: joinOps }]);
2502
2528
  await this.refreshJoins(sql, [record], joinOps);
@@ -2517,7 +2543,7 @@ var TableRuntime = (_class = class {
2517
2543
  const links = returning ? this.joinColumns(sql, [...this.tbl.joins.keys()]) : [];
2518
2544
  const list = returning ? sql` returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : joinOps.length ? sql` returning ${this.col(sql, "id")}` : sql``;
2519
2545
  const result = await this.exec(
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}`
2546
+ sets.length ? sql`update ${sql.raw(_chunkNKLOE4AKcjs.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(_chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table))} where ${where}`
2521
2547
  );
2522
2548
  const records = result.rows.map((r) => returning ? this.fromRaw(t, r) : r);
2523
2549
  await this.applyJoins(
@@ -2541,7 +2567,7 @@ var TableRuntime = (_class = class {
2541
2567
  if (row[f] === void 0) row[f] = this.tbl.toDb(f, args["where"][f]);
2542
2568
  }
2543
2569
  const { head, values } = this.insertSql(sql, t, [row]);
2544
- const table = _chunkX2US4RAMcjs.q.call(void 0, this.tbl.table);
2570
+ const table = _chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table);
2545
2571
  const update = await this.setList(sql, t, _nullishCoalesce(args["update"], () => ( {})), table);
2546
2572
  const { joinOps } = update;
2547
2573
  let { sets } = update;
@@ -2562,7 +2588,7 @@ var TableRuntime = (_class = class {
2562
2588
  const [out] = (await this.exec(
2563
2589
  sql`${head} values ${values} on conflict (${target}) do update set ${sql.join(sets, sql`, `)}${cond}${returning}`
2564
2590
  )).rows;
2565
- if (!out) throw new (0, _chunkX2US4RAMcjs.HttpError)(404, `${this.name} not found`);
2591
+ if (!out) throw new (0, _chunkNKLOE4AKcjs.HttpError)(404, `${this.name} not found`);
2566
2592
  const record = this.fromRaw(t, out);
2567
2593
  if (linked) {
2568
2594
  const ops = out["efc_inserted"] ? createOps.filter((o) => o.items.length) : joinOps;
@@ -2581,9 +2607,9 @@ var TableRuntime = (_class = class {
2581
2607
  const where = this.where(sql, t, args["where"]);
2582
2608
  const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
2583
2609
  const [row] = (await this.exec(
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``}`
2610
+ sql`delete from ${sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table))} where ${where} returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}`
2585
2611
  )).rows;
2586
- if (!row) throw new (0, _chunkX2US4RAMcjs.HttpError)(404, `${this.name} not found`);
2612
+ if (!row) throw new (0, _chunkNKLOE4AKcjs.HttpError)(404, `${this.name} not found`);
2587
2613
  return this.project(this.fromRaw(t, row), this.projection(args));
2588
2614
  });
2589
2615
  }
@@ -2591,7 +2617,7 @@ var TableRuntime = (_class = class {
2591
2617
  const { t, sql } = await this.ready(args["where"]);
2592
2618
  return this.tbl.guard(async () => {
2593
2619
  const where = _nullishCoalesce(this.where(sql, t, args["where"]), () => ( sql`true`));
2594
- const result = await this.tbl.client().execute(sql`delete from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${where}`);
2620
+ const result = await this.tbl.client().execute(sql`delete from ${sql.raw(_chunkNKLOE4AKcjs.q.call(void 0, this.tbl.table))} where ${where}`);
2595
2621
  return { count: _nullishCoalesce(result.rowCount, () => ( 0)) };
2596
2622
  });
2597
2623
  }
@@ -2600,10 +2626,10 @@ function relArgs(arg) {
2600
2626
  return isPlainObject(arg) ? arg : {};
2601
2627
  }
2602
2628
  function runtimeOf(name, from) {
2603
- const runtime = _optionalChain([_chunkX2US4RAMcjs.getRegisteredModel.call(void 0, name), 'optionalAccess', _65 => _65.tableRuntime, 'optionalCall', _66 => _66()]);
2629
+ const runtime = _optionalChain([_chunkNKLOE4AKcjs.getRegisteredModel.call(void 0, name), 'optionalAccess', _65 => _65.tableRuntime, 'optionalCall', _66 => _66()]);
2604
2630
  if (!runtime) {
2605
2631
  throw new Error(
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`
2632
+ _chunkNKLOE4AKcjs.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`
2607
2633
  );
2608
2634
  }
2609
2635
  return runtime;
@@ -2623,7 +2649,7 @@ var JSON_OPS = /* @__PURE__ */ new Set([
2623
2649
  "mode"
2624
2650
  ]);
2625
2651
  function createTable(name, schema, options = {}) {
2626
- _chunkX2US4RAMcjs.normalizeSchema.call(void 0, schema, "table", name);
2652
+ _chunkNKLOE4AKcjs.normalizeSchema.call(void 0, schema, "table", name);
2627
2653
  for (const [rel, def] of Object.entries(_nullishCoalesce(options.relations, () => ( {})))) {
2628
2654
  const where = `[EFC] ${name}.relations.${rel}`;
2629
2655
  if (rel in schema) throw new Error(`${where}: a field already has this name`);
@@ -2638,7 +2664,7 @@ function createTable(name, schema, options = {}) {
2638
2664
  }
2639
2665
  let runtime;
2640
2666
  const rt = () => {
2641
- const engine = _chunkX2US4RAMcjs.getDbEngine.call(void 0, );
2667
+ const engine = _chunkNKLOE4AKcjs.getDbEngine.call(void 0, );
2642
2668
  if (engine !== "postgresql") {
2643
2669
  throw new Error(
2644
2670
  `[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`
@@ -2670,19 +2696,28 @@ function createTable(name, schema, options = {}) {
2670
2696
  sync: (opts) => call((r) => r.tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _71 => _71.dryRun]), () => ( false)))),
2671
2697
  drop: () => call((r) => r.tbl.drop())
2672
2698
  };
2673
- _chunkVQSWSYK6cjs.traceOps.call(void 0,
2699
+ _chunkDUADUR6Rcjs.traceOps.call(void 0,
2674
2700
  name,
2675
2701
  model,
2676
2702
  Object.keys(model).filter((op) => !["name", "raw", "sync", "drop"].includes(op))
2677
2703
  );
2678
- _chunkX2US4RAMcjs.registerModel.call(void 0, {
2704
+ _chunkNKLOE4AKcjs.registerModel.call(void 0, {
2679
2705
  name,
2680
2706
  sync: model.sync,
2681
2707
  plan: (opts) => call((r) => r.tbl.plan(opts)),
2682
2708
  drop: model.drop,
2683
2709
  findByIds: (ids) => model.findMany({ where: { id: { in: ids } } }),
2684
2710
  pgTarget: () => ({ table: rt().tbl.table, idKind: rt().tbl.idKind }),
2685
- tableRuntime: () => rt()
2711
+ tableRuntime: () => rt(),
2712
+ studio: /* @__PURE__ */ (() => {
2713
+ const idOf = (id) => rt().tbl.idKind === "serial" ? Number(id) : rt().tbl.idKind === "bigserial" ? BigInt(id) : id;
2714
+ return {
2715
+ storage: async () => rt().tbl.table,
2716
+ create: (data) => model.create({ data }),
2717
+ update: (id, data) => model.update({ where: { id: idOf(id) }, data }),
2718
+ delete: (id) => model.delete({ where: { id: idOf(id) } })
2719
+ };
2720
+ })()
2686
2721
  });
2687
2722
  return model;
2688
2723
  }
@@ -2690,6 +2725,129 @@ function defineTable(name, schema, options) {
2690
2725
  return createTable(name, schema, _nullishCoalesce(options, () => ( {})));
2691
2726
  }
2692
2727
 
2728
+ // src/db/pipeline.ts
2729
+ var Pipeline = class _Pipeline {
2730
+ /** @internal */
2731
+ constructor(run, stages = []) {
2732
+ this.run = run;
2733
+ this.stages = stages;
2734
+ }
2735
+
2736
+
2737
+ next(...stage) {
2738
+ return new _Pipeline(this.run, [...this.stages, ...stage]);
2739
+ }
2740
+ /** `$match` — same filter vocabulary as `find`. */
2741
+ match(filter) {
2742
+ return this.next({ $match: filter });
2743
+ }
2744
+ sort(spec) {
2745
+ return this.next({ $sort: spec });
2746
+ }
2747
+ skip(n) {
2748
+ return this.next({ $skip: n });
2749
+ }
2750
+ limit(n) {
2751
+ return this.next({ $limit: n });
2752
+ }
2753
+ /** `$sample` — `n` random records. */
2754
+ sample(n) {
2755
+ return this.next({ $sample: { size: n } });
2756
+ }
2757
+ /** `$project` with an inclusion spec: the result has only those fields (and `id`). */
2758
+ project(spec) {
2759
+ return this.next({ $project: spec });
2760
+ }
2761
+ /**
2762
+ * `$unwind` an array field: one result per element, the field holding that element.
2763
+ * `preserveNullAndEmptyArrays` keeps records without elements (the field is then null).
2764
+ */
2765
+ unwind(path, options) {
2766
+ return this.next(
2767
+ _optionalChain([options, 'optionalAccess', _72 => _72.preserveNullAndEmptyArrays]) ? { $unwind: { path, preserveNullAndEmptyArrays: true } } : { $unwind: path }
2768
+ );
2769
+ }
2770
+ /** `$group` — `_id` is `'$field'`, `null` or `{ key: '$field' }`; accumulators are typed. */
2771
+ group(spec) {
2772
+ return this.next({ $group: spec });
2773
+ }
2774
+ /** `$count` — a single `{ [field]: n }` (no result at all when nothing matched). */
2775
+ count(field) {
2776
+ return this.next({ $count: field });
2777
+ }
2778
+ /** `$addFields` / `$set` — say what the new fields are: `addFields<{ total: number }>({ … })`. */
2779
+ addFields(spec) {
2780
+ return this.next({ $addFields: spec });
2781
+ }
2782
+ lookup(a, b) {
2783
+ const idField = (f) => f === "id" ? "_id" : f;
2784
+ if (typeof a === "string") {
2785
+ const field = a;
2786
+ const target2 = b;
2787
+ const isArray = `__efc_isarr_${field.replace(/\./g, "_")}`;
2788
+ return this.next(async () => [
2789
+ { $set: { [isArray]: { $isArray: `$${field}` } } },
2790
+ {
2791
+ $lookup: {
2792
+ from: await collectionOf(target2),
2793
+ localField: field,
2794
+ foreignField: "_id",
2795
+ as: field
2796
+ }
2797
+ },
2798
+ {
2799
+ $set: {
2800
+ [field]: {
2801
+ $cond: [
2802
+ `$${isArray}`,
2803
+ `$${field}`,
2804
+ { $ifNull: [{ $arrayElemAt: [`$${field}`, 0] }, null] }
2805
+ ]
2806
+ }
2807
+ }
2808
+ },
2809
+ { $unset: isArray }
2810
+ ]);
2811
+ }
2812
+ const { from: target, localField, foreignField, as } = a;
2813
+ return this.next(async () => [
2814
+ {
2815
+ $lookup: {
2816
+ from: await collectionOf(target),
2817
+ localField: idField(localField),
2818
+ foreignField: idField(foreignField),
2819
+ as
2820
+ }
2821
+ }
2822
+ ]);
2823
+ }
2824
+ /** Any other stage, with its output type spelled out: `stage<{ … }>({ $facet: … })`. */
2825
+ stage(stage) {
2826
+ return this.next(stage);
2827
+ }
2828
+ /** The stages as plain objects (lookups resolved to collection names). */
2829
+ async toArray() {
2830
+ const out = [];
2831
+ for (const s of this.stages) {
2832
+ if (typeof s === "function") out.push(...await s());
2833
+ else out.push(s);
2834
+ }
2835
+ return out;
2836
+ }
2837
+ async exec() {
2838
+ return await this.run(await this.toArray());
2839
+ }
2840
+ then(onfulfilled, onrejected) {
2841
+ return this.exec().then(onfulfilled, onrejected);
2842
+ }
2843
+ };
2844
+ async function collectionOf(target) {
2845
+ const model = await target.raw();
2846
+ const name = _nullishCoalesce(_optionalChain([model, 'access', _73 => _73.collection, 'optionalAccess', _74 => _74.collectionName]), () => ( _optionalChain([model, 'access', _75 => _75.collection, 'optionalAccess', _76 => _76.name])));
2847
+ if (!name) throw new Error(`[EFC] lookup: can't find the collection behind ${target.name}`);
2848
+ return name;
2849
+ }
2850
+
2693
2851
  // src/db/collection-model.ts
2694
2852
  function fromBson(value) {
2695
2853
  if (Array.isArray(value)) return value.map(fromBson);
@@ -2749,7 +2907,7 @@ function mapBulkOp(op) {
2749
2907
  return { [kind]: b };
2750
2908
  }
2751
2909
  function createCollection(name, schema, options) {
2752
- const tree = _chunkX2US4RAMcjs.normalizeSchema.call(void 0, schema, "collection", name);
2910
+ const tree = _chunkNKLOE4AKcjs.normalizeSchema.call(void 0, schema, "collection", name);
2753
2911
  const base = mongoModel(name, tree, options);
2754
2912
  const longs = hasLong(tree);
2755
2913
  const toRecord = (doc) => {
@@ -2758,7 +2916,7 @@ function createCollection(name, schema, options) {
2758
2916
  return longs ? castTree(rec, tree) : rec;
2759
2917
  };
2760
2918
  const model = async () => {
2761
- const engine = _chunkX2US4RAMcjs.getDbEngine.call(void 0, );
2919
+ const engine = _chunkNKLOE4AKcjs.getDbEngine.call(void 0, );
2762
2920
  if (engine !== "mongodb") {
2763
2921
  throw new Error(
2764
2922
  `[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`
@@ -2767,13 +2925,33 @@ function createCollection(name, schema, options) {
2767
2925
  return await base.raw();
2768
2926
  };
2769
2927
  const session = () => {
2770
- const tx = _chunkX2US4RAMcjs.currentTx.call(void 0, );
2771
- return _optionalChain([tx, 'optionalAccess', _72 => _72.engine]) === "mongodb" ? tx.session : null;
2928
+ const tx = _chunkNKLOE4AKcjs.currentTx.call(void 0, );
2929
+ return _optionalChain([tx, 'optionalAccess', _77 => _77.engine]) === "mongodb" ? tx.session : null;
2772
2930
  };
2773
2931
  const sess = () => {
2774
2932
  const s = session();
2775
2933
  return s ? { session: s } : {};
2776
2934
  };
2935
+ const runPipeline = (stages) => guard(async (M) => {
2936
+ let sourceShape = true;
2937
+ const prepared = stages.map((stage) => {
2938
+ const [op] = Object.keys(stage);
2939
+ if (!sourceShape) return stage;
2940
+ if (op === "$match") {
2941
+ const filter = mapFilter(stage["$match"]);
2942
+ return { $match: M.find().cast(M, filter) };
2943
+ }
2944
+ if (op === "$sort") return { $sort: mapSort(stage["$sort"]) };
2945
+ if (op !== "$skip" && op !== "$limit" && op !== "$sample") sourceShape = false;
2946
+ return stage;
2947
+ });
2948
+ const agg = M.aggregate(prepared);
2949
+ const s = session();
2950
+ if (s) agg.session(s);
2951
+ if (options.collation)
2952
+ agg.collation(options.collation);
2953
+ return (await agg).map(toRecord);
2954
+ });
2777
2955
  const guard = async (fn) => {
2778
2956
  const M = await model();
2779
2957
  try {
@@ -2783,22 +2961,22 @@ function createCollection(name, schema, options) {
2783
2961
  }
2784
2962
  };
2785
2963
  const findOpts = (q2, opts) => {
2786
- if (_optionalChain([opts, 'optionalAccess', _73 => _73.projection])) q2.select(opts.projection);
2787
- if (_optionalChain([opts, 'optionalAccess', _74 => _74.sort])) {
2964
+ if (_optionalChain([opts, 'optionalAccess', _78 => _78.projection])) q2.select(opts.projection);
2965
+ if (_optionalChain([opts, 'optionalAccess', _79 => _79.sort])) {
2788
2966
  const meta = Object.values(opts.sort).some((v) => typeof v === "object");
2789
2967
  q2.sort(meta ? opts.sort : mapSort(opts.sort));
2790
2968
  }
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));
2969
+ if (_optionalChain([opts, 'optionalAccess', _80 => _80.skip]) !== void 0) q2.skip(opts.skip);
2970
+ if (_optionalChain([opts, 'optionalAccess', _81 => _81.limit]) !== void 0) q2.limit(opts.limit);
2971
+ if (_optionalChain([opts, 'optionalAccess', _82 => _82.populate])) q2.populate(opts.populate);
2972
+ const collation = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _83 => _83.collation]), () => ( options.collation));
2795
2973
  if (collation) q2.collation(collation);
2796
2974
  q2.session(session());
2797
2975
  return q2;
2798
2976
  };
2799
2977
  const isBadId = (err) => {
2800
2978
  const e = err;
2801
- return _optionalChain([e, 'optionalAccess', _79 => _79.name]) === "CastError" && e.path === "_id";
2979
+ return _optionalChain([e, 'optionalAccess', _84 => _84.name]) === "CastError" && e.path === "_id";
2802
2980
  };
2803
2981
  const model$ = {
2804
2982
  name,
@@ -2839,7 +3017,7 @@ function createCollection(name, schema, options) {
2839
3017
  async (M) => writeResult(
2840
3018
  await M.updateOne(mapFilter(filter), update, {
2841
3019
  runValidators: true,
2842
- upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _80 => _80.upsert]), () => ( false)),
3020
+ upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _85 => _85.upsert]), () => ( false)),
2843
3021
  ...sess()
2844
3022
  })
2845
3023
  )
@@ -2848,7 +3026,7 @@ function createCollection(name, schema, options) {
2848
3026
  async (M) => writeResult(
2849
3027
  await M.updateMany(mapFilter(filter), update, {
2850
3028
  runValidators: true,
2851
- upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _81 => _81.upsert]), () => ( false)),
3029
+ upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _86 => _86.upsert]), () => ( false)),
2852
3030
  ...sess()
2853
3031
  })
2854
3032
  )
@@ -2857,7 +3035,7 @@ function createCollection(name, schema, options) {
2857
3035
  async (M) => writeResult(
2858
3036
  await M.replaceOne(mapFilter(filter), replacement, {
2859
3037
  runValidators: true,
2860
- upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _82 => _82.upsert]), () => ( false)),
3038
+ upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _87 => _87.upsert]), () => ( false)),
2861
3039
  ...sess()
2862
3040
  })
2863
3041
  )
@@ -2866,10 +3044,10 @@ function createCollection(name, schema, options) {
2866
3044
  async (M) => toRecord(
2867
3045
  await M.findOneAndUpdate(mapFilter(filter), update, {
2868
3046
  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 },
3047
+ upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _88 => _88.upsert]), () => ( false)),
3048
+ returnDocument: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _89 => _89.returnDocument]), () => ( "before")),
3049
+ ..._optionalChain([opts, 'optionalAccess', _90 => _90.projection]) && { projection: opts.projection },
3050
+ ..._optionalChain([opts, 'optionalAccess', _91 => _91.sort]) && { sort: opts.sort },
2873
3051
  ...sess()
2874
3052
  }).lean()
2875
3053
  )
@@ -2879,7 +3057,7 @@ function createCollection(name, schema, options) {
2879
3057
  return toRecord(
2880
3058
  await M.findByIdAndUpdate(id, update, {
2881
3059
  runValidators: true,
2882
- returnDocument: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _87 => _87.returnDocument]), () => ( "before")),
3060
+ returnDocument: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _92 => _92.returnDocument]), () => ( "before")),
2883
3061
  ...sess()
2884
3062
  }).lean()
2885
3063
  );
@@ -2891,7 +3069,7 @@ function createCollection(name, schema, options) {
2891
3069
  findOneAndDelete: (filter, opts) => guard(
2892
3070
  async (M) => toRecord(
2893
3071
  await M.findOneAndDelete(mapFilter(filter), {
2894
- ..._optionalChain([opts, 'optionalAccess', _88 => _88.sort]) && { sort: opts.sort },
3072
+ ..._optionalChain([opts, 'optionalAccess', _93 => _93.sort]) && { sort: opts.sort },
2895
3073
  ...sess()
2896
3074
  }).lean()
2897
3075
  )
@@ -2918,6 +3096,8 @@ function createCollection(name, schema, options) {
2918
3096
  agg.collation(options.collation);
2919
3097
  return (await agg).map(toRecord);
2920
3098
  }),
3099
+ pipeline: () => new Pipeline(runPipeline),
3100
+ lookup: (field, target, filter) => new Pipeline(runPipeline).match(_nullishCoalesce(filter, () => ( {}))).lookup(field, target).exec(),
2921
3101
  bulkWrite: (ops, opts) => guard(async (M) => {
2922
3102
  if (ops.length === 0) {
2923
3103
  return {
@@ -2931,7 +3111,7 @@ function createCollection(name, schema, options) {
2931
3111
  const r = await M.bulkWrite(
2932
3112
  ops.map(mapBulkOp),
2933
3113
  {
2934
- ordered: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _89 => _89.ordered]), () => ( true)),
3114
+ ordered: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _94 => _94.ordered]), () => ( true)),
2935
3115
  runValidators: true,
2936
3116
  ...sess()
2937
3117
  }
@@ -2950,13 +3130,13 @@ function createCollection(name, schema, options) {
2950
3130
  const open = async () => {
2951
3131
  const M = await model();
2952
3132
  stream ??= M.watch(pipeline, {
2953
- ..._optionalChain([opts, 'optionalAccess', _90 => _90.fullDocument]) && { fullDocument: opts.fullDocument }
3133
+ ..._optionalChain([opts, 'optionalAccess', _95 => _95.fullDocument]) && { fullDocument: opts.fullDocument }
2954
3134
  });
2955
3135
  return stream;
2956
3136
  };
2957
3137
  const close = async () => {
2958
3138
  closed = true;
2959
- await _optionalChain([stream, 'optionalAccess', _91 => _91.close, 'call', _92 => _92()]);
3139
+ await _optionalChain([stream, 'optionalAccess', _96 => _96.close, 'call', _97 => _97()]);
2960
3140
  };
2961
3141
  return {
2962
3142
  close,
@@ -2972,7 +3152,7 @@ function createCollection(name, schema, options) {
2972
3152
  const key = change["documentKey"];
2973
3153
  yield {
2974
3154
  operationType: String(change["operationType"]),
2975
- id: _optionalChain([key, 'optionalAccess', _93 => _93._id]) == null ? void 0 : String(key._id),
3155
+ id: _optionalChain([key, 'optionalAccess', _98 => _98._id]) == null ? void 0 : String(key._id),
2976
3156
  ...change["fullDocument"] != null && {
2977
3157
  fullDocument: toRecord(change["fullDocument"])
2978
3158
  },
@@ -2992,12 +3172,12 @@ function createCollection(name, schema, options) {
2992
3172
  sync: (opts) => model().then(() => base.sync(opts)),
2993
3173
  drop: () => model().then(() => base.drop())
2994
3174
  };
2995
- _chunkVQSWSYK6cjs.traceOps.call(void 0,
3175
+ _chunkDUADUR6Rcjs.traceOps.call(void 0,
2996
3176
  name,
2997
3177
  model$,
2998
3178
  Object.keys(model$).filter((op) => !["name", "raw", "sync", "drop", "watch"].includes(op))
2999
3179
  );
3000
- _chunkX2US4RAMcjs.registerModel.call(void 0, {
3180
+ _chunkNKLOE4AKcjs.registerModel.call(void 0, {
3001
3181
  name,
3002
3182
  sync: model$.sync,
3003
3183
  plan: (opts) => model().then(() => base.plan(opts)),
@@ -3005,6 +3185,12 @@ function createCollection(name, schema, options) {
3005
3185
  findByIds: (ids) => model$.find({ _id: { $in: ids } }),
3006
3186
  pgTarget: () => {
3007
3187
  throw new Error(`[EFC] ${name} is a MongoDB collection (defineCollection)`);
3188
+ },
3189
+ studio: {
3190
+ storage: async () => (await model()).collection.collectionName,
3191
+ create: (data) => model$.create(data),
3192
+ update: (id, data) => model$.findByIdAndUpdate(id, data, { returnDocument: "after" }),
3193
+ delete: (id) => model$.findByIdAndDelete(id)
3008
3194
  }
3009
3195
  });
3010
3196
  return model$;
@@ -3045,5 +3231,6 @@ var db = new Proxy({}, {
3045
3231
 
3046
3232
 
3047
3233
 
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
3234
+
3235
+ exports.loadMongoose = loadMongoose; exports.connectMongo = connectMongo; exports.defineModel = defineModel; exports.transaction = transaction; exports.defineTable = defineTable; exports.defineCollection = defineCollection; exports.setDbClient = setDbClient; exports.getDbClient = getDbClient; exports.db = db;
3236
+ //# sourceMappingURL=chunk-HBCY7ILD.cjs.map