@prisma/compute-sdk 0.48.0 → 0.49.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 (61) hide show
  1. package/README.md +22 -2
  2. package/dist/service/build/build-service.d.ts +1 -1
  3. package/dist/service/build/build-service.d.ts.map +1 -1
  4. package/dist/service/build/build-service.js +14 -5
  5. package/dist/service/build/build-service.js.map +1 -1
  6. package/dist/service/index.d.ts +1 -1
  7. package/dist/service/index.d.ts.map +1 -1
  8. package/dist/service/index.js.map +1 -1
  9. package/dist/service/output/build-output.d.ts +47 -0
  10. package/dist/service/output/build-output.d.ts.map +1 -0
  11. package/dist/service/output/build-output.js +97 -0
  12. package/dist/service/output/build-output.js.map +1 -0
  13. package/dist/service/output/copy.d.ts +15 -0
  14. package/dist/service/output/copy.d.ts.map +1 -0
  15. package/dist/service/output/copy.js +59 -0
  16. package/dist/service/output/copy.js.map +1 -0
  17. package/dist/service/output/entrypoint.d.ts +20 -0
  18. package/dist/service/output/entrypoint.d.ts.map +1 -0
  19. package/dist/service/output/entrypoint.js +183 -0
  20. package/dist/service/output/entrypoint.js.map +1 -0
  21. package/dist/service/output/source-files.d.ts +12 -0
  22. package/dist/service/output/source-files.d.ts.map +1 -0
  23. package/dist/service/output/source-files.js +46 -0
  24. package/dist/service/output/source-files.js.map +1 -0
  25. package/dist/service/output/trace/bins.d.ts +9 -0
  26. package/dist/service/output/trace/bins.d.ts.map +1 -0
  27. package/dist/service/output/trace/bins.js +26 -0
  28. package/dist/service/output/trace/bins.js.map +1 -0
  29. package/dist/service/output/trace/imports.d.ts +8 -0
  30. package/dist/service/output/trace/imports.d.ts.map +1 -0
  31. package/dist/service/output/trace/imports.js +24 -0
  32. package/dist/service/output/trace/imports.js.map +1 -0
  33. package/dist/service/output/trace/optional-peer-dependencies.d.ts +13 -0
  34. package/dist/service/output/trace/optional-peer-dependencies.d.ts.map +1 -0
  35. package/dist/service/output/trace/optional-peer-dependencies.js +34 -0
  36. package/dist/service/output/trace/optional-peer-dependencies.js.map +1 -0
  37. package/dist/service/output/trace/packages.d.ts +22 -0
  38. package/dist/service/output/trace/packages.d.ts.map +1 -0
  39. package/dist/service/output/trace/packages.js +50 -0
  40. package/dist/service/output/trace/packages.js.map +1 -0
  41. package/dist/service/output/trace/trace.d.ts +32 -0
  42. package/dist/service/output/trace/trace.d.ts.map +1 -0
  43. package/dist/service/output/trace/trace.js +53 -0
  44. package/dist/service/output/trace/trace.js.map +1 -0
  45. package/package.json +1 -1
  46. package/src/service/build/build-service.ts +15 -8
  47. package/src/service/index.ts +1 -1
  48. package/src/service/output/build-output.ts +174 -0
  49. package/src/service/output/copy.ts +69 -0
  50. package/src/service/output/entrypoint.ts +250 -0
  51. package/src/service/output/source-files.ts +64 -0
  52. package/src/service/output/trace/bins.ts +39 -0
  53. package/src/service/output/trace/imports.ts +37 -0
  54. package/src/service/output/trace/optional-peer-dependencies.ts +50 -0
  55. package/src/service/output/trace/packages.ts +81 -0
  56. package/src/service/output/trace/trace.ts +99 -0
  57. package/dist/service/output/write-build-output.d.ts +0 -16
  58. package/dist/service/output/write-build-output.d.ts.map +0 -1
  59. package/dist/service/output/write-build-output.js +0 -24
  60. package/dist/service/output/write-build-output.js.map +0 -1
  61. package/src/service/output/write-build-output.ts +0 -50
