@warlock.js/core 5.11.0 → 5.12.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 (129) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/esm/application/app.d.mts +3 -3
  3. package/esm/application/app.mjs +6 -6
  4. package/esm/application/app.mjs.map +1 -1
  5. package/esm/cli/cli-commands.utils.mjs +7 -3
  6. package/esm/cli/cli-commands.utils.mjs.map +1 -1
  7. package/esm/cli/commands/doctor/checks/health.check.mjs +1 -1
  8. package/esm/cli/commands/doctor/checks/health.check.mjs.map +1 -1
  9. package/esm/connectors/socket-connector.mjs +13 -16
  10. package/esm/connectors/socket-connector.mjs.map +1 -1
  11. package/esm/container/index.d.mts +20 -7
  12. package/esm/container/index.d.mts.map +1 -1
  13. package/esm/container/index.mjs +8 -5
  14. package/esm/container/index.mjs.map +1 -1
  15. package/esm/dev-server/dev-logger.mjs +12 -1
  16. package/esm/dev-server/dev-logger.mjs.map +1 -1
  17. package/esm/dev-server/development-server.mjs +1 -1
  18. package/esm/dev-server/development-server.mjs.map +1 -1
  19. package/esm/dev-server/file-event-handler.mjs +49 -8
  20. package/esm/dev-server/file-event-handler.mjs.map +1 -1
  21. package/esm/dev-server/file-manager.d.mts +8 -0
  22. package/esm/dev-server/file-manager.d.mts.map +1 -1
  23. package/esm/dev-server/file-manager.mjs +26 -4
  24. package/esm/dev-server/file-manager.mjs.map +1 -1
  25. package/esm/dev-server/files-orchestrator.mjs +3 -3
  26. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  27. package/esm/dev-server/files-watcher.mjs +16 -2
  28. package/esm/dev-server/files-watcher.mjs.map +1 -1
  29. package/esm/dev-server/flags.mjs +16 -1
  30. package/esm/dev-server/flags.mjs.map +1 -1
  31. package/esm/dev-server/layer-executor.mjs +19 -2
  32. package/esm/dev-server/layer-executor.mjs.map +1 -1
  33. package/esm/errors/container-key-missing-error.mjs +18 -6
  34. package/esm/errors/container-key-missing-error.mjs.map +1 -1
  35. package/esm/generations/stubs.mjs +10 -10
  36. package/esm/generations/stubs.mjs.map +1 -1
  37. package/esm/http/context/request-context.d.mts +14 -11
  38. package/esm/http/context/request-context.d.mts.map +1 -1
  39. package/esm/http/context/request-context.mjs +13 -9
  40. package/esm/http/context/request-context.mjs.map +1 -1
  41. package/esm/http/createHttpApplication.d.mts.map +1 -1
  42. package/esm/http/createHttpApplication.mjs +2 -0
  43. package/esm/http/createHttpApplication.mjs.map +1 -1
  44. package/esm/http/csp.d.mts +139 -0
  45. package/esm/http/csp.d.mts.map +1 -0
  46. package/esm/http/csp.mjs +134 -0
  47. package/esm/http/csp.mjs.map +1 -0
  48. package/esm/http/errors/errors.d.mts +17 -1
  49. package/esm/http/errors/errors.d.mts.map +1 -1
  50. package/esm/http/errors/errors.mjs +20 -1
  51. package/esm/http/errors/errors.mjs.map +1 -1
  52. package/esm/http/index.d.mts +8 -3
  53. package/esm/http/index.mjs +6 -1
  54. package/esm/http/middleware/concurrency-limit.middleware.d.mts +2 -2
  55. package/esm/http/middleware/concurrency-limit.middleware.mjs +1 -1
  56. package/esm/http/middleware/concurrency-limit.middleware.mjs.map +1 -1
  57. package/esm/http/middleware/inject-request-context.d.mts +1 -1
  58. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  59. package/esm/http/middleware/inject-request-context.mjs +10 -0
  60. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  61. package/esm/http/middleware/rate-limit.middleware.d.mts +1 -1
  62. package/esm/http/middleware/rate-limit.middleware.mjs.map +1 -1
  63. package/esm/http/middleware/utils/idempotency-key.d.mts.map +1 -1
  64. package/esm/http/middleware/utils/idempotency-key.mjs +13 -13
  65. package/esm/http/middleware/utils/idempotency-key.mjs.map +1 -1
  66. package/esm/http/request-controller.d.mts +1 -1
  67. package/esm/http/request.d.mts +32 -44
  68. package/esm/http/request.d.mts.map +1 -1
  69. package/esm/http/request.mjs +52 -44
  70. package/esm/http/request.mjs.map +1 -1
  71. package/esm/http/response.d.mts +18 -0
  72. package/esm/http/response.d.mts.map +1 -1
  73. package/esm/http/response.mjs +31 -0
  74. package/esm/http/response.mjs.map +1 -1
  75. package/esm/http/stream-react-response.d.mts +65 -0
  76. package/esm/http/stream-react-response.d.mts.map +1 -0
  77. package/esm/http/stream-react-response.mjs +46 -0
  78. package/esm/http/stream-react-response.mjs.map +1 -0
  79. package/esm/http/tracing/index.mjs +4 -0
  80. package/esm/http/tracing/trace-id.d.mts +14 -0
  81. package/esm/http/tracing/trace-id.d.mts.map +1 -0
  82. package/esm/http/tracing/trace-id.mjs +37 -0
  83. package/esm/http/tracing/trace-id.mjs.map +1 -0
  84. package/esm/http/tracing/tracing-dispatcher.d.mts +42 -0
  85. package/esm/http/tracing/tracing-dispatcher.d.mts.map +1 -0
  86. package/esm/http/tracing/tracing-dispatcher.mjs +94 -0
  87. package/esm/http/tracing/tracing-dispatcher.mjs.map +1 -0
  88. package/esm/http/tracing/tracing.type.d.mts +66 -0
  89. package/esm/http/tracing/tracing.type.d.mts.map +1 -0
  90. package/esm/http/types.d.mts +27 -21
  91. package/esm/http/types.d.mts.map +1 -1
  92. package/esm/index.d.mts +9 -4
  93. package/esm/index.mjs +6 -2
  94. package/esm/production/esbuild-preflight.mjs +47 -0
  95. package/esm/production/esbuild-preflight.mjs.map +1 -0
  96. package/esm/production/production-builder.mjs +19 -15
  97. package/esm/production/production-builder.mjs.map +1 -1
  98. package/esm/restful/restful.d.mts +1 -1
  99. package/esm/router/log-request-lifecycle.mjs +12 -2
  100. package/esm/router/log-request-lifecycle.mjs.map +1 -1
  101. package/esm/router/router.d.mts.map +1 -1
  102. package/esm/router/router.mjs +10 -0
  103. package/esm/router/router.mjs.map +1 -1
  104. package/esm/router/types.d.mts +1 -1
  105. package/esm/socket/utils.mjs +1 -2
  106. package/esm/socket/utils.mjs.map +1 -1
  107. package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
  108. package/esm/storage/drivers/cloud-driver.mjs +2 -5
  109. package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
  110. package/esm/warlock-config/types.d.mts +12 -0
  111. package/esm/warlock-config/types.d.mts.map +1 -1
  112. package/llms-full.txt +290 -25
  113. package/llms.txt +1 -0
  114. package/package.json +12 -12
  115. package/skills/add-connector/SKILL.md +1 -1
  116. package/skills/build-restful/SKILL.md +2 -2
  117. package/skills/configure-app/SKILL.md +31 -0
  118. package/skills/create-controller/SKILL.md +4 -4
  119. package/skills/request-tracing/SKILL.md +208 -0
  120. package/skills/send-response/SKILL.md +16 -0
  121. package/skills/store-file/SKILL.md +1 -1
  122. package/skills/upload-file/SKILL.md +2 -2
  123. package/skills/use-app-context/SKILL.md +2 -2
  124. package/skills/use-middleware/SKILL.md +2 -2
  125. package/skills/use-repository/SKILL.md +1 -1
  126. package/skills/use-request-locals/SKILL.md +1 -1
  127. package/skills/wire-socket/SKILL.md +3 -3
  128. package/skills/write-middleware/SKILL.md +11 -5
  129. package/skills/write-use-case/SKILL.md +1 -1
