@hublo/sentinel 1.4.0-alpha.3 → 1.4.0-alpha.5
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.
- package/dist/bin/sentinel.js +1 -2
- package/dist/chunk-2XLX6PFR.js.map +1 -0
- package/dist/chunk-3TDUIKVQ.js.map +1 -0
- package/dist/{chunk-SX5CBE3Z.js → chunk-7PUVK4YM.js} +102 -15
- package/dist/chunk-7PUVK4YM.js.map +1 -0
- package/dist/{chunk-MUQWAZQN.js → chunk-ASBZQAXV.js} +90 -34
- package/dist/chunk-CPCUPK4J.js.map +1 -0
- package/dist/chunk-PWV3BMDA.js.map +1 -0
- package/dist/chunk-WLFE5RUU.js.map +1 -0
- package/dist/index.js +1 -2
- package/dist/roles/test/nest/toolchain.d.ts +1 -1
- package/dist/roles/test/nest/toolchain.js +1 -1
- package/dist/roles/test/react/toolchain.d.ts +1 -1
- package/dist/roles/test/react/toolchain.js +1 -1
- package/dist/roles/test/setup/{nest.js → jest-parity.js} +3 -3
- package/dist/roles/test/setup/jest-parity.js.map +1 -0
- package/dist/roles/test/setup/workspace-entry.js.map +1 -1
- package/dist/{shared-test-config-CGxvMlmk.d.ts → roles/test/shared-test-config.d.ts} +5 -1
- package/dist/roles/test/shared-test-config.js +8 -0
- package/dist/roles/test/shared-test-config.js.map +1 -0
- package/docs/test-adoption.md +54 -10
- package/docs/using-sentinel.md +25 -10
- package/package.json +5 -7
- package/dist/roles/test/setup/nest.js.map +0 -1
- /package/dist/roles/test/setup/{nest.d.ts → jest-parity.d.ts} +0 -0
package/dist/bin/sentinel.js
CHANGED
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
registerAdapters,
|
|
17
17
|
resolve,
|
|
18
18
|
resolveBin
|
|
19
|
-
} from "../chunk-
|
|
19
|
+
} from "../chunk-ASBZQAXV.js";
|
|
20
20
|
import {
|
|
21
21
|
WORKSPACE_ROOT_MARKER,
|
|
22
22
|
ensureWorkspacePrep,
|
|
@@ -792,4 +792,3 @@ sentinel: ${asMessage2(error)}
|
|
|
792
792
|
`);
|
|
793
793
|
void exitWithoutTruncating(1);
|
|
794
794
|
});
|
|
795
|
-
//# sourceMappingURL=sentinel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/roles/test/setup/mock-extended.ts"],"sourcesContent":["/**\n * `jest-mock-extended`'s deep mocks, made answerable to the question Vitest's `spyOn` asks.\n *\n * A deep mock is a Proxy that invents a property the first time something READS it. Nothing exists\n * until then, so the object reports itself empty:\n *\n * const provider = mockDeep<InstitutionProvider>()\n * 'getAdminFirstAndLastNames' in provider // false\n * Object.getOwnPropertyDescriptor(provider, 'getAdmin...') // undefined\n * typeof provider.getAdminFirstAndLastNames // 'function', and now it exists\n *\n * jest's `spyOn` reads the property, so the Proxy created it and the spy worked. Vitest's asks the\n * object whether it HAS the property first, gets no for both questions, and throws\n * `The property \"getAdminFirstAndLastNames\" is not defined on the object.` The file then reports no\n * test at all, so its names simply go missing rather than failing.\n *\n * Measured on `apps/cloud/shift`: one such spy took 37 of its 108 tests away. The repo has 128 of\n * them across 29 files, mostly in `apps/nest/microservices` and\n * `apps/nest/backends-for-frontends`.\n *\n * ## Why it is fixed here and not in the 128 test files\n *\n * Because it is a difference between two runners, not something 29 suites each got wrong. A\n * codemod rewriting every site would put a migration artefact in front of every reader of those\n * files forever, and teams would carry it. One adapter keeps the test files exactly as they are.\n *\n * The two traps answer by doing what jest's `spyOn` did: read the property once, then answer. The\n * read is the Proxy's own documented way of materialising it, so nothing here reimplements the\n * mock, it only asks the question in the form the underlying object understands.\n *\n * `then` is never materialised. A deep mock that suddenly HAS a `then` is a thenable, and awaiting\n * it, or returning it from an async function, would hang on a promise nothing resolves.\n */\nimport * as mockExtended from 'vitest-mock-extended'\n\n/**\n * Keys that must stay absent however they are asked for.\n *\n * Not an arbitrary list: every one of them is a PROTOCOL PROBE, a property a framework reads to\n * decide what KIND of value it is holding. A deep mock invents whatever it is asked for, so it\n * answers yes to every probe, and each yes is a lie about what it is.\n *\n * then a thenable. Awaiting the mock, or returning it from an async function,\n * hangs on a promise nothing resolves.\n * asymmetricMatch an asymmetric matcher. Measured: `expect(p).rejects.toThrow(deepMock)`\n * answers `expected error to match asymmetric matcher` instead of comparing\n * against the class, so the assertion stops testing what it says.\n * $$typeof a React element. Serializers branch on it and read fields that are not\n * there.\n * nodeType a DOM node, which testing-library and serializers both branch on.\n *\n * Symbols never reach here: the materialiser returns early for a non-string key, so `Symbol.\n * iterator` and friends are already safe.\n */\nconst NEVER_MATERIALISED = new Set(['then', 'asymmetricMatch', '$$typeof', 'nodeType'])\n\nfunction materialise(target: object, key: PropertyKey): void {\n if (typeof key !== 'string' || NEVER_MATERIALISED.has(key)) return\n // The read IS the creation: that is how the deep mock's own Proxy works.\n void (target as Record<string, unknown>)[key]\n}\n\n/**\n * Wrap a deep mock so that `in` and `getOwnPropertyDescriptor` see what a read would create.\n *\n * Only the object handed back is wrapped, not what it returns: a nested spy would need its own\n * wrapper, and the corpus has none. Wrapping every read would also mean a new wrapper per access\n * unless they were cached, and an identity that changes between two reads is a worse bug than the\n * one being fixed.\n */\n/**\n * One proxy per underlying mock, so identity is stable.\n *\n * A suite holds on to `db.timeSlot` and compares it later, or passes it to `toHaveBeenCalledWith`.\n * Handing back a fresh proxy on every read would make the same mock unequal to itself.\n */\nconst wrappers = new WeakMap<object, object>()\n\nfunction answeringProxy<T extends object>(mock: T): T {\n return new Proxy(mock, {\n /*\n * A NESTED mock has to answer the same questions as the top-level one.\n *\n * The adapter used to wrap only what `mockDeep()` returned, and the level below it was a raw\n * mock again. Measured: `'deleteMany' in db.timeSlot` answered false and its descriptor was\n * absent, so `vi.spyOn(db.timeSlot, 'deleteMany')` failed with\n * `The property \"deleteMany\" is not defined on the function` — the exact error\n * `apps/nest/microservices/hublo-pool` reports, and the exact failure this adapter was written\n * to remove, one level down.\n *\n * Read from the TARGET, never with this proxy as the receiver: forwarding the receiver changes\n * what the deep mock hands back.\n */\n get(target, key) {\n if (typeof key === 'string' && NEVER_MATERIALISED.has(key)) return undefined\n\n const value = Reflect.get(target, key) as unknown\n if (value === null) return value\n if (typeof value !== 'object' && typeof value !== 'function') return value\n\n /*\n * A Proxy invariant, not a preference: for a property that is non-configurable AND\n * non-writable, `get` MUST hand back the target's own value. Wrapping one throws\n * `'get' on proxy: property 'mock' is a read-only and non-configurable data property on the\n * proxy target but the proxy did not return its actual value`, which is what a mock's own\n * `mock` record is.\n */\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key)\n if (\n descriptor !== undefined &&\n descriptor.configurable === false &&\n descriptor.writable === false\n ) {\n return value\n }\n\n const existing = wrappers.get(value as object)\n if (existing !== undefined) return existing\n\n const wrapper = answeringProxy(value as object)\n wrappers.set(value as object, wrapper)\n return wrapper\n },\n has(target, key) {\n if (Reflect.has(target, key)) return true\n materialise(target, key)\n return Reflect.has(target, key)\n },\n getOwnPropertyDescriptor(target, key) {\n const existing = Reflect.getOwnPropertyDescriptor(target, key)\n if (existing !== undefined) return existing\n materialise(target, key)\n return Reflect.getOwnPropertyDescriptor(target, key)\n },\n })\n}\n\n/*\n * Everything the fork exports, so a module importing `jest-mock-extended` still gets `mockReset`,\n * `mockClear`, `anyString`, the matchers and the types. The two names below are declared after it:\n * an explicit export wins over a star export, which is what lets this file override exactly two\n * functions and pass the rest through untouched.\n */\nexport * from 'vitest-mock-extended'\n\n/*\n * And the same names again, one by one.\n *\n * `export *` from a CJS package forwards only what a static read of that package can SEE.\n * `vitest-mock-extended` ships CommonJS and assembles part of its exports at runtime, so the star\n * carries the types and loses several of the functions. A spec importing one of them then reads\n * `undefined` and dies at the call, naming the binding and nothing else. Measured on\n * `apps/nest/microservices/mission`:\n *\n * TypeError: (0 , __vite_ssr_import_3__.mockReset) is not a function\n *\n * It is the same shape as the automock namespace built from a static export list, which\n * `server.deps.inline` exists to answer; here the file doing the re-export is ours, so it can\n * simply say the names out loud. A name that ever disappears from the fork breaks the build\n * instead of a suite, which is the better end of that trade.\n */\nexport {\n any,\n anyArray,\n anyBoolean,\n anyFunction,\n anyMap,\n anyNumber,\n anyObject,\n anySet,\n anyString,\n anySymbol,\n arrayIncludes,\n calledWithFn,\n captor,\n isA,\n isMockObject,\n mapHas,\n matches,\n mockClear,\n mocked,\n mockedFn,\n mockFn,\n mockReset,\n notEmpty,\n notNull,\n notUndefined,\n objectContainsKey,\n} from 'vitest-mock-extended'\n\n/**\n * Every deep mock handed out, so `vi.resetAllMocks()` can reach them.\n *\n * ⚠️ Kept on `globalThis`, and that is not laziness. This file is reached by TWO specifiers: the\n * setup imports it by its path, and a spec imports `jest-mock-extended`, which the preset aliases\n * here. Vite resolves those to two ids and instantiates the module twice, so a registry held in\n * module scope would be filled by one instance and read by the other, and the reset would find\n * nothing. It is the same dual-identity trap the axios alias exists to close, one layer up.\n *\n * ⚠️ It does not reach them on its own, and that is a silent divergence. jest's\n * `jest.resetAllMocks()` reset these because `jest-mock-extended` built them with `jest.fn()`, so\n * they sat in jest's own registry. `vitest-mock-extended` builds them its own way, so\n * `vi.resetAllMocks()` walks past them and their call history survives into the next test.\n *\n * Measured on `apps/nest/microservices/activity`, whose suite does exactly what jest expected:\n *\n * beforeEach(() => mocked.findEvents.mockResolvedValue([]))\n * afterEach(() => vi.resetAllMocks())\n *\n * Eleven tests asserting `toHaveBeenCalledTimes(0)` saw the call left by the test before them.\n * Each one PASSES on its own and fails right after its neighbour, which is the signature of\n * leakage rather than of a broken assertion.\n *\n * A plain Set: a test file gets its own module instance, so the registry lives and dies with it.\n */\nconst REGISTRY = Symbol.for('@hublo/sentinel/deep-mocks')\nconst handedOut: Set<object> = ((globalThis as Record<symbol, unknown>)[REGISTRY] ??=\n new Set<object>()) as Set<object>\n\n/** Reset every deep mock this adapter created, the way jest's registry did. */\nexport function resetDeepMocks(): void {\n for (const created of handedOut) mockExtended.mockReset(created as never)\n}\n\n/** Clear their calls without touching their implementations. */\nexport function clearDeepMocks(): void {\n for (const created of handedOut) mockExtended.mockClear(created as never)\n}\n\nexport const mock = ((...args: unknown[]) => {\n const created = (mockExtended.mock as (...rest: unknown[]) => object)(...args)\n handedOut.add(created)\n return answeringProxy(created)\n}) as unknown as typeof mockExtended.mock\n\nexport const mockDeep = ((...args: unknown[]) => {\n const created = (mockExtended.mockDeep as (...rest: unknown[]) => object)(...args)\n handedOut.add(created)\n return answeringProxy(created)\n}) as unknown as typeof mockExtended.mockDeep\n"],"mappings":";AAiCA,YAAY,kBAAkB;AA8G9B,cAAc;AAkBd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,aAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAtIP,IAAM,qBAAqB,oBAAI,IAAI,CAAC,QAAQ,mBAAmB,YAAY,UAAU,CAAC;AAEtF,SAAS,YAAY,QAAgB,KAAwB;AAC3D,MAAI,OAAO,QAAQ,YAAY,mBAAmB,IAAI,GAAG,EAAG;AAE5D,OAAM,OAAmC,GAAG;AAC9C;AAgBA,IAAM,WAAW,oBAAI,QAAwB;AAE7C,SAAS,eAAiCC,OAAY;AACpD,SAAO,IAAI,MAAMA,OAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAcrB,IAAI,QAAQ,KAAK;AACf,UAAI,OAAO,QAAQ,YAAY,mBAAmB,IAAI,GAAG,EAAG,QAAO;AAEnE,YAAM,QAAQ,QAAQ,IAAI,QAAQ,GAAG;AACrC,UAAI,UAAU,KAAM,QAAO;AAC3B,UAAI,OAAO,UAAU,YAAY,OAAO,UAAU,WAAY,QA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sources":["../src/roles/build/nest/decorator-metadata.ts","../src/roles/build/nest/tsconfig-aliases.ts"],"sourcesContent":["/**\n * Decorator metadata, which esbuild cannot emit and Nest cannot live without, plus the TypeScript\n * transformers a service declared on its webpack target.\n *\n * Vite's default transformer is esbuild, and esbuild does not implement `emitDecoratorMetadata`.\n * Nest resolves a constructor's parameters from exactly that metadata, so without it the DI\n * container comes up empty and the application fails on its first module. Measured in the\n * monorepo this ships to: `emitDecoratorMetadata: true` in `tsconfig.base.json`, and 7365 files\n * carrying `@Injectable`, `@Module` or `@Controller`.\n *\n * ## TWO modes, chosen exactly as nx chooses them\n *\n * This is the one decision in this file that is not ours, and trying to make it ours cost a day.\n *\n * `@nx/webpack` configures ts-loader with one line:\n *\n * transpileOnly: !hasPlugin // hasPlugin = this target declares `transformers`\n *\n * So webpack already had two behaviours. A service with no transformers compiled with\n * `transpileOnly`, which is `ts.transpileModule` semantics: no type checker, one file at a time.\n * A service WITH transformers compiled through a full `ts.Program`, because that is the only way\n * a TypeScript transformer can run at all.\n *\n * The difference is visible, and measured. On a property typed by an imported string enum:\n *\n * Program : __metadata(\"design:type\", String)\n * transpileModule : __metadata(\"design:type\", typeof (_a = ...) === \"function\" ? _a : Object)\n *\n * and on a `@Body()` whose DTO arrives through `import type`, a Program emits `Function` where\n * transpileOnly emits `Object`, which `@nestjs/swagger` turns into four `$ref: Function` request\n * bodies that the published contract does not have.\n *\n * This plugin used only the first mode and this file claimed it was \"the serializer ts-loader was\n * already using\". Half true, and the wrong half: it is what ts-loader uses for the 29 services\n * with no transformers, and those came back byte-identical. Then a Program was used for ALL of\n * them, which fixed the eight and moved the contract of `network`, which had been correct.\n *\n * Both were the same mistake: choosing one mode for everyone, when the tool being replaced chose\n * per service. So the condition is copied rather than invented, and there is no third case to\n * discover: nx has two, and both are reproduced here.\n *\n * The Program costs about six seconds more on the largest service (1419 files: ~1.9s to build it,\n * ~3.3ms per file against ~0.9ms). Only the services that declare a transformer pay it, which is\n * also what webpack did.\n *\n * ## The transformers, which are configuration and are read, never invented\n *\n * Eight services and BFFs declare `@nestjs/swagger/plugin` on their webpack target, with\n * `introspectComments` and `classValidatorShim`. It writes the `@ApiProperty` decorators a\n * developer would otherwise write by hand, turns JSDoc into descriptions, and projects\n * class-validator rules into the schema.\n *\n * Dropping it does not fail a build. Measured on `institution` by regenerating its committed\n * contract after a sentinel build: 385 insertions and 1378 deletions. Response schemas and every\n * `minItems`, `minimum`, `maximum`, `minLength` and `format` disappeared, silently.\n *\n * So `--init` reads the declaration off the webpack target and writes it into the generated Vite\n * config, and this plugin loads it. Nothing here decides which transformers a service runs.\n *\n * ## Why the MODULE's compiler now, and not sentinel's own\n *\n * This plugin used to pin sentinel's TypeScript, on the grounds that `typescript` in the consumer\n * could resolve to the 7.x native port, which exports a version and no compiler API. Measured\n * from a service today it resolves to `@typescript/typescript6` 6.0.2, with the full API.\n *\n * The pin cannot survive the transformers anyway: a plugin loaded from the module's\n * `node_modules` imports the module's TypeScript, and a transformer built against one compiler\n * cannot be handed a Program built by another. One compiler, the module's, is also what ts-loader\n * used, so it is the faithful answer rather than merely the workable one. The API is asserted at\n * `buildStart`, where a failure is reported.\n *\n * ## Why the module's own tsconfig, and not options chosen here\n *\n * Emit follows compiler options, so options invented here would be a second, silent source of\n * divergence from what ts-loader produced. `target` alone decides how classes and fields are\n * downlevelled: this workspace is on `es2021`, where `useDefineForClassFields` defaults to false\n * and a declared-but-unassigned DTO field is therefore NOT emitted. Defaulting to `es2022` here\n * would flip that, `Object.defineProperty` would write `undefined` over every field, and\n * `class-transformer` payloads would arrive empty at runtime with nothing in the build to explain\n * it.\n *\n * So the config is read, `extends` resolved by the compiler itself, and only what this plugin\n * genuinely owns is overridden.\n *\n * ## Still no type CHECKING, which is a different thing from having types\n *\n * The Program gives this plugin a type checker; it does not use it to report errors. Every Nest\n * project already runs `tsc -b` in its own `typecheck` target, and the build never was the thing\n * that type-checked. Emitting with type information and refusing to type-check are independent,\n * and only the first is needed to reproduce what ts-loader wrote.\n */\nimport { existsSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\n\nimport type TS from 'typescript'\nimport type { Plugin } from 'vite'\n\n/** Files this transform owns: TypeScript sources, never a dependency's compiled output. */\nconst TYPESCRIPT_SOURCE = /\\.ts$/\n\n/**\n * Where a Nest service keeps the config it builds with, most specific first.\n *\n * `tsconfig.app.json` is the one Nx generates for the application's own sources and the one\n * ts-loader was pointed at; `tsconfig.json` is the fallback for a service that never split them.\n * Measured on `main`: all 37 services still on webpack name `tsconfig.app.json`.\n */\nconst TSCONFIG_CANDIDATES = ['tsconfig.app.json', 'tsconfig.json']\n\n/** A TypeScript transformer a service runs at build time, as its build target declares it. */\nexport interface TransformerDeclaration {\n /** The package to load it from, e.g. `@nestjs/swagger/plugin`. */\n name: string\n /** Passed to the transformer's own factory, unread here. */\n options?: Record<string, unknown>\n}\n\nexport interface DecoratorMetadataOptions {\n /** The module being built. Its tsconfig is the one whose emit must be preserved. */\n root: string\n /**\n * An explicit tsconfig, when the service does not use either conventional name.\n *\n * Relative paths resolve against `root`.\n */\n tsconfig?: string\n /** The transformers this service declared, translated from its webpack target. */\n transformers?: readonly TransformerDeclaration[]\n}\n\n/**\n * The module's own TypeScript, with its emit API asserted.\n *\n * Resolved from `root` rather than from here, because a transformer loaded from the module binds\n * to the compiler the module resolves, and Programs are not interchangeable between compilers.\n */\nfunction loadCompiler(root: string): typeof TS {\n const require = createRequire(path.join(root, 'noop.js'))\n let compiler: typeof TS\n try {\n compiler = require('typescript') as typeof TS\n } catch {\n throw new Error(\n `sentinel build(nest): no \\`typescript\\` resolvable from ${root}. The build emits decorator ` +\n `metadata with the module's own compiler, so one has to be installed there.`,\n )\n }\n if (typeof compiler.createProgram !== 'function') {\n throw new Error(\n `sentinel build(nest): the typescript resolved from ${root} (${compiler.version ?? 'unknown'}) ` +\n `has no createProgram API. TypeScript 7 is the native port and exposes none; the emit API ` +\n `lives under @typescript/typescript6. Point this module's \\`typescript\\` at a compiler ` +\n `with an emit API, which is the one its \\`typecheck\\` target already uses.`,\n )\n }\n return compiler\n}\n\nfunction resolveTsconfig(options: DecoratorMetadataOptions): string {\n if (options.tsconfig) {\n const explicit = path.resolve(options.root, options.tsconfig)\n if (!existsSync(explicit)) {\n throw new Error(`sentinel build(nest): tsconfig not found at ${explicit}`)\n }\n return explicit\n }\n for (const candidate of TSCONFIG_CANDIDATES) {\n const found = path.join(options.root, candidate)\n if (existsSync(found)) return found\n }\n throw new Error(\n `sentinel build(nest): no ${TSCONFIG_CANDIDATES.join(' or ')} in ${options.root}. ` +\n `Pass \\`tsconfig\\` if this service keeps it elsewhere.`,\n )\n}\n\n/** The module's compiler options, with `extends` already resolved, plus what this plugin owns. */\nfunction readConfig(\n ts: typeof TS,\n options: DecoratorMetadataOptions,\n): { fileNames: string[]; compilerOptions: TS.CompilerOptions } {\n const configPath = resolveTsconfig(options)\n const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, {\n ...ts.sys,\n onUnRecoverableConfigFileDiagnostic: (diagnostic) => {\n throw new Error(\n `sentinel build(nest): could not read ${configPath}: ` +\n ts.flattenDiagnosticMessageText(diagnostic.messageText, ' '),\n )\n },\n } as TS.ParseConfigFileHost)\n\n return {\n fileNames: parsed?.fileNames ?? [],\n compilerOptions: {\n ...parsed?.options,\n // ESM out, so Rollup sees imports and exports rather than an opaque `require` it cannot\n // follow. The service still SHIPS as CJS: that conversion is the bundler's, further down.\n module: ts.ModuleKind.ESNext,\n // Vite consumes the map; the tsconfig's own answer is about a different pipeline.\n sourceMap: true,\n inlineSourceMap: false,\n inlineSources: false,\n // Types are another target's job, and emitting them here would write into the source tree.\n declaration: false,\n declarationMap: false,\n emitDeclarationOnly: false,\n noEmit: false,\n // `composite` projects refuse to emit without a `tsBuildInfoFile`, and there is no\n // incremental build here to inform.\n composite: false,\n incremental: false,\n },\n }\n}\n\n/**\n * The declared transformers, loaded from the MODULE so each binds to the compiler it expects.\n *\n * A name that cannot be loaded, or a package that exports no `before`, fails the build here\n * rather than producing a bundle quietly missing what the transformer contributes. That failure\n * mode is the reason this exists: dropping `@nestjs/swagger/plugin` costs a service most of its\n * published contract and nothing in the build says so.\n */\nfunction loadTransformers(\n root: string,\n program: TS.Program,\n declared: readonly TransformerDeclaration[],\n): TS.TransformerFactory<TS.SourceFile>[] {\n const require = createRequire(path.join(root, 'noop.js'))\n return declared.map(({ name, options }) => {\n let loaded: { before?: unknown }\n try {\n loaded = require(name) as { before?: unknown }\n } catch (error) {\n throw new Error(\n `sentinel build(nest): the build target declares the transformer \\`${name}\\`, which ` +\n `cannot be loaded from ${root}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n )\n }\n if (typeof loaded.before !== 'function') {\n throw new Error(\n `sentinel build(nest): \\`${name}\\` exports no \\`before\\` factory, so it cannot run as a ` +\n `TypeScript transformer. Building without it would drop whatever it contributes.`,\n )\n }\n const factory = loaded.before as (\n options: Record<string, unknown> | undefined,\n program: TS.Program,\n ) => TS.TransformerFactory<TS.SourceFile>\n return factory(options, program)\n })\n}\n\nexport const decoratorMetadata = (options: DecoratorMetadataOptions): Plugin => {\n /*\n * Everything is prepared in `buildStart`, and that placement is the whole point.\n *\n * It used to be resolved lazily inside `transform`, on the reasoning that an error belongs to\n * the build rather than to importing the preset. Half right: it belongs to the build, but\n * Rollup SWALLOWS a throwing `transform` hook. The wrong compiler, an unreadable tsconfig and a\n * missing one all produced the same symptom instead of their own message: \"1 modules\n * transformed\", nothing written, then an unrelated error from whichever later hook tripped over\n * the empty output directory. It cost two diagnoses to recognise.\n *\n * `buildStart` is reported. So the compiler is loaded, the config read, the Program built and\n * the transformers resolved exactly once, before a single file is transformed, where failing\n * says what failed.\n */\n /** `hasPlugin` in nx's own words: this service declares transformers, so it needs a Program. */\n const typeAware = (options.transformers ?? []).length > 0\n\n let ts: typeof TS | undefined\n let program: TS.Program | undefined\n let compilerOptions: TS.CompilerOptions | undefined\n let before: TS.TransformerFactory<TS.SourceFile>[] = []\n /** Files emitted without the Program, which is a fidelity gap and is reported, never silent. */\n const withoutTypes: string[] = []\n\n return {\n name: 'sentinel:decorator-metadata',\n // Before Vite's own transform, so esbuild never sees the decorators it cannot handle, and so\n // the source this plugin reads from the Program is still the source on disk.\n enforce: 'pre',\n buildStart() {\n ts = loadCompiler(options.root)\n const config = readConfig(ts, options)\n compilerOptions = config.compilerOptions\n // Built only in the type-aware mode. It costs ~1.9s on the largest service here and buys\n // nothing a service without transformers can use, which is why nx does not build one either.\n if (!typeAware) return\n program = ts.createProgram(config.fileNames, config.compilerOptions)\n before = loadTransformers(options.root, program, options.transformers ?? [])\n },\n transform(code, id) {\n if (!TYPESCRIPT_SOURCE.test(id) || id.includes('node_modules')) return null\n // Only reachable if `buildStart` did not run, which no Rollup build does. Named rather than\n // defaulted, so it cannot silently emit with TypeScript's defaults instead of the module's.\n if (ts === undefined || compilerOptions === undefined) {\n throw new Error(\n `sentinel build(nest): the compiler was never prepared, so ${id} would be emitted with ` +\n `defaults rather than this module's tsconfig.`,\n )\n }\n\n /*\n * The Program's own SourceFile, which is what carries the type information.\n *\n * Three cases emit without it. The service declares no transformer, which is `transpileOnly`\n * and is what ts-loader did for it. A file the Program never reached, because nothing\n * imports it from the entry. And a file another plugin has already rewritten, where the\n * Program's copy is no longer the truth: emitting that stale copy over someone else's\n * transform would be the worse failure.\n *\n * The last two are counted and reported at the end. The first is not a gap, it is the mode.\n *\n * Measured on the largest service here: neither of the last two fires, on any of its 5594\n * files. That is the point of reporting them rather than tolerating them quietly — a warning\n * from this build means something genuinely new, not a known rough edge.\n */\n const sourceFile = program?.getSourceFile(id)\n if (program === undefined || sourceFile === undefined || sourceFile.text !== code) {\n if (typeAware) withoutTypes.push(id)\n const output = ts.transpileModule(code, { fileName: id, compilerOptions })\n return { code: output.outputText, map: output.sourceMapText ?? null }\n }\n\n let emitted: string | undefined\n let map: string | undefined\n program.emit(\n sourceFile,\n (fileName, text) => {\n if (fileName.endsWith('.map')) map = text\n else emitted = text\n },\n undefined,\n false,\n { before },\n )\n if (emitted === undefined) {\n throw new Error(`sentinel build(nest): TypeScript emitted nothing for ${id}.`)\n }\n return { code: emitted, map: map ?? null }\n },\n closeBundle() {\n if (withoutTypes.length === 0) return\n const shown = withoutTypes.slice(0, 5).map((file) => path.relative(options.root, file))\n this.warn(\n `sentinel build(nest): ${withoutTypes.length} file(s) were emitted without type ` +\n `information, so their decorator metadata may differ from what ts-loader produced ` +\n `(${shown.join(', ')}${withoutTypes.length > shown.length ? ', …' : ''}). They are ` +\n `outside this module's tsconfig, or another plugin rewrote them first.`,\n )\n },\n }\n}\n","/**\n * The workspace's `paths` mappings, as Vite resolve aliases.\n *\n * They matter more than they look. The mappings point at SOURCE files, and that is what makes\n * a workspace library get BUNDLED rather than externalised: Vite treats anything outside\n * `node_modules` as source. Drop them and every `@hublo/nest/*` import becomes an external the\n * runtime cannot resolve, because those packages are never published.\n *\n * This reproduces what webpack did through `tsconfig-paths-webpack-plugin`, alongside\n * `webpack-node-externals` which only ever externalised real packages. Measured on the first\n * migrated service: 45 externals under Vite against 47 under webpack, and nothing externalised\n * by Vite that webpack did not.\n */\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport interface Alias {\n find: RegExp\n replacement: string\n}\n\n/** `tsconfig.base.json` carries `//` comments, which `JSON.parse` refuses. */\nconst stripLineComments = (json: string): string => json.replace(/^\\s*\\/\\/.*$/gm, '')\n\nconst toAlias = (workspaceRoot: string, pattern: string, target: string): Alias => {\n const escaped = pattern.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\\\\\*/g, '(.*)')\n return {\n find: new RegExp(`^${escaped}$`),\n replacement: join(workspaceRoot, target.replace(/\\*/g, '$1')),\n }\n}\n\n/**\n * Read the mappings from the workspace's base tsconfig.\n *\n * Longest pattern first, because Vite takes the first alias that matches and the mappings\n * overlap by design: `@front/theme/node` must not be swallowed by `@front/theme`.\n */\nexport const tsconfigAliases = (workspaceRoot: string, file = 'tsconfig.base.json'): Alias[] => {\n const raw = readFileSync(join(workspaceRoot, file), 'utf8')\n const { compilerOptions } = JSON.parse(stripLineComments(raw)) as {\n compilerOptions?: { paths?: Record<string, string[]> }\n }\n return Object.entries(compilerOptions?.paths ?? {})\n .flatMap(([pattern, targets]) => {\n const [target] = targets\n return target === undefined ? [] : [toAlias(workspaceRoot, pattern, target)]\n })\n .sort((a, b) => b.find.source.length - a.find.source.length)\n}\n"],"mappings":";AA2FA,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,OAAO,UAAU;AAMjB,IAAM,oBAAoB;AAS1B,IAAM,sBAAsB,CAAC,qBAAqB,eAAe;AA6BjE,SAAS,aAAa,MAAyB;AAC7C,QAAMA,WAAU,cAAc,KAAK,KAAK,MAAM,SAAS,CAAC;AACxD,MAAI;AACJ,MAAI;AACF,eAAWA,SAAQ,YAAY;AAAA,EACjC,QAAQ;AACN,UAAM,IAAI;AAAA,MACR,2DAA2D,IAAI;AAAA,IAEjE;AAAA,EACF;AACA,MAAI,OAAO,SAAS,kBAAkB,YAAY;AAChD,UAAM,IAAI;AAAA,MACR,sDAAsD,IAAI,KAAK,SAAS,WAAW,SAAS;AAAA,IAI9F;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,gBAAgB,SAA2C;AAClE,MAAI,QAAQ,UAAU;AACpB,UAAM,WAAW,KAAK,QAAQ,QAAQ,MAAM,QAAQ,QAAQ;AAC5D,QAAI,CAAC,WAAW,QAAQ,GAAG;AACzB,YAAM,IAAI,MAAM,+CAA+C,QAAQ,EAAE;AAAA,IAC3E;AACA,WAAO;AAAA,EACT;AACA,aAAW,aAAa,qBAAqB;AAC3C,UAAM,QAAQ,KAAK,KAAK,QAAQ,MAAM,SAAS;AAC/C,QAAI,WAAW,KAAK,EAAG,QAAO;AAAA,EAChC;AACA,QAAM,IAAI;AAAA,IACR,4BAA4B,oBAAoB,KAAK,MAAM,CAAC,OAAO,QAAQ,IAAI;AAAA,EAEjF;AACF;AAGA,SAA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-3,6 +3,12 @@ import {
|
|
|
3
3
|
tsconfigAliases
|
|
4
4
|
} from "./chunk-3TDUIKVQ.js";
|
|
5
5
|
|
|
6
|
+
// src/roles/test/shared-test-config.ts
|
|
7
|
+
import { existsSync } from "fs";
|
|
8
|
+
import { createRequire } from "module";
|
|
9
|
+
import { dirname, join } from "path";
|
|
10
|
+
import { fileURLToPath } from "url";
|
|
11
|
+
|
|
6
12
|
// src/roles/test/react/jest-export-conditions.ts
|
|
7
13
|
var ABSENT_UNDER_JEST = /* @__PURE__ */ new Set(["development", "development|production"]);
|
|
8
14
|
function stripInPlace(conditions) {
|
|
@@ -25,17 +31,21 @@ function jestExportConditions() {
|
|
|
25
31
|
}
|
|
26
32
|
|
|
27
33
|
// src/roles/test/shared-test-config.ts
|
|
28
|
-
import { existsSync } from "fs";
|
|
29
|
-
import { createRequire } from "module";
|
|
30
|
-
import { dirname, join } from "path";
|
|
31
|
-
import { fileURLToPath } from "url";
|
|
32
34
|
function siblingFile(relative) {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
35
|
+
const candidates = [
|
|
36
|
+
relative,
|
|
37
|
+
`roles/test/${relative.replace(/^\.\//, "")}`,
|
|
38
|
+
`../${relative.replace(/^\.\//, "")}`
|
|
39
|
+
];
|
|
40
|
+
for (const candidate of candidates) {
|
|
41
|
+
try {
|
|
42
|
+
const sibling = fileURLToPath(new URL(candidate, import.meta.url));
|
|
43
|
+
if (existsSync(sibling)) return sibling;
|
|
44
|
+
} catch {
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
38
47
|
}
|
|
48
|
+
return void 0;
|
|
39
49
|
}
|
|
40
50
|
function resolveFrom(specifier) {
|
|
41
51
|
try {
|
|
@@ -49,7 +59,7 @@ function resolveFrom(specifier) {
|
|
|
49
59
|
}
|
|
50
60
|
}
|
|
51
61
|
function mockExtendedAdapterPath() {
|
|
52
|
-
return siblingFile("
|
|
62
|
+
return siblingFile("./setup/mock-extended.js");
|
|
53
63
|
}
|
|
54
64
|
function vitestMockExtendedPath() {
|
|
55
65
|
try {
|
|
@@ -63,7 +73,7 @@ function vitestMockExtendedPath() {
|
|
|
63
73
|
}
|
|
64
74
|
}
|
|
65
75
|
function mswAliases() {
|
|
66
|
-
const server = siblingFile("
|
|
76
|
+
const server = siblingFile("./setup/msw-server.js");
|
|
67
77
|
const own = resolveFrom("msw");
|
|
68
78
|
return [
|
|
69
79
|
...own === void 0 ? [] : [{ find: /^msw$/, replacement: own }],
|
|
@@ -271,7 +281,36 @@ function baseConfig(options) {
|
|
|
271
281
|
* A module that declared its own concurrency overrides this, in both environments, exactly as
|
|
272
282
|
* it does today.
|
|
273
283
|
*/
|
|
274
|
-
fileParallelism: !process.env.CI
|
|
284
|
+
fileParallelism: !process.env.CI,
|
|
285
|
+
/*
|
|
286
|
+
* ⚠️ Sentinel's own setup files go through VITE, not round it, and that is load-bearing.
|
|
287
|
+
*
|
|
288
|
+
* Vitest externalizes anything under `node_modules`, so an installed `@hublo/sentinel` is
|
|
289
|
+
* loaded by Node while the module's own code is served by Vite. The two then hold DIFFERENT
|
|
290
|
+
* instances of the same package, and a setup whose whole job is to mutate per-copy state
|
|
291
|
+
* mutates a copy nobody reads.
|
|
292
|
+
*
|
|
293
|
+
* Measured on `apps/nest/microservices/agency`, with the published 1.4.0-alpha.4:
|
|
294
|
+
*
|
|
295
|
+
* zone of the copy sentinel pinned UTC
|
|
296
|
+
* zone of the copy the test imports Europe/Paris
|
|
297
|
+
* same object false
|
|
298
|
+
*
|
|
299
|
+
* Six tests that passed under jest failed, all comparing `DateTime.now().toISO()` against a
|
|
300
|
+
* date the provider had serialised: identical instants, one rendered `+02:00` and the other
|
|
301
|
+
* `Z`. The root jest setup pinned `Settings.defaultZone = 'utc'` and 97 modules named it, so
|
|
302
|
+
* this is not one module's edge case.
|
|
303
|
+
*
|
|
304
|
+
* ⚠️ It hid for a whole campaign because the harness SYMLINKS sentinel to its source tree.
|
|
305
|
+
* The resolved path then holds no `node_modules`, Vitest inlines it, and the pin lands on the
|
|
306
|
+
* right copy: 96 modules reported IDENTIQUE while the real install was red. An instrument
|
|
307
|
+
* that installs the package differently from a team does not measure what a team will see.
|
|
308
|
+
*
|
|
309
|
+
* The narrow form `/@hublo\/sentinel\/dist\/roles\//` was tried and does NOT work: the pin
|
|
310
|
+
* itself lives in a shared chunk at the dist root, which stays external. It has to be the
|
|
311
|
+
* whole package.
|
|
312
|
+
*/
|
|
313
|
+
server: { deps: { inline: [/@hublo\/sentinel/] } }
|
|
275
314
|
}
|
|
276
315
|
};
|
|
277
316
|
}
|
|
@@ -293,18 +332,66 @@ function sharedTestConfig(options) {
|
|
|
293
332
|
resolve: {
|
|
294
333
|
...base.resolve,
|
|
295
334
|
...options.overrides.resolve,
|
|
296
|
-
|
|
335
|
+
/*
|
|
336
|
+
* The module's own aliases come after sentinel's, and in a Vite alias ARRAY the FIRST match
|
|
337
|
+
* wins. So sentinel's win, which is the opposite of what this comment used to claim.
|
|
338
|
+
*
|
|
339
|
+
* ⚠️ The order is corrected here rather than in the code, because changing it would flip a
|
|
340
|
+
* behaviour that nothing exercises. Every alias sentinel adds is ANCHORED to one exact
|
|
341
|
+
* specifier: `^axios$`, `^luxon$`, `^msw$`, `^jest-mock-extended$` and
|
|
342
|
+
* `^@prisma/<x>/runtime/library$`. A module's own entry collides only by naming the identical
|
|
343
|
+
* string, and measured across every `jest.config*` in the repo, none does: the closest are
|
|
344
|
+
* `@front/type/axios` and `@front/api/msw-handlers` in `front-legacy`, different specifiers
|
|
345
|
+
* in the one module this role refuses anyway.
|
|
346
|
+
*
|
|
347
|
+
* So today the order decides nothing, and all 97 migrations were measured with it this way
|
|
348
|
+
* round. Reversing it on a hypothesis would be a silent behaviour change bought with nothing.
|
|
349
|
+
* What was actually wrong was a comment promising a module it could win, which a reader would
|
|
350
|
+
* have relied on.
|
|
351
|
+
*/
|
|
297
352
|
alias: [
|
|
298
353
|
...asAliasArray(base.resolve?.alias),
|
|
299
354
|
...asAliasArray(options.overrides.resolve?.alias)
|
|
300
355
|
]
|
|
301
356
|
},
|
|
302
|
-
test: {
|
|
357
|
+
test: {
|
|
358
|
+
...base.test,
|
|
359
|
+
...options.overrides.test,
|
|
360
|
+
/*
|
|
361
|
+
* ⚠️ `server.deps.inline` is the one key inside `test` that must not be REPLACED.
|
|
362
|
+
*
|
|
363
|
+
* The shallow spread above is right for everything else: a module overriding `environment`
|
|
364
|
+
* or `testTimeout` means to replace it. But the base uses this list to put sentinel's own
|
|
365
|
+
* setup inside Vite's graph, and a module declares its own entries there for its workspace
|
|
366
|
+
* packages. Dropping either half breaks something silently, and the halves have nothing to
|
|
367
|
+
* do with each other, so they are concatenated.
|
|
368
|
+
*
|
|
369
|
+
* Measured on `libs/front/api`, which declares `['@front/runtime-config', '@segment/snippet']`
|
|
370
|
+
* and would otherwise have discarded the base's entry and lost the timezone pin with it.
|
|
371
|
+
*/
|
|
372
|
+
server: mergeServerDeps(base.test?.server, options.overrides.test?.server)
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
function mergeServerDeps(base, override) {
|
|
377
|
+
if (base === void 0) return override;
|
|
378
|
+
if (override === void 0) return base;
|
|
379
|
+
const inline = [
|
|
380
|
+
...asInlineArray(base.deps?.inline) ?? [],
|
|
381
|
+
...asInlineArray(override.deps?.inline) ?? []
|
|
382
|
+
];
|
|
383
|
+
return {
|
|
384
|
+
...base,
|
|
385
|
+
...override,
|
|
386
|
+
deps: { ...base.deps, ...override.deps, ...inline.length > 0 ? { inline } : {} }
|
|
303
387
|
};
|
|
304
388
|
}
|
|
389
|
+
function asInlineArray(inline) {
|
|
390
|
+
return Array.isArray(inline) ? inline : void 0;
|
|
391
|
+
}
|
|
305
392
|
|
|
306
393
|
export {
|
|
307
394
|
jestExportConditions,
|
|
308
395
|
sharedTestConfig
|
|
309
396
|
};
|
|
310
|
-
//# sourceMappingURL=chunk-
|
|
397
|
+
//# sourceMappingURL=chunk-7PUVK4YM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/roles/test/shared-test-config.ts","../src/roles/test/react/jest-export-conditions.ts"],"sourcesContent":["/**\n * The Vitest config a Nest module gets, as one call instead of forty lines copied 133 times.\n *\n * The React family needed none of this: those modules already had a Vitest config, so adoption\n * moved its imports and changed nothing else. The Jest family has no config at all, so one has to\n * be WRITTEN, and writing the same four decisions into 133 files is how they drift. A module that\n * genuinely differs still can: `overrides` is merged over the base, the same shape `nestService`\n * uses on the build side.\n *\n * Every line below was established by running a real suite, not by reading a guide. `mission` is\n * the reference: 387 specs, the module the build role refused for having its own webpack config,\n * and the one with the only `isolateModules` in the repo.\n */\nimport { existsSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nimport type { Alias as ViteAlias, AliasOptions } from 'vite'\nimport type { ViteUserConfig } from 'vitest/config'\n\nimport { decoratorMetadata } from '../build/nest/decorator-metadata.js'\nimport { tsconfigAliases } from '../build/nest/tsconfig-aliases.js'\nimport type { Alias } from '../build/nest/tsconfig-aliases.js'\n\nimport { jestExportConditions } from './react/jest-export-conditions.js'\n\n/** Which family this config is for: it decides the three things that are not shared. */\nexport type TestFlavour = 'nest' | 'react'\n\nexport interface SharedTestOptions {\n /** Which family this config is for. It decides the three things that are not shared. */\n flavour?: TestFlavour\n /** The module's own directory: where its specs live and what its config is relative to. */\n root: string\n /** The workspace root, which is where `tsconfig.base.json` and its path aliases are. */\n workspaceRoot: string\n /**\n * Lower decorators with TypeScript before oxc sees them, for a module that needs it.\n *\n * ⚠️ Written by `--init --test` from the module's own sources, never by hand, because the\n * condition is not a preference: it is whether a decorator sits on an `abstract` class member,\n * the one construct oxc does not reproduce. See `generate-config.ts` for the measurement.\n *\n * Off by default, and that default is the measured one: on\n * `apps/nest/microservices/mission`, 715 of 716 decorated files need nothing, and running the\n * plugin for all of them took the suite from 98s to 249s.\n */\n lowerDecoratorsWithTypeScript?: boolean\n /** Merged over the base. For what a module genuinely needs to differ on, nothing else. */\n overrides?: ViteUserConfig\n}\n\n/** A file shipped beside this module in the build, or nothing when running from source. */\nfunction siblingFile(relative: string): string | undefined {\n /*\n * ⚠️ Several candidates, because the EMITTED layout is not ours to predict. This file is imported\n * by two toolchains, so the bundler extracts it into a shared chunk at the package root, and it\n * does so even when it is declared as its own entry (the entry then only re-exports the chunk).\n * A single `import.meta.url`-relative path therefore resolves differently depending on where the\n * bundler decided to put the code.\n *\n * That is not theoretical: it silently broke the jest-mock-extended and msw-server adapters, and\n * `apps/cloud/shift-offer` went from 83/83 to 56/83 with \"The property X is not defined on the\n * object\" — a mockDeep shape error that names nothing near the cause. The alias had quietly\n * fallen back to the raw fork.\n *\n * So the file is LOOKED FOR rather than computed, and the first one that exists wins.\n */\n const candidates = [\n relative,\n `roles/test/${relative.replace(/^\\.\\//, '')}`,\n `../${relative.replace(/^\\.\\//, '')}`,\n ]\n for (const candidate of candidates) {\n try {\n const sibling = fileURLToPath(new URL(candidate, import.meta.url))\n if (existsSync(sibling)) return sibling\n } catch {\n continue\n }\n }\n return undefined\n}\n\n/** A package resolved from SENTINEL, so the module gets the copy the setup uses. */\nfunction resolveFrom(specifier: string): string | undefined {\n try {\n return fileURLToPath(import.meta.resolve(specifier))\n } catch {\n try {\n return createRequire(import.meta.url).resolve(specifier)\n } catch {\n return undefined\n }\n }\n}\n\n/**\n * sentinel's own adapter around the fork, which the alias points at when it has been built.\n *\n * The adapter only makes a deep mock answer `in` and `getOwnPropertyDescriptor`, which Vitest's\n * `spyOn` asks and jest's did not; `mock-extended.ts` carries the measurement. Resolved as a\n * sibling file rather than by specifier, because it is not a package.\n *\n * Falls back to the fork itself when there is no build beside this module, which is the case while\n * sentinel's own suite runs from `src`. The alias then behaves exactly as it did before the\n * adapter existed, so a missing build degrades instead of throwing.\n */\nfunction mockExtendedAdapterPath(): string | undefined {\n return siblingFile('./setup/mock-extended.js')\n}\n\n/**\n * The ABSOLUTE path of the Vitest fork, resolved from sentinel rather than named.\n *\n * A bare specifier in an alias is resolved by Vite against the IMPORTER, which here is a spec file\n * inside the adopted module. `vitest-mock-extended` is sentinel's dependency, not the module's, so\n * under pnpm's isolated layout the module cannot see it and the alias points at nothing.\n *\n * Measured on `apps/cloud/agency`: three suites died with \"Cannot find package\n * 'jest-mock-extended'\" while the fork sat in the store, installed and unreachable. Same class of\n * defect as the axios alias below, and the same fix: resolve it where it actually is.\n *\n * Falls back to the bare name, which keeps the previous behaviour rather than throwing while a\n * config is being built.\n */\nfunction vitestMockExtendedPath(): string {\n /*\n * `import.meta.resolve` and not `createRequire().resolve`: the latter follows the `require`\n * condition and hands back the package's CJS entry, whose first line requires `vitest`. Vitest\n * refuses that outright (\"Vitest cannot be imported in a CommonJS module using require()\"), so\n * the alias resolved correctly and then failed one step later. Measured on `apps/cloud/agency`.\n */\n try {\n return fileURLToPath(import.meta.resolve('vitest-mock-extended'))\n } catch {\n try {\n return createRequire(import.meta.url).resolve('vitest-mock-extended')\n } catch {\n return 'vitest-mock-extended'\n }\n }\n}\n\n/**\n * The ONE msw copy a module's tests share with the server that listens.\n *\n * sentinel ships msw so that a module stands alone, and the codemod repoints the SPEC files to it.\n * Helpers are not spec files, so they keep `import { rest } from 'msw'` and build their handlers\n * with the WORKSPACE's copy while the server that listens was built with sentinel's. Same version,\n * two physical instances, and a handler registered on one is invisible to the other.\n *\n * Measured on `apps/cloud/shift-offer`, whose `setup-mocks.ts` registers every handler its suites\n * rely on: 19 tests failed on `captured a request without a matching request handler` for a URL the\n * helper had a handler for. The repo has 159 non-spec files importing msw, and 2 importing the\n * workspace's server directly, so this is not one module's habit.\n *\n * Aliased rather than codemodded, for the same reason as `jest-mock-extended` above: it lets an\n * UNMIGRATED shared helper keep working inside a migrated module, which is what makes the\n * per-module plan possible at all. `^msw$` only: `msw/node` stays the package's own, and it is\n * sentinel's setup that imports it.\n */\nfunction mswAliases(): Alias[] {\n const server = siblingFile('./setup/msw-server.js')\n const own = resolveFrom('msw')\n return [\n ...(own === undefined ? [] : [{ find: /^msw$/, replacement: own }]),\n ...(server === undefined ? [] : [{ find: /^@hublo\\/test\\/msw\\/server$/, replacement: server }]),\n ]\n}\n\n/**\n * One PHYSICAL axios, resolved from the MODULE and not from sentinel.\n *\n * pnpm installs axios twice here, same 1.17.0, differing only by a peer. The service client\n * resolves one copy and a provider's `import { AxiosError } from 'axios'` the other, so\n * `if (!(error instanceof AxiosError)) throw error` answers false on a genuine axios error and\n * rethrows it raw. The test then fails on the WRAPPER being absent, naming nothing near the cause.\n *\n * `resolve.dedupe` does NOT fix this, and neither does `deps.inline`: dedupe settles bare\n * specifiers, not two physical paths. The alias has to name the path.\n *\n * The module's OWN `node_modules`, checked directly rather than resolved.\n *\n * `createRequire(...).resolve()` was the first version and it is wrong twice. It walks UP the\n * tree, so a module without axios would be aliased to a PARENT's copy, which is the opposite of\n * pinning its own. And because it consults ambient resolution, the answer depends on where the\n * process runs: it correctly found nothing from a plain CLI run and found something under Vitest,\n * which is how a test of it became a test of its environment.\n *\n * pnpm links a module's direct dependencies into `<module>/node_modules`, so that path is both the\n * right answer and a deterministic one.\n *\n * Measured on `mission`: 378 passing suites to 381 of 387.\n *\n * ## ⚠️ And the workspace root when the module has none of its own\n *\n * The first version stopped there and returned nothing for a module without its own axios, on the\n * reasoning that pinning it to a PARENT's copy is the opposite of pinning its own. That reasoning\n * has an blind spot: a module with no copy of its own does not thereby have no axios PROBLEM. It\n * receives one through its dependencies, and it is still importing it two ways.\n *\n * Measured in `apps/nest/backends-for-frontends/backoffice`, which declares no axios, under this\n * very preset with no alias:\n *\n * the ESM AxiosError === the CJS AxiosError false\n * a CJS error instanceof the CJS class true\n * a CJS error instanceof the ESM class FALSE\n *\n * `@nestjs/axios` is externalised, so Node loads it and it throws the CJS class; the provider does\n * `import { AxiosError } from 'axios'` through Vite and gets the ESM one. Its\n * `if (error instanceof AxiosError) throw new RemoteBackendException(...)` therefore answers false\n * on a genuine axios error and rethrows it raw, and the test fails on the WRAPPER being absent,\n * naming nothing near the cause. Four modules reported it: `admin`, `backoffice`, `mission`,\n * `institution`.\n *\n * So: the module's own copy first, the workspace root second, nearest wins. That is the same shape\n * as `luxonAlias` above, and for the same reason: when a module has nothing of its own, the copy\n * it actually uses is the one to pin. Absent axios everywhere is still not an error.\n */\n/**\n * ONE physical luxon, for the same reason as axios: `Settings` is per-copy state.\n *\n * The setup pins `Settings.defaultZone = 'utc'`, which the root jest setup did for every suite in\n * the repo. It was reaching the copy `require` resolves, the CJS build, while the tests import the\n * one Vite resolves, the ESM build. Two instances, two `Settings`, and the pin landed on the one\n * nobody read.\n *\n * Measured on `libs/cloud/events-notifications`: the suite ran in `Europe/Paris`, so every date\n * came out two hours off and 12 assertions compared timestamps that differed by exactly that.\n *\n * luxon sits at the workspace root here rather than in each module, so both places are checked,\n * nearest first. Absent luxon is not an error: most modules have none.\n */\nfunction luxonAlias(root: string, workspaceRoot: string): Alias[] {\n for (const base of [root, workspaceRoot]) {\n const manifest = join(base, 'node_modules', 'luxon', 'package.json')\n if (existsSync(manifest)) return [{ find: /^luxon$/, replacement: dirname(manifest) }]\n }\n return []\n}\n\nfunction axiosAlias(root: string, workspaceRoot: string): Alias[] {\n for (const base of [root, workspaceRoot]) {\n const manifest = join(base, 'node_modules', 'axios', 'package.json')\n if (existsSync(manifest)) return [{ find: /^axios$/, replacement: dirname(manifest) }]\n }\n return []\n}\n\n/**\n * A generated Prisma client's runtime, resolved to the file the package actually ships.\n *\n * The generated client reaches its own runtime by package name, and the package's `exports` map\n * answers differently depending on which condition asks:\n *\n * \"./runtime/library\": { \"require\": \"./runtime/library.js\", // shipped\n * \"import\": \"./runtime/library.mjs\" } // NOT shipped\n *\n * jest asked as CJS and got the file. Vitest resolves the same specifier under `import`, is sent\n * to a `.mjs` that does not exist, and the spec file does not load at all, so its tests go missing\n * rather than failing. Node itself spells the answer out: \"Did you mean to import\n * .../runtime/library.js?\".\n *\n * Measured on `apps/nest/microservices/client-management` (1 file) and\n * `apps/nest/microservices/institution` (3 files), on two different generated clients. This repo\n * generates 31 of them, all with the same manifest, so this is a property of the generator rather\n * than of a module.\n *\n * Written as a pattern with a back-reference, not one entry per client: the module does not know\n * which clients its dependencies pull in, and enumerating 31 names would go stale the day a\n * thirty-second schema is added.\n *\n * ⚠️ Not a workaround for a mistake of ours. The package declares a target it does not ship, and\n * pointing at the shipped file is what `require` already did. Nothing else changes: the `.js` IS\n * the runtime, in the same package, at the version installed.\n */\nfunction prismaRuntimeAlias(workspaceRoot: string): Alias[] {\n const prisma = join(workspaceRoot, 'node_modules', '@prisma')\n if (!existsSync(prisma)) return []\n\n return [\n {\n find: /^@prisma\\/([^/]+)\\/runtime\\/library$/,\n replacement: join(prisma, '$1', 'runtime', 'library.js'),\n },\n ]\n}\n\n/**\n * The base every Nest module gets. Four decisions, each with its measurement.\n */\nfunction baseConfig(options: SharedTestOptions): ViteUserConfig {\n const { root, workspaceRoot } = options\n\n return {\n /*\n * NO decorator-metadata plugin, and that is a measured removal rather than an omission.\n *\n * Nest reads constructor parameter types from `emitDecoratorMetadata`, so this preset used to\n * run the BUILD role's SWC plugin to emit it, on the premise that the bundler does not. That\n * premise was true of esbuild and is false of Vite 8, which transforms with oxc: oxc lowers the\n * decorators itself and emits the metadata, provided a tsconfig with `experimentalDecorators`\n * applies to the file.\n *\n * Measured five times before removing it. On `apps/nest/microservices/mission`, with and\n * without the plugin, the output is strictly identical for `@Injectable()` constructors\n * (including a service caught in a two-file import CYCLE, all 8 parameters resolved), for route\n * handler parameters and return types, and for DTO properties; the suite then passes in 98s\n * instead of 249s. Confirmed by a direct `Reflect.getMetadata` probe on\n * `apps/nest/backends-for-frontends/admin` and on `libs/nest/starter`, and by two A/B runs\n * through this very preset: `agency-notification` (100 tests) identical with and without, and\n * `grid-leave` (3335 tests) identical without.\n *\n * One caveat that the same measurement produced, and which belongs to the CONSUMER rather than\n * here: a property typed by an interface or by a type-alias imported with `import type` emits\n * `Object`. That is `emitDecoratorMetadata`'s own behaviour, identical with and without the\n * plugin, not a Vite regression.\n *\n * The BUILD role keeps its plugin. Its context differs, it feeds a shipped artefact, and\n * removing it there needs its own proof.\n *\n * ⚠️ ONE construct escapes oxc, and the exception is why this line is a condition rather than\n * an empty array: a decorator on an `abstract` class member. swc emitted it, oxc erases the\n * member and the decorator with it, silently. There is exactly one such member in this repo,\n * so `lowerDecoratorsWithTypeScript` buys the plugin back for that module alone.\n */\n /*\n * `jestExportConditions` is UNCONDITIONAL, and it is the one plugin every migrated module gets.\n *\n * jest resolved with `['node', 'require', 'default']`, read off the installed `@nx/jest/preset`\n * rather than off its documentation. `development` was never in that list, so a package\n * shipping a separate development build loaded its PRODUCTION file. Vite's own conditions carry\n * `development|production`, so `@emotion/cache` loads `emotion-cache.development.cjs.js`, whose\n * extra stylis plugin calls `console.error(':first-child is potentially unsafe...')`, and with\n * `jest-fail-on-console` in the setup that console call IS a failure.\n *\n * Measured on `libs/front/components`: 2 of its 3 remaining failures, both green again with\n * this. `apps/front/front-legacy` has 100 over 26 files from the same cause.\n *\n * Unconditional rather than reserved for a jsdom module, because it is not a statement about\n * the DOM: it is what this migration is for, running the suite the way the runner it was\n * written for ran it. It changes nothing for a module with no dual-published dependency, which\n * is why nest and cloud were measured identical without it.\n */\n plugins: [\n jestExportConditions(),\n ...(options.lowerDecoratorsWithTypeScript ? [decoratorMetadata({ root })] : []),\n ],\n\n /*\n * The proviso in the paragraph above, made unconditional.\n *\n * oxc lowers decorators from the tsconfig that applies to the file, so a file belonging to NO\n * tsconfig `include` is lowered as if it used the STANDARD decorators, and comes out of Vite as\n * invalid JavaScript. Not merely without metadata: the file fails to parse, and every file that\n * imports it disappears with it.\n *\n * Measured on `apps/nest/microservices/mission`, where ONE uncovered helper,\n * `src/app/test/mission.test-wrapper.ts`, took down 158 of 416 test files. Reproduced on a\n * three-file case: covered file fine, uncovered file `SyntaxError: Invalid or unexpected\n * token`, and this option alone turns it into the same output the covered file gets, metadata\n * included.\n *\n * Declared here rather than left to each module's tsconfig `include`, because the alternative\n * is asking 107 teams to find which of their files no tsconfig covers, which is the work this\n * role exists to do for them.\n *\n * Two things the same measurement established, both deliberate:\n *\n * - it OVERRIDES the tsconfig, it is not a default the tsconfig refines. A file under a\n * tsconfig saying `emitDecoratorMetadata: false` gets metadata anyway. Acceptable because\n * this is the NEST preset and a Nest module is legacy decorators by definition: no tsconfig\n * under `apps/nest`, `libs/nest`, `apps/cloud` or `libs/cloud` sets either option to false.\n * - it needs no polyfill. Without `reflect-metadata` loaded, nothing throws, the metadata is\n * simply unreadable, exactly as before.\n */\n oxc: { decorator: { legacy: true, emitDecoratorMetadata: true } },\n\n resolve: {\n alias: [\n ...axiosAlias(root, workspaceRoot),\n ...luxonAlias(root, workspaceRoot),\n /*\n * Nest only, and measured: 1186 files under `apps/nest` and `libs/nest` mention `@prisma/`,\n * and ZERO under `apps/front` and `libs/front`. A React module paying for an alias to a\n * client it never generates is noise in a file someone has to read.\n */\n ...(options.flavour === 'nest' ? prismaRuntimeAlias(workspaceRoot) : []),\n ...mswAliases(),\n /*\n * `jest-mock-extended` loads `@jest/globals`, which refuses to run outside jest. 2491\n * files import it, 104 of them under `libs/` as SHARED helpers, so migrating those helpers\n * breaks every module still on jest and leaving them breaks every module moved to Vitest.\n * Old and new therefore do not cohabit on shared helpers, which would have killed the\n * per-module plan.\n *\n * This one line removes the constraint: an unmigrated helper resolves to the Vitest fork\n * inside an adopted module and keeps resolving to the jest one everywhere else.\n * `vitest-mock-extended@5.1.1` is a fork of the same package and exports the same names.\n *\n * Measured on `mission`: failing suites went from 159 to 10.\n */\n {\n find: /^jest-mock-extended$/,\n replacement: mockExtendedAdapterPath() ?? vitestMockExtendedPath(),\n },\n ...tsconfigAliases(workspaceRoot),\n ],\n },\n\n test: {\n globals: true,\n environment: 'node',\n root,\n /*\n * What the repo's jest preset actually matched, copied rather than approximated:\n * `**\\/?(*.)+(spec|test).[jt]s?(x)`.\n *\n * Both NAMES, because jest ran both: `**\\/*.spec.ts` alone read green while missing three\n * `.test.ts` files and 23 tests, with nothing saying so. And all four EXTENSIONS, for the\n * same reason one notch further out. Measured over the repo's 7063 test files:\n *\n * .ts 5844 .tsx 1108 .js 99 .mjs/.cjs 12\n *\n * The `.ts`-only form cost nothing on nest and cloud, which have none of the others, and it\n * cost `libs/front/api` three files and 13 tests on the first front module it met. Half the\n * front's test files are `.tsx`.\n *\n * `.mjs` and `.cjs` are deliberately OUT: jest's `[jt]s?(x)` does not match them either, and\n * Vitest's own default include does. Running a file the reference never ran is as wrong as\n * skipping one it did.\n */\n include: ['**/*.spec.[jt]s?(x)', '**/*.test.[jt]s?(x)'],\n /*\n * Kept, and it is not a performance knob. Nest registers metadata as an import SIDE EFFECT:\n * a decorator writes into a catalog when its module loads. Sharing a module registry across\n * files lets one suite see what another registered, and the failure appears in whichever\n * file happens to run second.\n */\n /*\n * Nest only. A Nest module registers metadata as an import SIDE EFFECT, so sharing a module\n * registry across files lets one suite see what another registered. A React module has no\n * such catalog, and isolation is not free.\n */\n ...(options.flavour === 'nest' ? { isolate: true } : {}),\n /*\n * Concurrency, transposed from what this repo does today rather than chosen.\n *\n * Every jest target inherits `configurations.ci = { ci: true, runInBand: true }` from the\n * `@nx/jest:jest` key in `nx.json`, and CI invokes every test target with\n * `--configuration=ci`. So on CI every suite in this repo runs ONE FILE AT A TIME today. That\n * key belongs to the jest executor and cannot be touched, because the workspace is mixed: it\n * still serves the modules that have not moved.\n *\n * ⚠️ And it is CI-ONLY. A local run omits `--configuration=ci`, so jest runs files in\n * PARALLEL on a developer's machine. A flat `fileParallelism: false` here would make local\n * runs slower than jest, which loses something the module had. Hence the condition rather\n * than the constant: parallel locally, one file at a time on CI, which is jest on both sides.\n *\n * Measured on three files that each hold the clock for 400ms and record their interval:\n *\n * default files overlap, 402ms\n * fileParallelism: false no overlap, 1442ms\n * maxWorkers: 1 no overlap, 1423ms\n *\n * Both candidates give the property that matters. `fileParallelism` is the one that says what\n * the module MEANS (\"do not run my files at the same time\"); `maxWorkers` is a pool size, and\n * it is what a module asking for a CAP gets instead (three BFFs ask for 4).\n *\n * A module that declared its own concurrency overrides this, in both environments, exactly as\n * it does today.\n */\n fileParallelism: !process.env.CI,\n\n /*\n * ⚠️ Sentinel's own setup files go through VITE, not round it, and that is load-bearing.\n *\n * Vitest externalizes anything under `node_modules`, so an installed `@hublo/sentinel` is\n * loaded by Node while the module's own code is served by Vite. The two then hold DIFFERENT\n * instances of the same package, and a setup whose whole job is to mutate per-copy state\n * mutates a copy nobody reads.\n *\n * Measured on `apps/nest/microservices/agency`, with the published 1.4.0-alpha.4:\n *\n * zone of the copy sentinel pinned UTC\n * zone of the copy the test imports Europe/Paris\n * same object false\n *\n * Six tests that passed under jest failed, all comparing `DateTime.now().toISO()` against a\n * date the provider had serialised: identical instants, one rendered `+02:00` and the other\n * `Z`. The root jest setup pinned `Settings.defaultZone = 'utc'` and 97 modules named it, so\n * this is not one module's edge case.\n *\n * ⚠️ It hid for a whole campaign because the harness SYMLINKS sentinel to its source tree.\n * The resolved path then holds no `node_modules`, Vitest inlines it, and the pin lands on the\n * right copy: 96 modules reported IDENTIQUE while the real install was red. An instrument\n * that installs the package differently from a team does not measure what a team will see.\n *\n * The narrow form `/@hublo\\/sentinel\\/dist\\/roles\\//` was tried and does NOT work: the pin\n * itself lives in a shared chunk at the dist root, which stays external. It has to be the\n * whole package.\n */\n server: { deps: { inline: [/@hublo\\/sentinel/] } },\n },\n }\n}\n\n/**\n * Vite accepts `alias` as an ARRAY or as an object map, and the two do not combine.\n *\n * The array form is the one that matters here: only it takes a RegExp `find`, which both the axios\n * and the `jest-mock-extended` aliases need. A module overriding with the object form gets its\n * entries converted rather than dropped, because silently losing an override is worse than a shape\n * the caller did not expect.\n */\nfunction asAliasArray(alias: AliasOptions | undefined): ViteAlias[] {\n if (alias === undefined) return []\n if (Array.isArray(alias)) return alias as ViteAlias[]\n return Object.entries(alias as Record<string, string>).map(([find, replacement]) => ({\n find,\n replacement,\n }))\n}\n\n/** A `test.server` block, named off Vitest's own type so the merge cannot drift from it. */\ntype TestServer = NonNullable<ViteUserConfig['test']>['server']\n\n/** The config, with the module's own overrides merged over it. */\nexport function sharedTestConfig(\n options: SharedTestOptions & { flavour: TestFlavour },\n): ViteUserConfig {\n const base = baseConfig(options)\n if (options.overrides === undefined) return base\n // Shallow by section rather than a deep merge helper: the three sections a module overrides in\n // practice are `test`, `resolve` and `plugins`, and a deep merge would silently concatenate\n // arrays a module meant to replace.\n return {\n ...base,\n ...options.overrides,\n plugins: [...(base.plugins ?? []), ...(options.overrides.plugins ?? [])],\n resolve: {\n ...base.resolve,\n ...options.overrides.resolve,\n /*\n * The module's own aliases come after sentinel's, and in a Vite alias ARRAY the FIRST match\n * wins. So sentinel's win, which is the opposite of what this comment used to claim.\n *\n * ⚠️ The order is corrected here rather than in the code, because changing it would flip a\n * behaviour that nothing exercises. Every alias sentinel adds is ANCHORED to one exact\n * specifier: `^axios$`, `^luxon$`, `^msw$`, `^jest-mock-extended$` and\n * `^@prisma/<x>/runtime/library$`. A module's own entry collides only by naming the identical\n * string, and measured across every `jest.config*` in the repo, none does: the closest are\n * `@front/type/axios` and `@front/api/msw-handlers` in `front-legacy`, different specifiers\n * in the one module this role refuses anyway.\n *\n * So today the order decides nothing, and all 97 migrations were measured with it this way\n * round. Reversing it on a hypothesis would be a silent behaviour change bought with nothing.\n * What was actually wrong was a comment promising a module it could win, which a reader would\n * have relied on.\n */\n alias: [\n ...asAliasArray(base.resolve?.alias),\n ...asAliasArray(options.overrides.resolve?.alias),\n ],\n },\n test: {\n ...base.test,\n ...options.overrides.test,\n /*\n * ⚠️ `server.deps.inline` is the one key inside `test` that must not be REPLACED.\n *\n * The shallow spread above is right for everything else: a module overriding `environment`\n * or `testTimeout` means to replace it. But the base uses this list to put sentinel's own\n * setup inside Vite's graph, and a module declares its own entries there for its workspace\n * packages. Dropping either half breaks something silently, and the halves have nothing to\n * do with each other, so they are concatenated.\n *\n * Measured on `libs/front/api`, which declares `['@front/runtime-config', '@segment/snippet']`\n * and would otherwise have discarded the base's entry and lost the timezone pin with it.\n */\n server: mergeServerDeps(base.test?.server, options.overrides.test?.server),\n },\n }\n}\n\n/** Two `server` blocks, with their `deps.inline` lists joined rather than one winning. */\nfunction mergeServerDeps(base: TestServer, override: TestServer): TestServer {\n if (base === undefined) return override\n if (override === undefined) return base\n\n const inline = [\n ...(asInlineArray(base.deps?.inline) ?? []),\n ...(asInlineArray(override.deps?.inline) ?? []),\n ]\n return {\n ...base,\n ...override,\n deps: { ...base.deps, ...override.deps, ...(inline.length > 0 ? { inline } : {}) },\n }\n}\n\n/** `inline` is a list or the literal `true`, and `true` cannot be concatenated with anything. */\nfunction asInlineArray(inline: unknown): (string | RegExp)[] | undefined {\n return Array.isArray(inline) ? (inline as (string | RegExp)[]) : undefined\n}\n","/**\n * Resolve packages the way jest did, for a suite that was written against jest's resolution.\n *\n * ## What jest resolved, measured rather than remembered\n *\n * Every suite in this repo ran through `@nx/jest/preset`, whose\n * `testEnvironmentOptions.customExportConditions` is exactly `['node', 'require', 'default']`\n * (read off the installed preset, not off its documentation). `development` was never in that\n * list, so a package shipping a separate development build behind that condition loaded its\n * PRODUCTION file under jest.\n *\n * Vitest resolves with Vite's conditions instead, and its default carries the\n * `development|production` token. Measured on a bare config, the resolved list is\n * `['node', 'development|production']`. `@emotion/cache` then loads\n * `emotion-cache.development.cjs.js`, whose extra stylis plugin calls\n * `console.error(':first-child is potentially unsafe...')`.\n *\n * With `jest-fail-on-console` in the setup, that console call IS a failure: **100 tests over 26\n * files on `apps/front/front-legacy`**, every one of them green under jest. `libs/front/components`\n * hits the same root cause on one test.\n *\n * ## Why a plugin and not a config line\n *\n * Declaring `ssr.resolve.conditions: ['node']` does nothing: Vite merges config arrays by\n * CONCATENATION, so Vitest's default is appended straight back. The token has to come off the\n * RESOLVED config, which is what `configResolved` is for.\n *\n * This is the same shape as the other thing that cannot be declared: a module cannot reproduce\n * `customExportConditions` either, because the list it asks for is PREFIXED to Vite's defaults\n * rather than substituted for them.\n *\n * ## The three lists are one array\n *\n * Measured on Vite 8: `config.resolve.conditions`, `config.ssr.resolve.conditions` and\n * `config.environments.ssr.resolve.conditions` are the SAME array object, so stripping one strips\n * all three. All three are stripped anyway. Relying on an aliasing that nothing promises is how a\n * silent regression arrives on a Vite upgrade, and the cost of being explicit is two lines.\n *\n * ## ⚠️ What this deliberately hides, said out loud\n *\n * emotion's warning is REAL: `libs/front/components` is consumed by a Next app, and a\n * `:first-child` selector is genuinely unsafe when the markup is rendered server-side. Restoring\n * jest's resolution puts that warning back out of sight.\n *\n * It is hidden here on purpose all the same, because a migration that also turns 100 green tests\n * red cannot be told apart from a migration that broke something. The baseline gate compares test\n * names, and it has no way to know which reds are progress. The selector belongs to the module's\n * owners as its own piece of work, with its own ticket, not as a side effect of changing runner.\n */\nimport type { Plugin } from 'vite'\n\n/**\n * The tokens jest never had.\n *\n * Both spellings, because the resolved config carries `development|production` (Vite's own\n * placeholder, replaced per environment) while a config written by hand may carry `development`.\n */\nconst ABSENT_UNDER_JEST = new Set(['development', 'development|production'])\n\n/** Remove them in place, since the resolved config is what the resolver will read. */\nfunction stripInPlace(conditions: string[] | undefined): void {\n if (conditions === undefined) return\n\n for (let index = conditions.length - 1; index >= 0; index -= 1) {\n const condition = conditions[index]\n if (condition !== undefined && ABSENT_UNDER_JEST.has(condition)) conditions.splice(index, 1)\n }\n}\n\n/**\n * Add to `plugins` in a module whose suite was written against jest's resolution.\n *\n * Not applied by the preset for everyone: it is a MIGRATION aid, and a module that was always on\n * Vitest never had jest's resolution to go back to. A module adopts it the day it migrates, and\n * can drop it the day its suite no longer depends on the production build.\n */\nexport function jestExportConditions(): Plugin {\n return {\n name: 'sentinel:jest-export-conditions',\n configResolved(config) {\n const environments = config as unknown as {\n environments?: { ssr?: { resolve?: { conditions?: string[] } } }\n }\n\n stripInPlace(config.resolve?.conditions as string[] | undefined)\n stripInPlace(config.ssr?.resolve?.conditions as string[] | undefined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