@styloviz/schematics 2.0.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -2
- package/collection.json +12 -0
- package/lib/sources-block.js +48 -0
- package/lib/workspace.js +54 -0
- package/migrate-primeng/index.js +1 -1
- package/migrate-primeng/map.json +63 -0
- package/ng-add/index.js +151 -35
- package/ng-add/schema.json +2 -1
- package/ng-add/sources-schema.json +9 -0
- package/package.json +4 -2
- package/sources/build-stats.js +139 -0
- package/sources/index.js +404 -0
- package/sources/parts.js +70 -0
- package/sources/schema.json +13 -0
- package/sources/walk.js +426 -0
package/ng-add/index.js
CHANGED
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
* 2. .postcssrc.json the Tailwind 4 PostCSS plugin, when the app has no PostCSS config.
|
|
10
10
|
* 3. global styles `@import "tailwindcss"`, the kit stylesheet (tokens, the
|
|
11
11
|
* class-based dark variant, component CSS) and an `@source`
|
|
12
|
-
* for the kit's templates,
|
|
12
|
+
* for the kit's templates (`@styloviz-pro` too, when Pro is
|
|
13
|
+
* installed), prepended once.
|
|
13
14
|
* 4. app.config.ts `provideStyloviz()` in the providers.
|
|
14
15
|
* 5. demo page /styloviz, a standalone page with a few buttons, routed
|
|
15
16
|
* lazily — the proof the setup works, and a thing to delete.
|
|
@@ -18,12 +19,27 @@
|
|
|
18
19
|
* Without them the first production build after adding an
|
|
19
20
|
* export feature prints ~18 warnings the app cannot act on
|
|
20
21
|
* (FL-L2). The templates ship the same list.
|
|
22
|
+
* 7. .npmrc under pnpm only: hoist the two Styloviz scopes, so the
|
|
23
|
+
* packages the install bundles bring in resolve by name.
|
|
24
|
+
* 8. sources `ng g @styloviz/core:sources` (M-1 A4): the broad `@source`
|
|
25
|
+
* lines become one line per kit file the app uses, and the
|
|
26
|
+
* kit stylesheet only the parts it uses — so the first build
|
|
27
|
+
* of a new app fits Angular's default budgets. It reads the
|
|
28
|
+
* installed packages, so it runs after the install task;
|
|
29
|
+
* when nothing is to be installed, in this run. Where it
|
|
30
|
+
* cannot run (packages not installed yet, `--skip-install`)
|
|
31
|
+
* or cannot be exact (a source root that holds
|
|
32
|
+
* node_modules), the broad lines stay and it says what to run.
|
|
33
|
+
* `--sources=false` keeps the broad lines.
|
|
21
34
|
*
|
|
22
35
|
* Every step is idempotent: running it twice changes nothing the second time.
|
|
23
36
|
*/
|
|
24
37
|
const { SchematicsException } = require('@angular-devkit/schematics');
|
|
25
|
-
const { NodePackageInstallTask } = require('@angular-devkit/schematics/tasks');
|
|
38
|
+
const { NodePackageInstallTask, RunSchematicTask } = require('@angular-devkit/schematics/tasks');
|
|
26
39
|
const { posix } = require('node:path');
|
|
40
|
+
const { readJson, resolveProject } = require('../lib/workspace');
|
|
41
|
+
const { hasSourcesBlock, hasPartsBlock } = require('../lib/sources-block');
|
|
42
|
+
const { sources } = require('../sources/index');
|
|
27
43
|
|
|
28
44
|
const KIT_VERSION = require('../package.json').version;
|
|
29
45
|
|
|
@@ -38,19 +54,26 @@ const DEV_DEPENDENCIES = {
|
|
|
38
54
|
postcss: '^8.5.0',
|
|
39
55
|
};
|
|
40
56
|
|
|
57
|
+
/**
|
|
58
|
+
* Scopes pnpm must hoist for the install bundles to work (live-user test M-2).
|
|
59
|
+
*
|
|
60
|
+
* pnpm links only a project's DIRECT dependencies into node_modules.
|
|
61
|
+
* `@styloviz/all` and `@styloviz-pro/all` are bundles: they depend on every
|
|
62
|
+
* package, and the app imports those packages by name — so under pnpm's
|
|
63
|
+
* defaults not one resolves, and the build fails with a "Could not resolve"
|
|
64
|
+
* per import. Hoisting the two scopes is pnpm's own answer, and with it
|
|
65
|
+
* Tailwind's `@source` scan reads the same files as under npm (the same
|
|
66
|
+
* stylesheet, byte for byte, measured on a real app).
|
|
67
|
+
*
|
|
68
|
+
* Written only for pnpm: npm warns about `.npmrc` keys it does not know.
|
|
69
|
+
* Keep in step with PNPM_HOIST_NPMRC in src/app/shared/registry.config.ts —
|
|
70
|
+
* scripts/schematics.node.spec.ts compares the two.
|
|
71
|
+
*/
|
|
72
|
+
const PNPM_HOIST_PATTERNS = ['@styloviz/*', '@styloviz-pro/*'];
|
|
73
|
+
|
|
41
74
|
/** jspdf's CommonJS modules — the same list scripts/lib/template-project.mjs gives the templates. */
|
|
42
75
|
const EXPORT_COMMONJS = ['html2canvas', 'canvg', 'raf', 'rgbcolor', 'core-js'];
|
|
43
76
|
|
|
44
|
-
function readJson(tree, path) {
|
|
45
|
-
const buf = tree.read(path);
|
|
46
|
-
if (!buf) return null;
|
|
47
|
-
try {
|
|
48
|
-
return JSON.parse(buf.toString('utf8'));
|
|
49
|
-
} catch {
|
|
50
|
-
throw new SchematicsException(`${path} is not valid JSON.`);
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
77
|
function addDependencies(tree, context) {
|
|
55
78
|
const pkg = readJson(tree, '/package.json');
|
|
56
79
|
if (!pkg) throw new SchematicsException('No package.json at the workspace root.');
|
|
@@ -69,24 +92,6 @@ function addDependencies(tree, context) {
|
|
|
69
92
|
return added.length > 0;
|
|
70
93
|
}
|
|
71
94
|
|
|
72
|
-
/** The app to set up, and where its files are. */
|
|
73
|
-
function resolveProject(tree, options) {
|
|
74
|
-
const workspace = readJson(tree, '/angular.json');
|
|
75
|
-
if (!workspace) throw new SchematicsException('No angular.json — run this inside an Angular workspace.');
|
|
76
|
-
const name =
|
|
77
|
-
options.project ||
|
|
78
|
-
Object.keys(workspace.projects).find((p) => workspace.projects[p].projectType === 'application');
|
|
79
|
-
const project = name && workspace.projects[name];
|
|
80
|
-
if (!project) throw new SchematicsException(`No application project ${options.project ? `"${options.project}" ` : ''}in angular.json.`);
|
|
81
|
-
const root = project.root || '';
|
|
82
|
-
const sourceRoot = project.sourceRoot || posix.join(root, 'src');
|
|
83
|
-
const build = project.architect?.build ?? project.targets?.build;
|
|
84
|
-
const styles = (build?.options?.styles ?? [])
|
|
85
|
-
.map((s) => (typeof s === 'string' ? s : s.input))
|
|
86
|
-
.find((s) => /\.css$/.test(s));
|
|
87
|
-
return { name, root, sourceRoot, styles: styles ?? posix.join(sourceRoot, 'styles.css') };
|
|
88
|
-
}
|
|
89
|
-
|
|
90
95
|
function addPostcssConfig(tree, context, root) {
|
|
91
96
|
const has = ['.postcssrc.json', 'postcss.config.js', 'postcss.config.mjs', 'postcss.config.cjs'].some((f) => tree.exists(posix.join('/', root, f)) || tree.exists(`/${f}`));
|
|
92
97
|
if (has) return;
|
|
@@ -103,14 +108,36 @@ function addStyles(tree, context, stylesPath) {
|
|
|
103
108
|
[/@import\s+['"]tailwindcss['"]/, `@import "tailwindcss";`],
|
|
104
109
|
[/@styloviz\/core\/styles\/styloviz\.css/, `@import "@styloviz/core/styles/styloviz.css";`],
|
|
105
110
|
[/@source\s+['"][^'"]*node_modules\/@styloviz['"]/, `@source "${toNodeModules}/@styloviz";`],
|
|
106
|
-
|
|
111
|
+
// Root cause 2 of M-1: without this line a Pro buyer's components rendered
|
|
112
|
+
// unstyled, with no error. Only when Pro is installed: an empty scope is noise.
|
|
113
|
+
...(isInstalledDir(tree, '/node_modules/@styloviz-pro') ? [[/@source\s+['"][^'"]*node_modules\/@styloviz-pro['"]/, `@source "${toNodeModules}/@styloviz-pro";`]] : []),
|
|
114
|
+
]
|
|
115
|
+
// Once `ng g @styloviz/core:sources` has written its blocks, they say what
|
|
116
|
+
// Tailwind scans and which parts of the kit stylesheet load; the broad
|
|
117
|
+
// line, or the whole stylesheet again, would undo them.
|
|
118
|
+
.filter(([marker, line]) => !marker.test(current) && !(line.startsWith('@source') && hasSourcesBlock(current)) && !(line.includes('styloviz.css') && hasPartsBlock(current)))
|
|
119
|
+
.map(([, line]) => line);
|
|
107
120
|
if (!lines.length) return;
|
|
121
|
+
// A Pro line added to a stylesheet that already has the rest goes after the free one.
|
|
122
|
+
const free = current.split('\n').findIndex((l) => /@source\s+['"][^'"]*node_modules\/@styloviz['"]/.test(l));
|
|
123
|
+
if (free >= 0 && lines.length === 1 && lines[0].includes('@styloviz-pro')) {
|
|
124
|
+
const rows = current.split('\n');
|
|
125
|
+
rows.splice(free + 1, 0, lines[0]);
|
|
126
|
+
tree.overwrite(path, rows.join('\n'));
|
|
127
|
+
context.logger.info(`✔ ${posix.basename(path)}: @source for the installed Pro packages`);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
108
130
|
const next = `${lines.join('\n')}\n${current ? `\n${current}` : ''}`;
|
|
109
131
|
if (tree.exists(path)) tree.overwrite(path, next);
|
|
110
132
|
else tree.create(path, next);
|
|
111
133
|
context.logger.info(`✔ ${posix.basename(path)}: Tailwind 4, the Styloviz stylesheet and @source`);
|
|
112
134
|
}
|
|
113
135
|
|
|
136
|
+
function isInstalledDir(tree, path) {
|
|
137
|
+
const dir = tree.getDir(path);
|
|
138
|
+
return dir.subdirs.length > 0 || dir.subfiles.length > 0;
|
|
139
|
+
}
|
|
140
|
+
|
|
114
141
|
function addProvider(tree, context, sourceRoot) {
|
|
115
142
|
const path = posix.join('/', sourceRoot, 'app/app.config.ts');
|
|
116
143
|
if (!tree.exists(path)) {
|
|
@@ -198,7 +225,76 @@ function allowExportCommonJs(tree, context, projectName) {
|
|
|
198
225
|
context.logger.info(`✔ angular.json: allowed jspdf's CommonJS modules (${missing.join(', ')})`);
|
|
199
226
|
}
|
|
200
227
|
|
|
201
|
-
/**
|
|
228
|
+
/**
|
|
229
|
+
* Whether the workspace installs with pnpm: its lockfile or workspace file,
|
|
230
|
+
* else the CLI's configured package manager, else the tool that launched us.
|
|
231
|
+
*/
|
|
232
|
+
function usesPnpm(tree) {
|
|
233
|
+
if (tree.exists('/pnpm-lock.yaml') || tree.exists('/pnpm-workspace.yaml')) return true;
|
|
234
|
+
const packageManager = readJson(tree, '/angular.json')?.cli?.packageManager;
|
|
235
|
+
if (packageManager) return packageManager === 'pnpm';
|
|
236
|
+
return (process.env.npm_config_user_agent ?? '').startsWith('pnpm/');
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Appends the missing hoist lines to the workspace `.npmrc`. True when it wrote any. */
|
|
240
|
+
function hoistForPnpm(tree, context) {
|
|
241
|
+
if (!usesPnpm(tree)) return false;
|
|
242
|
+
const current = tree.exists('/.npmrc') ? tree.read('/.npmrc').toString('utf8') : '';
|
|
243
|
+
const present = new Set(current.split(/\r?\n/).map((l) => l.trim()));
|
|
244
|
+
const missing = PNPM_HOIST_PATTERNS.map((p) => `public-hoist-pattern[]=${p}`).filter((l) => !present.has(l));
|
|
245
|
+
if (!missing.length) return false;
|
|
246
|
+
const next = `${current}${current && !current.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`;
|
|
247
|
+
if (tree.exists('/.npmrc')) tree.overwrite('/.npmrc', next);
|
|
248
|
+
else tree.create('/.npmrc', next);
|
|
249
|
+
context.logger.info("✔ .npmrc: pnpm hoists the Styloviz packages, so the bundles' components resolve");
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** The app's kit dependencies that are not in node_modules yet. */
|
|
254
|
+
function uninstalledKitPackages(tree) {
|
|
255
|
+
const pkg = readJson(tree, '/package.json') ?? {};
|
|
256
|
+
return Object.keys({ ...pkg.dependencies, ...pkg.devDependencies })
|
|
257
|
+
.filter((name) => /^@styloviz(?:-pro)?\//.test(name))
|
|
258
|
+
.filter((name) => !tree.exists(`/node_modules/${name}/package.json`))
|
|
259
|
+
.sort();
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const SOURCES_COMMAND = 'ng g @styloviz/core:sources';
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Step 8 — `sources`, for `ng add` (the private `ng-add-sources` schematic, run
|
|
266
|
+
* after the install; or in the same run when nothing is to be installed).
|
|
267
|
+
*
|
|
268
|
+
* `ng add` must still succeed when the exact list cannot be written, so the
|
|
269
|
+
* broad lines step 3 wrote stay and the user is told what to run:
|
|
270
|
+
* - a kit package the app depends on is not installed — an exact list made
|
|
271
|
+
* now would leave its files out, and its components unstyled;
|
|
272
|
+
* - `sources` refuses the workspace (a source root that holds node_modules, a
|
|
273
|
+
* Tailwind import with its own `source(…)`): its message says why.
|
|
274
|
+
*
|
|
275
|
+
* @param {{ project?: string }} options
|
|
276
|
+
*/
|
|
277
|
+
function ngAddSources(options = {}) {
|
|
278
|
+
return (tree, context) => {
|
|
279
|
+
const missing = uninstalledKitPackages(tree);
|
|
280
|
+
if (missing.length) {
|
|
281
|
+
context.logger.info(
|
|
282
|
+
` Tailwind scans every installed kit package for now. Once ${missing.join(', ')} ${missing.length === 1 ? 'is' : 'are'} installed, ` +
|
|
283
|
+
`run \`${SOURCES_COMMAND}\` so it reads only the kit files your app uses.`,
|
|
284
|
+
);
|
|
285
|
+
return tree;
|
|
286
|
+
}
|
|
287
|
+
try {
|
|
288
|
+
return sources({ project: options.project })(tree, context);
|
|
289
|
+
} catch (error) {
|
|
290
|
+
if (!(error instanceof SchematicsException)) throw error;
|
|
291
|
+
context.logger.warn(`! Kept the broad @source lines: ${error.message}`);
|
|
292
|
+
return tree;
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** @param {{ project?: string, demo?: boolean, skipInstall?: boolean, sources?: boolean }} options */
|
|
202
298
|
function ngAdd(options = {}) {
|
|
203
299
|
return (tree, context) => {
|
|
204
300
|
const project = resolveProject(tree, options);
|
|
@@ -208,10 +304,30 @@ function ngAdd(options = {}) {
|
|
|
208
304
|
addProvider(tree, context, project.sourceRoot);
|
|
209
305
|
if (options.demo !== false) addDemo(tree, context, project.sourceRoot);
|
|
210
306
|
allowExportCommonJs(tree, context, project.name);
|
|
211
|
-
|
|
307
|
+
// A new hoist pattern only takes effect on the next install, so it asks for one too.
|
|
308
|
+
const hoisted = hoistForPnpm(tree, context);
|
|
309
|
+
let install;
|
|
310
|
+
if ((changed || hoisted) && !options.skipInstall) {
|
|
311
|
+
// ★ pnpm rebuilds node_modules for a new hoist pattern and ASKS first. The
|
|
312
|
+
// task's defaults hide its output and give it no terminal, so pnpm
|
|
313
|
+
// aborted (ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY) — for every user
|
|
314
|
+
// who ran `pnpm add` before `ng add`. This install runs in their terminal.
|
|
315
|
+
// Not `confirmModulesPurge=false` in their config: that would change how
|
|
316
|
+
// pnpm behaves in their project from then on, silently.
|
|
317
|
+
install = context.addTask(hoisted ? new NodePackageInstallTask({ hideOutput: false, quiet: false }) : new NodePackageInstallTask());
|
|
318
|
+
if (hoisted) context.logger.info(' pnpm will ask to rebuild node_modules for the new hoist setting: answer Y.');
|
|
319
|
+
}
|
|
212
320
|
context.logger.info('Styloviz is set up. Docs: https://styloviz.dev/docs — or connect the MCP server: npx -y @styloviz/mcp');
|
|
213
|
-
|
|
321
|
+
if (options.sources === false) {
|
|
322
|
+
context.logger.info(` Tailwind scans every installed kit package. \`${SOURCES_COMMAND}\` makes it read only the kit files your app uses.`);
|
|
323
|
+
return tree;
|
|
324
|
+
}
|
|
325
|
+
if (install !== undefined) {
|
|
326
|
+
context.addTask(new RunSchematicTask('ng-add-sources', { project: project.name }), [install]);
|
|
327
|
+
return tree;
|
|
328
|
+
}
|
|
329
|
+
return ngAddSources({ project: project.name });
|
|
214
330
|
};
|
|
215
331
|
}
|
|
216
332
|
|
|
217
|
-
module.exports = { ngAdd };
|
|
333
|
+
module.exports = { ngAdd, ngAddSources, PNPM_HOIST_PATTERNS };
|
package/ng-add/schema.json
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
"properties": {
|
|
7
7
|
"project": { "type": "string", "description": "The application to set up. Defaults to the first application in angular.json.", "$default": { "$source": "projectName" } },
|
|
8
8
|
"demo": { "type": "boolean", "default": true, "description": "Add a demo page at /styloviz." },
|
|
9
|
-
"skipInstall": { "type": "boolean", "default": false, "description": "Do not run the package manager." }
|
|
9
|
+
"skipInstall": { "type": "boolean", "default": false, "description": "Do not run the package manager." },
|
|
10
|
+
"sources": { "type": "boolean", "default": true, "description": "Point Tailwind at only the kit files the app uses (ng g @styloviz/core:sources). false keeps the broad @source lines that scan every installed kit package." }
|
|
10
11
|
}
|
|
11
12
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@styloviz/schematics",
|
|
3
|
-
"version": "2.0
|
|
4
|
-
"description": "Angular schematics for the Styloviz UI kit — ng add (Tailwind 4, tokens, a demo page), migrate-primeng (PrimeNG 21 selectors to Styloviz) and the kit's ng update migrations.",
|
|
3
|
+
"version": "2.1.0",
|
|
4
|
+
"description": "Angular schematics for the Styloviz UI kit — ng add (Tailwind 4, tokens, a demo page), sources (Tailwind scans only the kit files an app imports), migrate-primeng (PrimeNG 21 selectors to Styloviz) and the kit's ng update migrations.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"angular",
|
|
7
7
|
"schematics",
|
|
@@ -32,8 +32,10 @@
|
|
|
32
32
|
"collection.json",
|
|
33
33
|
"migration.json",
|
|
34
34
|
"ng-add",
|
|
35
|
+
"sources",
|
|
35
36
|
"migrate-primeng",
|
|
36
37
|
"migrations",
|
|
38
|
+
"lib",
|
|
37
39
|
"README.md",
|
|
38
40
|
"LICENSE"
|
|
39
41
|
],
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* `sources --from-build` — the kit files a production build actually ships
|
|
4
|
+
* (live-user test M-1, step A2).
|
|
5
|
+
*
|
|
6
|
+
* The import walk is a safe superset: it keeps a component the app imports but
|
|
7
|
+
* never puts in a template. Angular drops such an import at compile time (it
|
|
8
|
+
* warns NG8113), so the build never ships it — measured on 2.0.2: an unused
|
|
9
|
+
* `SvCheckboxComponent` import is not even among the build's inputs. The build
|
|
10
|
+
* stats (`ng build --stats-json`) are esbuild's metafile; a kit file ships when
|
|
11
|
+
* some output chunk, lazy ones included, holds bytes of it. A file esbuild
|
|
12
|
+
* parsed and then tree-shook to nothing does not ship, so `inputs` alone is
|
|
13
|
+
* the wrong list: 25 parsed against 9 shipped for the `ng add` demo app.
|
|
14
|
+
*/
|
|
15
|
+
const fs = require('node:fs');
|
|
16
|
+
const nodePath = require('node:path');
|
|
17
|
+
const { posix } = require('node:path');
|
|
18
|
+
const { SchematicsException } = require('@angular-devkit/schematics');
|
|
19
|
+
const { buildTarget } = require('../lib/workspace');
|
|
20
|
+
|
|
21
|
+
const STATS_FILES = ['browser-stats.json', 'server-stats.json', 'stats.json'];
|
|
22
|
+
const KIT_FILE = /\/node_modules\/(@styloviz(?:-pro)?\/.+)$/;
|
|
23
|
+
/** pnpm's real path for a hoisted package: node_modules/.pnpm/<id>/node_modules/@scope/name/… */
|
|
24
|
+
const PNPM_STORE = /\/node_modules\/\.pnpm\/[^/]+\/node_modules\/(@styloviz(?:-pro)?\/.+)$/;
|
|
25
|
+
const LOCKFILES = ['/package.json', '/package-lock.json', '/pnpm-lock.yaml', '/yarn.lock', '/bun.lock', '/bun.lockb'];
|
|
26
|
+
|
|
27
|
+
function toTreePath(path) {
|
|
28
|
+
return posix.join('/', path.replace(/\\/g, '/'));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The folder a project's build writes to (angular.json `outputPath`, string or `{ base }`). */
|
|
32
|
+
function outputBase(workspace, name) {
|
|
33
|
+
const outputPath = buildTarget(workspace.projects[name])?.options?.outputPath;
|
|
34
|
+
const base = typeof outputPath === 'string' ? outputPath : outputPath?.base;
|
|
35
|
+
return toTreePath(base || `dist/${name}`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The stats files to read: the one named with --stats, else each app's under its output folder. */
|
|
39
|
+
function statsFiles(tree, workspace, appNames, statsOption) {
|
|
40
|
+
if (statsOption) {
|
|
41
|
+
const path = toTreePath(statsOption);
|
|
42
|
+
if (!tree.exists(path)) throw new SchematicsException(`No build stats at ${statsOption}.`);
|
|
43
|
+
return [path];
|
|
44
|
+
}
|
|
45
|
+
const found = [];
|
|
46
|
+
for (const name of appNames) {
|
|
47
|
+
const base = outputBase(workspace, name);
|
|
48
|
+
const files = STATS_FILES.map((f) => `${base}/${f}`).filter((p) => tree.exists(p));
|
|
49
|
+
if (!files.length) {
|
|
50
|
+
throw new SchematicsException(
|
|
51
|
+
`No build stats for "${name}" in ${base.slice(1)}. Build it first with: ng build ${name} --stats-json — then run this again.`,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
// The application builder writes browser- and server-stats; the old browser builder, stats.json alone.
|
|
55
|
+
found.push(...files.filter((p) => !p.endsWith('/stats.json') || files.length === 1));
|
|
56
|
+
}
|
|
57
|
+
return found;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The kit files that hold bytes in some output of these builds, as workspace
|
|
62
|
+
* paths under node_modules. A pnpm store path is mapped to its hoisted link,
|
|
63
|
+
* which does not change with the installed version.
|
|
64
|
+
*/
|
|
65
|
+
function shippedKitFiles(tree, statsPaths) {
|
|
66
|
+
const shipped = new Set();
|
|
67
|
+
for (const statsPath of statsPaths) {
|
|
68
|
+
let meta;
|
|
69
|
+
try {
|
|
70
|
+
meta = JSON.parse(tree.read(statsPath).toString('utf8'));
|
|
71
|
+
} catch {
|
|
72
|
+
throw new SchematicsException(`${statsPath.slice(1)} is not build stats (expected the JSON that ng build --stats-json writes).`);
|
|
73
|
+
}
|
|
74
|
+
if (!meta || typeof meta.outputs !== 'object') {
|
|
75
|
+
throw new SchematicsException(`${statsPath.slice(1)} has no "outputs": expected the JSON that ng build --stats-json writes.`);
|
|
76
|
+
}
|
|
77
|
+
for (const output of Object.values(meta.outputs)) {
|
|
78
|
+
for (const [input, info] of Object.entries(output?.inputs ?? {})) {
|
|
79
|
+
if (!(info?.bytesInOutput > 0)) continue;
|
|
80
|
+
const path = toTreePath(input.replace(/^[a-z-]+:/i, '')); // esbuild namespaces, e.g. "angular:…"
|
|
81
|
+
const store = PNPM_STORE.exec(path);
|
|
82
|
+
if (store) {
|
|
83
|
+
const hoisted = `/node_modules/${store[1]}`;
|
|
84
|
+
shipped.add(tree.exists(hoisted) ? hoisted : path);
|
|
85
|
+
} else if (KIT_FILE.test(path)) {
|
|
86
|
+
shipped.add(path);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return shipped;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The workspace folder on disk, or null when the tree is not backed by one (tests). */
|
|
95
|
+
function workspaceDir(tree) {
|
|
96
|
+
const marker = tree.read('/angular.json')?.toString('utf8');
|
|
97
|
+
for (let dir = process.cwd(); ; dir = nodePath.dirname(dir)) {
|
|
98
|
+
const candidate = nodePath.join(dir, 'angular.json');
|
|
99
|
+
if (fs.existsSync(candidate)) return fs.readFileSync(candidate, 'utf8') === marker ? dir : null;
|
|
100
|
+
if (nodePath.dirname(dir) === dir) return null;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The first input changed after the build that wrote the stats, or null.
|
|
106
|
+
* `mtime(path)` gives a workspace file's modification time in ms, or null if
|
|
107
|
+
* it has none. Inputs: the app's code and the install (package.json, lockfile).
|
|
108
|
+
*/
|
|
109
|
+
function newerThanBuild(statsPaths, inputs, mtime) {
|
|
110
|
+
const built = Math.min(...statsPaths.map((p) => mtime(p) ?? Infinity));
|
|
111
|
+
if (!Number.isFinite(built)) return null;
|
|
112
|
+
for (const path of inputs) {
|
|
113
|
+
const changed = mtime(path);
|
|
114
|
+
if (changed !== null && changed > built) return path;
|
|
115
|
+
}
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Refuses stats older than the code or the install: their list would leave out what was added since. */
|
|
120
|
+
function assertFresh(tree, statsPaths, appFiles) {
|
|
121
|
+
const dir = workspaceDir(tree);
|
|
122
|
+
if (!dir) return;
|
|
123
|
+
const mtime = (path) => {
|
|
124
|
+
try {
|
|
125
|
+
return fs.statSync(nodePath.join(dir, path)).mtimeMs;
|
|
126
|
+
} catch {
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
const stale = newerThanBuild(statsPaths, [...LOCKFILES, ...appFiles], mtime);
|
|
131
|
+
if (stale) {
|
|
132
|
+
throw new SchematicsException(
|
|
133
|
+
`${stale.slice(1)} changed after the build that wrote ${statsPaths[0].slice(1)}, so its list may miss a component. ` +
|
|
134
|
+
'Build again with --stats-json, then run this again.',
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
module.exports = { statsFiles, shippedKitFiles, assertFresh, newerThanBuild, outputBase };
|