@effected/bundler 0.0.0-stage → 0.2.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 (81) hide show
  1. package/Bundler.js +498 -0
  2. package/BundlerError.js +39 -0
  3. package/LICENSE +21 -0
  4. package/README.md +84 -2
  5. package/action/ActionBuilder.js +108 -0
  6. package/action/ActionBundle.js +272 -0
  7. package/action/ActionErrors.js +83 -0
  8. package/action/ActionValidation.js +195 -0
  9. package/action/ActionYml.js +366 -0
  10. package/action/PersistLocal.js +186 -0
  11. package/action/entries.js +23 -0
  12. package/action/ignore-stub-plugin.js +25 -0
  13. package/action/import-check.js +134 -0
  14. package/assets/Inter-SemiBold.ttf +0 -0
  15. package/assets/LICENSE-Inter.txt +92 -0
  16. package/catalog/resolve-catalogs.js +32 -0
  17. package/changesets/next-versions.js +50 -0
  18. package/config/ActionConfig.js +102 -0
  19. package/config/BuildConfig.js +438 -0
  20. package/config/EffectedConfigFile.js +171 -0
  21. package/config/merge.js +20 -0
  22. package/config/plugins.js +84 -0
  23. package/config-validation/ConfigValidator.js +73 -0
  24. package/dts/bundled-siblings.js +108 -0
  25. package/dts/parse.js +28 -0
  26. package/dts/reexport-stub.js +94 -0
  27. package/dts/relative-imports.js +33 -0
  28. package/dts/resolved-tsconfig.js +238 -0
  29. package/entries/ambient-dts.js +108 -0
  30. package/entries/export-paths.js +16 -0
  31. package/entries/extract.js +79 -0
  32. package/entries/package-json-entries.js +19 -0
  33. package/errors.js +37 -0
  34. package/exe/build.js +55 -0
  35. package/exe/config.js +54 -0
  36. package/exe/filename.js +13 -0
  37. package/index.d.ts +3619 -0
  38. package/index.js +57 -0
  39. package/internal/causeMessage.js +57 -0
  40. package/journal/BuildJournal.js +107 -0
  41. package/jsx/config.js +44 -0
  42. package/manifest/built-condition.js +120 -0
  43. package/manifest/emit-manifest.js +93 -0
  44. package/manifest/export-patterns.js +56 -0
  45. package/manifest/manifest-set.js +101 -0
  46. package/manifest/transform.js +324 -0
  47. package/meta/api-extractor.js +241 -0
  48. package/meta/bundle-config.js +22 -0
  49. package/meta/bundle-manifest.js +134 -0
  50. package/meta/bundle-source.js +106 -0
  51. package/meta/config.js +24 -0
  52. package/meta/generate.js +249 -0
  53. package/meta/merge-models.js +43 -0
  54. package/meta/message-suppressor.js +43 -0
  55. package/meta/og-image.js +137 -0
  56. package/meta/og-satori.js +140 -0
  57. package/meta/optimistic.js +32 -0
  58. package/meta/run-pass.js +124 -0
  59. package/meta/scrub-declaration-maps.js +63 -0
  60. package/meta/tsconfig-resolver.js +55 -0
  61. package/meta/tsdoc-config.js +47 -0
  62. package/package.json +86 -5
  63. package/passes/build-target-groups.js +347 -0
  64. package/passes/cjs-default-interop.js +98 -0
  65. package/passes/loose-files.js +57 -0
  66. package/passes/node-builtin-default-interop.js +79 -0
  67. package/passes/strip-maps.js +40 -0
  68. package/passes/sync-public.js +100 -0
  69. package/passes/target-groups.js +112 -0
  70. package/report/ci-annotations.js +36 -0
  71. package/report/collector.js +140 -0
  72. package/report/issues-artifact.js +149 -0
  73. package/report/metrics-plugin.js +76 -0
  74. package/report/schema.js +77 -0
  75. package/report/timer.js +19 -0
  76. package/report/tsdown-logger.js +58 -0
  77. package/targets/binding.js +19 -0
  78. package/targets/config.js +21 -0
  79. package/targets/resolve-targets.js +165 -0
  80. package/tsconfig/sync-options.js +20 -0
  81. package/tsdoc-metadata.json +11 -0
