express-file-cluster 0.7.0 → 0.8.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 (193) hide show
  1. package/README.md +3 -1
  2. package/dist/auth/index.d.cts +1 -1
  3. package/dist/auth/index.d.ts +1 -1
  4. package/dist/chunk-75O3WQKR.cjs +1386 -0
  5. package/dist/chunk-75O3WQKR.cjs.map +1 -0
  6. package/dist/{chunk-6OGOVV57.js → chunk-B2I7SYQ3.js} +100 -1261
  7. package/dist/chunk-B2I7SYQ3.js.map +1 -0
  8. package/dist/chunk-BBSZLGZW.js +113 -0
  9. package/dist/chunk-BBSZLGZW.js.map +1 -0
  10. package/dist/{chunk-AZYXQU3Z.cjs → chunk-FQFKHPLR.cjs} +217 -1378
  11. package/dist/chunk-FQFKHPLR.cjs.map +1 -0
  12. package/dist/chunk-OSES7ZQ5.js +1386 -0
  13. package/dist/chunk-OSES7ZQ5.js.map +1 -0
  14. package/dist/chunk-QL6EWT4B.cjs +113 -0
  15. package/dist/chunk-QL6EWT4B.cjs.map +1 -0
  16. package/dist/cli/db-runner.cjs +611 -26
  17. package/dist/cli/db-runner.cjs.map +1 -1
  18. package/dist/cli/db-runner.js +610 -25
  19. package/dist/cli/db-runner.js.map +1 -1
  20. package/dist/cli/index.cjs +1210 -12
  21. package/dist/cli/index.cjs.map +1 -1
  22. package/dist/cli/index.js +1221 -23
  23. package/dist/cli/index.js.map +1 -1
  24. package/dist/docs/api-reference/db.md +1 -0
  25. package/dist/docs/cli/add.md +136 -0
  26. package/dist/docs/cli/db.md +25 -2
  27. package/dist/docs/cli/index.md +10 -1
  28. package/dist/docs/core-concepts/middleware.md +1 -1
  29. package/dist/docs/getting-started/index.md +26 -18
  30. package/dist/docs/getting-started/project-structure.md +7 -8
  31. package/dist/docs/guides/authentication.md +3 -1
  32. package/dist/docs/guides/coming-from-prisma.md +75 -0
  33. package/dist/docs/guides/database.md +3 -2
  34. package/dist/docs/guides/generated-portals.md +36 -19
  35. package/dist/docs/guides/mailer.md +7 -10
  36. package/dist/docs/guides/migrations.md +114 -3
  37. package/dist/docs/guides/oauth.md +94 -0
  38. package/dist/docs/guides/rbac.md +5 -40
  39. package/dist/docs/index.md +5 -3
  40. package/dist/docs/skills/SKILL.md +3 -3
  41. package/dist/docs/skills/what-not-to-invent.md +22 -6
  42. package/dist/index.cjs +10 -8
  43. package/dist/index.cjs.map +1 -1
  44. package/dist/index.d.cts +2 -2
  45. package/dist/index.d.ts +2 -2
  46. package/dist/index.js +8 -6
  47. package/dist/index.js.map +1 -1
  48. package/dist/registry/index.json +506 -0
  49. package/dist/registry/js-mongo/_base.json +1 -0
  50. package/dist/registry/js-mongo/account-security.json +1 -0
  51. package/dist/registry/js-mongo/account-settings.json +1 -0
  52. package/dist/registry/js-mongo/admin-admins.json +1 -0
  53. package/dist/registry/js-mongo/admin-analytics.json +1 -0
  54. package/dist/registry/js-mongo/admin-billing.json +1 -0
  55. package/dist/registry/js-mongo/admin-content.json +1 -0
  56. package/dist/registry/js-mongo/admin-logs.json +1 -0
  57. package/dist/registry/js-mongo/admin-support.json +1 -0
  58. package/dist/registry/js-mongo/admin-system.json +1 -0
  59. package/dist/registry/js-mongo/admin-users.json +1 -0
  60. package/dist/registry/js-mongo/admin.json +1 -0
  61. package/dist/registry/js-mongo/auth.json +1 -0
  62. package/dist/registry/js-mongo/auth@apple.json +1 -0
  63. package/dist/registry/js-mongo/auth@google.json +1 -0
  64. package/dist/registry/js-mongo/billing.json +1 -0
  65. package/dist/registry/js-mongo/email-client.json +1 -0
  66. package/dist/registry/js-mongo/email-verification.json +1 -0
  67. package/dist/registry/js-mongo/files.json +1 -0
  68. package/dist/registry/js-mongo/forgot-password.json +1 -0
  69. package/dist/registry/js-mongo/notifications.json +1 -0
  70. package/dist/registry/js-mongo/support.json +1 -0
  71. package/dist/registry/js-mongo/user-profile.json +1 -0
  72. package/dist/registry/js-pg-model/_base.json +1 -0
  73. package/dist/registry/js-pg-model/account-security.json +1 -0
  74. package/dist/registry/js-pg-model/account-settings.json +1 -0
  75. package/dist/registry/js-pg-model/admin-admins.json +1 -0
  76. package/dist/registry/js-pg-model/admin-analytics.json +1 -0
  77. package/dist/registry/js-pg-model/admin-billing.json +1 -0
  78. package/dist/registry/js-pg-model/admin-content.json +1 -0
  79. package/dist/registry/js-pg-model/admin-logs.json +1 -0
  80. package/dist/registry/js-pg-model/admin-support.json +1 -0
  81. package/dist/registry/js-pg-model/admin-system.json +1 -0
  82. package/dist/registry/js-pg-model/admin-users.json +1 -0
  83. package/dist/registry/js-pg-model/admin.json +1 -0
  84. package/dist/registry/js-pg-model/auth.json +1 -0
  85. package/dist/registry/js-pg-model/auth@apple.json +1 -0
  86. package/dist/registry/js-pg-model/auth@google.json +1 -0
  87. package/dist/registry/js-pg-model/billing.json +1 -0
  88. package/dist/registry/js-pg-model/email-client.json +1 -0
  89. package/dist/registry/js-pg-model/email-verification.json +1 -0
  90. package/dist/registry/js-pg-model/files.json +1 -0
  91. package/dist/registry/js-pg-model/forgot-password.json +1 -0
  92. package/dist/registry/js-pg-model/notifications.json +1 -0
  93. package/dist/registry/js-pg-model/support.json +1 -0
  94. package/dist/registry/js-pg-model/user-profile.json +1 -0
  95. package/dist/registry/js-pg-table/_base.json +1 -0
  96. package/dist/registry/js-pg-table/account-security.json +1 -0
  97. package/dist/registry/js-pg-table/account-settings.json +1 -0
  98. package/dist/registry/js-pg-table/admin-admins.json +1 -0
  99. package/dist/registry/js-pg-table/admin-analytics.json +1 -0
  100. package/dist/registry/js-pg-table/admin-billing.json +1 -0
  101. package/dist/registry/js-pg-table/admin-content.json +1 -0
  102. package/dist/registry/js-pg-table/admin-logs.json +1 -0
  103. package/dist/registry/js-pg-table/admin-support.json +1 -0
  104. package/dist/registry/js-pg-table/admin-system.json +1 -0
  105. package/dist/registry/js-pg-table/admin-users.json +1 -0
  106. package/dist/registry/js-pg-table/admin.json +1 -0
  107. package/dist/registry/js-pg-table/auth.json +1 -0
  108. package/dist/registry/js-pg-table/auth@apple.json +1 -0
  109. package/dist/registry/js-pg-table/auth@google.json +1 -0
  110. package/dist/registry/js-pg-table/billing.json +1 -0
  111. package/dist/registry/js-pg-table/email-client.json +1 -0
  112. package/dist/registry/js-pg-table/email-verification.json +1 -0
  113. package/dist/registry/js-pg-table/files.json +1 -0
  114. package/dist/registry/js-pg-table/forgot-password.json +1 -0
  115. package/dist/registry/js-pg-table/notifications.json +1 -0
  116. package/dist/registry/js-pg-table/support.json +1 -0
  117. package/dist/registry/js-pg-table/user-profile.json +1 -0
  118. package/dist/registry/ts-mongo/_base.json +1 -0
  119. package/dist/registry/ts-mongo/account-security.json +1 -0
  120. package/dist/registry/ts-mongo/account-settings.json +1 -0
  121. package/dist/registry/ts-mongo/admin-admins.json +1 -0
  122. package/dist/registry/ts-mongo/admin-analytics.json +1 -0
  123. package/dist/registry/ts-mongo/admin-billing.json +1 -0
  124. package/dist/registry/ts-mongo/admin-content.json +1 -0
  125. package/dist/registry/ts-mongo/admin-logs.json +1 -0
  126. package/dist/registry/ts-mongo/admin-support.json +1 -0
  127. package/dist/registry/ts-mongo/admin-system.json +1 -0
  128. package/dist/registry/ts-mongo/admin-users.json +1 -0
  129. package/dist/registry/ts-mongo/admin.json +1 -0
  130. package/dist/registry/ts-mongo/auth.json +1 -0
  131. package/dist/registry/ts-mongo/auth@apple.json +1 -0
  132. package/dist/registry/ts-mongo/auth@google.json +1 -0
  133. package/dist/registry/ts-mongo/billing.json +1 -0
  134. package/dist/registry/ts-mongo/email-client.json +1 -0
  135. package/dist/registry/ts-mongo/email-verification.json +1 -0
  136. package/dist/registry/ts-mongo/files.json +1 -0
  137. package/dist/registry/ts-mongo/forgot-password.json +1 -0
  138. package/dist/registry/ts-mongo/notifications.json +1 -0
  139. package/dist/registry/ts-mongo/support.json +1 -0
  140. package/dist/registry/ts-mongo/user-profile.json +1 -0
  141. package/dist/registry/ts-pg-model/_base.json +1 -0
  142. package/dist/registry/ts-pg-model/account-security.json +1 -0
  143. package/dist/registry/ts-pg-model/account-settings.json +1 -0
  144. package/dist/registry/ts-pg-model/admin-admins.json +1 -0
  145. package/dist/registry/ts-pg-model/admin-analytics.json +1 -0
  146. package/dist/registry/ts-pg-model/admin-billing.json +1 -0
  147. package/dist/registry/ts-pg-model/admin-content.json +1 -0
  148. package/dist/registry/ts-pg-model/admin-logs.json +1 -0
  149. package/dist/registry/ts-pg-model/admin-support.json +1 -0
  150. package/dist/registry/ts-pg-model/admin-system.json +1 -0
  151. package/dist/registry/ts-pg-model/admin-users.json +1 -0
  152. package/dist/registry/ts-pg-model/admin.json +1 -0
  153. package/dist/registry/ts-pg-model/auth.json +1 -0
  154. package/dist/registry/ts-pg-model/auth@apple.json +1 -0
  155. package/dist/registry/ts-pg-model/auth@google.json +1 -0
  156. package/dist/registry/ts-pg-model/billing.json +1 -0
  157. package/dist/registry/ts-pg-model/email-client.json +1 -0
  158. package/dist/registry/ts-pg-model/email-verification.json +1 -0
  159. package/dist/registry/ts-pg-model/files.json +1 -0
  160. package/dist/registry/ts-pg-model/forgot-password.json +1 -0
  161. package/dist/registry/ts-pg-model/notifications.json +1 -0
  162. package/dist/registry/ts-pg-model/support.json +1 -0
  163. package/dist/registry/ts-pg-model/user-profile.json +1 -0
  164. package/dist/registry/ts-pg-table/_base.json +1 -0
  165. package/dist/registry/ts-pg-table/account-security.json +1 -0
  166. package/dist/registry/ts-pg-table/account-settings.json +1 -0
  167. package/dist/registry/ts-pg-table/admin-admins.json +1 -0
  168. package/dist/registry/ts-pg-table/admin-analytics.json +1 -0
  169. package/dist/registry/ts-pg-table/admin-billing.json +1 -0
  170. package/dist/registry/ts-pg-table/admin-content.json +1 -0
  171. package/dist/registry/ts-pg-table/admin-logs.json +1 -0
  172. package/dist/registry/ts-pg-table/admin-support.json +1 -0
  173. package/dist/registry/ts-pg-table/admin-system.json +1 -0
  174. package/dist/registry/ts-pg-table/admin-users.json +1 -0
  175. package/dist/registry/ts-pg-table/admin.json +1 -0
  176. package/dist/registry/ts-pg-table/auth.json +1 -0
  177. package/dist/registry/ts-pg-table/auth@apple.json +1 -0
  178. package/dist/registry/ts-pg-table/auth@google.json +1 -0
  179. package/dist/registry/ts-pg-table/billing.json +1 -0
  180. package/dist/registry/ts-pg-table/email-client.json +1 -0
  181. package/dist/registry/ts-pg-table/email-verification.json +1 -0
  182. package/dist/registry/ts-pg-table/files.json +1 -0
  183. package/dist/registry/ts-pg-table/forgot-password.json +1 -0
  184. package/dist/registry/ts-pg-table/notifications.json +1 -0
  185. package/dist/registry/ts-pg-table/support.json +1 -0
  186. package/dist/registry/ts-pg-table/user-profile.json +1 -0
  187. package/dist/tasks/index.d.cts +1 -1
  188. package/dist/tasks/index.d.ts +1 -1
  189. package/dist/{types-B6lVw4bj.d.cts → types-B1tJoI4g.d.cts} +6 -0
  190. package/dist/{types-B6lVw4bj.d.ts → types-B1tJoI4g.d.ts} +6 -0
  191. package/package.json +11 -2
  192. package/dist/chunk-6OGOVV57.js.map +0 -1
  193. package/dist/chunk-AZYXQU3Z.cjs.map +0 -1
@@ -6,447 +6,30 @@
6
6
 
7
7
 
8
8
 
9
- var _chunkMGH4VDV3cjs = require('./chunk-MGH4VDV3.cjs');
10
9
 
11
10
 
12
11
 
13
- var _chunkYL37D6KMcjs = require('./chunk-YL37D6KM.cjs');
14
12
 
15
- // src/errors.ts
16
- var HttpError = class _HttpError extends Error {
17
-
18
- constructor(statusCode, message) {
19
- super(message);
20
- this.name = "HttpError";
21
- this.statusCode = statusCode;
22
- Error.captureStackTrace(this, _HttpError);
23
- }
24
- /**
25
- * Wraps an unknown caught value into an `HttpError`.
26
- * If the value is already an `HttpError`, it is returned as-is.
27
- * Otherwise the `message` from the caught `Error` (or a fallback) is used.
28
- *
29
- * @example
30
- * } catch (err) {
31
- * throw HttpError.from(err, 500, 'Something went wrong');
32
- * }
33
- */
34
- static from(err, statusCode = 500, fallback = "Internal Server Error") {
35
- if (err instanceof _HttpError) return err;
36
- const message = err instanceof Error ? err.message : fallback;
37
- return new _HttpError(statusCode, message);
38
- }
39
- /** Returns a plain object representation suitable for JSON serialization. */
40
- toJSON() {
41
- return {
42
- statusCode: this.statusCode,
43
- error: this.name,
44
- message: this.message
45
- };
46
- }
47
- };
48
- function isHttpError(value) {
49
- return value instanceof HttpError;
50
- }
51
13
 
