express-file-cluster 0.9.6 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/dist/auth/index.cjs +7 -6
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +1 -1
  4. package/dist/auth/index.d.ts +1 -1
  5. package/dist/auth/index.js +5 -5
  6. package/dist/chunk-3SWI46YK.js +74 -0
  7. package/dist/chunk-3SWI46YK.js.map +1 -0
  8. package/dist/{chunk-DCJOWFVD.cjs → chunk-4GHK27JA.cjs} +3 -3
  9. package/dist/{chunk-DCJOWFVD.cjs.map → chunk-4GHK27JA.cjs.map} +1 -1
  10. package/dist/{chunk-NI2BNGGV.js → chunk-5LPRKZPB.js} +2 -2
  11. package/dist/chunk-74BSJXWD.cjs +220 -0
  12. package/dist/chunk-74BSJXWD.cjs.map +1 -0
  13. package/dist/{chunk-6KHBJOLB.cjs → chunk-7BC3AN7R.cjs} +14 -14
  14. package/dist/{chunk-6KHBJOLB.cjs.map → chunk-7BC3AN7R.cjs.map} +1 -1
  15. package/dist/chunk-AGOYTFRO.cjs +42 -0
  16. package/dist/chunk-AGOYTFRO.cjs.map +1 -0
  17. package/dist/{chunk-HBYSKULC.js → chunk-B6MB6HEG.js} +5 -1
  18. package/dist/chunk-B6MB6HEG.js.map +1 -0
  19. package/dist/{chunk-OFA7OGN5.js → chunk-BG4A7Z32.js} +176 -7
  20. package/dist/chunk-BG4A7Z32.js.map +1 -0
  21. package/dist/{chunk-45BWAR6P.js → chunk-C2FOZ7ME.js} +4 -4
  22. package/dist/chunk-CGY7JU4Y.cjs +8 -0
  23. package/dist/chunk-CGY7JU4Y.cjs.map +1 -0
  24. package/dist/{chunk-BBSZLGZW.js → chunk-DN4TCGYB.js} +43 -14
  25. package/dist/chunk-DN4TCGYB.js.map +1 -0
  26. package/dist/{chunk-TI24L4XE.cjs → chunk-H2PVWCWC.cjs} +6 -2
  27. package/dist/chunk-H2PVWCWC.cjs.map +1 -0
  28. package/dist/{chunk-TYCYYLLM.cjs → chunk-IUZ6A7PB.cjs} +20 -53
  29. package/dist/chunk-IUZ6A7PB.cjs.map +1 -0
  30. package/dist/{chunk-DUADUR6R.cjs → chunk-JP36TLL4.cjs} +171 -14
  31. package/dist/chunk-JP36TLL4.cjs.map +1 -0
  32. package/dist/chunk-KLWL7XSC.js +220 -0
  33. package/dist/chunk-KLWL7XSC.js.map +1 -0
  34. package/dist/{chunk-QL6EWT4B.cjs → chunk-M53GODCX.cjs} +44 -15
  35. package/dist/chunk-M53GODCX.cjs.map +1 -0
  36. package/dist/{chunk-7ZESZG3J.js → chunk-MUVO7MGS.js} +4 -4
  37. package/dist/{chunk-VWSUQKCJ.cjs → chunk-R2K7AFIB.cjs} +286 -117
  38. package/dist/chunk-R2K7AFIB.cjs.map +1 -0
  39. package/dist/{chunk-ULWNHN6P.js → chunk-RETV3GKE.js} +9 -42
  40. package/dist/chunk-RETV3GKE.js.map +1 -0
  41. package/dist/{chunk-7YEX4MQV.cjs → chunk-RPL2IFWK.cjs} +46 -7
  42. package/dist/chunk-RPL2IFWK.cjs.map +1 -0
  43. package/dist/{chunk-FMA76PRH.cjs → chunk-TBIVIR6L.cjs} +15 -15
  44. package/dist/{chunk-FMA76PRH.cjs.map → chunk-TBIVIR6L.cjs.map} +1 -1
  45. package/dist/{chunk-73XJUT2S.js → chunk-V73R76I4.js} +162 -5
  46. package/dist/chunk-V73R76I4.js.map +1 -0
  47. package/dist/chunk-XPY5TQDK.js +42 -0
  48. package/dist/chunk-XPY5TQDK.js.map +1 -0
  49. package/dist/{chunk-RGT4ZVHL.cjs → chunk-Y4NKIXUL.cjs} +110 -55
  50. package/dist/chunk-Y4NKIXUL.cjs.map +1 -0
  51. package/dist/{chunk-2SETEVMO.js → chunk-Y75V5FCU.js} +100 -45
  52. package/dist/chunk-Y75V5FCU.js.map +1 -0
  53. package/dist/cli/db-runner.cjs +2059 -126
  54. package/dist/cli/db-runner.cjs.map +1 -1
  55. package/dist/cli/db-runner.js +2034 -102
  56. package/dist/cli/db-runner.js.map +1 -1
  57. package/dist/cli/index.cjs +50 -29
  58. package/dist/cli/index.cjs.map +1 -1
  59. package/dist/cli/index.js +39 -21
  60. package/dist/cli/index.js.map +1 -1
  61. package/dist/docs/api-reference/auth.md +23 -0
  62. package/dist/docs/api-reference/collection.md +44 -1
  63. package/dist/docs/api-reference/compose.md +1 -1
  64. package/dist/docs/api-reference/db.md +8 -0
  65. package/dist/docs/api-reference/ignite.md +13 -1
  66. package/dist/docs/api-reference/testing.md +26 -0
  67. package/dist/docs/api-reference/types.md +99 -0
  68. package/dist/docs/cli/add.md +2 -2
  69. package/dist/docs/cli/db.md +2 -2
  70. package/dist/docs/core-concepts/background-tasks.md +6 -3
  71. package/dist/docs/core-concepts/file-based-routing.md +2 -0
  72. package/dist/docs/core-concepts/middleware.md +2 -2
  73. package/dist/docs/getting-started/index.md +6 -1
  74. package/dist/docs/guides/authentication.md +33 -0
  75. package/dist/docs/guides/caching.md +34 -1
  76. package/dist/docs/guides/database.md +17 -0
  77. package/dist/docs/guides/environment-variables.md +6 -0
  78. package/dist/docs/guides/feature-matrix.md +58 -0
  79. package/dist/docs/guides/generated-portals.md +3 -1
  80. package/dist/docs/guides/logging.md +17 -0
  81. package/dist/docs/guides/migrations.md +26 -3
  82. package/dist/docs/guides/testing.md +31 -0
  83. package/dist/docs/guides/which-api.md +2 -2
  84. package/dist/docs/index.md +4 -1
  85. package/dist/docs/skills/SKILL.md +5 -1
  86. package/dist/docs/skills/api-surface.md +25 -4
  87. package/dist/docs/skills/auth-internals.md +14 -1
  88. package/dist/docs/skills/pre-flight.md +6 -0
  89. package/dist/docs/skills/routing-rules.md +1 -1
  90. package/dist/docs/skills/tasks-internals.md +4 -3
  91. package/dist/docs/skills/what-not-to-invent.md +13 -4
  92. package/dist/docs/versioning.md +1 -1
  93. package/dist/index.cjs +135 -255
  94. package/dist/index.cjs.map +1 -1
  95. package/dist/index.d.cts +228 -3
  96. package/dist/index.d.ts +228 -3
  97. package/dist/index.js +96 -217
  98. package/dist/index.js.map +1 -1
  99. package/dist/pgboss-backend-4X2YT4RB.js +14 -0
  100. package/dist/pgboss-backend-UXQ3O2WT.cjs +15 -0
  101. package/dist/pgboss-backend-UXQ3O2WT.cjs.map +1 -0
  102. package/dist/registry/index.json +39 -3
  103. package/dist/registry/js-mongo/account-security.json +1 -1
  104. package/dist/registry/js-mongo/admin-users.json +1 -1
  105. package/dist/registry/js-mongo/auth.json +1 -1
  106. package/dist/registry/js-mongo/auth@apple.json +1 -1
  107. package/dist/registry/js-mongo/auth@google.json +1 -1
  108. package/dist/registry/js-mongo/forgot-password.json +1 -1
  109. package/dist/registry/js-mongo/user-profile.json +1 -1
  110. package/dist/registry/js-mongo-collection/_base.json +1 -0
  111. package/dist/registry/js-mongo-collection/account-security.json +1 -0
  112. package/dist/registry/js-mongo-collection/account-settings.json +1 -0
  113. package/dist/registry/js-mongo-collection/admin-admins.json +1 -0
  114. package/dist/registry/js-mongo-collection/admin-analytics.json +1 -0
  115. package/dist/registry/js-mongo-collection/admin-billing.json +1 -0
  116. package/dist/registry/js-mongo-collection/admin-content.json +1 -0
  117. package/dist/registry/js-mongo-collection/admin-logs.json +1 -0
  118. package/dist/registry/js-mongo-collection/admin-support.json +1 -0
  119. package/dist/registry/js-mongo-collection/admin-system.json +1 -0
  120. package/dist/registry/js-mongo-collection/admin-users.json +1 -0
  121. package/dist/registry/js-mongo-collection/admin.json +1 -0
  122. package/dist/registry/js-mongo-collection/auth.json +1 -0
  123. package/dist/registry/js-mongo-collection/auth@apple.json +1 -0
  124. package/dist/registry/js-mongo-collection/auth@google.json +1 -0
  125. package/dist/registry/js-mongo-collection/billing.json +1 -0
  126. package/dist/registry/js-mongo-collection/email-client.json +1 -0
  127. package/dist/registry/js-mongo-collection/email-verification.json +1 -0
  128. package/dist/registry/js-mongo-collection/files.json +1 -0
  129. package/dist/registry/js-mongo-collection/forgot-password.json +1 -0
  130. package/dist/registry/js-mongo-collection/notifications.json +1 -0
  131. package/dist/registry/js-mongo-collection/support.json +1 -0
  132. package/dist/registry/js-mongo-collection/user-profile.json +1 -0
  133. package/dist/registry/js-pg-model/account-security.json +1 -1
  134. package/dist/registry/js-pg-model/admin-users.json +1 -1
  135. package/dist/registry/js-pg-model/auth.json +1 -1
  136. package/dist/registry/js-pg-model/auth@apple.json +1 -1
  137. package/dist/registry/js-pg-model/auth@google.json +1 -1
  138. package/dist/registry/js-pg-model/forgot-password.json +1 -1
  139. package/dist/registry/js-pg-model/user-profile.json +1 -1
  140. package/dist/registry/js-pg-table/account-security.json +1 -1
  141. package/dist/registry/js-pg-table/admin-users.json +1 -1
  142. package/dist/registry/js-pg-table/auth.json +1 -1
  143. package/dist/registry/js-pg-table/auth@apple.json +1 -1
  144. package/dist/registry/js-pg-table/auth@google.json +1 -1
  145. package/dist/registry/js-pg-table/forgot-password.json +1 -1
  146. package/dist/registry/js-pg-table/user-profile.json +1 -1
  147. package/dist/registry/ts-mongo/account-security.json +1 -1
  148. package/dist/registry/ts-mongo/admin-users.json +1 -1
  149. package/dist/registry/ts-mongo/auth.json +1 -1
  150. package/dist/registry/ts-mongo/auth@apple.json +1 -1
  151. package/dist/registry/ts-mongo/auth@google.json +1 -1
  152. package/dist/registry/ts-mongo/forgot-password.json +1 -1
  153. package/dist/registry/ts-mongo/user-profile.json +1 -1
  154. package/dist/registry/ts-mongo-collection/_base.json +1 -0
  155. package/dist/registry/ts-mongo-collection/account-security.json +1 -0
  156. package/dist/registry/ts-mongo-collection/account-settings.json +1 -0
  157. package/dist/registry/ts-mongo-collection/admin-admins.json +1 -0
  158. package/dist/registry/ts-mongo-collection/admin-analytics.json +1 -0
  159. package/dist/registry/ts-mongo-collection/admin-billing.json +1 -0
  160. package/dist/registry/ts-mongo-collection/admin-content.json +1 -0
  161. package/dist/registry/ts-mongo-collection/admin-logs.json +1 -0
  162. package/dist/registry/ts-mongo-collection/admin-support.json +1 -0
  163. package/dist/registry/ts-mongo-collection/admin-system.json +1 -0
  164. package/dist/registry/ts-mongo-collection/admin-users.json +1 -0
  165. package/dist/registry/ts-mongo-collection/admin.json +1 -0
  166. package/dist/registry/ts-mongo-collection/auth.json +1 -0
  167. package/dist/registry/ts-mongo-collection/auth@apple.json +1 -0
  168. package/dist/registry/ts-mongo-collection/auth@google.json +1 -0
  169. package/dist/registry/ts-mongo-collection/billing.json +1 -0
  170. package/dist/registry/ts-mongo-collection/email-client.json +1 -0
  171. package/dist/registry/ts-mongo-collection/email-verification.json +1 -0
  172. package/dist/registry/ts-mongo-collection/files.json +1 -0
  173. package/dist/registry/ts-mongo-collection/forgot-password.json +1 -0
  174. package/dist/registry/ts-mongo-collection/notifications.json +1 -0
  175. package/dist/registry/ts-mongo-collection/support.json +1 -0
  176. package/dist/registry/ts-mongo-collection/user-profile.json +1 -0
  177. package/dist/registry/ts-pg-model/account-security.json +1 -1
  178. package/dist/registry/ts-pg-model/admin-users.json +1 -1
  179. package/dist/registry/ts-pg-model/auth.json +1 -1
  180. package/dist/registry/ts-pg-model/auth@apple.json +1 -1
  181. package/dist/registry/ts-pg-model/auth@google.json +1 -1
  182. package/dist/registry/ts-pg-model/forgot-password.json +1 -1
  183. package/dist/registry/ts-pg-model/user-profile.json +1 -1
  184. package/dist/registry/ts-pg-table/account-security.json +1 -1
  185. package/dist/registry/ts-pg-table/admin-users.json +1 -1
  186. package/dist/registry/ts-pg-table/auth.json +1 -1
  187. package/dist/registry/ts-pg-table/auth@apple.json +1 -1
  188. package/dist/registry/ts-pg-table/auth@google.json +1 -1
  189. package/dist/registry/ts-pg-table/forgot-password.json +1 -1
  190. package/dist/registry/ts-pg-table/user-profile.json +1 -1
  191. package/dist/tasks/index.cjs +5 -2
  192. package/dist/tasks/index.cjs.map +1 -1
  193. package/dist/tasks/index.d.cts +4 -2
  194. package/dist/tasks/index.d.ts +4 -2
  195. package/dist/tasks/index.js +3 -1
  196. package/dist/testing-cjs.cjs +5 -0
  197. package/dist/testing.cjs +59 -0
  198. package/dist/testing.cjs.map +1 -0
  199. package/dist/testing.d.cts +27 -0
  200. package/dist/testing.d.ts +27 -0
  201. package/dist/testing.js +58 -0
  202. package/dist/testing.js.map +1 -0
  203. package/dist/thread-runner.cjs +9 -0
  204. package/dist/thread-runner.cjs.map +1 -0
  205. package/dist/thread-runner.d.cts +3 -0
  206. package/dist/thread-runner.d.ts +3 -0
  207. package/dist/thread-runner.js +8 -0
  208. package/dist/thread-runner.js.map +1 -0
  209. package/dist/{types-DAsBKVM-.d.ts → types-CPMFTVXm.d.cts} +15 -1
  210. package/dist/{types-DAsBKVM-.d.cts → types-CPMFTVXm.d.ts} +15 -1
  211. package/package.json +6 -1
  212. package/dist/chunk-2SETEVMO.js.map +0 -1
  213. package/dist/chunk-73XJUT2S.js.map +0 -1
  214. package/dist/chunk-7YEX4MQV.cjs.map +0 -1
  215. package/dist/chunk-BBSZLGZW.js.map +0 -1
  216. package/dist/chunk-DUADUR6R.cjs.map +0 -1
  217. package/dist/chunk-HBYSKULC.js.map +0 -1
  218. package/dist/chunk-LJNSJFOL.js +0 -38
  219. package/dist/chunk-LJNSJFOL.js.map +0 -1
  220. package/dist/chunk-OFA7OGN5.js.map +0 -1
  221. package/dist/chunk-QL6EWT4B.cjs.map +0 -1
  222. package/dist/chunk-RGT4ZVHL.cjs.map +0 -1
  223. package/dist/chunk-TI24L4XE.cjs.map +0 -1
  224. package/dist/chunk-TYCYYLLM.cjs.map +0 -1
  225. package/dist/chunk-ULWNHN6P.js.map +0 -1
  226. package/dist/chunk-VWSUQKCJ.cjs.map +0 -1
  227. package/dist/pgboss-backend-DSO3QTNK.cjs +0 -14
  228. package/dist/pgboss-backend-DSO3QTNK.cjs.map +0 -1
  229. package/dist/pgboss-backend-I6DFUNRM.js +0 -14
  230. /package/dist/{chunk-NI2BNGGV.js.map → chunk-5LPRKZPB.js.map} +0 -0
  231. /package/dist/{chunk-45BWAR6P.js.map → chunk-C2FOZ7ME.js.map} +0 -0
  232. /package/dist/{chunk-7ZESZG3J.js.map → chunk-MUVO7MGS.js.map} +0 -0
  233. /package/dist/{pgboss-backend-I6DFUNRM.js.map → pgboss-backend-4X2YT4RB.js.map} +0 -0
