@powerhousedao/desktop 0.0.0-stage → 6.2.3-dev.101

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,1570 @@
1
+ import { createRequire } from "node:module";
2
+ import { colorVariants, imageVariants, layerStyleText, normalizeBackground, validateBackground } from "@powerhousedao/shared/connect";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { z } from "zod";
6
+ import { execSync, spawn, spawnSync } from "node:child_process";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
+ import { normalizePluginEntries } from "@powerhousedao/host-core";
9
+ import { isPassthroughImageRef } from "@powerhousedao/shared/connect/image-ref";
10
+ //#region src/app-json.ts
11
+ /**
12
+ * `hosts/desktop/app.json` — the builder's desktop identity (phase 7, mode 1:
13
+ * the builder ships under THEIR identity without writing Rust). It is the ONE
14
+ * file a builder edits; `shell-project.ts` projects it into a generated
15
+ * `tauri-shell/` that depends on the published `ph-desktop-shell` crate. Every
16
+ * field validates strictly so a typo fails with the field named, not silently.
17
+ */
18
+ const identifierSchema = z.string().min(1).regex(/^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/, "identifier must be reverse-DNS (e.g. com.acme.app): dot-separated alphanumeric segments");
19
+ const windowSchema = z.strictObject({
20
+ title: z.string().min(1).optional(),
21
+ width: z.number().int().positive().optional(),
22
+ height: z.number().int().positive().optional(),
23
+ resizable: z.boolean().optional(),
24
+ /** Smallest size the window can be dragged to (logical pixels). */
25
+ minWidth: z.number().int().positive().optional(),
26
+ minHeight: z.number().int().positive().optional()
27
+ }).optional();
28
+ const cssColorSchema = z.string().regex(/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/, "use a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa)");
29
+ /** The loading page's colors. */
30
+ const loadingColorsSchema = z.strictObject({
31
+ /** Page background (default #0f1115). */
32
+ background: cssColorSchema.nullable().optional(),
33
+ /** Status text color (default #e6e8eb). */
34
+ color: cssColorSchema.nullable().optional(),
35
+ /** The pulsing status dot (default #4ade80). */
36
+ accent: cssColorSchema.nullable().optional()
37
+ });
38
+ /** The loading page's look, so the window opens in the app's own colors
39
+ * instead of the default dark page. Every field is optional, and `null`
40
+ * means the default (the scaffold lists the fields that way). */
41
+ const loadingSchema = loadingColorsSchema.extend({
42
+ /** Status line under the art (default "Starting <productName>…"). */
43
+ message: z.string().min(1).nullable().optional(),
44
+ /** Colors for `prefers-color-scheme: dark`; without it the page keeps
45
+ * the light colors in both schemes. */
46
+ dark: loadingColorsSchema.nullable().optional(),
47
+ /** Deprecated: a decoration pinned to the bottom-right corner, relative
48
+ * to app.json, with `artDark` its dark-scheme counterpart. Superseded by
49
+ * the top-level `background`, which ignores these when set. */
50
+ art: z.string().min(1).nullable().optional(),
51
+ artDark: z.string().min(1).nullable().optional()
52
+ }).nullable().optional();
53
+ const imageRefSchema = z.string().min(1);
54
+ const schemedImageSchema = z.union([imageRefSchema, z.strictObject({
55
+ light: imageRefSchema,
56
+ dark: imageRefSchema.nullable().optional()
57
+ })]);
58
+ const lengthSchema = z.union([z.number(), z.string().min(1)]).nullable().optional();
59
+ const edgesSchema = z.strictObject({
60
+ top: lengthSchema,
61
+ right: lengthSchema,
62
+ bottom: lengthSchema,
63
+ left: lengthSchema
64
+ }).nullable().optional();
65
+ const backgroundLayerSchema = z.strictObject({
66
+ src: schemedImageSchema,
67
+ position: edgesSchema,
68
+ width: lengthSchema,
69
+ height: lengthSchema,
70
+ minWidth: lengthSchema,
71
+ minHeight: lengthSchema,
72
+ maxWidth: lengthSchema,
73
+ maxHeight: lengthSchema,
74
+ opacity: z.number().min(0).max(1).nullable().optional(),
75
+ fade: edgesSchema
76
+ });
77
+ const backgroundSchema = z.union([imageRefSchema, z.strictObject({
78
+ color: z.union([z.string().min(1), z.strictObject({
79
+ light: z.string().min(1),
80
+ dark: z.string().min(1).nullable().optional()
81
+ })]).nullable().optional(),
82
+ layers: z.array(backgroundLayerSchema)
83
+ })]).superRefine((background, ctx) => {
84
+ for (const problem of validateBackground(background, "background")) ctx.addIssue({
85
+ code: "custom",
86
+ message: problem
87
+ });
88
+ }).nullable().optional();
89
+ const fileAssociationSchema = z.strictObject({
90
+ /** Extensions WITHOUT the leading dot ("phd", not ".phd"). */
91
+ ext: z.array(z.string().min(1).regex(/^[^.]/, "drop the leading dot")).min(1),
92
+ name: z.string().min(1),
93
+ description: z.string().optional(),
94
+ mimeType: z.string().optional()
95
+ });
96
+ /** Where the generated Cargo.toml resolves `ph-desktop-shell` from. Default
97
+ * (omitted) = the published crates.io version. */
98
+ const shellSourceSchema = z.strictObject({
99
+ /** Local checkout for shell development (the lab points here). */
100
+ path: z.string().min(1).optional(),
101
+ /** Git source, pinned to a tag/rev, for pre-publication consumption. */
102
+ git: z.string().min(1).optional(),
103
+ tag: z.string().min(1).optional(),
104
+ rev: z.string().min(1).optional(),
105
+ /** crates.io version requirement (default DEFAULT_SHELL_CRATE_VERSION). */
106
+ version: z.string().min(1).optional()
107
+ }).refine((s) => !(s.path && s.git), { message: "shell.source: set path OR git, not both" }).optional();
108
+ const appJsonSchema = z.strictObject({
109
+ identifier: identifierSchema,
110
+ productName: z.string().min(1),
111
+ /** Ask who is using the app before anything runs: the stack then starts for
112
+ * that identity, with its own folder and as its admin. Off, the stack starts
113
+ * with the window, in one store. */
114
+ signIn: z.boolean().nullable().optional(),
115
+ /** Single source image (square PNG, 1024×1024 recommended); the icon set
116
+ * for every platform is generated from it via `tauri icon`. */
117
+ icon: z.string().min(1),
118
+ /** The loading page's background: images positioned and sized over a
119
+ * page colour (`{ color, layers }`), or one image pinned bottom-right.
120
+ * The status line stays centred above them. `ph generate desktop-shell`
121
+ * copies Connect's `connect.branding.homeBackground` here. null or
122
+ * omitted: the app icon (or `splash`) above the status line. */
123
+ background: backgroundSchema,
124
+ /** Deprecated in favour of `background`: a wide splash image shown above
125
+ * the status line instead of the square icon. Relative to this file. */
126
+ splash: z.string().min(1).nullable().optional(),
127
+ /** Deprecated with `splash`: its `prefers-color-scheme: dark` variant. */
128
+ splashDark: z.string().min(1).nullable().optional(),
129
+ loading: loadingSchema,
130
+ window: windowSchema,
131
+ fileAssociations: z.array(fileAssociationSchema).optional(),
132
+ shell: shellSourceSchema
133
+ });
134
+ /** Default crates.io version requirement for the shell crate (D7.b: the flip
135
+ * to crates.io default once published — the crate is live). A floor, not just
136
+ * a series: 0.1.0 can't run a stack from ph-run, and a Cargo.lock that still
137
+ * holds it satisfies "0.1", so a builder's lock would keep it forever. The
138
+ * 0.1.0-dev.N releases sort below 0.1.0 and never match either. */
139
+ const DEFAULT_SHELL_CRATE_VERSION = "0.1.1";
140
+ const APP_JSON_FILE = "app.json";
141
+ /** Read + validate hosts/<host>/app.json. Throws with the field named on a
142
+ * bad value, and a clear message when the file is absent. */
143
+ function loadAppJson(hostDir) {
144
+ const file = path.join(hostDir, APP_JSON_FILE);
145
+ if (!fs.existsSync(file)) throw new Error(`No ${APP_JSON_FILE} in ${hostDir} — run \`ph generate desktop-shell\` to scaffold the builder identity, or set runner.shell.project to a prebuilt shell.`);
146
+ let raw;
147
+ try {
148
+ raw = JSON.parse(fs.readFileSync(file, "utf8"));
149
+ } catch (error) {
150
+ throw new Error(`${file}: not valid JSON — ${String(error)}`, { cause: error });
151
+ }
152
+ const result = appJsonSchema.safeParse(raw);
153
+ if (!result.success) {
154
+ const issues = result.error.issues.map((i) => ` ${i.path.join(".") || "(root)"}: ${i.message}`).join("\n");
155
+ throw new Error(`${file} is invalid:\n${issues}`);
156
+ }
157
+ return result.data;
158
+ }
159
+ /** A filesystem/crate-safe slug of the product name — the generated binary
160
+ * and Cargo package name. Falls back to the identifier's last segment. */
161
+ function appSlug(app) {
162
+ const fromName = app.productName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
163
+ if (fromName) return fromName;
164
+ return (app.identifier.split(".").pop() ?? "app").toLowerCase().replace(/[^a-z0-9]+/g, "-");
165
+ }
166
+ //#endregion
167
+ //#region src/bundle-stack.ts
168
+ /**
169
+ * P6.3 — stage the shippable STACK into the shell project: everything the
170
+ * installed app needs to run `ph run desktop` with no environment at all
171
+ * (D6.c). The shell's resources map `../dist-stack` → `stack`, and its
172
+ * uniform-runners mode falls back to `resources/stack` when the env pair is
173
+ * absent. Layout:
174
+ *
175
+ * dist-stack/
176
+ * hosts/ the project's host files
177
+ * agents/ when present
178
+ * powerhouse.config.json
179
+ * package.json minimal, names the project
180
+ * dist/ the package's build (ph build)
181
+ * .ph/connect-build/dist/ the BUILT Connect (ph run connect build)
182
+ * node_modules/ vendored @powerhousedao/ph-run (hoisted,
183
+ * real files — computed-specifier imports and
184
+ * PGlite wasm forbid bundling)
185
+ */
186
+ const CONNECT_BUILD_DIR = path.join(".ph", "connect-build", "dist");
187
+ const BROWSER_ONLY_IN_DIST = [
188
+ "__react__",
189
+ "__reactor_worker__",
190
+ "__vendor__",
191
+ "assets",
192
+ "browser"
193
+ ];
194
+ /** The package a module specifier belongs to. */
195
+ function packageOf$1(specifier) {
196
+ return specifier.split("/").slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
197
+ }
198
+ /** The packages to ship for a host's plugins. One that doesn't resolve is a
199
+ * browser built-in of Connect's, already in the built app, and resolves no
200
+ * better in the stack (host-core's plugins-resolve). */
201
+ function pluginPackagesOf(entries, where, resolves) {
202
+ return normalizePluginEntries(entries, where).filter((entry) => entry.enabled && !entry.module.startsWith(".")).filter((entry) => resolves(entry.module)).map((entry) => packageOf$1(entry.module));
203
+ }
204
+ /** Where a stack keeps the OAuth clients its config names. */
205
+ const OAUTH_CLIENTS_DIR = "oauth";
206
+ /** Where a stack keeps the AI demo key its config names. */
207
+ const AI_DIR = "ai";
208
+ /**
209
+ * The project's config, with its OAuth clients made the app's own. They sit
210
+ * outside the project, so a packaged app would find nothing at those paths. A
211
+ * desktop client ships with the app: it can't keep its secret, so sign-ins
212
+ * always use PKCE. A web client belongs to a server and never leaves the machine.
213
+ */
214
+ function stageConfig(projectRoot, stackDir, log) {
215
+ const source = path.join(projectRoot, "powerhouse.config.json");
216
+ if (!fs.existsSync(source)) return;
217
+ const config = JSON.parse(fs.readFileSync(source, "utf8"));
218
+ if (config.ai?.demoKeyFile) {
219
+ const from = path.resolve(projectRoot, config.ai.demoKeyFile);
220
+ delete config.ai.demoKeyFile;
221
+ if (fs.existsSync(from)) {
222
+ const file = path.basename(from);
223
+ fs.mkdirSync(path.join(stackDir, AI_DIR), { recursive: true });
224
+ fs.copyFileSync(from, path.join(stackDir, AI_DIR, file));
225
+ config.ai.demoKeyFile = `./${AI_DIR}/${file}`;
226
+ log(" AI demo key staged");
227
+ } else log(" no AI demo key: this build won't offer one");
228
+ }
229
+ for (const app of config.workflows?.oauthApps ?? []) {
230
+ if (!app.clients) continue;
231
+ const desktop = app.clients.desktop;
232
+ const from = desktop && path.resolve(projectRoot, desktop);
233
+ app.clients = {};
234
+ if (!from || !fs.existsSync(from)) {
235
+ log(` oauth app ${app.id}: no desktop client, so it can't sign in`);
236
+ continue;
237
+ }
238
+ const file = path.basename(from);
239
+ fs.mkdirSync(path.join(stackDir, OAUTH_CLIENTS_DIR), { recursive: true });
240
+ fs.copyFileSync(from, path.join(stackDir, OAUTH_CLIENTS_DIR, file));
241
+ app.clients.desktop = `./${OAUTH_CLIENTS_DIR}/${file}`;
242
+ log(` oauth app ${app.id}: desktop client staged`);
243
+ }
244
+ fs.writeFileSync(path.join(stackDir, "powerhouse.config.json"), `${JSON.stringify(config, null, 2)}
245
+ `);
246
+ }
247
+ /** What runs a stack: `ph run` without the tools that build one, which is
248
+ * most of ph-cli's dependencies. */
249
+ const RUN_PACKAGE = "@powerhousedao/ph-run";
250
+ function copyIfExists(from, to) {
251
+ if (!fs.existsSync(from)) return false;
252
+ fs.cpSync(from, to, { recursive: true });
253
+ return true;
254
+ }
255
+ /** The version of a package the project has installed, if it has. */
256
+ function installedVersion(projectRoot, pkg) {
257
+ try {
258
+ return JSON.parse(fs.readFileSync(path.join(projectRoot, "node_modules", pkg, "package.json"), "utf8")).version;
259
+ } catch {
260
+ return;
261
+ }
262
+ }
263
+ /** The ph-run a stack runs: what the project was built and tested with, not
264
+ * whatever a tag points at when the build runs. It comes with ph-cli, at its
265
+ * version. */
266
+ function runVersion(options) {
267
+ return options.phCliVersion ?? installedVersion(options.projectRoot, "@powerhousedao/ph-cli") ?? "dev";
268
+ }
269
+ /** What a registry vendoring installs. host-core rides along with ph-run, as
270
+ * host files resolve runner modules (the generic compound) from the stack's
271
+ * own node_modules. Each package comes at the version the project has, and a
272
+ * version the host names is used for all of them. */
273
+ function registrySpecs(options) {
274
+ const version = runVersion(options);
275
+ const versionOf = (pkg) => options.phCliVersion ?? installedVersion(options.projectRoot, pkg) ?? version;
276
+ return [options.phCliSpec ?? `${RUN_PACKAGE}@${version}`, ...["@powerhousedao/host-core", ...options.plugins ?? []].map((pkg) => `${pkg}@${versionOf(pkg)}`)];
277
+ }
278
+ /** Stages each project file that exists, at its project path. One outside
279
+ * the project has no place in the stack. */
280
+ function stageProjectFiles(projectRoot, stackDir, files) {
281
+ let staged = 0;
282
+ for (const file of new Set(files)) {
283
+ const from = path.resolve(projectRoot, file);
284
+ const relative = path.relative(projectRoot, from);
285
+ if (relative.startsWith("..") || path.isAbsolute(relative)) continue;
286
+ if (!fs.statSync(from, { throwIfNoEntry: false })?.isFile()) continue;
287
+ const to = path.join(stackDir, relative);
288
+ fs.mkdirSync(path.dirname(to), { recursive: true });
289
+ fs.copyFileSync(from, to);
290
+ staged++;
291
+ }
292
+ return staged;
293
+ }
294
+ /**
295
+ * Recursively copy `src` → `dest`, skipping any path in `excludes`. Unlike
296
+ * fs.cpSync this tolerates `dest` living INSIDE `src`: in mode 1 the generated
297
+ * shell (and its `dist-stack`) sits under `hosts/<desktop>/`, so staging the
298
+ * project's `hosts/` straight into the shell would be a copy-into-self that
299
+ * cpSync rejects outright. Excluding the shell subtree both avoids that and
300
+ * keeps the crate + node sidecar out of the shippable stack.
301
+ */
302
+ function copyDirFiltered(src, dest, excludes) {
303
+ if (!fs.existsSync(src)) return false;
304
+ const skip = new Set(excludes.map((e) => path.resolve(e)));
305
+ const walk = (s, d) => {
306
+ if (skip.has(path.resolve(s))) return;
307
+ if (fs.statSync(s).isDirectory()) {
308
+ fs.mkdirSync(d, { recursive: true });
309
+ for (const entry of fs.readdirSync(s)) walk(path.join(s, entry), path.join(d, entry));
310
+ } else fs.copyFileSync(s, d);
311
+ };
312
+ walk(src, dest);
313
+ return true;
314
+ }
315
+ /** The npm spec of each tarball in `dir`, by the package name inside it. */
316
+ function readLocalPackages(dir) {
317
+ const root = path.resolve(dir);
318
+ const tarballs = fs.existsSync(root) ? fs.readdirSync(root).filter((f) => f.endsWith(".tgz")) : [];
319
+ if (tarballs.length === 0) throw new Error(`bundle-stack: no package tarballs (*.tgz) in ${root}`);
320
+ const specs = {};
321
+ for (const file of tarballs.sort()) {
322
+ const tarball = path.join(root, file);
323
+ const manifest = spawnSync("tar", [
324
+ "-xzOf",
325
+ file,
326
+ "package/package.json"
327
+ ], {
328
+ cwd: root,
329
+ encoding: "utf8",
330
+ windowsHide: true
331
+ });
332
+ if (manifest.status !== 0) throw new Error(`bundle-stack: ${tarball} has no package/package.json: ${manifest.stderr}`);
333
+ const { name } = JSON.parse(manifest.stdout);
334
+ if (specs[name]) throw new Error(`bundle-stack: two tarballs for ${name} in ${root} (a stale pack?): ${specs[name].slice(5)} and ${tarball}`);
335
+ specs[name] = `file:${tarball}`;
336
+ }
337
+ return specs;
338
+ }
339
+ /**
340
+ * The staged stack's package.json. With local packages, every one is an
341
+ * override (so transitive dependents get it too) and the direct dependencies
342
+ * name the same spec: npm rejects an override that contradicts one.
343
+ */
344
+ function stackManifest(options) {
345
+ const local = options.local ?? {};
346
+ const spec = (pkg, fallback) => local[pkg] ?? fallback;
347
+ const plugins = (options.plugins ?? []).map((pkg) => [pkg, spec(pkg, options.version)]);
348
+ return {
349
+ name: options.name,
350
+ private: true,
351
+ type: "module",
352
+ dependencies: {
353
+ [RUN_PACKAGE]: spec(RUN_PACKAGE, options.phCliSpec ?? options.version),
354
+ "@powerhousedao/host-core": spec("@powerhousedao/host-core", options.version),
355
+ ...Object.fromEntries(plugins)
356
+ },
357
+ ...Object.keys(local).length > 0 ? { overrides: local } : {}
358
+ };
359
+ }
360
+ /** A vendored tree installed from local tarballs: the same version numbers
361
+ * as the registry's, so npm would take either for the other. */
362
+ function vendoredFromLocal(stackDir) {
363
+ const lock = path.join(stackDir, "package-lock.json");
364
+ return fs.existsSync(lock) && fs.readFileSync(lock, "utf8").includes("\"resolved\": \"file:");
365
+ }
366
+ /** Types and source maps, which nothing reads at runtime. */
367
+ const UNREAD_FILE = /\.(d\.[cm]?ts|map)$/i;
368
+ const TEST_FILE = /\.(test|spec)\.[cm]?[jt]sx?$/;
369
+ /** Licences stay, as the packages' terms ask. */
370
+ const PACKAGE_NOTES = /^(readme|changelog|history)(\..*)?$/i;
371
+ /**
372
+ * Removes what a running app never reads. Windows creates and scans each file
373
+ * on its own, so these, over half the stack, were over half the install.
374
+ *
375
+ * @returns How many files went
376
+ */
377
+ function pruneStack(dir, inPackages = false) {
378
+ let removed = 0;
379
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
380
+ const full = path.join(dir, entry.name);
381
+ if (entry.isDirectory()) {
382
+ if (entry.name === "__tests__") {
383
+ removed += fs.readdirSync(full, {
384
+ recursive: true,
385
+ withFileTypes: true
386
+ }).filter((file) => file.isFile()).length;
387
+ fs.rmSync(full, {
388
+ recursive: true,
389
+ force: true
390
+ });
391
+ continue;
392
+ }
393
+ removed += pruneStack(full, inPackages || entry.name === "node_modules");
394
+ if (fs.readdirSync(full).length === 0) fs.rmdirSync(full);
395
+ } else if (entry.isFile() && (UNREAD_FILE.test(entry.name) || TEST_FILE.test(entry.name) || inPackages && PACKAGE_NOTES.test(entry.name))) {
396
+ fs.rmSync(full);
397
+ removed++;
398
+ }
399
+ }
400
+ return removed;
401
+ }
402
+ function bundleStack(options) {
403
+ const log = options.logger ?? console.log;
404
+ const stackDir = path.join(options.shellProjectDir, "dist-stack");
405
+ for (const entry of [
406
+ "hosts",
407
+ "agents",
408
+ "dist",
409
+ ".ph",
410
+ OAUTH_CLIENTS_DIR,
411
+ AI_DIR,
412
+ "powerhouse.config.json",
413
+ "package.json"
414
+ ]) fs.rmSync(path.join(stackDir, entry), {
415
+ recursive: true,
416
+ force: true
417
+ });
418
+ fs.mkdirSync(stackDir, { recursive: true });
419
+ log(` hosts/ ${copyDirFiltered(path.join(options.projectRoot, "hosts"), path.join(stackDir, "hosts"), options.excludeDirs ?? []) ? "staged" : "absent — skipped"}`);
420
+ const localKey = fileURLToPath(new URL("./local-key/local-key.mjs", import.meta.url));
421
+ if (fs.existsSync(localKey)) fs.copyFileSync(localKey, path.join(stackDir, "local-key.mjs"));
422
+ for (const dir of [
423
+ "agents",
424
+ "dist",
425
+ CONNECT_BUILD_DIR
426
+ ]) log(` ${dir}/ ${copyIfExists(path.join(options.projectRoot, dir), path.join(stackDir, dir)) ? "staged" : "absent — skipped"}`);
427
+ for (const dir of BROWSER_ONLY_IN_DIST) fs.rmSync(path.join(stackDir, "dist", dir), {
428
+ recursive: true,
429
+ force: true
430
+ });
431
+ const stagedDesktopHost = path.join(stackDir, "hosts", "desktop", "host.js");
432
+ if (fs.existsSync(stagedDesktopHost)) {
433
+ const source = fs.readFileSync(stagedDesktopHost, "utf8");
434
+ if (source.includes("@powerhousedao/desktop/runner")) {
435
+ fs.writeFileSync(stagedDesktopHost, "// STAGED COPY (bundle-stack): runner.module rewritten to the generic\n// compound — the packaged shell is the window; there is no nested shell.\n" + source.replace(/@powerhousedao\/desktop\/runner/g, "@powerhousedao/host-core/runners/compound"));
436
+ log(" hosts/desktop/host.js: runner rewritten to the generic compound (staged copy)");
437
+ }
438
+ }
439
+ stageConfig(options.projectRoot, stackDir, log);
440
+ if (options.projectFiles && options.projectFiles.length > 0) log(` ${stageProjectFiles(options.projectRoot, stackDir, options.projectFiles)} of ${options.projectFiles.length} files the hosts name staged`);
441
+ if (typeof options.connectPort === "number") {
442
+ fs.writeFileSync(path.join(stackDir, "shell.json"), `${JSON.stringify({ connectPort: options.connectPort }, null, 2)}\n`);
443
+ log(` shell.json: connectPort ${options.connectPort}`);
444
+ }
445
+ const sourcePkg = JSON.parse(fs.readFileSync(path.join(options.projectRoot, "package.json"), "utf8"));
446
+ const version = runVersion(options);
447
+ const name = sourcePkg.name ?? "powerhouse-desktop-stack";
448
+ const project = {
449
+ ...sourcePkg.version ? { version: sourcePkg.version } : {},
450
+ ...sourcePkg.exports ? { exports: sourcePkg.exports } : {}
451
+ };
452
+ const vendor = options.vendor !== false;
453
+ const local = options.localPackagesDir ? readLocalPackages(options.localPackagesDir) : void 0;
454
+ if (vendor && (local || vendoredFromLocal(stackDir))) for (const entry of ["node_modules", "package-lock.json"]) fs.rmSync(path.join(stackDir, entry), {
455
+ recursive: true,
456
+ force: true
457
+ });
458
+ fs.writeFileSync(path.join(stackDir, "package.json"), `${JSON.stringify({
459
+ ...local ? stackManifest({
460
+ name,
461
+ version,
462
+ phCliSpec: options.phCliSpec,
463
+ local,
464
+ plugins: options.plugins
465
+ }) : {
466
+ name,
467
+ private: true,
468
+ type: "module",
469
+ dependencies: { [RUN_PACKAGE]: version }
470
+ },
471
+ ...project
472
+ }, null, 2)}\n`);
473
+ let vendored = false;
474
+ if (vendor) {
475
+ const specs = local ? "" : registrySpecs(options).map((spec) => `"${spec}"`).join(" ");
476
+ log(local ? ` vendoring ${Object.keys(local).length} local packages from ${options.localPackagesDir} (hoisted, real files)…` : ` vendoring ${specs} (hoisted, real files)…`);
477
+ const result = spawnSync(`npm install ${specs} --install-strategy=hoisted --omit=dev --no-audit --no-fund`, {
478
+ cwd: stackDir,
479
+ stdio: "pipe",
480
+ shell: true,
481
+ windowsHide: true
482
+ });
483
+ if (result.status !== 0) throw new Error(`bundle-stack: vendoring failed (${result.status}):\n${result.stderr.toString().slice(-800)}`);
484
+ vendored = true;
485
+ } else log(" vendoring skipped (vendor: false) — existing tree left in place");
486
+ log(` ${pruneStack(stackDir)} files a running app never reads removed`);
487
+ return {
488
+ stackDir,
489
+ vendored
490
+ };
491
+ }
492
+ //#endregion
493
+ //#region src/shell-project.ts
494
+ /**
495
+ * P7.3 — project `hosts/desktop/app.json` into a generated `tauri-shell/`:
496
+ * a STANDALONE tauri crate that depends on the published `ph-desktop-shell`
497
+ * library, carries the builder's identity, and is built/run by the desktop
498
+ * runner's dev/build verbs. The builder never writes Rust.
499
+ *
500
+ * Everything here mirrors the known-good reference app
501
+ * (ph-desktop-shell/apps/powerhouse-desktop): the tauri plumbing (main.rs,
502
+ * build.rs, capabilities, the loading page, externalBin + icon mechanics) is
503
+ * copied verbatim; only identity/port fields are projected from app.json. The
504
+ * projection is idempotent and stale-detected — a file is rewritten only when
505
+ * its content changes, so Cargo.lock, the generated icon set, and tauri-build
506
+ * output are never disturbed by a regen with an unchanged app.json.
507
+ */
508
+ const SHELL_DIR = "tauri-shell";
509
+ /** The icon source the runner feeds to `tauri icon` (copied from app.icon). */
510
+ const ICON_SOURCE = "app-icon.png";
511
+ /** The version the installers and the macOS bundle carry: the numeric x.y.z
512
+ * of the project's version, as Windows' bundlers take nothing else. */
513
+ function bundleVersion(version) {
514
+ const numeric = /^(\d+)\.(\d+)\.(\d+)/.exec(version ?? "");
515
+ return numeric ? numeric.slice(1).join(".") : "0.1.0";
516
+ }
517
+ /** `ph-desktop-shell` dependency line for the generated Cargo.toml, from
518
+ * app.json's shell.source (path > git > crates.io version). */
519
+ function shellDependency(source) {
520
+ if (source?.path) {
521
+ const p = source.path.replace(/\\/g, "/");
522
+ return `ph-desktop-shell = { path = ${JSON.stringify(p)} }`;
523
+ }
524
+ if (source?.git) {
525
+ const parts = [`git = ${JSON.stringify(source.git)}`];
526
+ if (source.tag) parts.push(`tag = ${JSON.stringify(source.tag)}`);
527
+ if (source.rev) parts.push(`rev = ${JSON.stringify(source.rev)}`);
528
+ return `ph-desktop-shell = { ${parts.join(", ")} }`;
529
+ }
530
+ const version = source?.version ?? "0.1.1";
531
+ return `ph-desktop-shell = ${JSON.stringify(version)}`;
532
+ }
533
+ function cargoToml(app, binName) {
534
+ return `# GENERATED from ../app.json by @powerhousedao/desktop — do not edit by
535
+ # hand; edit app.json and re-run \`ph run desktop dev|build\`. Cargo.lock is
536
+ # preserved across regens.
537
+ [package]
538
+ name = ${JSON.stringify(binName)}
539
+ version = "0.1.0"
540
+ edition = "2021"
541
+
542
+ [build-dependencies]
543
+ tauri-build = { version = "2", features = [] }
544
+
545
+ [dependencies]
546
+ tauri = { version = "2", features = ["tray-icon", "devtools"] }
547
+ # Plugins must be DIRECT deps of the app crate: tauri-build only sees
548
+ # permission manifests (shell:allow-spawn etc.) from direct dependencies.
549
+ tauri-plugin-shell = "2"
550
+ tauri-plugin-single-instance = "2"
551
+ ${shellDependency(app.shell)}
552
+
553
+ [[bin]]
554
+ name = ${JSON.stringify(binName)}
555
+ path = "src/main.rs"
556
+
557
+ [profile.release]
558
+ codegen-units = 1
559
+ lto = true
560
+ `;
561
+ }
562
+ const MAIN_RS = `// GENERATED — identity bakes from tauri.conf.json via generate_context!;
563
+ // behavior is the shared ph-desktop-shell library. Edit ../app.json, not this.
564
+ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
565
+
566
+ fn main() {
567
+ ph_desktop_shell::run(tauri::generate_context!(), Default::default());
568
+ }
569
+ `;
570
+ const BUILD_RS = `// GENERATED — mirrors the reference shell. Connect is served over
571
+ // http://127.0.0.1 (a remote origin to Tauri), so the launch-queue commands
572
+ // need an explicit ACL; declaring the command manifest here generates the
573
+ // allow-<command> permissions that capabilities/*.json grant.
574
+ fn main() {
575
+ // The icon set is a COMPILE-TIME input (the Windows resource icon here,
576
+ // and the tray/window icon tauri::generate_context! embeds), but
577
+ // tauri-build registers no rerun trigger for it: without this line a
578
+ // regenerated icon set leaves the old icon compiled into the binary.
579
+ println!("cargo:rerun-if-changed=icons");
580
+ tauri_build::try_build(tauri_build::Attributes::new().app_manifest(
581
+ tauri_build::AppManifest::new().commands(&[
582
+ "take_launch_files",
583
+ "read_launch_file",
584
+ "log_from_webview",
585
+ "open_external",
586
+ "desktop_state",
587
+ "pick_root",
588
+ "save_renown_url",
589
+ "local_create",
590
+ "local_unlock",
591
+ "saved_credential",
592
+ "save_profile",
593
+ "adopt_old_data",
594
+ "start_stack",
595
+ "switch_identity",
596
+ ]),
597
+ ))
598
+ .expect("failed to run tauri-build");
599
+ }
600
+ `;
601
+ /** The sign-in page's script (app.json `signIn`), beside the page. */
602
+ const SIGN_IN_SCRIPT = "sign-in.js";
603
+ /** That script as this package built it (tsdown.config.ts). */
604
+ function builtSignInScript() {
605
+ return fs.readFileSync(fileURLToPath(new URL(`./sign-in/${SIGN_IN_SCRIPT}`, import.meta.url)));
606
+ }
607
+ /** The loading page's logo: app.json's icon SOURCE (1024² recommended), copied
608
+ * beside ui/index.html — not one of the downsampled `tauri icon` outputs, so
609
+ * it stays sharp on HiDPI screens. Generated, like the rest of ui/. */
610
+ const LOADING_LOGO = "logo.png";
611
+ /** The loading page's splash (app.json `splash`), copied beside it; shown
612
+ * instead of the square logo when set. Generated, like the rest of ui/. */
613
+ const LOADING_SPLASH = "splash.png";
614
+ /** Dark-scheme splash (app.json `splashDark`), beside the light one. */
615
+ const LOADING_SPLASH_DARK = "splash-dark.png";
616
+ /** CSS size of the logo; the 1024² source keeps it crisp up to 8x DPR. */
617
+ const LOGO_CSS_PX = 128;
618
+ /** The sign-in page's own look, on the loading page's colours. */
619
+ const SIGN_IN_CSS = `
620
+ body { overflow: auto; height: auto; min-height: 100vh; }
621
+ #sign-in {
622
+ position: relative; z-index: 1; box-sizing: border-box;
623
+ width: min(420px, calc(100vw - 32px)); margin: 24px 0; padding: 32px;
624
+ display: flex; flex-direction: column; gap: 12px; text-align: left;
625
+ background: color-mix(in srgb, var(--bg) 92%, var(--fg));
626
+ border: 1px solid color-mix(in srgb, var(--fg) 14%, transparent);
627
+ border-radius: 14px;
628
+ }
629
+ #sign-in h1 { margin: 0 0 8px; font-size: 24px; line-height: 1.2; font-weight: 600; }
630
+ #sign-in p { margin: 0; }
631
+ #sign-in small { opacity: .7; }
632
+ #sign-in button, #sign-in input {
633
+ font: inherit; color: inherit; border-radius: 8px; padding: 10px 14px;
634
+ border: 1px solid color-mix(in srgb, var(--fg) 22%, transparent);
635
+ background: transparent; box-sizing: border-box; width: 100%;
636
+ }
637
+ #sign-in button { cursor: pointer; }
638
+ #sign-in button.primary { background: var(--accent); border-color: var(--accent); color: var(--bg); font-weight: 600; }
639
+ #sign-in button.link { width: auto; padding: 0; border: 0; text-decoration: underline; }
640
+ #sign-in label { display: grid; gap: 4px; }
641
+ #sign-in details { font-size: 14px; display: grid; gap: 8px; }
642
+ #sign-in .folder { font-size: 13px; overflow-wrap: anywhere; }
643
+ #sign-in .notice { padding: 10px 12px; border-radius: 8px; font-size: 14px; background: color-mix(in srgb, var(--accent) 16%, transparent); }
644
+ #sign-in .identities { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
645
+ #sign-in .identity { display: flex; gap: 12px; align-items: center; text-align: left; }
646
+ #sign-in .identity img, #sign-in .initial {
647
+ width: 36px; height: 36px; border-radius: 50%; object-fit: cover; flex: none;
648
+ display: grid; place-items: center; font-weight: 600;
649
+ background: color-mix(in srgb, var(--accent) 30%, transparent);
650
+ }
651
+ #sign-in .identity b, #sign-in .identity small { display: block; }
652
+ #sign-in .busy { display: flex; align-items: center; justify-content: center; }
653
+ #sign-in:has(> .busy) { background: none; border: 0; }`;
654
+ function loadingHtml(app, art, signIn = false) {
655
+ const escape = (text) => text.replace(/[<&]/g, (c) => c === "<" ? "&lt;" : "&amp;");
656
+ const name = escape(app.productName);
657
+ const loading = app.loading;
658
+ const message = loading?.message ? escape(loading.message) : `Starting ${name}…`;
659
+ const pageColor = art.background?.color ?? null;
660
+ const background = pageColor?.light ?? loading?.background ?? "#0f1115";
661
+ const color = loading?.color ?? "#e6e8eb";
662
+ const accent = loading?.accent ?? "#4ade80";
663
+ const dark = loading?.dark;
664
+ const darkBackground = pageColor?.dark ?? dark?.background;
665
+ const darkVars = dark || darkBackground ? `
666
+ @media (prefers-color-scheme: dark) {
667
+ :root {
668
+ --bg: ${darkBackground ?? background};
669
+ --fg: ${dark?.color ?? color};
670
+ --accent: ${dark?.accent ?? accent};
671
+ }
672
+ }` : "";
673
+ const attr = (text) => text.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
674
+ const layersTag = art.background && art.background.layers.length > 0 ? `<div class="layers" aria-hidden="true">
675
+ ${art.background.layers.map((layer) => layer.dark ? `<picture>
676
+ <source srcset="${attr(layer.dark)}" media="(prefers-color-scheme: dark)" />
677
+ <img src="${attr(layer.light)}" alt="" style="${attr(layer.style)}" />
678
+ </picture>` : `<img src="${attr(layer.light)}" alt="" style="${attr(layer.style)}" />`).join("\n ")}
679
+ </div>
680
+ ` : "";
681
+ const picture = (cls, file, darkFile, attrs = "") => darkFile ? `<picture>
682
+ <source srcset="./${darkFile}" media="(prefers-color-scheme: dark)" />
683
+ <img class="${cls}" src="./${file}" alt=""${attrs} />
684
+ </picture>
685
+ ` : `<img class="${cls}" src="./${file}" alt=""${attrs} />
686
+ `;
687
+ const main = art.main;
688
+ const logoTag = main?.kind === "splash" ? picture("splash", main.file, main.dark) : main ? picture("logo", main.file, main.dark, ` width="${LOGO_CSS_PX}" height="${LOGO_CSS_PX}"`) : "";
689
+ const cornerTag = art.corner ? `<div class="corner" aria-hidden="true">${picture("art", art.corner.file, art.corner.dark)}</div>
690
+ ` : "";
691
+ return `<!doctype html>
692
+ <html lang="en">
693
+ <head>
694
+ <meta charset="utf-8" />
695
+ <title>${name}</title>
696
+ <style>
697
+ :root {
698
+ color-scheme: light dark;
699
+ --bg: ${background}; --fg: ${color}; --accent: ${accent};
700
+ }${darkVars}
701
+ body {
702
+ margin: 0; height: 100vh; overflow: hidden;
703
+ display: flex; align-items: center; justify-content: center;
704
+ font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
705
+ background: var(--bg); color: var(--fg);
706
+ }
707
+ .box {
708
+ position: relative; z-index: 1;
709
+ text-align: center;
710
+ display: flex; flex-direction: column; align-items: center; gap: 20px;
711
+ }
712
+ .logo {
713
+ width: ${LOGO_CSS_PX}px; height: ${LOGO_CSS_PX}px;
714
+ object-fit: contain; display: block;
715
+ }
716
+ .splash {
717
+ width: min(720px, 80vw); max-height: 65vh;
718
+ object-fit: contain; display: block;
719
+ }
720
+ .corner {
721
+ position: fixed; right: 0; bottom: 0; z-index: 0;
722
+ width: clamp(220px, 30vw, 520px); line-height: 0; pointer-events: none;
723
+ }
724
+ .layers { position: fixed; inset: 0; z-index: 0; }
725
+ .art { width: 100%; height: auto; display: block; }
726
+ .dot {
727
+ width: 10px; height: 10px; border-radius: 50%;
728
+ background: var(--accent); display: inline-block; margin-right: 8px;
729
+ animation: pulse 1.2s ease-in-out infinite;
730
+ }
731
+ @keyframes pulse { 0%,100% { opacity: .35 } 50% { opacity: 1 } }
732
+ @media (prefers-reduced-motion: reduce) { .dot { animation: none; } }${signIn ? SIGN_IN_CSS : ""}
733
+ </style>
734
+ </head>
735
+ <body>
736
+ ${signIn ? `<main id="sign-in"></main>
737
+ <script type="module" src="./sign-in.js"><\/script>` : `<div class="box">
738
+ ${logoTag}<div><span class="dot"></span>${message}</div>
739
+ </div>`}
740
+ ${layersTag}${cornerTag}</body>
741
+ </html>
742
+ `;
743
+ }
744
+ function tauriConf(input) {
745
+ const { app } = input;
746
+ const win = app.window ?? {};
747
+ const fileAssociations = app.fileAssociations && app.fileAssociations.length > 0 ? app.fileAssociations.map((fa) => ({
748
+ ext: fa.ext,
749
+ name: fa.name,
750
+ ...fa.description ? { description: fa.description } : {},
751
+ ...fa.mimeType ? { mimeType: fa.mimeType } : {}
752
+ })) : void 0;
753
+ const conf = {
754
+ $schema: "https://schema.tauri.app/config/2",
755
+ productName: app.productName,
756
+ version: bundleVersion(input.version),
757
+ identifier: app.identifier,
758
+ build: { frontendDist: "./ui" },
759
+ app: {
760
+ windows: [{
761
+ title: win.title ?? app.productName,
762
+ width: win.width ?? 1440,
763
+ height: win.height ?? 900,
764
+ resizable: win.resizable ?? true,
765
+ ...win.minWidth ? { minWidth: win.minWidth } : {},
766
+ ...win.minHeight ? { minHeight: win.minHeight } : {},
767
+ visible: true,
768
+ dragDropEnabled: false,
769
+ create: false
770
+ }],
771
+ security: { csp: null }
772
+ },
773
+ bundle: {
774
+ active: true,
775
+ targets: [
776
+ "nsis",
777
+ "app",
778
+ "dmg"
779
+ ],
780
+ icon: [
781
+ "icons/32x32.png",
782
+ "icons/128x128.png",
783
+ "icons/128x128@2x.png",
784
+ "icons/icon.icns",
785
+ "icons/icon.ico"
786
+ ],
787
+ ...fileAssociations ? { fileAssociations } : {},
788
+ externalBin: ["binaries/node"],
789
+ resources: { "./dist-stack": "stack" },
790
+ macOS: {
791
+ signingIdentity: "-",
792
+ hardenedRuntime: false
793
+ }
794
+ }
795
+ };
796
+ return JSON.stringify(conf, null, 2) + "\n";
797
+ }
798
+ function defaultCapability() {
799
+ return JSON.stringify({
800
+ $schema: "../gen/schemas/desktop-schema.json",
801
+ identifier: "default",
802
+ description: "Lets the shell spawn the bundled node sidecar.",
803
+ windows: ["main"],
804
+ permissions: [
805
+ "core:default",
806
+ "allow-take-launch-files",
807
+ "allow-read-launch-file",
808
+ "allow-log-from-webview",
809
+ {
810
+ identifier: "shell:allow-spawn",
811
+ allow: [{
812
+ name: "binaries/node",
813
+ sidecar: true,
814
+ args: true
815
+ }]
816
+ },
817
+ {
818
+ identifier: "shell:allow-execute",
819
+ allow: [{
820
+ name: "binaries/node",
821
+ sidecar: true,
822
+ args: true
823
+ }]
824
+ }
825
+ ]
826
+ }, null, 2) + "\n";
827
+ }
828
+ function connectCapability(connectPort) {
829
+ const origin = `http://127.0.0.1:${connectPort}`;
830
+ return JSON.stringify({
831
+ $schema: "../gen/schemas/desktop-schema.json",
832
+ identifier: "connect",
833
+ description: "Connect is served over http://127.0.0.1 (a remote origin to Tauri); without this the launch-queue commands are rejected before they run.",
834
+ windows: ["main"],
835
+ remote: { urls: [origin, `${origin}/*`] },
836
+ permissions: [
837
+ "allow-take-launch-files",
838
+ "allow-read-launch-file",
839
+ "allow-log-from-webview",
840
+ "allow-open-external",
841
+ "allow-desktop-state",
842
+ "allow-pick-root",
843
+ "allow-save-renown-url",
844
+ "allow-local-create",
845
+ "allow-local-unlock",
846
+ "allow-saved-credential",
847
+ "allow-save-profile",
848
+ "allow-adopt-old-data",
849
+ "allow-start-stack",
850
+ "allow-switch-identity"
851
+ ]
852
+ }, null, 2) + "\n";
853
+ }
854
+ const GITIGNORE = `# Generated tauri shell — only Cargo.lock and app-icon.png are tracked.
855
+ /target
856
+ /gen
857
+ /icons
858
+ /ui/logo.png
859
+ /ui/splash.png
860
+ /ui/splash-dark.png
861
+ /ui/art.*
862
+ /ui/art-dark.*
863
+ /ui/bg-*
864
+ /ui/sign-in.*
865
+ /dist-stack
866
+ /binaries
867
+ `;
868
+ const DIST_STACK_README = `This directory is replaced at \`ph run desktop build\` with the shippable
869
+ stack (hosts + powerhouse.config.json + built Connect + vendored ph-cli). It
870
+ is bundled as the app's \`stack\` resource so the installed app runs with no
871
+ environment. Kept as a placeholder so tauri's resource glob resolves in dev.
872
+ `;
873
+ /** Write a file only when its content differs; returns whether it changed. */
874
+ function writeIfChanged(file, content) {
875
+ if (fs.existsSync(file) && fs.readFileSync(file, "utf8") === content) return false;
876
+ fs.mkdirSync(path.dirname(file), { recursive: true });
877
+ fs.writeFileSync(file, content);
878
+ return true;
879
+ }
880
+ /**
881
+ * Materialize/refresh `<hostDir>/tauri-shell/` from app.json. Idempotent:
882
+ * unchanged app.json rewrites nothing. Does NOT run `tauri icon` or fetch the
883
+ * node binary — those are toolchain steps the runner performs at dev/build.
884
+ */
885
+ function projectShell(input) {
886
+ const { hostDir, app, connectPort } = input;
887
+ const binName = appSlug(app);
888
+ const shellDir = path.join(hostDir, SHELL_DIR);
889
+ const iconSrc = path.resolve(hostDir, app.icon);
890
+ const iconBytes = fs.existsSync(iconSrc) ? fs.readFileSync(iconSrc) : null;
891
+ const readRel = (rel) => {
892
+ if (!rel) return null;
893
+ const abs = path.resolve(hostDir, rel);
894
+ return fs.existsSync(abs) ? fs.readFileSync(abs) : null;
895
+ };
896
+ const splashBytes = readRel(app.splash);
897
+ const splashDarkBytes = readRel(app.splashDark);
898
+ const artBytes = readRel(app.loading?.art);
899
+ const artDarkBytes = readRel(app.loading?.artDark);
900
+ const artExt = (rel) => rel ? path.extname(rel).toLowerCase() || ".png" : ".png";
901
+ const artFile = `art${artExt(app.loading?.art)}`;
902
+ const artDarkFile = `art-dark${artExt(app.loading?.artDark)}`;
903
+ const background = normalizeBackground(app.background);
904
+ const staged = [];
905
+ const stage = (ref, stem) => {
906
+ if (isPassthroughImageRef(ref)) return ref;
907
+ const abs = path.resolve(hostDir, ref);
908
+ if (!fs.existsSync(abs)) return void 0;
909
+ const file = `${stem}${artExt(ref)}`;
910
+ staged.push([path.join(shellDir, "ui", file), fs.readFileSync(abs)]);
911
+ return `./${file}`;
912
+ };
913
+ const layers = (background?.layers ?? []).flatMap((layer, index) => {
914
+ const variants = imageVariants(layer.src);
915
+ const light = stage(variants.light, `bg-${index}`);
916
+ if (!light) return [];
917
+ const dark = variants.dark ? stage(variants.dark, `bg-${index}-dark`) : void 0;
918
+ return [{
919
+ light,
920
+ ...dark ? { dark } : {},
921
+ style: layerStyleText(layer)
922
+ }];
923
+ });
924
+ const art = {
925
+ main: background ? null : splashBytes ? {
926
+ kind: "splash",
927
+ file: LOADING_SPLASH,
928
+ ...splashDarkBytes ? { dark: LOADING_SPLASH_DARK } : {}
929
+ } : iconBytes ? {
930
+ kind: "logo",
931
+ file: LOADING_LOGO
932
+ } : null,
933
+ corner: !background && artBytes ? {
934
+ file: artFile,
935
+ ...artDarkBytes ? { dark: artDarkFile } : {}
936
+ } : null,
937
+ background: background ? {
938
+ color: colorVariants(background.color),
939
+ layers
940
+ } : null
941
+ };
942
+ const files = [
943
+ ["Cargo.toml", cargoToml(app, binName)],
944
+ ["src/main.rs", MAIN_RS],
945
+ ["build.rs", BUILD_RS],
946
+ ["tauri.conf.json", tauriConf(input)],
947
+ ["ui/index.html", loadingHtml(app, art)],
948
+ ["capabilities/default.json", defaultCapability()],
949
+ ["capabilities/connect.json", connectCapability(connectPort)],
950
+ [".gitignore", GITIGNORE],
951
+ ["dist-stack/README.md", DIST_STACK_README]
952
+ ];
953
+ if (app.signIn) files.push(["ui/sign-in.html", loadingHtml(app, art, true)]);
954
+ let changed = false;
955
+ for (const [rel, content] of files) if (writeIfChanged(path.join(shellDir, rel), content)) changed = true;
956
+ if (!app.signIn) for (const file of ["sign-in.html", SIGN_IN_SCRIPT]) {
957
+ const stale = path.join(shellDir, "ui", file);
958
+ if (fs.existsSync(stale)) {
959
+ fs.rmSync(stale);
960
+ changed = true;
961
+ }
962
+ }
963
+ const copies = [
964
+ [path.join(shellDir, "ui", SIGN_IN_SCRIPT), app.signIn ? input.signInScript ?? builtSignInScript() : null],
965
+ [path.join(shellDir, ICON_SOURCE), iconBytes],
966
+ [path.join(shellDir, "ui", LOADING_LOGO), iconBytes],
967
+ [path.join(shellDir, "ui", LOADING_SPLASH), splashBytes],
968
+ [path.join(shellDir, "ui", LOADING_SPLASH_DARK), splashDarkBytes],
969
+ [path.join(shellDir, "ui", artFile), artBytes],
970
+ [path.join(shellDir, "ui", artDarkFile), artDarkBytes],
971
+ ...staged
972
+ ];
973
+ for (const [dest, bytes] of copies) {
974
+ if (!bytes) continue;
975
+ if (!fs.existsSync(dest) || !fs.readFileSync(dest).equals(bytes)) {
976
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
977
+ fs.writeFileSync(dest, bytes);
978
+ changed = true;
979
+ }
980
+ }
981
+ return {
982
+ shellDir,
983
+ binName,
984
+ changed
985
+ };
986
+ }
987
+ //#endregion
988
+ //#region src/shell-toolchain.ts
989
+ /** The Node release triple for a build host — the sidecar filename tauri
990
+ * resolves (`node-<triple>`). Pure, so the mapping is unit-tested. */
991
+ function nodeSidecarTarget(platform, arch) {
992
+ const target = {
993
+ "win32 x64": {
994
+ triple: "x86_64-pc-windows-msvc",
995
+ dist: "win-x64",
996
+ bin: "node.exe",
997
+ ext: ".exe"
998
+ },
999
+ "darwin arm64": {
1000
+ triple: "aarch64-apple-darwin",
1001
+ dist: "darwin-arm64",
1002
+ bin: "bin/node",
1003
+ ext: ""
1004
+ },
1005
+ "darwin x64": {
1006
+ triple: "x86_64-apple-darwin",
1007
+ dist: "darwin-x64",
1008
+ bin: "bin/node",
1009
+ ext: ""
1010
+ },
1011
+ "linux x64": {
1012
+ triple: "x86_64-unknown-linux-gnu",
1013
+ dist: "linux-x64",
1014
+ bin: "bin/node",
1015
+ ext: ""
1016
+ }
1017
+ }[`${platform} ${arch}`];
1018
+ if (!target) throw new Error(`No Node sidecar mapping for ${platform} ${arch} — the desktop shell supports win32/x64, darwin/arm64, darwin/x64, linux/x64.`);
1019
+ return target;
1020
+ }
1021
+ /** Fetch the stock Node the shell ships as its sidecar into `<shellDir>/
1022
+ * binaries`, named per target triple. No-op when already present. Ported from
1023
+ * the reference repo's fetch-node.mjs (the builder has no such script). */
1024
+ function fetchNodeSidecar(shellDir, version = process.versions.node, platform = process.platform, arch = process.arch) {
1025
+ const target = nodeSidecarTarget(platform, arch);
1026
+ const binariesDir = path.join(shellDir, "binaries");
1027
+ fs.mkdirSync(binariesDir, { recursive: true });
1028
+ const dest = path.join(binariesDir, `node-${target.triple}${target.ext}`);
1029
+ if (fs.existsSync(dest)) return dest;
1030
+ if (platform === "win32") {
1031
+ const url = `https://nodejs.org/dist/v${version}/win-x64/node.exe`;
1032
+ execSync(`curl -fsSL -o "${dest}" "${url}"`, { stdio: "inherit" });
1033
+ } else {
1034
+ const name = `node-v${version}-${target.dist}`;
1035
+ const url = `https://nodejs.org/dist/v${version}/${name}.tar.gz`;
1036
+ execSync(`curl -fsSL "${url}" | tar -xz -C "${binariesDir}" --strip-components=2 ${name}/${target.bin}`, {
1037
+ stdio: "inherit",
1038
+ shell: "/bin/sh"
1039
+ });
1040
+ fs.renameSync(path.join(binariesDir, "node"), dest);
1041
+ fs.chmodSync(dest, 493);
1042
+ }
1043
+ return dest;
1044
+ }
1045
+ /** Default bundle targets for the build host (`cargo tauri build --bundles`).
1046
+ * macOS gets app+dmg, Windows nsis, Linux deb+appimage — a host only builds
1047
+ * installers it can produce. */
1048
+ function tauriBundlesForHost(platform = process.platform) {
1049
+ switch (platform) {
1050
+ case "darwin": return ["app", "dmg"];
1051
+ case "win32": return ["nsis"];
1052
+ default: return ["deb", "appimage"];
1053
+ }
1054
+ }
1055
+ /** Spawn parameters that avoid DEP0190 (args array + shell:true): cargo on
1056
+ * Windows needs the shell for PATH/.exe + subcommand resolution — pass ONE
1057
+ * string, empty args; everything else runs argv directly (shell:false). The
1058
+ * joined tokens here are our own constants/paths, never user input. */
1059
+ function tauriSpawn(tauri, subcommand) {
1060
+ const argv = [...tauri.prefix, ...subcommand];
1061
+ if (tauri.cmd === "cargo" && process.platform === "win32") return {
1062
+ command: ["cargo", ...argv].join(" "),
1063
+ args: [],
1064
+ shell: true
1065
+ };
1066
+ return {
1067
+ command: tauri.cmd,
1068
+ args: argv,
1069
+ shell: false
1070
+ };
1071
+ }
1072
+ function probe(cmd, args) {
1073
+ const onWin = process.platform === "win32";
1074
+ try {
1075
+ return spawnSync(onWin ? [cmd, ...args].join(" ") : cmd, onWin ? [] : args, {
1076
+ stdio: "ignore",
1077
+ shell: onWin
1078
+ }).status === 0;
1079
+ } catch {
1080
+ return false;
1081
+ }
1082
+ }
1083
+ /** Is a Rust `cargo` on PATH? (needed to compile the shell crate). */
1084
+ function hasCargo() {
1085
+ return probe("cargo", ["--version"]);
1086
+ }
1087
+ /** Resolve a Tauri CLI: a global `cargo tauri`, else a `@tauri-apps/cli`
1088
+ * resolvable from the project. Returns null when neither is available. */
1089
+ function resolveTauriCommand(projectRoot) {
1090
+ if (probe("cargo", ["tauri", "--version"])) return {
1091
+ cmd: "cargo",
1092
+ prefix: ["tauri"],
1093
+ via: "cargo-tauri"
1094
+ };
1095
+ try {
1096
+ const pkgJson = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href).resolve("@tauri-apps/cli/package.json");
1097
+ const pkgDir = path.dirname(pkgJson);
1098
+ const bin = JSON.parse(fs.readFileSync(pkgJson, "utf8")).bin;
1099
+ const rel = typeof bin === "string" ? bin : bin?.tauri;
1100
+ if (rel) return {
1101
+ cmd: process.execPath,
1102
+ prefix: [path.join(pkgDir, rel)],
1103
+ via: "node-cli"
1104
+ };
1105
+ } catch {}
1106
+ return null;
1107
+ }
1108
+ function detectToolchain(projectRoot) {
1109
+ return {
1110
+ cargo: hasCargo(),
1111
+ tauri: resolveTauriCommand(projectRoot)
1112
+ };
1113
+ }
1114
+ /** Throw a clear, actionable error when the native toolchain is incomplete —
1115
+ * the desktop verbs call this before any cargo work so a missing executable
1116
+ * is an instruction, not a stack trace. */
1117
+ function preflightOrThrow(tc, hostName) {
1118
+ const missing = [];
1119
+ if (!tc.cargo) missing.push(" • Rust/cargo — install from https://rustup.rs (then restart your shell)");
1120
+ if (!tc.tauri) missing.push(" • Tauri CLI — `cargo install tauri-cli --version \"^2\"` (or add @tauri-apps/cli@^2 to your project's devDependencies)");
1121
+ if (missing.length > 0 || !tc.tauri) throw new Error(`hosts/${hostName}: the desktop shell needs a native toolchain that is not installed:\n${missing.join("\n")}\nInstall the above, then re-run \`ph run ${hostName} dev\` / \`ph run ${hostName} build\`. (The headless stack — \`ph run ${hostName}\` — needs none of this.)`);
1122
+ return tc.tauri;
1123
+ }
1124
+ /** `<tauri> icon <source>` — generates the per-platform icon set (icon.ico +
1125
+ * icon.icns + pngs) the bundle references and tauri-build requires. */
1126
+ function runTauriIcon(tauri, shellDir, iconSource) {
1127
+ const { command, args, shell } = tauriSpawn(tauri, ["icon", iconSource]);
1128
+ const r = spawnSync(command, args, {
1129
+ cwd: shellDir,
1130
+ stdio: "inherit",
1131
+ shell
1132
+ });
1133
+ if (r.status !== 0) throw new Error(`\`tauri icon ${iconSource}\` failed (exit ${r.status ?? "?"}) in ${shellDir} — check that app.icon is a square PNG.`);
1134
+ }
1135
+ //#endregion
1136
+ //#region src/shell.ts
1137
+ function resolveShell(projectRoot, options, env) {
1138
+ const configured = options?.project ?? env.PH_DESKTOP_SHELL;
1139
+ if (!configured) throw new Error("No desktop shell configured: set runner.shell.project in the host file (path to a ph-win-desktop checkout) or the PH_DESKTOP_SHELL environment variable. `ph run desktop` (headless stack) needs neither.");
1140
+ const projectDir = path.resolve(projectRoot, configured);
1141
+ if (!fs.existsSync(path.join(projectDir, "src-tauri"))) throw new Error(`Desktop shell not found at ${projectDir} (no src-tauri/) — check runner.shell.project / PH_DESKTOP_SHELL.`);
1142
+ return {
1143
+ projectDir,
1144
+ exe: [
1145
+ path.join(projectDir, "src-tauri", "target", "debug", "ph-win.exe"),
1146
+ path.join(projectDir, "src-tauri", "target", "release", "ph-win.exe"),
1147
+ path.join(projectDir, "src-tauri", "target", "debug", "ph-win"),
1148
+ path.join(projectDir, "src-tauri", "target", "release", "ph-win")
1149
+ ].find((c) => fs.existsSync(c))
1150
+ };
1151
+ }
1152
+ /** Resolve the project's ph-cli entry from ITS dependency tree — the same
1153
+ * resolution `ph run` itself uses. */
1154
+ function resolvePhCliEntry(projectRoot) {
1155
+ const pkgPath = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href).resolve("@powerhousedao/ph-cli/package.json");
1156
+ return path.join(path.dirname(pkgPath), "dist", "cli.mjs");
1157
+ }
1158
+ /** The env trio (plus flag and userData) the shell's uniform-runners mode
1159
+ * reads — wired by the RUNNER so nobody exports variables by hand. */
1160
+ function shellEnv(projectRoot, connectPort, env) {
1161
+ return {
1162
+ FEATURE_UNIFORM_RUNNERS_ENABLED: "1",
1163
+ PH_RUN_PROJECT: projectRoot,
1164
+ PH_RUN_CLI: resolvePhCliEntry(projectRoot),
1165
+ PH_WIN_CONNECT_PORT: String(connectPort),
1166
+ ...env.PH_USER_DATA_DIR ? { PH_USER_DATA_DIR: env.PH_USER_DATA_DIR } : {}
1167
+ };
1168
+ }
1169
+ /** Project host shell options onto a tauri `--config` merge patch (D6.d) —
1170
+ * the host file stays the single source for app identity on tauri-cli
1171
+ * invocations; a built exe has these baked. */
1172
+ function tauriConfigPatch(options) {
1173
+ if (!options) return void 0;
1174
+ const patch = {};
1175
+ if (options.window) patch.app = { windows: [{
1176
+ ...options.window.title ? { title: options.window.title } : {},
1177
+ ...options.window.width ? { width: options.window.width } : {},
1178
+ ...options.window.height ? { height: options.window.height } : {}
1179
+ }] };
1180
+ if (options.fileAssociations?.length) patch.bundle = { fileAssociations: [{
1181
+ ext: options.fileAssociations.map((e) => e.replace(/^\./, "")),
1182
+ name: "Powerhouse Document"
1183
+ }] };
1184
+ return Object.keys(patch).length > 0 ? patch : void 0;
1185
+ }
1186
+ function launchShell(shell, envVars, options) {
1187
+ if (shell.exe) return spawn(shell.exe, [], {
1188
+ cwd: shell.projectDir,
1189
+ env: {
1190
+ ...process.env,
1191
+ ...envVars
1192
+ },
1193
+ stdio: "inherit",
1194
+ windowsHide: true
1195
+ });
1196
+ const patch = tauriConfigPatch(options);
1197
+ const args = ["tauri", "dev"];
1198
+ if (patch) args.push("--config", JSON.stringify(patch));
1199
+ return spawn("pnpm", args, {
1200
+ cwd: shell.projectDir,
1201
+ env: {
1202
+ ...process.env,
1203
+ ...envVars
1204
+ },
1205
+ stdio: "inherit",
1206
+ shell: true,
1207
+ windowsHide: true
1208
+ });
1209
+ }
1210
+ //#endregion
1211
+ //#region src/bundle-backend.ts
1212
+ /**
1213
+ * A packaged stack is a node_modules folder, and Windows installs by the file:
1214
+ * tens of thousands of them take as long to install as to uninstall, and a
1215
+ * start spends most of a cold disk's time reading them. This folds the stack
1216
+ * into a few hundred files with Rolldown, in the staged copy only.
1217
+ *
1218
+ * What's loaded by name keeps working by name. Each package an add-on, a host
1219
+ * file or the project's own build may import stays in node_modules with its
1220
+ * \`exports\`, and each of those is a Rolldown entry, so an import of
1221
+ * \`document-model\` from anywhere reaches the one bundled copy. Two copies would
1222
+ * break \`instanceof\` and shared state, and without an error.
1223
+ *
1224
+ * What's found by path keeps its path. Chunks and the worker scripts go in one
1225
+ * package, so a chunk finds \`./entry.mjs\` beside it and the piece worker's walk
1226
+ * up to a package.json finds \`dist/worker-entry.js\`.
1227
+ */
1228
+ /** Holds the chunks. A package, so the piece worker's lookup stops at it. */
1229
+ const CHUNKS_DIR = ".stack";
1230
+ /** Packages reached by name, by something that isn't in the bundle. */
1231
+ const BY_NAME = [
1232
+ /^@powerhousedao\//,
1233
+ /^@renown\/sdk$/,
1234
+ /^document-model$/,
1235
+ /^graphql$/,
1236
+ /^graphql-tag$/,
1237
+ /^kysely$/,
1238
+ /^zod$/
1239
+ ];
1240
+ /**
1241
+ * Left as files. PGlite finds its wasm and data beside it. React is what an
1242
+ * add-on's editor imports, and a server never calls it. The rest is only loaded
1243
+ * on a path a running app never takes, or by a native addon.
1244
+ */
1245
+ const EXTERNAL = [
1246
+ /\.node$/,
1247
+ /^@electric-sql\/pglite/,
1248
+ /^pglite-(legacy|tools)/,
1249
+ /^react($|\/)/,
1250
+ /^react-dom($|\/)/,
1251
+ /^vite($|\/)/,
1252
+ /^@powerhousedao\/vetra($|\/)/,
1253
+ /^@originjs\//,
1254
+ /^devcert$/,
1255
+ /^pg-native$/,
1256
+ /^bufferutil$/,
1257
+ /^utf-8-validate$/,
1258
+ /^@pyroscope\//
1259
+ ];
1260
+ /** How Rolldown writes a require it can't fold. A plain `require(` in a chunk is
1261
+ * text: a package's comments, error messages and generated code. */
1262
+ const REQUIRE_CALL = /\b__require\(\s*["']([^"']+)["']\s*\)/g;
1263
+ /** Copied into a kept package as they are, since a path reaches them. */
1264
+ const KEEP_AS_FILES = [path.join("dist", "node", "pieces")];
1265
+ /** What a package exports for a server: node, then import, then default. */
1266
+ function serverTarget(target) {
1267
+ if (typeof target === "string") return target;
1268
+ if (target === null || target === void 0) return null;
1269
+ for (const condition of [
1270
+ "node",
1271
+ "import",
1272
+ "default"
1273
+ ]) if (condition in target) {
1274
+ const found = serverTarget(target[condition]);
1275
+ if (found) return found;
1276
+ }
1277
+ return null;
1278
+ }
1279
+ /** Every subpath a package offers a server, with a wildcard's matches listed. */
1280
+ function exportedFiles(packageDir, manifest) {
1281
+ const files = /* @__PURE__ */ new Map();
1282
+ const exports = typeof manifest.exports === "string" ? { ".": manifest.exports } : manifest.exports;
1283
+ if (!exports) {
1284
+ const main = manifest.module ?? manifest.main ?? "index.js";
1285
+ const file = [
1286
+ main,
1287
+ `${main}.js`,
1288
+ path.join(main, "index.js")
1289
+ ].find((candidate) => isFile(path.join(packageDir, candidate)));
1290
+ if (file) files.set(".", file.replace(/^\.\//, ""));
1291
+ return files;
1292
+ }
1293
+ for (const [subpath, target] of Object.entries(exports)) {
1294
+ if (subpath === "./package.json") continue;
1295
+ const file = serverTarget(target);
1296
+ if (!file) continue;
1297
+ if (!subpath.includes("*")) {
1298
+ if (isFile(path.join(packageDir, file))) files.set(subpath, file.replace(/^\.\//, ""));
1299
+ continue;
1300
+ }
1301
+ for (const [match, found] of wildcardMatches(packageDir, file)) files.set(subpath.replace("*", match), found);
1302
+ }
1303
+ return files;
1304
+ }
1305
+ function isFile(file) {
1306
+ return fs.existsSync(file) && fs.statSync(file).isFile();
1307
+ }
1308
+ function wildcardMatches(packageDir, target) {
1309
+ const [before, after = ""] = target.replace(/^\.\//, "").split("*");
1310
+ const parent = before.endsWith("/") ? before : path.posix.dirname(before);
1311
+ const prefix = before.slice(parent.length).replace(/^\//, "");
1312
+ const matches = [];
1313
+ const folder = path.join(packageDir, parent);
1314
+ if (!fs.existsSync(folder)) return matches;
1315
+ for (const entry of fs.readdirSync(folder, { withFileTypes: true })) {
1316
+ const name = entry.name;
1317
+ const match = after.startsWith("/") ? name : name.endsWith(after) && name.startsWith(prefix) ? name.slice(prefix.length, name.length - after.length) : null;
1318
+ if (!match) continue;
1319
+ const file = path.posix.join(parent, `${prefix}${match}${after}`);
1320
+ if (isFile(path.join(packageDir, file))) matches.push([match, file]);
1321
+ }
1322
+ return matches;
1323
+ }
1324
+ /** Where a subpath's entry lands in its package. */
1325
+ function entryNameOf(pkg, subpath) {
1326
+ return `${pkg}/${subpath === "." ? "index" : subpath.replace(/^\.\//, "").replaceAll("/", "__")}`;
1327
+ }
1328
+ /** The package.json of a package whose code is now in the bundle. */
1329
+ function keptManifest(manifest, entries) {
1330
+ const { name, version } = manifest;
1331
+ const exports = { "./package.json": "./package.json" };
1332
+ for (const [subpath, file] of entries) exports[subpath] = `./${file}`;
1333
+ return {
1334
+ name,
1335
+ version,
1336
+ type: "module",
1337
+ exports
1338
+ };
1339
+ }
1340
+ /** Nearest install of \`dependency\` as seen from \`from\`, by node's rules. */
1341
+ function resolveInLock(lock, from, dependency) {
1342
+ let at = from;
1343
+ for (;;) {
1344
+ const candidate = `${at ? `${at}/` : ""}node_modules/${dependency}`;
1345
+ if (lock[candidate]) return candidate;
1346
+ if (!at) return null;
1347
+ const cut = at.lastIndexOf("node_modules/");
1348
+ at = cut <= 0 ? "" : at.slice(0, cut - 1);
1349
+ }
1350
+ }
1351
+ /** The install paths of `names` and everything they depend on. */
1352
+ function closureOf(lock, names) {
1353
+ const kept = /* @__PURE__ */ new Set();
1354
+ const queue = [...names].map((name) => `node_modules/${name}`).filter((key) => lock[key]);
1355
+ while (queue.length > 0) {
1356
+ const key = queue.pop();
1357
+ if (kept.has(key)) continue;
1358
+ kept.add(key);
1359
+ const entry = lock[key];
1360
+ for (const dependency of Object.keys({
1361
+ ...entry.dependencies,
1362
+ ...entry.optionalDependencies
1363
+ })) {
1364
+ const target = resolveInLock(lock, key, dependency);
1365
+ if (target) queue.push(target);
1366
+ }
1367
+ }
1368
+ return kept;
1369
+ }
1370
+ /** The package a bare specifier belongs to, or null for a built-in or a path. */
1371
+ function packageOf(specifier) {
1372
+ if (specifier.startsWith(".") || specifier.startsWith("/")) return null;
1373
+ if (specifier.startsWith("node:") || /^[a-z]+:/i.test(specifier)) return null;
1374
+ const parts = specifier.split("/");
1375
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
1376
+ }
1377
+ /** One file of every package's licence, as a bundle can't keep them beside
1378
+ * the code. Packages under the same text share it. */
1379
+ function licencesOf(modules, packages) {
1380
+ const byText = /* @__PURE__ */ new Map();
1381
+ let count = 0;
1382
+ for (const name of packages) {
1383
+ const dir = path.join(modules, name);
1384
+ if (!fs.existsSync(dir)) continue;
1385
+ const text = fs.readdirSync(dir).filter((file) => /^(licen[sc]e|copying|notice)/i.test(file) && isFile(path.join(dir, file))).sort().map((file) => fs.readFileSync(path.join(dir, file), "utf8").trim()).join("\n\n");
1386
+ const manifest = readJson(path.join(dir, "package.json"));
1387
+ const label = `${name}@${String(manifest.version ?? "")}`;
1388
+ const key = text || `License: ${JSON.stringify(manifest.license ?? "unknown")}`;
1389
+ byText.set(key, [...byText.get(key) ?? [], label]);
1390
+ count++;
1391
+ }
1392
+ return {
1393
+ text: [...byText.entries()].map(([text, labels]) => `${labels.join("\n")}\n\n${text}\n`).join(`\n${"-".repeat(72)}\n\n`),
1394
+ packages: count
1395
+ };
1396
+ }
1397
+ function readJson(file) {
1398
+ return JSON.parse(fs.readFileSync(file, "utf8"));
1399
+ }
1400
+ function packagesIn(modules) {
1401
+ const names = [];
1402
+ for (const entry of fs.readdirSync(modules, { withFileTypes: true })) {
1403
+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
1404
+ if (!entry.name.startsWith("@")) {
1405
+ names.push(entry.name);
1406
+ continue;
1407
+ }
1408
+ for (const scoped of fs.readdirSync(path.join(modules, entry.name))) names.push(`${entry.name}/${scoped}`);
1409
+ }
1410
+ return names;
1411
+ }
1412
+ /** `__dirname` and `require` per chunk, as a banner collides with any code that
1413
+ * declares its own. */
1414
+ const nodeGlobals = {
1415
+ name: "ph:node-globals",
1416
+ renderChunk(code) {
1417
+ const declared = (name) => new RegExp(`\\b(?:const|let|var|function)\\s+${name}\\b`).test(code);
1418
+ const used = (name) => new RegExp(`(?<![.\\w$])${name}\\b`).test(code);
1419
+ const wanted = [
1420
+ "__filename",
1421
+ "__dirname",
1422
+ "require"
1423
+ ].filter((name) => used(name) && !declared(name));
1424
+ if (wanted.length === 0) return null;
1425
+ const lines = [`import { fileURLToPath as __ph_path } from "node:url";`];
1426
+ if (wanted.includes("__dirname")) {
1427
+ lines.push(`import { dirname as __ph_dir } from "node:path";`);
1428
+ lines.push(`const __dirname = __ph_dir(__ph_path(import.meta.url));`);
1429
+ }
1430
+ if (wanted.includes("__filename")) lines.push(`const __filename = __ph_path(import.meta.url);`);
1431
+ if (wanted.includes("require")) {
1432
+ lines.push(`import { createRequire as __ph_require } from "node:module";`);
1433
+ lines.push(`const require = __ph_require(import.meta.url);`);
1434
+ }
1435
+ return {
1436
+ code: `${lines.join("\n")}\n${code}`,
1437
+ map: null
1438
+ };
1439
+ }
1440
+ };
1441
+ /** Replaces a staged stack's node_modules with a bundle of it. */
1442
+ async function bundleBackend(options) {
1443
+ const log = options.logger ?? (() => void 0);
1444
+ const { stackDir } = options;
1445
+ const modules = path.join(stackDir, "node_modules");
1446
+ const output = path.join(stackDir, ".bundle-output");
1447
+ fs.rmSync(output, {
1448
+ recursive: true,
1449
+ force: true
1450
+ });
1451
+ const lock = readJson(path.join(stackDir, "package-lock.json")).packages;
1452
+ const installed = packagesIn(modules);
1453
+ const byName = installed.filter((name) => BY_NAME.some((pattern) => pattern.test(name)));
1454
+ const input = {};
1455
+ const entriesOf = /* @__PURE__ */ new Map();
1456
+ const kept = /* @__PURE__ */ new Map();
1457
+ for (const name of byName) {
1458
+ const dir = path.join(modules, name);
1459
+ const manifest = readJson(path.join(dir, "package.json"));
1460
+ kept.set(name, manifest);
1461
+ const entries = /* @__PURE__ */ new Map();
1462
+ for (const [subpath, file] of exportedFiles(dir, manifest)) {
1463
+ if (!/\.[cm]?js$/.test(file)) continue;
1464
+ const entry = entryNameOf(name, subpath);
1465
+ input[entry] = path.join(dir, file);
1466
+ entries.set(subpath, `${path.posix.basename(entry)}.mjs`);
1467
+ }
1468
+ entriesOf.set(name, entries);
1469
+ }
1470
+ input["@powerhousedao/ph-run/dist/cli"] = path.join(modules, "@powerhousedao/ph-run/dist/cli.mjs");
1471
+ input[`${CHUNKS_DIR}/entry`] = path.join(modules, "@powerhousedao/reactor-api/dist/src/pglite/worker/entry.mjs");
1472
+ input[`${CHUNKS_DIR}/dist/worker-entry`] = path.join(modules, "@powerhousedao/reactor-workflow/dist/worker-entry.js");
1473
+ for (const [entry, file] of Object.entries(input)) if (!fs.existsSync(file)) throw new Error(`no entry ${entry} at ${file}`);
1474
+ log(` bundling ${Object.keys(input).length} entries of ${byName.length} packages…`);
1475
+ const { rolldown } = await import("rolldown");
1476
+ const build = await rolldown({
1477
+ cwd: stackDir,
1478
+ input,
1479
+ platform: "node",
1480
+ external: EXTERNAL,
1481
+ onLog() {},
1482
+ plugins: [nodeGlobals]
1483
+ });
1484
+ const { output: written } = await build.write({
1485
+ dir: output,
1486
+ format: "esm",
1487
+ entryFileNames: (chunk) => chunk.name === `${CHUNKS_DIR}/dist/worker-entry` ? `${CHUNKS_DIR}/dist/worker-entry.js` : "[name].mjs",
1488
+ chunkFileNames: `${CHUNKS_DIR}/[name]-[hash].mjs`,
1489
+ keepNames: true,
1490
+ sourcemap: false
1491
+ });
1492
+ await build.close();
1493
+ const ownFiles = new Set(written.map((file) => file.fileName));
1494
+ const reached = /* @__PURE__ */ new Set();
1495
+ for (const file of written) {
1496
+ if (file.type !== "chunk") continue;
1497
+ for (const specifier of [...file.imports, ...file.dynamicImports]) {
1498
+ const name = ownFiles.has(specifier) ? null : packageOf(specifier);
1499
+ if (name) reached.add(name);
1500
+ }
1501
+ for (const [, specifier] of file.code.matchAll(REQUIRE_CALL)) {
1502
+ const name = packageOf(specifier);
1503
+ if (name && lock[`node_modules/${name}`]) reached.add(name);
1504
+ }
1505
+ }
1506
+ log(` left as files: ${[...reached].sort().join(", ")}`);
1507
+ const keepInstalled = closureOf(lock, reached);
1508
+ const bundled = new Set(byName);
1509
+ const removed = installed.filter((name) => !keepInstalled.has(`node_modules/${name}`) && !bundled.has(name));
1510
+ const licences = licencesOf(modules, [...removed, ...byName]);
1511
+ fs.writeFileSync(path.join(stackDir, "THIRD-PARTY-LICENSES.txt"), licences.text);
1512
+ for (const name of byName) {
1513
+ const dir = path.join(modules, name);
1514
+ const staged = path.join(output, name);
1515
+ fs.mkdirSync(staged, { recursive: true });
1516
+ for (const relative of KEEP_AS_FILES) {
1517
+ const from = path.join(dir, relative);
1518
+ if (fs.existsSync(from)) fs.cpSync(from, path.join(staged, relative), { recursive: true });
1519
+ }
1520
+ for (const file of fs.readdirSync(dir)) {
1521
+ const from = path.join(dir, file);
1522
+ if (/\.json$/.test(file) && file !== "package.json" && isFile(from)) fs.copyFileSync(from, path.join(staged, file));
1523
+ }
1524
+ const manifest = kept.get(name) ?? {};
1525
+ const entries = entriesOf.get(name) ?? /* @__PURE__ */ new Map();
1526
+ for (const [subpath, file] of exportedFiles(dir, manifest)) {
1527
+ if (/\.[cm]?js$/.test(file)) continue;
1528
+ const target = path.join(staged, file);
1529
+ if (!isFile(path.join(dir, file))) continue;
1530
+ fs.mkdirSync(path.dirname(target), { recursive: true });
1531
+ fs.copyFileSync(path.join(dir, file), target);
1532
+ entries.set(subpath, file);
1533
+ }
1534
+ fs.writeFileSync(path.join(staged, "package.json"), `${JSON.stringify(keptManifest(manifest, entries), null, 2)}\n`);
1535
+ }
1536
+ fs.writeFileSync(path.join(output, CHUNKS_DIR, "package.json"), `${JSON.stringify({
1537
+ name: "ph-stack-bundle",
1538
+ private: true,
1539
+ type: "module"
1540
+ })}\n`);
1541
+ for (const name of [...removed, ...byName]) fs.rmSync(path.join(modules, name), {
1542
+ recursive: true,
1543
+ force: true
1544
+ });
1545
+ fs.rmSync(path.join(modules, ".bin"), {
1546
+ recursive: true,
1547
+ force: true
1548
+ });
1549
+ for (const entry of fs.readdirSync(modules, { withFileTypes: true })) {
1550
+ if (!entry.name.startsWith("@") || !entry.isDirectory()) continue;
1551
+ const scope = path.join(modules, entry.name);
1552
+ if (fs.readdirSync(scope).length === 0) fs.rmdirSync(scope);
1553
+ }
1554
+ fs.cpSync(output, modules, { recursive: true });
1555
+ fs.rmSync(output, {
1556
+ recursive: true,
1557
+ force: true
1558
+ });
1559
+ const chunks = written.filter((file) => file.type === "chunk").length;
1560
+ log(` bundled into ${chunks} files; ${removed.length} packages folded in, ${reached.size} left as files, licences of ${licences.packages} written`);
1561
+ return {
1562
+ chunks,
1563
+ removedPackages: removed.length,
1564
+ keptPackages: keepInstalled.size
1565
+ };
1566
+ }
1567
+ //#endregion
1568
+ export { appJsonSchema as C, DEFAULT_SHELL_CRATE_VERSION as S, loadAppJson as T, projectShell as _, shellEnv as a, pruneStack as b, fetchNodeSidecar as c, resolveTauriCommand as d, runTauriIcon as f, SHELL_DIR as g, ICON_SOURCE as h, resolveShell as i, nodeSidecarTarget as l, tauriSpawn as m, launchShell as n, tauriConfigPatch as o, tauriBundlesForHost as p, resolvePhCliEntry as r, detectToolchain as s, bundleBackend as t, preflightOrThrow as u, bundleStack as v, appSlug as w, APP_JSON_FILE as x, pluginPackagesOf as y };
1569
+
1570
+ //# sourceMappingURL=bundle-backend-CvUS8-oc.mjs.map