@warlock.js/core 5.34.3 → 5.36.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 (281) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/esm/cli/cli-commands.manager.mjs +1 -1
  3. package/esm/cli/cli-commands.manager.mjs.map +1 -1
  4. package/esm/cli/commands/add.command.mjs +1 -0
  5. package/esm/cli/commands/add.command.mjs.map +1 -1
  6. package/esm/cli/commands/build.command.mjs +30 -3
  7. package/esm/cli/commands/build.command.mjs.map +1 -1
  8. package/esm/cli/commands/check/check-command.action.mjs +1 -0
  9. package/esm/cli/commands/check/check-command.action.mjs.map +1 -1
  10. package/esm/cli/commands/check.command.mjs +5 -0
  11. package/esm/cli/commands/check.command.mjs.map +1 -1
  12. package/esm/cli/commands/explain/explain-command.action.mjs +21 -0
  13. package/esm/cli/commands/explain/explain-command.action.mjs.map +1 -1
  14. package/esm/cli/commands/explain.command.mjs +14 -4
  15. package/esm/cli/commands/explain.command.mjs.map +1 -1
  16. package/esm/cli/commands/generate/generate.command.mjs +19 -1
  17. package/esm/cli/commands/generate/generate.command.mjs.map +1 -1
  18. package/esm/cli/commands/generate/generators/endpoint.generator.mjs +1 -1
  19. package/esm/cli/commands/generate/generators/endpoint.generator.mjs.map +1 -1
  20. package/esm/cli/commands/generate/generators/web.generator.mjs +169 -0
  21. package/esm/cli/commands/generate/generators/web.generator.mjs.map +1 -0
  22. package/esm/cli/commands/generate/templates/web-stubs.mjs +231 -0
  23. package/esm/cli/commands/generate/templates/web-stubs.mjs.map +1 -0
  24. package/esm/cli/commands/inspect/inspect-command.action.mjs +4 -3
  25. package/esm/cli/commands/inspect/inspect-command.action.mjs.map +1 -1
  26. package/esm/cli/commands/inspect.command.mjs +13 -8
  27. package/esm/cli/commands/inspect.command.mjs.map +1 -1
  28. package/esm/cli/commands/mcp/mcp-command.action.mjs +1 -1
  29. package/esm/cli/commands/mcp/mcp-command.action.mjs.map +1 -1
  30. package/esm/config/config-loader.d.mts.map +1 -1
  31. package/esm/config/config-loader.mjs +2 -0
  32. package/esm/config/config-loader.mjs.map +1 -1
  33. package/esm/config/load-config-files.mjs +4 -0
  34. package/esm/config/load-config-files.mjs.map +1 -1
  35. package/esm/dev-server/file-event-handler.mjs +11 -1
  36. package/esm/dev-server/file-event-handler.mjs.map +1 -1
  37. package/esm/dev-server/file-manager.d.mts +1 -1
  38. package/esm/dev-server/file-manager.d.mts.map +1 -1
  39. package/esm/dev-server/file-manager.mjs.map +1 -1
  40. package/esm/dev-server/files-orchestrator.mjs +16 -1
  41. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  42. package/esm/dev-server/files-watcher.mjs +13 -4
  43. package/esm/dev-server/files-watcher.mjs.map +1 -1
  44. package/esm/dev-server/loader/loader-port-acks.mjs +21 -9
  45. package/esm/dev-server/loader/loader-port-acks.mjs.map +1 -1
  46. package/esm/dev-server/loader/register-loader.mjs +31 -12
  47. package/esm/dev-server/loader/register-loader.mjs.map +1 -1
  48. package/esm/dev-server/module-loader.mjs +15 -1
  49. package/esm/dev-server/module-loader.mjs.map +1 -1
  50. package/esm/dev-server/parse-imports.mjs +1 -1
  51. package/esm/dev-server/special-file-patterns.mjs +4 -1
  52. package/esm/dev-server/special-file-patterns.mjs.map +1 -1
  53. package/esm/dev-server/type-generator.mjs +1 -1
  54. package/esm/e2e/cdp.d.mts.map +1 -1
  55. package/esm/e2e/cdp.mjs +9 -2
  56. package/esm/e2e/cdp.mjs.map +1 -1
  57. package/esm/e2e/index.d.mts +2 -2
  58. package/esm/e2e/page.d.mts +14 -1
  59. package/esm/e2e/page.d.mts.map +1 -1
  60. package/esm/e2e/page.mjs +81 -8
  61. package/esm/e2e/page.mjs.map +1 -1
  62. package/esm/e2e/types.d.mts +49 -0
  63. package/esm/e2e/types.d.mts.map +1 -1
  64. package/esm/e2e/types.mjs.map +1 -1
  65. package/esm/errors/error-codes.d.mts +72 -0
  66. package/esm/errors/error-codes.d.mts.map +1 -1
  67. package/esm/errors/error-codes.mjs +72 -0
  68. package/esm/errors/error-codes.mjs.map +1 -1
  69. package/esm/errors/index.d.mts +2 -2
  70. package/esm/errors/index.mjs +2 -2
  71. package/esm/generations/add-command.action.mjs +2 -0
  72. package/esm/generations/add-command.action.mjs.map +1 -1
  73. package/esm/generations/design-system-payload.mjs +53 -0
  74. package/esm/generations/design-system-payload.mjs.map +1 -0
  75. package/esm/generations/features/design-system.feature.mjs +38 -0
  76. package/esm/generations/features/design-system.feature.mjs.map +1 -0
  77. package/esm/generations/features/index.mjs +3 -1
  78. package/esm/generations/features/index.mjs.map +1 -1
  79. package/esm/generations/features/notifications.feature.mjs +13 -2
  80. package/esm/generations/features/notifications.feature.mjs.map +1 -1
  81. package/esm/generations/features/test.feature.mjs +48 -13
  82. package/esm/generations/features/test.feature.mjs.map +1 -1
  83. package/esm/generations/features/web.feature.mjs +3 -3
  84. package/esm/generations/features/web.feature.mjs.map +1 -1
  85. package/esm/generations/stubs.mjs +9 -5
  86. package/esm/generations/stubs.mjs.map +1 -1
  87. package/esm/http/error-mapper.d.mts +1 -1
  88. package/esm/http/error-mapper.mjs +3 -3
  89. package/esm/http/error-mapper.mjs.map +1 -1
  90. package/esm/http/error-response.d.mts +3 -0
  91. package/esm/http/error-response.d.mts.map +1 -1
  92. package/esm/http/error-response.mjs +8 -2
  93. package/esm/http/error-response.mjs.map +1 -1
  94. package/esm/http/errors/errors.d.mts +8 -0
  95. package/esm/http/errors/errors.d.mts.map +1 -1
  96. package/esm/http/errors/errors.mjs +13 -1
  97. package/esm/http/errors/errors.mjs.map +1 -1
  98. package/esm/http/index.d.mts +3 -2
  99. package/esm/http/index.mjs +3 -2
  100. package/esm/http/list-endpoint.d.mts +35 -0
  101. package/esm/http/list-endpoint.d.mts.map +1 -0
  102. package/esm/http/list-endpoint.mjs +28 -0
  103. package/esm/http/list-endpoint.mjs.map +1 -0
  104. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  105. package/esm/http/middleware/inject-request-context.mjs +12 -2
  106. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  107. package/esm/http/server.mjs +1 -1
  108. package/esm/index.d.mts +10 -6
  109. package/esm/index.mjs +5 -2
  110. package/esm/localization/index.mjs +3 -1
  111. package/esm/localization/translation-usage-graph.d.mts +49 -0
  112. package/esm/localization/translation-usage-graph.d.mts.map +1 -0
  113. package/esm/localization/translation-usage-graph.mjs +128 -0
  114. package/esm/localization/translation-usage-graph.mjs.map +1 -0
  115. package/esm/localization/translation-usage.d.mts +85 -0
  116. package/esm/localization/translation-usage.d.mts.map +1 -0
  117. package/esm/localization/translation-usage.mjs +307 -0
  118. package/esm/localization/translation-usage.mjs.map +1 -0
  119. package/esm/openapi/security.mjs +12 -4
  120. package/esm/openapi/security.mjs.map +1 -1
  121. package/esm/openapi/types.d.mts +2 -0
  122. package/esm/openapi/types.d.mts.map +1 -1
  123. package/esm/production/build-budgets.d.mts +64 -0
  124. package/esm/production/build-budgets.d.mts.map +1 -0
  125. package/esm/production/build-budgets.mjs +109 -0
  126. package/esm/production/build-budgets.mjs.map +1 -0
  127. package/esm/production/production-builder.mjs +13 -1
  128. package/esm/production/production-builder.mjs.map +1 -1
  129. package/esm/production/resolve-build-config.d.mts +1 -1
  130. package/esm/production/resolve-build-config.d.mts.map +1 -1
  131. package/esm/production/resolve-build-config.mjs.map +1 -1
  132. package/esm/production/route-registration-snapshot.mjs +5 -3
  133. package/esm/production/route-registration-snapshot.mjs.map +1 -1
  134. package/esm/restful/restful.d.mts +1 -1
  135. package/esm/router/router.d.mts +2 -0
  136. package/esm/router/router.d.mts.map +1 -1
  137. package/esm/router/router.mjs +4 -1
  138. package/esm/router/router.mjs.map +1 -1
  139. package/esm/router/types.d.mts +19 -0
  140. package/esm/router/types.d.mts.map +1 -1
  141. package/esm/tests/fakes/storage-fake.d.mts +3 -1
  142. package/esm/tests/fakes/storage-fake.d.mts.map +1 -1
  143. package/esm/tests/fakes/storage-fake.mjs +3 -3
  144. package/esm/tests/fakes/storage-fake.mjs.map +1 -1
  145. package/esm/tests/fakes/test-fakes.d.mts +3 -1
  146. package/esm/tests/fakes/test-fakes.d.mts.map +1 -1
  147. package/esm/tests/fakes/test-fakes.mjs +3 -2
  148. package/esm/tests/fakes/test-fakes.mjs.map +1 -1
  149. package/esm/tests/index.d.mts +4 -2
  150. package/esm/tests/index.mjs +3 -1
  151. package/esm/tests/load-unit-config.mjs +24 -0
  152. package/esm/tests/load-unit-config.mjs.map +1 -0
  153. package/esm/tests/response-contract.d.mts +32 -0
  154. package/esm/tests/response-contract.d.mts.map +1 -0
  155. package/esm/tests/response-contract.mjs +116 -0
  156. package/esm/tests/response-contract.mjs.map +1 -0
  157. package/esm/tests/start-http-development-server.d.mts.map +1 -1
  158. package/esm/tests/start-http-development-server.mjs +10 -2
  159. package/esm/tests/start-http-development-server.mjs.map +1 -1
  160. package/esm/tests/test-lifecycle-state.mjs.map +1 -1
  161. package/esm/tests/test-locales.mjs +33 -0
  162. package/esm/tests/test-locales.mjs.map +1 -0
  163. package/esm/tests/test-runtime-scope.d.mts +15 -0
  164. package/esm/tests/test-runtime-scope.d.mts.map +1 -0
  165. package/esm/tests/test-runtime-scope.mjs +80 -0
  166. package/esm/tests/test-runtime-scope.mjs.map +1 -0
  167. package/esm/tests/vitest-setup.d.mts +13 -3
  168. package/esm/tests/vitest-setup.d.mts.map +1 -1
  169. package/esm/tests/vitest-setup.mjs +146 -18
  170. package/esm/tests/vitest-setup.mjs.map +1 -1
  171. package/esm/tooling/check/affected-files.d.mts +5 -0
  172. package/esm/tooling/check/affected-files.d.mts.map +1 -0
  173. package/esm/tooling/check/affected-files.mjs +56 -0
  174. package/esm/tooling/check/affected-files.mjs.map +1 -0
  175. package/esm/tooling/check/api-route-references.d.mts +16 -0
  176. package/esm/tooling/check/api-route-references.d.mts.map +1 -0
  177. package/esm/tooling/check/api-route-references.mjs +146 -0
  178. package/esm/tooling/check/api-route-references.mjs.map +1 -0
  179. package/esm/tooling/check/changed-files.d.mts +2 -0
  180. package/esm/tooling/check/changed-files.d.mts.map +1 -1
  181. package/esm/tooling/check/changed-files.mjs +2 -2
  182. package/esm/tooling/check/changed-files.mjs.map +1 -1
  183. package/esm/tooling/check/conventions-step.d.mts +7 -3
  184. package/esm/tooling/check/conventions-step.d.mts.map +1 -1
  185. package/esm/tooling/check/conventions-step.mjs +59 -8
  186. package/esm/tooling/check/conventions-step.mjs.map +1 -1
  187. package/esm/tooling/check/fixes.d.mts +8 -0
  188. package/esm/tooling/check/fixes.d.mts.map +1 -0
  189. package/esm/tooling/check/fixes.mjs +31 -0
  190. package/esm/tooling/check/fixes.mjs.map +1 -0
  191. package/esm/tooling/check/index.d.mts +12 -0
  192. package/esm/tooling/check/index.mjs +3 -2
  193. package/esm/tooling/check/run-check.d.mts +2 -0
  194. package/esm/tooling/check/run-check.d.mts.map +1 -1
  195. package/esm/tooling/check/run-check.mjs +23 -5
  196. package/esm/tooling/check/run-check.mjs.map +1 -1
  197. package/esm/tooling/check/run-tests.mjs +1 -1
  198. package/esm/tooling/check/source-ast.d.mts +1 -0
  199. package/esm/tooling/check/translation-conventions.mjs +32 -0
  200. package/esm/tooling/check/translation-conventions.mjs.map +1 -0
  201. package/esm/tooling/check/web-conventions.d.mts +10 -0
  202. package/esm/tooling/check/web-conventions.d.mts.map +1 -0
  203. package/esm/tooling/check/web-conventions.mjs +126 -0
  204. package/esm/tooling/check/web-conventions.mjs.map +1 -0
  205. package/esm/tooling/index.d.mts +7 -2
  206. package/esm/tooling/index.mjs +4 -2
  207. package/esm/tooling/inspect/collect-files.mjs +172 -0
  208. package/esm/tooling/inspect/collect-files.mjs.map +1 -0
  209. package/esm/tooling/inspect/collect-pages.mjs +3 -2
  210. package/esm/tooling/inspect/collect-pages.mjs.map +1 -1
  211. package/esm/tooling/inspect/collect-routes.mjs +1 -1
  212. package/esm/tooling/inspect/collect-routes.mjs.map +1 -1
  213. package/esm/tooling/inspect/explain-file.d.mts +12 -0
  214. package/esm/tooling/inspect/explain-file.d.mts.map +1 -0
  215. package/esm/tooling/inspect/explain-file.mjs +45 -0
  216. package/esm/tooling/inspect/explain-file.mjs.map +1 -0
  217. package/esm/tooling/inspect/index.d.mts +3 -2
  218. package/esm/tooling/inspect/index.mjs +2 -1
  219. package/esm/tooling/inspect/inspect-app.d.mts.map +1 -1
  220. package/esm/tooling/inspect/inspect-app.mjs +9 -3
  221. package/esm/tooling/inspect/inspect-app.mjs.map +1 -1
  222. package/esm/tooling/inspect/inspect-report.schema.mjs +34 -1
  223. package/esm/tooling/inspect/inspect-report.schema.mjs.map +1 -1
  224. package/esm/tooling/inspect/inspect-report.types.d.mts +17 -1
  225. package/esm/tooling/inspect/inspect-report.types.d.mts.map +1 -1
  226. package/esm/tooling/inspect/inspect-report.types.mjs +2 -1
  227. package/esm/tooling/inspect/inspect-report.types.mjs.map +1 -1
  228. package/esm/tooling/mcp/mcp-tools.d.mts.map +1 -1
  229. package/esm/tooling/mcp/mcp-tools.mjs +8 -2
  230. package/esm/tooling/mcp/mcp-tools.mjs.map +1 -1
  231. package/esm/tooling/problem.d.mts +4 -0
  232. package/esm/tooling/problem.d.mts.map +1 -1
  233. package/esm/tooling/problem.mjs +1 -0
  234. package/esm/tooling/problem.mjs.map +1 -1
  235. package/esm/tooling/syntax/ast.d.mts +2 -0
  236. package/esm/tooling/typecheck/run-typecheck.mjs +5 -1
  237. package/esm/tooling/typecheck/run-typecheck.mjs.map +1 -1
  238. package/esm/upgrade/codemods/index.mjs +2 -0
  239. package/esm/upgrade/codemods/index.mjs.map +1 -1
  240. package/esm/upgrade/codemods/vite-vitest.mjs +170 -0
  241. package/esm/upgrade/codemods/vite-vitest.mjs.map +1 -0
  242. package/esm/upgrade/notes.mjs +4 -0
  243. package/esm/upgrade/notes.mjs.map +1 -1
  244. package/esm/vite/index.d.mts +3 -1
  245. package/esm/vite/index.mjs +3 -1
  246. package/esm/vite/test-setup-reporter.d.mts +16 -0
  247. package/esm/vite/test-setup-reporter.d.mts.map +1 -0
  248. package/esm/vite/test-setup-reporter.mjs +55 -0
  249. package/esm/vite/test-setup-reporter.mjs.map +1 -0
  250. package/esm/vite/test-workers.d.mts +5 -0
  251. package/esm/vite/test-workers.d.mts.map +1 -0
  252. package/esm/vite/test-workers.mjs +38 -0
  253. package/esm/vite/test-workers.mjs.map +1 -0
  254. package/esm/warlock-config/index.d.mts +2 -1
  255. package/esm/warlock-config/types.d.mts +3 -0
  256. package/esm/warlock-config/types.d.mts.map +1 -1
  257. package/llms-full.txt +874 -9
  258. package/llms.txt +2 -0
  259. package/package.json +15 -14
  260. package/schemas/inspect-report.schema.json +47 -1
  261. package/skills/build-budgets/SKILL.md +51 -0
  262. package/skills/build-restful/SKILL.md +56 -0
  263. package/skills/configure-app/SKILL.md +7 -0
  264. package/skills/create-module/SKILL.md +9 -0
  265. package/skills/generate-web-ui/SKILL.md +71 -0
  266. package/skills/index.md +2 -2
  267. package/skills/register-route/SKILL.md +13 -0
  268. package/skills/run-app/SKILL.md +1 -1
  269. package/skills/send-mail/SKILL.md +25 -0
  270. package/skills/send-response/SKILL.md +50 -0
  271. package/skills/test-browser/SKILL.md +53 -0
  272. package/skills/test-http/SKILL.md +91 -0
  273. package/skills/test-service/SKILL.md +161 -3
  274. package/skills/upgrade-from-5-29/SKILL.md +109 -0
  275. package/skills/use-localization/SKILL.md +25 -0
  276. package/skills/warlock-check/SKILL.md +75 -1
  277. package/skills/warlock-inspect/SKILL.md +45 -2
  278. package/skills/warlock-mcp/SKILL.md +4 -0
  279. package/skills/write-cli-command/SKILL.md +18 -0
  280. package/esm/production/build-app-production.mjs +0 -14
  281. package/esm/production/build-app-production.mjs.map +0 -1