@@ -16,10 +16,11 @@
16
16
 
17
17
 
18
18
 
19
+ var _chunkIUZ6A7PBcjs = require('./chunk-IUZ6A7PB.cjs');
19
20
 
20
21
 
21
- var _chunkTYCYYLLMcjs = require('./chunk-TYCYYLLM.cjs');
22
22
 
23
+ var _chunkAGOYTFROcjs = require('./chunk-AGOYTFRO.cjs');
23
24
 
24
25
 
25
26
 
@@ -27,17 +28,18 @@ var _chunkTYCYYLLMcjs = require('./chunk-TYCYYLLM.cjs');
27
28
 
28
29
 
29
30
 
30
- var _chunkDUADUR6Rcjs = require('./chunk-DUADUR6R.cjs');
31
+
32
+ var _chunkJP36TLL4cjs = require('./chunk-JP36TLL4.cjs');
31
33
 
32
34
  // src/db/mongo-model.ts
33
35
  var mongoosePromise;
34
36
  function loadMongoose() {
35
37
  mongoosePromise ??= Promise.resolve().then(() => _interopRequireWildcard(require("mongoose"))).then((mod) => _nullishCoalesce(mod.default, () => ( mod))).then((mg) => {
36
- _chunkDUADUR6Rcjs.whenQueryTracking.call(void 0, () => mg.set("debug", _chunkDUADUR6Rcjs.countStatement));
38
+ _chunkJP36TLL4cjs.whenQueryTracking.call(void 0, () => mg.set("debug", _chunkJP36TLL4cjs.countStatement));
37
39
  return mg;
38
40
  }).catch((err) => {
39
41
  mongoosePromise = void 0;
40
- throw _chunkDUADUR6Rcjs.notInstalled.call(void 0, err, "mongoose", "npm install mongoose");
42
+ throw _chunkJP36TLL4cjs.notInstalled.call(void 0, err, "mongoose", "npm install mongoose");
41
43
  });
42
44
  return mongoosePromise;
43
45
  }
