express-file-cluster 0.9.3 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/dist/auth/index.cjs +6 -7
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +7 -2
  4. package/dist/auth/index.d.ts +7 -2
  5. package/dist/auth/index.js +5 -6
  6. package/dist/{chunk-QL6EWT4B.cjs → chunk-4DOHQU6I.cjs} +9 -7
  7. package/dist/chunk-4DOHQU6I.cjs.map +1 -0
  8. package/dist/chunk-73XJUT2S.js +366 -0
  9. package/dist/chunk-73XJUT2S.js.map +1 -0
  10. package/dist/{chunk-ATL4GYFU.js → chunk-7KC2H76D.js} +50 -8
  11. package/dist/chunk-7KC2H76D.js.map +1 -0
  12. package/dist/{chunk-TYR2GZZE.cjs → chunk-7KO4DJRJ.cjs} +19 -14
  13. package/dist/chunk-7KO4DJRJ.cjs.map +1 -0
  14. package/dist/{chunk-UBQYQPBU.js → chunk-ATVD2HGC.js} +4 -4
  15. package/dist/{chunk-R34R7QPD.cjs → chunk-DCJOWFVD.cjs} +3 -3
  16. package/dist/{chunk-R34R7QPD.cjs.map → chunk-DCJOWFVD.cjs.map} +1 -1
  17. package/dist/chunk-DUADUR6R.cjs +366 -0
  18. package/dist/chunk-DUADUR6R.cjs.map +1 -0
  19. package/dist/{chunk-BBSZLGZW.js → chunk-EGSSZUVO.js} +8 -6
  20. package/dist/chunk-EGSSZUVO.js.map +1 -0
  21. package/dist/{chunk-TI24L4XE.cjs → chunk-GBI77W5T.cjs} +6 -2
  22. package/dist/chunk-GBI77W5T.cjs.map +1 -0
  23. package/dist/{chunk-RTF7PHS2.cjs → chunk-HBCY7ILD.cjs} +306 -119
  24. package/dist/chunk-HBCY7ILD.cjs.map +1 -0
  25. package/dist/{chunk-ANUSWEAP.cjs → chunk-KFVFP2Q7.cjs} +59 -17
  26. package/dist/chunk-KFVFP2Q7.cjs.map +1 -0
  27. package/dist/{chunk-RS4MXCPW.js → chunk-NI2BNGGV.js} +2 -2
  28. package/dist/{chunk-X2US4RAM.cjs → chunk-NKLOE4AK.cjs} +11 -13
  29. package/dist/chunk-NKLOE4AK.cjs.map +1 -0
  30. package/dist/{chunk-RRQ2RK5M.js → chunk-PGJQK36V.js} +195 -8
  31. package/dist/chunk-PGJQK36V.js.map +1 -0
  32. package/dist/{chunk-QKQZF573.js → chunk-QDEDOHP7.js} +4 -6
  33. package/dist/chunk-QDEDOHP7.js.map +1 -0
  34. package/dist/{chunk-UTM4PEVG.js → chunk-R4XO4SVM.js} +10 -5
  35. package/dist/chunk-R4XO4SVM.js.map +1 -0
  36. package/dist/chunk-R52CUEGT.js +74 -0
  37. package/dist/chunk-R52CUEGT.js.map +1 -0
  38. package/dist/{chunk-HBYSKULC.js → chunk-RAB44UGX.js} +5 -1
  39. package/dist/chunk-RAB44UGX.js.map +1 -0
  40. package/dist/{chunk-7YEX4MQV.cjs → chunk-WBLUGOAG.cjs} +42 -6
  41. package/dist/chunk-WBLUGOAG.cjs.map +1 -0
  42. package/dist/{chunk-T4OHFU5T.cjs → chunk-YK4ZM3CA.cjs} +15 -15
  43. package/dist/{chunk-T4OHFU5T.cjs.map → chunk-YK4ZM3CA.cjs.map} +1 -1
  44. package/dist/cli/db-runner.cjs +2012 -120
  45. package/dist/cli/db-runner.cjs.map +1 -1
  46. package/dist/cli/db-runner.js +1989 -97
  47. package/dist/cli/db-runner.js.map +1 -1
  48. package/dist/cli/index.cjs +101 -43
  49. package/dist/cli/index.cjs.map +1 -1
  50. package/dist/cli/index.js +80 -22
  51. package/dist/cli/index.js.map +1 -1
  52. package/dist/docs/api-reference/auth.md +10 -8
  53. package/dist/docs/api-reference/collection.md +44 -1
  54. package/dist/docs/api-reference/ignite.md +22 -3
  55. package/dist/docs/api-reference/types.md +99 -0
  56. package/dist/docs/cli/add.md +1 -1
  57. package/dist/docs/cli/db.md +2 -2
  58. package/dist/docs/contributing/index.md +1 -1
  59. package/dist/docs/core-concepts/background-tasks.md +6 -3
  60. package/dist/docs/getting-started/index.md +3 -2
  61. package/dist/docs/guides/authentication.md +34 -24
  62. package/dist/docs/guides/caching.md +32 -1
  63. package/dist/docs/guides/database.md +14 -0
  64. package/dist/docs/guides/feature-matrix.md +58 -0
  65. package/dist/docs/guides/migrations.md +23 -2
  66. package/dist/docs/guides/oauth.md +15 -1
  67. package/dist/docs/guides/which-api.md +2 -2
  68. package/dist/docs/index.md +4 -1
  69. package/dist/docs/skills/SKILL.md +2 -2
  70. package/dist/docs/skills/api-surface.md +10 -4
  71. package/dist/docs/skills/auth-internals.md +3 -3
  72. package/dist/docs/skills/tasks-internals.md +4 -3
  73. package/dist/docs/skills/what-not-to-invent.md +4 -3
  74. package/dist/docs/versioning.md +42 -0
  75. package/dist/index.cjs +144 -51
  76. package/dist/index.cjs.map +1 -1
  77. package/dist/index.d.cts +204 -3
  78. package/dist/index.d.ts +204 -3
  79. package/dist/index.js +107 -14
  80. package/dist/index.js.map +1 -1
  81. package/dist/pgboss-backend-FW42SBSM.js +14 -0
  82. package/dist/pgboss-backend-RVHUBJTU.cjs +14 -0
  83. package/dist/{pgboss-backend-TCHI7CHM.cjs.map → pgboss-backend-RVHUBJTU.cjs.map} +1 -1
  84. package/dist/registry/index.json +34 -3
  85. package/dist/registry/js-mongo/account-security.json +1 -1
  86. package/dist/registry/js-mongo/admin-users.json +1 -1
  87. package/dist/registry/js-mongo/auth.json +1 -1
  88. package/dist/registry/js-mongo/auth@apple.json +1 -1
  89. package/dist/registry/js-mongo/auth@google.json +1 -1
  90. package/dist/registry/js-mongo/email-verification.json +1 -1
  91. package/dist/registry/js-mongo/forgot-password.json +1 -1
  92. package/dist/registry/js-mongo/user-profile.json +1 -1
  93. package/dist/registry/js-mongo-collection/_base.json +1 -0
  94. package/dist/registry/js-mongo-collection/account-security.json +1 -0
  95. package/dist/registry/js-mongo-collection/account-settings.json +1 -0
  96. package/dist/registry/js-mongo-collection/admin-admins.json +1 -0
  97. package/dist/registry/js-mongo-collection/admin-analytics.json +1 -0
  98. package/dist/registry/js-mongo-collection/admin-billing.json +1 -0
  99. package/dist/registry/js-mongo-collection/admin-content.json +1 -0
  100. package/dist/registry/js-mongo-collection/admin-logs.json +1 -0
  101. package/dist/registry/js-mongo-collection/admin-support.json +1 -0
  102. package/dist/registry/js-mongo-collection/admin-system.json +1 -0
  103. package/dist/registry/js-mongo-collection/admin-users.json +1 -0
  104. package/dist/registry/js-mongo-collection/admin.json +1 -0
  105. package/dist/registry/js-mongo-collection/auth.json +1 -0
  106. package/dist/registry/js-mongo-collection/auth@apple.json +1 -0
  107. package/dist/registry/js-mongo-collection/auth@google.json +1 -0
  108. package/dist/registry/js-mongo-collection/billing.json +1 -0
  109. package/dist/registry/js-mongo-collection/email-client.json +1 -0
  110. package/dist/registry/js-mongo-collection/email-verification.json +1 -0
  111. package/dist/registry/js-mongo-collection/files.json +1 -0
  112. package/dist/registry/js-mongo-collection/forgot-password.json +1 -0
  113. package/dist/registry/js-mongo-collection/notifications.json +1 -0
  114. package/dist/registry/js-mongo-collection/support.json +1 -0
  115. package/dist/registry/js-mongo-collection/user-profile.json +1 -0
  116. package/dist/registry/js-pg-model/account-security.json +1 -1
  117. package/dist/registry/js-pg-model/admin-users.json +1 -1
  118. package/dist/registry/js-pg-model/auth.json +1 -1
  119. package/dist/registry/js-pg-model/auth@apple.json +1 -1
  120. package/dist/registry/js-pg-model/auth@google.json +1 -1
  121. package/dist/registry/js-pg-model/email-verification.json +1 -1
  122. package/dist/registry/js-pg-model/forgot-password.json +1 -1
  123. package/dist/registry/js-pg-model/user-profile.json +1 -1
  124. package/dist/registry/js-pg-table/account-security.json +1 -1
  125. package/dist/registry/js-pg-table/admin-users.json +1 -1
  126. package/dist/registry/js-pg-table/auth.json +1 -1
  127. package/dist/registry/js-pg-table/auth@apple.json +1 -1
  128. package/dist/registry/js-pg-table/auth@google.json +1 -1
  129. package/dist/registry/js-pg-table/email-verification.json +1 -1
  130. package/dist/registry/js-pg-table/forgot-password.json +1 -1
  131. package/dist/registry/js-pg-table/user-profile.json +1 -1
  132. package/dist/registry/ts-mongo/account-security.json +1 -1
  133. package/dist/registry/ts-mongo/admin-users.json +1 -1
  134. package/dist/registry/ts-mongo/auth.json +1 -1
  135. package/dist/registry/ts-mongo/auth@apple.json +1 -1
  136. package/dist/registry/ts-mongo/auth@google.json +1 -1
  137. package/dist/registry/ts-mongo/email-verification.json +1 -1
  138. package/dist/registry/ts-mongo/forgot-password.json +1 -1
  139. package/dist/registry/ts-mongo/user-profile.json +1 -1
  140. package/dist/registry/ts-mongo-collection/_base.json +1 -0
  141. package/dist/registry/ts-mongo-collection/account-security.json +1 -0
  142. package/dist/registry/ts-mongo-collection/account-settings.json +1 -0
  143. package/dist/registry/ts-mongo-collection/admin-admins.json +1 -0
  144. package/dist/registry/ts-mongo-collection/admin-analytics.json +1 -0
  145. package/dist/registry/ts-mongo-collection/admin-billing.json +1 -0
  146. package/dist/registry/ts-mongo-collection/admin-content.json +1 -0
  147. package/dist/registry/ts-mongo-collection/admin-logs.json +1 -0
  148. package/dist/registry/ts-mongo-collection/admin-support.json +1 -0
  149. package/dist/registry/ts-mongo-collection/admin-system.json +1 -0
  150. package/dist/registry/ts-mongo-collection/admin-users.json +1 -0
  151. package/dist/registry/ts-mongo-collection/admin.json +1 -0
  152. package/dist/registry/ts-mongo-collection/auth.json +1 -0
  153. package/dist/registry/ts-mongo-collection/auth@apple.json +1 -0
  154. package/dist/registry/ts-mongo-collection/auth@google.json +1 -0
  155. package/dist/registry/ts-mongo-collection/billing.json +1 -0
  156. package/dist/registry/ts-mongo-collection/email-client.json +1 -0
  157. package/dist/registry/ts-mongo-collection/email-verification.json +1 -0
  158. package/dist/registry/ts-mongo-collection/files.json +1 -0
  159. package/dist/registry/ts-mongo-collection/forgot-password.json +1 -0
  160. package/dist/registry/ts-mongo-collection/notifications.json +1 -0
  161. package/dist/registry/ts-mongo-collection/support.json +1 -0
  162. package/dist/registry/ts-mongo-collection/user-profile.json +1 -0
  163. package/dist/registry/ts-pg-model/account-security.json +1 -1
  164. package/dist/registry/ts-pg-model/admin-users.json +1 -1
  165. package/dist/registry/ts-pg-model/auth.json +1 -1
  166. package/dist/registry/ts-pg-model/auth@apple.json +1 -1
  167. package/dist/registry/ts-pg-model/auth@google.json +1 -1
  168. package/dist/registry/ts-pg-model/email-verification.json +1 -1
  169. package/dist/registry/ts-pg-model/forgot-password.json +1 -1
  170. package/dist/registry/ts-pg-model/user-profile.json +1 -1
  171. package/dist/registry/ts-pg-table/account-security.json +1 -1
  172. package/dist/registry/ts-pg-table/admin-users.json +1 -1
  173. package/dist/registry/ts-pg-table/auth.json +1 -1
  174. package/dist/registry/ts-pg-table/auth@apple.json +1 -1
  175. package/dist/registry/ts-pg-table/auth@google.json +1 -1
  176. package/dist/registry/ts-pg-table/email-verification.json +1 -1
  177. package/dist/registry/ts-pg-table/forgot-password.json +1 -1
  178. package/dist/registry/ts-pg-table/user-profile.json +1 -1
  179. package/dist/tasks/index.cjs +4 -2
  180. package/dist/tasks/index.cjs.map +1 -1
  181. package/dist/tasks/index.d.cts +4 -2
  182. package/dist/tasks/index.d.ts +4 -2
  183. package/dist/tasks/index.js +3 -1
  184. package/dist/thread-runner.cjs +8 -0
  185. package/dist/thread-runner.cjs.map +1 -0
  186. package/dist/thread-runner.d.cts +3 -0
  187. package/dist/thread-runner.d.ts +3 -0
  188. package/dist/thread-runner.js +8 -0
  189. package/dist/thread-runner.js.map +1 -0
  190. package/dist/{types-BY-ObnZH.d.ts → types-Bnxvj3l0.d.cts} +14 -2
  191. package/dist/{types-BY-ObnZH.d.cts → types-Bnxvj3l0.d.ts} +14 -2
  192. package/package.json +1 -1
  193. package/dist/chunk-277BSYVH.js +0 -127
  194. package/dist/chunk-277BSYVH.js.map +0 -1
  195. package/dist/chunk-7YEX4MQV.cjs.map +0 -1
  196. package/dist/chunk-ANUSWEAP.cjs.map +0 -1
  197. package/dist/chunk-ATL4GYFU.js.map +0 -1
  198. package/dist/chunk-BBSZLGZW.js.map +0 -1
  199. package/dist/chunk-HBYSKULC.js.map +0 -1
  200. package/dist/chunk-HXV543HZ.js +0 -177
  201. package/dist/chunk-HXV543HZ.js.map +0 -1
  202. package/dist/chunk-LJNSJFOL.js +0 -38
  203. package/dist/chunk-LJNSJFOL.js.map +0 -1
  204. package/dist/chunk-QKQZF573.js.map +0 -1
  205. package/dist/chunk-QL6EWT4B.cjs.map +0 -1
  206. package/dist/chunk-RRQ2RK5M.js.map +0 -1
  207. package/dist/chunk-RTF7PHS2.cjs.map +0 -1
  208. package/dist/chunk-TI24L4XE.cjs.map +0 -1
  209. package/dist/chunk-TYR2GZZE.cjs.map +0 -1
  210. package/dist/chunk-UTM4PEVG.js.map +0 -1
  211. package/dist/chunk-VQSWSYK6.cjs +0 -177
  212. package/dist/chunk-VQSWSYK6.cjs.map +0 -1
  213. package/dist/chunk-X2US4RAM.cjs.map +0 -1
  214. package/dist/chunk-YL37D6KM.cjs +0 -127
  215. package/dist/chunk-YL37D6KM.cjs.map +0 -1
  216. package/dist/pgboss-backend-QKBXVJ6B.js +0 -14
  217. package/dist/pgboss-backend-TCHI7CHM.cjs +0 -14
  218. /package/dist/{chunk-UBQYQPBU.js.map → chunk-ATVD2HGC.js.map} +0 -0
  219. /package/dist/{chunk-RS4MXCPW.js.map → chunk-NI2BNGGV.js.map} +0 -0
  220. /package/dist/{pgboss-backend-QKBXVJ6B.js.map → pgboss-backend-FW42SBSM.js.map} +0 -0