@@ -0,0 +1,94 @@
1
+ import config from "@mongez/config";
2
+ import { log } from "@warlock.js/logger";
3
+
4
+ //#region ../core/src/http/tracing/tracing-dispatcher.ts
5
+ /**
6
+ * Tracing hook dispatch.
7
+ *
8
+ * `http.tracing` is resolved once — lazily, on first read, then cached for
9
+ * the life of the process — never per request. Every call site gates on
10
+ * `isTracingEnabled()` BEFORE doing anything else (building a context
11
+ * object, calling `performance.now()`), so a disabled app pays exactly one
12
+ * boolean check per call site and never allocates the attrs/context payload.
13
+ */
14
+ let resolved;
15
+ /**
16
+ * Resolve `http.tracing` once per process and cache it. Safe to call from
17
+ * every hot-path call site — after the first call this is a plain field
18
+ * read, no config lookup.
19
+ */
20
+ function resolveTracingConfig() {
21
+ if (resolved) return resolved;
22
+ const tracing = config.get("http.tracing", {}) ?? {};
23
+ resolved = {
24
+ enabled: tracing.enabled === true,
25
+ hooks: tracing.hooks ?? []
26
+ };
27
+ return resolved;
28
+ }
29
+ /** The single boolean check every instrumented call site guards on. */
30
+ function isTracingEnabled() {
31
+ return resolveTracingConfig().enabled;
32
+ }
33
+ /** Test-only: forces the next `resolveTracingConfig()` call to re-read config. */
34
+ function resetTracingConfigForTests() {
35
+ resolved = void 0;
36
+ reportedHooks = /* @__PURE__ */ new WeakMap();
37
+ }
38
+ /** Build the per-request context handed to every hook call. */
39
+ function buildTracingContext(request) {
40
+ return {
41
+ traceId: request.traceId,
42
+ requestId: request.id,
43
+ method: request.method,
44
+ route: request.route?.path,
45
+ path: request.path
46
+ };
47
+ }
48
+ /**
49
+ * Tracks which (hook, verb) pairs have already been reported, so a hook that
50
+ * throws on every request is reported to the error sink exactly once per
51
+ * process rather than flooding it.
52
+ */
53
+ let reportedHooks = /* @__PURE__ */ new WeakMap();
54
+ function reportHookErrorOnce(hook, verb, error) {
55
+ let reportedVerbs = reportedHooks.get(hook);
56
+ if (!reportedVerbs) {
57
+ reportedVerbs = /* @__PURE__ */ new Set();
58
+ reportedHooks.set(hook, reportedVerbs);
59
+ }
60
+ if (reportedVerbs.has(verb)) return;
61
+ reportedVerbs.add(verb);
62
+ log.error("http", "tracing-hook", error, { hook: verb });
63
+ }
64
+ function safeInvoke(hook, verb, invoke) {
65
+ const fn = hook[verb];
66
+ if (!fn) return;
67
+ try {
68
+ invoke(fn);
69
+ } catch (error) {
70
+ reportHookErrorOnce(hook, verb, error);
71
+ }
72
+ }
73
+ /** Dispatch `onRequestStart` to every configured hook. No-op when disabled. */
74
+ function dispatchRequestStart(ctx) {
75
+ const { enabled, hooks } = resolveTracingConfig();
76
+ if (!enabled) return;
77
+ for (const hook of hooks) safeInvoke(hook, "onRequestStart", (fn) => fn(ctx));
78
+ }
79
+ /** Dispatch `onRequestEnd` to every configured hook. No-op when disabled. */
80
+ function dispatchRequestEnd(ctx, result) {
81
+ const { enabled, hooks } = resolveTracingConfig();
82
+ if (!enabled) return;
83
+ for (const hook of hooks) safeInvoke(hook, "onRequestEnd", (fn) => fn(ctx, result));
84
+ }
85
+ /** Dispatch `onPhase` to every configured hook. No-op when disabled. */
86
+ function dispatchPhase(ctx, phase) {
87
+ const { enabled, hooks } = resolveTracingConfig();
88
+ if (!enabled) return;
89
+ for (const hook of hooks) safeInvoke(hook, "onPhase", (fn) => fn(ctx, phase));
90
+ }
91
+
92
+ //#endregion
93
+ export { buildTracingContext, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled, resetTracingConfigForTests, resolveTracingConfig };
94
+ //# sourceMappingURL=tracing-dispatcher.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracing-dispatcher.mjs","names":[],"sources":["../../../../../../../../core/src/http/tracing/tracing-dispatcher.ts"],"sourcesContent":["/**\n * Tracing hook dispatch.\n *\n * `http.tracing` is resolved once — lazily, on first read, then cached for\n * the life of the process — never per request. Every call site gates on\n * `isTracingEnabled()` BEFORE doing anything else (building a context\n * object, calling `performance.now()`), so a disabled app pays exactly one\n * boolean check per call site and never allocates the attrs/context payload.\n */\nimport config from \"@mongez/config\";\nimport { log } from \"@warlock.js/logger\";\nimport type {\n HttpTracingConfig,\n TracingContext,\n TracingHooks,\n TracingPhaseInfo,\n TracingRequestEndInfo,\n} from \"./tracing.type\";\n\ntype ResolvedTracing = {\n enabled: boolean;\n hooks: TracingHooks[];\n};\n\nlet resolved: ResolvedTracing | undefined;\n\n/**\n * Minimal request shape `buildTracingContext` needs. Kept structural (not a\n * `Request` import) so this module never creates an import cycle with\n * `../request`, which itself calls into this module.\n */\nexport type TracingContextSource = {\n traceId: string;\n id: string;\n method: string;\n path: string;\n route?: { path: string };\n};\n\n/**\n * Resolve `http.tracing` once per process and cache it. Safe to call from\n * every hot-path call site — after the first call this is a plain field\n * read, no config lookup.\n */\nexport function resolveTracingConfig(): ResolvedTracing {\n if (resolved) return resolved;\n\n const tracing = config.get(\"http.tracing\", {} as HttpTracingConfig) ?? {};\n\n resolved = {\n enabled: tracing.enabled === true,\n hooks: tracing.hooks ?? [],\n };\n\n return resolved;\n}\n\n/** The single boolean check every instrumented call site guards on. */\nexport function isTracingEnabled(): boolean {\n return resolveTracingConfig().enabled;\n}\n\n/** Test-only: forces the next `resolveTracingConfig()` call to re-read config. */\nexport function resetTracingConfigForTests(): void {\n resolved = undefined;\n reportedHooks = new WeakMap();\n}\n\n/** Build the per-request context handed to every hook call. */\nexport function buildTracingContext(request: TracingContextSource): TracingContext {\n return {\n traceId: request.traceId,\n requestId: request.id,\n method: request.method,\n route: request.route?.path,\n path: request.path,\n };\n}\n\n/**\n * Tracks which (hook, verb) pairs have already been reported, so a hook that\n * throws on every request is reported to the error sink exactly once per\n * process rather than flooding it.\n */\nlet reportedHooks = new WeakMap<TracingHooks, Set<string>>();\n\nfunction reportHookErrorOnce(hook: TracingHooks, verb: string, error: unknown): void {\n let reportedVerbs = reportedHooks.get(hook);\n\n if (!reportedVerbs) {\n reportedVerbs = new Set();\n reportedHooks.set(hook, reportedVerbs);\n }\n\n if (reportedVerbs.has(verb)) return;\n\n reportedVerbs.add(verb);\n\n // Never swallow the only copy of an error — but a throwing hook must never\n // break the request it was only meant to observe, so this is reported, not\n // re-thrown.\n log.error(\"http\", \"tracing-hook\", error, { hook: verb });\n}\n\nfunction safeInvoke<Verb extends keyof TracingHooks>(\n hook: TracingHooks,\n verb: Verb,\n invoke: (fn: NonNullable<TracingHooks[Verb]>) => void,\n): void {\n const fn = hook[verb];\n\n if (!fn) return;\n\n try {\n invoke(fn as NonNullable<TracingHooks[Verb]>);\n } catch (error) {\n reportHookErrorOnce(hook, verb, error);\n }\n}\n\n/** Dispatch `onRequestStart` to every configured hook. No-op when disabled. */\nexport function dispatchRequestStart(ctx: TracingContext): void {\n const { enabled, hooks } = resolveTracingConfig();\n\n if (!enabled) return;\n\n for (const hook of hooks) {\n safeInvoke(hook, \"onRequestStart\", (fn) => fn(ctx));\n }\n}\n\n/** Dispatch `onRequestEnd` to every configured hook. No-op when disabled. */\nexport function dispatchRequestEnd(ctx: TracingContext, result: TracingRequestEndInfo): void {\n const { enabled, hooks } = resolveTracingConfig();\n\n if (!enabled) return;\n\n for (const hook of hooks) {\n safeInvoke(hook, \"onRequestEnd\", (fn) => fn(ctx, result));\n }\n}\n\n/** Dispatch `onPhase` to every configured hook. No-op when disabled. */\nexport function dispatchPhase(ctx: TracingContext, phase: TracingPhaseInfo): void {\n const { enabled, hooks } = resolveTracingConfig();\n\n if (!enabled) return;\n\n for (const hook of hooks) {\n safeInvoke(hook, \"onPhase\", (fn) => fn(ctx, phase));\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,IAAI;;;;;;AAoBJ,SAAgB,uBAAwC;CACtD,IAAI,UAAU,OAAO;CAErB,MAAM,UAAU,OAAO,IAAI,gBAAgB,CAAC,CAAsB,KAAK,CAAC;CAExE,WAAW;EACT,SAAS,QAAQ,YAAY;EAC7B,OAAO,QAAQ,SAAS,CAAC;CAC3B;CAEA,OAAO;AACT;;AAGA,SAAgB,mBAA4B;CAC1C,OAAO,qBAAqB,CAAC,CAAC;AAChC;;AAGA,SAAgB,6BAAmC;CACjD,WAAW;CACX,gCAAgB,IAAI,QAAQ;AAC9B;;AAGA,SAAgB,oBAAoB,SAA+C;CACjF,OAAO;EACL,SAAS,QAAQ;EACjB,WAAW,QAAQ;EACnB,QAAQ,QAAQ;EAChB,OAAO,QAAQ,OAAO;EACtB,MAAM,QAAQ;CAChB;AACF;;;;;;AAOA,IAAI,gCAAgB,IAAI,QAAmC;AAE3D,SAAS,oBAAoB,MAAoB,MAAc,OAAsB;CACnF,IAAI,gBAAgB,cAAc,IAAI,IAAI;CAE1C,IAAI,CAAC,eAAe;EAClB,gCAAgB,IAAI,IAAI;EACxB,cAAc,IAAI,MAAM,aAAa;CACvC;CAEA,IAAI,cAAc,IAAI,IAAI,GAAG;CAE7B,cAAc,IAAI,IAAI;CAKtB,IAAI,MAAM,QAAQ,gBAAgB,OAAO,EAAE,MAAM,KAAK,CAAC;AACzD;AAEA,SAAS,WACP,MACA,MACA,QACM;CACN,MAAM,KAAK,KAAK;CAEhB,IAAI,CAAC,IAAI;CAET,IAAI;EACF,OAAO,EAAqC;CAC9C,SAAS,OAAO;EACd,oBAAoB,MAAM,MAAM,KAAK;CACvC;AACF;;AAGA,SAAgB,qBAAqB,KAA2B;CAC9D,MAAM,EAAE,SAAS,UAAU,qBAAqB;CAEhD,IAAI,CAAC,SAAS;CAEd,KAAK,MAAM,QAAQ,OACjB,WAAW,MAAM,mBAAmB,OAAO,GAAG,GAAG,CAAC;AAEtD;;AAGA,SAAgB,mBAAmB,KAAqB,QAAqC;CAC3F,MAAM,EAAE,SAAS,UAAU,qBAAqB;CAEhD,IAAI,CAAC,SAAS;CAEd,KAAK,MAAM,QAAQ,OACjB,WAAW,MAAM,iBAAiB,OAAO,GAAG,KAAK,MAAM,CAAC;AAE5D;;AAGA,SAAgB,cAAc,KAAqB,OAA+B;CAChF,MAAM,EAAE,SAAS,UAAU,qBAAqB;CAEhD,IAAI,CAAC,SAAS;CAEd,KAAK,MAAM,QAAQ,OACjB,WAAW,MAAM,YAAY,OAAO,GAAG,KAAK,KAAK,CAAC;AAEtD"}
@@ -0,0 +1,66 @@
1
+ //#region ../core/src/http/tracing/tracing.type.d.ts
2
+ /**
3
+ * Vendor-neutral request-tracing hook surface.
4
+ *
5
+ * `core` exposes this four-verb shape and stays framework-agnostic — no
6
+ * `@opentelemetry/api` dependency here, ever. Introducing a hard OTel
7
+ * dependency in `core` would push it onto every consumer of the framework,
8
+ * including apps that use a different tracer or none. An OTel (or any other
9
+ * vendor) bridge is a separate, optional package that subscribes to these
10
+ * hooks instead.
11
+ */
12
+ /**
13
+ * Per-request identity threaded through every hook call. `route` is the
14
+ * matched pattern (e.g. `/users/:id`), not the resolved path, so hooks can
15
+ * group by endpoint rather than by every distinct id a client happened to
16
+ * request; it is `undefined` until routing has matched (there is no path
17
+ * where a hook fires before that).
18
+ */
19
+ type TracingContext = {
20
+ /**
21
+ * A valid inbound W3C `traceparent` trace id when present, otherwise
22
+ * `request.id`. See `resolveTraceId` in `./trace-id.ts`.
23
+ */
24
+ traceId: string; /** `request.id` — the framework's own per-request correlation id. */
25
+ requestId: string;
26
+ method: string;
27
+ route?: string;
28
+ path: string;
29
+ };
30
+ /** Payload passed to `onPhase` for a single named phase of the request. */
31
+ type TracingPhaseInfo = {
32
+ name: string;
33
+ durationMs: number;
34
+ attrs?: Record<string, unknown>;
35
+ };
36
+ /** Payload passed to `onRequestEnd` once the request has settled. */
37
+ type TracingRequestEndInfo = {
38
+ status?: number;
39
+ durationMs: number;
40
+ error?: unknown;
41
+ };
42
+ /**
43
+ * A single tracing observer. Every verb is optional — a hook that only cares
44
+ * about phase spans need not implement `onRequestStart`/`onRequestEnd`.
45
+ *
46
+ * A throwing hook never breaks the request: the dispatcher catches it and
47
+ * reports it once per hook per process to the error sink, then continues.
48
+ */
49
+ type TracingHooks = {
50
+ onRequestStart?(ctx: TracingContext): void;
51
+ onRequestEnd?(ctx: TracingContext, result: TracingRequestEndInfo): void;
52
+ onPhase?(ctx: TracingContext, phase: TracingPhaseInfo): void;
53
+ };
54
+ /**
55
+ * `http.tracing` configuration. OFF by default — resolved once at boot (see
56
+ * `resolveTracingConfig` in `./tracing-dispatcher.ts`), so a disabled app
57
+ * pays a single cached boolean read per call site, never a per-request
58
+ * config lookup.
59
+ */
60
+ type HttpTracingConfig = {
61
+ /** @default false */enabled?: boolean;
62
+ hooks?: TracingHooks[];
63
+ };
64
+ //#endregion
65
+ export { HttpTracingConfig, TracingContext, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo };
66
+ //# sourceMappingURL=tracing.type.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracing.type.d.mts","names":[],"sources":["../../../../../../../../core/src/http/tracing/tracing.type.ts"],"mappings":";;AAkBA;;;;;;;;;;AAUM;AAIN;;;;;KAdY,cAAA;EAiBV;;;AAAc;EAZd,OAAA,UAgB+B;EAd/B,SAAA;EACA,MAAA;EACA,KAAA;EACA,IAAA;AAAA;;KAIU,gBAAA;EACV,IAAA;EACA,UAAA;EACA,KAAA,GAAQ,MAAM;AAAA;;KAIJ,qBAAA;EACV,MAAA;EACA,UAAA;EACA,KAAA;AAAA;;;;;;;;KAUU,YAAA;EACV,cAAA,EAAgB,GAAA,EAAK,cAAA;EACrB,YAAA,EAAc,GAAA,EAAK,cAAA,EAAgB,MAAA,EAAQ,qBAAA;EAC3C,OAAA,EAAS,GAAA,EAAK,cAAA,EAAgB,KAAA,EAAO,gBAAA;AAAA;;;AAAgB;AASvD;;;KAAY,iBAAA;EAEV,qBAAA,OAAA;EACA,KAAA,GAAQ,YAAY;AAAA"}
@@ -1,4 +1,6 @@
1
1
  import { Response } from "./response.mjs";
