@powerhousedao/desktop 6.2.3-dev.104 → 6.2.3-dev.106

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 @@
1
+ {"version":3,"file":"bundle-backend-D28j6a5_.mjs","names":["packageOf"],"sources":["../src/release.ts","../src/app-json.ts","../src/bundle-stack.ts","../src/shell-project.ts","../src/shell-toolchain.ts","../src/shell.ts","../src/bundle-backend.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AppJsonUpdates } from \"./app-json.js\";\n\n/**\n * What a build of an app with updates leaves for its release (app.json\n * `updates`): under `<shell>/target/release/bundle/release/`, every installer\n * it made, under a name no host rewrites, and the feed file that tells the\n * running apps of this system about them. Attach every file in that folder to\n * the release and the apps find it.\n *\n * One feed file per system and processor (`latest-linux-x86_64.json`), not one\n * for the whole release: each system builds in its own job, and a job that\n * fails then costs its own users the update and nobody else's. The app asks\n * for its own file by name (FEED_FILE_TEMPLATE).\n */\n\n/** Under the bundle folder: this build's release files. */\nexport const RELEASE_DIR = \"release\";\n\n/** The feed file a build writes for its system and processor. */\nexport function feedFileName(os: string, arch: string): string {\n return `latest-${os}-${arch}.json`;\n}\n\n/** That name in a feed address: the updater fills in the running app's own\n * system (linux, darwin, windows) and processor (x86_64, aarch64, …). */\nexport const FEED_FILE_TEMPLATE = \"latest-{{target}}-{{arch}}.json\";\n\n/** The updater's names for the systems and processors Node reports. */\nconst UPDATER_OS: Partial<Record<NodeJS.Platform, string>> = {\n linux: \"linux\",\n darwin: \"darwin\",\n win32: \"windows\",\n};\nconst UPDATER_ARCH: Partial<Record<string, string>> = {\n x64: \"x86_64\",\n arm64: \"aarch64\",\n ia32: \"i686\",\n arm: \"armv7\",\n};\n\n/** A file a build makes: where tauri puts it, and, when a running app can\n * install it, the updater's name for that way of installing. */\ntype Artifact = { dir: string; suffix: string; installer?: string };\nconst ARTIFACTS: Partial<Record<NodeJS.Platform, Artifact[]>> = {\n linux: [\n { dir: \"deb\", suffix: \".deb\", installer: \"deb\" },\n { dir: \"rpm\", suffix: \".rpm\", installer: \"rpm\" },\n { dir: \"appimage\", suffix: \".AppImage\", installer: \"appimage\" },\n ],\n win32: [{ dir: \"nsis\", suffix: \"-setup.exe\", installer: \"nsis\" }],\n darwin: [\n // The disk image is what a person downloads; a running app takes the\n // archive of the bundle.\n { dir: \"dmg\", suffix: \".dmg\" },\n { dir: \"macos\", suffix: \".app.tar.gz\", installer: \"app\" },\n ],\n};\n\n/** A file name every host keeps as it is: GitHub rewrites a space (and most\n * punctuation) in a release file's name to a dot, and a feed that names the\n * file as it was built would then point at nothing. */\nexport function releaseFileName(name: string): string {\n return name.replace(/[^A-Za-z0-9._-]/g, \".\");\n}\n\n/**\n * Where a release's files are downloaded from: PH_DESKTOP_RELEASE_URL when\n * set, else the GitHub release of app.json's `updates.github` under this\n * build's tag (the tag a workflow runs for, else `v<version>`). null when\n * neither says: the build then writes no feed file.\n */\nexport function releaseBaseUrl(\n updates: AppJsonUpdates,\n version: string | undefined,\n env: Record<string, string | undefined>,\n): string | null {\n const given = env.PH_DESKTOP_RELEASE_URL?.trim();\n if (given) {\n let url: URL | null = null;\n try {\n url = new URL(given);\n } catch {\n // reported below\n }\n if (url?.protocol !== \"https:\") {\n throw new Error(\n `PH_DESKTOP_RELEASE_URL must be the https address the release's files are downloaded from, not \"${given}\".`,\n );\n }\n return given.replace(/\\/+$/, \"\");\n }\n if (!updates.github) return null;\n const tag =\n env.GITHUB_REF_TYPE === \"tag\" && env.GITHUB_REF_NAME\n ? env.GITHUB_REF_NAME\n : `v${version ?? \"0.1.0\"}`;\n return `https://github.com/${updates.github}/releases/download/${encodeURIComponent(tag)}`;\n}\n\nexport interface CollectReleaseInput {\n /** `<shell>/target/release/bundle`. */\n bundleDir: string;\n productName: string;\n /** The version the installers carry, which is the one that was signed. */\n version: string;\n /** Where the files will be downloaded from; null writes no feed file. */\n baseUrl: string | null;\n /** Only what was written from this time on (ms): an earlier build's files\n * are no part of this release. */\n since?: number;\n platform?: NodeJS.Platform;\n arch?: string;\n now?: Date;\n}\n\nexport interface CollectedRelease {\n dir: string;\n /** Every file in `dir`, the feed included. */\n files: string[];\n /** The feed file's name, when one was written. */\n feed: string | null;\n /** What the feed offers: `linux-x86_64-deb`, … */\n targets: string[];\n /** Installers a running app could take, had they been signed. */\n unsigned: string[];\n}\n\n/** A second's slack: some filesystems keep a file's time to the second. */\nconst TIME_SLACK_MS = 1000;\n\n/** Gathers this build's release files and writes its feed file. */\nexport function collectRelease(input: CollectReleaseInput): CollectedRelease {\n const platform = input.platform ?? process.platform;\n const os = UPDATER_OS[platform];\n const arch = UPDATER_ARCH[input.arch ?? process.arch];\n const dir = path.join(input.bundleDir, RELEASE_DIR);\n fs.rmSync(dir, { recursive: true, force: true });\n fs.mkdirSync(dir, { recursive: true });\n const result: CollectedRelease = {\n dir,\n files: [],\n feed: null,\n targets: [],\n unsigned: [],\n };\n if (!os || !arch) return result;\n\n const fresh = (file: string): boolean =>\n fs.existsSync(file) &&\n (input.since === undefined ||\n fs.statSync(file).mtimeMs >= input.since - TIME_SLACK_MS);\n const platforms: Record<string, { signature: string; url: string }> = {};\n for (const artifact of ARTIFACTS[platform] ?? []) {\n const from = path.join(input.bundleDir, artifact.dir);\n if (!fs.existsSync(from)) continue;\n const built = fs\n .readdirSync(from)\n .filter((name) => name.endsWith(artifact.suffix))\n .map((name) => path.join(from, name))\n .filter((file) => fs.statSync(file).isFile() && fresh(file))\n // The newest last, so it is the one the feed offers.\n .sort((a, b) => fs.statSync(a).mtimeMs - fs.statSync(b).mtimeMs);\n for (const file of built) {\n // tauri names the bundle's archive after the app alone: the release\n // holds one per processor, so it gets the version and processor too.\n const name = releaseFileName(\n artifact.installer === \"app\"\n ? `${input.productName}_${input.version}_${arch}${artifact.suffix}`\n : path.basename(file),\n );\n fs.copyFileSync(\n file,\n path.join(dir, name),\n fs.constants.COPYFILE_FICLONE,\n );\n result.files.push(name);\n if (!artifact.installer) continue;\n const signatureFile = `${file}.sig`;\n if (!fresh(signatureFile)) {\n result.unsigned.push(name);\n continue;\n }\n if (input.baseUrl === null) continue;\n platforms[`${os}-${arch}-${artifact.installer}`] = {\n signature: fs.readFileSync(signatureFile, \"utf8\").trim(),\n url: `${input.baseUrl}/${name}`,\n };\n }\n }\n\n result.targets = Object.keys(platforms).sort();\n if (result.targets.length > 0) {\n const feed = feedFileName(os, arch);\n fs.writeFileSync(\n path.join(dir, feed),\n JSON.stringify(\n {\n version: input.version,\n pub_date: (input.now ?? new Date()).toISOString(),\n platforms,\n },\n null,\n 2,\n ) + \"\\n\",\n );\n result.feed = feed;\n result.files.push(feed);\n }\n return result;\n}\n\n/** What a build says about the release files it gathered. */\nexport function releaseReport(\n release: CollectedRelease,\n releaseUrl: string | null,\n): string[] {\n if (release.files.length === 0) {\n return [\"no release files: the build made no installer.\"];\n }\n const lines = [`release files in ${release.dir}:`];\n for (const file of release.files) lines.push(` ${file}`);\n for (const file of release.unsigned) {\n lines.push(`${file} has no signature, so the feed does not offer it.`);\n }\n if (release.feed) {\n lines.push(\n `${release.feed} offers ${release.targets.join(\", \")} from ${releaseUrl}: ` +\n `attach every file in that folder to the release there.`,\n );\n } else if (releaseUrl === null) {\n lines.push(\n \"no feed file: set PH_DESKTOP_RELEASE_URL to the address the release's \" +\n \"files are downloaded from (app.json names its own feed, not a GitHub repository).\",\n );\n }\n return lines;\n}\n","import type { PHBackground } from \"@powerhousedao/shared/clis\";\nimport { validateBackground } from \"@powerhousedao/shared/connect\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport { FEED_FILE_TEMPLATE } from \"./release.js\";\n\n/**\n * `hosts/desktop/app.json` — the builder's desktop identity (phase 7, mode 1:\n * the builder ships under THEIR identity without writing Rust). It is the ONE\n * file a builder edits; `shell-project.ts` projects it into a generated\n * `tauri-shell/` that depends on the published `ph-desktop-shell` crate. Every\n * field validates strictly so a typo fails with the field named, not silently.\n */\n\nconst identifierSchema = z\n .string()\n .min(1)\n .regex(\n /^[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)+$/,\n \"identifier must be reverse-DNS (e.g. com.acme.app): dot-separated alphanumeric segments\",\n );\n\nconst windowSchema = z\n .strictObject({\n title: z.string().min(1).optional(),\n width: z.number().int().positive().optional(),\n height: z.number().int().positive().optional(),\n resizable: z.boolean().optional(),\n /** Smallest size the window can be dragged to (logical pixels). */\n minWidth: z.number().int().positive().optional(),\n minHeight: z.number().int().positive().optional(),\n })\n .optional();\n\nconst cssColorSchema = z\n .string()\n .regex(\n /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/,\n \"use a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa)\",\n );\n\n/** The loading page's colors. */\nconst loadingColorsSchema = z.strictObject({\n /** Page background (default #0f1115). */\n background: cssColorSchema.nullable().optional(),\n /** Status text color (default #e6e8eb). */\n color: cssColorSchema.nullable().optional(),\n /** The pulsing status dot (default #4ade80). */\n accent: cssColorSchema.nullable().optional(),\n});\n\n/** The loading page's look, so the window opens in the app's own colors\n * instead of the default dark page. Every field is optional, and `null`\n * means the default (the scaffold lists the fields that way). */\nconst loadingSchema = loadingColorsSchema\n .extend({\n /** Status line under the art (default \"Starting <productName>…\"). */\n message: z.string().min(1).nullable().optional(),\n /** Colors for `prefers-color-scheme: dark`; without it the page keeps\n * the light colors in both schemes. */\n dark: loadingColorsSchema.nullable().optional(),\n /** Deprecated: a decoration pinned to the bottom-right corner, relative\n * to app.json, with `artDark` its dark-scheme counterpart. Superseded by\n * the top-level `background`, which ignores these when set. */\n art: z.string().min(1).nullable().optional(),\n artDark: z.string().min(1).nullable().optional(),\n })\n .nullable()\n .optional();\n\n// The loading page's background: the same `PHBackground` as Connect's\n// `connect.branding.homeBackground` (shared/clis/types.ts), so the scaffold\n// can copy one into the other and both pages place their art alike. Paths\n// are relative to app.json; URLs and data URIs pass through.\nconst imageRefSchema = z.string().min(1);\nconst schemedImageSchema = z.union([\n imageRefSchema,\n z.strictObject({\n light: imageRefSchema,\n dark: imageRefSchema.nullable().optional(),\n }),\n]);\nconst lengthSchema = z\n .union([z.number(), z.string().min(1)])\n .nullable()\n .optional();\nconst edgesSchema = z\n .strictObject({\n top: lengthSchema,\n right: lengthSchema,\n bottom: lengthSchema,\n left: lengthSchema,\n })\n .nullable()\n .optional();\nconst backgroundLayerSchema = z.strictObject({\n src: schemedImageSchema,\n position: edgesSchema,\n width: lengthSchema,\n height: lengthSchema,\n minWidth: lengthSchema,\n minHeight: lengthSchema,\n maxWidth: lengthSchema,\n maxHeight: lengthSchema,\n opacity: z.number().min(0).max(1).nullable().optional(),\n fade: edgesSchema,\n});\nconst backgroundSchema = z\n .union([\n imageRefSchema,\n z.strictObject({\n color: z\n .union([\n z.string().min(1),\n z.strictObject({\n light: z.string().min(1),\n dark: z.string().min(1).nullable().optional(),\n }),\n ])\n .nullable()\n .optional(),\n layers: z.array(backgroundLayerSchema),\n }),\n ])\n .superRefine((background: PHBackground, ctx) => {\n for (const problem of validateBackground(background, \"background\")) {\n ctx.addIssue({ code: \"custom\", message: problem });\n }\n })\n .nullable()\n .optional();\n\nconst fileAssociationSchema = z.strictObject({\n /** Extensions WITHOUT the leading dot (\"phd\", not \".phd\"). */\n ext: z.array(z.string().min(1).regex(/^[^.]/, \"drop the leading dot\")).min(1),\n name: z.string().min(1),\n description: z.string().optional(),\n mimeType: z.string().optional(),\n});\n\n/** Where the generated Cargo.toml resolves `ph-desktop-shell` from. Default\n * (omitted) = the published crates.io version. */\nconst shellSourceSchema = z\n .strictObject({\n /** Local checkout for shell development (the lab points here). */\n path: z.string().min(1).optional(),\n /** Git source, pinned to a tag/rev, for pre-publication consumption. */\n git: z.string().min(1).optional(),\n tag: z.string().min(1).optional(),\n rev: z.string().min(1).optional(),\n /** crates.io version requirement (default DEFAULT_SHELL_CRATE_VERSION). */\n version: z.string().min(1).optional(),\n })\n .refine((s) => !(s.path && s.git), {\n message: \"shell.source: set path OR git, not both\",\n })\n .optional();\n\n/** What is wrong with a release key, or null. The public half is base64 of a\n * minisign public key, as `tauri signer generate` writes its .pub file; the\n * private half looks alike at a glance and must never land in app.json. */\nfunction pubkeyProblem(value: string): string | null {\n const text = Buffer.from(value.trim(), \"base64\").toString(\"utf8\");\n if (/secret key/i.test(text)) {\n return \"this is the PRIVATE key: put the public one here (the .pub file) and keep the private one in your CI secrets\";\n }\n if (!/^untrusted comment: minisign public key/i.test(text)) {\n return \"not an update signing key: paste the content of the .pub file `tauri signer generate` writes\";\n }\n return null;\n}\n\n/** An update feed's address: https, as a release build asks nothing else. */\nconst feedUrlSchema = z.string().refine((value) => {\n try {\n return new URL(value).protocol === \"https:\";\n } catch {\n return false;\n }\n}, \"an update feed must be an https address\");\n\n/** Updates, for an app that wants them: where it asks for a newer version and\n * the key its releases are signed with. The window then offers each newer\n * release, downloads it, checks its signature and installs it. Omitted or\n * null: the app never asks, and is installed by hand as before. */\nconst updatesSchema = z\n .strictObject({\n /** The GitHub repository whose releases carry the app (\"owner/name\"): the\n * app asks its latest release for the feed file a build of its system\n * wrote (release.ts). */\n github: z\n .string()\n .regex(/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/, 'use \"owner/repository\"')\n .optional(),\n /** Or the feed's own addresses, asked in order. `{{target}}` and\n * `{{arch}}` in one stand for the running app's system and processor,\n * as in the feed file's name: `latest-{{target}}-{{arch}}.json`. */\n endpoints: z.array(feedUrlSchema).min(1).optional(),\n /** The public key the releases are signed with: the content of the .pub\n * file `tauri signer generate` writes. The private key signs each build\n * (TAURI_SIGNING_PRIVATE_KEY) and stays out of the repository. */\n pubkey: z\n .string()\n .min(1)\n .superRefine((value, ctx) => {\n const problem = pubkeyProblem(value);\n if (problem) ctx.addIssue({ code: \"custom\", message: problem });\n }),\n })\n .refine((u) => Boolean(u.github) !== Boolean(u.endpoints), {\n message: \"updates: set github OR endpoints\",\n })\n .nullable()\n .optional();\n\nexport const appJsonSchema = z.strictObject({\n identifier: identifierSchema,\n productName: z.string().min(1),\n /** Ask who is using the app before anything runs: the stack then starts for\n * that identity, with its own folder and as its admin. Off, the stack starts\n * with the window, in one store. */\n signIn: z.boolean().nullable().optional(),\n /** Single source image (square PNG, 1024×1024 recommended); the icon set\n * for every platform is generated from it via `tauri icon`. */\n icon: z.string().min(1),\n /** The loading page's background: images positioned and sized over a\n * page colour (`{ color, layers }`), or one image pinned bottom-right.\n * The status line stays centred above them. `ph generate desktop-shell`\n * copies Connect's `connect.branding.homeBackground` here. null or\n * omitted: the app icon (or `splash`) above the status line. */\n background: backgroundSchema,\n /** Deprecated in favour of `background`: a wide splash image shown above\n * the status line instead of the square icon. Relative to this file. */\n splash: z.string().min(1).nullable().optional(),\n /** Deprecated with `splash`: its `prefers-color-scheme: dark` variant. */\n splashDark: z.string().min(1).nullable().optional(),\n loading: loadingSchema,\n window: windowSchema,\n fileAssociations: z.array(fileAssociationSchema).optional(),\n updates: updatesSchema,\n shell: shellSourceSchema,\n});\n\nexport type AppJson = z.infer<typeof appJsonSchema>;\nexport type AppJsonShellSource = NonNullable<AppJson[\"shell\"]>;\nexport type AppJsonUpdates = NonNullable<AppJson[\"updates\"]>;\n\n/** Where an app with updates asks for a newer version. */\nexport function updateEndpoints(updates: AppJsonUpdates): string[] {\n return (\n updates.endpoints ?? [\n `https://github.com/${updates.github}/releases/latest/download/${FEED_FILE_TEMPLATE}`,\n ]\n );\n}\n\n/** Default crates.io version requirement for the shell crate (D7.b: the flip\n * to crates.io default once published — the crate is live). A floor, not just\n * a series: 0.1.0 can't run a stack from ph-run and 0.1.1 has no updater (an\n * app with `updates` would build and never ask), and a Cargo.lock that still\n * holds one of them satisfies \"0.1\", so a builder's lock would keep it\n * forever. The 0.1.x-dev.N releases sort below 0.1.x and never match either. */\nexport const DEFAULT_SHELL_CRATE_VERSION = \"0.1.2\";\n\nexport const APP_JSON_FILE = \"app.json\";\n\n/** Read + validate hosts/<host>/app.json. Throws with the field named on a\n * bad value, and a clear message when the file is absent. */\nexport function loadAppJson(hostDir: string): AppJson {\n const file = path.join(hostDir, APP_JSON_FILE);\n if (!fs.existsSync(file)) {\n throw new Error(\n `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.`,\n );\n }\n let raw: unknown;\n try {\n raw = JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch (error) {\n throw new Error(`${file}: not valid JSON — ${String(error)}`, {\n cause: error,\n });\n }\n const result = appJsonSchema.safeParse(raw);\n if (!result.success) {\n const issues = result.error.issues\n .map((i) => ` ${i.path.join(\".\") || \"(root)\"}: ${i.message}`)\n .join(\"\\n\");\n throw new Error(`${file} is invalid:\\n${issues}`);\n }\n return result.data;\n}\n\n/** A filesystem/crate-safe slug of the product name — the generated binary\n * and Cargo package name. Falls back to the identifier's last segment. */\nexport function appSlug(app: AppJson): string {\n const fromName = app.productName\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n if (fromName) return fromName;\n const seg = app.identifier.split(\".\").pop() ?? \"app\";\n return seg.toLowerCase().replace(/[^a-z0-9]+/g, \"-\");\n}\n","import { spawnSync } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n normalizePluginEntries,\n type PluginEntryData,\n} from \"@powerhousedao/host-core\";\n\n/**\n * P6.3 — stage the shippable STACK into the shell project: everything the\n * installed app needs to run `ph run desktop` with no environment at all\n * (D6.c). The shell's resources map `../dist-stack` → `stack`, and its\n * uniform-runners mode falls back to `resources/stack` when the env pair is\n * absent. Layout:\n *\n * dist-stack/\n * hosts/ the project's host files\n * agents/ when present\n * powerhouse.config.json\n * package.json minimal, names the project\n * dist/ the package's build (ph build)\n * .ph/connect-build/dist/ the BUILT Connect (ph run connect build)\n * node_modules/ vendored @powerhousedao/ph-run (hoisted,\n * real files — computed-specifier imports and\n * PGlite wasm forbid bundling)\n */\nconst CONNECT_BUILD_DIR = path.join(\".ph\", \"connect-build\", \"dist\");\nconst BROWSER_ONLY_IN_DIST = [\n \"__react__\",\n \"__reactor_worker__\",\n \"__vendor__\",\n \"assets\",\n \"browser\",\n];\n\n/** The package a module specifier belongs to. */\nfunction packageOf(specifier: string): string {\n const parts = specifier.split(\"/\");\n return parts.slice(0, specifier.startsWith(\"@\") ? 2 : 1).join(\"/\");\n}\n\n/** The packages to ship for a host's plugins. One that doesn't resolve is a\n * browser built-in of Connect's, already in the built app, and resolves no\n * better in the stack (host-core's plugins-resolve). */\nexport function pluginPackagesOf(\n entries: readonly PluginEntryData[],\n where: string,\n resolves: (specifier: string) => boolean,\n): string[] {\n return normalizePluginEntries(entries, where)\n .filter((entry) => entry.enabled && !entry.module.startsWith(\".\"))\n .filter((entry) => resolves(entry.module))\n .map((entry) => packageOf(entry.module));\n}\n\n/** Where a stack keeps the OAuth clients its config names. */\nconst OAUTH_CLIENTS_DIR = \"oauth\";\n/** Where a stack keeps the AI demo key its config names. */\nconst AI_DIR = \"ai\";\n\ninterface StagedConfig {\n ai?: { demoKeyFile?: string };\n workflows?: {\n oauthApps?: { id?: string; clients?: { desktop?: string; web?: string } }[];\n };\n}\n\n/**\n * The project's config, with its OAuth clients made the app's own. They sit\n * outside the project, so a packaged app would find nothing at those paths. A\n * desktop client ships with the app: it can't keep its secret, so sign-ins\n * always use PKCE. A web client belongs to a server and never leaves the machine.\n */\nfunction stageConfig(\n projectRoot: string,\n stackDir: string,\n log: (message: string) => void,\n): void {\n const source = path.join(projectRoot, \"powerhouse.config.json\");\n if (!fs.existsSync(source)) return;\n const config = JSON.parse(fs.readFileSync(source, \"utf8\")) as StagedConfig;\n // Whoever has the installer can read this. Without the file it ships no key,\n // and the app offers none.\n if (config.ai?.demoKeyFile) {\n const from = path.resolve(projectRoot, config.ai.demoKeyFile);\n delete config.ai.demoKeyFile;\n if (fs.existsSync(from)) {\n const file = path.basename(from);\n fs.mkdirSync(path.join(stackDir, AI_DIR), { recursive: true });\n fs.copyFileSync(from, path.join(stackDir, AI_DIR, file));\n config.ai.demoKeyFile = `./${AI_DIR}/${file}`;\n log(\" AI demo key staged\");\n } else {\n log(\" no AI demo key: this build won't offer one\");\n }\n }\n for (const app of config.workflows?.oauthApps ?? []) {\n if (!app.clients) continue;\n const desktop = app.clients.desktop;\n const from = desktop && path.resolve(projectRoot, desktop);\n app.clients = {};\n if (!from || !fs.existsSync(from)) {\n log(` oauth app ${app.id}: no desktop client, so it can't sign in`);\n continue;\n }\n const file = path.basename(from);\n fs.mkdirSync(path.join(stackDir, OAUTH_CLIENTS_DIR), { recursive: true });\n fs.copyFileSync(from, path.join(stackDir, OAUTH_CLIENTS_DIR, file));\n app.clients.desktop = `./${OAUTH_CLIENTS_DIR}/${file}`;\n log(` oauth app ${app.id}: desktop client staged`);\n }\n fs.writeFileSync(\n path.join(stackDir, \"powerhouse.config.json\"),\n `${JSON.stringify(config, null, 2)}\n`,\n );\n}\n\n/** What runs a stack: `ph run` without the tools that build one, which is\n * most of ph-cli's dependencies. */\nconst RUN_PACKAGE = \"@powerhousedao/ph-run\";\n\nexport interface BundleStackOptions {\n projectRoot: string;\n shellProjectDir: string;\n /** Vendor the runtime packages (slow). Skipped when false — an existing\n * vendored tree is left in place. */\n vendor?: boolean;\n /** The version/tag of ph-run to vendor, which ph-cli publishes alongside.\n * Default: the ph-cli the project has installed, else \"dev\". Until a nightly\n * carries it, pass `phCliSpec` with a locally packed tarball instead. */\n phCliVersion?: string;\n /** Overrides ph-run's install spec entirely (e.g. a `pnpm pack` tarball path\n * for a not-yet-published build). */\n phCliSpec?: string;\n /** A directory of `pnpm pack` tarballs (env PH_DESKTOP_LOCAL_PACKAGES).\n * Each replaces its package everywhere in the vendored tree: a packed\n * ph-run alone would still pull its dependencies, at the same version\n * number, from the registry. `pnpm pack:desktop-stack` in the monorepo\n * packs the set ph-run and host-core need. */\n localPackagesDir?: string;\n /** Packages the hosts' plugins come from. The stack resolves them from its\n * own node_modules, and ph-run brings only what it depends on. */\n plugins?: readonly string[];\n /** Files the hosts name by a project path, such as drive icons, staged at\n * the same paths: at run time the stack is the project root. */\n projectFiles?: readonly string[];\n /** The connect member's port — written into the stack's shell.json so the\n * shell knows where to probe/navigate with no environment at all. */\n connectPort?: number;\n /** Absolute paths to skip when staging `hosts/` — in mode 1 the generated\n * shell dir sits under `hosts/` and must not be copied into itself. */\n excludeDirs?: string[];\n logger?: (message: string) => void;\n}\n\nexport interface BundleStackResult {\n stackDir: string;\n vendored: boolean;\n}\n\nfunction copyIfExists(from: string, to: string): boolean {\n if (!fs.existsSync(from)) return false;\n fs.cpSync(from, to, { recursive: true });\n return true;\n}\n\n/** The version of a package the project has installed, if it has. */\nexport function installedVersion(\n projectRoot: string,\n pkg: string,\n): string | undefined {\n try {\n const manifest = JSON.parse(\n fs.readFileSync(\n path.join(projectRoot, \"node_modules\", pkg, \"package.json\"),\n \"utf8\",\n ),\n ) as { version?: string };\n return manifest.version;\n } catch {\n return undefined;\n }\n}\n\ntype VersionOptions = Pick<\n BundleStackOptions,\n \"projectRoot\" | \"phCliVersion\" | \"phCliSpec\" | \"plugins\"\n>;\n\n/** The ph-run a stack runs: what the project was built and tested with, not\n * whatever a tag points at when the build runs. It comes with ph-cli, at its\n * version. */\nfunction runVersion(options: VersionOptions): string {\n return (\n options.phCliVersion ??\n installedVersion(options.projectRoot, \"@powerhousedao/ph-cli\") ??\n \"dev\"\n );\n}\n\n/** What a registry vendoring installs. host-core rides along with ph-run, as\n * host files resolve runner modules (the generic compound) from the stack's\n * own node_modules. Each package comes at the version the project has, and a\n * version the host names is used for all of them. */\nexport function registrySpecs(options: VersionOptions): string[] {\n const version = runVersion(options);\n const versionOf = (pkg: string) =>\n options.phCliVersion ??\n installedVersion(options.projectRoot, pkg) ??\n version;\n return [\n options.phCliSpec ?? `${RUN_PACKAGE}@${version}`,\n ...[\"@powerhousedao/host-core\", ...(options.plugins ?? [])].map(\n (pkg) => `${pkg}@${versionOf(pkg)}`,\n ),\n ];\n}\n\n/** Stages each project file that exists, at its project path. One outside\n * the project has no place in the stack. */\nfunction stageProjectFiles(\n projectRoot: string,\n stackDir: string,\n files: readonly string[],\n): number {\n let staged = 0;\n for (const file of new Set(files)) {\n const from = path.resolve(projectRoot, file);\n const relative = path.relative(projectRoot, from);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) continue;\n if (!fs.statSync(from, { throwIfNoEntry: false })?.isFile()) continue;\n const to = path.join(stackDir, relative);\n fs.mkdirSync(path.dirname(to), { recursive: true });\n fs.copyFileSync(from, to);\n staged++;\n }\n return staged;\n}\n\n/**\n * Recursively copy `src` → `dest`, skipping any path in `excludes`. Unlike\n * fs.cpSync this tolerates `dest` living INSIDE `src`: in mode 1 the generated\n * shell (and its `dist-stack`) sits under `hosts/<desktop>/`, so staging the\n * project's `hosts/` straight into the shell would be a copy-into-self that\n * cpSync rejects outright. Excluding the shell subtree both avoids that and\n * keeps the crate + node sidecar out of the shippable stack.\n */\nfunction copyDirFiltered(\n src: string,\n dest: string,\n excludes: string[],\n): boolean {\n if (!fs.existsSync(src)) return false;\n const skip = new Set(excludes.map((e) => path.resolve(e)));\n const walk = (s: string, d: string): void => {\n if (skip.has(path.resolve(s))) return;\n const stat = fs.statSync(s);\n if (stat.isDirectory()) {\n fs.mkdirSync(d, { recursive: true });\n for (const entry of fs.readdirSync(s)) {\n walk(path.join(s, entry), path.join(d, entry));\n }\n } else {\n fs.copyFileSync(s, d);\n }\n };\n walk(src, dest);\n return true;\n}\n\n/** The npm spec of each tarball in `dir`, by the package name inside it. */\nexport function readLocalPackages(dir: string): Record<string, string> {\n const root = path.resolve(dir);\n const tarballs = fs.existsSync(root)\n ? fs.readdirSync(root).filter((f) => f.endsWith(\".tgz\"))\n : [];\n if (tarballs.length === 0) {\n throw new Error(`bundle-stack: no package tarballs (*.tgz) in ${root}`);\n }\n const specs: Record<string, string> = {};\n for (const file of tarballs.sort()) {\n const tarball = path.join(root, file);\n // By name from its folder: GNU tar reads the `C:` of a Windows path as a host.\n const manifest = spawnSync(\"tar\", [\"-xzOf\", file, \"package/package.json\"], {\n cwd: root,\n encoding: \"utf8\",\n windowsHide: true,\n });\n if (manifest.status !== 0) {\n throw new Error(\n `bundle-stack: ${tarball} has no package/package.json: ${manifest.stderr}`,\n );\n }\n const { name } = JSON.parse(manifest.stdout) as { name: string };\n if (specs[name]) {\n throw new Error(\n `bundle-stack: two tarballs for ${name} in ${root} (a stale pack?): ` +\n `${specs[name].slice(\"file:\".length)} and ${tarball}`,\n );\n }\n specs[name] = `file:${tarball}`;\n }\n return specs;\n}\n\nexport interface StackManifestOptions {\n name: string;\n /** The registry version for what `local` lacks. */\n version: string;\n phCliSpec?: string;\n /** Package name → spec, from readLocalPackages. */\n local?: Record<string, string>;\n /** Packages to depend on besides ph-run and host-core. */\n plugins?: readonly string[];\n}\n\n/**\n * The staged stack's package.json. With local packages, every one is an\n * override (so transitive dependents get it too) and the direct dependencies\n * name the same spec: npm rejects an override that contradicts one.\n */\nexport function stackManifest(options: StackManifestOptions) {\n const local = options.local ?? {};\n const spec = (pkg: string, fallback: string) => local[pkg] ?? fallback;\n const plugins = (options.plugins ?? []).map((pkg): [string, string] => [\n pkg,\n spec(pkg, options.version),\n ]);\n return {\n name: options.name,\n private: true,\n type: \"module\",\n dependencies: {\n [RUN_PACKAGE]: spec(RUN_PACKAGE, options.phCliSpec ?? options.version),\n \"@powerhousedao/host-core\": spec(\n \"@powerhousedao/host-core\",\n options.version,\n ),\n ...Object.fromEntries(plugins),\n },\n ...(Object.keys(local).length > 0 ? { overrides: local } : {}),\n };\n}\n\n/** A vendored tree installed from local tarballs: the same version numbers\n * as the registry's, so npm would take either for the other. */\nfunction vendoredFromLocal(stackDir: string): boolean {\n const lock = path.join(stackDir, \"package-lock.json\");\n return (\n fs.existsSync(lock) &&\n fs.readFileSync(lock, \"utf8\").includes('\"resolved\": \"file:')\n );\n}\n\n/** Types and source maps, which nothing reads at runtime. */\nconst UNREAD_FILE = /\\.(d\\.[cm]?ts|map)$/i;\nconst TEST_FILE = /\\.(test|spec)\\.[cm]?[jt]sx?$/;\n/** Licences stay, as the packages' terms ask. */\nconst PACKAGE_NOTES = /^(readme|changelog|history)(\\..*)?$/i;\n\n/**\n * Removes what a running app never reads. Windows creates and scans each file\n * on its own, so these, over half the stack, were over half the install.\n *\n * @returns How many files went\n */\nexport function pruneStack(dir: string, inPackages = false): number {\n let removed = 0;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === \"__tests__\") {\n removed += fs\n .readdirSync(full, { recursive: true, withFileTypes: true })\n .filter((file) => file.isFile()).length;\n fs.rmSync(full, { recursive: true, force: true });\n continue;\n }\n removed += pruneStack(full, inPackages || entry.name === \"node_modules\");\n if (fs.readdirSync(full).length === 0) fs.rmdirSync(full);\n } else if (\n entry.isFile() &&\n (UNREAD_FILE.test(entry.name) ||\n TEST_FILE.test(entry.name) ||\n (inPackages && PACKAGE_NOTES.test(entry.name)))\n ) {\n fs.rmSync(full);\n removed++;\n }\n }\n return removed;\n}\n\nexport function bundleStack(options: BundleStackOptions): BundleStackResult {\n const log = options.logger ?? console.log;\n const stackDir = path.join(options.shellProjectDir, \"dist-stack\");\n\n // Fresh staging for project files; the vendored node_modules survives\n // unless re-vendoring (it is by far the slowest part).\n for (const entry of [\n \"hosts\",\n \"agents\",\n \"dist\",\n \".ph\",\n OAUTH_CLIENTS_DIR,\n AI_DIR,\n \"powerhouse.config.json\",\n \"package.json\",\n ]) {\n fs.rmSync(path.join(stackDir, entry), { recursive: true, force: true });\n }\n fs.mkdirSync(stackDir, { recursive: true });\n\n // hosts/ gets the filtered copy — the generated shell subtree lives under\n // it and must not be copied into itself (nor shipped in the stack).\n const hostsStaged = copyDirFiltered(\n path.join(options.projectRoot, \"hosts\"),\n path.join(stackDir, \"hosts\"),\n options.excludeDirs ?? [],\n );\n log(` hosts/ ${hostsStaged ? \"staged\" : \"absent — skipped\"}`);\n // The local key's process: the stack holds no @powerhousedao/desktop, and\n // this file needs nothing from it.\n const localKey = fileURLToPath(\n new URL(\"./local-key/local-key.mjs\", import.meta.url),\n );\n if (fs.existsSync(localKey)) {\n fs.copyFileSync(localKey, path.join(stackDir, \"local-key.mjs\"));\n }\n // The built Connect at the path the stack's connect runner serves by default.\n for (const dir of [\"agents\", \"dist\", CONNECT_BUILD_DIR]) {\n const copied = copyIfExists(\n path.join(options.projectRoot, dir),\n path.join(stackDir, dir),\n );\n log(` ${dir}/ ${copied ? \"staged\" : \"absent — skipped\"}`);\n }\n // The window gets the build staged above. A server reads dist/node, and a\n // project that once built Connect into dist still has that build there.\n for (const dir of BROWSER_ONLY_IN_DIST) {\n fs.rmSync(path.join(stackDir, \"dist\", dir), {\n recursive: true,\n force: true,\n });\n }\n\n // Inside the package there is no nested shell — the shell IS the window —\n // so the staged desktop host runs on the generic compound. Rewrite the\n // runner.module projection in the STAGED copy only.\n const stagedDesktopHost = path.join(stackDir, \"hosts\", \"desktop\", \"host.js\");\n if (fs.existsSync(stagedDesktopHost)) {\n const source = fs.readFileSync(stagedDesktopHost, \"utf8\");\n if (source.includes(\"@powerhousedao/desktop/runner\")) {\n fs.writeFileSync(\n stagedDesktopHost,\n \"// STAGED COPY (bundle-stack): runner.module rewritten to the generic\\n\" +\n \"// compound — the packaged shell is the window; there is no nested shell.\\n\" +\n source.replace(\n /@powerhousedao\\/desktop\\/runner/g,\n \"@powerhousedao/host-core/runners/compound\",\n ),\n );\n log(\n \" hosts/desktop/host.js: runner rewritten to the generic compound (staged copy)\",\n );\n }\n }\n stageConfig(options.projectRoot, stackDir, log);\n if (options.projectFiles && options.projectFiles.length > 0) {\n const staged = stageProjectFiles(\n options.projectRoot,\n stackDir,\n options.projectFiles,\n );\n log(\n ` ${staged} of ${options.projectFiles.length} files the hosts name staged`,\n );\n }\n\n // shell.json: the stack's contract with the shell. The no-env (packaged)\n // path has nobody to set PH_WIN_CONNECT_PORT, so the shell reads the probe\n // and window port from here.\n if (typeof options.connectPort === \"number\") {\n fs.writeFileSync(\n path.join(stackDir, \"shell.json\"),\n `${JSON.stringify({ connectPort: options.connectPort }, null, 2)}\\n`,\n );\n log(` shell.json: connectPort ${options.connectPort}`);\n }\n\n // A minimal manifest: names the project (lock identity) and depends on\n // ph-run so the vendored tree resolves exactly like a real install.\n const sourcePkg = JSON.parse(\n fs.readFileSync(path.join(options.projectRoot, \"package.json\"), \"utf8\"),\n ) as { name?: string; version?: string; exports?: unknown };\n const version = runVersion(options);\n const name = sourcePkg.name ?? \"powerhouse-desktop-stack\";\n // The stack is the project's own package to the reactor, which loads it by\n // path: its pieces take this version, and workers find its models through\n // these exports. Without them the pieces are dropped, and a workflow pinned\n // to one quietly runs whatever the registry has instead.\n const project = {\n ...(sourcePkg.version ? { version: sourcePkg.version } : {}),\n ...(sourcePkg.exports ? { exports: sourcePkg.exports } : {}),\n };\n const vendor = options.vendor !== false;\n const local = options.localPackagesDir\n ? readLocalPackages(options.localPackagesDir)\n : undefined;\n // Switching between local and registry packages starts the tree afresh:\n // their version numbers match, so npm would keep whichever it has.\n if (vendor && (local || vendoredFromLocal(stackDir))) {\n for (const entry of [\"node_modules\", \"package-lock.json\"]) {\n fs.rmSync(path.join(stackDir, entry), { recursive: true, force: true });\n }\n }\n fs.writeFileSync(\n path.join(stackDir, \"package.json\"),\n `${JSON.stringify(\n {\n ...(local\n ? stackManifest({\n name,\n version,\n phCliSpec: options.phCliSpec,\n local,\n plugins: options.plugins,\n })\n : {\n name,\n private: true,\n type: \"module\",\n dependencies: { [RUN_PACKAGE]: version },\n }),\n ...project,\n },\n null,\n 2,\n )}\\n`,\n );\n\n let vendored = false;\n if (vendor) {\n // Local: the manifest names every spec.\n const specs = local\n ? \"\"\n : registrySpecs(options)\n .map((spec) => `\"${spec}\"`)\n .join(\" \");\n log(\n local\n ? ` vendoring ${Object.keys(local).length} local packages from ${options.localPackagesDir} (hoisted, real files)…`\n : ` vendoring ${specs} (hoisted, real files)…`,\n );\n // One command string: shell:true with an args ARRAY concatenates without\n // escaping (DEP0190 warns); the spec values are our own constants/paths.\n const result = spawnSync(\n `npm install ${specs} --install-strategy=hoisted --omit=dev --no-audit --no-fund`,\n { cwd: stackDir, stdio: \"pipe\", shell: true, windowsHide: true },\n );\n if (result.status !== 0) {\n throw new Error(\n `bundle-stack: vendoring failed (${result.status}):\\n` +\n `${result.stderr.toString().slice(-800)}`,\n );\n }\n vendored = true;\n } else {\n log(\" vendoring skipped (vendor: false) — existing tree left in place\");\n }\n\n log(` ${pruneStack(stackDir)} files a running app never reads removed`);\n\n return { stackDir, vendored };\n}\n","import {\n colorVariants,\n imageVariants,\n layerStyleText,\n normalizeBackground,\n} from \"@powerhousedao/shared/connect\";\nimport { isPassthroughImageRef } from \"@powerhousedao/shared/connect/image-ref\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n appSlug,\n DEFAULT_SHELL_CRATE_VERSION,\n type AppJson,\n type AppJsonShellSource,\n updateEndpoints,\n} from \"./app-json.js\";\n\n/**\n * P7.3 — project `hosts/desktop/app.json` into a generated `tauri-shell/`:\n * a STANDALONE tauri crate that depends on the published `ph-desktop-shell`\n * library, carries the builder's identity, and is built/run by the desktop\n * runner's dev/build verbs. The builder never writes Rust.\n *\n * Everything here mirrors the known-good reference app\n * (ph-desktop-shell/apps/powerhouse-desktop): the tauri plumbing (main.rs,\n * build.rs, capabilities, the loading page, externalBin + icon mechanics) is\n * copied verbatim; only identity/port fields are projected from app.json. The\n * projection is idempotent and stale-detected — a file is rewritten only when\n * its content changes, so Cargo.lock, the generated icon set, and tauri-build\n * output are never disturbed by a regen with an unchanged app.json.\n */\n\nexport const SHELL_DIR = \"tauri-shell\";\n/** The icon source the runner feeds to `tauri icon` (copied from app.icon). */\nexport const ICON_SOURCE = \"app-icon.png\";\n/** Beside tauri.conf.json in an app with updates: the settings of a build\n * that has no signing key to hand, which cannot be offered as an update. */\nexport const UNSIGNED_BUILD_CONF = \"tauri.unsigned.conf.json\";\n/** What a page may ask the shell about updates (ph-desktop-shell's update.rs).\n * Granted in every app: one without updates answers that it has none. */\nconst UPDATE_COMMANDS = [\"update_state\", \"update_check\", \"update_install\"];\nconst UPDATE_PERMISSIONS = UPDATE_COMMANDS.map(\n (command) => `allow-${command.replaceAll(\"_\", \"-\")}`,\n);\n\nexport interface ProjectShellInput {\n /** hosts/<host>/ — where app.json lives and tauri-shell/ is written. */\n hostDir: string;\n app: AppJson;\n /** The connect member's port — baked into the remote capability so the\n * served Connect origin can reach the shell's launch-queue commands. */\n connectPort: number;\n /** The app's version: the project's package.json version. */\n version?: string;\n /** The sign-in page's script, where the built one isn't to hand. */\n signInScript?: Buffer;\n}\n\n/** The version the installers and the macOS bundle carry: the numeric x.y.z\n * of the project's version, as Windows' bundlers take nothing else. */\nexport function bundleVersion(version: string | undefined): string {\n const numeric = /^(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version ?? \"\");\n return numeric ? numeric.slice(1).join(\".\") : \"0.1.0\";\n}\n\nexport interface ProjectShellResult {\n shellDir: string;\n /** The crate/bin name (and the built exe stem the runner looks for). */\n binName: string;\n /** True when any projected file was created or changed this call. */\n changed: boolean;\n}\n\n/** `ph-desktop-shell` dependency line for the generated Cargo.toml, from\n * app.json's shell.source (path > git > crates.io version). */\nfunction shellDependency(source: AppJsonShellSource | undefined): string {\n if (source?.path) {\n // Forward slashes work in Cargo.toml on every platform.\n const p = source.path.replace(/\\\\/g, \"/\");\n return `ph-desktop-shell = { path = ${JSON.stringify(p)} }`;\n }\n if (source?.git) {\n const parts = [`git = ${JSON.stringify(source.git)}`];\n if (source.tag) parts.push(`tag = ${JSON.stringify(source.tag)}`);\n if (source.rev) parts.push(`rev = ${JSON.stringify(source.rev)}`);\n return `ph-desktop-shell = { ${parts.join(\", \")} }`;\n }\n const version = source?.version ?? DEFAULT_SHELL_CRATE_VERSION;\n return `ph-desktop-shell = ${JSON.stringify(version)}`;\n}\n\nfunction cargoToml(app: AppJson, binName: string): string {\n return `# GENERATED from ../app.json by @powerhousedao/desktop — do not edit by\n# hand; edit app.json and re-run \\`ph run desktop dev|build\\`. Cargo.lock is\n# preserved across regens.\n[package]\nname = ${JSON.stringify(binName)}\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[build-dependencies]\ntauri-build = { version = \"2\", features = [] }\n\n[dependencies]\ntauri = { version = \"2\", features = [\"tray-icon\", \"devtools\"] }\n# Plugins must be DIRECT deps of the app crate: tauri-build only sees\n# permission manifests (shell:allow-spawn etc.) from direct dependencies.\ntauri-plugin-shell = \"2\"\ntauri-plugin-single-instance = \"2\"\n${\n app.updates\n ? `# The updater's settings are baked in by tauri::generate_context!, whose\n# output names serde_json in this crate.\nserde_json = \"1\"\n`\n : \"\"\n}${shellDependency(app.shell)}\n\n[[bin]]\nname = ${JSON.stringify(binName)}\npath = \"src/main.rs\"\n\n[profile.release]\ncodegen-units = 1\nlto = true\n`;\n}\n\nconst MAIN_RS = `// GENERATED — identity bakes from tauri.conf.json via generate_context!;\n// behavior is the shared ph-desktop-shell library. Edit ../app.json, not this.\n#![cfg_attr(not(debug_assertions), windows_subsystem = \"windows\")]\n\nfn main() {\n ph_desktop_shell::run(tauri::generate_context!(), Default::default());\n}\n`;\n\nconst BUILD_RS = `// GENERATED — mirrors the reference shell. Connect is served over\n// http://127.0.0.1 (a remote origin to Tauri), so the launch-queue commands\n// need an explicit ACL; declaring the command manifest here generates the\n// allow-<command> permissions that capabilities/*.json grant.\nfn main() {\n // The icon set is a COMPILE-TIME input (the Windows resource icon here,\n // and the tray/window icon tauri::generate_context! embeds), but\n // tauri-build registers no rerun trigger for it: without this line a\n // regenerated icon set leaves the old icon compiled into the binary.\n println!(\"cargo:rerun-if-changed=icons\");\n tauri_build::try_build(tauri_build::Attributes::new().app_manifest(\n tauri_build::AppManifest::new().commands(&[\n \"take_launch_files\",\n \"read_launch_file\",\n \"log_from_webview\",\n \"open_external\",\n \"desktop_state\",\n \"pick_root\",\n \"save_renown_url\",\n \"local_create\",\n \"local_unlock\",\n \"saved_credential\",\n \"save_profile\",\n \"adopt_old_data\",\n \"start_stack\",\n \"switch_identity\",\n \"update_state\",\n \"update_check\",\n \"update_install\",\n ]),\n ))\n .expect(\"failed to run tauri-build\");\n}\n`;\n\n/** The sign-in page's script (app.json `signIn`), beside the page. */\nconst SIGN_IN_SCRIPT = \"sign-in.js\";\n\n/** That script as this package built it (tsdown.config.ts). */\nfunction builtSignInScript(): Buffer {\n return fs.readFileSync(\n fileURLToPath(new URL(`./sign-in/${SIGN_IN_SCRIPT}`, import.meta.url)),\n );\n}\n\n/** The loading page's logo: app.json's icon SOURCE (1024² recommended), copied\n * beside ui/index.html — not one of the downsampled `tauri icon` outputs, so\n * it stays sharp on HiDPI screens. Generated, like the rest of ui/. */\nexport const LOADING_LOGO = \"logo.png\";\n\n/** The loading page's splash (app.json `splash`), copied beside it; shown\n * instead of the square logo when set. Generated, like the rest of ui/. */\nexport const LOADING_SPLASH = \"splash.png\";\n/** Dark-scheme splash (app.json `splashDark`), beside the light one. */\nexport const LOADING_SPLASH_DARK = \"splash-dark.png\";\n/** Corner decoration (app.json `loading.art` / `loading.artDark`). */\nexport const LOADING_ART = \"art\";\n/** The background's layers (app.json `background`): `bg-<n>.<ext>` and\n * `bg-<n>-dark.<ext>` beside the page. */\nexport const LOADING_BG = \"bg\";\n\n/** CSS size of the logo; the 1024² source keeps it crisp up to 8x DPR. */\nconst LOGO_CSS_PX = 128;\n\n/** One layer of the page's background, staged beside the page (or a URL /\n * data URI as given) with the style that places it. */\ntype LoadingLayer = { light: string; dark?: string; style: string };\n\n/** The art the loading page shows: a layered background (app.json\n * `background`) under the centred status line; or, without one, the wide\n * splash (with an optional dark counterpart) else the square logo above the\n * status line, plus an optional corner decoration. */\ntype LoadingArt = {\n main: { kind: \"logo\" | \"splash\"; file: string; dark?: string } | null;\n corner: { file: string; dark?: string } | null;\n background: {\n color: { light: string; dark?: string } | null;\n layers: LoadingLayer[];\n } | null;\n};\n\n/** The sign-in page's own look, on the loading page's colours. */\nconst SIGN_IN_CSS = `\n body { overflow: auto; height: auto; min-height: 100vh; }\n #sign-in {\n position: relative; z-index: 1; box-sizing: border-box;\n width: min(420px, calc(100vw - 32px)); margin: 24px 0; padding: 32px;\n display: flex; flex-direction: column; gap: 12px; text-align: left;\n background: color-mix(in srgb, var(--bg) 92%, var(--fg));\n border: 1px solid color-mix(in srgb, var(--fg) 14%, transparent);\n border-radius: 14px;\n }\n #sign-in h1 { margin: 0 0 8px; font-size: 24px; line-height: 1.2; font-weight: 600; }\n #sign-in p { margin: 0; }\n #sign-in small { opacity: .7; }\n #sign-in button, #sign-in input {\n font: inherit; color: inherit; border-radius: 8px; padding: 10px 14px;\n border: 1px solid color-mix(in srgb, var(--fg) 22%, transparent);\n background: transparent; box-sizing: border-box; width: 100%;\n }\n #sign-in button { cursor: pointer; }\n #sign-in button.primary { background: var(--accent); border-color: var(--accent); color: var(--bg); font-weight: 600; }\n #sign-in button.link { width: auto; padding: 0; border: 0; text-decoration: underline; }\n #sign-in label { display: grid; gap: 4px; }\n #sign-in details { font-size: 14px; display: grid; gap: 8px; }\n #sign-in .folder { font-size: 13px; overflow-wrap: anywhere; }\n #sign-in .notice { padding: 10px 12px; border-radius: 8px; font-size: 14px; background: color-mix(in srgb, var(--accent) 16%, transparent); }\n #sign-in .identities { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }\n #sign-in .identity { display: flex; gap: 12px; align-items: center; text-align: left; }\n #sign-in .identity img, #sign-in .initial {\n width: 36px; height: 36px; border-radius: 50%; object-fit: cover; flex: none;\n display: grid; place-items: center; font-weight: 600;\n background: color-mix(in srgb, var(--accent) 30%, transparent);\n }\n #sign-in .identity b, #sign-in .identity small { display: block; }\n #sign-in .busy { display: flex; align-items: center; justify-content: center; }\n #sign-in:has(> .busy) { background: none; border: 0; }`;\n\nfunction loadingHtml(app: AppJson, art: LoadingArt, signIn = false): string {\n const escape = (text: string) =>\n text.replace(/[<&]/g, (c) => (c === \"<\" ? \"&lt;\" : \"&amp;\"));\n const name = escape(app.productName);\n const loading = app.loading;\n const message = loading?.message\n ? escape(loading.message)\n : `Starting ${name}…`;\n // The background's own colour (scheme-aware) beats the loading colours.\n const pageColor = art.background?.color ?? null;\n const background = pageColor?.light ?? loading?.background ?? \"#0f1115\";\n const color = loading?.color ?? \"#e6e8eb\";\n const accent = loading?.accent ?? \"#4ade80\";\n const dark = loading?.dark;\n const darkBackground = pageColor?.dark ?? dark?.background;\n const darkVars =\n dark || darkBackground\n ? `\n @media (prefers-color-scheme: dark) {\n :root {\n --bg: ${darkBackground ?? background};\n --fg: ${dark?.color ?? color};\n --accent: ${dark?.accent ?? accent};\n }\n }`\n : \"\";\n const attr = (text: string) =>\n text.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n // The background's layers, each placed by the shared layer style (the\n // same declarations Connect's home screen applies), swapped by scheme.\n const layersTag =\n art.background && art.background.layers.length > 0\n ? `<div class=\"layers\" aria-hidden=\"true\">\n ${art.background.layers\n .map((layer) =>\n layer.dark\n ? `<picture>\n <source srcset=\"${attr(layer.dark)}\" media=\"(prefers-color-scheme: dark)\" />\n <img src=\"${attr(layer.light)}\" alt=\"\" style=\"${attr(layer.style)}\" />\n </picture>`\n : `<img src=\"${attr(layer.light)}\" alt=\"\" style=\"${attr(layer.style)}\" />`,\n )\n .join(\"\\n \")}\n </div>\n `\n : \"\";\n // <picture> swaps the file by color scheme; a plain <img> otherwise.\n const picture = (\n cls: string,\n file: string,\n darkFile: string | undefined,\n attrs = \"\",\n ) =>\n darkFile\n ? `<picture>\n <source srcset=\"./${darkFile}\" media=\"(prefers-color-scheme: dark)\" />\n <img class=\"${cls}\" src=\"./${file}\" alt=\"\"${attrs} />\n </picture>\n `\n : `<img class=\"${cls}\" src=\"./${file}\" alt=\"\"${attrs} />\n `;\n const main = art.main;\n const logoTag =\n main?.kind === \"splash\"\n ? picture(\"splash\", main.file, main.dark)\n : main\n ? picture(\n \"logo\",\n main.file,\n main.dark,\n ` width=\"${LOGO_CSS_PX}\" height=\"${LOGO_CSS_PX}\"`,\n )\n : \"\";\n const cornerTag = art.corner\n ? `<div class=\"corner\" aria-hidden=\"true\">${picture(\"art\", art.corner.file, art.corner.dark)}</div>\n `\n : \"\";\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <title>${name}</title>\n <style>\n :root {\n color-scheme: light dark;\n --bg: ${background}; --fg: ${color}; --accent: ${accent};\n }${darkVars}\n body {\n margin: 0; height: 100vh; overflow: hidden;\n display: flex; align-items: center; justify-content: center;\n font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", sans-serif;\n background: var(--bg); color: var(--fg);\n }\n .box {\n position: relative; z-index: 1;\n text-align: center;\n display: flex; flex-direction: column; align-items: center; gap: 20px;\n }\n .logo {\n width: ${LOGO_CSS_PX}px; height: ${LOGO_CSS_PX}px;\n object-fit: contain; display: block;\n }\n .splash {\n width: min(720px, 80vw); max-height: 65vh;\n object-fit: contain; display: block;\n }\n .corner {\n position: fixed; right: 0; bottom: 0; z-index: 0;\n width: clamp(220px, 30vw, 520px); line-height: 0; pointer-events: none;\n }\n .layers { position: fixed; inset: 0; z-index: 0; }\n .art { width: 100%; height: auto; display: block; }\n .dot {\n width: 10px; height: 10px; border-radius: 50%;\n background: var(--accent); display: inline-block; margin-right: 8px;\n animation: pulse 1.2s ease-in-out infinite;\n }\n @keyframes pulse { 0%,100% { opacity: .35 } 50% { opacity: 1 } }\n @media (prefers-reduced-motion: reduce) { .dot { animation: none; } }${signIn ? SIGN_IN_CSS : \"\"}\n </style>\n </head>\n <body>\n ${\n signIn\n ? `<main id=\"sign-in\"></main>\n <script type=\"module\" src=\"./sign-in.js\"></script>`\n : `<div class=\"box\">\n ${logoTag}<div><span class=\"dot\"></span>${message}</div>\n </div>`\n }\n ${layersTag}${cornerTag}</body>\n</html>\n`;\n}\n\nfunction tauriConf(input: ProjectShellInput): string {\n const { app } = input;\n const win = app.window ?? {};\n const fileAssociations =\n app.fileAssociations && app.fileAssociations.length > 0\n ? app.fileAssociations.map((fa) => ({\n ext: fa.ext,\n name: fa.name,\n ...(fa.description ? { description: fa.description } : {}),\n ...(fa.mimeType ? { mimeType: fa.mimeType } : {}),\n }))\n : undefined;\n const conf = {\n $schema: \"https://schema.tauri.app/config/2\",\n productName: app.productName,\n version: bundleVersion(input.version),\n identifier: app.identifier,\n build: { frontendDist: \"./ui\" },\n app: {\n windows: [\n {\n title: win.title ?? app.productName,\n width: win.width ?? 1440,\n height: win.height ?? 900,\n resizable: win.resizable ?? true,\n ...(win.minWidth ? { minWidth: win.minWidth } : {}),\n ...(win.minHeight ? { minHeight: win.minHeight } : {}),\n visible: true,\n dragDropEnabled: false,\n create: false,\n },\n ],\n security: { csp: null },\n },\n bundle: {\n active: true,\n // Cross-platform: nsis (Windows, no WiX), app+dmg (macOS). The runner\n // passes host-appropriate --bundles at build time; tauri skips targets\n // not valid for the build host.\n targets: [\"nsis\", \"app\", \"dmg\"],\n // `tauri icon` generates .ico (Windows) and .icns (macOS) + pngs from\n // the single app-icon.png; the config references the per-platform set.\n icon: [\n \"icons/32x32.png\",\n \"icons/128x128.png\",\n \"icons/128x128@2x.png\",\n \"icons/icon.icns\",\n \"icons/icon.ico\",\n ],\n ...(fileAssociations ? { fileAssociations } : {}),\n externalBin: [\"binaries/node\"],\n resources: { \"./dist-stack\": \"stack\" },\n // Ad-hoc: a signature over the whole bundle, so a downloaded app gets\n // macOS's \"Open Anyway\" rather than \"damaged\". APPLE_SIGNING_IDENTITY\n // overrides it. Tauri re-signs the node sidecar as well, and under the\n // hardened runtime V8 can't JIT without an entitlement: only\n // notarization needs that runtime, so it stays off until then.\n macOS: { signingIdentity: \"-\", hardenedRuntime: false },\n // Each installer gets a signature beside it, and macOS an archive of\n // the app: what a running app downloads and checks. Signing needs\n // TAURI_SIGNING_PRIVATE_KEY at build time.\n ...(app.updates ? { createUpdaterArtifacts: true } : {}),\n },\n ...(app.updates\n ? {\n plugins: {\n updater: {\n pubkey: app.updates.pubkey.trim(),\n endpoints: updateEndpoints(app.updates),\n // A feed's word is not signed, a release's signature is: the\n // version the feed announces has to be the one that was signed,\n // or an old release could be served as a new one.\n requireSignedVersion: true,\n },\n },\n }\n : {}),\n };\n return JSON.stringify(conf, null, 2) + \"\\n\";\n}\n\n/** Laid over tauri.conf.json for a build without the signing key. */\nconst UNSIGNED_BUILD_CONF_JSON =\n JSON.stringify({ bundle: { createUpdaterArtifacts: false } }, null, 2) + \"\\n\";\n\nfunction defaultCapability(): string {\n return (\n JSON.stringify(\n {\n $schema: \"../gen/schemas/desktop-schema.json\",\n identifier: \"default\",\n description: \"Lets the shell spawn the bundled node sidecar.\",\n windows: [\"main\"],\n permissions: [\n \"core:default\",\n \"allow-take-launch-files\",\n \"allow-read-launch-file\",\n \"allow-log-from-webview\",\n ...UPDATE_PERMISSIONS,\n {\n identifier: \"shell:allow-spawn\",\n allow: [{ name: \"binaries/node\", sidecar: true, args: true }],\n },\n {\n identifier: \"shell:allow-execute\",\n allow: [{ name: \"binaries/node\", sidecar: true, args: true }],\n },\n ],\n },\n null,\n 2,\n ) + \"\\n\"\n );\n}\n\nfunction connectCapability(connectPort: number): string {\n const origin = `http://127.0.0.1:${connectPort}`;\n return (\n JSON.stringify(\n {\n $schema: \"../gen/schemas/desktop-schema.json\",\n identifier: \"connect\",\n description:\n \"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.\",\n windows: [\"main\"],\n remote: { urls: [origin, `${origin}/*`] },\n permissions: [\n \"allow-take-launch-files\",\n \"allow-read-launch-file\",\n \"allow-log-from-webview\",\n \"allow-open-external\",\n \"allow-desktop-state\",\n \"allow-pick-root\",\n \"allow-save-renown-url\",\n \"allow-local-create\",\n \"allow-local-unlock\",\n \"allow-saved-credential\",\n \"allow-save-profile\",\n \"allow-adopt-old-data\",\n \"allow-start-stack\",\n \"allow-switch-identity\",\n ...UPDATE_PERMISSIONS,\n ],\n },\n null,\n 2,\n ) + \"\\n\"\n );\n}\n\nconst GITIGNORE = `# Generated tauri shell — only Cargo.lock and app-icon.png are tracked.\n/target\n/gen\n/icons\n/ui/logo.png\n/ui/splash.png\n/ui/splash-dark.png\n/ui/art.*\n/ui/art-dark.*\n/ui/bg-*\n/ui/sign-in.*\n/dist-stack\n/binaries\n`;\n\nconst DIST_STACK_README = `This directory is replaced at \\`ph run desktop build\\` with the shippable\nstack (hosts + powerhouse.config.json + built Connect + vendored ph-cli). It\nis bundled as the app's \\`stack\\` resource so the installed app runs with no\nenvironment. Kept as a placeholder so tauri's resource glob resolves in dev.\n`;\n\n/** Write a file only when its content differs; returns whether it changed. */\nfunction writeIfChanged(file: string, content: string): boolean {\n if (fs.existsSync(file) && fs.readFileSync(file, \"utf8\") === content) {\n return false;\n }\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(file, content);\n return true;\n}\n\n/**\n * Materialize/refresh `<hostDir>/tauri-shell/` from app.json. Idempotent:\n * unchanged app.json rewrites nothing. Does NOT run `tauri icon` or fetch the\n * node binary — those are toolchain steps the runner performs at dev/build.\n */\nexport function projectShell(input: ProjectShellInput): ProjectShellResult {\n const { hostDir, app, connectPort } = input;\n const binName = appSlug(app);\n const shellDir = path.join(hostDir, SHELL_DIR);\n const iconSrc = path.resolve(hostDir, app.icon);\n const iconBytes = fs.existsSync(iconSrc) ? fs.readFileSync(iconSrc) : null;\n const readRel = (rel: string | null | undefined): Buffer | null => {\n if (!rel) return null;\n const abs = path.resolve(hostDir, rel);\n return fs.existsSync(abs) ? fs.readFileSync(abs) : null;\n };\n const splashBytes = readRel(app.splash);\n const splashDarkBytes = readRel(app.splashDark);\n const artBytes = readRel(app.loading?.art);\n const artDarkBytes = readRel(app.loading?.artDark);\n const artExt = (rel: string | null | undefined) =>\n rel ? path.extname(rel).toLowerCase() || \".png\" : \".png\";\n const artFile = `${LOADING_ART}${artExt(app.loading?.art)}`;\n const artDarkFile = `${LOADING_ART}-dark${artExt(app.loading?.artDark)}`;\n // The background's layers: a file beside app.json is staged beside the\n // page as bg-<n>[-dark].<ext>; a URL or data URI is used as given; a layer\n // whose light image is missing is dropped (a missing dark one falls back\n // to the light one).\n const background = normalizeBackground(app.background);\n const staged: Array<[string, Buffer]> = [];\n const stage = (ref: string, stem: string): string | undefined => {\n if (isPassthroughImageRef(ref)) return ref;\n const abs = path.resolve(hostDir, ref);\n if (!fs.existsSync(abs)) return undefined;\n const file = `${stem}${artExt(ref)}`;\n staged.push([path.join(shellDir, \"ui\", file), fs.readFileSync(abs)]);\n return `./${file}`;\n };\n const layers = (background?.layers ?? []).flatMap(\n (layer, index): LoadingLayer[] => {\n const variants = imageVariants(layer.src);\n const light = stage(variants.light, `${LOADING_BG}-${index}`);\n if (!light) return [];\n const dark = variants.dark\n ? stage(variants.dark, `${LOADING_BG}-${index}-dark`)\n : undefined;\n return [\n { light, ...(dark ? { dark } : {}), style: layerStyleText(layer) },\n ];\n },\n );\n // A background replaces the splash/logo and the corner art: its layers are\n // the page's decoration, the status line stays centred above them.\n const art: LoadingArt = {\n main: background\n ? null\n : splashBytes\n ? {\n kind: \"splash\",\n file: LOADING_SPLASH,\n ...(splashDarkBytes ? { dark: LOADING_SPLASH_DARK } : {}),\n }\n : iconBytes\n ? { kind: \"logo\", file: LOADING_LOGO }\n : null,\n corner:\n !background && artBytes\n ? { file: artFile, ...(artDarkBytes ? { dark: artDarkFile } : {}) }\n : null,\n background: background\n ? { color: colorVariants(background.color), layers }\n : null,\n };\n const files: Array<[string, string]> = [\n [\"Cargo.toml\", cargoToml(app, binName)],\n [\"src/main.rs\", MAIN_RS],\n [\"build.rs\", BUILD_RS],\n [\"tauri.conf.json\", tauriConf(input)],\n [\"ui/index.html\", loadingHtml(app, art)],\n [\"capabilities/default.json\", defaultCapability()],\n [\"capabilities/connect.json\", connectCapability(connectPort)],\n [\".gitignore\", GITIGNORE],\n [\"dist-stack/README.md\", DIST_STACK_README],\n ];\n if (app.signIn) files.push([\"ui/sign-in.html\", loadingHtml(app, art, true)]);\n if (app.updates) files.push([UNSIGNED_BUILD_CONF, UNSIGNED_BUILD_CONF_JSON]);\n let changed = false;\n for (const [rel, content] of files) {\n if (writeIfChanged(path.join(shellDir, rel), content)) changed = true;\n }\n if (!app.updates) {\n const stale = path.join(shellDir, UNSIGNED_BUILD_CONF);\n if (fs.existsSync(stale)) {\n fs.rmSync(stale);\n changed = true;\n }\n }\n // The shell gates on the page being there, so turning it off has to remove it.\n if (!app.signIn) {\n for (const file of [\"sign-in.html\", SIGN_IN_SCRIPT]) {\n const stale = path.join(shellDir, \"ui\", file);\n if (fs.existsSync(stale)) {\n fs.rmSync(stale);\n changed = true;\n }\n }\n }\n // Stage the icon source next to the shell (tauri icon reads it at build),\n // the same full-resolution source as the loading page's logo, and the\n // splash when app.json names one.\n const copies: Array<[string, Buffer | null]> = [\n [\n path.join(shellDir, \"ui\", SIGN_IN_SCRIPT),\n app.signIn ? (input.signInScript ?? builtSignInScript()) : null,\n ],\n [path.join(shellDir, ICON_SOURCE), iconBytes],\n [path.join(shellDir, \"ui\", LOADING_LOGO), iconBytes],\n [path.join(shellDir, \"ui\", LOADING_SPLASH), splashBytes],\n [path.join(shellDir, \"ui\", LOADING_SPLASH_DARK), splashDarkBytes],\n [path.join(shellDir, \"ui\", artFile), artBytes],\n [path.join(shellDir, \"ui\", artDarkFile), artDarkBytes],\n ...staged,\n ];\n for (const [dest, bytes] of copies) {\n if (!bytes) continue;\n if (!fs.existsSync(dest) || !fs.readFileSync(dest).equals(bytes)) {\n fs.mkdirSync(path.dirname(dest), { recursive: true });\n fs.writeFileSync(dest, bytes);\n changed = true;\n }\n }\n return { shellDir, binName, changed };\n}\n","import { execSync, spawnSync } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n/**\n * The native toolchain the generated shell (mode 1) needs to build/run, and\n * the provisioning steps around it. `cargo tauri dev|build` compiles the\n * generated crate — but tauri-build validates two things AT COMPILE TIME that\n * must exist first (both confirmed against a live `cargo check`):\n * - the node sidecar `binaries/node-<triple>` (externalBin), and\n * - `icons/icon.ico` on Windows (the app's Win32 resource).\n * So dev/build provision the sidecar + icon set before invoking tauri, and\n * fail with install guidance when cargo or the Tauri CLI is absent — a\n * missing executable must read as a clear instruction, never a deep cargo\n * stack trace.\n */\n\nexport interface NodeTarget {\n triple: string;\n dist: string;\n /** Path within the extracted archive (POSIX) / \"node.exe\" on Windows. */\n bin: string;\n ext: string;\n}\n\n/** The Node release triple for a build host — the sidecar filename tauri\n * resolves (`node-<triple>`). Pure, so the mapping is unit-tested. */\nexport function nodeSidecarTarget(\n platform: NodeJS.Platform,\n arch: string,\n): NodeTarget {\n const table: Record<string, NodeTarget | undefined> = {\n \"win32 x64\": {\n triple: \"x86_64-pc-windows-msvc\",\n dist: \"win-x64\",\n bin: \"node.exe\",\n ext: \".exe\",\n },\n \"darwin arm64\": {\n triple: \"aarch64-apple-darwin\",\n dist: \"darwin-arm64\",\n bin: \"bin/node\",\n ext: \"\",\n },\n \"darwin x64\": {\n triple: \"x86_64-apple-darwin\",\n dist: \"darwin-x64\",\n bin: \"bin/node\",\n ext: \"\",\n },\n \"linux x64\": {\n triple: \"x86_64-unknown-linux-gnu\",\n dist: \"linux-x64\",\n bin: \"bin/node\",\n ext: \"\",\n },\n };\n const target = table[`${platform} ${arch}`];\n if (!target) {\n throw new Error(\n `No Node sidecar mapping for ${platform} ${arch} — the desktop shell ` +\n `supports win32/x64, darwin/arm64, darwin/x64, linux/x64.`,\n );\n }\n return target;\n}\n\n/** Fetch the stock Node the shell ships as its sidecar into `<shellDir>/\n * binaries`, named per target triple. No-op when already present. Ported from\n * the reference repo's fetch-node.mjs (the builder has no such script). */\nexport function fetchNodeSidecar(\n shellDir: string,\n version: string = process.versions.node,\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n): string {\n const target = nodeSidecarTarget(platform, arch);\n const binariesDir = path.join(shellDir, \"binaries\");\n fs.mkdirSync(binariesDir, { recursive: true });\n const dest = path.join(binariesDir, `node-${target.triple}${target.ext}`);\n if (fs.existsSync(dest)) return dest;\n\n if (platform === \"win32\") {\n const url = `https://nodejs.org/dist/v${version}/win-x64/node.exe`;\n execSync(`curl -fsSL -o \"${dest}\" \"${url}\"`, { stdio: \"inherit\" });\n } else {\n const name = `node-v${version}-${target.dist}`;\n const url = `https://nodejs.org/dist/v${version}/${name}.tar.gz`;\n execSync(\n `curl -fsSL \"${url}\" | tar -xz -C \"${binariesDir}\" --strip-components=2 ${name}/${target.bin}`,\n { stdio: \"inherit\", shell: \"/bin/sh\" },\n );\n fs.renameSync(path.join(binariesDir, \"node\"), dest);\n fs.chmodSync(dest, 0o755);\n }\n return dest;\n}\n\n/** Default bundle targets for the build host (`cargo tauri build --bundles`).\n * macOS gets app+dmg, Windows nsis, Linux deb+appimage — a host only builds\n * installers it can produce. */\nexport function tauriBundlesForHost(\n platform: NodeJS.Platform = process.platform,\n): string[] {\n switch (platform) {\n case \"darwin\":\n return [\"app\", \"dmg\"];\n case \"win32\":\n return [\"nsis\"];\n default:\n return [\"deb\", \"appimage\"];\n }\n}\n\n/** `tauri build`'s arguments. An app with updates signs what it builds, so\n * without the key (`TAURI_SIGNING_PRIVATE_KEY`) the build would fail at its\n * last step: such a build leaves the signatures out instead, laying\n * `unsignedConf` over the configuration, and still makes its installers. */\nexport function tauriBuildArgs(\n bundles: string[],\n updates: { on: boolean; signingKey: boolean; unsignedConf: string },\n): string[] {\n const args = [\"build\", \"--bundles\", bundles.join(\",\")];\n if (updates.on && !updates.signingKey) {\n args.push(\"--config\", updates.unsignedConf);\n }\n return args;\n}\n\nexport interface TauriCommand {\n /** The executable to spawn (e.g. \"cargo\" or a node path). */\n cmd: string;\n /** Args that precede the tauri subcommand (e.g. [\"tauri\"] for cargo). */\n prefix: string[];\n /** How the CLI was found — for logging + the preflight message. */\n via: \"cargo-tauri\" | \"node-cli\";\n}\n\n/** Spawn parameters that avoid DEP0190 (args array + shell:true): cargo on\n * Windows needs the shell for PATH/.exe + subcommand resolution — pass ONE\n * string, empty args; everything else runs argv directly (shell:false). The\n * joined tokens here are our own constants/paths, never user input. */\nexport function tauriSpawn(\n tauri: TauriCommand,\n subcommand: string[],\n): { command: string; args: string[]; shell: boolean } {\n const argv = [...tauri.prefix, ...subcommand];\n if (tauri.cmd === \"cargo\" && process.platform === \"win32\") {\n return { command: [\"cargo\", ...argv].join(\" \"), args: [], shell: true };\n }\n return { command: tauri.cmd, args: argv, shell: false };\n}\n\nfunction probe(cmd: string, args: string[]): boolean {\n const onWin = process.platform === \"win32\";\n try {\n const r = spawnSync(\n onWin ? [cmd, ...args].join(\" \") : cmd,\n onWin ? [] : args,\n { stdio: \"ignore\", shell: onWin },\n );\n return r.status === 0;\n } catch {\n return false;\n }\n}\n\n/** Is a Rust `cargo` on PATH? (needed to compile the shell crate). */\nexport function hasCargo(): boolean {\n return probe(\"cargo\", [\"--version\"]);\n}\n\n/** Resolve a Tauri CLI: a global `cargo tauri`, else a `@tauri-apps/cli`\n * resolvable from the project. Returns null when neither is available. */\nexport function resolveTauriCommand(projectRoot: string): TauriCommand | null {\n if (probe(\"cargo\", [\"tauri\", \"--version\"])) {\n return { cmd: \"cargo\", prefix: [\"tauri\"], via: \"cargo-tauri\" };\n }\n try {\n const require_ = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n // @tauri-apps/cli exposes its binary entry; resolve its package then bin.\n const pkgJson = require_.resolve(\"@tauri-apps/cli/package.json\");\n const pkgDir = path.dirname(pkgJson);\n const pkg = JSON.parse(fs.readFileSync(pkgJson, \"utf8\")) as {\n bin?: string | Record<string, string>;\n };\n const bin = pkg.bin;\n const rel = typeof bin === \"string\" ? bin : bin?.tauri;\n if (rel) {\n return {\n cmd: process.execPath,\n prefix: [path.join(pkgDir, rel)],\n via: \"node-cli\",\n };\n }\n } catch {\n // not installed in the project\n }\n return null;\n}\n\nexport interface Toolchain {\n cargo: boolean;\n tauri: TauriCommand | null;\n}\n\nexport function detectToolchain(projectRoot: string): Toolchain {\n return { cargo: hasCargo(), tauri: resolveTauriCommand(projectRoot) };\n}\n\n/** Throw a clear, actionable error when the native toolchain is incomplete —\n * the desktop verbs call this before any cargo work so a missing executable\n * is an instruction, not a stack trace. */\nexport function preflightOrThrow(\n tc: Toolchain,\n hostName: string,\n): TauriCommand {\n const missing: string[] = [];\n if (!tc.cargo) {\n missing.push(\n \" • Rust/cargo — install from https://rustup.rs (then restart your shell)\",\n );\n }\n if (!tc.tauri) {\n missing.push(\n ' • Tauri CLI — `cargo install tauri-cli --version \"^2\"` ' +\n \"(or add @tauri-apps/cli@^2 to your project's devDependencies)\",\n );\n }\n if (missing.length > 0 || !tc.tauri) {\n throw new Error(\n `hosts/${hostName}: the desktop shell needs a native toolchain that is ` +\n `not installed:\\n${missing.join(\"\\n\")}\\n` +\n `Install the above, then re-run \\`ph run ${hostName} dev\\` / ` +\n `\\`ph run ${hostName} build\\`. (The headless stack — \\`ph run ` +\n `${hostName}\\` — needs none of this.)`,\n );\n }\n return tc.tauri;\n}\n\n/** `<tauri> icon <source>` — generates the per-platform icon set (icon.ico +\n * icon.icns + pngs) the bundle references and tauri-build requires. */\nexport function runTauriIcon(\n tauri: TauriCommand,\n shellDir: string,\n iconSource: string,\n): void {\n const { command, args, shell } = tauriSpawn(tauri, [\"icon\", iconSource]);\n const r = spawnSync(command, args, {\n cwd: shellDir,\n stdio: \"inherit\",\n shell,\n });\n if (r.status !== 0) {\n throw new Error(\n `\\`tauri icon ${iconSource}\\` failed (exit ${r.status ?? \"?\"}) in ` +\n `${shellDir} — check that app.icon is a square PNG.`,\n );\n }\n}\n","import { spawn, type ChildProcess } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n/**\n * Shell discovery and launch. The Rust/Tauri shell lives in the\n * ph-win-desktop repo (cargo cannot ride an npm package); the runner locates\n * a checkout via `runner.shell.project` or PH_DESKTOP_SHELL and prefers its\n * BUILT exe (dev config like window title is baked into a build — the\n * `--config` projection below applies to tauri-cli invocations only).\n */\n\nexport interface ShellOptions {\n /** Path to a ph-win-desktop checkout (absolute or project-relative). */\n project?: string;\n window?: { title?: string; width?: number; height?: number };\n tray?: boolean;\n fileAssociations?: string[];\n}\n\nexport interface ResolvedShell {\n projectDir: string;\n /** A built exe when one exists (debug preferred for dev), else undefined →\n * fall back to `pnpm tauri dev`. */\n exe?: string;\n}\n\nexport function resolveShell(\n projectRoot: string,\n options: ShellOptions | undefined,\n env: Record<string, string | undefined>,\n): ResolvedShell {\n const configured = options?.project ?? env.PH_DESKTOP_SHELL;\n if (!configured) {\n throw new Error(\n \"No desktop shell configured: set runner.shell.project in the host file \" +\n \"(path to a ph-win-desktop checkout) or the PH_DESKTOP_SHELL \" +\n \"environment variable. `ph run desktop` (headless stack) needs neither.\",\n );\n }\n const projectDir = path.resolve(projectRoot, configured);\n if (!fs.existsSync(path.join(projectDir, \"src-tauri\"))) {\n throw new Error(\n `Desktop shell not found at ${projectDir} (no src-tauri/) — check ` +\n `runner.shell.project / PH_DESKTOP_SHELL.`,\n );\n }\n const candidates = [\n path.join(projectDir, \"src-tauri\", \"target\", \"debug\", \"ph-win.exe\"),\n path.join(projectDir, \"src-tauri\", \"target\", \"release\", \"ph-win.exe\"),\n path.join(projectDir, \"src-tauri\", \"target\", \"debug\", \"ph-win\"),\n path.join(projectDir, \"src-tauri\", \"target\", \"release\", \"ph-win\"),\n ];\n const exe = candidates.find((c) => fs.existsSync(c));\n return { projectDir, exe };\n}\n\n/** Resolve the project's ph-cli entry from ITS dependency tree — the same\n * resolution `ph run` itself uses. */\nexport function resolvePhCliEntry(projectRoot: string): string {\n const require_ = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n const pkgPath = require_.resolve(\"@powerhousedao/ph-cli/package.json\");\n return path.join(path.dirname(pkgPath), \"dist\", \"cli.mjs\");\n}\n\n/** The env trio (plus flag and userData) the shell's uniform-runners mode\n * reads — wired by the RUNNER so nobody exports variables by hand. */\nexport function shellEnv(\n projectRoot: string,\n connectPort: number,\n env: Record<string, string | undefined>,\n): Record<string, string> {\n return {\n FEATURE_UNIFORM_RUNNERS_ENABLED: \"1\",\n PH_RUN_PROJECT: projectRoot,\n PH_RUN_CLI: resolvePhCliEntry(projectRoot),\n PH_WIN_CONNECT_PORT: String(connectPort),\n ...(env.PH_USER_DATA_DIR ? { PH_USER_DATA_DIR: env.PH_USER_DATA_DIR } : {}),\n };\n}\n\n/** Project host shell options onto a tauri `--config` merge patch (D6.d) —\n * the host file stays the single source for app identity on tauri-cli\n * invocations; a built exe has these baked. */\nexport function tauriConfigPatch(\n options: ShellOptions | undefined,\n): Record<string, unknown> | undefined {\n if (!options) return undefined;\n const patch: Record<string, unknown> = {};\n if (options.window) {\n patch.app = {\n windows: [\n {\n ...(options.window.title ? { title: options.window.title } : {}),\n ...(options.window.width ? { width: options.window.width } : {}),\n ...(options.window.height ? { height: options.window.height } : {}),\n },\n ],\n };\n }\n if (options.fileAssociations?.length) {\n patch.bundle = {\n fileAssociations: [\n {\n ext: options.fileAssociations.map((e) => e.replace(/^\\./, \"\")),\n name: \"Powerhouse Document\",\n },\n ],\n };\n }\n return Object.keys(patch).length > 0 ? patch : undefined;\n}\n\nexport function launchShell(\n shell: ResolvedShell,\n envVars: Record<string, string>,\n options: ShellOptions | undefined,\n): ChildProcess {\n if (shell.exe) {\n return spawn(shell.exe, [], {\n cwd: shell.projectDir,\n env: { ...process.env, ...envVars },\n stdio: \"inherit\",\n windowsHide: true,\n });\n }\n // tauri dev (needs cargo); config projection applies here.\n const patch = tauriConfigPatch(options);\n const args = [\"tauri\", \"dev\"];\n if (patch) args.push(\"--config\", JSON.stringify(patch));\n return spawn(\"pnpm\", args, {\n cwd: shell.projectDir,\n env: { ...process.env, ...envVars },\n stdio: \"inherit\",\n shell: true,\n windowsHide: true,\n });\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * A packaged stack is a node_modules folder, and Windows installs by the file:\n * tens of thousands of them take as long to install as to uninstall, and a\n * start spends most of a cold disk's time reading them. This folds the stack\n * into a few hundred files with Rolldown, in the staged copy only.\n *\n * What's loaded by name keeps working by name. Each package an add-on, a host\n * file or the project's own build may import stays in node_modules with its\n * \\`exports\\`, and each of those is a Rolldown entry, so an import of\n * \\`document-model\\` from anywhere reaches the one bundled copy. Two copies would\n * break \\`instanceof\\` and shared state, and without an error.\n *\n * What's found by path keeps its path. Chunks and the worker scripts go in one\n * package, so a chunk finds \\`./entry.mjs\\` beside it and the piece worker's walk\n * up to a package.json finds \\`dist/worker-entry.js\\`.\n */\n\n/** Holds the chunks. A package, so the piece worker's lookup stops at it. */\nconst CHUNKS_DIR = \".stack\";\n\n/** Packages reached by name, by something that isn't in the bundle. */\nconst BY_NAME = [\n /^@powerhousedao\\//,\n /^@renown\\/sdk$/,\n /^document-model$/,\n /^graphql$/,\n /^graphql-tag$/,\n /^kysely$/,\n /^zod$/,\n];\n\n/**\n * Left as files. PGlite finds its wasm and data beside it. React is what an\n * add-on's editor imports, and a server never calls it. The rest is only loaded\n * on a path a running app never takes, or by a native addon.\n */\nconst EXTERNAL = [\n /\\.node$/,\n /^@electric-sql\\/pglite/,\n /^pglite-(legacy|tools)/,\n /^react($|\\/)/,\n /^react-dom($|\\/)/,\n /^vite($|\\/)/,\n /^@powerhousedao\\/vetra($|\\/)/,\n /^@originjs\\//,\n /^devcert$/,\n /^pg-native$/,\n /^bufferutil$/,\n /^utf-8-validate$/,\n /^@pyroscope\\//,\n];\n\n/** How Rolldown writes a require it can't fold. A plain `require(` in a chunk is\n * text: a package's comments, error messages and generated code. */\nconst REQUIRE_CALL = /\\b__require\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/g;\n\n/** Copied into a kept package as they are, since a path reaches them. */\nconst KEEP_AS_FILES = [path.join(\"dist\", \"node\", \"pieces\")];\n\ntype ExportTarget = string | { [condition: string]: ExportTarget } | null;\n\n/** What a package exports for a server: node, then import, then default. */\nexport function serverTarget(target: ExportTarget | undefined): string | null {\n if (typeof target === \"string\") return target;\n if (target === null || target === undefined) return null;\n for (const condition of [\"node\", \"import\", \"default\"]) {\n if (condition in target) {\n const found = serverTarget(target[condition]);\n if (found) return found;\n }\n }\n return null;\n}\n\n/** Every subpath a package offers a server, with a wildcard's matches listed. */\nexport function exportedFiles(\n packageDir: string,\n manifest: {\n exports?: Record<string, ExportTarget> | string;\n main?: string;\n module?: string;\n },\n): Map<string, string> {\n const files = new Map<string, string>();\n const exports =\n typeof manifest.exports === \"string\"\n ? { \".\": manifest.exports }\n : manifest.exports;\n if (!exports) {\n const main = manifest.module ?? manifest.main ?? \"index.js\";\n const file = [main, `${main}.js`, path.join(main, \"index.js\")].find(\n (candidate) => isFile(path.join(packageDir, candidate)),\n );\n if (file) files.set(\".\", file.replace(/^\\.\\//, \"\"));\n return files;\n }\n for (const [subpath, target] of Object.entries(exports)) {\n if (subpath === \"./package.json\") continue;\n const file = serverTarget(target);\n if (!file) continue;\n if (!subpath.includes(\"*\")) {\n // A package can name a file its server build doesn't have.\n if (isFile(path.join(packageDir, file))) {\n files.set(subpath, file.replace(/^\\.\\//, \"\"));\n }\n continue;\n }\n for (const [match, found] of wildcardMatches(packageDir, file)) {\n files.set(subpath.replace(\"*\", match), found);\n }\n }\n return files;\n}\n\nfunction isFile(file: string): boolean {\n return fs.existsSync(file) && fs.statSync(file).isFile();\n}\n\nfunction wildcardMatches(packageDir: string, target: string) {\n const relative = target.replace(/^\\.\\//, \"\");\n const [before, after = \"\"] = relative.split(\"*\");\n const parent = before.endsWith(\"/\") ? before : path.posix.dirname(before);\n const prefix = before.slice(parent.length).replace(/^\\//, \"\");\n const matches: [string, string][] = [];\n const folder = path.join(packageDir, parent);\n if (!fs.existsSync(folder)) return matches;\n for (const entry of fs.readdirSync(folder, { withFileTypes: true })) {\n const name = entry.name;\n const firstSegment = after.startsWith(\"/\");\n const match = firstSegment\n ? name\n : name.endsWith(after) && name.startsWith(prefix)\n ? name.slice(prefix.length, name.length - after.length)\n : null;\n if (!match) continue;\n const file = path.posix.join(parent, `${prefix}${match}${after}`);\n if (isFile(path.join(packageDir, file))) matches.push([match, file]);\n }\n return matches;\n}\n\n/** Where a subpath's entry lands in its package. */\nexport function entryNameOf(pkg: string, subpath: string): string {\n const name =\n subpath === \".\"\n ? \"index\"\n : subpath.replace(/^\\.\\//, \"\").replaceAll(\"/\", \"__\");\n return `${pkg}/${name}`;\n}\n\n/** The package.json of a package whose code is now in the bundle. */\nexport function keptManifest(\n manifest: Record<string, unknown>,\n entries: ReadonlyMap<string, string>,\n): Record<string, unknown> {\n const { name, version } = manifest;\n const exports: Record<string, string> = {\n \"./package.json\": \"./package.json\",\n };\n for (const [subpath, file] of entries) exports[subpath] = `./${file}`;\n return { name, version, type: \"module\", exports };\n}\n\ninterface LockEntry {\n dependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n version?: string;\n}\n\n/** Nearest install of \\`dependency\\` as seen from \\`from\\`, by node's rules. */\nfunction resolveInLock(\n lock: Record<string, LockEntry>,\n from: string,\n dependency: string,\n): string | null {\n let at = from;\n for (;;) {\n const candidate = `${at ? `${at}/` : \"\"}node_modules/${dependency}`;\n if (lock[candidate]) return candidate;\n if (!at) return null;\n const cut = at.lastIndexOf(\"node_modules/\");\n at = cut <= 0 ? \"\" : at.slice(0, cut - 1);\n }\n}\n\n/** The install paths of `names` and everything they depend on. */\nexport function closureOf(\n lock: Record<string, LockEntry>,\n names: Iterable<string>,\n): Set<string> {\n const kept = new Set<string>();\n const queue = [...names]\n .map((name) => `node_modules/${name}`)\n .filter((key) => lock[key]);\n while (queue.length > 0) {\n const key = queue.pop()!;\n if (kept.has(key)) continue;\n kept.add(key);\n const entry = lock[key];\n for (const dependency of Object.keys({\n ...entry.dependencies,\n ...entry.optionalDependencies,\n })) {\n const target = resolveInLock(lock, key, dependency);\n if (target) queue.push(target);\n }\n }\n return kept;\n}\n\n/** The package a bare specifier belongs to, or null for a built-in or a path. */\nexport function packageOf(specifier: string): string | null {\n if (specifier.startsWith(\".\") || specifier.startsWith(\"/\")) return null;\n if (specifier.startsWith(\"node:\") || /^[a-z]+:/i.test(specifier)) return null;\n const parts = specifier.split(\"/\");\n return specifier.startsWith(\"@\") ? parts.slice(0, 2).join(\"/\") : parts[0];\n}\n\n/** One file of every package's licence, as a bundle can't keep them beside\n * the code. Packages under the same text share it. */\nfunction licencesOf(\n modules: string,\n packages: Iterable<string>,\n): { text: string; packages: number } {\n const byText = new Map<string, string[]>();\n let count = 0;\n for (const name of packages) {\n const dir = path.join(modules, name);\n if (!fs.existsSync(dir)) continue;\n const files = fs\n .readdirSync(dir)\n .filter(\n (file) =>\n /^(licen[sc]e|copying|notice)/i.test(file) &&\n isFile(path.join(dir, file)),\n )\n .sort();\n const text = files\n .map((file) => fs.readFileSync(path.join(dir, file), \"utf8\").trim())\n .join(\"\\n\\n\");\n const manifest = readJson(path.join(dir, \"package.json\"));\n const label = `${name}@${String(manifest.version ?? \"\")}`;\n const key =\n text || `License: ${JSON.stringify(manifest.license ?? \"unknown\")}`;\n byText.set(key, [...(byText.get(key) ?? []), label]);\n count++;\n }\n const sections = [...byText.entries()].map(\n ([text, labels]) => `${labels.join(\"\\n\")}\\n\\n${text}\\n`,\n );\n return { text: sections.join(`\\n${\"-\".repeat(72)}\\n\\n`), packages: count };\n}\n\nfunction readJson(file: string): Record<string, unknown> {\n return JSON.parse(fs.readFileSync(file, \"utf8\")) as Record<string, unknown>;\n}\n\nfunction packagesIn(modules: string): string[] {\n const names: string[] = [];\n for (const entry of fs.readdirSync(modules, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.name.startsWith(\".\")) continue;\n if (!entry.name.startsWith(\"@\")) {\n names.push(entry.name);\n continue;\n }\n for (const scoped of fs.readdirSync(path.join(modules, entry.name))) {\n names.push(`${entry.name}/${scoped}`);\n }\n }\n return names;\n}\n\n/** `__dirname` and `require` per chunk, as a banner collides with any code that\n * declares its own. */\nconst nodeGlobals = {\n name: \"ph:node-globals\",\n renderChunk(code: string) {\n const declared = (name: string) =>\n new RegExp(`\\\\b(?:const|let|var|function)\\\\s+${name}\\\\b`).test(code);\n const used = (name: string) =>\n new RegExp(`(?<![.\\\\w$])${name}\\\\b`).test(code);\n const wanted = [\"__filename\", \"__dirname\", \"require\"].filter(\n (name) => used(name) && !declared(name),\n );\n if (wanted.length === 0) return null;\n const lines = [`import { fileURLToPath as __ph_path } from \"node:url\";`];\n if (wanted.includes(\"__dirname\")) {\n lines.push(`import { dirname as __ph_dir } from \"node:path\";`);\n lines.push(`const __dirname = __ph_dir(__ph_path(import.meta.url));`);\n }\n if (wanted.includes(\"__filename\")) {\n lines.push(`const __filename = __ph_path(import.meta.url);`);\n }\n if (wanted.includes(\"require\")) {\n lines.push(\n `import { createRequire as __ph_require } from \"node:module\";`,\n );\n lines.push(`const require = __ph_require(import.meta.url);`);\n }\n return { code: `${lines.join(\"\\n\")}\\n${code}`, map: null };\n },\n};\n\nexport interface BundleBackendOptions {\n /** A staged stack, with its node_modules installed. */\n stackDir: string;\n logger?: (line: string) => void;\n}\n\nexport interface BundleBackendResult {\n chunks: number;\n removedPackages: number;\n keptPackages: number;\n}\n\n/** Replaces a staged stack's node_modules with a bundle of it. */\nexport async function bundleBackend(\n options: BundleBackendOptions,\n): Promise<BundleBackendResult> {\n const log = options.logger ?? (() => undefined);\n const { stackDir } = options;\n const modules = path.join(stackDir, \"node_modules\");\n const output = path.join(stackDir, \".bundle-output\");\n fs.rmSync(output, { recursive: true, force: true });\n\n const lock = (\n readJson(path.join(stackDir, \"package-lock.json\")) as {\n packages: Record<string, LockEntry>;\n }\n ).packages;\n const installed = packagesIn(modules);\n const byName = installed.filter((name) =>\n BY_NAME.some((pattern) => pattern.test(name)),\n );\n\n const input: Record<string, string> = {};\n const entriesOf = new Map<string, Map<string, string>>();\n const kept = new Map<string, Record<string, unknown>>();\n for (const name of byName) {\n const dir = path.join(modules, name);\n const manifest = readJson(path.join(dir, \"package.json\"));\n kept.set(name, manifest);\n const entries = new Map<string, string>();\n for (const [subpath, file] of exportedFiles(dir, manifest)) {\n if (!/\\.[cm]?js$/.test(file)) continue;\n const entry = entryNameOf(name, subpath);\n input[entry] = path.join(dir, file);\n entries.set(subpath, `${path.posix.basename(entry)}.mjs`);\n }\n entriesOf.set(name, entries);\n }\n const cli = path.join(modules, \"@powerhousedao/ph-run/dist/cli.mjs\");\n input[\"@powerhousedao/ph-run/dist/cli\"] = cli;\n // Found by path: see the top of this file.\n input[`${CHUNKS_DIR}/entry`] = path.join(\n modules,\n \"@powerhousedao/reactor-api/dist/src/pglite/worker/entry.mjs\",\n );\n input[`${CHUNKS_DIR}/dist/worker-entry`] = path.join(\n modules,\n \"@powerhousedao/reactor-workflow/dist/worker-entry.js\",\n );\n for (const [entry, file] of Object.entries(input)) {\n if (!fs.existsSync(file)) throw new Error(`no entry ${entry} at ${file}`);\n }\n log(\n ` bundling ${Object.keys(input).length} entries of ${byName.length} packages…`,\n );\n\n const { rolldown } = await import(\"rolldown\");\n const build = await rolldown({\n cwd: stackDir,\n input,\n platform: \"node\",\n external: EXTERNAL,\n onLog() {\n // Rolldown's warnings about the packages it folds are nobody's to fix.\n },\n plugins: [nodeGlobals],\n });\n const { output: written } = await build.write({\n dir: output,\n format: \"esm\",\n entryFileNames: (chunk) =>\n chunk.name === `${CHUNKS_DIR}/dist/worker-entry`\n ? `${CHUNKS_DIR}/dist/worker-entry.js`\n : \"[name].mjs\",\n chunkFileNames: `${CHUNKS_DIR}/[name]-[hash].mjs`,\n // A piece is told from other exports by its constructor's name.\n keepNames: true,\n sourcemap: false,\n });\n await build.close();\n\n // Whatever stays external has to stay installed, with what it needs.\n const ownFiles = new Set(written.map((file) => file.fileName));\n const reached = new Set<string>();\n for (const file of written) {\n if (file.type !== \"chunk\") continue;\n for (const specifier of [...file.imports, ...file.dynamicImports]) {\n const name = ownFiles.has(specifier) ? null : packageOf(specifier);\n if (name) reached.add(name);\n }\n // A require() a package's own build left in is a string to Rolldown.\n for (const [, specifier] of file.code.matchAll(REQUIRE_CALL)) {\n const name = packageOf(specifier);\n if (name && lock[`node_modules/${name}`]) reached.add(name);\n }\n }\n log(` left as files: ${[...reached].sort().join(\", \")}`);\n const keepInstalled = closureOf(lock, reached);\n const bundled = new Set(byName);\n\n const removed = installed.filter(\n (name) => !keepInstalled.has(`node_modules/${name}`) && !bundled.has(name),\n );\n const licences = licencesOf(modules, [...removed, ...byName]);\n fs.writeFileSync(\n path.join(stackDir, \"THIRD-PARTY-LICENSES.txt\"),\n licences.text,\n );\n\n for (const name of byName) {\n const dir = path.join(modules, name);\n const staged = path.join(output, name);\n fs.mkdirSync(staged, { recursive: true });\n for (const relative of KEEP_AS_FILES) {\n const from = path.join(dir, relative);\n if (fs.existsSync(from)) {\n fs.cpSync(from, path.join(staged, relative), { recursive: true });\n }\n }\n for (const file of fs.readdirSync(dir)) {\n const from = path.join(dir, file);\n if (/\\.json$/.test(file) && file !== \"package.json\" && isFile(from)) {\n fs.copyFileSync(from, path.join(staged, file));\n }\n }\n const manifest = kept.get(name) ?? {};\n const entries = entriesOf.get(name) ?? new Map<string, string>();\n for (const [subpath, file] of exportedFiles(dir, manifest as never)) {\n if (/\\.[cm]?js$/.test(file)) continue;\n const target = path.join(staged, file);\n if (!isFile(path.join(dir, file))) continue;\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.copyFileSync(path.join(dir, file), target);\n entries.set(subpath, file);\n }\n fs.writeFileSync(\n path.join(staged, \"package.json\"),\n `${JSON.stringify(keptManifest(manifest, entries), null, 2)}\\n`,\n );\n }\n fs.writeFileSync(\n path.join(output, CHUNKS_DIR, \"package.json\"),\n `${JSON.stringify({ name: \"ph-stack-bundle\", private: true, type: \"module\" })}\\n`,\n );\n\n for (const name of [...removed, ...byName]) {\n fs.rmSync(path.join(modules, name), { recursive: true, force: true });\n }\n fs.rmSync(path.join(modules, \".bin\"), { recursive: true, force: true });\n for (const entry of fs.readdirSync(modules, { withFileTypes: true })) {\n if (!entry.name.startsWith(\"@\") || !entry.isDirectory()) continue;\n const scope = path.join(modules, entry.name);\n if (fs.readdirSync(scope).length === 0) fs.rmdirSync(scope);\n }\n fs.cpSync(output, modules, { recursive: true });\n fs.rmSync(output, { recursive: true, force: true });\n\n const chunks = written.filter((file) => file.type === \"chunk\").length;\n log(\n ` bundled into ${chunks} files; ${removed.length} packages folded in, ${reached.size} left as files, licences of ${licences.packages} written`,\n );\n return {\n chunks,\n removedPackages: removed.length,\n keptPackages: keepInstalled.size,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,cAAc;;AAG3B,SAAgB,aAAa,IAAY,MAAsB;CAC7D,OAAO,UAAU,GAAG,GAAG,KAAK;AAC9B;;;AAIA,MAAa,qBAAqB;;AAGlC,MAAM,aAAuD;CAC3D,OAAO;CACP,QAAQ;CACR,OAAO;AACT;AACA,MAAM,eAAgD;CACpD,KAAK;CACL,OAAO;CACP,MAAM;CACN,KAAK;AACP;AAKA,MAAM,YAA0D;CAC9D,OAAO;EACL;GAAE,KAAK;GAAO,QAAQ;GAAQ,WAAW;EAAM;EAC/C;GAAE,KAAK;GAAO,QAAQ;GAAQ,WAAW;EAAM;EAC/C;GAAE,KAAK;GAAY,QAAQ;GAAa,WAAW;EAAW;CAChE;CACA,OAAO,CAAC;EAAE,KAAK;EAAQ,QAAQ;EAAc,WAAW;CAAO,CAAC;CAChE,QAAQ,CAGN;EAAE,KAAK;EAAO,QAAQ;CAAO,GAC7B;EAAE,KAAK;EAAS,QAAQ;EAAe,WAAW;CAAM,CAC1D;AACF;;;;AAKA,SAAgB,gBAAgB,MAAsB;CACpD,OAAO,KAAK,QAAQ,oBAAoB,GAAG;AAC7C;;;;;;;AAQA,SAAgB,eACd,SACA,SACA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.ZodString>;
69
69
  mimeType: z.ZodOptional<z.ZodString>;
70
70
  }, z.core.$strict>>>;
71
+ updates: z.ZodOptional<z.ZodNullable<z.ZodObject<{
72
+ github: z.ZodOptional<z.ZodString>;
73
+ endpoints: z.ZodOptional<z.ZodArray<z.ZodString>>;
74
+ pubkey: z.ZodString;
75
+ }, z.core.$strict>>>;
71
76
  shell: z.ZodOptional<z.ZodObject<{
72
77
  path: z.ZodOptional<z.ZodString>;
73
78
  git: z.ZodOptional<z.ZodString>;
@@ -78,12 +83,16 @@ export declare const appJsonSchema: z.ZodObject<{
78
83
  }, z.core.$strict>;
79
84
  type AppJson = z.infer<typeof appJsonSchema>;
80
85
  type AppJsonShellSource = NonNullable<AppJson["shell"]>;
86
+ type AppJsonUpdates = NonNullable<AppJson["updates"]>;
87
+ /** Where an app with updates asks for a newer version. */
88
+ export declare function updateEndpoints(updates: AppJsonUpdates): string[];
81
89
  /** Default crates.io version requirement for the shell crate (D7.b: the flip
82
90
  * to crates.io default once published — the crate is live). A floor, not just
83
- * a series: 0.1.0 can't run a stack from ph-run, and a Cargo.lock that still
84
- * holds it satisfies "0.1", so a builder's lock would keep it forever. The
85
- * 0.1.0-dev.N releases sort below 0.1.0 and never match either. */
86
- export declare const DEFAULT_SHELL_CRATE_VERSION = "0.1.1";
91
+ * a series: 0.1.0 can't run a stack from ph-run and 0.1.1 has no updater (an
92
+ * app with `updates` would build and never ask), and a Cargo.lock that still
93
+ * holds one of them satisfies "0.1", so a builder's lock would keep it
94
+ * forever. The 0.1.x-dev.N releases sort below 0.1.x and never match either. */
95
+ export declare const DEFAULT_SHELL_CRATE_VERSION = "0.1.2";
87
96
  export declare const APP_JSON_FILE = "app.json";
88
97
  /** Read + validate hosts/<host>/app.json. Throws with the field named on a
89
98
  * bad value, and a clear message when the file is absent. */
@@ -157,6 +166,9 @@ export declare function bundleStack(options: BundleStackOptions): BundleStackRes
157
166
  export declare const SHELL_DIR = "tauri-shell";
158
167
  /** The icon source the runner feeds to `tauri icon` (copied from app.icon). */
159
168
  export declare const ICON_SOURCE = "app-icon.png";
169
+ /** Beside tauri.conf.json in an app with updates: the settings of a build
170
+ * that has no signing key to hand, which cannot be offered as an update. */
171
+ export declare const UNSIGNED_BUILD_CONF = "tauri.unsigned.conf.json";
160
172
  interface ProjectShellInput {
161
173
  /** hosts/<host>/ — where app.json lives and tauri-shell/ is written. */
162
174
  hostDir: string;
@@ -183,6 +195,68 @@ interface ProjectShellResult {
183
195
  */
184
196
  export declare function projectShell(input: ProjectShellInput): ProjectShellResult;
185
197
  //#endregion
198
+ //#region src/release.d.ts
199
+ /**
200
+ * What a build of an app with updates leaves for its release (app.json
201
+ * `updates`): under `<shell>/target/release/bundle/release/`, every installer
202
+ * it made, under a name no host rewrites, and the feed file that tells the
203
+ * running apps of this system about them. Attach every file in that folder to
204
+ * the release and the apps find it.
205
+ *
206
+ * One feed file per system and processor (`latest-linux-x86_64.json`), not one
207
+ * for the whole release: each system builds in its own job, and a job that
208
+ * fails then costs its own users the update and nobody else's. The app asks
209
+ * for its own file by name (FEED_FILE_TEMPLATE).
210
+ */
211
+ /** Under the bundle folder: this build's release files. */
212
+ export declare const RELEASE_DIR = "release";
213
+ /** The feed file a build writes for its system and processor. */
214
+ export declare function feedFileName(os: string, arch: string): string;
215
+ /** That name in a feed address: the updater fills in the running app's own
216
+ * system (linux, darwin, windows) and processor (x86_64, aarch64, …). */
217
+ export declare const FEED_FILE_TEMPLATE = "latest-{{target}}-{{arch}}.json";
218
+ /** A file name every host keeps as it is: GitHub rewrites a space (and most
219
+ * punctuation) in a release file's name to a dot, and a feed that names the
220
+ * file as it was built would then point at nothing. */
221
+ export declare function releaseFileName(name: string): string;
222
+ /**
223
+ * Where a release's files are downloaded from: PH_DESKTOP_RELEASE_URL when
224
+ * set, else the GitHub release of app.json's `updates.github` under this
225
+ * build's tag (the tag a workflow runs for, else `v<version>`). null when
226
+ * neither says: the build then writes no feed file.
227
+ */
228
+ export declare function releaseBaseUrl(updates: AppJsonUpdates, version: string | undefined, env: Record<string, string | undefined>): string | null;
229
+ interface CollectReleaseInput {
230
+ /** `<shell>/target/release/bundle`. */
231
+ bundleDir: string;
232
+ productName: string;
233
+ /** The version the installers carry, which is the one that was signed. */
234
+ version: string;
235
+ /** Where the files will be downloaded from; null writes no feed file. */
236
+ baseUrl: string | null;
237
+ /** Only what was written from this time on (ms): an earlier build's files
238
+ * are no part of this release. */
239
+ since?: number;
240
+ platform?: NodeJS.Platform;
241
+ arch?: string;
242
+ now?: Date;
243
+ }
244
+ interface CollectedRelease {
245
+ dir: string;
246
+ /** Every file in `dir`, the feed included. */
247
+ files: string[];
248
+ /** The feed file's name, when one was written. */
249
+ feed: string | null;
250
+ /** What the feed offers: `linux-x86_64-deb`, … */
251
+ targets: string[];
252
+ /** Installers a running app could take, had they been signed. */
253
+ unsigned: string[];
254
+ }
255
+ /** Gathers this build's release files and writes its feed file. */
256
+ export declare function collectRelease(input: CollectReleaseInput): CollectedRelease;
257
+ /** What a build says about the release files it gathered. */
258
+ export declare function releaseReport(release: CollectedRelease, releaseUrl: string | null): string[];
259
+ //#endregion
186
260
  //#region src/scaffold.d.ts
187
261
  /**
188
262
  * P7.5 — scaffold a builder-owned desktop identity: `hosts/desktop/app.json`
@@ -252,6 +326,15 @@ export declare function fetchNodeSidecar(shellDir: string, version?: string, pla
252
326
  * macOS gets app+dmg, Windows nsis, Linux deb+appimage — a host only builds
253
327
  * installers it can produce. */
254
328
  export declare function tauriBundlesForHost(platform?: NodeJS.Platform): string[];
329
+ /** `tauri build`'s arguments. An app with updates signs what it builds, so
330
+ * without the key (`TAURI_SIGNING_PRIVATE_KEY`) the build would fail at its
331
+ * last step: such a build leaves the signatures out instead, laying
332
+ * `unsignedConf` over the configuration, and still makes its installers. */
333
+ export declare function tauriBuildArgs(bundles: string[], updates: {
334
+ on: boolean;
335
+ signingKey: boolean;
336
+ unsignedConf: string;
337
+ }): string[];
255
338
  interface TauriCommand {
256
339
  /** The executable to spawn (e.g. "cargo" or a node path). */
257
340
  cmd: string;
@@ -328,6 +411,6 @@ interface BundleBackendResult {
328
411
  /** Replaces a staged stack's node_modules with a bundle of it. */
329
412
  export declare function bundleBackend(options: BundleBackendOptions): Promise<BundleBackendResult>;
330
413
  //#endregion
331
- export type { AppJson, AppJsonShellSource, BundleBackendResult, BundleStackOptions, BundleStackResult, NodeTarget, ProjectShellInput, ProjectShellResult, ResolvedShell, ScaffoldDesktopShellOptions, ScaffoldResult, ShellOptions, TauriCommand, Toolchain };
414
+ export type { AppJson, AppJsonShellSource, AppJsonUpdates, BundleBackendResult, BundleStackOptions, BundleStackResult, CollectReleaseInput, CollectedRelease, NodeTarget, ProjectShellInput, ProjectShellResult, ResolvedShell, ScaffoldDesktopShellOptions, ScaffoldResult, ShellOptions, TauriCommand, Toolchain };
332
415
  export {};
333
416
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/app-json.ts","../src/bundle-stack.ts","../src/shell-project.ts","../src/scaffold.ts","../src/shell-toolchain.ts","../src/shell.ts","../src/bundle-backend.ts"],"mappings":";;;;;qBA8Ja,eAAa,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyBxB,EAAA,KAAA;KAEU,UAAU,EAAE,aAAa;KACzB,qBAAqB,YAAY;;;;;;qBAOhC;qBAEA;;;wBAIG,YAAY,kBAAkB;;;wBA2B9B,QAAQ,KAAK;;;UCvGZ;EACf;EACA;;;EAGA;;;;EAIA;;;EAGA;;;;;;EAMA;;;EAGA;;;EAGA;;;EAGA;;;EAGA;EACA,UAAU;;UAGK;EACf;EACA;;;;;;;;wBAiNc,WAAW,aAAa;wBA2BxB,YAAY,SAAS,qBAAqB;;;;;;;;;;;;;;;;;qBC3W7C;;qBAEA;UAEI;;EAEf;EACA,KAAK;;;EAGL;;EAEA;;EAEA,eAAe;;UAUA;EACf;;EAEA;;EAEA;;;;;;;wBAwdc,aAAa,OAAO,oBAAoB;;;;;;;;;UCtgBvC;;EAEf;;EAEA;;EAEA;;;;EAIA,aAAa;;;;;;;wBAQC,iBACd,YAAY,cACZ,iBACA,gBACC;UAcc;EACf;;EAEA;;EAEA;;;;;wBAMc,SACd,cACA,yCACC;wBAoEa,qBACd,iBACA,SAAS,8BACR;;;;;;;;;;;;;;;UCrHc;EACf;EACA;;EAEA;EACA;;;;wBAKc,kBACd,UAAU,OAAO,UACjB,eACC;;;;wBAwCa,iBACd,kBACA,kBACA,WAAU,OAAO,UACjB;;;;wBA2Bc,oBACd,WAAU,OAAO;UAYF;;EAEf;;EAEA;;EAEA;;;;wBAuCc,oBAAoB,sBAAsB;UA6BzC;EACf;EACA,OAAO;;wBAGO,gBAAgB,sBAAsB;;;;wBAOtC,iBACd,IAAI,WACJ,mBACC;;;wBA2Ba,aACd,OAAO,cACP,kBACA;;;;;;;;;;UC7Ne;;EAEf;EACA;IAAW;IAAgB;IAAgB;;EAC3C;EACA;;UAGe;EACf;;;EAGA;;wBAGc,aACd,qBACA,SAAS,0BACT,KAAK,qCACJ;;;wBA4Ba,kBAAkB;;;wBAUlB,SACd,qBACA,qBACA,KAAK,qCACJ;;;;wBAaa,iBACd,SAAS,2BACR;wBA2Ba,YACd,OAAO,eACP,SAAS,wBACT,SAAS,2BACR;;;UCyLc;;EAEf;EACA,UAAU;;UAGK;EACf;EACA;EACA;;;wBAIoB,cACpB,SAAS,uBACR,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/app-json.ts","../src/bundle-stack.ts","../src/shell-project.ts","../src/release.ts","../src/scaffold.ts","../src/shell-toolchain.ts","../src/shell.ts","../src/bundle-backend.ts"],"mappings":";;;;;qBAwNa,eAAa,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BxB,EAAA,KAAA;KAEU,UAAU,E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sBAAsB;UA6BzC;EACf;EACA,OAAO;;wBAGO,gBAAgB,sBAAsB;;;;wBAOtC,iBACd,IAAI,WACJ,mBACC;;;wBA2Ba,aACd,OAAO,cACP,kBACA;;;;;;;;;;UC5Oe;;EAEf;EACA;IAAW;IAAgB;IAAgB;;EAC3C;EACA;;UAGe;EACf;;;EAGA;;wBAGc,aACd,qBACA,SAAS,0BACT,KAAK,qCACJ;;;wBA4Ba,kBAAkB;;;wBAUlB,SACd,qBACA,qBACA,KAAK,qCACJ;;;;wBAaa,iBACd,SAAS,2BACR;wBA2Ba,YACd,OAAO,eACP,SAAS,wBACT,SAAS,2BACR;;;UCyLc;;EAEf;EACA,UAAU;;UAGK;EACf;EACA;EACA;;;wBAIoB,cACpB,SAAS,uBACR,QAAQ"}
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { C as appJsonSchema, S as DEFAULT_SHELL_CRATE_VERSION, T as loadAppJson, _ as projectShell, a as shellEnv, b as pruneStack, c as fetchNodeSidecar, d as resolveTauriCommand, f as runTauriIcon, g as SHELL_DIR, h as ICON_SOURCE, i as resolveShell, l as nodeSidecarTarget, n as launchShell, o as tauriConfigPatch, p as tauriBundlesForHost, r as resolvePhCliEntry, s as detectToolchain, t as bundleBackend, u as preflightOrThrow, v as bundleStack, w as appSlug, x as APP_JSON_FILE } from "./bundle-backend-CvUS8-oc.mjs";
1
+ import { A as FEED_FILE_TEMPLATE, C as pruneStack, D as appSlug, E as appJsonSchema, F as releaseFileName, I as releaseReport, M as collectRelease, N as feedFileName, O as loadAppJson, P as releaseBaseUrl, T as DEFAULT_SHELL_CRATE_VERSION, _ as SHELL_DIR, a as shellEnv, b as projectShell, c as fetchNodeSidecar, d as resolveTauriCommand, f as runTauriIcon, g as ICON_SOURCE, i as resolveShell, j as RELEASE_DIR, k as updateEndpoints, l as nodeSidecarTarget, m as tauriBundlesForHost, n as launchShell, o as tauriConfigPatch, p as tauriBuildArgs, r as resolvePhCliEntry, s as detectToolchain, t as bundleBackend, u as preflightOrThrow, v as UNSIGNED_BUILD_CONF, w as APP_JSON_FILE, x as bundleStack } from "./bundle-backend-D28j6a5_.mjs";
2
2
  import { mapBackgroundImages } from "@powerhousedao/shared/connect";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
@@ -111,7 +111,8 @@ function scaffoldDesktopShell(hostDir, options) {
111
111
  ext: ["phd"],
112
112
  name: "Powerhouse Document",
113
113
  mimeType: "application/vnd.powerhouse.document+zip"
114
- }]
114
+ }],
115
+ updates: null
115
116
  };
116
117
  appJsonSchema.parse(app);
117
118
  const appJsonPath = path.join(hostDir, APP_JSON_FILE);
@@ -144,6 +145,6 @@ function scaffoldDesktopShell(hostDir, options) {
144
145
  };
145
146
  }