@@ -0,0 +1,40 @@
1
+ import { Effect, FileSystem, Path, Result } from "effect";
2
+ import { GlobPattern, GlobPatternOptions } from "@effected/glob";
3
+ import { descend } from "@effected/walker";
4
+
5
+ // src/passes/strip-maps.ts
6
+ /** `.d.ts.map` / `.d.cts.map` at any depth, dot-directories included. */
7
+ const STRIPPABLE_MAPS = Result.getOrThrow(GlobPattern.compileResult("**/*.d.{ts,cts}.map", GlobPatternOptions.make({ dot: true })));
8
+ /**
9
+ * Remove declaration source-map files (`.d.ts.map` / `.d.cts.map`) from a built `pkg`
10
+ * directory, returning the removed paths.
11
+ *
12
+ * The dts pass emits these next to each `.d.ts` (the resolved dts tsconfig sets
13
+ * `declarationMap: true`) because API Extractor reads them during meta generation to
14
+ * resolve original-source positions. But they are dead weight in a PUBLISHED package —
15
+ * they reference `.ts` sources the tarball does not ship — and they leak local source
16
+ * paths, so the prod build strips them AFTER meta generation has consumed them. The dev
17
+ * build keeps them (it is never published, and `savvy build --target meta` reads them).
18
+ *
19
+ * Recurses, but skips `node_modules` so it does not traverse a self-contained bundle's
20
+ * vendored tree — only the package's own emitted declarations carry maps worth stripping.
21
+ * @public
22
+ */
23
+ const removeDeclarationMaps = Effect.fnUntraced(function* (pkgDir) {
24
+ const fs = yield* FileSystem.FileSystem;
25
+ const path = yield* Path.Path;
26
+ const root = path.resolve(pkgDir);
27
+ const maps = yield* descend(STRIPPABLE_MAPS, {
28
+ cwd: root,
29
+ prune: ["node_modules"],
30
+ onUnreadable: "skip"
31
+ });
32
+ const removed = [];
33
+ for (const rel of maps) {
34
+ yield* fs.remove(path.join(root, rel), { force: true });
35
+ removed.push(path.join(pkgDir, rel));
36
+ }
37
+ return removed;
38
+ });
39
+
40
+ export { removeDeclarationMaps };
@@ -0,0 +1,100 @@
1
+ import { findRelativeSpecifiers } from "../dts/relative-imports.js";
2
+ import { ConfigValidationError } from "../errors.js";
3
+ import { Result } from "effect";
4
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { GlobPattern, GlobPatternOptions } from "@effected/glob";
7
+ import { descendSync } from "@effected/walker";
8
+ import { nodeWalkerSyncOps } from "@effected/walker/node-sync";
9
+
10
+ // src/passes/sync-public.ts
11
+ /** Every file at any depth, dotfiles included. */
12
+ const EVERY_FILE = Result.getOrThrow(GlobPattern.compileResult("**", GlobPatternOptions.make({ dot: true })));
13
+ /**
14
+ * Every file path under `dir`, relative to it (POSIX separators, sorted). Nothing is pruned, so a
15
+ * `public/.well-known/` or `public/node_modules/` asset still copies; symlinked directories are not entered.
16
+ */
17
+ function listFilesRel(dir) {
18
+ return Result.getOrThrow(descendSync(EVERY_FILE, {
19
+ cwd: resolve(dir),
20
+ prune: [],
21
+ ...nodeWalkerSyncOps
22
+ }));
23
+ }
24
+ /** True when both files exist with identical size and bytes. Size is checked first so the byte read is skipped for the common changed case. */
25
+ function sameBytes(a, b) {
26
+ if (statSync(a).size !== statSync(b).size) return false;
27
+ return readFileSync(a).equals(readFileSync(b));
28
+ }
29
+ /** Throw the standard public-asset collision error for a destination-relative path. */
30
+ function throwPublicCollision(rel) {
31
+ throw new ConfigValidationError({
32
+ path: `public/${rel}`,
33
+ reason: `public asset "${rel}" collides with a built output at the package root — rename or remove it`
34
+ });
35
+ }
36
+ /**
37
+ * Copy the CONTENTS of `sourceDir` into `outDir`, additively.
38
+ *
39
+ * Each `sourceDir/<rel>` copies to `outDir/<rel>` — only the `public/` directory itself is dropped;
40
+ * the substructure under it is preserved (`public/tsconfig/ecma.json` becomes `<pkg>/tsconfig/ecma.json`,
41
+ * NOT `<pkg>/ecma.json`). The published manifest mirrors this drop via `transformExports`, which strips
42
+ * a leading `public/` from export values. This function NEVER deletes: `outDir` is the shared package
43
+ * root that the JS/dts passes own, so deleting "files not in source" would wipe the build product.
44
+ * Stale-asset pruning on a non-clean rebuild is therefore out of scope (a full build's `clean: true` handles it).
45
+ *
46
+ * Collision guard: when a destination already exists, identical bytes mean a prior copy of the same
47
+ * asset (skipped); anything else — differing bytes, a directory where a file is needed, or a file
48
+ * where a parent directory is needed — means a built output occupies that path, so it throws
49
+ * {@link ConfigValidationError} rather than clobbering it or surfacing a raw fs error.
50
+ * @public
51
+ */
52
+ function copyPublicDir(sourceDir, outDir) {
53
+ if (!existsSync(sourceDir)) return;
54
+ for (const rel of listFilesRel(sourceDir)) {
55
+ const src = join(sourceDir, rel);
56
+ const dst = join(outDir, rel);
57
+ if (existsSync(dst)) {
58
+ if (statSync(dst).isFile() && sameBytes(src, dst)) continue;
59
+ throwPublicCollision(rel);
60
+ }
61
+ try {
62
+ mkdirSync(dirname(dst), { recursive: true });
63
+ copyFileSync(src, dst);
64
+ } catch (err) {
65
+ const code = err.code;
66
+ if (code === "ENOTDIR" || code === "EEXIST" || code === "EISDIR") throwPublicCollision(rel);
67
+ throw err;
68
+ }
69
+ }
70
+ }
71
+ /**
72
+ * Copy each ambient `.d.ts` export's source verbatim into `outDir/<outName>`, byte-stable (an
73
+ * unchanged file keeps its timestamp). The copy is NOT compiled or bundled, so the build owns two
74
+ * fast-fail checks: the source must exist, and it must be self-contained — a relative
75
+ * import/export/reference would not resolve once the file is flattened to the package root.
76
+ *
77
+ * Throws {@link ConfigValidationError} on a missing source or any relative specifier.
78
+ * @public
79
+ */
80
+ function copyAmbientDts(options) {
81
+ for (const a of options.ambient) {
82
+ const src = join(options.srcCwd, a.source);
83
+ if (!existsSync(src)) throw new ConfigValidationError({
84
+ path: `exports."${a.exportKey}"`,
85
+ reason: `ambient .d.ts source not found: ${a.source}`
86
+ });
87
+ const relativeSpecifiers = findRelativeSpecifiers(readFileSync(src, "utf-8"), a.source);
88
+ if (relativeSpecifiers.length > 0) throw new ConfigValidationError({
89
+ path: `exports."${a.exportKey}"`,
90
+ reason: `ambient .d.ts "${a.source}" has relative import(s) [${relativeSpecifiers.join(", ")}] that cannot resolve after a verbatim copy — use bare package specifiers or self-contained declare module/global blocks`
91
+ });
92
+ const dst = join(options.outDir, a.outName);
93
+ if (!existsSync(dst) || !sameBytes(src, dst)) {
94
+ mkdirSync(dirname(dst), { recursive: true });
95
+ copyFileSync(src, dst);
96
+ }
97
+ }
98
+ }
99
+
100
+ export { copyAmbientDts, copyPublicDir };
@@ -0,0 +1,112 @@
1
+ import { join } from "node:path";
2
+
3
+ // src/passes/target-groups.ts
4
+ /** The `file://` URL of the TypeScript module this package resolves (its own pinned dependency). */
5
+ const typescriptModuleUrl = () => import.meta.resolve("typescript");
6
+ /**
7
+ * Build the {@link DtsPassDtsOptions} for a resolved tsconfig path.
8
+ *
9
+ * @public
10
+ */
11
+ const dtsPassDtsOptions = (tsconfig) => ({
12
+ tsconfig,
13
+ emitDtsOnly: true,
14
+ generator: "tsgo",
15
+ tsgo: { moduleUrl: typescriptModuleUrl() }
16
+ });
17
+ /**
18
+ * The output dir for a group: `dist/prod/\<group\>/pkg`, or `dist/dev/pkg` for the unused dev group.
19
+ *
20
+ * @public
21
+ */
22
+ const outDirFor = (cwd, group) => group === "dev" ? join(cwd, "dist/dev/pkg") : join(cwd, "dist/prod", group, "pkg");
23
+ /**
24
+ * Per-module declarations dir for a prod group: a sibling of `pkg/`, NOT published, used only as
25
+ * API Extractor's diagnostics-run input so locations resolve to per-file source. Kept (not stripped)
26
+ * as a cacheable, inspectable build artifact (issue #162).
27
+ *
28
+ * @public
29
+ */
30
+ const declarationsDirFor = (cwd, group) => join(cwd, "dist/prod", group, "declarations");
31
+ /**
32
+ * Derive the JS-pass tsdown options for one TargetGroup (per-module JS, no dts).
33
+ *
34
+ * @public
35
+ */
36
+ function deriveTargetGroupOptions(options) {
37
+ const isProd = options.group !== "dev";
38
+ const format = options.format ?? ["esm"];
39
+ const hasCjs = format.includes("cjs");
40
+ return {
41
+ outDir: outDirFor(options.cwd, options.group),
42
+ sourcemap: !isProd,
43
+ minify: isProd && (options.minify ?? false),
44
+ format,
45
+ unbundle: !(options.bundleNodeModules ?? false),
46
+ clean: true,
47
+ platform: options.platform ?? "node",
48
+ fixedExtension: false,
49
+ entry: options.entry,
50
+ dts: false,
51
+ define: {
52
+ "process.env.__PACKAGE_VERSION__": JSON.stringify(options.version),
53
+ ...options.define
54
+ },
55
+ isProd,
56
+ ...hasCjs ? { cjsDefault: true } : {}
57
+ };
58
+ }
59
+ /**
60
+ * Derive the dts-pass tsdown options for one TargetGroup (bundled declarations only).
61
+ *
62
+ * @public
63
+ */
64
+ function deriveDtsPassOptions(options) {
65
+ const isProd = options.group !== "dev";
66
+ const format = options.format ?? ["esm"];
67
+ const entry = Object.fromEntries(Object.entries(options.entry).filter(([name]) => !name.startsWith("bin/")));
68
+ return {
69
+ outDir: outDirFor(options.cwd, options.group),
70
+ sourcemap: false,
71
+ format,
72
+ unbundle: false,
73
+ clean: false,
74
+ platform: "node",
75
+ fixedExtension: false,
76
+ entry,
77
+ dts: dtsPassDtsOptions(options.tsconfigPath),
78
+ define: {
79
+ "process.env.__PACKAGE_VERSION__": JSON.stringify(options.version),
80
+ ...options.define
81
+ },
82
+ isProd,
83
+ ...options.bundledPackages !== void 0 ? { bundledPackages: options.bundledPackages } : {}
84
+ };
85
+ }
86
+ /**
87
+ * Derive the per-module declarations pass (API Extractor diagnostics input). Mirrors
88
+ * {@link deriveDtsPassOptions} but `unbundle: true` (preserveModules → 1:1 source positions),
89
+ * esm-only (AE reads the `.d.ts` entry only), into the `declarations/` sibling dir. Bin entries
90
+ * are dropped (no exports).
91
+ * @internal
92
+ */
93
+ function deriveDeclarationsPassOptions(options) {
94
+ const entry = Object.fromEntries(Object.entries(options.entry).filter(([name]) => !name.startsWith("bin/")));
95
+ return {
96
+ outDir: declarationsDirFor(options.cwd, options.group),
97
+ sourcemap: false,
98
+ format: ["esm"],
99
+ unbundle: true,
100
+ platform: "node",
101
+ fixedExtension: false,
102
+ entry,
103
+ dts: dtsPassDtsOptions(options.tsconfigPath),
104
+ define: {
105
+ "process.env.__PACKAGE_VERSION__": JSON.stringify(options.version),
106
+ ...options.define
107
+ },
108
+ ...options.bundledPackages !== void 0 ? { bundledPackages: options.bundledPackages } : {}
109
+ };
110
+ }
111
+
112
+ export { declarationsDirFor, deriveDeclarationsPassOptions, deriveDtsPassOptions, deriveTargetGroupOptions, dtsPassDtsOptions, outDirFor };
@@ -0,0 +1,36 @@
1
+ // src/report/ci-annotations.ts
2
+ /** Removes C0 and C1 controls and DEL, which reach stdout raw here, keeping the line breaks the escapes below map. */
3
+ const stripControls = (s) => Array.from(s).filter((char) => {
4
+ const code = char.charCodeAt(0);
5
+ return code === 10 || code === 13 || !(code < 32 || code >= 127 && code <= 159);
6
+ }).join("");
7
+ /** A workflow command's message. */
8
+ const escapeData = (s) => stripControls(s).replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
9
+ /** A workflow command's property value, where `:` ends the list and `,` starts the next property. */
10
+ const escapeProperty = (s) => escapeData(s).replace(/:/g, "%3A").replace(/,/g, "%2C");
11
+ /**
12
+ * Render a build report as GitHub Actions workflow-command annotations, one `::error` or `::warning`
13
+ * line per diagnostic. Suppressed diagnostics are never annotated. Pure.
14
+ *
15
+ * @remarks
16
+ * The text is a diagnostic's, so it is untrusted: control characters are removed, so it cannot repaint a terminal, and
17
+ * property values have `:` and `,` escaped, so a file name cannot forge a property or end the list.
18
+ *
19
+ * @public
20
+ */
21
+ function renderCiAnnotations(report) {
22
+ const lines = [];
23
+ for (const g of report.targetGroups) {
24
+ for (const e of g.errors) {
25
+ const loc = e.file !== void 0 ? `,file=${escapeProperty(e.file)}${e.line !== void 0 ? `,line=${e.line}` : ""}` : "";
26
+ lines.push(`::error title=${escapeProperty(report.package)} (${escapeProperty(g.id)})${loc}::${escapeData(e.text)}`);
27
+ }
28
+ for (const w of g.warnings) {
29
+ const loc = w.file !== void 0 ? `,file=${escapeProperty(w.file)}${w.line !== void 0 ? `,line=${w.line}` : ""}` : "";
30
+ lines.push(`::warning title=${escapeProperty(report.package)} (${escapeProperty(g.id)})${loc}::${escapeData(w.text)}`);
31
+ }
32
+ }
33
+ return lines;
34
+ }
35
+
36
+ export { renderCiAnnotations };
@@ -0,0 +1,140 @@
1
+ import { BuildReport, DiagnosticEntry, EmittedFile, PassReport, ReportTimings, TargetGroupReport } from "./schema.js";
2
+ import { Context } from "effect";
3
+
4
+ // src/report/collector.ts
5
+ /**
6
+ * Stateful build-event accumulator. The write surface is synchronous so it can be called directly
7
+ * from tsdown's customLogger and API Extractor's messageCallback (both invoked synchronously).
8
+ * `snapshot` builds the immutable BuildReport the Effect render pipeline consumes.
9
+ * @public
10
+ */
11
+ var BuildCollector = class {
12
+ groups = /* @__PURE__ */ new Map();
13
+ group(groupId) {
14
+ let g = this.groups.get(groupId);
15
+ if (g === void 0) {
16
+ g = {
17
+ id: groupId,
18
+ entries: [],
19
+ passes: /* @__PURE__ */ new Map(),
20
+ warnings: [],
21
+ errors: [],
22
+ suppressed: [],
23
+ seenPaths: /* @__PURE__ */ new Set(),
24
+ seenDiagnostics: /* @__PURE__ */ new Set(),
25
+ seenSuppressed: /* @__PURE__ */ new Set()
26
+ };
27
+ this.groups.set(groupId, g);
28
+ }
29
+ return g;
30
+ }
31
+ pass(groupId, pass) {
32
+ const g = this.group(groupId);
33
+ let p = g.passes.get(pass);
34
+ if (p === void 0) {
35
+ p = {
36
+ files: [],
37
+ ms: 0
38
+ };
39
+ g.passes.set(pass, p);
40
+ }
41
+ return p;
42
+ }
43
+ registerGroup(groupId, entries) {
44
+ this.group(groupId).entries = [...entries];
45
+ }
46
+ recordEmitted(groupId, pass, file) {
47
+ const g = this.group(groupId);
48
+ if (g.seenPaths.has(file.path)) return;
49
+ g.seenPaths.add(file.path);
50
+ this.pass(groupId, pass).files.push({
51
+ path: file.path,
52
+ bytes: file.bytes,
53
+ ...file.gzip !== void 0 ? { gzip: file.gzip } : {}
54
+ });
55
+ }
56
+ recordPassTiming(groupId, pass, ms) {
57
+ this.pass(groupId, pass).ms += ms;
58
+ }
59
+ recordWarning(groupId, entry) {
60
+ const g = this.group(groupId);
61
+ const key = diagnosticKey(entry);
62
+ if (g.seenDiagnostics.has(key)) return;
63
+ g.seenDiagnostics.add(key);
64
+ g.warnings.push(toEntry(entry));
65
+ }
66
+ recordError(groupId, entry) {
67
+ const g = this.group(groupId);
68
+ const key = diagnosticKey(entry);
69
+ if (g.seenDiagnostics.has(key)) return;
70
+ g.seenDiagnostics.add(key);
71
+ g.errors.push(toEntry(entry));
72
+ }
73
+ recordSuppressed(groupId, entry) {
74
+ const g = this.group(groupId);
75
+ const key = diagnosticKey(entry);
76
+ if (g.seenSuppressed.has(key)) return;
77
+ g.seenSuppressed.add(key);
78
+ g.suppressed.push(toEntry(entry));
79
+ }
80
+ snapshot(packageName) {
81
+ const targetGroups = [];
82
+ for (const g of this.groups.values()) {
83
+ const passes = [];
84
+ let totalMs = 0;
85
+ for (const [id, p] of g.passes) {
86
+ const files = p.files.map((f) => new EmittedFile({
87
+ path: f.path,
88
+ bytes: f.bytes,
89
+ ...f.gzip !== void 0 ? { gzip: f.gzip } : {}
90
+ }));
91
+ passes.push(new PassReport({
92
+ id,
93
+ files,
94
+ ms: p.ms
95
+ }));
96
+ totalMs += p.ms;
97
+ }
98
+ targetGroups.push(new TargetGroupReport({
99
+ id: g.id,
100
+ entries: [...g.entries],
101
+ passes,
102
+ warnings: [...g.warnings],
103
+ errors: [...g.errors],
104
+ suppressed: [...g.suppressed],
105
+ timings: new ReportTimings({ totalMs })
106
+ }));
107
+ }
108
+ return [new BuildReport({
109
+ package: packageName,
110
+ targetGroups
111
+ })];
112
+ }
113
+ };
114
+ function diagnosticKey(input) {
115
+ return [
116
+ input.source,
117
+ input.level,
118
+ input.code ?? "",
119
+ input.text,
120
+ input.file ?? "",
121
+ String(input.line ?? ""),
122
+ String(input.column ?? "")
123
+ ].join("\0");
124
+ }
125
+ function toEntry(input) {
126
+ return new DiagnosticEntry({
127
+ source: input.source,
128
+ level: input.level,
129
+ text: input.text,
130
+ ...input.code !== void 0 ? { code: input.code } : {},
131
+ ...input.ciFatal !== void 0 ? { ciFatal: input.ciFatal } : {},
132
+ ...input.file !== void 0 ? { file: input.file } : {},
133
+ ...input.line !== void 0 ? { line: input.line } : {},
134
+ ...input.column !== void 0 ? { column: input.column } : {}
135
+ });
136
+ }
137
+ /** @public */
138
+ var BuildCollectorTag = class extends Context.Service()("@effected/bundler/BuildCollector") {};
139
+
140
+ export { BuildCollector, BuildCollectorTag };
@@ -0,0 +1,149 @@
1
+ import { DiagnosticEntry } from "./schema.js";
2
+ import { Clock, Effect, FileSystem, Path, Schema } from "effect";
3
+
4
+ // src/report/issues-artifact.ts
5
+ /**
6
+ * The schema of a {@link PlainDiagnostic}, for reading one back from `issues.json` or a journal.
7
+ *
8
+ * @public
9
+ */
10
+ const PlainDiagnosticSchema = Schema.Struct({
11
+ source: DiagnosticEntry.fields.source,
12
+ level: DiagnosticEntry.fields.level,
13
+ text: Schema.String,
14
+ code: Schema.optionalKey(Schema.String),
15
+ ciFatal: Schema.optionalKey(Schema.Boolean),
16
+ file: Schema.optionalKey(Schema.String),
17
+ line: Schema.optionalKey(Schema.Number),
18
+ column: Schema.optionalKey(Schema.Number)
19
+ });
20
+ /**
21
+ * The schema of a {@link BuildIssues} artifact, for reading `dist/<target>/issues.json` back.
22
+ *
23
+ * @remarks
24
+ * `buildOk` is required here: an artifact without the stamp is unknown rather than a pass, so it does not decode.
25
+ *
26
+ * @public
27
+ */
28
+ const BuildIssuesSchema = Schema.Struct({
29
+ generatedAt: Schema.String,
30
+ package: Schema.String,
31
+ target: Schema.Literals(["dev", "prod"]),
32
+ buildOk: Schema.Boolean,
33
+ failure: Schema.optionalKey(Schema.Struct({
34
+ name: Schema.optionalKey(Schema.String),
35
+ message: Schema.String
36
+ })),
37
+ warnings: Schema.Array(PlainDiagnosticSchema),
38
+ errors: Schema.Array(PlainDiagnosticSchema),
39
+ suppressed: Schema.Array(PlainDiagnosticSchema)
40
+ });
41
+ /** Copy a DiagnosticEntry to a plain object, omitting undefined optionals for stable output. */
42
+ function toPlain(d) {
43
+ const out = {
44
+ source: d.source,
45
+ level: d.level,
46
+ text: d.text
47
+ };
48
+ if (d.code !== void 0) out.code = d.code;
49
+ if (d.ciFatal !== void 0) out.ciFatal = d.ciFatal;
50
+ if (d.file !== void 0) out.file = d.file;
51
+ if (d.line !== void 0) out.line = d.line;
52
+ if (d.column !== void 0) out.column = d.column;
53
+ return out;
54
+ }
55
+ /** De-duplicate by the identity-bearing fields (registry target-groups carry identical diagnostics). */
56
+ function dedupe(entries) {
57
+ const seen = /* @__PURE__ */ new Set();
58
+ const out = [];
59
+ for (const e of entries) {
60
+ const key = JSON.stringify([
61
+ e.source,
62
+ e.level,
63
+ e.code ?? "",
64
+ e.text,
65
+ e.file ?? "",
66
+ e.line ?? -1,
67
+ e.column ?? -1
68
+ ]);
69
+ if (seen.has(key)) continue;
70
+ seen.add(key);
71
+ out.push(e);
72
+ }
73
+ return out;
74
+ }
75
+ /** Longest failure message kept in the artifact — enough for a stack-free error, short of a log dump. */
76
+ const MAX_FAILURE_MESSAGE = 2e3;
77
+ /** Normalize a caller-supplied failure into the stamped shape (message truncated, empty name dropped). */
78
+ function toFailure(failure) {
79
+ const message = failure.message.length > MAX_FAILURE_MESSAGE ? `${failure.message.slice(0, 1999)}…` : failure.message;
80
+ return failure.name !== void 0 && failure.name !== "" ? {
81
+ name: failure.name,
82
+ message
83
+ } : { message };
84
+ }
85
+ /**
86
+ * Flatten a build snapshot into the aggregated, de-duplicated issues artifact. Pure.
87
+ *
88
+ * `buildOk` defaults to `true`, so an existing caller that never fails keeps its current output plus
89
+ * the stamp; a caller that also writes on a failure path MUST pass `buildOk: false` (and ideally the
90
+ * `failure`), otherwise the artifact reads as a clean gate.
91
+ *
92
+ * @public
93
+ */
94
+ function flattenIssues(reports, opts) {
95
+ const warnings = [];
96
+ const errors = [];
97
+ const suppressed = [];
98
+ for (const report of reports) for (const g of report.targetGroups) {
99
+ for (const w of g.warnings) warnings.push(toPlain(w));
100
+ for (const e of g.errors) errors.push(toPlain(e));
101
+ for (const s of g.suppressed) suppressed.push(toPlain(s));
102
+ }
103
+ return {
104
+ generatedAt: opts.generatedAt,
105
+ package: reports[0]?.package ?? "unknown",
106
+ target: opts.target,
107
+ buildOk: opts.buildOk ?? true,
108
+ ...opts.failure !== void 0 ? { failure: toFailure(opts.failure) } : {},
109
+ warnings: dedupe(warnings),
110
+ errors: dedupe(errors),
111
+ suppressed: dedupe(suppressed)
112
+ };
113
+ }
114
+ /**
115
+ * Serialize the issues artifact to pretty JSON with a trailing newline.
116
+ *
117
+ * @public
118
+ */
119
+ function serializeIssues(issues) {
120
+ return `${JSON.stringify(issues, null, 2)}\n`;
121
+ }
122
+ /**
123
+ * Write the aggregated issues artifact to `<cwd>/dist/<target>/issues.json`. Returns the path written.
124
+ *
125
+ * The write is atomic: the JSON lands in a sibling temp file which is then `rename`d over the
126
+ * destination, so a concurrent reader observes either the previous artifact or the complete new one,
127
+ * never a torn or half-written file. Pass `buildOk: false` (plus `failure`, when there is an error to
128
+ * report) on a failure path — see the `buildOk` field of `BuildIssues`.
129
+ *
130
+ * @public
131
+ */
132
+ const writeIssuesArtifact = Effect.fnUntraced(function* (opts) {
133
+ const fs = yield* FileSystem.FileSystem;
134
+ const path = yield* Path.Path;
135
+ const generatedAt = opts.now !== void 0 ? opts.now() : new Date(yield* Clock.currentTimeMillis);
136
+ const issues = flattenIssues(opts.reports, {
137
+ target: opts.target,
138
+ generatedAt: generatedAt.toISOString(),
139
+ buildOk: opts.buildOk,
140
+ failure: opts.failure
141
+ });
142
+ const outPath = path.join(opts.cwd, "dist", opts.target, "issues.json");
143
+ yield* fs.makeDirectory(path.dirname(outPath), { recursive: true });
144
+ const tmpPath = `${outPath}.${process.pid}.tmp`;
145
+ yield* fs.writeFileString(tmpPath, serializeIssues(issues)).pipe(Effect.andThen(fs.rename(tmpPath, outPath)), Effect.onError(() => fs.remove(tmpPath, { force: true }).pipe(Effect.ignore)));
146
+ return outPath;
147
+ });
148
+
149
+ export { BuildIssuesSchema, PlainDiagnosticSchema, flattenIssues, serializeIssues, writeIssuesArtifact };
@@ -0,0 +1,76 @@
1
+ import { gzipSync } from "node:zlib";
2
+
3
+ // src/report/metrics-plugin.ts
4
+ function contentOf(chunk) {
5
+ const c = chunk;
6
+ if (c.type === "chunk") return c.code;
7
+ if (c.type === "asset") return c.source;
8
+ return c.code ?? c.source;
9
+ }
10
+ function byteLength(content) {
11
+ return typeof content === "string" ? Buffer.byteLength(content) : content.byteLength;
12
+ }
13
+ /**
14
+ * Rolldown plugin that records emitted-file metrics into the BuildCollector via writeBundle (which
15
+ * fires for the JS pass AND the emitDtsOnly dts pass — verified against tsdown 0.22.3), plus a
16
+ * defensive onLog for rolldown-level diagnostics that bypass tsdown's logger. Append it to each
17
+ * build pass's `plugins` array. `bytes` is taken from the in-memory chunk/asset content (no fs);
18
+ * `gzip` is computed only when `verbose`.
19
+ *
20
+ * Set `suppressMixedExports` for a pass whose emitted CJS carries the `cjsDefaultInterop()`
21
+ * footer — see the onLog comment below for why rolldown's MIXED_EXPORTS advice does not apply
22
+ * there.
23
+ * @public
24
+ */
25
+ function buildMetricsPlugin(collector, groupId, pass, verbose, suppressMixedExports = false) {
26
+ return {
27
+ name: "savvy:build-metrics",
28
+ writeBundle(_outputOptions, bundle) {
29
+ for (const [key, chunk] of Object.entries(bundle)) {
30
+ const content = contentOf(chunk);
31
+ if (content === void 0) continue;
32
+ const bytes = byteLength(content);
33
+ collector.recordEmitted(groupId, pass, {
34
+ path: key,
35
+ bytes,
36
+ ...verbose ? { gzip: gzipSync(typeof content === "string" ? Buffer.from(content) : content).length } : {}
37
+ });
38
+ }
39
+ },
40
+ onLog(level, log) {
41
+ const l = log;
42
+ if (l.code === "SOURCEMAP_BROKEN" && l.plugin?.startsWith("@tsdown/css")) return false;
43
+ const entry = {
44
+ text: l.message ?? String(log),
45
+ ...l.id !== void 0 ? { file: l.id } : {},
46
+ ...l.loc?.line !== void 0 ? { line: l.loc.line } : {},
47
+ ...l.loc?.column !== void 0 ? { column: l.loc.column } : {}
48
+ };
49
+ if (suppressMixedExports && l.code === "MIXED_EXPORTS") {
50
+ collector.recordSuppressed(groupId, {
51
+ source: "rolldown",
52
+ level: "warn",
53
+ code: "MIXED_EXPORTS",
54
+ ...entry
55
+ });
56
+ return false;
57
+ }
58
+ if (level === "error") {
59
+ collector.recordError(groupId, {
60
+ source: "rolldown",
61
+ level: "error",
62
+ ...entry
63
+ });
64
+ return;
65
+ }
66
+ if (level === "warn") collector.recordWarning(groupId, {
67
+ source: "rolldown",
68
+ level: "warn",
69
+ ...entry
70
+ });
71
+ return false;
72
+ }
73
+ };
74
+ }
75
+
76
+ export { buildMetricsPlugin };