solid-optimizer 0.2.0 → 0.4.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.
Files changed (53) hide show
  1. package/README.md +294 -14
  2. package/dist/compile-BQuBDA0Q.d.mts +199 -0
  3. package/dist/compile-BQuBDA0Q.d.mts.map +1 -0
  4. package/dist/compile-D3caSUtw.mjs +4244 -0
  5. package/dist/compile-D3caSUtw.mjs.map +1 -0
  6. package/dist/index.d.mts +2 -0
  7. package/dist/index.mjs +2 -0
  8. package/dist/vite.d.mts +53 -0
  9. package/dist/vite.d.mts.map +1 -0
  10. package/dist/vite.mjs +1743 -0
  11. package/dist/vite.mjs.map +1 -0
  12. package/package.json +60 -58
  13. package/src/ast.ts +271 -0
  14. package/src/compile.ts +355 -0
  15. package/src/constants.ts +249 -0
  16. package/src/context.ts +116 -0
  17. package/src/fold.ts +850 -0
  18. package/src/index.ts +5 -107
  19. package/src/inline.ts +2237 -0
  20. package/src/jsx.ts +170 -0
  21. package/src/memo.ts +416 -0
  22. package/src/provider.ts +899 -0
  23. package/src/scope.ts +588 -0
  24. package/src/server.ts +275 -0
  25. package/src/size.ts +309 -0
  26. package/src/value.ts +386 -0
  27. package/src/vite/index.ts +1378 -0
  28. package/src/vite/inject.ts +350 -0
  29. package/src/vite/namespace.ts +66 -0
  30. package/src/vite/refs.ts +99 -0
  31. package/src/vite/report.ts +74 -0
  32. package/src/vite/runtime.ts +370 -0
  33. package/src/vite/usage.ts +405 -0
  34. package/dist/cjs/development/index.cjs +0 -228
  35. package/dist/cjs/development/index.cjs.map +0 -7
  36. package/dist/cjs/production/index.cjs +0 -1
  37. package/dist/esm/development/index.mjs +0 -197
  38. package/dist/esm/development/index.mjs.map +0 -7
  39. package/dist/esm/production/index.mjs +0 -1
  40. package/dist/types/checks.d.ts +0 -9
  41. package/dist/types/checks.d.ts.map +0 -1
  42. package/dist/types/index.d.ts +0 -3
  43. package/dist/types/index.d.ts.map +0 -1
  44. package/dist/types/path-references-import.d.ts +0 -3
  45. package/dist/types/path-references-import.d.ts.map +0 -1
  46. package/dist/types/unwrap-node.d.ts +0 -7
  47. package/dist/types/unwrap-node.d.ts.map +0 -1
  48. package/dist/types/unwrap-path.d.ts +0 -6
  49. package/dist/types/unwrap-path.d.ts.map +0 -1
  50. package/src/checks.ts +0 -42
  51. package/src/path-references-import.ts +0 -82
  52. package/src/unwrap-node.ts +0 -27
  53. package/src/unwrap-path.ts +0 -18
