@hublo/sentinel 1.3.0 → 1.4.0-alpha.1

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 (33) hide show
  1. package/README.md +2 -0
  2. package/dist/bin/sentinel.d.ts +0 -1
  3. package/dist/bin/sentinel.js +22 -8
  4. package/dist/chunk-2XLX6PFR.js +132 -0
  5. package/dist/chunk-3TDUIKVQ.js +178 -0
  6. package/dist/{chunk-676GBPMS.js → chunk-O3XCQGTJ.js} +2856 -550
  7. package/dist/chunk-PWV3BMDA.js +15 -0
  8. package/dist/chunk-WLFE5RUU.js +264 -0
  9. package/dist/index.js +2 -1
  10. package/dist/roles/build/nest/toolchain.d.ts +4 -36
  11. package/dist/roles/build/nest/toolchain.js +10 -178
  12. package/dist/roles/build/nest/toolchain.js.map +1 -0
  13. package/dist/roles/build/toolchain.js.map +1 -0
  14. package/dist/roles/test/nest/toolchain.d.ts +29 -0
  15. package/dist/roles/test/nest/toolchain.js +224 -0
  16. package/dist/roles/test/nest/toolchain.js.map +1 -0
  17. package/dist/roles/test/react/toolchain.d.ts +62 -0
  18. package/dist/roles/test/react/toolchain.js +22 -0
  19. package/dist/roles/test/react/toolchain.js.map +1 -0
  20. package/dist/roles/test/setup/mock-extended.d.ts +46 -0
  21. package/dist/roles/test/setup/mock-extended.js +65 -0
  22. package/dist/roles/test/setup/mock-extended.js.map +1 -0
  23. package/dist/roles/test/setup/msw-lifecycle.d.ts +16 -0
  24. package/dist/roles/test/setup/msw-lifecycle.js +12 -0
  25. package/dist/roles/test/setup/msw-lifecycle.js.map +1 -0
  26. package/dist/roles/test/setup/msw-server.d.ts +3 -0
  27. package/dist/roles/test/setup/msw-server.js +10 -0
  28. package/dist/roles/test/setup/msw-server.js.map +1 -0
  29. package/dist/roles/test/setup/nest.d.ts +2 -0
  30. package/dist/roles/test/setup/nest.js +211 -0
  31. package/dist/roles/test/setup/nest.js.map +1 -0
  32. package/dist/tsconfig-aliases-Ce6axdJ4.d.ts +36 -0
  33. package/package.json +24 -3
