@prisma/compute-sdk 0.44.0 → 0.45.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 (127) hide show
  1. package/README.md +196 -0
  2. package/dist/archive.d.ts +2 -1
  3. package/dist/archive.d.ts.map +1 -1
  4. package/dist/archive.js +8 -4
  5. package/dist/archive.js.map +1 -1
  6. package/dist/build-strategy.d.ts +7 -0
  7. package/dist/build-strategy.d.ts.map +1 -1
  8. package/dist/build-strategy.js +3 -0
  9. package/dist/build-strategy.js.map +1 -1
  10. package/dist/compute-client.d.ts.map +1 -1
  11. package/dist/compute-client.js +1 -1
  12. package/dist/compute-client.js.map +1 -1
  13. package/dist/config/frameworks.d.ts +1 -1
  14. package/dist/errors.d.ts +14 -0
  15. package/dist/errors.d.ts.map +1 -1
  16. package/dist/errors.js +3 -0
  17. package/dist/errors.js.map +1 -1
  18. package/dist/package-manager.d.ts +6 -0
  19. package/dist/package-manager.d.ts.map +1 -0
  20. package/dist/package-manager.js +21 -0
  21. package/dist/package-manager.js.map +1 -0
  22. package/dist/service/artifact/exclude.d.ts +6 -0
  23. package/dist/service/artifact/exclude.d.ts.map +1 -0
  24. package/dist/service/artifact/exclude.js +8 -0
  25. package/dist/service/artifact/exclude.js.map +1 -0
  26. package/dist/service/artifact/launcher-file.d.ts +3 -0
  27. package/dist/service/artifact/launcher-file.d.ts.map +1 -0
  28. package/dist/service/artifact/launcher-file.js +13 -0
  29. package/dist/service/artifact/launcher-file.js.map +1 -0
  30. package/dist/service/artifact/write-artifact.d.ts +16 -0
  31. package/dist/service/artifact/write-artifact.d.ts.map +1 -0
  32. package/dist/service/artifact/write-artifact.js +24 -0
  33. package/dist/service/artifact/write-artifact.js.map +1 -0
  34. package/dist/service/build/build-output.d.ts +15 -0
  35. package/dist/service/build/build-output.d.ts.map +1 -0
  36. package/dist/service/build/build-output.js +63 -0
  37. package/dist/service/build/build-output.js.map +1 -0
  38. package/dist/service/build/build-service.d.ts +30 -0
  39. package/dist/service/build/build-service.d.ts.map +1 -0
  40. package/dist/service/build/build-service.js +95 -0
  41. package/dist/service/build/build-service.js.map +1 -0
  42. package/dist/service/build/run-step.d.ts +32 -0
  43. package/dist/service/build/run-step.d.ts.map +1 -0
  44. package/dist/service/build/run-step.js +29 -0
  45. package/dist/service/build/run-step.js.map +1 -0
  46. package/dist/service/index.d.ts +7 -0
  47. package/dist/service/index.d.ts.map +1 -0
  48. package/dist/service/index.js +7 -0
  49. package/dist/service/index.js.map +1 -0
  50. package/dist/service/launcher-contract/events.d.ts +22 -0
  51. package/dist/service/launcher-contract/events.d.ts.map +1 -0
  52. package/dist/service/launcher-contract/events.js +39 -0
  53. package/dist/service/launcher-contract/events.js.map +1 -0
  54. package/dist/service/launcher-contract/start-plan.d.ts +20 -0
  55. package/dist/service/launcher-contract/start-plan.d.ts.map +1 -0
  56. package/dist/service/launcher-contract/start-plan.js +10 -0
  57. package/dist/service/launcher-contract/start-plan.js.map +1 -0
  58. package/dist/service/launcher.mjs +482 -0
  59. package/dist/service/settings/dev-command.d.ts +6 -0
  60. package/dist/service/settings/dev-command.d.ts.map +1 -0
  61. package/dist/service/settings/dev-command.js +46 -0
  62. package/dist/service/settings/dev-command.js.map +1 -0
  63. package/dist/service/settings/index.d.ts +5 -0
  64. package/dist/service/settings/index.d.ts.map +1 -0
  65. package/dist/service/settings/index.js +3 -0
  66. package/dist/service/settings/index.js.map +1 -0
  67. package/dist/service/settings/install.d.ts +15 -0
  68. package/dist/service/settings/install.d.ts.map +1 -0
  69. package/dist/service/settings/install.js +58 -0
  70. package/dist/service/settings/install.js.map +1 -0
  71. package/dist/service/settings/node-version.d.ts +9 -0
  72. package/dist/service/settings/node-version.d.ts.map +1 -0
  73. package/dist/service/settings/node-version.js +18 -0
  74. package/dist/service/settings/node-version.js.map +1 -0
  75. package/dist/service/settings/package-json.d.ts +14 -0
  76. package/dist/service/settings/package-json.d.ts.map +1 -0
  77. package/dist/service/settings/package-json.js +51 -0
  78. package/dist/service/settings/package-json.js.map +1 -0
  79. package/dist/service/settings/resolve.d.ts +9 -0
  80. package/dist/service/settings/resolve.d.ts.map +1 -0
  81. package/dist/service/settings/resolve.js +49 -0
  82. package/dist/service/settings/resolve.js.map +1 -0
  83. package/dist/service/settings/start-order.d.ts +21 -0
  84. package/dist/service/settings/start-order.d.ts.map +1 -0
  85. package/dist/service/settings/start-order.js +138 -0
  86. package/dist/service/settings/start-order.js.map +1 -0
  87. package/dist/service/settings/types.d.ts +66 -0
  88. package/dist/service/settings/types.d.ts.map +1 -0
  89. package/dist/service/settings/types.js +2 -0
  90. package/dist/service/settings/types.js.map +1 -0
  91. package/dist/workspace.d.ts +4 -1
  92. package/dist/workspace.d.ts.map +1 -1
  93. package/dist/workspace.js +12 -23
  94. package/dist/workspace.js.map +1 -1
  95. package/package.json +16 -2
  96. package/src/archive.ts +9 -2
  97. package/src/build-strategy.ts +15 -1
  98. package/src/compute-client.ts +1 -0
  99. package/src/errors.ts +13 -0
  100. package/src/package-manager.ts +27 -0
  101. package/src/service/artifact/exclude.ts +7 -0
  102. package/src/service/artifact/launcher-file.ts +18 -0
  103. package/src/service/artifact/write-artifact.ts +50 -0
  104. package/src/service/build/build-output.ts +95 -0
  105. package/src/service/build/build-service.ts +171 -0
  106. package/src/service/build/run-step.ts +65 -0
  107. package/src/service/index.ts +24 -0
  108. package/src/service/launcher/bin-targets.ts +143 -0
  109. package/src/service/launcher/bin-wrappers.ts +48 -0
  110. package/src/service/launcher/bun-shell.ts +17 -0
  111. package/src/service/launcher/listening-ports.ts +112 -0
  112. package/src/service/launcher/main.ts +54 -0
  113. package/src/service/launcher/package-manager-shims.ts +147 -0
  114. package/src/service/launcher/proc.ts +112 -0
  115. package/src/service/launcher/run-command.ts +82 -0
  116. package/src/service/launcher/serve-static.ts +102 -0
  117. package/src/service/launcher-contract/events.ts +53 -0
  118. package/src/service/launcher-contract/start-plan.ts +18 -0
  119. package/src/service/settings/dev-command.ts +65 -0
  120. package/src/service/settings/index.ts +17 -0
  121. package/src/service/settings/install.ts +105 -0
  122. package/src/service/settings/node-version.ts +26 -0
  123. package/src/service/settings/package-json.ts +71 -0
  124. package/src/service/settings/resolve.ts +80 -0
  125. package/src/service/settings/start-order.ts +213 -0
  126. package/src/service/settings/types.ts +73 -0
  127. package/src/workspace.ts +20 -35
