@ngrs/build 0.0.0-stage → 0.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.
@@ -0,0 +1,151 @@
1
+ import { createRequire } from 'node:module';
2
+ import path from 'node:path';
3
+ import {
4
+ parseTargetString,
5
+ resolveProjectName,
6
+ resolveTargetOptions,
7
+ } from './workspace.mjs';
8
+
9
+ export const BuilderSymbol = Symbol.for('@angular-devkit/architect:builder');
10
+ export const BuilderVersionSymbol = Symbol.for('@angular-devkit/architect:version');
11
+
12
+ function tryLoadRealArchitect() {
13
+ const candidates = [
14
+ () => createRequire(path.join(process.cwd(), 'package.json'))('@angular-devkit/architect'),
15
+ () => createRequire(import.meta.url)('@angular-devkit/architect'),
16
+ ];
17
+ for (const load of candidates) {
18
+ try {
19
+ const mod = load();
20
+ if (mod && typeof mod.createBuilder === 'function') {
21
+ return mod;
22
+ }
23
+ } catch {
24
+ // Fall back to lightweight compat wrapper
25
+ }
26
+ }
27
+ return null;
28
+ }
29
+
30
+ /**
31
+ * Wraps an async-generator / promise / sync builder handler using `@angular-devkit/architect`'s
32
+ * `createBuilder` when installed in the workspace (so `ng build` / `ng serve` work natively!), and
33
+ * falls back to a zero-bloat compatible `Builder` descriptor otherwise.
34
+ */
35
+ export function createBuilder(handlerFn) {
36
+ const realArchitect = tryLoadRealArchitect();
37
+ if (realArchitect) {
38
+ const wrapped = realArchitect.createBuilder(handlerFn);
39
+ wrapped.execute = handlerFn;
40
+ return wrapped;
41
+ }
42
+
43
+ return {
44
+ handler: handlerFn,
45
+ execute: handlerFn,
46
+ [BuilderSymbol]: true,
47
+ [BuilderVersionSymbol]: '0.1900.0',
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Creates a clean console `LoggerApi` compatible with `@angular-devkit/core`'s `logging.LoggerApi`.
53
+ */
54
+ export function createConsoleLogger(verbose = false) {
55
+ return {
56
+ createChild() {
57
+ return createConsoleLogger(verbose);
58
+ },
59
+ log(level, message) {
60
+ if (level === 'debug' && !verbose) return;
61
+ if (level === 'error' || level === 'fatal') {
62
+ console.error(message);
63
+ } else if (level === 'warn') {
64
+ console.warn(message);
65
+ } else {
66
+ console.log(message);
67
+ }
68
+ },
69
+ debug(message) {
70
+ if (verbose) {
71
+ console.debug(message);
72
+ }
73
+ },
74
+ info(message) {
75
+ console.log(message);
76
+ },
77
+ warn(message) {
78
+ console.warn(message);
79
+ },
80
+ error(message) {
81
+ console.error(message);
82
+ },
83
+ fatal(message) {
84
+ console.error(message);
85
+ },
86
+ };
87
+ }
88
+
89
+ /**
90
+ * Creates an `@angular-devkit/architect`-compatible `BuilderContext` backed by a loaded
91
+ * `angular.json` workspace for standalone CLI (`ngrs build` / `ngrs serve`) and programmatic runs.
92
+ */
93
+ export function createWorkspaceBuilderContext({
94
+ workspaceRoot,
95
+ workspace,
96
+ target,
97
+ builderName = '@ngrs/build:application',
98
+ logger = createConsoleLogger(false),
99
+ }) {
100
+ const teardowns = [];
101
+
102
+ return {
103
+ id: 1,
104
+ builder: {
105
+ builderName,
106
+ description: 'ngrs builder',
107
+ optionSchema: {},
108
+ },
109
+ logger,
110
+ workspaceRoot,
111
+ currentDirectory: process.cwd(),
112
+ target,
113
+ teardowns,
114
+ addTeardown(fn) {
115
+ teardowns.push(fn);
116
+ },
117
+ reportRunning() {},
118
+ reportStatus() {},
119
+ reportProgress() {},
120
+ async getProjectMetadata(projectOrTarget) {
121
+ const projName =
122
+ typeof projectOrTarget === 'string'
123
+ ? projectOrTarget
124
+ : projectOrTarget?.project || resolveProjectName(workspace);
125
+ const proj = workspace?.projects?.[projName];
126
+ if (!proj) {
127
+ throw new Error(`Project "${projName}" does not exist in workspace.`);
128
+ }
129
+ return proj;
130
+ },
131
+ async getBuilderNameForTarget(t) {
132
+ const proj = workspace?.projects?.[t.project];
133
+ const targets = proj?.architect || proj?.targets || {};
134
+ return targets[t.target]?.builder || '@ngrs/build:application';
135
+ },
136
+ async getTargetOptions(t) {
137
+ return resolveTargetOptions(workspace, t);
138
+ },
139
+ async validateOptions(opts) {
140
+ return opts;
141
+ },
142
+ async runTeardowns() {
143
+ for (const fn of teardowns.splice(0)) {
144
+ await fn();
145
+ }
146
+ },
147
+ parseTarget(spec, defaultProj, defaultTarget) {
148
+ return parseTargetString(spec, defaultProj, defaultTarget);
149
+ },
150
+ };
151
+ }
@@ -0,0 +1,212 @@
1
+ export const BYTES_IN_KILOBYTE = 1000;
2
+
3
+ /**
4
+ * Formats byte counts using Angular CLI's `formatSize` decimal KB/MB/GB convention.
5
+ */
6
+ export function formatSize(bytes) {
7
+ if (bytes <= 0) {
8
+ return '0 bytes';
9
+ }
10
+ const abbreviations = ['bytes', 'kB', 'MB', 'GB'];
11
+ const index = Math.min(
12
+ Math.floor(Math.log(bytes) / Math.log(BYTES_IN_KILOBYTE)),
13
+ abbreviations.length - 1,
14
+ );
15
+ if (index === 0) {
16
+ return `${bytes} ${abbreviations[index]}`;
17
+ }
18
+ const value = bytes / BYTES_IN_KILOBYTE ** index;
19
+ return `${value.toFixed(2)} ${abbreviations[index]}`;
20
+ }
21
+
22
+ /**
23
+ * Parses Angular budget size strings (`"500kB"`, `"1MB"`, `"2kb"`, `"10%"`, `"4096"`), mirroring
24
+ * `calculateBytes` in `@angular/build/src/utils/bundle-calculator.ts`.
25
+ */
26
+ export function calculateBytes(input, baseline, factor = 1) {
27
+ const matches = String(input)
28
+ .trim()
29
+ .match(/^(\d+(?:\.\d+)?)[ \t]*(%|[kmg]?b)?$/i);
30
+ if (!matches) {
31
+ return Number.NaN;
32
+ }
33
+
34
+ const baselineBytes = (baseline && calculateBytes(baseline)) || 0;
35
+ let value = Number(matches[1]);
36
+ const unit = matches[2]?.toLowerCase();
37
+
38
+ switch (unit) {
39
+ case '%':
40
+ value = (baselineBytes * value) / 100;
41
+ break;
42
+ case 'kb':
43
+ value *= BYTES_IN_KILOBYTE;
44
+ break;
45
+ case 'mb':
46
+ value *= BYTES_IN_KILOBYTE * BYTES_IN_KILOBYTE;
47
+ break;
48
+ case 'gb':
49
+ value *= BYTES_IN_KILOBYTE * BYTES_IN_KILOBYTE * BYTES_IN_KILOBYTE;
50
+ break;
51
+ default:
52
+ break;
53
+ }
54
+
55
+ if (baselineBytes === 0) {
56
+ return value;
57
+ }
58
+ return baselineBytes + value * factor;
59
+ }
60
+
61
+ function* calculateThresholds(budget) {
62
+ if (budget.maximumWarning) {
63
+ yield {
64
+ limit: calculateBytes(budget.maximumWarning, budget.baseline, 1),
65
+ type: 'maximum',
66
+ severity: 'warning',
67
+ };
68
+ }
69
+ if (budget.maximumError) {
70
+ yield {
71
+ limit: calculateBytes(budget.maximumError, budget.baseline, 1),
72
+ type: 'maximum',
73
+ severity: 'error',
74
+ };
75
+ }
76
+ if (budget.minimumWarning) {
77
+ yield {
78
+ limit: calculateBytes(budget.minimumWarning, budget.baseline, -1),
79
+ type: 'minimum',
80
+ severity: 'warning',
81
+ };
82
+ }
83
+ if (budget.minimumError) {
84
+ yield {
85
+ limit: calculateBytes(budget.minimumError, budget.baseline, -1),
86
+ type: 'minimum',
87
+ severity: 'error',
88
+ };
89
+ }
90
+ if (budget.warning) {
91
+ yield {
92
+ limit: calculateBytes(budget.warning, budget.baseline, -1),
93
+ type: 'minimum',
94
+ severity: 'warning',
95
+ };
96
+ yield {
97
+ limit: calculateBytes(budget.warning, budget.baseline, 1),
98
+ type: 'maximum',
99
+ severity: 'warning',
100
+ };
101
+ }
102
+ if (budget.error) {
103
+ yield {
104
+ limit: calculateBytes(budget.error, budget.baseline, -1),
105
+ type: 'minimum',
106
+ severity: 'error',
107
+ };
108
+ yield {
109
+ limit: calculateBytes(budget.error, budget.baseline, 1),
110
+ type: 'maximum',
111
+ severity: 'error',
112
+ };
113
+ }
114
+ }
115
+
116
+ function calculateSizesForBudget(budget, stats) {
117
+ const chunks = stats.chunks || [];
118
+ const assets = stats.assets || [];
119
+ const assetSizeMap = new Map(assets.map((a) => [a.name, a.size]));
120
+
121
+ const sumChunkFiles = (chunk) =>
122
+ (chunk.files || [])
123
+ .filter((f) => !f.endsWith('.map'))
124
+ .reduce((acc, f) => acc + (assetSizeMap.get(f) ?? 0), 0);
125
+
126
+ switch (budget.type) {
127
+ case 'initial': {
128
+ const size = chunks
129
+ .filter((c) => c.initial)
130
+ .reduce((acc, c) => acc + sumChunkFiles(c), 0);
131
+ return [{ size, label: 'bundle initial' }];
132
+ }
133
+ case 'bundle': {
134
+ if (!budget.name) return [];
135
+ const size = chunks
136
+ .filter((c) => c.names?.includes(budget.name))
137
+ .reduce((acc, c) => acc + sumChunkFiles(c), 0);
138
+ return [{ size, label: budget.name }];
139
+ }
140
+ case 'allScript': {
141
+ const size = assets
142
+ .filter((a) => !a.componentStyle && /\.[cm]?js$/.test(a.name))
143
+ .reduce((acc, a) => acc + a.size, 0);
144
+ return [{ size, label: 'total scripts' }];
145
+ }
146
+ case 'all': {
147
+ const size = assets
148
+ .filter((a) => !a.name.endsWith('.map') && !a.componentStyle)
149
+ .reduce((acc, a) => acc + a.size, 0);
150
+ return [{ size, label: 'total' }];
151
+ }
152
+ case 'anyScript': {
153
+ return assets
154
+ .filter((a) => !a.componentStyle && /\.[cm]?js$/.test(a.name))
155
+ .map((a) => ({ size: a.size, label: a.name }));
156
+ }
157
+ case 'any': {
158
+ return assets
159
+ .filter((a) => !a.name.endsWith('.map') && !a.componentStyle)
160
+ .map((a) => ({ size: a.size, label: a.name }));
161
+ }
162
+ case 'anyComponentStyle': {
163
+ return assets
164
+ .filter((a) => a.componentStyle)
165
+ .map((a) => ({ size: a.size, label: a.name }));
166
+ }
167
+ default:
168
+ return [];
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Evaluates Angular `budgets` (`initial`, `anyComponentStyle`, `any`, `anyScript`, `all`,
174
+ * `allScript`, `bundle`) against build output stats, returning warnings and errors.
175
+ */
176
+ export function checkBudgets(budgets, stats) {
177
+ if (!budgets?.length) {
178
+ return [];
179
+ }
180
+
181
+ const results = [];
182
+ for (const budget of budgets) {
183
+ const sizes = calculateSizesForBudget(budget, stats);
184
+ const thresholds = [...calculateThresholds(budget)];
185
+ for (const { size, label } of sizes) {
186
+ for (const threshold of thresholds) {
187
+ if (Number.isNaN(threshold.limit)) continue;
188
+ if (threshold.type === 'maximum' && size > threshold.limit) {
189
+ const diff = formatSize(size - threshold.limit);
190
+ results.push({
191
+ severity: threshold.severity,
192
+ label,
193
+ message: `${label} exceeded maximum budget. Budget ${formatSize(
194
+ threshold.limit,
195
+ )} was not met by ${diff} with a total of ${formatSize(size)}.`,
196
+ });
197
+ } else if (threshold.type === 'minimum' && size < threshold.limit) {
198
+ const diff = formatSize(threshold.limit - size);
199
+ results.push({
200
+ severity: threshold.severity,
201
+ label,
202
+ message: `${label} failed to meet minimum budget. Budget ${formatSize(
203
+ threshold.limit,
204
+ )} was not met by ${diff} with a total of ${formatSize(size)}.`,
205
+ });
206
+ }
207
+ }
208
+ }
209
+ }
210
+
211
+ return results;
212
+ }
@@ -0,0 +1,13 @@
1
+ 'use strict';
2
+
3
+ const { createCjsBuilder } = require('../../architect-compat.cjs');
4
+
5
+ async function* buildApplicationProxy(options, context, extensions) {
6
+ const mod = await import('./index.mjs');
7
+ yield* mod.buildApplication(options, context, extensions);
8
+ }
9
+
10
+ const builder = createCjsBuilder(buildApplicationProxy);
11
+ builder.buildApplication = buildApplicationProxy;
12
+
13
+ module.exports = builder;