express-file-cluster 0.9.6 → 0.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/index.cjs +7 -6
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +5 -5
- package/dist/chunk-3SWI46YK.js +74 -0
- package/dist/chunk-3SWI46YK.js.map +1 -0
- package/dist/{chunk-DCJOWFVD.cjs → chunk-4GHK27JA.cjs} +3 -3
- package/dist/{chunk-DCJOWFVD.cjs.map → chunk-4GHK27JA.cjs.map} +1 -1
- package/dist/{chunk-NI2BNGGV.js → chunk-5LPRKZPB.js} +2 -2
- package/dist/chunk-74BSJXWD.cjs +220 -0
- package/dist/chunk-74BSJXWD.cjs.map +1 -0
- package/dist/{chunk-6KHBJOLB.cjs → chunk-7BC3AN7R.cjs} +14 -14
- package/dist/{chunk-6KHBJOLB.cjs.map → chunk-7BC3AN7R.cjs.map} +1 -1
- package/dist/chunk-AGOYTFRO.cjs +42 -0
- package/dist/chunk-AGOYTFRO.cjs.map +1 -0
- package/dist/{chunk-HBYSKULC.js → chunk-B6MB6HEG.js} +5 -1
- package/dist/chunk-B6MB6HEG.js.map +1 -0
- package/dist/{chunk-OFA7OGN5.js → chunk-BG4A7Z32.js} +176 -7
- package/dist/chunk-BG4A7Z32.js.map +1 -0
- package/dist/{chunk-45BWAR6P.js → chunk-C2FOZ7ME.js} +4 -4
- package/dist/chunk-CGY7JU4Y.cjs +8 -0
- package/dist/chunk-CGY7JU4Y.cjs.map +1 -0
- package/dist/{chunk-BBSZLGZW.js → chunk-DN4TCGYB.js} +43 -14
- package/dist/chunk-DN4TCGYB.js.map +1 -0
- package/dist/{chunk-TI24L4XE.cjs → chunk-H2PVWCWC.cjs} +6 -2
- package/dist/chunk-H2PVWCWC.cjs.map +1 -0
- package/dist/{chunk-TYCYYLLM.cjs → chunk-IUZ6A7PB.cjs} +20 -53
- package/dist/chunk-IUZ6A7PB.cjs.map +1 -0
- package/dist/{chunk-DUADUR6R.cjs → chunk-JP36TLL4.cjs} +171 -14
- package/dist/chunk-JP36TLL4.cjs.map +1 -0
- package/dist/chunk-KLWL7XSC.js +220 -0
- package/dist/chunk-KLWL7XSC.js.map +1 -0
- package/dist/{chunk-QL6EWT4B.cjs → chunk-M53GODCX.cjs} +44 -15
- package/dist/chunk-M53GODCX.cjs.map +1 -0
- package/dist/{chunk-7ZESZG3J.js → chunk-MUVO7MGS.js} +4 -4
- package/dist/{chunk-VWSUQKCJ.cjs → chunk-R2K7AFIB.cjs} +286 -117
- package/dist/chunk-R2K7AFIB.cjs.map +1 -0
- package/dist/{chunk-ULWNHN6P.js → chunk-RETV3GKE.js} +9 -42
- package/dist/chunk-RETV3GKE.js.map +1 -0
- package/dist/{chunk-7YEX4MQV.cjs → chunk-RPL2IFWK.cjs} +46 -7
- package/dist/chunk-RPL2IFWK.cjs.map +1 -0
- package/dist/{chunk-FMA76PRH.cjs → chunk-TBIVIR6L.cjs} +15 -15
- package/dist/{chunk-FMA76PRH.cjs.map → chunk-TBIVIR6L.cjs.map} +1 -1
- package/dist/{chunk-73XJUT2S.js → chunk-V73R76I4.js} +162 -5
- package/dist/chunk-V73R76I4.js.map +1 -0
- package/dist/chunk-XPY5TQDK.js +42 -0
- package/dist/chunk-XPY5TQDK.js.map +1 -0
- package/dist/{chunk-RGT4ZVHL.cjs → chunk-Y4NKIXUL.cjs} +110 -55
- package/dist/chunk-Y4NKIXUL.cjs.map +1 -0
- package/dist/{chunk-2SETEVMO.js → chunk-Y75V5FCU.js} +100 -45
- package/dist/chunk-Y75V5FCU.js.map +1 -0
- package/dist/cli/db-runner.cjs +2059 -126
- package/dist/cli/db-runner.cjs.map +1 -1
- package/dist/cli/db-runner.js +2034 -102
- package/dist/cli/db-runner.js.map +1 -1
- package/dist/cli/index.cjs +50 -29
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +39 -21
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +23 -0
- package/dist/docs/api-reference/collection.md +44 -1
- package/dist/docs/api-reference/compose.md +1 -1
- package/dist/docs/api-reference/db.md +8 -0
- package/dist/docs/api-reference/ignite.md +13 -1
- package/dist/docs/api-reference/testing.md +26 -0
- package/dist/docs/api-reference/types.md +99 -0
- package/dist/docs/cli/add.md +2 -2
- package/dist/docs/cli/db.md +2 -2
- package/dist/docs/core-concepts/background-tasks.md +6 -3
- package/dist/docs/core-concepts/file-based-routing.md +2 -0
- package/dist/docs/core-concepts/middleware.md +2 -2
- package/dist/docs/getting-started/index.md +6 -1
- package/dist/docs/guides/authentication.md +33 -0
- package/dist/docs/guides/caching.md +34 -1
- package/dist/docs/guides/database.md +17 -0
- package/dist/docs/guides/environment-variables.md +6 -0
- package/dist/docs/guides/feature-matrix.md +58 -0
- package/dist/docs/guides/generated-portals.md +3 -1
- package/dist/docs/guides/logging.md +17 -0
- package/dist/docs/guides/migrations.md +26 -3
- package/dist/docs/guides/testing.md +31 -0
- package/dist/docs/guides/which-api.md +2 -2
- package/dist/docs/index.md +4 -1
- package/dist/docs/skills/SKILL.md +5 -1
- package/dist/docs/skills/api-surface.md +25 -4
- package/dist/docs/skills/auth-internals.md +14 -1
- package/dist/docs/skills/pre-flight.md +6 -0
- package/dist/docs/skills/routing-rules.md +1 -1
- package/dist/docs/skills/tasks-internals.md +4 -3
- package/dist/docs/skills/what-not-to-invent.md +13 -4
- package/dist/docs/versioning.md +1 -1
- package/dist/index.cjs +135 -255
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +228 -3
- package/dist/index.d.ts +228 -3
- package/dist/index.js +96 -217
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-4X2YT4RB.js +14 -0
- package/dist/pgboss-backend-UXQ3O2WT.cjs +15 -0
- package/dist/pgboss-backend-UXQ3O2WT.cjs.map +1 -0
- package/dist/registry/index.json +39 -3
- package/dist/registry/js-mongo/account-security.json +1 -1
- package/dist/registry/js-mongo/admin-users.json +1 -1
- package/dist/registry/js-mongo/auth.json +1 -1
- package/dist/registry/js-mongo/auth@apple.json +1 -1
- package/dist/registry/js-mongo/auth@google.json +1 -1
- package/dist/registry/js-mongo/forgot-password.json +1 -1
- package/dist/registry/js-mongo/user-profile.json +1 -1
- package/dist/registry/js-mongo-collection/_base.json +1 -0
- package/dist/registry/js-mongo-collection/account-security.json +1 -0
- package/dist/registry/js-mongo-collection/account-settings.json +1 -0
- package/dist/registry/js-mongo-collection/admin-admins.json +1 -0
- package/dist/registry/js-mongo-collection/admin-analytics.json +1 -0
- package/dist/registry/js-mongo-collection/admin-billing.json +1 -0
- package/dist/registry/js-mongo-collection/admin-content.json +1 -0
- package/dist/registry/js-mongo-collection/admin-logs.json +1 -0
- package/dist/registry/js-mongo-collection/admin-support.json +1 -0
- package/dist/registry/js-mongo-collection/admin-system.json +1 -0
- package/dist/registry/js-mongo-collection/admin-users.json +1 -0
- package/dist/registry/js-mongo-collection/admin.json +1 -0
- package/dist/registry/js-mongo-collection/auth.json +1 -0
- package/dist/registry/js-mongo-collection/auth@apple.json +1 -0
- package/dist/registry/js-mongo-collection/auth@google.json +1 -0
- package/dist/registry/js-mongo-collection/billing.json +1 -0
- package/dist/registry/js-mongo-collection/email-client.json +1 -0
- package/dist/registry/js-mongo-collection/email-verification.json +1 -0
- package/dist/registry/js-mongo-collection/files.json +1 -0
- package/dist/registry/js-mongo-collection/forgot-password.json +1 -0
- package/dist/registry/js-mongo-collection/notifications.json +1 -0
- package/dist/registry/js-mongo-collection/support.json +1 -0
- package/dist/registry/js-mongo-collection/user-profile.json +1 -0
- package/dist/registry/js-pg-model/account-security.json +1 -1
- package/dist/registry/js-pg-model/admin-users.json +1 -1
- package/dist/registry/js-pg-model/auth.json +1 -1
- package/dist/registry/js-pg-model/auth@apple.json +1 -1
- package/dist/registry/js-pg-model/auth@google.json +1 -1
- package/dist/registry/js-pg-model/forgot-password.json +1 -1
- package/dist/registry/js-pg-model/user-profile.json +1 -1
- package/dist/registry/js-pg-table/account-security.json +1 -1
- package/dist/registry/js-pg-table/admin-users.json +1 -1
- package/dist/registry/js-pg-table/auth.json +1 -1
- package/dist/registry/js-pg-table/auth@apple.json +1 -1
- package/dist/registry/js-pg-table/auth@google.json +1 -1
- package/dist/registry/js-pg-table/forgot-password.json +1 -1
- package/dist/registry/js-pg-table/user-profile.json +1 -1
- package/dist/registry/ts-mongo/account-security.json +1 -1
- package/dist/registry/ts-mongo/admin-users.json +1 -1
- package/dist/registry/ts-mongo/auth.json +1 -1
- package/dist/registry/ts-mongo/auth@apple.json +1 -1
- package/dist/registry/ts-mongo/auth@google.json +1 -1
- package/dist/registry/ts-mongo/forgot-password.json +1 -1
- package/dist/registry/ts-mongo/user-profile.json +1 -1
- package/dist/registry/ts-mongo-collection/_base.json +1 -0
- package/dist/registry/ts-mongo-collection/account-security.json +1 -0
- package/dist/registry/ts-mongo-collection/account-settings.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-admins.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-analytics.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-billing.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-content.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-logs.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-support.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-system.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-users.json +1 -0
- package/dist/registry/ts-mongo-collection/admin.json +1 -0
- package/dist/registry/ts-mongo-collection/auth.json +1 -0
- package/dist/registry/ts-mongo-collection/auth@apple.json +1 -0
- package/dist/registry/ts-mongo-collection/auth@google.json +1 -0
- package/dist/registry/ts-mongo-collection/billing.json +1 -0
- package/dist/registry/ts-mongo-collection/email-client.json +1 -0
- package/dist/registry/ts-mongo-collection/email-verification.json +1 -0
- package/dist/registry/ts-mongo-collection/files.json +1 -0
- package/dist/registry/ts-mongo-collection/forgot-password.json +1 -0
- package/dist/registry/ts-mongo-collection/notifications.json +1 -0
- package/dist/registry/ts-mongo-collection/support.json +1 -0
- package/dist/registry/ts-mongo-collection/user-profile.json +1 -0
- package/dist/registry/ts-pg-model/account-security.json +1 -1
- package/dist/registry/ts-pg-model/admin-users.json +1 -1
- package/dist/registry/ts-pg-model/auth.json +1 -1
- package/dist/registry/ts-pg-model/auth@apple.json +1 -1
- package/dist/registry/ts-pg-model/auth@google.json +1 -1
- package/dist/registry/ts-pg-model/forgot-password.json +1 -1
- package/dist/registry/ts-pg-model/user-profile.json +1 -1
- package/dist/registry/ts-pg-table/account-security.json +1 -1
- package/dist/registry/ts-pg-table/admin-users.json +1 -1
- package/dist/registry/ts-pg-table/auth.json +1 -1
- package/dist/registry/ts-pg-table/auth@apple.json +1 -1
- package/dist/registry/ts-pg-table/auth@google.json +1 -1
- package/dist/registry/ts-pg-table/forgot-password.json +1 -1
- package/dist/registry/ts-pg-table/user-profile.json +1 -1
- package/dist/tasks/index.cjs +5 -2
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +4 -2
- package/dist/tasks/index.d.ts +4 -2
- package/dist/tasks/index.js +3 -1
- package/dist/testing-cjs.cjs +5 -0
- package/dist/testing.cjs +59 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +27 -0
- package/dist/testing.d.ts +27 -0
- package/dist/testing.js +58 -0
- package/dist/testing.js.map +1 -0
- package/dist/thread-runner.cjs +9 -0
- package/dist/thread-runner.cjs.map +1 -0
- package/dist/thread-runner.d.cts +3 -0
- package/dist/thread-runner.d.ts +3 -0
- package/dist/thread-runner.js +8 -0
- package/dist/thread-runner.js.map +1 -0
- package/dist/{types-DAsBKVM-.d.ts → types-CPMFTVXm.d.cts} +15 -1
- package/dist/{types-DAsBKVM-.d.cts → types-CPMFTVXm.d.ts} +15 -1
- package/package.json +6 -1
- package/dist/chunk-2SETEVMO.js.map +0 -1
- package/dist/chunk-73XJUT2S.js.map +0 -1
- package/dist/chunk-7YEX4MQV.cjs.map +0 -1
- package/dist/chunk-BBSZLGZW.js.map +0 -1
- package/dist/chunk-DUADUR6R.cjs.map +0 -1
- package/dist/chunk-HBYSKULC.js.map +0 -1
- package/dist/chunk-LJNSJFOL.js +0 -38
- package/dist/chunk-LJNSJFOL.js.map +0 -1
- package/dist/chunk-OFA7OGN5.js.map +0 -1
- package/dist/chunk-QL6EWT4B.cjs.map +0 -1
- package/dist/chunk-RGT4ZVHL.cjs.map +0 -1
- package/dist/chunk-TI24L4XE.cjs.map +0 -1
- package/dist/chunk-TYCYYLLM.cjs.map +0 -1
- package/dist/chunk-ULWNHN6P.js.map +0 -1
- package/dist/chunk-VWSUQKCJ.cjs.map +0 -1
- package/dist/pgboss-backend-DSO3QTNK.cjs +0 -14
- package/dist/pgboss-backend-DSO3QTNK.cjs.map +0 -1
- package/dist/pgboss-backend-I6DFUNRM.js +0 -14
- /package/dist/{chunk-NI2BNGGV.js.map → chunk-5LPRKZPB.js.map} +0 -0
- /package/dist/{chunk-45BWAR6P.js.map → chunk-C2FOZ7ME.js.map} +0 -0
- /package/dist/{chunk-7ZESZG3J.js.map → chunk-MUVO7MGS.js.map} +0 -0
- /package/dist/{pgboss-backend-I6DFUNRM.js.map → pgboss-backend-4X2YT4RB.js.map} +0 -0
|
@@ -267,3 +267,26 @@ Accepts any value the [`jose`](https://github.com/panva/jose) library supports:
|
|
|
267
267
|
## Algorithm
|
|
268
268
|
|
|
269
269
|
Tokens are signed with **HS256** (HMAC-SHA256). The secret is UTF-8 encoded before signing. Asymmetric algorithms (RS256, ES256) are not currently supported.
|
|
270
|
+
|
|
271
|
+
## Generated account-security routes
|
|
272
|
+
|
|
273
|
+
These are app templates, not exports from `/auth`. `POST /auth/change-password` verifies the authenticated account's old password, hashes the replacement, clears stored refresh credentials, and uses `revokeAllSessions` (cache required). Its 200 response is `{ message: 'Password changed successfully' }`; invalid input returns 400, invalid credentials 401, and suspended accounts 403. Revocation failures propagate. Existing access tokens, including the caller's, are revoked.
|
|
274
|
+
|
|
275
|
+
Generated 2FA routes (app code, not additional core exports):
|
|
276
|
+
|
|
277
|
+
| Method/path | Input | Result |
|
|
278
|
+
|---|---|---|
|
|
279
|
+
| `GET /auth/2fa/setup` | authenticated | `{ enabled, method, methods }` |
|
|
280
|
+
| `POST /auth/2fa/setup` | authenticated; `{ password, method }` | TOTP secret/`otpauthUrl` (200), or email `codeSent` (202) |
|
|
281
|
+
| `POST /auth/2fa/setup` | authenticated; `{ password, method, code }` | confirms enrollment; revokes sessions (200) |
|
|
282
|
+
| `POST /auth/login`, `POST /auth/2fa/verify` | `{ email, password, code? }` | no tokens until the enrolled factor passes; missing/invalid code returns 401 with `twoFactorRequired` and `method`; a password-verified email request without code sends one |
|
|
283
|
+
| `POST /auth/2fa/disable` | authenticated; `{ password, code? }` | email without code sends a disable code (202); valid password/code disables and revokes sessions (200) |
|
|
284
|
+
|
|
285
|
+
`TWO_FACTOR_METHOD=totp|email|both` limits enrollment choices. Each account has one method. TOTP is six-digit SHA-1 with 30-second steps (±1 step); email codes last five minutes. Accepted codes cannot be reused. Enrollment/disable require the current password. See [the full flow and upgrade steps](../guides/authentication.md#two-factor-authentication-totp-or-email-otp).
|
|
286
|
+
|
|
287
|
+
Device-session `/auth/sessions` (GET) and `/auth/sessions/:id` (DELETE) remain authenticated 501 extension points.
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
Generated User/Admin logout requires authentication, compare-and-sets the account's stored refresh token to empty (including bearer logout with no refresh cookie/body), then revokes the current access token and clears cookies. Login persists refresh credentials only while the password hash still matches its verified snapshot. Generated login/refresh tokens carry `efc_auth_at`, captured before credential reads; revocation rejects a token whose authentication started at or before the cutoff, even if it was signed afterwards. Custom token issuers may include this numeric epoch-millisecond claim for the same protection; it can only restrict access, never override a later server-issued time. Existing generated apps must update their owned auth routes as well as the framework to receive these fixes.
|
|
291
|
+
|
|
292
|
+
Password reset atomically consumes the matching, still-unexpired reset token while replacing the password and clearing stored refresh credentials and pending 2FA challenges. Concurrent use has one winner; expiry is rechecked in the database after hashing. Active 2FA enrollment remains enabled. Password changes also invalidate outstanding reset links. Custom auth-entity logout propagates revocation-store failures instead of returning a false success. Existing apps must update their owned reset-password, change-password, two-factor helper and custom logout files.
|
|
@@ -118,6 +118,49 @@ await Place.bulkWrite([
|
|
|
118
118
|
|
|
119
119
|
## Aggregation
|
|
120
120
|
|
|
121
|
+
### Typed pipelines
|
|
122
|
+
|
|
123
|
+
`pipeline()` builds an aggregation stage by stage, and each stage's output type is inferred from the schema — no hand-written result types:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
const ratings = await Place.pipeline()
|
|
127
|
+
.match({ owner: ownerId }) // string ids are cast, like find()
|
|
128
|
+
.unwind('$reviews') // reviews: { rating, text } (one per result)
|
|
129
|
+
.group({ _id: '$name', avg: { $avg: '$reviews.rating' }, n: { $sum: 1 } })
|
|
130
|
+
.sort({ avg: -1 });
|
|
131
|
+
// ratings: { _id: string; id: string; avg: number | null; n: number }[]
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
| Stage | Output type |
|
|
135
|
+
|---|---|
|
|
136
|
+
| `match(filter)`, `sort`, `skip`, `limit`, `sample(n)` | unchanged |
|
|
137
|
+
| `unwind('$field', { preserveNullAndEmptyArrays? })` | the array field holds one element (or `null` when preserved) |
|
|
138
|
+
| `group({ _id, …accumulators })` | `_id` (a `'$field'`, `null` or `{ key: '$field' }`), a string `id`, and per accumulator: `$sum`/`$count` → `number` (`$sum` of a `decimal128` → exact `string`), `$avg` → `number \| null`, `$min`/`$max`/`$first`/`$last` → the field's type, `$push`/`$addToSet` → an array of it |
|
|
139
|
+
| `project({ a: 1, b: 1 })` | only those fields, plus `id` |
|
|
140
|
+
| `count('n')` | `{ n: number }` (no result when nothing matched) |
|
|
141
|
+
| `lookup('ref', Model)` / `lookup({ from, localField, foreignField, as })` | see below |
|
|
142
|
+
| `addFields<{ x: number }>({ … })` | adds the fields you name in the generic |
|
|
143
|
+
| `stage<Out>({ … })` | anything else (`$facet`, `$bucket`, …), with its output type spelled out |
|
|
144
|
+
|
|
145
|
+
Field references (`'$name'`, `'$address.city'`) are checked against the record — one level into embedded objects. Await the builder, or call `.exec()`; `.toArray()` returns the stages as plain objects.
|
|
146
|
+
|
|
147
|
+
While the records still have the collection's shape, `match` and `sort` are cast like `find()` (`id` → `_id`, string ids → ObjectIds). After a stage that changes the shape (`group`, `unwind`, `lookup`, `project`, …) they're passed through as written.
|
|
148
|
+
|
|
149
|
+
### `lookup()`
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
const posts = await Post.lookup('author', User, { published: true });
|
|
153
|
+
// posts[0].author: User record | null (an array of refs → User records[])
|
|
154
|
+
|
|
155
|
+
const users = await User.pipeline()
|
|
156
|
+
.lookup({ from: Post, localField: 'id', foreignField: 'author', as: 'posts' });
|
|
157
|
+
// users[0].posts: Post records[]
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
The first form replaces a `ref` field with the record it points to (`null` when it points nowhere); the optional third argument filters first. Inside a pipeline it's `.lookup('author', User)`. The full form adds an array field; `id` means `_id` on either side. The target is a model, so the collection name is never spelled out.
|
|
161
|
+
|
|
162
|
+
### Raw pipelines
|
|
163
|
+
|
|
121
164
|
```ts
|
|
122
165
|
const ratings = await Place.aggregate<{ _id: string; avg: number }>([
|
|
123
166
|
{ $unwind: '$reviews' },
|
|
@@ -126,7 +169,7 @@ const ratings = await Place.aggregate<{ _id: string; avg: number }>([
|
|
|
126
169
|
]);
|
|
127
170
|
```
|
|
128
171
|
|
|
129
|
-
|
|
172
|
+
`aggregate()` passes the pipeline to MongoDB unchanged (no id casting); type the output with the generic. Results of both forms get the same conversions as records: decimals become strings, longs bigints, `_id` gains a string `id`.
|
|
130
173
|
|
|
131
174
|
## Change streams
|
|
132
175
|
|
|
@@ -41,7 +41,7 @@ export const POST = compose(
|
|
|
41
41
|
## Behaviour
|
|
42
42
|
|
|
43
43
|
- Handlers are called in the order they are passed.
|
|
44
|
-
-
|
|
44
|
+
- Calling `next()` (or `next(null)`) advances to the next handler in the chain. Calling `next(err)` stops the chain and forwards the error to Express; `next('route')` and `next('router')` are forwarded to Express as well.
|
|
45
45
|
- If the last handler calls `next()`, control passes to the surrounding Express middleware chain (equivalent to the route calling `next()`).
|
|
46
46
|
- If any handler throws synchronously or returns a rejected promise, the error is forwarded to `next(err)` and bubbles up to the global error handler.
|
|
47
47
|
|
|
@@ -350,3 +350,11 @@ It throws if accessed before Pre-Flight completes (e.g. at module load time) —
|
|
|
350
350
|
### `getDbClient()` / `setDbClient()`
|
|
351
351
|
|
|
352
352
|
Read or replace the client behind `db` — mainly for tests that bypass `ignite()`.
|
|
353
|
+
|
|
354
|
+
## PostgreSQL statement preparation
|
|
355
|
+
|
|
356
|
+
`ignite({ databasePool: { preparedStatements: true | false | { max?: number } } })` controls automatic naming of Drizzle model queries, including transaction queries. Default: `true`, with 100 names per physical connection. `max` must be a nonnegative safe integer; zero disables. Reused SQL shapes share names across values; excess new shapes use unnamed execution. The native `db` Pool and explicitly named driver queries retain their behavior. EFC schema sync/drop invalidates reusable shapes without exceeding the connection's lifetime name budget. Reconnect after external DDL; disable for incompatible poolers. See [database guide](../guides/database.md#postgresql-prepared-statements).
|
|
357
|
+
|
|
358
|
+
## Query metrics
|
|
359
|
+
|
|
360
|
+
`getQueryMetrics(): QueryMetricsSnapshot` and `resetQueryMetrics(): void` are exported from the main package. Opt in using `logging.queries.metrics: true | { maxEntries?: number }` (default off; enabled default limit 1000; zero disables). A snapshot contains `enabled`, `since` (epoch ms), `dropped` (untracked completed-call observations), and detached `entries: ReadonlyArray<QueryMetric>`. Each metric has `model`, `op`, `calls`, `errors`, `statements`, `totalMs`, `minMs`, `maxMs`, `meanMs`, `slow`. Reset starts a new process-local window and leaves collection enabled. Values/SQL/error strings are never included. Nested calls' statement counts are inclusive. [Details](../guides/logging.md#query-metrics).
|
|
@@ -31,7 +31,7 @@ interface EFCConfig {
|
|
|
31
31
|
// Database
|
|
32
32
|
database?: 'mongodb' | 'postgresql';
|
|
33
33
|
databaseUrl?: string;
|
|
34
|
-
databasePool?: { max?: number; idleTimeoutMs?: number; connectionTimeoutMs?: number };
|
|
34
|
+
databasePool?: { max?: number; idleTimeoutMs?: number; connectionTimeoutMs?: number; preparedStatements?: boolean | { max?: number } };
|
|
35
35
|
|
|
36
36
|
// Auth
|
|
37
37
|
authStrategy?: 'http-only' | 'bearer'; // 'localStorage' = old name for 'bearer'
|
|
@@ -90,6 +90,15 @@ ignite({ dashboard: true });
|
|
|
90
90
|
|
|
91
91
|
---
|
|
92
92
|
|
|
93
|
+
### `trustProxy`
|
|
94
|
+
|
|
95
|
+
Express's `trust proxy`. Set it when the app runs behind a proxy or load balancer (Render, Fly, Heroku, nginx, a cloud LB) so `req.ip` is the client, not the proxy: `true`, the number of hops (usually `1`), or addresses / subnets. Off by default, so `X-Forwarded-For` can't be spoofed. [`rateLimit`](../guides/caching.md#rate-limiting) keys on `req.ip`.
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
// efc.config.ts (scaffolded)
|
|
99
|
+
trustProxy: process.env.TRUST_PROXY ? Number(process.env.TRUST_PROXY) : undefined,
|
|
100
|
+
```
|
|
101
|
+
|
|
93
102
|
### `port`
|
|
94
103
|
|
|
95
104
|
HTTP listen port. Default: `3000`. `ignite()` never reads `PORT` from the environment itself — pass it explicitly, typically by reading `process.env.PORT` in `efc.config.ts` (see [Environment Variables](../guides/environment-variables.md)).
|
|
@@ -162,6 +171,7 @@ databasePool: { max: 5, idleTimeoutMs: 30_000, connectionTimeoutMs: 5_000 },
|
|
|
162
171
|
| Option | PostgreSQL (`pg` Pool) | MongoDB (mongoose) |
|
|
163
172
|
|---|---|---|
|
|
164
173
|
| `max` | `max` — default 10 | `maxPoolSize` — default 100 |
|
|
174
|
+
| `preparedStatements` | `true` (default): up to 100 named statements per connection; `{ max: n }` changes the lifetime budget, `false` / `{ max: 0 }` disables | ignored |
|
|
165
175
|
| `idleTimeoutMs` | `idleTimeoutMillis` — default 10000 | `maxIdleTimeMS` — default: never |
|
|
166
176
|
| `connectionTimeoutMs` | `connectionTimeoutMillis` — default: no limit | `serverSelectionTimeoutMS` (default 30000) and `waitQueueTimeoutMS` (default: no limit) |
|
|
167
177
|
|
|
@@ -353,3 +363,5 @@ ignite({ port: 3000 })
|
|
|
353
363
|
| `timeoutMs` | `number` | `10_000` | Force-exit after this many milliseconds if `server.close()` hasn't finished |
|
|
354
364
|
|
|
355
365
|
On a worker, the signal closes the HTTP server (in-flight requests finish), drains running task jobs, then exits. On the cluster primary it relays `SIGTERM` to every worker — so `docker stop` / Kubernetes, which signal only PID 1, still shut down gracefully — and force-exits after `timeoutMs + 2s` if a worker hangs. Repeated signals are ignored rather than killing a worker mid-drain.
|
|
366
|
+
|
|
367
|
+
`logging.queries.metrics: true | { maxEntries?: number }` enables bounded per-process query counters and latency summaries (default off; enabled default limit 1000). Read/reset through `getQueryMetrics` / `resetQueryMetrics` from the main package; see [query metrics](../guides/logging.md#query-metrics).
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# `createTestApp(options)`
|
|
2
|
+
|
|
3
|
+
```ts
|
|
4
|
+
import { createTestApp } from 'express-file-cluster/testing';
|
|
5
|
+
import type { TestAppOptions } from 'express-file-cluster/testing';
|
|
6
|
+
```
|
|
7
|
+
|
|
8
|
+
Returns `Promise<express.Express>` with real file-based routes mounted, without starting a listener or booting services.
|
|
9
|
+
|
|
10
|
+
| Option | Default | Behavior |
|
|
11
|
+
|---|---|---|
|
|
12
|
+
| `apiDir: string` | required | Absolute path, or path resolved against the current working directory; rejects a nonexistent/non-directory path. |
|
|
13
|
+
| `basePath?: string` | `/v1/api` | Mount point for the API router. |
|
|
14
|
+
| `globalMiddlewares?: RequestHandler[]` | `[]` | Runs after body/cookie parsing and before file middleware/validation. |
|
|
15
|
+
| `auth?: { secret; strategy?; expiresIn?; cookieDomain? }` | unchanged | Configures process-wide auth; strategy defaults to `http-only`, expiry to `1h`. |
|
|
16
|
+
| `requestTimeout?: number` | disabled | Production request timeout in milliseconds; responds 408. |
|
|
17
|
+
| `trustProxy?` | Express default | Same value type as `EFCConfig.trustProxy`; supports client-IP tests behind a proxy. |
|
|
18
|
+
| `onError?: ErrorRequestHandler` | production error handler | Express error middleware mounted after the API. |
|
|
19
|
+
|
|
20
|
+
Shared behavior with production: JSON/form/cookie parsing, AsyncLocalStorage request context, request IDs, bigint JSON serialization, route scanning/order, file middleware, schema validation, method dispatch, and safe error responses. CORS, logging, the dashboard and service initialization are disabled/omitted. Auth/logging and imported modules retain process-wide state; see [test isolation](../guides/testing.md).
|
|
21
|
+
|
|
22
|
+
This helper's `apiDir` is **not** a new `ignite()` option. `createTestApp` is exported only from `/testing`; no `/db`, `/router` or `/middleware` subpaths are added.
|
|
23
|
+
|
|
24
|
+
The CommonJS `/testing` entry delegates to the ESM helper using native `import()`, so dynamically imported ESM routes share its authentication and request context. The Node/runner must support the route files' module format.
|
|
25
|
+
|
|
26
|
+
The ESM and CommonJS builds share process-wide auth configuration, request AsyncLocalStorage and cache state. CommonJS `requireAuth` global middleware therefore sees helper auth options, preserves `getCurrentUser()` across awaits into ESM routes, and observes the same revocations. Model/queue fixtures are still configured separately.
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# Type inference
|
|
2
|
+
|
|
3
|
+
EFC models are typed from their schema literal — there's no interface to write or keep in step. All three model APIs (`defineModel`, `defineTable`, `defineCollection`) share the rules below; each also types its own queries.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { defineTable, type InferRecord, type InferCreate } from 'express-file-cluster';
|
|
7
|
+
|
|
8
|
+
export const Order = defineTable('Order', {
|
|
9
|
+
number: { type: 'string', required: true, unique: true },
|
|
10
|
+
status: { type: 'string', enum: ['open', 'paid'], default: 'open' },
|
|
11
|
+
total: { type: 'decimal', precision: 10, scale: 2, required: true },
|
|
12
|
+
lines: [{ sku: { type: 'string', required: true }, qty: { type: 'integer' } }],
|
|
13
|
+
paidAt: { type: 'date' },
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
type OrderRecord = InferRecord<typeof Order>;
|
|
17
|
+
// { id: string; number: string; status: 'open' | 'paid'; total: string;
|
|
18
|
+
// lines?: { sku: string; qty?: number }[]; paidAt?: Date; createdAt: Date; updatedAt: Date }
|
|
19
|
+
|
|
20
|
+
type NewOrder = InferCreate<typeof Order>;
|
|
21
|
+
// { number: string; total: string | number; status?: 'open' | 'paid'; lines?: …; paidAt?: Date | string | number }
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
| Helper | Gives you |
|
|
25
|
+
|---|---|
|
|
26
|
+
| `InferRecord<typeof M>` | What reads return: every stored field, `id`, timestamps |
|
|
27
|
+
| `InferCreate<typeof M>` | What `create()` accepts |
|
|
28
|
+
| `InferTableRecord<typeof M>` | Same as `InferRecord`, for `defineTable` models (kept for older code) |
|
|
29
|
+
|
|
30
|
+
## Field types
|
|
31
|
+
|
|
32
|
+
| Schema `type` | Record type | `create()` / update input | `defineModel` | `defineTable` | `defineCollection` |
|
|
33
|
+
|---|---|---|:-:|:-:|:-:|
|
|
34
|
+
| `'string'` | `string` | `string` | ✓ | ✓ | ✓ |
|
|
35
|
+
| `'number'` | `number` | `number` | ✓ | ✓ | ✓ |
|
|
36
|
+
| `'boolean'` | `boolean` | `boolean` | ✓ | ✓ | ✓ |
|
|
37
|
+
| `'date'` | `Date` | `Date \| string \| number` | ✓ | ✓ | ✓ |
|
|
38
|
+
| `'objectId'` | `string` | `string` | ✓ | ✓ | ✓ |
|
|
39
|
+
| `'integer'` | `number` (whole, 32-bit) | `number` | | ✓ | |
|
|
40
|
+
| `'bigint'` | `bigint` | `bigint \| number` | | ✓ | |
|
|
41
|
+
| `'decimal'` | `string` (exact) | `string \| number` | | ✓ | |
|
|
42
|
+
| `'uuid'` | `string` | `string` | | ✓ | |
|
|
43
|
+
| `'json'` | `unknown` | `unknown` | | ✓ | |
|
|
44
|
+
| `'decimal128'` | `string` (exact) | `string \| number` | | | ✓ |
|
|
45
|
+
| `'long'` | `bigint` | `bigint \| number` | | | ✓ |
|
|
46
|
+
| `'geoPoint'` | `{ type: 'Point'; coordinates: [number, number] }` | same | | | ✓ |
|
|
47
|
+
| `'binary'` | `Buffer` | `Buffer` | | | ✓ |
|
|
48
|
+
| `enum: [...]` | union of the literals | same | ✓ | ✓ | ✓ |
|
|
49
|
+
| `{ type: 'array', of: X }` | `X[]` | `X[]` (input form of `X`) | ✓ | ✓ | ✓ |
|
|
50
|
+
| `[{ …schema }]` / `of: { …schema }` | array of the inferred object | same | ✓ | ✓ | ✓ |
|
|
51
|
+
| nested schema / `{ type: 'object', fields }` | the inferred object | same, with create rules | ✓ | ✓ | ✓ |
|
|
52
|
+
| `{ type: 'object' }` without `fields`, `{ type: 'array' }` without `of` | `unknown` / `unknown[]` | same | ✓ | ✓ | ✓ |
|
|
53
|
+
|
|
54
|
+
A type that isn't valid for the API (`'decimal128'` in `defineTable`, `'integer'` in `defineCollection`) is a compile error, and throws at definition time in JavaScript.
|
|
55
|
+
|
|
56
|
+
## Optional or not
|
|
57
|
+
|
|
58
|
+
| The field has | Record | `create()` input |
|
|
59
|
+
|---|---|---|
|
|
60
|
+
| `required: true` | present | mandatory |
|
|
61
|
+
| `required: true` + `default` (or `sequence`) | present | optional |
|
|
62
|
+
| `default` or `sequence` only | present | optional |
|
|
63
|
+
| none of these | optional (`?`) | optional |
|
|
64
|
+
|
|
65
|
+
The rules apply inside embedded objects too; an embedded object's inner `required` fields only apply when the object is there.
|
|
66
|
+
|
|
67
|
+
## Ids and timestamps
|
|
68
|
+
|
|
69
|
+
| | `id` |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `defineModel`, `defineCollection` | `string` |
|
|
72
|
+
| `defineTable` | `string` (uuid, default) · `number` with `{ id: 'serial' }` · `bigint` with `{ id: 'bigserial' }` |
|
|
73
|
+
|
|
74
|
+
`createdAt` / `updatedAt: Date` are added unless `options.timestamps` is `false`; `{ createdAt: 'created_at', updatedAt: false }` renames or drops one, and the type follows.
|
|
75
|
+
|
|
76
|
+
## Typed queries
|
|
77
|
+
|
|
78
|
+
- **Filters, updates, sorts and `distinct()`** take the record's fields only; an undeclared field or a value outside an `enum` is a compile error.
|
|
79
|
+
- **`defineTable` `select` / `omit`** narrow the result type to those fields. **`include`** types the related records once the models are registered:
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
declare module 'express-file-cluster' {
|
|
83
|
+
interface Tables { User: typeof User; Post: typeof Post }
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Apps from `create-efc-app` (and `efc db pull`) write this in `src/model/index.ts`. See [`defineTable` relations](./table.md).
|
|
88
|
+
- **`defineCollection` `pipeline()`** types every stage's output — `group` accumulators, `unwind`, `lookup`, `project`, `count` — and `lookup('ref', Model)` replaces a ref with the referenced record type. See [typed pipelines](./collection.md#typed-pipelines).
|
|
89
|
+
|
|
90
|
+
## When there's nothing to infer from
|
|
91
|
+
|
|
92
|
+
A schema stored in a variable annotated with the wide type has lost its literal:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
const schema: ModelSchema = { title: { type: 'string' } }; // ✗ InferRecord is a loose object
|
|
96
|
+
const schema = { title: { type: 'string' } } as const satisfies ModelSchema; // ✓
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Declare it inline (or `as const satisfies …`). `defineModel<T>('Name', schema)` with an explicit interface still works and keeps the v0.4 behaviour (`create()` takes `Partial<T>`).
|
package/dist/docs/cli/add.md
CHANGED
|
@@ -47,7 +47,7 @@ efc diff # compare installed features with the regi
|
|
|
47
47
|
| `auth@apple` | Sign in with Apple: `GET /auth/apple` → Apple → `POST /auth/apple/callback` (+ `OAuthAccount`). Asks for Services ID, Team ID, Key ID and the `.p8` key | auth |
|
|
48
48
|
| `user-profile` | `GET/PUT /user/profile` | auth |
|
|
49
49
|
| `forgot-password` | `/auth/forgot-password`, `/auth/reset-password` | auth |
|
|
50
|
-
| `account-security` |
|
|
50
|
+
| `account-security` | password changes, token refresh, TOTP/email OTP (asks allowed methods); device-session extension points return 501; `Session` model | auth |
|
|
51
51
|
| `email-verification` | `/auth/verify-email`, resend | auth |
|
|
52
52
|
| `account-settings` | avatar, settings, account, dashboard, activity | auth |
|
|
53
53
|
| `notifications` | `Notification` model + `/user/notifications` | auth |
|
|
@@ -140,7 +140,7 @@ Wrong answers are asked again. A question is only asked for a variable the app d
|
|
|
140
140
|
|
|
141
141
|
```json
|
|
142
142
|
{
|
|
143
|
-
"registry": "0.
|
|
143
|
+
"registry": "0.10.2",
|
|
144
144
|
"language": "typescript",
|
|
145
145
|
"database": "postgresql",
|
|
146
146
|
"modelApi": "defineTable",
|
package/dist/docs/cli/db.md
CHANGED
|
@@ -8,11 +8,11 @@ efc db generate --verify # fail if the migrations miss anything the models
|
|
|
8
8
|
efc db sync [--dry-run] # reconcile tables/collections + indexes with src/model(s)/
|
|
9
9
|
efc db sync --dry-run --exit-code # exit 2 when the database has drifted from the models
|
|
10
10
|
efc db migrate [--baseline] # run pending migrations (one new batch); --baseline only records them
|
|
11
|
-
efc db pull [--out src/model] # write
|
|
11
|
+
efc db pull [--out src/model] [--sample 1000] # write models for the database: defineTable (PostgreSQL) / defineCollection (MongoDB)
|
|
12
12
|
efc db rollback [--steps 2] # revert the last batch(es)
|
|
13
13
|
efc db status # applied vs pending
|
|
14
14
|
efc db seed [name] # run all seeds, or one
|
|
15
|
-
efc db studio [--port 4983]
|
|
15
|
+
efc db studio [--port 4983] [--write] # browser on 127.0.0.1 (rows + structure); --write edits through src/model
|
|
16
16
|
```
|
|
17
17
|
|
|
18
18
|
## Common options
|
|
@@ -44,7 +44,7 @@ Pass `{ thread: true }` as the first argument. The handler runs in a dedicated `
|
|
|
44
44
|
|
|
45
45
|
```ts
|
|
46
46
|
// src/tasks/ResizeImage.ts
|
|
47
|
-
import { defineTask } from 'express-file-cluster/tasks';
|
|
47
|
+
import { defineTask, enqueue } from 'express-file-cluster/tasks';
|
|
48
48
|
import sharp from 'sharp';
|
|
49
49
|
|
|
50
50
|
interface ResizePayload {
|
|
@@ -58,10 +58,13 @@ export default defineTask<ResizePayload>(
|
|
|
58
58
|
const input = await downloadFromStorage(key);
|
|
59
59
|
const out = await sharp(input).resize(width).toBuffer();
|
|
60
60
|
await uploadToStorage(`${key}@${width}`, out);
|
|
61
|
+
await enqueue('NotifyUploaded', { key, width }); // works from a thread too
|
|
61
62
|
},
|
|
62
63
|
);
|
|
63
64
|
```
|
|
64
65
|
|
|
66
|
+
`enqueue()` works inside a thread task: the call is forwarded to the main thread, which owns the queue, and resolves (or rejects with the same error) once the job is queued — so a CPU-heavy step can hand off to the next one. The thread is a fresh module scope: open its own clients (database, storage) if it needs them, and don't rely on state from the main thread. The task module's `default` export must be the `defineTask(...)` result.
|
|
67
|
+
|
|
65
68
|
---
|
|
66
69
|
|
|
67
70
|
## Task options
|
|
@@ -210,8 +213,8 @@ The backend is inferred — BullMQ when `REDIS_URL` is set, pg-boss for a `postg
|
|
|
210
213
|
|
|
211
214
|
`packages/core/src/tasks/thread-runner.ts` is a dual-purpose module:
|
|
212
215
|
|
|
213
|
-
- **Worker-thread side** — when loaded inside a `worker_threads` worker
|
|
214
|
-
- **Main-thread side** — exports `runInThread(handlerPath, payload)` which spawns a `new Worker(thread-runner.js, { workerData })` and returns a `Promise<void>` that resolves on `
|
|
216
|
+
- **Worker-thread side** — when loaded inside a `worker_threads` worker (`workerData.efcTask`), imports the task file, calls `def.handler(payload)`, and posts `{ type: 'done', ok }` back. `enqueue()` in the thread posts `{ type: 'enqueue', id, name, payload }` and waits for `{ type: 'enqueued', id, error? }`; the port only keeps the thread alive while such a call is waiting, so a finished task's thread exits.
|
|
217
|
+
- **Main-thread side** — exports `runInThread(handlerPath, payload)` which spawns a `new Worker(thread-runner.js, { workerData })`, answers `enqueue` messages with the real `enqueue()`, and returns a `Promise<void>` that resolves on `done` / rejects on error. The build emits `dist/thread-runner.js` as its own file because the worker loads it by path.
|
|
215
218
|
|
|
216
219
|
---
|
|
217
220
|
|
|
@@ -23,6 +23,8 @@ EFC turns your directory tree into your route tree. The scanner walks `src/api/`
|
|
|
23
23
|
|
|
24
24
|
**`[...spread]` → catch-all** — matches one or more remaining segments; `req.params.slug` is a **string array** (`/docs/a/b` → `['a', 'b']`, each segment URI-decoded). With double brackets it also matches zero segments (`[]`). A catch-all must be the last segment of the path — `[...slug]/edit.ts` is rejected at startup.
|
|
25
25
|
|
|
26
|
+
Catch-all paths are split into segments **before** each segment is URI-decoded once. `/docs/100%25/a%2Fb/a%252Fb` produces `['100%', 'a/b', 'a%2Fb']`; an encoded slash stays inside its original segment. Named parameters preceding the catch-all are also decoded once.
|
|
27
|
+
|
|
26
28
|
**`index.ts` → parent path** — a file named `index.ts` (or `.js`) inside a directory maps to the directory's URL without a trailing `/index`.
|
|
27
29
|
|
|
28
30
|
---
|
|
@@ -74,7 +74,7 @@ export const POST = compose(
|
|
|
74
74
|
|
|
75
75
|
## How `compose` works
|
|
76
76
|
|
|
77
|
-
`compose(...handlers)` in `packages/core/src/compose.ts` returns a single `RequestHandler` that chains the provided handlers in sequence. Each handler calls `next()` to advance to the next one. If any handler throws or rejects, the error is forwarded to Express's error chain via `next(err)`.
|
|
77
|
+
`compose(...handlers)` in `packages/core/src/compose.ts` returns a single `RequestHandler` that chains the provided handlers in sequence. Each handler calls `next()` to advance to the next one. Calling `next(err)` stops the composed chain and forwards the error; `next('route')` and `next('router')` retain their Express meanings. If any handler throws or rejects, the error is forwarded to Express's error chain via `next(err)`.
|
|
78
78
|
|
|
79
79
|
```ts
|
|
80
80
|
export function compose(...handlers: RequestHandler[]): RequestHandler {
|
|
@@ -85,7 +85,7 @@ export function compose(...handlers: RequestHandler[]): RequestHandler {
|
|
|
85
85
|
if (i >= handlers.length) { next(); return; }
|
|
86
86
|
const handler = handlers[i];
|
|
87
87
|
try {
|
|
88
|
-
Promise.resolve(handler(req, res, () => dispatch(i + 1))).catch(next);
|
|
88
|
+
Promise.resolve(handler(req, res, (err) => err ? next(err) : dispatch(i + 1))).catch(next);
|
|
89
89
|
} catch (err) {
|
|
90
90
|
next(err);
|
|
91
91
|
}
|
|
@@ -20,7 +20,8 @@ The interactive wizard asks for the **base** app, then offers features:
|
|
|
20
20
|
? Project name: my-api
|
|
21
21
|
? Language: TypeScript | JavaScript
|
|
22
22
|
? Database: MongoDB | PostgreSQL
|
|
23
|
-
? Models: defineTable | defineModel (PostgreSQL
|
|
23
|
+
? Models: defineTable | defineModel (PostgreSQL)
|
|
24
|
+
defineCollection | defineModel (MongoDB)
|
|
24
25
|
? Task queue backend: pg-boss | BullMQ (BullMQ on MongoDB)
|
|
25
26
|
? Multi-core clustering? Yes
|
|
26
27
|
? Add features now? (none by default — or add any later with `efc add`)
|
|
@@ -97,3 +98,7 @@ The server is live at `http://localhost:3000`. The scaffolder creates a `src/api
|
|
|
97
98
|
- [Migrations & Seeds](../guides/migrations.md) — evolving the schema.
|
|
98
99
|
- [Validation](../guides/validation.md) — `export const schema` with zod & co.
|
|
99
100
|
- [CLI Reference](../cli/index.md) — all `efc` commands.
|
|
101
|
+
|
|
102
|
+
### Choosing two-factor authentication
|
|
103
|
+
|
|
104
|
+
Select **Account security** in the init feature picker, then choose **Authenticator app (TOTP)**, **Email OTP**, or **Both — users choose**. Email/both automatically adds the SMTP email client and asks for mail settings. Each user or admin can enroll one allowed method. The generated `TWO_FACTOR_METHOD` setting controls the choices and `TWO_FACTOR_KEY` protects stored secrets; keep the key stable across deployments. See [enrollment, login and disable](../guides/authentication.md#two-factor-authentication-totp-or-email-otp).
|
|
@@ -282,3 +282,36 @@ future default doesn't lock anyone out. Apps scaffolded before 0.9.2 stored **bc
|
|
|
282
282
|
`verifyPassword` deliberately rejects (EFC carries no bcrypt code or dependency): those users reset
|
|
283
283
|
their password once — the reset route stores a scrypt hash. See the
|
|
284
284
|
[auth API reference](../api-reference/auth.md#hashpassword--verifypassword--passwordneedsrehash).
|
|
285
|
+
|
|
286
|
+
## Generated password changes and security extension points
|
|
287
|
+
|
|
288
|
+
`efc add account-security` adds a protected `POST /auth/change-password`. Send nonempty strings `oldPassword` and `newPassword`. The route verifies the current password for the authenticated User or Admin, stores a new `hashPassword()` hash, invalidates its stored refresh token, and revokes existing access tokens with `revokeAllSessions`. The current session is also revoked: log in again with the new password. The endpoint limits attempts to ten per account per fifteen minutes and needs the scaffolded cache.
|
|
289
|
+
|
|
290
|
+
Revocation errors propagate instead of reporting success. Because the database update precedes cache revocation, a cache failure can leave the new password persisted even though the request fails; restore cache access and log in again.
|
|
291
|
+
|
|
292
|
+
Device-session list/revoke routes remain authenticated 501 extension points. Two-factor authentication is implemented as generated app code, described below.
|
|
293
|
+
|
|
294
|
+
## Two-factor authentication: TOTP or email OTP
|
|
295
|
+
|
|
296
|
+
When selecting **Account security** during `create-efc-app`, choose **Authenticator app (TOTP)**, **Email OTP**, or **Both — users choose**. Email-capable choices also add the email-client integration and ask for SMTP settings. `efc add account-security` asks the same method question; install `efc add email-client` as well when choosing email or both. `TWO_FACTOR_METHOD=totp|email|both` controls allowed methods; each User or Admin enrolls one allowed method. Changing the app setting does not silently downgrade enrolled accounts: an account using a method you disable cannot sign in until you restore it or migrate the account.
|
|
297
|
+
|
|
298
|
+
Keep the generated `TWO_FACTOR_KEY` (64 hex characters / 32 random bytes) in your secret store and identical across instances. It encrypts TOTP secrets with AES-256-GCM and authenticates stored email-code digests, independently of `JWT_SECRET`. Keep it when upgrading or rotating JWT keys. Replacing it without migrating/re-enrolling the accounts prevents verification of existing secrets.
|
|
299
|
+
|
|
300
|
+
1. Authenticate, then `GET /auth/2fa/setup` to see `{ enabled, method, methods }`.
|
|
301
|
+
2. Start enrollment with `POST /auth/2fa/setup`, body `{ password, method: 'totp' | 'email' }`. The current password is required. TOTP returns `{ secret, otpauthUrl, expiresIn: 600 }`: enter the secret in an authenticator or render the URI as a QR code in your UI. Email sends a six-digit code to the account's stored email and returns 202 `{ method: 'email', codeSent: true, expiresIn: 300 }`.
|
|
302
|
+
3. Confirm with `POST /auth/2fa/setup`, body `{ password, method, code }`. The method must match the pending enrollment. Only a valid, unexpired code enables 2FA. Successful enrollment clears refresh credentials and revokes existing access tokens, including the current session.
|
|
303
|
+
4. Sign in with `POST /auth/login` or `/auth/2fa/verify`, body `{ email, password, code }`. Both endpoints run the same credential checks and rate limit. Without a code, an enrolled account gets 401 `{ twoFactorRequired: true, method }` and no access/refresh token. For email accounts, this password-verified request sends the OTP; repeat with the received code. For TOTP, use the current authenticator code. Wrong passwords never send an email code.
|
|
304
|
+
5. Disable with authenticated `POST /auth/2fa/disable`, body `{ password, code }`. Email users first send `{ password }` to request a purpose-specific disable code (202), then submit it. Disable requires the current password and a fresh code, erases secrets, clears refresh credentials, and revokes access tokens. To switch methods, disable the current one and enroll the other. Disable email 2FA before changing the email address through the profile route.
|
|
305
|
+
|
|
306
|
+
TOTP uses [RFC 6238](https://www.rfc-editor.org/rfc/rfc6238) SHA-1, six digits and 30-second intervals, accepting one interval of clock drift. Accepted time steps are atomically recorded so the same code cannot be reused, even across workers. Enrollment consumes its code too: wait for the next authenticator code before logging in. Email codes expire in five minutes, are purpose/account/address bound, and are consumed atomically; resending replaces the previous code. Only a keyed digest is stored. Pending TOTP secrets expire after ten minutes. Secret/code fields are stripped from generated record responses; enrollment responses use `Cache-Control: no-store`.
|
|
307
|
+
|
|
308
|
+
Login and verification share a ten-attempt per-account, fifteen-minute limit across both paths; management endpoints share a separate limit. These limits require the scaffolded cache and reject requests when it is unavailable. Use Redis across multiple app instances. SMTP settings and a working task backend are required for email delivery; queue failures invalidate the pending code and propagate instead of reporting success.
|
|
309
|
+
|
|
310
|
+
Refresh tokens are issued only after completing 2FA. Enabling/disabling clears older refresh tokens, and refresh rotation uses a database compare-and-set to reject replay. OAuth sign-in refuses accounts with 2FA enabled; use password plus verification code instead, so OAuth cannot bypass this app-level second factor. OAuth-only accounts must set a password before enrolling. Password reset does not disable 2FA. Recovery codes and automated lost-device recovery are not implemented; provide a separately verified support process before offering enrollment to end users.
|
|
311
|
+
|
|
312
|
+
Existing apps must update their auth-owned models, login/refresh/OAuth helpers and record sanitizers as well as the 2FA routes. Review `efc diff auth account-security`, preserve edited files, and run the normal model migration process if auto-sync is disabled. Set `TWO_FACTOR_KEY` and configure the mailer before enabling email OTP. Updating only the setup endpoint leaves other login paths unchanged.
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
Generated User/Admin logout requires authentication, compare-and-sets the account's stored refresh token to empty (including bearer logout with no refresh cookie/body), then revokes the current access token and clears cookies. Login persists refresh credentials only while the password hash still matches its verified snapshot. Generated login/refresh tokens carry `efc_auth_at`, captured before credential reads; revocation rejects a token whose authentication started at or before the cutoff, even if it was signed afterwards. Custom token issuers may include this numeric epoch-millisecond claim for the same protection; it can only restrict access, never override a later server-issued time. Existing generated apps must update their owned auth routes as well as the framework to receive these fixes.
|
|
316
|
+
|
|
317
|
+
Password reset atomically consumes the matching, still-unexpired reset token while replacing the password and clearing stored refresh credentials and pending 2FA challenges. Concurrent use has one winner; expiry is rechecked in the database after hashing. Active 2FA enrollment remains enabled. Password changes also invalidate outstanding reset links. Custom auth-entity logout propagates revocation-store failures instead of returning a false success. Existing apps must update their owned reset-password, change-password, two-factor helper and custom logout files.
|
|
@@ -41,13 +41,44 @@ await cache.clear('user:'); // every key with this pref
|
|
|
41
41
|
|
|
42
42
|
// Get-or-compute: concurrent callers in one process share a single computation
|
|
43
43
|
const stats = await cache.wrap('stats:daily', 60, () => Stats.aggregate(pipeline));
|
|
44
|
+
|
|
45
|
+
// Atomic counter — one count across every worker (and, on Redis, every instance)
|
|
46
|
+
const n = await cache.incr('signups:today', { ttl: 86_400 }); // TTL set when the key is created
|
|
44
47
|
```
|
|
45
48
|
|
|
46
49
|
Values are stored as JSON — `Date`s come back as ISO strings. `undefined` is never cached.
|
|
47
50
|
|
|
48
51
|
### When Redis is down
|
|
49
52
|
|
|
50
|
-
The cache **degrades instead of failing**: `get` returns `undefined`, `set`/`del` are no-ops, `wrap` just runs your function. Requests keep working (only slower), and a warning is logged at most every 30 seconds. Boot waits up to ~2 s for the first connection, then continues regardless.
|
|
53
|
+
The cache **degrades instead of failing**: `get` returns `undefined`, `set`/`del` are no-ops, `wrap` just runs your function, `incr` returns `undefined` (a count can't be made up). Requests keep working (only slower), and a warning is logged at most every 30 seconds. Boot waits up to ~2 s for the first connection, then continues regardless.
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## Rate limiting
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { rateLimit } from 'express-file-cluster';
|
|
61
|
+
|
|
62
|
+
// src/api/auth/login.ts
|
|
63
|
+
export const middlewares = [rateLimit({ window: '15m', max: 10 })];
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`rateLimit` counts in the cache (`cache.incr`), so the limit is one limit for the whole app — an in-memory counter per worker would let 8 workers accept 8 × `max`. With the `memory` backend that's per machine; use `redis` when you run several instances.
|
|
67
|
+
|
|
68
|
+
| Option | Default | |
|
|
69
|
+
|---|---|---|
|
|
70
|
+
| `window` | — | Seconds, or `'30s'` / `'15m'` / `'1h'` / `'1d'`. Windows are aligned to the clock. |
|
|
71
|
+
| `max` | — | Requests per window and key. The next one gets **429** with `Retry-After`. |
|
|
72
|
+
| `key` | client IP (`req.ip`) | Who a request counts against; return `undefined` to not limit it. |
|
|
73
|
+
| `name` | the route pattern | Routes with the same `name` share a limit. |
|
|
74
|
+
| `onCacheError` | `'allow'` | Cache unreachable: let requests through, or `'reject'` with 503. |
|
|
75
|
+
| `headers` | `true` | `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset`. |
|
|
76
|
+
|
|
77
|
+
**Behind a proxy or load balancer, set `trustProxy` in `ignite()`** (`TRUST_PROXY=1` in scaffolded apps). Otherwise `req.ip` is the proxy's for every client, and an IP-keyed limit is one limit for everyone. The login and forgot-password routes `create-efc-app` generates key on the email too (`10 / 15 min per address + account`, `5 reset emails / hour per address`), so even then they limit one account, never everyone:
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
rateLimit({ window: '15m', max: 10, key: (req) => `${req.ip}:${String(req.body?.email ?? '').toLowerCase()}` })
|
|
81
|
+
```
|
|
51
82
|
|
|
52
83
|
---
|
|
53
84
|
|
|
@@ -122,3 +153,5 @@ cache: { backend: 'redis', url: process.env.REDIS_URL, onRevocationCheckError: '
|
|
|
122
153
|
Either way the failure is logged (at most every 30 seconds), and calling `revokeSession` / `revokeAllSessions` during an outage **throws**, so a failed logout is never reported as a success. Plain `cache.get/set` calls are unaffected — they degrade to misses.
|
|
123
154
|
|
|
124
155
|
`revokeToken(res)` still exists and only clears the cookie — prefer `revokeSession` when a cache is configured.
|
|
156
|
+
|
|
157
|
+
ESM and CommonJS imports share the configured backend, key prefix, pending cache fills and revocation failure policy within one process. A backend configured by one build is used by the other; closing it closes the shared backend. Use one application/cache configuration per process.
|
|
@@ -125,6 +125,8 @@ if (typeof refreshToken !== 'string') return res.status(400).json({ error: 'Inva
|
|
|
125
125
|
const user = await User.findOne({ refreshToken });
|
|
126
126
|
```
|
|
127
127
|
|
|
128
|
+
Without the check, `{"refreshToken": {"$ne": null}}` (or `{"not": ""}` on `defineTable`) matches any account that has a token — the account takeover fixed in the generated routes in 0.9.6 ([GHSA-85c7-prvr-q2rp](https://github.com/pr4shxnt/efc.js/security/advisories/GHSA-85c7-prvr-q2rp)).
|
|
129
|
+
|
|
128
130
|
— or validate the body with `export const schema` ([validation](./validation.md)), which replaces it with the parsed, typed output.
|
|
129
131
|
|
|
130
132
|
## Writing
|
|
@@ -230,3 +232,18 @@ export default defineTask({ schedule: '0 * * * *' }, async () => {
|
|
|
230
232
|
await Session.deleteMany({ expiresAt: { $lt: new Date() } });
|
|
231
233
|
});
|
|
232
234
|
```
|
|
235
|
+
|
|
236
|
+
## PostgreSQL prepared statements
|
|
237
|
+
|
|
238
|
+
EFC's PostgreSQL model queries use named prepared statements by default, through node-postgres. SQL shapes are reused across parameter values on each connection, including inside `transaction()`. Drizzle's encoders, row mode and result parsers are preserved; query logging still counts one execution as one statement. Native `db.query()` is unchanged.
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
ignite({
|
|
242
|
+
databaseUrl: process.env.DATABASE_URL,
|
|
243
|
+
databasePool: { max: 5, preparedStatements: { max: 100 } },
|
|
244
|
+
});
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
The default budget is 100 automatically named statements per physical connection. Existing shapes are reused; when the budget is full, new shapes run unnamed. There is no concurrent eviction/DEALLOCATE. Server statements remain bounded until the connection closes. EFC invalidates reusable shapes after its schema sync/drop changes a table, keeping the same lifetime budget. It does not automatically invalidate after DDL issued outside EFC: reconnect after external schema changes. Named statements explicitly supplied by an application are preserved and are outside this automatic budget. DDL, transaction control and multi-statement SQL are not automatically prepared.
|
|
248
|
+
|
|
249
|
+
Set `databasePool.preparedStatements: false` for transaction poolers that do not support named protocol statements. For PgBouncer, check its [prepared-statement configuration](https://www.pgbouncer.org/config.html#max_prepared_statements); do not assume every deployment supports it. MongoDB ignores this option. This feature avoids repeated parse work for reused SQL; it does not promise faster performance for every query.
|
|
@@ -104,3 +104,9 @@ SMTP_FROM=you@example.com
|
|
|
104
104
|
In development (`efc start dev`), the CLI loads `.env` into `process.env` before your app runs, so `efc.config.ts`'s `process.env.X` reads see it. It re-reads `.env` fresh on every `tsx watch` restart — editing `.env` and saving a source file is enough to pick up the change, no need to stop and restart `efc start dev` itself. Variables already present in `process.env` (e.g. real OS-exported vars, CI-injected secrets) take precedence over `.env`.
|
|
105
105
|
|
|
106
106
|
In production (`efc start prod`), `.env` is loaded if one exists in the working directory — handy on a plain VPS. Platforms (Docker, Kubernetes, Railway, Heroku) that inject secrets directly into `process.env` always win: the file only fills in variables that aren't already set.
|
|
107
|
+
|
|
108
|
+
## Generated two-factor authentication
|
|
109
|
+
|
|
110
|
+
- `TWO_FACTOR_METHOD`: `totp` (default), `email`, or `both`. Init asks when Account security is selected; with both, each account chooses one method at enrollment. Disabling a method does not silently disable enrolled accounts.
|
|
111
|
+
- `TWO_FACTOR_KEY`: independent 32-byte encryption/HMAC key as 64 hex characters (`openssl rand -hex 32`). Init generates it for auth. Keep it stable and shared across instances; changing it requires migrating encrypted secrets or re-enrolling accounts. `ignite()` does not read it; generated `src/lib/two-factor` does.
|
|
112
|
+
- Email OTP needs the email-client's `SMTP_*` settings and a running task backend. Init automatically adds the email client for email/both; with `efc add account-security`, add `efc add email-client` too. Codes expire after five minutes.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# Feature matrix
|
|
2
|
+
|
|
3
|
+
What each model API does on which engine — and the test that proves it. Every test named here runs against a real database in CI; a test (`feature-matrix.test.ts`) fails if a cited test is renamed or removed, so this page can't quietly go stale.
|
|
4
|
+
|
|
5
|
+
✓ supported · — not available (by design: each native API speaks its engine's vocabulary — see [Which API?](./which-api.md))
|
|
6
|
+
|
|
7
|
+
## Models and validation
|
|
8
|
+
|
|
9
|
+
| Feature | `defineModel` MongoDB | `defineModel` PostgreSQL | `defineTable` | `defineCollection` | Proven by |
|
|
10
|
+
|---|:-:|:-:|:-:|:-:|---|
|
|
11
|
+
| Types inferred from the schema | ✓ | ✓ | ✓ | ✓ | `types/docs-types.test-d.ts: type-checked by tsc` |
|
|
12
|
+
| Validation on create and update → 400 | ✓ | ✓ | ✓ | ✓ | `db/engines.integration.test.ts: validates fields, embedded objects and array items` · `db/table.integration.test.ts: validates on create` · `db/collection.integration.test.ts: validates on create and on updates` |
|
|
13
|
+
| Unique violations → 409 | ✓ | ✓ | ✓ | ✓ | `db/engines.integration.test.ts: rejects duplicates of a unique field with 409` · `db/table.integration.test.ts: rejects duplicates with 409` |
|
|
14
|
+
| Defaults, `$now` / `$uuid` / sequences | ✓ | ✓ | ✓ | ✓ | `db/engines.integration.test.ts: creates records with defaults, sequences` · `db/model.smoke.test.ts: resolves $now / $uuid default operator codes` |
|
|
15
|
+
| Embedded objects and arrays | ✓ | ✓ (jsonb) | ✓ (jsonb) | ✓ | `db/engines.integration.test.ts: returns dates nested in objects and arrays as Date on both engines` |
|
|
16
|
+
| Undeclared fields ignored | ✓ | ✓ | ✓ | ✓ | `db/engines.integration.test.ts: ignores undeclared fields on writes` · `db/table.integration.test.ts: AND / OR / NOT combine, undefined is ignored, undeclared fields match nothing` |
|
|
17
|
+
| Engine guard (wrong engine fails clearly) | — | — | ✓ | ✓ | `db/engines.integration.test.ts: engine-native models refuse to run on the other engine` · `db/collection.integration.test.ts: rejects SQL-only types and PostgreSQL connections` |
|
|
18
|
+
| SQL types: integer, bigint, decimal, uuid, varchar, arrays, enums | — | — | ✓ | — | `db/table.integration.test.ts: creates SQL-native columns` · `db/table.integration.test.ts: create returns typed values` |
|
|
19
|
+
| BSON types: decimal128, long, binary, geoPoint | — | — | — | ✓ | `db/collection.integration.test.ts: round-trips BSON types` |
|
|
20
|
+
|
|
21
|
+
## Queries
|
|
22
|
+
|
|
23
|
+
| Feature | `defineModel` MongoDB | `defineModel` PostgreSQL | `defineTable` | `defineCollection` | Proven by |
|
|
24
|
+
|---|:-:|:-:|:-:|:-:|---|
|
|
25
|
+
| Filter operators, dotted paths, `$or`, `$exists` | ✓ | ✓ | — | ✓ | `db/engines.integration.test.ts: filters with operators, dotted paths, array containment` |
|
|
26
|
+
| Prisma-style `where` (incl. `mode: 'insensitive'`) | — | — | ✓ | — | `db/table.integration.test.ts: scalar filters: equals, not, in/notIn, ranges, strings, mode insensitive` |
|
|
27
|
+
| Sort, limit, skip, select / projection | ✓ | ✓ | ✓ | ✓ | `db/engines.integration.test.ts: supports sort, limit, skip and select` · `db/table.integration.test.ts: orderBy (multi-key, nulls), select, omit and distinct` · `db/collection.integration.test.ts: find with projection, sort, skip, limit` |
|
|
28
|
+
| Cursor pagination | — | — | ✓ | — | `db/table.integration.test.ts: cursor: walks every row exactly once` |
|
|
29
|
+
| `exists`, `distinct`, `updateOne`, `deleteOne`, `upsert` | ✓ | ✓ | ✓ | ✓ | `db/engines.integration.test.ts: upsert() creates, then updates, and survives concurrent calls` · `db/table.integration.test.ts: upsert is one INSERT … ON CONFLICT` |
|
|
30
|
+
| `aggregate` / `groupBy` | ✓ (pipeline) | — | ✓ | ✓ | `db/table.integration.test.ts: groupBy with aggregates, having, orderBy and take` · `db/collection.integration.test.ts: aggregate pipelines and populate` |
|
|
31
|
+
| Typed aggregation pipeline + `lookup()` | — | — | — | ✓ | `db/collection.integration.test.ts: typed pipeline: match (ids cast)` · `db/collection.integration.test.ts: lookup: a ref becomes its record` |
|
|
32
|
+
| Geo (`$near`) and `$text` | — | — | — | ✓ | `db/collection.integration.test.ts: find with projection, sort, skip, limit; geo $near; $text` |
|
|
33
|
+
| `bulkWrite`, change streams (`watch`) | — | — | — | ✓ | `db/collection.integration.test.ts: bulkWrite` · `db/collection.integration.test.ts: watch streams changes` |
|
|
34
|
+
| `findOneAndUpdate` (before / after / upsert) | — | — | — | ✓ | `db/collection.integration.test.ts: updates: results, findOneAndUpdate` |
|
|
35
|
+
|
|
36
|
+
## Relations
|
|
37
|
+
|
|
38
|
+
| Feature | `defineModel` MongoDB | `defineModel` PostgreSQL | `defineTable` | `defineCollection` | Proven by |
|
|
39
|
+
|---|:-:|:-:|:-:|:-:|---|
|
|
40
|
+
| `ref` + `populate` | ✓ | ✓ (plain column) | — | ✓ | `db/engines.integration.test.ts: populates single and array refs` |
|
|
41
|
+
| Real foreign keys (`onDelete` restrict / cascade / setNull) | — | — | ✓ | — | `db/table-relations.integration.test.ts: cascade deletes, setNull clears, restrict refuses with a 409` |
|
|
42
|
+
| Many-to-many join tables | — | — | ✓ | — | `db/table-m2n.integration.test.ts: stores the relation in a join table` |
|
|
43
|
+
| `include` in one SQL statement, any depth | — | — | ✓ | — | `db/table-include.integration.test.ts: nests includes with where, orderBy, take, skip — in one statement` |
|
|
44
|
+
| Relation filters (`some` / `every` / `none`, `is` / `isNot`) | — | — | ✓ | — | `db/table-nested.integration.test.ts: some / none / every on a hasMany back-relation` |
|
|
45
|
+
| Nested writes (`connect`, `create`, `connectOrCreate`, …) | — | — | ✓ | — | `db/table-nested.integration.test.ts: creates with connect, create and connectOrCreate` |
|
|
46
|
+
|
|
47
|
+
## Transactions, schema and tooling
|
|
48
|
+
|
|
49
|
+
| Feature | `defineModel` MongoDB | `defineModel` PostgreSQL | `defineTable` | `defineCollection` | Proven by |
|
|
50
|
+
|---|:-:|:-:|:-:|:-:|---|
|
|
51
|
+
| `transaction()` | ✓ (replica set) | ✓ | ✓ | ✓ (replica set) | `db/table.integration.test.ts: joins transaction() and rolls back` · `db/collection.integration.test.ts: joins transactions` |
|
|
52
|
+
| Auto-sync on first use (never drops data) | ✓ | ✓ | ✓ | ✓ | `db/engines.integration.test.ts: works on first use — no sync() or migration needed` · `db/engines.integration.test.ts: evolving a model never strands writes or rows` |
|
|
53
|
+
| `efc db generate` migrations from model diffs | ✓ | ✓ | ✓ | ✓ | `integration/db-generate.test.ts: writes a migration from the models, verifies it` · `integration/db-generate.test.ts: creates collections and indexes` |
|
|
54
|
+
| `efc db pull` | — | ✓ (as defineTable) | ✓ | ✓ | `integration/db-generate.test.ts: import-prisma → generate → migrate → pull round-trips` · `db/pull-mongo.integration.test.ts: the pulled models read the data and find nothing to sync` |
|
|
55
|
+
| `efc import-prisma` | — | — | ✓ | — | `db/prisma-import.test.ts: maps scalars, ids, timestamps, defaults` |
|
|
56
|
+
| Query logging + N+1 warnings | ✓ | ✓ | ✓ | ✓ | `db/query-log.integration.test.ts: warns once per request about an N+1 pattern` |
|
|
57
|
+
| `efc db studio --write` (through the model) | ✓ | ✓ | ✓ | ✓ | `db/studio.integration.test.ts: inserts, edits and deletes through the model` · `db/studio.integration.test.ts: writes through defineCollection` |
|
|
58
|
+
| Same table from `defineModel` and `defineTable` | — | ✓ | ✓ | — | `db/table.integration.test.ts: defineModel and defineTable over the same table` |
|