@warlock.js/core 5.25.0 → 5.26.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 (80) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/esm/cli/commands/doctor/checks/index.mjs +2 -0
  3. package/esm/cli/commands/doctor/checks/index.mjs.map +1 -1
  4. package/esm/cli/commands/doctor/checks/locales-ts-deprecated.check.mjs +170 -0
  5. package/esm/cli/commands/doctor/checks/locales-ts-deprecated.check.mjs.map +1 -0
  6. package/esm/cli/commands/doctor/doctor-command.action.mjs +7 -2
  7. package/esm/cli/commands/doctor/doctor-command.action.mjs.map +1 -1
  8. package/esm/cli/commands/doctor.command.mjs +5 -0
  9. package/esm/cli/commands/doctor.command.mjs.map +1 -1
  10. package/esm/cli/commands/generate/generators/module.generator.mjs +1 -12
  11. package/esm/cli/commands/generate/generators/module.generator.mjs.map +1 -1
  12. package/esm/cli/commands/typings-generator.command.mjs +4 -1
  13. package/esm/cli/commands/typings-generator.command.mjs.map +1 -1
  14. package/esm/database/migrate-action.mjs +2 -2
  15. package/esm/database/migrate-action.mjs.map +1 -1
  16. package/esm/dev-server/legacy-locales-warning.mjs +16 -0
  17. package/esm/dev-server/legacy-locales-warning.mjs.map +1 -0
  18. package/esm/dev-server/module-loader.mjs +16 -0
  19. package/esm/dev-server/module-loader.mjs.map +1 -1
  20. package/esm/dev-server/special-file-patterns.mjs +2 -2
  21. package/esm/dev-server/special-file-patterns.mjs.map +1 -1
  22. package/esm/dev-server/translation-keys-sources.mjs +7 -3
  23. package/esm/dev-server/translation-keys-sources.mjs.map +1 -1
  24. package/esm/dev-server/type-generator.mjs +27 -4
  25. package/esm/dev-server/type-generator.mjs.map +1 -1
  26. package/esm/generations/features/access.feature.mjs +38 -18
  27. package/esm/generations/features/access.feature.mjs.map +1 -1
  28. package/esm/generations/features/bull-board.feature.mjs +2 -2
  29. package/esm/generations/features/bull-board.feature.mjs.map +1 -1
  30. package/esm/http/build-rate-limit-options.d.mts +8 -2
  31. package/esm/http/build-rate-limit-options.d.mts.map +1 -1
  32. package/esm/http/build-rate-limit-options.mjs +1 -0
  33. package/esm/http/build-rate-limit-options.mjs.map +1 -1
  34. package/esm/http/errors/errors.d.mts +1 -17
  35. package/esm/http/errors/errors.d.mts.map +1 -1
  36. package/esm/http/errors/errors.mjs +1 -20
  37. package/esm/http/errors/errors.mjs.map +1 -1
  38. package/esm/http/index.d.mts +2 -2
  39. package/esm/http/index.mjs +1 -1
  40. package/esm/http/middleware/inject-request-context.d.mts +1 -1
  41. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  42. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  43. package/esm/http/middleware/rate-limit.middleware.d.mts.map +1 -1
  44. package/esm/http/middleware/rate-limit.middleware.mjs +5 -1
  45. package/esm/http/middleware/rate-limit.middleware.mjs.map +1 -1
  46. package/esm/http/request.d.mts +7 -24
  47. package/esm/http/request.d.mts.map +1 -1
  48. package/esm/http/request.mjs +1 -22
  49. package/esm/http/request.mjs.map +1 -1
  50. package/esm/http/response.d.mts.map +1 -1
  51. package/esm/http/response.mjs +4 -2
  52. package/esm/http/response.mjs.map +1 -1
  53. package/esm/index.d.mts +5 -3
  54. package/esm/index.mjs +5 -2
  55. package/esm/localization/index.mjs +4 -0
  56. package/esm/localization/parse-locale-dictionary.d.mts +23 -0
  57. package/esm/localization/parse-locale-dictionary.d.mts.map +1 -0
  58. package/esm/localization/parse-locale-dictionary.mjs +215 -0
  59. package/esm/localization/parse-locale-dictionary.mjs.map +1 -0
  60. package/esm/localization/register-locale-dictionary.d.mts +12 -0
  61. package/esm/localization/register-locale-dictionary.d.mts.map +1 -0
  62. package/esm/localization/register-locale-dictionary.mjs +58 -0
  63. package/esm/localization/register-locale-dictionary.mjs.map +1 -0
  64. package/esm/production/production-builder.mjs +11 -2
  65. package/esm/production/production-builder.mjs.map +1 -1
  66. package/esm/router/types.d.mts +8 -0
  67. package/esm/router/types.d.mts.map +1 -1
  68. package/esm/tests/start-http-development-server.d.mts +10 -0
  69. package/esm/tests/start-http-development-server.d.mts.map +1 -1
  70. package/esm/tests/start-http-development-server.mjs +16 -2
  71. package/esm/tests/start-http-development-server.mjs.map +1 -1
  72. package/esm/validation/validateAll.mjs +48 -1
  73. package/esm/validation/validateAll.mjs.map +1 -1
  74. package/llms-full.txt +118 -75
  75. package/llms.txt +1 -1
  76. package/package.json +20 -20
  77. package/skills/README.md +1 -1
  78. package/skills/create-controller/SKILL.md +4 -0
  79. package/skills/test-http/SKILL.md +9 -1
  80. package/skills/use-localization/SKILL.md +39 -26
