@elumixor/devkit 0.9.0 → 0.10.1

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.
@@ -0,0 +1,36 @@
1
+ import { $ } from "bun";
2
+ import { isolatedWebEnv } from "../web-build.ts";
3
+
4
+ export interface TauriMacosBuildOptions {
5
+ /** Tauri project dir, holding `src-tauri` (default `apps/frontend`). */
6
+ frontendDir?: string;
7
+ /** Bundles to produce (default `app` — the `.app`, which is what a check needs). */
8
+ bundles?: string;
9
+ /** Suffix for this build's own web output, kit and cache dirs (default `mac`). */
10
+ webSuffix?: string;
11
+ }
12
+
13
+ /**
14
+ * Builds the macOS app, and nothing else: no Developer ID, no notarization, no install.
15
+ *
16
+ * This is the build that answers "does the Mac shell still compile against this frontend" while
17
+ * the other platforms are answering the same question for themselves. Signing and shipping belong
18
+ * to the `tauri-macos` *deploy* target, which does its own release build.
19
+ */
20
+ export async function buildTauriMacos(options: TauriMacosBuildOptions = {}) {
21
+ const frontendDir = options.frontendDir ?? "apps/frontend";
22
+ const bundles = options.bundles ?? "app";
23
+ const suffix = options.webSuffix ?? "mac";
24
+ const env = isolatedWebEnv(suffix);
25
+
26
+ // Tauri reads `frontendDist` from its own config file, which has no environment override — so
27
+ // the directory the isolated web build writes into is pointed at through a config overlay.
28
+ const overlay = JSON.stringify({ build: { frontendDist: `../${env.BUILD_DIR}` } });
29
+
30
+ await $`bunx tauri build --bundles ${bundles} --config ${overlay}`.cwd(frontendDir).env({
31
+ ...process.env,
32
+ ...env,
33
+ // macOS refuses an unsigned bundle outright; ad-hoc is enough for a build nobody downloads.
34
+ APPLE_SIGNING_IDENTITY: "-",
35
+ });
36
+ }
@@ -0,0 +1,80 @@
1
+ import { existsSync } from "node:fs";
2
+ import { cp, rename, rm } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import { $ } from "bun";
5
+
6
+ /** A client-rendered web app and a Nitro API packed into one Vercel deployment. */
7
+ export interface WebBuildOptions {
8
+ /** Web app dir, run with `bun run build` (default `apps/frontend`). */
9
+ frontendDir?: string;
10
+ /** Nitro dir, built with `bunx nitro build --preset vercel` (default `apps/backend`). */
11
+ backendDir?: string;
12
+ /** Where the web build lands inside `frontendDir` (default `build`). */
13
+ webBuildDir?: string;
14
+ /** Path prefixes the API owns; everything else answers with the app shell. */
15
+ apiPrefixes: string[];
16
+ /** Extra staged directories to serve, as `{ "<source dir>": "<path under the site>" }`. */
17
+ include?: Record<string, string>;
18
+ }
19
+
20
+ /**
21
+ * Build a client-rendered web app and a Nitro API into a single Vercel deployment: the app as
22
+ * static files, the API as the one serverless function behind them. Both end up at the same
23
+ * origin, so the web client calls the API without CORS and there is one URL to remember.
24
+ */
25
+ export async function buildWeb(options: WebBuildOptions) {
26
+ const root = process.cwd();
27
+ const frontend = resolve(root, options.frontendDir ?? "apps/frontend");
28
+ const backend = resolve(root, options.backendDir ?? "apps/backend");
29
+ const webDir = join(backend, "public");
30
+ const nitroOutput = join(backend, ".vercel/output");
31
+ const finalOutput = join(root, ".vercel/output");
32
+
33
+ await $`bun run build`.cwd(frontend);
34
+ await rm(webDir, { recursive: true, force: true });
35
+ await cp(join(frontend, options.webBuildDir ?? "build"), webDir, { recursive: true });
36
+
37
+ // Anything a sibling platform staged for the site to hand out — an installer, say — rides along
38
+ // with the web files rather than living in the frontend's static folder, which other builds
39
+ // copy wholesale.
40
+ for (const [from, to] of Object.entries(options.include ?? {})) {
41
+ const staged = resolve(root, from);
42
+ if (!existsSync(staged)) {
43
+ console.log(`Nothing staged at ${from} — the site will serve no ${to}`);
44
+ continue;
45
+ }
46
+ await cp(staged, join(webDir, to), { recursive: true });
47
+ console.log(`Serving ${from} at /${to}`);
48
+ }
49
+
50
+ await rm(nitroOutput, { recursive: true, force: true });
51
+ await $`bunx nitro build --preset vercel`.cwd(backend);
52
+
53
+ await rm(finalOutput, { recursive: true, force: true });
54
+ await rename(nitroOutput, finalOutput);
55
+
56
+ await routeUnmatchedPathsToTheApp(finalOutput, options.apiPrefixes ?? []);
57
+ }
58
+
59
+ /**
60
+ * The app is one client-rendered bundle, so every path it owns has to answer with `index.html`
61
+ * and let the router sort it out. Nitro ends its routes with a catch-all into the function, which
62
+ * would otherwise answer an unknown web path with an API-shaped 404 JSON body.
63
+ */
64
+ async function routeUnmatchedPathsToTheApp(output: string, apiPrefixes: readonly string[]) {
65
+ if (!apiPrefixes.length) throw new Error('"apiPrefixes" must list the paths the API owns');
66
+
67
+ const configPath = join(output, "config.json");
68
+ const config = await Bun.file(configPath).json();
69
+ const staticDir = join(output, "static");
70
+ if (!existsSync(staticDir)) throw new Error(`No static output at ${staticDir} — did the web build land?`);
71
+
72
+ const catchAll = config.routes.findIndex((route: { dest?: string }) => route.dest === "/__fallback");
73
+ config.routes.splice(catchAll < 0 ? config.routes.length : catchAll, 0, {
74
+ src: `/((?!${apiPrefixes.join("|")}).*)`,
75
+ dest: "/index.html",
76
+ });
77
+
78
+ await Bun.write(configPath, JSON.stringify(config, null, 2));
79
+ console.log("Unmatched web paths route to the app shell");
80
+ }
@@ -0,0 +1,9 @@
1
+ import { type XcodeBuild, xcodeBuild } from "../apple.ts";
2
+
3
+ /**
4
+ * Compiles one Xcode scheme for a simulator — a watch app, a widget, anything native that carries
5
+ * no web bundle of its own and so needs nothing built before it.
6
+ */
7
+ export async function buildXcode(options: XcodeBuild) {
8
+ await xcodeBuild(options);
9
+ }
package/src/build.ts CHANGED
@@ -1,75 +1,8 @@
1
- import { existsSync } from "node:fs";
2
- import { cp, rename, rm } from "node:fs/promises";
3
- import { join, resolve } from "node:path";
4
- import { $ } from "bun";
5
1
  import { loadConfig } from "./config.ts";
