@styloviz/schematics 2.0.2 → 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 CHANGED
@@ -17,12 +17,74 @@ ng add @styloviz/core
17
17
  - creates `.postcssrc.json` for the Tailwind 4 PostCSS plugin, unless you have a
18
18
  PostCSS config;
19
19
  - prepends `@import "tailwindcss"`, the kit stylesheet and an `@source` for the
20
- kit's templates to your global stylesheet;
20
+ kit's templates to your global stylesheet (`@styloviz-pro` too, when Pro is
21
+ installed);
21
22
  - adds `provideStyloviz()` to `app.config.ts`;
22
- - adds a demo page at `/styloviz` (pass `--demo=false` to skip it).
23
+ - adds a demo page at `/styloviz` (pass `--demo=false` to skip it);
24
+ - under pnpm, adds two lines to `.npmrc` that hoist the `@styloviz/*` and
25
+ `@styloviz-pro/*` packages. pnpm links only your direct dependencies, so
26
+ without them nothing that `@styloviz/all` or `@styloviz-pro/all` brings in
27
+ resolves. pnpm then asks to rebuild `node_modules` once: answer Y;
28
+ - runs `sources` (below), after the install: Tailwind then reads only the kit
29
+ files your app uses, and the first build of a new app fits Angular's default
30
+ budgets. Where that cannot work yet — a kit package in `package.json` that
31
+ is not installed (`--skip-install`), or a source root that contains
32
+ `node_modules` — the broad `@source` lines stay and `ng add` says what to do.
33
+ `--sources=false` keeps the broad lines.
23
34
 
24
35
  Running it again changes nothing. The same schematic is `ng add @styloviz/schematics`.
25
36
 