@@ -0,0 +1,215 @@
1
+ //#region ../core/src/localization/parse-locale-dictionary.ts
2
+ const SEGMENT = /^[A-Za-z_][A-Za-z0-9_-]*$/;
3
+ const LOCALE_CODE = /^[A-Za-z][A-Za-z0-9]*(?:-[A-Za-z0-9]+)*$/;
4
+ const FORBIDDEN_SEGMENTS = new Set([
5
+ "__proto__",
6
+ "prototype",
7
+ "constructor"
8
+ ]);
9
+ /** A source error that always names both the locale file and the offending JSON key. */
10
+ var LocaleDictionaryError = class extends Error {
11
+ constructor(sourceFile, key, detail) {
12
+ super(`Cannot parse route locales in "${sourceFile}" at "${key}": ${detail}.`);
13
+ this.sourceFile = sourceFile;
14
+ this.key = key;
15
+ this.name = "LocaleDictionaryError";
16
+ }
17
+ };
18
+ function fail(sourceFile, key, detail) {
19
+ throw new LocaleDictionaryError(sourceFile, key, detail);
20
+ }
21
+ /** A deliberately small JSON parser: unlike JSON.parse, it preserves duplicate property names. */
22
+ var StrictJsonParser = class {
23
+ constructor(sourceFile, source) {
24
+ this.sourceFile = sourceFile;
25
+ this.source = source;
26
+ this.offset = 0;
27
+ }
28
+ parse() {
29
+ if (this.source.charCodeAt(0) === 65279) this.offset = 1;
30
+ const value = this.value("$");
31
+ this.whitespace();
32
+ if (this.offset !== this.source.length) this.invalid("$", "unexpected trailing JSON");
33
+ return value;
34
+ }
35
+ value(key) {
36
+ this.whitespace();
37
+ const character = this.source[this.offset];
38
+ if (character === "{") return this.object(key);
39
+ if (character === "[") return this.array(key);
40
+ if (character === "\"") return this.string(key);
41
+ if (this.source.startsWith("true", this.offset)) return this.literal("true", true);
42
+ if (this.source.startsWith("false", this.offset)) return this.literal("false", false);
43
+ if (this.source.startsWith("null", this.offset)) return this.literal("null", null);
44
+ if (character === "-" || character !== void 0 && /[0-9]/.test(character)) return this.number(key);
45
+ this.invalid(key, "invalid JSON value");
46
+ }
47
+ object(key) {
48
+ this.offset++;
49
+ this.whitespace();
50
+ const object = /* @__PURE__ */ new Map();
51
+ if (this.source[this.offset] === "}") {
52
+ this.offset++;
53
+ return object;
54
+ }
55
+ while (true) {
56
+ this.whitespace();
57
+ if (this.source[this.offset] !== "\"") this.invalid(key, "object keys must be JSON strings");
58
+ const property = this.string(key);
59
+ const propertyKey = `${key}.${property}`;
60
+ if (object.has(property)) this.invalid(propertyKey, "duplicate JSON property");
61
+ this.whitespace();
62
+ if (this.source[this.offset] !== ":") this.invalid(propertyKey, "expected ':' after object key");
63
+ this.offset++;
64
+ object.set(property, this.value(propertyKey));
65
+ this.whitespace();
66
+ const separator = this.source[this.offset];
67
+ if (separator === "}") {
68
+ this.offset++;
69
+ return object;
70
+ }
71
+ if (separator !== ",") this.invalid(key, "expected ',' or '}' in object");
72
+ this.offset++;
73
+ }
74
+ }
75
+ array(key) {
76
+ this.offset++;
77
+ this.whitespace();
78
+ const values = [];
79
+ if (this.source[this.offset] === "]") {
80
+ this.offset++;
81
+ return values;
82
+ }
83
+ while (true) {
84
+ values.push(this.value(key));
85
+ this.whitespace();
86
+ const separator = this.source[this.offset];
87
+ if (separator === "]") {
88
+ this.offset++;
89
+ return values;
90
+ }
91
+ if (separator !== ",") this.invalid(key, "expected ',' or ']' in array");
92
+ this.offset++;
93
+ }
94
+ }
95
+ string(key) {
96
+ const start = this.offset++;
97
+ let escaped = false;
98
+ while (this.offset < this.source.length) {
99
+ const character = this.source[this.offset++];
100
+ if (escaped) {
101
+ escaped = false;
102
+ continue;
103
+ }
104
+ if (character === "\\") {
105
+ escaped = true;
106
+ continue;
107
+ }
108
+ if (character === "\"") try {
109
+ return JSON.parse(this.source.slice(start, this.offset));
110
+ } catch {
111
+ this.invalid(key, "invalid JSON string");
112
+ }
113
+ if (character !== void 0 && character.charCodeAt(0) < 32) this.invalid(key, "unescaped control character in JSON string");
114
+ }
115
+ this.invalid(key, "unterminated JSON string");
116
+ }
117
+ number(key) {
118
+ const match = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
119
+ match.lastIndex = this.offset;
120
+ const token = match.exec(this.source)?.[0];
121
+ if (token === void 0) this.invalid(key, "invalid JSON number");
122
+ this.offset += token.length;
123
+ return Number(token);
124
+ }
125
+ literal(written, value) {
126
+ this.offset += written.length;
127
+ return value;
128
+ }
129
+ whitespace() {
130
+ while (this.offset < this.source.length) {
131
+ const character = this.source[this.offset];
132
+ if (character === void 0 || !" \n\r".includes(character)) return;
133
+ this.offset++;
134
+ }
135
+ }
136
+ invalid(key, detail) {
137
+ fail(this.sourceFile, key, detail);
138
+ }
139
+ };
140
+ function assertNamespaceSegment(sourceFile, segment, key) {
141
+ if (!SEGMENT.test(segment)) fail(sourceFile, key, "segments must match [A-Za-z_][A-Za-z0-9_-]*");
142
+ if (FORBIDDEN_SEGMENTS.has(segment)) fail(sourceFile, key, "segments cannot be reserved");
143
+ }
144
+ function assertSegment(sourceFile, segment, key) {
145
+ if (segment.includes(".")) fail(sourceFile, key, "JSON keys cannot contain '.'");
146
+ assertNamespaceSegment(sourceFile, segment, key);
147
+ }
148
+ function explicitGroup(sourceFile, value) {
149
+ if (value === "") fail(sourceFile, "$group", "'$group' cannot be empty");
150
+ for (const segment of value.split(".")) {
151
+ if (segment === "") fail(sourceFile, "$group", "'$group' cannot contain empty segments");
152
+ assertNamespaceSegment(sourceFile, segment, "$group");
153
+ }
154
+ return value;
155
+ }
156
+ function isObject(value) {
157
+ return value instanceof Map;
158
+ }
159
+ function readLeaf(sourceFile, key, value, localeCodes) {
160
+ const locales = localeCodes === void 0 ? void 0 : new Set(localeCodes);
161
+ const entry = Object.create(null);
162
+ for (const [locale, translation] of value) {
163
+ if (!LOCALE_CODE.test(locale)) fail(sourceFile, `${key}.${locale}`, "invalid locale code");
164
+ if (typeof translation !== "string") fail(sourceFile, `${key}.${locale}`, "locale values must be strings");
165
+ if (locales !== void 0 && !locales.has(locale)) fail(sourceFile, `${key}.${locale}`, "unknown locale code");
166
+ entry[locale] = translation;
167
+ }
168
+ if (localeCodes !== void 0) {
169
+ for (const locale of localeCodes) if (!(locale in entry)) fail(sourceFile, key, `missing locale code "${locale}"`);
170
+ }
171
+ return entry;
172
+ }
173
+ function collectEntries(sourceFile, object, group, localeCodes, entries, nested) {
174
+ if (nested && object.size === 0) fail(sourceFile, group, "nested objects cannot be empty");
175
+ for (const [segment, value] of object) {
176
+ const key = group === "" ? segment : `${group}.${segment}`;
177
+ if (segment === "$group") fail(sourceFile, key, "'$group' is only allowed at the root");
178
+ assertSegment(sourceFile, segment, key);
179
+ if (!isObject(value)) fail(sourceFile, key, "entries must be locale objects or nested objects");
180
+ if (value.has("$group")) fail(sourceFile, `${key}.$group`, "'$group' is only allowed at the root");
181
+ const values = [...value.values()];
182
+ const hasString = values.some((item) => typeof item === "string");
183
+ const allObjects = values.every(isObject);
184
+ if (hasString) {
185
+ if (!values.every((item) => typeof item === "string")) fail(sourceFile, key, "cannot mix locale values with nested entries");
186
+ entries[key] = readLeaf(sourceFile, key, value, localeCodes);
187
+ continue;
188
+ }
189
+ if (!allObjects) fail(sourceFile, key, "cannot mix locale values with nested entries");
190
+ if (localeCodes !== void 0 && [...value.keys()].some((child) => localeCodes.includes(child))) fail(sourceFile, key, "cannot mix locale codes with nested entries");
191
+ collectEntries(sourceFile, value, key, localeCodes, entries, true);
192
+ }
193
+ }
194
+ /** Parses one locale dictionary source without reading the filesystem or loading application code. */
195
+ function parseLocaleDictionary(input) {
196
+ const { sourceFile, source, defaultNamespace, localeCodes } = input;
197
+ const parsed = new StrictJsonParser(sourceFile, source).parse();
198
+ if (!isObject(parsed)) fail(sourceFile, "$", "root JSON value must be an object");
199
+ const groupValue = parsed.get("$group");
200
+ if (groupValue !== void 0 && typeof groupValue !== "string") fail(sourceFile, "$group", "'$group' must be a string");
201
+ const group = groupValue === void 0 ? defaultNamespace === "" ? "" : explicitGroup(sourceFile, defaultNamespace) : explicitGroup(sourceFile, groupValue);
202
+ const entries = Object.create(null);
203
+ const rootEntries = new Map(parsed);
204
+ rootEntries.delete("$group");
205
+ collectEntries(sourceFile, rootEntries, group, localeCodes, entries, false);
206
+ return {
207
+ sourceFile,
208
+ group,
209
+ entries
210
+ };
211
+ }
212
+
213
+ //#endregion
214
+ export { LocaleDictionaryError, parseLocaleDictionary };
215
+ //# sourceMappingURL=parse-locale-dictionary.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parse-locale-dictionary.mjs","names":[],"sources":["../../../../../../../core/src/localization/parse-locale-dictionary.ts"],"sourcesContent":["export type LocaleDictionaryEntries = Record<string, Record<string, string>>;\n\nexport type ParsedLocaleDictionary = {\n sourceFile: string;\n group: string;\n entries: LocaleDictionaryEntries;\n};\n\ntype JsonValue = string | number | boolean | null | JsonObject | JsonValue[];\ntype JsonObject = Map<string, JsonValue>;\n\nconst SEGMENT = /^[A-Za-z_][A-Za-z0-9_-]*$/;\nconst LOCALE_CODE = /^[A-Za-z][A-Za-z0-9]*(?:-[A-Za-z0-9]+)*$/;\nconst FORBIDDEN_SEGMENTS = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\n\n/** A source error that always names both the locale file and the offending JSON key. */\nexport class LocaleDictionaryError extends Error {\n public constructor(\n public readonly sourceFile: string,\n public readonly key: string,\n detail: string,\n ) {\n super(`Cannot parse route locales in \"${sourceFile}\" at \"${key}\": ${detail}.`);\n this.name = \"LocaleDictionaryError\";\n }\n}\n\nfunction fail(sourceFile: string, key: string, detail: string): never {\n throw new LocaleDictionaryError(sourceFile, key, detail);\n}\n\n/** A deliberately small JSON parser: unlike JSON.parse, it preserves duplicate property names. */\nclass StrictJsonParser {\n private offset = 0;\n\n public constructor(\n private readonly sourceFile: string,\n private readonly source: string,\n ) {}\n\n public parse(): JsonValue {\n if (this.source.charCodeAt(0) === 0xfeff) this.offset = 1;\n const value = this.value(\"$\");\n this.whitespace();\n if (this.offset !== this.source.length) this.invalid(\"$\", \"unexpected trailing JSON\");\n return value;\n }\n\n private value(key: string): JsonValue {\n this.whitespace();\n const character = this.source[this.offset];\n if (character === \"{\") return this.object(key);\n if (character === \"[\") return this.array(key);\n if (character === '\"') return this.string(key);\n if (this.source.startsWith(\"true\", this.offset)) return this.literal(\"true\", true);\n if (this.source.startsWith(\"false\", this.offset)) return this.literal(\"false\", false);\n if (this.source.startsWith(\"null\", this.offset)) return this.literal(\"null\", null);\n if (character === \"-\" || (character !== undefined && /[0-9]/.test(character)))\n return this.number(key);\n this.invalid(key, \"invalid JSON value\");\n }\n\n private object(key: string): JsonObject {\n this.offset++;\n this.whitespace();\n const object = new Map<string, JsonValue>();\n if (this.source[this.offset] === \"}\") {\n this.offset++;\n return object;\n }\n while (true) {\n this.whitespace();\n if (this.source[this.offset] !== '\"') this.invalid(key, \"object keys must be JSON strings\");\n const property = this.string(key);\n const propertyKey = `${key}.${property}`;\n if (object.has(property)) this.invalid(propertyKey, \"duplicate JSON property\");\n this.whitespace();\n if (this.source[this.offset] !== \":\")\n this.invalid(propertyKey, \"expected ':' after object key\");\n this.offset++;\n object.set(property, this.value(propertyKey));\n this.whitespace();\n const separator = this.source[this.offset];\n if (separator === \"}\") {\n this.offset++;\n return object;\n }\n if (separator !== \",\") this.invalid(key, \"expected ',' or '}' in object\");\n this.offset++;\n }\n }\n\n private array(key: string): JsonValue[] {\n this.offset++;\n this.whitespace();\n const values: JsonValue[] = [];\n if (this.source[this.offset] === \"]\") {\n this.offset++;\n return values;\n }\n while (true) {\n values.push(this.value(key));\n this.whitespace();\n const separator = this.source[this.offset];\n if (separator === \"]\") {\n this.offset++;\n return values;\n }\n if (separator !== \",\") this.invalid(key, \"expected ',' or ']' in array\");\n this.offset++;\n }\n }\n\n private string(key: string): string {\n const start = this.offset++;\n let escaped = false;\n while (this.offset < this.source.length) {\n const character = this.source[this.offset++];\n if (escaped) {\n escaped = false;\n continue;\n }\n if (character === \"\\\\\") {\n escaped = true;\n continue;\n }\n if (character === '\"') {\n try {\n return JSON.parse(this.source.slice(start, this.offset)) as string;\n } catch {\n this.invalid(key, \"invalid JSON string\");\n }\n }\n if (character !== undefined && character.charCodeAt(0) < 0x20)\n this.invalid(key, \"unescaped control character in JSON string\");\n }\n this.invalid(key, \"unterminated JSON string\");\n }\n\n private number(key: string): number {\n const match = /-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;\n match.lastIndex = this.offset;\n const token = match.exec(this.source)?.[0];\n if (token === undefined) this.invalid(key, \"invalid JSON number\");\n this.offset += token.length;\n return Number(token);\n }\n\n private literal<T extends boolean | null>(written: string, value: T): T {\n this.offset += written.length;\n return value;\n }\n\n private whitespace(): void {\n while (this.offset < this.source.length) {\n const character = this.source[this.offset];\n if (character === undefined || !\" \\t\\n\\r\".includes(character)) return;\n this.offset++;\n }\n }\n\n private invalid(key: string, detail: string): never {\n fail(this.sourceFile, key, detail);\n }\n}\n\nfunction assertNamespaceSegment(sourceFile: string, segment: string, key: string): void {\n if (!SEGMENT.test(segment)) fail(sourceFile, key, \"segments must match [A-Za-z_][A-Za-z0-9_-]*\");\n if (FORBIDDEN_SEGMENTS.has(segment)) fail(sourceFile, key, \"segments cannot be reserved\");\n}\n\nfunction assertSegment(sourceFile: string, segment: string, key: string): void {\n if (segment.includes(\".\")) fail(sourceFile, key, \"JSON keys cannot contain '.'\");\n assertNamespaceSegment(sourceFile, segment, key);\n}\n\nfunction explicitGroup(sourceFile: string, value: string): string {\n if (value === \"\") fail(sourceFile, \"$group\", \"'$group' cannot be empty\");\n for (const segment of value.split(\".\")) {\n if (segment === \"\") fail(sourceFile, \"$group\", \"'$group' cannot contain empty segments\");\n assertNamespaceSegment(sourceFile, segment, \"$group\");\n }\n return value;\n}\n\nfunction isObject(value: JsonValue): value is JsonObject {\n return value instanceof Map;\n}\n\nfunction readLeaf(\n sourceFile: string,\n key: string,\n value: JsonObject,\n localeCodes: readonly string[] | undefined,\n): Record<string, string> {\n const locales = localeCodes === undefined ? undefined : new Set(localeCodes);\n const entry: Record<string, string> = Object.create(null) as Record<string, string>;\n for (const [locale, translation] of value) {\n if (!LOCALE_CODE.test(locale)) fail(sourceFile, `${key}.${locale}`, \"invalid locale code\");\n if (typeof translation !== \"string\")\n fail(sourceFile, `${key}.${locale}`, \"locale values must be strings\");\n if (locales !== undefined && !locales.has(locale))\n fail(sourceFile, `${key}.${locale}`, \"unknown locale code\");\n entry[locale] = translation;\n }\n if (localeCodes !== undefined)\n for (const locale of localeCodes)\n if (!(locale in entry)) fail(sourceFile, key, `missing locale code \"${locale}\"`);\n return entry;\n}\n\nfunction collectEntries(\n sourceFile: string,\n object: JsonObject,\n group: string,\n localeCodes: readonly string[] | undefined,\n entries: LocaleDictionaryEntries,\n nested: boolean,\n): void {\n if (nested && object.size === 0) fail(sourceFile, group, \"nested objects cannot be empty\");\n for (const [segment, value] of object) {\n const key = group === \"\" ? segment : `${group}.${segment}`;\n if (segment === \"$group\") fail(sourceFile, key, \"'$group' is only allowed at the root\");\n assertSegment(sourceFile, segment, key);\n if (!isObject(value)) fail(sourceFile, key, \"entries must be locale objects or nested objects\");\n if (value.has(\"$group\"))\n fail(sourceFile, `${key}.$group`, \"'$group' is only allowed at the root\");\n const values = [...value.values()];\n const hasString = values.some((item) => typeof item === \"string\");\n const allObjects = values.every(isObject);\n if (hasString) {\n if (!values.every((item) => typeof item === \"string\"))\n fail(sourceFile, key, \"cannot mix locale values with nested entries\");\n entries[key] = readLeaf(sourceFile, key, value, localeCodes);\n continue;\n }\n if (!allObjects) fail(sourceFile, key, \"cannot mix locale values with nested entries\");\n if (localeCodes !== undefined && [...value.keys()].some((child) => localeCodes.includes(child)))\n fail(sourceFile, key, \"cannot mix locale codes with nested entries\");\n collectEntries(sourceFile, value, key, localeCodes, entries, true);\n }\n}\n\n/** Parses one locale dictionary source without reading the filesystem or loading application code. */\nexport function parseLocaleDictionary(input: {\n sourceFile: string;\n source: string;\n defaultNamespace: string;\n localeCodes?: readonly string[];\n}): ParsedLocaleDictionary {\n const { sourceFile, source, defaultNamespace, localeCodes } = input;\n const parsed = new StrictJsonParser(sourceFile, source).parse();\n if (!isObject(parsed)) fail(sourceFile, \"$\", \"root JSON value must be an object\");\n const groupValue = parsed.get(\"$group\");\n if (groupValue !== undefined && typeof groupValue !== \"string\")\n fail(sourceFile, \"$group\", \"'$group' must be a string\");\n const group =\n groupValue === undefined\n ? defaultNamespace === \"\"\n ? \"\"\n : explicitGroup(sourceFile, defaultNamespace)\n : explicitGroup(sourceFile, groupValue);\n const entries: LocaleDictionaryEntries = Object.create(null) as LocaleDictionaryEntries;\n const rootEntries = new Map(parsed);\n rootEntries.delete(\"$group\");\n collectEntries(sourceFile, rootEntries, group, localeCodes, entries, false);\n return { sourceFile, group, entries };\n}\n"],"mappings":";AAWA,MAAM,UAAU;AAChB,MAAM,cAAc;AACpB,MAAM,qBAAqB,IAAI,IAAI;CAAC;CAAa;CAAa;AAAa,CAAC;;AAG5E,IAAa,wBAAb,cAA2C,MAAM;CAC/C,AAAO,YACL,AAAgB,YAChB,AAAgB,KAChB,QACA;EACA,MAAM,kCAAkC,WAAW,QAAQ,IAAI,KAAK,OAAO,EAAE;EAJ7D;EACA;EAIhB,KAAK,OAAO;CACd;AACF;AAEA,SAAS,KAAK,YAAoB,KAAa,QAAuB;CACpE,MAAM,IAAI,sBAAsB,YAAY,KAAK,MAAM;AACzD;;AAGA,IAAM,mBAAN,MAAuB;CAGrB,AAAO,YACL,AAAiB,YACjB,AAAiB,QACjB;EAFiB;EACA;gBA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A8C;GACtE,QAAQ,OAAO,SAAS,YAAY,KAAK,OAAO,WAAW;GAC3D;EACF;EACA,IAAI,CAAC,YAAY,KAAK,YAAY,KAAK,8CAA8C;EACrF,IAAI,gBAAgB,UAAa,CAAC,GAAG,MAAM,KAAK,CAAC,CAAC,CAAC,MAAM,UAAU,YAAY,SAAS,KAAK,CAAC,GAC5F,KAAK,YAAY,KAAK,6CAA6C;EACrE,eAAe,YAAY,OAAO,KAAK,aAAa,SAAS,IAAI;CACnE;AACF;;AAGA,SAAgB,sBAAsB,OAKX;CACzB,MAAM,EAAE,YAAY,QAAQ,kBAAkB,gBAAgB;CAC9D,MAAM,SAAS,IAAI,iBAAiB,YAAY,MAAM,CAAC,CAAC,MAAM;CAC9D,IAAI,CAAC,SAAS,MAAM,GAAG,KAAK,YAAY,KAAK,mCAAmC;CAChF,MAAM,aAAa,OAAO,IAAI,QAAQ;CACtC,IAAI,eAAe,UAAa,OAAO,eAAe,UACpD,KAAK,YAAY,UAAU,2BAA2B;CACxD,MAAM,QACJ,eAAe,SACX,qBAAqB,KACnB,KACA,cAAc,YAAY,gBAAgB,IAC5C,cAAc,YAAY,UAAU;CAC1C,MAAM,UAAmC,OAAO,OAAO,IAAI;CAC3D,MAAM,cAAc,IAAI,IAAI,MAAM;CAClC,YAAY,OAAO,QAAQ;CAC3B,eAAe,YAAY,aAAa,OAAO,aAAa,SAAS,KAAK;CAC1E,OAAO;EAAE;EAAY;EAAO;CAAQ;AACtC"}
@@ -0,0 +1,12 @@
1
+ //#region ../core/src/localization/register-locale-dictionary.d.ts
2
+ declare function registerGroupedTranslationKeys(sourceFile: string, keys: readonly string[]): void;
3
+ /** Undo JSON entries during HMR while preserving unrelated global translations. */
4
+ declare function unregisterLocaleDictionary(sourceFile: string): void;
5
+ declare function registerLocaleDictionary(input: {
6
+ sourceFile: string;
7
+ source: string;
8
+ defaultNamespace: string;
9
+ }): () => void;
10
+ //#endregion
11
+ export { registerGroupedTranslationKeys, registerLocaleDictionary, unregisterLocaleDictionary };
12
+ //# sourceMappingURL=register-locale-dictionary.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"register-locale-dictionary.d.mts","names":[],"sources":["../../../../../../../core/src/localization/register-locale-dictionary.ts"],"mappings":";iBAwBgB,8BAAA,CAA+B,UAAA,UAAoB,IAAuB;AAA1F;AAAA,iBAKgB,0BAAA,CAA2B,UAAkB;AAAA,iBAyB7C,wBAAA,CAAyB,KAAA;EACvC,UAAA;EACA,MAAA;EACA,gBAAA;AAAA"}
@@ -0,0 +1,58 @@
1
+ import { parseLocaleDictionary } from "./parse-locale-dictionary.mjs";
2
+ import config from "@mongez/config";
3
+ import { getTranslationsList, groupedTranslations, setTranslationsList } from "@mongez/localization";
4
+
5
+ //#region ../core/src/localization/register-locale-dictionary.ts
6
+ const owners = /* @__PURE__ */ new Map();
7
+ const keysBySource = /* @__PURE__ */ new Map();
8
+ function claim(sourceFile, kind, keys) {
9
+ for (const key of keys) {
10
+ const owner = owners.get(key);
11
+ if (owner && owner.sourceFile !== sourceFile) throw new Error(`Translation key "${key}" is owned by both "${owner.sourceFile}" and "${sourceFile}".`);
12
+ }
13
+ for (const key of keys) owners.set(key, {
14
+ sourceFile,
15
+ kind
16
+ });
17
+ keysBySource.set(sourceFile, [...keys]);
18
+ }
19
+ function registerGroupedTranslationKeys(sourceFile, keys) {
20
+ claim(sourceFile, "ts", keys);
21
+ }
22
+ /** Undo JSON entries during HMR while preserving unrelated global translations. */
23
+ function unregisterLocaleDictionary(sourceFile) {
24
+ const keys = keysBySource.get(sourceFile) ?? [];
25
+ keysBySource.delete(sourceFile);
26
+ for (const key of keys) owners.delete(key);
27
+ const translations = getTranslationsList();
28
+ for (const key of keys) for (const locale of Object.keys(translations)) {
29
+ const segments = key.split(".");
30
+ let target = translations[locale];
31
+ for (const segment of segments.slice(0, -1)) {
32
+ const next = target?.[segment];
33
+ if (!next || typeof next !== "object") {
34
+ target = void 0;
35
+ break;
36
+ }
37
+ target = next;
38
+ }
39
+ if (target) delete target[segments.at(-1)];
40
+ }
41
+ setTranslationsList(translations);
42
+ }
43
+ function registerLocaleDictionary(input) {
44
+ unregisterLocaleDictionary(input.sourceFile);
45
+ const localeCodes = config.get("app.localeCodes");
46
+ const parsed = parseLocaleDictionary({
47
+ ...input,
48
+ localeCodes: Array.isArray(localeCodes) ? localeCodes : void 0
49
+ });
50
+ const keys = Object.keys(parsed.entries);
51
+ claim(input.sourceFile, "json", keys);
52
+ groupedTranslations(parsed.entries);
53
+ return () => unregisterLocaleDictionary(input.sourceFile);
54
+ }
55
+
56
+ //#endregion
57
+ export { registerGroupedTranslationKeys, registerLocaleDictionary, unregisterLocaleDictionary };
58
+ //# sourceMappingURL=register-locale-dictionary.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"register-locale-dictionary.mjs","names":[],"sources":["../../../../../../../core/src/localization/register-locale-dictionary.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport {\n getTranslationsList,\n groupedTranslations,\n setTranslationsList,\n} from \"@mongez/localization\";\nimport { parseLocaleDictionary } from \"./parse-locale-dictionary\";\n\ntype Owner = { sourceFile: string; kind: \"json\" | \"ts\" };\nconst owners = new Map<string, Owner>();\nconst keysBySource = new Map<string, string[]>();\n\nfunction claim(sourceFile: string, kind: Owner[\"kind\"], keys: readonly string[]): void {\n for (const key of keys) {\n const owner = owners.get(key);\n if (owner && owner.sourceFile !== sourceFile)\n throw new Error(\n `Translation key \"${key}\" is owned by both \"${owner.sourceFile}\" and \"${sourceFile}\".`,\n );\n }\n for (const key of keys) owners.set(key, { sourceFile, kind });\n keysBySource.set(sourceFile, [...keys]);\n}\n\nexport function registerGroupedTranslationKeys(sourceFile: string, keys: readonly string[]): void {\n claim(sourceFile, \"ts\", keys);\n}\n\n/** Undo JSON entries during HMR while preserving unrelated global translations. */\nexport function unregisterLocaleDictionary(sourceFile: string): void {\n const keys = keysBySource.get(sourceFile) ?? [];\n keysBySource.delete(sourceFile);\n for (const key of keys) owners.delete(key);\n const translations = getTranslationsList();\n for (const key of keys)\n for (const locale of Object.keys(translations)) {\n const segments = key.split(\".\");\n let target: Record<string, unknown> | undefined = translations[locale] as Record<\n string,\n unknown\n >;\n for (const segment of segments.slice(0, -1)) {\n const next = target?.[segment];\n if (!next || typeof next !== \"object\") {\n target = undefined;\n break;\n }\n target = next as Record<string, unknown>;\n }\n if (target) delete target[segments.at(-1)!];\n }\n setTranslationsList(translations);\n}\n\nexport function registerLocaleDictionary(input: {\n sourceFile: string;\n source: string;\n defaultNamespace: string;\n}): () => void {\n unregisterLocaleDictionary(input.sourceFile);\n const localeCodes = config.get(\"app.localeCodes\");\n const parsed = parseLocaleDictionary({\n ...input,\n localeCodes: Array.isArray(localeCodes) ? localeCodes : undefined,\n });\n const keys = Object.keys(parsed.entries);\n claim(input.sourceFile, \"json\", keys);\n groupedTranslations(parsed.entries);\n return () => unregisterLocaleDictionary(input.sourceFile);\n}\n"],"mappings":";;;;;AASA,MAAM,yBAAS,IAAI,IAAmB;AACtC,MAAM,+BAAe,IAAI,IAAsB;AAE/C,SAAS,MAAM,YAAoB,MAAqB,MAA+B;CACrF,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,QAAQ,OAAO,IAAI,GAAG;EAC5B,IAAI,SAAS,MAAM,eAAe,YAChC,MAAM,IAAI,MACR,oBAAoB,IAAI,sBAAsB,MAAM,WAAW,SAAS,WAAW,GACrF;CACJ;CACA,KAAK,MAAM,OAAO,MAAM,OAAO,IAAI,KAAK;EAAE;EAAY;CAAK,CAAC;CAC5D,aAAa,IAAI,YAAY,CAAC,GAAG,IAAI,CAAC;AACxC;AAEA,SAAgB,+BAA+B,YAAoB,MAA+B;CAChG,MAAM,YAAY,MAAM,IAAI;AAC9B;;AAGA,SAAgB,2BAA2B,YAA0B;CACnE,MAAM,OAAO,aAAa,IAAI,UAAU,KAAK,CAAC;CAC9C,aAAa,OAAO,UAAU;CAC9B,KAAK,MAAM,OAAO,MAAM,OAAO,OAAO,GAAG;CACzC,MAAM,eAAe,oBAAoB;CACzC,KAAK,MAAM,OAAO,MAChB,KAAK,MAAM,UAAU,OAAO,KAAK,YAAY,GAAG;EAC9C,MAAM,WAAW,IAAI,MAAM,GAAG;EAC9B,IAAI,SAA8C,aAAa;EAI/D,KAAK,MAAM,WAAW,SAAS,MAAM,GAAG,EAAE,GAAG;GAC3C,MAAM,OAAO,SAAS;GACtB,IAAI,CAAC,QAAQ,OAAO,SAAS,UAAU;IACrC,SAAS;IACT;GACF;GACA,SAAS;EACX;EACA,IAAI,QAAQ,OAAO,OAAO,SAAS,GAAG,EAAE;CAC1C;CACF,oBAAoB,YAAY;AAClC;AAEA,SAAgB,yBAAyB,OAI1B;CACb,2BAA2B,MAAM,UAAU;CAC3C,MAAM,cAAc,OAAO,IAAI,iBAAiB;CAChD,MAAM,SAAS,sBAAsB;EACnC,GAAG;EACH,aAAa,MAAM,QAAQ,WAAW,IAAI,cAAc;CAC1D,CAAC;CACD,MAAM,OAAO,OAAO,KAAK,OAAO,OAAO;CACvC,MAAM,MAAM,YAAY,QAAQ,IAAI;CACpC,oBAAoB,OAAO,OAAO;CAClC,aAAa,2BAA2B,MAAM,UAAU;AAC1D"}
@@ -278,7 +278,7 @@ bootstrap();
278
278
  * Returns relative paths from .warlock/production/ to src/app/