146
147
  //#endregion
147
- export { APP_JSON_FILE, DEFAULT_SHELL_CRATE_VERSION, ICON_SOURCE, SHELL_DIR, appJsonSchema, appSlug, bundleBackend, bundleStack, detectToolchain, fetchNodeSidecar, launchShell, loadAppJson, nodeSidecarTarget, preflightOrThrow, projectShell, pruneStack, rebaseBackground, resolvePhCliEntry, resolveShell, resolveTauriCommand, runTauriIcon, scaffoldDesktopShell, shellEnv, solidPng, tauriBundlesForHost, tauriConfigPatch };
148
+ export { APP_JSON_FILE, DEFAULT_SHELL_CRATE_VERSION, FEED_FILE_TEMPLATE, ICON_SOURCE, RELEASE_DIR, SHELL_DIR, UNSIGNED_BUILD_CONF, appJsonSchema, appSlug, bundleBackend, bundleStack, collectRelease, detectToolchain, feedFileName, fetchNodeSidecar, launchShell, loadAppJson, nodeSidecarTarget, preflightOrThrow, projectShell, pruneStack, rebaseBackground, releaseBaseUrl, releaseFileName, releaseReport, resolvePhCliEntry, resolveShell, resolveTauriCommand, runTauriIcon, scaffoldDesktopShell, shellEnv, solidPng, tauriBuildArgs, tauriBundlesForHost, tauriConfigPatch, updateEndpoints };
148
149
 