@@ -0,0 +1,15 @@
1
+ // src/roles/test/setup/msw.ts
2
+ import { setupServer } from "msw/node";
3
+ var server = setupServer();
4
+ var LISTEN_OPTIONS = { onUnhandledRequest: "error" };
5
+ function installMswLifecycle(hooks) {
6
+ server.listen(LISTEN_OPTIONS);
7
+ hooks.beforeAll(() => server.listen(LISTEN_OPTIONS));
8
+ hooks.afterAll(() => server.close());
9
+ }
10
+
11
+ export {
12
+ server,
13
+ installMswLifecycle
14
+ };
15
+ //# sourceMappingURL=chunk-PWV3BMDA.js.map
@@ -0,0 +1,264 @@
1
+ // src/shared/package-json.ts
2
+ import { existsSync, readFileSync } from "fs";
3
+ import { basename, dirname, join } from "path";
4
+ import { fileURLToPath } from "url";
5
+ function readOwnPackage() {
6
+ let dir = dirname(fileURLToPath(import.meta.url));
7
+ for (; ; ) {
8
+ const pkgPath = join(dir, "package.json");
9
+ if (existsSync(pkgPath)) {
10
+ try {
11
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
12
+ if (typeof pkg.version === "string") {
13
+ const bin = typeof pkg.bin === "string" ? pkg.bin : Object.values(pkg.bin ?? {})[0];
14
+ return { name: pkg.name ?? "@hublo/sentinel", version: pkg.version, bin };
15
+ }
16
+ } catch {
17
+ }
18
+ }
19
+ const parent = dirname(dir);
20
+ if (parent === dir) return { name: "@hublo/sentinel", version: "0.0.0" };
21
+ dir = parent;
22
+ }
23
+ }
24
+ function readOwnVersion() {
25
+ return readOwnPackage().version;
26
+ }
27
+ function readProjectPackageJson(dir) {
28
+ const path = join(dir, "package.json");
29
+ if (!existsSync(path)) return {};
30
+ try {
31
+ return JSON.parse(readFileSync(path, "utf8"));
32
+ } catch {
33
+ process.stderr.write(`sentinel: could not parse ${path}; ignoring for detection.
34
+ `);
35
+ return {};
36
+ }
37
+ }
38
+ function readNxProjectName(dir) {
39
+ const path = join(dir, "project.json");
40
+ if (!existsSync(path)) return void 0;
41
+ try {
42
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
43
+ return typeof parsed.name === "string" ? parsed.name : void 0;
44
+ } catch {
45
+ return void 0;
46
+ }
47
+ }
48
+ function moduleName(dir) {
49
+ const declared = readProjectPackageJson(dir).name;
50
+ return readNxProjectName(dir) ?? (declared === void 0 ? basename(dir) : declared);
51
+ }
52
+
53
+ // src/core/workspace-prep.ts
54
+ import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
55
+ import { dirname as dirname2, join as join2, relative } from "path";
56
+
57
+ // src/core/settings.ts
58
+ var WORKSPACE_ROOT_MARKER = "nx.json";
59
+ var DEFAULT_MAX_DIAGNOSTICS = 100;
60
+
61
+ // src/core/workspace-prep.ts
62
+ var OVERRIDE_KEY = "i18next>typescript";
63
+ var NATIVE_TS_ALIAS = "@typescript/native";
64
+ var WORKSPACE_YAML = "pnpm-workspace.yaml";
65
+ var RELEASE_AGE_KEY = "minimumReleaseAgeExclude";
66
+ var LIST_ITEM = /^(\s*)-\s+(.*?)\s*$/;
67
+ var MAP_ENTRY = /^(\s+)(.*?):\s+(.*?)\s*$/;
68
+ function findWorkspaceRoot(startDir) {
69
+ let dir = startDir;
70
+ for (; ; ) {
71
+ if (existsSync2(join2(dir, WORKSPACE_ROOT_MARKER))) return dir;
72
+ const parent = dirname2(dir);
73
+ if (parent === dir) return void 0;
74
+ dir = parent;
75
+ }
76
+ }
77
+ function declaredNativeTs(pkg) {
78
+ const spec = pkg.dependencies?.[NATIVE_TS_ALIAS] ?? pkg.devDependencies?.[NATIVE_TS_ALIAS];
79
+ if (!spec) return void 0;
80
+ const version = spec.slice(spec.lastIndexOf("@") + 1).replace(/^[\^~>=<\s]+/, "");
81
+ return version || void 0;
82
+ }
83
+ function ensureI18nextSingleton(root, dryRun) {
84
+ const pkgPath = join2(root, "package.json");
85
+ if (!existsSync2(pkgPath)) return void 0;
86
+ const pkg = JSON.parse(readFileSync2(pkgPath, "utf8"));
87
+ const want = declaredNativeTs(pkg);
88
+ if (!want) return void 0;
89
+ const yamlPath = join2(root, WORKSPACE_YAML);
90
+ if (!existsSync2(yamlPath)) return void 0;
91
+ const lines = readFileSync2(yamlPath, "utf8").split("\n");
92
+ const entry = findOverrideEntry(lines);
93
+ if (entry.valueIdx !== void 0 && entry.value === want) return void 0;
94
+ if (dryRun) return `would pin ${OVERRIDE_KEY} to ${want} in ${WORKSPACE_YAML} (i18next singleton)`;
95
+ applyOverride(lines, entry, want);
96
+ writeFileSync(yamlPath, lines.join("\n"));
97
+ return `pinned ${OVERRIDE_KEY} to ${want} in ${WORKSPACE_YAML} (i18next singleton)`;
98
+ }
99
+ function findOverrideEntry(lines) {
100
+ const blockIdx = lines.findIndex((line) => line.replace(/\s+$/, "") === "overrides:");
101
+ if (blockIdx === -1) return { indent: " " };
102
+ let lastEntryIdx = blockIdx;
103
+ let indent = " ";
104
+ for (let i = blockIdx + 1; i < lines.length; i++) {
105
+ const match = lines[i]?.match(MAP_ENTRY);
106
+ if (!match) break;
107
+ indent = match[1] ?? indent;
108
+ lastEntryIdx = i;
109
+ if ((match[2] ?? "").replace(/^['"]|['"]$/g, "") === OVERRIDE_KEY) {
110
+ return {
111
+ valueIdx: i,
112
+ value: (match[3] ?? "").replace(/^['"]|['"]$/g, ""),
113
+ blockIdx,
114
+ lastEntryIdx,
115
+ indent
116
+ };
117
+ }
118
+ }
119
+ return { blockIdx, lastEntryIdx, indent };
120
+ }
121
+ function applyOverride(lines, entry, want) {
122
+ const line = `${entry.indent}'${OVERRIDE_KEY}': ${want}`;
123
+ if (entry.valueIdx !== void 0) {
124
+ lines[entry.valueIdx] = line;
125
+ return;
126
+ }
127
+ if (entry.lastEntryIdx !== void 0) {
128
+ lines.splice(entry.lastEntryIdx + 1, 0, line);
129
+ return;
130
+ }
131
+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
132
+ lines.push("overrides:", line, "");
133
+ }
134
+ function ensureReleaseAgeAllowList(root, dryRun) {
135
+ const yamlPath = join2(root, WORKSPACE_YAML);
136
+ if (!existsSync2(yamlPath)) return void 0;
137
+ const own = readOwnPackage().name;
138
+ const lines = readFileSync2(yamlPath, "utf8").split("\n");
139
+ const keyIdx = lines.findIndex((line) => line.replace(/\s+$/, "") === `${RELEASE_AGE_KEY}:`);
140
+ if (keyIdx === -1) return void 0;
141
+ let lastItemIdx = keyIdx;
142
+ let indent = " ";
143
+ for (let i = keyIdx + 1; i < lines.length; i++) {
144
+ const match = lines[i]?.match(LIST_ITEM);
145
+ if (!match) break;
146
+ indent = match[1] ?? indent;
147
+ lastItemIdx = i;
148
+ if ((match[2] ?? "").replace(/^['"]|['"]$/g, "") === own) return void 0;
149
+ }
150
+ if (dryRun) return `would allow-list ${own} under ${RELEASE_AGE_KEY}`;
151
+ lines.splice(lastItemIdx + 1, 0, `${indent}- '${own}'`);
152
+ writeFileSync(yamlPath, lines.join("\n"));
153
+ return `allow-listed ${own} under ${RELEASE_AGE_KEY} in ${WORKSPACE_YAML}`;
154
+ }
155
+ var PRETTIER_IGNORE = ".prettierignore";
156
+ var EXCLUSION_HEADER = "# @hublo/sentinel: modules formatted by oxfmt, not by the root Prettier";
157
+ var ROOT_PRETTIER_CONFIGS = [
158
+ ".prettierrc",
159
+ ".prettierrc.json",
160
+ ".prettierrc.json5",
161
+ ".prettierrc.yml",
162
+ ".prettierrc.yaml",
163
+ ".prettierrc.js",
164
+ ".prettierrc.cjs",
165
+ ".prettierrc.mjs",
166
+ "prettier.config.js",
167
+ "prettier.config.cjs",
168
+ "prettier.config.mjs"
169
+ ];
170
+ function ensureFormatterExclusion(root, moduleDir, dryRun) {
171
+ const rel = relative(root, moduleDir).replaceAll("\\", "/");
172
+ if (rel === "" || rel.startsWith("..")) return void 0;
173
+ const ignorePath = join2(root, PRETTIER_IGNORE);
174
+ const hasPrettier = existsSync2(ignorePath) || ROOT_PRETTIER_CONFIGS.some((name) => existsSync2(join2(root, name)));
175
+ if (!hasPrettier) return void 0;
176
+ const pattern = `/${rel}/`;
177
+ const existing = existsSync2(ignorePath) ? readFileSync2(ignorePath, "utf8") : "";
178
+ const lines = existing.split("\n");
179
+ if (lines.some((line) => line.trim().replace(/\/$/, "") === pattern.replace(/\/$/, ""))) {
180
+ return void 0;
181
+ }
182
+ if (dryRun) return `would exclude ${rel} from the root Prettier (${PRETTIER_IGNORE})`;
183
+ const headerIdx = lines.findIndex((line) => line.trim() === EXCLUSION_HEADER);
184
+ if (headerIdx === -1) {
185
+ const prefix = existing.trim() === "" ? "" : `${existing.replace(/\n*$/, "")}
186
+
187
+ `;
188
+ writeFileSync(ignorePath, `${prefix}${EXCLUSION_HEADER}
189
+ ${pattern}
190
+ `);
191
+ } else {
192
+ let end = headerIdx + 1;
193
+ while (end < lines.length && lines[end]?.trim().startsWith("/")) end += 1;
194
+ const managed = [...lines.slice(headerIdx + 1, end), pattern].sort();
195
+ writeFileSync(
196
+ ignorePath,
197
+ [...lines.slice(0, headerIdx + 1), ...managed, ...lines.slice(end)].join("\n")
198
+ );
199
+ }
200
+ return `excluded ${rel} from the root Prettier (${PRETTIER_IGNORE}): it formats itself now`;
201
+ }
202
+ function ensureWorkspacePrep(opts) {
203
+ const dryRun = Boolean(opts.dryRun);
204
+ return [
205
+ ensureI18nextSingleton(opts.root, dryRun),
206
+ ensureReleaseAgeAllowList(opts.root, dryRun),
207
+ opts.formattedModule === void 0 ? void 0 : ensureFormatterExclusion(opts.root, opts.formattedModule, dryRun)
208
+ ].filter((message) => message !== void 0);
209
+ }
210
+ function inspectWorkspacePrep(root) {
211
+ const entries = [];
212
+ let pkg = {};
213
+ const pkgPath = join2(root, "package.json");
214
+ if (existsSync2(pkgPath)) {
215
+ try {
216
+ pkg = JSON.parse(readFileSync2(pkgPath, "utf8"));
217
+ } catch {
218
+ pkg = {};
219
+ }
220
+ }
221
+ const yamlPath = join2(root, WORKSPACE_YAML);
222
+ const yaml = existsSync2(yamlPath) ? readFileSync2(yamlPath, "utf8") : void 0;
223
+ const pinned = yaml === void 0 ? void 0 : findOverrideEntry(yaml.split("\n")).value;
224
+ if (pinned !== void 0) {
225
+ const stillForks = declaredNativeTs(pkg);
226
+ entries.push({
227
+ rule: `${WORKSPACE_YAML} \u2192 overrides.${OVERRIDE_KEY}`,
228
+ reason: stillForks === void 0 ? `pinned to ${pinned}, but the root no longer declares ${NATIVE_TS_ALIAS}, so nothing forks any more. This override is now dead config and can be removed.` : `pinned to ${pinned}, matching the second TypeScript the root declares (${NATIVE_TS_ALIAS}). It re-resolves i18next for EVERY module that depends on it, not only adopted ones. It retires with the second TypeScript.`
229
+ });
230
+ }
231
+ const legacy = pkg.pnpm?.overrides?.[OVERRIDE_KEY];
232
+ if (legacy !== void 0) {
233
+ entries.push({
234
+ rule: `package.json \u2192 pnpm.overrides.${OVERRIDE_KEY}`,
235
+ reason: `pinned to ${legacy}, but pnpm 11 no longer reads the \`pnpm\` field of package.json and says nothing about it, so this override is not applied. Move it to ${WORKSPACE_YAML} under \`overrides:\`, which pnpm 10 and 11 both read.`
236
+ });
237
+ }
238
+ const own = readOwnPackage().name;
239
+ if (yaml !== void 0) {
240
+ const listed = new RegExp(`^\\s*-\\s*['"]?${own.replace("/", "\\/")}['"]?\\s*$`, "m").test(yaml);
241
+ if (listed) {
242
+ const gated = new RegExp(`^\\s*minimumReleaseAge\\s*:`, "m").test(yaml);
243
+ entries.push({
244
+ rule: `${WORKSPACE_YAML} \u2192 ${RELEASE_AGE_KEY}: ${own}`,
245
+ reason: gated ? `${own} is exempt from this workspace's release-age gate, so a freshly published version installs instead of being held. That is a standing exemption from a supply-chain control: the exposure is one bump wide, since the version is pinned and the lockfile carries its integrity, so a re-publish of the same version does not pass. Retire it once a bump can simply wait out the window.` : `${own} is allow-listed, but this workspace no longer sets minimumReleaseAge, so there is no gate to be exempt from. This entry is now dead config and can be removed.`
246
+ });
247
+ }
248
+ }
249
+ return entries;
250
+ }
251
+
252
+ export {
253
+ readOwnPackage,
254
+ readOwnVersion,
255
+ readProjectPackageJson,
256
+ readNxProjectName,
257
+ moduleName,
258
+ WORKSPACE_ROOT_MARKER,
259
+ DEFAULT_MAX_DIAGNOSTICS,
260
+ findWorkspaceRoot,
261
+ ensureWorkspacePrep,
262
+ inspectWorkspacePrep
263
+ };
264
+ //# sourceMappingURL=chunk-WLFE5RUU.js.map
package/dist/index.js CHANGED
@@ -7,7 +7,8 @@ import {
7
7
  registerAdapters,
8
8
  resolve,
9
9
  setDefaultRunner
10
- } from "./chunk-676GBPMS.js";
10
+ } from "./chunk-O3XCQGTJ.js";
11
+ import "./chunk-WLFE5RUU.js";
11
12
  export {
12
13
  BaseAdapter,
13
14
  all,
@@ -1,8 +1,9 @@
1
1
  import { UserConfig, Plugin } from 'vite';
2
2
  export { Plugin, PluginOption, UserConfig, UserConfigExport, defineConfig, loadEnv, mergeConfig } from 'vite';
3
+ export { A as Alias, D as DecoratorMetadataOptions, d as decoratorMetadata, t as tsconfigAliases } from '../../../tsconfig-aliases-Ce6axdJ4.js';
3
4
 
4
5
  /** A transformer as the target declares it, passed through to the config unchanged. */
5
- interface TransformerDeclaration$1 {
6
+ interface TransformerDeclaration {
6
7
  name: string;
7
8
  options?: Record<string, unknown>;
8
9
  }
@@ -41,7 +42,7 @@ interface NestServiceOptions {
41
42
  * without it succeeds and silently costs them most of their published contract (measured on
42
43
  * `institution`: 385 insertions, 1378 deletions in the committed OpenAPI document).
43
44
  */
44
- transformers?: readonly TransformerDeclaration$1[];
45
+ transformers?: readonly TransformerDeclaration[];
45
46
  /**
46
47
  * Files copied into the output beside the bundle, in the shape `@nx/webpack` declared them.
47
48
  *
@@ -60,27 +61,6 @@ interface NestServiceOptions {
60
61
  }
61
62
  declare const nestService: (options: NestServiceOptions) => UserConfig;
62
63
 
63
- /** A TypeScript transformer a service runs at build time, as its build target declares it. */
64
- interface TransformerDeclaration {
65
- /** The package to load it from, e.g. `@nestjs/swagger/plugin`. */
66
- name: string;
67
- /** Passed to the transformer's own factory, unread here. */
68
- options?: Record<string, unknown>;
69
- }
70
- interface DecoratorMetadataOptions {
71
- /** The module being built. Its tsconfig is the one whose emit must be preserved. */
72
- root: string;
73
- /**
74
- * An explicit tsconfig, when the service does not use either conventional name.
75
- *
76
- * Relative paths resolve against `root`.
77
- */
78
- tsconfig?: string;
79
- /** The transformers this service declared, translated from its webpack target. */
80
- transformers?: readonly TransformerDeclaration[];
81
- }
82
- declare const decoratorMetadata: (options: DecoratorMetadataOptions) => Plugin;
83
-
84
64
  interface NodeManifestOptions {
85
65
  /** The nx project name, which is how the graph is keyed. */
86
66
  project: string;
@@ -115,16 +95,4 @@ interface NodeManifestOptions {
115
95
  */
116
96
  declare const nodeManifest: (options: NodeManifestOptions) => Plugin;
117
97
 
118
- interface Alias {
119
- find: RegExp;
120
- replacement: string;
121
- }
122
- /**
123
- * Read the mappings from the workspace's base tsconfig.
124
- *
125
- * Longest pattern first, because Vite takes the first alias that matches and the mappings
126
- * overlap by design: `@front/theme/node` must not be swallowed by `@front/theme`.
127
- */
128
- declare const tsconfigAliases: (workspaceRoot: string, file?: string) => Alias[];
129
-
130
- export { type Alias, type DecoratorMetadataOptions, type NestServiceOptions, type NodeManifestOptions, decoratorMetadata, nestService, nodeManifest, tsconfigAliases };
98
+ export { type NestServiceOptions, type NodeManifestOptions, nestService, nodeManifest };
@@ -1,5 +1,10 @@
1
+ import {
2
+ decoratorMetadata,
3
+ tsconfigAliases
4
+ } from "../../../chunk-3TDUIKVQ.js";
5
+
1
6
  // src/roles/build/nest/nest-service.ts
2
- import { join as join4 } from "path";
7
+ import { join as join3 } from "path";
3
8
  import { mergeConfig } from "vite";
4
9
 
5
10
  // src/roles/build/nest/copy-assets.ts
@@ -76,161 +81,8 @@ var copyAssets = (options) => ({
76
81
  }
77
82
  });
78
83
 
79
- // src/roles/build/nest/decorator-metadata.ts
80
- import { existsSync as existsSync2 } from "fs";
81
- import { createRequire } from "module";
82
- import path from "path";
83
- var TYPESCRIPT_SOURCE = /\.ts$/;
84
- var TSCONFIG_CANDIDATES = ["tsconfig.app.json", "tsconfig.json"];
85
- function loadCompiler(root) {
86
- const require2 = createRequire(path.join(root, "noop.js"));
87
- let compiler;
88
- try {
89
- compiler = require2("typescript");
90
- } catch {
91
- throw new Error(
92
- `sentinel build(nest): no \`typescript\` resolvable from ${root}. The build emits decorator metadata with the module's own compiler, so one has to be installed there.`
93
- );
94
- }
95
- if (typeof compiler.createProgram !== "function") {
96
- throw new Error(
97
- `sentinel build(nest): the typescript resolved from ${root} (${compiler.version ?? "unknown"}) has no createProgram API. TypeScript 7 is the native port and exposes none; the emit API lives under @typescript/typescript6. Point this module's \`typescript\` at a compiler with an emit API, which is the one its \`typecheck\` target already uses.`
98
- );
99
- }
100
- return compiler;
101
- }
102
- function resolveTsconfig(options) {
103
- if (options.tsconfig) {
104
- const explicit = path.resolve(options.root, options.tsconfig);
105
- if (!existsSync2(explicit)) {
106
- throw new Error(`sentinel build(nest): tsconfig not found at ${explicit}`);
107
- }
108
- return explicit;
109
- }
110
- for (const candidate of TSCONFIG_CANDIDATES) {
111
- const found = path.join(options.root, candidate);
112
- if (existsSync2(found)) return found;
113
- }
114
- throw new Error(
115
- `sentinel build(nest): no ${TSCONFIG_CANDIDATES.join(" or ")} in ${options.root}. Pass \`tsconfig\` if this service keeps it elsewhere.`
116
- );
117
- }
118
- function readConfig(ts, options) {
119
- const configPath = resolveTsconfig(options);
120
- const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, {
121
- ...ts.sys,
122
- onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
123
- throw new Error(
124
- `sentinel build(nest): could not read ${configPath}: ` + ts.flattenDiagnosticMessageText(diagnostic.messageText, " ")
125
- );
126
- }
127
- });
128
- return {
129
- fileNames: parsed?.fileNames ?? [],
130
- compilerOptions: {
131
- ...parsed?.options,
132
- // ESM out, so Rollup sees imports and exports rather than an opaque `require` it cannot
133
- // follow. The service still SHIPS as CJS: that conversion is the bundler's, further down.
134
- module: ts.ModuleKind.ESNext,
135
- // Vite consumes the map; the tsconfig's own answer is about a different pipeline.
136
- sourceMap: true,
137
- inlineSourceMap: false,
138
- inlineSources: false,
139
- // Types are another target's job, and emitting them here would write into the source tree.
140
- declaration: false,
141
- declarationMap: false,
142
- emitDeclarationOnly: false,
143
- noEmit: false,
144
- // `composite` projects refuse to emit without a `tsBuildInfoFile`, and there is no
145
- // incremental build here to inform.
146
- composite: false,
147
- incremental: false
148
- }
149
- };
150
- }
151
- function loadTransformers(root, program, declared) {
152
- const require2 = createRequire(path.join(root, "noop.js"));
153
- return declared.map(({ name, options }) => {
154
- let loaded;
155
- try {
156
- loaded = require2(name);
157
- } catch (error) {
158
- throw new Error(
159
- `sentinel build(nest): the build target declares the transformer \`${name}\`, which cannot be loaded from ${root}: ${error instanceof Error ? error.message : String(error)}`,
160
- { cause: error }
161
- );
162
- }
163
- if (typeof loaded.before !== "function") {
164
- throw new Error(
165
- `sentinel build(nest): \`${name}\` exports no \`before\` factory, so it cannot run as a TypeScript transformer. Building without it would drop whatever it contributes.`
166
- );
167
- }
168
- const factory = loaded.before;
169
- return factory(options, program);
170
- });
171
- }
172
- var decoratorMetadata = (options) => {
173
- const typeAware = (options.transformers ?? []).length > 0;
174
- let ts;
175
- let program;
176
- let compilerOptions;
177
- let before = [];
178
- const withoutTypes = [];
179
- return {
180
- name: "sentinel:decorator-metadata",
181
- // Before Vite's own transform, so esbuild never sees the decorators it cannot handle, and so
182
- // the source this plugin reads from the Program is still the source on disk.
183
- enforce: "pre",
184
- buildStart() {
185
- ts = loadCompiler(options.root);
186
- const config = readConfig(ts, options);
187
- compilerOptions = config.compilerOptions;
188
- if (!typeAware) return;
189
- program = ts.createProgram(config.fileNames, config.compilerOptions);
190
- before = loadTransformers(options.root, program, options.transformers ?? []);
191
- },
192
- transform(code, id) {
193
- if (!TYPESCRIPT_SOURCE.test(id) || id.includes("node_modules")) return null;
194
- if (ts === void 0 || compilerOptions === void 0) {
195
- throw new Error(
196
- `sentinel build(nest): the compiler was never prepared, so ${id} would be emitted with defaults rather than this module's tsconfig.`
197
- );
198
- }
199
- const sourceFile = program?.getSourceFile(id);
200
- if (program === void 0 || sourceFile === void 0 || sourceFile.text !== code) {
201
- if (typeAware) withoutTypes.push(id);
202
- const output = ts.transpileModule(code, { fileName: id, compilerOptions });
203
- return { code: output.outputText, map: output.sourceMapText ?? null };
204
- }
205
- let emitted;
206
- let map;
207
- program.emit(
208
- sourceFile,
209
- (fileName, text) => {
210
- if (fileName.endsWith(".map")) map = text;
211
- else emitted = text;
212
- },
213
- void 0,
214
- false,
215
- { before }
216
- );
217
- if (emitted === void 0) {
218
- throw new Error(`sentinel build(nest): TypeScript emitted nothing for ${id}.`);
219
- }
220
- return { code: emitted, map: map ?? null };
221
- },
222
- closeBundle() {
223
- if (withoutTypes.length === 0) return;
224
- const shown = withoutTypes.slice(0, 5).map((file) => path.relative(options.root, file));
225
- this.warn(
226
- `sentinel build(nest): ${withoutTypes.length} file(s) were emitted without type information, so their decorator metadata may differ from what ts-loader produced (${shown.join(", ")}${withoutTypes.length > shown.length ? ", \u2026" : ""}). They are outside this module's tsconfig, or another plugin rewrote them first.`
227
- );
228
- }
229
- };
230
- };
231
-
232
84
  // src/roles/build/nest/node-manifest.ts
233
- import { existsSync as existsSync3, writeFileSync } from "fs";
85
+ import { existsSync as existsSync2, writeFileSync } from "fs";
234
86
  import { isBuiltin } from "module";
235
87
  import { join as join2 } from "path";
236
88
  var DEFAULT_PROVIDED_BY_IMAGE = ["@prisma"];
@@ -260,7 +112,7 @@ var nodeManifest = (options) => {
260
112
  },
261
113
  async closeBundle() {
262
114
  const entry = options.entry ?? "main.js";
263
- if (!existsSync3(join2(options.outDir, entry))) return;
115
+ if (!existsSync2(join2(options.outDir, entry))) return;
264
116
  const { createProjectGraphAsync } = await import("nx/src/devkit-exports.js");
265
117
  const { createPackageJson, createLockFile, getLockFileName } = await import("@nx/js");
266
118
  const graph = await createProjectGraphAsync({ exitOnError: false });
@@ -294,30 +146,10 @@ var assertManifestCovers = (required, manifest, options) => {
294
146
  );
295
147
  };
296
148
 
297
- // src/roles/build/nest/tsconfig-aliases.ts
298
- import { readFileSync } from "fs";
299
- import { join as join3 } from "path";
300
- var stripLineComments = (json) => json.replace(/^\s*\/\/.*$/gm, "");
301
- var toAlias = (workspaceRoot, pattern, target) => {
302
- const escaped = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, "(.*)");
303
- return {
304
- find: new RegExp(`^${escaped}$`),
305
- replacement: join3(workspaceRoot, target.replace(/\*/g, "$1"))
306
- };
307
- };
308
- var tsconfigAliases = (workspaceRoot, file = "tsconfig.base.json") => {
309
- const raw = readFileSync(join3(workspaceRoot, file), "utf8");
310
- const { compilerOptions } = JSON.parse(stripLineComments(raw));
311
- return Object.entries(compilerOptions?.paths ?? {}).flatMap(([pattern, targets]) => {
312
- const [target] = targets;
313
- return target === void 0 ? [] : [toAlias(workspaceRoot, pattern, target)];
314
- }).sort((a, b) => b.find.source.length - a.find.source.length);
315
- };
316
-
317
149
  // src/roles/build/nest/nest-service.ts
318
150
  var baseConfig = (options) => {
319
- const outDir = join4(options.workspaceRoot, options.outDir ?? `dist/${options.project}`);
320
- const entry = join4(options.root, options.entry ?? "src/main.ts");
151
+ const outDir = join3(options.workspaceRoot, options.outDir ?? `dist/${options.project}`);
152
+ const entry = join3(options.root, options.entry ?? "src/main.ts");
321
153
  return {
322
154
  plugins: [
323
155
  decoratorMetadata({
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/roles/build/nest/nest-service.ts","../../../../src/roles/build/nest/copy-assets.ts","../../../../src/roles/build/nest/node-manifest.ts","../../../../src/roles/build/nest/toolchain.ts"],"sourcesContent":["/**\n * The whole Vite config for a Nest service, so an adopted module holds two lines.\n *\n * ## Why a shape here, and pieces on the React side\n *\n * It looks inconsistent until you measure the two families. The four React apps each carry a\n * heavy, genuinely different config: one has a plugin wedged between two shared ones, another\n * has two different route-tree footers on the branches of one ternary. Two attempts at a\n * shared shape for them were abandoned, and the rule that survived is that sentinel rewrites\n * their IMPORTS and touches nothing else.\n *\n * The Nest side is the opposite by measurement: 38 services, one shared 25-line webpack config\n * between them, and nothing per-module to preserve. Owning the shape there is not a different\n * philosophy, it is the same one applied to a different fact: sentinel provides the FORM where\n * the form is shared, and the PIECES where it is not.\n *\n * The consequences are the point. An adopted module is readable in review. A correction to the\n * form is one publish instead of 38 diffs. And the day Nest becomes ESM-native, `format`\n * changes here rather than in 38 configs.\n *\n * ## It is a composition, not a block\n *\n * `nestService` assembles the same plugins this module exports individually. A service that\n * needs something else can pass `overrides`, or drop to the pieces entirely. And if the React\n * configs ever converge, a `reactApp()` can be built the same way with no new mechanism.\n */\nimport { join } from 'node:path'\n\nimport { mergeConfig, type UserConfig } from 'vite'\n\nimport { copyAssets } from './copy-assets.js'\nimport { decoratorMetadata } from './decorator-metadata.js'\nimport { nodeManifest } from './node-manifest.js'\nimport type { AssetDeclaration, TransformerDeclaration } from './nx-target.js'\nimport { tsconfigAliases } from './tsconfig-aliases.js'\n\nexport interface NestServiceOptions {\n /** The nx project name. Keys the dependency graph, and names the module in messages. */\n project: string\n /** Absolute path to the module's directory, normally `__dirname`. */\n root: string\n /** Absolute path to the workspace root. */\n workspaceRoot: string\n /** Entry point, relative to `root`. */\n entry?: string\n /**\n * The tsconfig whose emit must be preserved, when the service uses neither conventional name.\n *\n * Relative to `root`. Defaults to `tsconfig.app.json`, then `tsconfig.json`.\n */\n tsconfig?: string\n /** Output directory, relative to `workspaceRoot`. */\n outDir?: string\n /**\n * TypeScript transformers this service compiles with, as its build target declared them.\n *\n * Read off the webpack target by `--init` and written here, never inferred: what a service\n * compiles with is the service's own. Eight services and BFFs run `@nestjs/swagger/plugin`,\n * which writes the `@ApiProperty` decorators their DTOs do not declare by hand. Building\n * without it succeeds and silently costs them most of their published contract (measured on\n * `institution`: 385 insertions, 1378 deletions in the committed OpenAPI document).\n */\n transformers?: readonly TransformerDeclaration[]\n /**\n * Files copied into the output beside the bundle, in the shape `@nx/webpack` declared them.\n *\n * One service here uses it: `planning-period` ships the pug, css and ttf templates it renders\n * printed documents from. Without them the service starts and fails on its first print.\n */\n assets?: readonly AssetDeclaration[]\n /**\n * Anything this service needs that the shape does not give it.\n *\n * Merged with Vite's own `mergeConfig`, never with a merge of our own: plugins concatenate\n * and aliases stack the way Vite does it everywhere else, so there is no second set of\n * semantics to learn or to document.\n */\n overrides?: UserConfig\n}\n\nconst baseConfig = (options: NestServiceOptions): UserConfig => {\n const outDir = join(options.workspaceRoot, options.outDir ?? `dist/${options.project}`)\n const entry = join(options.root, options.entry ?? 'src/main.ts')\n return {\n plugins: [\n decoratorMetadata({\n root: options.root,\n tsconfig: options.tsconfig,\n transformers: options.transformers,\n }),\n ...(options.assets?.length\n ? [copyAssets({ workspaceRoot: options.workspaceRoot, outDir, assets: options.assets })]\n : []),\n nodeManifest({\n project: options.project,\n workspaceRoot: options.workspaceRoot,\n outDir,\n }),\n ],\n resolve: { alias: tsconfigAliases(options.workspaceRoot) },\n ssr: {\n // `importHelpers: true` in the workspace tsconfig makes TypeScript emit `require(\"tslib\")`\n // for `__decorate` and `__metadata`, so every decorated file depends on it. Hoisted into\n // one scope Rollup inlined it and nobody noticed; preserving modules left it external, and\n // the manifest nx generates from the project graph does not list it, because no module\n // DECLARES tslib. The image therefore did not install it and the service died on its first\n // require, only in the image: locally and in CI the workspace root has tslib.\n noExternal: ['tslib'],\n },\n build: {\n // An SSR build targets Node and leaves real packages external, which is what\n // `webpack-node-externals` did: the image installs them from the generated manifest.\n ssr: entry,\n outDir,\n emptyOutDir: true,\n sourcemap: true,\n target: 'node20',\n // The bundle is read by humans when a stack trace points into it, and minifying a\n // server bundle buys nothing: it is never downloaded.\n minify: false,\n rollupOptions: {\n output: {\n format: 'cjs',\n // One output file per source module, instead of hoisting everything into one scope.\n //\n // This is not a preference, it is the only shape that keeps the OpenAPI contract.\n // Merging every module into one scope forces Rollup to rename duplicate class names,\n // and `@nestjs/swagger` keys its schemas on `class.name`, so a renamed class silently\n // becomes a renamed schema in the published API. Measured on `network`, which has two\n // such collisions: single bundle renames `InvalidPermissionError` and\n // `PermissionNotFoundError`; preserving modules renames nothing and reproduces the\n // committed contract byte for byte.\n //\n // The cost is 4.5 MB across 2003 files against 2.9 MB in one, still well under\n // webpack's 6.9 MB for the same service, so nothing regresses against what it replaces.\n preserveModules: true,\n // The image runs `./dist/main.js`, so the entry keeps that name at the root while\n // every other module keeps its own path. Under `preserveModules` a plain string here\n // would be applied to all of them, which numbers them (`main962.js`) and loses the\n // entry.\n entryFileNames: (chunk) => (chunk.facadeModuleId === entry ? 'main.js' : '[name].js'),\n },\n // Nest registers metadata as an IMPORT SIDE EFFECT: a decorator writes into a catalog\n // when its module loads, and nothing references that module afterwards. Rollup may\n // drop such a module; webpack never did.\n //\n // Measured on the first migrated service this changes nothing, so it is insurance\n // rather than a fix, and it is recorded as such rather than credited with the smaller\n // bundle (that comes from barrel re-exports the service does not use).\n treeshake: { moduleSideEffects: true },\n },\n },\n }\n}\n\nexport const nestService = (options: NestServiceOptions): UserConfig =>\n options.overrides === undefined\n ? baseConfig(options)\n : mergeConfig(baseConfig(options), options.overrides)\n","/**\n * The files a service ships beside its bundle, which webpack copied and a bundler does not.\n *\n * `@nx/webpack` takes an `assets` list and copies each match into the output. Nothing in a Vite\n * build does that for a Node target: `publicDir` is a browser concept and is disabled for SSR\n * builds, so an unmigrated `assets` entry is not a smaller output, it is a service that starts\n * and then fails the first time it reaches for a file that is not there.\n *\n * One service in this repo declares it. `planning-period` ships the pug templates, stylesheet and\n * font it renders printed documents from, under `templates/`. Dropping them leaves a build that\n * succeeds, an image that boots, and a printing feature that throws.\n *\n * ## Copied at `closeBundle`, and only what the target declared\n *\n * The declaration is carried through from the webpack target unchanged, globs and all, so this\n * plugin has nothing to decide: it resolves each `input` against the workspace root, matches the\n * glob, and writes under `output` inside the bundle's directory. `closeBundle` because that is\n * when the output directory exists and Vite has finished emptying it.\n *\n * An entry matching nothing FAILS the build. A glob that has quietly stopped matching is the same\n * silent loss as no glob at all, and the point of this file is that this class of loss is loud.\n */\nimport { cpSync, existsSync, mkdirSync, readdirSync, statSync } from 'node:fs'\nimport { dirname, join, relative, sep } from 'node:path'\n\nimport type { Plugin } from 'vite'\n\nimport type { AssetDeclaration } from './nx-target.js'\n\nexport interface CopyAssetsOptions {\n /** Absolute path to the workspace root, which `input` is relative to. */\n workspaceRoot: string\n /** Absolute path to the build's output directory. */\n outDir: string\n assets: readonly AssetDeclaration[]\n}\n\n/**\n * `@nx/webpack`'s glob dialect, reduced to what it means for a file name.\n *\n * Only the forms the declarations here use are supported, and anything else is rejected at build\n * time rather than silently matching nothing: `**` for any depth, `*` within a segment, and a\n * `{a,b}` alternation. Written out rather than pulled from a glob library because the whole\n * dependency would exist to read one line of configuration.\n */\nfunction globToRegExp(glob: string): RegExp {\n let pattern = ''\n for (let index = 0; index < glob.length; index++) {\n const char = glob[index] ?? ''\n if (char === '*') {\n if (glob[index + 1] === '*') {\n // `**/` matches any number of directories, including none.\n pattern += glob[index + 2] === '/' ? '(?:.*/)?' : '.*'\n index += glob[index + 2] === '/' ? 2 : 1\n } else {\n pattern += '[^/]*'\n }\n continue\n }\n if (char === '{') {\n const close = glob.indexOf('}', index)\n if (close === -1)\n throw new Error(`sentinel build(nest): unbalanced \\`{\\` in asset glob ${glob}`)\n const alternatives = glob.slice(index + 1, close).split(',')\n pattern += `(?:${alternatives.map((one) => one.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')).join('|')})`\n index = close\n continue\n }\n pattern += char.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n }\n return new RegExp(`^${pattern}$`)\n}\n\n/** Every file under `root`, as paths relative to it and with forward slashes. */\nfunction filesUnder(root: string): string[] {\n const found: string[] = []\n const walk = (dir: string): void => {\n for (const entry of readdirSync(dir)) {\n const full = join(dir, entry)\n if (statSync(full).isDirectory()) walk(full)\n else found.push(relative(root, full).split(sep).join('/'))\n }\n }\n walk(root)\n return found\n}\n\n/** What each declaration copies, or the reason it cannot. */\nexport function resolveAssets(options: CopyAssetsOptions): { from: string; to: string }[] {\n const copies: { from: string; to: string }[] = []\n for (const asset of options.assets) {\n const input = join(options.workspaceRoot, asset.input)\n if (!existsSync(input)) {\n throw new Error(\n `sentinel build(nest): the build target declares an asset from \\`${asset.input}\\`, which ` +\n `does not exist. webpack copied it into the output, so the built service would be ` +\n `missing files it reads at runtime.`,\n )\n }\n const matcher = globToRegExp(asset.glob)\n const matched = filesUnder(input).filter((file) => matcher.test(file))\n if (matched.length === 0) {\n throw new Error(\n `sentinel build(nest): the asset glob \\`${asset.glob}\\` under \\`${asset.input}\\` matches ` +\n `no file. An entry that matches nothing is the same silent loss as no entry at all.`,\n )\n }\n for (const file of matched) {\n copies.push({ from: join(input, file), to: join(options.outDir, asset.output, file) })\n }\n }\n return copies\n}\n\nexport const copyAssets = (options: CopyAssetsOptions): Plugin => ({\n name: 'sentinel:copy-assets',\n // After the bundle is written and the output directory has stopped being emptied.\n closeBundle() {\n for (const { from, to } of resolveAssets(options)) {\n mkdirSync(dirname(to), { recursive: true })\n cpSync(from, to)\n }\n },\n})\n","/**\n * The pruned `package.json` and lockfile a Node image installs from.\n *\n * This is the half that made the nx executor look load-bearing. `--generatePackageJson` was an\n * option of `@nx/webpack:webpack`, and the backend image is built on its two outputs:\n *\n * COPY --from=build /app/dist/apps/nest/<service>/package.json /app/package.json\n * COPY --from=build /app/dist/apps/nest/<service>/pnpm-lock.yaml /app/pnpm-lock.yaml\n * RUN pnpm i --prod=true --frozen-lockfile\n *\n * It is not bound to the executor. The executor supplies one thing, the project graph, and\n * every function that does the work is exported by `@nx/js`. So the same two files can be\n * produced from a Vite plugin, and `--frozen-lockfile` accepting them afterwards is the proof\n * that they agree with each other: pnpm refuses the install otherwise.\n *\n * ## Why the graph, and not something simpler\n *\n * A Nest service here declares almost nothing of its own: measured, one dependency in its\n * manifest against 1463 installed in its image. Everything it uses is declared at the\n * workspace root and reaches it through source imports. So the dependency list can only be\n * computed from what the code imports, which is what the graph knows.\n *\n * Deriving it from the bundle's own externals is not equivalent either: measured on the first\n * service, the bundle statically requires 42 packages while the correct manifest holds 65. The\n * 23 missing ones are transitive or required dynamically at runtime (`fastify` behind\n * `@nestjs/platform-fastify`, `jsonwebtoken`, the LaunchDarkly SDK). Shipping the short list\n * fails in production, not in the build.\n */\nimport { existsSync, writeFileSync } from 'node:fs'\nimport { isBuiltin } from 'node:module'\nimport { join } from 'node:path'\n\nimport type { Plugin, Rollup } from 'vite'\n\nexport interface NodeManifestOptions {\n /** The nx project name, which is how the graph is keyed. */\n project: string\n /** Absolute path to the workspace root. */\n workspaceRoot: string\n /** Where the bundle is written; the two files land beside it. */\n outDir: string\n /** Entry file name, written as `main` so `node .` resolves inside the image. */\n entry?: string\n /**\n * Packages the IMAGE provides, which are therefore allowed to be required without being\n * declared in the manifest.\n *\n * The generated Prisma clients are the case this exists for: the Dockerfile copies\n * `node_modules/@prisma` from its own stage, so they resolve at runtime while no module\n * declares them. Everything else that is required and undeclared is a bug, and the check\n * below refuses the build.\n */\n providedByImage?: readonly string[]\n}\n\n/** What the Dockerfile copies in itself, so requiring it without declaring it is legitimate. */\nconst DEFAULT_PROVIDED_BY_IMAGE = ['@prisma'] as const\n\n/**\n * Every real package the emitted output requires, from Rollup's own record rather than a scan\n * of the text.\n *\n * `chunk.imports` mixes three things, and only the third is a dependency:\n *\n * - other EMITTED chunks. Under `preserveModules` these are relative output paths that do not\n * begin with `.`, so `apps/…`, `libs/…` and `_virtual/…` read exactly like package names.\n * They are recognised by being keys of the bundle itself.\n * - Node BUILTINS, which appear both bare (`crypto`) and prefixed (`node:crypto`).\n * - genuine external packages, which is what the manifest has to cover.\n */\nconst externalPackages = (bundle: Rollup.OutputBundle): Set<string> => {\n const emitted = new Set(Object.keys(bundle))\n const packages = new Set<string>()\n\n for (const emittedFile of Object.values(bundle)) {\n // Assets carry no imports, and the bundle holds both. Narrowing on the discriminant is what\n // replaced a cast through `unknown`, which asserted the same thing without checking it.\n if (emittedFile.type !== 'chunk') continue\n\n for (const imported of emittedFile.imports) {\n if (emitted.has(imported)) continue\n if (imported.startsWith('.') || imported.startsWith('/')) continue\n if (isBuiltin(imported)) continue\n\n const parts = imported.split('/')\n const name = imported.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]\n if (name) packages.add(name)\n }\n }\n return packages\n}\n\n/**\n * Writes the manifest and lockfile once the bundle is on disk.\n *\n * `closeBundle` rather than `writeBundle`, so the files land after Vite has finished with the\n * directory and cannot be cleared by `emptyOutDir`.\n *\n * `closeBundle` also runs after a FAILED build, where there is no directory to write into. Left\n * alone this hook then threw `ENOENT` on the manifest, and since it is the last error raised it\n * became the one Vite printed, hiding the failure that actually stopped the build. It cost two\n * diagnoses before being recognised, so the missing directory is now read as what it is: the\n * bundle was never written, and this plugin has nothing to say about why.\n */\nexport const nodeManifest = (options: NodeManifestOptions): Plugin => {\n /*\n * Captured while the bundle still exists in memory, and read back once the manifest is built.\n *\n * `undefined` until `generateBundle` runs, deliberately: an empty SET would make the coverage\n * check below pass by having seen nothing, which is the worst way for a guard to succeed. The\n * two states have to be told apart.\n */\n let required: Set<string> | undefined\n\n return {\n name: 'sentinel:node-manifest',\n apply: 'build',\n\n generateBundle(_outputOptions, bundle) {\n required = externalPackages(bundle)\n },\n\n async closeBundle() {\n // `closeBundle` runs after a FAILED build too. The ENTRY is what says a bundle was really\n // written: `emptyOutDir` leaves the directory in place, so its existence alone would let a\n // failed build still produce a manifest describing nothing.\n const entry = options.entry ?? 'main.js'\n if (!existsSync(join(options.outDir, entry))) return\n\n // Imported here rather than at module scope: a front config importing this file must not\n // pay for loading the nx graph machinery it will never call.\n const { createProjectGraphAsync } = await import('nx/src/devkit-exports.js')\n const { createPackageJson, createLockFile, getLockFileName } = await import('@nx/js')\n\n const graph = await createProjectGraphAsync({ exitOnError: false })\n const manifest = createPackageJson(options.project, graph, {\n root: options.workspaceRoot,\n isProduction: true,\n })\n manifest.main = entry\n\n if (required === undefined) {\n throw new Error(\n `sentinel build(nest): the bundle was written but never inspected, so the manifest ` +\n `could not be checked against what it requires. Refusing to write one that might ` +\n `not install.`,\n )\n }\n assertManifestCovers(required, manifest, options)\n\n writeFileSync(join(options.outDir, 'package.json'), `${JSON.stringify(manifest, null, 2)}\\n`)\n writeFileSync(\n join(options.outDir, getLockFileName('pnpm')),\n createLockFile(manifest, graph, 'pnpm'),\n )\n },\n }\n}\n\n/**\n * Refuse a bundle that requires something the image will not install.\n *\n * The manifest is derived from the project GRAPH, so it lists what modules declare. The bundle\n * requires what the bundler left external. Those two sets agreeing is an assumption, and it was\n * wrong: `tslib` arrives through `importHelpers` in the workspace tsconfig without any module\n * declaring it, so the manifest omitted it and the service died on its first require.\n *\n * It died only in the image. Locally and in CI the workspace root has the package, so the gap is\n * invisible until a container starts, which is the most expensive place to discover it. Checking\n * here turns that into a build failure naming the package.\n */\nconst assertManifestCovers = (\n required: ReadonlySet<string>,\n manifest: { dependencies?: Record<string, string> },\n options: NodeManifestOptions,\n): void => {\n const declared = new Set(Object.keys(manifest.dependencies ?? {}))\n const provided = options.providedByImage ?? DEFAULT_PROVIDED_BY_IMAGE\n const missing = [...required]\n .filter((name) => !declared.has(name))\n .filter((name) => !provided.some((prefix) => name === prefix || name.startsWith(`${prefix}/`)))\n .sort()\n\n if (missing.length === 0) return\n\n throw new Error(\n `sentinel build(nest): the bundle requires ${missing.length} package(s) the generated ` +\n `manifest does not declare, so the image would not install them: ${missing.join(', ')}. ` +\n `Either declare them in the module's package.json, inline them with ` +\n `\\`ssr.noExternal\\`, or list them in \\`providedByImage\\` if the Dockerfile copies them in.`,\n )\n}\n","/**\n * What `@hublo/sentinel/build/nest` gives an adopted service.\n *\n * The sibling `build/react` entry is a re-export surface: the module keeps its own config and\n * only its import lines move. This one carries a shape as well, because 38 Nest services share\n * one config and have nothing of their own to preserve. See `nest-service.ts` for why the two\n * answers differ, and why that is one rule rather than two.\n *\n * Its own entry point, like the React one, so importing it at build time never drags the CLI\n * and its adapters into a Vite config.\n */\nexport { nestService, type NestServiceOptions } from './nest-service.js'\n\n// The pieces the shape is built from, exported individually so a service that needs something\n// the shape does not give it can compose its own without leaving sentinel.\nexport { decoratorMetadata, type DecoratorMetadataOptions } from './decorator-metadata.js'\nexport { nodeManifest, type NodeManifestOptions } from './node-manifest.js'\nexport { tsconfigAliases, type Alias } from './tsconfig-aliases.js'\n\n// Vite's own, so an adopted config imports everything from one place and the module can drop\n// `vite` from its dependencies.\nexport { defineConfig, loadEnv, mergeConfig } from 'vite'\nexport type { Plugin, PluginOption, UserConfig, UserConfigExport } from 'vite'\n"],"mappings":";;;;;;AA0BA,SAAS,QAAAA,aAAY;AAErB,SAAS,mBAAoC;;;ACN7C,SAAS,QAAQ,YAAY,WAAW,aAAa,gBAAgB;AACrE,SAAS,SAAS,MAAM,UAAU,WAAW;AAsB7C,SAAS,aAAa,MAAsB;AAC1C,MAAI,UAAU;AACd,WAAS,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS;AAChD,UAAM,OAAO,KAAK,KAAK,KAAK;AAC5B,QAAI,SAAS,KAAK;AAChB,UAAI,KAAK,QAAQ,CAAC,MAAM,KAAK;AAE3B,mBAAW,KAAK,QAAQ,CAAC,MAAM,MAAM,aAAa;AAClD,iBAAS,KAAK,QAAQ,CAAC,MAAM,MAAM,IAAI;AAAA,MACzC,OAAO;AACL,mBAAW;AAAA,MACb;AACA;AAAA,IACF;AACA,QAAI,SAAS,KAAK;AAChB,YAAM,QAAQ,KAAK,QAAQ,KAAK,KAAK;AACrC,UAAI,UAAU;AACZ,cAAM,IAAI,MAAM,wDAAwD,IAAI,EAAE;AAChF,YAAM,eAAe,KAAK,MAAM,QAAQ,GAAG,KAAK,EAAE,MAAM,GAAG;AAC3D,iBAAW,MAAM,aAAa,IAAI,CAAC,QAAQ,IAAI,QAAQ,uBAAuB,MAAM,CAAC,EAAE,KAAK,GAAG,CAAC;AAChG,cAAQ;AACR;AAAA,IACF;AACA,eAAW,KAAK,QAAQ,sBAAsB,MAAM;A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,QAAQ;AAAA,QAClB,cAAc,QAAQ;AAAA,MACxB,CAAC;AAAA,MACD,GAAI,QAAQ,QAAQ,SAChB,CAAC,WAAW,EAAE,eAAe,QAAQ,eAAe,QAAQ,QAAQ,QAAQ,OAAO,CAAC,CAAC,IACrF,CAAC;AAAA,MACL,aAAa;AAAA,QACX,SAAS,QAAQ;AAAA,QACjB,eAAe,QAAQ;AAAA,QACvB;AAAA,MACF,CAAC;AAAA,IACH;AAAA,IACA,SAAS,EAAE,OAAO,gBAAgB,QAAQ,aAAa,EAAE;AAAA,IACzD,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOH,YAAY,CAAC,OAAO;AAAA,IACtB;AAAA,IACA,OAAO;AAAA;AAAA;AAAA,MAGL,KAAK;AAAA,MACL;AAAA,MACA,aAAa;AAAA,MACb,WAAW;AAAA,MACX,QAAQ;AAAA;AAAA;AAAA,MAGR,QAAQ;AAAA,MACR,eAAe;AAAA,QACb,QAAQ;AAAA,UACN,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAaR,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA,UAKjB,gBAAgB,CAAC,UAAW,MAAM,mBAAmB,QAAQ,YAAY;AAAA,QAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAQA,WAAW,EAAE,mBAAmB,KAAK;AAAA,MACvC;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,cAAc,CAAC,YAC1B,QAAQ,cAAc,SAClB,WAAW,OAAO,IAClB,YAAY,WAAW,OAAO,GAAG,QAAQ,SAAS;;;AGzIxD,SAAS,cAAc,SAAS,eAAAC,oBAAmB;","names":["join","existsSync","join","join","mergeConfig"]}
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/roles/build/toolchain.ts"],"sourcesContent":["/**\n * The build toolchain, re-exported so an app imports it from sentinel instead of from the\n * workspace root.\n *\n * This is what makes adoption a REFACTOR rather than a rewrite, and it is the whole point.\n * Today `vite`, `@vitejs/plugin-react`, `@tailwindcss/vite`, `vite-plugin-svgr` and `nitro`\n * sit in the monorepo's root `package.json`, which is what stops any front app from being\n * built or moved on its own. An app adopts by changing WHERE its tools come from, and nothing\n * else: every attribute of its config, every alias, every path stays exactly as it was.\n *\n * The alternative was to read the app's config and rebuild it around `reactApp`. That was\n * designed and rejected, correctly: it means understanding a file that is code rather than\n * configuration, and its failure mode is a build that SUCCEEDS and ships the wrong bundle.\n * Here there is nothing to understand, so there is nothing to lose. The two configs are\n * equivalent by construction, because only the import specifiers changed.\n *\n * `reactApp` remains, and stays optional: an app that wants the shared composition adopts it\n * as a second, separate step, with `--inspect --build` to check the result. Nobody has to do\n * that to unblock the root.\n *\n * TanStack is deliberately NOT here. 48 app source files import `@tanstack/react-start`\n * directly, so it is a framework the app codes against rather than a tool that builds it, and\n * the router plugin generates the app's own route tree. Same for `@rolldown/plugin-babel` and\n * `@locator/babel-jsx`, which the apps declare themselves: verified, neither is at the root,\n * so neither is sentinel's to take.\n */\nexport { default as tailwindcss } from '@tailwindcss/vite'\nexport { default as react } from '@vitejs/plugin-react'\nexport { nitro } from 'nitro/vite'\nexport { default as svgr } from 'vite-plugin-svgr'\n\n/**\n * Vite's own API, re-exported for the same reason.\n *\n * `defineConfig`, `loadEnv` and `mergeConfig` are what the configs in this repo import from\n * `vite`; once the root drops the package, those imports are the ones that stop resolving.\n * `mergeConfig` is here because of a file the build role nearly missed: `vitest.config.ts`.\n * Three of them import from `vite` (career and host-admin take `loadEnv`, `libs/front/ui`\n * takes `mergeConfig`), and they are a SECOND door into the same toolchain. Note that\n * `vitest/config` exports a `mergeConfig` of its own, which is vitest's and stays put: the\n * rewriter matches on the specifier, never on the name. The types travel\n * with them, because a config that imports `PluginOption` from a package it no longer declares\n * fails to typecheck even though it builds.\n */\nexport { defineConfig, loadEnv, mergeConfig } from 'vite'\nexport type {\n Plugin,\n PluginOption,\n SassPreprocessorOptions,\n UserConfig,\n UserConfigExport,\n} from 'vite'\n"],"mappings":";AA0BA,SAAoB,WAAXA,gBAA8B;AACvC,SAAoB,WAAXA,gBAAwB;AACjC,SAAS,aAAa;AACtB,SAAoB,WAAXA,gBAAuB;AAehC,SAAS,cAAc,SAAS,mBAAmB;","names":["default"]}