Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

cli-external-packages.ts

134 lines5.7 KB

1/**
2 * The single source of truth for packages the server CLI bundle must NOT inline.
3 *
4 * Two consumers derive from this list, and they must never disagree:
5 *
6 * - apps/server/vite.config.ts decides what stays external to the bundle.
7 * - scripts/build-desktop-artifact.ts selects the runtime dependency roots for
8 * the Windows server sidecar.
9 *
10 * A runtime package that is external but absent from the sidecar fails as soon
11 * as Node resolves it from the emitted bundle. Keeping both consumers on one
12 * list prevents packaging from drifting away from the bundle boundary.
13 *
14 * Entries are matched as prefixes (`id.startsWith(prefix)`), so they also cover
15 * a package's platform-specific siblings — `node-gyp-build` covers
16 * `node-gyp-build-optional-packages`, `@yuuang/` covers every `ffi-rs-*` binding.
17 */
18/**
19 * External because Node actually loads them from disk at runtime.
20 *
21 * Native addons (.node), the JS wrappers that dlopen them by real path, and —
22 * critically — the ordinary JS packages those wrappers require. An external
23 * package is loaded from the real filesystem, so its own `require` also
24 * resolves from the real filesystem; a dependency that was bundled away exists
25 * only inside the emitted bundle and is unreachable there. This closure is
26 * enforced by a test, not by inspection.
27 */
28export const CLI_RUNTIME_EXTERNAL_PREFIXES = [
29 "node-pty",
30 "ffi-rs",
31 "@yuuang/",
32 "@ff-labs/",
33 "@clerk/electron-passkeys",
34 "@msgpackr-extract/",
35 "msgpackr-extract",
36 "node-gyp-build",
37 "node-addon-api",
38 // Required by node-gyp-build-optional-packages. Not native, but in the
39 // closure: without it, WSL gets MODULE_NOT_FOUND while Windows is fine.
40 "detect-libc",
41 // ws's optional accelerators. Nothing in this repo declares them, so they are
42 // not in the staged production install and the packaged app does not ship
43 // them either way -- ws wraps the require in try/catch and falls back to its
44 // JS paths. They are listed because they were being inlined from the dev
45 // store: both carry binding.gyp and prebuilds and load through
46 // node-gyp-build, and a native loader inlined into a bundle chunk searches
47 // for prebuilds that cannot be beside it. Listing them keeps that from
48 // becoming real if either is ever declared as a dependency.
49 "bufferutil",
50 "utf-8-validate",
51] as const;
52​
53export function isRuntimeExternalCliDependency(id: string): boolean {
54 return CLI_RUNTIME_EXTERNAL_PREFIXES.some((prefix) => id.startsWith(prefix));
56​
57/**
58 * True when `id` must stay out of the bundle.
59 *
60 * This has to be wired to the bundler's `neverBundle`, not just to
61 * `alwaysBundle`. `alwaysBundle` only forces packages IN — returning false from
62 * it means "no opinion", and the default then applies: a declared dependency
63 * stays external, but a transitive one gets bundled. That is how
64 * msgpackr-extract, node-gyp-build-optional-packages and detect-libc ended up
65 * inlined while node-pty (a declared dependency) stayed external.
66 */
67export function isExternalCliDependency(id: string): boolean {
68 return isRuntimeExternalCliDependency(id);
70​
71/** True when the CLI bundle should inline `id` rather than leave it external. */
72export function shouldBundleCliDependency(id: string): boolean {
73 if (id.startsWith("node:")) return false;
74 return !isExternalCliDependency(id);
76​
77/** Select direct dependency roots whose runtime closure belongs in the sidecar. */
78export function selectCliRuntimeExternalDependencies(
79 dependencies: Readonly<Record<string, string>>,
80): Record<string, string> {
81 return Object.fromEntries(
82 Object.entries(dependencies).filter(([name]) => isRuntimeExternalCliDependency(name)),
83 );
85​
86/**
87 * Scan an emitted bundle chunk for runtime-external packages that were inlined.
88 *
89 * Configuring the bundler is not the same as checking what it produced. The
90 * `alwaysBundle` predicate only forces packages IN; returning false from it
91 * means "no opinion", so a transitive dependency still gets bundled by default.
92 * msgpackr-extract, node-gyp-build-optional-packages and detect-libc were
93 * inlined that way while every list-based test passed, which is why this reads
94 * the artifact instead.
95 *
96 * `regionCount` is reported so the caller can tell "nothing was inlined" apart
97 * from "the marker format changed and this scan no longer sees anything".
98 *
99 * `inlinedPackages` is every package seen in a region, which lets the caller
100 * check the opposite direction too. Verifying only that externals are absent
101 * would still pass if the bundler reverted to leaving everything external: the
102 * scan would see source-file regions, report nothing inlined, and the packaged
103 * backends would then fail with ERR_MODULE_NOT_FOUND because those packages
104 * are not in the selected sidecar closure either.
105 */
106export function findInlinedExternalPackages(source: string): {
107 readonly regionCount: number;
108 readonly inlined: ReadonlyArray<string>;
109 readonly inlinedPackages: ReadonlyArray<string>;
110} {
111 // Rolldown marks each inlined module with a `//#region <path>` comment.
112 const regionPattern = /\/\/#region\s+(\S+)/g;
113 const packagePattern = /node_modules\/((?:@[^/\s]+\/)?[^/\s]+)\//g;
114​
115 let regionCount = 0;
116 const inlined = new Set<string>();
117 const inlinedPackages = new Set<string>();
118 for (const region of source.matchAll(regionPattern)) {
119 regionCount += 1;
120 const regionPath = region[1] ?? "";
121 for (const candidate of regionPath.matchAll(packagePattern)) {
122 const name = candidate[1];
123 if (name === undefined || name === ".pnpm") continue;
124 inlinedPackages.add(name);
125 if (isExternalCliDependency(name)) inlined.add(name);
126 }
127 }
128​
129 return {
130 regionCount,
131 inlined: [...inlined].sort(),
132 inlinedPackages: [...inlinedPackages].sort(),
133 };