@venizia/dev-configs 0.4.8-0 → 0.4.8-10
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/README.md +65 -16
- package/dist/checks/catalog.d.ts +15 -2
- package/dist/checks/catalog.js +1 -0
- package/dist/checks/catalog.js.map +1 -1
- package/dist/checks/module-cycles.d.ts +2 -0
- package/dist/checks/module-cycles.js +2 -0
- package/dist/checks/module-cycles.js.map +1 -1
- package/dist/checks/purity/manifest.d.ts +6 -1
- package/dist/checks/purity/manifest.js.map +1 -1
- package/dist/checks/purity/probe.d.ts +4 -1
- package/dist/checks/purity/probe.js +1 -0
- package/dist/checks/purity/probe.js.map +1 -1
- package/dist/checks/purity/run.d.ts +3 -0
- package/dist/checks/purity/run.js +1 -0
- package/dist/checks/purity/run.js.map +1 -1
- package/dist/checks/split-report.d.ts +1 -0
- package/dist/checks/split-report.js +1 -0
- package/dist/checks/split-report.js.map +1 -1
- package/dist/checks/test-controls.d.ts +11 -2
- package/dist/checks/test-controls.js +1 -0
- package/dist/checks/test-controls.js.map +1 -1
- package/dist/checks/test-dead-code.d.ts +1 -0
- package/dist/checks/test-dead-code.js +1 -0
- package/dist/checks/test-dead-code.js.map +1 -1
- package/dist/checks/test-mutate.d.ts +14 -2
- package/dist/checks/test-mutate.js +1 -0
- package/dist/checks/test-mutate.js.map +1 -1
- package/dist/checks/test-weight.d.ts +3 -0
- package/dist/checks/test-weight.js +1 -0
- package/dist/checks/test-weight.js.map +1 -1
- package/dist/cli/codemod/any-aliases.d.ts +35 -0
- package/dist/cli/codemod/any-aliases.js +544 -0
- package/dist/cli/codemod/any-aliases.js.map +1 -0
- package/dist/cli/codemod/async-style.d.ts +2 -2
- package/dist/cli/codemod/async-style.js +4 -2
- package/dist/cli/codemod/async-style.js.map +1 -1
- package/dist/cli/codemod/connector-imports.d.ts +5 -1
- package/dist/cli/codemod/connector-imports.js +21 -7
- package/dist/cli/codemod/connector-imports.js.map +1 -1
- package/dist/cli/codemod/env-get.d.ts +56 -0
- package/dist/cli/codemod/env-get.js +599 -0
- package/dist/cli/codemod/env-get.js.map +1 -0
- package/dist/cli/codemod/index.js +31 -2
- package/dist/cli/codemod/index.js.map +1 -1
- package/dist/cli/codemod/namespace-functions/index.d.ts +2 -1
- package/dist/cli/codemod/namespace-functions/index.js +14 -5
- package/dist/cli/codemod/namespace-functions/index.js.map +1 -1
- package/dist/cli/codemod/namespace-functions/mappings/core-server.js +6 -14
- package/dist/cli/codemod/namespace-functions/mappings/core-server.js.map +1 -1
- package/dist/cli/codemod/namespace-functions/mappings/helpers.d.ts +3 -0
- package/dist/cli/codemod/namespace-functions/mappings/helpers.js +4 -9
- package/dist/cli/codemod/namespace-functions/mappings/helpers.js.map +1 -1
- package/dist/cli/codemod/namespace-functions/mappings/kernel.js +1 -1
- package/dist/cli/codemod/namespace-functions/mappings/kernel.js.map +1 -1
- package/dist/cli/codemod/namespace-functions/reverse.d.ts +40 -0
- package/dist/cli/codemod/namespace-functions/reverse.js +348 -0
- package/dist/cli/codemod/namespace-functions/reverse.js.map +1 -0
- package/dist/cli/codemod/namespace-functions/rewriter.d.ts +21 -2
- package/dist/cli/codemod/namespace-functions/rewriter.js +1 -1
- package/dist/cli/codemod/namespace-functions/rewriter.js.map +1 -1
- package/dist/cli/index.js +2 -0
- package/dist/cli/index.js.map +1 -1
- package/dist/linters/eslint.js +6 -1
- package/dist/linters/eslint.js.map +1 -1
- package/dist/linters/house/async-rules.d.ts +1 -1
- package/dist/linters/house/async-rules.js +3 -1
- package/dist/linters/house/async-rules.js.map +1 -1
- package/dist/linters/house/await-support.js +45 -38
- package/dist/linters/house/await-support.js.map +1 -1
- package/dist/linters/house/common.d.ts +43 -0
- package/dist/linters/house/common.js +43 -0
- package/dist/linters/house/common.js.map +1 -1
- package/dist/linters/house/const-class-values.rule.js +9 -8
- package/dist/linters/house/const-class-values.rule.js.map +1 -1
- package/dist/linters/house/hook-support.js +11 -7
- package/dist/linters/house/hook-support.js.map +1 -1
- package/dist/linters/house/index.d.ts +1 -0
- package/dist/linters/house/index.js +1 -0
- package/dist/linters/house/index.js.map +1 -1
- package/dist/linters/house/max-params-own.rule.d.ts +3 -1
- package/dist/linters/house/max-params-own.rule.js +13 -12
- package/dist/linters/house/max-params-own.rule.js.map +1 -1
- package/dist/linters/house/no-await-new-chain.rule.d.ts +37 -0
- package/dist/linters/house/no-await-new-chain.rule.js +179 -0
- package/dist/linters/house/no-await-new-chain.rule.js.map +1 -0
- package/dist/linters/house/no-await-promise-chain.rule.js +23 -22
- package/dist/linters/house/no-await-promise-chain.rule.js.map +1 -1
- package/dist/linters/house/no-inline-await.rule.js +4 -3
- package/dist/linters/house/no-inline-await.rule.js.map +1 -1
- package/dist/linters/house/no-leaked-render.rule.js +3 -3
- package/dist/linters/house/no-leaked-render.rule.js.map +1 -1
- package/dist/linters/house/no-new-error.rule.js +1 -1
- package/dist/linters/house/no-new-error.rule.js.map +1 -1
- package/dist/linters/house/no-return-await.rule.js +5 -4
- package/dist/linters/house/no-return-await.rule.js.map +1 -1
- package/dist/linters/house/no-silent-catch.rule.js +4 -3
- package/dist/linters/house/no-silent-catch.rule.js.map +1 -1
- package/dist/linters/house/plugin.js +2 -0
- package/dist/linters/house/plugin.js.map +1 -1
- package/dist/linters/house/promise-chain-support.js +25 -25
- package/dist/linters/house/promise-chain-support.js.map +1 -1
- package/dist/linters/oxlint.d.ts +11 -5
- package/dist/linters/oxlint.js +8 -3
- package/dist/linters/oxlint.js.map +1 -1
- package/dist/linters/rules/no-unused-vars.rule.d.ts +6 -1
- package/dist/linters/rules/no-unused-vars.rule.js +1 -1
- package/dist/linters/rules/no-unused-vars.rule.js.map +1 -1
- package/dist/testing/rejection.helper.d.ts +1 -0
- package/dist/testing/rejection.helper.js +1 -0
- package/dist/testing/rejection.helper.js.map +1 -1
- package/dist/testing/repo-tmp.d.ts +1 -0
- package/dist/testing/repo-tmp.js +18 -10
- package/dist/testing/repo-tmp.js.map +1 -1
- package/dist/testing/spawn.helper.d.ts +1 -0
- package/dist/testing/spawn.helper.js +1 -0
- package/dist/testing/spawn.helper.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@ it as a dev dependency in an application that wants the same rules.
|
|
|
9
9
|
bun add -d @venizia/dev-configs oxlint oxlint-tsgolint eslint typescript
|
|
10
10
|
```
|
|
11
11
|
|
|
12
|
-
`oxlint` (>=1.
|
|
12
|
+
`oxlint` (>=1.89.0), `oxlint-tsgolint` (>=7.0.2004), `eslint` (9 or 10),
|
|
13
13
|
`typescript` (5 or 6) are optional peers. Install only the tools you use. Formatting is `bun fmt` (Bun 1.4.4 or newer), set in `bunfig.toml`: see [Formatting](#formatting). Keep the
|
|
14
14
|
ESLint config `.mjs`: a TypeScript one (`.mts`) makes ESLint require `jiti`, one more dependency. A
|
|
15
15
|
project that only wants the full ESLint preset installs `eslint` and skips the oxc tools.
|
|
@@ -95,19 +95,21 @@ Every IGNIS package and example does.
|
|
|
95
95
|
| Flag | Base value | Why |
|
|
96
96
|
| :--- | :--- | :--- |
|
|
97
97
|
| `experimentalDecorators` | `true` | `@inject`, `@controller`, `@repository` and the other decorators need it |
|
|
98
|
-
| `emitDecoratorMetadata` | `true` | Optional - restate it only if your code reads `design:*` metadata. IGNIS reads `design:paramtypes` once, to validate a `@repository` constructor, and skips the check when the metadata is absent. Under Bun it turns an interface-typed constructor parameter into a runtime import (`Export named 'X' not found`), so import such names with `import type`; `
|
|
98
|
+
| `emitDecoratorMetadata` | `true` | Optional - restate it only if your code reads `design:*` metadata. IGNIS reads `design:paramtypes` once, to validate a `@repository` constructor, and skips the check when the metadata is absent. Under Bun it turns an interface-typed constructor parameter into a runtime import (`Export named 'X' not found`), so import such names with `import type`; `bun check` (TS1272; the base tsconfig sets `isolatedModules`) finds most of them, loading `src/index.ts` under Bun the rest |
|
|
99
99
|
| `useDefineForClassFields` | `false` | Class fields are assigned, not defined, so a subclass field initializer does not shadow a value the base constructor set |
|
|
100
100
|
|
|
101
101
|
## Entry points
|
|
102
102
|
|
|
103
103
|
| Entry point | What it gives |
|
|
104
104
|
| :--- | :--- |
|
|
105
|
-
| `@venizia/dev-configs` |
|
|
105
|
+
| `@venizia/dev-configs` | `/compilers` and `/linters`, re-exported. Not `/checks` or `/testing` |
|
|
106
106
|
| `@venizia/dev-configs/compilers` | `BunCompiler` |
|
|
107
107
|
| `@venizia/dev-configs/testing` | `RejectionHelper` (`rejectionOf`, `expectRejection`), `SpawnHelper` (`spawnSyncBounded`), `RepoTmp` (`findRoot`, `apply`) - test helpers (imports `bun:test`; tests only) |
|
|
108
|
-
| `@venizia/dev-configs/
|
|
108
|
+
| `@venizia/dev-configs/testing/tmpdir-preload` | A bunfig test preload: a bare `bun test` keeps its temp folders in the repository (calls `RepoTmp.apply()`) |
|
|
109
|
+
| `@venizia/dev-configs/checks` | The engines behind `devz check <name>`: catalog, module cycles, purity, split report and the test-trimming checks. Bun-only tooling, never import it from browser code |
|
|
110
|
+
| `@venizia/dev-configs/linters` | `oxlintConfigs`, `OxlintConfigs`, `BrowserOxlintConfigs`, `ReactOxlintConfigs`, `LintIgnore`, `namingConventionConfigs`, `reactNamingConventionConfigs`, `houseConfigs`, `reactHouseConfigs`, `eslintConfigs`, `paddingConfigs`, the rule classes and their types |
|
|
109
111
|
| `@venizia/dev-configs/linters/oxlint` | `oxlintConfigs`, `OxlintConfigs`, `IOxlintPresetOptions`, `BrowserOxlintConfigs`, `ReactOxlintConfigs`, `LintIgnore`, the rule classes and their types: everything an oxlint config needs, and nothing that loads ESLint. Loads in milliseconds: `/linters` also loads ESLint and its plugins, which an oxlint config never uses |
|
|
110
|
-
| `@venizia/dev-configs/tsconfig.base.json` | Target and lib ES2025, `module`
|
|
112
|
+
| `@venizia/dev-configs/tsconfig.base.json` | Target and lib ES2025, `module` esnext with `moduleResolution` bundler, strict mode (`noImplicitAny` and `useUnknownInCatchVariables` on) with `strictPropertyInitialization` off (DI-injected properties have no initializer), `noEmitOnError`, tests excluded |
|
|
111
113
|
| `@venizia/dev-configs/tsconfig.common.json` | Extends the base and restates `module` as `esnext` and `moduleResolution` as `bundler` |
|
|
112
114
|
| `@venizia/dev-configs/tsconfig.browser.json` | Extends the base for a browser library built with a bundler: `module` ESNext, `moduleResolution` bundler, lib ES2025 + `DOM` + `DOM.Iterable`, `types: []` so no Bun types reach `dist` |
|
|
113
115
|
| `@venizia/dev-configs/tsconfig.react.json` | Extends `tsconfig.browser.json` and sets `jsx: react-jsx` |
|
|
@@ -123,7 +125,7 @@ Every IGNIS package and example does.
|
|
|
123
125
|
becomes a runtime import when Bun runs a decorated class's source, and loading fails with
|
|
124
126
|
`Export named 'X' not found`. `oxlint --fix` rewrites them.
|
|
125
127
|
|
|
126
|
-
oxlint
|
|
128
|
+
oxlint does not read decorator metadata, so it also rewrites the import of a decorated
|
|
127
129
|
constructor parameter's class to `import { type X }`. tsc then emits `Function` (or `Object` under Bun)
|
|
128
130
|
as that parameter's `design:paramtypes` entry. IGNIS never injects by that entry - `@inject` names its
|
|
129
131
|
key, and `@repository` skips `Object` and `Function` - so nothing breaks. Code that does read
|
|
@@ -142,9 +144,10 @@ Not ported:
|
|
|
142
144
|
|
|
143
145
|
#### lenientFallback
|
|
144
146
|
|
|
145
|
-
`prefer-nullish-coalescing` flags `||` on
|
|
146
|
-
`
|
|
147
|
-
|
|
147
|
+
`prefer-nullish-coalescing` flags `||` on a nullable left side, because `||` also swallows a real `0`
|
|
148
|
+
or `false`. `||` on a string is allowed in every preset: `opts.name?.trim() || 'guest'` is an
|
|
149
|
+
intentional empty-string fallback, and `??` would keep the `''`. A project where `0` falls back on
|
|
150
|
+
purpose too opts in with one line:
|
|
148
151
|
|
|
149
152
|
```ts
|
|
150
153
|
// .configs/lints/oxlint.config.mts
|
|
@@ -160,8 +163,9 @@ booleans. `BrowserOxlintConfigs.create()` and `ReactOxlintConfigs.create()` take
|
|
|
160
163
|
|
|
161
164
|
### houseConfigs and the house rules
|
|
162
165
|
|
|
163
|
-
`houseConfigs` is `namingConventionConfigs` plus the house rules oxlint cannot express
|
|
164
|
-
|
|
166
|
+
`houseConfigs` is `namingConventionConfigs` plus the house rules oxlint cannot express, the four async style rules
|
|
167
|
+
and the blank-line padding rules (`paddingConfigs`, below); `reactHouseConfigs` is the same over
|
|
168
|
+
`reactNamingConventionConfigs`, plus the React rules. The house rules ship as the ESLint plugin
|
|
165
169
|
`houseEslintPlugin`, registered as `venizia`:
|
|
166
170
|
|
|
167
171
|
| Class | Rule | Default | What it enforces |
|
|
@@ -176,10 +180,25 @@ booleans. `BrowserOxlintConfigs.create()` and `ReactOxlintConfigs.create()` take
|
|
|
176
180
|
with `[ConstClassValuesRule.NAME]: ConstClassValuesRule.build({ severity: 'error' })`. The 5-parameter
|
|
177
181
|
limit (V-C-02) is `venizia/max-params-own`, an error.
|
|
178
182
|
|
|
183
|
+
#### Blank-line padding
|
|
184
|
+
|
|
185
|
+
`paddingConfigs` holds two `@stylistic` rules, both `error`, on `.ts`, `.tsx`, `.mts` and `.cts` files.
|
|
186
|
+
`houseConfigs`, `reactHouseConfigs` and `eslintConfigs` carry it. It has no parser of its own: it rides on the
|
|
187
|
+
TypeScript parser of `namingConventionConfigs` or `eslintConfigs`. oxlint has none of these rules, so a
|
|
188
|
+
project that lints with oxlint alone gets no padding check. `devz lint --fix` writes the blank lines.
|
|
189
|
+
|
|
190
|
+
| Rule | What it enforces |
|
|
191
|
+
| :--- | :--- |
|
|
192
|
+
| `@stylistic/padding-line-between-statements` | A blank line after the imports (none needed between two imports), before a `return`, and around a block-like statement (a statement that ends in a block, such as `if`, `for`, `while`, `switch`, `try`, a function declaration or a bare block). Stacked `case` and `default` labels stay together |
|
|
193
|
+
| `@stylistic/lines-between-class-members` | A blank line between class members, except after a one-line member, so a run of one-line properties stays together |
|
|
194
|
+
|
|
195
|
+
Turn one off after the preset with `'off'`. See the
|
|
196
|
+
[changelog](https://ignis.venizia.ai/changelogs/2026-11-04-blank-line-padding-rules).
|
|
197
|
+
|
|
179
198
|
### namingConventionConfigs
|
|
180
199
|
|
|
181
200
|
`namingConventionConfigs` (type `Linter.Config[]`) sets only `@typescript-eslint/naming-convention`, with
|
|
182
|
-
its
|
|
201
|
+
its 16 selectors. It targets `.ts`, `.tsx`, `.mts` and `.cts`, and ignores `dist`, `build`,
|
|
183
202
|
`coverage`, `*.d.ts` and plain JavaScript. ESLint does not report unused disable comments in this
|
|
184
203
|
config, because oxlint owns the other rules.
|
|
185
204
|
|
|
@@ -239,9 +258,8 @@ flavor = "oxfmt"
|
|
|
239
258
|
|
|
240
259
|
### eslintConfigs
|
|
241
260
|
|
|
242
|
-
`eslintConfigs`
|
|
243
|
-
|
|
244
|
-
conventions, `curly`, plus these IGNIS rules (the node-protocol check runs in `oxlintConfigs` only):
|
|
261
|
+
`eslintConfigs` is the full ESLint preset: ESLint recommended, typescript-eslint, naming
|
|
262
|
+
conventions, `curly`, the padding rules, plus these IGNIS rules (the node-protocol check runs in `oxlintConfigs` only):
|
|
245
263
|
|
|
246
264
|
| Rule | Setting |
|
|
247
265
|
| :--- | :--- |
|
|
@@ -289,7 +307,13 @@ table above, as strict as the base. `react/no-deprecated` is left out: oxlint ha
|
|
|
289
307
|
Both React presets run the same fifteen `jsx-a11y` rules, including the six that need a human
|
|
290
308
|
decision (`click-events-have-key-events`, `no-static-element-interactions`,
|
|
291
309
|
`no-noninteractive-element-interactions`, `label-has-associated-control`, `heading-has-content`,
|
|
292
|
-
`anchor-is-valid`). `reactHouseConfigs` adds
|
|
310
|
+
`anchor-is-valid`). `reactHouseConfigs` adds three house rules oxlint has no port of:
|
|
311
|
+
|
|
312
|
+
| Rule | What it enforces |
|
|
313
|
+
| :--- | :--- |
|
|
314
|
+
| `venizia/no-leaked-render` | See the table above. On JSX files |
|
|
315
|
+
| `venizia/no-async-hook-callback` | A hook never gets an async function. On all source files |
|
|
316
|
+
| `venizia/effect-cleanup-consistency` | An effect callback returns a cleanup on every path or on none. On all source files |
|
|
293
317
|
|
|
294
318
|
The presets start strict. An application that wants less overrides the rule after the preset:
|
|
295
319
|
|
|
@@ -360,6 +384,31 @@ await BunCompiler.compile({
|
|
|
360
384
|
});
|
|
361
385
|
```
|
|
362
386
|
|
|
387
|
+
## The devz command
|
|
388
|
+
|
|
389
|
+
The package installs a `devz` binary. Run `devz --help` for the list, and `devz clean --help`,
|
|
390
|
+
`devz check --help` or `devz codemod --help` for the options of one command. A usage error in a command exits 2.
|
|
391
|
+
|
|
392
|
+
| Command | What it does |
|
|
393
|
+
| :--- | :--- |
|
|
394
|
+
| `devz lint [--fix] [files]` | Runs oxlint, ESLint and `bun fmt` from `.configs/lints/` and `.configs/formatters/.ignore`, and stops at the first tool that fails. With no file it checks the project; with files it handles only those, as a pre-commit hook passes them. `--fix` writes |
|
|
395
|
+
| `devz check purity --claims <file> [package] [--json]` | Probes every entry claimed browser-pure. Needs a build |
|
|
396
|
+
| `devz check module-cycles <dir> [--max <n>]` | Lists the import cycles of a built ESM folder; exits 1 when there are more than `--max` |
|
|
397
|
+
| `devz check split-report [--dist <dir>] [folder...]` | Reports hub files, stray types, missing barrels, long files and cycles. Never a gate |
|
|
398
|
+
| `devz check catalog [--glob <pattern>]... [--pinned <file>]... [--preset-prefix <prefix>]` | Guards dependency ranges against the root `workspaces.catalog` |
|
|
399
|
+
| `devz clean` | Removes `dist`, `node_modules/.cache` and the `*.tsbuildinfo` files next to the tsconfig. It takes no argument |
|
|
400
|
+
| `devz codemod <name> [paths...]` | Rewrites source files. A dry run unless `--write`; `--check` exits 1 while a rewrite remains |
|
|
401
|
+
|
|
402
|
+
`devz check` also runs the four tools of the test-trimming method: `test-weight`, `test-dead-code`,
|
|
403
|
+
`test-mutate` and `test-controls`.
|
|
404
|
+
|
|
405
|
+
The codemods are `drop-redundant-casts` (removes `as X` casts the compiler no longer needs),
|
|
406
|
+
`const-classes` (turns a string-literal union into a const class), `async-style` (applies the async style
|
|
407
|
+
fixers and lists the rest), `namespace-functions` (moves calls of a function that moved into a class to the
|
|
408
|
+
class form), `connector-imports` (moves `@venizia/ignis/<connector sub-path>` imports to
|
|
409
|
+
`@venizia/ignis-connectors`) and `env-get` (strips the type arguments of `applicationEnvironment.get()`
|
|
410
|
+
for the string-reading `get()`; the receiver is a name the call's scope resolves to an import of `applicationEnvironment` or `AppEnvs` from the store module, or a const initialised from one; every other `get<...>(key)` call is listed as skipped, and a call it cannot place as manual, with its file and line) and `any-aliases` (replaces the removed `AnyType` and `AnyObject` aliases by what they stood for, `any` and `Record<string | symbol | number, any>`, so no type changes, and drops them from the imports; `--strict` writes `unknown` and `Record<string, unknown>` instead; it reads imports from `@venizia/ignis`, `-helpers`, `-inversion`, and from `@venizia/ardor` and `-kernel`, which re-exported them).
|
|
411
|
+
|
|
363
412
|
## Where it sits
|
|
364
413
|
|
|
365
414
|
The root of the chain, with no IGNIS dependency: **dev-configs** -> inversion -> {filter, helpers}
|
package/dist/checks/catalog.d.ts
CHANGED
|
@@ -9,10 +9,19 @@ export interface ICatalogProblem {
|
|
|
9
9
|
file: string;
|
|
10
10
|
message: string;
|
|
11
11
|
}
|
|
12
|
+
/** Options of `CatalogCheck.find`: which manifests to check besides the workspace packages' `package.json`, and how presets and pinned files are treated. */
|
|
12
13
|
export interface ICatalogOptions {
|
|
13
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* The repository root: where the root `package.json` and the globs resolve.
|
|
16
|
+
*
|
|
17
|
+
* @default process.cwd()
|
|
18
|
+
*/
|
|
14
19
|
root?: string;
|
|
15
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* Manifests to check, beside the workspace packages' `package.json`. A glob relative to the root.
|
|
22
|
+
*
|
|
23
|
+
* @default []
|
|
24
|
+
*/
|
|
16
25
|
globs?: string[];
|
|
17
26
|
/**
|
|
18
27
|
* Files that are not published manifests but carry `dependencies` and `devDependencies` the
|
|
@@ -24,9 +33,12 @@ export interface ICatalogOptions {
|
|
|
24
33
|
/**
|
|
25
34
|
* Manifests outside the workspace (a wiki with its own lockfile): `catalog:` does not resolve
|
|
26
35
|
* there, so a catalogued dependency must be pinned to exactly the catalog's version instead.
|
|
36
|
+
*
|
|
37
|
+
* @default []
|
|
27
38
|
*/
|
|
28
39
|
pinned?: string[];
|
|
29
40
|
}
|
|
41
|
+
/** Result of `CatalogCheck.find`: every problem found, how many catalog entries exist and how many a manifest references. */
|
|
30
42
|
export interface ICatalogReport {
|
|
31
43
|
problems: ICatalogProblem[];
|
|
32
44
|
entries: number;
|
|
@@ -34,6 +46,7 @@ export interface ICatalogReport {
|
|
|
34
46
|
/** Set when there is no `workspaces.catalog` to check against. */
|
|
35
47
|
noCatalog: boolean;
|
|
36
48
|
}
|
|
49
|
+
/** Checks that `catalog:` references and version ranges in package manifests agree with the root `workspaces.catalog`. */
|
|
37
50
|
export declare class CatalogCheck {
|
|
38
51
|
/** Reads the root catalog and every manifest the options name, and reports everything wrong with their ranges. */
|
|
39
52
|
static find(opts?: ICatalogOptions): Promise<ICatalogReport>;
|
package/dist/checks/catalog.js
CHANGED
|
@@ -7,6 +7,7 @@ const node_path_1 = require("node:path");
|
|
|
7
7
|
/** `peerDependencies` are compatibility statements for consumers and stay deliberately looser than the install range. */
|
|
8
8
|
const CATALOGUED_BLOCKS = ['dependencies', 'devDependencies'];
|
|
9
9
|
const DEFAULT_GLOB = 'packages/*/package.json';
|
|
10
|
+
/** Checks that `catalog:` references and version ranges in package manifests agree with the root `workspaces.catalog`. */
|
|
10
11
|
class CatalogCheck {
|
|
11
12
|
/** Reads the root catalog and every manifest the options name, and reports everything wrong with their ranges. */
|
|
12
13
|
static async find(opts = {}) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../src/checks/catalog.ts"],"names":[],"mappings":";;;AAAA,6BAA2B;AAC3B,qCAAqC;AACrC,yCAAiC;
|
|
1
|
+
{"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../src/checks/catalog.ts"],"names":[],"mappings":";;;AAAA,6BAA2B;A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CAAC;YAED,QAAQ,CAAC,IAAI,CAAC;gBACZ,IAAI,EAAE,cAAc;gBACpB,OAAO,EAAE,kBAAkB,GAAG,2CAA2C;aAC1E,CAAC,CAAC;QACL,CAAC;QAED,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,UAAU,EAAE,UAAU,CAAC,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IAClG,CAAC;CACF;AA3GD,oCA2GC","sourcesContent":["import { Glob } from 'bun';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/**\n * Guards dependency versions against the root `workspaces.catalog`.\n *\n * A catalogued dep is referenced as `catalog:` and resolved at publish time by `bun publish`, which\n * substitutes the real range while packing. `npm publish` does NOT - it ships `catalog:` verbatim\n * and the manifest is unresolvable for every consumer, which is how 0.1.1-9 / -6 / -4 broke.\n */\nexport interface ICatalogProblem {\n file: string;\n message: string;\n}\n\n/** Options of `CatalogCheck.find`: which manifests to check besides the workspace packages' `package.json`, and how presets and pinned files are treated. */\nexport interface ICatalogOptions {\n /**\n * The repository root: where the root `package.json` and the globs resolve.\n *\n * @default process.cwd()\n */\n root?: string;\n\n /**\n * Manifests to check, beside the workspace packages' `package.json`. A glob relative to the root.\n *\n * @default []\n */\n globs?: string[];\n\n /**\n * Files that are not published manifests but carry `dependencies` and `devDependencies` the\n * release resolves (a VULCAN preset): `catalog:` is allowed in their `peerDependencies`, because a\n * library preset gives one name one catalog range. A file belongs here when its path starts with\n * this prefix, for example `presets/`.\n */\n presetPrefix?: string;\n\n /**\n * Manifests outside the workspace (a wiki with its own lockfile): `catalog:` does not resolve\n * there, so a catalogued dependency must be pinned to exactly the catalog's version instead.\n *\n * @default []\n */\n pinned?: string[];\n}\n\n/** Result of `CatalogCheck.find`: every problem found, how many catalog entries exist and how many a manifest references. */\nexport interface ICatalogReport {\n problems: ICatalogProblem[];\n entries: number;\n referenced: number;\n\n /** Set when there is no `workspaces.catalog` to check against. */\n noCatalog: boolean;\n}\n\n/** `peerDependencies` are compatibility statements for consumers and stay deliberately looser than the install range. */\nconst CATALOGUED_BLOCKS = ['dependencies', 'devDependencies'] as const;\n\nconst DEFAULT_GLOB = 'packages/*/package.json';\n\ninterface IManifest {\n workspaces?: { catalog?: Record<string, string> };\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n}\n\n/** Checks that `catalog:` references and version ranges in package manifests agree with the root `workspaces.catalog`. */\nexport class CatalogCheck {\n /** Reads the root catalog and every manifest the options name, and reports everything wrong with their ranges. */\n static async find(opts: ICatalogOptions = {}): Promise<ICatalogReport> {\n const { root = process.cwd(), globs = [], presetPrefix, pinned = [] } = opts;\n const result = await Bun.file(join(root, 'package.json')).text();\n const rootJson: IManifest = JSON.parse(result);\n const catalog: Record<string, string> = rootJson.workspaces?.catalog ?? {};\n\n if (Object.keys(catalog).length === 0) {\n return { problems: [], entries: 0, referenced: 0, noCatalog: true };\n }\n\n const problems: ICatalogProblem[] = [];\n const referenced = new Set<string>();\n const presentPinned = pinned.filter((file) => existsSync(join(root, file)));\n\n const files = new Set<string>();\n\n for (const pattern of [DEFAULT_GLOB, ...globs]) {\n for await (const file of new Glob(pattern).scan(root)) {\n files.add(file);\n }\n }\n\n for (const file of [...files, ...presentPinned]) {\n let json: IManifest;\n\n try {\n const result2 = await Bun.file(join(root, file)).text();\n json = JSON.parse(result2);\n } catch (error) {\n problems.push({\n file,\n message: `invalid JSON - ${error instanceof Error ? error.message : error}`,\n });\n continue;\n }\n\n const isPinned = presentPinned.includes(file);\n\n for (const block of CATALOGUED_BLOCKS) {\n const entriesList = Object.entries(json[block] ?? {});\n\n for (const [dep, range] of entriesList) {\n if (!(dep in catalog)) {\n continue;\n }\n\n referenced.add(dep);\n\n if (isPinned) {\n if (range !== catalog[dep]) {\n problems.push({\n file,\n message: `${block}.${dep} is \"${range}\" but the catalog pins \"${catalog[dep]}\" - this project is outside the workspace, so pin exactly that`,\n });\n }\n\n continue;\n }\n\n if (range === 'catalog:') {\n continue;\n }\n\n problems.push({\n file,\n message: `${block}.${dep} is \"${range}\" but the catalog owns it - use \"catalog:\" (catalog pins ${catalog[dep]})`,\n });\n }\n }\n\n // A preset is not a published manifest: its markers are resolved by the release, and the library kind gives a\n // name one catalog range, so a lib's peer takes the same marker as its dev dependency.\n const isPreset = presetPrefix !== undefined && file.startsWith(presetPrefix);\n\n // A peer resolved from the catalog would collapse to the exact install range, losing the looseness that makes it a peer.\n const peerEntries = Object.entries(json.peerDependencies ?? {});\n\n for (const [dep, range] of peerEntries) {\n if (range !== 'catalog:' || isPreset) {\n continue;\n }\n\n problems.push({\n file,\n message: `peerDependencies.${dep} uses \"catalog:\" - a peer range must stay hand-authored and looser than the install range`,\n });\n }\n }\n\n // A catalog entry nobody references is dead weight that will drift out of date unnoticed.\n const catalogKeys = Object.keys(catalog);\n\n for (const dep of catalogKeys) {\n if (referenced.has(dep)) {\n continue;\n }\n\n problems.push({\n file: 'package.json',\n message: `catalog entry \"${dep}\" is referenced by no workspace - drop it`,\n });\n }\n\n return { problems, entries: catalogKeys.length, referenced: referenced.size, noCatalog: false };\n }\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/** The relative-import graph of a built ESM directory; build it with `fromDirectory` and read its import cycles with `cycles()`. */
|
|
1
2
|
export declare class ModuleGraph {
|
|
2
3
|
private readonly root;
|
|
3
4
|
private readonly edges;
|
|
@@ -10,6 +11,7 @@ export declare class ModuleGraph {
|
|
|
10
11
|
private static walk;
|
|
11
12
|
private static resolveRelative;
|
|
12
13
|
}
|
|
14
|
+
/** The `devz check module-cycles` command: prints the import cycles of a built ESM directory and returns the exit code. */
|
|
13
15
|
export declare class ModuleCyclesCheck {
|
|
14
16
|
/**
|
|
15
17
|
* `devz check module-cycles <dir> [--max <n>]`: prints the cycles of a built ESM directory and
|
|
@@ -12,6 +12,7 @@ const node_util_1 = require("node:util");
|
|
|
12
12
|
// Only match import/export statements at the start of a line (after optional
|
|
13
13
|
// whitespace), ignoring matches inside comments or string literals.
|
|
14
14
|
const IMPORT_PATTERN = /^\s*(?:import|export)\s[^;]*?from\s+'([^']+)'|^\s*import\s+'([^']+)'/gm;
|
|
15
|
+
/** The relative-import graph of a built ESM directory; build it with `fromDirectory` and read its import cycles with `cycles()`. */
|
|
15
16
|
class ModuleGraph {
|
|
16
17
|
constructor(root, edges) {
|
|
17
18
|
this.root = root;
|
|
@@ -113,6 +114,7 @@ class ModuleGraph {
|
|
|
113
114
|
}
|
|
114
115
|
}
|
|
115
116
|
exports.ModuleGraph = ModuleGraph;
|
|
117
|
+
/** The `devz check module-cycles` command: prints the import cycles of a built ESM directory and returns the exit code. */
|
|
116
118
|
class ModuleCyclesCheck {
|
|
117
119
|
/**
|
|
118
120
|
* `devz check module-cycles <dir> [--max <n>]`: prints the cycles of a built ESM directory and
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"module-cycles.js","sourceRoot":"","sources":["../../src/checks/module-cycles.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,qCAA0E;AAC1E,yCAA6D;AAC7D,yCAAsC;AAEtC,6EAA6E;AAC7E,oEAAoE;AACpE,MAAM,cAAc,GAAG,wEAAwE,CAAC;AAEhG,MAAa,WAAW;IACtB,YACmB,IAAY,EACZ,KAA4B;QAD5B,SAAI,GAAJ,IAAI,CAAQ;QACZ,UAAK,GAAL,KAAK,CAAuB;IAC5C,CAAC;IAEJ,MAAM,CAAC,aAAa,CAAC,IAAqB;QACxC,MAAM,IAAI,GAAG,IAAA,mBAAO,EAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,KAAK,GAAG,WAAW,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC;QAC9C,MAAM,KAAK,GAAG,IAAI,GAAG,EAAoB,CAAC;QAE1C,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,MAAM,IAAI,GAAG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OAAO,CAAC,CAAC;YACX,CAAC;YAED,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC3B,CAAC;QAED,MAAM,MAAM,GAAG,WAAW,CAAC,aAAa,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC;QAC3D,KAAK,CAAC,GAAG,GAAG,KAAK,MAAM,CAAC,MAAM,WAAW,CAAC,CAAC;QAE3C,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;YAC3B,KAAK,CAAC,OAAO,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;QACtC,CAAC;QAED,OAAO,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACrC,CAAC;CACF;AA9CD,8CA8CC","sourcesContent":["/**\n * Lists import cycles in a built ESM directory. bun turns every member of a\n * cycle into a lazy initializer, and a barrel `export *` over such a member\n * can leave its exports undefined. Usage: devz check module-cycles packages/helpers/dist/esm [--max 0]\n */\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { dirname, join, relative, resolve } from 'node:path';\nimport { parseArgs } from 'node:util';\n\n// Only match import/export statements at the start of a line (after optional\n// whitespace), ignoring matches inside comments or string literals.\nconst IMPORT_PATTERN = /^\\s*(?:import|export)\\s[^;]*?from\\s+'([^']+)'|^\\s*import\\s+'([^']+)'/gm;\n\nexport class ModuleGraph {\n private constructor(\n private readonly root: string,\n private readonly edges: Map<string, string[]>,\n ) {}\n\n static fromDirectory(opts: { dir: string }): ModuleGraph {\n const root = resolve(opts.dir);\n const files = ModuleGraph.walk({ dir: root });\n const edges = new Map<string, string[]>();\n\n for (const file of files) {\n const text = readFileSync(file, 'utf8');\n const targets = new Set<string>();\n const matches = text.matchAll(IMPORT_PATTERN);\n\n for (const match of matches) {\n const target = ModuleGraph.resolveRelative({\n from: file,\n specifier: match[1] ?? match[2],\n });\n\n if (target) {\n targets.add(target);\n }\n }\n\n edges.set(file, [...targets]);\n }\n\n return new ModuleGraph(root, edges);\n }\n\n /** Strongly connected components with more than one member, as repo-relative paths. */\n cycles(): string[][] {\n let index = 0;\n const stack: string[] = [];\n const onStack = new Set<string>();\n const indices = new Map<string, number>();\n const lowLinks = new Map<string, number>();\n const found: string[][] = [];\n\n const visit = (node: string): void => {\n indices.set(node, index);\n lowLinks.set(node, index);\n index++;\n stack.push(node);\n onStack.add(node);\n\n const nexts = this.edges.get(node) ?? [];\n\n for (const next of nexts) {\n if (!indices.has(next)) {\n visit(next);\n lowLinks.set(node, Math.min(lowLinks.get(node)!, lowLinks.get(next)!));\n } else if (onStack.has(next)) {\n lowLinks.set(node, Math.min(lowLinks.get(node)!, indices.get(next)!));\n }\n }\n\n if (lowLinks.get(node) !== indices.get(node)) {\n return;\n }\n\n const component: string[] = [];\n let member: string;\n\n do {\n member = stack.pop()!;\n onStack.delete(member);\n component.push(relative(this.root, member));\n } while (member !== node);\n\n if (component.length > 1) {\n found.push(component.sort());\n }\n };\n\n const edgesKeys = this.edges.keys();\n\n for (const node of edgesKeys) {\n if (!indices.has(node)) {\n visit(node);\n }\n }\n\n return found;\n }\n\n private static walk(opts: { dir: string }): string[] {\n const out: string[] = [];\n const dirEntries = readdirSync(opts.dir);\n\n for (const name of dirEntries) {\n const full = join(opts.dir, name);\n\n if (statSync(full).isDirectory()) {\n out.push(...ModuleGraph.walk({ dir: full }));\n } else if (full.endsWith('.js')) {\n out.push(full);\n }\n }\n\n return out;\n }\n\n private static resolveRelative(opts: { from: string; specifier: string }): string | undefined {\n if (!opts.specifier.startsWith('.')) {\n return undefined;\n }\n\n const base = resolve(dirname(opts.from), opts.specifier);\n const candidates = [base, `${base}.js`, join(base, 'index.js')];\n\n for (const candidate of candidates) {\n if (existsSync(candidate) && statSync(candidate).isFile()) {\n return candidate;\n }\n }\n\n return undefined;\n }\n}\n\nexport class ModuleCyclesCheck {\n /**\n * `devz check module-cycles <dir> [--max <n>]`: prints the cycles of a built ESM directory and\n * returns 1 when there are more than `max` (no bound by default), 2 on a usage error.\n */\n static run(opts: {\n args: string[];\n print: (line: string) => void;\n printError: (line: string) => void;\n }): number {\n const { args, print, printError } = opts;\n const { positionals, values } = parseArgs({\n args,\n allowPositionals: true,\n options: { max: { type: 'string' }, dist: { type: 'string' } },\n });\n const dir = values.dist ?? positionals[0];\n const usage = 'usage: devz check module-cycles <built ESM dir> [--max <n>]';\n\n if (!dir) {\n printError(usage);\n\n return 2;\n }\n\n let max = Number.POSITIVE_INFINITY;\n\n if (values.max !== undefined) {\n if (!/^\\d+$/.test(values.max)) {\n printError(usage);\n\n return 2;\n }\n\n max = Number(values.max);\n }\n\n const cycles = ModuleGraph.fromDirectory({ dir }).cycles();\n print(`${dir}: ${cycles.length} cycle(s)`);\n\n for (const cycle of cycles) {\n print(` - ${cycle.join(' <-> ')}`);\n }\n\n return cycles.length > max ? 1 : 0;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"module-cycles.js","sourceRoot":"","sources":["../../src/checks/module-cycles.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,qCAA0E;AAC1E,yCAA6D;AAC7D,yCAAsC;AAEtC,6EAA6E;AAC7E,oEAAoE;AACpE,MAAM,cAAc,GAAG,wEAAwE,CAAC;AAEhG,oIAAoI;AACpI,MAAa,WAAW;IACtB,YACmB,IAAY,EACZ,KAA4B;QAD5B,SAAI,GAAJ,IAAI,CAAQ;QACZ,UAAK,GAAL,KAAK,CAAuB;IAC5C,CAAC;IAEJ,MAAM,CAAC,aAAa,CAAC,IAAqB;QACxC,MAAM,IAAI,GAAG,IAAA,mBAAO,EAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,KAAK,GAAG,WAAW,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC;QAC9C,MAAM,KAAK,GAAG,IAAI,GAAG,EAAoB,CAAC;QAE1C,KAAK,MAAM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GAAG,CAAC,EAAE,CAAC;gBAC9B,UAAU,CAAC,KAAK,CAAC,CAAC;gBAElB,OAAO,CAAC,CAAC;YACX,CAAC;YAED,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC3B,CAAC;QAED,MAAM,MAAM,GAAG,WAAW,CAAC,aAAa,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC;QAC3D,KAAK,CAAC,GAAG,GAAG,KAAK,MAAM,CAAC,MAAM,WAAW,CAAC,CAAC;QAE3C,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;YAC3B,KAAK,CAAC,OAAO,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;QACtC,CAAC;QAED,OAAO,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACrC,CAAC;CACF;AA9CD,8CA8CC","sourcesContent":["/**\n * Lists import cycles in a built ESM directory. bun turns every member of a\n * cycle into a lazy initializer, and a barrel `export *` over such a member\n * can leave its exports undefined. Usage: devz check module-cycles packages/helpers/dist/esm [--max 0]\n */\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { dirname, join, relative, resolve } from 'node:path';\nimport { parseArgs } from 'node:util';\n\n// Only match import/export statements at the start of a line (after optional\n// whitespace), ignoring matches inside comments or string literals.\nconst IMPORT_PATTERN = /^\\s*(?:import|export)\\s[^;]*?from\\s+'([^']+)'|^\\s*import\\s+'([^']+)'/gm;\n\n/** The relative-import graph of a built ESM directory; build it with `fromDirectory` and read its import cycles with `cycles()`. */\nexport class ModuleGraph {\n private constructor(\n private readonly root: string,\n private readonly edges: Map<string, string[]>,\n ) {}\n\n static fromDirectory(opts: { dir: string }): ModuleGraph {\n const root = resolve(opts.dir);\n const files = ModuleGraph.walk({ dir: root });\n const edges = new Map<string, string[]>();\n\n for (const file of files) {\n const text = readFileSync(file, 'utf8');\n const targets = new Set<string>();\n const matches = text.matchAll(IMPORT_PATTERN);\n\n for (const match of matches) {\n const target = ModuleGraph.resolveRelative({\n from: file,\n specifier: match[1] ?? match[2],\n });\n\n if (target) {\n targets.add(target);\n }\n }\n\n edges.set(file, [...targets]);\n }\n\n return new ModuleGraph(root, edges);\n }\n\n /** Strongly connected components with more than one member, as repo-relative paths. */\n cycles(): string[][] {\n let index = 0;\n const stack: string[] = [];\n const onStack = new Set<string>();\n const indices = new Map<string, number>();\n const lowLinks = new Map<string, number>();\n const found: string[][] = [];\n\n const visit = (node: string): void => {\n indices.set(node, index);\n lowLinks.set(node, index);\n index++;\n stack.push(node);\n onStack.add(node);\n\n const nexts = this.edges.get(node) ?? [];\n\n for (const next of nexts) {\n if (!indices.has(next)) {\n visit(next);\n lowLinks.set(node, Math.min(lowLinks.get(node)!, lowLinks.get(next)!));\n } else if (onStack.has(next)) {\n lowLinks.set(node, Math.min(lowLinks.get(node)!, indices.get(next)!));\n }\n }\n\n if (lowLinks.get(node) !== indices.get(node)) {\n return;\n }\n\n const component: string[] = [];\n let member: string;\n\n do {\n member = stack.pop()!;\n onStack.delete(member);\n component.push(relative(this.root, member));\n } while (member !== node);\n\n if (component.length > 1) {\n found.push(component.sort());\n }\n };\n\n const edgesKeys = this.edges.keys();\n\n for (const node of edgesKeys) {\n if (!indices.has(node)) {\n visit(node);\n }\n }\n\n return found;\n }\n\n private static walk(opts: { dir: string }): string[] {\n const out: string[] = [];\n const dirEntries = readdirSync(opts.dir);\n\n for (const name of dirEntries) {\n const full = join(opts.dir, name);\n\n if (statSync(full).isDirectory()) {\n out.push(...ModuleGraph.walk({ dir: full }));\n } else if (full.endsWith('.js')) {\n out.push(full);\n }\n }\n\n return out;\n }\n\n private static resolveRelative(opts: { from: string; specifier: string }): string | undefined {\n if (!opts.specifier.startsWith('.')) {\n return undefined;\n }\n\n const base = resolve(dirname(opts.from), opts.specifier);\n const candidates = [base, `${base}.js`, join(base, 'index.js')];\n\n for (const candidate of candidates) {\n if (existsSync(candidate) && statSync(candidate).isFile()) {\n return candidate;\n }\n }\n\n return undefined;\n }\n}\n\n/** The `devz check module-cycles` command: prints the import cycles of a built ESM directory and returns the exit code. */\nexport class ModuleCyclesCheck {\n /**\n * `devz check module-cycles <dir> [--max <n>]`: prints the cycles of a built ESM directory and\n * returns 1 when there are more than `max` (no bound by default), 2 on a usage error.\n */\n static run(opts: {\n args: string[];\n print: (line: string) => void;\n printError: (line: string) => void;\n }): number {\n const { args, print, printError } = opts;\n const { positionals, values } = parseArgs({\n args,\n allowPositionals: true,\n options: { max: { type: 'string' }, dist: { type: 'string' } },\n });\n const dir = values.dist ?? positionals[0];\n const usage = 'usage: devz check module-cycles <built ESM dir> [--max <n>]';\n\n if (!dir) {\n printError(usage);\n\n return 2;\n }\n\n let max = Number.POSITIVE_INFINITY;\n\n if (values.max !== undefined) {\n if (!/^\\d+$/.test(values.max)) {\n printError(usage);\n\n return 2;\n }\n\n max = Number(values.max);\n }\n\n const cycles = ModuleGraph.fromDirectory({ dir }).cycles();\n print(`${dir}: ${cycles.length} cycle(s)`);\n\n for (const cycle of cycles) {\n print(` - ${cycle.join(' <-> ')}`);\n }\n\n return cycles.length > max ? 1 : 0;\n }\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/** One built entry file that the browser-purity gate probes; rows are derived from the package `exports` map, not written by hand. */
|
|
1
2
|
export interface IPurityEntry {
|
|
2
3
|
label: string;
|
|
3
4
|
package: string;
|
|
@@ -51,7 +52,11 @@ export interface IPurityOptions {
|
|
|
51
52
|
* the claim unconsumable. Omit it for a repository that publishes a single build.
|
|
52
53
|
*/
|
|
53
54
|
esmEntryPrefix?: string;
|
|
54
|
-
/**
|
|
55
|
+
/**
|
|
56
|
+
* Package-name prefix of this repository's own packages; an `external` may never start with it.
|
|
57
|
+
*
|
|
58
|
+
* @default '@venizia/'
|
|
59
|
+
*/
|
|
55
60
|
workspaceScope?: string;
|
|
56
61
|
}
|
|
57
62
|
/** Derives the rows of the purity gate from the `exports` map of each claimed package, then runs the guards on them. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../../../src/checks/purity/manifest.ts"],"names":[],"mappings":";;;AAAA,qCAAuC;AACvC,yCAAiC;AA8DjC,MAAM,uBAAuB,GAAG,WAAW,CAAC;AAE5C,wIAAwI;AACxI,sGAAsG;AACtG,MAAM,WAAW,GAAG,CAAC,OAAe,EAAS,EAAE,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;AAEnE,6FAA6F;AAC7F,MAAM,qBAAqB,GAAG,OAAO,CAAC;AACtC,MAAM,gBAAgB,GAAG,gBAAgB,CAAC;AAI1C,MAAM,cAAc,GAAG,CAAC,IAGvB,EAAkC,EAAE;IACnC,MAAM,YAAY,GAAG,IAAA,gBAAI,EAAC,IAAI,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC;IAC/E,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,IAAA,sBAAY,EAAC,YAAY,EAAE,MAAM,CAAC,CAE7D,CAAC;IAEF,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;QACtB,MAAM,WAAW,CACf,uBAAuB,IAAI,CAAC,OAAO,2DAA2D;YAC5F,0EAA0E,CAC7E,CAAC;IACJ,CAAC;IAED,OAAO,QAAQ,CAAC,OAAO,CAAC;AAC1B,CAAC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,oBAAoB,GAAG,CAC3B,MAAsB,EACsB,EAAE;IAC9C,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC/B,OAAO,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;IAClD,CAAC;IAED,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,MAAM,OAAO,GAA+C,EAAE,CA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YAC9C,QAAQ,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,cAAc,CAAC,aAAa,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YACnF,cAAc;SACf,CAAC,CAAC;IACL,CAAC;CACF;AA9LD,wCA8LC","sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport interface IPurityEntry {\n label: string;\n package: string;\n /** Repository-relative path to the built file the `exports` map points at. */\n entry: string;\n /**\n * Specifiers to pass through as `bun build --external`. Only for a third-party dependency whose\n * OWN packaging is out of this gate's remit - e.g. one that relies on its `package.json` `browser`\n * field remap, which the downstream app's bundler (Vite, ...) honours and `bun build` does not.\n * Never for the repository's own source: an external hides that file from the module graph\n * entirely, so using it on our own code would let a real leak through unseen rather than prove\n * anything pure. Enforced by {@link PurityManifest.assertNoWorkspaceExternal}, not left to this comment alone.\n */\n external?: string[];\n /**\n * This row is EXPECTED to be impure, so failing is its passing state. Derived from\n * {@link IPurityClaim.impure} - never authored on a row directly.\n */\n expectImpure?: boolean;\n}\n\n/**\n * A package whose published entry points carry a browser-purity claim.\n *\n * The ROW SET IS NEVER AUTHORED. It is read from the package's own `exports` map, so a sub-path\n * added to a manifest is probed the moment it is published.\n */\nexport interface IPurityClaim {\n /** Directory under `packages/`, and the token `devz check purity <token>` filters on. */\n package: string;\n /**\n * Sub-paths (as spelled in `exports`) when the claim covers only PART of the published surface.\n * Omit it and the whole surface is claimed. Every sub-path named here must still exist in\n * `exports`; a rename fails the derivation loudly rather than quietly dropping a row.\n */\n subpaths?: string[];\n /** `external` for one sub-path - see {@link IPurityEntry.external}. Keyed as spelled in `exports`. */\n external?: Record<string, string[]>;\n /**\n * Entries that CANNOT be browser-pure, keyed as spelled in `exports`, valued by the conditions\n * that are impure. The waiver is exact in BOTH directions: a listed entry that turns out to be\n * pure fails as loudly as an unlisted one that is not. Deriving still owns the ROW SET, so a\n * sub-path added later is claimed pure by default and has to earn its line here.\n */\n impure?: Record<string, string[]>;\n}\n\n/** What a repository may tune about the engine; everything else is the engine's contract. */\nexport interface IPurityOptions {\n /**\n * When set, every claimed sub-path must publish its runtime entries below this prefix (for\n * example `./dist/esm/`): a browser bundler needs an ES module, so a CommonJS-only entry makes\n * the claim unconsumable. Omit it for a repository that publishes a single build.\n */\n esmEntryPrefix?: string;\n\n /** Package-name prefix of this repository's own packages; an `external` may never start with it. Default `@venizia/`. */\n workspaceScope?: string;\n}\n\nconst DEFAULT_WORKSPACE_SCOPE = '@venizia/';\n\n/** The one place this engine builds an `Error`: `getError` would make dev-configs depend on inversion, which depends on dev-configs. */\n// eslint-disable-next-line venizia/no-new-error -- getError would be a dev-configs -> inversion cycle\nconst purityError = (message: string): Error => new Error(message);\n\n/** `types` describes the entry, it is not a runtime target; `./package.json` is not code. */\nconst NON_RUNTIME_CONDITION = 'types';\nconst NON_CODE_SUBPATH = './package.json';\n\ntype TExportsTarget = string | Record<string, string>;\n\nconst readExportsMap = (opts: {\n root: string;\n package: string;\n}): Record<string, TExportsTarget> => {\n const manifestPath = join(opts.root, 'packages', opts.package, 'package.json');\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as {\n exports?: Record<string, TExportsTarget>;\n };\n\n if (!manifest.exports) {\n throw purityError(\n `[purity][manifest] '${opts.package}' claims browser purity but publishes no \\`exports\\` map ` +\n `| There is nothing to derive rows from - remove the claim or add the map`,\n );\n }\n\n return manifest.exports;\n};\n\n/**\n * `exports` may spell one sub-path as several conditions pointing at different builds - the dual\n * CJS/ESM packages do exactly that - and each is a separately resolvable file that a consumer can\n * end up importing, so each is probed. `default` normally repeats `require`, so files are deduped\n * and the FIRST condition naming a file is the one that labels it.\n */\nconst listConditionTargets = (\n target: TExportsTarget,\n): Array<{ condition: string; file: string }> => {\n if (typeof target === 'string') {\n return [{ condition: 'default', file: target }];\n }\n\n const seen = new Set<string>();\n const targets: Array<{ condition: string; file: string }> = [];\n\n const targetEntries = Object.entries(target);\n\n for (const [condition, file] of targetEntries) {\n if (condition === NON_RUNTIME_CONDITION || seen.has(file)) {\n continue;\n }\n\n seen.add(file);\n targets.push({ condition, file });\n }\n\n return targets;\n};\n\nconst buildLabel = (opts: {\n package: string;\n subpath: string;\n condition: string;\n isSoleTarget: boolean;\n}): string => {\n const { package: packageName, subpath, condition, isSoleTarget } = opts;\n const suffix = subpath === '.' ? '' : subpath.slice(1);\n const base = `${packageName}${suffix}`;\n\n return isSoleTarget ? base : `${base} [${condition}]`;\n};\n\n/** Derives the rows of the purity gate from the `exports` map of each claimed package, then runs the guards on them. */\nexport class PurityManifest {\n /**\n * A code-level guard, not just the JSDoc on `external`: it is an escape hatch from this gate, and a\n * hatch with no lock is one bad edit away from hiding a real leak - `external: ['@venizia/ignis-helpers']`\n * on a red entry would silently turn it green by removing the exact root-barrel import this gate\n * exists to catch from the module graph, rather than proving it absent.\n *\n * A plain `Error`, not `getError`: the engine runs from the repository root through `devz`, outside\n * every workspace package, and has no logger to resolve.\n */\n static assertNoWorkspaceExternal(opts: {\n manifest: IPurityEntry[];\n workspaceScope?: string;\n }): IPurityEntry[] {\n const { manifest, workspaceScope = DEFAULT_WORKSPACE_SCOPE } = opts;\n\n for (const row of manifest) {\n const specifiers = row.external ?? [];\n\n for (const specifier of specifiers) {\n if (!specifier.startsWith(workspaceScope)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] Entry '${row.label}' externalises '${specifier}', a workspace package ` +\n `| \\`external\\` may only exempt THIRD-PARTY packaging, never the repository's own code - doing so ` +\n `would hide the exact leak this gate exists to catch`,\n );\n }\n }\n\n return manifest;\n }\n\n /**\n * Public for the tests, which have to drive a claim that no longer matches its package's\n * `exports` map - the staleness guard is the whole point of deriving, and it cannot be asserted\n * through a built manifest, which by construction is never stale.\n */\n static deriveEntries(opts: { claim: IPurityClaim; root: string }): IPurityEntry[] {\n const { claim, root } = opts;\n const exportsMap = readExportsMap({ root, package: claim.package });\n const published = Object.keys(exportsMap).filter((subpath) => subpath !== NON_CODE_SUBPATH);\n\n const subpathsList = claim.subpaths ?? [];\n\n for (const subpath of subpathsList) {\n if (published.includes(subpath)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' claims '${subpath}', which its \\`exports\\` map no longer ` +\n `publishes | Published: ${published.join(', ')} - a renamed sub-path must not silently drop its row`,\n );\n }\n\n const claimExternalKeys = Object.keys(claim.external ?? {});\n\n for (const subpath of claimExternalKeys) {\n if (published.includes(subpath)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' declares \\`external\\` for '${subpath}', which its ` +\n `\\`exports\\` map no longer publishes | An external that outlives its entry is a waiver ` +\n `nobody is reading`,\n );\n }\n\n const claimed = claim.subpaths ?? published;\n\n const claimImpureKeys = Object.keys(claim.impure ?? {});\n\n for (const subpath of claimImpureKeys) {\n if (claimed.includes(subpath)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' waives '${subpath}' as impure, but that sub-path is not ` +\n `claimed | Claimed: ${claimed.join(', ')} - a waiver against nothing is one nobody is reading`,\n );\n }\n\n const entries: IPurityEntry[] = [];\n\n for (const subpath of claimed) {\n const targets = listConditionTargets(exportsMap[subpath]!);\n\n const conditions = claim.impure?.[subpath] ?? [];\n\n for (const condition of conditions) {\n if (targets.some((target) => target.condition === condition)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' waives '${subpath}' under condition '${condition}', ` +\n `which its \\`exports\\` map does not publish | Published: ${targets.map((t) => t.condition).join(', ')}`,\n );\n }\n\n for (const { condition, file } of targets) {\n entries.push({\n label: buildLabel({\n package: claim.package,\n subpath,\n condition,\n isSoleTarget: targets.length === 1,\n }),\n package: claim.package,\n entry: join('packages', claim.package, file),\n ...(claim.external?.[subpath] ? { external: claim.external[subpath] } : {}),\n ...(claim.impure?.[subpath]?.includes(condition) ? { expectImpure: true } : {}),\n });\n }\n }\n\n return entries;\n }\n\n /**\n * A browser claim is only honest if a browser bundler can actually consume the entry. A CommonJS\n * entry forces every consumer into a workaround, so the claim carries the obligation: every claimed\n * sub-path must publish its runtime entries below `esmEntryPrefix`. Checked here rather than trusted\n * to a comment, for the same reason as {@link PurityManifest.assertNoWorkspaceExternal} - the failure is otherwise\n * invisible until someone tries to bundle the package downstream.\n */\n static assertBrowserEsmEntry(opts: {\n claims: IPurityClaim[];\n root: string;\n esmEntryPrefix: string;\n }): IPurityClaim[] {\n const { claims, root, esmEntryPrefix } = opts;\n\n for (const claim of claims) {\n const exportsMap = readExportsMap({ root, package: claim.package });\n const claimed =\n claim.subpaths ?? Object.keys(exportsMap).filter((s) => s !== NON_CODE_SUBPATH);\n\n for (const subpath of claimed) {\n const target = exportsMap[subpath];\n\n const runtimeTargets =\n typeof target === 'object' && target !== null\n ? Object.entries(target)\n .filter(([condition]) => condition !== NON_RUNTIME_CONDITION)\n .map(([, file]) => file)\n : [];\n\n if (\n runtimeTargets.length > 0 &&\n runtimeTargets.every((file) => file.startsWith(esmEntryPrefix))\n ) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' claims browser purity for '${subpath}' but its runtime ` +\n `entry is not in ${esmEntryPrefix.replace(/^\\.\\//, '')} | A browser bundler needs an ES module, so the claim ` +\n `cannot be consumed - build the package as ES modules`,\n );\n }\n }\n\n return claims;\n }\n\n /** The rows of a whole repository: every claim derived from its package's `exports`, then the guards. */\n static build(opts: {\n claims: IPurityClaim[];\n root: string;\n options?: IPurityOptions;\n }): IPurityEntry[] {\n const { claims, root, options = {} } = opts;\n const { esmEntryPrefix, workspaceScope = DEFAULT_WORKSPACE_SCOPE } = options;\n\n const checked =\n esmEntryPrefix === undefined\n ? claims\n : PurityManifest.assertBrowserEsmEntry({ claims, root, esmEntryPrefix });\n\n return PurityManifest.assertNoWorkspaceExternal({\n manifest: checked.flatMap((claim) => PurityManifest.deriveEntries({ claim, root })),\n workspaceScope,\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../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E,CAAC,CAAC;YACnF,cAAc;SACf,CAAC,CAAC;IACL,CAAC;CACF;AA9LD,wCA8LC","sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/** One built entry file that the browser-purity gate probes; rows are derived from the package `exports` map, not written by hand. */\nexport interface IPurityEntry {\n label: string;\n package: string;\n /** Repository-relative path to the built file the `exports` map points at. */\n entry: string;\n /**\n * Specifiers to pass through as `bun build --external`. Only for a third-party dependency whose\n * OWN packaging is out of this gate's remit - e.g. one that relies on its `package.json` `browser`\n * field remap, which the downstream app's bundler (Vite, ...) honours and `bun build` does not.\n * Never for the repository's own source: an external hides that file from the module graph\n * entirely, so using it on our own code would let a real leak through unseen rather than prove\n * anything pure. Enforced by {@link PurityManifest.assertNoWorkspaceExternal}, not left to this comment alone.\n */\n external?: string[];\n /**\n * This row is EXPECTED to be impure, so failing is its passing state. Derived from\n * {@link IPurityClaim.impure} - never authored on a row directly.\n */\n expectImpure?: boolean;\n}\n\n/**\n * A package whose published entry points carry a browser-purity claim.\n *\n * The ROW SET IS NEVER AUTHORED. It is read from the package's own `exports` map, so a sub-path\n * added to a manifest is probed the moment it is published.\n */\nexport interface IPurityClaim {\n /** Directory under `packages/`, and the token `devz check purity <token>` filters on. */\n package: string;\n /**\n * Sub-paths (as spelled in `exports`) when the claim covers only PART of the published surface.\n * Omit it and the whole surface is claimed. Every sub-path named here must still exist in\n * `exports`; a rename fails the derivation loudly rather than quietly dropping a row.\n */\n subpaths?: string[];\n /** `external` for one sub-path - see {@link IPurityEntry.external}. Keyed as spelled in `exports`. */\n external?: Record<string, string[]>;\n /**\n * Entries that CANNOT be browser-pure, keyed as spelled in `exports`, valued by the conditions\n * that are impure. The waiver is exact in BOTH directions: a listed entry that turns out to be\n * pure fails as loudly as an unlisted one that is not. Deriving still owns the ROW SET, so a\n * sub-path added later is claimed pure by default and has to earn its line here.\n */\n impure?: Record<string, string[]>;\n}\n\n/** What a repository may tune about the engine; everything else is the engine's contract. */\nexport interface IPurityOptions {\n /**\n * When set, every claimed sub-path must publish its runtime entries below this prefix (for\n * example `./dist/esm/`): a browser bundler needs an ES module, so a CommonJS-only entry makes\n * the claim unconsumable. Omit it for a repository that publishes a single build.\n */\n esmEntryPrefix?: string;\n\n /**\n * Package-name prefix of this repository's own packages; an `external` may never start with it.\n *\n * @default '@venizia/'\n */\n workspaceScope?: string;\n}\n\nconst DEFAULT_WORKSPACE_SCOPE = '@venizia/';\n\n/** The one place this engine builds an `Error`: `getError` would make dev-configs depend on inversion, which depends on dev-configs. */\n// eslint-disable-next-line venizia/no-new-error -- getError would be a dev-configs -> inversion cycle\nconst purityError = (message: string): Error => new Error(message);\n\n/** `types` describes the entry, it is not a runtime target; `./package.json` is not code. */\nconst NON_RUNTIME_CONDITION = 'types';\nconst NON_CODE_SUBPATH = './package.json';\n\ntype TExportsTarget = string | Record<string, string>;\n\nconst readExportsMap = (opts: {\n root: string;\n package: string;\n}): Record<string, TExportsTarget> => {\n const manifestPath = join(opts.root, 'packages', opts.package, 'package.json');\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as {\n exports?: Record<string, TExportsTarget>;\n };\n\n if (!manifest.exports) {\n throw purityError(\n `[purity][manifest] '${opts.package}' claims browser purity but publishes no \\`exports\\` map ` +\n `| There is nothing to derive rows from - remove the claim or add the map`,\n );\n }\n\n return manifest.exports;\n};\n\n/**\n * `exports` may spell one sub-path as several conditions pointing at different builds - the dual\n * CJS/ESM packages do exactly that - and each is a separately resolvable file that a consumer can\n * end up importing, so each is probed. `default` normally repeats `require`, so files are deduped\n * and the FIRST condition naming a file is the one that labels it.\n */\nconst listConditionTargets = (\n target: TExportsTarget,\n): Array<{ condition: string; file: string }> => {\n if (typeof target === 'string') {\n return [{ condition: 'default', file: target }];\n }\n\n const seen = new Set<string>();\n const targets: Array<{ condition: string; file: string }> = [];\n\n const targetEntries = Object.entries(target);\n\n for (const [condition, file] of targetEntries) {\n if (condition === NON_RUNTIME_CONDITION || seen.has(file)) {\n continue;\n }\n\n seen.add(file);\n targets.push({ condition, file });\n }\n\n return targets;\n};\n\nconst buildLabel = (opts: {\n package: string;\n subpath: string;\n condition: string;\n isSoleTarget: boolean;\n}): string => {\n const { package: packageName, subpath, condition, isSoleTarget } = opts;\n const suffix = subpath === '.' ? '' : subpath.slice(1);\n const base = `${packageName}${suffix}`;\n\n return isSoleTarget ? base : `${base} [${condition}]`;\n};\n\n/** Derives the rows of the purity gate from the `exports` map of each claimed package, then runs the guards on them. */\nexport class PurityManifest {\n /**\n * A code-level guard, not just the JSDoc on `external`: it is an escape hatch from this gate, and a\n * hatch with no lock is one bad edit away from hiding a real leak - `external: ['@venizia/ignis-helpers']`\n * on a red entry would silently turn it green by removing the exact root-barrel import this gate\n * exists to catch from the module graph, rather than proving it absent.\n *\n * A plain `Error`, not `getError`: the engine runs from the repository root through `devz`, outside\n * every workspace package, and has no logger to resolve.\n */\n static assertNoWorkspaceExternal(opts: {\n manifest: IPurityEntry[];\n workspaceScope?: string;\n }): IPurityEntry[] {\n const { manifest, workspaceScope = DEFAULT_WORKSPACE_SCOPE } = opts;\n\n for (const row of manifest) {\n const specifiers = row.external ?? [];\n\n for (const specifier of specifiers) {\n if (!specifier.startsWith(workspaceScope)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] Entry '${row.label}' externalises '${specifier}', a workspace package ` +\n `| \\`external\\` may only exempt THIRD-PARTY packaging, never the repository's own code - doing so ` +\n `would hide the exact leak this gate exists to catch`,\n );\n }\n }\n\n return manifest;\n }\n\n /**\n * Public for the tests, which have to drive a claim that no longer matches its package's\n * `exports` map - the staleness guard is the whole point of deriving, and it cannot be asserted\n * through a built manifest, which by construction is never stale.\n */\n static deriveEntries(opts: { claim: IPurityClaim; root: string }): IPurityEntry[] {\n const { claim, root } = opts;\n const exportsMap = readExportsMap({ root, package: claim.package });\n const published = Object.keys(exportsMap).filter((subpath) => subpath !== NON_CODE_SUBPATH);\n\n const subpathsList = claim.subpaths ?? [];\n\n for (const subpath of subpathsList) {\n if (published.includes(subpath)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' claims '${subpath}', which its \\`exports\\` map no longer ` +\n `publishes | Published: ${published.join(', ')} - a renamed sub-path must not silently drop its row`,\n );\n }\n\n const claimExternalKeys = Object.keys(claim.external ?? {});\n\n for (const subpath of claimExternalKeys) {\n if (published.includes(subpath)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' declares \\`external\\` for '${subpath}', which its ` +\n `\\`exports\\` map no longer publishes | An external that outlives its entry is a waiver ` +\n `nobody is reading`,\n );\n }\n\n const claimed = claim.subpaths ?? published;\n\n const claimImpureKeys = Object.keys(claim.impure ?? {});\n\n for (const subpath of claimImpureKeys) {\n if (claimed.includes(subpath)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' waives '${subpath}' as impure, but that sub-path is not ` +\n `claimed | Claimed: ${claimed.join(', ')} - a waiver against nothing is one nobody is reading`,\n );\n }\n\n const entries: IPurityEntry[] = [];\n\n for (const subpath of claimed) {\n const targets = listConditionTargets(exportsMap[subpath]!);\n\n const conditions = claim.impure?.[subpath] ?? [];\n\n for (const condition of conditions) {\n if (targets.some((target) => target.condition === condition)) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' waives '${subpath}' under condition '${condition}', ` +\n `which its \\`exports\\` map does not publish | Published: ${targets.map((t) => t.condition).join(', ')}`,\n );\n }\n\n for (const { condition, file } of targets) {\n entries.push({\n label: buildLabel({\n package: claim.package,\n subpath,\n condition,\n isSoleTarget: targets.length === 1,\n }),\n package: claim.package,\n entry: join('packages', claim.package, file),\n ...(claim.external?.[subpath] ? { external: claim.external[subpath] } : {}),\n ...(claim.impure?.[subpath]?.includes(condition) ? { expectImpure: true } : {}),\n });\n }\n }\n\n return entries;\n }\n\n /**\n * A browser claim is only honest if a browser bundler can actually consume the entry. A CommonJS\n * entry forces every consumer into a workaround, so the claim carries the obligation: every claimed\n * sub-path must publish its runtime entries below `esmEntryPrefix`. Checked here rather than trusted\n * to a comment, for the same reason as {@link PurityManifest.assertNoWorkspaceExternal} - the failure is otherwise\n * invisible until someone tries to bundle the package downstream.\n */\n static assertBrowserEsmEntry(opts: {\n claims: IPurityClaim[];\n root: string;\n esmEntryPrefix: string;\n }): IPurityClaim[] {\n const { claims, root, esmEntryPrefix } = opts;\n\n for (const claim of claims) {\n const exportsMap = readExportsMap({ root, package: claim.package });\n const claimed =\n claim.subpaths ?? Object.keys(exportsMap).filter((s) => s !== NON_CODE_SUBPATH);\n\n for (const subpath of claimed) {\n const target = exportsMap[subpath];\n\n const runtimeTargets =\n typeof target === 'object' && target !== null\n ? Object.entries(target)\n .filter(([condition]) => condition !== NON_RUNTIME_CONDITION)\n .map(([, file]) => file)\n : [];\n\n if (\n runtimeTargets.length > 0 &&\n runtimeTargets.every((file) => file.startsWith(esmEntryPrefix))\n ) {\n continue;\n }\n\n throw purityError(\n `[purity][manifest] '${claim.package}' claims browser purity for '${subpath}' but its runtime ` +\n `entry is not in ${esmEntryPrefix.replace(/^\\.\\//, '')} | A browser bundler needs an ES module, so the claim ` +\n `cannot be consumed - build the package as ES modules`,\n );\n }\n }\n\n return claims;\n }\n\n /** The rows of a whole repository: every claim derived from its package's `exports`, then the guards. */\n static build(opts: {\n claims: IPurityClaim[];\n root: string;\n options?: IPurityOptions;\n }): IPurityEntry[] {\n const { claims, root, options = {} } = opts;\n const { esmEntryPrefix, workspaceScope = DEFAULT_WORKSPACE_SCOPE } = options;\n\n const checked =\n esmEntryPrefix === undefined\n ? claims\n : PurityManifest.assertBrowserEsmEntry({ claims, root, esmEntryPrefix });\n\n return PurityManifest.assertNoWorkspaceExternal({\n manifest: checked.flatMap((claim) => PurityManifest.deriveEntries({ claim, root })),\n workspaceScope,\n });\n }\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/** Outcome of probing one entry: `ok` is the verdict, `builtins` and `globals` are what made it fail, `sizeBytes` is the bundle size. */
|
|
1
2
|
export interface IPurityResult {
|
|
2
3
|
entry: string;
|
|
3
4
|
ok: boolean;
|
|
@@ -23,6 +24,7 @@ export declare class ProbeSeverities {
|
|
|
23
24
|
static readonly SCHEME_SET: Set<string>;
|
|
24
25
|
static isValid(value: string): value is TProbeSeverity;
|
|
25
26
|
}
|
|
27
|
+
/** `error` or `guarded`: whether a matched Node global fails the probe or is only reported. */
|
|
26
28
|
export type TProbeSeverity = Extract<(typeof ProbeSeverities)[keyof typeof ProbeSeverities], string>;
|
|
27
29
|
/**
|
|
28
30
|
* Node globals survive verbatim into a `target: 'browser'` bundle, so a gate reading only module
|
|
@@ -48,6 +50,7 @@ export declare const GLOBAL_PATTERNS: Array<{
|
|
|
48
50
|
pattern: RegExp;
|
|
49
51
|
severity: TProbeSeverity;
|
|
50
52
|
}>;
|
|
53
|
+
/** Bundles a built entry for the browser with `bun build` and reports the Node builtins and Node globals that reach the bundle. */
|
|
51
54
|
export declare class PurityProbe {
|
|
52
55
|
/**
|
|
53
56
|
* Public so `probe.test.ts` can assert against the literal collision string directly, without
|
|
@@ -65,7 +68,7 @@ export declare class PurityProbe {
|
|
|
65
68
|
entry: string;
|
|
66
69
|
cwd: string;
|
|
67
70
|
external?: string[];
|
|
68
|
-
/**
|
|
71
|
+
/** @default join(cwd, PURITY_SCRATCH_DIR) */
|
|
69
72
|
scratchDir?: string;
|
|
70
73
|
}): Promise<IPurityResult>;
|
|
71
74
|
}
|
|
@@ -183,6 +183,7 @@ const readMetafile = async (path) => {
|
|
|
183
183
|
await (0, promises_1.rm)(path, { force: true });
|
|
184
184
|
}
|
|
185
185
|
};
|
|
186
|
+
/** Bundles a built entry for the browser with `bun build` and reports the Node builtins and Node globals that reach the bundle. */
|
|
186
187
|
class PurityProbe {
|
|
187
188
|
/**
|
|
188
189
|
* Public so `probe.test.ts` can assert against the literal collision string directly, without
|