279
279
  */
280
280
  async globModule(matches) {
281
- return (await glob("**/*.{ts,tsx}", {
281
+ return (await glob("**/*.{ts,tsx,json}", {
282
282
  cwd: appPath(),
283
283
  absolute: false
284
284
  })).filter((file) => matches("src/app/" + file)).sort().map((file) => "../../src/app/" + file.replace(/\.(ts|tsx)$/, ""));
@@ -327,7 +327,16 @@ bootstrap();
327
327
  async generateLocales() {
328
328
  const files = await this.globModule(isLocaleFile);
329
329
  if (files.length === 0) return false;
330
- await this.generateImportsFile(files, "locales.ts");
330
+ const content = files.map((file, index) => {
331
+ if (!file.endsWith(".json")) return `import "${file}";`;
332
+ const moduleFolder = file.split("/").at(-3);
333
+ return [
334
+ `import dictionary${index} from "${file}";`,
335
+ "import { registerLocaleDictionary } from \"@warlock.js/core\";",
336
+ `registerLocaleDictionary({ sourceFile: ${JSON.stringify(file)}, source: JSON.stringify(dictionary${index}), defaultNamespace: ${JSON.stringify(moduleFolder)} });`
337
+ ].join("\n");
338
+ }).join("\n");
339
+ await putFileAsync(path.join(this.productionDir, "locales.ts"), content + "\n");
331
340
  return true;
332
341
  }
333
342
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"production-builder.mjs","names":[],"sources":["../../../../../../../core/src/production/production-builder.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport {\n ensureDirectoryAsync,\n fileExistsAsync,\n getFileAsync,\n getJsonFileAsync,\n putFileAsync,\n removeDirectoryAsync,\n} from \"@warlock.js/fs\";\nimport esbuild from \"esbuild\";\nimport glob from \"fast-glob\";\nimport path from \"path\";\nimport { assertNoReservedConnectorNames } from \"../connectors/assert-no-reserved-connector-names\";\nimport { assertUniqueConnectorNames } from \"../connectors/assert-unique-connector-names\";\nimport type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\nimport { configKeyFromPath } from \"../config/config-key-from-path\";\nimport {\n isConfigFile,\n isEventFile,\n isLocaleFile,\n isMainFile,\n isRouteFile,\n isWorkerFile,\n} from \"../dev-server/special-file-patterns\";\nimport { tsconfigManager } from \"../dev-server/tsconfig-manager\";\nimport { appPath, rootPath, warlockPath } from \"../utils\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\nimport { bundleFrameworkDependencies } from \"./bundle-framework-dependencies\";\nimport { dedupe, runEmitContributions, runGenerateContributions } from \"./build-contributions\";\nimport { writeDistBuildManifestAsync } from \"./dist-build-manifest\";\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\nimport { assertEsbuildBinaryIsLinked } from \"./esbuild-preflight\";\nimport { collectRouteRegistrationSnapshot } from \"./route-registration-snapshot\";\nimport { clearOwnedRouteTypes } from \"../dev-server/route-types-publisher\";\nimport {\n commitDistAsync,\n createTempOutputDir,\n rollbackDistAsync,\n stageDistAsync,\n type StagedDist,\n} from \"./promote-dist\";\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\nimport { tsconfigPathAliases } from \"./tsconfig-path-aliases\";\nimport { toKebabCase } from \"@mongez/reinforcements\";\n\n/**\n * Recreates `require`, `__filename` and `__dirname` at the top of an ESM bundle.\n *\n * Bundled CommonJS dependencies call `require(\"node:assert\")` and read\n * `__dirname` to locate their own assets. Neither exists in an ES module, so\n * esbuild substitutes a stub that throws — **after the build has reported\n * success**. `Dynamic require of \"node:assert\" is not supported` is that stub\n * firing, and it is the defect this shim removes.\n *\n * `__dirname` matters as much as `require`: without it a dependency resolving\n * an asset path silently gets `undefined` and fails later, further from the\n * cause.\n *\n * Written as one line because esbuild inserts a banner verbatim above the\n * bundle and a multi-line string here would shift every mapped line.\n */\nconst ESM_INTEROP_SHIM =\n \"import{createRequire as __wlCreateRequire}from'node:module';\" +\n \"import{fileURLToPath as __wlFileURLToPath}from'node:url';\" +\n \"import{dirname as __wlDirname}from'node:path';\" +\n \"const require=__wlCreateRequire(import.meta.url);\" +\n \"const __filename=__wlFileURLToPath(import.meta.url);\" +\n \"const __dirname=__wlDirname(__filename);\";\n\n/**\n * Combine the framework's banner with the user's, keeping both.\n *\n * esbuild's `banner` is an object keyed by output type, and every merge in the\n * path to it — the config merge and the options spread — REPLACES that object\n * rather than merging it. So whichever is applied second silently deletes the\n * other. This is the only place the two can coexist.\n *\n * The shim goes first: it defines `require`, which a user banner may use.\n *\n * @param userBanner banner from `warlock.config.ts`, if any\n * @param shim the interop shim, or undefined when it does not apply\n */\nfunction mergeBanner(\n userBanner: Record<string, string> | undefined,\n shim: string | undefined,\n): Record<string, string> | undefined {\n if (!shim) return userBanner;\n\n const userJs = userBanner?.js;\n\n return {\n ...userBanner,\n js: userJs ? `${shim}${userJs}` : shim,\n };\n}\n\n/**\n * Prefix every generated file uses to reach the app root.\n *\n * Generated sources are written into `.warlock/production/`, two levels below\n * the app root, so `../../` lands back on it — the same hop already spelled\n * out in the `../../src/app/…` and `../../src/config/…` imports the module and\n * config-loader generators emit. Named once so a generator that needs a new\n * app-root file (`warlock.config`) cannot pick a different depth.\n */\nconst APP_ROOT_FROM_PRODUCTION_DIR = \"../../\";\n\n/**\n * Production Builder\n * Generates production-ready files and bundles them for deployment\n * Build options are loaded from warlock.config.ts\n */\nexport class ProductionBuilder {\n private options!: ResolvedBuildConfig;\n private readonly productionDir = warlockPath(\"production\");\n\n /**\n * Connectors declared in `warlock.config.ts`. Read statically — `build`\n * never calls `boot()`/`start()` on them; it only\n * drains their `build` contributions.\n */\n private connectors: readonly Connector[] = [];\n\n /**\n * The contributors' merged esbuild patch, produced by the `generate` pass\n * and consumed by {@link bundle}.\n */\n private contributedEsbuild: ConnectorEsbuildPatch = {};\n\n /** Browser-safe API metadata captured in a fresh registration-only child. */\n private namedApiRoutes?: readonly import(\"../router/types\").NamedApiRoute[];\n\n /**\n * Main build entry point\n *\n * The esbuild bundle is written into a TEMP directory next to the real\n * output directory, never into it, and that directory is renamed over\n * `outdir` as one filesystem operation — so `outdir` is never observed as\n * a mix of the old build and the new one, and a build that fails before\n * that rename never touches `outdir` at all.\n *\n * `this.options.outdir` is NOT repointed at the temp directory while that\n * happens, and must never be. It is not merely a write target: consumers\n * BAKE it into runtime output — `web`'s build contribution derives the\n * `clientDir` recorded in its pages manifest from it\n * (`web/src/build/contribution.ts`) — so a temp path reaching them\n * produces an artifact whose browser paths point at a directory promotion\n * has since renamed away. The temp path is passed explicitly, as a\n * parameter, to the one operation that writes into it ({@link bundle});\n * everything else, `buildContext()` included, keeps reading the final\n * destination.\n *\n * That is also why promotion is STAGED rather than done at the very end.\n * Connector `emit` hooks write real artifacts (the web client bundle) and\n * see the final `outdir`, so they must run when `outdir` genuinely holds\n * this build — after the rename, not before it, or promotion would replace\n * the directory they just wrote into. The previous build is kept parked\n * aside until they finish: `emit` throwing rolls the whole promotion back,\n * and the build-success marker `warlock start` checks is written last of\n * all, so a failure at any point leaves no `dist` that start will boot.\n */\n public async build(): Promise<void> {\n console.log(colors.cyan(\"Building for production...\\n\"));\n\n // Step 0: Fail fast when esbuild's native binary never got linked (the\n // state pnpm leaves a project in when its build-script approval gate\n // blocked esbuild's postinstall) rather than let bundling die on esbuild's\n // own cryptic \"package could not be found\" error several steps from now.\n assertEsbuildBinaryIsLinked();\n\n // Step 1: Initialize options from config\n await this.initializeOptions();\n\n const finalOutDir = this.options.outdir!;\n const tempOutDir = createTempOutputDir(finalOutDir);\n\n // Set once the temp directory has been renamed onto `finalOutDir`. Its\n // presence is what tells the catch below whether a failure has a\n // promotion to undo or only a temp directory to discard.\n let staged: StagedDist | undefined;\n\n try {\n // Step 2: Generate combined files\n await this.generateCombinedFiles();\n\n // Step 3: Generate entry point\n await this.generateEntryPoint();\n\n // Step 4: Refuse to bundle code the app could not resolve at runtime\n await this.assertGeneratedImports();\n\n // Step 4.5: Drain the connectors' `generate` contributions\n await this.captureNamedApiRoutesForWeb();\n const contributed = await this.runGenerateContributions();\n\n // Step 4.6: Re-assert over what the contributors just wrote.\n //\n // Step 4 only saw core's own generated files; a contributor writes its\n // code (a pages barrel, say) AFTER that assertion, so an undeclared bare\n // specifier in it reaches the bundle unchecked. Under\n // `packages: \"external\"` that specifier survives verbatim into the\n // artifact and dies as ERR_MODULE_NOT_FOUND at runtime — the same failure\n // step 4 exists to prevent. Skipped when nothing contributed: re-globbing\n // and re-reading the production dir is pure cost in the common case.\n if (contributed) {\n await this.assertGeneratedImports();\n }\n\n // Step 5: Bundle with esbuild into the temp directory. The ONLY\n // operation handed that path — it is a write target, not config.\n await this.bundle(tempOutDir);\n\n // Step 5.5: Promote the bundle into `outdir`, keeping the previous\n // build parked aside. `outdir` now holds exactly this build, so the\n // steps below write into — and record — the real destination.\n staged = await stageDistAsync(tempOutDir, finalOutDir);\n\n // Step 5.6: Drain the connectors' `emit` contributions — after the\n // bundle is in place (so what they write survives promotion and the\n // paths they bake in resolve), and BEFORE step 6 deletes the\n // production directory they may still read.\n await runEmitContributions(this.connectors, this.buildContext());\n\n // Step 5.7: Mark `dist` as a genuine, complete build — the one thing\n // `warlock start` trusts. Written LAST on purpose: every earlier step\n // can still fail, and until this file exists nothing will boot what\n // they left behind.\n await writeDistBuildManifestAsync(finalOutDir);\n\n // Step 5.8: Commit — drop the parked previous build. Cannot throw.\n await commitDistAsync(staged);\n } catch (error) {\n if (staged) {\n // The promotion already happened; put the previous build back and\n // take this half-finished one out of `outdir`.\n await rollbackDistAsync(staged);\n } else {\n // Nothing this build produced ever reached `outdir` — discard the\n // temp directory and leave `outdir` exactly as it was.\n await removeDirectoryAsync(tempOutDir).catch(() => undefined);\n }\n\n throw error;\n }\n\n // Step 6: Remove production folder\n await removeDirectoryAsync(this.productionDir);\n\n console.log(colors.green(\"Build complete!\"));\n console.log(`Start production server by running ${colors.cyan(\"warlock start\")}`);\n }\n\n /**\n * Initialize options from warlock.config.ts\n */\n private async initializeOptions(): Promise<void> {\n this.options = resolveBuildConfig();\n // Same config object `resolveBuildConfig` just read — `warlock build`\n // preloads warlock.config.ts, so no additional load happens here.\n const connectors = warlockConfigManager.get(\"connectors\") ?? [];\n\n // Checked here, where the array is first read, so nothing downstream has\n // drained anything yet: the `generate` and `emit` passes run per ENTRY, so\n // a name listed twice would write its files and merge its esbuild options\n // twice into an artifact the runtime then boots that name only once from.\n // A build that half-applied a connector and reported success is worse than\n // one that never started.\n assertUniqueConnectorNames([...connectors]);\n\n // And here rather than only at boot, for the same reason: a name a built-in\n // already owns is skipped by the runtime, so an artifact built from it\n // carries the custom connector's generated files and esbuild patches while\n // the server boots the built-in instead. Refusing it at boot alone would\n // mean the build had already emitted that artifact — the failure has to\n // land on the developer running `warlock build`, not on whoever starts the\n // server. Same assertion the registration half calls, over the same names.\n assertNoReservedConnectorNames([...connectors]);\n\n this.connectors = connectors;\n\n // Ensure production directory exists\n await ensureDirectoryAsync(this.productionDir);\n }\n\n /**\n * The context handed to every build contribution.\n */\n private buildContext(): ConnectorBuildContext {\n return {\n productionDir: this.productionDir,\n appRoot: rootPath(),\n options: this.options,\n namedApiRoutes: this.namedApiRoutes,\n };\n }\n\n /**\n * Web route declarations need application API registration, which cannot be\n * inferred from generated files. Capture it once in a disposable child before\n * contributors write build artifacts; no connector lifecycle runs there.\n */\n private async captureNamedApiRoutesForWeb(): Promise<void> {\n if (!this.connectors.some((connector) => connector.name === \"web\")) {\n await clearOwnedRouteTypes(rootPath());\n return;\n }\n\n this.namedApiRoutes = (\n await collectRouteRegistrationSnapshot({\n cwd: rootPath(),\n timeoutMs: this.options.routeRegistrationTimeoutMs,\n })\n ).routes;\n }\n\n /**\n * Drain the `generate` hooks and fold what they returned back into the\n * build.\n *\n * The entry point is REGENERATED here rather than generated later. The\n * contribution slot is fixed — after `assertGeneratedImports` (so nothing\n * bundles that the app could not resolve) and before `bundle` — while\n * `generateEntryPoint` must stay at step 3, because `app.ts` is itself\n * generated code the assertion has to see; moving it past the assertion\n * would silently drop the entry from that check. Rewriting one small file\n * is cheaper than losing either guarantee, and the write is pure\n * (`generatedFiles` + these imports), so doing it twice is not a\n * correctness risk.\n *\n * @returns whether any connector ran a `generate` hook — the caller uses it\n * to decide if the import assertion is worth a second pass. Keyed on the\n * hook EXISTING, not on what it returned: a hook that returns nothing may\n * still have written files into `productionDir`, and those are exactly the\n * files the second pass is there to read.\n */\n private async runGenerateContributions(): Promise<boolean> {\n const contributed = this.connectors.some((connector) => Boolean(connector.build?.generate));\n\n const { entryImports, esbuild } = await runGenerateContributions(\n this.connectors,\n this.buildContext(),\n );\n\n this.contributedEsbuild = esbuild;\n\n if (entryImports.length > 0) {\n await this.generateEntryPoint(entryImports);\n }\n\n return contributed;\n }\n\n /**\n * Track which special files were generated\n */\n private generatedFiles = {\n locales: false,\n events: false,\n main: false,\n routes: false,\n workers: false,\n };\n\n /**\n * Generate all combined files\n */\n private async generateCombinedFiles(): Promise<void> {\n console.log(colors.yellow(\" Generating production files...\"));\n\n // Generate bootstrap.ts file\n await this.generateBootstrap();\n\n // Generate config loader\n await this.generateConfigLoader();\n\n // Generate special files and track which ones have content\n const [locales, events, main, routes, workers] = await Promise.all([\n this.generateLocales(),\n this.generateEvents(),\n this.generateMain(),\n this.generateRoutes(),\n this.generateWorkers(),\n ]);\n\n this.generatedFiles = { locales, events, main, routes, workers };\n }\n\n /**\n * Generate bootstrap.ts - ensures bootstrap() runs first and sets production environment\n */\n private async generateBootstrap(): Promise<void> {\n // ESM hoists imports, so the app bootstrap must be the first import to run first\n const appBootstrapImport = (await fileExistsAsync(appPath(\"bootstrap.ts\")))\n ? \"import './../../src/app/bootstrap';\\n\"\n : \"\";\n\n const content = `${appBootstrapImport}import { bootstrap, Application } from \"@warlock.js/core\";\n\n// Production runtime; NODE_ENV is only defaulted so an explicit value (e.g. staging) wins\nApplication.setRuntimeStrategy(\"production\");\nif (!process.env.NODE_ENV) {\n Application.setEnvironment(\"production\");\n}\n\n// Bootstrap the application\nbootstrap();\n`;\n\n await putFileAsync(path.join(this.productionDir, \"bootstrap.ts\"), content);\n }\n\n /**\n * Fail the build when generated code imports a package the app does not\n * declare.\n *\n * The bundler is configured `packages: \"external\"`, so every bare specifier\n * written above survives verbatim into an artifact that resolves against the\n * **consuming app's** node_modules. A framework-internal dependency imported\n * there resolves by accident under npm/yarn hoisting and dies under pnpm —\n * which is how a production app shipped that could not boot. Rewriting the\n * offending import fixes today's bundle; this check is what stops the next\n * change to the generator from quietly reintroducing it.\n */\n private async assertGeneratedImports(): Promise<void> {\n const generatedPaths = await glob(\"**/*.{ts,tsx,js,mjs}\", {\n cwd: this.productionDir,\n absolute: false,\n });\n\n const [files, appPackage] = await Promise.all([\n Promise.all(\n generatedPaths.map(async (file) => ({\n file,\n content: await getFileAsync(path.join(this.productionDir, file)),\n })),\n ),\n getJsonFileAsync<{ dependencies?: Record<string, string> }>(rootPath(\"package.json\")),\n ]);\n\n assertGeneratedImportsAreDeclared(files, Object.keys(appPackage.dependencies ?? {}));\n }\n\n /**\n * Glob `src/app` and keep the files the shared dev-server predicate accepts,\n * so production discovers exactly what the dev collector does.\n * Returns relative paths from .warlock/production/ to src/app/\n */\n private async globModule(matches: (relativePath: string) => boolean): Promise<string[]> {\n const files = await glob(\"**/*.{ts,tsx}\", {\n cwd: appPath(),\n absolute: false,\n });\n\n // e.g., \"users/main.ts\" -> \"../../src/app/users/main\"\n return files\n .filter((file) => matches(\"src/app/\" + file))\n .sort()\n .map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\n }\n\n /**\n * Generate config-loader.ts\n */\n private async generateConfigLoader(): Promise<void> {\n const configDirectory = path.join(process.cwd(), \"src/config\");\n\n const files = await glob(\"**/*.{ts,tsx}\", {\n cwd: configDirectory,\n absolute: false,\n });\n\n // Same key rule as the dev config loader: the raw path, never camel-cased\n const configNames = files\n .filter((f) => isConfigFile(\"src/config/\" + f))\n .map((f) => ({\n path: f.replace(/\\.(ts|tsx)$/, \"\"),\n key: configKeyFromPath(\"src/config/\" + f),\n }))\n .filter((entry): entry is { path: string; key: string } => entry.key !== undefined)\n .sort((a, b) => a.path.localeCompare(b.path));\n\n // Only `@warlock.js/core` — the one package the app itself declares. See\n // `assertGeneratedImportsAreDeclared`: `@mongez/config` is core's own\n // dependency, so a bare import of it resolved by luck under npm/yarn\n // hoisting and died under pnpm's strict layout.\n const imports: string[] = [\n 'import { setConfig, configSpecialHandlers } from \"@warlock.js/core\";',\n ];\n const configImports: string[] = [];\n const configSetCalls: string[] = [];\n const executors: string[] = [];\n\n configNames.forEach(({ path: configPath, key }, index) => {\n // Index-based identifier: keys like \"rate-limit\" or \"mail/smtp\" are not valid names\n const varName = `config${index}`;\n configImports.push(`import ${varName} from \"../../src/config/${configPath}\";`);\n configSetCalls.push(`setConfig(${JSON.stringify(key)}, ${varName});`);\n executors.push(`await configSpecialHandlers.execute(${JSON.stringify(key)}, ${varName});`);\n });\n\n // ESM hoists imports, so prestart must be the first import to run first\n const prestartImports = (await fileExistsAsync(appPath(\"prestart.ts\")))\n ? [\"import './../../src/app/prestart';\"]\n : [];\n\n const content = [\n ...prestartImports,\n ...imports,\n \"\",\n \"// Config imports\",\n ...configImports,\n \"\",\n \"// Register configs\",\n ...configSetCalls,\n \"\",\n \"// Special handlers\",\n ...executors,\n \"\",\n ].join(\"\\n\");\n\n await putFileAsync(path.join(this.productionDir, \"config-loader.ts\"), content);\n }\n\n /**\n * Generate locales.ts (only if there are locale files)\n * @returns true if file was generated with content\n */\n private async generateLocales(): Promise<boolean> {\n const files = await this.globModule(isLocaleFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"locales.ts\");\n return true;\n }\n\n /**\n * Generate events.ts (only if there are event files)\n * @returns true if file was generated with content\n */\n private async generateEvents(): Promise<boolean> {\n const files = await this.globModule(isEventFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"events.ts\");\n return true;\n }\n\n /**\n * Generate main.ts (only if there are main files)\n * @returns true if file was generated with content\n */\n private async generateMain(): Promise<boolean> {\n const files = await this.globModule(isMainFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"main.ts\");\n return true;\n }\n\n /**\n * Generate routes.ts (only if there are route files)\n * @returns true if file was generated with content\n */\n private async generateRoutes(): Promise<boolean> {\n const files = await this.globModule(isRouteFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"routes.ts\");\n return true;\n }\n\n /**\n * Generate workers.ts (only if there are worker files)\n * @returns true if file was generated with content\n */\n private async generateWorkers(): Promise<boolean> {\n const files = await this.globModule(isWorkerFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"workers.ts\");\n return true;\n }\n\n /**\n * Generate a file with imports from all given files\n */\n private async generateImportsFile(importPaths: string[], outputFile: string): Promise<void> {\n const imports = importPaths.map((importPath) => `import \"${importPath}\";`);\n const content = imports.join(\"\\n\") + \"\\n\";\n await putFileAsync(path.join(this.productionDir, outputFile), content);\n }\n\n /**\n * Generate the main entry point (app.ts)\n *\n * @param contributedImports lines from connector `generate` hooks, appended\n * to section 4 after `./routes`\n */\n private async generateEntryPoint(contributedImports: string[] = []): Promise<void> {\n console.log(colors.yellow(\" Generating entry point...\"));\n\n // The names this build resolved, baked in as a literal. The entry imports\n // the config source, and that source is re-evaluated at startup — an\n // env-conditional `connectors` array can hand the boot a different list\n // than the one drained here. A literal is the only part of the array that\n // survives into the artifact unchanged, so it is what the boot compares\n // against.\n const expectedNames = this.connectors\n .map((connector) => JSON.stringify(connector.name))\n .join(\", \");\n\n // Build imports based on which files were generated\n const imports: string[] = [\n \"// 1. Bootstrap (loads .env, initializes framework)\",\n 'import \"./bootstrap\";',\n \"\",\n \"// 2. Load configs\",\n 'import \"./config-loader\";',\n \"\",\n // Registration has to sit between the config being available and the\n // first phase starting: the connectors listed in `connectors` are the\n // same ones this build drained contributions from, so the bundle boots\n // exactly what it was built for. Register any later and an early-phase\n // connector would miss its own start.\n \"// 2.5 Register connectors declared in warlock.config (the same array this\",\n \"// build read its contributions from, so built-for and boots-with match).\",\n \"// The config is imported STATICALLY so esbuild bakes it into the bundle\",\n \"// and the array is handed over explicitly — an artifact has no\",\n \"// warlock.config.ts beside it to read at runtime, and a registration\",\n \"// that quietly found nothing to register is the exact drift this\",\n \"// section exists to prevent.\",\n \"// `expectedNames` is the list this build resolved, in order — boot\",\n \"// refuses to start when the config hands over a different set or order.\",\n 'import { registerConfiguredConnectors } from \"@warlock.js/core\";',\n `import warlockConfig from \"${APP_ROOT_FROM_PRODUCTION_DIR}warlock.config\";`,\n `registerConfiguredConnectors(warlockConfig.connectors ?? [], { expectedNames: [${expectedNames}] });`,\n \"\",\n \"// 2.6 Fail fast on a busy port. `http` is a LATE-phase connector, so its\",\n \"// own preflight is not reached until the database and cache have\",\n \"// connected and every app module has been imported — seconds of work\",\n \"// thrown away before anyone learns the port was taken. This probe is\",\n \"// a bind-and-release on a socket that is never served, and it reports\",\n \"// on stderr because no log channel is configured this early.\",\n 'import { Application, connectorsManager, ConnectorLifecyclePhase, preflightConfiguredHttpPort } from \"@warlock.js/core\";',\n 'if (Application.hasRole(\"api\") || Application.hasRole(\"web\")) {',\n \" await preflightConfiguredHttpPort();\",\n \"}\",\n \"\",\n \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\n \"// so data sources, cache, etc. are ready before app code runs\",\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\",\n ];\n\n // App code uses dynamic `await import(...)` so each module's side\n // effects fire at THIS point in execution. Static imports would be\n // hoisted to module-instantiation time (before the early-phase await\n // resolves), which is exactly the bug this split is meant to fix.\n //\n // The guarantee comes from the imports being DYNAMIC — esbuild wraps a\n // dynamically-imported module in its `__esm(() => {…})` helper and runs\n // it at the await, not at instantiation. It does NOT come from\n // `splitting: true`, which only decides one-file-vs-chunks. This\n // previously said splitting was required; it is not, and `singleBundle`\n // (splitting: false) preserves the ordering.\n imports.push(\"\", \"// 4. Load app code (events, locales, main, routes)\");\n\n if (this.generatedFiles.events) {\n imports.push('await import(\"./events\");');\n }\n if (this.generatedFiles.locales) {\n imports.push('await import(\"./locales\");');\n }\n if (this.generatedFiles.main) {\n imports.push('await import(\"./main\");');\n }\n if (this.generatedFiles.routes) {\n imports.push('if (Application.hasRole(\"api\")) {', ' await import(\"./routes\");', \"}\");\n }\n if (this.generatedFiles.workers) {\n imports.push('if (Application.hasRole(\"worker\")) {', ' await import(\"./workers\");', \"}\");\n }\n\n // Contributor imports come AFTER `./routes`, never before: a connector\n // that registers pages needs the routes app code already collected —\n // the same ordering dev uses (routes first, then the connector installs\n // on top of them). Emitted verbatim; the contributor writes the whole\n // statement (e.g. `await import(\"./pages\");`).\n imports.push(...contributedImports);\n\n // A rejecting validator (Application.onValidateBoot) must abort boot\n // before late-phase connectors bind a port.\n imports.push(\n \"\",\n \"// 5. Run startup validators registered via Application.onValidateBoot(...)\",\n \"await Application.runStartupValidators();\",\n );\n\n // Start late-phase connectors after app code registers routes/listeners\n imports.push(\n \"\",\n \"// 6. Start late-phase connectors (http, socket) — routes and\",\n \"// listeners registered by app code are now ready to bind\",\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\",\n \"\",\n \"// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire\",\n \"Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });\",\n \"connectorsManager.shutdownOnProcessKill();\",\n );\n\n const content = imports.join(\"\\n\") + \"\\n\";\n await putFileAsync(path.join(this.productionDir, \"app.ts\"), content);\n }\n\n /**\n * Bundle with esbuild\n *\n * @param writeOutDir the directory esbuild writes into — the build's\n * private temp directory, NOT `options.outdir`. Taken as a parameter\n * rather than read off `this.options` because the two are different paths\n * with different meanings: `options.outdir` is the final destination every\n * consumer bakes into the artifact, and this is only where bytes land\n * before promotion moves them there.\n */\n private async bundle(writeOutDir: string): Promise<void> {\n console.log(colors.magenta(\" Bundling with esbuild...\"));\n\n const entryPoint = path.join(this.productionDir, \"app.ts\");\n const outFileName = this.options.outFile!;\n // Strip extension so entryNames produces \"<base>.js\" via esbuild\n const entryName = path.basename(outFileName, path.extname(outFileName));\n\n // `singleBundle` and `esmShim` are ours, not esbuild's — it throws on\n // unknown keys, and the user options are spread into its call verbatim.\n const singleBundle = this.options.singleBundle === true;\n const esmShim = this.options.esmShim !== false;\n // Read before deleting: the merged banner is applied AFTER the user\n // spread, so a user banner must not be lost to it or clobber the shim.\n const userBanner = this.options.banner;\n\n // `outFile` and `entryPath` are REQUIRED on ResolvedBuildConfig on purpose:\n // resolve-build-config.ts documents that widening them pushed a lie downstream\n // into start-production.command.ts, which then could not trust its own config.\n // This is the one place they must be absent - the object is spread into esbuild's\n // call verbatim and esbuild throws on unknown keys.\n //\n // Stripped off a LOCAL COPY of `this.options`, never off `this.options`\n // itself: `buildContext()` hands `this.options` to every `generate`/`emit`\n // contribution hook, including the `emit` pass that runs AFTER this method\n // returns (`build()` step 5.6). Deleting these keys from the shared object\n // used to leave those hooks reading `undefined` for `outFile`, `entryPath`,\n // `singleBundle`, `esmShim` and `banner` even though `ConnectorBuildContext`\n // types them as present. A shallow copy is enough — every field this method\n // reads off it is either scalar or already re-merged below (`define`,\n // `external`, `loader`, `banner`), so nothing here needs a deep clone.\n const esbuildOptions: Partial<ResolvedBuildConfig> = { ...this.options };\n\n delete esbuildOptions.outFile;\n delete esbuildOptions.entryPath;\n delete esbuildOptions.singleBundle;\n delete esbuildOptions.esmShim;\n delete esbuildOptions.banner;\n delete esbuildOptions.routeRegistrationTimeoutMs;\n\n await ensureDirectoryAsync(writeOutDir);\n\n const alias = this.buildAliasMapFromTsconfig();\n\n // Whether this build decides externality per import EDGE\n // (`bundle-framework-dependencies.ts`, which explains the rule at\n // length) or keeps the blunt `packages: \"external\"`.\n //\n // Not in `singleBundle` mode: that bundles everything by definition, and\n // a plugin that can only ever ADD an external would silently narrow it.\n // Not when the user set `packages` themselves: their value has always\n // won over the default below, and it must keep winning — the plugin is\n // the default's implementation, not a new policy layered on top.\n const perEdgeExternals = !singleBundle && (esbuildOptions as any).packages === undefined;\n\n // The user can override `format`, so gate the shim on the EFFECTIVE\n // format rather than on the default below. A CJS build already has\n // `require` and friends; injecting them there would be a redefinition.\n const isEsm = (esbuildOptions.format ?? \"esm\") === \"esm\";\n const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : undefined);\n\n // Contributor patch, split into the part that can ride the spread order\n // and the three keys that cannot. `jsx` and `jsxImportSource` are placed\n // BEFORE the user spread below, which gives the ruled precedence for\n // free: builder defaults < contributor < user config.\n //\n // `define`, `external` and `loader` are pulled out because a spread\n // REPLACES them wholesale — the same trap `banner` documents. Two\n // contributors' env defines, a contributor's optional peers plus the\n // user's, or a contributor's `.svg` loader alongside the user's `.png`,\n // must both survive, so they are merged by key/by set and re-applied\n // after the spread with the user still winning per key.\n const {\n define: contributedDefine,\n external: contributedExternal,\n loader: contributedLoader,\n plugins: contributedPlugins,\n ...contributedOptions\n } = this.contributedEsbuild;\n\n const userDefine: Record<string, string> | undefined = esbuildOptions.define;\n const userExternal: string[] | undefined = esbuildOptions.external;\n const userLoader: ConnectorEsbuildPatch[\"loader\"] = esbuildOptions.loader;\n\n const define =\n contributedDefine || userDefine ? { ...contributedDefine, ...userDefine } : undefined;\n\n const loader =\n contributedLoader || userLoader ? { ...contributedLoader, ...userLoader } : undefined;\n\n const external =\n contributedExternal || userExternal\n ? dedupe([...(contributedExternal ?? []), ...(userExternal ?? [])])\n : undefined;\n\n if (singleBundle) {\n console.log(\n colors.magenta(\n \" Single-bundle mode — one JS file\" +\n (esmShim && isEsm ? \" with the ESM interop shim\" : \"\") +\n \". Native .node addons are still emitted alongside it.\",\n ),\n );\n }\n\n try {\n await esbuild.build({\n platform: \"node\",\n entryPoints: [entryPoint],\n bundle: true,\n // Both are DEFAULTS the user can override — they sit before the\n // `...esbuildOptions` spread deliberately. `singleBundle` moves them,\n // an explicit `splitting`/`packages` in warlock.config.ts beats both.\n //\n // Phase ordering does not depend on `splitting`: it comes from the\n // generated app.ts using dynamic `await import(...)` (see\n // generateAppEntry above), which esbuild defers to the call site in\n // either mode. Splitting only decides one file vs chunks.\n splitting: !singleBundle,\n // `\"bundle\"` under `perEdgeExternals` is not \"bundle everything\":\n // the plugin below returns `external: true` for every bare specifier\n // this build must not bundle, which is all of them bar the framework's\n // own declared dependencies. Saying `\"external\"` here instead would\n // externalise them before the plugin could rule.\n packages: singleBundle || perEdgeExternals ? \"bundle\" : \"external\",\n minify: esbuildOptions.minify,\n sourcemap: esbuildOptions.sourcemap === true ? \"linked\" : esbuildOptions.sourcemap,\n format: \"esm\",\n // Targeting a concrete Node version (not \"esnext\") so esbuild\n // transpiles TC39 stage 3 decorators into helpers — Node does not\n // implement them natively yet.\n target: [\"node22\"],\n entryNames: entryName,\n alias,\n plugins: [\n nativeNodeModulesPlugin,\n // BEFORE the framework-dependency plugin, and the order is\n // load-bearing: the first `onResolve` callback to answer wins, and\n // `app/users/...` is a bare specifier the other one would rule\n // external.\n tsconfigPathAliases(this.tsconfigPathAliasConfig()),\n ...(perEdgeExternals\n ? [bundleFrameworkDependencies({ appRoot: rootPath(), aliasKeys: Object.keys(alias) })]\n : []),\n // Contributor plugins run last: they load their own file types and\n // must not shadow the resolvers above.\n ...(contributedPlugins ?? []),\n ],\n // Between the defaults and the user spread — the ruled precedence.\n ...contributedOptions,\n ...(esbuildOptions as any),\n // AFTER the spread, and NOT overridable: `esbuildOptions.outdir` rides\n // that spread carrying the FINAL destination, which is exactly where\n // this build must not write yet. The final path is the user's setting\n // and stays authoritative for everyone reading the config — it is only\n // this one esbuild call that is redirected, and only until promotion\n // moves the result onto that very path.\n outdir: writeOutDir,\n // AFTER the spread for the same reason `banner` is: a spread replaces\n // these objects instead of merging them, so the merged values are\n // re-applied here. The user still wins — they were merged in last.\n ...(define ? { define } : {}),\n ...(external ? { external } : {}),\n ...(loader ? { loader } : {}),\n // AFTER the spread, and intentionally so: `banner` is an object, and\n // both the config merge and this spread REPLACE it wholesale rather\n // than merging. Left as a default above, any user banner would delete\n // the shim; left to the spread, the shim would delete theirs. The\n // merge is the only form that keeps both.\n ...(banner ? { banner } : {}),\n });\n } catch (e) {\n console.log(e);\n throw e;\n }\n }\n\n /**\n * The WILDCARD half of the same tsconfig `paths` map that\n * {@link ProductionBuilder.buildAliasMapFromTsconfig} reads the exact half\n * of. `tsconfig-path-aliases.ts` explains why the two halves need different\n * mechanisms — in short, esbuild's `alias` option cannot express a wildcard,\n * so the entries it skips have to be resolved by a plugin instead of being\n * left to no one.\n */\n private tsconfigPathAliasConfig(): { baseUrl: string; paths: Record<string, string[]> } {\n tsconfigManager.init();\n\n return {\n baseUrl: path.resolve(process.cwd(), tsconfigManager.baseUrl),\n paths: tsconfigManager.aliases as Record<string, string[]>,\n };\n }\n\n /**\n * Build an alias map from tsconfig `paths` so esbuild resolves local\n * source aliases (e.g. `@warlock.js/cascade`) to their on-disk source\n * folders during bundling. Without this, `packages: \"external\"` would\n * leave those bare specifiers as raw imports and Node would fail to\n * resolve them at runtime (they aren't installed in node_modules).\n *\n * Only exact (non-wildcard) aliases are included — esbuild's `alias`\n * option doesn't support glob-style mappings. The wildcard half is not\n * dropped, it is handled elsewhere: see\n * {@link ProductionBuilder.tsconfigPathAliasConfig}.\n */\n private buildAliasMapFromTsconfig(): Record<string, string> {\n tsconfigManager.init();\n\n const alias: Record<string, string> = {};\n const baseUrl = path.resolve(process.cwd(), tsconfigManager.baseUrl);\n\n for (const [from, to] of Object.entries(tsconfigManager.aliases)) {\n if (from.endsWith(\"/*\") || !Array.isArray(to) || to.length === 0) {\n continue;\n }\n\n const target = to[0];\n\n if (target === undefined) {\n continue;\n }\n\n alias[from] = path.resolve(baseUrl, target);\n }\n\n return alias;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,MAAM,mBACJ;;;;;;;;;;;;;;AAoBF,SAAS,YACP,YACA,MACoC;CACpC,IAAI,CAAC,MAAM,OAAO;CAElB,MAAM,SAAS,YAAY;CAE3B,OAAO;EACL,GAAG;EACH,IAAI,SAAS,GAAG,OAAO,WAAW;CACpC;AACF;;;;;;;;;;AAWA,MAAM,+BAA+B;;;;;;AAOrC,IAAa,oBAAb,MAA+B;;uBAEI,YAAY,YAAY;oBAOd,CAAC;4BAMQ,CAAC;wBAoO5B;GACvB,SAAS;GACT,QAAQ;GACR,MAAM;GACN,QAAQ;GACR,SAAS;EACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAxMA,MAAa,QAAuB;EAClC,QAAQ,IAAI,OAAO,KAAK,8BAA8B,CAAC;EAMvD,4BAA4B;EAG5B,MAAM,KAAK,kBAAkB;EAE7B,MAAM,cAAc,KAAK,QAAQ;EACjC,MAAM,aAAa,oBAAoB,WAAW;EAKlD,IAAI;EAEJ,IAAI;GAEF,MAAM,KAAK,sBAAsB;GAGjC,MAAM,KAAK,mBAAmB;GAG9B,MAAM,KAAK,uBAAuB;GAGlC,MAAM,KAAK,4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CAAC;IAC3B,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;IAC/B,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;IAM3B,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;GAC7B,CAAC;EACH,SAAS,GAAG;GACV,QAAQ,IAAI,CAAC;GACb,MAAM;EACR;CACF;;;;;;;;;CAUA,AAAQ,0BAAgF;EACtF,gBAAgB,KAAK;EAErB,OAAO;GACL,SAAS,KAAK,QAAQ,QAAQ,IAAI,GAAG,gBAAgB,OAAO;GAC5D,OAAO,gBAAgB;EACzB;CACF;;;;;;;;;;;;;CAcA,AAAQ,4BAAoD;EAC1D,gBAAgB,KAAK;EAErB,MAAM,QAAgC,CAAC;EACvC,MAAM,UAAU,KAAK,QAAQ,QAAQ,IAAI,GAAG,gBAAgB,OAAO;EAEnE,KAAK,MAAM,CAAC,MAAM,OAAO,OAAO,QAAQ,gBAAgB,OAAO,GAAG;GAChE,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,QAAQ,EAAE,KAAK,GAAG,WAAW,GAC7D;GAGF,MAAM,SAAS,GAAG;GAElB,IAAI,WAAW,QACb;GAGF,MAAM,QAAQ,KAAK,QAAQ,SAAS,MAAM;EAC5C;EAEA,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"production-builder.mjs","names":[],"sources":["../../../../../../../core/src/production/production-builder.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport {\n ensureDirectoryAsync,\n fileExistsAsync,\n getFileAsync,\n getJsonFileAsync,\n putFileAsync,\n removeDirectoryAsync,\n} from \"@warlock.js/fs\";\nimport esbuild from \"esbuild\";\nimport glob from \"fast-glob\";\nimport path from \"path\";\nimport { assertNoReservedConnectorNames } from \"../connectors/assert-no-reserved-connector-names\";\nimport { assertUniqueConnectorNames } from \"../connectors/assert-unique-connector-names\";\nimport type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\nimport { configKeyFromPath } from \"../config/config-key-from-path\";\nimport {\n isConfigFile,\n isEventFile,\n isLocaleFile,\n isMainFile,\n isRouteFile,\n isWorkerFile,\n} from \"../dev-server/special-file-patterns\";\nimport { tsconfigManager } from \"../dev-server/tsconfig-manager\";\nimport { appPath, rootPath, warlockPath } from \"../utils\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\nimport { bundleFrameworkDependencies } from \"./bundle-framework-dependencies\";\nimport { dedupe, runEmitContributions, runGenerateContributions } from \"./build-contributions\";\nimport { writeDistBuildManifestAsync } from \"./dist-build-manifest\";\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\nimport { assertEsbuildBinaryIsLinked } from \"./esbuild-preflight\";\nimport { collectRouteRegistrationSnapshot } from \"./route-registration-snapshot\";\nimport { clearOwnedRouteTypes } from \"../dev-server/route-types-publisher\";\nimport {\n commitDistAsync,\n createTempOutputDir,\n rollbackDistAsync,\n stageDistAsync,\n type StagedDist,\n} from \"./promote-dist\";\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\nimport { tsconfigPathAliases } from \"./tsconfig-path-aliases\";\nimport { toKebabCase } from \"@mongez/reinforcements\";\n\n/**\n * Recreates `require`, `__filename` and `__dirname` at the top of an ESM bundle.\n *\n * Bundled CommonJS dependencies call `require(\"node:assert\")` and read\n * `__dirname` to locate their own assets. Neither exists in an ES module, so\n * esbuild substitutes a stub that throws — **after the build has reported\n * success**. `Dynamic require of \"node:assert\" is not supported` is that stub\n * firing, and it is the defect this shim removes.\n *\n * `__dirname` matters as much as `require`: without it a dependency resolving\n * an asset path silently gets `undefined` and fails later, further from the\n * cause.\n *\n * Written as one line because esbuild inserts a banner verbatim above the\n * bundle and a multi-line string here would shift every mapped line.\n */\nconst ESM_INTEROP_SHIM =\n \"import{createRequire as __wlCreateRequire}from'node:module';\" +\n \"import{fileURLToPath as __wlFileURLToPath}from'node:url';\" +\n \"import{dirname as __wlDirname}from'node:path';\" +\n \"const require=__wlCreateRequire(import.meta.url);\" +\n \"const __filename=__wlFileURLToPath(import.meta.url);\" +\n \"const __dirname=__wlDirname(__filename);\";\n\n/**\n * Combine the framework's banner with the user's, keeping both.\n *\n * esbuild's `banner` is an object keyed by output type, and every merge in the\n * path to it — the config merge and the options spread — REPLACES that object\n * rather than merging it. So whichever is applied second silently deletes the\n * other. This is the only place the two can coexist.\n *\n * The shim goes first: it defines `require`, which a user banner may use.\n *\n * @param userBanner banner from `warlock.config.ts`, if any\n * @param shim the interop shim, or undefined when it does not apply\n */\nfunction mergeBanner(\n userBanner: Record<string, string> | undefined,\n shim: string | undefined,\n): Record<string, string> | undefined {\n if (!shim) return userBanner;\n\n const userJs = userBanner?.js;\n\n return {\n ...userBanner,\n js: userJs ? `${shim}${userJs}` : shim,\n };\n}\n\n/**\n * Prefix every generated file uses to reach the app root.\n *\n * Generated sources are written into `.warlock/production/`, two levels below\n * the app root, so `../../` lands back on it — the same hop already spelled\n * out in the `../../src/app/…` and `../../src/config/…` imports the module and\n * config-loader generators emit. Named once so a generator that needs a new\n * app-root file (`warlock.config`) cannot pick a different depth.\n */\nconst APP_ROOT_FROM_PRODUCTION_DIR = \"../../\";\n\n/**\n * Production Builder\n * Generates production-ready files and bundles them for deployment\n * Build options are loaded from warlock.config.ts\n */\nexport class ProductionBuilder {\n private options!: ResolvedBuildConfig;\n private readonly productionDir = warlockPath(\"production\");\n\n /**\n * Connectors declared in `warlock.config.ts`. Read statically — `build`\n * never calls `boot()`/`start()` on them; it only\n * drains their `build` contributions.\n */\n private connectors: readonly Connector[] = [];\n\n /**\n * The contributors' merged esbuild patch, produced by the `generate` pass\n * and consumed by {@link bundle}.\n */\n private contributedEsbuild: ConnectorEsbuildPatch = {};\n\n /** Browser-safe API metadata captured in a fresh registration-only child. */\n private namedApiRoutes?: readonly import(\"../router/types\").NamedApiRoute[];\n\n /**\n * Main build entry point\n *\n * The esbuild bundle is written into a TEMP directory next to the real\n * output directory, never into it, and that directory is renamed over\n * `outdir` as one filesystem operation — so `outdir` is never observed as\n * a mix of the old build and the new one, and a build that fails before\n * that rename never touches `outdir` at all.\n *\n * `this.options.outdir` is NOT repointed at the temp directory while that\n * happens, and must never be. It is not merely a write target: consumers\n * BAKE it into runtime output — `web`'s build contribution derives the\n * `clientDir` recorded in its pages manifest from it\n * (`web/src/build/contribution.ts`) — so a temp path reaching them\n * produces an artifact whose browser paths point at a directory promotion\n * has since renamed away. The temp path is passed explicitly, as a\n * parameter, to the one operation that writes into it ({@link bundle});\n * everything else, `buildContext()` included, keeps reading the final\n * destination.\n *\n * That is also why promotion is STAGED rather than done at the very end.\n * Connector `emit` hooks write real artifacts (the web client bundle) and\n * see the final `outdir`, so they must run when `outdir` genuinely holds\n * this build — after the rename, not before it, or promotion would replace\n * the directory they just wrote into. The previous build is kept parked\n * aside until they finish: `emit` throwing rolls the whole promotion back,\n * and the build-success marker `warlock start` checks is written last of\n * all, so a failure at any point leaves no `dist` that start will boot.\n */\n public async build(): Promise<void> {\n console.log(colors.cyan(\"Building for production...\\n\"));\n\n // Step 0: Fail fast when esbuild's native binary never got linked (the\n // state pnpm leaves a project in when its build-script approval gate\n // blocked esbuild's postinstall) rather than let bundling die on esbuild's\n // own cryptic \"package could not be found\" error several steps from now.\n assertEsbuildBinaryIsLinked();\n\n // Step 1: Initialize options from config\n await this.initializeOptions();\n\n const finalOutDir = this.options.outdir!;\n const tempOutDir = createTempOutputDir(finalOutDir);\n\n // Set once the temp directory has been renamed onto `finalOutDir`. Its\n // presence is what tells the catch below whether a failure has a\n // promotion to undo or only a temp directory to discard.\n let staged: StagedDist | undefined;\n\n try {\n // Step 2: Generate combined files\n await this.generateCombinedFiles();\n\n // Step 3: Generate entry point\n await this.generateEntryPoint();\n\n // Step 4: Refuse to bundle code the app could not resolve at runtime\n await this.assertGeneratedImports();\n\n // Step 4.5: Drain the connectors' `generate` contributions\n await this.captureNamedApiRoutesForWeb();\n const contributed = await this.runGenerateContributions();\n\n // Step 4.6: Re-assert over what the contributors just wrote.\n //\n // Step 4 only saw core's own generated files; a contributor writes its\n // code (a pages barrel, say) AFTER that assertion, so an undeclared bare\n // specifier in it reaches the bundle unchecked. Under\n // `packages: \"external\"` that specifier survives verbatim into the\n // artifact and dies as ERR_MODULE_NOT_FOUND at runtime — the same failure\n // step 4 exists to prevent. Skipped when nothing contributed: re-globbing\n // and re-reading the production dir is pure cost in the common case.\n if (contributed) {\n await this.assertGeneratedImports();\n }\n\n // Step 5: Bundle with esbuild into the temp directory. The ONLY\n // operation handed that path — it is a write target, not config.\n await this.bundle(tempOutDir);\n\n // Step 5.5: Promote the bundle into `outdir`, keeping the previous\n // build parked aside. `outdir` now holds exactly this build, so the\n // steps below write into — and record — the real destination.\n staged = await stageDistAsync(tempOutDir, finalOutDir);\n\n // Step 5.6: Drain the connectors' `emit` contributions — after the\n // bundle is in place (so what they write survives promotion and the\n // paths they bake in resolve), and BEFORE step 6 deletes the\n // production directory they may still read.\n await runEmitContributions(this.connectors, this.buildContext());\n\n // Step 5.7: Mark `dist` as a genuine, complete build — the one thing\n // `warlock start` trusts. Written LAST on purpose: every earlier step\n // can still fail, and until this file exists nothing will boot what\n // they left behind.\n await writeDistBuildManifestAsync(finalOutDir);\n\n // Step 5.8: Commit — drop the parked previous build. Cannot throw.\n await commitDistAsync(staged);\n } catch (error) {\n if (staged) {\n // The promotion already happened; put the previous build back and\n // take this half-finished one out of `outdir`.\n await rollbackDistAsync(staged);\n } else {\n // Nothing this build produced ever reached `outdir` — discard the\n // temp directory and leave `outdir` exactly as it was.\n await removeDirectoryAsync(tempOutDir).catch(() => undefined);\n }\n\n throw error;\n }\n\n // Step 6: Remove production folder\n await removeDirectoryAsync(this.productionDir);\n\n console.log(colors.green(\"Build complete!\"));\n console.log(`Start production server by running ${colors.cyan(\"warlock start\")}`);\n }\n\n /**\n * Initialize options from warlock.config.ts\n */\n private async initializeOptions(): Promise<void> {\n this.options = resolveBuildConfig();\n // Same config object `resolveBuildConfig` just read — `warlock build`\n // preloads warlock.config.ts, so no additional load happens here.\n const connectors = warlockConfigManager.get(\"connectors\") ?? [];\n\n // Checked here, where the array is first read, so nothing downstream has\n // drained anything yet: the `generate` and `emit` passes run per ENTRY, so\n // a name listed twice would write its files and merge its esbuild options\n // twice into an artifact the runtime then boots that name only once from.\n // A build that half-applied a connector and reported success is worse than\n // one that never started.\n assertUniqueConnectorNames([...connectors]);\n\n // And here rather than only at boot, for the same reason: a name a built-in\n // already owns is skipped by the runtime, so an artifact built from it\n // carries the custom connector's generated files and esbuild patches while\n // the server boots the built-in instead. Refusing it at boot alone would\n // mean the build had already emitted that artifact — the failure has to\n // land on the developer running `warlock build`, not on whoever starts the\n // server. Same assertion the registration half calls, over the same names.\n assertNoReservedConnectorNames([...connectors]);\n\n this.connectors = connectors;\n\n // Ensure production directory exists\n await ensureDirectoryAsync(this.productionDir);\n }\n\n /**\n * The context handed to every build contribution.\n */\n private buildContext(): ConnectorBuildContext {\n return {\n productionDir: this.productionDir,\n appRoot: rootPath(),\n options: this.options,\n namedApiRoutes: this.namedApiRoutes,\n };\n }\n\n /**\n * Web route declarations need application API registration, which cannot be\n * inferred from generated files. Capture it once in a disposable child before\n * contributors write build artifacts; no connector lifecycle runs there.\n */\n private async captureNamedApiRoutesForWeb(): Promise<void> {\n if (!this.connectors.some((connector) => connector.name === \"web\")) {\n await clearOwnedRouteTypes(rootPath());\n return;\n }\n\n this.namedApiRoutes = (\n await collectRouteRegistrationSnapshot({\n cwd: rootPath(),\n timeoutMs: this.options.routeRegistrationTimeoutMs,\n })\n ).routes;\n }\n\n /**\n * Drain the `generate` hooks and fold what they returned back into the\n * build.\n *\n * The entry point is REGENERATED here rather than generated later. The\n * contribution slot is fixed — after `assertGeneratedImports` (so nothing\n * bundles that the app could not resolve) and before `bundle` — while\n * `generateEntryPoint` must stay at step 3, because `app.ts` is itself\n * generated code the assertion has to see; moving it past the assertion\n * would silently drop the entry from that check. Rewriting one small file\n * is cheaper than losing either guarantee, and the write is pure\n * (`generatedFiles` + these imports), so doing it twice is not a\n * correctness risk.\n *\n * @returns whether any connector ran a `generate` hook — the caller uses it\n * to decide if the import assertion is worth a second pass. Keyed on the\n * hook EXISTING, not on what it returned: a hook that returns nothing may\n * still have written files into `productionDir`, and those are exactly the\n * files the second pass is there to read.\n */\n private async runGenerateContributions(): Promise<boolean> {\n const contributed = this.connectors.some((connector) => Boolean(connector.build?.generate));\n\n const { entryImports, esbuild } = await runGenerateContributions(\n this.connectors,\n this.buildContext(),\n );\n\n this.contributedEsbuild = esbuild;\n\n if (entryImports.length > 0) {\n await this.generateEntryPoint(entryImports);\n }\n\n return contributed;\n }\n\n /**\n * Track which special files were generated\n */\n private generatedFiles = {\n locales: false,\n events: false,\n main: false,\n routes: false,\n workers: false,\n };\n\n /**\n * Generate all combined files\n */\n private async generateCombinedFiles(): Promise<void> {\n console.log(colors.yellow(\" Generating production files...\"));\n\n // Generate bootstrap.ts file\n await this.generateBootstrap();\n\n // Generate config loader\n await this.generateConfigLoader();\n\n // Generate special files and track which ones have content\n const [locales, events, main, routes, workers] = await Promise.all([\n this.generateLocales(),\n this.generateEvents(),\n this.generateMain(),\n this.generateRoutes(),\n this.generateWorkers(),\n ]);\n\n this.generatedFiles = { locales, events, main, routes, workers };\n }\n\n /**\n * Generate bootstrap.ts - ensures bootstrap() runs first and sets production environment\n */\n private async generateBootstrap(): Promise<void> {\n // ESM hoists imports, so the app bootstrap must be the first import to run first\n const appBootstrapImport = (await fileExistsAsync(appPath(\"bootstrap.ts\")))\n ? \"import './../../src/app/bootstrap';\\n\"\n : \"\";\n\n const content = `${appBootstrapImport}import { bootstrap, Application } from \"@warlock.js/core\";\n\n// Production runtime; NODE_ENV is only defaulted so an explicit value (e.g. staging) wins\nApplication.setRuntimeStrategy(\"production\");\nif (!process.env.NODE_ENV) {\n Application.setEnvironment(\"production\");\n}\n\n// Bootstrap the application\nbootstrap();\n`;\n\n await putFileAsync(path.join(this.productionDir, \"bootstrap.ts\"), content);\n }\n\n /**\n * Fail the build when generated code imports a package the app does not\n * declare.\n *\n * The bundler is configured `packages: \"external\"`, so every bare specifier\n * written above survives verbatim into an artifact that resolves against the\n * **consuming app's** node_modules. A framework-internal dependency imported\n * there resolves by accident under npm/yarn hoisting and dies under pnpm —\n * which is how a production app shipped that could not boot. Rewriting the\n * offending import fixes today's bundle; this check is what stops the next\n * change to the generator from quietly reintroducing it.\n */\n private async assertGeneratedImports(): Promise<void> {\n const generatedPaths = await glob(\"**/*.{ts,tsx,js,mjs}\", {\n cwd: this.productionDir,\n absolute: false,\n });\n\n const [files, appPackage] = await Promise.all([\n Promise.all(\n generatedPaths.map(async (file) => ({\n file,\n content: await getFileAsync(path.join(this.productionDir, file)),\n })),\n ),\n getJsonFileAsync<{ dependencies?: Record<string, string> }>(rootPath(\"package.json\")),\n ]);\n\n assertGeneratedImportsAreDeclared(files, Object.keys(appPackage.dependencies ?? {}));\n }\n\n /**\n * Glob `src/app` and keep the files the shared dev-server predicate accepts,\n * so production discovers exactly what the dev collector does.\n * Returns relative paths from .warlock/production/ to src/app/\n */\n private async globModule(matches: (relativePath: string) => boolean): Promise<string[]> {\n const files = await glob(\"**/*.{ts,tsx,json}\", {\n cwd: appPath(),\n absolute: false,\n });\n\n // e.g., \"users/main.ts\" -> \"../../src/app/users/main\"\n return files\n .filter((file) => matches(\"src/app/\" + file))\n .sort()\n .map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\n }\n\n /**\n * Generate config-loader.ts\n */\n private async generateConfigLoader(): Promise<void> {\n const configDirectory = path.join(process.cwd(), \"src/config\");\n\n const files = await glob(\"**/*.{ts,tsx}\", {\n cwd: configDirectory,\n absolute: false,\n });\n\n // Same key rule as the dev config loader: the raw path, never camel-cased\n const configNames = files\n .filter((f) => isConfigFile(\"src/config/\" + f))\n .map((f) => ({\n path: f.replace(/\\.(ts|tsx)$/, \"\"),\n key: configKeyFromPath(\"src/config/\" + f),\n }))\n .filter((entry): entry is { path: string; key: string } => entry.key !== undefined)\n .sort((a, b) => a.path.localeCompare(b.path));\n\n // Only `@warlock.js/core` — the one package the app itself declares. See\n // `assertGeneratedImportsAreDeclared`: `@mongez/config` is core's own\n // dependency, so a bare import of it resolved by luck under npm/yarn\n // hoisting and died under pnpm's strict layout.\n const imports: string[] = [\n 'import { setConfig, configSpecialHandlers } from \"@warlock.js/core\";',\n ];\n const configImports: string[] = [];\n const configSetCalls: string[] = [];\n const executors: string[] = [];\n\n configNames.forEach(({ path: configPath, key }, index) => {\n // Index-based identifier: keys like \"rate-limit\" or \"mail/smtp\" are not valid names\n const varName = `config${index}`;\n configImports.push(`import ${varName} from \"../../src/config/${configPath}\";`);\n configSetCalls.push(`setConfig(${JSON.stringify(key)}, ${varName});`);\n executors.push(`await configSpecialHandlers.execute(${JSON.stringify(key)}, ${varName});`);\n });\n\n // ESM hoists imports, so prestart must be the first import to run first\n const prestartImports = (await fileExistsAsync(appPath(\"prestart.ts\")))\n ? [\"import './../../src/app/prestart';\"]\n : [];\n\n const content = [\n ...prestartImports,\n ...imports,\n \"\",\n \"// Config imports\",\n ...configImports,\n \"\",\n \"// Register configs\",\n ...configSetCalls,\n \"\",\n \"// Special handlers\",\n ...executors,\n \"\",\n ].join(\"\\n\");\n\n await putFileAsync(path.join(this.productionDir, \"config-loader.ts\"), content);\n }\n\n /**\n * Generate locales.ts (only if there are locale files)\n * @returns true if file was generated with content\n */\n private async generateLocales(): Promise<boolean> {\n const files = await this.globModule(isLocaleFile);\n if (files.length === 0) return false;\n const content = files\n .map((file, index) => {\n if (!file.endsWith(\".json\")) return `import \"${file}\";`;\n const moduleFolder = file.split(\"/\").at(-3)!;\n return [\n `import dictionary${index} from \"${file}\";`,\n 'import { registerLocaleDictionary } from \"@warlock.js/core\";',\n `registerLocaleDictionary({ sourceFile: ${JSON.stringify(file)}, source: JSON.stringify(dictionary${index}), defaultNamespace: ${JSON.stringify(moduleFolder)} });`,\n ].join(\"\\n\");\n })\n .join(\"\\n\");\n await putFileAsync(path.join(this.productionDir, \"locales.ts\"), content + \"\\n\");\n return true;\n }\n\n /**\n * Generate events.ts (only if there are event files)\n * @returns true if file was generated with content\n */\n private async generateEvents(): Promise<boolean> {\n const files = await this.globModule(isEventFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"events.ts\");\n return true;\n }\n\n /**\n * Generate main.ts (only if there are main files)\n * @returns true if file was generated with content\n */\n private async generateMain(): Promise<boolean> {\n const files = await this.globModule(isMainFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"main.ts\");\n return true;\n }\n\n /**\n * Generate routes.ts (only if there are route files)\n * @returns true if file was generated with content\n */\n private async generateRoutes(): Promise<boolean> {\n const files = await this.globModule(isRouteFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"routes.ts\");\n return true;\n }\n\n /**\n * Generate workers.ts (only if there are worker files)\n * @returns true if file was generated with content\n */\n private async generateWorkers(): Promise<boolean> {\n const files = await this.globModule(isWorkerFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"workers.ts\");\n return true;\n }\n\n /**\n * Generate a file with imports from all given files\n */\n private async generateImportsFile(importPaths: string[], outputFile: string): Promise<void> {\n const imports = importPaths.map((importPath) => `import \"${importPath}\";`);\n const content = imports.join(\"\\n\") + \"\\n\";\n await putFileAsync(path.join(this.productionDir, outputFile), content);\n }\n\n /**\n * Generate the main entry point (app.ts)\n *\n * @param contributedImports lines from connector `generate` hooks, appended\n * to section 4 after `./routes`\n */\n private async generateEntryPoint(contributedImports: string[] = []): Promise<void> {\n console.log(colors.yellow(\" Generating entry point...\"));\n\n // The names this build resolved, baked in as a literal. The entry imports\n // the config source, and that source is re-evaluated at startup — an\n // env-conditional `connectors` array can hand the boot a different list\n // than the one drained here. A literal is the only part of the array that\n // survives into the artifact unchanged, so it is what the boot compares\n // against.\n const expectedNames = this.connectors\n .map((connector) => JSON.stringify(connector.name))\n .join(\", \");\n\n // Build imports based on which files were generated\n const imports: string[] = [\n \"// 1. Bootstrap (loads .env, initializes framework)\",\n 'import \"./bootstrap\";',\n \"\",\n \"// 2. Load configs\",\n 'import \"./config-loader\";',\n \"\",\n // Registration has to sit between the config being available and the\n // first phase starting: the connectors listed in `connectors` are the\n // same ones this build drained contributions from, so the bundle boots\n // exactly what it was built for. Register any later and an early-phase\n // connector would miss its own start.\n \"// 2.5 Register connectors declared in warlock.config (the same array this\",\n \"// build read its contributions from, so built-for and boots-with match).\",\n \"// The config is imported STATICALLY so esbuild bakes it into the bundle\",\n \"// and the array is handed over explicitly — an artifact has no\",\n \"// warlock.config.ts beside it to read at runtime, and a registration\",\n \"// that quietly found nothing to register is the exact drift this\",\n \"// section exists to prevent.\",\n \"// `expectedNames` is the list this build resolved, in order — boot\",\n \"// refuses to start when the config hands over a different set or order.\",\n 'import { registerConfiguredConnectors } from \"@warlock.js/core\";',\n `import warlockConfig from \"${APP_ROOT_FROM_PRODUCTION_DIR}warlock.config\";`,\n `registerConfiguredConnectors(warlockConfig.connectors ?? [], { expectedNames: [${expectedNames}] });`,\n \"\",\n \"// 2.6 Fail fast on a busy port. `http` is a LATE-phase connector, so its\",\n \"// own preflight is not reached until the database and cache have\",\n \"// connected and every app module has been imported — seconds of work\",\n \"// thrown away before anyone learns the port was taken. This probe is\",\n \"// a bind-and-release on a socket that is never served, and it reports\",\n \"// on stderr because no log channel is configured this early.\",\n 'import { Application, connectorsManager, ConnectorLifecyclePhase, preflightConfiguredHttpPort } from \"@warlock.js/core\";',\n 'if (Application.hasRole(\"api\") || Application.hasRole(\"web\")) {',\n \" await preflightConfiguredHttpPort();\",\n \"}\",\n \"\",\n \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\n \"// so data sources, cache, etc. are ready before app code runs\",\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\",\n ];\n\n // App code uses dynamic `await import(...)` so each module's side\n // effects fire at THIS point in execution. Static imports would be\n // hoisted to module-instantiation time (before the early-phase await\n // resolves), which is exactly the bug this split is meant to fix.\n //\n // The guarantee comes from the imports being DYNAMIC — esbuild wraps a\n // dynamically-imported module in its `__esm(() => {…})` helper and runs\n // it at the await, not at instantiation. It does NOT come from\n // `splitting: true`, which only decides one-file-vs-chunks. This\n // previously said splitting was required; it is not, and `singleBundle`\n // (splitting: false) preserves the ordering.\n imports.push(\"\", \"// 4. Load app code (events, locales, main, routes)\");\n\n if (this.generatedFiles.events) {\n imports.push('await import(\"./events\");');\n }\n if (this.generatedFiles.locales) {\n imports.push('await import(\"./locales\");');\n }\n if (this.generatedFiles.main) {\n imports.push('await import(\"./main\");');\n }\n if (this.generatedFiles.routes) {\n imports.push('if (Application.hasRole(\"api\")) {', ' await import(\"./routes\");', \"}\");\n }\n if (this.generatedFiles.workers) {\n imports.push('if (Application.hasRole(\"worker\")) {', ' await import(\"./workers\");', \"}\");\n }\n\n // Contributor imports come AFTER `./routes`, never before: a connector\n // that registers pages needs the routes app code already collected —\n // the same ordering dev uses (routes first, then the connector installs\n // on top of them). Emitted verbatim; the contributor writes the whole\n // statement (e.g. `await import(\"./pages\");`).\n imports.push(...contributedImports);\n\n // A rejecting validator (Application.onValidateBoot) must abort boot\n // before late-phase connectors bind a port.\n imports.push(\n \"\",\n \"// 5. Run startup validators registered via Application.onValidateBoot(...)\",\n \"await Application.runStartupValidators();\",\n );\n\n // Start late-phase connectors after app code registers routes/listeners\n imports.push(\n \"\",\n \"// 6. Start late-phase connectors (http, socket) — routes and\",\n \"// listeners registered by app code are now ready to bind\",\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\",\n \"\",\n \"// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire\",\n \"Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });\",\n \"connectorsManager.shutdownOnProcessKill();\",\n );\n\n const content = imports.join(\"\\n\") + \"\\n\";\n await putFileAsync(path.join(this.productionDir, \"app.ts\"), content);\n }\n\n /**\n * Bundle with esbuild\n *\n * @param writeOutDir the directory esbuild writes into — the build's\n * private temp directory, NOT `options.outdir`. Taken as a parameter\n * rather than read off `this.options` because the two are different paths\n * with different meanings: `options.outdir` is the final destination every\n * consumer bakes into the artifact, and this is only where bytes land\n * before promotion moves them there.\n */\n private async bundle(writeOutDir: string): Promise<void> {\n console.log(colors.magenta(\" Bundling with esbuild...\"));\n\n const entryPoint = path.join(this.productionDir, \"app.ts\");\n const outFileName = this.options.outFile!;\n // Strip extension so entryNames produces \"<base>.js\" via esbuild\n const entryName = path.basename(outFileName, path.extname(outFileName));\n\n // `singleBundle` and `esmShim` are ours, not esbuild's — it throws on\n // unknown keys, and the user options are spread into its call verbatim.\n const singleBundle = this.options.singleBundle === true;\n const esmShim = this.options.esmShim !== false;\n // Read before deleting: the merged banner is applied AFTER the user\n // spread, so a user banner must not be lost to it or clobber the shim.\n const userBanner = this.options.banner;\n\n // `outFile` and `entryPath` are REQUIRED on ResolvedBuildConfig on purpose:\n // resolve-build-config.ts documents that widening them pushed a lie downstream\n // into start-production.command.ts, which then could not trust its own config.\n // This is the one place they must be absent - the object is spread into esbuild's\n // call verbatim and esbuild throws on unknown keys.\n //\n // Stripped off a LOCAL COPY of `this.options`, never off `this.options`\n // itself: `buildContext()` hands `this.options` to every `generate`/`emit`\n // contribution hook, including the `emit` pass that runs AFTER this method\n // returns (`build()` step 5.6). Deleting these keys from the shared object\n // used to leave those hooks reading `undefined` for `outFile`, `entryPath`,\n // `singleBundle`, `esmShim` and `banner` even though `ConnectorBuildContext`\n // types them as present. A shallow copy is enough — every field this method\n // reads off it is either scalar or already re-merged below (`define`,\n // `external`, `loader`, `banner`), so nothing here needs a deep clone.\n const esbuildOptions: Partial<ResolvedBuildConfig> = { ...this.options };\n\n delete esbuildOptions.outFile;\n delete esbuildOptions.entryPath;\n delete esbuildOptions.singleBundle;\n delete esbuildOptions.esmShim;\n delete esbuildOptions.banner;\n delete esbuildOptions.routeRegistrationTimeoutMs;\n\n await ensureDirectoryAsync(writeOutDir);\n\n const alias = this.buildAliasMapFromTsconfig();\n\n // Whether this build decides externality per import EDGE\n // (`bundle-framework-dependencies.ts`, which explains the rule at\n // length) or keeps the blunt `packages: \"external\"`.\n //\n // Not in `singleBundle` mode: that bundles everything by definition, and\n // a plugin that can only ever ADD an external would silently narrow it.\n // Not when the user set `packages` themselves: their value has always\n // won over the default below, and it must keep winning — the plugin is\n // the default's implementation, not a new policy layered on top.\n const perEdgeExternals = !singleBundle && (esbuildOptions as any).packages === undefined;\n\n // The user can override `format`, so gate the shim on the EFFECTIVE\n // format rather than on the default below. A CJS build already has\n // `require` and friends; injecting them there would be a redefinition.\n const isEsm = (esbuildOptions.format ?? \"esm\") === \"esm\";\n const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : undefined);\n\n // Contributor patch, split into the part that can ride the spread order\n // and the three keys that cannot. `jsx` and `jsxImportSource` are placed\n // BEFORE the user spread below, which gives the ruled precedence for\n // free: builder defaults < contributor < user config.\n //\n // `define`, `external` and `loader` are pulled out because a spread\n // REPLACES them wholesale — the same trap `banner` documents. Two\n // contributors' env defines, a contributor's optional peers plus the\n // user's, or a contributor's `.svg` loader alongside the user's `.png`,\n // must both survive, so they are merged by key/by set and re-applied\n // after the spread with the user still winning per key.\n const {\n define: contributedDefine,\n external: contributedExternal,\n loader: contributedLoader,\n plugins: contributedPlugins,\n ...contributedOptions\n } = this.contributedEsbuild;\n\n const userDefine: Record<string, string> | undefined = esbuildOptions.define;\n const userExternal: string[] | undefined = esbuildOptions.external;\n const userLoader: ConnectorEsbuildPatch[\"loader\"] = esbuildOptions.loader;\n\n const define =\n contributedDefine || userDefine ? { ...contributedDefine, ...userDefine } : undefined;\n\n const loader =\n contributedLoader || userLoader ? { ...contributedLoader, ...userLoader } : undefined;\n\n const external =\n contributedExternal || userExternal\n ? dedupe([...(contributedExternal ?? []), ...(userExternal ?? [])])\n : undefined;\n\n if (singleBundle) {\n console.log(\n colors.magenta(\n \" Single-bundle mode — one JS file\" +\n (esmShim && isEsm ? \" with the ESM interop shim\" : \"\") +\n \". Native .node addons are still emitted alongside it.\",\n ),\n );\n }\n\n try {\n await esbuild.build({\n platform: \"node\",\n entryPoints: [entryPoint],\n bundle: true,\n // Both are DEFAULTS the user can override — they sit before the\n // `...esbuildOptions` spread deliberately. `singleBundle` moves them,\n // an explicit `splitting`/`packages` in warlock.config.ts beats both.\n //\n // Phase ordering does not depend on `splitting`: it comes from the\n // generated app.ts using dynamic `await import(...)` (see\n // generateAppEntry above), which esbuild defers to the call site in\n // either mode. Splitting only decides one file vs chunks.\n splitting: !singleBundle,\n // `\"bundle\"` under `perEdgeExternals` is not \"bundle everything\":\n // the plugin below returns `external: true` for every bare specifier\n // this build must not bundle, which is all of them bar the framework's\n // own declared dependencies. Saying `\"external\"` here instead would\n // externalise them before the plugin could rule.\n packages: singleBundle || perEdgeExternals ? \"bundle\" : \"external\",\n minify: esbuildOptions.minify,\n sourcemap: esbuildOptions.sourcemap === true ? \"linked\" : esbuildOptions.sourcemap,\n format: \"esm\",\n // Targeting a concrete Node version (not \"esnext\") so esbuild\n // transpiles TC39 stage 3 decorators into helpers — Node does not\n // implement them natively yet.\n target: [\"node22\"],\n entryNames: entryName,\n alias,\n plugins: [\n nativeNodeModulesPlugin,\n // BEFORE the framework-dependency plugin, and the order is\n // load-bearing: the first `onResolve` callback to answer wins, and\n // `app/users/...` is a bare specifier the other one would rule\n // external.\n tsconfigPathAliases(this.tsconfigPathAliasConfig()),\n ...(perEdgeExternals\n ? [bundleFrameworkDependencies({ appRoot: rootPath(), aliasKeys: Object.keys(alias) })]\n : []),\n // Contributor plugins run last: they load their own file types and\n // must not shadow the resolvers above.\n ...(contributedPlugins ?? []),\n ],\n // Between the defaults and the user spread — the ruled precedence.\n ...contributedOptions,\n ...(esbuildOptions as any),\n // AFTER the spread, and NOT overridable: `esbuildOptions.outdir` rides\n // that spread carrying the FINAL destination, which is exactly where\n // this build must not write yet. The final path is the user's setting\n // and stays authoritative for everyone reading the config — it is only\n // this one esbuild call that is redirected, and only until promotion\n // moves the result onto that very path.\n outdir: writeOutDir,\n // AFTER the spread for the same reason `banner` is: a spread replaces\n // these objects instead of merging them, so the merged values are\n // re-applied here. The user still wins — they were merged in last.\n ...(define ? { define } : {}),\n ...(external ? { external } : {}),\n ...(loader ? { loader } : {}),\n // AFTER the spread, and intentionally so: `banner` is an object, and\n // both the config merge and this spread REPLACE it wholesale rather\n // than merging. Left as a default above, any user banner would delete\n // the shim; left to the spread, the shim would delete theirs. The\n // merge is the only form that keeps both.\n ...(banner ? { banner } : {}),\n });\n } catch (e) {\n console.log(e);\n throw e;\n }\n }\n\n /**\n * The WILDCARD half of the same tsconfig `paths` map that\n * {@link ProductionBuilder.buildAliasMapFromTsconfig} reads the exact half\n * of. `tsconfig-path-aliases.ts` explains why the two halves need different\n * mechanisms — in short, esbuild's `alias` option cannot express a wildcard,\n * so the entries it skips have to be resolved by a plugin instead of being\n * left to no one.\n */\n private tsconfigPathAliasConfig(): { baseUrl: string; paths: Record<string, string[]> } {\n tsconfigManager.init();\n\n return {\n baseUrl: path.resolve(process.cwd(), tsconfigManager.baseUrl),\n paths: tsconfigManager.aliases as Record<string, string[]>,\n };\n }\n\n /**\n * Build an alias map from tsconfig `paths` so esbuild resolves local\n * source aliases (e.g. `@warlock.js/cascade`) to their on-disk source\n * folders during bundling. Without this, `packages: \"external\"` would\n * leave those bare specifiers as raw imports and Node would fail to\n * resolve them at runtime (they aren't installed in node_modules).\n *\n * Only exact (non-wildcard) aliases are included — esbuild's `alias`\n * option doesn't support glob-style mappings. The wildcard half is not\n * dropped, it is handled elsewhere: see\n * {@link ProductionBuilder.tsconfigPathAliasConfig}.\n */\n private buildAliasMapFromTsconfig(): Record<string, string> {\n tsconfigManager.init();\n\n const alias: Record<string, string> = {};\n const baseUrl = path.resolve(process.cwd(), tsconfigManager.baseUrl);\n\n for (const [from, to] of Object.entries(tsconfigManager.aliases)) {\n if (from.endsWith(\"/*\") || !Array.isArray(to) || to.length === 0) {\n continue;\n }\n\n const target = to[0];\n\n if (target ===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