52
- // src/db/schema.ts
53
- var _crypto = require('crypto');
54
- var MODEL_TYPES = /* @__PURE__ */ new Set(["string", "number", "boolean", "date", "object", "objectId", "array"]);
55
- var TABLE_ONLY_TYPES = /* @__PURE__ */ new Set(["integer", "bigint", "decimal", "uuid", "json"]);
56
- var TABLE_ONLY_OPTIONS = ["precision", "scale", "nativeEnum", "column", "onDelete"];
57
- var REFERENTIAL_ACTIONS = /* @__PURE__ */ new Set(["restrict", "cascade", "setNull"]);
58
- var FOREIGN_KEY_TYPES = /* @__PURE__ */ new Set(["objectId", "uuid", "integer", "bigint"]);
59
- function isFieldDefinition(value) {
60
- if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
61
- const type = value.type;
62
- return typeof type === "string" && (MODEL_TYPES.has(type) || TABLE_ONLY_TYPES.has(type));
63
- }
64
- var untyped = () => ({ kind: "json", def: { type: "object" } });
65
- var SchemaBuilder = class {
66
- constructor(model, mode) {
67
- this.model = model;
68
- this.mode = mode;
69
- }
70
-
71
-
72
- fail(path, message) {
73
- throw new Error(`[EFC] ${this.model}.${path}: ${message}`);
74
- }
75
- checkType(type, path) {
76
- if (this.mode === "model" && TABLE_ONLY_TYPES.has(type)) {
77
- this.fail(path, `type '${type}' is PostgreSQL-only \u2014 use defineTable, or a portable type`);
78
- }
79
- }
80
- checkDefinition(def, path, topLevel) {
81
- this.checkType(def.type, path);
82
- if (this.mode === "model") {
83
- for (const opt of TABLE_ONLY_OPTIONS) {
84
- if (def[opt] !== void 0) this.fail(path, `'${opt}' is a defineTable option`);
85
- }
86
- return;
87
- }
88
- if ((def.precision !== void 0 || def.scale !== void 0) && def.type !== "decimal") {
89
- this.fail(path, `'precision' / 'scale' only apply to decimal fields`);
90
- }
91
- if (def.scale !== void 0 && def.precision === void 0) {
92
- this.fail(path, `'scale' needs 'precision'`);
93
- }
94
- if (def.nativeEnum && !(def.enum && def.enum.every((v) => typeof v === "string"))) {
95
- this.fail(path, `'nativeEnum' needs a string 'enum'`);
96
- }
97
- if (def.column !== void 0 && !topLevel) {
98
- this.fail(path, `'column' only applies to top-level fields`);
99
- }
100
- if (def.onDelete !== void 0) {
101
- if (def.ref === void 0) this.fail(path, `'onDelete' needs 'ref'`);
102
- if (!REFERENTIAL_ACTIONS.has(def.onDelete)) {
103
- this.fail(path, `onDelete must be 'restrict', 'cascade' or 'setNull'`);
104
- }
105
- if (def.onDelete === "setNull" && def.required) {
106
- this.fail(path, `onDelete: 'setNull' can't clear a required field`);
107
- }
108
- }
109
- if (def.ref !== void 0) {
110
- const many = def.type === "array";
111
- if (!topLevel) this.fail(path, `'ref' only applies to top-level fields`);
112
- if (!FOREIGN_KEY_TYPES.has(many ? String(def.of) : def.type)) {
113
- this.fail(
114
- path,
115
- many ? `a many-to-many 'ref' needs of: objectId, uuid, integer or bigint` : `'ref' needs an id type: objectId, uuid, integer or bigint`
116
- );
117
- }
118
- if (many && def.onDelete !== void 0) {
119
- this.fail(
120
- path,
121
- `'onDelete' doesn't apply to many-to-many refs \u2014 links are always removed with either record`
122
- );
123
- }
124
- if (many && (def.unique || def.index)) {
125
- this.fail(path, `many-to-many refs are indexed already; 'unique' / 'index' don't apply`);
126
- }
127
- }
128
- }
129
- item(of, parent, path) {
130
- if (of === void 0) return untyped();
131
- if (typeof of === "string") {
132
- this.checkType(of, path);
133
- if (of === "object" || of === "json") return untyped();
134
- const def = {
135
- type: of,
136
- ...parent.ref !== void 0 && { ref: parent.ref }
137
- };
138
- return { kind: "scalar", type: of, def };
139
- }
140
- return { kind: "object", fields: this.tree(of, `${path}.$`), def: { type: "object" } };
141
- }
142
- field(field, path, topLevel) {
143
- if (Array.isArray(field)) {
144
- const inner = field[0];
145
- return {
146
- kind: "array",
147
- item: inner ? { kind: "object", fields: this.tree(inner, `${path}.$`), def: { type: "object" } } : untyped(),
148
- def: { type: "array" }
149
- };
150
- }
151
- if (!isFieldDefinition(field)) {
152
- const type = field.type;
153
- if (typeof type === "string") this.fail(path, `unknown field type '${type}'`);
154
- return {
155
- kind: "object",
156
- fields: this.tree(field, path),
157
- def: { type: "object" }
158
- };
159
- }
160
- const def = field;
161
- this.checkDefinition(def, path, topLevel);
162
- if (def.type === "array") return { kind: "array", item: this.item(def.of, def, path), def };
163
- if (def.type === "object") {
164
- return def.fields ? { kind: "object", fields: this.tree(def.fields, path), def } : { kind: "json", def };
165
- }
166
- if (def.type === "json") return { kind: "json", def };
167
- return { kind: "scalar", type: def.type, def };
168
- }
169
- tree(schema, prefix = "") {
170
- const out = {};
171
- for (const [key, field] of Object.entries(schema)) {
172
- out[key] = this.field(field, prefix ? `${prefix}.${key}` : key, prefix === "");
173
- }
174
- return out;
175
- }
176
- };
177
- function normalizeSchema(schema, mode = "model", model = "Model") {
178
- return new SchemaBuilder(model, mode).tree(schema);
179
- }
180
- function timestampFields(options) {
181
- const ts = _nullishCoalesce(options.timestamps, () => ( true));
182
- if (ts === false) return {};
183
- if (ts === true) return { createdAt: "createdAt", updatedAt: "updatedAt" };
184
- const out = {};
185
- if (ts.createdAt !== false) out.createdAt = _nullishCoalesce(ts.createdAt, () => ( "createdAt"));
186
- if (ts.updatedAt !== false) out.updatedAt = _nullishCoalesce(ts.updatedAt, () => ( "updatedAt"));
187
- return out;
188
- }
189
- var STATIC_DEFAULT_OPERATORS = {
190
- $now: () => /* @__PURE__ */ new Date(),
191
- $uuid: () => _crypto.randomUUID.call(void 0, ),
192
- $timestamp: () => Date.now(),
193
- $shortId: () => _crypto.randomBytes.call(void 0, 12).toString("base64url")
194
- };
195
- var FIXED_DEFAULT_OPERATORS = /* @__PURE__ */ new Set(["$now", "$uuid", "$objectId", "$timestamp", "$shortId"]);
196
- function isCurrentUserOperator(value) {
197
- return typeof value === "string" && (value === "$currentUser" || value.startsWith("$currentUser."));
198
- }
199
- function isDefaultOperator(value) {
200
- return typeof value === "string" && FIXED_DEFAULT_OPERATORS.has(value) || isCurrentUserOperator(value);
201
- }
202
- function resolveDefault(value, objectId) {
203
- if (!isDefaultOperator(value)) return value;
204
- if (value === "$objectId") return objectId;
205
- if (value === "$currentUser") return () => _chunkYL37D6KMcjs.getCurrentUser.call(void 0, );
206
- if (isCurrentUserOperator(value)) {
207
- const key = value.slice("$currentUser.".length);
208
- return () => _optionalChain([_chunkYL37D6KMcjs.getCurrentUser.call(void 0, ), 'optionalAccess', _ => _[key]]);
209
- }
210
- return STATIC_DEFAULT_OPERATORS[value];
211
- }
212
- function applyDefaults(tree, data, objectId) {
213
- const out = { ...data };
214
- for (const [key, node] of Object.entries(tree)) {
215
- if (out[key] === void 0 && node.def.default !== void 0) {
216
- const d = resolveDefault(node.def.default, objectId);
217
- const value = typeof d === "function" ? d() : structuredClone(d);
218
- if (value !== void 0) out[key] = value;
219
- }
220
- if (node.kind === "object" && out[key] != null && typeof out[key] === "object") {
221
- out[key] = applyDefaults(node.fields, out[key], objectId);
222
- }
223
- if (node.kind === "array" && node.item.kind === "object" && Array.isArray(out[key])) {
224
- const fields = node.item.fields;
225
- out[key] = out[key].map(
226
- (v) => v != null && typeof v === "object" ? applyDefaults(fields, v, objectId) : v
227
- );
228
- }
229
- }
230
- return out;
231
- }
232
- var ModelValidationError = class extends HttpError {
233
-
234
- constructor(model, issues) {
235
- super(
236
- 400,
237
- `${model} validation failed: ${issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`
238
- );
239
- this.name = "ModelValidationError";
240
- this.issues = issues;
241
- }
242
- };
243
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
244
- var INT4 = 2 ** 31;
245
- var INT8_MIN = -(2n ** 63n);
246
- var INT8_MAX = 2n ** 63n - 1n;
247
- var DECIMAL_RE = /^[+-]?(\d+(\.\d*)?|\.\d+)$/;
248
- function decimalDigits(value) {
249
- const str = typeof value === "number" ? String(value) : value;
250
- const [i = "", f = ""] = str.replace(/^[+-]/, "").split(".");
251
- return { int: i.replace(/^0+/, "").length, frac: f.replace(/0+$/, "").length };
252
- }
253
- function typeError(type, def, value) {
254
- switch (type) {
255
- case "string":
256
- return typeof value === "string" ? null : "must be a string";
257
- case "number":
258
- return typeof value === "number" && Number.isFinite(value) ? null : "must be a number";
259
- case "integer":
260
- return typeof value === "number" && Number.isInteger(value) && value >= -INT4 && value < INT4 ? null : "must be a 32-bit integer";
261
- case "bigint": {
262
- const big = typeof value === "bigint" ? value : typeof value === "number" && Number.isSafeInteger(value) ? BigInt(value) : void 0;
263
- return big !== void 0 && big >= INT8_MIN && big <= INT8_MAX ? null : "must be a 64-bit integer (bigint)";
264
- }
265
- case "decimal": {
266
- const ok = typeof value === "number" && Number.isFinite(value) || typeof value === "string" && DECIMAL_RE.test(value);
267
- if (!ok) return "must be a decimal number or numeric string";
268
- if (def.precision !== void 0) {
269
- const scale = _nullishCoalesce(def.scale, () => ( 0));
270
- const { int, frac } = decimalDigits(value);
271
- if (frac > scale) return `must have at most ${scale} decimal places`;
272
- if (int > def.precision - scale)
273
- return `must have at most ${def.precision - scale} digits before the decimal point`;
274
- }
275
- return null;
276
- }
277
- case "boolean":
278
- return typeof value === "boolean" ? null : "must be a boolean";
279
- case "date":
280
- return !Number.isNaN(new Date(value).getTime()) ? null : "must be a date";
281
- case "objectId":
282
- return typeof value === "string" && UUID_RE.test(value) ? null : "must be a valid id";
283
- case "uuid":
284
- return typeof value === "string" && UUID_RE.test(value) ? null : "must be a UUID";
285
- }
286
- }
287
- function compareBound(def, value, bound) {
288
- if (def.type === "bigint") {
289
- const a = BigInt(value);
290
- const b = BigInt(bound instanceof Date ? bound.getTime() : bound);
291
- return a < b ? -1 : a > b ? 1 : 0;
292
- }
293
- const num = (v) => v instanceof Date ? v.getTime() : def.type === "date" ? new Date(v).getTime() : Number(v);
294
- return num(value) - num(bound);
295
- }
296
- async function checkRules(def, value, path, issues) {
297
- if (def.enum && !def.enum.includes(value)) {
298
- issues.push({ path, message: `must be one of: ${def.enum.join(", ")}` });
299
- }
300
- const ordered = typeof value === "number" || typeof value === "bigint" || value instanceof Date || def.type === "date" || def.type === "decimal" && typeof value === "string";
301
- if (ordered) {
302
- if (def.min !== void 0 && compareBound(def, value, def.min) < 0)
303
- issues.push({ path, message: `must be >= ${String(def.min)}` });
304
- if (def.max !== void 0 && compareBound(def, value, def.max) > 0)
305
- issues.push({ path, message: `must be <= ${String(def.max)}` });
306
- }
307
- if (typeof value === "string" && def.type !== "decimal") {
308
- if (def.minLength !== void 0 && value.length < def.minLength)
309
- issues.push({ path, message: `must be at least ${def.minLength} characters` });
310
- if (def.maxLength !== void 0 && value.length > def.maxLength)
311
- issues.push({ path, message: `must be at most ${def.maxLength} characters` });
312
- if (def.match && !def.match.test(value))
313
- issues.push({ path, message: `must match ${String(def.match)}` });
314
- }
315
- if (def.validate) {
316
- const result = await def.validate(value);
317
- if (result !== true)
318
- issues.push({ path, message: typeof result === "string" ? result : "is invalid" });
319
- }
320
- }
321
- async function validateNode(node, value, path, issues, partial) {
322
- if (value === void 0 || value === null) {
323
- if (node.def.required && !partial) issues.push({ path, message: "is required" });
324
- if (node.def.required && partial && value === null)
325
- issues.push({ path, message: "is required" });
326
- return;
327
- }
328
- switch (node.kind) {
329
- case "scalar": {
330
- const err = typeError(node.type, node.def, value);
331
- if (err) {
332
- issues.push({ path, message: err });
333
- return;
334
- }
335
- await checkRules(node.def, value, path, issues);
336
- return;
337
- }
338
- case "json":
339
- await checkRules(node.def, value, path, issues);
340
- return;
341
- case "object":
342
- if (typeof value !== "object" || Array.isArray(value)) {
343
- issues.push({ path, message: "must be an object" });
344
- return;
345
- }
346
- await validateTree(node.fields, value, issues, false, path);
347
- await checkRules(node.def, value, path, issues);
348
- return;
349
- case "array":
350
- if (!Array.isArray(value)) {
351
- issues.push({ path, message: "must be an array" });
352
- return;
353
- }
354
- for (let i = 0; i < value.length; i++) {
355
- await validateNode(
356
- { ...node.item, def: { ...node.item.def, required: true } },
357
- value[i],
358
- `${path}.${i}`,
359
- issues,
360
- false
361
- );
362
- }
363
- await checkRules(node.def, value, path, issues);
364
- }
365
- }
366
- async function validateTree(tree, data, issues, partial, prefix = "") {
367
- for (const [key, node] of Object.entries(tree)) {
368
- if (partial && !(key in data)) continue;
369
- await validateNode(node, data[key], prefix ? `${prefix}.${key}` : key, issues, partial);
370
- }
371
- return issues;
372
- }
373
- function refFields(tree) {
374
- const refs = /* @__PURE__ */ new Map();
375
- for (const [key, node] of Object.entries(tree)) {
376
- if (node.kind === "scalar" && node.type === "objectId" && node.def.ref) {
377
- refs.set(key, { model: node.def.ref, many: false });
378
- } else if (node.kind === "array" && node.item.kind === "scalar" && node.item.type === "objectId" && node.def.ref) {
379
- refs.set(key, { model: node.def.ref, many: true });
380
- }
381
- }
382
- return refs;
383
- }
384
- function sequenceFields(name, tree) {
385
- const out = [];
386
- for (const [path, node] of Object.entries(tree)) {
387
- if (node.def.sequence) {
388
- out.push({
389
- path,
390
- key: typeof node.def.sequence === "string" ? node.def.sequence : `${name}.${path}`
391
- });
392
- }
393
- }
394
- return out;
395
- }
396
- function nodeAt(tree, path) {
397
- let node = tree[path[0]];
398
- for (const part of path.slice(1)) {
399
- if (!node) return void 0;
400
- if (node.kind === "object") node = node.fields[part];
401
- else if (node.kind === "array" && /^\d+$/.test(part)) node = node.item;
402
- else if (node.kind === "json")
403
- return node;
404
- else return void 0;
405
- }
406
- return node;
407
- }
408
- async function validateAtPath(tree, dotted, value, issues) {
409
- const node = nodeAt(tree, dotted.split("."));
410
- if (!node) {
411
- issues.push({ path: dotted, message: "unknown field" });
412
- return;
413
- }
414
- await validateNode(node, value, dotted, issues, true);
415
- }
416
14
 
417
- // src/db/engine.ts
418
- var _async_hooks = require('async_hooks');
419
- var engine;
420
- function setDbEngine(value) {
421
- engine = value;
422
- }
423
- function getDbEngine() {
424
- return _nullishCoalesce(engine, () => ( "mongodb"));
425
- }
426
- var autoSync = true;
427
- function setAutoSync(value) {
428
- autoSync = value;
429
- }
430
- function isAutoSync() {
431
- return autoSync;
432
- }
433
- var registry = /* @__PURE__ */ new Map();
434
- function registerModel(model) {
435
- registry.set(model.name, model);
436
- }
437
- function getRegisteredModel(name) {
438
- return registry.get(name);
439
- }
440
- function registeredModels() {
441
- return [...registry.values()];
442
- }
443
- var txStorage = new (0, _async_hooks.AsyncLocalStorage)();
444
- function currentTx() {
445
- return txStorage.getStore();
446
- }
447
- function runInTx(handle, fn) {
448
- return txStorage.run(handle, fn);
449
- }
15
+
16
+
17
+
18
+
19
+
20
+
21
+ var _chunk75O3WQKRcjs = require('./chunk-75O3WQKR.cjs');
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+ var _chunkMGH4VDV3cjs = require('./chunk-MGH4VDV3.cjs');
30
+
31
+
32
+ var _chunkYL37D6KMcjs = require('./chunk-YL37D6KM.cjs');
450
33
 
451
34
  // src/db/mongo-model.ts
452
35
  var mongoosePromise;