37
+ ## `ng g @styloviz/core:sources`
38
+
39
+ Makes an app pay, in stylesheet size, only for the kit components it uses:
40
+
41
+ ```sh
42
+ ng g @styloviz/core:sources # write the list
43
+ ng g @styloviz/core:sources --check # in CI: fail when the list is out of date
44
+ ng g @styloviz/core:sources --all # go back to scanning every kit package
45
+
46
+ ng build --stats-json # exact: what the production build ships
47
+ ng g @styloviz/core:sources --from-build
48
+ ```
49
+
50
+ A broad `@source` for `node_modules/@styloviz` scans every installed package. With an install
51
+ bundle that is every package, so even an empty app builds a 434 kB stylesheet
52
+ and an initial bundle over Angular's 500 kB budget warning. `ng add` runs this
53
+ schematic for you; run it yourself after you change your kit imports. It follows the app's
54
+ imports into the installed packages — by name through each package's barrel, so
55
+ one checkbox from `@styloviz/forms` reaches the checkbox file and nothing else —
56
+ and writes one `@source` per kit file reached into a marked block of the global
57
+ stylesheet. The `ng add` demo app goes from 434 kB to 86 kB of CSS.
58
+
59
+ It also adds `source(none)` to `@import "tailwindcss"`. That is needed: Tailwind
60
+ widens a file `@source` inside `node_modules` to its whole package whenever
61
+ another source contains `node_modules`, and the default import scans the whole
62
+ workspace. So the block also lists what the automatic scan used to find: the
63
+ app's source root, every library project's source root, the build's asset
64
+ folders, and any app file imported from outside them.
65
+
66
+ It also imports the kit stylesheet in parts. `@styloviz/core/styles/styloviz.css`
67
+ is shipped cut into `styles/parts/*.css` too: the tokens and the bare-border
68
+ default every app needs, and the rest — the glow, each preset theme, each
69
+ component's animations — as parts of their own. The single import becomes a
70
+ second marked block of `@import`s for the parts your code and the listed kit
71
+ files mention, in styloviz.css's order, so the cascade is unchanged. The `ng
72
+ add` demo app goes from 86 kB to 47 kB of CSS this way. A preset whose class
73
+ name your code builds at run time (`'sv-theme-' + name`) brings all four.
74
+
75
+ By default the list is every kit file the imports reach, which is a safe
76
+ superset: a component you import but never put in a template is still listed.
77
+ `--from-build` reads the kit files a production build actually shipped from its
78
+ `--stats-json` output instead (lazy chunks and the server build included), and
79
+ refuses stats older than your code or your install. `--stats <file>` names the
80
+ stats file when it is not in the app's output folder.
81
+
82
+ Run it again whenever you import another kit component; `--check` catches a
83
+ forgotten run (with `--from-build`, after a fresh `ng build --stats-json`). In a
84
+ development build, a component whose file is missing from the list says so in
85
+ the console, with this command. A class name built at run time from pieces (`'bg-' + tone`)
86
+ was never found by any scan; list it with `@source inline("…")`.
87
+
26
88
  ## `ng g @styloviz/schematics:migrate-primeng`
27
89
 
28
90
  Moves a PrimeNG 21 app onto Styloviz, applying the selector map that
package/collection.json CHANGED
@@ -6,6 +6,18 @@
6
6
  "factory": "./ng-add/index#ngAdd",
7
7
  "schema": "./ng-add/schema.json"
8
8
  },
9
+ "ng-add-sources": {
10
+ "description": "ng add, step 8: run sources once the packages are installed, keeping the broad lines where an exact list cannot be written.",
11
+ "factory": "./ng-add/index#ngAddSources",
12
+ "schema": "./ng-add/sources-schema.json",
13
+ "private": true,
14
+ "hidden": true
15
+ },
16
+ "sources": {
17
+ "description": "Point Tailwind at only the kit files the app imports, in one marked block of the global stylesheet. --check fails when it is out of date; --all scans every installed kit package again.",
18
+ "factory": "./sources/index#sources",
19
+ "schema": "./sources/schema.json"
20
+ },
9
21
  "migrate-primeng": {
10
22
  "description": "Rewrite PrimeNG 21 component selectors and imports to their Styloviz equivalents, and report what could not be mapped.",
11
23
  "factory": "./migrate-primeng/index#migratePrimeng",
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+ /**
3
+ * The marked block `ng g @styloviz/core:sources` owns in an app's global
4
+ * stylesheet. `ng add` reads it too: once the block is there, the block decides
5
+ * what Tailwind scans, and `ng add` must not put the broad line back.
6
+ */
7
+ const BLOCK_START =
8
+ '/* styloviz:sources start — written by `ng g @styloviz/core:sources` from what this app imports. ' +
9
+ 'Run it again after importing another kit component; `--check` fails when this list is out of date. ' +
10
+ 'Do not edit between the two markers. */';
11
+ const BLOCK_END = '/* styloviz:sources end */';
12
+
13
+ const START_MARK = 'styloviz:sources start';
14
+ const END_MARK = 'styloviz:sources end';
15
+
16
+ /**
17
+ * The second block: the parts of the kit stylesheet the app uses, in place of
18
+ * the single `@import "@styloviz/core/styles/styloviz.css"` (M-1, step A3).
19
+ */
20
+ const PARTS_START =
21
+ '/* styloviz:parts start — written by `ng g @styloviz/core:sources`: the parts of the kit stylesheet this app uses, ' +
22
+ 'in the order styloviz.css has them. `--all` puts the single styloviz.css import back. Do not edit between the two markers. */';
23
+ const PARTS_END = '/* styloviz:parts end */';
24
+ const PARTS_START_MARK = 'styloviz:parts start';
25
+ const PARTS_END_MARK = 'styloviz:parts end';
26
+
27
+ /** Whether a stylesheet already carries the @source block. */
28
+ function hasSourcesBlock(css) {
29
+ return css.includes(START_MARK);
30
+ }
31
+
32
+ /** Whether a stylesheet imports the kit stylesheet in parts. */
33
+ function hasPartsBlock(css) {
34
+ return css.includes(PARTS_START_MARK);
35
+ }
36
+
37
+ module.exports = {
38
+ BLOCK_START,
39
+ BLOCK_END,
40
+ START_MARK,
41
+ END_MARK,
42
+ PARTS_START,
43
+ PARTS_END,
44
+ PARTS_START_MARK,
45
+ PARTS_END_MARK,
46
+ hasSourcesBlock,
47
+ hasPartsBlock,
48
+ };
@@ -0,0 +1,54 @@
1
+ 'use strict';
2
+ /**
3
+ * Reading angular.json — shared by `ng add` and `sources`, so both agree on
4
+ * which project is an app, where its code lives and which stylesheet is global.
5
+ */
6
+ const { SchematicsException } = require('@angular-devkit/schematics');
7
+ const { posix } = require('node:path');
8
+
9
+ function readJson(tree, path) {
10
+ const buf = tree.read(path);
11
+ if (!buf) return null;
12
+ try {
13
+ return JSON.parse(buf.toString('utf8'));
14
+ } catch {
15
+ throw new SchematicsException(`${path} is not valid JSON.`);
16
+ }
17
+ }
18
+
19
+ function readWorkspace(tree) {
20
+ const workspace = readJson(tree, '/angular.json');
21
+ if (!workspace) throw new SchematicsException('No angular.json — run this inside an Angular workspace.');
22
+ return workspace;
23
+ }
24
+
25
+ /** The project's build target, under either spelling angular.json allows. */
26
+ function buildTarget(project) {
27
+ return project.architect?.build ?? project.targets?.build;
28
+ }
29
+
30
+ /** Where a project's files are: its root, and its source root (default `<root>/src`). */
31
+ function projectPaths(project) {
32
+ const root = project.root || '';
33
+ return { root, sourceRoot: project.sourceRoot || posix.join(root, 'src') };
34
+ }
35
+
36
+ /** The first global `.css` stylesheet the project's build lists, or null. */
37
+ function globalCss(project) {
38
+ const styles = buildTarget(project)?.options?.styles ?? [];
39
+ return styles.map((s) => (typeof s === 'string' ? s : s.input)).find((s) => /\.css$/.test(s)) ?? null;
40
+ }
41
+
42
+ /** The app `ng add` sets up, and where its files are. */
43
+ function resolveProject(tree, options) {
44
+ const workspace = readWorkspace(tree);
45
+ const name =
46
+ options.project ||
47
+ Object.keys(workspace.projects).find((p) => workspace.projects[p].projectType === 'application');
48
+ const project = name && workspace.projects[name];
49
+ if (!project) throw new SchematicsException(`No application project ${options.project ? `"${options.project}" ` : ''}in angular.json.`);
50
+ const { root, sourceRoot } = projectPaths(project);
51
+ return { name, root, sourceRoot, styles: globalCss(project) ?? posix.join(sourceRoot, 'styles.css') };
52
+ }
53
+
54
+ module.exports = { readJson, readWorkspace, buildTarget, projectPaths, globalCss, resolveProject };
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, prepended once.
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
- ].filter(([marker]) => !marker.test(current)).map(([, line]) => line);
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
- /** @param {{ project?: string, demo?: boolean, skipInstall?: boolean }} options */
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
- if (changed && !options.skipInstall) context.addTask(new NodePackageInstallTask());
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
- return tree;
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 };
@@ -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
  }
@@ -0,0 +1,9 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema",
3
+ "$id": "StylovizNgAddSources",
4
+ "title": "Styloviz ng add — sources step",
5
+ "type": "object",
6
+ "properties": {
7
+ "project": { "type": "string", "description": "The application ng add set up." }
8
+ }
9
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@styloviz/schematics",
3
- "version": "2.0.2",
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 };