@@ -0,0 +1,350 @@
1
+ /**
2
+ * Copies components from other modules into a module before bundling, so
3
+ * the inline pass can inline them there.
4
+ *
5
+ * In chunk mode, the chunk step inlines any component in the same chunk.
6
+ * It runs after the bundler has split the chunks, so a shared chunk still
7
+ * exports what an inlined component needed, like the runtime's `spread`.
8
+ * Inlining an imported component while its importer is transformed lets
9
+ * the bundler drop the component, and what only it used, before splitting.
10
+ *
11
+ * A copy refers to the bindings of its own module. Imports are imported
12
+ * again by the module they resolve to. A binding the module declares but
13
+ * does not export is exported under an extra name, which `exposeLocals`
14
+ * adds when the module is transformed.
15
+ */
16
+ import MagicString from 'magic-string';
17
+ import type { Expression, Node, Program } from 'oxc-parser';
18
+ import { forEachChild, parse, unwrap } from '../ast';
19
+ import type { Binding, ScopeAnalysis } from '../scope';
20
+ import { analyzeScopes } from '../scope';
21
+ import { MARKER } from './runtime';
22
+ import type { EditResult } from './runtime';
23
+
24
+ /**
25
+ * Whether a binding is `const X = createContext(...)`, with `createContext`
26
+ * imported from Solid.
27
+ */
28
+ function isContext(
29
+ binding: Binding,
30
+ scopes: ScopeAnalysis,
31
+ moduleSources: readonly string[],
32
+ ): boolean {
33
+ const { declaration } = binding;
34
+ if (
35
+ binding.kind !== 'const' ||
36
+ binding.mutated ||
37
+ declaration.type !== 'VariableDeclarator' ||
38
+ !declaration.init
39
+ ) {
40
+ return false;
41
+ }
42
+ const init = unwrap(declaration.init);
43
+ if (init.type !== 'CallExpression' || init.callee.type !== 'Identifier') {
44
+ return false;
45
+ }
46
+ const callee = scopes.references.get(init.callee);
47
+ return (
48
+ callee?.kind === 'import' &&
49
+ callee.imported === 'createContext' &&
50
+ callee.source !== undefined &&
51
+ moduleSources.includes(callee.source)
52
+ );
53
+ }
54
+
55
+ /** The prefix of the name a module exports a local binding under. */
56
+ export const LOCAL_EXPORT = '__so_local$';
57
+
58
+ function generateMap(s: MagicString, filename: string): string {
59
+ return s.generateMap({ source: filename, hires: true, includeContent: true }).toString();
60
+ }
61
+
62
+ function isCapitalized(name: string): boolean {
63
+ return /^[A-Z]/.test(name);
64
+ }
65
+
66
+ interface TopLevelFunction {
67
+ readonly binding: Binding;
68
+ /** The function, or the arrow or function expression a `const` holds. */
69
+ readonly fn: Node;
70
+ /** The node to copy: the function declaration, or the expression. */
71
+ readonly kind: 'declaration' | 'expression';
72
+ }
73
+
74
+ /**
75
+ * The function a top-level binding holds: `function A() {}`, or
76
+ * `const A = () => ...`.
77
+ */
78
+ function functionOf(binding: Binding): TopLevelFunction | undefined {
79
+ const { declaration } = binding;
80
+ if (declaration.type === 'FunctionDeclaration') {
81
+ return { binding, fn: declaration, kind: 'declaration' };
82
+ }
83
+ if (
84
+ declaration.type === 'VariableDeclarator' &&
85
+ binding.kind === 'const' &&
86
+ declaration.id === binding.identifier &&
87
+ declaration.init
88
+ ) {
89
+ const init = unwrap(declaration.init);
90
+ if (init.type === 'ArrowFunctionExpression' || init.type === 'FunctionExpression') {
91
+ return { binding, fn: init, kind: 'expression' };
92
+ }
93
+ }
94
+ return undefined;
95
+ }
96
+
97
+ /**
98
+ * The names a module exports, each with the top-level binding it exports.
99
+ */
100
+ function exportsOf(program: Program, scopes: ScopeAnalysis): Map<string, Binding> {
101
+ const exports = new Map<string, Binding>();
102
+ const { bindings } = scopes.root;
103
+ for (const statement of program.body) {
104
+ if (statement.type === 'ExportNamedDeclaration' && !statement.source) {
105
+ const { declaration } = statement;
106
+ if (declaration?.type === 'FunctionDeclaration' && declaration.id) {
107
+ const binding = bindings.get(declaration.id.name);
108
+ if (binding) {
109
+ exports.set(declaration.id.name, binding);
110
+ }
111
+ } else if (declaration?.type === 'VariableDeclaration') {
112
+ const declared = declaration.declarations.map((declarator) =>
113
+ declarator.id.type === 'Identifier' ? bindings.get(declarator.id.name) : undefined,
114
+ );
115
+ for (const binding of declared.filter((item) => item !== undefined)) {
116
+ exports.set(binding.name, binding);
117
+ }
118
+ }
119
+ for (const specifier of statement.specifiers) {
120
+ const local = specifier.local.type === 'Identifier' ? specifier.local.name : undefined;
121
+ const exported =
122
+ specifier.exported.type === 'Identifier'
123
+ ? specifier.exported.name
124
+ : specifier.exported.value;
125
+ const binding = local === undefined ? undefined : bindings.get(local);
126
+ if (binding) {
127
+ exports.set(exported, binding);
128
+ }
129
+ }
130
+ } else if (statement.type === 'ExportDefaultDeclaration') {
131
+ const { declaration } = statement;
132
+ if (declaration.type === 'FunctionDeclaration' && declaration.id) {
133
+ const binding = bindings.get(declaration.id.name);
134
+ if (binding) {
135
+ exports.set('default', binding);
136
+ }
137
+ } else if (declaration.type === 'Identifier') {
138
+ const binding = bindings.get(declaration.name);
139
+ if (binding) {
140
+ exports.set('default', binding);
141
+ }
142
+ }
143
+ }
144
+ }
145
+ return exports;
146
+ }
147
+
148
+ /**
149
+ * The top-level bindings a function refers to, other than itself.
150
+ */
151
+ function outerBindings(fn: Node, self: Binding, scopes: ScopeAnalysis): Map<Node, Binding> {
152
+ const outer = new Map<Node, Binding>();
153
+ for (const [reference, binding] of scopes.references) {
154
+ if (
155
+ binding &&
156
+ binding !== self &&
157
+ binding.scope === scopes.root &&
158
+ reference.start >= fn.start &&
159
+ reference.end <= fn.end
160
+ ) {
161
+ outer.set(reference, binding);
162
+ }
163
+ }
164
+ return outer;
165
+ }
166
+
167
+ /**
168
+ * Exports the top-level bindings that the module's exported components
169
+ * refer to but the module does not export, under an extra name. A copy of
170
+ * such a component in another module imports them from here.
171
+ */
172
+ export function exposeLocals(code: string, filename: string): EditResult | undefined {
173
+ const program = parse(filename, code);
174
+ const scopes = analyzeScopes(program);
175
+ const exports = exportsOf(program, scopes);
176
+ const exported = new Set(exports.values());
177
+ const needed = new Set<Binding>();
178
+ for (const [name, binding] of exports) {
179
+ const component =
180
+ isCapitalized(binding.name) || name === 'default' ? functionOf(binding) : undefined;
181
+ if (!component) {
182
+ continue;
183
+ }
184
+ for (const outer of outerBindings(component.fn, binding, scopes).values()) {
185
+ if (outer.kind !== 'import' && !exported.has(outer)) {
186
+ needed.add(outer);
187
+ }
188
+ }
189
+ }
190
+ if (needed.size === 0) {
191
+ return undefined;
192
+ }
193
+ const s = new MagicString(code);
194
+ const specifiers = [...needed].map(
195
+ (binding) => `${binding.name} as ${LOCAL_EXPORT}${binding.name}`,
196
+ );
197
+ s.append(`\nexport { ${specifiers.join(', ')} };\n`);
198
+ return { code: s.toString(), map: generateMap(s, filename) };
199
+ }
200
+
201
+ /** A binding a copied component needs from its own module's scope. */
202
+ export type Dependency =
203
+ /** An import of that module, imported again by the module it resolves to. */
204
+ | { readonly kind: 'import'; readonly source: string; readonly imported: string }
205
+ /** A binding that module exports, imported from it under this name. */
206
+ | { readonly kind: 'export'; readonly exported: string; readonly context: boolean };
207
+
208
+ export interface ExportedComponent {
209
+ /** Each top-level binding the component refers to, by its name in the module. */
210
+ readonly dependencies: ReadonlyMap<string, Dependency>;
211
+ /**
212
+ * The component's declaration under `name`, with each dependency renamed
213
+ * as `rename` gives it.
214
+ */
215
+ readonly copy: (name: string, rename: ReadonlyMap<string, string>) => string;
216
+ /**
217
+ * Whether the component only returns a call of another component of its
218
+ * module, like `(props) => <Icon {...props}><path /></Icon>`.
219
+ */
220
+ readonly wrapsLocal: boolean;
221
+ }
222
+
223
+ /**
224
+ * Whether a function returns JSX whose root calls a component declared at
225
+ * the top of its own module.
226
+ */
227
+ function returnsLocalCall(fn: TopLevelFunction['fn'], scopes: ScopeAnalysis): boolean {
228
+ if (
229
+ fn.type !== 'FunctionDeclaration' &&
230
+ fn.type !== 'FunctionExpression' &&
231
+ fn.type !== 'ArrowFunctionExpression'
232
+ ) {
233
+ return false;
234
+ }
235
+ const { body } = fn;
236
+ if (!body) {
237
+ return false;
238
+ }
239
+ let root: Expression | null | undefined;
240
+ if (body.type === 'BlockStatement') {
241
+ const last = body.body.at(-1);
242
+ root = last?.type === 'ReturnStatement' ? last.argument : undefined;
243
+ } else {
244
+ root = body;
245
+ }
246
+ if (!root) {
247
+ return false;
248
+ }
249
+ const inner = unwrap(root);
250
+ if (inner.type !== 'JSXElement' || inner.openingElement.name.type !== 'JSXIdentifier') {
251
+ return false;
252
+ }
253
+ const binding = scopes.references.get(inner.openingElement.name);
254
+ return binding !== undefined && binding.scope === scopes.root && binding.kind !== 'import';
255
+ }
256
+
257
+ /**
258
+ * Reads the component a module exports under `exportName`, from the module
259
+ * as the bundler loaded it. `undefined` when that export is not a function
260
+ * component, or it refers to a top-level binding the module cannot export.
261
+ */
262
+ export function readExportedComponent(
263
+ code: string,
264
+ filename: string,
265
+ exportName: string,
266
+ moduleSources: readonly string[],
267
+ ): ExportedComponent | undefined {
268
+ const program = parse(filename, code);
269
+ const scopes = analyzeScopes(program);
270
+ const exports = exportsOf(program, scopes);
271
+ const binding = exports.get(exportName);
272
+ const component = binding ? functionOf(binding) : undefined;
273
+ if (!binding || !component) {
274
+ return undefined;
275
+ }
276
+ const exportNames = new Map<Binding, string>();
277
+ for (const [name, exported] of exports) {
278
+ if (!exportNames.has(exported)) {
279
+ exportNames.set(exported, name);
280
+ }
281
+ }
282
+
283
+ const outer = outerBindings(component.fn, binding, scopes);
284
+ const dependencies = new Map<string, Dependency>();
285
+ for (const dependency of outer.values()) {
286
+ if (dependencies.has(dependency.name)) {
287
+ continue;
288
+ }
289
+ if (dependency.kind === 'import') {
290
+ if (dependency.source === undefined || dependency.imported === undefined) {
291
+ return undefined;
292
+ }
293
+ dependencies.set(dependency.name, {
294
+ kind: 'import',
295
+ source: dependency.source,
296
+ imported: dependency.imported,
297
+ });
298
+ continue;
299
+ }
300
+ // A local binding is exported under its extra name, which `exposeLocals` added.
301
+ const name = exportNames.get(dependency);
302
+ if (name === undefined) {
303
+ return undefined;
304
+ }
305
+ dependencies.set(dependency.name, {
306
+ kind: 'export',
307
+ exported: name,
308
+ context: isContext(dependency, scopes, moduleSources),
309
+ });
310
+ }
311
+
312
+ // The helper markers in the copy belong to the module it comes from.
313
+ const markers: Node[] = [];
314
+ const findMarkers = (node: Node): void => {
315
+ if (
316
+ node.type === 'ExpressionStatement' &&
317
+ node.expression.type === 'CallExpression' &&
318
+ node.expression.callee.type === 'Identifier' &&
319
+ node.expression.callee.name === MARKER
320
+ ) {
321
+ markers.push(node);
322
+ return;
323
+ }
324
+ forEachChild(node, findMarkers);
325
+ };
326
+ findMarkers(component.fn);
327
+
328
+ const copy = (name: string, rename: ReadonlyMap<string, string>): string => {
329
+ const s = new MagicString(code);
330
+ for (const [reference, dependency] of outer) {
331
+ const renamed = rename.get(dependency.name);
332
+ if (renamed !== undefined && renamed !== dependency.name) {
333
+ s.overwrite(reference.start, reference.end, renamed);
334
+ }
335
+ }
336
+ for (const marker of markers) {
337
+ s.remove(marker.start, marker.end);
338
+ }
339
+ if (
340
+ component.kind === 'declaration' &&
341
+ component.fn.type === 'FunctionDeclaration' &&
342
+ component.fn.id
343
+ ) {
344
+ s.overwrite(component.fn.id.start, component.fn.id.end, name);
345
+ return s.slice(component.fn.start, component.fn.end);
346
+ }
347
+ return `const ${name} = ${s.slice(component.fn.start, component.fn.end)};`;
348
+ };
349
+ return { dependencies, copy, wrapsLocal: returnsLocalCall(component.fn, scopes) };
350
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Rewrites JSX tags that read a member of a namespace import, like
3
+ * `<Button.Root>` with `import * as Button from '...'`, to a named import.
4
+ *
5
+ * A bundler resolves `Button.Root` in code to the export it reads, and
6
+ * drops the namespace. In a JSX tag name it does not, so a module that
7
+ * keeps its JSX through bundling would make the bundle build a namespace
8
+ * object with every export of the module.
9
+ */
10
+ import MagicString from 'magic-string';
11
+ import { collectParents, parse } from '../ast';
12
+ import { analyzeScopes } from '../scope';
13
+ import type { EditResult } from './runtime';
14
+
15
+ export function nameNamespaceTags(code: string, filename: string): EditResult | undefined {
16
+ const program = parse(filename, code);
17
+ const scopes = analyzeScopes(program);
18
+ const parents = collectParents(program);
19
+ const s = new MagicString(code);
20
+ const names = new Set(scopes.names);
21
+ const imports: string[] = [];
22
+ for (const binding of scopes.root.bindings.values()) {
23
+ const statement = parents.get(binding.declaration);
24
+ if (
25
+ binding.kind !== 'import' ||
26
+ binding.imported !== '*' ||
27
+ binding.source === undefined ||
28
+ statement?.type !== 'ImportDeclaration' ||
29
+ statement.importKind === 'type'
30
+ ) {
31
+ continue;
32
+ }
33
+ // One local name for each member, shared by its opening and closing tags.
34
+ const locals = new Map<string, string>();
35
+ for (const reference of binding.references) {
36
+ const member = parents.get(reference);
37
+ if (
38
+ reference.type !== 'JSXIdentifier' ||
39
+ member?.type !== 'JSXMemberExpression' ||
40
+ member.object !== reference
41
+ ) {
42
+ continue;
43
+ }
44
+ const { name } = member.property;
45
+ let local = locals.get(name);
46
+ if (local === undefined) {
47
+ local = `${binding.name}$${name}`;
48
+ for (let index = 1; names.has(local); index += 1) {
49
+ local = `${binding.name}$${name}$${String(index)}`;
50
+ }
51
+ names.add(local);
52
+ locals.set(name, local);
53
+ imports.push(`import { ${name} as ${local} } from ${JSON.stringify(binding.source)};`);
54
+ }
55
+ s.overwrite(member.start, member.end, local);
56
+ }
57
+ }
58
+ if (imports.length === 0) {
59
+ return undefined;
60
+ }
61
+ s.prepend(`${imports.join('\n')}\n`);
62
+ return {
63
+ code: s.toString(),
64
+ map: s.generateMap({ source: filename, hires: true, includeContent: true }).toString(),
65
+ };
66
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Keeps a `ref` that names a variable working through bundling.
3
+ *
4
+ * Solid's JSX transform turns `<input ref={el} />` into code that assigns
5
+ * the element to `el`. In chunk mode the JSX reaches the bundler before that
6
+ * code exists, so the bundler only sees `el` read. A `let el` that nothing
7
+ * else writes to then looks like it is always `undefined`, and the bundler
8
+ * folds its reads, like `el ? el.value : ''`, to the `undefined` branch.
9
+ *
10
+ * Before bundling, `ref={el}` becomes `ref={__SO_REF__(el, (v) => (el = v))}`,
11
+ * which shows the bundler the write. The bundler renames both uses of `el`
12
+ * alike. Before the chunk is lowered, the call becomes `ref={el}` again, so
13
+ * the JSX transform writes the same code it would have.
14
+ */
15
+ import type { CallExpression, JSXAttribute, Node } from 'oxc-parser';
16
+ import MagicString from 'magic-string';
17
+ import { forEachChild, parse } from '../ast';
18
+ import { analyzeScopes } from '../scope';
19
+ import type { EditResult } from './runtime';
20
+
21
+ export const REF_MARKER = '__SO_REF__';
22
+
23
+ function generateMap(s: MagicString, filename: string): string {
24
+ return s.generateMap({ source: filename, hires: true, includeContent: true }).toString();
25
+ }
26
+
27
+ function isRefAttribute(node: Node): node is JSXAttribute {
28
+ return (
29
+ node.type === 'JSXAttribute' && node.name.type === 'JSXIdentifier' && node.name.name === 'ref'
30
+ );
31
+ }
32
+
33
+ /**
34
+ * Wraps each `ref` whose value is a `let` or `var` binding, so the bundler
35
+ * sees it written. `undefined` when there is none.
36
+ */
37
+ export function protectRefs(code: string, filename: string): EditResult | undefined {
38
+ if (!code.includes('ref')) {
39
+ return undefined;
40
+ }
41
+ const program = parse(filename, code);
42
+ const scopes = analyzeScopes(program);
43
+ const s = new MagicString(code);
44
+ const visit = (node: Node): void => {
45
+ if (isRefAttribute(node) && node.value?.type === 'JSXExpressionContainer') {
46
+ const { expression } = node.value;
47
+ const binding =
48
+ expression.type === 'Identifier' ? scopes.references.get(expression) : undefined;
49
+ if (
50
+ expression.type === 'Identifier' &&
51
+ (binding?.kind === 'let' || binding?.kind === 'var')
52
+ ) {
53
+ const { name } = expression;
54
+ s.overwrite(
55
+ expression.start,
56
+ expression.end,
57
+ `${REF_MARKER}(${name}, (__so_ref) => (${name} = __so_ref))`,
58
+ );
59
+ }
60
+ }
61
+ forEachChild(node, visit);
62
+ };
63
+ visit(program);
64
+ return s.hasChanged() ? { code: s.toString(), map: generateMap(s, filename) } : undefined;
65
+ }
66
+
67
+ /**
68
+ * Turns each wrapped `ref` back into its variable. `undefined` when there
69
+ * is none.
70
+ */
71
+ export function restoreRefs(code: string, filename: string): EditResult | undefined {
72
+ if (!code.includes(REF_MARKER)) {
73
+ return undefined;
74
+ }
75
+ const program = parse(filename, code);
76
+ const s = new MagicString(code);
77
+ const visit = (node: Node): void => {
78
+ if (isRefAttribute(node) && node.value?.type === 'JSXExpressionContainer') {
79
+ const { expression } = node.value;
80
+ if (isMarkerCall(expression)) {
81
+ const target = expression.arguments.at(0);
82
+ if (target?.type === 'Identifier') {
83
+ s.overwrite(expression.start, expression.end, target.name);
84
+ }
85
+ }
86
+ }
87
+ forEachChild(node, visit);
88
+ };
89
+ visit(program);
90
+ return s.hasChanged() ? { code: s.toString(), map: generateMap(s, filename) } : undefined;
91
+ }
92
+
93
+ function isMarkerCall(node: Node): node is CallExpression {
94
+ return (
95
+ node.type === 'CallExpression' &&
96
+ node.callee.type === 'Identifier' &&
97
+ node.callee.name === REF_MARKER
98
+ );
99
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The report of what the optimizer leaves alone in a build, and why.
3
+ *
4
+ * Each pass records a short reason code for every component call, provider,
5
+ * and memo it does not optimize. The plugin collects them from the final
6
+ * compile of each chunk or module, and prints them grouped by reason.
7
+ */
8
+ import type { Skip, SkipPass } from '../context';
9
+
10
+ /** What the optimizer left alone in one build environment. */
11
+ export interface OptimizerReport {
12
+ /** The Vite environment, like `client` or `ssr`. */
13
+ readonly environment: string;
14
+ readonly skips: readonly Skip[];
15
+ }
16
+
17
+ export interface ReasonSummary {
18
+ readonly pass: SkipPass;
19
+ readonly reason: string;
20
+ readonly count: number;
21
+ /** How many times each name was skipped for this reason, most first. */
22
+ readonly names: readonly (readonly [string, number])[];
23
+ }
24
+
25
+ /**
26
+ * Groups skips by pass and reason, most frequent first.
27
+ */
28
+ export function summarizeSkips(skips: readonly Skip[]): ReasonSummary[] {
29
+ const groups = new Map<string, { pass: SkipPass; reason: string; names: Map<string, number> }>();
30
+ for (const skip of skips) {
31
+ const key = `${skip.pass}\0${skip.reason}`;
32
+ const group = groups.get(key) ?? { pass: skip.pass, reason: skip.reason, names: new Map() };
33
+ group.names.set(skip.name, (group.names.get(skip.name) ?? 0) + 1);
34
+ groups.set(key, group);
35
+ }
36
+ return [...groups.values()]
37
+ .map(({ pass, reason, names }) => ({
38
+ pass,
39
+ reason,
40
+ count: [...names.values()].reduce((sum, count) => sum + count, 0),
41
+ names: [...names].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])),
42
+ }))
43
+ .sort(
44
+ (a, b) =>
45
+ b.count - a.count || a.pass.localeCompare(b.pass) || a.reason.localeCompare(b.reason),
46
+ );
47
+ }
48
+
49
+ /** The most names listed for a reason. */
50
+ const NAMES_SHOWN = 6;
51
+
52
+ /**
53
+ * The report as text, one line per reason.
54
+ */
55
+ export function formatReport(report: OptimizerReport): string {
56
+ const lines = [`solid-optimizer: what stays as written in ${report.environment}`];
57
+ const summaries = summarizeSkips(report.skips);
58
+ if (summaries.length === 0) {
59
+ lines.push(' nothing');
60
+ }
61
+ const reasonWidth = Math.max(0, ...summaries.map((summary) => summary.reason.length));
62
+ for (const summary of summaries) {
63
+ const shown = summary.names
64
+ .slice(0, NAMES_SHOWN)
65
+ .map(([name, count]) => (count > 1 ? `${name}×${String(count)}` : name));
66
+ if (summary.names.length > NAMES_SHOWN) {
67
+ shown.push(`${String(summary.names.length - NAMES_SHOWN)} more`);
68
+ }
69
+ lines.push(
70
+ ` ${summary.pass.padEnd(8)} ${summary.reason.padEnd(reasonWidth)} ${String(summary.count).padStart(4)} ${shown.join(', ')}`,
71
+ );
72
+ }
73
+ return lines.join('\n');
74
+ }