@shware/workflow-ui 2.2.8 → 2.2.10

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.
package/dist/cli.mjs CHANGED
@@ -535,7 +535,9 @@ function sourcePosition(cwd, rawFile, line) {
535
535
  * journey project keeps beside its code. `fs.allow` spans the project and its linked workspace
536
536
  * packages (see {@link studioFsAllow}), so without these
537
537
  * `/@fs/<path>/.dev.vars` (wrangler's secrets), an APNs `.p8` or a Firebase service account would
538
- * be one request away for any page that can reach the port.
538
+ * be one request away for any page that can reach the port. The same goes for what sits beside
539
+ * any project: registry and network tokens (`.npmrc`, `.netrc`), direnv's `.envrc` (which
540
+ * `.env.*` does not match), key stores, and the wrangler config with its `vars`.
539
541
  */
540
542
  const STUDIO_FS_DENY = [
541
543
  ...[
@@ -545,10 +547,17 @@ const STUDIO_FS_DENY = [
545
547
  "**/.git/**"
546
548
  ],
547
549
  "**/.dev.vars*",
550
+ "**/.envrc",
551
+ "**/.npmrc",
552
+ "**/.netrc",
553
+ "**/wrangler.{toml,json,jsonc}",
548
554
  "**/*.p8",
549
555
  "**/*.plist",
550
556
  "**/google-services.json",
551
557
  "**/*.pfx",
558
+ "**/*.p12",
559
+ "**/*.jks",
560
+ "**/*.keystore",
552
561
  "**/*.pem",
553
562
  "**/*.key"
554
563
  ];
package/dist/cli.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.mjs","names":[],"sources":["../src/server/project.ts","../src/server.ts","../src/generate.ts","../src/cli.ts"],"sourcesContent":["import {\n ConfigCompileError,\n type JourneyConfig,\n compileConfig,\n isConfig,\n isDiscordTemplate,\n isEmailTemplate,\n isPushTemplate,\n isSlackTemplate,\n} from '@shware/workflow';\nimport type { ViteDevServer } from 'vite';\nimport type { ResolvedStudioConfig, StudioError } from '../config';\n\n/**\n * Reading the project — on the dev server, never in the browser.\n *\n * workflow.config.ts default-exports `defineConfig({...})` from\n * `@shware/workflow`, and the studio reads exactly that: its workflows,\n * segments, actions, template registries, title and what the email templates share. It is\n * compiled with `compileConfig`, the same compile the Worker deploys, so the\n * studio lists exactly what would ship.\n *\n * What crosses to the browser is decided here too. The config is a source\n * object — schemas, components, the contract, runtime settings, whatever the\n * host imports — so it stays on the server. The browser receives the compiled\n * IR as JSON, and imports the two template registries (the code a preview has\n * to run) straight from the modules that export them, located by identity in\n * Vite's SSR module graph. It never imports workflow.config.ts.\n */\n\n/** How the server evaluates a project module (Vite's ssrLoadModule in the studio). */\nexport type ModuleLoader = (file: string) => Promise<Record<string, unknown>>;\n\n/** Every module the loader has evaluated so far, with its exports. */\nexport type LoadedModules = () => Iterable<[file: string, exports: Record<string, unknown>]>;\n\n/** The modules a Vite server has evaluated for SSR — where registries are located by identity. */\nexport function ssrModulesOf(server: ViteDevServer): LoadedModules {\n return function* () {\n for (const mod of server.moduleGraph.idToModuleMap.values()) {\n const exports = mod.ssrModule as Record<string, unknown> | null;\n if (mod.file !== null && exports !== null) yield [mod.file, exports];\n }\n };\n}\n\ntype Channel = 'email' | 'push' | 'discord' | 'slack';\n\n/** One named export the browser imports — or one channel of it, for an exported `{ email, push }`. */\nexport interface ModuleRef {\n file: string;\n name: string;\n property?: Channel;\n}\n\n/** Per channel: how to recognise its entries, the factory to name, the virtual module's field. */\nconst CHANNELS: Record<\n Channel,\n { is: (value: unknown) => boolean; factory: string; field: string }\n> = {\n email: { is: isEmailTemplate, factory: 'emailTemplate', field: 'emails' },\n push: { is: isPushTemplate, factory: 'pushTemplate', field: 'pushes' },\n discord: { is: isDiscordTemplate, factory: 'discordTemplate', field: 'discords' },\n slack: { is: isSlackTemplate, factory: 'slackTemplate', field: 'slacks' },\n};\n\nexport interface StudioSnapshot {\n /** The JSON half of the virtual module: compiled output and labels only. */\n payload: Omit<ResolvedStudioConfig, 'emails' | 'pushes' | 'discords' | 'slacks' | 'stats'>;\n /** The import half: where each registry comes from. */\n registries: Record<Channel, ModuleRef | undefined>;\n}\n\n/** A project the studio cannot read: the message says what to change. */\nclass StudioLoadError extends Error {}\n\n/* --------------------------------- Imports --------------------------------- */\n\n/**\n * The module that exports `registry`, by identity: the registry itself, or\n * else an exported `{ email, push }` holding it (`export const templates =\n * { email, push }`).\n * workflow.config.ts itself is never a candidate: importing it would bring the\n * whole config (and everything it imports) into the browser. Sorted by path,\n * so the answer does not depend on load order.\n */\nfunction locate(\n channel: Channel,\n registry: Record<string, unknown> | undefined,\n modules: LoadedModules,\n configPath: string\n): ModuleRef | undefined {\n if (registry === undefined) return undefined;\n const { is: isTemplate, factory } = CHANNELS[channel];\n for (const [key, entry] of Object.entries(registry)) {\n if (!isTemplate(entry)) {\n throw new StudioLoadError(\n `templates.${channel}['${key}'] is not a ${factory}({...}) definition — every entry of the ${channel} registry must be one.`\n );\n }\n }\n /* An empty registry has nothing for the browser to import. */\n if (Object.keys(registry).length === 0) return undefined;\n const sorted = [...modules()]\n .filter(([file]) => file !== configPath)\n .sort(([a], [b]) => a.localeCompare(b));\n for (const [file, exports] of sorted) {\n for (const [name, exported] of Object.entries(exports)) {\n if (exported === registry) return { file, name };\n }\n }\n for (const [file, exports] of sorted) {\n for (const [name, exported] of Object.entries(exports)) {\n if (\n typeof exported === 'object' &&\n exported !== null &&\n (exported as Partial<Record<Channel, unknown>>)[channel] === registry\n ) {\n return { file, name, property: channel };\n }\n }\n }\n throw new StudioLoadError(\n `templates.${channel} is not exported from a module of its own. Export the registry ` +\n `(e.g. \\`export const ${channel} = {...}\\` in src/${channel}/index.ts, or ` +\n '`export const templates = { email, push }` in src/templates.ts) ' +\n 'and import it into workflow.config.ts — the studio loads that module, never the config, into the browser.'\n );\n}\n\n/* --------------------------------- Snapshot -------------------------------- */\n\nfunction errorOf(error: unknown): StudioError {\n return {\n kind: error instanceof ConfigCompileError ? 'compile' : 'load',\n message: error instanceof Error ? error.message : String(error),\n };\n}\n\nfunction failed(error: unknown, title?: string): StudioSnapshot {\n return {\n payload: {\n ...(title !== undefined ? { title } : {}),\n workflows: {},\n segments: [],\n email: {},\n error: errorOf(error),\n },\n registries: { email: undefined, push: undefined, discord: undefined, slack: undefined },\n };\n}\n\n/**\n * Load and compile. Never throws: a config that fails to load, is not a\n * `defineConfig({...})`, holds something other than template definitions, or\n * does not compile becomes a snapshot carrying the error, which the studio\n * shows in place of its views — a compile error names the workflow and node.\n */\nexport async function loadSnapshot(options: {\n configPath: string;\n load: ModuleLoader;\n modules: LoadedModules;\n}): Promise<StudioSnapshot> {\n const { configPath, load, modules } = options;\n let config: JourneyConfig;\n let registries: StudioSnapshot['registries'];\n try {\n const exported = (await load(configPath)).default;\n if (!isConfig(exported)) {\n throw new StudioLoadError(\n `${configPath} must \\`export default defineConfig({...})\\` from '@shware/workflow'.`\n );\n }\n config = exported;\n registries = {\n email: locate('email', config.templates?.email, modules, configPath),\n push: locate('push', config.templates?.push, modules, configPath),\n discord: locate('discord', config.templates?.discord, modules, configPath),\n slack: locate('slack', config.templates?.slack, modules, configPath),\n };\n } catch (error) {\n return failed(error);\n }\n\n const unsubscribeUrl = config.email?.unsubscribeUrl;\n const quickClickMs = config.email?.tracking?.quickClickMs;\n const shared = {\n ...(config.title !== undefined ? { title: config.title } : {}),\n email: {\n ...(unsubscribeUrl !== undefined ? { unsubscribeUrl } : {}),\n ...(quickClickMs !== undefined ? { tracking: { quickClickMs } } : {}),\n },\n };\n\n try {\n const bundle = compileConfig(config);\n return {\n payload: {\n ...shared,\n workflows: Object.fromEntries(bundle.workflows.map((workflow) => [workflow.id, workflow])),\n segments: bundle.segments,\n },\n registries,\n };\n } catch (error) {\n return {\n payload: { ...shared, workflows: {}, segments: [], error: errorOf(error) },\n registries,\n };\n }\n}\n\n/* ------------------------------ Virtual module ----------------------------- */\n\n/** The `StatsSource` methods, the only names the stats endpoint answers. */\nexport const STATS_METHODS = [\n 'reports',\n 'segments',\n 'profiles',\n 'nodeStats',\n 'metrics',\n 'links',\n 'messages',\n] as const;\nexport type StatsMethod = (typeof STATS_METHODS)[number];\n\n/**\n * The module the browser imports as `virtual:workflow-config`: the payload as\n * a JSON literal, the template registries as imports from their own modules\n * (re-keyed by template id), and\n * the stats source as calls to the studio's server, one per method\n * workflow.stats.ts defines — the source itself runs there, next to the\n * database and the secrets it reads with, never in the browser.\n */\n/** An export name as an import names it: quoted (ES2022) when it is not an identifier. */\nconst exportName = (name: string) =>\n /^[A-Za-z_$][\\w$]*$/.test(name) ? name : JSON.stringify(name);\n\nexport function virtualModule(\n snapshot: StudioSnapshot,\n statsMethods: readonly StatsMethod[] | undefined\n): string {\n const imports: string[] = [];\n const importOf = (ref: ModuleRef, local: string): string => {\n /* One channel of an exported `{ email, push }`: import the whole under its own alias. */\n const binding = ref.property === undefined ? local : `${local}Source`;\n imports.push(\n ref.name === 'default'\n ? `import ${binding} from ${JSON.stringify(ref.file)};`\n : `import { ${ref.name === binding ? binding : `${exportName(ref.name)} as ${binding}`} } from ${JSON.stringify(ref.file)};`\n );\n return ref.property === undefined ? binding : `${binding}.${ref.property}`;\n };\n const registries = (Object.keys(CHANNELS) as Channel[]).map((channel) => {\n const ref = snapshot.registries[channel];\n const { field } = CHANNELS[channel];\n return ` ${field}: ${ref === undefined ? '{}' : `byId(${importOf(ref, field)})`},`;\n });\n const stats =\n statsMethods === undefined\n ? undefined\n : `{ ${statsMethods.map((method) => `${method}: call(${JSON.stringify(method)})`).join(', ')} }`;\n const call =\n stats === undefined\n ? ''\n : `\nconst call = (method) => async (...args) => {\n const response = await fetch(\\`/__studio/stats/\\${method}\\`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(args),\n });\n const body = await response.json();\n if (!response.ok) throw new Error(body.error ?? \\`stats \\${method} failed: \\${response.status}\\`);\n return body;\n};`;\n\n return `${imports.join('\\n')}${call}\n/* The views look a template up by its id, the name messages use, never by the property holding it. */\nconst byId = (registry) => Object.fromEntries(Object.values(registry).map((t) => [t.id, t]));\nconst payload = ${JSON.stringify(snapshot.payload)};\nexport default {\n ...payload,\n${registries.join('\\n')}${stats === undefined ? '' : `\\n stats: ${stats},`}\n};\n`;\n}\n","import { existsSync, lstatSync, readdirSync, realpathSync } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport tailwindcss from '@tailwindcss/vite';\nimport react from '@vitejs/plugin-react';\nimport {\n type Plugin,\n type ViteDevServer,\n createServer,\n normalizePath,\n searchForWorkspaceRoot,\n} from 'vite';\nimport svgr from 'vite-plugin-svgr';\nimport {\n STATS_METHODS,\n type StatsMethod,\n loadSnapshot,\n ssrModulesOf,\n virtualModule,\n} from './server/project';\n\n/**\n * The studio dev server.\n *\n * Rather than shipping a prebuilt SPA and a JSON API, the CLI runs Vite over\n * the app source with the project injected as a virtual module: compiled on\n * the server, the template registries imported by the browser from their own\n * modules. Vite serves our app and the user's react-email components as one\n * graph — HMR on every one of them for free, and email previews render with\n * exactly the component code on disk.\n */\n\nconst packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));\n\n/** `src/app` when running from source in the monorepo, the published copy otherwise. */\nfunction resolveAppRoot(): string {\n const candidates = [resolve(packageRoot, 'src/app'), resolve(packageRoot, '../src/app')];\n const found = candidates.find((path) => existsSync(resolve(path, 'index.html')));\n if (!found) throw new Error('workflow-ui: could not locate the app root');\n return found;\n}\n\nconst CONFIG_CANDIDATES = [\n 'workflow.config.ts',\n 'workflow.config.tsx',\n 'workflow.config.js',\n 'workflow.config.mjs',\n];\n\n/**\n * The project file — `export default defineConfig({...})` from\n * `@shware/workflow`. Required: it is the only place the studio reads\n * definitions from.\n */\nexport function findConfig(cwd: string, explicit?: string): string {\n if (explicit !== undefined) {\n const path = resolve(cwd, explicit);\n if (!existsSync(path)) throw new Error(`workflow-ui: config not found at ${path}`);\n return path;\n }\n const found = CONFIG_CANDIDATES.map((name) => resolve(cwd, name)).find((path) =>\n existsSync(path)\n );\n if (found === undefined) {\n throw new Error(\n `workflow-ui: no workflow.config.ts in ${cwd}.\\n` +\n `Export defineConfig({ workflows, templates }) from '@shware/workflow' there, or pass --config <path>.`\n );\n }\n return found;\n}\n\nconst STATS_CANDIDATES = ['workflow.stats.ts', 'workflow.stats.tsx', 'workflow.stats.js'];\n\n/**\n * The studio's optional stats source, apart from the project: an explicit\n * path must exist; otherwise `workflow.stats.ts` beside the config, if any.\n */\nexport function findStats(cwd: string, explicit?: string): string | undefined {\n if (explicit !== undefined) {\n const path = resolve(cwd, explicit);\n if (!existsSync(path)) throw new Error(`workflow-ui: stats source not found at ${path}`);\n return path;\n }\n return STATS_CANDIDATES.map((name) => resolve(cwd, name)).find((path) => existsSync(path));\n}\n\n/* ---------------------------------- Project --------------------------------- */\n\nconst VIRTUAL_ID = 'virtual:workflow-config';\nconst RESOLVED_ID = `\\0${VIRTUAL_ID}`;\n\nconst NODE_MODULES = /[/\\\\]node_modules[/\\\\]/;\n\n/**\n * Every file the last project load evaluated: the config and, transitively,\n * whatever it imported in Vite's SSR module graph — wherever those files live.\n * Dependencies under node_modules are left out: they change with an install,\n * not an edit.\n */\nfunction evaluatedFiles(dev: ViteDevServer, configPath: string): Set<string> {\n const files = new Set<string>([resolve(configPath)]);\n const graph = dev.environments.ssr.moduleGraph;\n const queue = [...(graph.getModulesByFile(configPath) ?? [])];\n const seen = new Set(queue);\n while (queue.length > 0) {\n const mod = queue.pop();\n if (mod === undefined) continue;\n if (mod.file !== null) {\n if (NODE_MODULES.test(mod.file)) continue;\n files.add(resolve(mod.file));\n }\n for (const imported of mod.importedModules) {\n if (!seen.has(imported)) {\n seen.add(imported);\n queue.push(imported);\n }\n }\n }\n return files;\n}\n\n/**\n * Serve `virtual:workflow-config` and keep it current.\n *\n * The project is evaluated on the server (ssrLoadModule) and compiled there;\n * see server/project.ts for what reaches the browser. After every load the\n * plugin records the files that load evaluated — the config and everything it\n * imported, inside the working directory or not (`--config ../shared/...`,\n * a contract in a sibling package) — and watches them. A change to any of\n * them drops those evaluated modules and pushes a fresh snapshot over HMR, so\n * adding a workflow or a template to the registration list shows up without a\n * reload. Template components also update through their own client-side HMR,\n * as any module does.\n */\n/** The stats source's default export, evaluated on the dev server. */\nasync function loadStats(\n dev: ViteDevServer,\n statsPath: string\n): Promise<Partial<Record<StatsMethod, (...args: unknown[]) => unknown>>> {\n const mod = await dev.ssrLoadModule(statsPath);\n const stats: unknown = mod.default;\n if (typeof stats !== 'object' || stats === null) {\n throw new Error(`workflow-ui: ${statsPath} must default-export defineStats({...})`);\n }\n return stats;\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolveBody, reject) => {\n let body = '';\n req.setEncoding('utf8');\n req.on('data', (chunk: string) => {\n body += chunk;\n });\n req.on('end', () => resolveBody(body));\n req.on('error', reject);\n });\n}\n\nexport function projectPlugin(configPath: string, statsPath: string | undefined): Plugin {\n let server: ViteDevServer | undefined;\n let evaluated = new Set<string>([resolve(configPath)]);\n return {\n name: 'workflow-ui:project',\n resolveId: (id) => (id === VIRTUAL_ID ? RESOLVED_ID : null),\n async load(id) {\n if (id !== RESOLVED_ID || server === undefined) return null;\n const dev = server;\n const snapshot = await loadSnapshot({\n configPath,\n load: (file) => dev.ssrLoadModule(file),\n modules: ssrModulesOf(dev),\n });\n evaluated = evaluatedFiles(dev, configPath);\n let methods: StatsMethod[] | undefined;\n if (statsPath !== undefined) {\n const stats = await loadStats(dev, statsPath);\n methods = STATS_METHODS.filter((method) => typeof stats[method] === 'function');\n for (const file of evaluatedFiles(dev, statsPath)) evaluated.add(file);\n }\n dev.watcher.add([...evaluated]);\n return virtualModule(snapshot, methods);\n },\n configureServer(dev) {\n server = dev;\n /* Positions the DSL captures while the project is evaluated are then lines on disk. */\n process.setSourceMapsEnabled(true);\n for (const file of [configPath, statsPath]) {\n if (file !== undefined) dev.watcher.add(file);\n }\n const refresh = (file: string): void => {\n if (!evaluated.has(resolve(file))) return;\n const virtual = dev.moduleGraph.getModuleById(RESOLVED_ID);\n if (virtual === undefined) return;\n /*\n * ssrLoadModule keeps an evaluated module until it is invalidated, and\n * the config caches everything it imported — so every evaluated module\n * goes, not just the file that changed.\n */\n for (const path of evaluated) {\n for (const mod of dev.moduleGraph.getModulesByFile(path) ?? []) {\n dev.moduleGraph.invalidateModule(mod);\n }\n }\n dev.moduleGraph.invalidateModule(virtual);\n void dev.reloadModule(virtual);\n };\n dev.watcher.on('change', refresh);\n dev.watcher.on('add', refresh);\n dev.watcher.on('unlink', refresh);\n\n /*\n * The stats source runs here, not in the browser: it reads the project's\n * own database or API, with credentials the page must never hold. The\n * page calls one method per request — the arguments as a JSON array, the\n * answer as JSON — and only the StatsSource method names are served.\n */\n dev.middlewares.use('/__studio/stats/', (req, res) => {\n const sendJson = (status: number, body: unknown): void => {\n res.statusCode = status;\n res.setHeader('content-type', 'application/json');\n res.end(JSON.stringify(body));\n };\n void (async () => {\n if (req.method !== 'POST') {\n res.setHeader('allow', 'POST');\n sendJson(405, { error: 'stats calls are POST' });\n return;\n }\n const rejection = studioRequestRejection(req);\n if (rejection !== undefined) {\n sendJson(403, { error: rejection });\n return;\n }\n const method = (req.url ?? '').replace(/^\\//, '').split('?')[0] as StatsMethod;\n if (statsPath === undefined || !STATS_METHODS.includes(method)) {\n sendJson(404, { error: `no stats method '${method}'` });\n return;\n }\n try {\n const args: unknown = JSON.parse((await readBody(req)) || '[]');\n if (!Array.isArray(args)) {\n sendJson(400, { error: 'the body is the arguments, as a JSON array' });\n return;\n }\n const fn = (await loadStats(dev, statsPath))[method];\n if (fn === undefined) {\n sendJson(404, { error: `workflow.stats.ts defines no '${method}'` });\n return;\n }\n sendJson(200, (await fn(...args)) ?? null);\n } catch (error) {\n dev.config.logger.error(`[workflow-ui] stats ${method} failed: ${String(error)}`);\n sendJson(500, { error: error instanceof Error ? error.message : String(error) });\n }\n })();\n });\n },\n };\n}\n\n/* -------------------------------- Studio API -------------------------------- */\n\n/** `Sec-Fetch-Site` values no other site can produce: our own page, or a direct navigation. */\nconst OWN_FETCH_SITES = new Set(['same-origin', 'none']);\n\nfunction headerValue(raw: string | string[] | undefined): string | undefined {\n const value = Array.isArray(raw) ? raw[0] : raw;\n return value === undefined || value === '' ? undefined : value;\n}\n\n/**\n * Refuse any request another website could have caused, and say why.\n *\n * The node endpoint reads the developer's source files to answer, so a page\n * they merely *visit* should not be able to probe it. Vite's CORS handling\n * decides who may read a response; this decides whether the request is served\n * at all.\n *\n * - `Sec-Fetch-Site` is attached by the browser and cannot be set from\n * script, so anything but `same-origin` (our page) or `none` (the address\n * bar) is a request some other page caused — including `same-site`, which\n * covers another port on localhost.\n * - `Origin` covers clients that send no fetch metadata: present and not our\n * own host means cross-origin. Absent is allowed on purpose — a same-origin\n * GET and a terminal `curl` both have no Origin at all, and a cross-origin\n * browser request always has one.\n */\nexport function studioRequestRejection(req: Pick<IncomingMessage, 'headers'>): string | undefined {\n const site = headerValue(req.headers['sec-fetch-site']);\n if (site !== undefined && !OWN_FETCH_SITES.has(site)) {\n return `refused: sec-fetch-site is '${site}', so another site caused this request`;\n }\n const origin = headerValue(req.headers.origin);\n if (origin !== undefined) {\n const host = headerValue(req.headers.host);\n let originHost: string | undefined;\n try {\n originHost = new URL(origin).host;\n } catch {\n /* Opaque origins ('null' from a sandboxed frame or file://) never match. */\n originHost = undefined;\n }\n if (host === undefined || originHost?.toLowerCase() !== host.toLowerCase()) {\n return `refused: cross-origin request from ${origin}`;\n }\n }\n return undefined;\n}\n\n/**\n * The studio's dev-server API — read-only. The studio views source and never\n * writes it: edits happen in the editor, and Vite's watcher and HMR bring them\n * to the page. The one endpoint resolves a node's captured position to a line\n * on disk for display; everything else under `/__studio` answers 404, so the\n * write routes earlier versions served (`/__studio/envelope`,\n * `/__studio/addresses`, POST `/__studio/node`) are gone rather than hidden.\n */\nexport function studioApiPlugin(cwd: string): Plugin {\n const sendJson = (res: ServerResponse, status: number, body: unknown): void => {\n res.statusCode = status;\n res.setHeader('content-type', 'application/json');\n res.end(JSON.stringify(body));\n };\n\n return {\n name: 'workflow-ui:studio-api',\n configureServer(server) {\n /*\n * The client sends the position the DSL captured (NodeMetaIR.loc). The\n * project is evaluated on the server with source maps enabled, so that\n * is already a line on disk; this checks the path stays inside the\n * project and answers it relative to it. Navigation only: the panel\n * shows the row when this answers and leaves it out when it does not.\n */\n server.middlewares.use('/__studio/node', (req, res) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n res.setHeader('allow', 'GET, HEAD');\n sendJson(res, 405, { error: 'the studio is read-only: GET only' });\n return;\n }\n const rejection = studioRequestRejection(req);\n if (rejection !== undefined) {\n sendJson(res, 403, { error: rejection });\n return;\n }\n const params = new URL(req.url ?? '/', 'http://internal').searchParams;\n const found = sourcePosition(cwd, params.get('file') ?? '', Number(params.get('line')));\n if ('error' in found) {\n sendJson(res, 422, { error: found.error });\n return;\n }\n sendJson(res, 200, { file: relative(cwd, found.file), line: found.line });\n });\n\n /* Registered after the routes above, so it only sees what none of them took. */\n server.middlewares.use('/__studio', (_req, res) => {\n sendJson(res, 404, { error: 'no such studio endpoint' });\n });\n },\n };\n}\n\ntype Located = { file: string; line: number } | { error: string };\n\n/** The two `node:path` functions containment needs, so the suite can hand in `path.win32`. */\ninterface PathOps {\n isAbsolute: (path: string) => boolean;\n relative: (from: string, to: string) => string;\n}\n\n/**\n * Is `candidate` `root` itself or something below it?\n *\n * Asked through `relative`, never a string prefix. A prefix test needs a\n * trailing separator (or `/proj-evil` passes for `/proj`), and the separator it\n * appends is the wrong one on Windows, where `resolve()` returns `C:\\proj\\…`:\n * that mismatch failed every path on Windows, which is how the whole\n * /__studio/node surface came to answer \"outside the project\" there.\n */\nexport function isInsideDir(\n root: string,\n candidate: string,\n ops: PathOps = { isAbsolute, relative }\n): boolean {\n const rel = ops.relative(root, candidate);\n if (rel === '') return true;\n /* An absolute answer means there is no way down from root — another drive. */\n if (ops.isAbsolute(rel)) return false;\n /* Segment-wise, so a file legitimately named '..rc' is not read as an escape. */\n return rel.split(/[/\\\\]/)[0] !== '..';\n}\n\n/**\n * Keep a path that arrived from the browser inside the project.\n *\n * The scope is `cwd` — the project the studio was started in — and not the\n * workspace root `searchForWorkspaceRoot` walks up to: in a monorepo that root\n * is the whole repo, so a studio started in `apps/marketing` accepted\n * `file=../../packages/billing/src/rates.ts` and read it.\n */\nexport function isInsideProject(cwd: string, candidate: string): boolean {\n const root = resolve(cwd);\n const path = resolve(candidate);\n if (!isInsideDir(root, path)) return false;\n /*\n * Then again on the real paths: a symlink inside the project may point\n * anywhere, and the check above only ever sees the link's own path. A path\n * that does not exist has nothing to resolve — the caller reports that.\n */\n if (!existsSync(path)) return true;\n return isInsideDir(realpathSync(root), realpathSync(path));\n}\n\n/**\n * Check a captured position before answering with it.\n *\n * The path is validated against cwd before anything is touched: it arrives\n * from the browser, and an endpoint that follows an arbitrary path is a\n * read-anywhere endpoint.\n */\nfunction sourcePosition(cwd: string, rawFile: string, line: number): Located {\n let path = rawFile;\n if (/^https?:\\/\\//.test(path)) path = new URL(path).pathname;\n const fsPrefix = '/@fs';\n if (path.startsWith(fsPrefix)) path = path.slice(fsPrefix.length);\n path = resolve(cwd, decodeURIComponent(path));\n\n if (!isInsideProject(cwd, path)) return { error: 'source file is outside the project' };\n if (!existsSync(path)) return { error: `no such source file: ${path}` };\n if (!Number.isInteger(line) || line < 1) return { error: 'expected a line number' };\n return { file: path, line };\n}\n\n/** Vite's own `server.fs.deny` default; setting the option replaces it, so it is spelled out. */\nconst VITE_DEFAULT_DENY = ['.env', '.env.*', '*.{crt,pem}', '**/.git/**'];\n\n/**\n * What `server.fs.deny` refuses whatever the project: Vite's default, plus the credentials a\n * journey project keeps beside its code. `fs.allow` spans the project and its linked workspace\n * packages (see {@link studioFsAllow}), so without these\n * `/@fs/<path>/.dev.vars` (wrangler's secrets), an APNs `.p8` or a Firebase service account would\n * be one request away for any page that can reach the port.\n */\nexport const STUDIO_FS_DENY: readonly string[] = [\n ...VITE_DEFAULT_DENY,\n '**/.dev.vars*',\n '**/*.p8',\n '**/*.plist',\n '**/google-services.json',\n '**/*.pfx',\n '**/*.pem',\n '**/*.key',\n];\n\n/**\n * `server.fs.deny` patterns for files the page must never be served.\n *\n * `fs.allow` covers the project so the browser can import the template\n * registries, which also made `GET /@fs/<cwd>/workflow.stats.ts`\n * answer with the stats source — a file the README calls server-only, and the\n * one place a connection string is likely to be written as a literal. The\n * browser never imports the config or the stats file (the virtual module\n * imports the registries by their own paths; a registry written inline in the\n * config is refused for this reason), so both are denied outright.\n *\n * Patterns go through picomatch, so the path is spelled literally: its glob\n * characters escaped, slashes normalized the way Vite normalizes the file it\n * checks. A symlinked file is denied under both of its names.\n */\nexport function projectFileDeny(paths: readonly (string | undefined)[]): string[] {\n const deny = new Set<string>();\n for (const path of paths) {\n if (path === undefined) continue;\n const literal = resolve(path);\n deny.add(normalizePath(literal));\n if (existsSync(literal)) deny.add(normalizePath(realpathSync(literal)));\n }\n return [...deny].map((path) => path.replace(/[\\\\*?[\\]{}()!+@]/g, '\\\\$&'));\n}\n\n/** Whether `path` lies inside some `node_modules` directory (a store entry, not a workspace link). */\nfunction inNodeModules(path: string): boolean {\n return path.split(sep).includes('node_modules');\n}\n\n/**\n * Real paths of the workspace packages `dir` links in through `node_modules` (pnpm's\n * `workspace:` dependencies, npm/yarn workspaces), followed transitively. A link that resolves\n * into a `node_modules` directory is a store entry, covered by the store's own allow entry.\n */\nfunction linkedWorkspacePackages(dir: string, found = new Set<string>()): Set<string> {\n const modules = join(dir, 'node_modules');\n let names: string[];\n try {\n names = readdirSync(modules);\n } catch {\n return found;\n }\n const entries = names.flatMap((name) => {\n if (!name.startsWith('@')) return [join(modules, name)];\n try {\n return readdirSync(join(modules, name)).map((child) => join(modules, name, child));\n } catch {\n return [];\n }\n });\n for (const entry of entries) {\n let real: string;\n try {\n if (!lstatSync(entry).isSymbolicLink()) continue;\n real = realpathSync(entry);\n } catch {\n continue; // a dangling link\n }\n if (inNodeModules(real) || found.has(real)) continue;\n found.add(real);\n linkedWorkspacePackages(real, found);\n }\n return found;\n}\n\n/**\n * `server.fs.allow` for the studio: only what the page actually imports.\n *\n * - the studio package itself (the app source, its css and fonts);\n * - the consuming project: the directory the studio is started from, and the config's own\n * directory when `--config` points outside it (the registries the browser imports live there);\n * - the workspace packages those link in (a template importing `@acme/contract` from a sibling\n * workspace package), followed transitively;\n * - the `node_modules` of each workspace root involved: under pnpm every dependency's real path is\n * in the virtual store `node_modules/.pnpm` beside the workspace root rather than below the app,\n * and with npm/yarn or a hoisted pnpm layout they are directly in `node_modules`.\n *\n * Nothing else in the workspace: a sibling app's source and secrets are not one `/@fs/` request\n * away. The deny list still applies inside every one of these.\n */\nexport function studioFsAllow(options: {\n cwd: string;\n configPath: string;\n packageRoot: string;\n appRoot: string;\n}): string[] {\n const { cwd, configPath, packageRoot, appRoot } = options;\n const projectDirs = [cwd, dirname(configPath)];\n const allow = new Set<string>([packageRoot, appRoot, ...projectDirs]);\n for (const dir of [...projectDirs, packageRoot]) {\n for (const linked of linkedWorkspacePackages(dir)) allow.add(linked);\n allow.add(join(searchForWorkspaceRoot(dir), 'node_modules'));\n }\n return [...allow];\n}\n\nexport interface StartOptions {\n cwd?: string;\n config?: string;\n /** The studio's stats source (default ./workflow.stats.ts, if present). */\n stats?: string;\n port?: number;\n open?: boolean;\n}\n\nexport async function startStudio(options: StartOptions = {}): Promise<ViteDevServer> {\n const cwd = options.cwd ?? process.cwd();\n // The config is required (findConfig throws); the stats source is optional.\n // The resolved path is what the plugin loads — resolving again from cwd\n // inside it is what once made --config point at a file it does not name.\n const configPath = findConfig(cwd, options.config);\n const statsPath = findStats(cwd, options.stats);\n const appRoot = resolveAppRoot();\n\n const server = await createServer({\n root: appRoot,\n configFile: false,\n envDir: false,\n plugins: [\n react(),\n svgr(),\n tailwindcss(),\n projectPlugin(configPath, statsPath),\n studioApiPlugin(cwd),\n ],\n server: {\n port: options.port ?? 4321,\n open: options.open ?? false,\n fs: {\n allow: studioFsAllow({ cwd, configPath, packageRoot, appRoot }),\n deny: [...STUDIO_FS_DENY, ...projectFileDeny([configPath, statsPath])],\n },\n // The studio is its own origin and calls no one else's; no page elsewhere may read it\n cors: false,\n },\n // The app and the user's project each have their own react; one copy only. One\n // @shware/workflow too: the preview's <EmailProvider> and the project's layout calling\n // useEmailContext() must share the context object\n resolve: { dedupe: ['react', 'react-dom', '@shware/workflow'] },\n /*\n * @react-email/render imports react-dom/server lazily, so the dep scan never\n * sees it: the first email preview made Vite discover it, re-optimize and\n * change the deps hash under a page that still held the old one — the\n * preview then failed with \"Failed to fetch dynamically imported module\"\n * (a 504 Outdated Optimize Dep) until a reload. Bundling both up front\n * keeps the hash stable from the first request. The project's config is\n * scanned too (never served — only crawled), so its templates'\n * dependencies (@react-email/components, zod, …) are bundled before the\n * first preview rather than discovered by it.\n */\n optimizeDeps: {\n entries: ['index.html', configPath],\n include: ['@react-email/render', 'react-dom/server'],\n },\n });\n\n await server.listen();\n return server;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, relative, resolve } from 'node:path';\nimport { type JourneyConfig, isConfig } from '@shware/workflow';\nimport { renderDrizzleSchema } from '@shware/workflow/store';\nimport { runnerImport } from 'vite';\nimport { findConfig } from './server';\n\n/**\n * `workflow-ui generate` — the engine's Postgres tables as one drizzle file, on the schema the\n * project's `database.schema` names (`workflow` by default). The host re-exports the file from\n * its drizzle schema and lets drizzle-kit write the migration, so the migration history stays the\n * host's. `--check` exits non-zero when the file on disk differs (CI, after an SDK upgrade).\n */\n\nexport interface GenerateOptions {\n cwd?: string;\n config?: string;\n out: string;\n check?: boolean;\n}\n\nexport type GenerateResult = 'written' | 'unchanged' | 'outdated';\n\n/** The host's formatter may rewrap the file, change quotes or trailing commas: not a difference. */\nfunction normalize(source: string): string {\n return (\n source\n .replace(/\"/g, \"'\")\n .replace(/\\s+/g, ' ')\n // Spaces around punctuation, and trailing commas, are the formatter's choice\n .replace(/ ?([{}()[\\],;:=<>.]) ?/g, '$1')\n .replace(/,([}\\])])/g, '$1')\n .trim()\n );\n}\n\nexport async function generateSchema(options: GenerateOptions): Promise<GenerateResult> {\n const cwd = options.cwd ?? process.cwd();\n const configPath = findConfig(cwd, options.config);\n const { module } = await runnerImport<{ default?: unknown }>(configPath);\n if (!isConfig(module.default)) {\n throw new Error(\n `workflow-ui: ${relative(cwd, configPath)} must \\`export default defineConfig({...})\\``\n );\n }\n const config: JourneyConfig = module.default;\n const file = renderDrizzleSchema(config.database?.schema);\n\n const out = resolve(cwd, options.out);\n const current = existsSync(out) ? readFileSync(out, 'utf8') : undefined;\n if (current !== undefined && normalize(current) === normalize(file)) return 'unchanged';\n if (options.check) return 'outdated';\n mkdirSync(dirname(out), { recursive: true });\n writeFileSync(out, file);\n return 'written';\n}\n","#!/usr/bin/env node\nimport { generateSchema } from './generate';\nimport { startStudio } from './server';\n\n/**\n * `workflow-ui` — start the studio over the project in ./workflow.config.ts.\n *\n * npx workflow-ui # reads ./workflow.config.ts (and ./workflow.stats.ts)\n * npx workflow-ui --port 5000\n * npx workflow-ui --config apps/marketing/workflow.config.ts\n * npx workflow-ui generate --out ../../packages/db/src/schema/workflow.ts [--check]\n * npx workflow-ui plan --database-url $DATABASE_URL\n */\n\ninterface Args {\n port?: number;\n config?: string;\n stats?: string;\n out?: string;\n databaseUrl?: string;\n check: boolean;\n open: boolean;\n help: boolean;\n}\n\nfunction parseArgs(argv: string[]): Args {\n const args: Args = { open: false, check: false, help: false };\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === '--help' || arg === '-h') args.help = true;\n else if (arg === '--open') args.open = true;\n else if (arg === '--check') args.check = true;\n else if (arg === '--out' || arg === '-o') args.out = argv[++i];\n else if (arg === '--database-url' || arg === '-d') args.databaseUrl = argv[++i];\n else if (arg === '--port' || arg === '-p') args.port = Number(argv[++i]);\n else if (arg === '--config' || arg === '-c') args.config = argv[++i];\n else if (arg === '--stats' || arg === '-s') args.stats = argv[++i];\n }\n return args;\n}\n\nconst HELP = `\n workflow-ui — review your workflows, templates and reports\n\n Usage\n $ workflow-ui [dev] [options]\n $ workflow-ui generate --out <file> [--check] [--config <path>]\n $ workflow-ui plan --database-url <url> [--config <path>]\n\n Options\n -p, --port <port> Port to listen on (default 4321)\n -c, --config <path> Project file (default ./workflow.config.ts)\n -s, --stats <path> Stats source (default ./workflow.stats.ts, if present)\n --open Open the browser on start\n -o, --out <file> generate: where the drizzle schema file goes\n --check generate: fail when the file is out of date, write nothing\n -d, --database-url plan: the engine's database (default $DATABASE_URL); exits 1 when the\n bundle would break journeys still running there\n -h, --help Show this message\n`;\n\nasync function main(): Promise<void> {\n const [command, ...rest] = process.argv.slice(2);\n if (command === 'generate') {\n const args = parseArgs(rest);\n if (args.help || args.out === undefined) {\n console.log(HELP);\n if (args.out === undefined && !args.help) process.exitCode = 1;\n return;\n }\n try {\n const result = await generateSchema({\n out: args.out,\n check: args.check,\n ...(args.config !== undefined ? { config: args.config } : {}),\n });\n if (result === 'outdated') {\n console.error(\n `\\n ${args.out} is out of date — run workflow-ui generate, then your migration tool\\n`\n );\n process.exitCode = 1;\n } else {\n console.log(`\\n ${args.out} ${result === 'written' ? 'written' : 'is up to date'}\\n`);\n }\n } catch (error) {\n console.error(`\\n${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n }\n return;\n }\n\n if (command === 'plan') {\n const args = parseArgs(rest);\n const databaseUrl = args.databaseUrl ?? process.env.DATABASE_URL;\n if (args.help || databaseUrl === undefined) {\n console.log(HELP);\n if (!args.help) {\n console.error('\\n plan needs --database-url <url> (or DATABASE_URL in the environment)\\n');\n process.exitCode = 1;\n }\n return;\n }\n try {\n // Loaded here, not at the top: `plan` is the one command that needs `postgres`, an optional\n // peer — a static import would make every command, `--help` included, fail without it\n const { formatPlan, planDeploy } = await import('./plan');\n const report = await planDeploy({\n databaseUrl,\n ...(args.config !== undefined ? { config: args.config } : {}),\n });\n console.log(`\\n ${formatPlan(report).join('\\n ')}\\n`);\n if (report.problems.length > 0) process.exitCode = 1;\n } catch (error) {\n console.error(`\\n${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n }\n return;\n }\n\n // `dev` is accepted so the command reads well; the studio is the default mode\n const argv = process.argv.slice(2).filter((arg) => arg !== 'dev');\n const args = parseArgs(argv);\n\n if (args.help) {\n console.log(HELP);\n return;\n }\n\n try {\n const server = await startStudio({\n ...(args.port !== undefined ? { port: args.port } : {}),\n ...(args.config !== undefined ? { config: args.config } : {}),\n ...(args.stats !== undefined ? { stats: args.stats } : {}),\n open: args.open,\n });\n const address = server.resolvedUrls?.local[0] ?? `http://localhost:${args.port ?? 4321}`;\n console.log(`\\n workflow-ui ready at ${address}\\n`);\n } catch (error) {\n console.error(`\\n${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n }\n}\n\nvoid main();\n"],"mappings":";;;;;;;;;;;;AAqCA,SAAgB,aAAa,QAAsC;CACjE,OAAO,aAAa;EAClB,KAAK,MAAM,OAAO,OAAO,YAAY,cAAc,OAAO,GAAG;GAC3D,MAAM,UAAU,IAAI;GACpB,IAAI,IAAI,SAAS,QAAQ,YAAY,MAAM,MAAM,CAAC,IAAI,MAAM,OAAO;EACrE;CACF;AACF;;AAYA,MAAM,WAGF;CACF,OAAO;EAAE,IAAI;EAAiB,SAAS;EAAiB,OAAO;CAAS;CACxE,MAAM;EAAE,IAAI;EAAgB,SAAS;EAAgB,OAAO;CAAS;CACrE,SAAS;EAAE,IAAI;EAAmB,SAAS;EAAmB,OAAO;CAAW;CAChF,OAAO;EAAE,IAAI;EAAiB,SAAS;EAAiB,OAAO;CAAS;AAC1E;;AAUA,IAAM,kBAAN,cAA8B,MAAM,CAAC;;;;;;;;;AAYrC,SAAS,OACP,SACA,UACA,SACA,YACuB;CACvB,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;CACnC,MAAM,EAAE,IAAI,YAAY,YAAY,SAAS;CAC7C,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAChD,IAAI,CAAC,WAAW,KAAK,GACnB,MAAM,I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,IAAI;GAGF,MAAM,EAAE,YAAY,eAAe,MAAM,OAAO;GAChD,MAAM,SAAS,MAAM,WAAW;IAC9B;IACA,GAAI,KAAK,WAAW,KAAA,IAAY,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;GAC7D,CAAC;GACD,QAAQ,IAAI,OAAO,WAAW,MAAM,CAAC,CAAC,KAAK,MAAM,EAAE,GAAG;GACtD,IAAI,OAAO,SAAS,SAAS,GAAG,QAAQ,WAAW;EACrD,SAAS,OAAO;GACd,QAAQ,MAAM,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,GAAG;GAC7E,QAAQ,WAAW;EACrB;EACA;CACF;CAIA,MAAM,OAAO,UADA,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,QAAQ,QAAQ,KACjC,CAAC;CAE3B,IAAI,KAAK,MAAM;EACb,QAAQ,IAAI,IAAI;EAChB;CACF;CAEA,IAAI;EAOF,MAAM,WAAU,MANK,YAAY;GAC/B,GAAI,KAAK,SAAS,KAAA,IAAY,EAAE,MAAM,KAAK,KAAK,IAAI,CAAC;GACrD,GAAI,KAAK,WAAW,KAAA,IAAY,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;GAC3D,GAAI,KAAK,UAAU,KAAA,IAAY,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;GACxD,MAAM,KAAK;EACb,CAAC,EAAA,CACsB,cAAc,MAAM,MAAM,oBAAoB,KAAK,QAAQ;EAClF,QAAQ,IAAI,4BAA4B,QAAQ,GAAG;CACrD,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,GAAG;EAC7E,QAAQ,WAAW;CACrB;AACF;AAEK,KAAK"}
1
+ {"version":3,"file":"cli.mjs","names":[],"sources":["../src/server/project.ts","../src/server.ts","../src/generate.ts","../src/cli.ts"],"sourcesContent":["import {\n ConfigCompileError,\n type JourneyConfig,\n compileConfig,\n isConfig,\n isDiscordTemplate,\n isEmailTemplate,\n isPushTemplate,\n isSlackTemplate,\n} from '@shware/workflow';\nimport type { ViteDevServer } from 'vite';\nimport type { ResolvedStudioConfig, StudioError } from '../config';\n\n/**\n * Reading the project — on the dev server, never in the browser.\n *\n * workflow.config.ts default-exports `defineConfig({...})` from\n * `@shware/workflow`, and the studio reads exactly that: its workflows,\n * segments, actions, template registries, title and what the email templates share. It is\n * compiled with `compileConfig`, the same compile the Worker deploys, so the\n * studio lists exactly what would ship.\n *\n * What crosses to the browser is decided here too. The config is a source\n * object — schemas, components, the contract, runtime settings, whatever the\n * host imports — so it stays on the server. The browser receives the compiled\n * IR as JSON, and imports the two template registries (the code a preview has\n * to run) straight from the modules that export them, located by identity in\n * Vite's SSR module graph. It never imports workflow.config.ts.\n */\n\n/** How the server evaluates a project module (Vite's ssrLoadModule in the studio). */\nexport type ModuleLoader = (file: string) => Promise<Record<string, unknown>>;\n\n/** Every module the loader has evaluated so far, with its exports. */\nexport type LoadedModules = () => Iterable<[file: string, exports: Record<string, unknown>]>;\n\n/** The modules a Vite server has evaluated for SSR — where registries are located by identity. */\nexport function ssrModulesOf(server: ViteDevServer): LoadedModules {\n return function* () {\n for (const mod of server.moduleGraph.idToModuleMap.values()) {\n const exports = mod.ssrModule as Record<string, unknown> | null;\n if (mod.file !== null && exports !== null) yield [mod.file, exports];\n }\n };\n}\n\ntype Channel = 'email' | 'push' | 'discord' | 'slack';\n\n/** One named export the browser imports — or one channel of it, for an exported `{ email, push }`. */\nexport interface ModuleRef {\n file: string;\n name: string;\n property?: Channel;\n}\n\n/** Per channel: how to recognise its entries, the factory to name, the virtual module's field. */\nconst CHANNELS: Record<\n Channel,\n { is: (value: unknown) => boolean; factory: string; field: string }\n> = {\n email: { is: isEmailTemplate, factory: 'emailTemplate', field: 'emails' },\n push: { is: isPushTemplate, factory: 'pushTemplate', field: 'pushes' },\n discord: { is: isDiscordTemplate, factory: 'discordTemplate', field: 'discords' },\n slack: { is: isSlackTemplate, factory: 'slackTemplate', field: 'slacks' },\n};\n\nexport interface StudioSnapshot {\n /** The JSON half of the virtual module: compiled output and labels only. */\n payload: Omit<ResolvedStudioConfig, 'emails' | 'pushes' | 'discords' | 'slacks' | 'stats'>;\n /** The import half: where each registry comes from. */\n registries: Record<Channel, ModuleRef | undefined>;\n}\n\n/** A project the studio cannot read: the message says what to change. */\nclass StudioLoadError extends Error {}\n\n/* --------------------------------- Imports --------------------------------- */\n\n/**\n * The module that exports `registry`, by identity: the registry itself, or\n * else an exported `{ email, push }` holding it (`export const templates =\n * { email, push }`).\n * workflow.config.ts itself is never a candidate: importing it would bring the\n * whole config (and everything it imports) into the browser. Sorted by path,\n * so the answer does not depend on load order.\n */\nfunction locate(\n channel: Channel,\n registry: Record<string, unknown> | undefined,\n modules: LoadedModules,\n configPath: string\n): ModuleRef | undefined {\n if (registry === undefined) return undefined;\n const { is: isTemplate, factory } = CHANNELS[channel];\n for (const [key, entry] of Object.entries(registry)) {\n if (!isTemplate(entry)) {\n throw new StudioLoadError(\n `templates.${channel}['${key}'] is not a ${factory}({...}) definition — every entry of the ${channel} registry must be one.`\n );\n }\n }\n /* An empty registry has nothing for the browser to import. */\n if (Object.keys(registry).length === 0) return undefined;\n const sorted = [...modules()]\n .filter(([file]) => file !== configPath)\n .sort(([a], [b]) => a.localeCompare(b));\n for (const [file, exports] of sorted) {\n for (const [name, exported] of Object.entries(exports)) {\n if (exported === registry) return { file, name };\n }\n }\n for (const [file, exports] of sorted) {\n for (const [name, exported] of Object.entries(exports)) {\n if (\n typeof exported === 'object' &&\n exported !== null &&\n (exported as Partial<Record<Channel, unknown>>)[channel] === registry\n ) {\n return { file, name, property: channel };\n }\n }\n }\n throw new StudioLoadError(\n `templates.${channel} is not exported from a module of its own. Export the registry ` +\n `(e.g. \\`export const ${channel} = {...}\\` in src/${channel}/index.ts, or ` +\n '`export const templates = { email, push }` in src/templates.ts) ' +\n 'and import it into workflow.config.ts — the studio loads that module, never the config, into the browser.'\n );\n}\n\n/* --------------------------------- Snapshot -------------------------------- */\n\nfunction errorOf(error: unknown): StudioError {\n return {\n kind: error instanceof ConfigCompileError ? 'compile' : 'load',\n message: error instanceof Error ? error.message : String(error),\n };\n}\n\nfunction failed(error: unknown, title?: string): StudioSnapshot {\n return {\n payload: {\n ...(title !== undefined ? { title } : {}),\n workflows: {},\n segments: [],\n email: {},\n error: errorOf(error),\n },\n registries: { email: undefined, push: undefined, discord: undefined, slack: undefined },\n };\n}\n\n/**\n * Load and compile. Never throws: a config that fails to load, is not a\n * `defineConfig({...})`, holds something other than template definitions, or\n * does not compile becomes a snapshot carrying the error, which the studio\n * shows in place of its views — a compile error names the workflow and node.\n */\nexport async function loadSnapshot(options: {\n configPath: string;\n load: ModuleLoader;\n modules: LoadedModules;\n}): Promise<StudioSnapshot> {\n const { configPath, load, modules } = options;\n let config: JourneyConfig;\n let registries: StudioSnapshot['registries'];\n try {\n const exported = (await load(configPath)).default;\n if (!isConfig(exported)) {\n throw new StudioLoadError(\n `${configPath} must \\`export default defineConfig({...})\\` from '@shware/workflow'.`\n );\n }\n config = exported;\n registries = {\n email: locate('email', config.templates?.email, modules, configPath),\n push: locate('push', config.templates?.push, modules, configPath),\n discord: locate('discord', config.templates?.discord, modules, configPath),\n slack: locate('slack', config.templates?.slack, modules, configPath),\n };\n } catch (error) {\n return failed(error);\n }\n\n const unsubscribeUrl = config.email?.unsubscribeUrl;\n const quickClickMs = config.email?.tracking?.quickClickMs;\n const shared = {\n ...(config.title !== undefined ? { title: config.title } : {}),\n email: {\n ...(unsubscribeUrl !== undefined ? { unsubscribeUrl } : {}),\n ...(quickClickMs !== undefined ? { tracking: { quickClickMs } } : {}),\n },\n };\n\n try {\n const bundle = compileConfig(config);\n return {\n payload: {\n ...shared,\n workflows: Object.fromEntries(bundle.workflows.map((workflow) => [workflow.id, workflow])),\n segments: bundle.segments,\n },\n registries,\n };\n } catch (error) {\n return {\n payload: { ...shared, workflows: {}, segments: [], error: errorOf(error) },\n registries,\n };\n }\n}\n\n/* ------------------------------ Virtual module ----------------------------- */\n\n/** The `StatsSource` methods, the only names the stats endpoint answers. */\nexport const STATS_METHODS = [\n 'reports',\n 'segments',\n 'profiles',\n 'nodeStats',\n 'metrics',\n 'links',\n 'messages',\n] as const;\nexport type StatsMethod = (typeof STATS_METHODS)[number];\n\n/**\n * The module the browser imports as `virtual:workflow-config`: the payload as\n * a JSON literal, the template registries as imports from their own modules\n * (re-keyed by template id), and\n * the stats source as calls to the studio's server, one per method\n * workflow.stats.ts defines — the source itself runs there, next to the\n * database and the secrets it reads with, never in the browser.\n */\n/** An export name as an import names it: quoted (ES2022) when it is not an identifier. */\nconst exportName = (name: string) =>\n /^[A-Za-z_$][\\w$]*$/.test(name) ? name : JSON.stringify(name);\n\nexport function virtualModule(\n snapshot: StudioSnapshot,\n statsMethods: readonly StatsMethod[] | undefined\n): string {\n const imports: string[] = [];\n const importOf = (ref: ModuleRef, local: string): string => {\n /* One channel of an exported `{ email, push }`: import the whole under its own alias. */\n const binding = ref.property === undefined ? local : `${local}Source`;\n imports.push(\n ref.name === 'default'\n ? `import ${binding} from ${JSON.stringify(ref.file)};`\n : `import { ${ref.name === binding ? binding : `${exportName(ref.name)} as ${binding}`} } from ${JSON.stringify(ref.file)};`\n );\n return ref.property === undefined ? binding : `${binding}.${ref.property}`;\n };\n const registries = (Object.keys(CHANNELS) as Channel[]).map((channel) => {\n const ref = snapshot.registries[channel];\n const { field } = CHANNELS[channel];\n return ` ${field}: ${ref === undefined ? '{}' : `byId(${importOf(ref, field)})`},`;\n });\n const stats =\n statsMethods === undefined\n ? undefined\n : `{ ${statsMethods.map((method) => `${method}: call(${JSON.stringify(method)})`).join(', ')} }`;\n const call =\n stats === undefined\n ? ''\n : `\nconst call = (method) => async (...args) => {\n const response = await fetch(\\`/__studio/stats/\\${method}\\`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(args),\n });\n const body = await response.json();\n if (!response.ok) throw new Error(body.error ?? \\`stats \\${method} failed: \\${response.status}\\`);\n return body;\n};`;\n\n return `${imports.join('\\n')}${call}\n/* The views look a template up by its id, the name messages use, never by the property holding it. */\nconst byId = (registry) => Object.fromEntries(Object.values(registry).map((t) => [t.id, t]));\nconst payload = ${JSON.stringify(snapshot.payload)};\nexport default {\n ...payload,\n${registries.join('\\n')}${stats === undefined ? '' : `\\n stats: ${stats},`}\n};\n`;\n}\n","import { existsSync, lstatSync, readdirSync, realpathSync } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport tailwindcss from '@tailwindcss/vite';\nimport react from '@vitejs/plugin-react';\nimport {\n type Plugin,\n type ViteDevServer,\n createServer,\n normalizePath,\n searchForWorkspaceRoot,\n} from 'vite';\nimport svgr from 'vite-plugin-svgr';\nimport {\n STATS_METHODS,\n type StatsMethod,\n loadSnapshot,\n ssrModulesOf,\n virtualModule,\n} from './server/project';\n\n/**\n * The studio dev server.\n *\n * Rather than shipping a prebuilt SPA and a JSON API, the CLI runs Vite over\n * the app source with the project injected as a virtual module: compiled on\n * the server, the template registries imported by the browser from their own\n * modules. Vite serves our app and the user's react-email components as one\n * graph — HMR on every one of them for free, and email previews render with\n * exactly the component code on disk.\n */\n\nconst packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));\n\n/** `src/app` when running from source in the monorepo, the published copy otherwise. */\nfunction resolveAppRoot(): string {\n const candidates = [resolve(packageRoot, 'src/app'), resolve(packageRoot, '../src/app')];\n const found = candidates.find((path) => existsSync(resolve(path, 'index.html')));\n if (!found) throw new Error('workflow-ui: could not locate the app root');\n return found;\n}\n\nconst CONFIG_CANDIDATES = [\n 'workflow.config.ts',\n 'workflow.config.tsx',\n 'workflow.config.js',\n 'workflow.config.mjs',\n];\n\n/**\n * The project file — `export default defineConfig({...})` from\n * `@shware/workflow`. Required: it is the only place the studio reads\n * definitions from.\n */\nexport function findConfig(cwd: string, explicit?: string): string {\n if (explicit !== undefined) {\n const path = resolve(cwd, explicit);\n if (!existsSync(path)) throw new Error(`workflow-ui: config not found at ${path}`);\n return path;\n }\n const found = CONFIG_CANDIDATES.map((name) => resolve(cwd, name)).find((path) =>\n existsSync(path)\n );\n if (found === undefined) {\n throw new Error(\n `workflow-ui: no workflow.config.ts in ${cwd}.\\n` +\n `Export defineConfig({ workflows, templates }) from '@shware/workflow' there, or pass --config <path>.`\n );\n }\n return found;\n}\n\nconst STATS_CANDIDATES = ['workflow.stats.ts', 'workflow.stats.tsx', 'workflow.stats.js'];\n\n/**\n * The studio's optional stats source, apart from the project: an explicit\n * path must exist; otherwise `workflow.stats.ts` beside the config, if any.\n */\nexport function findStats(cwd: string, explicit?: string): string | undefined {\n if (explicit !== undefined) {\n const path = resolve(cwd, explicit);\n if (!existsSync(path)) throw new Error(`workflow-ui: stats source not found at ${path}`);\n return path;\n }\n return STATS_CANDIDATES.map((name) => resolve(cwd, name)).find((path) => existsSync(path));\n}\n\n/* ---------------------------------- Project --------------------------------- */\n\nconst VIRTUAL_ID = 'virtual:workflow-config';\nconst RESOLVED_ID = `\\0${VIRTUAL_ID}`;\n\nconst NODE_MODULES = /[/\\\\]node_modules[/\\\\]/;\n\n/**\n * Every file the last project load evaluated: the config and, transitively,\n * whatever it imported in Vite's SSR module graph — wherever those files live.\n * Dependencies under node_modules are left out: they change with an install,\n * not an edit.\n */\nfunction evaluatedFiles(dev: ViteDevServer, configPath: string): Set<string> {\n const files = new Set<string>([resolve(configPath)]);\n const graph = dev.environments.ssr.moduleGraph;\n const queue = [...(graph.getModulesByFile(configPath) ?? [])];\n const seen = new Set(queue);\n while (queue.length > 0) {\n const mod = queue.pop();\n if (mod === undefined) continue;\n if (mod.file !== null) {\n if (NODE_MODULES.test(mod.file)) continue;\n files.add(resolve(mod.file));\n }\n for (const imported of mod.importedModules) {\n if (!seen.has(imported)) {\n seen.add(imported);\n queue.push(imported);\n }\n }\n }\n return files;\n}\n\n/**\n * Serve `virtual:workflow-config` and keep it current.\n *\n * The project is evaluated on the server (ssrLoadModule) and compiled there;\n * see server/project.ts for what reaches the browser. After every load the\n * plugin records the files that load evaluated — the config and everything it\n * imported, inside the working directory or not (`--config ../shared/...`,\n * a contract in a sibling package) — and watches them. A change to any of\n * them drops those evaluated modules and pushes a fresh snapshot over HMR, so\n * adding a workflow or a template to the registration list shows up without a\n * reload. Template components also update through their own client-side HMR,\n * as any module does.\n */\n/** The stats source's default export, evaluated on the dev server. */\nasync function loadStats(\n dev: ViteDevServer,\n statsPath: string\n): Promise<Partial<Record<StatsMethod, (...args: unknown[]) => unknown>>> {\n const mod = await dev.ssrLoadModule(statsPath);\n const stats: unknown = mod.default;\n if (typeof stats !== 'object' || stats === null) {\n throw new Error(`workflow-ui: ${statsPath} must default-export defineStats({...})`);\n }\n return stats;\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolveBody, reject) => {\n let body = '';\n req.setEncoding('utf8');\n req.on('data', (chunk: string) => {\n body += chunk;\n });\n req.on('end', () => resolveBody(body));\n req.on('error', reject);\n });\n}\n\nexport function projectPlugin(configPath: string, statsPath: string | undefined): Plugin {\n let server: ViteDevServer | undefined;\n let evaluated = new Set<string>([resolve(configPath)]);\n return {\n name: 'workflow-ui:project',\n resolveId: (id) => (id === VIRTUAL_ID ? RESOLVED_ID : null),\n async load(id) {\n if (id !== RESOLVED_ID || server === undefined) return null;\n const dev = server;\n const snapshot = await loadSnapshot({\n configPath,\n load: (file) => dev.ssrLoadModule(file),\n modules: ssrModulesOf(dev),\n });\n evaluated = evaluatedFiles(dev, configPath);\n let methods: StatsMethod[] | undefined;\n if (statsPath !== undefined) {\n const stats = await loadStats(dev, statsPath);\n methods = STATS_METHODS.filter((method) => typeof stats[method] === 'function');\n for (const file of evaluatedFiles(dev, statsPath)) evaluated.add(file);\n }\n dev.watcher.add([...evaluated]);\n return virtualModule(snapshot, methods);\n },\n configureServer(dev) {\n server = dev;\n /* Positions the DSL captures while the project is evaluated are then lines on disk. */\n process.setSourceMapsEnabled(true);\n for (const file of [configPath, statsPath]) {\n if (file !== undefined) dev.watcher.add(file);\n }\n const refresh = (file: string): void => {\n if (!evaluated.has(resolve(file))) return;\n const virtual = dev.moduleGraph.getModuleById(RESOLVED_ID);\n if (virtual === undefined) return;\n /*\n * ssrLoadModule keeps an evaluated module until it is invalidated, and\n * the config caches everything it imported — so every evaluated module\n * goes, not just the file that changed.\n */\n for (const path of evaluated) {\n for (const mod of dev.moduleGraph.getModulesByFile(path) ?? []) {\n dev.moduleGraph.invalidateModule(mod);\n }\n }\n dev.moduleGraph.invalidateModule(virtual);\n void dev.reloadModule(virtual);\n };\n dev.watcher.on('change', refresh);\n dev.watcher.on('add', refresh);\n dev.watcher.on('unlink', refresh);\n\n /*\n * The stats source runs here, not in the browser: it reads the project's\n * own database or API, with credentials the page must never hold. The\n * page calls one method per request — the arguments as a JSON array, the\n * answer as JSON — and only the StatsSource method names are served.\n */\n dev.middlewares.use('/__studio/stats/', (req, res) => {\n const sendJson = (status: number, body: unknown): void => {\n res.statusCode = status;\n res.setHeader('content-type', 'application/json');\n res.end(JSON.stringify(body));\n };\n void (async () => {\n if (req.method !== 'POST') {\n res.setHeader('allow', 'POST');\n sendJson(405, { error: 'stats calls are POST' });\n return;\n }\n const rejection = studioRequestRejection(req);\n if (rejection !== undefined) {\n sendJson(403, { error: rejection });\n return;\n }\n const method = (req.url ?? '').replace(/^\\//, '').split('?')[0] as StatsMethod;\n if (statsPath === undefined || !STATS_METHODS.includes(method)) {\n sendJson(404, { error: `no stats method '${method}'` });\n return;\n }\n try {\n const args: unknown = JSON.parse((await readBody(req)) || '[]');\n if (!Array.isArray(args)) {\n sendJson(400, { error: 'the body is the arguments, as a JSON array' });\n return;\n }\n const fn = (await loadStats(dev, statsPath))[method];\n if (fn === undefined) {\n sendJson(404, { error: `workflow.stats.ts defines no '${method}'` });\n return;\n }\n sendJson(200, (await fn(...args)) ?? null);\n } catch (error) {\n dev.config.logger.error(`[workflow-ui] stats ${method} failed: ${String(error)}`);\n sendJson(500, { error: error instanceof Error ? error.message : String(error) });\n }\n })();\n });\n },\n };\n}\n\n/* -------------------------------- Studio API -------------------------------- */\n\n/** `Sec-Fetch-Site` values no other site can produce: our own page, or a direct navigation. */\nconst OWN_FETCH_SITES = new Set(['same-origin', 'none']);\n\nfunction headerValue(raw: string | string[] | undefined): string | undefined {\n const value = Array.isArray(raw) ? raw[0] : raw;\n return value === undefined || value === '' ? undefined : value;\n}\n\n/**\n * Refuse any request another website could have caused, and say why.\n *\n * The node endpoint reads the developer's source files to answer, so a page\n * they merely *visit* should not be able to probe it. Vite's CORS handling\n * decides who may read a response; this decides whether the request is served\n * at all.\n *\n * - `Sec-Fetch-Site` is attached by the browser and cannot be set from\n * script, so anything but `same-origin` (our page) or `none` (the address\n * bar) is a request some other page caused — including `same-site`, which\n * covers another port on localhost.\n * - `Origin` covers clients that send no fetch metadata: present and not our\n * own host means cross-origin. Absent is allowed on purpose — a same-origin\n * GET and a terminal `curl` both have no Origin at all, and a cross-origin\n * browser request always has one.\n */\nexport function studioRequestRejection(req: Pick<IncomingMessage, 'headers'>): string | undefined {\n const site = headerValue(req.headers['sec-fetch-site']);\n if (site !== undefined && !OWN_FETCH_SITES.has(site)) {\n return `refused: sec-fetch-site is '${site}', so another site caused this request`;\n }\n const origin = headerValue(req.headers.origin);\n if (origin !== undefined) {\n const host = headerValue(req.headers.host);\n let originHost: string | undefined;\n try {\n originHost = new URL(origin).host;\n } catch {\n /* Opaque origins ('null' from a sandboxed frame or file://) never match. */\n originHost = undefined;\n }\n if (host === undefined || originHost?.toLowerCase() !== host.toLowerCase()) {\n return `refused: cross-origin request from ${origin}`;\n }\n }\n return undefined;\n}\n\n/**\n * The studio's dev-server API — read-only. The studio views source and never\n * writes it: edits happen in the editor, and Vite's watcher and HMR bring them\n * to the page. The one endpoint resolves a node's captured position to a line\n * on disk for display; everything else under `/__studio` answers 404, so the\n * write routes earlier versions served (`/__studio/envelope`,\n * `/__studio/addresses`, POST `/__studio/node`) are gone rather than hidden.\n */\nexport function studioApiPlugin(cwd: string): Plugin {\n const sendJson = (res: ServerResponse, status: number, body: unknown): void => {\n res.statusCode = status;\n res.setHeader('content-type', 'application/json');\n res.end(JSON.stringify(body));\n };\n\n return {\n name: 'workflow-ui:studio-api',\n configureServer(server) {\n /*\n * The client sends the position the DSL captured (NodeMetaIR.loc). The\n * project is evaluated on the server with source maps enabled, so that\n * is already a line on disk; this checks the path stays inside the\n * project and answers it relative to it. Navigation only: the panel\n * shows the row when this answers and leaves it out when it does not.\n */\n server.middlewares.use('/__studio/node', (req, res) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n res.setHeader('allow', 'GET, HEAD');\n sendJson(res, 405, { error: 'the studio is read-only: GET only' });\n return;\n }\n const rejection = studioRequestRejection(req);\n if (rejection !== undefined) {\n sendJson(res, 403, { error: rejection });\n return;\n }\n const params = new URL(req.url ?? '/', 'http://internal').searchParams;\n const found = sourcePosition(cwd, params.get('file') ?? '', Number(params.get('line')));\n if ('error' in found) {\n sendJson(res, 422, { error: found.error });\n return;\n }\n sendJson(res, 200, { file: relative(cwd, found.file), line: found.line });\n });\n\n /* Registered after the routes above, so it only sees what none of them took. */\n server.middlewares.use('/__studio', (_req, res) => {\n sendJson(res, 404, { error: 'no such studio endpoint' });\n });\n },\n };\n}\n\ntype Located = { file: string; line: number } | { error: string };\n\n/** The two `node:path` functions containment needs, so the suite can hand in `path.win32`. */\ninterface PathOps {\n isAbsolute: (path: string) => boolean;\n relative: (from: string, to: string) => string;\n}\n\n/**\n * Is `candidate` `root` itself or something below it?\n *\n * Asked through `relative`, never a string prefix. A prefix test needs a\n * trailing separator (or `/proj-evil` passes for `/proj`), and the separator it\n * appends is the wrong one on Windows, where `resolve()` returns `C:\\proj\\…`:\n * that mismatch failed every path on Windows, which is how the whole\n * /__studio/node surface came to answer \"outside the project\" there.\n */\nexport function isInsideDir(\n root: string,\n candidate: string,\n ops: PathOps = { isAbsolute, relative }\n): boolean {\n const rel = ops.relative(root, candidate);\n if (rel === '') return true;\n /* An absolute answer means there is no way down from root — another drive. */\n if (ops.isAbsolute(rel)) return false;\n /* Segment-wise, so a file legitimately named '..rc' is not read as an escape. */\n return rel.split(/[/\\\\]/)[0] !== '..';\n}\n\n/**\n * Keep a path that arrived from the browser inside the project.\n *\n * The scope is `cwd` — the project the studio was started in — and not the\n * workspace root `searchForWorkspaceRoot` walks up to: in a monorepo that root\n * is the whole repo, so a studio started in `apps/marketing` accepted\n * `file=../../packages/billing/src/rates.ts` and read it.\n */\nexport function isInsideProject(cwd: string, candidate: string): boolean {\n const root = resolve(cwd);\n const path = resolve(candidate);\n if (!isInsideDir(root, path)) return false;\n /*\n * Then again on the real paths: a symlink inside the project may point\n * anywhere, and the check above only ever sees the link's own path. A path\n * that does not exist has nothing to resolve — the caller reports that.\n */\n if (!existsSync(path)) return true;\n return isInsideDir(realpathSync(root), realpathSync(path));\n}\n\n/**\n * Check a captured position before answering with it.\n *\n * The path is validated against cwd before anything is touched: it arrives\n * from the browser, and an endpoint that follows an arbitrary path is a\n * read-anywhere endpoint.\n */\nfunction sourcePosition(cwd: string, rawFile: string, line: number): Located {\n let path = rawFile;\n if (/^https?:\\/\\//.test(path)) path = new URL(path).pathname;\n const fsPrefix = '/@fs';\n if (path.startsWith(fsPrefix)) path = path.slice(fsPrefix.length);\n path = resolve(cwd, decodeURIComponent(path));\n\n if (!isInsideProject(cwd, path)) return { error: 'source file is outside the project' };\n if (!existsSync(path)) return { error: `no such source file: ${path}` };\n if (!Number.isInteger(line) || line < 1) return { error: 'expected a line number' };\n return { file: path, line };\n}\n\n/** Vite's own `server.fs.deny` default; setting the option replaces it, so it is spelled out. */\nconst VITE_DEFAULT_DENY = ['.env', '.env.*', '*.{crt,pem}', '**/.git/**'];\n\n/**\n * What `server.fs.deny` refuses whatever the project: Vite's default, plus the credentials a\n * journey project keeps beside its code. `fs.allow` spans the project and its linked workspace\n * packages (see {@link studioFsAllow}), so without these\n * `/@fs/<path>/.dev.vars` (wrangler's secrets), an APNs `.p8` or a Firebase service account would\n * be one request away for any page that can reach the port. The same goes for what sits beside\n * any project: registry and network tokens (`.npmrc`, `.netrc`), direnv's `.envrc` (which\n * `.env.*` does not match), key stores, and the wrangler config with its `vars`.\n */\nexport const STUDIO_FS_DENY: readonly string[] = [\n ...VITE_DEFAULT_DENY,\n '**/.dev.vars*',\n '**/.envrc',\n '**/.npmrc',\n '**/.netrc',\n '**/wrangler.{toml,json,jsonc}',\n '**/*.p8',\n '**/*.plist',\n '**/google-services.json',\n '**/*.pfx',\n '**/*.p12',\n '**/*.jks',\n '**/*.keystore',\n '**/*.pem',\n '**/*.key',\n];\n\n/**\n * `server.fs.deny` patterns for files the page must never be served.\n *\n * `fs.allow` covers the project so the browser can import the template\n * registries, which also made `GET /@fs/<cwd>/workflow.stats.ts`\n * answer with the stats source — a file the README calls server-only, and the\n * one place a connection string is likely to be written as a literal. The\n * browser never imports the config or the stats file (the virtual module\n * imports the registries by their own paths; a registry written inline in the\n * config is refused for this reason), so both are denied outright.\n *\n * Patterns go through picomatch, so the path is spelled literally: its glob\n * characters escaped, slashes normalized the way Vite normalizes the file it\n * checks. A symlinked file is denied under both of its names.\n */\nexport function projectFileDeny(paths: readonly (string | undefined)[]): string[] {\n const deny = new Set<string>();\n for (const path of paths) {\n if (path === undefined) continue;\n const literal = resolve(path);\n deny.add(normalizePath(literal));\n if (existsSync(literal)) deny.add(normalizePath(realpathSync(literal)));\n }\n return [...deny].map((path) => path.replace(/[\\\\*?[\\]{}()!+@]/g, '\\\\$&'));\n}\n\n/** Whether `path` lies inside some `node_modules` directory (a store entry, not a workspace link). */\nfunction inNodeModules(path: string): boolean {\n return path.split(sep).includes('node_modules');\n}\n\n/**\n * Real paths of the workspace packages `dir` links in through `node_modules` (pnpm's\n * `workspace:` dependencies, npm/yarn workspaces), followed transitively. A link that resolves\n * into a `node_modules` directory is a store entry, covered by the store's own allow entry.\n */\nfunction linkedWorkspacePackages(dir: string, found = new Set<string>()): Set<string> {\n const modules = join(dir, 'node_modules');\n let names: string[];\n try {\n names = readdirSync(modules);\n } catch {\n return found;\n }\n const entries = names.flatMap((name) => {\n if (!name.startsWith('@')) return [join(modules, name)];\n try {\n return readdirSync(join(modules, name)).map((child) => join(modules, name, child));\n } catch {\n return [];\n }\n });\n for (const entry of entries) {\n let real: string;\n try {\n if (!lstatSync(entry).isSymbolicLink()) continue;\n real = realpathSync(entry);\n } catch {\n continue; // a dangling link\n }\n if (inNodeModules(real) || found.has(real)) continue;\n found.add(real);\n linkedWorkspacePackages(real, found);\n }\n return found;\n}\n\n/**\n * `server.fs.allow` for the studio: only what the page actually imports.\n *\n * - the studio package itself (the app source, its css and fonts);\n * - the consuming project: the directory the studio is started from, and the config's own\n * directory when `--config` points outside it (the registries the browser imports live there);\n * - the workspace packages those link in (a template importing `@acme/contract` from a sibling\n * workspace package), followed transitively;\n * - the `node_modules` of each workspace root involved: under pnpm every dependency's real path is\n * in the virtual store `node_modules/.pnpm` beside the workspace root rather than below the app,\n * and with npm/yarn or a hoisted pnpm layout they are directly in `node_modules`.\n *\n * Nothing else in the workspace: a sibling app's source and secrets are not one `/@fs/` request\n * away. The deny list still applies inside every one of these.\n */\nexport function studioFsAllow(options: {\n cwd: string;\n configPath: string;\n packageRoot: string;\n appRoot: string;\n}): string[] {\n const { cwd, configPath, packageRoot, appRoot } = options;\n const projectDirs = [cwd, dirname(configPath)];\n const allow = new Set<string>([packageRoot, appRoot, ...projectDirs]);\n for (const dir of [...projectDirs, packageRoot]) {\n for (const linked of linkedWorkspacePackages(dir)) allow.add(linked);\n allow.add(join(searchForWorkspaceRoot(dir), 'node_modules'));\n }\n return [...allow];\n}\n\nexport interface StartOptions {\n cwd?: string;\n config?: string;\n /** The studio's stats source (default ./workflow.stats.ts, if present). */\n stats?: string;\n port?: number;\n open?: boolean;\n}\n\nexport async function startStudio(options: StartOptions = {}): Promise<ViteDevServer> {\n const cwd = options.cwd ?? process.cwd();\n // The config is required (findConfig throws); the stats source is optional.\n // The resolved path is what the plugin loads — resolving again from cwd\n // inside it is what once made --config point at a file it does not name.\n const configPath = findConfig(cwd, options.config);\n const statsPath = findStats(cwd, options.stats);\n const appRoot = resolveAppRoot();\n\n const server = await createServer({\n root: appRoot,\n configFile: false,\n envDir: false,\n plugins: [\n react(),\n svgr(),\n tailwindcss(),\n projectPlugin(configPath, statsPath),\n studioApiPlugin(cwd),\n ],\n server: {\n port: options.port ?? 4321,\n open: options.open ?? false,\n fs: {\n allow: studioFsAllow({ cwd, configPath, packageRoot, appRoot }),\n deny: [...STUDIO_FS_DENY, ...projectFileDeny([configPath, statsPath])],\n },\n // The studio is its own origin and calls no one else's; no page elsewhere may read it\n cors: false,\n },\n // The app and the user's project each have their own react; one copy only. One\n // @shware/workflow too: the preview's <EmailProvider> and the project's layout calling\n // useEmailContext() must share the context object\n resolve: { dedupe: ['react', 'react-dom', '@shware/workflow'] },\n /*\n * @react-email/render imports react-dom/server lazily, so the dep scan never\n * sees it: the first email preview made Vite discover it, re-optimize and\n * change the deps hash under a page that still held the old one — the\n * preview then failed with \"Failed to fetch dynamically imported module\"\n * (a 504 Outdated Optimize Dep) until a reload. Bundling both up front\n * keeps the hash stable from the first request. The project's config is\n * scanned too (never served — only crawled), so its templates'\n * dependencies (@react-email/components, zod, …) are bundled before the\n * first preview rather than discovered by it.\n */\n optimizeDeps: {\n entries: ['index.html', configPath],\n include: ['@react-email/render', 'react-dom/server'],\n },\n });\n\n await server.listen();\n return server;\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, relative, resolve } from 'node:path';\nimport { type JourneyConfig, isConfig } from '@shware/workflow';\nimport { renderDrizzleSchema } from '@shware/workflow/store';\nimport { runnerImport } from 'vite';\nimport { findConfig } from './server';\n\n/**\n * `workflow-ui generate` — the engine's Postgres tables as one drizzle file, on the schema the\n * project's `database.schema` names (`workflow` by default). The host re-exports the file from\n * its drizzle schema and lets drizzle-kit write the migration, so the migration history stays the\n * host's. `--check` exits non-zero when the file on disk differs (CI, after an SDK upgrade).\n */\n\nexport interface GenerateOptions {\n cwd?: string;\n config?: string;\n out: string;\n check?: boolean;\n}\n\nexport type GenerateResult = 'written' | 'unchanged' | 'outdated';\n\n/** The host's formatter may rewrap the file, change quotes or trailing commas: not a difference. */\nfunction normalize(source: string): string {\n return (\n source\n .replace(/\"/g, \"'\")\n .replace(/\\s+/g, ' ')\n // Spaces around punctuation, and trailing commas, are the formatter's choice\n .replace(/ ?([{}()[\\],;:=<>.]) ?/g, '$1')\n .replace(/,([}\\])])/g, '$1')\n .trim()\n );\n}\n\nexport async function generateSchema(options: GenerateOptions): Promise<GenerateResult> {\n const cwd = options.cwd ?? process.cwd();\n const configPath = findConfig(cwd, options.config);\n const { module } = await runnerImport<{ default?: unknown }>(configPath);\n if (!isConfig(module.default)) {\n throw new Error(\n `workflow-ui: ${relative(cwd, configPath)} must \\`export default defineConfig({...})\\``\n );\n }\n const config: JourneyConfig = module.default;\n const file = renderDrizzleSchema(config.database?.schema);\n\n const out = resolve(cwd, options.out);\n const current = existsSync(out) ? readFileSync(out, 'utf8') : undefined;\n if (current !== undefined && normalize(current) === normalize(file)) return 'unchanged';\n if (options.check) return 'outdated';\n mkdirSync(dirname(out), { recursive: true });\n writeFileSync(out, file);\n return 'written';\n}\n","#!/usr/bin/env node\nimport { generateSchema } from './generate';\nimport { startStudio } from './server';\n\n/**\n * `workflow-ui` — start the studio over the project in ./workflow.config.ts.\n *\n * npx workflow-ui # reads ./workflow.config.ts (and ./workflow.stats.ts)\n * npx workflow-ui --port 5000\n * npx workflow-ui --config apps/marketing/workflow.config.ts\n * npx workflow-ui generate --out ../../packages/db/src/schema/workflow.ts [--check]\n * npx workflow-ui plan --database-url $DATABASE_URL\n */\n\ninterface Args {\n port?: number;\n config?: string;\n stats?: string;\n out?: string;\n databaseUrl?: string;\n check: boolean;\n open: boolean;\n help: boolean;\n}\n\nfunction parseArgs(argv: string[]): Args {\n const args: Args = { open: false, check: false, help: false };\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === '--help' || arg === '-h') args.help = true;\n else if (arg === '--open') args.open = true;\n else if (arg === '--check') args.check = true;\n else if (arg === '--out' || arg === '-o') args.out = argv[++i];\n else if (arg === '--database-url' || arg === '-d') args.databaseUrl = argv[++i];\n else if (arg === '--port' || arg === '-p') args.port = Number(argv[++i]);\n else if (arg === '--config' || arg === '-c') args.config = argv[++i];\n else if (arg === '--stats' || arg === '-s') args.stats = argv[++i];\n }\n return args;\n}\n\nconst HELP = `\n workflow-ui — review your workflows, templates and reports\n\n Usage\n $ workflow-ui [dev] [options]\n $ workflow-ui generate --out <file> [--check] [--config <path>]\n $ workflow-ui plan --database-url <url> [--config <path>]\n\n Options\n -p, --port <port> Port to listen on (default 4321)\n -c, --config <path> Project file (default ./workflow.config.ts)\n -s, --stats <path> Stats source (default ./workflow.stats.ts, if present)\n --open Open the browser on start\n -o, --out <file> generate: where the drizzle schema file goes\n --check generate: fail when the file is out of date, write nothing\n -d, --database-url plan: the engine's database (default $DATABASE_URL); exits 1 when the\n bundle would break journeys still running there\n -h, --help Show this message\n`;\n\nasync function main(): Promise<void> {\n const [command, ...rest] = process.argv.slice(2);\n if (command === 'generate') {\n const args = parseArgs(rest);\n if (args.help || args.out === undefined) {\n console.log(HELP);\n if (args.out === undefined && !args.help) process.exitCode = 1;\n return;\n }\n try {\n const result = await generateSchema({\n out: args.out,\n check: args.check,\n ...(args.config !== undefined ? { config: args.config } : {}),\n });\n if (result === 'outdated') {\n console.error(\n `\\n ${args.out} is out of date — run workflow-ui generate, then your migration tool\\n`\n );\n process.exitCode = 1;\n } else {\n console.log(`\\n ${args.out} ${result === 'written' ? 'written' : 'is up to date'}\\n`);\n }\n } catch (error) {\n console.error(`\\n${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n }\n return;\n }\n\n if (command === 'plan') {\n const args = parseArgs(rest);\n const databaseUrl = args.databaseUrl ?? process.env.DATABASE_URL;\n if (args.help || databaseUrl === undefined) {\n console.log(HELP);\n if (!args.help) {\n console.error('\\n plan needs --database-url <url> (or DATABASE_URL in the environment)\\n');\n process.exitCode = 1;\n }\n return;\n }\n try {\n // Loaded here, not at the top: `plan` is the one command that needs `postgres`, an optional\n // peer — a static import would make every command, `--help` included, fail without it\n const { formatPlan, planDeploy } = await import('./plan');\n const report = await planDeploy({\n databaseUrl,\n ...(args.config !== undefined ? { config: args.config } : {}),\n });\n console.log(`\\n ${formatPlan(report).join('\\n ')}\\n`);\n if (report.problems.length > 0) process.exitCode = 1;\n } catch (error) {\n console.error(`\\n${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n }\n return;\n }\n\n // `dev` is accepted so the command reads well; the studio is the default mode\n const argv = process.argv.slice(2).filter((arg) => arg !== 'dev');\n const args = parseArgs(argv);\n\n if (args.help) {\n console.log(HELP);\n return;\n }\n\n try {\n const server = await startStudio({\n ...(args.port !== undefined ? { port: args.port } : {}),\n ...(args.config !== undefined ? { config: args.config } : {}),\n ...(args.stats !== undefined ? { stats: args.stats } : {}),\n open: args.open,\n });\n const address = server.resolvedUrls?.local[0] ?? `http://localhost:${args.port ?? 4321}`;\n console.log(`\\n workflow-ui ready at ${address}\\n`);\n } catch (error) {\n console.error(`\\n${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n }\n}\n\nvoid main();\n"],"mappings":";;;;;;;;;;;;AAqCA,SAAgB,aAAa,QAAsC;CACjE,OAAO,aAAa;EAClB,KAAK,MAAM,OAAO,OAAO,YAAY,cAAc,OAAO,GAAG;GAC3D,MAAM,UAAU,IAAI;GACpB,IAAI,IAAI,SAAS,QAAQ,YAAY,MAAM,MAAM,CAAC,IAAI,MAAM,OAAO;EACrE;CACF;AACF;;AAYA,MAAM,WAGF;CACF,OAAO;EAAE,IAAI;EAAiB,SAAS;EAAiB,OAAO;CAAS;CACxE,MAAM;EAAE,IAAI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3D,GAAI,KAAK,UAAU,KAAA,IAAY,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;GACxD,MAAM,KAAK;EACb,CAAC,EAAA,CACsB,cAAc,MAAM,MAAM,oBAAoB,KAAK,QAAQ;EAClF,QAAQ,IAAI,4BAA4B,QAAQ,GAAG;CACrD,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,GAAG;EAC7E,QAAQ,WAAW;CACrB;AACF;AAEK,KAAK"}
package/dist/index.d.mts CHANGED
@@ -411,9 +411,15 @@ interface CanvasEdge {
411
411
  source: string;
412
412
  target: string;
413
413
  label?: string;
414
- /** Label anchor: `target` = the arm's entry corner (real arm); `source` = just below the deciding node (empty pass-through arm). */
414
+ /**
415
+ * Label anchor: `target` = the arm's entry corner (real arm); `source` = just below the deciding node (empty pass-through arm).
416
+ * `lane` is the x of the empty arm's own column, set when the straight way down from the
417
+ * deciding node is taken by another arm's cards: the connector then runs down that column and
418
+ * turns back to its target below the arms, with its label hanging in the column.
419
+ */
415
420
  data?: {
416
421
  anchor: 'source' | 'target';
422
+ lane?: number;
417
423
  };
418
424
  }
419
425
  export declare function layout(ir: WorkflowIR, stats?: NodeStats): {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":["Props","Props","Props"],"sources":["../src/components/button/index.tsx","../src/components/corner-shape.ts","../src/components/workflow-canvas.tsx","../src/utils/template-content.ts","../src/components/template-refs.ts","../src/components/templates-page.tsx","../src/components/push-preview.tsx","../src/components/workflow-list.tsx","../src/components/metric-card.tsx","../src/components/date-range.tsx","../src/components/channel-icon.ts","../src/components/avatar.tsx","../src/components/sparkline.tsx","../src/components/layout.ts"],"mappings":";;;;;;;;;;;;;;KAWY;UAEFA,gBAAc,KAAK;EAC3B,OAAO;EACP,WAAW;EACX;EACA;;wBAyCc,SACd,UACA,WACA,MACA,OACA,MACA,YACG,SACFA,0BAAK,IAAA;;;;;;;;;;;qBCtDK,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OAAO,MAAM;;wBAQb,YAAY,cAAc;;wBAM1B,SAAS,gBAAgB;;wBAQzB,UAAU,aAAa;UAU7B;EACR,OAAO;EACP,WAAW,OAAO;EAClB;;;;;;;;;;wBAWc,kBAAkB,OAAO,UAAU,aAAa,wBAAK,IAAA;;;;;;;;;;qBC3DxD,cAAc,OAAO,eAAe;;qBAYpC,mBAAmB;qBAEnB,cAAW,SAAa,8BAA4B;;;;;;;;;;;UCxBhD;;EAEf;;EAEA;;EAEA;;wBASc,SAAS,SAAS,OAAO,QAAe,8BAAW,IAAA;;;;;;;;UCrBlD;EACf;EACA;EACA;EACA;;wBAGc,YAAY,QAAQ,OAAY,QAAa,aAAa,iCAAc,IAAA;;;;;;;;;;KCD5E;KAEA;UAmBK,uBAAuB;EACtC;EACA;EACA,UAAU;;EAEV;EACA,MAAM;;EAEN;;;qBAIW;WAAc;WAAQ;;;;;;;;qBAOtB;WAAc;WAAgB;;UAE1B;EACf;EACA;EACA;IAAY;IAAW;;EACvB,MAAM;;UAGS;EACf;EACA;EACA;EACA;;EAEA;IAAS;;;wBAuNK,OACd,IAAI,YACJ,QAAQ;EACL,OAAO;EAAc,OAAO"}
1
+ {"version":3,"file":"index.d.mts","names":["Props","Props","Props"],"sources":["../src/components/button/index.tsx","../src/components/corner-shape.ts","../src/components/workflow-canvas.tsx","../src/utils/template-content.ts","../src/components/template-refs.ts","../src/components/templates-page.tsx","../src/components/push-preview.tsx","../src/components/workflow-list.tsx","../src/components/metric-card.tsx","../src/components/date-range.tsx","../src/components/channel-icon.ts","../src/components/avatar.tsx","../src/components/sparkline.tsx","../src/components/layout.ts"],"mappings":";;;;;;;;;;;;;;KAWY;UAEFA,gBAAc,KAAK;EAC3B,OAAO;EACP,WAAW;EACX;EACA;;wBAyCc,SACd,UACA,WACA,MACA,OACA,MACA,YACG,SACFA,0BAAK,IAAA;;;;;;;;;;;qBCtDK,cAAuD;;;;;;;;;;;;UCgDnD;EACf,IAAI;;EAEJ,QAAQ;;;;;;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BAQzB,UAAU,aAAa;UAU7B;EACR,OAAO;EACP,WAAW,OAAO;EAClB;;;;;;;;;;wBAWc,kBAAkB,OAAO,UAAU,aAAa,wBAAK,IAAA;;;;;;;;;;qBC3DxD,cAAc,OAAO,eAAe;;qBAYpC,mBAAmB;qBAEnB,cAAW,SAAa,8BAA4B;;;;;;;;;;;UCxBhD;;EAEf;;EAEA;;EAEA;;wBASc,SAAS,SAAS,OAAO,QAAe,8BAAW,IAAA;;;;;;;;UCrBlD;EACf;EACA;EACA;EACA;;wBAGc,YAAY,QAAQ,OAAY,QAAa,aAAa,iCAAc,IAAA;;;;;;;;;;KCD5E;KAEA;UAmBK,uBAAuB;EACtC;EACA;EACA,UAAU;;EAEV;EACA,MAAM;;EAEN;;;qBAIW;WAAc;WAAQ;;;;;;;;qBAOtB;WAAc;WAAgB;;UAE1B;EACf;EACA;EACA;IAAY;IAAW;;EACvB,MAAM;;UAGS;EACf;EACA;EACA;EACA;;;;;;;EAOA;IAAS;IAA6B;;;wBA2NxB,OACd,IAAI,YACJ,QAAQ;EACL,OAAO;EAAc,OAAO"}
package/dist/index.mjs CHANGED
@@ -120,10 +120,11 @@ const OP_LABEL = {
120
120
  function conditionLabel(c, fallback) {
121
121
  if (c.type === "segment") return c.segment;
122
122
  if (c.type === "not") return `not ${conditionLabel(c.condition, fallback)}`;
123
- if (c.type === "property") {
123
+ if (c.type === "property" || c.type === "trigger_payload") {
124
+ const path = c.type === "property" ? c.path : `trigger.${c.path}`;
124
125
  const op = OP_LABEL[c.op] ?? c.op;
125
126
  const value = c.op === "between" ? `${c.values?.[0]} – ${c.values?.[1]}` : c.op === "in_array" || c.op === "not_in_array" ? `[${c.values?.join(", ")}]` : c.value !== void 0 ? String(c.value) : "";
126
- return value === "" ? `${c.path} ${op}` : `${c.path} ${op} ${value}`;
127
+ return value === "" ? `${path} ${op}` : `${path} ${op} ${value}`;
127
128
  }
128
129
  if (c.type === "performed") return `did ${c.event}`;
129
130
  if (c.type === "reachable") return `reachable by ${c.channel}`;
@@ -285,7 +286,10 @@ function layout(ir, stats) {
285
286
  source: t.id,
286
287
  target,
287
288
  ...t.label !== void 0 ? { label: t.label } : {},
288
- ...t.anchor !== void 0 ? { data: { anchor: t.anchor } } : {}
289
+ ...t.anchor !== void 0 ? { data: {
290
+ anchor: t.anchor,
291
+ ...t.lane !== void 0 ? { lane: t.lane } : {}
292
+ } } : {}
289
293
  });
290
294
  };
291
295
  /** Lay out one sequence recursively: `cx` is the centre line; returns the bottom y and the tails that continue downward. */
@@ -313,12 +317,20 @@ function layout(ir, stats) {
313
317
  const groupTop = bottom + FORK_GAP;
314
318
  let maxBottom = groupTop;
315
319
  const groupTails = [];
320
+ let left = gx;
321
+ const blocked = groups.some((g, gi) => {
322
+ const right = left + (widths[gi] ?? W);
323
+ const across = g.nodes.length > 0 && left < cx && cx < right;
324
+ left = right + HGAP;
325
+ return across;
326
+ });
316
327
  groups.forEach((g, gi) => {
317
328
  const center = gx + (widths[gi] ?? W) / 2;
318
329
  if (g.nodes.length === 0) groupTails.push({
319
330
  id: n.id,
320
331
  label: g.label,
321
- anchor: "source"
332
+ anchor: "source",
333
+ ...blocked ? { lane: center } : {}
322
334
  });
323
335
  else {
324
336
  const r = layoutSeq(g.nodes, center, groupTop, [{
@@ -593,6 +605,12 @@ const edgeLabelStyle = {
593
605
  const BEND = 16;
594
606
  /** How far a labelled fork runs straight down before it turns. */
595
607
  const FORK_STEM = 28;
608
+ /**
609
+ * How far above its target a lane connector turns back. The layout keeps the arms' last card 72
610
+ * above the node they rejoin at, and that arm's own connector turns halfway down: the lane
611
+ * joins it on the same line.
612
+ */
613
+ const LANE_REJOIN = 36;
596
614
  /** Where a label pill hangs below the deciding node. */
597
615
  const LABEL_DROP = 56;
598
616
  const DOT_R = 3.5;
@@ -642,6 +660,31 @@ function orthogonalPath(sx, sy, tx, ty, splitY) {
642
660
  ].join(" ");
643
661
  }
644
662
  /**
663
+ * A pass-through arm's route when the straight way down is taken by another arm's cards (see
664
+ * `CanvasEdge.data.lane`): out to the arm's own empty column like any fork, down that column
665
+ * past the arms, and back in to the target.
666
+ */
667
+ function lanePath(sx, sy, tx, ty, lane, splitY) {
668
+ const rejoinY = Math.max(splitY, ty - LANE_REJOIN);
669
+ const out = Math.sign(lane - sx);
670
+ const back = Math.sign(tx - lane);
671
+ const drop = rejoinY - splitY;
672
+ const r1 = Math.max(0, Math.min(BEND, Math.abs(lane - sx) / 2, splitY - sy, drop / 2));
673
+ const r2 = Math.max(0, Math.min(BEND, Math.abs(tx - lane) / 2, drop / 2, ty - rejoinY));
674
+ return [
675
+ `M ${sx} ${sy}`,
676
+ `L ${sx} ${splitY - r1}`,
677
+ corner(sx, splitY - r1, sx, splitY, sx + out * r1, splitY),
678
+ `L ${lane - out * r1} ${splitY}`,
679
+ corner(lane - out * r1, splitY, lane, splitY, lane, splitY + r1),
680
+ `L ${lane} ${rejoinY - r2}`,
681
+ corner(lane, rejoinY - r2, lane, rejoinY, lane + back * r2, rejoinY),
682
+ `L ${tx - back * r2} ${rejoinY}`,
683
+ corner(tx - back * r2, rejoinY, tx, rejoinY, tx, rejoinY + r2),
684
+ `L ${tx} ${ty}`
685
+ ].join(" ");
686
+ }
687
+ /**
645
688
  * Custom edge with an HTML label: SVG EdgeText's height floats with the font's
646
689
  * bounding box, and only HTML can be pinned to exact pixels.
647
690
  *
@@ -652,11 +695,12 @@ function orthogonalPath(sx, sy, tx, ty, splitY) {
652
695
  * keeps several merge-edge labels from colliding at the far end)
653
696
  */
654
697
  function WorkflowEdge({ id, sourceX, sourceY, targetX, targetY, label, style, data }) {
655
- const anchoredAtSource = data?.anchor === "source";
698
+ const lane = data?.lane;
699
+ const anchoredAtSource = data?.anchor === "source" && lane === void 0;
656
700
  const splitY = label ? sourceY + (anchoredAtSource ? LABEL_DROP : FORK_STEM) : (sourceY + targetY) / 2;
657
- const path = orthogonalPath(sourceX, sourceY - HANDLE_INSET, targetX, targetY + HANDLE_INSET, splitY);
701
+ const path = lane === void 0 ? orthogonalPath(sourceX, sourceY - HANDLE_INSET, targetX, targetY + HANDLE_INSET, splitY) : lanePath(sourceX, sourceY - HANDLE_INSET, targetX, targetY + HANDLE_INSET, lane, splitY);
658
702
  const labelPos = {
659
- x: anchoredAtSource ? sourceX : targetX,
703
+ x: lane ?? (anchoredAtSource ? sourceX : targetX),
660
704
  y: sourceY + LABEL_DROP
661
705
  };
662
706
  return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(BaseEdge, {