/** * The declaration files a package ships: those reachable from its * types//index.d.ts, nothing else. * * tsc emits declarations for every package into one dist/types/ (one run, see * scripts/build.ts), including modules no public type reaches (dev.d.ts, an * internal module like toaster's lifetime.d.ts). Shipping the whole tree put * every component's types in every package, and an unreached file's bare * import (`@pebble/pebble`) in a package that does not depend on it. * * The walk follows `import … from`, `export … from`, `import("…")` and * `import "…"`. It throws when a relative import leaves types// (a * package's types must stand alone) or a bare import is not in `declared` * (the package's dependencies and peerDependencies): either would break a * consumer's type check. */ import { existsSync, readFileSync } from "node:fs"; import { dirname, join, relative } from "node:path"; const SPECIFIERS = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)["']([^"']+)["']/g; /** The file a relative specifier names: `x.d.ts`, or `x/index.d.ts`. */ function resolved(from: string, specifier: string): string | null { const base = join(dirname(from), specifier.replace(/\.(js|ts)$/, "")); for (const candidate of [`${base}.d.ts`, join(base, "index.d.ts")]) if (existsSync(candidate)) return candidate; return null; } /** Paths under types// to ship, relative to it, sorted. */ export function shipped(typesRoot: string, name: string, declared: readonly string[]): string[] { const root = join(typesRoot, name); const entry = join(root, "index.d.ts"); if (!existsSync(entry)) throw new Error(`${name}: no ${relative(typesRoot, entry)} to start from`); const seen = new Set([entry]); const pending = [entry]; while (pending.length > 0) { const file = pending.pop()!; for (const [, specifier] of readFileSync(file, "utf8").matchAll(SPECIFIERS)) { if (specifier.startsWith(".")) { const target = resolved(file, specifier); if (target === null) throw new Error(`${name}: ${relative(typesRoot, file)} imports "${specifier}", which has no declaration`); if (relative(root, target).startsWith("..")) { throw new Error(`${name}: ${relative(typesRoot, file)} imports "${specifier}", outside types/${name}/`); } if (!seen.has(target)) { seen.add(target); pending.push(target); } } else { const pkg = specifier.startsWith("@") ? specifier.split("/").slice(0, 2).join("/") : specifier.split("/")[0]; if (!declared.includes(pkg)) { throw new Error(`${name}: ${relative(typesRoot, file)} imports "${specifier}", but ${pkg} is not a dependency of the package`); } } } } return [...seen].map(file => relative(root, file)).sort(); }