2
+ import { CspConfig } from "./csp.mjs";
3
+ import { HttpTracingConfig } from "./tracing/tracing.type.mjs";
2
4
  import { Middleware } from "../router/types.mjs";
3
5
  import { CookieSerializeOptions } from "@fastify/cookie";
4
6
  import { FastifyCorsOptions } from "@fastify/cors";
@@ -31,32 +33,20 @@ type RequestEvent = "executingMiddleware" | "executedMiddleware" | "executingAct
31
33
  */
32
34
  interface RequestLocals {
33
35
  /**
34
- * Whether this request has, at any point, been assigned a `user` or a
35
- * `decodedAccessToken` — set by their accessors in `request.ts`, never by
36
+ * Whether this request has, at any point, been assigned a
37
+ * `decodedAccessToken` — set by its accessor in `request.ts`, never by
36
38
  * anything else, and never cleared once set. Absent (not `false`) on a
37
39
  * request that never touched auth state; a later stage reads this to
38
40
  * decide cache headers, but that stage is not this one.
41
+ *
42
+ * `@warlock.js/auth` writes the authenticated user to `locals.user` (a key
43
+ * it augments onto this interface — see `RequestUser` in that package) but
44
+ * does not set `authDerived` when doing so; only `decodedAccessToken`
45
+ * marks this flag. Core intentionally does not restore a user-triggered
46
+ * cache mark here (see the 5.12.0 CHANGELOG for the design ruling).
39
47
  */
40
48
  authDerived?: boolean;
41
49
  }