@@ -23,13 +23,13 @@ Auth must be configured before any of these functions are called. Configuration
23
23
 
24
24
  ## `issueToken(res, payload)`
25
25
 
26
- Signs a JWT and sets it as an `HttpOnly` cookie on the response. Use with the `'http-only'` auth strategy.
26
+ Signs a JWT and delivers it the way `authStrategy` says: with `'http-only'` it sets an `HttpOnly` cookie and resolves `undefined`; with `'bearer'` it sets no cookie and resolves the token, for you to put in the response body. Writing `res.json({ ...(token ? { token } : {}) })` makes one route work under both.
27
27
 
28
28
  ```ts
29
29
  async function issueToken(
30
30
  res: Response,
31
31
  payload: Record<string, unknown>,
32
- ): Promise<void>
32
+ ): Promise<string | undefined>
33
33
  ```
34
34
 
35
35
  | Parameter | Type | Description |
@@ -37,7 +37,7 @@ async function issueToken(
37
37
  | `res` | `Response` | Express response object |
38
38
  | `payload` | `Record<string, unknown>` | JWT claims (e.g. `{ sub: user.id, role: user.role }`) |
39
39
 
40
- The cookie is named `efc_token` and is set with:
40
+ With `'http-only'`, the cookie is named `efc_token` and is set with:
41
41
 
42
42
  - `HttpOnly: true` — not accessible via `document.cookie`
43
43
  - `Secure: true` — only sent over HTTPS (when `NODE_ENV === 'production'`)
@@ -52,11 +52,13 @@ import { issueToken } from 'express-file-cluster/auth';
52
52
 
53
53
  export const POST = async (req, res) => {
54
54
  const user = await verifyCredentials(req.body.email, req.body.password);
55
- await issueToken(res, { sub: user.id, role: user.role });
56
- res.json({ message: 'Logged in' });
55
+ const token = await issueToken(res, { sub: user.id, role: user.role });
56
+ res.json({ message: 'Logged in', ...(token ? { token } : {}) });
57
57
  };
58
58
  ```
59
59
 
60
+ > Before 0.9.4, `issueToken` always set the cookie and resolved `undefined`, even with the Bearer strategy — bearer clients never received a token. Use the return value.
61
+
60
62
  ---
61
63
 
62
64
  ## `revokeToken(res)`
@@ -105,7 +107,7 @@ Every token EFC signs carries a `jti` and an issue time, which these checks use.
105
107
 
106
108
  ## `signToken(payload)`
107
109
 
108
- Signs a JWT and returns the token string. Use with the `'localStorage'` strategy; the client stores the token and attaches it as `Authorization: Bearer <token>`.
110
+ Signs a JWT and returns the token string, whatever the strategy — for tokens you hand out yourself (e.g. to a service). For login, prefer `issueToken`, which follows `authStrategy`.
109
111
 
110
112
  ```ts
111
113
  async function signToken(
@@ -126,7 +128,7 @@ export const POST = async (req, res) => {
126
128
  };
127
129
  ```
128
130
 
129
- The client then stores the token (e.g. `localStorage.setItem('token', token)`) and sends it on subsequent requests:
131
+ A bearer client keeps the token in secure storage (Keychain / Keystore — not browser `localStorage`) and sends it on subsequent requests:
130
132
 
131
133
  ```http
132
134
  Authorization: Bearer <token>
@@ -153,7 +155,7 @@ Behaviour depends on the configured `authStrategy`:
153
155
  | Strategy | Token source |
154
156
  |---|---|
155
157
  | `'http-only'` | `req.cookies.efc_token` |
156
- | `'localStorage'` | `Authorization: Bearer <token>` header |
158
+ | `'bearer'` (or the old name `'localStorage'`) | `Authorization: Bearer <token>` header |
157
159
 
158
160
  **Route-level, auth only (protects all handlers in the file):**
159
161
 
@@ -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
- The pipeline is passed to MongoDB unchanged; type the output with the generic. Results get the same conversions as records: decimals become strings, longs bigints, `_id` gains a string `id`. `$lookup` joins other collections by collection name.
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
 
@@ -34,7 +34,7 @@ interface EFCConfig {
34
34
  databasePool?: { max?: number; idleTimeoutMs?: number; connectionTimeoutMs?: number };
35
35
 
36
36
  // Auth
37
- authStrategy?: 'http-only' | 'localStorage';
37
+ authStrategy?: 'http-only' | 'bearer'; // 'localStorage' = old name for 'bearer'
38
38
  jwtSecret?: string;
39
39
  jwtExpiresIn?: string;
40
40
  cookieDomain?: string;
@@ -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)).
@@ -167,6 +176,16 @@ databasePool: { max: 5, idleTimeoutMs: 30_000, connectionTimeoutMs: 5_000 },
167
176
 
168
177
  Unset options keep the driver's default. `efc db` commands use the defaults.
169
178
 
179
+ At boot, one process per machine logs the total — `workers × (max + 10 for pg-boss on the same database)` on PostgreSQL, `workers × max` on MongoDB. On PostgreSQL it compares that with the server's `max_connections` (minus the superuser reserve) and **warns** when this machine alone could exhaust it:
180
+
181
+ ```
182
+ [EFC] PostgreSQL connections: up to 110 from this machine (11 worker(s) × (pool 10)), but the server allows 97 …
183
+ ```
184
+
185
+ Several instances share the server, so multiply by the instance count — or put PgBouncer in front.
186
+
187
+ Failed connections name the fix instead of echoing the driver: a `DATABASE_URL` without a password, a wrong password, a missing database or role, a server that needs `?sslmode=require`, nothing listening at the host/port (PostgreSQL); a rejected login or an unreachable server (MongoDB). The password is never printed; the driver's error is kept as `cause`.
188
+
170
189
  ---
171
190
 
172
191
  ### `authStrategy`
@@ -176,9 +195,9 @@ How JWTs are delivered to clients:
176
195
  | Value | Mechanism |
177
196
  |---|---|
178
197
  | `'http-only'` | `HttpOnly + Secure + SameSite=Strict` cookie named `efc_token` |
179
- | `'localStorage'` | Token returned in response body; client attaches `Authorization: Bearer <token>` |
198
+ | `'bearer'` | `issueToken` returns the token for the response body; the client sends `Authorization: Bearer <token>` |
180
199
 
181
- Default: `'http-only'`.
200
+ Default: `'http-only'`. Use `'http-only'` for browsers (websites and SPAs) and `'bearer'` for mobile/desktop apps and API clients — see [Choosing a strategy](../guides/authentication.md#choosing-a-strategy). `'localStorage'` is the pre-0.9.4 name for `'bearer'` and still works; any other value is treated as `'bearer'` with a startup warning (an error from 1.0).
182
201
 
183
202
  ---
184
203
 
@@ -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>`).
@@ -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.9.3",
143
+ "registry": "0.10.0",
144
144
  "language": "typescript",
145
145
  "database": "postgresql",
146
146
  "modelApi": "defineTable",
@@ -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 defineTable models for the database (PostgreSQL)
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] # read-only browser on 127.0.0.1 (rows + table structure)
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
@@ -77,7 +77,7 @@ Follow [Conventional Commits](https://www.conventionalcommits.org/):
77
77
  ```
78
78
  feat(router): support catch-all wildcard routes
79
79
  fix(cluster): prevent infinite respawn loop on startup crash
80
- docs(auth): add localStorage strategy example
80
+ docs(auth): add bearer strategy example
81
81
  chore(deps): upgrade jose to v5
82
82
  ```
83
83
 
@@ -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, reads `workerData.handlerPath` and `workerData.payload`, imports the task file, calls `def.handler(payload)`, and posts `{ ok: true }` or `{ ok: false, error }` back to the main thread.
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 `{ ok: true }` or rejects on error.
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
 
@@ -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 only)
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`)
@@ -41,7 +42,7 @@ On **PostgreSQL**, models default to [`defineTable`](../api-reference/table.md):
41
42
  Depending on what you pick, you'll see follow-up questions:
42
43
 
43
44
  - **Task queue backend.** `pg-boss` stores jobs in your PostgreSQL, so there's no Redis to run. `BullMQ` uses Redis (`REDIS_URL` in `.env`).
44
- - **Authentication** (or any feature that needs it) → pick a strategy: `http-only` (cookie) or `localStorage` (Bearer token).
45
+ - **Authentication** → `http-only cookie` (browsers — websites and SPAs, recommended), `Bearer token` (mobile/desktop apps, API clients), or `None` (add it later with `efc add auth`). Asked before the feature list; picking a strategy ticks the Authentication feature.
45
46
  - **Sign in with Google / Apple** → the OAuth client credentials (Apple: Services ID, Team ID, Key ID and the path to your `.p8` key). See [Sign in with Google & Apple](../guides/oauth.md).
46
47
  - **Email client** → pick an email provider: `Gmail` (preconfigured `smtp.gmail.com`, no host or port to type) or `Other (custom SMTP)` (asks for host + port). Either way you're then asked for the sending email address and password. **For Gmail this must be a 16-character App Password, not your normal Gmail password.** The prompt rejects anything that isn't 16 characters. See [Mailer](../guides/mailer.md) for the full walkthrough, including how to generate an App Password.
47
48
 
@@ -1,6 +1,6 @@
1
1
  # Authentication Guide
2
2
 
3
- EFC ships a complete JWT authentication system. Choose between two delivery strategies depending on your frontend architecture.
3
+ EFC ships a complete JWT authentication system. Choose between two delivery strategies depending on who your clients are.
4
4
 
5
5
  > Ready-made routes: `efc add auth` (register / login / logout / me) and `efc add auth@google` / `auth@apple` ([Sign in with Google & Apple](./oauth.md)). See [efc add](../cli/add.md).
6
6
 
@@ -8,21 +8,28 @@ EFC ships a complete JWT authentication system. Choose between two delivery stra
8
8
 
9
9
  ## Choosing a strategy
10
10
 
11
- | | `http-only` | `localStorage` |
11
+ The question is **who the client is**, not "website or app":
12
+
13
+ | | `http-only` (default) | `bearer` |
12
14
  |---|---|---|
13
- | **Token location** | `HttpOnly` cookie | Response body → client storage |
14
- | **XSS risk** | Immune (JS can't read the cookie) | Exposed (JS reads `localStorage`) |
15
- | **CSRF risk** | Mitigated by `SameSite=Strict` | Not applicable (no cookie) |
16
- | **Best for** | SSR / SSG frontends, same-origin SPAs | SPAs on a different origin, mobile apps |
17
- | **`requireAuth` reads from** | `req.cookies.efc_token` | `Authorization: Bearer` header |
15
+ | **For** | Browsers — websites **and** SPAs (React, Vue, …) | Mobile / desktop apps, CLIs, server-to-server API clients |
16
+ | **Token travels as** | `HttpOnly` cookie | `Authorization: Bearer <token>` header |
17
+ | **Client stores it in** | Nothing — the browser handles the cookie | iOS Keychain / Android Keystore / OS credential store |
18
+ | **XSS** | Script can't read the token | A token kept in browser `localStorage` can be stolen by any script on the page |
19
+ | **CSRF** | Mitigated by `SameSite=Strict` | Not applicable (no cookie) |
20
+ | **`requireAuth` reads** | `req.cookies.efc_token` | the `Authorization` header |
21
+
22
+ Pick `http-only` for anything that runs in a browser — including SPAs. `bearer` is for clients that have no cookie jar (native apps) or that call the API on behalf of something else. The one browser case for `bearer` is an SPA on a completely different site than the API, where cookies would need `SameSite=None` and credentialed CORS.
18
23
 
19
- Configure the strategy in `ignite()`:
24
+ `create-efc-app` asks this up front; `efc add auth` asks it too and writes the answer to `efc.config`. To switch later, change one line — the generated routes work with both:
20
25
 
21
26
  ```ts
22
- ignite({ authStrategy: 'http-only' }); // default
23
- ignite({ authStrategy: 'localStorage' });
27
+ // efc.config.ts
28
+ authStrategy: 'http-only', // or 'bearer'
24
29
  ```
25
30
 
31
+ > `'localStorage'` is the pre-0.9.4 name for `'bearer'` and still works. Any other value is treated as `'bearer'` and logs a warning at startup; from 1.0 it's an error.
32
+
26
33
  ---
27
34
 
28
35
  ## `http-only` strategy
@@ -90,15 +97,17 @@ export const GET = async (req, res) => {
90
97
 
91
98
  ---
92
99
 
93
- ## `localStorage` strategy
100
+ ## `bearer` strategy
94
101
 
95
102
  ### Login
96
103
 
104
+ `issueToken` hands the token back instead of setting a cookie, so the same route serves both strategies:
105
+
97
106
  ```ts
98
107
  // src/api/auth/login.ts
99
108
  import type { Request, Response } from 'express';
100
109
  import { HttpError } from 'express-file-cluster';
101
- import { signToken, verifyPassword } from 'express-file-cluster/auth';
110
+ import { issueToken, verifyPassword } from 'express-file-cluster/auth';
102
111
  import { User } from '../../model/User.js';
103
112
 
104
113
  export const POST = async (req: Request, res: Response) => {
@@ -107,27 +116,28 @@ export const POST = async (req: Request, res: Response) => {
107
116
  throw new HttpError(401, 'Invalid credentials');
108
117
  }
109
118
 
110
- const token = await signToken({ sub: user.id, role: user.role });
111
- res.json({ token });
119
+ // http-only: sets the cookie, returns undefined. bearer: returns the token.
120
+ const token = await issueToken(res, { sub: user.id, role: user.role });
121
+ res.json({ message: 'Logged in', ...(token ? { token } : {}) });
112
122
  };
113
123
  ```
114
124
 
115
- The client stores the token:
125
+ The scaffolded login and `/auth/refresh` routes also return `refreshToken` in bearer mode; post it back as `{ refreshToken }` to `/auth/refresh` for a new pair. Google/Apple sign-in never puts the JWT in a URL: the app starts it with a PKCE `code_challenge`, gets `OAUTH_SUCCESS_REDIRECT#code=<code>` back and posts `{ code, code_verifier }` to `/auth/oauth/exchange` for the token. The code works once, for 60 seconds, and only with the app's verifier — see [Sign in with Google & Apple](./oauth.md#bearer-apps-mobile--desktop).
116
126
 
117
- ```js
118
- // frontend
119
- const { token } = await fetch('/auth/login', { method: 'POST', body: ... }).then(r => r.json());
120
- localStorage.setItem('authToken', token);
121
- ```
122
-
123
- And attaches it on protected requests:
127
+ The client keeps the token in secure storage and sends it on every request:
124
128
 
125
129
  ```js
126
- fetch('/profile', {
127
- headers: { Authorization: `Bearer ${localStorage.getItem('authToken')}` },
130
+ // React Native (expo-secure-store); on iOS/Android natively: Keychain / Keystore
131
+ const { token } = await fetch(`${API}/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }) }).then(r => r.json());
132
+ await SecureStore.setItemAsync('token', token);
133
+
134
+ await fetch(`${API}/profile`, {
135
+ headers: { Authorization: `Bearer ${await SecureStore.getItemAsync('token')}` },
128
136
  });
129
137
  ```
130
138
 
139
+ Avoid browser `localStorage` for the token — that's what `http-only` is for.
140
+
131
141
  ### Protecting routes
132
142
 
133
143
  Identical to `http-only` — `requireAuth` reads from the correct source based on the configured strategy:
@@ -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
 
@@ -115,6 +115,20 @@ Filters, sorting and pagination behave the same on both engines.
115
115
 
116
116
  ---
117
117
 
118
+ ### Check request values before they reach a filter
119
+
120
+ Filters accept operator objects, and JSON bodies (and `?a[b]=c` query strings) can carry objects where you expect a string. Check the type of anything from `req.body` / `req.query` before using it in a lookup:
121
+
122
+ ```ts
123
+ const { refreshToken } = req.body;
124
+ if (typeof refreshToken !== 'string') return res.status(400).json({ error: 'Invalid refresh token' });
125
+ const user = await User.findOne({ refreshToken });
126
+ ```
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
+
130
+ — or validate the body with `export const schema` ([validation](./validation.md)), which replaces it with the parsed, typed output.
131
+
118
132
  ## Writing
119
133
 
120
134
  ```ts
@@ -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` |