@@ -3,7 +3,7 @@ import { DEFAULT_CSP_DIRECTIVES, InvalidCspDirectiveError, applyCspHeader, build
3
3
  import { HttpErrorCodes } from "./error-codes.mjs";
4
4
  import { isAllowedCsrfOrigin, normalizeOrigin, originOf, ownOrigin, resolveCsrfOriginVerdict } from "./csrf-origin-policy.mjs";
5
5
  import { requiresDefaultCsrfGuard, runDefaultCsrfGuard } from "./csrf-default-guard.mjs";
6
- import { BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./errors/errors.mjs";
6
+ import { AppError, BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./errors/errors.mjs";
7
7
  import { deriveTraceId, parseTraceparentTraceId } from "./tracing/trace-id.mjs";
8
8
  import { buildTracingContext, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled, registerTracingHooks, resetTracingConfigForTests, resolveTracingConfig } from "./tracing/tracing-dispatcher.mjs";
9
9
  import "./tracing/index.mjs";
@@ -41,5 +41,6 @@ import { notifyHttpServerRebuilt, onHttpServerRebuilt } from "./server-rebuilt.m
41
41
  import { escapeHeaderValue } from "./escape-header-value.mjs";
42
42
  import { isSafeRedirect, safeRedirect } from "./safe-redirect.mjs";
43
43
  import { requestMemo } from "./context/request-memo.mjs";
44
+ import { listEndpoint } from "./list-endpoint.mjs";
44
45
 
45
- export { BadRequestError, ConflictError, CookieJarUnavailableError, DEFAULT_CSP_DIRECTIVES, ForbiddenError, HttpError, HttpErrorCodes, ImageVariantsConfigError, InvalidCspDirectiveError, NotAcceptableError, NotAllowedError, PortInUseError, Request, RequestController, RequestLog, ResourceNotFoundError, Response, ResponseStatus, ServerError, UPLOADS_DEFAULTS, URL_CREDENTIAL_PARAMS, UnAuthorizedError, UploadedFile, anyMatch, applyCspHeader, assertConfiguredHttpPortIsFree, assertPortIsAvailable, beginHttpDrain, buildCspHeaderValue, buildIdempotencyCacheKey, buildRequestLogSnapshot, buildTracingContext, closeServerWithTimeout, createHttpApplication, createRequestStore, createUploadedFileController, defaultHttpConfigurations, deriveTraceId, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, escapeHeaderValue, evaluateConditionalRequest, generateImageVariants, getHttpReadyReport, getHttpServer, hashBody, health, httpConfig, ipMatches, isAllowedCsrfOrigin, isPortAvailable, isSafeRedirect, isTracingEnabled, isValidIdempotencyKey, logResponse, matchesIfMatch, matchesIfNoneMatch, mergeCspDirectives, middleware, normalizeOrigin, notifyHttpServerRebuilt, onHttpServerRebuilt, originOf, ownOrigin, parseEntityTag, parseEntityTagList, parseSize, parseTraceparentTraceId, preflightConfiguredHttpPort, purgeImageVariants, redactQueryCredentials, redactUrlCredentials, registerHttpPlugins, registerTracingHooks, remedyLines, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetTracingConfigForTests, resolveCspConfig, resolveCsrfOriginVerdict, resolveImageVariant, resolvePublicRoot, resolveRequestLoggingOptions, resolveTracingConfig, runDefaultCsrfGuard, safeRedirect, serializeCspDirectives, setHttpReadyReport, shouldPreflightHttpPort, startHttpServer, stopHttpApplication, streamReactResponse, strongEntityTagMatch, t, toSingleLineSseField, trackConnectionsForDrain, uploadedFileController, uploadsConfig, useCurrentUser, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, weakEntityTagMatch, wrapResponseInDataKey };
46
+ export { AppError, BadRequestError, ConflictError, CookieJarUnavailableError, DEFAULT_CSP_DIRECTIVES, ForbiddenError, HttpError, HttpErrorCodes, ImageVariantsConfigError, InvalidCspDirectiveError, NotAcceptableError, NotAllowedError, PortInUseError, Request, RequestController, RequestLog, ResourceNotFoundError, Response, ResponseStatus, ServerError, UPLOADS_DEFAULTS, URL_CREDENTIAL_PARAMS, UnAuthorizedError, UploadedFile, anyMatch, applyCspHeader, assertConfiguredHttpPortIsFree, assertPortIsAvailable, beginHttpDrain, buildCspHeaderValue, buildIdempotencyCacheKey, buildRequestLogSnapshot, buildTracingContext, closeServerWithTimeout, createHttpApplication, createRequestStore, createUploadedFileController, defaultHttpConfigurations, deriveTraceId, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, escapeHeaderValue, evaluateConditionalRequest, generateImageVariants, getHttpReadyReport, getHttpServer, hashBody, health, httpConfig, ipMatches, isAllowedCsrfOrigin, isPortAvailable, isSafeRedirect, isTracingEnabled, isValidIdempotencyKey, listEndpoint, logResponse, matchesIfMatch, matchesIfNoneMatch, mergeCspDirectives, middleware, normalizeOrigin, notifyHttpServerRebuilt, onHttpServerRebuilt, originOf, ownOrigin, parseEntityTag, parseEntityTagList, parseSize, parseTraceparentTraceId, preflightConfiguredHttpPort, purgeImageVariants, redactQueryCredentials, redactUrlCredentials, registerHttpPlugins, registerTracingHooks, remedyLines, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetTracingConfigForTests, resolveCspConfig, resolveCsrfOriginVerdict, resolveImageVariant, resolvePublicRoot, resolveRequestLoggingOptions, resolveTracingConfig, runDefaultCsrfGuard, safeRedirect, serializeCspDirectives, setHttpReadyReport, shouldPreflightHttpPort, startHttpServer, stopHttpApplication, streamReactResponse, strongEntityTagMatch, t, toSingleLineSseField, trackConnectionsForDrain, uploadedFileController, uploadsConfig, useCurrentUser, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, weakEntityTagMatch, wrapResponseInDataKey };
@@ -0,0 +1,35 @@
1
+ import { Request } from "./request.mjs";
2
+ import { PaginationResult, RepositoryOptions } from "../repositories/contracts/types.mjs";
3
+ import "../repositories/contracts/index.mjs";
4
+ //#region ../../packages/core/src/http/list-endpoint.d.ts
5
+ export type ListQuery = {
6
+ page?: number;
7
+ limit?: number;
8
+ orderBy?: string;
9
+ orderDir?: "asc" | "desc";
10
+ };
11
+ export type ListEndpointOptions<Key extends string, Query extends ListQuery> = {
12
+ pluralKey: Key & (Key extends "pagination" ? never : unknown);
13
+ /** Indexed columns clients may sort on. */
14
+ orderBy: readonly string[];
15
+ /** Only these validated query fields reach repository filters. */
16
+ filters?: readonly Exclude<keyof Query & string, keyof ListQuery>[];
17
+ defaultLimit?: number;
18
+ maxLimit?: number;
19
+ };
20
+ export type ListEndpointRepositoryOptions<Query extends ListQuery> = RepositoryOptions & Partial<Omit<Query, keyof ListQuery>> & {
21
+ page: number;
22
+ limit: number;
23
+ paginate: true;
24
+ paginationMode: "pages";
25
+ };
26
+ export type ListEndpointBody<Key extends string, Item> = Record<Key, Item[]> & {
27
+ pagination: PaginationResult<Item>["pagination"];
28
+ };
29
+ /** Build a bounded, page-based list body from validated query values only. */
30
+ export declare function listEndpoint<Key extends string, Query extends ListQuery, Item>(request: Request<Query>, list: (options: ListEndpointRepositoryOptions<Query>) => Promise<PaginationResult<Item>>, options: ListEndpointOptions<Key, Query>): Promise<ListEndpointBody<Key, Item>>;
31
+ export declare function listEndpoint<Key extends string, Query extends ListQuery, Item>(request: {
32
+ validated(): Query;
33
+ }, list: (options: ListEndpointRepositoryOptions<Query>) => Promise<PaginationResult<Item>>, options: ListEndpointOptions<Key, Query>): Promise<ListEndpointBody<Key, Item>>;
34
+ //#endregion
35
+ //# sourceMappingURL=list-endpoint.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"list-endpoint.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/http/list-endpoint.ts"],"mappings":";;;;YAIY;EACV;EACA;EACA;EACA;;YAGU,oBAAoB,oBAAoB,cAAc;EAChE,WAAW,OAAO;;EAElB;;EAEA,mBAAmB,cAAc,sBAAsB;EACvD;EACA;;YAGU,8BAA8B,cAAc,aAAa,oBACnE,QAAQ,KAAK,aAAa;EACxB;EACA;EACA;EACA;;YAGQ,iBAAiB,oBAAoB,QAAQ,OAAO,KAAK;EACnE,YAAY,iBAAiB;;;wBAIf,aAAa,oBAAoB,cAAc,WAAW,MACxE,SAAS,QAAQ,QACjB,OAAO,SAAS,8BAA8B,WAAW,QAAQ,iBAAiB,QAClF,SAAS,oBAAoB,KAAK,SACjC,QAAQ,iBAAiB,KAAK;wBACjB,aAAa,oBAAoB,cAAc,WAAW,MACxE;EAAW,aAAa;GACxB,OAAO,SAAS,8BAA8B,WAAW,QAAQ,iBAAiB,QAClF,SAAS,oBAAoB,KAAK,SACjC,QAAQ,iBAAiB,KAAK"}
@@ -0,0 +1,28 @@
1
+ import { AppError } from "./errors/errors.mjs";
2
+
3
+ //#region ../../packages/core/src/http/list-endpoint.ts
4
+ async function listEndpoint(request, list, options) {
5
+ const maxLimit = options.maxLimit ?? 100;
6
+ const defaultLimit = options.defaultLimit ?? 20;
7
+ if (!Number.isSafeInteger(maxLimit) || maxLimit < 1 || !Number.isSafeInteger(defaultLimit) || defaultLimit < 1 || options.pluralKey === "pagination" || !options.pluralKey) throw new TypeError("Invalid listEndpoint configuration.");
8
+ const query = request.validated();
9
+ const page = query.page ?? 1;
10
+ const requestedLimit = query.limit ?? defaultLimit;
11
+ if (!Number.isSafeInteger(page) || page < 1 || !Number.isSafeInteger(requestedLimit) || requestedLimit < 1 || query.orderBy !== void 0 && !options.orderBy.includes(query.orderBy) || query.orderDir !== void 0 && query.orderDir !== "asc" && query.orderDir !== "desc") throw new AppError("invalidListQuery", 422, "Invalid list query.");
12
+ const result = await list({
13
+ ...Object.fromEntries((options.filters ?? []).filter((key) => query[key] !== void 0).map((key) => [key, query[key]])),
14
+ page,
15
+ limit: Math.min(requestedLimit, maxLimit),
16
+ paginate: true,
17
+ paginationMode: "pages",
18
+ ...query.orderBy === void 0 ? {} : { orderBy: [query.orderBy, query.orderDir ?? "asc"] }
19
+ });
20
+ return {
21
+ [options.pluralKey]: result.data,
22
+ pagination: result.pagination
23
+ };
24
+ }
25
+
26
+ //#endregion
27
+ export { listEndpoint };
28
+ //# sourceMappingURL=list-endpoint.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"list-endpoint.mjs","names":[],"sources":["../../../../../../../../packages/core/src/http/list-endpoint.ts"],"sourcesContent":["import type { PaginationResult, RepositoryOptions } from \"../repositories/contracts\";\nimport type { Request } from \"./request\";\nimport { AppError } from \"./errors\";\n\nexport type ListQuery = {\n page?: number;\n limit?: number;\n orderBy?: string;\n orderDir?: \"asc\" | \"desc\";\n};\n\nexport type ListEndpointOptions<Key extends string, Query extends ListQuery> = {\n pluralKey: Key & (Key extends \"pagination\" ? never : unknown);\n /** Indexed columns clients may sort on. */\n orderBy: readonly string[];\n /** Only these validated query fields reach repository filters. */\n filters?: readonly Exclude<keyof Query & string, keyof ListQuery>[];\n defaultLimit?: number;\n maxLimit?: number;\n};\n\nexport type ListEndpointRepositoryOptions<Query extends ListQuery> = RepositoryOptions &\n Partial<Omit<Query, keyof ListQuery>> & {\n page: number;\n limit: number;\n paginate: true;\n paginationMode: \"pages\";\n };\n\nexport type ListEndpointBody<Key extends string, Item> = Record<Key, Item[]> & {\n pagination: PaginationResult<Item>[\"pagination\"];\n};\n\n/** Build a bounded, page-based list body from validated query values only. */\nexport function listEndpoint<Key extends string, Query extends ListQuery, Item>(\n request: Request<Query>,\n list: (options: ListEndpointRepositoryOptions<Query>) => Promise<PaginationResult<Item>>,\n options: ListEndpointOptions<Key, Query>,\n): Promise<ListEndpointBody<Key, Item>>;\nexport function listEndpoint<Key extends string, Query extends ListQuery, Item>(\n request: { validated(): Query },\n list: (options: ListEndpointRepositoryOptions<Query>) => Promise<PaginationResult<Item>>,\n options: ListEndpointOptions<Key, Query>,\n): Promise<ListEndpointBody<Key, Item>>;\nexport async function listEndpoint<Key extends string, Query extends ListQuery, Item>(\n request: { validated(): Query },\n list: (options: ListEndpointRepositoryOptions<Query>) => Promise<PaginationResult<Item>>,\n options: ListEndpointOptions<Key, Query>,\n): Promise<ListEndpointBody<Key, Item>> {\n const maxLimit = options.maxLimit ?? 100;\n const defaultLimit = options.defaultLimit ?? 20;\n if (\n !Number.isSafeInteger(maxLimit) ||\n maxLimit < 1 ||\n !Number.isSafeInteger(defaultLimit) ||\n defaultLimit < 1 ||\n options.pluralKey === \"pagination\" ||\n !options.pluralKey\n ) {\n throw new TypeError(\"Invalid listEndpoint configuration.\");\n }\n const query = request.validated();\n const page = query.page ?? 1;\n const requestedLimit = query.limit ?? defaultLimit;\n if (\n !Number.isSafeInteger(page) ||\n page < 1 ||\n !Number.isSafeInteger(requestedLimit) ||\n requestedLimit < 1 ||\n (query.orderBy !== undefined && !options.orderBy.includes(query.orderBy)) ||\n (query.orderDir !== undefined && query.orderDir !== \"asc\" && query.orderDir !== \"desc\")\n ) {\n throw new AppError(\"invalidListQuery\", 422, \"Invalid list query.\");\n }\n const filters = Object.fromEntries(\n (options.filters ?? [])\n .filter((key) => query[key] !== undefined)\n .map((key) => [key, query[key]]),\n ) as Partial<Omit<Query, keyof ListQuery>>;\n const result = await list({\n ...filters,\n page,\n limit: Math.min(requestedLimit, maxLimit),\n paginate: true,\n paginationMode: \"pages\",\n ...(query.orderBy === undefined\n ? {}\n : {\n orderBy: [query.orderBy, query.orderDir ?? \"asc\"] as [string, \"asc\" | \"desc\"],\n }),\n });\n return { [options.pluralKey]: result.data, pagination: result.pagination } as Record<\n Key,\n Item[]\n > & { pagination: PaginationResult<Item>[\"pagination\"] };\n}\n"],"mappings":";;;AA4CA,eAAsB,aACpB,SACA,MACA,SACsC;CACtC,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,eAAe,QAAQ,gBAAgB;CAC7C,IACE,CAAC,OAAO,cAAc,QAAQ,KAC9B,WAAW,KACX,CAAC,OAAO,cAAc,YAAY,KAClC,eAAe,KACf,QAAQ,cAAc,gBACtB,CAAC,QAAQ,WAET,MAAM,IAAI,UAAU,qCAAqC;CAE3D,MAAM,QAAQ,QAAQ,UAAU;CAChC,MAAM,OAAO,MAAM,QAAQ;CAC3B,MAAM,iBAAiB,MAAM,SAAS;CACtC,IACE,CAAC,OAAO,cAAc,IAAI,KAC1B,OAAO,KACP,CAAC,OAAO,cAAc,cAAc,KACpC,iBAAiB,KAChB,MAAM,YAAY,UAAa,CAAC,QAAQ,QAAQ,SAAS,MAAM,OAAO,KACtE,MAAM,aAAa,UAAa,MAAM,aAAa,SAAS,MAAM,aAAa,QAEhF,MAAM,IAAI,SAAS,oBAAoB,KAAK,qBAAqB;CAOnE,MAAM,SAAS,MAAM,KAAK;EACxB,GANc,OAAO,aACpB,QAAQ,WAAW,CAAC,EAAC,CACnB,QAAQ,QAAQ,MAAM,SAAS,MAAS,CAAC,CACzC,KAAK,QAAQ,CAAC,KAAK,MAAM,IAAI,CAAC,CAGxB;EACT;EACA,OAAO,KAAK,IAAI,gBAAgB,QAAQ;EACxC,UAAU;EACV,gBAAgB;EAChB,GAAI,MAAM,YAAY,SAClB,CAAC,IACD,EACE,SAAS,CAAC,MAAM,SAAS,MAAM,YAAY,KAAK,EAClD;CACN,CAAC;CACD,OAAO;GAAG,QAAQ,YAAY,OAAO;EAAM,YAAY,OAAO;CAAW;AAI3E"}
@@ -1 +1 @@
1
- {"version":3,"file":"inject-request-context.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/http/middleware/inject-request-context.ts"],"mappings":";;;;;;;;;wBA+CgB,mBACd,SAAS,cACT,UAAU,WACT,QAAQ;;;;wBAuNK,EAAE,iBAAiB,eAAe"}
1
+ {"version":3,"file":"inject-request-context.d.mts","names":[],"sources":["../../../../../../../../../packages/core/src/http/middleware/inject-request-context.ts"],"mappings":";;;;;;;;;wBAgDgB,mBACd,SAAS,cACT,UAAU,WACT,QAAQ;;;;wBAqOK,EAAE,iBAAiB,eAAe"}
@@ -3,7 +3,8 @@ import { requestContext } from "../context/request-context.mjs";
3
3
  import "../../utils/index.mjs";
4
4
  import { applyCspHeader } from "../csp.mjs";
5
5
  import { runDefaultCsrfGuard } from "../csrf-default-guard.mjs";
6
- import { HttpError } from "../errors/errors.mjs";
6
+ import { setResponseAppError } from "../error-response.mjs";
7
+ import { AppError, HttpError } from "../errors/errors.mjs";
7
8
  import { mapRequestError } from "../error-mapper.mjs";
8
9
  import { buildTracingContext, dispatchPhase, isTracingEnabled } from "../tracing/tracing-dispatcher.mjs";
9
10
  import "../tracing/index.mjs";
@@ -85,7 +86,7 @@ function createRequestStore(request, response) {
85
86
  * @internal
86
87
  */
87
88
  function resolveRequestErrorStatus(error) {
88
- if (error instanceof HttpError) return error.status;
89
+ if (error instanceof HttpError || error instanceof AppError) return error.status;
89
90
  if (error instanceof DatabaseWriterValidationError) return baseConfig.get("http.modelValidationErrorStatus", 500);
90
91
  }
91
92
  /**
@@ -118,6 +119,15 @@ function reportUnhandledRequestError(error, request) {
118
119
  */
119
120
  function handleRequestError(error, response, request) {
120
121
  response.header("Cache-Control", "private, no-store");
122
+ if (error instanceof AppError) {
123
+ if (error.status >= 500) log.error("http", "request-error", error, { requestId: request.id });
124
+ setResponseAppError(response.baseResponse, error);
125
+ return response.setStatusCode(error.status).send({ error: {
126
+ code: error.code,
127
+ message: error.publicMessage,
128
+ ...error.details === void 0 ? {} : { details: error.details }
129
+ } });
130
+ }
121
131
  if (error instanceof HttpError) {
122
132
  if (error.status >= 500) log.error("http", "request-error", error, { requestId: request.id });
123
133
  const payload = { error: error.message };
@@ -1 +1 @@
1
- {"version":3,"file":"inject-request-context.mjs","names":["config","requestContextInstance"],"sources":["../../../../../../../../../packages/core/src/http/middleware/inject-request-context.ts"],"sourcesContent":["/**\n * Request Context Middleware\n *\n * Creates a unified context for each request using the ContextManager.\n * All framework contexts (request, storage, database) are available throughout the request lifecycle.\n */\nimport { trans } from \"@mongez/localization\";\nimport { type GenericObject } from \"@mongez/reinforcements\";\nimport { DatabaseWriterValidationError } from \"@warlock.js/cascade\";\nimport { contextManager } from \"@warlock.js/context\";\nimport { log } from \"@warlock.js/logger\";\nimport config from \"@mongez/config\";\nimport { environment } from \"../../utils\";\nimport { requestContext as requestContextInstance } from \"../context/request-context\";\nimport { applyCspHeader } from \"../csp\";\nimport { runDefaultCsrfGuard } from \"../csrf-default-guard\";\nimport { mapRequestError } from \"../error-mapper\";\nimport { HttpError } from \"../errors\";\nimport { type Request } from \"../request\";\nimport { type Response } from \"../response\";\nimport { buildTracingContext, dispatchPhase, isTracingEnabled } from \"../tracing\";\nimport { type ReturnedResponse } from \"./../types\";\n\n// Contexts are now registered in core/context/init-contexts.ts via initializeContexts()\n\n/**\n * Echo `request.id` back as a response header so the FE / proxies / log\n * aggregators can correlate by the same value the server logs against.\n *\n * Reads the header name from `http.requestId.header` (default `X-Request-Id`).\n * Skip when `http.requestId.enabled` is explicitly false.\n */\nfunction stampRequestIdHeader(request: Request, response: Response) {\n const requestIdConfig = config.get(\"http.requestId\", {} as Record<string, any>);\n\n if (requestIdConfig.enabled === false) return;\n\n const headerName = requestIdConfig.header || \"X-Request-Id\";\n\n response.header(headerName, request.id);\n}\n\n/**\n * Create request store and execute middleware + handler\n *\n * Runs all registered contexts together using ContextManager.\n */\nexport function createRequestStore(\n request: Request<any>,\n response: Response,\n): Promise<ReturnedResponse> {\n stampRequestIdHeader(request, response);\n\n // Stamped this early — before any middleware or handler runs — so the\n // header carries the SAME nonce the web layer later reads off\n // `request.nonce` for its `<script>` tags: `request.nonce` caches on first\n // read, and this is deliberately the first read. A no-op when the app\n // hasn't opted into `http.csp` (see `csp.ts`).\n applyCspHeader(request, response);\n\n // Build all context stores using the immutable API\n // Each context defines its own store initialization via buildStore()\n const httpContextStore = contextManager.buildStores({ request, response });\n\n // Run all contexts together!\n return contextManager.runAll(httpContextStore, async () => {\n try {\n // Default CSRF-Origin guard (SECURITY, card 8a752ab2) — the earliest\n // seam common to every request, BEFORE the route's own middleware\n // (`request.runMiddleware()` below) and before any app handler, so it\n // applies even to a route that never attaches\n // `authMiddleware(\"cookie:*\")`. See `../csrf-default-guard.ts` for the\n // full scope rule and `{ csrf: false }` exemption.\n const csrfGuardResponse = await runDefaultCsrfGuard(request, response, t, (reason) => {\n log.error(\n \"http\",\n \"csrf-default-guard\",\n new Error(`Default CSRF Origin guard refused request: ${reason}`),\n );\n });\n\n if (csrfGuardResponse) {\n return csrfGuardResponse as ReturnedResponse;\n }\n\n // Run middleware chain\n const result = await request.runMiddleware();\n\n if (result) {\n return result as ReturnedResponse;\n }\n\n // Execute route handler\n request.trigger(\"executingAction\", request.route);\n\n const handler = request.getHandler();\n\n request.log(\"Executing Handler\", \"info\");\n\n const tracingEnabled = isTracingEnabled();\n const handlerStartedAt = tracingEnabled ? performance.now() : 0;\n\n const output = await handler({ request, response });\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(request), {\n name: \"handler\",\n durationMs: performance.now() - handlerStartedAt,\n });\n }\n\n request.log(\"Handler Executed Successfully\", \"success\");\n\n request.trigger(\"executedAction\", request.route);\n\n return output as ReturnedResponse;\n } catch (thrown) {\n const error = mapRequestError(thrown, request);\n\n logRequestError(error, request);\n return handleRequestError(error, response, request);\n }\n });\n}\n\n/**\n * The HTTP status an error will be answered with, or `undefined` when it is not\n * one of the known HTTP-answerable shapes (those fall through to the opaque 500).\n *\n * Single source for `handleRequestError` and the request logger, so the rule\n * that decides the response status is the same rule that decides the log level.\n * @internal\n */\nfunction resolveRequestErrorStatus(error: unknown): number | undefined {\n if (error instanceof HttpError) {\n return error.status;\n }\n\n if (error instanceof DatabaseWriterValidationError) {\n return config.get(\"http.modelValidationErrorStatus\", 500);\n }\n\n return undefined;\n}\n\n/**\n * Log a request error at the right severity. An error answered with a 4xx is an\n * expected client error (a thrown 404/409/422): one `warn` line, no stack.\n * Everything else (5xx, unknown errors) keeps the error-level entry with its stack.\n * @internal\n */\nfunction logRequestError(error: unknown, request: Request<any>) {\n const status = resolveRequestErrorStatus(error);\n\n if (status !== undefined && status < 500 && error instanceof Error) {\n request.log(`${error.name}: ${error.message} (${status})`, \"warn\");\n\n return;\n }\n\n request.log(error, \"error\");\n}\n\n/**\n * Unconditional floor for an unhandled request error (canon 8d3c13a8): route it\n * through the logger, and when no logger channel is configured (nothing would\n * record it) fall back to `console.error` so the only copy is never lost.\n * @internal\n */\nfunction reportUnhandledRequestError(error: unknown, request: Request<any>) {\n log.error(\"http\", \"unhandled-request-error\", error, { requestId: request.id });\n\n if (log.channels.length === 0) {\n console.error(`[http] unhandled-request-error (requestId: ${request.id})`, error);\n }\n}\n\n/**\n * Handle request errors\n * @internal\n */\nfunction handleRequestError(\n error: unknown,\n response: Response,\n request: Request<any>,\n): ReturnedResponse {\n // Availability floor, not a cache-policy nit: `handleRequestError` is the\n // single funnel every unhandled error in every Warlock app passes through\n // (`createRequestStore`'s catch above), and none of the branches below set\n // a `Cache-Control` header. Without this, an error response — a 500 as\n // much as a 401/403/404 carrying per-request/-user state — can be stored\n // by a shared cache or CDN and replayed to other requests/users long after\n // the condition that caused it is gone: a cached 500 becomes an outage\n // that outlives its cause; a cached 401/403 becomes a leak across users.\n // Set once, here, before any branch runs — not per branch — because the\n // branches below do not partition by status. `ResourceNotFoundError`,\n // `UnAuthorizedError`, `ForbiddenError`, `BadRequestError` and `ServerError`\n // all extend `HttpError`, so the `HttpError` branch answers for every one of\n // them, and a raw `HttpError` can carry any caller-chosen status, 4xx or 5xx.\n // Gating the floor on the eventual status would mean re-deriving that status\n // per branch — one rule meeting one form while others reach the same output.\n // Applying it once, unconditionally, is both simpler and safer.\n response.header(\"Cache-Control\", \"private, no-store\");\n\n if (error instanceof HttpError) {\n // 5xx HttpErrors (e.g. `ServerError`) are server faults: send them to the\n // logger channels too, tagged with the request id.\n if (error.status >= 500) {\n log.error(\"http\", \"request-error\", error, { requestId: request.id });\n }\n\n const payload: GenericObject = {\n error: error.message,\n };\n if (error.payload) {\n payload.payload = error.payload;\n }\n\n if (environment() === \"development\") {\n payload.stack = error.stack;\n }\n\n return response.setStatusCode(error.status).send(payload);\n }\n\n if (error instanceof DatabaseWriterValidationError) {\n const status = resolveRequestErrorStatus(error) as number;\n\n // A 4xx is an expected client error, already logged as a one-line warn by\n // `logRequestError`; only a 5xx gets the error-level entry with its stack.\n if (status >= 500) {\n log.error(\"http\", \"model-write-validation-error\", error, {\n requestId: request.id,\n errors: error.errors,\n });\n }\n\n // A 4xx status means the app treats this as the client's fault, so the\n // field errors are useful to it; a 5xx stays opaque.\n if (status < 500) {\n return response.setStatusCode(status).send({\n errors: error.errors,\n });\n }\n\n return response.setStatusCode(status).send({\n error: \"Internal server error.\",\n });\n }\n\n // Last resort: the error matched none of the known shapes above, so the\n // client gets a deliberately opaque message. Without this line the error\n // itself is discarded here — no stack, no message, nothing in any log — and\n // an unrecognised failure becomes indistinguishable from a working server\n // returning 500. Never swallow the only copy of an error (`65e476ee`).\n reportUnhandledRequestError(error, request);\n\n return response.serverError({\n error: \"Internal server error.\",\n });\n}\n\n/**\n * Translate a keyword (uses request context for locale)\n */\nexport function t(keyword: string, placeholders?: Record<string, unknown>): string {\n return (\n requestContextInstance.getRequest()?.trans(keyword, placeholders) ||\n trans(keyword, placeholders)\n );\n}\n\n// `fromRequest` was removed in v5. It cached computed values as dynamic\n// properties on the Request instance, which only compiled because of the\n// `[key: string]: any` index signature that v5 deletes (eed20184). Use\n// `requestMemo(key, fn)` from `../context/request-memo` instead — same\n// per-request lifetime, single-flight, and it never touches the Request object.\n"],"mappings":"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"}
1
+ {"version":3,"file":"inject-request-context.mjs","names":["config","requestContextInstance"],"sources":["../../../../../../../../../packages/core/src/http/middleware/inject-request-context.ts"],"sourcesContent":["/**\n * Request Context Middleware\n *\n * Creates a unified context for each request using the ContextManager.\n * All framework contexts (request, storage, database) are available throughout the request lifecycle.\n */\nimport { trans } from \"@mongez/localization\";\nimport { type GenericObject } from \"@mongez/reinforcements\";\nimport { DatabaseWriterValidationError } from \"@warlock.js/cascade\";\nimport { contextManager } from \"@warlock.js/context\";\nimport { log } from \"@warlock.js/logger\";\nimport config from \"@mongez/config\";\nimport { environment } from \"../../utils\";\nimport { requestContext as requestContextInstance } from \"../context/request-context\";\nimport { applyCspHeader } from \"../csp\";\nimport { runDefaultCsrfGuard } from \"../csrf-default-guard\";\nimport { setResponseAppError } from \"../error-response\";\nimport { mapRequestError } from \"../error-mapper\";\nimport { AppError, HttpError } from \"../errors\";\nimport { type Request } from \"../request\";\nimport { type Response } from \"../response\";\nimport { buildTracingContext, dispatchPhase, isTracingEnabled } from \"../tracing\";\nimport { type ReturnedResponse } from \"./../types\";\n\n// Contexts are now registered in core/context/init-contexts.ts via initializeContexts()\n\n/**\n * Echo `request.id` back as a response header so the FE / proxies / log\n * aggregators can correlate by the same value the server logs against.\n *\n * Reads the header name from `http.requestId.header` (default `X-Request-Id`).\n * Skip when `http.requestId.enabled` is explicitly false.\n */\nfunction stampRequestIdHeader(request: Request, response: Response) {\n const requestIdConfig = config.get(\"http.requestId\", {} as Record<string, any>);\n\n if (requestIdConfig.enabled === false) return;\n\n const headerName = requestIdConfig.header || \"X-Request-Id\";\n\n response.header(headerName, request.id);\n}\n\n/**\n * Create request store and execute middleware + handler\n *\n * Runs all registered contexts together using ContextManager.\n */\nexport function createRequestStore(\n request: Request<any>,\n response: Response,\n): Promise<ReturnedResponse> {\n stampRequestIdHeader(request, response);\n\n // Stamped this early — before any middleware or handler runs — so the\n // header carries the SAME nonce the web layer later reads off\n // `request.nonce` for its `<script>` tags: `request.nonce` caches on first\n // read, and this is deliberately the first read. A no-op when the app\n // hasn't opted into `http.csp` (see `csp.ts`).\n applyCspHeader(request, response);\n\n // Build all context stores using the immutable API\n // Each context defines its own store initialization via buildStore()\n const httpContextStore = contextManager.buildStores({ request, response });\n\n // Run all contexts together!\n return contextManager.runAll(httpContextStore, async () => {\n try {\n // Default CSRF-Origin guard (SECURITY, card 8a752ab2) — the earliest\n // seam common to every request, BEFORE the route's own middleware\n // (`request.runMiddleware()` below) and before any app handler, so it\n // applies even to a route that never attaches\n // `authMiddleware(\"cookie:*\")`. See `../csrf-default-guard.ts` for the\n // full scope rule and `{ csrf: false }` exemption.\n const csrfGuardResponse = await runDefaultCsrfGuard(request, response, t, (reason) => {\n log.error(\n \"http\",\n \"csrf-default-guard\",\n new Error(`Default CSRF Origin guard refused request: ${reason}`),\n );\n });\n\n if (csrfGuardResponse) {\n return csrfGuardResponse as ReturnedResponse;\n }\n\n // Run middleware chain\n const result = await request.runMiddleware();\n\n if (result) {\n return result as ReturnedResponse;\n }\n\n // Execute route handler\n request.trigger(\"executingAction\", request.route);\n\n const handler = request.getHandler();\n\n request.log(\"Executing Handler\", \"info\");\n\n const tracingEnabled = isTracingEnabled();\n const handlerStartedAt = tracingEnabled ? performance.now() : 0;\n\n const output = await handler({ request, response });\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(request), {\n name: \"handler\",\n durationMs: performance.now() - handlerStartedAt,\n });\n }\n\n request.log(\"Handler Executed Successfully\", \"success\");\n\n request.trigger(\"executedAction\", request.route);\n\n return output as ReturnedResponse;\n } catch (thrown) {\n const error = mapRequestError(thrown, request);\n\n logRequestError(error, request);\n return handleRequestError(error, response, request);\n }\n });\n}\n\n/**\n * The HTTP status an error will be answered with, or `undefined` when it is not\n * one of the known HTTP-answerable shapes (those fall through to the opaque 500).\n *\n * Single source for `handleRequestError` and the request logger, so the rule\n * that decides the response status is the same rule that decides the log level.\n * @internal\n */\nfunction resolveRequestErrorStatus(error: unknown): number | undefined {\n if (error instanceof HttpError || error instanceof AppError) {\n return error.status;\n }\n\n if (error instanceof DatabaseWriterValidationError) {\n return config.get(\"http.modelValidationErrorStatus\", 500);\n }\n\n return undefined;\n}\n\n/**\n * Log a request error at the right severity. An error answered with a 4xx is an\n * expected client error (a thrown 404/409/422): one `warn` line, no stack.\n * Everything else (5xx, unknown errors) keeps the error-level entry with its stack.\n * @internal\n */\nfunction logRequestError(error: unknown, request: Request<any>) {\n const status = resolveRequestErrorStatus(error);\n\n if (status !== undefined && status < 500 && error instanceof Error) {\n request.log(`${error.name}: ${error.message} (${status})`, \"warn\");\n\n return;\n }\n\n request.log(error, \"error\");\n}\n\n/**\n * Unconditional floor for an unhandled request error (canon 8d3c13a8): route it\n * through the logger, and when no logger channel is configured (nothing would\n * record it) fall back to `console.error` so the only copy is never lost.\n * @internal\n */\nfunction reportUnhandledRequestError(error: unknown, request: Request<any>) {\n log.error(\"http\", \"unhandled-request-error\", error, { requestId: request.id });\n\n if (log.channels.length === 0) {\n console.error(`[http] unhandled-request-error (requestId: ${request.id})`, error);\n }\n}\n\n/**\n * Handle request errors\n * @internal\n */\nfunction handleRequestError(\n error: unknown,\n response: Response,\n request: Request<any>,\n): ReturnedResponse {\n // Availability floor, not a cache-policy nit: `handleRequestError` is the\n // single funnel every unhandled error in every Warlock app passes through\n // (`createRequestStore`'s catch above), and none of the branches below set\n // a `Cache-Control` header. Without this, an error response — a 500 as\n // much as a 401/403/404 carrying per-request/-user state — can be stored\n // by a shared cache or CDN and replayed to other requests/users long after\n // the condition that caused it is gone: a cached 500 becomes an outage\n // that outlives its cause; a cached 401/403 becomes a leak across users.\n // Set once, here, before any branch runs — not per branch — because the\n // branches below do not partition by status. `ResourceNotFoundError`,\n // `UnAuthorizedError`, `ForbiddenError`, `BadRequestError` and `ServerError`\n // all extend `HttpError`, so the `HttpError` branch answers for every one of\n // them, and a raw `HttpError` can carry any caller-chosen status, 4xx or 5xx.\n // Gating the floor on the eventual status would mean re-deriving that status\n // per branch — one rule meeting one form while others reach the same output.\n // Applying it once, unconditionally, is both simpler and safer.\n response.header(\"Cache-Control\", \"private, no-store\");\n\n if (error instanceof AppError) {\n if (error.status >= 500) {\n log.error(\"http\", \"request-error\", error, { requestId: request.id });\n }\n setResponseAppError(response.baseResponse, error);\n return response.setStatusCode(error.status).send({\n error: {\n code: error.code,\n message: error.publicMessage,\n ...(error.details === undefined ? {} : { details: error.details }),\n },\n });\n }\n\n if (error instanceof HttpError) {\n // 5xx HttpErrors (e.g. `ServerError`) are server faults: send them to the\n // logger channels too, tagged with the request id.\n if (error.status >= 500) {\n log.error(\"http\", \"request-error\", error, { requestId: request.id });\n }\n\n const payload: GenericObject = {\n error: error.message,\n };\n if (error.payload) {\n payload.payload = error.payload;\n }\n\n if (environment() === \"development\") {\n payload.stack = error.stack;\n }\n\n return response.setStatusCode(error.status).send(payload);\n }\n\n if (error instanceof DatabaseWriterValidationError) {\n const status = resolveRequestErrorStatus(error) as number;\n\n // A 4xx is an expected client error, already logged as a one-line warn by\n // `logRequestError`; only a 5xx gets the error-level entry with its stack.\n if (status >= 500) {\n log.error(\"http\", \"model-write-validation-error\", error, {\n requestId: request.id,\n errors: error.errors,\n });\n }\n\n // A 4xx status means the app treats this as the client's fault, so the\n // field errors are useful to it; a 5xx stays opaque.\n if (status < 500) {\n return response.setStatusCode(status).send({\n errors: error.errors,\n });\n }\n\n return response.setStatusCode(status).send({\n error: \"Internal server error.\",\n });\n }\n\n // Last resort: the error matched none of the known shapes above, so the\n // client gets a deliberately opaque message. Without this line the error\n // itself is discarded here — no stack, no message, nothing in any log — and\n // an unrecognised failure becomes indistinguishable from a working server\n // returning 500. Never swallow the only copy of an error (`65e476ee`).\n reportUnhandledRequestError(error, request);\n\n return response.serverError({\n error: \"Internal server error.\",\n });\n}\n\n/**\n * Translate a keyword (uses request context for locale)\n */\nexport function t(keyword: string, placeholders?: Record<string, unknown>): string {\n return (\n requestContextInstance.getRequest()?.trans(keyword, placeholders) ||\n trans(keyword, placeholders)\n );\n}\n\n// `fromRequest` was removed in v5. It cached computed values as dynamic\n// properties on the Request instance, which only compiled because of the\n// `[key: string]: any` index signature that v5 deletes (eed20184). Use\n// `requestMemo(key, fn)` from `../context/request-memo` instead — same\n// per-request lifetime, single-flight, and it never touches the Request object.\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAS,qBAAqB,SAAkB,UAAoB;CAClE,MAAM,kBAAkBA,WAAO,IAAI,kBAAkB,CAAC,CAAwB;CAE9E,IAAI,gBAAgB,YAAY,OAAO;CAEvC,MAAM,aAAa,gBAAgB,UAAU;CAE7C,SAAS,OAAO,YAAY,QAAQ,EAAE;AACxC;;;;;;AAOA,SAAgB,mBACd,SACA,UAC2B;CAC3B,qBAAqB,SAAS,QAAQ;CAOtC,eAAe,SAAS,QAAQ;CAIhC,MAAM,mBAAmB,eAAe,YAAY;EAAE;EAAS;CAAS,CAAC;CAGzE,OAAO,eAAe,OAAO,kBAAkB,YAAY;EACzD,IAAI;GAOF,MAAM,oBAAoB,MAAM,oBAAoB,SAAS,UAAU,IAAI,WAAW;IACpF,IAAI,MACF,QACA,sCACA,IAAI,MAAM,8CAA8C,QAAQ,CAClE;GACF,CAAC;GAED,IAAI,mBACF,OAAO;GAIT,MAAM,SAAS,MAAM,QAAQ,cAAc;GAE3C,IAAI,QACF,OAAO;GAIT,QAAQ,QAAQ,mBAAmB,QAAQ,KAAK;GAEhD,MAAM,UAAU,QAAQ,WAAW;GAEnC,QAAQ,IAAI,qBAAqB,MAAM;GAEvC,MAAM,iBAAiB,iBAAiB;GACxC,MAAM,mBAAmB,iBAAiB,YAAY,IAAI,IAAI;GAE9D,MAAM,SAAS,MAAM,QAAQ;IAAE;IAAS;GAAS,CAAC;GAElD,IAAI,gBACF,cAAc,oBAAoB,OAAO,GAAG;IAC1C,MAAM;IACN,YAAY,YAAY,IAAI,IAAI;GAClC,CAAC;GAGH,QAAQ,IAAI,iCAAiC,SAAS;GAEtD,QAAQ,QAAQ,kBAAkB,QAAQ,KAAK;GAE/C,OAAO;EACT,SAAS,QAAQ;GACf,MAAM,QAAQ,gBAAgB,QAAQ,OAAO;GAE7C,gBAAgB,OAAO,OAAO;GAC9B,OAAO,mBAAmB,OAAO,UAAU,OAAO;EACpD;CACF,CAAC;AACH;;;;;;;;;AAUA,SAAS,0BAA0B,OAAoC;CACrE,IAAI,iBAAiB,aAAa,iBAAiB,UACjD,OAAO,MAAM;CAGf,IAAI,iBAAiB,+BACnB,OAAOA,WAAO,IAAI,mCAAmC,GAAG;AAI5D;;;;;;;AAQA,SAAS,gBAAgB,OAAgB,SAAuB;CAC9D,MAAM,SAAS,0BAA0B,KAAK;CAE9C,IAAI,WAAW,UAAa,SAAS,OAAO,iBAAiB,OAAO;EAClE,QAAQ,IAAI,GAAG,MAAM,KAAK,IAAI,MAAM,QAAQ,IAAI,OAAO,IAAI,MAAM;EAEjE;CACF;CAEA,QAAQ,IAAI,OAAO,OAAO;AAC5B;;;;;;;AAQA,SAAS,4BAA4B,OAAgB,SAAuB;CAC1E,IAAI,MAAM,QAAQ,2BAA2B,OAAO,EAAE,WAAW,QAAQ,GAAG,CAAC;CAE7E,IAAI,IAAI,SAAS,WAAW,GAC1B,QAAQ,MAAM,8CAA8C,QAAQ,GAAG,IAAI,KAAK;AAEpF;;;;;AAMA,SAAS,mBACP,OACA,UACA,SACkB;CAiBlB,SAAS,OAAO,iBAAiB,mBAAmB;CAEpD,IAAI,iBAAiB,UAAU;EAC7B,IAAI,MAAM,UAAU,KAClB,IAAI,MAAM,QAAQ,iBAAiB,OAAO,EAAE,WAAW,QAAQ,GAAG,CAAC;EAErE,oBAAoB,SAAS,cAAc,KAAK;EAChD,OAAO,SAAS,cAAc,MAAM,MAAM,CAAC,CAAC,KAAK,EAC/C,OAAO;GACL,MAAM,MAAM;GACZ,SAAS,MAAM;GACf,GAAI,MAAM,YAAY,SAAY,CAAC,IAAI,EAAE,SAAS,MAAM,QAAQ;EAClE,EACF,CAAC;CACH;CAEA,IAAI,iBAAiB,WAAW;EAG9B,IAAI,MAAM,UAAU,KAClB,IAAI,MAAM,QAAQ,iBAAiB,OAAO,EAAE,WAAW,QAAQ,GAAG,CAAC;EAGrE,MAAM,UAAyB,EAC7B,OAAO,MAAM,QACf;EACA,IAAI,MAAM,SACR,QAAQ,UAAU,MAAM;EAG1B,IAAI,YAAY,MAAM,eACpB,QAAQ,QAAQ,MAAM;EAGxB,OAAO,SAAS,cAAc,MAAM,MAAM,CAAC,CAAC,KAAK,OAAO;CAC1D;CAEA,IAAI,iBAAiB,+BAA+B;EAClD,MAAM,SAAS,0BAA0B,KAAK;EAI9C,IAAI,UAAU,KACZ,IAAI,MAAM,QAAQ,gCAAgC,OAAO;GACvD,WAAW,QAAQ;GACnB,QAAQ,MAAM;EAChB,CAAC;EAKH,IAAI,SAAS,KACX,OAAO,SAAS,cAAc,MAAM,CAAC,CAAC,KAAK,EACzC,QAAQ,MAAM,OAChB,CAAC;EAGH,OAAO,SAAS,cAAc,MAAM,CAAC,CAAC,KAAK,EACzC,OAAO,yBACT,CAAC;CACH;CAOA,4BAA4B,OAAO,OAAO;CAE1C,OAAO,SAAS,YAAY,EAC1B,OAAO,yBACT,CAAC;AACH;;;;AAKA,SAAgB,EAAE,SAAiB,cAAgD;CACjF,OACEC,eAAuB,WAAW,CAAC,EAAE,MAAM,SAAS,YAAY,KAChE,MAAM,SAAS,YAAY;AAE/B"}
@@ -1,5 +1,5 @@
1
- import { normalizeRequestPath } from "../router/normalize-request-path.mjs";
2
1
  import { registerErrorResponseFormatter } from "./error-response.mjs";
2
+ import { normalizeRequestPath } from "../router/normalize-request-path.mjs";
3
3
  import baseConfig from "@mongez/config";
4
4
  import Fastify from "fastify";
5
5
 
package/esm/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
1
+ import { AppError, BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
2
2
  import { ERROR_CODES, ERROR_CODES_DOCS_URL, ErrorCodeArea, ErrorCodeCategory, ErrorCodeDefinition, WarlockErrorCode, errorCodeDocsUrl, errorCodeOf, explainErrorCode, isWarlockErrorCode } from "./errors/error-codes.mjs";
3
3
  import { WarlockError } from "./errors/warlock-error.mjs";
4
4
  import { normalizeRoutePath } from "./router/normalize-route-path.mjs";
@@ -77,6 +77,11 @@ import { TracingContextSource, buildTracingContext, dispatchPhase, dispatchReque
77
77
  import { RequestContextStore, requestContext, useCurrentUser, useRequest, useRequestStore } from "./http/context/request-context.mjs";
78
78
  import { requestMemo } from "./http/context/request-memo.mjs";
79
79
  import { ModelResourceRegistry, Serialized, SerializedWire } from "./http/serialized.mjs";
80
+ import { RepositoryManager } from "./repositories/repository.manager.mjs";
81
+ import { RepositoryAdapterContract } from "./repositories/contracts/repository-adapter.contract.mjs";
82
+ import { AllRepositoryOptions, CachedRepositoryOptions, ChunkCallback, CursorPaginationOptions, CursorPaginationResult, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, PaginationMode, PaginationResult, RepositoryConfigurations, RepositoryEvent, RepositoryOptions, RepositoryOptionsWithCursor, RepositoryOptionsWithPages, SaveMode, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, WhereOperator } from "./repositories/contracts/types.mjs";
83
+ import { AggregateExpressionInput, AggregateExpressions, GroupByFields, QueryBuilderContract } from "./repositories/contracts/query-builder.contract.mjs";
84
+ import { ListEndpointBody, ListEndpointOptions, ListEndpointRepositoryOptions, ListQuery, listEndpoint } from "./http/list-endpoint.mjs";
80
85
  import "./http/index.mjs";
81
86
  import { LocalizedObject, getLocalized } from "./utils/get-localized.mjs";
82
87
  import { ResourceFieldBuilder } from "./resource/resource-field-builder.mjs";
@@ -116,6 +121,7 @@ import { ConfigIssue, ConfigModuleEntry, ConfigOf, ConfigSchema, ConfigSchemaOpt
116
121
  import { setConfig } from "./config/config-setter.mjs";
117
122
  import { ConfigSpecialHandlers, configSpecialHandlers } from "./config/config-special-handlers.mjs";
118
123
  import "./config/index.mjs";
124
+ import { BudgetPage, BudgetViolation, BuildBudgetReport, BuildBudgets, PageBudget, PayloadBudget } from "./production/build-budgets.mjs";
119
125
  import { WarlockConfig } from "./warlock-config/types.mjs";
120
126
  import { Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority } from "./connectors/types.mjs";
121
127
  import { BaseConnector } from "./connectors/base-connector.mjs";
@@ -162,6 +168,8 @@ import { setLogConfigurations } from "./logger/logger.mjs";
162
168
  import "./logger/index.mjs";
163
169
  import { LocaleDictionaryEntries, LocaleDictionaryError, ParsedLocaleDictionary, parseLocaleDictionary } from "./localization/parse-locale-dictionary.mjs";
164
170
  import { registerGroupedTranslationKeys, registerLocaleDictionary, unregisterLocaleDictionary } from "./localization/register-locale-dictionary.mjs";
171
+ import { EMPTY_TRANSLATION_USAGE, TranslationDynamicSite, TranslationSourceScan, TranslationUsage, isTranslationKeyUsed, mergeTranslationUsage, readTranslationDeclarations, scanTranslationSource, translationDeclarationUsage, usageOf } from "./localization/translation-usage.mjs";
172
+ import { TranslationGraphInput, TranslationGraphResult, analyzePageTranslationUsage, analyzeTranslationGraph, readSourceFile, resolveSourceImport } from "./localization/translation-usage-graph.mjs";
165
173
  import { CapturedMail, MailAddress, MailAttachment, MailConfigurations, MailError, MailErrorCode, MailEvents, MailMode, MailOptions, MailPriority, MailResult, MailersConfig, NormalizedMail, SESConfigurations, SMTPConfigurations } from "./mail/types.mjs";
166
174
  import { getDefaultMailConfig, getExplicitMailMode, getMailMode, getMailerConfig, isDevelopmentMode, isProductionMode, isTestMode, resetMailConfig, resetMailMode, resolveMailConfig, setMailConfigurations, setMailMode } from "./mail/config.mjs";
167
175
  import { MAIL_EVENTS, generateMailId, getMailEventName, mailEvents } from "./mail/events.mjs";
@@ -179,10 +187,6 @@ import { exampleFromSchema } from "./openapi/postman/example-from-schema.mjs";
179
187
  import { DEFAULT_POSTMAN_BASE_URL, POSTMAN_COLLECTION_SCHEMA, openApiToPostmanCollection } from "./openapi/postman/openapi-to-postman-collection.mjs";
180
188
  import "./openapi/index.mjs";
181
189
  import { renderReact } from "./react/index.mjs";
182
- import { RepositoryManager } from "./repositories/repository.manager.mjs";
183
- import { RepositoryAdapterContract } from "./repositories/contracts/repository-adapter.contract.mjs";
184
- import { AllRepositoryOptions, CachedRepositoryOptions, ChunkCallback, CursorPaginationOptions, CursorPaginationResult, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, PaginationMode, PaginationResult, RepositoryConfigurations, RepositoryEvent, RepositoryOptions, RepositoryOptionsWithCursor, RepositoryOptionsWithPages, SaveMode, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, WhereOperator } from "./repositories/contracts/types.mjs";
185
- import { AggregateExpressionInput, AggregateExpressions, GroupByFields, QueryBuilderContract } from "./repositories/contracts/query-builder.contract.mjs";
186
190
  import { CascadeAdapter, UPDATE_MANY_BATCH_SIZE } from "./repositories/adapters/cascade/cascade-adapter.mjs";
187
191
  import { CascadeQueryBuilder } from "./repositories/adapters/cascade/cascade-query-builder.mjs";
188
192
  import "./repositories/index.mjs";
@@ -233,7 +237,7 @@ import "./warlock-config/index.mjs";
233
237
  import { env } from "@mongez/dotenv";
234
238
  import { colors } from "@mongez/copper";
235
239
  export * from "@mongez/localization";
236
- export { $registerUseCase, $unregisterUseCase, APP_ROLES, AUTH_GUARD_MARKER, AccessConnector, AggregateExpressionInput, AggregateExpressions, AiConnector, AllRepositoryOptions, AppConfigurations, AppRole, Application, AuthDescriptor, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseCastOutput, BaseConnector, type BenchmarkChannel, type BenchmarkConfigurations, type BenchmarkErrorResult, type BenchmarkOptions, BenchmarkProfiler, type BenchmarkProfilerOptions, type BenchmarkResult, BenchmarkSnapshots, type BenchmarkSnapshotsOptions, type BenchmarkStats, type BenchmarkSuccessResult, BootContext, BootListener, BootSignal, BootSignalType, BootValidator, CLICommand, type CLICommandAction, type CLICommandOption, type CLICommandOptions, type CLICommandPreload, type CLICommandSource, CacheConnector, type CacheMiddlewareOptions, CachedRepositoryOptions, type CapturedMail, CascadeAdapter, CascadeQueryBuilder, CastOutput, ChunkCallback, ClockSource, ClosableServer, CloudDriver, CloudStorageDriverContract, CloudStorageDriverOptions, CloudStorageFileData, type CommandActionData, type ConcurrencyLimitOptions, ConditionalRequestInput, ConditionalRequestOutcome, ConfigIssue, ConfigKey, ConfigKeyRegistry, ConfigModuleEntry, ConfigName, ConfigOf, ConfigRegistry, ConfigSchema, ConfigSchemaOptions, ConfigSpecialHandlers, ConflictError, Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority, ConnectorsManager, ConsoleChannel, ContainerTypes, CookieJarUnavailableError, CookieOptions, CspConfig, CsrfOriginCheckReason, CsrfOriginVerdict, CursorPaginationOptions, CursorPaginationResult, DEFAULT_CSP_DIRECTIVES, DEFAULT_POSTMAN_BASE_URL, DOSpacesDriver, DatabaseCacheDriver, type DatabaseCacheOptions, DatabaseConnector, DatabaseLog, DatabaseLogModel, DatabaseLogOptions, DecodedAccessToken, DefineResourceOptions, DeleteManyResult, DetectedImageFormat, type DevelopmentAppModuleEntry, type DevelopmentAppModules, type DevelopmentModelModuleEntry, type DevelopmentModelModuleState, type DevelopmentModelModules, DevelopmentPostmanResult, ERROR_CODES, ERROR_CODES_DOCS_URL, EncryptionConfigurations, EncryptionPasswordConfigurations, EntityTag, Environment, ErrorCodeArea, ErrorCodeCategory, ErrorCodeDefinition, EventSubscription, ExistsExceptCurrentIdRuleOptions, ExistsExceptCurrentUserRuleOptions, FastifyInstance, FieldOutput, FileNamingStrategy, FileValidationOptions, FileValidator, FileVisibility, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, ForbiddenError, GenerateImageVariantsOptions, GeneratedImageDescriptor, GeneratedImageVariant, GroupByFields, GroupedRoutesOptions, HealthCheck, HealthStatus, HeraldConnector, HttpConfigurations, HttpConnector, HttpContext, HttpError, HttpErrorCodes, type HttpErrorMapper, type HttpErrorMapping, type HttpErrorResponseContext, type HttpErrorResponseFormatter, HttpLoggingConfig, HttpReadyReport, HttpServerOptions, HttpServerRebuiltListener, HttpTracingConfig, type IdempotencyOptions, IdsSource, Image, ImageFormat, ImageInput, ImageTransformCallback, ImageTransformConfig, ImageTransformOptions, ImageVariantDefinition, ImageVariantFit, ImageVariantOutputFormat, ImageVariantsConfigError, InvalidConfigError, InvalidCspDirectiveError, type IpFilterOptions, JavaScriptRuntime, JavaScriptRuntimeName, ListOptions, LocalDriver, LocalStorageDriverOptions, LocaleDictionaryEntries, LocaleDictionaryError, LocalizedObject, LogConfigurations, LoggerConnector, MAIL_EVENTS, Mail, type MailAddress, type MailAttachment, type MailConfigurations, MailError, type MailErrorCode, type MailEvents, type MailMode, type MailOptions, type MailPriority, type MailResult, MailerConnector, type MailersConfig, type MaintenanceOptions, MemorySecretBackend, Middleware, MiddlewareResponse, MimeTypes, ModelResourceRegistry, NULLABLE_RESOURCE, NamedApiRoute, NamedApiRoutesOptions, NoopChannel, type NormalizedMail, NotAcceptableError, NotAllowedError, NotificationsConnector, NullableResource, NullableResourceTarget, OPENAPI_JSON_SCHEMA_DIALECT, OpenApiBuildResult, OpenApiComponents, OpenApiContext, OpenApiDocument, OpenApiOperation, OpenApiParameter, OpenApiRequestBody, OpenApiResponse, OpenApiRouteInput, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSecurityScheme, OpenApiValidationResponseConfig, POSTMAN_COLLECTION_SCHEMA, PaginationMode, PaginationResult, ParsedLocaleDictionary, PartialMiddleware, PartialPick, Path, PipeableReactStream, PipelineOptions, PortInUseError, PositionalHandlerSuspect, PostmanAuth, PostmanAuthEntry, PostmanBody, PostmanCollection, PostmanCollectionOptions, PostmanFolder, PostmanFormParam, PostmanHeader, PostmanItem, PostmanOriginalRequest, PostmanQueryParam, PostmanRequest, PostmanRequestItem, PostmanResponse, PostmanUrl, PostmanVariable, PrefixConfig, PrefixOptions, PresignedOptions, PresignedUploadOptions, PrivateRequestLoggingRule, PurgeImageVariantsOptions, PutDirectoryOptions, PutDirectoryResult, PutFromUrlOptions, PutOptions, QueryBuilderContract, Queue, R2Driver, R2StorageDriverOptions, type RateLimitOptions, RegisterConfiguredConnectorsOptions, RegisterResource, RegisteredUseCase, RepositoryAdapterContract, RepositoryConfigurations, RepositoryEvent, RepositoryManager, RepositoryOptions, RepositoryOptionsWithCursor, RepositoryOptionsWithPages, Request, RequestContextStore, RequestController, RequestControllerContract, RequestEvent, RequestHandler, RequestHandlerType, RequestHandlerValidation, RequestLocals, RequestLog, RequestLogSnapshot, RequestLogSource, RequestLoggingOptions, RequestMethod, RequestTranslator, ResolveImageVariantInput, type ResolvedCLICommandOption, ResolvedImageVariant, ResolvedImageVariantsConfig, Resource, ResourceArraySchema, ResourceCastType, ResourceConstructor, ResourceContract, ResourceFieldBuilder, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceMethod, ResourceNotFoundError, ResourceOutput, ResourceOutputOf, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, Response, ResponseBodyOutput, ResponseBodyValue, ResponseEvent, ResponseSSEController, ResponseSSEMessageOptions, ResponseSSEOptions, ResponseSchema, ResponseSchemaOutput, ResponseStatus, ResponseStreamController, ResponseStreamOptions, Restful, RestfulMiddleware, ReturnedResponse, Route, RouteNameTakenError, RouteOptions, RouteRateLimitOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, RuntimeStrategy, S3Driver, type SESConfigurations, type SMTPConfigurations, SUPPORTED_RUNTIMES_DOCS_URL, SafeFetchOptions, SafeFetchResult, SafeRedirectOptions, SaveAsOptions, SaveMode, SaveOptions, ScopedStorage, ScopedStorageContract, type SecretBackend, type SecretBackendType, SecretStore, SecretStoreError, SecretStoreErrorCode, type SecretStoreOptions, type SecretsConfigurations, SeedClock, SeedContext, SeedRecordRef, SeedResult, Seeder, SeederDependencyCycleError, SeederMetadata, SendBufferOptions, SendFileOptions, Serialized, SerializedWire, ServerError, ShutdownListener, SocketAdapterFactory, SocketConnector, SocketOptions, StaticMountOptions, Storage, StorageCapabilityError, StorageConfigurations, StorageConnector, StorageCopyEventPayload, StorageDriverConfig, StorageDriverContextStore, StorageDriverContract, StorageDriverName, StorageDriverRegistry, StorageDriverType, StorageError, StorageErrorOptions, StorageEventHandler, StorageEventPayload, StorageEventType, StorageFile, StorageFileData, StorageFileInfo, StorageManagerContract, StorageNotInitializedError, StoragePutEventPayload, StreamReactResponseOptions, TemporaryTokenError, TemporaryTokenPayload, TemporaryTokenValidation, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, Track, TrackableModel, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, URL_CREDENTIAL_PARAMS, UnAuthorizedError, UniqueExceptCurrentIdRuleOptions, UniqueExceptCurrentUserRuleOptions, UnknownSeederDependencyError, UploadedFile, UploadedFileControllerOptions, UploadedFileImageOptions, UploadedFileJson, UploadedFileQuery, UploadsConfigurations, UploadsImagesConfigurations, UseCase, UseCaseAfterMiddleware, UseCaseBeforeMiddleware, UseCaseBroadcastChannel, UseCaseBroadcastEvent, UseCaseBroadcastOption, UseCaseConfigurations, UseCaseContext, UseCaseErrorResult, UseCaseEventsCallbacksMap, UseCaseGuard, UseCaseHandler, UseCaseOnExecutingContext, UseCaseResult, UseCaseRuntimeOptions, UseCaseWithSchema, ValidationConfiguration, ValidationFailureContext, ValidationFailureHandler, ValidationFailureResponse, ValidationResponseConfiguration, VariantOutputFormat, VariantSourceFormat, WarlockConfig, WarlockConfigManager, WarlockError, WarlockErrorCode, WarningSink, WatermarkConfig, WhereOperator, XMLable, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertNodeOnlyCommand, assertPortIsAvailable, assertSitesRequireWebRole, assertUniqueConnectorNames, assertValidConfigModules, assetsUrl, beginHttpDrain, bootstrap, broadcastSocketEvent, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildOpenApiDocument, buildRequestLogSnapshot, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, clock, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, createUploadedFileController, decrypt, defaultHttpConfigurations, defineConfig, defineConfigSchema, defineResource, deriveTraceId, describeJavaScriptRuntime, describePositionalHandlerSuspect, detectJavaScriptRuntime, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, errorCodeDocsUrl, errorCodeOf, escapeHeaderValue, evaluateConditionalRequest, exampleFromSchema, existsExceptCurrentIdRule, existsExceptCurrentUserRule, explainErrorCode, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, formatConfigIssues, generateImageVariants, generateMailId, getDefaultMailConfig, getDevelopmentOpenApiDocument, getDevelopmentPostmanCollection, getExplicitMailMode, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getRoles, getSites, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hasRole, hashBody, hashPassword, health, hmacHash, httpConfig, ids, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isAuthGuardMiddleware, isBootSignal, isConfigSchema, isDevelopmentMode, isNewerVersion, isNullableResource, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isSafeRedirect, isTestMode, isTracingEnabled, isUnguardedMutatingRoute, isUnknownTsExtensionError, isUnresolvedConfigImportError, isUnsupportedTypeStrippingError, isValidIdempotencyKey, isWarlockErrorCode, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, markAuthGuard, matchesDerivedRouteName, matchesIfMatch, matchesIfNoneMatch, measure, mergeCspDirectives, middleware, nodeOnlyCommandError, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, notifyHttpServerRebuilt, nullable, onHttpServerRebuilt, openApiToPostmanCollection, originOf, ownOrigin, parseEntityTag, parseEntityTagList, parseLocaleDictionary, parseRoles, parseSites, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, purgeImageVariants, redactQueryCredentials, redactUrlCredentials, registerAppConfig, registerConfiguredConnectors, registerDevelopmentOpenApiProvider, registerGroupedTranslationKeys, registerHttpPlugins, registerLocaleDictionary, registerTracingHooks, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, reportUnguardedMutatingRoutes, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetMailMode, resetRolesCacheForTests, resetTracingConfigForTests, resetUnguardedRouteReports, resolveCspConfig, resolveCsrfOriginVerdict, resolveImageVariant, resolveMailConfig, resolvePublicRoot, resolveRequestLoggingOptions, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, safeRedirect, sanitizePath, secrets, seeder, sendBootSignal, sendMail, serializeCspDirectives, servesHttp, setBaseUrl, setClockSource, setConfig, setEnvironment, setHttpReadyReport, setIdsSource, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, strongEntityTagMatch, t, tempPath, toJson, toSingleLineSseField, trackConnectionsForDrain, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, unregisterLocaleDictionary, unverifiedBuildRuntimeNotice, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateConfigValue, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, weakEntityTagMatch, wrapResponseInDataKey };
240
+ export { $registerUseCase, $unregisterUseCase, APP_ROLES, AUTH_GUARD_MARKER, AccessConnector, AggregateExpressionInput, AggregateExpressions, AiConnector, AllRepositoryOptions, AppConfigurations, AppError, AppRole, Application, AuthDescriptor, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseCastOutput, BaseConnector, type BenchmarkChannel, type BenchmarkConfigurations, type BenchmarkErrorResult, type BenchmarkOptions, BenchmarkProfiler, type BenchmarkProfilerOptions, type BenchmarkResult, BenchmarkSnapshots, type BenchmarkSnapshotsOptions, type BenchmarkStats, type BenchmarkSuccessResult, BootContext, BootListener, BootSignal, BootSignalType, BootValidator, type BudgetPage, type BudgetViolation, type BuildBudgetReport, type BuildBudgets, CLICommand, type CLICommandAction, type CLICommandOption, type CLICommandOptions, type CLICommandPreload, type CLICommandSource, CacheConnector, type CacheMiddlewareOptions, CachedRepositoryOptions, type CapturedMail, CascadeAdapter, CascadeQueryBuilder, CastOutput, ChunkCallback, ClockSource, ClosableServer, CloudDriver, CloudStorageDriverContract, CloudStorageDriverOptions, CloudStorageFileData, type CommandActionData, type ConcurrencyLimitOptions, ConditionalRequestInput, ConditionalRequestOutcome, ConfigIssue, ConfigKey, ConfigKeyRegistry, ConfigModuleEntry, ConfigName, ConfigOf, ConfigRegistry, ConfigSchema, ConfigSchemaOptions, ConfigSpecialHandlers, ConflictError, Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority, ConnectorsManager, ConsoleChannel, ContainerTypes, CookieJarUnavailableError, CookieOptions, CspConfig, CsrfOriginCheckReason, CsrfOriginVerdict, CursorPaginationOptions, CursorPaginationResult, DEFAULT_CSP_DIRECTIVES, DEFAULT_POSTMAN_BASE_URL, DOSpacesDriver, DatabaseCacheDriver, type DatabaseCacheOptions, DatabaseConnector, DatabaseLog, DatabaseLogModel, DatabaseLogOptions, DecodedAccessToken, DefineResourceOptions, DeleteManyResult, DetectedImageFormat, type DevelopmentAppModuleEntry, type DevelopmentAppModules, type DevelopmentModelModuleEntry, type DevelopmentModelModuleState, type DevelopmentModelModules, DevelopmentPostmanResult, EMPTY_TRANSLATION_USAGE, ERROR_CODES, ERROR_CODES_DOCS_URL, EncryptionConfigurations, EncryptionPasswordConfigurations, EntityTag, Environment, ErrorCodeArea, ErrorCodeCategory, ErrorCodeDefinition, EventSubscription, ExistsExceptCurrentIdRuleOptions, ExistsExceptCurrentUserRuleOptions, FastifyInstance, FieldOutput, FileNamingStrategy, FileValidationOptions, FileValidator, FileVisibility, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, ForbiddenError, GenerateImageVariantsOptions, GeneratedImageDescriptor, GeneratedImageVariant, GroupByFields, GroupedRoutesOptions, HealthCheck, HealthStatus, HeraldConnector, HttpConfigurations, HttpConnector, HttpContext, HttpError, HttpErrorCodes, type HttpErrorMapper, type HttpErrorMapping, type HttpErrorResponseContext, type HttpErrorResponseFormatter, HttpLoggingConfig, HttpReadyReport, HttpServerOptions, HttpServerRebuiltListener, HttpTracingConfig, type IdempotencyOptions, IdsSource, Image, ImageFormat, ImageInput, ImageTransformCallback, ImageTransformConfig, ImageTransformOptions, ImageVariantDefinition, ImageVariantFit, ImageVariantOutputFormat, ImageVariantsConfigError, InvalidConfigError, InvalidCspDirectiveError, type IpFilterOptions, JavaScriptRuntime, JavaScriptRuntimeName, ListEndpointBody, ListEndpointOptions, ListEndpointRepositoryOptions, ListOptions, ListQuery, LocalDriver, LocalStorageDriverOptions, LocaleDictionaryEntries, LocaleDictionaryError, LocalizedObject, LogConfigurations, LoggerConnector, MAIL_EVENTS, Mail, type MailAddress, type MailAttachment, type MailConfigurations, MailError, type MailErrorCode, type MailEvents, type MailMode, type MailOptions, type MailPriority, type MailResult, MailerConnector, type MailersConfig, type MaintenanceOptions, MemorySecretBackend, Middleware, MiddlewareResponse, MimeTypes, ModelResourceRegistry, NULLABLE_RESOURCE, NamedApiRoute, NamedApiRoutesOptions, NoopChannel, type NormalizedMail, NotAcceptableError, NotAllowedError, NotificationsConnector, NullableResource, NullableResourceTarget, OPENAPI_JSON_SCHEMA_DIALECT, OpenApiBuildResult, OpenApiComponents, OpenApiContext, OpenApiDocument, OpenApiOperation, OpenApiParameter, OpenApiRequestBody, OpenApiResponse, OpenApiRouteInput, OpenApiSchema, OpenApiSecurityRequirement, OpenApiSecurityScheme, OpenApiValidationResponseConfig, POSTMAN_COLLECTION_SCHEMA, type PageBudget, PaginationMode, PaginationResult, ParsedLocaleDictionary, PartialMiddleware, PartialPick, Path, type PayloadBudget, PipeableReactStream, PipelineOptions, PortInUseError, PositionalHandlerSuspect, PostmanAuth, PostmanAuthEntry, PostmanBody, PostmanCollection, PostmanCollectionOptions, PostmanFolder, PostmanFormParam, PostmanHeader, PostmanItem, PostmanOriginalRequest, PostmanQueryParam, PostmanRequest, PostmanRequestItem, PostmanResponse, PostmanUrl, PostmanVariable, PrefixConfig, PrefixOptions, PresignedOptions, PresignedUploadOptions, PrivateRequestLoggingRule, PurgeImageVariantsOptions, PutDirectoryOptions, PutDirectoryResult, PutFromUrlOptions, PutOptions, QueryBuilderContract, Queue, R2Driver, R2StorageDriverOptions, type RateLimitOptions, RegisterConfiguredConnectorsOptions, RegisterResource, RegisteredUseCase, RepositoryAdapterContract, RepositoryConfigurations, RepositoryEvent, RepositoryManager, RepositoryOptions, RepositoryOptionsWithCursor, RepositoryOptionsWithPages, Request, RequestContextStore, RequestController, RequestControllerContract, RequestEvent, RequestHandler, RequestHandlerType, RequestHandlerValidation, RequestLocals, RequestLog, RequestLogSnapshot, RequestLogSource, RequestLoggingOptions, RequestMethod, RequestTranslator, ResolveImageVariantInput, type ResolvedCLICommandOption, ResolvedImageVariant, ResolvedImageVariantsConfig, Resource, ResourceArraySchema, ResourceCastType, ResourceConstructor, ResourceContract, ResourceFieldBuilder, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceMethod, ResourceNotFoundError, ResourceOutput, ResourceOutputOf, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, Response, ResponseBodyOutput, ResponseBodyValue, ResponseEvent, ResponseSSEController, ResponseSSEMessageOptions, ResponseSSEOptions, ResponseSchema, ResponseSchemaOutput, ResponseStatus, ResponseStreamController, ResponseStreamOptions, Restful, RestfulMiddleware, ReturnedResponse, Route, RouteNameTakenError, RouteOptions, RouteRateLimitOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, RuntimeStrategy, S3Driver, type SESConfigurations, type SMTPConfigurations, SUPPORTED_RUNTIMES_DOCS_URL, SafeFetchOptions, SafeFetchResult, SafeRedirectOptions, SaveAsOptions, SaveMode, SaveOptions, ScopedStorage, ScopedStorageContract, type SecretBackend, type SecretBackendType, SecretStore, SecretStoreError, SecretStoreErrorCode, type SecretStoreOptions, type SecretsConfigurations, SeedClock, SeedContext, SeedRecordRef, SeedResult, Seeder, SeederDependencyCycleError, SeederMetadata, SendBufferOptions, SendFileOptions, Serialized, SerializedWire, ServerError, ShutdownListener, SocketAdapterFactory, SocketConnector, SocketOptions, StaticMountOptions, Storage, StorageCapabilityError, StorageConfigurations, StorageConnector, StorageCopyEventPayload, StorageDriverConfig, StorageDriverContextStore, StorageDriverContract, StorageDriverName, StorageDriverRegistry, StorageDriverType, StorageError, StorageErrorOptions, StorageEventHandler, StorageEventPayload, StorageEventType, StorageFile, StorageFileData, StorageFileInfo, StorageManagerContract, StorageNotInitializedError, StoragePutEventPayload, StreamReactResponseOptions, TemporaryTokenError, TemporaryTokenPayload, TemporaryTokenValidation, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, Track, TrackableModel, TranslationDynamicSite, TranslationGraphInput, TranslationGraphResult, TranslationSourceScan, TranslationUsage, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, URL_CREDENTIAL_PARAMS, UnAuthorizedError, UniqueExceptCurrentIdRuleOptions, UniqueExceptCurrentUserRuleOptions, UnknownSeederDependencyError, UploadedFile, UploadedFileControllerOptions, UploadedFileImageOptions, UploadedFileJson, UploadedFileQuery, UploadsConfigurations, UploadsImagesConfigurations, UseCase, UseCaseAfterMiddleware, UseCaseBeforeMiddleware, UseCaseBroadcastChannel, UseCaseBroadcastEvent, UseCaseBroadcastOption, UseCaseConfigurations, UseCaseContext, UseCaseErrorResult, UseCaseEventsCallbacksMap, UseCaseGuard, UseCaseHandler, UseCaseOnExecutingContext, UseCaseResult, UseCaseRuntimeOptions, UseCaseWithSchema, ValidationConfiguration, ValidationFailureContext, ValidationFailureHandler, ValidationFailureResponse, ValidationResponseConfiguration, VariantOutputFormat, VariantSourceFormat, WarlockConfig, WarlockConfigManager, WarlockError, WarlockErrorCode, WarningSink, WatermarkConfig, WhereOperator, XMLable, addUseCaseHistory, analyzePageTranslationUsage, analyzeTranslationGraph, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertNodeOnlyCommand, assertPortIsAvailable, assertSitesRequireWebRole, assertUniqueConnectorNames, assertValidConfigModules, assetsUrl, beginHttpDrain, bootstrap, broadcastSocketEvent, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildOpenApiDocument, buildRequestLogSnapshot, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, clock, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, createUploadedFileController, decrypt, defaultHttpConfigurations, defineConfig, defineConfigSchema, defineResource, deriveTraceId, describeJavaScriptRuntime, describePositionalHandlerSuspect, detectJavaScriptRuntime, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, errorCodeDocsUrl, errorCodeOf, escapeHeaderValue, evaluateConditionalRequest, exampleFromSchema, existsExceptCurrentIdRule, existsExceptCurrentUserRule, explainErrorCode, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, formatConfigIssues, generateImageVariants, generateMailId, getDefaultMailConfig, getDevelopmentOpenApiDocument, getDevelopmentPostmanCollection, getExplicitMailMode, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getRoles, getSites, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hasRole, hashBody, hashPassword, health, hmacHash, httpConfig, ids, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isAuthGuardMiddleware, isBootSignal, isConfigSchema, isDevelopmentMode, isNewerVersion, isNullableResource, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isSafeRedirect, isTestMode, isTracingEnabled, isTranslationKeyUsed, isUnguardedMutatingRoute, isUnknownTsExtensionError, isUnresolvedConfigImportError, isUnsupportedTypeStrippingError, isValidIdempotencyKey, isWarlockErrorCode, listEndpoint, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, markAuthGuard, matchesDerivedRouteName, matchesIfMatch, matchesIfNoneMatch, measure, mergeCspDirectives, mergeTranslationUsage, middleware, nodeOnlyCommandError, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, notifyHttpServerRebuilt, nullable, onHttpServerRebuilt, openApiToPostmanCollection, originOf, ownOrigin, parseEntityTag, parseEntityTagList, parseLocaleDictionary, parseRoles, parseSites, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, purgeImageVariants, readSourceFile, readTranslationDeclarations, redactQueryCredentials, redactUrlCredentials, registerAppConfig, registerConfiguredConnectors, registerDevelopmentOpenApiProvider, registerGroupedTranslationKeys, registerHttpPlugins, registerLocaleDictionary, registerTracingHooks, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, reportUnguardedMutatingRoutes, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetMailMode, resetRolesCacheForTests, resetTracingConfigForTests, resetUnguardedRouteReports, resolveCspConfig, resolveCsrfOriginVerdict, resolveImageVariant, resolveMailConfig, resolvePublicRoot, resolveRequestLoggingOptions, resolveSourceImport, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, safeRedirect, sanitizePath, scanTranslationSource, secrets, seeder, sendBootSignal, sendMail, serializeCspDirectives, servesHttp, setBaseUrl, setClockSource, setConfig, setEnvironment, setHttpReadyReport, setIdsSource, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, strongEntityTagMatch, t, tempPath, toJson, toSingleLineSseField, trackConnectionsForDrain, translationDeclarationUsage, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, unregisterLocaleDictionary, unverifiedBuildRuntimeNotice, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, usageOf, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateConfigValue, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, weakEntityTagMatch, wrapResponseInDataKey };
237
241
  import "./config/types.mjs";
238
242
  import "./http/request.mjs";
239
243
  import "./http/serialized.mjs";
package/esm/index.mjs CHANGED
@@ -28,7 +28,7 @@ import { DEFAULT_CSP_DIRECTIVES, InvalidCspDirectiveError, applyCspHeader, build
28
28
  import { HttpErrorCodes } from "./http/error-codes.mjs";
29
29
  import { isAllowedCsrfOrigin, normalizeOrigin, originOf, ownOrigin, resolveCsrfOriginVerdict } from "./http/csrf-origin-policy.mjs";
30
30
  import { requiresDefaultCsrfGuard, runDefaultCsrfGuard } from "./http/csrf-default-guard.mjs";
31
- import { BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
31
+ import { AppError, BadRequestError, ConflictError, CookieJarUnavailableError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
32
32
  import { deriveTraceId, parseTraceparentTraceId } from "./http/tracing/trace-id.mjs";
33
33
  import { buildTracingContext, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled, registerTracingHooks, resetTracingConfigForTests, resolveTracingConfig } from "./http/tracing/tracing-dispatcher.mjs";
34
34
  import { createRequestStore, t } from "./http/middleware/inject-request-context.mjs";
@@ -101,6 +101,7 @@ import { notifyHttpServerRebuilt, onHttpServerRebuilt } from "./http/server-rebu
101
101
  import { escapeHeaderValue } from "./http/escape-header-value.mjs";
102
102
  import { isSafeRedirect, safeRedirect } from "./http/safe-redirect.mjs";
103
103
  import { requestMemo } from "./http/context/request-memo.mjs";
104
+ import { listEndpoint } from "./http/list-endpoint.mjs";
104
105
  import "./http/index.mjs";
105
106
  import { existsExceptCurrentIdRule } from "./validation/database/exists-except-current-id.mjs";
106
107
  import { existsExceptCurrentUserRule } from "./validation/database/exists-except-current-user.mjs";
@@ -168,6 +169,8 @@ import "./secrets/index.mjs";
168
169
  import { ERROR_CODES, ERROR_CODES_DOCS_URL, errorCodeDocsUrl, errorCodeOf, explainErrorCode, isWarlockErrorCode } from "./errors/error-codes.mjs";
169
170
  import { LocaleDictionaryError, parseLocaleDictionary } from "./localization/parse-locale-dictionary.mjs";
170
171
  import { registerGroupedTranslationKeys, registerLocaleDictionary, unregisterLocaleDictionary } from "./localization/register-locale-dictionary.mjs";
172
+ import { EMPTY_TRANSLATION_USAGE, isTranslationKeyUsed, mergeTranslationUsage, readTranslationDeclarations, scanTranslationSource, translationDeclarationUsage, usageOf } from "./localization/translation-usage.mjs";
173
+ import { analyzePageTranslationUsage, analyzeTranslationGraph, readSourceFile, resolveSourceImport } from "./localization/translation-usage-graph.mjs";
171
174
  import "./localization/index.mjs";
172
175
  import { exampleFromSchema } from "./openapi/postman/example-from-schema.mjs";
173
176
  import { DEFAULT_POSTMAN_BASE_URL, POSTMAN_COLLECTION_SCHEMA, openApiToPostmanCollection } from "./openapi/postman/openapi-to-postman-collection.mjs";
@@ -203,4 +206,4 @@ import { colors } from "@mongez/copper";
203
206
 
204
207
  export * from "@mongez/localization"
205
208
 
206
- export { $registerUseCase, $unregisterUseCase, APP_ROLES, AUTH_GUARD_MARKER, AccessConnector, AiConnector, Application, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseConnector, BenchmarkProfiler, BenchmarkSnapshots, CLICommand, CacheConnector, CascadeAdapter, CascadeQueryBuilder, CloudDriver, ConfigSpecialHandlers, ConflictError, ConnectorLifecyclePhase, ConnectorPriority, ConnectorsManager, ConsoleChannel, CookieJarUnavailableError, DEFAULT_CSP_DIRECTIVES, DEFAULT_POSTMAN_BASE_URL, DOSpacesDriver, DatabaseCacheDriver, DatabaseConnector, DatabaseLog, DatabaseLogModel, ERROR_CODES, ERROR_CODES_DOCS_URL, FileValidator, ForbiddenError, HeraldConnector, HttpConnector, HttpError, HttpErrorCodes, Image, ImageVariantsConfigError, InvalidConfigError, InvalidCspDirectiveError, LocalDriver, LocaleDictionaryError, LoggerConnector, MAIL_EVENTS, Mail, MailError, MailerConnector, MemorySecretBackend, MimeTypes, NULLABLE_RESOURCE, NoopChannel, NotAcceptableError, NotAllowedError, NotificationsConnector, OPENAPI_JSON_SCHEMA_DIALECT, POSTMAN_COLLECTION_SCHEMA, Path, PortInUseError, Queue, R2Driver, RegisterResource, RepositoryManager, Request, RequestController, RequestLog, Resource, ResourceFieldBuilder, ResourceNotFoundError, Response, ResponseStatus, Restful, RouteNameTakenError, RouteRegistry, Router, S3Driver, SUPPORTED_RUNTIMES_DOCS_URL, ScopedStorage, SecretStore, SecretStoreError, SeederDependencyCycleError, ServerError, SocketConnector, Storage, StorageCapabilityError, StorageConnector, StorageError, StorageFile, StorageNotInitializedError, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, URL_CREDENTIAL_PARAMS, UnAuthorizedError, UnknownSeederDependencyError, UploadedFile, WarlockConfigManager, WarlockError, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertNodeOnlyCommand, assertPortIsAvailable, assertSitesRequireWebRole, assertUniqueConnectorNames, assertValidConfigModules, assetsUrl, beginHttpDrain, bootstrap, broadcastSocketEvent, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildOpenApiDocument, buildRequestLogSnapshot, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, clock, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, createUploadedFileController, decrypt, defaultHttpConfigurations, defineConfig, defineConfigSchema, defineResource, deriveTraceId, describeJavaScriptRuntime, describePositionalHandlerSuspect, detectJavaScriptRuntime, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, errorCodeDocsUrl, errorCodeOf, escapeHeaderValue, evaluateConditionalRequest, exampleFromSchema, existsExceptCurrentIdRule, existsExceptCurrentUserRule, explainErrorCode, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, formatConfigIssues, generateImageVariants, generateMailId, getDefaultMailConfig, getDevelopmentOpenApiDocument, getDevelopmentPostmanCollection, getExplicitMailMode, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getRoles, getSites, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hasRole, hashBody, hashPassword, health, hmacHash, httpConfig, ids, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isAuthGuardMiddleware, isBootSignal, isConfigSchema, isDevelopmentMode, isNewerVersion, isNullableResource, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isSafeRedirect, isTestMode, isTracingEnabled, isUnguardedMutatingRoute, isUnknownTsExtensionError, isUnresolvedConfigImportError, isUnsupportedTypeStrippingError, isValidIdempotencyKey, isWarlockErrorCode, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, markAuthGuard, matchesDerivedRouteName, matchesIfMatch, matchesIfNoneMatch, measure, mergeCspDirectives, middleware, nodeOnlyCommandError, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, notifyHttpServerRebuilt, nullable, onHttpServerRebuilt, openApiToPostmanCollection, originOf, ownOrigin, parseEntityTag, parseEntityTagList, parseLocaleDictionary, parseRoles, parseSites, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, purgeImageVariants, redactQueryCredentials, redactUrlCredentials, registerAppConfig, registerConfiguredConnectors, registerDevelopmentOpenApiProvider, registerGroupedTranslationKeys, registerHttpPlugins, registerLocaleDictionary, registerTracingHooks, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, reportUnguardedMutatingRoutes, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetMailMode, resetRolesCacheForTests, resetTracingConfigForTests, resetUnguardedRouteReports, resolveCspConfig, resolveCsrfOriginVerdict, resolveImageVariant, resolveMailConfig, resolvePublicRoot, resolveRequestLoggingOptions, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, safeRedirect, sanitizePath, secrets, seeder, sendBootSignal, sendMail, serializeCspDirectives, servesHttp, setBaseUrl, setClockSource, setConfig, setEnvironment, setHttpReadyReport, setIdsSource, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, strongEntityTagMatch, t, tempPath, toJson, toSingleLineSseField, trackConnectionsForDrain, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, unregisterLocaleDictionary, unverifiedBuildRuntimeNotice, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateConfigValue, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, weakEntityTagMatch, wrapResponseInDataKey };
209
+ export { $registerUseCase, $unregisterUseCase, APP_ROLES, AUTH_GUARD_MARKER, AccessConnector, AiConnector, AppError, Application, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, BaseConnector, BenchmarkProfiler, BenchmarkSnapshots, CLICommand, CacheConnector, CascadeAdapter, CascadeQueryBuilder, CloudDriver, ConfigSpecialHandlers, ConflictError, ConnectorLifecyclePhase, ConnectorPriority, ConnectorsManager, ConsoleChannel, CookieJarUnavailableError, DEFAULT_CSP_DIRECTIVES, DEFAULT_POSTMAN_BASE_URL, DOSpacesDriver, DatabaseCacheDriver, DatabaseConnector, DatabaseLog, DatabaseLogModel, EMPTY_TRANSLATION_USAGE, ERROR_CODES, ERROR_CODES_DOCS_URL, FileValidator, ForbiddenError, HeraldConnector, HttpConnector, HttpError, HttpErrorCodes, Image, ImageVariantsConfigError, InvalidConfigError, InvalidCspDirectiveError, LocalDriver, LocaleDictionaryError, LoggerConnector, MAIL_EVENTS, Mail, MailError, MailerConnector, MemorySecretBackend, MimeTypes, NULLABLE_RESOURCE, NoopChannel, NotAcceptableError, NotAllowedError, NotificationsConnector, OPENAPI_JSON_SCHEMA_DIALECT, POSTMAN_COLLECTION_SCHEMA, Path, PortInUseError, Queue, R2Driver, RegisterResource, RepositoryManager, Request, RequestController, RequestLog, Resource, ResourceFieldBuilder, ResourceNotFoundError, Response, ResponseStatus, Restful, RouteNameTakenError, RouteRegistry, Router, S3Driver, SUPPORTED_RUNTIMES_DOCS_URL, ScopedStorage, SecretStore, SecretStoreError, SeederDependencyCycleError, ServerError, SocketConnector, Storage, StorageCapabilityError, StorageConnector, StorageError, StorageFile, StorageNotInitializedError, UPDATE_MANY_BATCH_SIZE, UPLOADS_DEFAULTS, URL_CREDENTIAL_PARAMS, UnAuthorizedError, UnknownSeederDependencyError, UploadedFile, WarlockConfigManager, WarlockError, addUseCaseHistory, analyzePageTranslationUsage, analyzeTranslationGraph, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertNodeOnlyCommand, assertPortIsAvailable, assertSitesRequireWebRole, assertUniqueConnectorNames, assertValidConfigModules, assetsUrl, beginHttpDrain, bootstrap, broadcastSocketEvent, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildOpenApiDocument, buildRequestLogSnapshot, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, clock, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, createUploadedFileController, decrypt, defaultHttpConfigurations, defineConfig, defineConfigSchema, defineResource, deriveTraceId, describeJavaScriptRuntime, describePositionalHandlerSuspect, detectJavaScriptRuntime, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, errorCodeDocsUrl, errorCodeOf, escapeHeaderValue, evaluateConditionalRequest, exampleFromSchema, existsExceptCurrentIdRule, existsExceptCurrentUserRule, explainErrorCode, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, formatConfigIssues, generateImageVariants, generateMailId, getDefaultMailConfig, getDevelopmentOpenApiDocument, getDevelopmentPostmanCollection, getExplicitMailMode, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getPublicUrl, getRoles, getSites, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hasRole, hashBody, hashPassword, health, hmacHash, httpConfig, ids, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isAllowedCsrfOrigin, isAuthGuardMiddleware, isBootSignal, isConfigSchema, isDevelopmentMode, isNewerVersion, isNullableResource, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isSafeRedirect, isTestMode, isTracingEnabled, isTranslationKeyUsed, isUnguardedMutatingRoute, isUnknownTsExtensionError, isUnresolvedConfigImportError, isUnsupportedTypeStrippingError, isValidIdempotencyKey, isWarlockErrorCode, listEndpoint, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, markAuthGuard, matchesDerivedRouteName, matchesIfMatch, matchesIfNoneMatch, measure, mergeCspDirectives, mergeTranslationUsage, middleware, nodeOnlyCommandError, normalizeOrigin, normalizeRequestPath, normalizeRoutePath, notifyHttpServerRebuilt, nullable, onHttpServerRebuilt, openApiToPostmanCollection, originOf, ownOrigin, parseEntityTag, parseEntityTagList, parseLocaleDictionary, parseRoles, parseSites, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, purgeImageVariants, readSourceFile, readTranslationDeclarations, redactQueryCredentials, redactUrlCredentials, registerAppConfig, registerConfiguredConnectors, registerDevelopmentOpenApiProvider, registerGroupedTranslationKeys, registerHttpPlugins, registerLocaleDictionary, registerTracingHooks, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, reportUnguardedMutatingRoutes, requestContext, requestMemo, requiresDefaultCsrfGuard, resetHttpReadyReport, resetMailConfig, resetMailMode, resetRolesCacheForTests, resetTracingConfigForTests, resetUnguardedRouteReports, resolveCspConfig, resolveCsrfOriginVerdict, resolveImageVariant, resolveMailConfig, resolvePublicRoot, resolveRequestLoggingOptions, resolveSourceImport, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runDefaultCsrfGuard, runPipeline, safeFetchToBuffer, safeRedirect, sanitizePath, scanTranslationSource, secrets, seeder, sendBootSignal, sendMail, serializeCspDirectives, servesHttp, setBaseUrl, setClockSource, setConfig, setEnvironment, setHttpReadyReport, setIdsSource, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, strongEntityTagMatch, t, tempPath, toJson, toSingleLineSseField, trackConnectionsForDrain, translationDeclarationUsage, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, unregisterLocaleDictionary, unverifiedBuildRuntimeNotice, uploadedFileController, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, usageOf, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateConfigValue, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, weakEntityTagMatch, wrapResponseInDataKey };
@@ -1,4 +1,6 @@
1
1
  import { LocaleDictionaryError, parseLocaleDictionary } from "./parse-locale-dictionary.mjs";
2
2
  import { registerGroupedTranslationKeys, registerLocaleDictionary, unregisterLocaleDictionary } from "./register-locale-dictionary.mjs";
3
+ import { EMPTY_TRANSLATION_USAGE, isTranslationKeyUsed, mergeTranslationUsage, readTranslationDeclarations, scanTranslationSource, translationDeclarationUsage, usageOf } from "./translation-usage.mjs";
4
+ import { analyzePageTranslationUsage, analyzeTranslationGraph, readSourceFile, resolveSourceImport } from "./translation-usage-graph.mjs";
3
5
 
4
- export { LocaleDictionaryError, parseLocaleDictionary, registerGroupedTranslationKeys, registerLocaleDictionary, unregisterLocaleDictionary };
6
+ export { EMPTY_TRANSLATION_USAGE, LocaleDictionaryError, analyzePageTranslationUsage, analyzeTranslationGraph, isTranslationKeyUsed, mergeTranslationUsage, parseLocaleDictionary, readSourceFile, readTranslationDeclarations, registerGroupedTranslationKeys, registerLocaleDictionary, resolveSourceImport, scanTranslationSource, translationDeclarationUsage, unregisterLocaleDictionary, usageOf };
@@ -0,0 +1,49 @@
1
+ import { TranslationUsage } from "./translation-usage.mjs";
2
+ //#region ../../packages/core/src/localization/translation-usage-graph.d.ts
3
+ export type TranslationGraphInput = {
4
+ /** The client entry files a render can execute: the page, its layouts, the root and error pages. */
5
+ readonly entries: readonly string[];
6
+ /** Setup files whose `config.translations` declare keys static analysis cannot see. */
7
+ readonly setupFiles?: readonly string[];
8
+ /** Source text of a file, or `undefined` when it cannot be read. */
9
+ readonly readSource: (file: string) => string | undefined;
10
+ /** Resolves a specifier imported by `importer` to a project file, or `undefined` for a package. */
11
+ readonly resolveImport: (specifier: string, importer: string) => string | undefined;
12
+ };
13
+ export type TranslationGraphResult = {
14
+ /** The union of every reachable file's usage and the declared keys. */
15
+ readonly usage: TranslationUsage;
16
+ /** Every project file the walk read, so a caller can tell when the answer may have changed. */
17
+ readonly files: readonly string[];
18
+ };
19
+ /**
20
+ * Walk the client module graph from `entries` and union what every reachable
21
+ * file can look up.
22
+ *
23
+ * The walk follows value imports, re-exports and dynamic `import()` into
24
+ * project files only. A package is not followed: packages do not carry
25
+ * application translation keys. Fail closed: a reachable file that cannot be
26
+ * read or parsed makes the whole graph dynamic, so the caller ships everything
27
+ * rather than a set that might be missing a key.
28
+ */
29
+ export declare function analyzeTranslationGraph(input: TranslationGraphInput): TranslationGraphResult;
30
+ /**
31
+ * Resolve a specifier for the translation graph: relative paths, and the
32
+ * `web/` and `app/` conventions under the source root. Anything else is a
33
+ * package and resolves to `undefined`.
34
+ */
35
+ export declare function resolveSourceImport(specifier: string, importer: string, appSrcRoot: string): string | undefined;
36
+ /** Read a file as UTF-8, or `undefined` when it is missing or unreadable. */
37
+ export declare function readSourceFile(file: string): string | undefined;
38
+ /**
39
+ * Analyze a page's client graph against the filesystem: the convenience the
40
+ * build and the development server both use. `appSrcRoot` is the application's
41
+ * `src` directory, which the `web/` and `app/` specifiers resolve against.
42
+ */
43
+ export declare function analyzePageTranslationUsage(input: {
44
+ readonly appSrcRoot: string;
45
+ readonly entries: readonly string[];
46
+ readonly setupFiles?: readonly string[];
47
+ }): TranslationGraphResult;
48
+ //#endregion
49
+ //# sourceMappingURL=translation-usage-graph.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"translation-usage-graph.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/localization/translation-usage-graph.ts"],"mappings":";;YAkBY;;WAED;;WAEA;;WAEA,aAAa;;WAEb,gBAAgB,mBAAmB;;YAGlC;;WAED,OAAO;;WAEP;;;;;;;;;;;;wBAaK,wBAAwB,OAAO,wBAAwB;;;;;;wBAqEvD,oBACd,mBACA,kBACA;;wBAiCc,eAAe;;;;;;wBAaf,4BAA4B;WACjC;WACA;WACA;IACP"}
@@ -0,0 +1,128 @@
1
+ import { EMPTY_TRANSLATION_USAGE, mergeTranslationUsage, readTranslationDeclarations, scanTranslationSource, translationDeclarationUsage, usageOf } from "./translation-usage.mjs";
2
+ import path from "node:path";
3
+ import fsSync from "node:fs";
4
+
5
+ //#region ../../packages/core/src/localization/translation-usage-graph.ts
6
+ /** Source files the walk reads. */
7
+ const CODE_FILE = /\.[cm]?[jt]sx?$/;
8
+ /** Extensions tried, in order, for an extension-less specifier. */
9
+ const SOURCE_EXTENSIONS = [
10
+ ".ts",
11
+ ".tsx",
12
+ ".mts",
13
+ ".js",
14
+ ".jsx",
15
+ ".mjs"
16
+ ];
17
+ /**
18
+ * Walk the client module graph from `entries` and union what every reachable
19
+ * file can look up.
20
+ *
21
+ * The walk follows value imports, re-exports and dynamic `import()` into
22
+ * project files only. A package is not followed: packages do not carry
23
+ * application translation keys. Fail closed: a reachable file that cannot be
24
+ * read or parsed makes the whole graph dynamic, so the caller ships everything
25
+ * rather than a set that might be missing a key.
26
+ */
27
+ function analyzeTranslationGraph(input) {
28
+ const seen = /* @__PURE__ */ new Set();
29
+ const files = [];
30
+ const usages = [];
31
+ const queue = [...input.entries];
32
+ for (const setupFile of input.setupFiles ?? []) {
33
+ files.push(setupFile);
34
+ usages.push(readDeclarations(input, setupFile));
35
+ }
36
+ for (let file = queue.pop(); file !== void 0; file = queue.pop()) {
37
+ if (seen.has(file)) continue;
38
+ seen.add(file);
39
+ files.push(file);
40
+ const text = input.readSource(file);
41
+ if (text === void 0) {
42
+ usages.push(unreadable(file, "the file could not be read"));
43
+ continue;
44
+ }
45
+ try {
46
+ const scan = scanTranslationSource(file, text);
47
+ usages.push(scan.usage);
48
+ for (const specifier of scan.imports) {
49
+ const resolved = input.resolveImport(specifier, file);
50
+ if (resolved !== void 0 && !seen.has(resolved)) queue.push(resolved);
51
+ }
52
+ } catch (error) {
53
+ usages.push(unreadable(file, `the file could not be parsed (${error instanceof Error ? error.message : String(error)})`));
54
+ }
55
+ }
56
+ return {
57
+ usage: mergeTranslationUsage(usages),
58
+ files
59
+ };
60
+ }
61
+ function readDeclarations(input, setupFile) {
62
+ const text = input.readSource(setupFile);
63
+ if (text === void 0) return unreadable(setupFile, "the setup file could not be read");
64
+ const entries = readTranslationDeclarations(setupFile, text);
65
+ if (entries === void 0) return EMPTY_TRANSLATION_USAGE;
66
+ return mergeTranslationUsage(entries.map((entry) => translationDeclarationUsage(entry, setupFile)));
67
+ }
68
+ /** A dynamic usage that names the file which forced it. */
69
+ function unreadable(file, reason) {
70
+ return usageOf({
71
+ dynamic: true,
72
+ dynamicSites: [{
73
+ file,
74
+ line: 1,
75
+ column: 1,
76
+ text: `<${reason}>`
77
+ }]
78
+ });
79
+ }
80
+ /**
81
+ * Resolve a specifier for the translation graph: relative paths, and the
82
+ * `web/` and `app/` conventions under the source root. Anything else is a
83
+ * package and resolves to `undefined`.
84
+ */
85
+ function resolveSourceImport(specifier, importer, appSrcRoot) {
86
+ let base;
87
+ if (specifier.startsWith(".")) base = path.resolve(path.dirname(importer), specifier);
88
+ else if (specifier.startsWith("web/") || specifier.startsWith("app/")) base = path.join(appSrcRoot, specifier);
89
+ else return;
90
+ const candidates = [
91
+ base,
92
+ ...SOURCE_EXTENSIONS.map((extension) => `${base}${extension}`),
93
+ ...SOURCE_EXTENSIONS.map((extension) => path.join(base, `index${extension}`))
94
+ ];
95
+ if (/\.jsx?$/.test(base)) {
96
+ const stripped = base.replace(/\.jsx?$/, "");
97
+ candidates.push(...SOURCE_EXTENSIONS.map((extension) => `${stripped}${extension}`));
98
+ }
99
+ return candidates.find((candidate) => CODE_FILE.test(candidate) && isFile(candidate));
100
+ }
101
+ function isFile(candidate) {
102
+ return fsSync.statSync(candidate, { throwIfNoEntry: false })?.isFile() === true;
103
+ }
104
+ /** Read a file as UTF-8, or `undefined` when it is missing or unreadable. */
105
+ function readSourceFile(file) {
106
+ try {
107
+ return fsSync.readFileSync(file, "utf8");
108
+ } catch {
109
+ return;
110
+ }
111
+ }
112
+ /**
113
+ * Analyze a page's client graph against the filesystem: the convenience the
114
+ * build and the development server both use. `appSrcRoot` is the application's
115
+ * `src` directory, which the `web/` and `app/` specifiers resolve against.
116
+ */
117
+ function analyzePageTranslationUsage(input) {
118
+ return analyzeTranslationGraph({
119
+ entries: input.entries,
120
+ setupFiles: input.setupFiles,
121
+ readSource: readSourceFile,
122
+ resolveImport: (specifier, importer) => resolveSourceImport(specifier, importer, input.appSrcRoot)
123
+ });
124
+ }
125
+
126
+ //#endregion
127
+ export { analyzePageTranslationUsage, analyzeTranslationGraph, readSourceFile, resolveSourceImport };
128
+ //# sourceMappingURL=translation-usage-graph.mjs.map