42
- /**
43
- * The authenticated user attached to the current request — `request.user`.
44
- *
45
- * Empty by default so any shape is assignable at the declaration site;
46
- * apps/packages narrow it via module augmentation instead of the v4
47
- * `GuardedRequest` intersection type (`Request<T> & { user: User }`,
48
- * hand-declared per app):
49
- *
50
- * @example
51
- * ```typescript
52
- * declare module "@warlock.js/core" {
53
- * interface RequestUser {
54
- * id: string | number;
55
- * }
56
- * }
57
- * ```
58
- */
59
- interface RequestUser {}
60
50
  /**
61
51
  * Decoded access-token claims attached to the current request —
62
52
  * `request.decodedAccessToken`.
@@ -246,6 +236,16 @@ interface HttpConfigurations {
246
236
  */
247
237
  options?: CookieSerializeOptions;
248
238
  };
239
+ /**
240
+ * Opt-in `Content-Security-Policy` header, built per-request from a
241
+ * documented default policy merged with these directives, plus the
242
+ * framework's own per-request CSP nonce on `script-src`.
243
+ *
244
+ * Disabled by default — no header, no behaviour change — until `enabled`
245
+ * is set `true`. See `csp.ts` for the default policy and merge rules, and
246
+ * the `configure-app` / `send-response` skills for usage.
247
+ */
248
+ csp?: CspConfig;
249
249
  /**
250
250
  * Rate limit
251
251
  */
@@ -407,6 +407,12 @@ interface HttpConfigurations {
407
407
  */
408
408
  except?: PartialMiddleware;
409
409
  };
410
+ /**
411
+ * Opt-in request tracing hooks. OFF by default; resolved
412
+ * once at boot, not per request — see `resolveTracingConfig` in
413
+ * `./tracing/tracing-dispatcher.ts`.
414
+ */
415
+ tracing?: HttpTracingConfig;
410
416
  }