@@ -0,0 +1,69 @@
1
+ // Copies files of the Service folder to the same place in the build output folder.
2
+ import {
3
+ copyFile,
4
+ lstat,
5
+ mkdir,
6
+ readdir,
7
+ readlink,
8
+ symlink,
9
+ } from "node:fs/promises";
10
+ import path from "node:path";
11
+ import { excludedFromBuildOutput } from "./exclude.ts";
12
+
13
+ /** Copies paths from one folder to the same relative place in another. A link stays a link. */
14
+ export class Copy {
15
+ files = 0;
16
+ bytes = 0;
17
+ readonly #from: string;
18
+ readonly #to: string;
19
+ readonly #done = new Set<string>();
20
+
21
+ constructor(from: string, to: string) {
22
+ this.#from = from;
23
+ this.#to = to;
24
+ }
25
+
26
+ /** One file or link. A folder is only created: its files are copied when they are named. */
27
+ async file(source: string): Promise<void> {
28
+ if (this.#done.has(source)) {
29
+ return;
30
+ }
31
+ this.#done.add(source);
32
+
33
+ const info = await lstat(source).catch(() => null);
34
+ if (info === null) {
35
+ return;
36
+ }
37
+
38
+ const destination = path.join(this.#to, path.relative(this.#from, source));
39
+ await mkdir(path.dirname(destination), { recursive: true });
40
+ if (info.isSymbolicLink()) {
41
+ await symlink(await readlink(source), destination);
42
+ } else if (info.isDirectory()) {
43
+ await mkdir(destination, { recursive: true });
44
+ } else if (info.isFile()) {
45
+ await copyFile(source, destination);
46
+ this.files++;
47
+ this.bytes += info.size;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * A package folder with everything in it, except the packages in its own `node_modules`
53
+ * and what `excludedFromBuildOutput` names.
54
+ */
55
+ async packageFolder(dir: string): Promise<void> {
56
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
57
+ const full = path.join(dir, entry.name);
58
+ if (excludedFromBuildOutput(entry.name)) {
59
+ continue;
60
+ }
61
+
62
+ if (!entry.isDirectory()) {
63
+ await this.file(full);
64
+ } else if (entry.name !== "node_modules") {
65
+ await this.packageFolder(full);
66
+ }
67
+ }
68
+ }
69
+ }
@@ -0,0 +1,250 @@
1
+ // Reads a start command: the entrypoints of the server, and the bins it runs.
2
+ // The command is never changed. The Launcher runs it as written.
3
+ import { existsSync, realpathSync, statSync } from "node:fs";
4
+ import path from "node:path";
5
+ import type { PackageJson } from "../settings/types.ts";
6
+ import { excludedFromBuildOutput } from "./exclude.ts";
7
+
8
+ /** What a start command runs. */
9
+ export interface StartCommand {
10
+ /**
11
+ * The files the server starts from, such as `dist/main.js` in `node dist/main.js`,
12
+ * and the files a runtime option preloads, such as `./setup.js` in `node --require ./setup.js server.js`. Absolute.
13
+ */
14
+ entrypoints: string[];
15
+ /** The names in `node_modules/.bin` that the command runs, such as `tsx` in `tsx src/index.ts`. */
16
+ bins: string[];
17
+ /** The packages a runtime option preloads by name, such as `dotenv` in `node -r dotenv/config server.js`. */
18
+ preloadedPackages: string[];
19
+ }
20
+
21
+ const SOURCE_FILE = /\.(c|m)?(j|t)sx?$/;
22
+ const RUNTIMES = new Set(["node", "bun", "deno", "tsx", "ts-node"]);
23
+ const PACKAGE_MANAGERS = new Set(["npm", "pnpm", "yarn", "bun"]);
24
+ /** Runtime options that preload a module before the entrypoint: `--require ./setup.js` or `--require=./setup.js`. */
25
+ const PRELOAD_OPTIONS = new Set([
26
+ "-r",
27
+ "--require",
28
+ "--import",
29
+ "--loader",
30
+ "--experimental-loader",
31
+ "--preload",
32
+ ]);
33
+ /** Node.js reads the value of a preload option as a file only when it is a path. Any other value names a package. */
34
+ const FILE_PATH = /^\.{0,2}\//;
35
+ /** Words that run the command after them. */
36
+ const PREFIXES = new Set([
37
+ "cross-env",
38
+ "dotenv",
39
+ "dotenvx",
40
+ "env",
41
+ "exec",
42
+ "npx",
43
+ "bunx",
44
+ "pnpx",
45
+ ]);
46
+
47
+ /**
48
+ * The entrypoints, bins and preloaded packages of `command`, and of the `package.json` scripts it runs.
49
+ * A word that is neither a runtime, a script nor a bin is left out: it is a shell
50
+ * built-in or something the machine provides.
51
+ */
52
+ export function readStartCommand(
53
+ serviceDir: string,
54
+ command: string,
55
+ packageJson: PackageJson,
56
+ ): StartCommand {
57
+ const found: StartCommand = {
58
+ entrypoints: [],
59
+ bins: [],
60
+ preloadedPackages: [],
61
+ };
62
+ read(serviceDir, command, packageJson, found, new Set());
63
+
64
+ return {
65
+ entrypoints: [...new Set(found.entrypoints)],
66
+ bins: [...new Set(found.bins)],
67
+ preloadedPackages: [...new Set(found.preloadedPackages)],
68
+ };
69
+ }
70
+
71
+ function read(
72
+ serviceDir: string,
73
+ command: string,
74
+ packageJson: PackageJson,
75
+ found: StartCommand,
76
+ seenScripts: Set<string>,
77
+ ): void {
78
+ const scripts = packageJson.scripts ?? {};
79
+
80
+ for (const simple of command.split(/&&|\|\||;|\|/)) {
81
+ const [name, ...rest] = wordsOf(simple);
82
+ if (name === undefined) {
83
+ continue;
84
+ }
85
+
86
+ const positional = rest.filter((word) => !word.startsWith("-"));
87
+ const script = scriptName(name, positional, scripts);
88
+ if (script !== undefined) {
89
+ if (!seenScripts.has(script)) {
90
+ seenScripts.add(script);
91
+ // npm runs `prestart` and `poststart` around `start`.
92
+ for (const hook of [`pre${script}`, script, `post${script}`]) {
93
+ const text = scripts[hook];
94
+ if (text !== undefined) {
95
+ read(serviceDir, text, packageJson, found, seenScripts);
96
+ }
97
+ }
98
+ }
99
+ continue;
100
+ }
101
+
102
+ // A runtime takes one file. A bin may take several: `react-router-serve ./build/server/index.js`.
103
+ const runtime = RUNTIMES.has(name)
104
+ ? readRuntimeWords(rest, (word) =>
105
+ resolveFile(serviceDir, word, packageJson),
106
+ )
107
+ : null;
108
+ const files =
109
+ runtime?.files ?? positional.filter((word) => SOURCE_FILE.test(word));
110
+ found.preloadedPackages.push(...(runtime?.packages ?? []));
111
+ for (const word of files) {
112
+ const file = resolveFile(serviceDir, word, packageJson);
113
+ if (file !== null) {
114
+ found.entrypoints.push(file);
115
+ }
116
+ }
117
+
118
+ if (existsSync(path.join(serviceDir, "node_modules", ".bin", name))) {
119
+ found.bins.push(name);
120
+ }
121
+ }
122
+ }
123
+
124
+ /** The words of one simple command, without the variable assignments and prefixes in front of it. */
125
+ function wordsOf(simple: string): string[] {
126
+ let words = simple.trim().split(/\s+/).filter(Boolean);
127
+
128
+ for (;;) {
129
+ const [first] = words;
130
+ if (first === undefined) {
131
+ return [];
132
+ }
133
+
134
+ const isAssignment = /^[A-Za-z_][A-Za-z0-9_]*=/.test(first);
135
+ if (!isAssignment && !PREFIXES.has(first) && first !== "--") {
136
+ return words;
137
+ }
138
+
139
+ words = words.slice(1);
140
+ while (words[0]?.startsWith("-") && words[0] !== "--") {
141
+ words = words.slice(1);
142
+ }
143
+ }
144
+ }
145
+
146
+ /**
147
+ * The files a runtime runs and the packages it preloads, from the words after its name.
148
+ *
149
+ * Its entrypoint is the first word that names a script by its extension. With none, it is the
150
+ * first word that names a file, as `bin/www` in `node ./bin/www`. The value of another option
151
+ * can come first, as `.env` in `node --env-file .env server.js`, so a script wins over it
152
+ * and a dotenv file is never the entrypoint.
153
+ */
154
+ function readRuntimeWords(
155
+ words: string[],
156
+ resolve: (word: string) => string | null,
157
+ ): {
158
+ files: string[];
159
+ packages: string[];
160
+ } {
161
+ const files: string[] = [];
162
+ const packages: string[] = [];
163
+ let withoutExtension: string | undefined;
164
+
165
+ for (let index = 0; index < words.length; index++) {
166
+ const word = words[index] ?? "";
167
+ const [option = "", ...value] = word.split("=");
168
+ if (PRELOAD_OPTIONS.has(option)) {
169
+ const preloaded = value.length > 0 ? value.join("=") : words[++index];
170
+ if (preloaded === undefined) {
171
+ continue;
172
+ }
173
+
174
+ if (FILE_PATH.test(preloaded)) {
175
+ files.push(preloaded);
176
+ } else {
177
+ packages.push(packageNameOf(preloaded));
178
+ }
179
+ } else if (!word.startsWith("-")) {
180
+ const file = resolve(word);
181
+ if (file !== null && SOURCE_FILE.test(file)) {
182
+ return { files: [...files, word], packages };
183
+ }
184
+
185
+ const isDotenv = excludedFromBuildOutput(path.basename(file ?? ""));
186
+ if (file !== null && !isDotenv) {
187
+ withoutExtension ??= word;
188
+ }
189
+ }
190
+ }
191
+
192
+ if (withoutExtension !== undefined) {
193
+ files.push(withoutExtension);
194
+ }
195
+
196
+ return { files, packages };
197
+ }
198
+
199
+ /** The package a module name is in: `dotenv` for `dotenv/config`, `@scope/name` for `@scope/name/register`. */
200
+ function packageNameOf(moduleName: string): string {
201
+ return moduleName
202
+ .split("/")
203
+ .slice(0, moduleName.startsWith("@") ? 2 : 1)
204
+ .join("/");
205
+ }
206
+
207
+ /** The `package.json` script that `npm run x`, `npm start` or `yarn x` runs, if the words name one. */
208
+ function scriptName(
209
+ packageManager: string,
210
+ positional: string[],
211
+ scripts: Record<string, string>,
212
+ ): string | undefined {
213
+ if (!PACKAGE_MANAGERS.has(packageManager)) {
214
+ return undefined;
215
+ }
216
+
217
+ const [first, second] = positional;
218
+ const name = first === "run" || first === "run-script" ? second : first;
219
+
220
+ return name !== undefined && scripts[name] !== undefined ? name : undefined;
221
+ }
222
+
223
+ /** The file a word names, as Node.js resolves a path to run: the file, with an extension added, or a folder's index. */
224
+ function resolveFile(
225
+ serviceDir: string,
226
+ word: string,
227
+ packageJson: PackageJson,
228
+ ): string | null {
229
+ const target = path.resolve(serviceDir, word);
230
+ const candidates = [
231
+ target,
232
+ `${target}.js`,
233
+ `${target}.mjs`,
234
+ `${target}.cjs`,
235
+ `${target}.ts`,
236
+ path.join(target, "index.js"),
237
+ path.join(target, "index.mjs"),
238
+ ];
239
+ if (target === serviceDir) {
240
+ candidates.unshift(
241
+ path.resolve(serviceDir, packageJson.main ?? "index.js"),
242
+ );
243
+ }
244
+
245
+ const found = candidates.find(
246
+ (file) => existsSync(file) && statSync(file).isFile(),
247
+ );
248
+
249
+ return found === undefined ? null : realpathSync(found);
250
+ }
@@ -0,0 +1,64 @@
1
+ // The files of a Service that are its own: the repository's files and the output directories.
2
+ import { readdir } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import type { OutputDirectories } from "../settings/types.ts";
5
+ import { excludedFromBuildOutput } from "./exclude.ts";
6
+
7
+ /** Build caches inside an output directory. Nothing reads them at run time. */
8
+ const CACHE_FOLDERS = new Set(["cache", ".cache"]);
9
+
10
+ /**
11
+ * Every file of the Service folder except the installed `node_modules`, `.prisma`,
12
+ * and what `excludedFromBuildOutput` names.
13
+ *
14
+ * An output directory is kept with a `node_modules` folder of its own: Nuxt and
15
+ * Next.js put the packages their server needs there. Its cache folders are left out.
16
+ */
17
+ export async function sourceFiles(
18
+ serviceDir: string,
19
+ outputDirectories: OutputDirectories,
20
+ signal?: AbortSignal,
21
+ ): Promise<string[]> {
22
+ const outputDirs = new Set(outputDirectories.newDirs);
23
+ const found: string[] = [];
24
+
25
+ async function walk(dir: string, inOutputDir: boolean): Promise<void> {
26
+ signal?.throwIfAborted();
27
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
28
+ const full = path.join(dir, entry.name);
29
+ if (excludedFromBuildOutput(entry.name)) {
30
+ continue;
31
+ }
32
+
33
+ if (!entry.isDirectory()) {
34
+ found.push(full);
35
+ continue;
36
+ }
37
+
38
+ const atRoot = dir === serviceDir;
39
+ const output = inOutputDir || (atRoot && outputDirs.has(entry.name));
40
+ const left =
41
+ (entry.name === "node_modules" && !output) ||
42
+ (atRoot && entry.name === ".prisma") ||
43
+ (inOutputDir && CACHE_FOLDERS.has(entry.name));
44
+ if (!left) {
45
+ await walk(full, output);
46
+ }
47
+ }
48
+ }
49
+
50
+ await walk(serviceDir, false);
51
+
52
+ return found;
53
+ }
54
+
55
+ /** True when `file` is in one of the output directories. */
56
+ export function inOutputDirectory(
57
+ serviceDir: string,
58
+ outputDirectories: OutputDirectories,
59
+ file: string,
60
+ ): boolean {
61
+ const [top] = path.relative(serviceDir, file).split(path.sep);
62
+
63
+ return top !== undefined && outputDirectories.newDirs.includes(top);
64
+ }
@@ -0,0 +1,39 @@
1
+ // A bin the start command runs, such as `tsx` or `react-router-serve`.
2
+ import { realpathSync } from "node:fs";
3
+ import path from "node:path";
4
+ import {
5
+ addWithDependencies,
6
+ findPackage,
7
+ type InstalledPackage,
8
+ packageDirOf,
9
+ readManifest,
10
+ } from "./packages.ts";
11
+
12
+ /**
13
+ * The packages of the bins, each with the packages it depends on.
14
+ *
15
+ * A bin loads its own files by path, which imports do not show: tracing `tsx` misses
16
+ * a file it needs. So the package of a bin goes into the build output whole.
17
+ */
18
+ export function binPackages(
19
+ serviceDir: string,
20
+ bins: string[],
21
+ ): Map<string, InstalledPackage> {
22
+ const found = new Map<string, InstalledPackage>();
23
+
24
+ for (const name of bins) {
25
+ const bin = path.join(serviceDir, "node_modules", ".bin", name);
26
+ const dir = packageDirOf(realpathSync(bin));
27
+ if (dir === null) {
28
+ continue;
29
+ }
30
+
31
+ // Under pnpm the package is reached through a link in `node_modules`, which the bin's own link points at.
32
+ const packageName = readManifest(dir).name;
33
+ const installed =
34
+ packageName === undefined ? null : findPackage(serviceDir, packageName);
35
+ addWithDependencies(installed ?? { link: dir, dir }, found);
36
+ }
37
+
38
+ return found;
39
+ }
@@ -0,0 +1,37 @@
1
+ // Follows imports from files with `@vercel/nft`.
2
+ import path from "node:path";
3
+ import { nodeFileTrace } from "@vercel/nft";
4
+
5
+ /**
6
+ * Every file that `files` import, directly or through other files. Absolute paths.
7
+ *
8
+ * Compute runs a Service with Bun, which reads a package's `bun` export condition.
9
+ * nft's `conditions` replaces the default set, so the imports are followed twice.
10
+ */
11
+ export async function traceImports(
12
+ files: string[],
13
+ serviceDir: string,
14
+ ): Promise<string[]> {
15
+ if (files.length === 0) {
16
+ return [];
17
+ }
18
+
19
+ const base = path.parse(serviceDir).root;
20
+ const traces = await Promise.all(
21
+ [undefined, ["bun"]].map((conditions) =>
22
+ nodeFileTrace(files, {
23
+ base,
24
+ processCwd: serviceDir,
25
+ ...(conditions ? { conditions } : {}),
26
+ }),
27
+ ),
28
+ );
29
+
30
+ return [
31
+ ...new Set(
32
+ traces.flatMap((trace) =>
33
+ [...trace.fileList].map((file) => path.join(base, file)),
34
+ ),
35
+ ),
36
+ ];
37
+ }
@@ -0,0 +1,50 @@
1
+ // Optional peer dependencies that the Service installs for a package it uses.
2
+ import type { PackageJson } from "../../settings/types.ts";
3
+ import {
4
+ findPackage,
5
+ type InstalledPackage,
6
+ packageDirOf,
7
+ readManifest,
8
+ } from "./packages.ts";
9
+
10
+ /**
11
+ * A package loaded by a name held in a variable does not show as an import:
12
+ * sequelize loads `pg` that way. Such packages are declared as optional peer dependencies.
13
+ *
14
+ * When a traced package declares one and the Service lists it in `dependencies`,
15
+ * the Service installed it for that package, and it belongs in the build output.
16
+ */
17
+ export function optionalPeerDependencies(
18
+ serviceDir: string,
19
+ packageJson: PackageJson,
20
+ tracedFiles: string[],
21
+ ): Array<InstalledPackage & { name: string }> {
22
+ const listed = new Set(Object.keys(packageJson.dependencies ?? {}));
23
+ const tracedPackages = new Set<string>();
24
+ for (const file of tracedFiles) {
25
+ const dir = packageDirOf(file);
26
+ if (dir !== null) {
27
+ tracedPackages.add(dir);
28
+ }
29
+ }
30
+
31
+ const tracedNames = new Set(
32
+ [...tracedPackages].map((dir) => readManifest(dir).name),
33
+ );
34
+ const found = new Map<string, InstalledPackage>();
35
+ for (const dir of tracedPackages) {
36
+ const declared = readManifest(dir).peerDependenciesMeta ?? {};
37
+ for (const [name, { optional }] of Object.entries(declared)) {
38
+ if (!optional || !listed.has(name) || tracedNames.has(name)) {
39
+ continue;
40
+ }
41
+
42
+ const installed = findPackage(serviceDir, name);
43
+ if (installed !== null) {
44
+ found.set(name, installed);
45
+ }
46
+ }
47
+ }
48
+
49
+ return [...found].map(([name, installed]) => ({ name, ...installed }));
50
+ }
@@ -0,0 +1,81 @@
1
+ // Finds packages in `node_modules`, for the parts of a trace that take whole packages.
2
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ /** A package as it is found: `link` is the path it is reached by, a link under pnpm. `dir` holds its files. */
6
+ export interface InstalledPackage {
7
+ link: string;
8
+ dir: string;
9
+ }
10
+
11
+ /** The fields of a dependency's `package.json` that tracing reads. */
12
+ export interface PackageManifest {
13
+ name?: string;
14
+ dependencies?: Record<string, string>;
15
+ optionalDependencies?: Record<string, string>;
16
+ peerDependenciesMeta?: Record<string, { optional?: boolean }>;
17
+ }
18
+
19
+ export function readManifest(packageDir: string): PackageManifest {
20
+ try {
21
+ return JSON.parse(
22
+ readFileSync(path.join(packageDir, "package.json"), "utf8"),
23
+ );
24
+ } catch {
25
+ return {};
26
+ }
27
+ }
28
+
29
+ /** Finds a package the way Node.js does: in the `node_modules` of `from` and of each folder above it. */
30
+ export function findPackage(
31
+ from: string,
32
+ name: string,
33
+ ): InstalledPackage | null {
34
+ for (let dir = from; dir !== path.dirname(dir); dir = path.dirname(dir)) {
35
+ const link = path.join(dir, "node_modules", name);
36
+ if (existsSync(path.join(link, "package.json"))) {
37
+ return { link, dir: realpathSync(link) };
38
+ }
39
+ }
40
+
41
+ return null;
42
+ }
43
+
44
+ /** The folder of the package that holds `file`: the nearest folder with a `package.json` that sits in a `node_modules`. */
45
+ export function packageDirOf(file: string): string | null {
46
+ for (
47
+ let dir = path.dirname(file);
48
+ dir !== path.dirname(dir);
49
+ dir = path.dirname(dir)
50
+ ) {
51
+ const parent = path.basename(path.dirname(dir));
52
+ const inNodeModules = parent === "node_modules" || parent.startsWith("@");
53
+ if (inNodeModules && existsSync(path.join(dir, "package.json"))) {
54
+ return dir;
55
+ }
56
+ }
57
+
58
+ return null;
59
+ }
60
+
61
+ /** Adds a package and, in turn, every package it depends on. */
62
+ export function addWithDependencies(
63
+ installed: InstalledPackage,
64
+ found: Map<string, InstalledPackage>,
65
+ ): void {
66
+ if (found.has(installed.link)) {
67
+ return;
68
+ }
69
+
70
+ found.set(installed.link, installed);
71
+ const manifest = readManifest(installed.dir);
72
+ for (const name of Object.keys({
73
+ ...manifest.dependencies,
74
+ ...manifest.optionalDependencies,
75
+ })) {
76
+ const dependency = findPackage(installed.dir, name);
77
+ if (dependency !== null) {
78
+ addWithDependencies(dependency, found);
79
+ }
80
+ }
81
+ }
@@ -0,0 +1,99 @@
1
+ // The trace of a server: every file it loads from `node_modules`.
2
+ import { realpathSync } from "node:fs";
3
+ import path from "node:path";
4
+ import type { PackageJson } from "../../settings/types.ts";
5
+ import { readStartCommand } from "../entrypoint.ts";
6
+ import { binPackages } from "./bins.ts";
7
+ import { traceImports } from "./imports.ts";
8
+ import { optionalPeerDependencies } from "./optional-peer-dependencies.ts";
9
+ import {
10
+ addWithDependencies,
11
+ findPackage,
12
+ type InstalledPackage,
13
+ } from "./packages.ts";
14
+
15
+ /** What a server loads, found from its start command. */
16
+ export interface ServerTrace {
17
+ /** The files the server starts from. */
18
+ entrypoints: string[];
19
+ /** The bins the start command runs. */
20
+ bins: string[];
21
+ /** Every file the entrypoints and the built scripts import. */
22
+ files: string[];
23
+ /** Packages that go in whole: those of the bins, those the start command preloads, and the optional peer dependencies. */
24
+ packages: InstalledPackage[];
25
+ /** The names of the optional peer dependencies among `packages`. */
26
+ optionalPeerDependencies: string[];
27
+ }
28
+
29
+ /** Why a server could not be traced. */
30
+ export type Untraceable =
31
+ | "the start command runs no file and no bin that can be followed"
32
+ | "the server imports files from outside the Service folder";
33
+
34
+ /**
35
+ * Traces the server that `command` starts:
36
+ * 1. the imports of its entrypoints, and of the scripts the build wrote;
37
+ * 2. the packages of the bins it runs, and the packages it preloads;
38
+ * 3. the optional peer dependencies of what was traced.
39
+ */
40
+ export async function traceServer(options: {
41
+ serviceDir: string;
42
+ command: string;
43
+ packageJson: PackageJson;
44
+ /** Scripts in the output directories. A framework's server loads them by path, and they import packages. */
45
+ builtScripts: string[];
46
+ signal?: AbortSignal;
47
+ }): Promise<ServerTrace | Untraceable> {
48
+ const { packageJson } = options;
49
+ // Traced files are real paths, so the Service folder they are compared with must be its real path too.
50
+ const serviceDir = realpathSync(options.serviceDir);
51
+ const { entrypoints, bins, preloadedPackages } = readStartCommand(
52
+ serviceDir,
53
+ options.command,
54
+ packageJson,
55
+ );
56
+ if (entrypoints.length === 0 && bins.length === 0) {
57
+ return "the start command runs no file and no bin that can be followed";
58
+ }
59
+
60
+ options.signal?.throwIfAborted();
61
+ const files = await traceImports(
62
+ [...entrypoints, ...options.builtScripts],
63
+ serviceDir,
64
+ );
65
+
66
+ const packages = binPackages(serviceDir, bins);
67
+ // A preloaded package goes in whole, as a bin's package does: `tsx` loads its own files by path.
68
+ for (const name of preloadedPackages) {
69
+ const preloaded = findPackage(serviceDir, name);
70
+ if (preloaded !== null) {
71
+ addWithDependencies(preloaded, packages);
72
+ }
73
+ }
74
+
75
+ const peers = optionalPeerDependencies(serviceDir, packageJson, files);
76
+ for (const peer of peers) {
77
+ addWithDependencies(peer, packages);
78
+ }
79
+
80
+ const inside = (file: string) => {
81
+ const relative = path.relative(serviceDir, file);
82
+
83
+ return !relative.startsWith("..") && !path.isAbsolute(relative);
84
+ };
85
+ if (
86
+ !files.every(inside) ||
87
+ ![...packages.values()].every((found) => inside(found.dir))
88
+ ) {
89
+ return "the server imports files from outside the Service folder";
90
+ }
91
+
92
+ return {
93
+ entrypoints,
94
+ bins,
95
+ files,
96
+ packages: [...packages.values()],
97
+ optionalPeerDependencies: peers.map((peer) => peer.name),
98
+ };
99
+ }