2
+ import { type GraphOptions, runGraph } from "./graph.ts";
6
3
 
7
- /**
8
- * Build a client-rendered web app and a Nitro API into a single Vercel deployment: the app as
9
- * static files, the API as the one serverless function behind them. Both end up at the same
10
- * origin, so the web client calls the API without CORS and there is one URL to remember.
11
- */
12
- export async function runBuild() {
13
- const { build } = loadConfig();
14
- if (!build) throw new Error('No "devkit.build" config in package.json');
15
-
16
- const root = process.cwd();
17
- const frontend = resolve(root, build.frontendDir ?? "apps/frontend");
18
- const backend = resolve(root, build.backendDir ?? "apps/backend");
19
- const webDir = join(backend, "public");
20
- const nitroOutput = join(backend, ".vercel/output");
21
- const finalOutput = join(root, ".vercel/output");
22
-
23
- // The typed client is generated from the route handlers, so it has to exist before the app
24
- // compiles — unless a release already did it, in which case regenerating it now would be writing
25
- // to files a build running alongside is reading.
26
- if (build.clientCommand && !process.env.SKIP_CLIENT_GEN) await $`sh -c ${build.clientCommand}`.cwd(backend);
27
-
28
- await $`bun run build`.cwd(frontend);
29
- await rm(webDir, { recursive: true, force: true });
30
- await cp(join(frontend, build.webBuildDir ?? "build"), webDir, { recursive: true });
31
-
32
- // Anything a sibling target staged for the site to hand out — an installer, say — rides along
33
- // with the web files rather than living in the frontend's static folder, which other builds
34
- // copy wholesale.
35
- for (const [from, to] of Object.entries(build.include ?? {})) {
36
- const staged = resolve(root, from);
37
- if (!existsSync(staged)) {
38
- console.log(`Nothing staged at ${from} — the site will serve no ${to}`);
39
- continue;
40
- }
41
- await cp(staged, join(webDir, to), { recursive: true });
42
- console.log(`Serving ${from} at /${to}`);
43
- }
44
-
45
- await rm(nitroOutput, { recursive: true, force: true });
46
- await $`bunx nitro build --preset vercel`.cwd(backend);
47
-
48
- await rm(finalOutput, { recursive: true, force: true });
49
- await rename(nitroOutput, finalOutput);
50
-
51
- await routeUnmatchedPathsToTheApp(finalOutput, build.apiPrefixes ?? []);
52
- }
53
-
54
- /**
55
- * The app is one client-rendered bundle, so every path it owns has to answer with `index.html`
56
- * and let the router sort it out. Nitro ends its routes with a catch-all into the function, which
57
- * would otherwise answer an unknown web path with an API-shaped 404 JSON body.
58
- */
59
- async function routeUnmatchedPathsToTheApp(output: string, apiPrefixes: readonly string[]) {
60
- if (!apiPrefixes.length) throw new Error('"devkit.build.apiPrefixes" must list the paths the API owns');
61
-
62
- const configPath = join(output, "config.json");
63
- const config = await Bun.file(configPath).json();
64
- const staticDir = join(output, "static");
65
- if (!existsSync(staticDir)) throw new Error(`No static output at ${staticDir} — did the web build land?`);
66
-
67
- const catchAll = config.routes.findIndex((route: { dest?: string }) => route.dest === "/__fallback");
68
- config.routes.splice(catchAll < 0 ? config.routes.length : catchAll, 0, {
69
- src: `/((?!${apiPrefixes.join("|")}).*)`,
70
- dest: "/index.html",
71
- });
72
-
73
- await Bun.write(configPath, JSON.stringify(config, null, 2));
74
- console.log("Unmatched web paths route to the app shell");
4
+ /** Build every configured platform at once, or only the ones named. */
5
+ export async function runBuild(only: string[], options: GraphOptions = {}) {
6
+ const { build, generate } = loadConfig();
7
+ await runGraph("build", build, only, generate, options);
75
8
  }
package/src/config.ts CHANGED
@@ -1,24 +1,61 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { resolve } from "node:path";
3
3
 
4
- /** One dev process, keyed by its name. Resolved into a shell command by {@link commandFor}. */
5
- export interface DevApp {
6
- /** Explicit `bun --filter <target>` (defaults to the name). */
4
+ /**
5
+ * The three things a repo does with its platforms, and the three commands that do them.
6
+ *
7
+ * Every phase is the same shape — a map of platform name to one step — so `devkit build` and
8
+ * `devkit build:mac` are the same command with a different selection, and a platform is named
9
+ * once and means the same thing everywhere.
10
+ */
11
+ export type Phase = "dev" | "build" | "deploy";
12
+
13
+ export const PHASES: readonly Phase[] = ["dev", "build", "deploy"];
14
+
15
+ /** One step of a phase: a shell command, or a built-in target named by `type`. */
16
+ export interface Step {
17
+ /** Shell command that performs this step. Omit when `type` names a built-in target instead. */
18
+ command?: string;
19
+ /** A built-in target — see `src/<phase>-targets/`. `options` is that target's own config. */
20
+ type?: string;
21
+ // biome-ignore lint/suspicious/noExplicitAny: each `type` has its own options shape
22
+ options?: any;
23
+ /** Platforms that must run first — built before this one, or already up in the dev case. */
24
+ needs?: string[];
25
+ /** Colour for this step's line on the board. */
26
+ color?: string;
27
+ }
28
+
29
+ /** One long-running dev process. Resolved into a shell command by `commandFor` in `dev.ts`. */
30
+ export interface DevProcess extends Step {
31
+ /** Explicit `bun --filter <target>` (defaults to the process name). */
7
32
  filter?: string;
8
- /** Run via `bun --cwd <cwd> run <script>` instead of `--filter`. */
33
+ /** Run via `bun run --cwd <cwd> <script>` instead of `--filter`. */
9
34
  cwd?: string;
10
35
  /** Script to run in the workspace (default `dev`). */
11
36
  script?: string;
12
- /** Raw shell command; overrides filter/cwd/script (e.g. `vite dev`). */
13
- command?: string;
14
37
  /** Port to free on start and show in the URL banner. */
15
38
  port?: number;
16
- /** Prefix color for this process's output. */
17
- color?: string;
18
- /** With `--open`, open this app's URL once its port is live. */
39
+ /** With `--open`, open this process's URL once its port is live. */
19
40
  open?: boolean;
20
41
  }
21
42
 
43
+ /**
44
+ * One platform's dev setup: either a single process, or several under `processes` — a web
45
+ * platform is a client and an API, and neither is worth naming as a platform of its own.
46
+ */
47
+ export interface DevPlatform extends DevProcess {
48
+ processes?: Record<string, DevProcess>;
49
+ }
50
+
51
+ /** A command run once before a build or deploy graph, ahead of everything running in parallel. */
52
+ export interface GenerateConfig {
53
+ /** Shell command to run (e.g. `bunx nitro-client`). */
54
+ command: string;
55
+ /** Directory to run it in, relative to the root (default `.`). */
56
+ cwd?: string;
57
+ }
58
+
22
59
  /** A gitignored env file that must be carried to a new machine, and the template listing its keys. */
23
60
  export interface EnvFile {
24
61
  /** Path to the env file, relative to the root (default `.env`). */
@@ -51,60 +88,6 @@ export interface SetupConfig {
51
88
  steps?: string[];
52
89
  }
53
90
 
54
- /**
55
- * One deploy step. Targets with no `needs` all start at once; a target with `needs` waits for
56
- * those, which is what lets a build that another one packages up run first without serialising
57
- * the whole release.
58
- */
59
- export interface DeployTarget {
60
- /** Shell command that performs this deploy. Omit when `type` names a built-in target instead. */
61
- command?: string;
62
- /** A built-in deploy target — see `src/deploy-targets/`. `options` is that target's own config. */
63
- type?: "vercel" | "tauri-macos" | "fastlane-ios";
64
- // biome-ignore lint/suspicious/noExplicitAny: each `type` has its own options shape
65
- options?: any;
66
- /** Targets that must finish first. */
67
- needs?: string[];
68
- /** Colour for this target's line on the board. */
69
- color?: string;
70
- }
71
-
72
- /**
73
- * `devkit build`: a client-rendered web app and a Nitro API packed into one Vercel deployment.
74
- */
75
- export interface BuildConfig {
76
- /** Web app dir, run with `bun run build` (default `apps/frontend`). */
77
- frontendDir?: string;
78
- /** Nitro dir, built with `bunx nitro build --preset vercel` (default `apps/backend`). */
79
- backendDir?: string;
80
- /** Where the web build lands inside `frontendDir` (default `build`). */
81
- webBuildDir?: string;
82
- /** Path prefixes the API owns; everything else answers with the app shell. */
83
- apiPrefixes: string[];
84
- /** Run in `backendDir` before the web build, unless `SKIP_CLIENT_GEN` is set (e.g. `bunx nitro-client`). */
85
- clientCommand?: string;
86
- /** Extra staged directories to serve, as `{ "<source dir>": "<path under the site>" }`. */
87
- include?: Record<string, string>;
88
- }
89
-
90
- /** `devkit sim`: an Apple app built and launched on a simulator, without opening Xcode. */
91
- export interface SimConfig {
92
- /** Path to the `.xcodeproj`. */
93
- project: string;
94
- /** Scheme to build; also the name of the built `.app`. */
95
- scheme: string;
96
- /** Bundle id to install and launch. */
97
- bundleId: string;
98
- /** Simulator to run on — overridable with `--device` or `DEVKIT_SIM_DEVICE`. */
99
- device: string;
100
- /** Simulator SDK the products are built for (default `watchsimulator`). */
101
- sdk?: string;
102
- /** Derived data dir (default `build/sim`). */
103
- derivedDataDir?: string;
104
- /** Env var the app reads to show sample data; set unless `--real` is passed. */
105
- previewEnv?: string;
106
- }
107
-
108
91
  /** `devkit version`: one version, declared once and written everywhere else it appears. */
109
92
  export interface VersionConfig {
110
93
  /** JSON file whose `version` field is the number the rest follow. */
@@ -121,13 +104,13 @@ export interface VersionConfig {
121
104
  plists?: string[];
122
105
  }
123
106
 
124
- /** Apps and deploy targets are written as name-keyed maps, so a name is never repeated or missing. */
107
+ /** Phases are name-keyed maps, so a platform is never repeated or missing a name. */
125
108
  export interface DevkitConfig {
126
- apps?: Record<string, DevApp>;
109
+ dev?: Record<string, DevPlatform>;
110
+ build?: Record<string, Step>;
111
+ deploy?: Record<string, Step>;
112
+ generate?: GenerateConfig;
127
113
  setup?: SetupConfig;
128
- deploy?: Record<string, DeployTarget>;
129
- build?: BuildConfig;
130
- sim?: SimConfig;
131
114
  version?: VersionConfig;
132
115
  }
133
116
 
@@ -136,11 +119,11 @@ export type Named<T> = T & { readonly name: string };
136
119
 
137
120
  /** What the commands read: the same config, with each map flattened into named entries. */
138
121
  export interface LoadedConfig {
139
- apps: Named<DevApp>[];
122
+ dev: Named<DevPlatform>[];
123
+ build: Named<Step>[];
124
+ deploy: Named<Step>[];
125
+ generate?: GenerateConfig;
140
126
  setup?: SetupConfig;
141
- deploy: Named<DeployTarget>[];
142
- build?: BuildConfig;
143
- sim?: SimConfig;
144
127
  version?: VersionConfig;
145
128
  }
146
129
 
@@ -149,22 +132,56 @@ export function loadConfig(dir: string = process.cwd()): LoadedConfig {
149
132
  const pkgPath = resolve(dir, "package.json");
150
133
  const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as { devkit?: DevkitConfig };
151
134
  const cfg = pkg.devkit;
152
- // `devkit deploy` is useful in a repo that runs nothing locally, so only the dev command
153
- // insists on apps.
135
+ // `devkit deploy` is useful in a repo that runs nothing locally, so no phase is required here —
136
+ // each command says what it needs when it finds nothing to run.
154
137
  if (!cfg) throw new Error(`No "devkit" config found in ${pkgPath}`);
155
138
  return {
156
- apps: named(cfg.apps, "apps", pkgPath),
157
- setup: cfg.setup,
139
+ dev: named(cfg.dev, "dev", pkgPath),
140
+ build: named(cfg.build, "build", pkgPath),
158
141
  deploy: named(cfg.deploy, "deploy", pkgPath),
159
- build: cfg.build,
160
- sim: cfg.sim,
142
+ generate: cfg.generate,
143
+ setup: cfg.setup,
161
144
  version: cfg.version,
162
145
  };
163
146
  }
164
147
 
148
+ /** The entries of one phase, in config order. */
149
+ export function phaseOf(config: LoadedConfig, phase: Phase): Named<Step>[] {
150
+ return phase === "dev" ? config.dev : phase === "build" ? config.build : config.deploy;
151
+ }
152
+
165
153
  function named<T>(map: Record<string, T> | undefined, key: string, pkgPath: string): Named<T>[] {
166
154
  if (map === undefined) return [];
167
155
  if (Array.isArray(map))
168
156
  throw new Error(`"devkit.${key}" in ${pkgPath} is a list — it is now a map of name to settings`);
169
157
  return Object.entries(map).map(([name, entry]) => ({ ...entry, name }));
170
158
  }
159
+
160
+ /**
161
+ * The platforms asked for, plus whatever they depend on — a step can't run without its needs,
162
+ * and a dev process can't be developed against a stack that isn't up.
163
+ */
164
+ export function withNeeds<T extends Step>(entries: Named<T>[], only: string[]): Named<T>[] {
165
+ if (!only.length) return entries;
166
+ const unknown = only.filter((name) => !entries.some((entry) => entry.name === name));
167
+ if (unknown.length) {
168
+ const known = entries.map((entry) => entry.name).join(", ") || "none configured";
169
+ throw new Error(`Unknown platform${unknown.length > 1 ? "s" : ""}: ${unknown.join(", ")} (have: ${known})`);
170
+ }
171
+
172
+ const wanted = new Set(only);
173
+ let grew = true;
174
+ while (grew) {
175
+ grew = false;
176
+ for (const entry of entries) {
177
+ if (!wanted.has(entry.name)) continue;
178
+ for (const need of entry.needs ?? []) {
179
+ if (!wanted.has(need)) {
180
+ wanted.add(need);
181
+ grew = true;
182
+ }
183
+ }
184
+ }
185
+ }
186
+ return entries.filter((entry) => wanted.has(entry.name));
187
+ }
@@ -2,12 +2,11 @@ import { existsSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { $ } from "bun";
5
+ import { isolatedWebEnv } from "../web-build.ts";
5
6
 
6
7
  export interface FastlaneIosTargetOptions {
7
8
  /** Capacitor/frontend dir (default `apps/frontend`). */
8
9
  frontendDir?: string;
9
- /** Backend dir to generate a typed API client from before building, if any. */
10
- backendDir?: string;
11
10
  /** iOS project dir (default `<frontendDir>/ios`). */
12
11
  iosDir?: string;
13
12
  /** Fastlane lane to run (default `beta`). */
@@ -56,21 +55,10 @@ export async function deployFastlaneIos(options: FastlaneIosTargetOptions) {
56
55
  };
57
56
  if (!existsSync(keyPath)) throw new Error(`No App Store Connect key at ${keyPath}`);
58
57
 
59
- // Same order as a web deploy: the typed client is generated from the routes the app compiles
60
- // against. A `deploy` running every target generates it once up front, because two builds
61
- // writing those files at the same time is the one thing running in parallel can't survive.
62
- if (options.backendDir && !process.env.SKIP_CLIENT_GEN) await $`bunx nitro-client`.cwd(options.backendDir);
63
-
64
58
  // The web build a release ships to Vercel is happening in the next directory over, against the
65
59
  // same sources — this one gets its own output, cache and Capacitor web root so neither sees half
66
60
  // of the other's build.
67
- const buildEnv = {
68
- ...process.env,
69
- VITE_API_BASE_URL: apiBaseUrl,
70
- BUILD_DIR: "build-ios",
71
- KIT_DIR: ".svelte-kit-ios",
72
- VITE_CACHE_DIR: "node_modules/.vite-ios",
73
- };
61
+ const buildEnv = { ...process.env, VITE_API_BASE_URL: apiBaseUrl, ...isolatedWebEnv("ios") };
74
62
  await $`bun run build`.cwd(frontendDir).env(buildEnv);
75
63
  await $`bunx cap sync ios`.cwd(frontendDir).env(buildEnv);
76
64