@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
package/Bundler.js ADDED
@@ -0,0 +1,498 @@
1
+ import { BundlerError } from "./BundlerError.js";
2
+ import { MetaConfig } from "./config/BuildConfig.js";
3
+ import { ConfigValidator } from "./config-validation/ConfigValidator.js";
4
+ import { writeResolvedTsconfig } from "./dts/resolved-tsconfig.js";
5
+ import { assertNoEntryCollisions, extractAmbientDts } from "./entries/ambient-dts.js";
6
+ import { deriveExportPaths } from "./entries/export-paths.js";
7
+ import { createEntryName } from "./entries/extract.js";
8
+ import { packageJsonEntries } from "./entries/package-json-entries.js";
9
+ import { ConfigValidationError } from "./errors.js";
10
+ import { normalizeExeOptions } from "./exe/config.js";
11
+ import { computeExeFileName } from "./exe/filename.js";
12
+ import { causeMessage } from "./internal/causeMessage.js";
13
+ import { readTsconfigJsx, resolveJsxConfig } from "./jsx/config.js";
14
+ import { builtConditionTargets, mismatchedBuiltTargets, stripBuiltCondition } from "./manifest/built-condition.js";
15
+ import { buildEmittedManifest } from "./manifest/emit-manifest.js";
16
+ import { unmatchedExportPatterns } from "./manifest/export-patterns.js";
17
+ import { emittedPackageName, validateManifestSet } from "./manifest/manifest-set.js";
18
+ import { assertBuildableConditionExports } from "./manifest/transform.js";
19
+ import { bundleMetaOptionsOf } from "./meta/bundle-config.js";
20
+ import { resolveOgGenerator } from "./meta/og-image.js";
21
+ import { buildTargetGroups } from "./passes/build-target-groups.js";
22
+ import { normalizeLooseFiles } from "./passes/loose-files.js";
23
+ import { removeDeclarationMaps } from "./passes/strip-maps.js";
24
+ import { BuildCollector } from "./report/collector.js";
25
+ import { writeIssuesArtifact } from "./report/issues-artifact.js";
26
+ import { BuildReport } from "./report/schema.js";
27
+ import { writeTargetsBinding } from "./targets/binding.js";
28
+ import { releaseWarnings, resolveTargets } from "./targets/resolve-targets.js";
29
+ import { Cause, Effect, Exit, Schema } from "effect";
30
+ import * as Fs from "effect/FileSystem";
31
+ import * as PathService from "effect/Path";
32
+
33
+ // src/Bundler.ts
34
+ /**
35
+ * A finished build.
36
+ *
37
+ * @public
38
+ */
39
+ var BundlerBuildResult = class extends Schema.Class("BundlerBuildResult")({
40
+ /** Everything the build recorded. */
41
+ report: BuildReport,
42
+ /** Where `issues.json` was written. */
43
+ issuesPath: Schema.String,
44
+ /** Where `targets.json` was written. */
45
+ targetsPath: Schema.UndefinedOr(Schema.String)
46
+ }) {};
47
+ const defaultRunMetaPass = (options) => import("./meta/run-pass.js").then((module) => module.runMetaPass(options));
48
+ const defaultRunExeBuild = (options) => import("./exe/build.js").then((module) => module.runExeBuild(options));
49
+ /** Reduce a thrown value to the `{ name?, message }` shape the issues artifact stamps on a failed build. */
50
+ function describeFailure(err) {
51
+ if (err instanceof Error) return err.name !== "" ? {
52
+ name: err.name,
53
+ message: err.message
54
+ } : { message: err.message };
55
+ if (typeof err === "object" && err !== null) {
56
+ const rec = err;
57
+ const name = typeof rec._tag === "string" ? rec._tag : typeof rec.name === "string" ? rec.name : void 0;
58
+ const message = typeof rec.message === "string" ? rec.message : String(err);
59
+ return name !== void 0 ? {
60
+ name,
61
+ message
62
+ } : { message };
63
+ }
64
+ return { message: String(err) };
65
+ }
66
+ /** Read and parse a JSON file, answering `undefined` on any error. */
67
+ const readJsonOrUndefined = (file) => Effect.flatMap(Fs.FileSystem, (fs) => fs.readFileString(file).pipe(Effect.flatMap((text) => Effect.try(() => JSON.parse(text))), Effect.orElseSucceed(() => void 0)));
68
+ /** Read and parse package.json at cwd, answering an empty object on any error. */
69
+ const readPackageJson = (cwd, path) => Effect.map(readJsonOrUndefined(path.join(cwd, "package.json")), (pkg) => pkg ?? {});
70
+ /** Write the resolved tsconfig with the resolved JSX settings in `compilerOptions`. */
71
+ function writeTsconfig(cwd, jsx) {
72
+ return writeResolvedTsconfig({
73
+ cwd,
74
+ ...jsx?.runtime === "automatic" ? {
75
+ jsx: "react-jsx",
76
+ jsxImportSource: jsx.importSource
77
+ } : {},
78
+ ...jsx?.runtime === "classic" ? { jsx: "react" } : {}
79
+ });
80
+ }
81
+ /** The publish targets declared in `publishConfig.targets`; only the map form drives multi-target. */
82
+ function readPublishTargets(pkg) {
83
+ const declared = pkg.publishConfig?.targets;
84
+ return declared !== void 0 && !Array.isArray(declared) && typeof declared === "object" ? declared : void 0;
85
+ }
86
+ /** Resolve the prod build groups and the target binding from publishConfig.targets (or the single-npm default). */
87
+ function deriveProdGroups(targets, baseName) {
88
+ const effective = targets !== void 0 && Object.keys(targets).length > 0 ? targets : { npm: true };
89
+ const resolution = resolveTargets({
90
+ targets: effective,
91
+ baseName
92
+ });
93
+ return {
94
+ groups: resolution.groups.map((g) => ({
95
+ id: g.id,
96
+ name: g.name
97
+ })),
98
+ resolution
99
+ };
100
+ }
101
+ const overridesError = (reason) => new ConfigValidationError({
102
+ path: "overrides",
103
+ reason
104
+ });
105
+ /** The partitions, base entries and export-key sets that per-entry overrides produce. */
106
+ function partitionOverrides(config, entries, exportsMap, packageName) {
107
+ const subdirExports = /* @__PURE__ */ new Set();
108
+ if (config.overrides.length === 0) return {
109
+ partitions: [],
110
+ baseEntries: entries,
111
+ dualExports: void 0,
112
+ subdirExports
113
+ };
114
+ const partitions = [];
115
+ const overriddenEntryNames = /* @__PURE__ */ new Set();
116
+ const dualExports = /* @__PURE__ */ new Set();
117
+ const exportPathByEntry = deriveExportPaths(entries, exportsMap);
118
+ for (const ov of config.overrides) {
119
+ if (ov.outSubdir !== void 0 && ov.entries.length !== 1) throw overridesError(`outSubdir "${ov.outSubdir}" must pin exactly one export path (got ${ov.entries.length})`);
120
+ const partEntry = {};
121
+ for (const exportPath of ov.entries) {
122
+ if (exportPath !== "." && !exportPath.startsWith("./")) throw overridesError(`entry "${exportPath}" must be a canonical export path — use "." for the root or a "./"-prefixed subpath (e.g. "./changesets/markdownlint")`);
123
+ const flatName = createEntryName(exportPath, false);
124
+ const src = entries[flatName];
125
+ if (src === void 0) throw overridesError(`export path "${exportPath}" (entry "${flatName}") is not a build entry of ${packageName}`);
126
+ partEntry[ov.outSubdir !== void 0 ? "index" : flatName] = src;
127
+ overriddenEntryNames.add(flatName);
128
+ if (ov.outSubdir !== void 0) subdirExports.add(exportPath);
129
+ if ((ov.format ?? config.format).includes("cjs")) dualExports.add(exportPath);
130
+ }
131
+ partitions.push({
132
+ entry: partEntry,
133
+ ...ov.format !== void 0 ? { format: ov.format } : {},
134
+ ...ov.externals !== void 0 ? { externals: ov.externals } : {},
135
+ ...ov.bundle !== void 0 ? { bundle: ov.bundle } : {},
136
+ ...ov.bundleNodeModules !== void 0 ? { bundleNodeModules: ov.bundleNodeModules } : {},
137
+ ...ov.bundledPackages !== void 0 ? { bundledPackages: ov.bundledPackages } : {},
138
+ ...ov.dtsExternals !== void 0 ? { dtsExternals: ov.dtsExternals } : {},
139
+ ...ov.platform !== void 0 ? { platform: ov.platform } : {},
140
+ ...ov.css !== void 0 ? { css: ov.css } : {},
141
+ ...ov.outSubdir !== void 0 ? { outSubdir: ov.outSubdir } : {}
142
+ });
143
+ }
144
+ const baseEntries = {};
145
+ const baseIsDual = config.format.includes("cjs");
146
+ for (const [name, src] of Object.entries(entries)) {
147
+ if (overriddenEntryNames.has(name)) continue;
148
+ baseEntries[name] = src;
149
+ if (baseIsDual) dualExports.add(exportPathByEntry[name] ?? (name === "index" ? "." : `./${name}`));
150
+ }
151
+ return {
152
+ partitions,
153
+ baseEntries,
154
+ dualExports,
155
+ subdirExports
156
+ };
157
+ }
158
+ /** Refuses a `copy` the build could not honour: no JS pass to run it, or a destination outside `pkg/`. */
159
+ function validateCopy(config, hasJsEntries, path) {
160
+ const { isAbsolute, relative, resolve, sep } = path;
161
+ if (config.copy.length === 0) return;
162
+ if (!hasJsEntries && config.exe !== void 0) throw new ConfigValidationError({
163
+ path: "copy",
164
+ reason: "a package that only compiles a binary runs no JS pass, so nothing would copy these files"
165
+ });
166
+ for (const entry of config.copy) {
167
+ if (typeof entry === "string" || entry.to === void 0) continue;
168
+ const fromPkg = relative("/pkg", resolve("/pkg", entry.to));
169
+ if (isAbsolute(entry.to) || fromPkg === ".." || fromPkg.startsWith(`..${sep}`)) throw new ConfigValidationError({
170
+ path: "copy",
171
+ reason: `"to" must stay inside the group's pkg/ directory (got "${entry.to}")`
172
+ });
173
+ }
174
+ }
175
+ /** The `exports` of a group's emitted manifest, or `undefined` when there is none to read. */
176
+ const readEmittedExports = (cwd, groupId, path) => Effect.map(readJsonOrUndefined(path.join(cwd, "dist", "prod", groupId, "pkg", "package.json")), (manifest) => typeof manifest === "object" && manifest !== null ? manifest.exports : void 0);
177
+ /**
178
+ * The optimistic next-version read for a package `set.name` renames: changesets key the release by the workspace
179
+ * package's own name, so the emitted name takes that entry's version.
180
+ */
181
+ function aliasNextVersions(seam, sourceName, emittedName) {
182
+ const read = seam ?? ((cwd) => import("./changesets/next-versions.js").then((module) => module.resolveNextVersions(cwd)));
183
+ return async (cwd) => {
184
+ const { versions } = await read(cwd);
185
+ const own = versions.get(sourceName);
186
+ if (own === void 0) return { versions };
187
+ const aliased = new Map(versions);
188
+ aliased.set(emittedName, own);
189
+ return { versions: aliased };
190
+ };
191
+ }
192
+ /** A decoded empty `[package.build.meta]` table, which a config that never wrote one also decodes to. */
193
+ const defaultMetaFingerprint = JSON.stringify(Schema.decodeUnknownSync(MetaConfig)({}));
194
+ /**
195
+ * The generator the bundle table names, if any. A failure is named in `issues.json` the way the meta pass names a
196
+ * renderer failure, since it never reaches that pass.
197
+ */
198
+ function resolveConfiguredGenerator(options, packageName, groups, collector, seams) {
199
+ const name = options.bundle?.openGraph?.generate;
200
+ if (name === void 0) return Effect.succeed(void 0);
201
+ return resolveOgGenerator(name, {
202
+ packageName,
203
+ ...seams.importOgPeer !== void 0 ? { importModule: seams.importOgPeer } : {}
204
+ }).pipe(Effect.tapError((err) => Effect.sync(() => {
205
+ for (const g of groups) collector.recordError(g.id, {
206
+ source: "meta",
207
+ level: "error",
208
+ code: "og-generate-failed",
209
+ text: err.message
210
+ });
211
+ })));
212
+ }
213
+ /**
214
+ * The orchestration. Its own reads and writes go through `FileSystem` and `Path`; the passes it hands to tsdown,
215
+ * API Extractor and the SEA compiler stay promise-returning and are awaited through `Effect.promise`, so a rejection
216
+ * reaches {@link Bundler.build} as the thrown value itself. A ported module's synchronous throw is a defect for the
217
+ * same reason. The issues artifact is written on the way out of either terminal path.
218
+ */
219
+ const runBuild = Effect.fnUntraced(function* (options, collector, progress) {
220
+ const { cwd, config, noExe, verbose, seams = {} } = options;
221
+ const fs = yield* Fs.FileSystem;
222
+ const path = yield* PathService.Path;
223
+ const { join, resolve } = path;
224
+ let issuesPath = join(cwd, "dist", "prod", "issues.json");
225
+ const writeIssuesBestEffort = (err) => {
226
+ return Effect.suspend(() => {
227
+ const input = {
228
+ cwd,
229
+ target: "prod",
230
+ reports: collector.snapshot(progress.packageName),
231
+ buildOk: err === void 0,
232
+ ...err !== void 0 ? { failure: describeFailure(err) } : {}
233
+ };
234
+ return seams.writeIssues !== void 0 ? Effect.sync(() => seams.writeIssues?.(input)) : writeIssuesArtifact(input);
235
+ }).pipe(Effect.tap((written) => Effect.sync(() => {
236
+ if (written !== void 0) issuesPath = written;
237
+ })), Effect.catchCause(() => Effect.void));
238
+ };
239
+ const exit = yield* Effect.exit(Effect.gen(function* () {
240
+ const sourcePkg = seams.readPackageJson !== void 0 ? seams.readPackageJson(cwd) : yield* readPackageJson(cwd, path);
241
+ const version = sourcePkg.version ?? "0.0.0";
242
+ const sourceName = sourcePkg.name ?? "unknown";
243
+ progress.packageName = sourceName;
244
+ validateManifestSet(config.manifest.set, config.manifest.drop);
245
+ const packageName = emittedPackageName(config.manifest.set, sourceName);
246
+ const builtTargets = builtConditionTargets(sourcePkg.exports);
247
+ const pkg = stripBuiltCondition(sourcePkg);
248
+ const tsconfigJsx = seams.readTsconfigJsx !== void 0 ? seams.readTsconfigJsx(cwd) : yield* readTsconfigJsx(cwd);
249
+ const jsx = resolveJsxConfig(tsconfigJsx, config.jsx);
250
+ const tsconfigPath = (seams.writeTsconfig ?? writeTsconfig)(cwd, jsx);
251
+ const exportsMap = pkg.exports;
252
+ const publishTargets = readPublishTargets(pkg);
253
+ const osCpu = {
254
+ os: pkg.os ?? [],
255
+ cpu: pkg.cpu ?? []
256
+ };
257
+ const meta = config.meta === false ? void 0 : {
258
+ localPaths: config.meta.localPaths,
259
+ optimistic: config.meta.optimistic === "auto" ? !options.ci : config.meta.optimistic,
260
+ tsdoc: config.meta.tsdoc
261
+ };
262
+ const hasLooseFiles = Object.keys(config.looseFiles).length > 0;
263
+ const metaIsExplicit = config.meta !== false && JSON.stringify(config.meta) !== defaultMetaFingerprint;
264
+ yield* Effect.flatMap(ConfigValidator, (v) => v.validate({
265
+ baseName: packageName,
266
+ hasExports: exportsMap !== void 0 && Object.keys(exportsMap).length > 0,
267
+ ...publishTargets !== void 0 ? { targets: publishTargets } : {},
268
+ ...config.exe !== void 0 ? { exe: config.exe } : {},
269
+ osCpu,
270
+ ...meta !== void 0 && metaIsExplicit ? { meta: {
271
+ ...meta,
272
+ localPaths: meta.localPaths?.map((path) => resolve(cwd, path))
273
+ } } : {},
274
+ ...hasLooseFiles ? { looseFiles: config.looseFiles } : {}
275
+ })).pipe(Effect.provide(ConfigValidator.layer));
276
+ const exeSpecs = config.exe !== void 0 ? normalizeExeOptions(config.exe, osCpu) : [];
277
+ if (config.exe !== void 0 && (exeSpecs.length !== 1 || (exeSpecs[0]?.targets.length ?? 0) !== 1)) throw new ConfigValidationError({
278
+ path: "exe",
279
+ reason: `exe build requires exactly one binary with one target (got ${exeSpecs.length} spec(s), ${exeSpecs[0]?.targets.length ?? 0} target(s) on the first). A package's exports["."] resolves to a single SEA — cross-platform binaries must each ship as their own per-platform package.`
280
+ });
281
+ const exeSpec = exeSpecs[0];
282
+ const exeTarget = exeSpec?.targets[0];
283
+ const exeFileName = exeSpec && exeTarget ? computeExeFileName(exeSpec.fileName, exeTarget) : void 0;
284
+ const exeEntrySource = exeSpec?.entry ?? "./src/bin.ts";
285
+ const exeRewrite = config.exe !== void 0 && exeFileName !== void 0 ? {
286
+ source: exeEntrySource,
287
+ fileName: exeFileName,
288
+ dir: "bin"
289
+ } : void 0;
290
+ const entries = packageJsonEntries({
291
+ pkg: {
292
+ exports: pkg.exports,
293
+ bin: pkg.bin
294
+ },
295
+ ...config.exe !== void 0 ? { excludeSources: [exeEntrySource] } : {}
296
+ });
297
+ const hasJsEntries = Object.keys(entries).length > 0;
298
+ const ambient = extractAmbientDts({
299
+ exports: pkg.exports,
300
+ bin: pkg.bin
301
+ }, {});
302
+ assertNoEntryCollisions(Object.keys(entries), ambient);
303
+ assertBuildableConditionExports(pkg.exports, config.exe !== void 0 ? { exeSource: exeEntrySource } : {});
304
+ if (ambient.length > 0 && !hasJsEntries && config.exe === void 0) throw new ConfigValidationError({
305
+ path: "exports",
306
+ reason: "a types-only package with only ambient .d.ts exports is not supported — add at least one JS entry (or an exe) alongside the ambient declarations"
307
+ });
308
+ validateCopy(config, hasJsEntries, path);
309
+ const { partitions, baseEntries, dualExports, subdirExports } = partitionOverrides(config, entries, exportsMap, sourceName);
310
+ const looseFiles = hasLooseFiles ? normalizeLooseFiles(config.looseFiles) : void 0;
311
+ const { groups, resolution } = deriveProdGroups(publishTargets, packageName);
312
+ const anchor = resolution.groups[0]?.id ?? "npm";
313
+ for (const text of releaseWarnings(resolution)) collector.recordWarning(anchor, {
314
+ source: "config",
315
+ level: "warn",
316
+ code: "targets-no-final-release",
317
+ text
318
+ });
319
+ if (hasJsEntries || config.exe === void 0) {
320
+ progress.phase = "js";
321
+ const buildGroups = seams.buildTargetGroups ?? buildTargetGroups;
322
+ yield* Effect.promise(() => buildGroups({
323
+ cwd,
324
+ version,
325
+ entry: baseEntries,
326
+ tsconfigPath,
327
+ groups,
328
+ devManifest: "preserve",
329
+ externals: config.externals,
330
+ drop: config.manifest.drop,
331
+ ...Object.keys(config.manifest.set).length > 0 ? { set: config.manifest.set } : {},
332
+ format: config.format,
333
+ emitDts: config.emitDts,
334
+ emitDeclarations: true,
335
+ collector,
336
+ verbose,
337
+ onPass: (pass) => {
338
+ progress.phase = pass === "dts" ? "dts" : "js";
339
+ },
340
+ ...config.bundledPackages.length > 0 ? { bundledPackages: config.bundledPackages } : {},
341
+ ...config.dtsExternals.length > 0 ? { dtsExternals: config.dtsExternals } : {},
342
+ ...config.bundleNodeModules ? { bundleNodeModules: true } : {},
343
+ ...config.bundle.length > 0 ? { bundle: config.bundle } : {},
344
+ ...config.minify ? { minify: true } : {},
345
+ ...Object.keys(config.define).length > 0 ? { define: config.define } : {},
346
+ ...partitions.length > 0 ? { overrides: partitions } : {},
347
+ ...dualExports !== void 0 ? { dualExports } : {},
348
+ ...subdirExports.size > 0 ? { subdirExports } : {},
349
+ ...looseFiles !== void 0 ? { looseFiles } : {},
350
+ ...config.copy.length > 0 ? { copy: config.copy } : {},
351
+ ...options.plugins.length > 0 ? { extraPlugins: options.plugins } : {},
352
+ ...exeRewrite !== void 0 ? { exeRewrite } : {}
353
+ }));
354
+ }
355
+ progress.phase = "manifest";
356
+ const targetsPath = seams.writeTargetsBinding !== void 0 ? seams.writeTargetsBinding(cwd, resolution) : yield* writeTargetsBinding(cwd, resolution);
357
+ if (meta !== void 0 && config.emitDts && (config.exe === void 0 || hasJsEntries)) {
358
+ progress.phase = "meta";
359
+ const generate = yield* resolveConfiguredGenerator(options, packageName, groups, collector, seams);
360
+ const bundleMeta = options.bundle !== void 0 ? bundleMetaOptionsOf(options.bundle, generate) : void 0;
361
+ const runMetaPass = seams.runMetaPass ?? defaultRunMetaPass;
362
+ yield* Effect.promise(() => runMetaPass({
363
+ cwd,
364
+ packageName,
365
+ tsconfigPath,
366
+ groups,
367
+ entries,
368
+ exportsMap,
369
+ overrides: config.overrides,
370
+ meta: {
371
+ ...meta,
372
+ ...bundleMeta !== void 0 ? { bundle: bundleMeta } : {}
373
+ },
374
+ collector,
375
+ ci: options.ci,
376
+ targets: resolution.targets,
377
+ ...seams.generateMeta !== void 0 ? { generateMeta: seams.generateMeta } : {},
378
+ ...packageName !== sourceName ? { resolveNextVersions: aliasNextVersions(seams.resolveNextVersions, sourceName, packageName) } : seams.resolveNextVersions !== void 0 ? { resolveNextVersions: seams.resolveNextVersions } : {}
379
+ }));
380
+ }
381
+ progress.phase = "dts";
382
+ for (const g of groups) yield* removeDeclarationMaps(join(cwd, "dist", "prod", g.id, "pkg"));
383
+ if (exeSpec !== void 0 && exeRewrite !== void 0 && exeFileName !== void 0) for (const g of groups) {
384
+ const outDir = join(cwd, "dist", "prod", g.id, "pkg");
385
+ if (!hasJsEntries) {
386
+ progress.phase = "manifest";
387
+ const manifest = yield* Effect.promise(() => buildEmittedManifest({
388
+ pkg,
389
+ cwd,
390
+ targetGroup: {
391
+ id: g.id,
392
+ name: g.name,
393
+ isProd: true
394
+ },
395
+ devManifest: "preserve",
396
+ drop: config.manifest.drop,
397
+ set: config.manifest.set,
398
+ exeRewrite
399
+ }));
400
+ yield* fs.makeDirectory(outDir, { recursive: true });
401
+ yield* fs.writeFileString(join(outDir, "package.json"), `${JSON.stringify(manifest, null, " ")}\n`);
402
+ for (const file of ["LICENSE", "README.md"]) yield* fs.copyFile(join(cwd, file), join(outDir, file)).pipe(Effect.ignore);
403
+ }
404
+ if (!noExe) {
405
+ progress.phase = "exe";
406
+ const binDir = join(outDir, "bin");
407
+ const runExeBuild = seams.runExeBuild ?? defaultRunExeBuild;
408
+ yield* Effect.promise(() => runExeBuild({
409
+ cwd,
410
+ outDir: binDir,
411
+ specs: exeSpecs,
412
+ collector,
413
+ groupId: g.id,
414
+ verbose
415
+ }));
416
+ if (seams.runExeBuild === void 0 && !(yield* fs.exists(join(binDir, exeFileName)).pipe(Effect.orElseSucceed(() => false)))) throw new Error(`exe: expected compiled binary at ${join(binDir, exeFileName)} but it is missing — tsdown's emitted name may have drifted from computeExeFileName`);
417
+ }
418
+ }
419
+ const exeExportPath = exeRewrite !== void 0 ? `./${exeRewrite.dir}/${exeRewrite.fileName}` : void 0;
420
+ for (const g of groups) for (const { field, key, target } of yield* unmatchedExportPatterns(join(cwd, "dist", "prod", g.id, "pkg"), { ...exeExportPath !== void 0 ? { ignore: [exeExportPath] } : {} })) collector.recordWarning(g.id, {
421
+ source: "config",
422
+ level: "warn",
423
+ code: "exports-pattern-unmatched",
424
+ text: field === "bin" ? `The bin "${key}" points at "${target}", which is not a file in the emitted package. Point it at a source the build emits, or ship the file from public/ or with [package.build] copy.` : target.includes("*") ? `The exports pattern "${key}" points at "${target}", which matches no file in the emitted package. Ship the files from public/ or with [package.build] copy.` : `The export "${key}" points at "${target}", which is not a file in the emitted package. Point it at a source the build emits, or ship the file from public/ or with [package.build] copy.`
425
+ });
426
+ if (builtTargets.length > 0) {
427
+ const emitted = yield* Effect.forEach(groups, (g) => Effect.map(readEmittedExports(cwd, g.id, path), (exports) => ({
428
+ groupId: g.id,
429
+ exports
430
+ })));
431
+ for (const { exportKey, target, expected } of mismatchedBuiltTargets(builtTargets, emitted)) collector.recordWarning(anchor, {
432
+ source: "config",
433
+ level: "warn",
434
+ code: "exports-built-condition-unmatched",
435
+ text: expected !== void 0 ? `The export "${exportKey}" names "${target}" under the effected-built condition, which is not the file the build emits for it. Write "${expected}".` : `The export "${exportKey}" names "${target}" under the effected-built condition, but the build emits no JS file for that export.`
436
+ });
437
+ }
438
+ return targetsPath;
439
+ }));
440
+ if (Exit.isSuccess(exit)) {
441
+ yield* writeIssuesBestEffort();
442
+ return {
443
+ issuesPath,
444
+ targetsPath: exit.value
445
+ };
446
+ }
447
+ yield* writeIssuesBestEffort(Cause.squash(exit.cause));
448
+ return yield* Effect.failCause(exit.cause);
449
+ });
450
+ /**
451
+ * Builds one package: the JS and declaration passes for every publish group, the emitted manifest,
452
+ * `dist/prod/targets.json`, the API model, an optional SEA binary, and `dist/prod/issues.json`.
453
+ *
454
+ * @public
455
+ */
456
+ var Bundler = class {
457
+ /**
458
+ * Runs a build of the package at `options.cwd`, writing into its `dist/prod`.
459
+ *
460
+ * @remarks
461
+ * It writes nothing to stdout; rendering the report belongs to the caller. A structurally invalid config fails
462
+ * {@link ConfigValidationError} before any build work, and anything thrown afterwards fails
463
+ * {@link BundlerError} naming the phase. Both paths write `issues.json` stamped `buildOk: false` first.
464
+ *
465
+ * The build's own reads and writes (`package.json`, the package's tsconfig, `targets.json`, `issues.json`, the
466
+ * emitted manifest's checks) go through the provided `FileSystem` and `Path`, while tsdown, API Extractor and the
467
+ * SEA compiler always work on the host disk. Provide the host's (`NodeServices.layer`) for a real build. A memory
468
+ * filesystem suits a build whose passes are all replaced through `seams`.
469
+ */
470
+ static build = Effect.fn("Bundler.build")(function* (options) {
471
+ const collector = new BuildCollector();
472
+ const progress = {
473
+ phase: "validate",
474
+ packageName: "unknown"
475
+ };
476
+ const snapshot = () => collector.snapshot(progress.packageName)[0] ?? BuildReport.make({
477
+ package: progress.packageName,
478
+ targetGroups: []
479
+ });
480
+ const { issuesPath, targetsPath } = yield* runBuild(options, collector, progress).pipe(Effect.catchCause((cause) => {
481
+ if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
482
+ const err = Cause.squash(cause);
483
+ return Effect.fail(err instanceof ConfigValidationError ? err : BundlerError.make({
484
+ phase: progress.phase,
485
+ message: causeMessage(err) ?? String(err),
486
+ cause: err,
487
+ report: snapshot()
488
+ }));
489
+ }));
490
+ return BundlerBuildResult.make({
491
+ report: snapshot(),
492
+ issuesPath,
493
+ targetsPath
494
+ });
495
+ });
496
+ };
497
+
498
+ export { Bundler, BundlerBuildResult };
@@ -0,0 +1,39 @@
1
+ import { BuildReport } from "./report/schema.js";
2
+ import { Schema } from "effect";
3
+
4
+ // src/BundlerError.ts
5
+ /**
6
+ * The part of a build a {@link BundlerError} failed in.
7
+ *
8
+ * @public
9
+ */
10
+ const BundlerPhase = Schema.Literals([
11
+ "validate",
12
+ "js",
13
+ "dts",
14
+ "meta",
15
+ "exe",
16
+ "manifest"
17
+ ]);
18
+ /**
19
+ * A build ended before it finished.
20
+ *
21
+ * @remarks
22
+ * `report` is the collector's snapshot at the moment of failure, so a caller can still render the diagnostics
23
+ * the build gathered. `dist/prod/issues.json` was written with `buildOk: false` before this failure was raised,
24
+ * unless writing it failed too.
25
+ *
26
+ * @public
27
+ */
28
+ var BundlerError = class extends Schema.TaggedError()("BundlerError", {
29
+ /** The part of the build that failed. */
30
+ phase: BundlerPhase,
31
+ /** What went wrong, read from the thrown value and its cause chain. */
32
+ message: Schema.String,
33
+ /** The thrown value, carried structurally. */
34
+ cause: Schema.optionalKey(Schema.Defect()),
35
+ /** Everything the build recorded before it failed. */
36
+ report: BuildReport
37
+ }) {};
38
+
39
+ export { BundlerError, BundlerPhase };
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 C. Spencer Beggs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,85 @@
1
- # Temporary Holding Version
1
+ # @effected/bundler
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@effected%2Fbundler?label=npm&color=cb3837)](https://www.npmjs.com/package/@effected/bundler)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-4caf50.svg)](https://opensource.org/licenses/MIT)
5
+ [![Node.js %3E%3D24.11.0](https://img.shields.io/badge/Node.js-%3E%3D24.11.0-5fa04e.svg)](https://nodejs.org/)
6
+
7
+ The build pipeline of the `@effected/*` kit as a library. Give it a package directory and a decoded `effected.toml`, and it writes what a release packs: per-module JS and rolled-up declarations through tsdown, the publishable `package.json`, an API Extractor model with its `bundle.json` manifest, an optional single-executable binary, and a structured `issues.json`.
8
+
9
+ > **Pre-`1.0.0`.** This package is part of the `@effected/*` kit, built on stable
10
+ > Effect v4 and still in `0.x` development. Pin an exact version: even a package
11
+ > marked *stable* before `1.0.0` can introduce a breaking change by accident, and
12
+ > an exact pin turns that into a type-check error rather than a runtime surprise.
13
+ > Full policy: [release strategy](https://github.com/spencerbeggs/effected#release-strategy).
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ pnpm add @effected/bundler effect typescript
19
+ ```
20
+
21
+ Requires Node.js >=24.11.0. `effect` and `typescript` are peer dependencies. To generate an Open Graph image, also install the optional peers `satori` and `@resvg/resvg-js`. All `@effected/*` packages are ESM-only.
22
+
23
+ ## Quick start
24
+
25
+ ```ts
26
+ import { NodeFileSystem, NodePath } from "@effect/platform-node";
27
+ import { Bundler, EffectedConfigFile } from "@effected/bundler";
28
+ import { WorkspaceDiscovery, WorkspaceRoot } from "@effected/workspaces";
29
+ import { Effect, Layer } from "effect";
30
+
31
+ const platform = Layer.merge(NodeFileSystem.layer, NodePath.layer);
32
+ const discovery = WorkspaceDiscovery.layer().pipe(
33
+ Layer.provideMerge(WorkspaceRoot.layer),
34
+ Layer.provideMerge(platform),
35
+ );
36
+
37
+ const program = Effect.gen(function* () {
38
+ const cwd = process.cwd();
39
+ const { config } = yield* EffectedConfigFile.load({ cwd });
40
+ const result = yield* Bundler.build({
41
+ cwd,
42
+ config: config.package.build,
43
+ bundle: config.package.bundle,
44
+ noExe: false,
45
+ verbose: false,
46
+ plugins: [],
47
+ ci: Boolean(process.env.CI),
48
+ });
49
+ return result.issuesPath;
50
+ });
51
+
52
+ Effect.runPromise(program.pipe(Effect.provide(discovery))).then(console.log);
53
+ ```
54
+
55
+ ## What it writes
56
+
57
+ All under the package:
58
+
59
+ | Path | What it is |
60
+ | --- | --- |
61
+ | `dist/prod/<group>/pkg` | the directory to publish, one per publish target group |
62
+ | `dist/prod/<group>/meta` | the `.api.json` model, `package.json`, a portable `tsconfig.json`, `bundle.json` and any Open Graph image |
63
+ | `dist/prod/targets.json` | which target publishes which group |
64
+ | `dist/prod/issues.json` | every diagnostic, and whether the build finished |
65
+
66
+ Gate on `issues.json`'s `buildOk` first, never on an empty `errors` list: the file is written on failure too, and a crash can leave every bucket empty.
67
+
68
+ ## Failures
69
+
70
+ `Bundler.build` fails with one of two typed errors, and writes `issues.json` stamped `buildOk: false` before either:
71
+
72
+ - `ConfigValidationError`: the config cannot describe a build. Nothing was built.
73
+ - `BundlerError`: something failed during the build. Its `phase` names where (`validate`, `js`, `dts`, `meta`, `exe` or `manifest`) and its `report` carries what the build had recorded, so you can still render it.
74
+
75
+ The module writes nothing to stdout. Rendering the report is the caller's.
76
+
77
+ ## Limits
78
+
79
+ - `cwd` must be an absolute path.
80
+ - `bundledPackages` cannot name a workspace sibling that resolves to its TypeScript source: the build fails, because the declaration generator covers only the package's own project.
81
+ - API Extractor reporting `ae-wrong-input-file-type` about a file outside the package, as it does for a sibling resolved to source, is recorded as suppressed. About a file inside the package, it stays a warning.
82
+
83
+ ## License
84
+
85
+ [MIT](./LICENSE)