boatwright 0.0.0-stage → 0.1.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 (3) hide show
  1. package/boatwright.ts +715 -0
  2. package/package.json +11 -4
  3. package/README.md +0 -3
package/boatwright.ts ADDED
@@ -0,0 +1,715 @@
1
+ #!/usr/bin/env bun
2
+ // boatwright: builds a package's dist/ from its src/, with package.json as
3
+ // the only input, so every package builds the same way and nothing is
4
+ // configured.
5
+ //
6
+ // bunx --bun boatwright [dir] [--json]
7
+ //
8
+ // - Each "./dist/<name>.js" in `exports` or `bin` builds from
9
+ // src/<name>.ts: ESM, one shared chunk, bin files executable.
10
+ // - Each "./dist/<name>.js" or "./dist/<name>.d.ts" in `exports` gets one
11
+ // rolled-up dist/<name>.d.ts. A Bun-only package ships src/ and builds
12
+ // only these.
13
+ // - The target is node when `engines.node` is set, otherwise bun.
14
+ // - peerDependencies stay external; there are no other dependencies.
15
+ // - Exports are listed by name: no `export *`, no default export.
16
+ //
17
+ // Declarations are emitted without a type check (noCheck), so a build
18
+ // installs nothing; type checking happens before release, not here.
19
+
20
+ import {
21
+ chmodSync,
22
+ existsSync,
23
+ mkdirSync,
24
+ mkdtempSync,
25
+ readFileSync,
26
+ realpathSync,
27
+ rmSync,
28
+ writeFileSync,
29
+ } from "node:fs";
30
+ import { tmpdir } from "node:os";
31
+ import { dirname, join, normalize } from "node:path";
32
+
33
+ import type { BunPlugin } from "bun";
34
+
35
+ type Manifest = {
36
+ version?: string;
37
+ exports?: unknown;
38
+ bin?: unknown;
39
+ engines?: { node?: string };
40
+ peerDependencies?: Record<string, string>;
41
+ };
42
+
43
+ function readManifest(path: string): Manifest {
44
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
45
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
46
+ }
47
+
48
+ const DIST_FILE = /^\.\/dist\/([\w-]+)\.(js|d\.ts)$/;
49
+
50
+ // The <name> of every "./dist/<name>.<ext>" in an `exports` or `bin` value,
51
+ // however nested.
52
+ function distNames(value: unknown, ext: "js" | "d.ts"): string[] {
53
+ if (typeof value === "string") {
54
+ const m = DIST_FILE.exec(value);
55
+ return m?.[1] && m[2] === ext ? [m[1]] : [];
56
+ }
57
+ if (typeof value !== "object" || value === null) return [];
58
+ return Object.values(value).flatMap((v) => distNames(v, ext));
59
+ }
60
+
61
+ // A module that imports package.json for its version would otherwise
62
+ // bundle the whole manifest.
63
+ const versionOnly: BunPlugin = {
64
+ name: "version-only",
65
+ setup(builder) {
66
+ builder.onLoad({ filter: /[\\/]package\.json$/ }, ({ path }) => ({
67
+ contents: JSON.stringify({ version: readManifest(path).version }),
68
+ loader: "json",
69
+ }));
70
+ },
71
+ };
72
+
73
+ // Declarations need no type definitions when nothing is checked.
74
+ const NO_CHECK = JSON.stringify({
75
+ compilerOptions: {
76
+ noCheck: true,
77
+ skipLibCheck: true,
78
+ types: [],
79
+ target: "esnext",
80
+ module: "preserve",
81
+ moduleResolution: "bundler",
82
+ allowImportingTsExtensions: true,
83
+ verbatimModuleSyntax: true,
84
+ },
85
+ });
86
+
87
+ type BuildResult = { files: string[]; errors: string[] };
88
+
89
+ /** Builds `dir`/dist from `dir`/src and `dir`/package.json. */
90
+ export async function build(dir: string): Promise<BuildResult> {
91
+ const root = realpathSync(dir);
92
+ const manifest = readManifest(join(root, "package.json"));
93
+ const exported = distNames(manifest.exports, "js");
94
+ const executables = [...new Set(distNames(manifest.bin, "js"))];
95
+ const entries = [...new Set([...exported, ...executables])];
96
+ const typed = [
97
+ ...new Set([...exported, ...distNames(manifest.exports, "d.ts")]),
98
+ ];
99
+ if (entries.length === 0 && typed.length === 0) {
100
+ const errors = [
101
+ `${dir}/package.json points no export or bin into ./dist/.`,
102
+ ];
103
+ return { files: [], errors };
104
+ }
105
+
106
+ rmSync(join(root, "dist"), { recursive: true, force: true });
107
+ if (entries.length > 0) {
108
+ const errors = await bundle(root, entries, manifest);
109
+ if (errors.length) return { files: [], errors };
110
+ }
111
+ for (const name of executables) {
112
+ chmodSync(join(root, "dist", `${name}.js`), 0o755);
113
+ }
114
+
115
+ if (typed.length > 0) {
116
+ const dts = await declarations(root, typed);
117
+ if (dts.errors.length) return { files: [], errors: dts.errors };
118
+ mkdirSync(join(root, "dist"), { recursive: true });
119
+ for (const [name, text] of dts.files) {
120
+ writeFileSync(join(root, "dist", `${name}.d.ts`), text);
121
+ }
122
+ }
123
+ const files = [...new Bun.Glob("*").scanSync({ cwd: join(root, "dist") })];
124
+ return {
125
+ files: files.toSorted().map((f) => join(dir, "dist", f)),
126
+ errors: [],
127
+ };
128
+ }
129
+
130
+ // One .js per entry, plus the shared chunk.
131
+ async function bundle(
132
+ root: string,
133
+ entries: readonly string[],
134
+ manifest: Manifest,
135
+ ): Promise<string[]> {
136
+ // invariant: build from inside the package with relative paths. Bun embeds
137
+ // paths relative to the working directory, so building from elsewhere
138
+ // makes the output, and chunk hashes, depend on where it's checked out.
139
+ // A second shared chunk collides with the fixed name and fails the build,
140
+ // which is when to revisit it.
141
+ const home = process.cwd();
142
+ process.chdir(root);
143
+ let js;
144
+ try {
145
+ js = await Bun.build({
146
+ entrypoints: entries.map((name) => `./src/${name}.ts`),
147
+ root: "./src",
148
+ outdir: "./dist",
149
+ naming: { entry: "[name].[ext]", chunk: "shared.[ext]" },
150
+ target: manifest.engines?.node ? "node" : "bun",
151
+ format: "esm",
152
+ splitting: true,
153
+ external: Object.keys(manifest.peerDependencies ?? {}),
154
+ plugins: [versionOnly],
155
+ throw: false,
156
+ });
157
+ } finally {
158
+ process.chdir(home);
159
+ }
160
+ return js.success ? [] : js.logs.map(String);
161
+ }
162
+
163
+ // Bun emits one .d.ts per module, in memory; rollup() joins them per entry.
164
+ async function declarations(
165
+ root: string,
166
+ names: readonly string[],
167
+ ): Promise<RollupResult> {
168
+ const temp = mkdtempSync(join(tmpdir(), "boatwright-"));
169
+ writeFileSync(join(temp, "tsconfig.json"), NO_CHECK);
170
+ let emitted;
171
+ try {
172
+ emitted = await Bun.build({
173
+ entrypoints: names.map((name) => join(root, "src", `${name}.ts`)),
174
+ root,
175
+ target: "bun",
176
+ dts: true,
177
+ tsconfig: join(temp, "tsconfig.json"),
178
+ throw: false,
179
+ });
180
+ } finally {
181
+ rmSync(temp, { recursive: true, force: true });
182
+ }
183
+ if (!emitted.success) {
184
+ return { files: new Map(), errors: emitted.logs.map(String) };
185
+ }
186
+ const texts = new Map<string, string>();
187
+ for (const output of emitted.outputs) {
188
+ if (output.path.endsWith(".d.ts")) {
189
+ texts.set(normalize(output.path), await output.text());
190
+ }
191
+ }
192
+ if (texts.size === 0) {
193
+ const error = `Bun ${Bun.version} emitted no declarations: Bun.build({ dts }) needs Bun 1.4.6 or later.`;
194
+ return { files: new Map(), errors: [error] };
195
+ }
196
+ const entries = new Map(names.map((name) => [name, `src/${name}.d.ts`]));
197
+ return rollup(entries, (path) => texts.get(normalize(path)));
198
+ }
199
+
200
+ // The rollup. Bun emits one .d.ts per module; rollup() joins them into one
201
+ // per entry: only the declarations its exports reach, aliases renamed,
202
+ // clashes reported instead of guessed, and a declaration an earlier entry
203
+ // exports imported from that entry, not copied.
204
+
205
+ /** A file's text, or undefined when it doesn't exist. */
206
+ type Reader = (path: string) => string | undefined;
207
+
208
+ const readFromDisk: Reader = (path) =>
209
+ existsSync(path) ? readFileSync(path, "utf8") : undefined;
210
+
211
+ type Declaration = { text: string; kind: "value" | "type" };
212
+
213
+ type Module = {
214
+ declarations: Map<string, Declaration[]>;
215
+ // Local name to where it comes from.
216
+ imports: Map<string, { from: string; name: string }>;
217
+ // Public name to where it comes from; no `from` means this module.
218
+ exports: Map<string, { from?: string; name: string }>;
219
+ };
220
+
221
+ type RollupResult = { files: Map<string, string>; errors: string[] };
222
+
223
+ const DECLARATION =
224
+ /^(?:export\s+)?(?:declare\s+)?(?:abstract\s+)?(?<keyword>function|class|interface|type|const|let|var|enum)\s+(?<name>[A-Za-z_$][\w$]*)/;
225
+ const VALUE_KEYWORDS = new Set([
226
+ "function",
227
+ "class",
228
+ "const",
229
+ "let",
230
+ "var",
231
+ "enum",
232
+ ]);
233
+ // `import { … } from "…"` and `export { … } from "…"`.
234
+ const FROM =
235
+ /^(?<verb>import|export)\s+(?:type\s+)?\{(?<list>[^}]*)\}\s+from\s+["'](?<spec>[^"']+)["']/;
236
+ const EXPORT_LIST = /^export\s+(?:type\s+)?\{(?<list>[^}]*)\}\s*;?\s*$/;
237
+ const EXPORT_NOTHING = /^export\s*\{\s*\}\s*;?$/;
238
+ const EXPORT_UNNAMED = /^export\s*(?:\*|default\b|=)/;
239
+ const INLINE_IMPORT =
240
+ /import\(\s*["'](?<spec>[^"']+)["']\s*\)\.(?<name>[A-Za-z_$][\w$]*)/g;
241
+ const IDENT = /[A-Za-z_$][\w$]*/g;
242
+ // An identifier, with what marks it as a property: a dot before it, or a
243
+ // colon after it.
244
+ const IDENT_IN_CONTEXT = /(\.\s*)?\b([A-Za-z_$][\w$]*)\b(\??:)?/g;
245
+
246
+ // Where the comment or string literal starting at `i` ends, or -1 when none
247
+ // starts there. A line comment ends before its newline.
248
+ function skipAt(text: string, i: number): number {
249
+ const c = text[i];
250
+ const next = text[i + 1];
251
+ if (c === "/" && next === "/") {
252
+ const newline = text.indexOf("\n", i);
253
+ return newline < 0 ? text.length : newline;
254
+ }
255
+ if (c === "/" && next === "*") {
256
+ const close = text.indexOf("*/", i + 2);
257
+ return close < 0 ? text.length : close + 2;
258
+ }
259
+ if (c === '"' || c === "'" || c === "`") {
260
+ let j = i + 1;
261
+ while (j < text.length && text[j] !== c) j += text[j] === "\\" ? 2 : 1;
262
+ return j + 1;
263
+ }
264
+ return -1;
265
+ }
266
+
267
+ /** Splits declaration text into top-level statements, comments attached. */
268
+ export function splitStatements(text: string): string[] {
269
+ const statements: string[] = [];
270
+ let start = 0;
271
+ let depth = 0;
272
+ const cut = (at: number) => {
273
+ const statement = text.slice(start, at).trim();
274
+ if (statement) statements.push(statement);
275
+ start = at;
276
+ };
277
+ for (let i = 0; i < text.length;) {
278
+ const skip = skipAt(text, i);
279
+ if (skip >= 0) {
280
+ i = skip;
281
+ continue;
282
+ }
283
+ const c = text[i];
284
+ i++;
285
+ if (c === "{" || c === "(" || c === "[") depth++;
286
+ if (c === "}" || c === ")" || c === "]") depth--;
287
+ if (depth > 0) continue;
288
+ // A statement ends at a top-level `;`, or at a top-level `}` that ends
289
+ // its line, as an interface's body does.
290
+ if (c === ";" || (c === "}" && /^[ \t]*(\n|$)/.test(text.slice(i)))) {
291
+ cut(i);
292
+ }
293
+ }
294
+ cut(text.length);
295
+ return statements;
296
+ }
297
+
298
+ /** Applies `fn` to code only, leaving comments and string literals as-is. */
299
+ export function mapCode(text: string, fn: (code: string) => string): string {
300
+ let out = "";
301
+ let code = "";
302
+ for (let i = 0; i < text.length;) {
303
+ const skip = skipAt(text, i);
304
+ if (skip < 0) {
305
+ code += text.charAt(i);
306
+ i++;
307
+ continue;
308
+ }
309
+ out += fn(code) + text.slice(i, skip);
310
+ code = "";
311
+ i = skip;
312
+ }
313
+ return out + fn(code);
314
+ }
315
+
316
+ // `text` without its comments; string literals stay.
317
+ function withoutComments(text: string): string {
318
+ let out = "";
319
+ for (let i = 0; i < text.length;) {
320
+ const skip = skipAt(text, i);
321
+ if (skip < 0) {
322
+ out += text.charAt(i);
323
+ i++;
324
+ continue;
325
+ }
326
+ if (text[i] !== "/") out += text.slice(i, skip);
327
+ i = skip;
328
+ }
329
+ return out;
330
+ }
331
+
332
+ // The comments before a statement (its JSDoc), and the statement.
333
+ function splitLead(text: string): { lead: string; rest: string } {
334
+ let i = 0;
335
+ for (;;) {
336
+ while (/\s/.test(text.charAt(i))) i++;
337
+ const skip = text[i] === "/" ? skipAt(text, i) : -1;
338
+ if (skip < 0) break;
339
+ i = skip;
340
+ }
341
+ return { lead: text.slice(0, i), rest: text.slice(i) };
342
+ }
343
+
344
+ // `a, type b as c` to [{ name: "a", alias: "a" }, { name: "b", alias: "c" }].
345
+ function specifiers(list: string): { name: string; alias: string }[] {
346
+ return list
347
+ .split(",")
348
+ .map((part) => part.trim().replace(/^type\s+/, ""))
349
+ .filter(Boolean)
350
+ .map((part) => {
351
+ const [name = "", alias = name] = part.split(/\s+as\s+/);
352
+ return { name, alias };
353
+ });
354
+ }
355
+
356
+ // The emitted .d.ts a relative specifier names, or undefined for a bare one.
357
+ function moduleAt(
358
+ from: string,
359
+ spec: string,
360
+ read: Reader,
361
+ ): string | undefined {
362
+ if (!spec.startsWith(".")) return undefined;
363
+ const base = normalize(join(dirname(from), spec)).replace(
364
+ /\.(js|ts|mjs|d\.ts)$/,
365
+ "",
366
+ );
367
+ return [`${base}.d.ts`, join(base, "index.d.ts")].find(
368
+ (path) => read(path) !== undefined,
369
+ );
370
+ }
371
+
372
+ function parseModule(path: string, read: Reader, errors: string[]): Module {
373
+ const module: Module = {
374
+ declarations: new Map(),
375
+ imports: new Map(),
376
+ exports: new Map(),
377
+ };
378
+ const source = (spec: string) => moduleAt(path, spec, read) ?? spec;
379
+ for (const text of splitStatements(read(path) ?? "")) {
380
+ const { rest: statement } = splitLead(text);
381
+ if (EXPORT_NOTHING.test(statement)) continue;
382
+ if (EXPORT_UNNAMED.test(statement)) {
383
+ errors.push(
384
+ `${path}: "${statement.slice(0, 40)}" isn't supported; list exports by name.`,
385
+ );
386
+ continue;
387
+ }
388
+ const from = FROM.exec(statement)?.groups;
389
+ if (from) {
390
+ const { verb, list = "", spec = "" } = from;
391
+ const into = verb === "import" ? module.imports : module.exports;
392
+ for (const { name, alias } of specifiers(list)) {
393
+ into.set(alias, { from: source(spec), name });
394
+ }
395
+ continue;
396
+ }
397
+ const listed = EXPORT_LIST.exec(statement)?.groups;
398
+ if (listed) {
399
+ for (const { name, alias } of specifiers(listed.list ?? "")) {
400
+ module.exports.set(alias, { name });
401
+ }
402
+ continue;
403
+ }
404
+ const declared = DECLARATION.exec(statement)?.groups;
405
+ if (!declared) {
406
+ errors.push(`${path}: can't read "${statement.slice(0, 40)}".`);
407
+ continue;
408
+ }
409
+ const { keyword = "", name = "" } = declared;
410
+ const kind = VALUE_KEYWORDS.has(keyword) ? "value" : "type";
411
+ const group = module.declarations.get(name) ?? [];
412
+ module.declarations.set(name, [...group, { text, kind }]);
413
+ if (/^export\s/.test(statement)) module.exports.set(name, { name });
414
+ }
415
+ return module;
416
+ }
417
+
418
+ // Where a name is declared: "<path>#<name>" for a module of the package,
419
+ // "bare:<specifier>#<name>" for one outside it, such as node:fs.
420
+ type Key = string;
421
+
422
+ const isBare = (key: Key) => key.startsWith("bare:");
423
+
424
+ function parts(key: Key): { path: string; name: string } {
425
+ const hash = key.lastIndexOf("#");
426
+ const path = key.slice(0, hash);
427
+ return {
428
+ path: isBare(key) ? path.slice("bare:".length) : path,
429
+ name: key.slice(hash + 1),
430
+ };
431
+ }
432
+
433
+ // What an entry's exports reach.
434
+ type Reached = {
435
+ // The entry's public names.
436
+ exported: Map<Key, string>;
437
+ // Declarations written into the entry's file, in order, by output name.
438
+ written: Map<Key, string>;
439
+ // Names it imports from another entry or a bare module, by output name.
440
+ outside: Map<Key, string>;
441
+ // The outside names a written declaration uses.
442
+ used: Set<Key>;
443
+ };
444
+
445
+ /**
446
+ * Rolls up declarations for each entry. `entries` maps an output name
447
+ * (`index`) to the emitted `.d.ts` of its source module.
448
+ */
449
+ export function rollup(
450
+ entries: ReadonlyMap<string, string>,
451
+ read: Reader = readFromDisk,
452
+ ): RollupResult {
453
+ const errors: string[] = [];
454
+ const modules = new Map<string, Module>();
455
+ const load = (path: string): Module => {
456
+ const known = modules.get(path);
457
+ if (known) return known;
458
+ const module = parseModule(path, read, errors);
459
+ modules.set(path, module);
460
+ return module;
461
+ };
462
+
463
+ // Follows imports and re-exports from `path` to where `name` is declared.
464
+ const declaredAt = (
465
+ path: string,
466
+ name: string,
467
+ seen = new Set<Key>(),
468
+ ): Key => {
469
+ if (!path.endsWith(".d.ts")) return `bare:${path}#${name}`;
470
+ const key = `${path}#${name}`;
471
+ if (seen.has(key)) return key;
472
+ seen.add(key);
473
+ const module = load(path);
474
+ if (module.declarations.has(name)) return key;
475
+ const exported = module.exports.get(name);
476
+ if (exported?.from) return declaredAt(exported.from, exported.name, seen);
477
+ if (exported && exported.name !== name) {
478
+ return declaredAt(path, exported.name, seen);
479
+ }
480
+ const imported = module.imports.get(name);
481
+ if (imported) return declaredAt(imported.from, imported.name, seen);
482
+ errors.push(`${path}: no declaration for ${name}.`);
483
+ return key;
484
+ };
485
+
486
+ // Each entry's public names. The first entry to export a declaration owns
487
+ // it; a later entry imports it from the owner.
488
+ const publicNames = new Map<string, Map<Key, string>>();
489
+ const owners = new Map<Key, { entry: string; alias: string }>();
490
+ for (const [entry, path] of entries) {
491
+ const names = new Map<Key, string>();
492
+ for (const alias of load(path).exports.keys()) {
493
+ const key = declaredAt(path, alias);
494
+ if (!names.has(key)) names.set(key, alias);
495
+ if (!owners.has(key)) owners.set(key, { entry, alias });
496
+ }
497
+ publicNames.set(entry, names);
498
+ }
499
+
500
+ const reach = (entry: string): Reached => {
501
+ const reached: Reached = {
502
+ exported: publicNames.get(entry) ?? new Map<Key, string>(),
503
+ written: new Map(),
504
+ outside: new Map(),
505
+ used: new Set(),
506
+ };
507
+ const isOutside = (key: Key) => {
508
+ const owner = owners.get(key);
509
+ return isBare(key) || (owner !== undefined && owner.entry !== entry);
510
+ };
511
+ const visit = (key: Key, byDeclaration: boolean) => {
512
+ if (byDeclaration && isOutside(key)) reached.used.add(key);
513
+ if (reached.written.has(key) || reached.outside.has(key)) return;
514
+ const { path, name } = parts(key);
515
+ if (isOutside(key)) {
516
+ const owned = isBare(key) ? undefined : owners.get(key)?.alias;
517
+ reached.outside.set(key, owned ?? name);
518
+ return;
519
+ }
520
+ reached.written.set(key, reached.exported.get(key) ?? name);
521
+ const module = load(path);
522
+ for (const { text } of module.declarations.get(name) ?? []) {
523
+ const code = withoutComments(text);
524
+ for (const match of code.matchAll(INLINE_IMPORT)) {
525
+ const { spec = "", name: imported = "" } = match.groups ?? {};
526
+ const from = moduleAt(path, spec, read) ?? spec;
527
+ visit(declaredAt(from, imported), true);
528
+ }
529
+ for (const [ident] of code.matchAll(IDENT)) {
530
+ if (ident === name) continue;
531
+ if (module.declarations.has(ident) || module.imports.has(ident)) {
532
+ visit(declaredAt(path, ident), true);
533
+ }
534
+ }
535
+ }
536
+ };
537
+ for (const key of reached.exported.keys()) visit(key, false);
538
+ return reached;
539
+ };
540
+
541
+ // One name, one declaration.
542
+ const checkNames = (entry: string, { written, outside }: Reached) => {
543
+ const claimed = new Map<string, Key>();
544
+ for (const [key, name] of [...written, ...outside]) {
545
+ const prior = claimed.get(name);
546
+ if (prior !== undefined && prior !== key) {
547
+ errors.push(
548
+ `${entry}.d.ts: "${name}" names both ${parts(prior).path} and ${parts(key).path}. Rename one at the source.`,
549
+ );
550
+ }
551
+ claimed.set(name, key);
552
+ }
553
+ };
554
+
555
+ const render = (entry: string, reached: Reached): string => {
556
+ const { exported, written, outside, used } = reached;
557
+ const lines: string[] = [];
558
+
559
+ const fromBare = new Map<string, string[]>();
560
+ const fromEntries = new Map<string, string[]>();
561
+ for (const [key, alias] of outside) {
562
+ if (!used.has(key)) continue;
563
+ const { path, name } = parts(key);
564
+ const owner = owners.get(key);
565
+ if (isBare(key)) {
566
+ const names = fromBare.get(path) ?? [];
567
+ fromBare.set(path, [
568
+ ...names,
569
+ name === alias ? name : `${name} as ${alias}`,
570
+ ]);
571
+ } else if (owner) {
572
+ fromEntries.set(owner.entry, [
573
+ ...(fromEntries.get(owner.entry) ?? []),
574
+ alias,
575
+ ]);
576
+ }
577
+ }
578
+ for (const [spec, names] of [...fromBare].sort()) {
579
+ lines.push(`import type { ${names.sort().join(", ")} } from "${spec}";`);
580
+ }
581
+ for (const [other, names] of [...fromEntries].sort()) {
582
+ lines.push(
583
+ `import type { ${names.sort().join(", ")} } from "./${other}.js";`,
584
+ );
585
+ }
586
+ if (lines.length) lines.push("");
587
+
588
+ for (const key of written.keys()) {
589
+ const { path, name } = parts(key);
590
+ const module = load(path);
591
+ const outputName = (ident: string): string | undefined => {
592
+ if (ident === name) return written.get(key);
593
+ if (!module.declarations.has(ident) && !module.imports.has(ident)) {
594
+ return undefined;
595
+ }
596
+ const target = declaredAt(path, ident);
597
+ return written.get(target) ?? outside.get(target);
598
+ };
599
+ for (const { text } of module.declarations.get(name) ?? []) {
600
+ const inlined = text.replace(
601
+ INLINE_IMPORT,
602
+ (whole, spec: string, imported: string) => {
603
+ const from = moduleAt(path, spec, read);
604
+ if (!from) return whole;
605
+ const target = declaredAt(from, imported);
606
+ return written.get(target) ?? outside.get(target) ?? imported;
607
+ },
608
+ );
609
+ const renamed = mapCode(inlined, (code) =>
610
+ code.replace(
611
+ IDENT_IN_CONTEXT,
612
+ (
613
+ whole: string,
614
+ dot: string | undefined,
615
+ ident: string,
616
+ colon: string | undefined,
617
+ ) => {
618
+ if (dot || colon) return whole;
619
+ const to = outputName(ident);
620
+ return to && to !== ident ? whole.replace(ident, to) : whole;
621
+ },
622
+ ),
623
+ );
624
+ const { lead, rest } = splitLead(renamed);
625
+ const declaration = rest.replace(/^export\s+/, "");
626
+ lines.push(
627
+ `${lead}${exported.has(key) ? "export " : ""}${declaration}`,
628
+ );
629
+ }
630
+ }
631
+
632
+ // Names a bare module declares, and names another entry owns.
633
+ const reexports = new Map<string, { values: string[]; types: string[] }>();
634
+ for (const [key, alias] of exported) {
635
+ const { path, name } = parts(key);
636
+ const as = (original: string) =>
637
+ original === alias ? alias : `${original} as ${alias}`;
638
+ if (isBare(key)) {
639
+ lines.push(`export type { ${as(name)} } from "${path}";`);
640
+ continue;
641
+ }
642
+ const owner = owners.get(key);
643
+ if (!owner || owner.entry === entry) continue;
644
+ const kind = load(path).declarations.get(name)?.[0]?.kind ?? "type";
645
+ const group = reexports.get(owner.entry) ?? { values: [], types: [] };
646
+ (kind === "value" ? group.values : group.types).push(as(owner.alias));
647
+ reexports.set(owner.entry, group);
648
+ }
649
+ for (const [other, { values, types }] of [...reexports].sort()) {
650
+ if (values.length) {
651
+ lines.push(
652
+ `export { ${values.sort().join(", ")} } from "./${other}.js";`,
653
+ );
654
+ }
655
+ if (types.length) {
656
+ lines.push(
657
+ `export type { ${types.sort().join(", ")} } from "./${other}.js";`,
658
+ );
659
+ }
660
+ }
661
+ if (!lines.some((line) => /^export\s/m.test(line)))
662
+ lines.push("export {};");
663
+ return `${lines.join("\n").trim()}\n`;
664
+ };
665
+
666
+ const files = new Map<string, string>();
667
+ for (const entry of entries.keys()) {
668
+ const reached = reach(entry);
669
+ checkNames(entry, reached);
670
+ files.set(entry, render(entry, reached));
671
+ }
672
+ return { files, errors };
673
+ }
674
+
675
+ const USAGE = `boatwright: build a package's dist/ from src/ and package.json
676
+
677
+ Usage: bunx --bun boatwright [dir] [--json]
678
+
679
+ dir the package directory (default: .)
680
+ --json one object: schemaVersion, ok, files, errors
681
+
682
+ Exit: 0 built, 1 the build failed, 2 called wrong.`;
683
+
684
+ if (import.meta.main) {
685
+ const args = Bun.argv.slice(2);
686
+ if (args.includes("--help") || args.includes("-h")) {
687
+ console.log(USAGE);
688
+ process.exit(0);
689
+ }
690
+ const json = args.includes("--json");
691
+ const rest = args.filter((arg) => arg !== "--json");
692
+ const wrong = rest.find((arg) => arg.startsWith("-")) ?? rest[1];
693
+ if (wrong !== undefined) {
694
+ console.error(
695
+ `boatwright: unexpected ${wrong}; it takes [dir], --json and --help.`,
696
+ );
697
+ process.exit(2);
698
+ }
699
+ const dir = rest[0] ?? ".";
700
+ if (!existsSync(join(dir, "package.json"))) {
701
+ console.error(`boatwright: no package.json in ${dir}.`);
702
+ process.exit(2);
703
+ }
704
+ const result = await build(dir);
705
+ if (json) {
706
+ const ok = result.errors.length === 0;
707
+ console.log(JSON.stringify({ schemaVersion: 1, ok, ...result }));
708
+ } else if (result.errors.length) {
709
+ console.error(result.errors.join("\n"));
710
+ } else {
711
+ const list = result.files.map((f) => ` ${f}`).join("\n");
712
+ console.log(`boatwright · ${dir} · ${result.files.length} files\n${list}`);
713
+ }
714
+ if (result.errors.length) process.exit(1);
715
+ }
package/package.json CHANGED
@@ -1,6 +1,13 @@
1
1
  {
2
2
  "name": "boatwright",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Builds a package's dist/ from src/ and package.json, with nothing to configure",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "boatwright": "./boatwright.ts"
9
+ },
10
+ "files": [
11
+ "boatwright.ts"
12
+ ]
13
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.