411
417
  type ResponseStreamController = {
412
418
  /**
@@ -453,5 +459,5 @@ type ResponseSSEController = {
453
459
  ended: boolean;
454
460
  };
455
461
  //#endregion
456
- export { DecodedAccessToken, HttpConfigurations, PartialMiddleware, RequestEvent, RequestLocals, RequestUser, ResponseEvent, ResponseSSEController, ResponseStreamController, ReturnedResponse };
462
+ export { DecodedAccessToken, HttpConfigurations, PartialMiddleware, RequestEvent, RequestLocals, ResponseEvent, ResponseSSEController, ResponseStreamController, ReturnedResponse };
457
463
  //# sourceMappingURL=types.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../core/src/http/types.ts"],"mappings":";;;;;;;KAMY,YAAA;;;AAAZ;;;;AAAwB;AA0BxB;;;;AAQa;AAoBb;;;;AAA4B;AAc5B;;;;AACU;AAMV;UAjDiB,aAAA;;;;;;;;EAQf,WAAW;AAAA;;;;;;;;;;AAiEF;AAKX;;;;AAAyB;AAiEzB;;UAnHiB,WAAA;;;;;;AAkIO;AAMxB;;;;;;KA1HY,kBAAA;EACV,QAAQ;AAAA;;;;KAME,gBAAA;;;;AAIR;;;;EAIA,OAAA,CAAQ,QAAA;;;;EAIR,MAAA;;;;EAIA,OAAA,CAAQ,MAAA;;;;;;;;EAQR,OAAA;;;;KAKQ,aAAA;;;;;;;;;;;;;;;AAgTkB;;;;;;;;;;;;;;AAoBvB;AAGP;;AAHO;;;;;;;;;;;;;;;;;;;;;;AA2BA;;;;;;;;;;UA9RU,iBAAA;;;;;EAKf,MAAA;;;;;;EAMA,WAAA;;;;EAIA,UAAA,EAAY,UAAU;AAAA;;;;UAMP,kBAAA;;;;EAIf,IAAA;;;;EAIA,GAAA;;;;EAIA,IAAA,GAAO,kBAAA;;;;;;EAMP,eAAA;;;;;;;;;;EAUA,SAAA;;;;;;;;;;;;;;;;;;;;EAoBA,UAAA,mCAA6C,OAAA,UAAiB,GAAA;EAC9D,OAAA;;;;IAIE,MAAA;;;;IAIA,OAAA,GAAU,sBAAA;EAAA;;;;EAKZ,SAAA;;;;;;IAME,GAAA;;;;;;IAMA,QAAA;EAAA;;;;;;;;EASF,SAAA;;;;;;IAME,MAAA;;;;IAIA,SAAA;;;;;;;IAOA,OAAA;EAAA;;;;EAKF,WAAA;;;;;;IAME,GAAA;;;;;;IAMA,UAAA;;;;;;;IAOA,OAAA;;;;IAIA,MAAA;EAAA;;;;EAKF,WAAA;;;;;;;IAOE,OAAA;;;;;;IAMA,SAAA;;;;;;IAMA,UAAA;EAAA;;;;EAKF,gBAAA;;;;;;;IAOE,OAAA;;;;;;;;IAQA,qBAAA;EAAA;;;;EAKF,MAAA;;;;;;IAME,OAAA;;;;;;;IAOA,IAAA;;;;;;;IAOA,aAAA;EAAA;;;;EAKF,IAAA;;;;EAIA,UAAA;;;;IAIE,GAAA,GAAM,UAAA;;;;IAIN,IAAA,GAAO,iBAAA;;;;IAIP,MAAA,GAAS,iBAAA;EAAA;AAAA;AAAA,KAID,wBAAA;;;;EAIV,IAAA,GAAO,IAAA;;;;EAIP,MAAA,GAAS,IAAA,EAAM,KAAA,CAAM,SAAS;;;;EAI9B,GAAA;;;;EAIA,KAAA;AAAA;AAAA,KAGU,qBAAA;;;;;;;EAOV,IAAA,GAAO,KAAA,UAAe,IAAA,OAAW,EAAA,cAAgB,qBAAA;;;;EAIjD,OAAA,GAAU,OAAA,aAAoB,qBAAA;;;;EAI9B,GAAA,QAAW,qBAAA;;;;;EAKX,YAAA,GAAe,OAAA,iBAAwB,qBAAA;;;;EAIvC,KAAA;AAAA"}
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../core/src/http/types.ts"],"mappings":";;;;;;;;;KAQY,YAAA;;;AAAZ;;;;AAAwB;AA0BxB;;;;AAca;AAeb;;;;AACU;AAMV;;;;;;UApCiB,aAAA;EAoDL;;;;;;;;;;;;;EAtCV,WAAW;AAAA;;;;AAmDY;AAiEzB;;;;;;;;KArGY,kBAAA;EACV,QAAQ;AAAA;;;;KAME,gBAAA;;;;AAIR;;;;EAIA,OAAA,CAAQ,QAAA;;;;EAIR,MAAA;;;;EAIA,OAAA,CAAQ,MAAA;;;;;;;;EAQR,OAAA;;;;KAKQ,aAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiUiB;AAG7B;;AAH6B;;;;;;;;;;;AAmBtB;;;;;;;;;;;;;;;;;;;;;UAnRU,iBAAA;EA0SwB;;;AAIlC;EAzSL,MAAA;;;;;;EAMA,WAAA;;;;EAIA,UAAA,EAAY,UAAU;AAAA;;;;UAMP,kBAAA;;;;EAIf,IAAA;;;;EAIA,GAAA;;;;EAIA,IAAA,GAAO,kBAAA;;;;;;EAMP,eAAA;;;;;;;;;;EAUA,SAAA;;;;;;;;;;;;;;;;;;;;EAoBA,UAAA,mCAA6C,OAAA,UAAiB,GAAA;EAC9D,OAAA;;;;IAIE,MAAA;;;;IAIA,OAAA,GAAU,sBAAA;EAAA;;;;;;;;;;EAWZ,GAAA,GAAM,SAAA;;;;EAIN,SAAA;;;;;;IAME,GAAA;;;;;;IAMA,QAAA;EAAA;;;;;;;;EASF,SAAA;;;;;;IAME,MAAA;;;;IAIA,SAAA;;;;;;;IAOA,OAAA;EAAA;;;;EAKF,WAAA;;;;;;IAME,GAAA;;;;;;IAMA,UAAA;;;;;;;IAOA,OAAA;;;;IAIA,MAAA;EAAA;;;;EAKF,WAAA;;;;;;;IAOE,OAAA;;;;;;IAMA,SAAA;;;;;;IAMA,UAAA;EAAA;;;;EAKF,gBAAA;;;;;;;IAOE,OAAA;;;;;;;;IAQA,qBAAA;EAAA;;;;EAKF,MAAA;;;;;;IAME,OAAA;;;;;;;IAOA,IAAA;;;;;;;IAOA,aAAA;EAAA;;;;EAKF,IAAA;;;;EAIA,UAAA;;;;IAIE,GAAA,GAAM,UAAA;;;;IAIN,IAAA,GAAO,iBAAA;;;;IAIP,MAAA,GAAS,iBAAA;EAAA;;;;;;EAOX,OAAA,GAAU,iBAAA;AAAA;AAAA,KAGA,wBAAA;;;;EAIV,IAAA,GAAO,IAAA;;;;EAIP,MAAA,GAAS,IAAA,EAAM,KAAA,CAAM,SAAS;;;;EAI9B,GAAA;;;;EAIA,KAAA;AAAA;AAAA,KAGU,qBAAA;;;;;;;EAOV,IAAA,GAAO,KAAA,UAAe,IAAA,OAAW,EAAA,cAAgB,qBAAA;;;;EAIjD,OAAA,GAAU,OAAA,aAAoB,qBAAA;;;;EAI9B,GAAA,QAAW,qBAAA;;;;;EAKX,YAAA,GAAe,OAAA,iBAAwB,qBAAA;;;;EAIvC,KAAA;AAAA"}
package/esm/index.d.mts CHANGED
@@ -15,12 +15,15 @@ import { DOSpacesDriver } from "./storage/drivers/do-spaces-driver.mjs";
15
15
  import { LocalDriver } from "./storage/drivers/local-driver.mjs";
16
16
  import { R2Driver } from "./storage/drivers/r2-driver.mjs";
17
17
  import { S3Driver } from "./storage/drivers/s3-driver.mjs";
18
+ import { PipeableReactStream, StreamReactResponseOptions, streamReactResponse } from "./http/stream-react-response.mjs";
19
+ import { CookieOptions, Response, ResponseStatus, SendBufferOptions, SendFileOptions } from "./http/response.mjs";
18
20
  import { Image, ImageFormat, ImageInput, ImageTransformOptions, WatermarkConfig } from "./image/image.mjs";
19
21
  import { FileNamingStrategy, ImageTransformCallback, ImageTransformConfig, PrefixConfig, PrefixOptions, SaveAsOptions, SaveOptions, UploadedFileImageOptions, UploadsConfigurations } from "./http/uploads-types.mjs";
20
22
  import { FileValidationOptions, UploadedFile, UploadedFileJson } from "./http/uploaded-file.mjs";
21
23
  import { Request } from "./http/request.mjs";
22
- import { CookieOptions, Response, ResponseStatus, SendBufferOptions, SendFileOptions } from "./http/response.mjs";
23
- import { DecodedAccessToken, HttpConfigurations, PartialMiddleware, RequestEvent, RequestLocals, RequestUser, ResponseEvent, ResponseSSEController, ResponseStreamController, ReturnedResponse } from "./http/types.mjs";
24
+ import { CspConfig, DEFAULT_CSP_DIRECTIVES, InvalidCspDirectiveError, applyCspHeader, buildCspHeaderValue, mergeCspDirectives, resolveCspConfig, serializeCspDirectives, validateCspConfigAtBoot, validateCspDirectives } from "./http/csp.mjs";
25
+ import { HttpTracingConfig, TracingContext, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo } from "./http/tracing/tracing.type.mjs";
26
+ import { DecodedAccessToken, HttpConfigurations, PartialMiddleware, RequestEvent, RequestLocals, ResponseEvent, ResponseSSEController, ResponseStreamController, ReturnedResponse } from "./http/types.mjs";
24
27
  import { defaultHttpConfigurations, httpConfig } from "./http/config.mjs";
25
28
  import { createHttpApplication, stopHttpApplication } from "./http/createHttpApplication.mjs";
26
29
  import { RequestLog } from "./http/database/RequestLog.mjs";
@@ -29,7 +32,7 @@ import { logResponse, wrapResponseInDataKey } from "./http/events.mjs";
29
32
  import { HealthCheck, HealthStatus, health } from "./http/health.mjs";
30
33
  import { RequestController } from "./http/request-controller.mjs";
31
34
  import { UPLOADS_DEFAULTS, uploadsConfig } from "./http/uploads-config.mjs";
32
- import { BadRequestError, ConflictError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
35
+ import { BadRequestError, ConflictError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, RequestUserMovedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
33
36
  import { CacheMiddlewareOptions } from "./http/middleware/cache-response-middleware.mjs";
34
37
  import { ConcurrencyLimitOptions } from "./http/middleware/concurrency-limit.middleware.mjs";
35
38
  import { IdempotencyOptions } from "./http/middleware/idempotency.middleware.mjs";
@@ -46,6 +49,8 @@ import { registerHttpPlugins } from "./http/plugins.mjs";
46
49
  import { assertConfiguredHttpPortIsFree, preflightConfiguredHttpPort, remedyLines, shouldPreflightHttpPort } from "./http/boot-port-preflight.mjs";
47
50
  import { PortInUseError, assertPortIsAvailable, isPortAvailable } from "./http/port-preflight.mjs";
48
51
  import { HttpReadyReport, getHttpReadyReport, resetHttpReadyReport, setHttpReadyReport } from "./http/ready-report.mjs";
52
+ import { deriveTraceId, parseTraceparentTraceId } from "./http/tracing/trace-id.mjs";
53
+ import { TracingContextSource, buildTracingContext, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled, resetTracingConfigForTests, resolveTracingConfig } from "./http/tracing/tracing-dispatcher.mjs";
49
54
  import { RequestContextStore, requestContext, useCurrentUser, useRequest, useRequestStore } from "./http/context/request-context.mjs";
50
55
  import { requestMemo } from "./http/context/request-memo.mjs";
51
56
  import { LocalizedObject, getLocalized } from "./utils/get-localized.mjs";
@@ -161,7 +166,7 @@ import { WarlockConfigManager, isUnknownTsExtensionError, warlockConfigManager }
161
166
  import { env } from "@mongez/dotenv";
162
167
  import { colors } from "@mongez/copper";
163
168
  export * from "@mongez/localization";
164
- export { $registerUseCase, $unregisterUseCase, AccessConnector, AggregateExpressionInput, AggregateExpressions, AiConnector, AllRepositoryOptions, AppConfigurations, Application, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, 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, ChunkCallback, ClosableServer, CloudDriver, CloudStorageDriverContract, CloudStorageDriverOptions, CloudStorageFileData, type CommandActionData, type ConcurrencyLimitOptions, ConfigKey, ConfigKeyRegistry, ConfigName, ConfigRegistry, ConfigSpecialHandlers, ConflictError, Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority, ConnectorsManager, ConsoleChannel, ContainerTypes, CookieOptions, CursorPaginationOptions, CursorPaginationResult, DOSpacesDriver, DatabaseCacheDriver, type DatabaseCacheOptions, DatabaseConnector, DatabaseLog, DatabaseLogModel, DatabaseLogOptions, DecodedAccessToken, DefineResourceOptions, DeleteManyResult, EncryptionConfigurations, EncryptionPasswordConfigurations, Environment, EventSubscription, ExistsExceptCurrentIdRuleOptions, ExistsExceptCurrentUserRuleOptions, FastifyInstance, FileNamingStrategy, FileValidationOptions, FileValidator, FileVisibility, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, ForbiddenError, GroupByFields, GroupedRoutesOptions, HealthCheck, HealthStatus, HeraldConnector, HttpConfigurations, HttpConnector, HttpContext, HttpError, HttpErrorCodes, HttpReadyReport, type IdempotencyOptions, Image, ImageFormat, ImageInput, ImageTransformCallback, ImageTransformConfig, ImageTransformOptions, type IpFilterOptions, ListOptions, LocalDriver, LocalStorageDriverOptions, 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, Middleware, MiddlewareResponse, MimeTypes, NoopChannel, type NormalizedMail, NotAcceptableError, NotAllowedError, NotificationsConnector, PaginationMode, PaginationResult, PartialMiddleware, PartialPick, Path, PipelineOptions, PortInUseError, PositionalHandlerSuspect, PrefixConfig, PrefixOptions, PresignedOptions, PresignedUploadOptions, 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, RequestMethod, RequestUser, type ResolvedCLICommandOption, Resource, ResourceArraySchema, ResourceCastType, ResourceConstructor, ResourceContract, ResourceFieldBuilder, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceMethod, ResourceNotFoundError, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, Response, ResponseBodyValue, ResponseEvent, ResponseSSEController, ResponseSchema, ResponseStatus, ResponseStreamController, Restful, RestfulMiddleware, ReturnedResponse, Route, RouteOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, RuntimeStrategy, S3Driver, type SESConfigurations, type SMTPConfigurations, SafeFetchOptions, SafeFetchResult, SaveAsOptions, SaveMode, SaveOptions, ScopedStorage, ScopedStorageContract, SeedClock, SeedContext, SeedRecordRef, SeedResult, Seeder, SeederDependencyCycleError, SeederMetadata, SendBufferOptions, SendFileOptions, ServerError, ShutdownListener, SocketConnector, SocketOptions, Storage, StorageConfigurations, StorageConnector, StorageCopyEventPayload, StorageDriverConfig, StorageDriverContextStore, StorageDriverContract, StorageDriverName, StorageDriverRegistry, StorageDriverType, StorageError, StorageErrorOptions, StorageEventHandler, StorageEventPayload, StorageEventType, StorageFile, StorageFileData, StorageFileInfo, StorageManagerContract, StoragePutEventPayload, TemporaryTokenError, TemporaryTokenPayload, TemporaryTokenValidation, Track, TrackableModel, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, UPLOADS_DEFAULTS, UnAuthorizedError, UniqueExceptCurrentIdRuleOptions, UniqueExceptCurrentUserRuleOptions, UnknownSeederDependencyError, UploadedFile, UploadedFileImageOptions, UploadedFileJson, UploadsConfigurations, UseCase, UseCaseAfterMiddleware, UseCaseBeforeMiddleware, UseCaseBroadcastChannel, UseCaseBroadcastEvent, UseCaseBroadcastOption, UseCaseConfigurations, UseCaseContext, UseCaseErrorResult, UseCaseEventsCallbacksMap, UseCaseGuard, UseCaseHandler, UseCaseOnExecutingContext, UseCaseResult, UseCaseRuntimeOptions, UseCaseWithSchema, ValidationConfiguration, WarlockConfig, WarlockConfigManager, WatermarkConfig, WhereOperator, addUseCaseHistory, anyMatch, app, appLog, appPath, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildIdempotencyCacheKey, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, describePositionalHandlerSuspect, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateMailId, getDefaultMailConfig, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isBootSignal, isDevelopmentMode, isNewerVersion, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, middleware, normalizeRequestPath, normalizeRoutePath, parseSize, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerHttpPlugins, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, resetHttpReadyReport, resetMailConfig, resolveMailConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
169
+ export { $registerUseCase, $unregisterUseCase, AccessConnector, AggregateExpressionInput, AggregateExpressions, AiConnector, AllRepositoryOptions, AppConfigurations, Application, BOOT_SIGNAL_ENV_KEY, BOOT_SIGNAL_VERSION, BadRequestError, BadSchemaUseCaseError, 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, ChunkCallback, ClosableServer, CloudDriver, CloudStorageDriverContract, CloudStorageDriverOptions, CloudStorageFileData, type CommandActionData, type ConcurrencyLimitOptions, ConfigKey, ConfigKeyRegistry, ConfigName, ConfigRegistry, ConfigSpecialHandlers, ConflictError, Connector, ConnectorBuildContext, ConnectorBuildContribution, ConnectorBuildGenerateResult, ConnectorEsbuildPatch, ConnectorLifecyclePhase, ConnectorName, ConnectorPriority, ConnectorsManager, ConsoleChannel, ContainerTypes, CookieOptions, CspConfig, CursorPaginationOptions, CursorPaginationResult, DEFAULT_CSP_DIRECTIVES, DOSpacesDriver, DatabaseCacheDriver, type DatabaseCacheOptions, DatabaseConnector, DatabaseLog, DatabaseLogModel, DatabaseLogOptions, DecodedAccessToken, DefineResourceOptions, DeleteManyResult, EncryptionConfigurations, EncryptionPasswordConfigurations, Environment, EventSubscription, ExistsExceptCurrentIdRuleOptions, ExistsExceptCurrentUserRuleOptions, FastifyInstance, FileNamingStrategy, FileValidationOptions, FileValidator, FileVisibility, FilterFunction, FilterOperator, FilterOptions, FilterRule, FilterRules, ForbiddenError, GroupByFields, GroupedRoutesOptions, HealthCheck, HealthStatus, HeraldConnector, HttpConfigurations, HttpConnector, HttpContext, HttpError, HttpErrorCodes, HttpReadyReport, HttpTracingConfig, type IdempotencyOptions, Image, ImageFormat, ImageInput, ImageTransformCallback, ImageTransformConfig, ImageTransformOptions, InvalidCspDirectiveError, type IpFilterOptions, ListOptions, LocalDriver, LocalStorageDriverOptions, 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, Middleware, MiddlewareResponse, MimeTypes, NoopChannel, type NormalizedMail, NotAcceptableError, NotAllowedError, NotificationsConnector, PaginationMode, PaginationResult, PartialMiddleware, PartialPick, Path, PipeableReactStream, PipelineOptions, PortInUseError, PositionalHandlerSuspect, PrefixConfig, PrefixOptions, PresignedOptions, PresignedUploadOptions, 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, RequestMethod, RequestUserMovedError, type ResolvedCLICommandOption, Resource, ResourceArraySchema, ResourceCastType, ResourceConstructor, ResourceContract, ResourceFieldBuilder, ResourceFieldBuilderDateOutputOptions, ResourceFieldConfig, ResourceMethod, ResourceNotFoundError, ResourceOutputValueCastType, ResourceSchema, ResourceSelfReference, Response, ResponseBodyValue, ResponseEvent, ResponseSSEController, ResponseSchema, ResponseStatus, ResponseStreamController, Restful, RestfulMiddleware, ReturnedResponse, Route, RouteOptions, RouteRegistry, RouteResource, Router, RouterGroupCallback, RouterStacks, RuntimeStrategy, S3Driver, type SESConfigurations, type SMTPConfigurations, SafeFetchOptions, SafeFetchResult, SaveAsOptions, SaveMode, SaveOptions, ScopedStorage, ScopedStorageContract, SeedClock, SeedContext, SeedRecordRef, SeedResult, Seeder, SeederDependencyCycleError, SeederMetadata, SendBufferOptions, SendFileOptions, ServerError, ShutdownListener, SocketConnector, SocketOptions, Storage, StorageConfigurations, StorageConnector, StorageCopyEventPayload, StorageDriverConfig, StorageDriverContextStore, StorageDriverContract, StorageDriverName, StorageDriverRegistry, StorageDriverType, StorageError, StorageErrorOptions, StorageEventHandler, StorageEventPayload, StorageEventType, StorageFile, StorageFileData, StorageFileInfo, StorageManagerContract, StoragePutEventPayload, StreamReactResponseOptions, TemporaryTokenError, TemporaryTokenPayload, TemporaryTokenValidation, TracingContext, TracingContextSource, TracingHooks, TracingPhaseInfo, TracingRequestEndInfo, Track, TrackableModel, TypedAllRepositoryOptions, TypedRepositoryOptions, TypedRepositoryOptionsWithCursor, TypedRepositoryOptionsWithPages, UPLOADS_DEFAULTS, UnAuthorizedError, UniqueExceptCurrentIdRuleOptions, UniqueExceptCurrentUserRuleOptions, UnknownSeederDependencyError, UploadedFile, UploadedFileImageOptions, UploadedFileJson, UploadsConfigurations, UseCase, UseCaseAfterMiddleware, UseCaseBeforeMiddleware, UseCaseBroadcastChannel, UseCaseBroadcastEvent, UseCaseBroadcastOption, UseCaseConfigurations, UseCaseContext, UseCaseErrorResult, UseCaseEventsCallbacksMap, UseCaseGuard, UseCaseHandler, UseCaseOnExecutingContext, UseCaseResult, UseCaseRuntimeOptions, UseCaseWithSchema, ValidationConfiguration, WarlockConfig, WarlockConfigManager, WatermarkConfig, WhereOperator, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, deriveTraceId, describePositionalHandlerSuspect, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateMailId, getDefaultMailConfig, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isBootSignal, isDevelopmentMode, isNewerVersion, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isTracingEnabled, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, mergeCspDirectives, middleware, normalizeRequestPath, normalizeRoutePath, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerHttpPlugins, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, resetHttpReadyReport, resetMailConfig, resetTracingConfigForTests, resolveCspConfig, resolveMailConfig, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, serializeCspDirectives, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
165
170
  import "./config/types.mjs";
166
171
  import "./http/request.mjs";
167
172
  import "./http/types.mjs";
package/esm/index.mjs CHANGED
@@ -20,7 +20,10 @@ import { toJson } from "./utils/to-json.mjs";
20
20
  import { assetsUrl, publicUrl, setBaseUrl, uploadsUrl, url } from "./utils/urls.mjs";
21
21
  import { isNewerVersion } from "./utils/version-compare.mjs";
22
22
  import "./utils/index.mjs";
23
- import { BadRequestError, ConflictError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
23
+ import { DEFAULT_CSP_DIRECTIVES, InvalidCspDirectiveError, applyCspHeader, buildCspHeaderValue, mergeCspDirectives, resolveCspConfig, serializeCspDirectives, validateCspConfigAtBoot, validateCspDirectives } from "./http/csp.mjs";
24
+ import { BadRequestError, ConflictError, ForbiddenError, HttpError, NotAcceptableError, NotAllowedError, RequestUserMovedError, ResourceNotFoundError, ServerError, UnAuthorizedError } from "./http/errors/errors.mjs";
25
+ import { deriveTraceId, parseTraceparentTraceId } from "./http/tracing/trace-id.mjs";
26
+ import { buildTracingContext, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, isTracingEnabled, resetTracingConfigForTests, resolveTracingConfig } from "./http/tracing/tracing-dispatcher.mjs";
24
27
  import { createRequestStore, t } from "./http/middleware/inject-request-context.mjs";
25
28
  import { defaultHttpConfigurations, httpConfig } from "./http/config.mjs";
26
29
  import { normalizeRoutePath } from "./router/normalize-route-path.mjs";
@@ -47,6 +50,7 @@ import { S3Driver } from "./storage/drivers/s3-driver.mjs";
47
50
  import { Storage, storage } from "./storage/storage.mjs";
48
51
  import "./storage/index.mjs";
49
52
  import { renderReact } from "./react/index.mjs";
53
+ import { streamReactResponse } from "./http/stream-react-response.mjs";
50
54
  import { Response, ResponseStatus } from "./http/response.mjs";
51
55
  import { Image } from "./image/image.mjs";
52
56
  import "./image/index.mjs";
@@ -159,4 +163,4 @@ import { colors } from "@mongez/copper";
159
163
 
160
164
  export * from "@mongez/localization"
161
165
 
162
- export { $registerUseCase, $unregisterUseCase, 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, DOSpacesDriver, DatabaseCacheDriver, DatabaseConnector, DatabaseLog, DatabaseLogModel, FileValidator, ForbiddenError, HeraldConnector, HttpConnector, HttpError, HttpErrorCodes, Image, LocalDriver, LoggerConnector, MAIL_EVENTS, Mail, MailError, MailerConnector, MimeTypes, NoopChannel, NotAcceptableError, NotAllowedError, NotificationsConnector, Path, PortInUseError, Queue, R2Driver, RegisterResource, RepositoryManager, Request, RequestController, RequestLog, Resource, ResourceFieldBuilder, ResourceNotFoundError, Response, ResponseStatus, Restful, RouteRegistry, Router, S3Driver, ScopedStorage, SeederDependencyCycleError, ServerError, SocketConnector, Storage, StorageConnector, StorageError, StorageFile, UPLOADS_DEFAULTS, UnAuthorizedError, UnknownSeederDependencyError, UploadedFile, WarlockConfigManager, addUseCaseHistory, anyMatch, app, appLog, appPath, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildIdempotencyCacheKey, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, describePositionalHandlerSuspect, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateMailId, getDefaultMailConfig, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isBootSignal, isDevelopmentMode, isNewerVersion, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, middleware, normalizeRequestPath, normalizeRoutePath, parseSize, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerHttpPlugins, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, resetHttpReadyReport, resetMailConfig, resolveMailConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
166
+ export { $registerUseCase, $unregisterUseCase, 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, DEFAULT_CSP_DIRECTIVES, DOSpacesDriver, DatabaseCacheDriver, DatabaseConnector, DatabaseLog, DatabaseLogModel, FileValidator, ForbiddenError, HeraldConnector, HttpConnector, HttpError, HttpErrorCodes, Image, InvalidCspDirectiveError, LocalDriver, LoggerConnector, MAIL_EVENTS, Mail, MailError, MailerConnector, MimeTypes, NoopChannel, NotAcceptableError, NotAllowedError, NotificationsConnector, Path, PortInUseError, Queue, R2Driver, RegisterResource, RepositoryManager, Request, RequestController, RequestLog, RequestUserMovedError, Resource, ResourceFieldBuilder, ResourceNotFoundError, Response, ResponseStatus, Restful, RouteRegistry, Router, S3Driver, ScopedStorage, SeederDependencyCycleError, ServerError, SocketConnector, Storage, StorageConnector, StorageError, StorageFile, UPLOADS_DEFAULTS, UnAuthorizedError, UnknownSeederDependencyError, UploadedFile, WarlockConfigManager, addUseCaseHistory, anyMatch, app, appLog, appPath, applyCspHeader, assertConfiguredHttpPortIsFree, assertMailCount, assertMailSent, assertNoReservedConnectorNames, assertPortIsAvailable, assertUniqueConnectorNames, assetsUrl, bootstrap, broadcastUseCaseResult, buildCspHeaderValue, buildIdempotencyCacheKey, buildTracingContext, cachePath, captureMail, clearPositionalHandlerSuspects, clearTestMailbox, closeAllMailers, closeMailer, closeServerWithTimeout, colors, command, config, configPath, configSpecialHandlers, connectorsManager, container, createHttpApplication, createRequestStore, decrypt, defaultHttpConfigurations, defineConfig, defineResource, deriveTraceId, describePositionalHandlerSuspect, dispatchPhase, dispatchRequestEnd, dispatchRequestStart, displayEnvironmentMode, encrypt, ensureFatalIsVisible, env, environment, existsExceptCurrentIdRule, existsExceptCurrentUserRule, fetchLatestVersion, fileExtensionRule, fileRule, fileTypeRule, findMailsBySubject, findMailsTo, fireLifecycleEvent, forgetPositionalHandlerSuspects, generateMailId, getDefaultMailConfig, getHttpReadyReport, getHttpServer, getLastMail, getLocalized, getMailEventName, getMailMode, getMailboxSize, getMailer, getMailerConfig, getMimeType, getPoolStats, getSocketServer, getTestMailbox, getUseCase, getUseCaseHistory, getUseCases, globalEventsCallbacksMap, globalUseCasesEvents, hashBody, hashPassword, health, hmacHash, httpConfig, imageRule, increaseUseCaseFailedCalls, increaseUseCaseSuccessCalls, inspectHandlerSignature, ipMatches, isBootSignal, isDevelopmentMode, isNewerVersion, isPortAvailable, isPrivateOrReservedIp, isProductionMode, isTestMode, isTracingEnabled, isUnknownTsExtensionError, isValidIdempotencyKey, listPositionalHandlerSuspects, loadS3, logResponse, logsPath, looksLikePositionalHandler, mailEvents, matchesDerivedRouteName, measure, mergeCspDirectives, middleware, normalizeRequestPath, normalizeRoutePath, parseSize, parseTraceparentTraceId, paths, preflightConfiguredHttpPort, promiseAllObject, publicPath, publicUrl, registerAppConfig, registerConfiguredConnectors, registerHttpPlugins, remedyLines, renderReact, renderReactMail, reportPositionalHandlerSuspects, requestContext, requestMemo, resetHttpReadyReport, resetMailConfig, resetTracingConfigForTests, resolveCspConfig, resolveMailConfig, resolveTracingConfig, resolveWithinRoot, rootPath, routeNameMethodSuffix, router, runPipeline, safeFetchToBuffer, sanitizePath, seeder, sendBootSignal, sendMail, serializeCspDirectives, setBaseUrl, setConfig, setEnvironment, setHttpReadyReport, setLogConfigurations, setMailConfigurations, setMailMode, shouldPreflightHttpPort, sleep, sluggable, srcPath, startHttpServer, stopHttpApplication, storage, storageConfig, storageConfigurations, storageDriverContext, storagePath, streamReactResponse, t, tempPath, toJson, uniqueExceptCurrentIdRule, uniqueExceptCurrentUserRule, uploadedFileMetadataSchema, uploadsConfig, uploadsPath, uploadsUrl, url, useCase, useComputedModel, useComputedSlug, useCurrentUser, useHashedPassword, useRequest, useRequestStore, validateCspConfigAtBoot, validateCspDirectives, verifyMailer, verifyPassword, warlockConfigManager, warlockPath, wasMailSentTo, wasMailSentWithSubject, wrapResponseInDataKey };
@@ -0,0 +1,47 @@
1
+ import esbuild from "esbuild";
2
+
3
+ //#region ../core/src/production/esbuild-preflight.ts
4
+ /**
5
+ * The exact substring esbuild's own loader throws when the platform-specific
6
+ * binary package (e.g. `@esbuild/win32-x64`) never got installed. This is
7
+ * the signature pnpm's build-script approval gate leaves behind: it blocks
8
+ * esbuild's postinstall script, so the binary is never linked into place,
9
+ * and any later call into esbuild dies with this message instead of a
10
+ * project-shaped one.
11
+ *
12
+ * Source: `pkgAndSubpathForCurrentPlatform` in esbuild's `lib/main.js`.
13
+ */
14
+ const UNLINKED_BINARY_SIGNATURE = "could not be found, and is needed by esbuild";
15
+ /**
16
+ * Fail fast, before bundling, when esbuild's native binary is not linked.
17
+ *
18
+ * Runs a single trivial `transformSync` call — the cheapest operation that
19
+ * forces esbuild to resolve its platform binary — so it adds no measurable
20
+ * delay to `warlock build`. Only called from the production build path;
21
+ * never from `warlock dev`.
22
+ *
23
+ * A healthy esbuild install is a no-op. A binary genuinely missing because
24
+ * pnpm blocked its postinstall script is turned into a message that names
25
+ * the cause and the fix. Any other failure (a real syntax error, a platform
26
+ * mismatch, …) is rethrown unchanged — this preflight only owns the one
27
+ * known failure mode.
28
+ */
29
+ function assertEsbuildBinaryIsLinked() {
30
+ try {
31
+ esbuild.transformSync("", { loader: "js" });
32
+ } catch (error) {
33
+ if (isUnlinkedBinaryError(error)) throw new Error("esbuild's native binary is not installed for this platform, so `warlock build` cannot bundle.\n\nThis usually happens when pnpm's build-script approval gate blocked esbuild's postinstall script, so the platform binary was never linked. Fix it with:\n\n pnpm approve-builds\n\nthen reinstall, or reinstall dependencies with build scripts enabled if esbuild was excluded on purpose.");
34
+ throw error;
35
+ }
36
+ }
37
+ /**
38
+ * Narrow an unknown thrown value down to esbuild's known "binary not
39
+ * linked" failure, identified by the fixed substring esbuild itself throws.
40
+ */
41
+ function isUnlinkedBinaryError(error) {
42
+ return error instanceof Error && error.message.includes(UNLINKED_BINARY_SIGNATURE);
43
+ }
44
+
45
+ //#endregion
46
+ export { assertEsbuildBinaryIsLinked };
47
+ //# sourceMappingURL=esbuild-preflight.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"esbuild-preflight.mjs","names":[],"sources":["../../../../../../../core/src/production/esbuild-preflight.ts"],"sourcesContent":["import esbuild from \"esbuild\";\n\n/**\n * The exact substring esbuild's own loader throws when the platform-specific\n * binary package (e.g. `@esbuild/win32-x64`) never got installed. This is\n * the signature pnpm's build-script approval gate leaves behind: it blocks\n * esbuild's postinstall script, so the binary is never linked into place,\n * and any later call into esbuild dies with this message instead of a\n * project-shaped one.\n *\n * Source: `pkgAndSubpathForCurrentPlatform` in esbuild's `lib/main.js`.\n */\nconst UNLINKED_BINARY_SIGNATURE = \"could not be found, and is needed by esbuild\";\n\n/**\n * Fail fast, before bundling, when esbuild's native binary is not linked.\n *\n * Runs a single trivial `transformSync` call — the cheapest operation that\n * forces esbuild to resolve its platform binary — so it adds no measurable\n * delay to `warlock build`. Only called from the production build path;\n * never from `warlock dev`.\n *\n * A healthy esbuild install is a no-op. A binary genuinely missing because\n * pnpm blocked its postinstall script is turned into a message that names\n * the cause and the fix. Any other failure (a real syntax error, a platform\n * mismatch, …) is rethrown unchanged — this preflight only owns the one\n * known failure mode.\n */\nexport function assertEsbuildBinaryIsLinked(): void {\n try {\n esbuild.transformSync(\"\", { loader: \"js\" });\n } catch (error) {\n if (isUnlinkedBinaryError(error)) {\n throw new Error(\n \"esbuild's native binary is not installed for this platform, so \" +\n \"`warlock build` cannot bundle.\\n\\n\" +\n \"This usually happens when pnpm's build-script approval gate \" +\n \"blocked esbuild's postinstall script, so the platform binary \" +\n \"was never linked. Fix it with:\\n\\n\" +\n \" pnpm approve-builds\\n\\n\" +\n \"then reinstall, or reinstall dependencies with build scripts \" +\n \"enabled if esbuild was excluded on purpose.\",\n );\n }\n\n throw error;\n }\n}\n\n/**\n * Narrow an unknown thrown value down to esbuild's known \"binary not\n * linked\" failure, identified by the fixed substring esbuild itself throws.\n */\nfunction isUnlinkedBinaryError(error: unknown): boolean {\n return error instanceof Error && error.message.includes(UNLINKED_BINARY_SIGNATURE);\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAM,4BAA4B;;;;;;;;;;;;;;;AAgBlC,SAAgB,8BAAoC;CAClD,IAAI;EACF,QAAQ,cAAc,IAAI,EAAE,QAAQ,KAAK,CAAC;CAC5C,SAAS,OAAO;EACd,IAAI,sBAAsB,KAAK,GAC7B,MAAM,IAAI,MACR,+XAQF;EAGF,MAAM;CACR;AACF;;;;;AAMA,SAAS,sBAAsB,OAAyB;CACtD,OAAO,iBAAiB,SAAS,MAAM,QAAQ,SAAS,yBAAyB;AACnF"}
@@ -9,6 +9,7 @@ import { bundleFrameworkDependencies } from "./bundle-framework-dependencies.mjs
9
9
  import { dedupe, runEmitContributions, runGenerateContributions } from "./build-contributions.mjs";
10
10
  import { writeDistBuildManifestAsync } from "./dist-build-manifest.mjs";
11
11
  import { nativeNodeModulesPlugin } from "./esbuild-plugins.mjs";
12
+ import { assertEsbuildBinaryIsLinked } from "./esbuild-preflight.mjs";
12
13
  import { commitDistAsync, createTempOutputDir, rollbackDistAsync, stageDistAsync } from "./promote-dist.mjs";
13
14
  import { resolveBuildConfig } from "./resolve-build-config.mjs";
14
15
  import { tsconfigPathAliases } from "./tsconfig-path-aliases.mjs";
@@ -116,6 +117,7 @@ var ProductionBuilder = class {
116
117
  */
117
118
  async build() {
118
119
  console.log(colors.cyan("Building for production...\n"));
120
+ assertEsbuildBinaryIsLinked();
119
121
  await this.initializeOptions();
120
122
  const finalOutDir = this.options.outdir;
121
123
  const tempOutDir = createTempOutputDir(finalOutDir);
@@ -419,21 +421,21 @@ bootstrap();
419
421
  const singleBundle = this.options.singleBundle === true;
420
422
  const esmShim = this.options.esmShim !== false;
421
423
  const userBanner = this.options.banner;
422
- const strippable = this.options;
423
- delete strippable.outFile;
424
- delete strippable.entryPath;
425
- delete this.options.singleBundle;
426
- delete this.options.esmShim;
427
- delete this.options.banner;
424
+ const esbuildOptions = { ...this.options };
425
+ delete esbuildOptions.outFile;
426
+ delete esbuildOptions.entryPath;
427
+ delete esbuildOptions.singleBundle;
428
+ delete esbuildOptions.esmShim;
429
+ delete esbuildOptions.banner;
428
430
  await ensureDirectoryAsync(writeOutDir);
429
431
  const alias = this.buildAliasMapFromTsconfig();
430
- const perEdgeExternals = !singleBundle && this.options.packages === void 0;
431
- const isEsm = (this.options.format ?? "esm") === "esm";
432
+ const perEdgeExternals = !singleBundle && esbuildOptions.packages === void 0;
433
+ const isEsm = (esbuildOptions.format ?? "esm") === "esm";
432
434
  const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : void 0);
433
435
  const { define: contributedDefine, external: contributedExternal, loader: contributedLoader, ...contributedOptions } = this.contributedEsbuild;
434
- const userDefine = this.options.define;
435
- const userExternal = this.options.external;
436
- const userLoader = this.options.loader;
436
+ const userDefine = esbuildOptions.define;
437
+ const userExternal = esbuildOptions.external;
438
+ const userLoader = esbuildOptions.loader;
437
439
  const define = contributedDefine || userDefine ? {
438
440
  ...contributedDefine,
439
441
  ...userDefine
@@ -451,8 +453,8 @@ bootstrap();
451
453
  bundle: true,
452
454
  splitting: !singleBundle,
453
455
  packages: singleBundle || perEdgeExternals ? "bundle" : "external",
454
- minify: this.options.minify,
455
- sourcemap: this.options.sourcemap === true ? "linked" : this.options.sourcemap,
456
+ minify: esbuildOptions.minify,
457
+ sourcemap: esbuildOptions.sourcemap === true ? "linked" : esbuildOptions.sourcemap,
456
458
  format: "esm",
457
459
  target: ["node22"],
458
460
  entryNames: entryName,
@@ -466,7 +468,7 @@ bootstrap();
466
468
  })] : []
467
469
  ],
468
470
  ...contributedOptions,
469
- ...this.options,
471
+ ...esbuildOptions,
470
472
  outdir: writeOutDir,
471
473
  ...define ? { define } : {},
472
474
  ...external ? { external } : {},
@@ -511,7 +513,9 @@ bootstrap();
511
513
  const baseUrl = path.resolve(process.cwd(), tsconfigManager.baseUrl);
512
514
  for (const [from, to] of Object.entries(tsconfigManager.aliases)) {
513
515
  if (from.endsWith("/*") || !Array.isArray(to) || to.length === 0) continue;
514
- alias[from] = path.resolve(baseUrl, to[0]);
516
+ const target = to[0];
517
+ if (target === void 0) continue;
518
+ alias[from] = path.resolve(baseUrl, target);
515
519
  }
516
520
  return alias;
517
521
  }