@@ -482,7 +65,7 @@ function rules(node, mg) {
482
65
  if (d.unique !== void 0) entry["unique"] = d.unique;
483
66
  if (d.index !== void 0) entry["index"] = d.index;
484
67
  if (d.default !== void 0)
485
- entry["default"] = resolveDefault(d.default, () => new mg.Types.ObjectId());
68
+ entry["default"] = _chunk75O3WQKRcjs.resolveDefault.call(void 0, d.default, () => new mg.Types.ObjectId());
486
69
  if (d.enum !== void 0) entry["enum"] = d.enum;
487
70
  if (d.min !== void 0) entry["min"] = d.min;
488
71
  if (d.max !== void 0) entry["max"] = d.max;
@@ -555,8 +138,8 @@ function normalise(value) {
555
138
  }
556
139
  function translateError(model, err) {
557
140
  const e = err;
558
- if (_optionalChain([e, 'optionalAccess', _2 => _2.name]) === "ValidationError" && e.errors) {
559
- throw new ModelValidationError(
141
+ if (_optionalChain([e, 'optionalAccess', _ => _.name]) === "ValidationError" && e.errors) {
142
+ throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(
560
143
  model,
561
144
  Object.entries(e.errors).map(([path, v]) => ({
562
145
  path,
@@ -567,20 +150,20 @@ function translateError(model, err) {
567
150
  }))
568
151
  );
569
152
  }
570
- if (_optionalChain([e, 'optionalAccess', _3 => _3.name]) === "CastError") {
571
- throw new ModelValidationError(model, [
153
+ if (_optionalChain([e, 'optionalAccess', _2 => _2.name]) === "CastError") {
154
+ throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(model, [
572
155
  { path: _nullishCoalesce(e.path, () => ( "")), message: _nullishCoalesce(e.message, () => ( "invalid value")) }
573
156
  ]);
574
157
  }
575
- if (_optionalChain([e, 'optionalAccess', _4 => _4.code]) === 11e3) {
158
+ if (_optionalChain([e, 'optionalAccess', _3 => _3.code]) === 11e3) {
576
159
  const field = _nullishCoalesce(Object.keys(_nullishCoalesce(e.keyValue, () => ( {})))[0], () => ( "field"));
577
- throw new HttpError(409, `${model} with this ${field} already exists`);
160
+ throw new (0, _chunk75O3WQKRcjs.HttpError)(409, `${model} with this ${field} already exists`);
578
161
  }
579
162
  throw err;
580
163
  }
581
164
  function isCastErrorOnId(err) {
582
165
  const e = err;
583
- return _optionalChain([e, 'optionalAccess', _5 => _5.name]) === "CastError" && e.path === "_id";
166
+ return _optionalChain([e, 'optionalAccess', _4 => _4.name]) === "CastError" && e.path === "_id";
584
167
  }
585
168
  function mapFilter(filter) {
586
169
  if (!filter) return {};
@@ -606,8 +189,8 @@ function mongoModel(name, tree, options) {
606
189
  const schema = new mg.Schema(buildTree(tree, mg), {
607
190
  timestamps: _nullishCoalesce(options.timestamps, () => ( true)),
608
191
  // autoSync: false hands collection and index creation to migrations, on MongoDB too.
609
- autoIndex: isAutoSync(),
610
- autoCreate: isAutoSync(),
192
+ autoIndex: _chunk75O3WQKRcjs.isAutoSync.call(void 0, ),
193
+ autoCreate: _chunk75O3WQKRcjs.isAutoSync.call(void 0, ),
611
194
  ...options.collection !== void 0 && { collection: options.collection }
612
195
  });
613
196
  for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
@@ -619,7 +202,7 @@ function mongoModel(name, tree, options) {
619
202
  ...idx.name !== void 0 && { name: idx.name }
620
203
  });
621
204
  }
622
- const sequences = sequenceFields(name, tree);
205
+ const sequences = _chunk75O3WQKRcjs.sequenceFields.call(void 0, name, tree);
623
206
  if (sequences.length > 0) {
624
207
  schema.pre("validate", async function() {
625
208
  if (!this.isNew) return;
@@ -629,7 +212,7 @@ function mongoModel(name, tree, options) {
629
212
  });
630
213
  }
631
214
  const M = mg.model(name, schema);
632
- if (isAutoSync()) {
215
+ if (_chunk75O3WQKRcjs.isAutoSync.call(void 0, )) {
633
216
  await M.init().catch((err) => {
634
217
  _chunkYL37D6KMcjs.getLogger.call(void 0, ).warn(
635
218
  { model: name, err: err.message },
@@ -641,17 +224,17 @@ function mongoModel(name, tree, options) {
641
224
  })
642
225
  );
643
226
  const session = () => {
644
- const tx = currentTx();
645
- return _optionalChain([tx, 'optionalAccess', _6 => _6.engine]) === "mongodb" ? { session: tx.session } : {};
227
+ const tx = _chunk75O3WQKRcjs.currentTx.call(void 0, );
228
+ return _optionalChain([tx, 'optionalAccess', _5 => _5.engine]) === "mongodb" ? { session: tx.session } : {};
646
229
  };
647
230
  const applyQueryOptions = (q2, opts) => {
648
- if (_optionalChain([opts, 'optionalAccess', _7 => _7.populate])) q2.populate(opts.populate);
649
- if (_optionalChain([opts, 'optionalAccess', _8 => _8.select])) q2.select(opts.select.join(" "));
231
+ if (_optionalChain([opts, 'optionalAccess', _6 => _6.populate])) q2.populate(opts.populate);
232
+ if (_optionalChain([opts, 'optionalAccess', _7 => _7.select])) q2.select(opts.select.join(" "));
650
233
  const f = opts;
651
- const sort = mapSort(_optionalChain([f, 'optionalAccess', _9 => _9.sort]));
234
+ const sort = mapSort(_optionalChain([f, 'optionalAccess', _8 => _8.sort]));
652
235
  if (sort) q2.sort(sort);
653
- if (_optionalChain([f, 'optionalAccess', _10 => _10.skip]) !== void 0) q2.skip(f.skip);
654
- if (_optionalChain([f, 'optionalAccess', _11 => _11.limit]) !== void 0) q2.limit(f.limit);
236
+ if (_optionalChain([f, 'optionalAccess', _9 => _9.skip]) !== void 0) q2.skip(f.skip);
237
+ if (_optionalChain([f, 'optionalAccess', _10 => _10.limit]) !== void 0) q2.limit(f.limit);
655
238
  return q2;
656
239
  };
657
240
  const guard = async (fn) => {
@@ -775,6 +358,7 @@ function mongoModel(name, tree, options) {
775
358
  }),
776
359
  raw: () => model(),
777
360
  async sync(opts) {
361
+ if (_chunk75O3WQKRcjs.isSyncSuppressed.call(void 0, )) return [];
778
362
  const M = await model();
779
363
  const changes = [];
780
364
  const exists = (await M.db.db.listCollections({ name: M.collection.collectionName }).toArray()).length > 0;
@@ -782,15 +366,74 @@ function mongoModel(name, tree, options) {
782
366
  const diff = await M.diffIndexes().catch(() => ({ toDrop: [], toCreate: [] }));
783
367
  for (const idx of diff.toDrop) changes.push(`dropIndex ${String(idx)}`);
784
368
  for (const idx of diff.toCreate) changes.push(`createIndex ${JSON.stringify(idx)}`);
785
- if (_optionalChain([opts, 'optionalAccess', _12 => _12.dryRun])) return changes;
369
+ if (_optionalChain([opts, 'optionalAccess', _11 => _11.dryRun])) return changes;
786
370
  if (!exists) {
787
371
  await M.createCollection().catch((err) => {
788
- if (_optionalChain([err, 'optionalAccess', _13 => _13.code]) !== 48) throw err;
372
+ if (_optionalChain([err, 'optionalAccess', _12 => _12.code]) !== 48) throw err;
789
373
  });
790
374
  }
791
375
  await M.syncIndexes();
792
376
  return changes;
793
377
  },
378
+ // MongoDB has no columns: a migration creates the collection, builds and drops
379
+ // indexes, and moves `renamedFrom` fields in the stored documents.
380
+ async plan() {
381
+ const M = await model();
382
+ const col = M.collection.collectionName;
383
+ const J = (v) => JSON.stringify(v);
384
+ const on = `db.collection(${J(col)})`;
385
+ const steps = [];
386
+ const exists = (await M.db.db.listCollections({ name: col }).toArray()).length > 0;
387
+ if (!exists) {
388
+ steps.push({
389
+ phase: "main",
390
+ sql: `await db.createCollection(${J(col)}).catch((err) => { if (err?.code !== 48) throw err; });`,
391
+ down: `await db.dropCollection(${J(col)}).catch((err) => { if (err?.code !== 26) throw err; });`
392
+ });
393
+ }
394
+ const live = exists ? await M.collection.indexes() : [];
395
+ const diff = await M.diffIndexes().catch(() => ({ toDrop: [], toCreate: [] }));
396
+ for (const idx of diff.toDrop) {
397
+ const spec = live.find((i) => i.name === idx);
398
+ const { key, name: idxName, ...rest } = _nullishCoalesce(spec, () => ( {}));
399
+ delete rest["v"];
400
+ steps.push({
401
+ phase: "main",
402
+ sql: `await ${on}.dropIndex(${J(idx)}).catch((err) => { if (err?.code !== 27) throw err; });`,
403
+ ...key !== void 0 && {
404
+ down: `await ${on}.createIndex(${J(key)}, ${J({ ...rest, name: idxName })});`
405
+ }
406
+ });
407
+ }
408
+ for (const [field, node] of Object.entries(tree)) {
409
+ const from = node.def.renamedFrom;
410
+ if (from === void 0) continue;
411
+ const move = (a, b) => `await ${on}.updateMany({ ${J(a)}: { $exists: true }, ${J(b)}: { $exists: false } }, { $rename: { ${J(a)}: ${J(b)} } });`;
412
+ steps.push({ phase: "main", sql: move(from, field), down: move(field, from) });
413
+ }
414
+ const declared = M.schema.indexes();
415
+ for (const keys of diff.toCreate) {
416
+ const found = declared.find(([k]) => J(k) === J(keys));
417
+ const opts = {};
418
+ for (const [k, v] of Object.entries(_nullishCoalesce(_optionalChain([found, 'optionalAccess', _13 => _13[1]]), () => ( {}))))
419
+ if ([
420
+ "unique",
421
+ "sparse",
422
+ "expireAfterSeconds",
423
+ "name",
424
+ "partialFilterExpression",
425
+ "weights"
426
+ ].includes(k))
427
+ opts[k] = v;
428
+ const idxName = _nullishCoalesce(opts["name"], () => ( Object.entries(keys).map(([k, v]) => `${k}_${String(v)}`).join("_")));
429
+ steps.push({
430
+ phase: "main",
431
+ sql: `await ${on}.createIndex(${J(keys)}, ${J({ ...opts, name: idxName })});`,
432
+ down: `await ${on}.dropIndex(${J(idxName)}).catch(() => {});`
433
+ });
434
+ }
435
+ return steps;
436
+ },
794
437
  async drop() {
795
438
  const M = await model();
796
439
  await M.collection.drop().catch((err) => {
@@ -808,812 +451,11 @@ async function connectMongo(url) {
808
451
  return mg.connection;
809
452
  }
810
453
 
811
- // src/db/pg-table.ts
812
-
813
- var drizzlePromise;
814
- function loadDrizzle() {
815
- drizzlePromise ??= Promise.all([Promise.resolve().then(() => _interopRequireWildcard(require("drizzle-orm"))), Promise.resolve().then(() => _interopRequireWildcard(require("drizzle-orm/pg-core")))]).then(([orm, pgCore]) => ({ sql: orm.sql, pgCore })).catch(() => {
816
- drizzlePromise = void 0;
817
- throw new Error("[EFC] drizzle-orm is not installed. Run: npm install pg drizzle-orm");
818
- });
819
- return drizzlePromise;
820
- }
821
- function tableNameFor(model) {
822
- const lower = model.toLowerCase();
823
- if (/[^aeiou]y$/.test(lower)) return lower.slice(0, -1) + "ies";
824
- if (/(s|x|z|ch|sh)$/.test(lower)) return lower + "es";
825
- return lower + "s";
826
- }
827
- var snakeCase = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase();
828
- var q = (ident) => `"${ident.replace(/"/g, '""')}"`;
829
- var sequenceName = (key) => `efc_seq_${key.replace(/[^A-Za-z0-9_]/g, "_").toLowerCase()}`;
830
- var literal = (v) => typeof v === "number" ? String(v) : `'${v.replace(/'/g, "''")}'`;
831
- var syncing = /* @__PURE__ */ new Map();
832
- var ACTION_SQL = {
833
- restrict: "RESTRICT",
834
- cascade: "CASCADE",
835
- setNull: "SET NULL"
836
- };
837
- var ACTION_CODE = {
838
- restrict: "r",
839
- cascade: "c",
840
- setNull: "n"
841
- };
842
- var ID_COLUMN = {
843
- uuid: { kind: "uuid", type: "uuid" },
844
- serial: { kind: "integer", type: "integer" },
845
- bigserial: { kind: "bigint", type: "bigint" }
846
- };
847
- var modelOfTable = (table) => _nullishCoalesce(_optionalChain([registeredModels, 'call', _15 => _15(), 'access', _16 => _16.find, 'call', _17 => _17((m) => {
848
- try {
849
- return _optionalChain([m, 'access', _18 => _18.pgTarget, 'optionalCall', _19 => _19(), 'access', _20 => _20.table]) === table;
850
- } catch (e2) {
851
- return false;
852
- }
853
- }), 'optionalAccess', _21 => _21.name]), () => ( table));
854
- function scalarSpec(type, def, native) {
855
- switch (type) {
856
- case "string":
857
- if (native && def.maxLength !== void 0) {
858
- return {
859
- kind: "varchar",
860
- ddl: `varchar(${def.maxLength})`,
861
- formatted: `character varying(${def.maxLength})`,
862
- length: def.maxLength
863
- };
864
- }
865
- return { kind: "text", ddl: "text", formatted: "text" };
866
- case "number":
867
- return { kind: "double", ddl: "double precision", formatted: "double precision" };
868
- case "integer":
869
- return { kind: "integer", ddl: "integer", formatted: "integer" };
870
- case "bigint":
871
- return { kind: "bigint", ddl: "bigint", formatted: "bigint", bigintAs: "bigint" };
872
- case "decimal": {
873
- if (def.precision === void 0)
874
- return { kind: "numeric", ddl: "numeric", formatted: "numeric" };
875
- const t = `numeric(${def.precision},${_nullishCoalesce(def.scale, () => ( 0))})`;
876
- return {
877
- kind: "numeric",
878
- ddl: t,
879
- formatted: t,
880
- precision: def.precision,
881
- scale: _nullishCoalesce(def.scale, () => ( 0))
882
- };
883
- }
884
- case "boolean":
885
- return { kind: "boolean", ddl: "boolean", formatted: "boolean" };
886
- case "date":
887
- return { kind: "timestamptz", ddl: "timestamptz", formatted: "timestamp with time zone" };
888
- case "objectId":
889
- case "uuid":
890
- return { kind: "uuid", ddl: "uuid", formatted: "uuid" };
891
- }
892
- }
893
- function pgTable(name, tree, options, config) {
894
- const snake = config.native && options.naming === "snake_case";
895
- const table = _nullishCoalesce(options.collection, () => ( tableNameFor(snake ? snakeCase(name) : name)));
896
- const columnName = (field, def) => _nullishCoalesce(_optionalChain([def, 'optionalAccess', _22 => _22.column]), () => ( (snake ? snakeCase(field) : field)));
897
- const idKind = config.native && options.id || "uuid";
898
- if (tree["id"]) throw new Error(`[EFC] ${name}: "id" is the primary key \u2014 don't declare it`);
899
- const ts = timestampFields(options);
900
- const sequences = sequenceFields(name, tree);
901
- const sequenceKeys = new Map(sequences.map((s) => [s.path, s.key]));
902
- const refs = refFields(tree);
903
- const columns = /* @__PURE__ */ new Map();
904
- const joins = /* @__PURE__ */ new Map();
905
- const idSpec = idKind === "uuid" ? { field: "id", column: "id", kind: "uuid", ddl: "uuid", formatted: "uuid" } : idKind === "serial" ? { field: "id", column: "id", kind: "integer", ddl: "integer", formatted: "integer" } : {
906
- field: "id",
907
- column: "id",
908
- kind: "bigint",
909
- ddl: "bigint",
910
- formatted: "bigint",
911
- bigintAs: "bigint"
912
- };
913
- columns.set("id", idSpec);
914
- for (const [field, node] of Object.entries(tree)) {
915
- const column = columnName(field, node.def);
916
- const base = { field, column, node };
917
- if (sequenceKeys.has(field)) {
918
- columns.set(field, {
919
- ...base,
920
- kind: "bigint",
921
- ddl: "bigint",
922
- formatted: "bigint",
923
- bigintAs: "number"
924
- });
925
- } else if (node.kind === "scalar") {
926
- if (config.native && node.def.nativeEnum && node.def.enum) {
927
- const enumType = `${table}_${column}_enum`;
928
- columns.set(field, {
929
- ...base,
930
- kind: "enum",
931
- ddl: q(enumType),
932
- formatted: /^[a-z_][a-z0-9_]*$/.test(enumType) ? enumType : q(enumType),
933
- enumType,
934
- enumValues: node.def.enum.map(String)
935
- });
936
- } else {
937
- columns.set(field, { ...base, ...scalarSpec(node.type, node.def, config.native) });
938
- }
939
- } else if (config.native && node.kind === "array" && node.item.kind === "scalar" && node.def.ref !== void 0) {
940
- const item = scalarSpec(node.item.type, node.item.def, false).kind;
941
- joins.set(field, {
942
- field,
943
- table: `${table}_${column}`,
944
- legacyColumn: column,
945
- target: node.def.ref,
946
- item,
947
- ddl: `${item}[]`,
948
- node
949
- });
950
- } else if (config.native && node.kind === "array" && node.item.kind === "scalar") {
951
- const item = scalarSpec(node.item.type, node.item.def, false);
952
- columns.set(field, {
953
- ...base,
954
- ...item,
955
- kind: "array",
956
- item: item.kind,
957
- ddl: `${item.ddl}[]`,
958
- formatted: `${item.formatted}[]`
959
- });
960
- } else {
961
- columns.set(field, { ...base, kind: "jsonb", ddl: "jsonb", formatted: "jsonb" });
962
- }
963
- }
964
- for (const field of [ts.createdAt, ts.updatedAt]) {
965
- if (field) {
966
- columns.set(field, {
967
- field,
968
- column: columnName(field),
969
- kind: "timestamptz",
970
- ddl: "timestamptz",
971
- formatted: "timestamp with time zone"
972
- });
973
- }
974
- }
975
- const byColumn = new Map([...columns.values()].map((c) => [c.column, c]));
976
- const builder = (pgCore, kind, spec) => {
977
- const c = spec.column;
978
- switch (kind) {
979
- case "varchar":
980
- return pgCore.varchar(c, { length: spec.length });
981
- case "double":
982
- return pgCore.doublePrecision(c);
983
- case "integer":
984
- return pgCore.integer(c);
985
- case "bigint":
986
- return pgCore.bigint(c, { mode: _nullishCoalesce(spec.bigintAs, () => ( "bigint")) });
987
- case "numeric":
988
- return pgCore.numeric(
989
- c,
990
- spec.precision !== void 0 ? { precision: spec.precision, scale: spec.scale } : {}
991
- );
992
- case "boolean":
993
- return pgCore.boolean(c);
994
- case "timestamptz":
995
- return pgCore.timestamp(c, { withTimezone: true, mode: "date" });
996
- case "uuid":
997
- return pgCore.uuid(c);
998
- default:
999
- return pgCore.text(c);
1000
- }
1001
- };
1002
- let compiled;
1003
- const compile = () => compiled ??= loadDrizzle().then(({ sql, pgCore }) => {
1004
- const cols = {};
1005
- for (const [field, spec] of columns) {
1006
- let c;
1007
- if (spec.kind === "jsonb") c = pgCore.jsonb(spec.column);
1008
- else if (spec.kind === "array") c = builder(pgCore, spec.item, spec).array();
1009
- else c = builder(pgCore, spec.kind, spec);
1010
- if (field === "id") {
1011
- c = idKind === "uuid" ? c.primaryKey().defaultRandom() : c.primaryKey().generatedByDefaultAsIdentity();
1012
- }
1013
- cols[field] = c;
1014
- }
1015
- return { t: pgCore.pgTable(table, cols), sql };
1016
- });
1017
- let synced;
1018
- const ready = async () => {
1019
- const result = await compile();
1020
- if (isAutoSync()) {
1021
- synced ??= reconcile(false).then(
1022
- (changes) => {
1023
- if (changes.length)
1024
- _chunkYL37D6KMcjs.getLogger.call(void 0, ).info({ table, changes: changes.length }, `Synced table ${table}`);
1025
- },
1026
- (err) => {
1027
- synced = void 0;
1028
- throw err;
1029
- }
1030
- );
1031
- await synced;
1032
- }
1033
- return result;
1034
- };
1035
- const client = () => {
1036
- const tx = currentTx();
1037
- return _optionalChain([tx, 'optionalAccess', _23 => _23.engine]) === "postgresql" ? tx.tx : _chunkMGH4VDV3cjs.getOrm.call(void 0, );
1038
- };
1039
- const columnFor = (t, field) => {
1040
- if (!columns.has(field))
1041
- throw new ModelValidationError(name, [{ path: field, message: "unknown field" }]);
1042
- return t[field];
1043
- };
1044
- const scalarToDb = (kind, spec, v) => {
1045
- if (v == null) return v;
1046
- if (kind === "timestamptz") return v instanceof Date ? v : new Date(v);
1047
- if (kind === "bigint")
1048
- return spec.bigintAs === "number" ? Number(v) : BigInt(v);
1049
- if (kind === "numeric") return String(v);
1050
- return v;
1051
- };
1052
- const toDb = (field, value) => {
1053
- const spec = columns.get(field);
1054
- if (!spec || value == null) return value;
1055
- if (spec.kind === "array") {
1056
- return Array.isArray(value) ? value.map((v) => scalarToDb(spec.item, spec, v)) : value;
1057
- }
1058
- if (spec.kind === "jsonb") return value;
1059
- return scalarToDb(spec.kind, spec, value);
1060
- };
1061
- const revive = (node, value) => {
1062
- if (value == null) return value;
1063
- if (node.kind === "scalar") {
1064
- if (node.type === "date" && typeof value === "string") return new Date(value);
1065
- return value;
1066
- }
1067
- if (node.kind === "array" && Array.isArray(value))
1068
- return value.map((v) => revive(node.item, v));
1069
- if (node.kind === "object" && typeof value === "object" && !Array.isArray(value)) {
1070
- const out = { ...value };
1071
- for (const [k, child] of Object.entries(node.fields)) {
1072
- if (out[k] !== void 0) out[k] = revive(child, out[k]);
1073
- }
1074
- return out;
1075
- }
1076
- return value;
1077
- };
1078
- const hasNestedDate = (node) => node.kind === "scalar" ? node.type === "date" : node.kind === "array" ? hasNestedDate(node.item) : node.kind === "object" && Object.values(node.fields).some(hasNestedDate);
1079
- const datedJson = [...columns.values()].filter(
1080
- (c) => c.kind === "jsonb" && c.node && hasNestedDate(c.node)
1081
- );
1082
- const bigintCols = [...columns.values()].filter(
1083
- (c) => c.kind === "bigint" && c.bigintAs === "bigint" || c.kind === "array" && c.item === "bigint"
1084
- );
1085
- const fromRow = (row) => {
1086
- const out = {};
1087
- for (const [k, v] of Object.entries(row)) if (v !== null) out[k] = v;
1088
- for (const c of datedJson)
1089
- if (out[c.field] !== void 0) out[c.field] = revive(c.node, out[c.field]);
1090
- for (const c of bigintCols) {
1091
- const v = out[c.field];
1092
- if (typeof v === "string" || typeof v === "number") out[c.field] = BigInt(v);
1093
- else if (Array.isArray(v)) out[c.field] = v.map((x) => x == null ? x : BigInt(x));
1094
- }
1095
- return out;
1096
- };
1097
- const fromRawRow = (row) => {
1098
- const keyed = {};
1099
- for (const [col, v] of Object.entries(row)) {
1100
- const spec = byColumn.get(col);
1101
- if (!spec) continue;
1102
- keyed[spec.field] = v != null && spec.kind === "timestamptz" && !(v instanceof Date) ? new Date(v) : v;
1103
- }
1104
- return fromRow(keyed);
1105
- };
1106
- const validate = async (data, partial) => {
1107
- const issues = [];
1108
- const checkTree = {};
1109
- for (const [k, node] of Object.entries(tree)) {
1110
- checkTree[k] = sequenceKeys.has(k) ? { ...node, def: { ...node.def, required: false } } : node;
1111
- }
1112
- await validateTree(checkTree, data, issues, partial);
1113
- if (issues.length) throw new ModelValidationError(name, issues);
1114
- };
1115
- const known = (data) => Object.fromEntries(
1116
- Object.entries(data).filter(([k]) => {
1117
- const top = k.split(".")[0];
1118
- return columns.has(top) || joins.has(top);
1119
- })
1120
- );
1121
- const prepareInsert = async (input) => {
1122
- const { id, ...rest } = known(input);
1123
- for (const f of [ts.createdAt, ts.updatedAt]) if (f) delete rest[f];
1124
- const data = applyDefaults(tree, rest, _crypto.randomUUID);
1125
- await validate(data, false);
1126
- const now = /* @__PURE__ */ new Date();
1127
- if (ts.createdAt) data[ts.createdAt] = now;
1128
- if (ts.updatedAt) data[ts.updatedAt] = now;
1129
- if (id !== void 0) data["id"] = id;
1130
- for (const [k, v] of Object.entries(data)) data[k] = toDb(k, v);
1131
- return data;
1132
- };
1133
- const fieldOfColumn = (column) => _nullishCoalesce(_optionalChain([byColumn, 'access', _24 => _24.get, 'call', _25 => _25(column), 'optionalAccess', _26 => _26.field]), () => ( column));
1134
- const guard = async (fn) => {
1135
- try {
1136
- return await fn();
1137
- } catch (err) {
1138
- const e = _nullishCoalesce(err.cause, () => ( err));
1139
- if (_optionalChain([e, 'optionalAccess', _27 => _27.code]) === "42P01") {
1140
- throw new Error(
1141
- `[EFC] ${name}: table "${table}" does not exist \u2014 autoSync is off, so create it with a migration (Model.sync() / efc db sync)`
1142
- );
1143
- }
1144
- if (_optionalChain([e, 'optionalAccess', _28 => _28.code]) === "23505") {
1145
- const cols = _nullishCoalesce(_optionalChain([/\(([^)]+)\)=/, 'access', _29 => _29.exec, 'call', _30 => _30(_nullishCoalesce(e.detail, () => ( ""))), 'optionalAccess', _31 => _31[1]]), () => ( "field"));
1146
- const fields = cols.split(",").map((c) => fieldOfColumn(c.trim().replace(/"/g, ""))).join(", ");
1147
- throw new HttpError(409, `${name} with this ${fields} already exists`);
1148
- }
1149
- if (_optionalChain([e, 'optionalAccess', _32 => _32.code]) === "23503" || _optionalChain([e, 'optionalAccess', _33 => _33.code]) === "23001") {
1150
- const ref = /Key \(([^)]+)\)=\([^)]*\) is not present in table "([^"]+)"/.exec(
1151
- _nullishCoalesce(e.detail, () => ( ""))
1152
- );
1153
- if (ref) {
1154
- throw new ModelValidationError(name, [
1155
- {
1156
- // In a join table: the many-to-many field it backs.
1157
- path: _nullishCoalesce(joinByTable.get(_nullishCoalesce(e.table, () => ( ""))), () => ( fieldOfColumn(ref[1].replace(/"/g, "")))),
1158
- message: `${modelOfTable(ref[2])} not found`
1159
- }
1160
- ]);
1161
- }
1162
- const by = _optionalChain([/is (?:still )?referenced from table "([^"]+)"/, 'access', _34 => _34.exec, 'call', _35 => _35(_nullishCoalesce(e.detail, () => ( ""))), 'optionalAccess', _36 => _36[1]]);
1163
- throw new HttpError(
1164
- 409,
1165
- `${name} is still referenced${by ? ` by ${modelOfTable(by)}` : ""} \u2014 delete or reassign those records first`
1166
- );
1167
- }
1168
- if (_optionalChain([e, 'optionalAccess', _37 => _37.code]) === "23502")
1169
- throw new ModelValidationError(name, [
1170
- { path: fieldOfColumn(_nullishCoalesce(e.column, () => ( ""))), message: "is required" }
1171
- ]);
1172
- if (_optionalChain([e, 'optionalAccess', _38 => _38.code]) === "22P02" || _optionalChain([e, 'optionalAccess', _39 => _39.code]) === "22003" || _optionalChain([e, 'optionalAccess', _40 => _40.code]) === "23514")
1173
- throw new ModelValidationError(name, [{ path: "", message: "invalid value" }]);
1174
- throw err;
1175
- }
1176
- };
1177
- const JSONB_TO_ARRAY = "efc_jsonb_text_array";
1178
- const jsonbToArrayFn = `CREATE OR REPLACE FUNCTION ${JSONB_TO_ARRAY}(j jsonb) RETURNS text[] LANGUAGE sql IMMUTABLE AS $$ SELECT CASE WHEN j IS NULL OR jsonb_typeof(j) = 'null' THEN NULL WHEN jsonb_typeof(j) = 'array' THEN ARRAY(SELECT jsonb_array_elements_text(j)) ELSE ARRAY[j #>> '{}'] END $$`;
1179
- const castExpr = (spec, from) => {
1180
- const c = q(spec.column);
1181
- if (spec.kind === "jsonb") return `to_jsonb(${c})`;
1182
- if (spec.kind === "array") {
1183
- if (from === "jsonb") return `${JSONB_TO_ARRAY}(${c})::${spec.ddl}`;
1184
- if (from.endsWith("[]")) return `${c}::${spec.ddl}`;
1185
- return `CASE WHEN ${c} IS NULL THEN NULL ELSE ARRAY[${c}::text]::${spec.ddl} END`;
1186
- }
1187
- const scalar = from === "jsonb" ? `(${c} #>> '{}')` : c;
1188
- if (spec.kind === "enum") return `${scalar}::text::${spec.ddl}`;
1189
- if (spec.kind === "bigint" || spec.kind === "integer") {
1190
- return `round(${scalar}::numeric)::${spec.ddl}`;
1191
- }
1192
- return `${scalar}::${spec.ddl}`;
1193
- };
1194
- const needsTypeChange = (spec, existing) => {
1195
- if (existing === spec.formatted) return false;
1196
- if (spec.kind === "varchar") {
1197
- if (existing === "text") return false;
1198
- const m = /^character varying\((\d+)\)$/.exec(existing);
1199
- if (m && Number(m[1]) >= spec.length) return false;
1200
- }
1201
- return true;
1202
- };
1203
- const enumCheck = (column) => `${table}_${column}_enum`;
1204
- const fkName = (column) => `${table}_${column}_fkey`;
1205
- const isForeignKey = (spec) => config.native && _optionalChain([spec, 'access', _41 => _41.node, 'optionalAccess', _42 => _42.kind]) === "scalar" && spec.node.def.ref !== void 0;
1206
- function resolveTarget(field, targetName, kind, many) {
1207
- const target = targetName === name ? { table, idKind } : _optionalChain([getRegisteredModel, 'call', _43 => _43(targetName), 'optionalAccess', _44 => _44.pgTarget, 'optionalCall', _45 => _45()]);
1208
- if (!target) {
1209
- throw new Error(
1210
- `[EFC] ${name}.${field} references "${targetName}", which is not defined \u2014 import that model before using ${name}`
1211
- );
1212
- }
1213
- const want = ID_COLUMN[target.idKind];
1214
- if (kind !== want.kind) {
1215
- const hint = many ? `{ type: 'array', of: '${want.type}', ref: '${targetName}' }` : `{ type: '${want.type}', ref: '${targetName}' }`;
1216
- throw new Error(
1217
- `[EFC] ${name}.${field} references ${targetName}, whose id is ${want.type} (id: '${target.idKind}') \u2014 declare it ${hint}`
1218
- );
1219
- }
1220
- return target;
1221
- }
1222
- function foreignKeys() {
1223
- const out = [];
1224
- for (const spec of columns.values()) {
1225
- if (!isForeignKey(spec)) continue;
1226
- const def = spec.node.def;
1227
- const target = resolveTarget(spec.field, def.ref, spec.kind, false);
1228
- out.push({
1229
- field: spec.field,
1230
- onTable: table,
1231
- column: spec.column,
1232
- name: fkName(spec.column),
1233
- target: def.ref,
1234
- targetTable: target.table,
1235
- action: _nullishCoalesce(def.onDelete, () => ( "restrict"))
1236
- });
1237
- }
1238
- for (const join of joins.values()) {
1239
- const target = resolveTarget(join.field, join.target, join.item, true);
1240
- const base = { field: join.field, onTable: join.table, action: "cascade" };
1241
- out.push(
1242
- {
1243
- ...base,
1244
- column: "owner_id",
1245
- name: `${join.table}_owner_id_fkey`,
1246
- target: name,
1247
- targetTable: table
1248
- },
1249
- {
1250
- ...base,
1251
- column: "ref_id",
1252
- name: `${join.table}_ref_id_fkey`,
1253
- target: join.target,
1254
- targetTable: target.table
1255
- }
1256
- );
1257
- }
1258
- return out;
1259
- }
1260
- const joinByTable = new Map([...joins.values()].map((j) => [j.table, j.field]));
1261
- const managedIndexName = /_(key|idx)$/;
1262
- function desiredIndexes() {
1263
- const out = /* @__PURE__ */ new Map();
1264
- for (const spec of columns.values()) {
1265
- const def = _optionalChain([spec, 'access', _46 => _46.node, 'optionalAccess', _47 => _47.def]);
1266
- if (!def) continue;
1267
- const col = spec.column;
1268
- if (def.unique) {
1269
- out.set(
1270
- `${table}_${col}_key`,
1271
- `CREATE UNIQUE INDEX ${q(`${table}_${col}_key`)} ON ${q(table)} (${q(col)})`
1272
- );
1273
- } else if (def.index || isForeignKey(spec) && def.index !== false) {
1274
- out.set(
1275
- `${table}_${col}_idx`,
1276
- `CREATE INDEX ${q(`${table}_${col}_idx`)} ON ${q(table)} (${q(col)})`
1277
- );
1278
- }
1279
- }
1280
- for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
1281
- const fields = Object.entries(idx.fields).map(
1282
- ([f, d]) => [_nullishCoalesce(_optionalChain([columns, 'access', _48 => _48.get, 'call', _49 => _49(f), 'optionalAccess', _50 => _50.column]), () => ( f)), d]
1283
- );
1284
- if (idx.expireAfterSeconds !== void 0) {
1285
- throw new Error(`[EFC] ${name}: TTL indexes (expireAfterSeconds) are MongoDB-only`);
1286
- }
1287
- const idxName = _nullishCoalesce(idx.name, () => ( `${table}_${fields.map(([f]) => f).join("_")}_${idx.unique ? "key" : "idx"}`));
1288
- if (fields.some(([, d]) => d === "text")) {
1289
- const doc = fields.map(([f]) => `coalesce(${q(f)}::text, '')`).join(` || ' ' || `);
1290
- out.set(
1291
- idxName,
1292
- `CREATE INDEX ${q(idxName)} ON ${q(table)} USING gin (to_tsvector('simple', ${doc}))`
1293
- );
1294
- } else {
1295
- const cols = fields.map(([f, d]) => `${q(f)} ${d === -1 ? "DESC" : "ASC"}`).join(", ");
1296
- out.set(
1297
- idxName,
1298
- `CREATE ${idx.unique ? "UNIQUE " : ""}INDEX ${q(idxName)} ON ${q(table)} (${cols})`
1299
- );
1300
- }
1301
- }
1302
- return out;
1303
- }
1304
- const tableExists = async (t) => (await _chunkMGH4VDV3cjs.getPool.call(void 0, ).query(
1305
- `SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
1306
- WHERE c.relname = $1 AND n.nspname = current_schema() AND c.relkind IN ('r', 'p')`,
1307
- [t]
1308
- )).rowCount > 0;
1309
- async function reconcile(dryRun) {
1310
- const fks = foreignKeys();
1311
- if (dryRun) return reconcileTable(true, fks, /* @__PURE__ */ new Set());
1312
- let release;
1313
- const mine = new Promise((resolve) => release = resolve);
1314
- const prev = syncing.get(table);
1315
- syncing.set(table, mine);
1316
- try {
1317
- const deferred = /* @__PURE__ */ new Set();
1318
- const tx = currentTx();
1319
- if (_optionalChain([tx, 'optionalAccess', _51 => _51.engine]) === "postgresql" && fks.length) {
1320
- for (const fk of fks) deferred.add(fk.name);
1321
- tx.afterCommit.push(() => {
1322
- reconcile(false).catch(
1323
- (err) => _chunkYL37D6KMcjs.getLogger.call(void 0, ).error({ err }, `${name}: adding foreign keys to "${table}" failed`)
1324
- );
1325
- });
1326
- }
1327
- for (const fk of fks) {
1328
- if (deferred.has(fk.name)) continue;
1329
- if (fk.targetTable === table || await tableExists(fk.targetTable)) continue;
1330
- const running = syncing.get(fk.targetTable);
1331
- if (running) {
1332
- deferred.add(fk.name);
1333
- void running.then(() => reconcile(false)).catch(
1334
- (err) => _chunkYL37D6KMcjs.getLogger.call(void 0, ).error({ err }, `${name}: adding foreign keys to "${table}" failed`)
1335
- );
1336
- } else {
1337
- await getRegisteredModel(fk.target).sync();
1338
- }
1339
- }
1340
- return await reconcileTable(false, fks, deferred);
1341
- } finally {
1342
- release();
1343
- if (syncing.get(table) === mine) {
1344
- if (prev) syncing.set(table, prev);
1345
- else syncing.delete(table);
1346
- }
1347
- }
1348
- }
1349
- async function reconcileTable(dryRun, fks, deferred) {
1350
- const pool = _chunkMGH4VDV3cjs.getPool.call(void 0, );
1351
- const conn = await pool.connect();
1352
- try {
1353
- await conn.query("BEGIN");
1354
- await conn.query("SELECT pg_advisory_xact_lock(hashtext($1))", [`efc_sync:${table}`]);
1355
- const existing = new Map(
1356
- (await conn.query(
1357
- `SELECT a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, NOT a.attnotnull AS nullable
1358
- FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace
1359
- WHERE c.relname = $1 AND n.nspname = current_schema() AND a.attnum > 0 AND NOT a.attisdropped`,
1360
- [table]
1361
- )).rows.map((r) => [r.name, { type: r.type, nullable: r.nullable }])
1362
- );
1363
- const checks = new Map(
1364
- (await conn.query(
1365
- `SELECT con.conname AS name, pg_get_constraintdef(con.oid) AS def
1366
- FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace
1367
- WHERE c.relname = $1 AND n.nspname = current_schema() AND con.contype = 'c'`,
1368
- [table]
1369
- )).rows.map((r) => [r.name, r.def])
1370
- );
1371
- const indexes = new Set(
1372
- (await conn.query(
1373
- `SELECT indexname AS name FROM pg_indexes WHERE tablename = $1 AND schemaname = current_schema()`,
1374
- [table]
1375
- )).rows.map((r) => r.name)
1376
- );
1377
- const liveFks = new Map(
1378
- (await conn.query(
1379
- `SELECT con.conname AS name, ft.relname AS target, con.confdeltype AS action, con.convalidated AS valid
1380
- FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace
1381
- JOIN pg_class ft ON ft.oid = con.confrelid
1382
- WHERE c.relname = ANY($1) AND n.nspname = current_schema() AND con.contype = 'f'`,
1383
- [[table, ...joinByTable.keys()]]
1384
- )).rows.map((r) => [r.name, r])
1385
- );
1386
- const liveJoinTables = new Set(
1387
- (await conn.query(
1388
- `SELECT c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
1389
- WHERE c.relname = ANY($1) AND n.nspname = current_schema() AND c.relkind IN ('r', 'p')`,
1390
- [[...joinByTable.keys()]]
1391
- )).rows.map((r) => r.name)
1392
- );
1393
- const plan = [];
1394
- const wantedFks = new Map(fks.map((fk) => [fk.name, fk]));
1395
- for (const [con, live] of liveFks) {
1396
- const want = wantedFks.get(con);
1397
- const ours = [...joinByTable.keys()].some((jt) => con.startsWith(`${jt}_`)) || [...columns.values()].some((c) => c.field !== "id" && fkName(c.column) === con);
1398
- if (ours && (!want || live.target !== want.targetTable || live.action !== ACTION_CODE[want.action])) {
1399
- const on = _nullishCoalesce([...joinByTable.keys()].find((jt) => con.startsWith(`${jt}_`)), () => ( table));
1400
- plan.push(`ALTER TABLE ${q(on)} DROP CONSTRAINT ${q(con)}`);
1401
- liveFks.delete(con);
1402
- }
1403
- }
1404
- for (const { key } of sequences) {
1405
- const seq = sequenceName(key);
1406
- const found = await conn.query(
1407
- "SELECT 1 FROM pg_class WHERE relkind = $1 AND relname = $2",
1408
- ["S", seq]
1409
- );
1410
- if (found.rowCount === 0) plan.push(`CREATE SEQUENCE IF NOT EXISTS ${q(seq)}`);
1411
- }
1412
- const enumSpecs = [...columns.values()].filter((c) => c.kind === "enum");
1413
- if (enumSpecs.length) {
1414
- const live = /* @__PURE__ */ new Map();
1415
- for (const r of (await conn.query(
1416
- `SELECT t.typname AS type, e.enumlabel AS label FROM pg_type t
1417
- JOIN pg_namespace n ON n.oid = t.typnamespace LEFT JOIN pg_enum e ON e.enumtypid = t.oid
1418
- WHERE n.nspname = current_schema() AND t.typname = ANY($1)`,
1419
- [enumSpecs.map((c) => c.enumType)]
1420
- )).rows) {
1421
- const set = _nullishCoalesce(live.get(r.type), () => ( /* @__PURE__ */ new Set()));
1422
- if (r.label !== null) set.add(r.label);
1423
- live.set(r.type, set);
1424
- }
1425
- for (const spec of enumSpecs) {
1426
- const have = live.get(spec.enumType);
1427
- if (!have) {
1428
- plan.push(
1429
- `CREATE TYPE ${spec.ddl} AS ENUM (${spec.enumValues.map(literal).join(", ")})`
1430
- );
1431
- } else {
1432
- for (const v of spec.enumValues) {
1433
- if (!have.has(v))
1434
- plan.push(`ALTER TYPE ${spec.ddl} ADD VALUE IF NOT EXISTS ${literal(v)}`);
1435
- }
1436
- }
1437
- }
1438
- }
1439
- const columnSql = (spec) => {
1440
- const seq = sequenceKeys.get(spec.field);
1441
- return `${q(spec.column)} ${spec.ddl}${seq ? ` DEFAULT nextval('${sequenceName(seq)}')` : ""}`;
1442
- };
1443
- const idSql = idKind === "uuid" ? `${q("id")} uuid PRIMARY KEY DEFAULT gen_random_uuid()` : `${q("id")} ${idSpec.ddl} GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY`;
1444
- if (existing.size === 0) {
1445
- const defs = [...columns.values()].map(
1446
- (spec) => spec.field === "id" ? idSql : columnSql(spec)
1447
- );
1448
- plan.push(`CREATE TABLE IF NOT EXISTS ${q(table)} (
1449
- ${defs.join(",\n ")}
1450
- )`);
1451
- } else {
1452
- const alters = [];
1453
- for (const spec of columns.values()) {
1454
- const col = existing.get(spec.column);
1455
- if (!col) {
1456
- alters.push(`ALTER TABLE ${q(table)} ADD COLUMN ${columnSql(spec)}`);
1457
- } else if (spec.field !== "id" && needsTypeChange(spec, col.type)) {
1458
- if (spec.kind === "array" && col.type === "jsonb" && !plan.includes(jsonbToArrayFn))
1459
- plan.push(jsonbToArrayFn);
1460
- alters.push(
1461
- `ALTER TABLE ${q(table)} ALTER COLUMN ${q(spec.column)} TYPE ${spec.ddl} USING ${castExpr(spec, col.type)}`
1462
- );
1463
- }
1464
- }
1465
- plan.push(...new Set(alters));
1466
- for (const [column, col] of existing) {
1467
- if (column !== "id" && !col.nullable) {
1468
- plan.push(`ALTER TABLE ${q(table)} ALTER COLUMN ${q(column)} DROP NOT NULL`);
1469
- }
1470
- }
1471
- }
1472
- const wantedChecks = /* @__PURE__ */ new Map();
1473
- for (const spec of columns.values()) {
1474
- const def = _optionalChain([spec, 'access', _52 => _52.node, 'optionalAccess', _53 => _53.def]);
1475
- if (_optionalChain([spec, 'access', _54 => _54.node, 'optionalAccess', _55 => _55.kind]) === "scalar" && _optionalChain([def, 'optionalAccess', _56 => _56.enum]) && spec.kind !== "enum") {
1476
- wantedChecks.set(
1477
- enumCheck(spec.column),
1478
- `CHECK (${q(spec.column)} IN (${def.enum.map(literal).join(", ")}))`
1479
- );
1480
- }
1481
- }
1482
- for (const [con, def] of checks) {
1483
- const legacy = con.endsWith("_check") && con.startsWith(`${table}_`);
1484
- if (con.endsWith("_enum") && con.startsWith(`${table}_`) && !wantedChecks.has(con) || legacy) {
1485
- plan.push(`ALTER TABLE ${q(table)} DROP CONSTRAINT ${q(con)}`);
1486
- checks.delete(con);
1487
- } else if (wantedChecks.has(con)) {
1488
- const want = wantedChecks.get(con);
1489
- const values = (d) => [...d.matchAll(/'((?:[^']|'')*)'|(-?\d+(?:\.\d+)?)/g)].map((m) => _nullishCoalesce(m[1], () => ( m[2]))).sort().join("|");
1490
- if (values(def) !== values(want)) {
1491
- plan.push(`ALTER TABLE ${q(table)} DROP CONSTRAINT ${q(con)}`);
1492
- checks.delete(con);
1493
- }
1494
- }
1495
- }
1496
- for (const [con, def] of wantedChecks) {
1497
- if (!checks.has(con))
1498
- plan.push(`ALTER TABLE ${q(table)} ADD CONSTRAINT ${q(con)} ${def} NOT VALID`);
1499
- }
1500
- const wantedIndexes = desiredIndexes();
1501
- for (const idx of indexes) {
1502
- if (idx !== `${table}_pkey` && idx.startsWith(`${table}_`) && managedIndexName.test(idx) && !wantedIndexes.has(idx)) {
1503
- plan.push(`DROP INDEX ${q(idx)}`);
1504
- }
1505
- }
1506
- for (const [idx, create] of wantedIndexes) if (!indexes.has(idx)) plan.push(create);
1507
- const ownerDdl = idSpec.ddl;
1508
- for (const join of joins.values()) {
1509
- if (liveJoinTables.has(join.table)) continue;
1510
- const refDdl = join.item;
1511
- plan.push(
1512
- `CREATE TABLE IF NOT EXISTS ${q(join.table)} (
1513
- ${q("owner_id")} ${ownerDdl} NOT NULL,
1514
- ${q("ref_id")} ${refDdl} NOT NULL,
1515
- ${q("position")} integer NOT NULL DEFAULT 0,
1516
- PRIMARY KEY (${q("owner_id")}, ${q("ref_id")})
1517
- )`,
1518
- `CREATE INDEX IF NOT EXISTS ${q(`${join.table}_ref_id_idx`)} ON ${q(join.table)} (${q("ref_id")})`
1519
- );
1520
- const legacy = _optionalChain([existing, 'access', _57 => _57.get, 'call', _58 => _58(join.legacyColumn), 'optionalAccess', _59 => _59.type]);
1521
- if (legacy === "jsonb" || _optionalChain([legacy, 'optionalAccess', _60 => _60.endsWith, 'call', _61 => _61("[]")])) {
1522
- const c = `o.${q(join.legacyColumn)}`;
1523
- const items = legacy === "jsonb" ? `jsonb_array_elements_text(CASE WHEN jsonb_typeof(${c}) = 'array' THEN ${c} ELSE '[]'::jsonb END)` : `unnest(${c}::text[])`;
1524
- const valid = join.item === "uuid" ? `'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'` : `'^-?[0-9]{1,18}$'`;
1525
- plan.push(
1526
- `INSERT INTO ${q(join.table)} (${q("owner_id")}, ${q("ref_id")}, ${q("position")}) SELECT o.${q("id")}, x.v::${refDdl}, x.n FROM ${q(table)} o, ${items} WITH ORDINALITY AS x(v, n) WHERE x.v ~ ${valid} ON CONFLICT DO NOTHING`
1527
- );
1528
- }
1529
- }
1530
- const toValidate = [];
1531
- for (const fk of fks) {
1532
- if (deferred.has(fk.name)) continue;
1533
- const live = liveFks.get(fk.name);
1534
- if (!live) {
1535
- plan.push(
1536
- `ALTER TABLE ${q(fk.onTable)} ADD CONSTRAINT ${q(fk.name)} FOREIGN KEY (${q(fk.column)}) REFERENCES ${q(fk.targetTable)} (${q("id")}) ON DELETE ${ACTION_SQL[fk.action]} NOT VALID`
1537
- );
1538
- }
1539
- if (!_optionalChain([live, 'optionalAccess', _62 => _62.valid])) toValidate.push(fk);
1540
- }
1541
- const validations = toValidate.map(
1542
- (fk) => `ALTER TABLE ${q(fk.onTable)} VALIDATE CONSTRAINT ${q(fk.name)}`
1543
- );
1544
- if (!dryRun) {
1545
- for (const stmt of plan) {
1546
- try {
1547
- await conn.query(stmt);
1548
- } catch (err) {
1549
- throw new Error(
1550
- `[EFC] ${name}: syncing table "${table}" failed on: ${stmt}
1551
- ${err.message}`
1552
- );
1553
- }
1554
- }
1555
- }
1556
- await conn.query(dryRun ? "ROLLBACK" : "COMMIT");
1557
- if (!dryRun) {
1558
- for (const [i, fk] of toValidate.entries()) {
1559
- try {
1560
- await conn.query(validations[i]);
1561
- } catch (e3) {
1562
- const orphans = await conn.query(
1563
- `SELECT count(*) AS n FROM ${q(fk.onTable)} r WHERE ${q(fk.column)} IS NOT NULL
1564
- AND NOT EXISTS (SELECT 1 FROM ${q(fk.targetTable)} t WHERE t.${q("id")} = r.${q(fk.column)})`
1565
- ).then((r) => _nullishCoalesce(_optionalChain([r, 'access', _63 => _63.rows, 'access', _64 => _64[0], 'optionalAccess', _65 => _65.n]), () => ( "?"))).catch(() => "?");
1566
- _chunkYL37D6KMcjs.getLogger.call(void 0, ).warn(
1567
- { table, constraint: fk.name, orphans: Number(orphans) },
1568
- `${name}.${fk.field}: ${orphans} row(s) reference a missing ${fk.target} \u2014 the foreign key applies to new writes; fix those rows, then run efc db sync to validate it`
1569
- );
1570
- }
1571
- }
1572
- }
1573
- return [...plan, ...validations];
1574
- } catch (err) {
1575
- await conn.query("ROLLBACK").catch(() => {
1576
- });
1577
- throw err;
1578
- } finally {
1579
- conn.release();
1580
- }
1581
- }
1582
- async function drop() {
1583
- const { sql } = await compile();
1584
- await client().execute(sql.raw(`DROP TABLE IF EXISTS ${q(table)}`));
1585
- }
1586
- return {
1587
- name,
1588
- table,
1589
- tree,
1590
- idKind,
1591
- columns,
1592
- joins,
1593
- ts,
1594
- sequenceKeys,
1595
- refs,
1596
- compile,
1597
- ready,
1598
- client,
1599
- columnFor,
1600
- toDb,
1601
- fromRow,
1602
- fromRawRow,
1603
- validate,
1604
- known,
1605
- prepareInsert,
1606
- guard,
1607
- reconcile,
1608
- drop
1609
- };
1610
- }
1611
-
1612
454
  // src/db/pg-model.ts
1613
455
  function pgModel(name, tree, options) {
1614
- const tbl = pgTable(name, tree, options, { native: false, api: "defineModel" });
456
+ const tbl = _chunk75O3WQKRcjs.pgTable.call(void 0, name, tree, options, { native: false, api: "defineModel" });
1615
457
  const { columns, ts, refs, ready, compile, client, columnFor, toDb, fromRow, validate, guard } = tbl;
1616
- const kindOf = (field) => _optionalChain([columns, 'access', _66 => _66.get, 'call', _67 => _67(field), 'optionalAccess', _68 => _68.kind]);
458
+ const kindOf = (field) => _optionalChain([columns, 'access', _15 => _15.get, 'call', _16 => _16(field), 'optionalAccess', _17 => _17.kind]);
1617
459
  function missingField(sql, cond) {
1618
460
  const ops = cond !== null && typeof cond === "object" && !Array.isArray(cond) && !(cond instanceof Date) && !(cond instanceof RegExp) ? cond : { $eq: cond };
1619
461
  const matches = Object.entries(ops).every(([op, v]) => {
@@ -1711,7 +553,7 @@ function pgModel(name, tree, options) {
1711
553
  break;
1712
554
  }
1713
555
  default:
1714
- throw new ModelValidationError(name, [
556
+ throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(name, [
1715
557
  { path, message: `operator ${op} is not supported on PostgreSQL` }
1716
558
  ]);
1717
559
  }
@@ -1742,8 +584,8 @@ function pgModel(name, tree, options) {
1742
584
  for (const path of Array.isArray(paths) ? paths : [paths]) {
1743
585
  const ref = refs.get(path);
1744
586
  if (!ref)
1745
- throw new ModelValidationError(name, [{ path, message: "is not a populatable ref field" }]);
1746
- const target = getRegisteredModel(ref.model);
587
+ throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(name, [{ path, message: "is not a populatable ref field" }]);
588
+ const target = _chunk75O3WQKRcjs.getRegisteredModel.call(void 0, ref.model);
1747
589
  if (!target) throw new Error(`[EFC] populate: model "${ref.model}" is not defined`);
1748
590
  const ids = [
1749
591
  ...new Set(
@@ -1769,24 +611,24 @@ function pgModel(name, tree, options) {
1769
611
  };
1770
612
  async function runFind(filter, opts) {
1771
613
  const { t, sql } = await ready();
1772
- const sel = selection(t, _optionalChain([opts, 'optionalAccess', _69 => _69.select]));
614
+ const sel = selection(t, _optionalChain([opts, 'optionalAccess', _18 => _18.select]));
1773
615
  let query = (sel ? client().select(sel) : client().select()).from(t);
1774
616
  const w = where(sql, t, filter);
1775
617
  if (w) query = query.where(w);
1776
- if (_optionalChain([opts, 'optionalAccess', _70 => _70.sort])) {
618
+ if (_optionalChain([opts, 'optionalAccess', _19 => _19.sort])) {
1777
619
  const order = Object.entries(opts.sort).filter(([f]) => columns.has(f)).map(([f, dir]) => {
1778
620
  const col = columnFor(t, f);
1779
621
  return dir === -1 || dir === "desc" ? sql`${col} desc nulls last` : sql`${col} asc nulls first`;
1780
622
  });
1781
623
  if (order.length) query = query.orderBy(...order);
1782
624
  }
1783
- if (_optionalChain([opts, 'optionalAccess', _71 => _71.limit]) !== void 0) query = query.limit(opts.limit);
1784
- if (_optionalChain([opts, 'optionalAccess', _72 => _72.skip]) !== void 0) query = query.offset(opts.skip);
625
+ if (_optionalChain([opts, 'optionalAccess', _20 => _20.limit]) !== void 0) query = query.limit(opts.limit);
626
+ if (_optionalChain([opts, 'optionalAccess', _21 => _21.skip]) !== void 0) query = query.offset(opts.skip);
1785
627
  const rows = (await query).map(fromRow);
1786
- return populate(rows, _optionalChain([opts, 'optionalAccess', _73 => _73.populate]));
628
+ return populate(rows, _optionalChain([opts, 'optionalAccess', _22 => _22.populate]));
1787
629
  }
1788
630
  const strictUpdate = (update) => {
1789
- const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || nodeAt(tree, path.split(".")) !== void 0);
631
+ const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || _chunk75O3WQKRcjs.nodeAt.call(void 0, tree, path.split(".")) !== void 0);
1790
632
  const out = {};
1791
633
  for (const [k, v] of Object.entries(update)) {
1792
634
  if (k.startsWith("$") && v !== null && typeof v === "object") {
@@ -1801,7 +643,7 @@ function pgModel(name, tree, options) {
1801
643
  const ops = update;
1802
644
  for (const op of Object.keys(update).filter((k) => k.startsWith("$"))) {
1803
645
  if (!["$set", "$unset", "$inc", "$push", "$pull"].includes(op)) {
1804
- throw new ModelValidationError(name, [
646
+ throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(name, [
1805
647
  { path: op, message: "update operator is not supported on PostgreSQL" }
1806
648
  ]);
1807
649
  }
@@ -1814,25 +656,25 @@ function pgModel(name, tree, options) {
1814
656
  for (const [k, v] of Object.entries($set)) if (!k.includes(".")) topLevel[k] = v;
1815
657
  for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) if (!k.includes(".")) topLevel[k] = null;
1816
658
  for (const [k, v] of Object.entries($set))
1817
- if (k.includes(".")) await validateAtPath(tree, k, v, issues);
659
+ if (k.includes(".")) await _chunk75O3WQKRcjs.validateAtPath.call(void 0, tree, k, v, issues);
1818
660
  for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) {
1819
- if (k.includes(".")) await validateAtPath(tree, k, null, issues);
661
+ if (k.includes(".")) await _chunk75O3WQKRcjs.validateAtPath.call(void 0, tree, k, null, issues);
1820
662
  }
1821
663
  for (const [k, by] of Object.entries(_nullishCoalesce(ops["$inc"], () => ( {})))) {
1822
664
  if (typeof by !== "number") issues.push({ path: k, message: "$inc needs a number" });
1823
- const node = k.includes(".") ? nodeAt(tree, k.split(".")) : tree[k];
665
+ const node = k.includes(".") ? _chunk75O3WQKRcjs.nodeAt.call(void 0, tree, k.split(".")) : tree[k];
1824
666
  if (node && !(node.kind === "scalar" && node.type === "number") && node.kind !== "json") {
1825
667
  issues.push({ path: k, message: "$inc only applies to number fields" });
1826
668
  }
1827
669
  }
1828
- if (issues.length) throw new ModelValidationError(name, issues);
670
+ if (issues.length) throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(name, issues);
1829
671
  await validate(topLevel, true);
1830
672
  const set = {};
1831
673
  const nested = /* @__PURE__ */ new Map();
1832
674
  const touchedTop = /* @__PURE__ */ new Set();
1833
675
  const acc = (field) => _nullishCoalesce(nested.get(field), () => ( columnFor(t, field)));
1834
676
  const conflict = (path) => {
1835
- throw new ModelValidationError(name, [{ path, message: "conflicting update paths" }]);
677
+ throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(name, [{ path, message: "conflicting update paths" }]);
1836
678
  };
1837
679
  const top = (field, value) => {
1838
680
  if (touchedTop.has(field) || nested.has(field)) conflict(field);
@@ -1892,11 +734,11 @@ function pgModel(name, tree, options) {
1892
734
  if (ts.updatedAt) set[ts.updatedAt] = /* @__PURE__ */ new Date();
1893
735
  return set;
1894
736
  }
1895
- const UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
737
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1896
738
  return {
1897
739
  find: (filter, opts) => guard(async () => await runFind(filter, opts)),
1898
740
  findById: (id, opts) => guard(async () => {
1899
- if (!UUID_RE2.test(id)) return null;
741
+ if (!UUID_RE.test(id)) return null;
1900
742
  return await _asyncNullishCoalesce((await runFind({ id }, { ...opts, limit: 1 }))[0], async () => ( null));
1901
743
  }),
1902
744
  findOne: (filter, opts) => guard(
@@ -1932,7 +774,7 @@ function pgModel(name, tree, options) {
1932
774
  );
1933
775
  }),
1934
776
  update: (id, data) => guard(async () => {
1935
- if (!UUID_RE2.test(id)) return null;
777
+ if (!UUID_RE.test(id)) return null;
1936
778
  const { t, sql } = await ready();
1937
779
  const set = await buildSet(data);
1938
780
  const [row] = await client().update(t).set(set).where(sql`${t.id} = ${id}`).returning();
@@ -1956,7 +798,7 @@ function pgModel(name, tree, options) {
1956
798
  return (await query.returning({ id: t.id })).length;
1957
799
  }),
1958
800
  delete: (id) => guard(async () => {
1959
- if (!UUID_RE2.test(id)) return;
801
+ if (!UUID_RE.test(id)) return;
1960
802
  const { t, sql } = await ready();
1961
803
  await client().delete(t).where(sql`${t.id} = ${id}`);
1962
804
  }),
@@ -1978,7 +820,7 @@ function pgModel(name, tree, options) {
1978
820
  const w = where(sql, t, filter);
1979
821
  if (w) query = query.where(w);
1980
822
  const [row] = await query;
1981
- return _nullishCoalesce(_optionalChain([row, 'optionalAccess', _74 => _74.n]), () => ( 0));
823
+ return _nullishCoalesce(_optionalChain([row, 'optionalAccess', _23 => _23.n]), () => ( 0));
1982
824
  }),
1983
825
  aggregate() {
1984
826
  return Promise.reject(
@@ -1988,7 +830,8 @@ function pgModel(name, tree, options) {
1988
830
  );
1989
831
  },
1990
832
  raw: async () => (await compile()).t,
1991
- sync: (opts) => tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _75 => _75.dryRun]), () => ( false))),
833
+ sync: (opts) => tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _24 => _24.dryRun]), () => ( false))),
834
+ plan: (opts) => tbl.plan(opts),
1992
835
  drop: () => tbl.drop()
1993
836
  };
1994
837
  }
@@ -2002,7 +845,7 @@ function defineModel(name, schema, options) {
2002
845
  return createModel(name, schema, _nullishCoalesce(options, () => ( {})));
2003
846
  }
2004
847
  function distinctFields(tree, options) {
2005
- const ts = timestampFields(options);
848
+ const ts = _chunk75O3WQKRcjs.timestampFields.call(void 0, options);
2006
849
  const fields = /* @__PURE__ */ new Set(["id", ...Object.values(ts)]);
2007
850
  for (const [key, node] of Object.entries(tree)) if (node.kind === "scalar") fields.add(key);
2008
851
  return fields;
@@ -2027,17 +870,17 @@ var MODEL_OPS = [
2027
870
  ];
2028
871
  var sortKey = (v) => v instanceof Date ? v.getTime() : v;
2029
872
  function createModel(name, schema, options, native) {
2030
- const tree = normalizeSchema(schema, "model", name);
873
+ const tree = _chunk75O3WQKRcjs.normalizeSchema.call(void 0, schema, "model", name);
2031
874
  let engineModel;
2032
875
  const impl = () => {
2033
876
  if (engineModel) return engineModel;
2034
- const engine2 = getDbEngine();
2035
- if (native && native.engine !== engine2) {
877
+ const engine = _chunk75O3WQKRcjs.getDbEngine.call(void 0, );
878
+ if (native && native.engine !== engine) {
2036
879
  throw new Error(
2037
- `[EFC] ${name} is a ${ENGINE_LABEL[native.engine]} ${native.kind} (${native.api}) but the app is connected to ${ENGINE_LABEL[engine2]} \u2014 check DATABASE_URL / config.database, or use defineModel for a model that runs on both`
880
+ `[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`
2038
881
  );
2039
882
  }
2040
- engineModel = engine2 === "postgresql" ? pgModel(name, tree, options) : mongoModel(name, tree, options);
883
+ engineModel = engine === "postgresql" ? pgModel(name, tree, options) : mongoModel(name, tree, options);
2041
884
  return engineModel;
2042
885
  };
2043
886
  const call = (fn) => Promise.resolve().then(() => fn(impl()));
@@ -2073,7 +916,7 @@ function createModel(name, schema, options, native) {
2073
916
  try {
2074
917
  return await m.create(create);
2075
918
  } catch (err) {
2076
- if (isHttpError(err) && err.statusCode === 409 && !currentTx()) {
919
+ if (_chunk75O3WQKRcjs.isHttpError.call(void 0, err) && err.statusCode === 409 && !_chunk75O3WQKRcjs.currentTx.call(void 0, )) {
2077
920
  const retried = await m.updateOne(filter, update);
2078
921
  if (retried) return retried;
2079
922
  }
@@ -2090,24 +933,25 @@ function createModel(name, schema, options, native) {
2090
933
  drop: () => call((m) => m.drop())
2091
934
  };
2092
935
  _chunkMGH4VDV3cjs.traceOps.call(void 0, name, model, MODEL_OPS);
2093
- registerModel({
936
+ _chunk75O3WQKRcjs.registerModel.call(void 0, {
2094
937
  name,
2095
938
  sync: model.sync,
939
+ plan: (opts) => call((m) => m.plan(opts)),
2096
940
  drop: model.drop,
2097
941
  findByIds: (ids) => model.find({ id: { $in: ids } }),
2098
- pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => ( tableNameFor(name))), idKind: "uuid" })
942
+ pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => ( _chunk75O3WQKRcjs.tableNameFor.call(void 0, name))), idKind: "uuid" })
2099
943
  });
2100
944
  return model;
2101
945
  }
2102
946
 
2103
947
  // src/db/transaction.ts
2104
948
  async function transaction(fn) {
2105
- if (currentTx()) return fn();
2106
- if (getDbEngine() === "postgresql") {
949
+ if (_chunk75O3WQKRcjs.currentTx.call(void 0, )) return fn();
950
+ if (_chunk75O3WQKRcjs.getDbEngine.call(void 0, ) === "postgresql") {
2107
951
  let result;
2108
952
  const afterCommit = [];
2109
953
  await _chunkMGH4VDV3cjs.getOrm.call(void 0, ).transaction(async (tx) => {
2110
- result = await runInTx({ engine: "postgresql", tx, afterCommit }, fn);
954
+ result = await _chunk75O3WQKRcjs.runInTx.call(void 0, { engine: "postgresql", tx, afterCommit }, fn);
2111
955
  });
2112
956
  for (const run of afterCommit) run();
2113
957
  return result;
@@ -2117,7 +961,7 @@ async function transaction(fn) {
2117
961
  try {
2118
962
  let result;
2119
963
  await session.withTransaction(async () => {
2120
- result = await runInTx({ engine: "mongodb", session }, fn);
964
+ result = await _chunk75O3WQKRcjs.runInTx.call(void 0, { engine: "mongodb", session }, fn);
2121
965
  });
2122
966
  return result;
2123
967
  } finally {
@@ -2126,7 +970,7 @@ async function transaction(fn) {
2126
970
  }
2127
971
 
2128
972
  // src/db/table-model.ts
2129
-
973
+ var _crypto = require('crypto');
2130
974
  var AGGREGATES = ["_count", "_sum", "_avg", "_min", "_max"];
2131
975
  var NUMERIC_KINDS = /* @__PURE__ */ new Set(["double", "integer", "bigint", "numeric"]);
2132
976
  var isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Date) && !(v instanceof RegExp) && typeof v !== "bigint";
@@ -2147,7 +991,7 @@ var BACK_ONE_OPS = /* @__PURE__ */ new Set(["connect", "create", "disconnect", "
2147
991
  var BACK_MANY_OPS = /* @__PURE__ */ new Set(["connect", "create", "disconnect", "set", "delete", "deleteMany"]);
2148
992
  var idJson = (_k, v) => typeof v === "bigint" ? String(v) : v;
2149
993
  var aliasSeq = 0;
2150
- var literal2 = (s) => `'${s.replace(/'/g, "''")}'`;
994
+ var literal = (s) => `'${s.replace(/'/g, "''")}'`;
2151
995
  var JSON_PAIRS_PER_CALL = 50;
2152
996
  var idText = (v) => v == null ? v : String(v);
2153
997
  var dedupe = (items) => {
@@ -2163,11 +1007,11 @@ var TableRuntime = (_class = class {
2163
1007
  constructor(name, schema, options) {;_class.prototype.__init.call(this);
2164
1008
  this.name = name;
2165
1009
  this.options = options;
2166
- const tree = normalizeSchema(schema, "table", name);
2167
- this.tbl = pgTable(name, tree, options, { native: true, api: "defineTable" });
1010
+ const tree = _chunk75O3WQKRcjs.normalizeSchema.call(void 0, schema, "table", name);
1011
+ this.tbl = _chunk75O3WQKRcjs.pgTable.call(void 0, name, tree, options, { native: true, api: "defineTable" });
2168
1012
  this.uniqueSets = [["id"]];
2169
1013
  for (const spec of this.tbl.columns.values()) {
2170
- if (_optionalChain([spec, 'access', _76 => _76.node, 'optionalAccess', _77 => _77.def, 'access', _78 => _78.unique])) this.uniqueSets.push([spec.field]);
1014
+ if (_optionalChain([spec, 'access', _25 => _25.node, 'optionalAccess', _26 => _26.def, 'access', _27 => _27.unique])) this.uniqueSets.push([spec.field]);
2171
1015
  }
2172
1016
  for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
2173
1017
  if (idx.unique) this.uniqueSets.push(Object.keys(idx.fields));
@@ -2191,7 +1035,7 @@ var TableRuntime = (_class = class {
2191
1035
  /** Many-to-many fields as list columns, so filters and projections treat them alike. */
2192
1036
  __init() {this.joinSpecs = /* @__PURE__ */ new Map()}
2193
1037
  fail(path, message) {
2194
- throw new ModelValidationError(this.name, [{ path, message }]);
1038
+ throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(this.name, [{ path, message }]);
2195
1039
  }
2196
1040
  spec(field) {
2197
1041
  return _nullishCoalesce(this.tbl.columns.get(field), () => ( this.joinSpecs.get(field)));
@@ -2202,18 +1046,18 @@ var TableRuntime = (_class = class {
2202
1046
  /** A many-to-many field's ids, in order, for the row `owner` (a table name or alias). */
2203
1047
  joinExpr(sql, join, owner) {
2204
1048
  return sql.raw(
2205
- `coalesce((select array_agg(efc_j.ref_id order by efc_j.position) from ${q(join.table)} efc_j where efc_j.owner_id = ${owner}.${q("id")}), '{}'::${join.ddl})`
1049
+ `coalesce((select array_agg(efc_j.ref_id order by efc_j.position) from ${_chunk75O3WQKRcjs.q.call(void 0, join.table)} efc_j where efc_j.owner_id = ${owner}.${_chunk75O3WQKRcjs.q.call(void 0, "id")}), '{}'::${join.ddl})`
2206
1050
  );
2207
1051
  }
2208
1052
  col(sql, field, alias) {
2209
1053
  const join = this.join(field);
2210
- if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => ( q(this.tbl.table))));
1054
+ if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => ( _chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))));
2211
1055
  const spec = this.spec(field);
2212
- return sql.raw(alias ? `${alias}.${q(spec.column)}` : q(spec.column));
1056
+ return sql.raw(alias ? `${alias}.${_chunk75O3WQKRcjs.q.call(void 0, spec.column)}` : _chunk75O3WQKRcjs.q.call(void 0, spec.column));
2213
1057
  }
2214
1058
  /** SELECT items for the many-to-many fields among `fields`, as text arrays. */
2215
1059
  joinColumns(sql, fields, owner) {
2216
- return fields.filter((f) => this.join(f)).map((f) => sql`${this.col(sql, f, owner)}::text[] as ${sql.raw(q(relAlias(f)))}`);
1060
+ return fields.filter((f) => this.join(f)).map((f) => sql`${this.col(sql, f, owner)}::text[] as ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, relAlias(f)))}`);
2217
1061
  }
2218
1062
  /** `col` for SELECT lists: many-to-many fields come back as text arrays under an alias. */
2219
1063
  selectCols(sql, fields, owner) {
@@ -2487,7 +1331,7 @@ var TableRuntime = (_class = class {
2487
1331
  }
2488
1332
  /** Checks `where` names a unique key (id, a unique field, or a compound unique index). */
2489
1333
  uniqueKey(where, op) {
2490
- const plain = (f) => _optionalChain([where, 'optionalAccess', _79 => _79[f]]) !== void 0 && where[f] !== null && !isPlainObject(where[f]);
1334
+ const plain = (f) => _optionalChain([where, 'optionalAccess', _28 => _28[f]]) !== void 0 && where[f] !== null && !isPlainObject(where[f]);
2491
1335
  const key = this.uniqueSets.find((set) => set.every(plain));
2492
1336
  if (!key) {
2493
1337
  this.fail(
@@ -2505,7 +1349,7 @@ var TableRuntime = (_class = class {
2505
1349
  if (args["cursor"]) {
2506
1350
  this.uniqueKey(args["cursor"], "cursor");
2507
1351
  const cw = this.where(sql, t, args["cursor"]);
2508
- const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(q(this.tbl.table))} where ${cw})`;
1352
+ const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} where ${cw})`;
2509
1353
  const ors = [];
2510
1354
  const same = (o) => sql`${this.col(sql, o.field)} is not distinct from ${at(o.field)}`;
2511
1355
  for (let i = 0; i < order.length; i++) {
@@ -2518,7 +1362,7 @@ var TableRuntime = (_class = class {
2518
1362
  ors.push(eqs.length ? sql`(${sql.join([...eqs, after], sql` and `)})` : after);
2519
1363
  }
2520
1364
  ors.push(sql`(${sql.join(order.map(same), sql` and `)})`);
2521
- parts.push(sql`exists (select 1 from ${sql.raw(q(this.tbl.table))} where ${cw})`);
1365
+ parts.push(sql`exists (select 1 from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} where ${cw})`);
2522
1366
  parts.push(sql`(${sql.join(ors, sql` or `)})`);
2523
1367
  }
2524
1368
  return parts.length ? sql.join(parts, sql` and `) : sql`true`;
@@ -2543,9 +1387,9 @@ var TableRuntime = (_class = class {
2543
1387
  const offset = args["skip"] ? sql` offset ${sql.param(args["skip"])}` : sql``;
2544
1388
  const orderBy = order.length ? sql` order by ${this.orderSql(sql, order)}` : sql``;
2545
1389
  const where = this.readWhere(sql, t, args, order);
2546
- const from = sql.raw(q(this.tbl.table));
2547
- const distinct = _optionalChain([args, 'access', _80 => _80["distinct"], 'optionalAccess', _81 => _81.filter, 'call', _82 => _82((f) => this.spec(f))]);
2548
- if (_optionalChain([distinct, 'optionalAccess', _83 => _83.length])) {
1390
+ const from = sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table));
1391
+ const distinct = _optionalChain([args, 'access', _29 => _29["distinct"], 'optionalAccess', _30 => _30.filter, 'call', _31 => _31((f) => this.spec(f))]);
1392
+ if (_optionalChain([distinct, 'optionalAccess', _32 => _32.length])) {
2549
1393
  const dcols = sql.join(
2550
1394
  distinct.map((f) => this.col(sql, f)),
2551
1395
  sql`, `
@@ -2566,14 +1410,14 @@ var TableRuntime = (_class = class {
2566
1410
  const { t, sql } = await this.ready(args["where"], args["cursor"]);
2567
1411
  return this.tbl.guard(async () => {
2568
1412
  const fields = this.projection(args);
2569
- const distinct = _optionalChain([args, 'access', _84 => _84["distinct"], 'optionalAccess', _85 => _85.some, 'call', _86 => _86((f) => this.spec(f))]);
1413
+ const distinct = _optionalChain([args, 'access', _33 => _33["distinct"], 'optionalAccess', _34 => _34.some, 'call', _35 => _35((f) => this.spec(f))]);
2570
1414
  const cols = this.selectCols(
2571
1415
  sql,
2572
1416
  [.../* @__PURE__ */ new Set(["id", ...fields])],
2573
1417
  distinct ? "efc_distinct" : void 0
2574
1418
  );
2575
1419
  const include = this.includeArg(args);
2576
- const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : q(this.tbl.table), 1) : [];
1420
+ const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : _chunk75O3WQKRcjs.q.call(void 0, this.tbl.table), 1) : [];
2577
1421
  const { query, reversed } = this.readQuery(
2578
1422
  sql,
2579
1423
  t,
@@ -2595,7 +1439,7 @@ var TableRuntime = (_class = class {
2595
1439
  if (this.relationCache) return this.relationCache;
2596
1440
  const out = /* @__PURE__ */ new Map();
2597
1441
  for (const spec of this.tbl.columns.values()) {
2598
- const ref = _optionalChain([spec, 'access', _87 => _87.node, 'optionalAccess', _88 => _88.kind]) === "scalar" ? spec.node.def.ref : void 0;
1442
+ const ref = _optionalChain([spec, 'access', _36 => _36.node, 'optionalAccess', _37 => _37.kind]) === "scalar" ? spec.node.def.ref : void 0;
2599
1443
  if (ref)
2600
1444
  out.set(spec.field, {
2601
1445
  name: spec.field,
@@ -2648,7 +1492,7 @@ var TableRuntime = (_class = class {
2648
1492
  for (const [name, arg] of Object.entries(include)) {
2649
1493
  if (!arg) continue;
2650
1494
  const expr = await this.relationExpr(sql, this.relation(name), relArgs(arg), owner, depth);
2651
- out.push(sql`${expr} as ${sql.raw(q(incAlias(name)))}`);
1495
+ out.push(sql`${expr} as ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, incAlias(name)))}`);
2652
1496
  }
2653
1497
  return out;
2654
1498
  }
@@ -2682,27 +1526,27 @@ var TableRuntime = (_class = class {
2682
1526
  */
2683
1527
  relationSource(rel, owner, a, j) {
2684
1528
  const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
2685
- const target = `${q(T.tbl.table)} ${a}`;
2686
- const ownerId = `${owner}.${q("id")}`;
1529
+ const target = `${_chunk75O3WQKRcjs.q.call(void 0, T.tbl.table)} ${a}`;
1530
+ const ownerId = `${owner}.${_chunk75O3WQKRcjs.q.call(void 0, "id")}`;
2687
1531
  if (rel.via === "fk") {
2688
1532
  return {
2689
1533
  T,
2690
1534
  from: target,
2691
- cond: `${a}.${q("id")} = ${owner}.${q(rel.column)}`,
2692
- defaultOrder: `${a}.${q("id")}`
1535
+ cond: `${a}.${_chunk75O3WQKRcjs.q.call(void 0, "id")} = ${owner}.${_chunk75O3WQKRcjs.q.call(void 0, rel.column)}`,
1536
+ defaultOrder: `${a}.${_chunk75O3WQKRcjs.q.call(void 0, "id")}`
2693
1537
  };
2694
1538
  }
2695
1539
  let from;
2696
1540
  let cond;
2697
1541
  let defaultOrder;
2698
1542
  if (rel.via === "join") {
2699
- from = `${q(rel.join.table)} ${j} join ${target} on ${a}.${q("id")} = ${j}.ref_id`;
1543
+ from = `${_chunk75O3WQKRcjs.q.call(void 0, rel.join.table)} ${j} join ${target} on ${a}.${_chunk75O3WQKRcjs.q.call(void 0, "id")} = ${j}.ref_id`;
2700
1544
  cond = `${j}.owner_id = ${ownerId}`;
2701
1545
  defaultOrder = `${j}.position`;
2702
1546
  } else {
2703
1547
  const join = T.tbl.joins.get(rel.foreignKey);
2704
1548
  const column = T.tbl.columns.get(rel.foreignKey);
2705
- const refs = join ? join.target : _optionalChain([column, 'optionalAccess', _89 => _89.node, 'optionalAccess', _90 => _90.kind]) === "scalar" && column.node.def.ref;
1549
+ const refs = join ? join.target : _optionalChain([column, 'optionalAccess', _38 => _38.node, 'optionalAccess', _39 => _39.kind]) === "scalar" && column.node.def.ref;
2706
1550
  if (refs !== this.name) {
2707
1551
  throw new Error(
2708
1552
  `[EFC] ${this.name}.${rel.name}: ${rel.target}.${rel.foreignKey} must be a ref to ${this.name}`
@@ -2714,7 +1558,7 @@ var TableRuntime = (_class = class {
2714
1558
  `[EFC] ${this.name}.${rel.name}: ${rel.target}.${rel.foreignKey} is many-to-many \u2014 use hasMany`
2715
1559
  );
2716
1560
  }
2717
- from = `${q(join.table)} ${j} join ${target} on ${a}.${q("id")} = ${j}.owner_id`;
1561
+ from = `${_chunk75O3WQKRcjs.q.call(void 0, join.table)} ${j} join ${target} on ${a}.${_chunk75O3WQKRcjs.q.call(void 0, "id")} = ${j}.owner_id`;
2718
1562
  cond = `${j}.ref_id = ${ownerId}`;
2719
1563
  } else {
2720
1564
  if (rel.kind === "one" && !column.node.def.unique) {
@@ -2723,9 +1567,9 @@ var TableRuntime = (_class = class {
2723
1567
  );
2724
1568
  }
2725
1569
  from = target;
2726
- cond = `${a}.${q(column.column)} = ${ownerId}`;
1570
+ cond = `${a}.${_chunk75O3WQKRcjs.q.call(void 0, column.column)} = ${ownerId}`;
2727
1571
  }
2728
- defaultOrder = `${a}.${q("id")}`;
1572
+ defaultOrder = `${a}.${_chunk75O3WQKRcjs.q.call(void 0, "id")}`;
2729
1573
  }
2730
1574
  return { T, from, cond, defaultOrder };
2731
1575
  }
@@ -2750,7 +1594,7 @@ var TableRuntime = (_class = class {
2750
1594
  const where = isPlainObject(w) ? w : { id: w };
2751
1595
  const found = await T.findUnique({ where, select: { id: true } });
2752
1596
  if (!found) {
2753
- throw new ModelValidationError(this.name, [
1597
+ throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(this.name, [
2754
1598
  { path, message: `no ${rel.target} matches ${JSON.stringify(where, idJson)}` }
2755
1599
  ]);
2756
1600
  }
@@ -2842,8 +1686,8 @@ var TableRuntime = (_class = class {
2842
1686
  try {
2843
1687
  await T.updateNested({ where: whereOf(w), data: { [fk]: owner } });
2844
1688
  } catch (err) {
2845
- if (isHttpError(err) && err.statusCode === 404) {
2846
- throw new ModelValidationError(this.name, [
1689
+ if (_chunk75O3WQKRcjs.isHttpError.call(void 0, err) && err.statusCode === 404) {
1690
+ throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(this.name, [
2847
1691
  {
2848
1692
  path: key,
2849
1693
  message: `no ${rel.target} matches ${JSON.stringify(whereOf(w), idJson)}`
@@ -2864,29 +1708,29 @@ var TableRuntime = (_class = class {
2864
1708
  };
2865
1709
  after.push(async (owner) => {
2866
1710
  if (rel.kind === "one") {
2867
- if (mode === "update" && (_optionalChain([ops, 'optionalAccess', _91 => _91["create"]]) || _optionalChain([ops, 'optionalAccess', _92 => _92["connect"]]) || _optionalChain([ops, 'optionalAccess', _93 => _93["disconnect"]]))) {
1711
+ if (mode === "update" && (_optionalChain([ops, 'optionalAccess', _40 => _40["create"]]) || _optionalChain([ops, 'optionalAccess', _41 => _41["connect"]]) || _optionalChain([ops, 'optionalAccess', _42 => _42["disconnect"]]))) {
2868
1712
  await unlink(owner);
2869
1713
  }
2870
- if (_optionalChain([ops, 'optionalAccess', _94 => _94["delete"]])) await T.deleteMany({ where: mine(owner) });
2871
- if (_optionalChain([ops, 'optionalAccess', _95 => _95["connect"]]) !== void 0) await link(owner, ops["connect"]);
2872
- if (_optionalChain([ops, 'optionalAccess', _96 => _96["create"]]) !== void 0) await createChild(owner, ops["create"]);
1714
+ if (_optionalChain([ops, 'optionalAccess', _43 => _43["delete"]])) await T.deleteMany({ where: mine(owner) });
1715
+ if (_optionalChain([ops, 'optionalAccess', _44 => _44["connect"]]) !== void 0) await link(owner, ops["connect"]);
1716
+ if (_optionalChain([ops, 'optionalAccess', _45 => _45["create"]]) !== void 0) await createChild(owner, ops["create"]);
2873
1717
  return;
2874
1718
  }
2875
- if (_optionalChain([ops, 'optionalAccess', _97 => _97["set"]]) !== void 0) {
1719
+ if (_optionalChain([ops, 'optionalAccess', _46 => _46["set"]]) !== void 0) {
2876
1720
  const keep = list(ops["set"]).map(whereOf);
2877
1721
  await unlink(owner, keep.length ? { NOT: { OR: keep } } : void 0);
2878
1722
  for (const w of keep) await link(owner, w);
2879
1723
  }
2880
- for (const w of list(_optionalChain([ops, 'optionalAccess', _98 => _98["disconnect"]]))) await unlink(owner, whereOf(w));
2881
- for (const w of list(_optionalChain([ops, 'optionalAccess', _99 => _99["delete"]])))
1724
+ for (const w of list(_optionalChain([ops, 'optionalAccess', _47 => _47["disconnect"]]))) await unlink(owner, whereOf(w));
1725
+ for (const w of list(_optionalChain([ops, 'optionalAccess', _48 => _48["delete"]])))
2882
1726
  await T.deleteMany({ where: { AND: [mine(owner), whereOf(w)] } });
2883
- if (_optionalChain([ops, 'optionalAccess', _100 => _100["deleteMany"]]) !== void 0) {
1727
+ if (_optionalChain([ops, 'optionalAccess', _49 => _49["deleteMany"]]) !== void 0) {
2884
1728
  for (const w of list(ops["deleteMany"])) {
2885
1729
  await T.deleteMany({ where: { AND: [mine(owner), ...isPlainObject(w) ? [w] : []] } });
2886
1730
  }
2887
1731
  }
2888
- for (const w of list(_optionalChain([ops, 'optionalAccess', _101 => _101["connect"]]))) await link(owner, w);
2889
- for (const c of list(_optionalChain([ops, 'optionalAccess', _102 => _102["create"]]))) await createChild(owner, c);
1732
+ for (const w of list(_optionalChain([ops, 'optionalAccess', _50 => _50["connect"]]))) await link(owner, w);
1733
+ for (const c of list(_optionalChain([ops, 'optionalAccess', _51 => _51["create"]]))) await createChild(owner, c);
2890
1734
  });
2891
1735
  }
2892
1736
  return { data: out, after };
@@ -2988,7 +1832,7 @@ var TableRuntime = (_class = class {
2988
1832
  const a = `efc_f${++aliasSeq}`;
2989
1833
  const { T, from, cond } = this.relationSource(
2990
1834
  rel,
2991
- _nullishCoalesce(owner, () => ( q(this.tbl.table))),
1835
+ _nullishCoalesce(owner, () => ( _chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))),
2992
1836
  a,
2993
1837
  `efc_fj${aliasSeq}`
2994
1838
  );
@@ -3030,13 +1874,13 @@ var TableRuntime = (_class = class {
3030
1874
  const include = this.includeArg(args);
3031
1875
  const pairs = [];
3032
1876
  for (const f of this.projection(args)) {
3033
- if (_optionalChain([include, 'optionalAccess', _103 => _103[f]])) continue;
3034
- pairs.push(sql`${sql.raw(literal2(f))}, ${this.jsonValue(sql, f, alias)}`);
1877
+ if (_optionalChain([include, 'optionalAccess', _52 => _52[f]])) continue;
1878
+ pairs.push(sql`${sql.raw(literal(f))}, ${this.jsonValue(sql, f, alias)}`);
3035
1879
  }
3036
1880
  for (const [name, arg] of Object.entries(_nullishCoalesce(include, () => ( {})))) {
3037
1881
  if (!arg) continue;
3038
1882
  const expr = await this.relationExpr(sql, this.relation(name), relArgs(arg), alias, depth);
3039
- pairs.push(sql`${sql.raw(literal2(name))}, ${expr}`);
1883
+ pairs.push(sql`${sql.raw(literal(name))}, ${expr}`);
3040
1884
  }
3041
1885
  if (pairs.length === 0) return sql`'{}'::jsonb`;
3042
1886
  const chunks = [];
@@ -3061,7 +1905,7 @@ var TableRuntime = (_class = class {
3061
1905
  const include = this.includeArg(args);
3062
1906
  const keyed = {};
3063
1907
  for (const f of this.projection(args)) {
3064
- if (_optionalChain([include, 'optionalAccess', _104 => _104[f]])) continue;
1908
+ if (_optionalChain([include, 'optionalAccess', _53 => _53[f]])) continue;
3065
1909
  const v = json[f];
3066
1910
  const join = this.join(f);
3067
1911
  if (v == null || join) {
@@ -3129,7 +1973,7 @@ var TableRuntime = (_class = class {
3129
1973
  }
3130
1974
  async orThrow(p) {
3131
1975
  const r = await p;
3132
- if (r === null) throw new HttpError(404, `${this.name} not found`);
1976
+ if (r === null) throw new (0, _chunk75O3WQKRcjs.HttpError)(404, `${this.name} not found`);
3133
1977
  return r;
3134
1978
  }
3135
1979
  async count(args = {}) {
@@ -3139,7 +1983,7 @@ var TableRuntime = (_class = class {
3139
1983
  const counted = select ? Object.entries(select).filter(([f, on]) => on && (f === "_all" || this.spec(f))) : [["_all", true]];
3140
1984
  const exprs = sql.join(
3141
1985
  counted.map(
3142
- ([f]) => f === "_all" ? sql`count(*)::int as ${sql.raw(q("_all"))}` : sql`count(${this.col(sql, f, "efc_rows")})::int as ${sql.raw(q(f))}`
1986
+ ([f]) => f === "_all" ? sql`count(*)::int as ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, "_all"))}` : sql`count(${this.col(sql, f, "efc_rows")})::int as ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, f))}`
3143
1987
  ),
3144
1988
  sql`, `
3145
1989
  );
@@ -3214,7 +2058,7 @@ var TableRuntime = (_class = class {
3214
2058
  const specs = this.aggregateSpec(args);
3215
2059
  if (specs.length === 0) return {};
3216
2060
  const exprs = sql.join(
3217
- specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(q(s.alias))}`),
2061
+ specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, s.alias))}`),
3218
2062
  sql`, `
3219
2063
  );
3220
2064
  const { query } = this.readQuery(sql, t, { ...args, select: void 0 }, sql`*`);
@@ -3272,7 +2116,7 @@ var TableRuntime = (_class = class {
3272
2116
  [
3273
2117
  ...by.map((f) => this.col(sql, f)),
3274
2118
  ...specs.map(
3275
- (s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(q(s.alias))}`
2119
+ (s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, s.alias))}`
3276
2120
  )
3277
2121
  ],
3278
2122
  sql`, `
@@ -3296,7 +2140,7 @@ var TableRuntime = (_class = class {
3296
2140
  }
3297
2141
  }
3298
2142
  }
3299
- const query = sql`select ${select} from ${sql.raw(q(this.tbl.table))}${where ? sql` where ${where}` : sql``} group by ${sql.join(
2143
+ const query = sql`select ${select} from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))}${where ? sql` where ${where}` : sql``} group by ${sql.join(
3300
2144
  by.map((f) => this.col(sql, f)),
3301
2145
  sql`, `
3302
2146
  )}${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``}`;
@@ -3374,7 +2218,7 @@ var TableRuntime = (_class = class {
3374
2218
  }
3375
2219
  }
3376
2220
  }
3377
- if (issues.length) throw new ModelValidationError(this.name, issues);
2221
+ if (issues.length) throw new (0, _chunk75O3WQKRcjs.ModelValidationError)(this.name, issues);
3378
2222
  await this.tbl.validate(plain, true);
3379
2223
  for (const [field, v] of Object.entries(plain)) {
3380
2224
  sets.push(
@@ -3416,7 +2260,7 @@ var TableRuntime = (_class = class {
3416
2260
  }
3417
2261
  for (const [field, entries] of byField) {
3418
2262
  const join = this.join(field);
3419
- const jt = sql.raw(q(join.table));
2263
+ const jt = sql.raw(_chunk75O3WQKRcjs.q.call(void 0, join.table));
3420
2264
  const sets = entries.filter((e) => e.op.mode === "set");
3421
2265
  if (sets.length) {
3422
2266
  const owners2 = sets.map((e) => idText(e.id));
@@ -3463,7 +2307,7 @@ var TableRuntime = (_class = class {
3463
2307
  const idDdl = this.tbl.columns.get("id").ddl;
3464
2308
  const owners = sql`${sql.param(ids.map(idText))}::${sql.raw(idDdl)}[]`;
3465
2309
  const parts = joins.map(
3466
- (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(q(j.table))} where owner_id = any(${owners}) group by owner_id`
2310
+ (j) => sql`select ${sql.param(j.field)}::text as f, owner_id::text as o, array_agg(ref_id::text order by position) as ids from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, j.table))} where owner_id = any(${owners}) group by owner_id`
3467
2311
  );
3468
2312
  const { rows } = await this.exec(sql.join(parts, sql` union all `));
3469
2313
  for (const j of joins) out.set(j.field, /* @__PURE__ */ new Map());
@@ -3485,7 +2329,7 @@ var TableRuntime = (_class = class {
3485
2329
  }
3486
2330
  insertSql(sql, t, rows) {
3487
2331
  const fields = [...new Set(rows.flatMap((r) => Object.keys(r)))];
3488
- const head = sql`insert into ${sql.raw(q(this.tbl.table))} (${sql.join(
2332
+ const head = sql`insert into ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} (${sql.join(
3489
2333
  fields.map((f) => this.col(sql, f)),
3490
2334
  sql`, `
3491
2335
  )})`;
@@ -3564,7 +2408,7 @@ var TableRuntime = (_class = class {
3564
2408
  const ops = new Map(split.map((x) => [String(x.row["id"]), x.ops]));
3565
2409
  for (const record of records) {
3566
2410
  for (const join of this.tbl.joins.values()) {
3567
- const op = _optionalChain([ops, 'access', _105 => _105.get, 'call', _106 => _106(String(record["id"])), 'optionalAccess', _107 => _107.find, 'call', _108 => _108((o) => o.field === join.field)]);
2411
+ const op = _optionalChain([ops, 'access', _54 => _54.get, 'call', _55 => _55(String(record["id"])), 'optionalAccess', _56 => _56.find, 'call', _57 => _57((o) => o.field === join.field)]);
3568
2412
  record[join.field] = this.joinValues(join, op ? dedupe(op.items).map(idText) : []);
3569
2413
  }
3570
2414
  }
@@ -3582,7 +2426,7 @@ var TableRuntime = (_class = class {
3582
2426
  return;
3583
2427
  }
3584
2428
  const { rows: ids } = await this.exec(
3585
- sql`select nextval(pg_get_serial_sequence(${sql.param(q(this.tbl.table))}, 'id'))::text as id from generate_series(1, ${sql.param(missing.length)})`
2429
+ sql`select nextval(pg_get_serial_sequence(${sql.param(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))}, 'id'))::text as id from generate_series(1, ${sql.param(missing.length)})`
3586
2430
  );
3587
2431
  missing.forEach((r, i) => {
3588
2432
  const id = ids[i]["id"];
@@ -3611,9 +2455,9 @@ var TableRuntime = (_class = class {
3611
2455
  const where = this.where(sql, t, args["where"]);
3612
2456
  const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
3613
2457
  const extra = links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``;
3614
- const query = sets.length ? sql`update ${sql.raw(q(this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *${extra}` : sql`select *${extra} from ${sql.raw(q(this.tbl.table))} where ${where} limit 1`;
2458
+ const query = sets.length ? sql`update ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *${extra}` : sql`select *${extra} from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} where ${where} limit 1`;
3615
2459
  const [row] = (await this.exec(query)).rows;
3616
- if (!row) throw new HttpError(404, `${this.name} not found`);
2460
+ if (!row) throw new (0, _chunk75O3WQKRcjs.HttpError)(404, `${this.name} not found`);
3617
2461
  const record = this.fromRaw(t, row);
3618
2462
  await this.applyJoins(sql, [{ id: record["id"], ops: joinOps }]);
3619
2463
  await this.refreshJoins(sql, [record], joinOps);
@@ -3634,7 +2478,7 @@ var TableRuntime = (_class = class {
3634
2478
  const links = returning ? this.joinColumns(sql, [...this.tbl.joins.keys()]) : [];
3635
2479
  const list = returning ? sql` returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : joinOps.length ? sql` returning ${this.col(sql, "id")}` : sql``;
3636
2480
  const result = await this.exec(
3637
- sets.length ? sql`update ${sql.raw(q(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(q(this.tbl.table))} where ${where}`
2481
+ sets.length ? sql`update ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where}${list}` : sql`select ${returning ? sql`*${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : this.col(sql, "id")} from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} where ${where}`
3638
2482
  );
3639
2483
  const records = result.rows.map((r) => returning ? this.fromRaw(t, r) : r);
3640
2484
  await this.applyJoins(
@@ -3658,7 +2502,7 @@ var TableRuntime = (_class = class {
3658
2502
  if (row[f] === void 0) row[f] = this.tbl.toDb(f, args["where"][f]);
3659
2503
  }
3660
2504
  const { head, values } = this.insertSql(sql, t, [row]);
3661
- const table = q(this.tbl.table);
2505
+ const table = _chunk75O3WQKRcjs.q.call(void 0, this.tbl.table);
3662
2506
  const update = await this.setList(sql, t, _nullishCoalesce(args["update"], () => ( {})), table);
3663
2507
  const { joinOps } = update;
3664
2508
  let { sets } = update;
@@ -3679,7 +2523,7 @@ var TableRuntime = (_class = class {
3679
2523
  const [out] = (await this.exec(
3680
2524
  sql`${head} values ${values} on conflict (${target}) do update set ${sql.join(sets, sql`, `)}${cond}${returning}`
3681
2525
  )).rows;
3682
- if (!out) throw new HttpError(404, `${this.name} not found`);
2526
+ if (!out) throw new (0, _chunk75O3WQKRcjs.HttpError)(404, `${this.name} not found`);
3683
2527
  const record = this.fromRaw(t, out);
3684
2528
  if (linked) {
3685
2529
  const ops = out["efc_inserted"] ? createOps.filter((o) => o.items.length) : joinOps;
@@ -3698,9 +2542,9 @@ var TableRuntime = (_class = class {
3698
2542
  const where = this.where(sql, t, args["where"]);
3699
2543
  const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
3700
2544
  const [row] = (await this.exec(
3701
- sql`delete from ${sql.raw(q(this.tbl.table))} where ${where} returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}`
2545
+ sql`delete from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} where ${where} returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}`
3702
2546
  )).rows;
3703
- if (!row) throw new HttpError(404, `${this.name} not found`);
2547
+ if (!row) throw new (0, _chunk75O3WQKRcjs.HttpError)(404, `${this.name} not found`);
3704
2548
  return this.project(this.fromRaw(t, row), this.projection(args));
3705
2549
  });
3706
2550
  }
@@ -3708,7 +2552,7 @@ var TableRuntime = (_class = class {
3708
2552
  const { t, sql } = await this.ready(args["where"]);
3709
2553
  return this.tbl.guard(async () => {
3710
2554
  const where = _nullishCoalesce(this.where(sql, t, args["where"]), () => ( sql`true`));
3711
- const result = await this.tbl.client().execute(sql`delete from ${sql.raw(q(this.tbl.table))} where ${where}`);
2555
+ const result = await this.tbl.client().execute(sql`delete from ${sql.raw(_chunk75O3WQKRcjs.q.call(void 0, this.tbl.table))} where ${where}`);
3712
2556
  return { count: _nullishCoalesce(result.rowCount, () => ( 0)) };
3713
2557
  });
3714
2558
  }
@@ -3717,10 +2561,10 @@ function relArgs(arg) {
3717
2561
  return isPlainObject(arg) ? arg : {};
3718
2562
  }
3719
2563
  function runtimeOf(name, from) {
3720
- const runtime = _optionalChain([getRegisteredModel, 'call', _109 => _109(name), 'optionalAccess', _110 => _110.tableRuntime, 'optionalCall', _111 => _111()]);
2564
+ const runtime = _optionalChain([_chunk75O3WQKRcjs.getRegisteredModel.call(void 0, name), 'optionalAccess', _58 => _58.tableRuntime, 'optionalCall', _59 => _59()]);
3721
2565
  if (!runtime) {
3722
2566
  throw new Error(
3723
- getRegisteredModel(name) ? `[EFC] ${from}: include needs ${name} to be a defineTable model` : `[EFC] ${from}: "${name}" is not defined \u2014 import that model before including it`
2567
+ _chunk75O3WQKRcjs.getRegisteredModel.call(void 0, name) ? `[EFC] ${from}: include needs ${name} to be a defineTable model` : `[EFC] ${from}: "${name}" is not defined \u2014 import that model before including it`
3724
2568
  );
3725
2569
  }
3726
2570
  return runtime;
@@ -3740,7 +2584,7 @@ var JSON_OPS = /* @__PURE__ */ new Set([
3740
2584
  "mode"
3741
2585
  ]);
3742
2586
  function createTable(name, schema, options = {}) {
3743
- normalizeSchema(schema, "table", name);
2587
+ _chunk75O3WQKRcjs.normalizeSchema.call(void 0, schema, "table", name);
3744
2588
  for (const [rel, def] of Object.entries(_nullishCoalesce(options.relations, () => ( {})))) {
3745
2589
  const where = `[EFC] ${name}.relations.${rel}`;
3746
2590
  if (rel in schema) throw new Error(`${where}: a field already has this name`);
@@ -3755,8 +2599,8 @@ function createTable(name, schema, options = {}) {
3755
2599
  }
3756
2600
  let runtime;
3757
2601
  const rt = () => {
3758
- const engine2 = getDbEngine();
3759
- if (engine2 !== "postgresql") {
2602
+ const engine = _chunk75O3WQKRcjs.getDbEngine.call(void 0, );
2603
+ if (engine !== "postgresql") {
3760
2604
  throw new Error(
3761
2605
  `[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`
3762
2606
  );
@@ -3775,16 +2619,16 @@ function createTable(name, schema, options = {}) {
3775
2619
  aggregate: (args) => call((r) => r.aggregate(args)),
3776
2620
  groupBy: (args) => call((r) => r.groupBy(args)),
3777
2621
  create: (args) => call((r) => r.withInclude(args, (a) => r.createNested(a))),
3778
- createMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _112 => _112["data"]]), "createMany"), r.createMany(args, false))),
3779
- createManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _113 => _113["data"]]), "createMany"), r.createMany(args, true))),
2622
+ createMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _60 => _60["data"]]), "createMany"), r.createMany(args, false))),
2623
+ createManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _61 => _61["data"]]), "createMany"), r.createMany(args, true))),
3780
2624
  update: (args) => call((r) => r.withInclude(args, (a) => r.updateNested(a))),
3781
- updateMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _114 => _114["data"]]), "updateMany"), r.updateMany(args, false))),
3782
- updateManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _115 => _115["data"]]), "updateMany"), r.updateMany(args, true))),
2625
+ updateMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _62 => _62["data"]]), "updateMany"), r.updateMany(args, false))),
2626
+ updateManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _63 => _63["data"]]), "updateMany"), r.updateMany(args, true))),
3783
2627
  upsert: (args) => call((r) => r.withInclude(args, (a) => r.upsertNested(a))),
3784
2628
  delete: (args) => call((r) => r.deleteWithInclude(args)),
3785
2629
  deleteMany: (args) => call((r) => r.deleteMany(args)),
3786
2630
  raw: () => call(async (r) => (await r.tbl.compile()).t),
3787
- sync: (opts) => call((r) => r.tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _116 => _116.dryRun]), () => ( false)))),
2631
+ sync: (opts) => call((r) => r.tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _64 => _64.dryRun]), () => ( false)))),
3788
2632
  drop: () => call((r) => r.tbl.drop())
3789
2633
  };
3790
2634
  _chunkMGH4VDV3cjs.traceOps.call(void 0,
@@ -3792,9 +2636,10 @@ function createTable(name, schema, options = {}) {
3792
2636
  model,
3793
2637
  Object.keys(model).filter((op) => !["name", "raw", "sync", "drop"].includes(op))
3794
2638
  );
3795
- registerModel({
2639
+ _chunk75O3WQKRcjs.registerModel.call(void 0, {
3796
2640
  name,
3797
2641
  sync: model.sync,
2642
+ plan: (opts) => call((r) => r.tbl.plan(opts)),
3798
2643
  drop: model.drop,
3799
2644
  findByIds: (ids) => model.findMany({ where: { id: { in: ids } } }),
3800
2645
  pgTarget: () => ({ table: rt().tbl.table, idKind: rt().tbl.idKind }),
@@ -3837,11 +2682,5 @@ var db = new Proxy({}, {
3837
2682
 
3838
2683
 
3839
2684
 
3840
-
3841
-
3842
-
3843
-
3844
-
3845
-
3846
- exports.HttpError = HttpError; exports.isHttpError = isHttpError; exports.ModelValidationError = ModelValidationError; exports.setDbEngine = setDbEngine; exports.setAutoSync = setAutoSync; exports.registeredModels = registeredModels; exports.connectMongo = connectMongo; exports.defineModel = defineModel; exports.transaction = transaction; exports.defineTable = defineTable; exports.setDbClient = setDbClient; exports.getDbClient = getDbClient; exports.db = db;
3847
- //# sourceMappingURL=chunk-AZYXQU3Z.cjs.map
2685
+ exports.connectMongo = connectMongo; exports.defineModel = defineModel; exports.transaction = transaction; exports.defineTable = defineTable; exports.setDbClient = setDbClient; exports.getDbClient = getDbClient; exports.db = db;
2686
+ //# sourceMappingURL=chunk-FQFKHPLR.cjs.map