@effected/bundler 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,37 @@
1
+ // src/config/EffectedConfigSchema.ts
2
+ /**
3
+ * Where the `effected.toml` JSON Schema is published, as data.
4
+ *
5
+ * @remarks
6
+ * One place for the identity, so the document the repository builds and the
7
+ * `#:schema` directive a scaffold writes can never name different URLs. `host`
8
+ * is the input to `@effected/schemastore`'s `HostedSchema.github`, whose
9
+ * derived `$id` is `url`. `directive` is the first line of an `effected.toml`
10
+ * that points tombi, taplo and other TOML editors at the schema; tombi wants a
11
+ * blank line after it.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { EffectedConfigSchema } from "@effected/bundler";
16
+ *
17
+ * const toml = `${EffectedConfigSchema.directive}\n\n[action.entries]\nmain = "src/main.ts"\n`;
18
+ * ```
19
+ *
20
+ * @public
21
+ */
22
+ const EffectedConfigSchema = {
23
+ /** The `HostedSchema.github` input that publishes the document. */
24
+ host: {
25
+ repo: "spencerbeggs/effected",
26
+ path: "schemas",
27
+ name: "config",
28
+ versions: ["1.0"],
29
+ appendVersion: false
30
+ },
31
+ /** The document's canonical URL, its `$id`. */
32
+ url: "https://raw.githubusercontent.com/spencerbeggs/effected/main/schemas/1.0/config.json",
33
+ /** The `#:schema` directive line naming {@link EffectedConfigSchema.url}. */
34
+ directive: "#:schema https://raw.githubusercontent.com/spencerbeggs/effected/main/schemas/1.0/config.json"
35
+ };
36
+
37
+ export { EffectedConfigSchema };
@@ -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;