@@ -0,0 +1,82 @@
1
+ // Command mode: the Launcher runs the Service's start command and reports what happens.
2
+ import { rmSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { formatLauncherEvent } from "../launcher-contract/events.ts";
5
+ import {
6
+ BUN_BINARY,
7
+ linkNodeToBun,
8
+ WRAPPER_DIR,
9
+ writeBinWrappers,
10
+ } from "./bin-wrappers.ts";
11
+ import { runInBunShell } from "./bun-shell.ts";
12
+ import { watchForListeningPort } from "./listening-ports.ts";
13
+ import { writePackageManagerShims } from "./package-manager-shims.ts";
14
+
15
+ export interface RunCommandOptions {
16
+ /** The Service's start command, as the Start plan states it. */
17
+ command: string;
18
+ serviceDir: string;
19
+ /** The port Compute routes to. */
20
+ port: number;
21
+ /** The path of the running Launcher. The package manager shims start it again. */
22
+ launcherFile: string;
23
+ }
24
+
25
+ /**
26
+ * Runs the start command until it ends and returns its exit code.
27
+ * Writes the `start` event, then `listening` when the Service listens, then `exit`.
28
+ */
29
+ export async function runCommand(options: RunCommandOptions): Promise<number> {
30
+ const { command, serviceDir, port, launcherFile } = options;
31
+
32
+ writeWrappers(serviceDir, WRAPPER_DIR, launcherFile);
33
+
34
+ const stopWatching = watchForListeningPort(port, (listeningPort) => {
35
+ console.log(
36
+ formatLauncherEvent({ event: "listening", port: listeningPort }),
37
+ );
38
+ });
39
+
40
+ console.log(formatLauncherEvent({ event: "start", command, port }));
41
+ const exitCode = await runInBunShell(command, {
42
+ cwd: serviceDir,
43
+ env: serviceEnvironment(process.env, port),
44
+ });
45
+ stopWatching();
46
+ console.log(formatLauncherEvent({ event: "exit", code: exitCode }));
47
+
48
+ return exitCode;
49
+ }
50
+
51
+ /**
52
+ * Fills the wrapper folder with the bin wrappers, the package manager shims and the `node` link.
53
+ * It starts from an empty folder: /tmp can outlive one start, and a file of an earlier start must not be reused.
54
+ */
55
+ export function writeWrappers(
56
+ serviceDir: string,
57
+ wrapperDir: string,
58
+ launcherFile: string,
59
+ ): void {
60
+ rmSync(wrapperDir, { recursive: true, force: true });
61
+ writeBinWrappers(serviceDir, wrapperDir);
62
+ writePackageManagerShims(wrapperDir, launcherFile);
63
+ linkNodeToBun(wrapperDir);
64
+ }
65
+
66
+ /**
67
+ * The environment of the Service: what the Launcher got, plus the variables most servers read to know where to listen.
68
+ * The PATH holds the wrappers and Bun, and nothing else.
69
+ */
70
+ export function serviceEnvironment(
71
+ launcherEnv: NodeJS.ProcessEnv,
72
+ port: number,
73
+ ): Record<string, string | undefined> {
74
+ return {
75
+ ...launcherEnv,
76
+ PORT: String(port),
77
+ HOST: "0.0.0.0",
78
+ HOSTNAME: "0.0.0.0",
79
+ NODE_ENV: launcherEnv["NODE_ENV"] ?? "production",
80
+ PATH: `${WRAPPER_DIR}:${dirname(BUN_BINARY)}`,
81
+ };
82
+ }
@@ -0,0 +1,102 @@
1
+ // Static mode: the Launcher serves a folder of files itself.
2
+ import { statSync } from "node:fs";
3
+ import { join, normalize, relative, sep } from "node:path";
4
+
5
+ /** The one folder with a leading dot that a site publishes, for files such as `security.txt`. */
6
+ const PUBLIC_DOT_FOLDER = ".well-known";
7
+
8
+ /** Serves the files in `root` on `port`, on every network address. */
9
+ export function serveStatic(root: string, port: number): Bun.Server<undefined> {
10
+ return Bun.serve({
11
+ port,
12
+ hostname: "0.0.0.0",
13
+ fetch: (request) => respond(root, new URL(request.url).pathname),
14
+ });
15
+ }
16
+
17
+ function respond(root: string, pathname: string): Response {
18
+ const requested = requestedFile(root, pathname);
19
+
20
+ if (requested === null) {
21
+ return notFound();
22
+ }
23
+
24
+ const file = candidateFiles(requested).find(isFile);
25
+
26
+ if (file !== undefined) {
27
+ return new Response(Bun.file(file));
28
+ }
29
+
30
+ return unknownPathResponse(root);
31
+ }
32
+
33
+ /**
34
+ * The file a request path names inside `root`, or null when the path must not be served.
35
+ * A name that starts with a dot is not content: `.prisma/` holds the Launcher and the Start plan,
36
+ * and a Service folder can hold files such as `.npmrc`.
37
+ */
38
+ export function requestedFile(root: string, pathname: string): string | null {
39
+ const path = decodePath(pathname);
40
+
41
+ if (path === null) {
42
+ return null;
43
+ }
44
+
45
+ const file = join(root, normalize(path));
46
+ const names = relative(root, file).split(sep);
47
+
48
+ if (!isInside(root, file) || names.some(isHidden)) {
49
+ return null;
50
+ }
51
+
52
+ return file;
53
+ }
54
+
55
+ /** The files that can answer a request, in the order they are tried. The last two let `/docs` and `/about` name `docs/index.html` and `about.html`. */
56
+ function candidateFiles(requested: string): string[] {
57
+ return [requested, join(requested, "index.html"), `${requested}.html`];
58
+ }
59
+
60
+ /** A site with a 404 page has a page per route. Any other site is a single-page app and gets its index.html. */
61
+ function unknownPathResponse(root: string): Response {
62
+ const notFoundPage = join(root, "404.html");
63
+
64
+ if (isFile(notFoundPage)) {
65
+ return new Response(Bun.file(notFoundPage), { status: 404 });
66
+ }
67
+
68
+ const indexPage = join(root, "index.html");
69
+
70
+ return isFile(indexPage) ? new Response(Bun.file(indexPage)) : notFound();
71
+ }
72
+
73
+ function notFound(): Response {
74
+ return new Response("Not found", { status: 404 });
75
+ }
76
+
77
+ /** The path of a request with its `%` codes decoded, or null when a code is malformed. */
78
+ function decodePath(pathname: string): string | null {
79
+ try {
80
+ return decodeURIComponent(pathname);
81
+ } catch {
82
+ // decodeURIComponent throws only for a malformed code, and such a path names no file.
83
+ return null;
84
+ }
85
+ }
86
+
87
+ function isHidden(name: string): boolean {
88
+ return name.startsWith(".") && name !== PUBLIC_DOT_FOLDER;
89
+ }
90
+
91
+ function isInside(dir: string, file: string): boolean {
92
+ return file === dir || file.startsWith(`${dir}${sep}`);
93
+ }
94
+
95
+ function isFile(file: string): boolean {
96
+ try {
97
+ return statSync(file).isFile();
98
+ } catch {
99
+ // The path comes from a request, so any failure to read it means there is no file to serve.
100
+ return false;
101
+ }
102
+ }
@@ -0,0 +1,53 @@
1
+ // What the Launcher says about a start. It writes one line per event into the Service's log.
2
+ // The lines show in the log how the start went, and a start check can read them back.
3
+
4
+ export type LauncherEvent =
5
+ /** The Launcher is about to run the Service's start command. */
6
+ | { event: "start"; command: string; port: number }
7
+ /** A process of the Service listens on `port`. */
8
+ | { event: "listening"; port: number }
9
+ /** The Service's start command ended. */
10
+ | { event: "exit"; code: number };
11
+
12
+ const PREFIX = "[prisma] ";
13
+
14
+ /** The log line for one event, without a line break. */
15
+ export function formatLauncherEvent(event: LauncherEvent): string {
16
+ return `${PREFIX}${JSON.stringify(event)}`;
17
+ }
18
+
19
+ /** The Launcher event on one log line, or null when the line is the Service's own output. */
20
+ export function parseLauncherEvent(line: string): LauncherEvent | null {
21
+ if (!line.startsWith(PREFIX)) {
22
+ return null;
23
+ }
24
+
25
+ try {
26
+ const parsed: unknown = JSON.parse(line.slice(PREFIX.length));
27
+ return isLauncherEvent(parsed) ? parsed : null;
28
+ } catch {
29
+ // A Service may print a line that starts like ours. It is the Service's output, not an event.
30
+ return null;
31
+ }
32
+ }
33
+
34
+ function isLauncherEvent(value: unknown): value is LauncherEvent {
35
+ if (typeof value !== "object" || value === null) {
36
+ return false;
37
+ }
38
+
39
+ const fields = value as Record<string, unknown>;
40
+ switch (fields["event"]) {
41
+ case "start":
42
+ return (
43
+ typeof fields["command"] === "string" &&
44
+ typeof fields["port"] === "number"
45
+ );
46
+ case "listening":
47
+ return typeof fields["port"] === "number";
48
+ case "exit":
49
+ return typeof fields["code"] === "number";
50
+ default:
51
+ return false;
52
+ }
53
+ }
@@ -0,0 +1,18 @@
1
+ // The Start plan: what the Build runner tells the Launcher to do on the Runtime.
2
+ // The build writes it into the Artifact beside the Launcher, and the Launcher reads it at every start.
3
+ // Both files come from the same SDK version, so the format needs no version field.
4
+
5
+ /** The Launcher, relative to the Artifact folder. Compute starts this file. */
6
+ export const LAUNCHER_FILE = ".prisma/launcher.mjs";
7
+
8
+ /** The Start plan, relative to the Artifact folder. */
9
+ export const START_PLAN_FILE = ".prisma/plan.json";
10
+
11
+ /** The port the Service gets as `PORT` when Compute sets none and the user stated none. */
12
+ export const DEFAULT_PORT = 8080;
13
+
14
+ export type StartPlan =
15
+ /** Run the Service's own start command. `port` is the port the user stated, or null. */
16
+ | { kind: "command"; command: string; port: number | null }
17
+ /** Serve a folder of static files. `dir` is relative to the Artifact folder. */
18
+ | { kind: "static"; dir: string; port: number | null };
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Commands whose `start` form runs a development server.
3
+ * This list and `BARE_VITE` are the only places in the Build rules that name a tool.
4
+ */
5
+ const DEV_COMMANDS = [
6
+ "react-scripts start",
7
+ "docusaurus start",
8
+ "expo start",
9
+ "webpack-dev-server",
10
+ "nodemon",
11
+ "ts-node-dev",
12
+ ];
13
+
14
+ /** `vite` alone or with flags only runs its development server. `vite preview` and `vite build` do not. */
15
+ const BARE_VITE = /^vite(\s+-|\s*$)/;
16
+
17
+ /** A subcommand or flag that makes a tool run in development mode. */
18
+ const DEV_WORDS = new Set(["dev", "develop", "serve", "watch", "--watch"]);
19
+
20
+ /**
21
+ * True when a script runs a development server. Such a script is never the start:
22
+ * a development server must not run in production.
23
+ */
24
+ export function isDevCommand(
25
+ script: string,
26
+ scripts: Record<string, string> = {},
27
+ ): boolean {
28
+ const command = script.trim();
29
+
30
+ return (
31
+ isTheDevScript(command, scripts) ||
32
+ startsWithDevCommand(command) ||
33
+ hasDevWord(command)
34
+ );
35
+ }
36
+
37
+ function isTheDevScript(
38
+ command: string,
39
+ scripts: Record<string, string>,
40
+ ): boolean {
41
+ const dev = scripts["dev"];
42
+ if (!dev) {
43
+ return false;
44
+ }
45
+
46
+ return command === dev.trim();
47
+ }
48
+
49
+ function startsWithDevCommand(command: string): boolean {
50
+ return (
51
+ DEV_COMMANDS.some((devCommand) => command.startsWith(devCommand)) ||
52
+ BARE_VITE.test(command)
53
+ );
54
+ }
55
+
56
+ /** Looks at the arguments of each command in a chain such as `a && b`. The tool's own name is not an argument. */
57
+ function hasDevWord(command: string): boolean {
58
+ return command.split(/&&|\|\||;/).some((part) =>
59
+ part
60
+ .trim()
61
+ .split(/\s+/)
62
+ .slice(1)
63
+ .some((word) => DEV_WORDS.has(word)),
64
+ );
65
+ }
@@ -0,0 +1,17 @@
1
+ // The public API of `@prisma/compute-sdk/service/settings`: the Build rules.
2
+ // Nothing here loads a process or file API, so the rules also run in a browser or a Worker.
3
+ export type { PackageManager } from "../../package-manager.ts";
4
+ export { isDevCommand } from "./dev-command.ts";
5
+ export {
6
+ resolveServiceBuildSettings,
7
+ resolveStartAfterBuild,
8
+ } from "./resolve.ts";
9
+ export type {
10
+ BuildOutput,
11
+ ReadFile,
12
+ Resolved,
13
+ ServiceBuildSettings,
14
+ ServiceConfig,
15
+ Source,
16
+ Start,
17
+ } from "./types.ts";
@@ -0,0 +1,105 @@
1
+ import {
2
+ LOCKFILES,
3
+ type PackageManager,
4
+ packageManagerFromField,
5
+ } from "../../package-manager.ts";
6
+ import type {
7
+ PackageJson,
8
+ ReadFile,
9
+ Resolved,
10
+ ServiceConfig,
11
+ } from "./types.ts";
12
+
13
+ /** The Service's package manager, and the lockfile found in the Service folder, if any. */
14
+ export interface PackageManagerChoice {
15
+ packageManager: PackageManager;
16
+ lockfile: string | null;
17
+ }
18
+
19
+ /** With a lockfile the install is frozen: a deploy must install what the lockfile says. */
20
+ const INSTALL_COMMANDS: Record<
21
+ PackageManager,
22
+ { frozen: string; unfrozen: string }
23
+ > = {
24
+ npm: { frozen: "npm ci", unfrozen: "npm install" },
25
+ pnpm: { frozen: "pnpm install --frozen-lockfile", unfrozen: "pnpm install" },
26
+ yarn: { frozen: "yarn install --frozen-lockfile", unfrozen: "yarn install" },
27
+ bun: { frozen: "bun install --frozen-lockfile", unfrozen: "bun install" },
28
+ };
29
+
30
+ /** Yarn 2+ replaced `--frozen-lockfile` with `--immutable`. A repository on Yarn 2+ has a `.yarnrc.yml`. */
31
+ const YARN_2_FROZEN_INSTALL = "yarn install --immutable";
32
+ const YARN_2_CONFIG_FILE = ".yarnrc.yml";
33
+
34
+ /** The package manager: the `packageManager` field, then the lockfile, then npm. */
35
+ export async function choosePackageManager(
36
+ read: ReadFile,
37
+ packageJson: PackageJson,
38
+ ): Promise<PackageManagerChoice> {
39
+ const lockfile = await findLockfile(read);
40
+
41
+ return {
42
+ packageManager:
43
+ packageManagerFromField(packageJson.packageManager) ??
44
+ lockfile?.packageManager ??
45
+ "npm",
46
+ lockfile: lockfile?.file ?? null,
47
+ };
48
+ }
49
+
50
+ /**
51
+ * The install command: Service config first, then the package manager's own command.
52
+ * A malformed `package.json` hides its dependencies, so the install runs and the package manager reports the file.
53
+ */
54
+ export async function resolveInstall(
55
+ read: ReadFile,
56
+ packageJson: PackageJson,
57
+ choice: PackageManagerChoice,
58
+ config: ServiceConfig,
59
+ malformed = false,
60
+ ): Promise<Resolved<string | null>> {
61
+ if (config.install) {
62
+ return { value: config.install, from: "config" };
63
+ }
64
+
65
+ const from = choice.lockfile === null ? "default" : "lockfile";
66
+ if (!malformed && !hasDependencies(packageJson)) {
67
+ return { value: null, from };
68
+ }
69
+
70
+ return { value: await installCommand(read, choice), from };
71
+ }
72
+
73
+ async function findLockfile(
74
+ read: ReadFile,
75
+ ): Promise<{ file: string; packageManager: PackageManager } | null> {
76
+ for (const [file, packageManager] of LOCKFILES) {
77
+ if ((await read(file)) !== null) {
78
+ return { file, packageManager };
79
+ }
80
+ }
81
+
82
+ return null;
83
+ }
84
+
85
+ /** No dependencies means no install step. */
86
+ function hasDependencies(packageJson: PackageJson): boolean {
87
+ const all = { ...packageJson.dependencies, ...packageJson.devDependencies };
88
+
89
+ return Object.keys(all).length > 0;
90
+ }
91
+
92
+ async function installCommand(
93
+ read: ReadFile,
94
+ { packageManager, lockfile }: PackageManagerChoice,
95
+ ): Promise<string> {
96
+ if (lockfile === null) {
97
+ return INSTALL_COMMANDS[packageManager].unfrozen;
98
+ }
99
+
100
+ if (packageManager === "yarn" && (await read(YARN_2_CONFIG_FILE)) !== null) {
101
+ return YARN_2_FROZEN_INSTALL;
102
+ }
103
+
104
+ return INSTALL_COMMANDS[packageManager].frozen;
105
+ }
@@ -0,0 +1,26 @@
1
+ import type { PackageJson, ReadFile } from "./types.ts";
2
+
3
+ /** One version such as `22`, `v20.11.1` or `^18`. The first group is its major version. */
4
+ const SINGLE_VERSION = /^\s*(?:v|\^|~)?(\d+)(?:\.[\dx*]+)*\s*$/;
5
+
6
+ /**
7
+ * The major Node.js version the repository pins, or null when it pins none.
8
+ * The first of `.nvmrc`, `.node-version` and `engines.node` that exists decides.
9
+ */
10
+ export async function pinnedNodeVersion(
11
+ read: ReadFile,
12
+ packageJson: PackageJson,
13
+ ): Promise<string | null> {
14
+ const stated =
15
+ (await read(".nvmrc")) ??
16
+ (await read(".node-version")) ??
17
+ packageJson.engines?.node ??
18
+ null;
19
+
20
+ return stated === null ? null : pinnedMajor(String(stated));
21
+ }
22
+
23
+ /** Only a single version counts. A range such as `>=18` is a minimum, not a request, so it pins nothing. */
24
+ export function pinnedMajor(stated: string): string | null {
25
+ return SINGLE_VERSION.exec(stated)?.[1] ?? null;
26
+ }
@@ -0,0 +1,71 @@
1
+ // Reads the `package.json` of a Service. The file is the user's, so every field is checked before the Build rules use it.
2
+ import type { PackageJson, ReadFile } from "./types.ts";
3
+
4
+ /** What the Build rules get. `malformed` is true when the file exists but is not a JSON object. */
5
+ export interface ReadPackageJson {
6
+ packageJson: PackageJson;
7
+ malformed: boolean;
8
+ }
9
+
10
+ /**
11
+ * Reads `package.json`. A Service with none has no scripts and no dependencies.
12
+ * A malformed file reads as empty: the install then runs, and the package manager reports the file.
13
+ */
14
+ export async function readPackageJson(
15
+ read: ReadFile,
16
+ ): Promise<ReadPackageJson> {
17
+ const text = await read("package.json");
18
+ if (!text) {
19
+ return { packageJson: {}, malformed: false };
20
+ }
21
+
22
+ const packageJson = parsePackageJson(text);
23
+
24
+ return { packageJson: packageJson ?? {}, malformed: packageJson === null };
25
+ }
26
+
27
+ /** The fields the Build rules read, each kept only when it has the type they expect. Null when the text is not a JSON object. */
28
+ export function parsePackageJson(text: string): PackageJson | null {
29
+ const fields = record(parseJson(text));
30
+ if (fields === undefined) {
31
+ return null;
32
+ }
33
+
34
+ return {
35
+ packageManager: string(fields["packageManager"]),
36
+ scripts: strings(fields["scripts"]),
37
+ dependencies: strings(fields["dependencies"]),
38
+ devDependencies: strings(fields["devDependencies"]),
39
+ engines: { node: string(record(fields["engines"])?.["node"]) },
40
+ main: string(fields["main"]),
41
+ module: string(fields["module"]),
42
+ };
43
+ }
44
+
45
+ function parseJson(text: string): unknown {
46
+ try {
47
+ return JSON.parse(text);
48
+ } catch {
49
+ // JSON.parse throws only for text that is not JSON.
50
+ return undefined;
51
+ }
52
+ }
53
+
54
+ function record(value: unknown): Record<string, unknown> | undefined {
55
+ return typeof value === "object" && value !== null && !Array.isArray(value)
56
+ ? (value as Record<string, unknown>)
57
+ : undefined;
58
+ }
59
+
60
+ function string(value: unknown): string | undefined {
61
+ return typeof value === "string" ? value : undefined;
62
+ }
63
+
64
+ /** The entries of an object whose values are strings, such as `scripts`. */
65
+ function strings(value: unknown): Record<string, string> | undefined {
66
+ const entries = Object.entries(record(value) ?? {}).filter(
67
+ (entry): entry is [string, string] => typeof entry[1] === "string",
68
+ );
69
+
70
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
71
+ }
@@ -0,0 +1,80 @@
1
+ // Resolves a Service's Build settings from the files of its repository.
2
+ import type { PackageManager } from "../../package-manager.ts";
3
+ import { choosePackageManager, resolveInstall } from "./install.ts";
4
+ import { pinnedNodeVersion } from "./node-version.ts";
5
+ import { readPackageJson } from "./package-json.ts";
6
+ import { startAfterBuild, startBeforeBuild } from "./start-order.ts";
7
+ import type {
8
+ BuildOutput,
9
+ ReadFile,
10
+ Resolved,
11
+ ServiceBuildSettings,
12
+ ServiceConfig,
13
+ Start,
14
+ } from "./types.ts";
15
+
16
+ /**
17
+ * Resolves the Build settings that can be known before the build runs.
18
+ * `start` is `"after build"` when only the build output can decide it.
19
+ */
20
+ export async function resolveServiceBuildSettings(
21
+ read: ReadFile,
22
+ config: ServiceConfig = {},
23
+ signal?: AbortSignal,
24
+ ): Promise<ServiceBuildSettings> {
25
+ signal?.throwIfAborted();
26
+ const { packageJson, malformed } = await readPackageJson(read);
27
+ const scripts = packageJson.scripts ?? {};
28
+ const choice = await choosePackageManager(read, packageJson);
29
+ const { start, notes } = startBeforeBuild({ config, scripts });
30
+
31
+ return {
32
+ packageManager: choice.packageManager,
33
+ node: await pinnedNodeVersion(read, packageJson),
34
+ install: await resolveInstall(read, packageJson, choice, config, malformed),
35
+ build: resolveBuild(scripts, choice.packageManager, config),
36
+ start,
37
+ port: resolvePort(config),
38
+ notes: malformed ? [MALFORMED_PACKAGE_JSON_NOTE, ...notes] : notes,
39
+ };
40
+ }
41
+
42
+ /** Decides the start from the build output and the source. Null means no rule matched. */
43
+ export async function resolveStartAfterBuild(
44
+ read: ReadFile,
45
+ output: BuildOutput,
46
+ signal?: AbortSignal,
47
+ ): Promise<Resolved<Start> | null> {
48
+ signal?.throwIfAborted();
49
+
50
+ return startAfterBuild({
51
+ read,
52
+ output,
53
+ packageJson: (await readPackageJson(read)).packageJson,
54
+ });
55
+ }
56
+
57
+ const MALFORMED_PACKAGE_JSON_NOTE =
58
+ "package.json cannot be read as a JSON object.";
59
+
60
+ /** The repository's own `build` script is the build. Without one there is no build step. */
61
+ function resolveBuild(
62
+ scripts: Record<string, string>,
63
+ packageManager: PackageManager,
64
+ config: ServiceConfig,
65
+ ): Resolved<string | null> {
66
+ if (config.build !== undefined) {
67
+ return { value: config.build, from: "config" };
68
+ }
69
+
70
+ if (scripts["build"]) {
71
+ return { value: `${packageManager} run build`, from: "package.json" };
72
+ }
73
+
74
+ return { value: null, from: "default" };
75
+ }
76
+
77
+ /** Only the user states a port. No rule reads one from the repository. */
78
+ function resolvePort(config: ServiceConfig): Resolved<number> | null {
79
+ return config.port ? { value: config.port, from: "config" } : null;
80
+ }