@effected/bundler 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Bundler.js CHANGED
@@ -44,7 +44,7 @@ var BundlerBuildResult = class extends Schema.Class("BundlerBuildResult")({
44
44
  /** Where `targets.json` was written. */
45
45
  targetsPath: Schema.UndefinedOr(Schema.String)
46
46
  }) {};
47
- const defaultRunMetaPass = (options) => import("./meta/run-pass.js").then((module) => module.runMetaPass(options));
47
+ const defaultRunMetaPass = (options) => Effect.flatMap(Effect.promise(() => import("./meta/run-pass.js")), (module) => module.runMetaPass(options));
48
48
  const defaultRunExeBuild = (options) => import("./exe/build.js").then((module) => module.runExeBuild(options));
49
49
  /** Reduce a thrown value to the `{ name?, message }` shape the issues artifact stamps on a failed build. */
50
50
  function describeFailure(err) {
@@ -68,16 +68,14 @@ const readJsonOrUndefined = (file) => Effect.flatMap(Fs.FileSystem, (fs) => fs.r
68
68
  /** Read and parse package.json at cwd, answering an empty object on any error. */
69
69
  const readPackageJson = (cwd, path) => Effect.map(readJsonOrUndefined(path.join(cwd, "package.json")), (pkg) => pkg ?? {});
70
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
- }
71
+ const writeTsconfig = (cwd, jsx) => writeResolvedTsconfig({
72
+ cwd,
73
+ ...jsx?.runtime === "automatic" ? {
74
+ jsx: "react-jsx",
75
+ jsxImportSource: jsx.importSource
76
+ } : {},
77
+ ...jsx?.runtime === "classic" ? { jsx: "react" } : {}
78
+ });
81
79
  /** The publish targets declared in `publishConfig.targets`; only the map form drives multi-target. */
82
80
  function readPublishTargets(pkg) {
83
81
  const declared = pkg.publishConfig?.targets;
@@ -178,8 +176,8 @@ const readEmittedExports = (cwd, groupId, path) => Effect.map(readJsonOrUndefine
178
176
  * The optimistic next-version read for a package `set.name` renames: changesets key the release by the workspace
179
177
  * package's own name, so the emitted name takes that entry's version.
180
178
  */
181
- function aliasNextVersions(seam, sourceName, emittedName) {
182
- const read = seam ?? ((cwd) => import("./changesets/next-versions.js").then((module) => module.resolveNextVersions(cwd)));
179
+ function aliasNextVersions(seam, sourceName, emittedName, run) {
180
+ const read = seam ?? ((cwd) => import("./changesets/next-versions.js").then((module) => run(module.resolveNextVersions(cwd))));
183
181
  return async (cwd) => {
184
182
  const { versions } = await read(cwd);
185
183
  const own = versions.get(sourceName);
@@ -211,15 +209,16 @@ function resolveConfiguredGenerator(options, packageName, groups, collector, sea
211
209
  })));
212
210
  }
213
211
  /**
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.
212
+ * The orchestration. Its own reads and writes, and those of the JS, declaration and meta passes, go through
213
+ * `FileSystem` and `Path`. tsdown, API Extractor and the SEA compiler stay promise-returning or synchronous and work
214
+ * on the host disk; a rejection from one reaches {@link Bundler.build} as the thrown value itself, and so does a
215
+ * promise-typed seam's. The issues artifact is written on the way out of either terminal path.
218
216
  */
219
217
  const runBuild = Effect.fnUntraced(function* (options, collector, progress) {
220
218
  const { cwd, config, noExe, verbose, seams = {} } = options;
221
219
  const fs = yield* Fs.FileSystem;
222
220
  const path = yield* PathService.Path;
221
+ const services = yield* Effect.context();
223
222
  const { join, resolve } = path;
224
223
  let issuesPath = join(cwd, "dist", "prod", "issues.json");
225
224
  const writeIssuesBestEffort = (err) => {
@@ -247,7 +246,7 @@ const runBuild = Effect.fnUntraced(function* (options, collector, progress) {
247
246
  const pkg = stripBuiltCondition(sourcePkg);
248
247
  const tsconfigJsx = seams.readTsconfigJsx !== void 0 ? seams.readTsconfigJsx(cwd) : yield* readTsconfigJsx(cwd);
249
248
  const jsx = resolveJsxConfig(tsconfigJsx, config.jsx);
250
- const tsconfigPath = (seams.writeTsconfig ?? writeTsconfig)(cwd, jsx);
249
+ const tsconfigPath = seams.writeTsconfig !== void 0 ? seams.writeTsconfig(cwd, jsx) : yield* writeTsconfig(cwd, jsx);
251
250
  const exportsMap = pkg.exports;
252
251
  const publishTargets = readPublishTargets(pkg);
253
252
  const osCpu = {
@@ -318,8 +317,7 @@ const runBuild = Effect.fnUntraced(function* (options, collector, progress) {
318
317
  });
319
318
  if (hasJsEntries || config.exe === void 0) {
320
319
  progress.phase = "js";
321
- const buildGroups = seams.buildTargetGroups ?? buildTargetGroups;
322
- yield* Effect.promise(() => buildGroups({
320
+ const buildOptions = {
323
321
  cwd,
324
322
  version,
325
323
  entry: baseEntries,
@@ -350,7 +348,10 @@ const runBuild = Effect.fnUntraced(function* (options, collector, progress) {
350
348
  ...config.copy.length > 0 ? { copy: config.copy } : {},
351
349
  ...options.plugins.length > 0 ? { extraPlugins: options.plugins } : {},
352
350
  ...exeRewrite !== void 0 ? { exeRewrite } : {}
353
- }));
351
+ };
352
+ const buildGroups = seams.buildTargetGroups;
353
+ if (buildGroups !== void 0) yield* Effect.promise(() => buildGroups(buildOptions));
354
+ else yield* buildTargetGroups(buildOptions);
354
355
  }
355
356
  progress.phase = "manifest";
356
357
  const targetsPath = seams.writeTargetsBinding !== void 0 ? seams.writeTargetsBinding(cwd, resolution) : yield* writeTargetsBinding(cwd, resolution);
@@ -358,8 +359,7 @@ const runBuild = Effect.fnUntraced(function* (options, collector, progress) {
358
359
  progress.phase = "meta";
359
360
  const generate = yield* resolveConfiguredGenerator(options, packageName, groups, collector, seams);
360
361
  const bundleMeta = options.bundle !== void 0 ? bundleMetaOptionsOf(options.bundle, generate) : void 0;
361
- const runMetaPass = seams.runMetaPass ?? defaultRunMetaPass;
362
- yield* Effect.promise(() => runMetaPass({
362
+ const metaPassOptions = {
363
363
  cwd,
364
364
  packageName,
365
365
  tsconfigPath,
@@ -375,8 +375,11 @@ const runBuild = Effect.fnUntraced(function* (options, collector, progress) {
375
375
  ci: options.ci,
376
376
  targets: resolution.targets,
377
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
- }));
378
+ ...packageName !== sourceName ? { resolveNextVersions: aliasNextVersions(seams.resolveNextVersions, sourceName, packageName, Effect.runPromiseWith(services)) } : seams.resolveNextVersions !== void 0 ? { resolveNextVersions: seams.resolveNextVersions } : {}
379
+ };
380
+ const runMetaPass = seams.runMetaPass;
381
+ if (runMetaPass !== void 0) yield* Effect.promise(() => runMetaPass(metaPassOptions));
382
+ else yield* defaultRunMetaPass(metaPassOptions);
380
383
  }
381
384
  progress.phase = "dts";
382
385
  for (const g of groups) yield* removeDeclarationMaps(join(cwd, "dist", "prod", g.id, "pkg"));
@@ -384,7 +387,7 @@ const runBuild = Effect.fnUntraced(function* (options, collector, progress) {
384
387
  const outDir = join(cwd, "dist", "prod", g.id, "pkg");
385
388
  if (!hasJsEntries) {
386
389
  progress.phase = "manifest";
387
- const manifest = yield* Effect.promise(() => buildEmittedManifest({
390
+ const manifest = yield* buildEmittedManifest({
388
391
  pkg,
389
392
  cwd,
390
393
  targetGroup: {
@@ -396,7 +399,7 @@ const runBuild = Effect.fnUntraced(function* (options, collector, progress) {
396
399
  drop: config.manifest.drop,
397
400
  set: config.manifest.set,
398
401
  exeRewrite
399
- }));
402
+ });
400
403
  yield* fs.makeDirectory(outDir, { recursive: true });
401
404
  yield* fs.writeFileString(join(outDir, "package.json"), `${JSON.stringify(manifest, null, " ")}\n`);
402
405
  for (const file of ["LICENSE", "README.md"]) yield* fs.copyFile(join(cwd, file), join(outDir, file)).pipe(Effect.ignore);
@@ -1,12 +1,8 @@
1
- import { Effect, Layer } from "effect";
1
+ import { Effect } from "effect";
2
2
  import { Manifest } from "@effected/npm";
3
- import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
4
- import * as NodePath from "@effect/platform-node/NodePath";
5
3
  import { Workspaces } from "@effected/workspaces";
6
4
 
7
5
  // src/catalog/resolve-catalogs.ts
8
- /** Bound once: the platform layer is stateless and layers memoize by reference. */
9
- const platform = Layer.mergeAll(NodeFileSystem.layer, NodePath.layer);
10
6
  /**
11
7
  * Resolve every `catalog:`/`workspace:` specifier in a manifest to a concrete spec,
12
8
  * delegating to `@effected/workspaces`' one-shot `Workspaces.resolveManifest`. The
@@ -15,18 +11,15 @@ const platform = Layer.mergeAll(NodeFileSystem.layer, NodePath.layer);
15
11
  * config-dependency hook-replay + lockfile), so no transient
16
12
  * `.pnpm-workspace-state-v1.json` is required.
17
13
  *
18
- * Rejects with `ManifestDecodeError` when a dependency field is not a string-to-string
14
+ * Fails with `ManifestDecodeError` when a dependency field is not a string-to-string
19
15
  * record, `UnresolvedDependencyError` on a specifier the workspace cannot answer, or
20
16
  * `CatalogAssemblyError`/`DependencyResolutionError` when catalog assembly or the
21
17
  * resolution mechanism itself fails.
22
18
  * @public
23
19
  */
24
- function resolveManifest(pkg, cwd) {
25
- const program = Effect.gen(function* () {
26
- const manifest = yield* Manifest.decode(pkg);
27
- return (manifest.needsResolution ? yield* Workspaces.resolveManifest(manifest, { cwd }) : manifest).toRecord();
28
- });
29
- return Effect.runPromise(program.pipe(Effect.provide(platform)));
30
- }
20
+ const resolveManifest = (pkg, cwd) => Effect.gen(function* () {
21
+ const manifest = yield* Manifest.decode(pkg);
22
+ return (manifest.needsResolution ? yield* Workspaces.resolveManifest(manifest, { cwd }) : manifest).toRecord();
23
+ });
31
24
 
32
25
  export { resolveManifest };
@@ -1,29 +1,23 @@
1
- import { Effect, Layer } from "effect";
2
- import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
3
- import * as NodePath from "@effect/platform-node/NodePath";
1
+ import { Effect } from "effect";
4
2
  import { WorkspaceDiscovery, Workspaces } from "@effected/workspaces";
5
3
  import { ReleasePlan } from "@effected/changesets";
6
4
 
7
5
  // src/changesets/next-versions.ts
8
- /** Bound once: the platform layer is stateless and layers memoize by reference. */
9
- const platform = Layer.mergeAll(NodeFileSystem.layer, NodePath.layer);
10
6
  /**
11
7
  * Resolve the next release version of every workspace package from pending changesets.
12
8
  *
13
9
  * Walks up from `cwd` to the monorepo root via `@effected/workspaces`' `WorkspaceDiscovery`,
14
10
  * seeds the map with each package's CURRENT version, then overlays `newVersion` for
15
11
  * changeset-affected packages via `ReleasePlan.read`, including pre-release versions in pre
16
- * mode and fixed or linked groups. Never rejects: any failure (not a workspace, missing
12
+ * mode and fixed or linked groups. Never fails: any failure (not a workspace, missing
17
13
  * `.changeset/config.json`, an invalid config or `pre.json`, parse error) degrades to current
18
14
  * versions (or an empty map).
19
15
  * @public
20
16
  */
21
- async function resolveNextVersions(cwd) {
22
- try {
23
- const workspace = Workspaces.layer({ cwd }).pipe(Layer.provideMerge(platform));
24
- const packages = await Effect.runPromise(Effect.gen(function* () {
25
- return yield* (yield* WorkspaceDiscovery).listPackages();
26
- }).pipe(Effect.provide(workspace)));
17
+ const resolveNextVersions = (cwd) => {
18
+ const workspace = Workspaces.layer({ cwd });
19
+ return Effect.gen(function* () {
20
+ const packages = yield* Effect.flatMap(WorkspaceDiscovery, (discovery) => discovery.listPackages()).pipe(Effect.provide(workspace));
27
21
  const rootDir = packages[0]?.isRootWorkspace ? packages[0].path : cwd;
28
22
  const versions = /* @__PURE__ */ new Map();
29
23
  for (const p of packages) {
@@ -31,20 +25,20 @@ async function resolveNextVersions(cwd) {
31
25
  if (p.version === void 0) continue;
32
26
  versions.set(p.name, p.version);
33
27
  }
34
- try {
35
- const plan = await Effect.runPromise(ReleasePlan.read(rootDir).pipe(Effect.provide(workspace)));
28
+ yield* ReleasePlan.read(rootDir).pipe(Effect.provide(workspace), Effect.tap((plan) => Effect.sync(() => {
36
29
  for (const r of plan.releases) versions.set(r.name, r.newVersion);
37
- } catch {}
30
+ })), Effect.orElseSucceed(() => void 0), Effect.catchDefect(() => Effect.void));
38
31
  return {
39
32
  root: rootDir,
40
33
  versions
41
34
  };
42
- } catch {
43
- return {
44
- root: cwd,
45
- versions: /* @__PURE__ */ new Map()
46
- };
47
- }
48
- }
35
+ }).pipe(Effect.orElseSucceed(() => ({
36
+ root: cwd,
37
+ versions: /* @__PURE__ */ new Map()
38
+ })), Effect.catchDefect(() => Effect.succeed({
39
+ root: cwd,
40
+ versions: /* @__PURE__ */ new Map()
41
+ })));
42
+ };
49
43
 
50
44
  export { resolveNextVersions };
@@ -1,64 +1,59 @@
1
1
  import { ConfigValidationError } from "../errors.js";
2
- import { Effect, Layer } from "effect";
3
- import { existsSync, readFileSync, realpathSync } from "node:fs";
4
- import { dirname, join, relative, sep } from "node:path";
5
- import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
6
- import * as NodePath from "@effect/platform-node/NodePath";
2
+ import { existsLikeNode } from "../internal/exists.js";
3
+ import { Effect, FileSystem, Path } from "effect";
7
4
  import { WorkspaceRoot } from "@effected/workspaces";
8
5
 
9
6
  // src/dts/bundled-siblings.ts
10
7
  /** The package a `bundledPackages` entry belongs to: an entry may name a subpath, since tsdown matches them exactly. */
11
8
  const packageNameOf = (entry) => entry.split("/").slice(0, entry.startsWith("@") ? 2 : 1).join("/");
12
- /** Bound once: the platform layer is stateless and layers memoize by reference. */
13
- const platform = Layer.mergeAll(NodeFileSystem.layer, NodePath.layer);
14
- const rootLayer = WorkspaceRoot.layer.pipe(Layer.provide(platform));
15
9
  /** The workspace root above `cwd`, canonical; absent for a package outside any workspace. */
16
- const findWorkspaceRoot = (cwd) => Effect.runPromise(Effect.gen(function* () {
17
- return yield* (yield* WorkspaceRoot).find(cwd);
18
- }).pipe(Effect.provide(rootLayer), Effect.map((root) => realpathSync(root)), Effect.catch(() => Effect.void.pipe(Effect.as(void 0)))));
10
+ const findWorkspaceRoot = (cwd) => Effect.gen(function* () {
11
+ const root = yield* Effect.flatMap(WorkspaceRoot, (workspaceRoot) => workspaceRoot.find(cwd)).pipe(Effect.provide(WorkspaceRoot.layer), Effect.option);
12
+ if (root._tag === "None") return void 0;
13
+ return yield* (yield* FileSystem.FileSystem).realPath(root.value).pipe(Effect.orDie);
14
+ });
19
15
  /**
20
16
  * The directory `name` links to when that is a sibling: the first `node_modules/<name>` found from `cwd` up to the
21
17
  * root, realpathed into the root and outside any `node_modules`. A registry package and a `file:` link to another
22
18
  * checkout both fail that, and are inlined the ordinary way.
23
19
  */
24
- const siblingDirOf = (name, cwd, root) => {
25
- let dir = realpathSync(cwd);
20
+ const siblingDirOf = Effect.fnUntraced(function* (name, cwd, root) {
21
+ const fs = yield* FileSystem.FileSystem;
22
+ const path = yield* Path.Path;
23
+ let dir = yield* fs.realPath(cwd);
26
24
  for (;;) {
27
- const link = join(dir, "node_modules", name);
28
- if (existsSync(link)) {
29
- const target = realpathSync(link);
30
- const segments = relative(root, target).split(sep);
25
+ const link = path.join(dir, "node_modules", name);
26
+ if (yield* existsLikeNode(link)) {
27
+ const target = yield* fs.realPath(link);
28
+ const segments = path.relative(root, target).split(path.sep);
31
29
  return segments[0] === ".." || segments.includes("node_modules") ? void 0 : target;
32
30
  }
33
- if (dir === root || dirname(dir) === dir) return void 0;
34
- dir = dirname(dir);
31
+ if (dir === root || path.dirname(dir) === dir) return void 0;
32
+ dir = path.dirname(dir);
35
33
  }
36
- };
34
+ });
35
+ /** Reads and parses a JSON file; absent, unreadable or malformed reads as `undefined`. */
36
+ const readJson = (file) => Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFileString(file)).pipe(Effect.flatMap((text) => Effect.try(() => JSON.parse(text))), Effect.orElseSucceed(() => void 0));
37
37
  /** The group a sibling's `targets.json` names canonical, by the meta pass's rule; `npm` when it has none to read. */
38
- const canonicalGroupOf = (siblingDir, name) => {
38
+ const canonicalGroupOf = (siblingDir, name, path) => Effect.map(readJson(path.join(siblingDir, "dist", "prod", "targets.json")), (parsed) => {
39
39
  try {
40
- const { groups } = JSON.parse(readFileSync(join(siblingDir, "dist", "prod", "targets.json"), "utf-8"));
40
+ const { groups } = parsed;
41
41
  return (groups.find((group) => group.name === name) ?? groups[0])?.id ?? "npm";
42
42
  } catch {
43
43
  return "npm";
44
44
  }
45
- };
45
+ });
46
46
  /** Nested subpaths of the sibling's emitted manifest, each to its absolute declaration file. */
47
- const nestedExportsOf = (pkgDir, name) => {
48
- let exportsMap;
49
- try {
50
- exportsMap = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf-8")).exports;
51
- } catch {
52
- return {};
53
- }
47
+ const nestedExportsOf = (pkgDir, name, path) => Effect.map(readJson(path.join(pkgDir, "package.json")), (parsed) => {
48
+ const exportsMap = parsed?.exports;
54
49
  if (typeof exportsMap !== "object" || exportsMap === null) return {};
55
50
  const nested = {};
56
51
  for (const [key, value] of Object.entries(exportsMap)) {
57
52
  const types = value?.types;
58
- if (/^\.\/[^*]*\/[^*]*$/.test(key) && typeof types === "string") nested[`${name}${key.slice(1)}`] = join(pkgDir, types);
53
+ if (/^\.\/[^*]*\/[^*]*$/.test(key) && typeof types === "string") nested[`${name}${key.slice(1)}`] = path.join(pkgDir, types);
59
54
  }
60
55
  return nested;
61
- };
56
+ });
62
57
  /**
63
58
  * Finds the workspace siblings among `names` and locates each one's built declarations.
64
59
  *
@@ -66,36 +61,37 @@ const nestedExportsOf = (pkgDir, name) => {
66
61
  * Names that are not siblings are left out, and nothing is read when `names` is empty. An entry naming a subpath
67
62
  * locates the package it belongs to.
68
63
  *
69
- * @throws {@link ConfigValidationError} when a sibling has no built `index.d.ts`.
64
+ * Fails {@link ConfigValidationError} when a sibling has no built `index.d.ts`.
70
65
  * @public
71
66
  */
72
- async function resolveBundledSiblings(cwd, names) {
67
+ const resolveBundledSiblings = Effect.fnUntraced(function* (cwd, names) {
73
68
  if (names.length === 0) return [];
74
- const root = await findWorkspaceRoot(cwd);
69
+ const root = yield* findWorkspaceRoot(cwd);
75
70
  if (root === void 0) return [];
71
+ const path = yield* Path.Path;
76
72
  const siblings = [];
77
73
  for (const name of new Set(names.map(packageNameOf))) {
78
- const siblingDir = siblingDirOf(name, cwd, root);
74
+ const siblingDir = yield* siblingDirOf(name, cwd, root);
79
75
  if (siblingDir === void 0) continue;
80
- const pkgDir = join(siblingDir, "dist", "prod", canonicalGroupOf(siblingDir, name), "pkg");
81
- if (!existsSync(join(pkgDir, "index.d.ts"))) throw new ConfigValidationError({
76
+ const pkgDir = path.join(siblingDir, "dist", "prod", yield* canonicalGroupOf(siblingDir, name, path), "pkg");
77
+ if (!(yield* existsLikeNode(path.join(pkgDir, "index.d.ts")))) return yield* new ConfigValidationError({
82
78
  path: "bundledPackages",
83
- reason: `"${name}" is a workspace sibling with no built declarations at ${join(pkgDir, "index.d.ts")}. Build ${name} first; a turbo build task that inlines a sibling's types needs dependsOn: ["^build"] in that package's own turbo.json.`
79
+ reason: `"${name}" is a workspace sibling with no built declarations at ${path.join(pkgDir, "index.d.ts")}. Build ${name} first; a turbo build task that inlines a sibling's types needs dependsOn: ["^build"] in that package's own turbo.json.`
84
80
  });
85
81
  siblings.push({
86
82
  name,
87
83
  pkgDir,
88
- nestedExports: nestedExportsOf(pkgDir, name)
84
+ nestedExports: yield* nestedExportsOf(pkgDir, name, path)
89
85
  });
90
86
  }
91
87
  return siblings;
92
- }
88
+ });
93
89
  /**
94
90
  * The tsconfig `paths` map resolving each sibling, and nothing else, to its built declarations.
95
91
  *
96
92
  * @public
97
93
  */
98
- function siblingPaths(siblings) {
94
+ function siblingPaths(siblings, { join }) {
99
95
  const paths = {};
100
96
  for (const { name, pkgDir, nestedExports } of siblings) {
101
97
  paths[name] = [join(pkgDir, "index.d.ts")];
@@ -1,11 +1,10 @@
1
- import { tsconfigSyncOptions } from "../tsconfig/sync-options.js";
2
- import { Result } from "effect";
3
- import { existsSync, realpathSync, writeFileSync } from "node:fs";
1
+ import { existsLikeNode } from "../internal/exists.js";
2
+ import { nativeRealPath } from "../internal/native-realpath.js";
3
+ import { Effect, FileSystem, Path, Result } from "effect";
4
4
  import { tmpdir } from "node:os";
5
- import { dirname, isAbsolute, join, resolve } from "node:path";
6
5
  import { createHash } from "node:crypto";
7
6
  import { GlobPattern, GlobPatternOptions } from "@effected/glob";
8
- import { TsconfigLoaderSync } from "@effected/tsconfig-json";
7
+ import { TsconfigLoader } from "@effected/tsconfig-json";
9
8
 
10
9
  // src/dts/resolved-tsconfig.ts
11
10
  /**
@@ -35,7 +34,7 @@ const DTS_OVERLAY = {
35
34
  *
36
35
  * @internal
37
36
  */
38
- function fallbackCompilerOptions(cwd) {
37
+ function fallbackCompilerOptions(cwd, join) {
39
38
  return {
40
39
  declaration: true,
41
40
  emitDeclarationOnly: false,
@@ -51,7 +50,7 @@ function fallbackCompilerOptions(cwd) {
51
50
  *
52
51
  * @remarks
53
52
  * Resolves the package's own `<cwd>/tsconfig.json` (which extends the shared
54
- * `ecma.json` base) through `@effected/tsconfig-json`'s `TsconfigLoaderSync`, so the
53
+ * `ecma.json` base) through `@effected/tsconfig-json`'s `TsconfigLoader`, so the
55
54
  * result carries the package's real effective options — target, module, lib, strict,
56
55
  * jsx — with `${configDir}` already substituted to absolute paths. Only the dts-pass
57
56
  * overlay (composite/incremental/tsBuildInfoFile forced off, declarationMap forced on)
@@ -63,17 +62,13 @@ function fallbackCompilerOptions(cwd) {
63
62
  *
64
63
  * @public
65
64
  */
66
- function buildResolvedTsconfig(options) {
65
+ const buildResolvedTsconfig = Effect.fnUntraced(function* (options) {
66
+ const { join } = yield* Path.Path;
67
67
  const cwd = options.cwd;
68
68
  const ownConfig = join(cwd, "tsconfig.json");
69
69
  let base;
70
- if (existsSync(ownConfig)) try {
71
- base = { ...TsconfigLoaderSync.resolve(ownConfig, tsconfigSyncOptions).compilerOptions };
72
- } catch (error) {
73
- const message = error instanceof Error ? error.message : String(error);
74
- throw new Error(`Cannot resolve tsconfig at ${ownConfig}: ${message}`, { cause: error });
75
- }
76
- else base = fallbackCompilerOptions(cwd);
70
+ if (yield* existsLikeNode(ownConfig)) base = { ...(yield* TsconfigLoader.resolve(ownConfig).pipe(Effect.mapError((error) => new Error(`Cannot resolve tsconfig at ${ownConfig}: ${error instanceof Error ? error.message : String(error)}`, { cause: error })))).compilerOptions };
71
+ else base = fallbackCompilerOptions(cwd, join);
77
72
  return {
78
73
  compilerOptions: {
79
74
  ...base,
@@ -90,7 +85,7 @@ function buildResolvedTsconfig(options) {
90
85
  ],
91
86
  exclude: [join(cwd, "node_modules"), join(cwd, "dist/**/*")]
92
87
  };
93
- }
88
+ });
94
89
  /**
95
90
  * The base's `files`/`include`/`exclude` (through its whole `extends` chain) as absolute CANONICAL
96
91
  * paths under `baseDir`; a base declaring neither `files` nor `include` gets TypeScript's default
@@ -99,23 +94,21 @@ function buildResolvedTsconfig(options) {
99
94
  * symlinked cwd cannot smuggle a non-canonical name past the canonical `extends`. A base the loader
100
95
  * cannot resolve contributes nothing (the wrapper then inherits whatever the base declares, as before).
101
96
  */
102
- function absoluteFileSet(configPath, baseDir) {
103
- let resolved;
104
- try {
105
- resolved = TsconfigLoaderSync.resolve(configPath, tsconfigSyncOptions);
106
- } catch {
107
- return {};
108
- }
109
- const abs = (p) => canonicalGlob(isAbsolute(p) ? p : join(baseDir, p));
110
- const files = resolved.files?.map(abs);
111
- const include = resolved.include?.map(abs) ?? (files === void 0 ? [join(baseDir, "**/*")] : void 0);
112
- const exclude = resolved.exclude?.map(abs);
97
+ const absoluteFileSet = Effect.fnUntraced(function* (configPath, baseDir) {
98
+ const path = yield* Path.Path;
99
+ const resolved = yield* TsconfigLoader.resolve(configPath).pipe(Effect.option);
100
+ if (resolved._tag === "None") return {};
101
+ const abs = (p) => canonicalGlob(path.isAbsolute(p) ? p : path.join(baseDir, p));
102
+ const absAll = (paths) => paths === void 0 ? Effect.succeed(void 0) : Effect.forEach(paths, abs);
103
+ const files = yield* absAll(resolved.value.files);
104
+ const include = (yield* absAll(resolved.value.include)) ?? (files === void 0 ? [path.join(baseDir, "**/*")] : void 0);
105
+ const exclude = yield* absAll(resolved.value.exclude);
113
106
  return {
114
107
  ...files !== void 0 ? { files } : {},
115
108
  ...include !== void 0 ? { include } : {},
116
109
  ...exclude !== void 0 ? { exclude } : {}
117
110
  };
118
- }
111
+ });
119
112
  /**
120
113
  * Compiler options the dts program must never inherit, each written as `null`: `customConditions` and `paths`
121
114
  * exist to make the TYPECHECK program resolve siblings from source (an export condition, a path alias), while the
@@ -140,20 +133,16 @@ const TSCONFIG_GLOB = GlobPatternOptions.make({
140
133
  * first segment carrying a glob character), leaving the pattern tail untouched. A pattern the kit rejects,
141
134
  * a prefix that does not exist, or one whose spelling the kit changed (an undone escape) is returned unchanged.
142
135
  */
143
- function canonicalGlob(absPath) {
136
+ const canonicalGlob = Effect.fnUntraced(function* (absPath) {
144
137
  const compiled = GlobPattern.compileResult(absPath, TSCONFIG_GLOB);
145
138
  if (Result.isFailure(compiled)) return absPath;
146
139
  const prefix = compiled.success.literalPrefix;
147
140
  if (!absPath.startsWith(prefix)) return absPath;
148
141
  const tail = absPath.slice(prefix.length);
149
- let canonicalPrefix;
150
- try {
151
- canonicalPrefix = realpathSync.native(prefix);
152
- } catch {
153
- return absPath;
154
- }
155
- return /^\/*$/.test(tail) ? canonicalPrefix : join(canonicalPrefix, tail);
156
- }
142
+ const canonicalPrefix = yield* nativeRealPath(prefix).pipe(Effect.option);
143
+ if (canonicalPrefix._tag === "None") return absPath;
144
+ return /^\/*$/.test(tail) ? canonicalPrefix.value : (yield* Path.Path).join(canonicalPrefix.value, tail);
145
+ });
157
146
  /** The longest filename the platforms we build on accept. */
158
147
  const MAX_FILE_NAME = 255;
159
148
  /**
@@ -171,12 +160,12 @@ function tempTsconfigName(prefix, key) {
171
160
  *
172
161
  * @public
173
162
  */
174
- function writeResolvedTsconfig(options) {
175
- const cfg = buildResolvedTsconfig(options);
176
- const path = join(tmpdir(), tempTsconfigName("tsconfig-bundle", options.cwd));
177
- writeFileSync(path, `${JSON.stringify(cfg, null, " ")}\n`, "utf-8");
163
+ const writeResolvedTsconfig = Effect.fnUntraced(function* (options) {
164
+ const cfg = yield* buildResolvedTsconfig(options);
165
+ const path = (yield* Path.Path).join(tmpdir(), tempTsconfigName("tsconfig-bundle", options.cwd));
166
+ yield* (yield* FileSystem.FileSystem).writeFileString(path, `${JSON.stringify(cfg, null, " ")}\n`);
178
167
  return path;
179
- }
168
+ });
180
169
  /**
181
170
  * Derive a dts-EMIT variant of an already-written resolved tsconfig that adds
182
171
  * `stableTypeOrdering: true`, and return its path. This makes the TypeScript declaration emitter
@@ -205,7 +194,7 @@ function writeResolvedTsconfig(options) {
205
194
  * manifest says, never through a typecheck-only condition or path alias that would pull source files into the
206
195
  * emitted declarations. The one exception is `options.paths`, the bundled workspace siblings resolved to their built
207
196
  * declarations, which is the only `paths` map this file ever carries. The only reader of this file is the tsgo
208
- * declaration generator; nothing in the bundler reads it back through the kit's `TsconfigLoaderSync`, which rejects
197
+ * declaration generator; nothing in the bundler reads it back through the kit's `TsconfigLoader`, which rejects
209
198
  * `null` compiler options.
210
199
  *
211
200
  * Best-effort: if the base tsconfig cannot be read or parsed (e.g. a synthetic test path that was
@@ -214,11 +203,13 @@ function writeResolvedTsconfig(options) {
214
203
  *
215
204
  * @public
216
205
  */
217
- function writeDtsEmitTsconfig(resolvedTsconfigPath, options = {}) {
218
- const absBase = isAbsolute(resolvedTsconfigPath) ? resolvedTsconfigPath : resolve(resolvedTsconfigPath);
219
- if (!existsSync(absBase)) return resolvedTsconfigPath;
220
- const canonicalBase = realpathSync.native(absBase);
221
- const baseDir = dirname(canonicalBase);
206
+ const writeDtsEmitTsconfig = Effect.fnUntraced(function* (resolvedTsconfigPath, options = {}) {
207
+ const fs = yield* FileSystem.FileSystem;
208
+ const path = yield* Path.Path;
209
+ const absBase = path.isAbsolute(resolvedTsconfigPath) ? resolvedTsconfigPath : path.resolve(resolvedTsconfigPath);
210
+ if (!(yield* existsLikeNode(absBase))) return resolvedTsconfigPath;
211
+ const canonicalBase = yield* nativeRealPath(absBase).pipe(Effect.orDie);
212
+ const baseDir = path.dirname(canonicalBase);
222
213
  const paths = options.paths !== void 0 && Object.keys(options.paths).length > 0 ? options.paths : void 0;
223
214
  const cfg = {
224
215
  extends: canonicalBase,
@@ -227,12 +218,12 @@ function writeDtsEmitTsconfig(resolvedTsconfigPath, options = {}) {
227
218
  ...DTS_RESET_OPTIONS,
228
219
  ...paths !== void 0 ? { paths } : {}
229
220
  },
230
- ...absoluteFileSet(canonicalBase, baseDir)
221
+ ...yield* absoluteFileSet(canonicalBase, baseDir)
231
222
  };
232
223
  const key = paths !== void 0 ? `${absBase}:${Object.keys(paths).join(",")}` : absBase;
233
- const path = join(tmpdir(), tempTsconfigName("tsconfig-dts-emit", key));
234
- writeFileSync(path, `${JSON.stringify(cfg, null, " ")}\n`, "utf-8");
235
- return path;
236
- }
224
+ const out = path.join(tmpdir(), tempTsconfigName("tsconfig-dts-emit", key));
225
+ yield* fs.writeFileString(out, `${JSON.stringify(cfg, null, " ")}\n`);
226
+ return out;
227
+ });
237
228
 
238
229
  export { buildResolvedTsconfig, writeDtsEmitTsconfig, writeResolvedTsconfig };
@@ -1,6 +1,4 @@
1
1
  import { extractEntries } from "./extract.js";
2
- import { readFileSync } from "node:fs";
3
- import { resolve } from "node:path";
4
2
 
5
3
  // src/entries/package-json-entries.ts
6
4
  /**
@@ -8,9 +6,8 @@ import { resolve } from "node:path";
8
6
  *
9
7
  * @public
10
8
  */
11
- function packageJsonEntries(options = {}) {
12
- const pkg = options.pkg ?? JSON.parse(readFileSync(resolve(options.cwd ?? process.cwd(), "package.json"), "utf-8"));
13
- return extractEntries(pkg, {
9
+ function packageJsonEntries(options) {
10
+ return extractEntries(options.pkg, {
14
11
  exportsAsIndexes: options.exportsAsIndexes,
15
12
  excludeSources: options.excludeSources
16
13
  }).entries;