149
150
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/scaffold.ts"],"sourcesContent":["import type { PHBackground } from \"@powerhousedao/shared/clis\";\nimport { mapBackgroundImages } from \"@powerhousedao/shared/connect\";\nimport { isPassthroughImageRef } from \"@powerhousedao/shared/connect/image-ref\";\nimport { deflateSync } from \"node:zlib\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { appJsonSchema, APP_JSON_FILE, type AppJson } from \"./app-json.js\";\n\n/**\n * P7.5 — scaffold a builder-owned desktop identity: `hosts/desktop/app.json`\n * (the ONE file a builder edits), a placeholder square icon source, and a\n * `.gitignore` for the generated shell. `ph generate desktop-shell` calls\n * this; the runner's dev/build then project app.json into `tauri-shell/`.\n */\n\nexport interface ScaffoldDesktopShellOptions {\n /** Reverse-DNS app identifier (e.g. com.acme.app). */\n identifier: string;\n /** Human product name (the window title + macOS app name). */\n productName: string;\n /** Overwrite an existing app.json (default: refuse, to protect edits). */\n force?: boolean;\n /** The loading page's background, with its paths already relative to the\n * host directory (see `rebaseBackground`); `ph generate desktop-shell`\n * passes Connect's `connect.home.background`. Default: none. */\n background?: PHBackground | null;\n}\n\n/**\n * A background whose project-relative paths are rewritten to be relative to\n * another directory (powerhouse.config.json's root -> hosts/desktop, where\n * app.json resolves them from). URLs and data URIs are left as they are.\n */\nexport function rebaseBackground(\n background: PHBackground,\n fromDir: string,\n toDir: string,\n): PHBackground {\n const rebase = (ref: string): string => {\n if (isPassthroughImageRef(ref)) return ref;\n const rel = path\n .relative(toDir, path.resolve(fromDir, ref))\n .split(path.sep)\n .join(\"/\");\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n };\n return typeof background === \"string\"\n ? rebase(background)\n : mapBackgroundImages(background, rebase);\n}\n\nexport interface ScaffoldResult {\n hostDir: string;\n /** Files created this call (absolute paths). */\n created: string[];\n /** Files already present and left untouched. */\n skipped: string[];\n}\n\n/** Minimal PNG encoder — a solid square so `tauri icon` always has a valid\n * source. Pure Node (zlib); no binary asset ships in the package. The builder\n * replaces it with their real 1024×1024 artwork. */\nexport function solidPng(\n size: number,\n rgba: [number, number, number, number],\n): Buffer {\n const [r, g, b, a] = rgba;\n // raw image: each row is a filter byte (0) + size*4 RGBA bytes\n const row = Buffer.alloc(1 + size * 4);\n for (let x = 0; x < size; x++) {\n const o = 1 + x * 4;\n row[o] = r;\n row[o + 1] = g;\n row[o + 2] = b;\n row[o + 3] = a;\n }\n const raw = Buffer.concat(Array.from({ length: size }, () => row));\n const idat = deflateSync(raw);\n\n const chunk = (type: string, data: Buffer): Buffer => {\n const len = Buffer.alloc(4);\n len.writeUInt32BE(data.length, 0);\n const typeBuf = Buffer.from(type, \"ascii\");\n const body = Buffer.concat([typeBuf, data]);\n const crc = Buffer.alloc(4);\n crc.writeUInt32BE(crc32(body) >>> 0, 0);\n return Buffer.concat([len, body, crc]);\n };\n\n const ihdr = Buffer.alloc(13);\n ihdr.writeUInt32BE(size, 0);\n ihdr.writeUInt32BE(size, 4);\n ihdr[8] = 8; // bit depth\n ihdr[9] = 6; // color type RGBA\n ihdr[10] = 0; // compression\n ihdr[11] = 0; // filter\n ihdr[12] = 0; // interlace\n\n return Buffer.concat([\n Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),\n chunk(\"IHDR\", ihdr),\n chunk(\"IDAT\", idat),\n chunk(\"IEND\", Buffer.alloc(0)),\n ]);\n}\n\nlet crcTable: number[] | undefined;\nfunction crc32(buf: Buffer): number {\n if (!crcTable) {\n crcTable = [];\n for (let n = 0; n < 256; n++) {\n let c = n;\n for (let k = 0; k < 8; k++) {\n c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n }\n crcTable[n] = c;\n }\n }\n let crc = 0xffffffff;\n for (let i = 0; i < buf.length; i++) {\n crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);\n }\n return crc ^ 0xffffffff;\n}\n\nconst GITIGNORE = `# Generated tauri shell — only Cargo.lock and app-icon.png are tracked.\n/tauri-shell/target\n/tauri-shell/gen\n/tauri-shell/icons\n/tauri-shell/dist-stack\n/tauri-shell/binaries\n`;\n\nexport function scaffoldDesktopShell(\n hostDir: string,\n options: ScaffoldDesktopShellOptions,\n): ScaffoldResult {\n const created: string[] = [];\n const skipped: string[] = [];\n fs.mkdirSync(hostDir, { recursive: true });\n\n const iconFile = \"icon.png\";\n const app: AppJson = {\n identifier: options.identifier,\n productName: options.productName,\n icon: `./${iconFile}`,\n // The loading page's branding; null = the defaults (see app-json.ts).\n background: options.background ?? null,\n loading: null,\n window: { title: options.productName, width: 1440, height: 900 },\n fileAssociations: [\n {\n ext: [\"phd\"],\n name: \"Powerhouse Document\",\n mimeType: \"application/vnd.powerhouse.document+zip\",\n },\n ],\n };\n // Fail fast if we ever emit something the loader would reject.\n appJsonSchema.parse(app);\n\n const appJsonPath = path.join(hostDir, APP_JSON_FILE);\n if (fs.existsSync(appJsonPath) && !options.force) {\n skipped.push(appJsonPath);\n } else {\n fs.writeFileSync(appJsonPath, `${JSON.stringify(app, null, 2)}\\n`);\n created.push(appJsonPath);\n }\n\n const iconPath = path.join(hostDir, iconFile);\n if (fs.existsSync(iconPath)) {\n skipped.push(iconPath);\n } else {\n // 1024² indigo placeholder — a real, square, replaceable source icon.\n fs.writeFileSync(iconPath, solidPng(1024, [79, 70, 229, 255]));\n created.push(iconPath);\n }\n\n const gitignorePath = path.join(hostDir, \".gitignore\");\n if (fs.existsSync(gitignorePath)) {\n skipped.push(gitignorePath);\n } else {\n fs.writeFileSync(gitignorePath, GITIGNORE);\n created.push(gitignorePath);\n }\n\n return { hostDir, created, skipped };\n}\n"],"mappings":";;;;;;;;;;;;AAiCA,SAAgB,iBACd,YACA,SACA,OACc;CACd,MAAM,UAAU,QAAwB;EACtC,IAAI,sBAAsB,GAAG,GAAG,OAAO;EACvC,MAAM,MAAM,KACT,SAAS,OAAO,KAAK,QAAQ,SAAS,GAAG,CAAC,CAAC,CAC3C,MAAM,KAAK,GAAG,CAAC,CACf,KAAK,GAAG;EACX,OAAO,IAAI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EL,GAAG,cAAc,UAAU,SAAS,MAAM;GAAC;GAAI;GAAI;GAAK;EAAG,CAAC,CAAC;EAC7D,QAAQ,KAAK,QAAQ;CACvB;CAEA,MAAM,gBAAgB,KAAK,KAAK,SAAS,YAAY;CACrD,IAAI,GAAG,WAAW,aAAa,GAC7B,QAAQ,KAAK,aAAa;MACrB;EACL,GAAG,cAAc,eAAe,SAAS;EACzC,QAAQ,KAAK,aAAa;CAC5B;CAEA,OAAO;EAAE;EAAS;EAAS;CAAQ;AACrC"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/scaffold.ts"],"sourcesContent":["import type { PHBackground } from \"@powerhousedao/shared/clis\";\nimport { mapBackgroundImages } from \"@powerhousedao/shared/connect\";\nimport { isPassthroughImageRef } from \"@powerhousedao/shared/connect/image-ref\";\nimport { deflateSync } from \"node:zlib\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { appJsonSchema, APP_JSON_FILE, type AppJson } from \"./app-json.js\";\n\n/**\n * P7.5 — scaffold a builder-owned desktop identity: `hosts/desktop/app.json`\n * (the ONE file a builder edits), a placeholder square icon source, and a\n * `.gitignore` for the generated shell. `ph generate desktop-shell` calls\n * this; the runner's dev/build then project app.json into `tauri-shell/`.\n */\n\nexport interface ScaffoldDesktopShellOptions {\n /** Reverse-DNS app identifier (e.g. com.acme.app). */\n identifier: string;\n /** Human product name (the window title + macOS app name). */\n productName: string;\n /** Overwrite an existing app.json (default: refuse, to protect edits). */\n force?: boolean;\n /** The loading page's background, with its paths already relative to the\n * host directory (see `rebaseBackground`); `ph generate desktop-shell`\n * passes Connect's `connect.home.background`. Default: none. */\n background?: PHBackground | null;\n}\n\n/**\n * A background whose project-relative paths are rewritten to be relative to\n * another directory (powerhouse.config.json's root -> hosts/desktop, where\n * app.json resolves them from). URLs and data URIs are left as they are.\n */\nexport function rebaseBackground(\n background: PHBackground,\n fromDir: string,\n toDir: string,\n): PHBackground {\n const rebase = (ref: string): string => {\n if (isPassthroughImageRef(ref)) return ref;\n const rel = path\n .relative(toDir, path.resolve(fromDir, ref))\n .split(path.sep)\n .join(\"/\");\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n };\n return typeof background === \"string\"\n ? rebase(background)\n : mapBackgroundImages(background, rebase);\n}\n\nexport interface ScaffoldResult {\n hostDir: string;\n /** Files created this call (absolute paths). */\n created: string[];\n /** Files already present and left untouched. */\n skipped: string[];\n}\n\n/** Minimal PNG encoder — a solid square so `tauri icon` always has a valid\n * source. Pure Node (zlib); no binary asset ships in the package. The builder\n * replaces it with their real 1024×1024 artwork. */\nexport function solidPng(\n size: number,\n rgba: [number, number, number, number],\n): Buffer {\n const [r, g, b, a] = rgba;\n // raw image: each row is a filter byte (0) + size*4 RGBA bytes\n const row = Buffer.alloc(1 + size * 4);\n for (let x = 0; x < size; x++) {\n const o = 1 + x * 4;\n row[o] = r;\n row[o + 1] = g;\n row[o + 2] = b;\n row[o + 3] = a;\n }\n const raw = Buffer.concat(Array.from({ length: size }, () => row));\n const idat = deflateSync(raw);\n\n const chunk = (type: string, data: Buffer): Buffer => {\n const len = Buffer.alloc(4);\n len.writeUInt32BE(data.length, 0);\n const typeBuf = Buffer.from(type, \"ascii\");\n const body = Buffer.concat([typeBuf, data]);\n const crc = Buffer.alloc(4);\n crc.writeUInt32BE(crc32(body) >>> 0, 0);\n return Buffer.concat([len, body, crc]);\n };\n\n const ihdr = Buffer.alloc(13);\n ihdr.writeUInt32BE(size, 0);\n ihdr.writeUInt32BE(size, 4);\n ihdr[8] = 8; // bit depth\n ihdr[9] = 6; // color type RGBA\n ihdr[10] = 0; // compression\n ihdr[11] = 0; // filter\n ihdr[12] = 0; // interlace\n\n return Buffer.concat([\n Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),\n chunk(\"IHDR\", ihdr),\n chunk(\"IDAT\", idat),\n chunk(\"IEND\", Buffer.alloc(0)),\n ]);\n}\n\nlet crcTable: number[] | undefined;\nfunction crc32(buf: Buffer): number {\n if (!crcTable) {\n crcTable = [];\n for (let n = 0; n < 256; n++) {\n let c = n;\n for (let k = 0; k < 8; k++) {\n c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n }\n crcTable[n] = c;\n }\n }\n let crc = 0xffffffff;\n for (let i = 0; i < buf.length; i++) {\n crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);\n }\n return crc ^ 0xffffffff;\n}\n\nconst GITIGNORE = `# Generated tauri shell — only Cargo.lock and app-icon.png are tracked.\n/tauri-shell/target\n/tauri-shell/gen\n/tauri-shell/icons\n/tauri-shell/dist-stack\n/tauri-shell/binaries\n`;\n\nexport function scaffoldDesktopShell(\n hostDir: string,\n options: ScaffoldDesktopShellOptions,\n): ScaffoldResult {\n const created: string[] = [];\n const skipped: string[] = [];\n fs.mkdirSync(hostDir, { recursive: true });\n\n const iconFile = \"icon.png\";\n const app: AppJson = {\n identifier: options.identifier,\n productName: options.productName,\n icon: `./${iconFile}`,\n // The loading page's branding; null = the defaults (see app-json.ts).\n background: options.background ?? null,\n loading: null,\n window: { title: options.productName, width: 1440, height: 900 },\n fileAssociations: [\n {\n ext: [\"phd\"],\n name: \"Powerhouse Document\",\n mimeType: \"application/vnd.powerhouse.document+zip\",\n },\n ],\n // Off until the app has a release feed and a signing key (app-json.ts).\n updates: null,\n };\n // Fail fast if we ever emit something the loader would reject.\n appJsonSchema.parse(app);\n\n const appJsonPath = path.join(hostDir, APP_JSON_FILE);\n if (fs.existsSync(appJsonPath) && !options.force) {\n skipped.push(appJsonPath);\n } else {\n fs.writeFileSync(appJsonPath, `${JSON.stringify(app, null, 2)}\\n`);\n created.push(appJsonPath);\n }\n\n const iconPath = path.join(hostDir, iconFile);\n if (fs.existsSync(iconPath)) {\n skipped.push(iconPath);\n } else {\n // 1024² indigo placeholder — a real, square, replaceable source icon.\n fs.writeFileSync(iconPath, solidPng(1024, [79, 70, 229, 255]));\n created.push(iconPath);\n }\n\n const gitignorePath = path.join(hostDir, \".gitignore\");\n if (fs.existsSync(gitignorePath)) {\n skipped.push(gitignorePath);\n } else {\n fs.writeFileSync(gitignorePath, GITIGNORE);\n created.push(gitignorePath);\n }\n\n return { hostDir, created, skipped };\n}\n"],"mappings":";;;;;;;;;;;;AAiCA,SAAgB,iBACd,YACA,SACA,OACc;CACd,MAAM,UAAU,QAAwB;EACtC,IAAI,sBAAsB,GAAG,GAAG,OAAO;EACvC,MAAM,MAAM,KACT,SAAS,OAAO,KAAK,QAAQ,SAAS,GAAG,CAAC,CAAC,CAC3C,MAAM,KAAK,GAAG,CAAC,CACf,KAAK,GAAG;EACX,OAAO,IAAI,WAAW,GAAG,IAAI,MAAM,KAAK;CAC1C;CACA,OAAO,OAAO,eAAe,WACzB,OAAO,UAAU,IACjB,oBAAoB,YAAY,MAAM;AAC5C;;;;AAaA,SAAgB,SACd,MACA,MACQ;CACR,MAAM,CAAC,GAAG,GAAG,GAAG,KAAK;CAErB,MAAM,MAAM,OAAO,MAAM,IAAI,OAAO,CAAC;CACrC,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK;EAC7B,MAAM,IAAI,IAAI,IAAI;EAClB,IAAI,KAAK;EACT,IAAI,IAAI,KAAK;EACb,IAAI,IAAI,KAAK;EACb,IAAI,IAAI,KAAK;CACf;CACA,MAAM,MAAM,OAAO,OAAO,MAAM,KAAK,EAAE,QAAQ,KAAK,SAAS,GAAG,CAAC;CACjE,MAAM,OAAO,YAAY,GAAG;CAE5B,MAAM,SAAS,MAAc,SAAyB;EACpD,MAAM,MAAM,OAAO,MAAM,CAAC;EAC1B,IAAI,cAAc,KAAK,QAAQ,CAAC;EAChC,MAAM,UAAU,OAAO,KAAK,MAAM,OAAO;EACzC,MAAM,OAAO,OAAO,OAAO,CAAC,SAAS,IAAI,CAAC;EAC1C,MAAM,MAAM,OAAO,MAAM,CAAC;EAC1B,IAAI,cAAc,MAAM,IAAI,MAAM,GAAG,CAAC;EACtC,OAAO,OAAO,OAAO;GA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