@@ -86,7 +88,7 @@ function rules(node, mg) {
86
88
  if (d.unique !== void 0) entry["unique"] = d.unique;
87
89
  if (d.index !== void 0) entry["index"] = d.index;
88
90
  if (d.default !== void 0)
89
- entry["default"] = _chunkTYCYYLLMcjs.resolveDefault.call(void 0, d.default, () => new mg.Types.ObjectId());
91
+ entry["default"] = _chunkIUZ6A7PBcjs.resolveDefault.call(void 0, d.default, () => new mg.Types.ObjectId());
90
92
  if (d.enum !== void 0) entry["enum"] = d.enum;
91
93
  if (d.min !== void 0) entry["min"] = d.min;
92
94
  if (d.max !== void 0) entry["max"] = d.max;
@@ -160,7 +162,7 @@ function normalise(value) {
160
162
  function translateError(model, err) {
161
163
  const e = err;
162
164
  if (_optionalChain([e, 'optionalAccess', _ => _.name]) === "ValidationError" && e.errors) {
163
- throw new (0, _chunkTYCYYLLMcjs.ModelValidationError)(
165
+ throw new (0, _chunkIUZ6A7PBcjs.ModelValidationError)(
164
166
  model,
165
167
  Object.entries(e.errors).map(([path, v]) => ({
166
168
  path,
@@ -172,13 +174,13 @@ function translateError(model, err) {
172
174
  );
173
175
  }
174
176
  if (_optionalChain([e, 'optionalAccess', _2 => _2.name]) === "CastError") {
175
- throw new (0, _chunkTYCYYLLMcjs.ModelValidationError)(model, [
177
+ throw new (0, _chunkIUZ6A7PBcjs.ModelValidationError)(model, [
176
178
  { path: _nullishCoalesce(e.path, () => ( "")), message: _nullishCoalesce(e.message, () => ( "invalid value")) }
177
179
  ]);
178
180
  }
179
181
  if (_optionalChain([e, 'optionalAccess', _3 => _3.code]) === 11e3) {
180
182
  const field = _nullishCoalesce(Object.keys(_nullishCoalesce(e.keyValue, () => ( {})))[0], () => ( "field"));
181
- throw new (0, _chunkTYCYYLLMcjs.HttpError)(409, `${model} with this ${field} already exists`);
183
+ throw new (0, _chunkAGOYTFROcjs.HttpError)(409, `${model} with this ${field} already exists`);
182
184
  }
183
185
  throw err;
184
186
  }
@@ -204,14 +206,14 @@ function mapSort(sort) {
204
206
  }
205
207
  function mongoModel(name, tree, options) {
206
208
  let compiled;
207
- const model = () => compiled ??= _chunkDUADUR6Rcjs.untracked.call(void 0,
209
+ const model = () => compiled ??= _chunkJP36TLL4cjs.untracked.call(void 0,
208
210
  () => loadMongoose().then(async (mg) => {
209
211
  if (mg.models[name]) return mg.models[name];
210
212
  const schema = new mg.Schema(buildTree(tree, mg), {
211
213
  timestamps: _nullishCoalesce(options.timestamps, () => ( true)),
212
214
  // autoSync: false hands collection and index creation to migrations, on MongoDB too.
213
- autoIndex: _chunkTYCYYLLMcjs.isAutoSync.call(void 0, ),
214
- autoCreate: _chunkTYCYYLLMcjs.isAutoSync.call(void 0, ),
215
+ autoIndex: _chunkIUZ6A7PBcjs.isAutoSync.call(void 0, ),
216
+ autoCreate: _chunkIUZ6A7PBcjs.isAutoSync.call(void 0, ),
215
217
  ...options.collection !== void 0 && { collection: options.collection }
216
218
  });
217
219
  for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
@@ -226,7 +228,7 @@ function mongoModel(name, tree, options) {
226
228
  }
227
229
  });
228
230
  }
229
- const sequences = _chunkTYCYYLLMcjs.sequenceFields.call(void 0, name, tree);
231
+ const sequences = _chunkIUZ6A7PBcjs.sequenceFields.call(void 0, name, tree);
230
232
  if (sequences.length > 0) {
231
233
  schema.pre("validate", async function() {
232
234
  if (!this.isNew) return;
@@ -236,9 +238,9 @@ function mongoModel(name, tree, options) {
236
238
  });
237
239
  }
238
240
  const M = mg.model(name, schema);
239
- if (_chunkTYCYYLLMcjs.isAutoSync.call(void 0, )) {
241
+ if (_chunkIUZ6A7PBcjs.isAutoSync.call(void 0, )) {
240
242
  await M.init().catch((err) => {
241
- _chunkDUADUR6Rcjs.getLogger.call(void 0, ).warn(
243
+ _chunkJP36TLL4cjs.getLogger.call(void 0, ).warn(
242
244
  { model: name, err: err.message },
243
245
  `${name}: could not build its indexes \u2014 fix the data, then run efc db sync`
244
246
  );
@@ -248,7 +250,7 @@ function mongoModel(name, tree, options) {
248
250
  })
249
251
  );
250
252
  const session = () => {
251
- const tx = _chunkTYCYYLLMcjs.currentTx.call(void 0, );
253
+ const tx = _chunkIUZ6A7PBcjs.currentTx.call(void 0, );
252
254
  return _optionalChain([tx, 'optionalAccess', _5 => _5.engine]) === "mongodb" ? { session: tx.session } : {};
253
255
  };
254
256
  const applyQueryOptions = (q2, opts) => {
@@ -382,7 +384,7 @@ function mongoModel(name, tree, options) {
382
384
  }),
383
385
  raw: () => model(),
384
386
  async sync(opts) {
385
- if (_chunkTYCYYLLMcjs.isSyncSuppressed.call(void 0, )) return [];
387
+ if (_chunkIUZ6A7PBcjs.isSyncSuppressed.call(void 0, )) return [];
386
388
  const M = await model();
387
389
  const changes = [];
388
390
  const exists = (await M.db.db.listCollections({ name: M.collection.collectionName }).toArray()).length > 0;
@@ -480,7 +482,7 @@ async function connectMongo(url, pool = {}) {
480
482
  }).catch((err) => {
481
483
  throw explainMongoError(err, url);
482
484
  });
483
- _chunkDUADUR6Rcjs.getLogger.call(void 0, ).info("MongoDB connected");
485
+ _chunkJP36TLL4cjs.getLogger.call(void 0, ).info("MongoDB connected");
484
486
  return mg.connection;
485
487
  }
486
488
  function explainMongoError(err, url) {
@@ -506,7 +508,7 @@ function explainMongoError(err, url) {
506
508
 
507
509
  // src/db/pg-model.ts
508
510
  function pgModel(name, tree, options) {
509
- const tbl = _chunkTYCYYLLMcjs.pgTable.call(void 0, name, tree, options, { native: false, api: "defineModel" });
511
+ const tbl = _chunkIUZ6A7PBcjs.pgTable.call(void 0, name, tree, options, { native: false, api: "defineModel" });
510
512
  const { columns, ts, refs, ready, compile, client, columnFor, toDb, fromRow, validate, guard } = tbl;
511
513
  const kindOf = (field) => _optionalChain([columns, 'access', _15 => _15.get, 'call', _16 => _16(field), 'optionalAccess', _17 => _17.kind]);
512
514
  function missingField(sql, cond) {
@@ -606,7 +608,7 @@ function pgModel(name, tree, options) {
606
608
  break;
607
609
  }
608
610
  default:
609
- throw new (0, _chunkTYCYYLLMcjs.ModelValidationError)(name, [
611
+ throw new (0, _chunkIUZ6A7PBcjs.ModelValidationError)(name, [
610
612
  { path, message: `operator ${op} is not supported on PostgreSQL` }
611
613
  ]);
612
614
  }
@@ -637,8 +639,8 @@ function pgModel(name, tree, options) {
637
639
  for (const path of Array.isArray(paths) ? paths : [paths]) {
638
640
  const ref = refs.get(path);
639
641
  if (!ref)
640
- throw new (0, _chunkTYCYYLLMcjs.ModelValidationError)(name, [{ path, message: "is not a populatable ref field" }]);
641
- const target = _chunkTYCYYLLMcjs.getRegisteredModel.call(void 0, ref.model);
642
+ throw new (0, _chunkIUZ6A7PBcjs.ModelValidationError)(name, [{ path, message: "is not a populatable ref field" }]);
643
+ const target = _chunkIUZ6A7PBcjs.getRegisteredModel.call(void 0, ref.model);
642
644
  if (!target) throw new Error(`[EFC] populate: model "${ref.model}" is not defined`);
643
645
  const ids = [
644
646
  ...new Set(
@@ -681,7 +683,7 @@ function pgModel(name, tree, options) {
681
683
  return populate(rows, _optionalChain([opts, 'optionalAccess', _22 => _22.populate]));
682
684
  }
683
685
  const strictUpdate = (update) => {
684
- const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || _chunkTYCYYLLMcjs.nodeAt.call(void 0, tree, path.split(".")) !== void 0);
686
+ const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || _chunkIUZ6A7PBcjs.nodeAt.call(void 0, tree, path.split(".")) !== void 0);
685
687
  const out = {};
686
688
  for (const [k, v] of Object.entries(update)) {
687
689
  if (k.startsWith("$") && v !== null && typeof v === "object") {
@@ -696,7 +698,7 @@ function pgModel(name, tree, options) {
696
698
  const ops = update;
697
699
  for (const op of Object.keys(update).filter((k) => k.startsWith("$"))) {
698
700
  if (!["$set", "$unset", "$inc", "$push", "$pull"].includes(op)) {
699
- throw new (0, _chunkTYCYYLLMcjs.ModelValidationError)(name, [
701
+ throw new (0, _chunkIUZ6A7PBcjs.ModelValidationError)(name, [
700
702
  { path: op, message: "update operator is not supported on PostgreSQL" }
701
703
  ]);
702
704
  }
@@ -709,25 +711,25 @@ function pgModel(name, tree, options) {
709
711
  for (const [k, v] of Object.entries($set)) if (!k.includes(".")) topLevel[k] = v;
710
712
  for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) if (!k.includes(".")) topLevel[k] = null;
711
713
  for (const [k, v] of Object.entries($set))
712
- if (k.includes(".")) await _chunkTYCYYLLMcjs.validateAtPath.call(void 0, tree, k, v, issues);
714
+ if (k.includes(".")) await _chunkIUZ6A7PBcjs.validateAtPath.call(void 0, tree, k, v, issues);
713
715
  for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) {
714
- if (k.includes(".")) await _chunkTYCYYLLMcjs.validateAtPath.call(void 0, tree, k, null, issues);
716
+ if (k.includes(".")) await _chunkIUZ6A7PBcjs.validateAtPath.call(void 0, tree, k, null, issues);
715
717
  }
716
718
  for (const [k, by] of Object.entries(_nullishCoalesce(ops["$inc"], () => ( {})))) {
717
719
  if (typeof by !== "number") issues.push({ path: k, message: "$inc needs a number" });
718
- const node = k.includes(".") ? _chunkTYCYYLLMcjs.nodeAt.call(void 0, tree, k.split(".")) : tree[k];
720
+ const node = k.includes(".") ? _chunkIUZ6A7PBcjs.nodeAt.call(void 0, tree, k.split(".")) : tree[k];
719
721
  if (node && !(node.kind === "scalar" && node.type === "number") && node.kind !== "json") {
720
722
  issues.push({ path: k, message: "$inc only applies to number fields" });
721
723
  }
722
724
  }
723
- if (issues.length) throw new (0, _chunkTYCYYLLMcjs.ModelValidationError)(name, issues);
725
+ if (issues.length) throw new (0, _chunkIUZ6A7PBcjs.ModelValidationError)(name, issues);
724
726
  await validate(topLevel, true);
725
727
  const set = {};
726
728
  const nested = /* @__PURE__ */ new Map();
727
729
  const touchedTop = /* @__PURE__ */ new Set();
728
730
  const acc = (field) => _nullishCoalesce(nested.get(field), () => ( columnFor(t, field)));
729
731
  const conflict = (path) => {
730
- throw new (0, _chunkTYCYYLLMcjs.ModelValidationError)(name, [{ path, message: "conflicting update paths" }]);
732
+ throw new (0, _chunkIUZ6A7PBcjs.ModelValidationError)(name, [{ path, message: "conflicting update paths" }]);
731
733
  };
732
734
  const top = (field, value) => {
733
735
  if (touchedTop.has(field) || nested.has(field)) conflict(field);
@@ -898,7 +900,7 @@ function defineModel(name, schema, options) {
898
900
  return createModel(name, schema, _nullishCoalesce(options, () => ( {})));
899
901
  }
900
902
  function distinctFields(tree, options) {
901
- const ts = _chunkTYCYYLLMcjs.timestampFields.call(void 0, options);
903
+ const ts = _chunkIUZ6A7PBcjs.timestampFields.call(void 0, options);
902
904
  const fields = /* @__PURE__ */ new Set(["id", ...Object.values(ts)]);
903
905
  for (const [key, node] of Object.entries(tree)) if (node.kind === "scalar") fields.add(key);
904
906
  return fields;
@@ -923,11 +925,11 @@ var MODEL_OPS = [
923
925
  ];
924
926
  var sortKey = (v) => v instanceof Date ? v.getTime() : v;
925
927
  function createModel(name, schema, options, native) {
926
- const tree = _chunkTYCYYLLMcjs.normalizeSchema.call(void 0, schema, "model", name);
928
+ const tree = _chunkIUZ6A7PBcjs.normalizeSchema.call(void 0, schema, "model", name);
927
929
  let engineModel;
928
930
  const impl = () => {
929
931
  if (engineModel) return engineModel;
930
- const engine = _chunkTYCYYLLMcjs.getDbEngine.call(void 0, );
932
+ const engine = _chunkIUZ6A7PBcjs.getDbEngine.call(void 0, );
931
933
  if (native && native.engine !== engine) {
932
934
  throw new Error(
933
935
  `[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`
@@ -969,7 +971,7 @@ function createModel(name, schema, options, native) {
969
971
  try {
970
972
  return await m.create(create);
971
973
  } catch (err) {
972
- if (_chunkTYCYYLLMcjs.isHttpError.call(void 0, err) && err.statusCode === 409 && !_chunkTYCYYLLMcjs.currentTx.call(void 0, )) {
974
+ if (_chunkAGOYTFROcjs.isHttpError.call(void 0, err) && err.statusCode === 409 && !_chunkIUZ6A7PBcjs.currentTx.call(void 0, )) {
973
975
  const retried = await m.updateOne(filter, update);
974
976
  if (retried) return retried;
975
977
  }
@@ -985,26 +987,32 @@ function createModel(name, schema, options, native) {
985
987
  sync: (opts) => call((m) => m.sync(opts)),
986
988
  drop: () => call((m) => m.drop())
987
989
  };
988
- _chunkDUADUR6Rcjs.traceOps.call(void 0, name, model, MODEL_OPS);
989
- _chunkTYCYYLLMcjs.registerModel.call(void 0, {
990
+ _chunkJP36TLL4cjs.traceOps.call(void 0, name, model, MODEL_OPS);
991
+ _chunkIUZ6A7PBcjs.registerModel.call(void 0, {
990
992
  name,
991
993
  sync: model.sync,
992
994
  plan: (opts) => call((m) => m.plan(opts)),
993
995
  drop: model.drop,
994
996
  findByIds: (ids) => model.find({ id: { $in: ids } }),
995
- pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => ( _chunkTYCYYLLMcjs.tableNameFor.call(void 0, name))), idKind: "uuid" })
997
+ pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => ( _chunkIUZ6A7PBcjs.tableNameFor.call(void 0, name))), idKind: "uuid" }),
998
+ studio: {
999
+ storage: async () => _chunkIUZ6A7PBcjs.getDbEngine.call(void 0, ) === "mongodb" ? (await model.raw()).collection.collectionName : _nullishCoalesce(options.collection, () => ( _chunkIUZ6A7PBcjs.tableNameFor.call(void 0, name))),
1000
+ create: (data) => model.create(data),
1001
+ update: (id, data) => model.update(id, data),
1002
+ delete: (id) => model.delete(id)
1003
+ }
996
1004
  });
997
1005
  return model;
998
1006
  }
999
1007
 
1000
1008
  // src/db/transaction.ts
1001
1009
  async function transaction(fn) {
1002
- if (_chunkTYCYYLLMcjs.currentTx.call(void 0, )) return fn();
1003
- if (_chunkTYCYYLLMcjs.getDbEngine.call(void 0, ) === "postgresql") {
1010
+ if (_chunkIUZ6A7PBcjs.currentTx.call(void 0, )) return fn();
1011
+ if (_chunkIUZ6A7PBcjs.getDbEngine.call(void 0, ) === "postgresql") {
1004
1012
  let result;
1005
1013
  const afterCommit = [];
1006
- await _chunkDUADUR6Rcjs.getOrm.call(void 0, ).transaction(async (tx) => {
1007
- result = await _chunkTYCYYLLMcjs.runInTx.call(void 0, { engine: "postgresql", tx, afterCommit }, fn);
1014
+ await _chunkJP36TLL4cjs.getOrm.call(void 0, ).transaction(async (tx) => {
1015
+ result = await _chunkIUZ6A7PBcjs.runInTx.call(void 0, { engine: "postgresql", tx, afterCommit }, fn);
1008
1016
  });
1009
1017
  for (const run of afterCommit) run();
1010
1018
  return result;
@@ -1014,7 +1022,7 @@ async function transaction(fn) {
1014
1022
  try {
1015
1023
  let result;
1016
1024
  await session.withTransaction(async () => {
1017
- result = await _chunkTYCYYLLMcjs.runInTx.call(void 0, { engine: "mongodb", session }, fn);
1025
+ result = await _chunkIUZ6A7PBcjs.runInTx.call(void 0, { engine: "mongodb", session }, fn);
1018
1026
  });
1019
1027
  return result;
1020
1028
  } finally {
@@ -1060,8 +1068,8 @@ var TableRuntime = (_class = class {
1060
1068
  constructor(name, schema, options) {;_class.prototype.__init.call(this);
1061
1069
  this.name = name;
1062
1070
  this.options = options;
1063
- const tree = _chunkTYCYYLLMcjs.normalizeSchema.call(void 0, schema, "table", name);
1064
- this.tbl = _chunkTYCYYLLMcjs.pgTable.call(void 0, name, tree, options, { native: true, api: "defineTable" });
1071
+ const tree = _chunkIUZ6A7PBcjs.normalizeSchema.call(void 0, schema, "table", name);
1072
+ this.tbl = _chunkIUZ6A7PBcjs.pgTable.call(void 0, name, tree, options, { native: true, api: "defineTable" });
1065
1073
  this.uniqueSets = [["id"]];
1066
1074
  for (const spec of this.tbl.columns.values()) {
1067
1075
  if (_optionalChain([spec, 'access', _25 => _25.node, 'optionalAccess', _26 => _26.def, 'access', _27 => _27.unique])) this.uniqueSets.push([spec.field]);
@@ -1088,7 +1096,7 @@ var TableRuntime = (_class = class {
1088
1096
  /** Many-to-many fields as list columns, so filters and projections treat them alike. */
1089
1097
  __init() {this.joinSpecs = /* @__PURE__ */ new Map()}
1090
1098
  fail(path, message) {
1091
- throw new (0, _chunkTYCYYLLMcjs.ModelValidationError)(this.name, [{ path, message }]);
1099
+ throw new (0, _chunkIUZ6A7PBcjs.ModelValidationError)(this.name, [{ path, message }]);
1092
1100
  }
1093
1101
  spec(field) {
1094
1102
  return _nullishCoalesce(this.tbl.columns.get(field), () => ( this.joinSpecs.get(field)));
@@ -1099,18 +1107,18 @@ var TableRuntime = (_class = class {
1099
1107
  /** A many-to-many field's ids, in order, for the row `owner` (a table name or alias). */
1100
1108
  joinExpr(sql, join, owner) {
1101
1109
  return sql.raw(
1102
- `coalesce((select array_agg(efc_j.ref_id order by efc_j.position) from ${_chunkTYCYYLLMcjs.q.call(void 0, join.table)} efc_j where efc_j.owner_id = ${owner}.${_chunkTYCYYLLMcjs.q.call(void 0, "id")}), '{}'::${join.ddl})`
1110
+ `coalesce((select array_agg(efc_j.ref_id order by efc_j.position) from ${_chunkIUZ6A7PBcjs.q.call(void 0, join.table)} efc_j where efc_j.owner_id = ${owner}.${_chunkIUZ6A7PBcjs.q.call(void 0, "id")}), '{}'::${join.ddl})`
1103
1111
  );
1104
1112
  }
1105
1113
  col(sql, field, alias) {
1106
1114
  const join = this.join(field);
1107
- if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => ( _chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table))));
1115
+ if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => ( _chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table))));
1108
1116
  const spec = this.spec(field);
1109
- return sql.raw(alias ? `${alias}.${_chunkTYCYYLLMcjs.q.call(void 0, spec.column)}` : _chunkTYCYYLLMcjs.q.call(void 0, spec.column));
1117
+ return sql.raw(alias ? `${alias}.${_chunkIUZ6A7PBcjs.q.call(void 0, spec.column)}` : _chunkIUZ6A7PBcjs.q.call(void 0, spec.column));
1110
1118
  }
1111
1119
  /** SELECT items for the many-to-many fields among `fields`, as text arrays. */
1112
1120
  joinColumns(sql, fields, owner) {
1113
- return fields.filter((f) => this.join(f)).map((f) => sql`${this.col(sql, f, owner)}::text[] as ${sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, relAlias(f)))}`);
1121
+ return fields.filter((f) => this.join(f)).map((f) => sql`${this.col(sql, f, owner)}::text[] as ${sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, relAlias(f)))}`);
1114
1122
  }
1115
1123
  /** `col` for SELECT lists: many-to-many fields come back as text arrays under an alias. */
1116
1124
  selectCols(sql, fields, owner) {
@@ -1402,7 +1410,7 @@ var TableRuntime = (_class = class {
1402
1410
  if (args["cursor"]) {
1403
1411
  this.uniqueKey(args["cursor"], "cursor");
1404
1412
  const cw = this.where(sql, t, args["cursor"]);
1405
- const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table))} where ${cw})`;
1413
+ const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table))} where ${cw})`;
1406
1414
  const ors = [];
1407
1415
  const same = (o) => sql`${this.col(sql, o.field)} is not distinct from ${at(o.field)}`;
1408
1416
  for (let i = 0; i < order.length; i++) {
@@ -1415,7 +1423,7 @@ var TableRuntime = (_class = class {
1415
1423
  ors.push(eqs.length ? sql`(${sql.join([...eqs, after], sql` and `)})` : after);
1416
1424
  }
1417
1425
  ors.push(sql`(${sql.join(order.map(same), sql` and `)})`);
1418
- parts.push(sql`exists (select 1 from ${sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table))} where ${cw})`);
1426
+ parts.push(sql`exists (select 1 from ${sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table))} where ${cw})`);
1419
1427
  parts.push(sql`(${sql.join(ors, sql` or `)})`);
1420
1428
  }
1421
1429
  return parts.length ? sql.join(parts, sql` and `) : sql`true`;
@@ -1440,7 +1448,7 @@ var TableRuntime = (_class = class {
1440
1448
  const offset = args["skip"] ? sql` offset ${sql.param(args["skip"])}` : sql``;
1441
1449
  const orderBy = order.length ? sql` order by ${this.orderSql(sql, order)}` : sql``;
1442
1450
  const where = this.readWhere(sql, t, args, order);
1443
- const from = sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table));
1451
+ const from = sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table));
1444
1452
  const distinct = _optionalChain([args, 'access', _29 => _29["distinct"], 'optionalAccess', _30 => _30.filter, 'call', _31 => _31((f) => this.spec(f))]);
1445
1453
  if (_optionalChain([distinct, 'optionalAccess', _32 => _32.length])) {
1446
1454
  const dcols = sql.join(
@@ -1470,7 +1478,7 @@ var TableRuntime = (_class = class {
1470
1478
  distinct ? "efc_distinct" : void 0
1471
1479
  );
1472
1480
  const include = this.includeArg(args);
1473
- const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : _chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table), 1) : [];
1481
+ const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : _chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table), 1) : [];
1474
1482
  const { query, reversed } = this.readQuery(
1475
1483
  sql,
1476
1484
  t,
@@ -1545,7 +1553,7 @@ var TableRuntime = (_class = class {
1545
1553
  for (const [name, arg] of Object.entries(include)) {
1546
1554
  if (!arg) continue;
1547
1555
  const expr = await this.relationExpr(sql, this.relation(name), relArgs(arg), owner, depth);
1548
- out.push(sql`${expr} as ${sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, incAlias(name)))}`);
1556
+ out.push(sql`${expr} as ${sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, incAlias(name)))}`);
1549
1557
  }
1550
1558
  return out;
1551
1559
  }
@@ -1579,21 +1587,21 @@ var TableRuntime = (_class = class {
1579
1587
  */
1580
1588
  relationSource(rel, owner, a, j) {
1581
1589
  const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
1582
- const target = `${_chunkTYCYYLLMcjs.q.call(void 0, T.tbl.table)} ${a}`;
1583
- const ownerId = `${owner}.${_chunkTYCYYLLMcjs.q.call(void 0, "id")}`;
1590
+ const target = `${_chunkIUZ6A7PBcjs.q.call(void 0, T.tbl.table)} ${a}`;
1591
+ const ownerId = `${owner}.${_chunkIUZ6A7PBcjs.q.call(void 0, "id")}`;
1584
1592
  if (rel.via === "fk") {
1585
1593
  return {
1586
1594
  T,
1587
1595
  from: target,
1588
- cond: `${a}.${_chunkTYCYYLLMcjs.q.call(void 0, "id")} = ${owner}.${_chunkTYCYYLLMcjs.q.call(void 0, rel.column)}`,
1589
- defaultOrder: `${a}.${_chunkTYCYYLLMcjs.q.call(void 0, "id")}`
1596
+ cond: `${a}.${_chunkIUZ6A7PBcjs.q.call(void 0, "id")} = ${owner}.${_chunkIUZ6A7PBcjs.q.call(void 0, rel.column)}`,
1597
+ defaultOrder: `${a}.${_chunkIUZ6A7PBcjs.q.call(void 0, "id")}`
1590
1598
  };
1591
1599
  }
1592
1600
  let from;
1593
1601
  let cond;
1594
1602
  let defaultOrder;
1595
1603
  if (rel.via === "join") {
1596
- from = `${_chunkTYCYYLLMcjs.q.call(void 0, rel.join.table)} ${j} join ${target} on ${a}.${_chunkTYCYYLLMcjs.q.call(void 0, "id")} = ${j}.ref_id`;
1604
+ from = `${_chunkIUZ6A7PBcjs.q.call(void 0, rel.join.table)} ${j} join ${target} on ${a}.${_chunkIUZ6A7PBcjs.q.call(void 0, "id")} = ${j}.ref_id`;
1597
1605
  cond = `${j}.owner_id = ${ownerId}`;
1598
1606
  defaultOrder = `${j}.position`;
1599
1607
  } else {
@@ -1611,7 +1619,7 @@ var TableRuntime = (_class = class {
1611
1619
  `[EFC] ${this.name}.${rel.name}: ${rel.target}.${rel.foreignKey} is many-to-many \u2014 use hasMany`
1612
1620
  );
1613
1621
  }
1614
- from = `${_chunkTYCYYLLMcjs.q.call(void 0, join.table)} ${j} join ${target} on ${a}.${_chunkTYCYYLLMcjs.q.call(void 0, "id")} = ${j}.owner_id`;
1622
+ from = `${_chunkIUZ6A7PBcjs.q.call(void 0, join.table)} ${j} join ${target} on ${a}.${_chunkIUZ6A7PBcjs.q.call(void 0, "id")} = ${j}.owner_id`;
1615
1623
  cond = `${j}.ref_id = ${ownerId}`;
1616
1624
  } else {
1617
1625
  if (rel.kind === "one" && !column.node.def.unique) {
@@ -1620,9 +1628,9 @@ var TableRuntime = (_class = class {
1620
1628
  );
1621
1629
  }
1622
1630
  from = target;
1623
- cond = `${a}.${_chunkTYCYYLLMcjs.q.call(void 0, column.column)} = ${ownerId}`;
1631
+ cond = `${a}.${_chunkIUZ6A7PBcjs.q.call(void 0, column.column)} = ${ownerId}`;
1624
1632
  }
1625
- defaultOrder = `${a}.${_chunkTYCYYLLMcjs.q.call(void 0, "id")}`;
1633
+ defaultOrder = `${a}.${_chunkIUZ6A7PBcjs.q.call(void 0, "id")}`;
1626
1634
  }
1627
1635
  return { T, from, cond, defaultOrder };
1628
1636
  }
@@ -1647,7 +1655,7 @@ var TableRuntime = (_class = class {
1647
1655
  const where = isPlainObject(w) ? w : { id: w };
1648
1656
  const found = await T.findUnique({ where, select: { id: true } });
1649
1657
  if (!found) {
1650
- throw new (0, _chunkTYCYYLLMcjs.ModelValidationError)(this.name, [
1658
+ throw new (0, _chunkIUZ6A7PBcjs.ModelValidationError)(this.name, [
1651
1659
  { path, message: `no ${rel.target} matches ${JSON.stringify(where, idJson)}` }
1652
1660
  ]);
1653
1661
  }
@@ -1739,8 +1747,8 @@ var TableRuntime = (_class = class {
1739
1747
  try {
1740
1748
  await T.updateNested({ where: whereOf(w), data: { [fk]: owner } });
1741
1749
  } catch (err) {
1742
- if (_chunkTYCYYLLMcjs.isHttpError.call(void 0, err) && err.statusCode === 404) {
1743
- throw new (0, _chunkTYCYYLLMcjs.ModelValidationError)(this.name, [
1750
+ if (_chunkAGOYTFROcjs.isHttpError.call(void 0, err) && err.statusCode === 404) {
1751
+ throw new (0, _chunkIUZ6A7PBcjs.ModelValidationError)(this.name, [
1744
1752
  {
1745
1753
  path: key,
1746
1754
  message: `no ${rel.target} matches ${JSON.stringify(whereOf(w), idJson)}`
@@ -1891,7 +1899,7 @@ var TableRuntime = (_class = class {
1891
1899
  const a = `efc_f${++aliasSeq}`;
1892
1900
  const { T, from, cond } = this.relationSource(
1893
1901
  rel,
1894
- _nullishCoalesce(owner, () => ( _chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table))),
1902
+ _nullishCoalesce(owner, () => ( _chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table))),
1895
1903
  a,
1896
1904
  `efc_fj${aliasSeq}`
1897
1905
  );
@@ -2032,7 +2040,7 @@ var TableRuntime = (_class = class {
2032
2040
  }
2033
2041
  async orThrow(p) {
2034
2042
  const r = await p;
2035
- if (r === null) throw new (0, _chunkTYCYYLLMcjs.HttpError)(404, `${this.name} not found`);
2043
+ if (r === null) throw new (0, _chunkAGOYTFROcjs.HttpError)(404, `${this.name} not found`);
2036
2044
  return r;
2037
2045
  }
2038
2046
  async count(args = {}) {
@@ -2042,7 +2050,7 @@ var TableRuntime = (_class = class {
2042
2050
  const counted = select ? Object.entries(select).filter(([f, on]) => on && (f === "_all" || this.spec(f))) : [["_all", true]];
2043
2051
  const exprs = sql.join(
2044
2052
  counted.map(
2045
- ([f]) => f === "_all" ? sql`count(*)::int as ${sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, "_all"))}` : sql`count(${this.col(sql, f, "efc_rows")})::int as ${sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, f))}`
2053
+ ([f]) => f === "_all" ? sql`count(*)::int as ${sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, "_all"))}` : sql`count(${this.col(sql, f, "efc_rows")})::int as ${sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, f))}`
2046
2054
  ),
2047
2055
  sql`, `
2048
2056
  );
@@ -2117,7 +2125,7 @@ var TableRuntime = (_class = class {
2117
2125
  const specs = this.aggregateSpec(args);
2118
2126
  if (specs.length === 0) return {};
2119
2127
  const exprs = sql.join(
2120
- specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, s.alias))}`),
2128
+ specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, s.alias))}`),
2121
2129
  sql`, `
2122
2130
  );
2123
2131
  const { query } = this.readQuery(sql, t, { ...args, select: void 0 }, sql`*`);
@@ -2175,7 +2183,7 @@ var TableRuntime = (_class = class {
2175
2183
  [
2176
2184
  ...by.map((f) => this.col(sql, f)),
2177
2185
  ...specs.map(
2178
- (s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, s.alias))}`
2186
+ (s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, s.alias))}`
2179
2187
  )
2180
2188
  ],
2181
2189
  sql`, `
@@ -2199,7 +2207,7 @@ var TableRuntime = (_class = class {
2199
2207
  }
2200
2208
  }
2201
2209
  }
2202
- const query = sql`select ${select} from ${sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table))}${where ? sql` where ${where}` : sql``} group by ${sql.join(
2210
+ const query = sql`select ${select} from ${sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table))}${where ? sql` where ${where}` : sql``} group by ${sql.join(
2203
2211
  by.map((f) => this.col(sql, f)),
2204
2212
  sql`, `
2205
2213
  )}${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``}`;
@@ -2277,7 +2285,7 @@ var TableRuntime = (_class = class {
2277
2285
  }
2278
2286
  }
2279
2287
  }
2280
- if (issues.length) throw new (0, _chunkTYCYYLLMcjs.ModelValidationError)(this.name, issues);
2288
+ if (issues.length) throw new (0, _chunkIUZ6A7PBcjs.ModelValidationError)(this.name, issues);
2281
2289
  await this.tbl.validate(plain, true);
2282
2290
  for (const [field, v] of Object.entries(plain)) {
2283
2291
  sets.push(
@@ -2319,7 +2327,7 @@ var TableRuntime = (_class = class {
2319
2327
  }
2320
2328
  for (const [field, entries] of byField) {
2321
2329
  const join = this.join(field);
2322
- const jt = sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, join.table));
2330
+ const jt = sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, join.table));
2323
2331
  const sets = entries.filter((e) => e.op.mode === "set");
2324
2332
  if (sets.length) {
2325
2333
  const owners2 = sets.map((e) => idText(e.id));
@@ -2366,7 +2374,7 @@ var TableRuntime = (_class = class {
2366
2374
  const idDdl = this.tbl.columns.get("id").ddl;
2367
2375
  const owners = sql`${sql.param(ids.map(idText))}::${sql.raw(idDdl)}[]`;
2368
2376
  const parts = joins.map(
2369
- (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(_chunkTYCYYLLMcjs.q.call(void 0, j.table))} where owner_id = any(${owners}) group by owner_id`
2377
+ (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(_chunkIUZ6A7PBcjs.q.call(void 0, j.table))} where owner_id = any(${owners}) group by owner_id`
2370
2378
  );
2371
2379
  const { rows } = await this.exec(sql.join(parts, sql` union all `));
2372
2380
  for (const j of joins) out.set(j.field, /* @__PURE__ */ new Map());
@@ -2388,7 +2396,7 @@ var TableRuntime = (_class = class {
2388
2396
  }
2389
2397
  insertSql(sql, t, rows) {
2390
2398
  const fields = [...new Set(rows.flatMap((r) => Object.keys(r)))];
2391
- const head = sql`insert into ${sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table))} (${sql.join(
2399
+ const head = sql`insert into ${sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table))} (${sql.join(
2392
2400
  fields.map((f) => this.col(sql, f)),
2393
2401
  sql`, `
2394
2402
  )})`;
@@ -2485,7 +2493,7 @@ var TableRuntime = (_class = class {
2485
2493
  return;
2486
2494
  }
2487
2495
  const { rows: ids } = await this.exec(
2488
- sql`select nextval(pg_get_serial_sequence(${sql.param(_chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table))}, 'id'))::text as id from generate_series(1, ${sql.param(missing.length)})`
2496
+ sql`select nextval(pg_get_serial_sequence(${sql.param(_chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table))}, 'id'))::text as id from generate_series(1, ${sql.param(missing.length)})`
2489
2497
  );
2490
2498
  missing.forEach((r, i) => {
2491
2499
  const id = ids[i]["id"];
@@ -2514,9 +2522,9 @@ var TableRuntime = (_class = class {
2514
2522
  const where = this.where(sql, t, args["where"]);
2515
2523
  const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
2516
2524
  const extra = links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``;
2517
- const query = sets.length ? sql`update ${sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *${extra}` : sql`select *${extra} from ${sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table))} where ${where} limit 1`;
2525
+ const query = sets.length ? sql`update ${sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *${extra}` : sql`select *${extra} from ${sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table))} where ${where} limit 1`;
2518
2526
  const [row] = (await this.exec(query)).rows;
2519
- if (!row) throw new (0, _chunkTYCYYLLMcjs.HttpError)(404, `${this.name} not found`);
2527
+ if (!row) throw new (0, _chunkAGOYTFROcjs.HttpError)(404, `${this.name} not found`);
2520
2528
  const record = this.fromRaw(t, row);
2521
2529
  await this.applyJoins(sql, [{ id: record["id"], ops: joinOps }]);
2522
2530
  await this.refreshJoins(sql, [record], joinOps);
@@ -2537,7 +2545,7 @@ var TableRuntime = (_class = class {
2537
2545
  const links = returning ? this.joinColumns(sql, [...this.tbl.joins.keys()]) : [];
2538
2546
  const list = returning ? sql` returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : joinOps.length ? sql` returning ${this.col(sql, "id")}` : sql``;
2539
2547
  const result = await this.exec(
2540
- sets.length ? sql`update ${sql.raw(_chunkTYCYYLLMcjs.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(_chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table))} where ${where}`
2548
+ sets.length ? sql`update ${sql.raw(_chunkIUZ6A7PBcjs.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(_chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table))} where ${where}`
2541
2549
  );
2542
2550
  const records = result.rows.map((r) => returning ? this.fromRaw(t, r) : r);
2543
2551
  await this.applyJoins(
@@ -2561,7 +2569,7 @@ var TableRuntime = (_class = class {
2561
2569
  if (row[f] === void 0) row[f] = this.tbl.toDb(f, args["where"][f]);
2562
2570
  }
2563
2571
  const { head, values } = this.insertSql(sql, t, [row]);
2564
- const table = _chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table);
2572
+ const table = _chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table);
2565
2573
  const update = await this.setList(sql, t, _nullishCoalesce(args["update"], () => ( {})), table);
2566
2574
  const { joinOps } = update;
2567
2575
  let { sets } = update;
@@ -2582,7 +2590,7 @@ var TableRuntime = (_class = class {
2582
2590
  const [out] = (await this.exec(
2583
2591
  sql`${head} values ${values} on conflict (${target}) do update set ${sql.join(sets, sql`, `)}${cond}${returning}`
2584
2592
  )).rows;
2585
- if (!out) throw new (0, _chunkTYCYYLLMcjs.HttpError)(404, `${this.name} not found`);
2593
+ if (!out) throw new (0, _chunkAGOYTFROcjs.HttpError)(404, `${this.name} not found`);
2586
2594
  const record = this.fromRaw(t, out);
2587
2595
  if (linked) {
2588
2596
  const ops = out["efc_inserted"] ? createOps.filter((o) => o.items.length) : joinOps;
@@ -2601,9 +2609,9 @@ var TableRuntime = (_class = class {
2601
2609
  const where = this.where(sql, t, args["where"]);
2602
2610
  const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
2603
2611
  const [row] = (await this.exec(
2604
- sql`delete from ${sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table))} where ${where} returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}`
2612
+ sql`delete from ${sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table))} where ${where} returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}`
2605
2613
  )).rows;
2606
- if (!row) throw new (0, _chunkTYCYYLLMcjs.HttpError)(404, `${this.name} not found`);
2614
+ if (!row) throw new (0, _chunkAGOYTFROcjs.HttpError)(404, `${this.name} not found`);
2607
2615
  return this.project(this.fromRaw(t, row), this.projection(args));
2608
2616
  });
2609
2617
  }
@@ -2611,7 +2619,7 @@ var TableRuntime = (_class = class {
2611
2619
  const { t, sql } = await this.ready(args["where"]);
2612
2620
  return this.tbl.guard(async () => {
2613
2621
  const where = _nullishCoalesce(this.where(sql, t, args["where"]), () => ( sql`true`));
2614
- const result = await this.tbl.client().execute(sql`delete from ${sql.raw(_chunkTYCYYLLMcjs.q.call(void 0, this.tbl.table))} where ${where}`);
2622
+ const result = await this.tbl.client().execute(sql`delete from ${sql.raw(_chunkIUZ6A7PBcjs.q.call(void 0, this.tbl.table))} where ${where}`);
2615
2623
  return { count: _nullishCoalesce(result.rowCount, () => ( 0)) };
2616
2624
  });
2617
2625
  }
@@ -2620,10 +2628,10 @@ function relArgs(arg) {
2620
2628
  return isPlainObject(arg) ? arg : {};
2621
2629
  }
2622
2630
  function runtimeOf(name, from) {
2623
- const runtime = _optionalChain([_chunkTYCYYLLMcjs.getRegisteredModel.call(void 0, name), 'optionalAccess', _65 => _65.tableRuntime, 'optionalCall', _66 => _66()]);
2631
+ const runtime = _optionalChain([_chunkIUZ6A7PBcjs.getRegisteredModel.call(void 0, name), 'optionalAccess', _65 => _65.tableRuntime, 'optionalCall', _66 => _66()]);
2624
2632
  if (!runtime) {
2625
2633
  throw new Error(
2626
- _chunkTYCYYLLMcjs.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`
2634
+ _chunkIUZ6A7PBcjs.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`
2627
2635
  );
2628
2636
  }
2629
2637
  return runtime;
@@ -2643,7 +2651,7 @@ var JSON_OPS = /* @__PURE__ */ new Set([
2643
2651
  "mode"
2644
2652
  ]);
2645
2653
  function createTable(name, schema, options = {}) {
2646
- _chunkTYCYYLLMcjs.normalizeSchema.call(void 0, schema, "table", name);
2654
+ _chunkIUZ6A7PBcjs.normalizeSchema.call(void 0, schema, "table", name);
2647
2655
  for (const [rel, def] of Object.entries(_nullishCoalesce(options.relations, () => ( {})))) {
2648
2656
  const where = `[EFC] ${name}.relations.${rel}`;
2649
2657
  if (rel in schema) throw new Error(`${where}: a field already has this name`);
@@ -2658,7 +2666,7 @@ function createTable(name, schema, options = {}) {
2658
2666
  }
2659
2667
  let runtime;
2660
2668
  const rt = () => {
2661
- const engine = _chunkTYCYYLLMcjs.getDbEngine.call(void 0, );
2669
+ const engine = _chunkIUZ6A7PBcjs.getDbEngine.call(void 0, );
2662
2670
  if (engine !== "postgresql") {
2663
2671
  throw new Error(
2664
2672
  `[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`
@@ -2690,19 +2698,28 @@ function createTable(name, schema, options = {}) {
2690
2698
  sync: (opts) => call((r) => r.tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _71 => _71.dryRun]), () => ( false)))),
2691
2699
  drop: () => call((r) => r.tbl.drop())
2692
2700
  };
2693
- _chunkDUADUR6Rcjs.traceOps.call(void 0,
2701
+ _chunkJP36TLL4cjs.traceOps.call(void 0,
2694
2702
  name,
2695
2703
  model,
2696
2704
  Object.keys(model).filter((op) => !["name", "raw", "sync", "drop"].includes(op))
2697
2705
  );
2698
- _chunkTYCYYLLMcjs.registerModel.call(void 0, {
2706
+ _chunkIUZ6A7PBcjs.registerModel.call(void 0, {
2699
2707
  name,
2700
2708
  sync: model.sync,
2701
2709
  plan: (opts) => call((r) => r.tbl.plan(opts)),
2702
2710
  drop: model.drop,
2703
2711
  findByIds: (ids) => model.findMany({ where: { id: { in: ids } } }),
2704
2712
  pgTarget: () => ({ table: rt().tbl.table, idKind: rt().tbl.idKind }),
2705
- tableRuntime: () => rt()
2713
+ tableRuntime: () => rt(),
2714
+ studio: /* @__PURE__ */ (() => {
2715
+ const idOf = (id) => rt().tbl.idKind === "serial" ? Number(id) : rt().tbl.idKind === "bigserial" ? BigInt(id) : id;
2716
+ return {
2717
+ storage: async () => rt().tbl.table,
2718
+ create: (data) => model.create({ data }),
2719
+ update: (id, data) => model.update({ where: { id: idOf(id) }, data }),
2720
+ delete: (id) => model.delete({ where: { id: idOf(id) } })
2721
+ };
2722
+ })()
2706
2723
  });
2707
2724
  return model;
2708
2725
  }
@@ -2710,6 +2727,129 @@ function defineTable(name, schema, options) {
2710
2727
  return createTable(name, schema, _nullishCoalesce(options, () => ( {})));
2711
2728
  }
2712
2729
 
2730
+ // src/db/pipeline.ts
2731
+ var Pipeline = class _Pipeline {
2732
+ /** @internal */
2733
+ constructor(run, stages = []) {
2734
+ this.run = run;
2735
+ this.stages = stages;
2736
+ }
2737
+
2738
+
2739
+ next(...stage) {
2740
+ return new _Pipeline(this.run, [...this.stages, ...stage]);
2741
+ }
2742
+ /** `$match` — same filter vocabulary as `find`. */
2743
+ match(filter) {
2744
+ return this.next({ $match: filter });
2745
+ }
2746
+ sort(spec) {
2747
+ return this.next({ $sort: spec });
2748
+ }
2749
+ skip(n) {
2750
+ return this.next({ $skip: n });
2751
+ }
2752
+ limit(n) {
2753
+ return this.next({ $limit: n });
2754
+ }
2755
+ /** `$sample` — `n` random records. */
2756
+ sample(n) {
2757
+ return this.next({ $sample: { size: n } });
2758
+ }
2759
+ /** `$project` with an inclusion spec: the result has only those fields (and `id`). */
2760
+ project(spec) {
2761
+ return this.next({ $project: spec });
2762
+ }
2763
+ /**
2764
+ * `$unwind` an array field: one result per element, the field holding that element.
2765
+ * `preserveNullAndEmptyArrays` keeps records without elements (the field is then null).
2766
+ */
2767
+ unwind(path, options) {
2768
+ return this.next(
2769
+ _optionalChain([options, 'optionalAccess', _72 => _72.preserveNullAndEmptyArrays]) ? { $unwind: { path, preserveNullAndEmptyArrays: true } } : { $unwind: path }
2770
+ );
2771
+ }
2772
+ /** `$group` — `_id` is `'$field'`, `null` or `{ key: '$field' }`; accumulators are typed. */
2773
+ group(spec) {
2774
+ return this.next({ $group: spec });
2775
+ }
2776
+ /** `$count` — a single `{ [field]: n }` (no result at all when nothing matched). */
2777
+ count(field) {
2778
+ return this.next({ $count: field });
2779
+ }
2780
+ /** `$addFields` / `$set` — say what the new fields are: `addFields<{ total: number }>({ … })`. */
2781
+ addFields(spec) {
2782
+ return this.next({ $addFields: spec });
2783
+ }
2784
+ lookup(a, b) {
2785
+ const idField = (f) => f === "id" ? "_id" : f;
2786
+ if (typeof a === "string") {
2787
+ const field = a;
2788
+ const target2 = b;
2789
+ const isArray = `__efc_isarr_${field.replace(/\./g, "_")}`;
2790
+ return this.next(async () => [
2791
+ { $set: { [isArray]: { $isArray: `$${field}` } } },
2792
+ {
2793
+ $lookup: {
2794
+ from: await collectionOf(target2),
2795
+ localField: field,
2796
+ foreignField: "_id",
2797
+ as: field
2798
+ }
2799
+ },
2800
+ {
2801
+ $set: {
2802
+ [field]: {
2803
+ $cond: [
2804
+ `$${isArray}`,
2805
+ `$${field}`,
2806
+ { $ifNull: [{ $arrayElemAt: [`$${field}`, 0] }, null] }
2807
+ ]
2808
+ }
2809
+ }
2810
+ },
2811
+ { $unset: isArray }
2812
+ ]);
2813
+ }
2814
+ const { from: target, localField, foreignField, as } = a;
2815
+ return this.next(async () => [
2816
+ {
2817
+ $lookup: {
2818
+ from: await collectionOf(target),
2819
+ localField: idField(localField),
2820
+ foreignField: idField(foreignField),
2821
+ as
2822
+ }
2823
+ }
2824
+ ]);
2825
+ }
2826
+ /** Any other stage, with its output type spelled out: `stage<{ … }>({ $facet: … })`. */
2827
+ stage(stage) {
2828
+ return this.next(stage);
2829
+ }
2830
+ /** The stages as plain objects (lookups resolved to collection names). */
2831
+ async toArray() {
2832
+ const out = [];
2833
+ for (const s of this.stages) {
2834
+ if (typeof s === "function") out.push(...await s());
2835
+ else out.push(s);
2836
+ }
2837
+ return out;
2838
+ }
2839
+ async exec() {
2840
+ return await this.run(await this.toArray());
2841
+ }
2842
+ then(onfulfilled, onrejected) {
2843
+ return this.exec().then(onfulfilled, onrejected);
2844
+ }
2845
+ };
2846
+ async function collectionOf(target) {
2847
+ const model = await target.raw();
2848
+ const name = _nullishCoalesce(_optionalChain([model, 'access', _73 => _73.collection, 'optionalAccess', _74 => _74.collectionName]), () => ( _optionalChain([model, 'access', _75 => _75.collection, 'optionalAccess', _76 => _76.name])));
2849
+ if (!name) throw new Error(`[EFC] lookup: can't find the collection behind ${target.name}`);
2850
+ return name;
2851
+ }
2852
+
2713
2853
  // src/db/collection-model.ts
2714
2854
  function fromBson(value) {
2715
2855
  if (Array.isArray(value)) return value.map(fromBson);
@@ -2769,7 +2909,7 @@ function mapBulkOp(op) {
2769
2909
  return { [kind]: b };
2770
2910
  }
2771
2911
  function createCollection(name, schema, options) {
2772
- const tree = _chunkTYCYYLLMcjs.normalizeSchema.call(void 0, schema, "collection", name);
2912
+ const tree = _chunkIUZ6A7PBcjs.normalizeSchema.call(void 0, schema, "collection", name);
2773
2913
  const base = mongoModel(name, tree, options);
2774
2914
  const longs = hasLong(tree);
2775
2915
  const toRecord = (doc) => {
@@ -2778,7 +2918,7 @@ function createCollection(name, schema, options) {
2778
2918
  return longs ? castTree(rec, tree) : rec;
2779
2919
  };
2780
2920
  const model = async () => {
2781
- const engine = _chunkTYCYYLLMcjs.getDbEngine.call(void 0, );
2921
+ const engine = _chunkIUZ6A7PBcjs.getDbEngine.call(void 0, );
2782
2922
  if (engine !== "mongodb") {
2783
2923
  throw new Error(
2784
2924
  `[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`
@@ -2787,13 +2927,33 @@ function createCollection(name, schema, options) {
2787
2927
  return await base.raw();
2788
2928
  };
2789
2929
  const session = () => {
2790
- const tx = _chunkTYCYYLLMcjs.currentTx.call(void 0, );
2791
- return _optionalChain([tx, 'optionalAccess', _72 => _72.engine]) === "mongodb" ? tx.session : null;
2930
+ const tx = _chunkIUZ6A7PBcjs.currentTx.call(void 0, );
2931
+ return _optionalChain([tx, 'optionalAccess', _77 => _77.engine]) === "mongodb" ? tx.session : null;
2792
2932
  };
2793
2933
  const sess = () => {
2794
2934
  const s = session();
2795
2935
  return s ? { session: s } : {};
2796
2936
  };
2937
+ const runPipeline = (stages) => guard(async (M) => {
2938
+ let sourceShape = true;
2939
+ const prepared = stages.map((stage) => {
2940
+ const [op] = Object.keys(stage);
2941
+ if (!sourceShape) return stage;
2942
+ if (op === "$match") {
2943
+ const filter = mapFilter(stage["$match"]);
2944
+ return { $match: M.find().cast(M, filter) };
2945
+ }
2946
+ if (op === "$sort") return { $sort: mapSort(stage["$sort"]) };
2947
+ if (op !== "$skip" && op !== "$limit" && op !== "$sample") sourceShape = false;
2948
+ return stage;
2949
+ });
2950
+ const agg = M.aggregate(prepared);
2951
+ const s = session();
2952
+ if (s) agg.session(s);
2953
+ if (options.collation)
2954
+ agg.collation(options.collation);
2955
+ return (await agg).map(toRecord);
2956
+ });
2797
2957
  const guard = async (fn) => {
2798
2958
  const M = await model();
2799
2959
  try {
@@ -2803,22 +2963,22 @@ function createCollection(name, schema, options) {
2803
2963
  }
2804
2964
  };
2805
2965
  const findOpts = (q2, opts) => {
2806
- if (_optionalChain([opts, 'optionalAccess', _73 => _73.projection])) q2.select(opts.projection);
2807
- if (_optionalChain([opts, 'optionalAccess', _74 => _74.sort])) {
2966
+ if (_optionalChain([opts, 'optionalAccess', _78 => _78.projection])) q2.select(opts.projection);
2967
+ if (_optionalChain([opts, 'optionalAccess', _79 => _79.sort])) {
2808
2968
  const meta = Object.values(opts.sort).some((v) => typeof v === "object");
2809
2969
  q2.sort(meta ? opts.sort : mapSort(opts.sort));
2810
2970
  }
2811
- if (_optionalChain([opts, 'optionalAccess', _75 => _75.skip]) !== void 0) q2.skip(opts.skip);
2812
- if (_optionalChain([opts, 'optionalAccess', _76 => _76.limit]) !== void 0) q2.limit(opts.limit);
2813
- if (_optionalChain([opts, 'optionalAccess', _77 => _77.populate])) q2.populate(opts.populate);
2814
- const collation = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _78 => _78.collation]), () => ( options.collation));
2971
+ if (_optionalChain([opts, 'optionalAccess', _80 => _80.skip]) !== void 0) q2.skip(opts.skip);
2972
+ if (_optionalChain([opts, 'optionalAccess', _81 => _81.limit]) !== void 0) q2.limit(opts.limit);
2973
+ if (_optionalChain([opts, 'optionalAccess', _82 => _82.populate])) q2.populate(opts.populate);
2974
+ const collation = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _83 => _83.collation]), () => ( options.collation));
2815
2975
  if (collation) q2.collation(collation);
2816
2976
  q2.session(session());
2817
2977
  return q2;
2818
2978
  };
2819
2979
  const isBadId = (err) => {
2820
2980
  const e = err;
2821
- return _optionalChain([e, 'optionalAccess', _79 => _79.name]) === "CastError" && e.path === "_id";
2981
+ return _optionalChain([e, 'optionalAccess', _84 => _84.name]) === "CastError" && e.path === "_id";
2822
2982
  };
2823
2983
  const model$ = {
2824
2984
  name,
@@ -2859,7 +3019,7 @@ function createCollection(name, schema, options) {
2859
3019
  async (M) => writeResult(
2860
3020
  await M.updateOne(mapFilter(filter), update, {
2861
3021
  runValidators: true,
2862
- upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _80 => _80.upsert]), () => ( false)),
3022
+ upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _85 => _85.upsert]), () => ( false)),
2863
3023
  ...sess()
2864
3024
  })
2865
3025
  )
@@ -2868,7 +3028,7 @@ function createCollection(name, schema, options) {
2868
3028
  async (M) => writeResult(
2869
3029
  await M.updateMany(mapFilter(filter), update, {
2870
3030
  runValidators: true,
2871
- upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _81 => _81.upsert]), () => ( false)),
3031
+ upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _86 => _86.upsert]), () => ( false)),
2872
3032
  ...sess()
2873
3033
  })
2874
3034
  )
@@ -2877,7 +3037,7 @@ function createCollection(name, schema, options) {
2877
3037
  async (M) => writeResult(
2878
3038
  await M.replaceOne(mapFilter(filter), replacement, {
2879
3039
  runValidators: true,
2880
- upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _82 => _82.upsert]), () => ( false)),
3040
+ upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _87 => _87.upsert]), () => ( false)),
2881
3041
  ...sess()
2882
3042
  })
2883
3043
  )
@@ -2886,10 +3046,10 @@ function createCollection(name, schema, options) {
2886
3046
  async (M) => toRecord(
2887
3047
  await M.findOneAndUpdate(mapFilter(filter), update, {
2888
3048
  runValidators: true,
2889
- upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _83 => _83.upsert]), () => ( false)),
2890
- returnDocument: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _84 => _84.returnDocument]), () => ( "before")),
2891
- ..._optionalChain([opts, 'optionalAccess', _85 => _85.projection]) && { projection: opts.projection },
2892
- ..._optionalChain([opts, 'optionalAccess', _86 => _86.sort]) && { sort: opts.sort },
3049
+ upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _88 => _88.upsert]), () => ( false)),
3050
+ returnDocument: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _89 => _89.returnDocument]), () => ( "before")),
3051
+ ..._optionalChain([opts, 'optionalAccess', _90 => _90.projection]) && { projection: opts.projection },
3052
+ ..._optionalChain([opts, 'optionalAccess', _91 => _91.sort]) && { sort: opts.sort },
2893
3053
  ...sess()
2894
3054
  }).lean()
2895
3055
  )
@@ -2899,7 +3059,7 @@ function createCollection(name, schema, options) {
2899
3059
  return toRecord(
2900
3060
  await M.findByIdAndUpdate(id, update, {
2901
3061
  runValidators: true,
2902
- returnDocument: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _87 => _87.returnDocument]), () => ( "before")),
3062
+ returnDocument: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _92 => _92.returnDocument]), () => ( "before")),
2903
3063
  ...sess()
2904
3064
  }).lean()
2905
3065
  );
@@ -2911,7 +3071,7 @@ function createCollection(name, schema, options) {
2911
3071
  findOneAndDelete: (filter, opts) => guard(
2912
3072
  async (M) => toRecord(
2913
3073
  await M.findOneAndDelete(mapFilter(filter), {
2914
- ..._optionalChain([opts, 'optionalAccess', _88 => _88.sort]) && { sort: opts.sort },
3074
+ ..._optionalChain([opts, 'optionalAccess', _93 => _93.sort]) && { sort: opts.sort },
2915
3075
  ...sess()
2916
3076
  }).lean()
2917
3077
  )
@@ -2938,6 +3098,8 @@ function createCollection(name, schema, options) {
2938
3098
  agg.collation(options.collation);
2939
3099
  return (await agg).map(toRecord);
2940
3100
  }),
3101
+ pipeline: () => new Pipeline(runPipeline),
3102
+ lookup: (field, target, filter) => new Pipeline(runPipeline).match(_nullishCoalesce(filter, () => ( {}))).lookup(field, target).exec(),
2941
3103
  bulkWrite: (ops, opts) => guard(async (M) => {
2942
3104
  if (ops.length === 0) {
2943
3105
  return {
@@ -2951,7 +3113,7 @@ function createCollection(name, schema, options) {
2951
3113
  const r = await M.bulkWrite(
2952
3114
  ops.map(mapBulkOp),
2953
3115
  {
2954
- ordered: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _89 => _89.ordered]), () => ( true)),
3116
+ ordered: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _94 => _94.ordered]), () => ( true)),
2955
3117
  runValidators: true,
2956
3118
  ...sess()
2957
3119
  }
@@ -2970,13 +3132,13 @@ function createCollection(name, schema, options) {
2970
3132
  const open = async () => {
2971
3133
  const M = await model();
2972
3134
  stream ??= M.watch(pipeline, {
2973
- ..._optionalChain([opts, 'optionalAccess', _90 => _90.fullDocument]) && { fullDocument: opts.fullDocument }
3135
+ ..._optionalChain([opts, 'optionalAccess', _95 => _95.fullDocument]) && { fullDocument: opts.fullDocument }
2974
3136
  });
2975
3137
  return stream;
2976
3138
  };
2977
3139
  const close = async () => {
2978
3140
  closed = true;
2979
- await _optionalChain([stream, 'optionalAccess', _91 => _91.close, 'call', _92 => _92()]);
3141
+ await _optionalChain([stream, 'optionalAccess', _96 => _96.close, 'call', _97 => _97()]);
2980
3142
  };
2981
3143
  return {
2982
3144
  close,
@@ -2992,7 +3154,7 @@ function createCollection(name, schema, options) {
2992
3154
  const key = change["documentKey"];
2993
3155
  yield {
2994
3156
  operationType: String(change["operationType"]),
2995
- id: _optionalChain([key, 'optionalAccess', _93 => _93._id]) == null ? void 0 : String(key._id),
3157
+ id: _optionalChain([key, 'optionalAccess', _98 => _98._id]) == null ? void 0 : String(key._id),
2996
3158
  ...change["fullDocument"] != null && {
2997
3159
  fullDocument: toRecord(change["fullDocument"])
2998
3160
  },
@@ -3012,12 +3174,12 @@ function createCollection(name, schema, options) {
3012
3174
  sync: (opts) => model().then(() => base.sync(opts)),
3013
3175
  drop: () => model().then(() => base.drop())
3014
3176
  };
3015
- _chunkDUADUR6Rcjs.traceOps.call(void 0,
3177
+ _chunkJP36TLL4cjs.traceOps.call(void 0,
3016
3178
  name,
3017
3179
  model$,
3018
3180
  Object.keys(model$).filter((op) => !["name", "raw", "sync", "drop", "watch"].includes(op))
3019
3181
  );
3020
- _chunkTYCYYLLMcjs.registerModel.call(void 0, {
3182
+ _chunkIUZ6A7PBcjs.registerModel.call(void 0, {
3021
3183
  name,
3022
3184
  sync: model$.sync,
3023
3185
  plan: (opts) => model().then(() => base.plan(opts)),
@@ -3025,6 +3187,12 @@ function createCollection(name, schema, options) {
3025
3187
  findByIds: (ids) => model$.find({ _id: { $in: ids } }),
3026
3188
  pgTarget: () => {
3027
3189
  throw new Error(`[EFC] ${name} is a MongoDB collection (defineCollection)`);
3190
+ },
3191
+ studio: {
3192
+ storage: async () => (await model()).collection.collectionName,
3193
+ create: (data) => model$.create(data),
3194
+ update: (id, data) => model$.findByIdAndUpdate(id, data, { returnDocument: "after" }),
3195
+ delete: (id) => model$.findByIdAndDelete(id)
3028
3196
  }
3029
3197
  });
3030
3198
  return model$;
@@ -3065,5 +3233,6 @@ var db = new Proxy({}, {
3065
3233
 
3066
3234
 
3067
3235
 
3068
- exports.connectMongo = connectMongo; exports.defineModel = defineModel; exports.transaction = transaction; exports.defineTable = defineTable; exports.defineCollection = defineCollection; exports.setDbClient = setDbClient; exports.getDbClient = getDbClient; exports.db = db;
3069
- //# sourceMappingURL=chunk-VWSUQKCJ.cjs.map
3236
+
3237
+ 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;
3238
+ //# sourceMappingURL=chunk-R2K7AFIB.cjs.map