@brickkit/cli 0.13.2 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"workflows2.js","names":[],"sources":["../src/workflows.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n resolveWorkflowPaths,\n WORKFLOW_BUNDLE,\n type BrickApp,\n} from \"@brickkit/core\";\nimport { ConfigError } from \"./config\";\n\ninterface Builders {\n StandaloneBuilder: new (config: Record<string, unknown>) => {\n build(): Promise<void>;\n getInputFiles(): Promise<string[]>;\n findTsConfigPath(): Promise<string | undefined>;\n };\n detectWorkflowPatterns(source: string): {\n hasDirective: boolean;\n hasSerde: boolean;\n };\n applySwcTransform(\n filename: string,\n source: string,\n mode: \"step\" | \"workflow\" | \"detect\" | false,\n absolutePath: string,\n projectRoot: string,\n moduleSpecifierRoot?: string,\n ): Promise<{ code: string }>;\n}\n\ntype BunPlugin = Parameters<typeof Bun.plugin>[0];\n\nconst DIRECTIVE = /[\"']use (?:step|workflow)[\"']/;\n\n/**\n * Every project source file. Not the generated bundle: it holds the directives as\n * text inside the SDK's own code and is already built. Not `.cjs` and `.cts`\n * either: Bun drops `module.exports` from a file a plugin loads.\n */\nconst TRANSFORMED = new RegExp(\n String.raw`^(?!.*(?:node_modules|${WORKFLOW_BUNDLE.dir.replaceAll(\".\", \"\\\\.\")}/)).*\\.(?:m?[jt]s|[jt]sx)$`,\n);\n\n/** Bun's own loader for each extension: JSX is allowed in `.js` but not in `.mjs`. */\nfunction loaderFor(path: string): \"ts\" | \"tsx\" | \"js\" | \"jsx\" {\n if (path.endsWith(\".tsx\")) return \"tsx\";\n if (/\\.m?ts$/.test(path)) return \"ts\";\n return path.endsWith(\".mjs\") ? \"js\" : \"jsx\";\n}\n\nasync function loadBuilders(\n root: string,\n): Promise<{ builders: Builders; path: string } | undefined> {\n let path: string;\n try {\n path = createRequire(join(root, \"package.json\")).resolve(\n \"@workflow/builders\",\n );\n } catch {\n // Not installed: the app uses no workflows. A broken install throws below.\n return undefined;\n }\n return {\n builders: (await import(pathToFileURL(path).href)) as Builders,\n path,\n };\n}\n\n/**\n * The plugin that turns `\"use workflow\"` and `\"use step\"` files into workflows and\n * steps. `registerWorkflowTransform` installs it for the running process;\n * `brick build` hands it to `Bun.build`.\n *\n * @param root - The project root, where the SDK is installed. Default: the working directory.\n * @returns The plugin, or `undefined` when the Workflow SDK and its builders are not\n * installed in the project.\n */\nexport async function workflowTransformPlugin(\n root: string = process.cwd(),\n): Promise<BunPlugin | undefined> {\n const load = await transformer(root);\n if (!load) return undefined;\n return {\n name: \"brick:workflows\",\n setup(build) {\n build.onLoad({ filter: TRANSFORMED }, load);\n },\n };\n}\n\ntype Load = Bun.OnLoadCallback;\n\n/** The transform for files of the project at `root`, or `undefined` without the SDK. */\nasync function transformer(root: string): Promise<Load | undefined> {\n const projectRoot = resolve(root);\n const builders = (await loadBuilders(projectRoot))?.builders;\n if (!builders) return undefined;\n // Not async: Bun treats a module whose load returns a promise as async, and\n // `require()` refuses it. Only a file with a directive waits for SWC.\n return (args) => {\n const source = readFileSync(args.path, \"utf8\");\n if (!DIRECTIVE.test(source))\n return { contents: source, loader: loaderFor(args.path) };\n // SWC strips the types but leaves JSX as it is.\n return builders\n .applySwcTransform(\n relative(projectRoot, args.path).replaceAll(\"\\\\\", \"/\"),\n source,\n \"step\",\n args.path,\n projectRoot,\n projectRoot,\n )\n .then(({ code }) => ({ contents: code, loader: \"jsx\" as const }));\n };\n}\n\n/** The transform of each root registered in this process. */\nconst registered = new Map<string, Load>();\n\n/** The registered root a file belongs to: the innermost that holds it, else the first. */\nfunction rootOf(file: string): string {\n let found: string | undefined;\n for (const root of registered.keys())\n if (file.startsWith(root + sep) && root.length > (found?.length ?? -1))\n found = root;\n return found ?? registered.keys().next().value!;\n}\n\n/**\n * Make files marked `\"use workflow\"` or `\"use step\"` load as workflows and steps.\n *\n * A workflow function gets the `workflowId` that `defineListener({ workflow })`\n * needs, and a step registers itself so the runtime can run it in this process.\n * `brick dev`, `brick start` and `brick worker` call it before they load the app.\n * Call it in a script or test before importing the files, with the project root.\n *\n * It does nothing, and returns `false`, when the Workflow SDK and its builders are\n * not installed in the project. Each root gets ids relative to itself; a file\n * under no registered root uses the first one.\n *\n * @param root - The project root, where the SDK is installed. Default: the working directory.\n * @returns Whether the transform is active.\n */\nexport async function registerWorkflowTransform(\n root: string = process.cwd(),\n): Promise<boolean> {\n const projectRoot = resolve(root);\n if (registered.has(projectRoot)) return true;\n const load = await transformer(projectRoot);\n if (!load) return false;\n registered.set(projectRoot, load);\n // Bun keeps a plugin until the process ends, so one plugin serves every root.\n if (registered.size === 1)\n Bun.plugin({\n name: \"brick:workflows\",\n setup(build) {\n build.onLoad({ filter: TRANSFORMED }, (args) =>\n registered.get(rootOf(args.path))!(args),\n );\n },\n });\n return true;\n}\n\n/** The state of the last build, kept beside the bundle it describes. */\nconst STATE_FILE = \".brick-build.json\";\n/** Bump it when what the state records changes, so an older state is not trusted. */\nconst STATE_VERSION = 2;\n/**\n * esbuild starts each module of a bundle with a `// <path>` comment, whatever\n * the file (`data.json` too). The other comments it keeps name no file.\n */\nconst MODULE_COMMENT = /^\\/\\/ (.+)$/gm;\nconst LOCKFILES = [\n \"bun.lock\",\n \"bun.lockb\",\n \"package-lock.json\",\n \"pnpm-lock.yaml\",\n \"yarn.lock\",\n];\n\n/** A file's modification time and size, or an empty string when it is gone. */\ntype Stamps = Record<string, string>;\n\ninterface BuildState {\n key: string;\n /** Every source file the builder looks at. */\n sources: Stamps;\n /** The files the bundle holds or was built with; the bundle is stale when one changes. */\n inputs: Stamps;\n}\n\nasync function stamps(paths: Iterable<string>): Promise<Stamps> {\n const list = [...paths];\n const all = await Promise.all(\n list.map(async (path) => {\n try {\n const { mtimeMs, size } = await stat(path);\n return `${mtimeMs}:${size}`;\n } catch {\n return \"\";\n }\n }),\n );\n return Object.fromEntries(list.map((path, index) => [path, all[index]]));\n}\n\nfunction lockfileOf(root: string): string | undefined {\n for (let dir = root; ; dir = dirname(dir)) {\n for (const name of LOCKFILES)\n if (existsSync(join(dir, name))) return join(dir, name);\n if (dirname(dir) === dir) return undefined;\n }\n}\n\nasync function tsconfigInputs(path: string | undefined): Promise<string[]> {\n const files = new Set<string>();\n async function visit(file: string) {\n if (files.has(file)) return;\n files.add(file);\n let config: unknown;\n try {\n config = Bun.JSONC.parse(await readFile(file, \"utf8\"));\n } catch {\n return;\n }\n if (!config || typeof config !== \"object\" || !(\"extends\" in config)) return;\n const parents = Array.isArray(config.extends)\n ? config.extends\n : [config.extends];\n const require = createRequire(file);\n for (const parent of parents) {\n if (typeof parent !== \"string\") continue;\n // esbuild's order, which builds the bundle: a path as written, then with\n // .json; for a package, its tsconfig.json before `${parent}.json`, never `main`.\n const isPath =\n isAbsolute(parent) ||\n parent.startsWith(\"./\") ||\n parent.startsWith(\"../\");\n const candidates = isPath\n ? [parent, `${parent}.json`]\n : [`${parent}/tsconfig.json`, `${parent}.json`, parent];\n let found: string | undefined;\n for (const specifier of candidates) {\n try {\n found = require.resolve(specifier);\n } catch {\n continue;\n }\n if (found.endsWith(\".json\")) break;\n found = undefined;\n }\n // esbuild still reads the tsconfig.json of a package whose `exports` hides it.\n found ??= isPath\n ? undefined\n : require.resolve\n .paths(parent)\n ?.map((dir) => join(dir, parent, \"tsconfig.json\"))\n .find(existsSync);\n if (found) await visit(found);\n }\n }\n if (path) await visit(path);\n return [...files];\n}\n\n/**\n * Whether the bundle on disk still matches its sources: nothing it was built\n * from has changed, and no other source has come to hold a workflow, a step or a\n * serializable class that the bundle would need to know.\n */\nasync function isCurrent(\n statePath: string,\n key: string,\n sources: string[],\n builders: Builders,\n outputs: string[],\n): Promise<boolean> {\n let state: BuildState;\n try {\n state = JSON.parse(await readFile(statePath, \"utf8\")) as BuildState;\n } catch {\n return false;\n }\n if (state.key !== key || !outputs.every((file) => existsSync(file)))\n return false;\n // A file added or removed can change what an import resolves to.\n if (\n sources.length !== Object.keys(state.sources).length ||\n sources.some((path) => !(path in state.sources))\n )\n return false;\n const inputs = await stamps(Object.keys(state.inputs));\n if (\n Object.entries(state.inputs).some(([path, stamp]) => inputs[path] !== stamp)\n )\n return false;\n const others = sources.filter((path) => !(path in state.inputs));\n const now = await stamps(others);\n const changed = others.filter((path) => now[path] !== state.sources[path]);\n const holds = await Promise.all(\n changed.map(async (path) => {\n const found = builders.detectWorkflowPatterns(\n await readFile(path, \"utf8\"),\n );\n return found.hasDirective || found.hasSerde;\n }),\n );\n return !holds.some(Boolean);\n}\n\n/**\n * Write down what the bundle was built from: the files esbuild bundled (it names\n * each one in a comment), every file with a directive or a serializable class, and\n * the files that decide how imports resolve. Writes nothing when one of them\n * changed while the build ran, because the bundle may then not match what was\n * recorded.\n */\nasync function recordState(\n statePath: string,\n key: string,\n sources: string[],\n builders: Builders,\n root: string,\n dir: string,\n bundles: string[],\n extra: (string | undefined)[],\n startedAt: number,\n): Promise<void> {\n // Stamped before they are read, so an edit made in between shows on the next reload.\n const sourceStamps = await stamps(sources);\n const found = new Set(extra.filter((path) => path !== undefined));\n for (const bundle of bundles) {\n const text = await readFile(bundle, \"utf8\");\n for (const [, path] of text.matchAll(MODULE_COMMENT)) {\n // The flow bundle imports the steps bundle as a module; both are outputs.\n const file = resolve(root, path);\n if (!file.startsWith(dir)) found.add(file);\n }\n }\n await Promise.all(\n sources.map(async (path) => {\n const patterns = builders.detectWorkflowPatterns(\n await readFile(path, \"utf8\"),\n );\n if (patterns.hasDirective || patterns.hasSerde) found.add(path);\n }),\n );\n // A comment that names no file, such as `// see foo.ts`, stamps as empty.\n const inputs = Object.fromEntries(\n Object.entries(await stamps(found)).filter(([, stamp]) => stamp),\n );\n if (\n Object.values(inputs).some((stamp) => Number.parseFloat(stamp) >= startedAt)\n )\n return;\n const state: BuildState = { key, sources: sourceStamps, inputs };\n await writeFile(statePath, JSON.stringify(state));\n}\n\n/**\n * Build the bundle that runs an app's workflows: `flow.mjs` and `manifest.json`\n * in `<root>/.well-known/workflow/v1`, from every file under `root` marked\n * `\"use workflow\"` or `\"use step\"`.\n *\n * `brick dev` and `brick start` call it before events start. Call it in a script\n * or test before starting events.\n *\n * @param options - `root`: the project root. Default: the working directory.\n * `reuse`: keep the bundle of the last build when nothing it was built from has\n * changed, which saves about a second on each reload of `brick dev`. Default:\n * `false`, always build.\n * @returns Whether it built the bundle; `false` when it kept the last one.\n * @throws When `@workflow/builders` is not installed in the project.\n */\nexport async function buildWorkflows(\n options: { root?: string; reuse?: boolean } = {},\n): Promise<boolean> {\n const { root, dir } = resolveWorkflowPaths(options);\n const loaded = await loadBuilders(root);\n if (!loaded)\n throw new Error(\n `Cannot build workflows: @workflow/builders is not installed in ${root}. Add it with: bun add -d @workflow/builders`,\n );\n const { builders } = loaded;\n const output = (name: string) =>\n `./${relative(root, join(dir, name)).replaceAll(\"\\\\\", \"/\")}`;\n const builder = new builders.StandaloneBuilder({\n buildTarget: \"standalone\",\n dirs: [\".\"],\n workingDir: root,\n stepsBundlePath: output(WORKFLOW_BUNDLE.steps),\n workflowsBundlePath: output(WORKFLOW_BUNDLE.flow),\n webhookBundlePath: output(WORKFLOW_BUNDLE.webhook),\n suppressCreateWorkflowsBundleLogs: true,\n suppressCreateWebhookBundleLogs: true,\n suppressCreateManifestLogs: true,\n });\n const statePath = join(dir, STATE_FILE);\n const bundles = [WORKFLOW_BUNDLE.flow, WORKFLOW_BUNDLE.steps].map((name) =>\n join(dir, name),\n );\n const outputs = [\n ...bundles,\n join(dir, WORKFLOW_BUNDLE.manifest),\n join(dir, WORKFLOW_BUNDLE.webhook),\n ];\n const configs = await tsconfigInputs(await builder.findTsConfigPath());\n const key = JSON.stringify([\n STATE_VERSION,\n loaded.path,\n // Resolve again on reload so a formerly missing parent also invalidates reuse.\n await stamps(configs),\n // The builder reads these too, and writes a different bundle for each.\n ...[\n \"NODE_ENV\",\n \"WORKFLOW_DISCOVER_NODE_MODULES\",\n \"WORKFLOW_SOURCEMAP\",\n \"WORKFLOW_EMIT_SOURCEMAPS_FOR_DEBUGGING\",\n \"WORKFLOW_PUBLIC_MANIFEST\",\n ].map((name) => process.env[name] ?? \"\"),\n ]);\n const sources = await builder.getInputFiles();\n if (\n options.reuse &&\n (await isCurrent(statePath, key, sources, builders, outputs))\n )\n return false;\n // A build that fails halfway leaves outputs the old state no longer describes.\n await rm(statePath, { force: true });\n const startedAt = Date.now();\n await builder.build();\n try {\n await recordState(\n statePath,\n key,\n sources,\n builders,\n root,\n dir,\n bundles,\n [join(root, \"package.json\"), lockfileOf(root), ...configs],\n startedAt,\n );\n } catch {\n // Without a state the next reload builds again, which is only slower.\n }\n return true;\n}\n\n/**\n * Build the workflow bundle an app needs, if it has workflow listeners.\n *\n * @param app - The loaded app.\n * @param options - `reuse`: keep the last bundle when its sources have not changed.\n * @returns Whether the app has a bundle, built now or kept from the last build.\n */\nexport async function buildAppWorkflows(\n app: BrickApp,\n options: { reuse?: boolean } = {},\n): Promise<boolean> {\n const target = app.events?.workflows;\n if (!target) return false;\n // Ids come from the path relative to the root, so the transform the files\n // loaded with and the bundle must share it. `brick build` loads none.\n if (registered.size && !registered.has(resolve(target.root)))\n throw new ConfigError(\n `Brick: the app's workflows root ${target.root} is not the folder its workflow files were transformed from (${[...registered.keys()].join(\", \")}). Run brick from the workflows root, or leave events.workflows.root unset.`,\n );\n const started = performance.now();\n const built = await buildWorkflows({\n root: target.root,\n reuse: options.reuse,\n });\n if (built)\n console.log(\n `[Brick-TS] Built workflows in ${Math.round(performance.now() - started)}ms`,\n );\n return true;\n}\n"],"mappings":";;;;;;;;AAkCA,MAAM,YAAY;;;;;;AAOlB,MAAM,cAAc,IAAI,OACtB,OAAO,GAAG,yBAAyB,gBAAgB,IAAI,WAAW,KAAK,KAA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readFileSync } from \"node:fs\";\nimport { cp, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n resolveWorkflowPaths,\n WORKFLOW_BUNDLE,\n type BrickApp,\n} from \"@brickkit/core\";\nimport { ConfigError } from \"./config\";\n\ninterface Builders {\n StandaloneBuilder: new (config: Record<string, unknown>) => {\n build(): Promise<void>;\n getInputFiles(): Promise<string[]>;\n findTsConfigPath(): Promise<string | undefined>;\n };\n detectWorkflowPatterns(source: string): {\n hasUseWorkflow: boolean;\n hasDirective: boolean;\n hasSerde: boolean;\n };\n applySwcTransform(\n filename: string,\n source: string,\n mode: \"step\" | \"workflow\" | \"detect\" | false,\n absolutePath: string,\n projectRoot: string,\n moduleSpecifierRoot?: string,\n ): Promise<{ code: string }>;\n}\n\ntype BunPlugin = Parameters<typeof Bun.plugin>[0];\n\nconst DIRECTIVE = /[\"']use (?:step|workflow)[\"']/;\n\n/**\n * Every project source file. Not the generated bundle: it holds the directives as\n * text inside the SDK's own code and is already built. Not `.cjs` and `.cts`\n * either: Bun drops `module.exports` from a file a plugin loads.\n */\nconst TRANSFORMED = new RegExp(\n String.raw`^(?!.*(?:node_modules|${WORKFLOW_BUNDLE.dir.replaceAll(\".\", \"\\\\.\")}/)).*\\.(?:m?[jt]s|[jt]sx)$`,\n);\n\n/** Bun's own loader for each extension: JSX is allowed in `.js` but not in `.mjs`. */\nfunction loaderFor(path: string): \"ts\" | \"tsx\" | \"js\" | \"jsx\" {\n if (path.endsWith(\".tsx\")) return \"tsx\";\n if (/\\.m?ts$/.test(path)) return \"ts\";\n return path.endsWith(\".mjs\") ? \"js\" : \"jsx\";\n}\n\nasync function loadBuilders(\n root: string,\n): Promise<{ builders: Builders; path: string } | undefined> {\n let path: string;\n try {\n path = createRequire(join(root, \"package.json\")).resolve(\n \"@workflow/builders\",\n );\n } catch {\n // Not installed: the app uses no workflows. A broken install throws below.\n return undefined;\n }\n return {\n builders: (await import(pathToFileURL(path).href)) as Builders,\n path,\n };\n}\n\n/**\n * The plugin that turns `\"use workflow\"` and `\"use step\"` files into workflows and\n * steps. `registerWorkflowTransform` installs it for the running process;\n * `brick build` hands it to `Bun.build`.\n *\n * @param root - The project root, where the SDK is installed. Default: the working directory.\n * @param onDirective - Called for each file it loads that holds a `\"use workflow\"` function.\n * @returns The plugin, or `undefined` when the Workflow SDK and its builders are not\n * installed in the project.\n */\nexport async function workflowTransformPlugin(\n root: string = process.cwd(),\n onDirective?: () => void,\n): Promise<BunPlugin | undefined> {\n const load = await transformer(root, onDirective);\n if (!load) return undefined;\n return {\n name: \"brick:workflows\",\n setup(build) {\n build.onLoad({ filter: TRANSFORMED }, load);\n },\n };\n}\n\ntype Load = Bun.OnLoadCallback;\n\n/** The transform for files of the project at `root`, or `undefined` without the SDK. */\nasync function transformer(\n root: string,\n onDirective?: () => void,\n): Promise<Load | undefined> {\n const projectRoot = resolve(root);\n const builders = (await loadBuilders(projectRoot))?.builders;\n if (!builders) return undefined;\n // Not async: Bun treats a module whose load returns a promise as async, and\n // `require()` refuses it. Only a file with a directive waits for SWC.\n return (args) => {\n const source = readFileSync(args.path, \"utf8\");\n if (!DIRECTIVE.test(source))\n return { contents: source, loader: loaderFor(args.path) };\n if (onDirective && builders.detectWorkflowPatterns(source).hasUseWorkflow)\n onDirective();\n // SWC strips the types but leaves JSX as it is.\n return builders\n .applySwcTransform(\n relative(projectRoot, args.path).replaceAll(\"\\\\\", \"/\"),\n source,\n \"step\",\n args.path,\n projectRoot,\n projectRoot,\n )\n .then(({ code }) => ({ contents: code, loader: \"jsx\" as const }));\n };\n}\n\n/** The transform of each root registered in this process. */\nconst registered = new Map<string, Load>();\n\n/** The registered root a file belongs to: the innermost that holds it, else the first. */\nfunction rootOf(file: string): string {\n let found: string | undefined;\n for (const root of registered.keys())\n if (file.startsWith(root + sep) && root.length > (found?.length ?? -1))\n found = root;\n return found ?? registered.keys().next().value!;\n}\n\n/**\n * Make files marked `\"use workflow\"` or `\"use step\"` load as workflows and steps.\n *\n * A workflow function gets the `workflowId` that `defineListener({ workflow })`\n * needs, and a step registers itself so the runtime can run it in this process.\n * `brick dev`, `brick start` and `brick worker` call it before they load the app.\n * Call it in a script or test before importing the files, with the project root.\n *\n * It does nothing, and returns `false`, when the Workflow SDK and its builders are\n * not installed in the project. Each root gets ids relative to itself; a file\n * under no registered root uses the first one.\n *\n * @param root - The project root, where the SDK is installed. Default: the working directory.\n * @returns Whether the transform is active.\n */\nexport async function registerWorkflowTransform(\n root: string = process.cwd(),\n): Promise<boolean> {\n const projectRoot = resolve(root);\n if (registered.has(projectRoot)) return true;\n const load = await transformer(projectRoot);\n if (!load) return false;\n registered.set(projectRoot, load);\n // Bun keeps a plugin until the process ends, so one plugin serves every root.\n if (registered.size === 1)\n Bun.plugin({\n name: \"brick:workflows\",\n setup(build) {\n build.onLoad({ filter: TRANSFORMED }, (args) =>\n registered.get(rootOf(args.path))!(args),\n );\n },\n });\n return true;\n}\n\n/** The state of the last build, kept beside the bundle it describes. */\nconst STATE_FILE = \".brick-build.json\";\n/** Bump it when what the state records changes, so an older state is not trusted. */\nconst STATE_VERSION = 2;\n/**\n * esbuild starts each module of a bundle with a `// <path>` comment, whatever\n * the file (`data.json` too). The other comments it keeps name no file.\n */\nconst MODULE_COMMENT = /^\\/\\/ (.+)$/gm;\nconst LOCKFILES = [\n \"bun.lock\",\n \"bun.lockb\",\n \"package-lock.json\",\n \"pnpm-lock.yaml\",\n \"yarn.lock\",\n];\n\n/** A file's modification time and size, or an empty string when it is gone. */\ntype Stamps = Record<string, string>;\n\ninterface BuildState {\n key: string;\n /** Every source file the builder looks at. */\n sources: Stamps;\n /** The files the bundle holds or was built with; the bundle is stale when one changes. */\n inputs: Stamps;\n}\n\nasync function stamps(paths: Iterable<string>): Promise<Stamps> {\n const list = [...paths];\n const all = await Promise.all(\n list.map(async (path) => {\n try {\n const { mtimeMs, size } = await stat(path);\n return `${mtimeMs}:${size}`;\n } catch {\n return \"\";\n }\n }),\n );\n return Object.fromEntries(list.map((path, index) => [path, all[index]]));\n}\n\nfunction lockfileOf(root: string): string | undefined {\n for (let dir = root; ; dir = dirname(dir)) {\n for (const name of LOCKFILES)\n if (existsSync(join(dir, name))) return join(dir, name);\n if (dirname(dir) === dir) return undefined;\n }\n}\n\nasync function tsconfigInputs(path: string | undefined): Promise<string[]> {\n const files = new Set<string>();\n async function visit(file: string) {\n if (files.has(file)) return;\n files.add(file);\n let config: unknown;\n try {\n config = Bun.JSONC.parse(await readFile(file, \"utf8\"));\n } catch {\n return;\n }\n if (!config || typeof config !== \"object\" || !(\"extends\" in config)) return;\n const parents = Array.isArray(config.extends)\n ? config.extends\n : [config.extends];\n const require = createRequire(file);\n for (const parent of parents) {\n if (typeof parent !== \"string\") continue;\n // esbuild's order, which builds the bundle: a path as written, then with\n // .json; for a package, its tsconfig.json before `${parent}.json`, never `main`.\n const isPath =\n isAbsolute(parent) ||\n parent.startsWith(\"./\") ||\n parent.startsWith(\"../\");\n const candidates = isPath\n ? [parent, `${parent}.json`]\n : [`${parent}/tsconfig.json`, `${parent}.json`, parent];\n let found: string | undefined;\n for (const specifier of candidates) {\n try {\n found = require.resolve(specifier);\n } catch {\n continue;\n }\n if (found.endsWith(\".json\")) break;\n found = undefined;\n }\n // esbuild still reads the tsconfig.json of a package whose `exports` hides it.\n found ??= isPath\n ? undefined\n : require.resolve\n .paths(parent)\n ?.map((dir) => join(dir, parent, \"tsconfig.json\"))\n .find(existsSync);\n if (found) await visit(found);\n }\n }\n if (path) await visit(path);\n return [...files];\n}\n\n/**\n * Whether the bundle on disk still matches its sources: nothing it was built\n * from has changed, and no other source has come to hold a workflow, a step or a\n * serializable class that the bundle would need to know.\n */\nasync function isCurrent(\n statePath: string,\n key: string,\n sources: string[],\n builders: Builders,\n outputs: string[],\n): Promise<boolean> {\n let state: BuildState;\n try {\n state = JSON.parse(await readFile(statePath, \"utf8\")) as BuildState;\n } catch {\n return false;\n }\n if (state.key !== key || !outputs.every((file) => existsSync(file)))\n return false;\n // A file added or removed can change what an import resolves to.\n if (\n sources.length !== Object.keys(state.sources).length ||\n sources.some((path) => !(path in state.sources))\n )\n return false;\n const inputs = await stamps(Object.keys(state.inputs));\n if (\n Object.entries(state.inputs).some(([path, stamp]) => inputs[path] !== stamp)\n )\n return false;\n const others = sources.filter((path) => !(path in state.inputs));\n const now = await stamps(others);\n const changed = others.filter((path) => now[path] !== state.sources[path]);\n const holds = await Promise.all(\n changed.map(async (path) => {\n const found = builders.detectWorkflowPatterns(\n await readFile(path, \"utf8\"),\n );\n return found.hasDirective || found.hasSerde;\n }),\n );\n return !holds.some(Boolean);\n}\n\n/**\n * Write down what the bundle was built from: the files esbuild bundled (it names\n * each one in a comment), every file with a directive or a serializable class, and\n * the files that decide how imports resolve. Writes nothing when one of them\n * changed while the build ran, because the bundle may then not match what was\n * recorded.\n */\nasync function recordState(\n statePath: string,\n key: string,\n sources: string[],\n builders: Builders,\n root: string,\n dir: string,\n bundles: string[],\n extra: (string | undefined)[],\n startedAt: number,\n): Promise<void> {\n // Stamped before they are read, so an edit made in between shows on the next reload.\n const sourceStamps = await stamps(sources);\n const found = new Set(extra.filter((path) => path !== undefined));\n for (const bundle of bundles) {\n const text = await readFile(bundle, \"utf8\");\n for (const [, path] of text.matchAll(MODULE_COMMENT)) {\n // The flow bundle imports the steps bundle as a module; both are outputs.\n const file = resolve(root, path);\n if (!file.startsWith(dir)) found.add(file);\n }\n }\n await Promise.all(\n sources.map(async (path) => {\n const patterns = builders.detectWorkflowPatterns(\n await readFile(path, \"utf8\"),\n );\n if (patterns.hasDirective || patterns.hasSerde) found.add(path);\n }),\n );\n // A comment that names no file, such as `// see foo.ts`, stamps as empty.\n const inputs = Object.fromEntries(\n Object.entries(await stamps(found)).filter(([, stamp]) => stamp),\n );\n if (\n Object.values(inputs).some((stamp) => Number.parseFloat(stamp) >= startedAt)\n )\n return;\n const state: BuildState = { key, sources: sourceStamps, inputs };\n await writeFile(statePath, JSON.stringify(state));\n}\n\n/**\n * Build the bundle that runs an app's workflows: `flow.mjs` and `manifest.json`\n * in `<root>/.well-known/workflow/v1`, from every file under `root` marked\n * `\"use workflow\"` or `\"use step\"`.\n *\n * `brick dev` and `brick start` call it before events start. Call it in a script\n * or test before starting events.\n *\n * @param options - `root`: the project root. Default: the working directory.\n * `reuse`: keep the bundle of the last build when nothing it was built from has\n * changed, which saves about a second on each reload of `brick dev`. Default:\n * `false`, always build.\n * @returns Whether it built the bundle; `false` when it kept the last one.\n * @throws When `@workflow/builders` is not installed in the project.\n */\nexport async function buildWorkflows(\n options: { root?: string; reuse?: boolean } = {},\n): Promise<boolean> {\n const { root, dir } = resolveWorkflowPaths(options);\n const loaded = await loadBuilders(root);\n if (!loaded)\n throw new Error(\n `Cannot build workflows: @workflow/builders is not installed in ${root}. Add it with: bun add -d @workflow/builders`,\n );\n const { builders } = loaded;\n const output = (name: string) =>\n `./${relative(root, join(dir, name)).replaceAll(\"\\\\\", \"/\")}`;\n const builder = new builders.StandaloneBuilder({\n buildTarget: \"standalone\",\n dirs: [\".\"],\n workingDir: root,\n stepsBundlePath: output(WORKFLOW_BUNDLE.steps),\n workflowsBundlePath: output(WORKFLOW_BUNDLE.flow),\n webhookBundlePath: output(WORKFLOW_BUNDLE.webhook),\n suppressCreateWorkflowsBundleLogs: true,\n suppressCreateWebhookBundleLogs: true,\n suppressCreateManifestLogs: true,\n });\n const statePath = join(dir, STATE_FILE);\n const bundles = [WORKFLOW_BUNDLE.flow, WORKFLOW_BUNDLE.steps].map((name) =>\n join(dir, name),\n );\n const outputs = [\n ...bundles,\n join(dir, WORKFLOW_BUNDLE.manifest),\n join(dir, WORKFLOW_BUNDLE.webhook),\n ];\n const configs = await tsconfigInputs(await builder.findTsConfigPath());\n const key = JSON.stringify([\n STATE_VERSION,\n loaded.path,\n // Resolve again on reload so a formerly missing parent also invalidates reuse.\n await stamps(configs),\n // The builder reads these too, and writes a different bundle for each.\n ...[\n \"NODE_ENV\",\n \"WORKFLOW_DISCOVER_NODE_MODULES\",\n \"WORKFLOW_SOURCEMAP\",\n \"WORKFLOW_EMIT_SOURCEMAPS_FOR_DEBUGGING\",\n \"WORKFLOW_PUBLIC_MANIFEST\",\n ].map((name) => process.env[name] ?? \"\"),\n ]);\n const sources = await builder.getInputFiles();\n if (\n options.reuse &&\n (await isCurrent(statePath, key, sources, builders, outputs))\n )\n return false;\n // A build that fails halfway leaves outputs the old state no longer describes.\n await rm(statePath, { force: true });\n const startedAt = Date.now();\n await builder.build();\n try {\n await recordState(\n statePath,\n key,\n sources,\n builders,\n root,\n dir,\n bundles,\n [join(root, \"package.json\"), lockfileOf(root), ...configs],\n startedAt,\n );\n } catch {\n // Without a state the next reload builds again, which is only slower.\n }\n return true;\n}\n\n/**\n * Build the workflow bundle an app needs, if it has workflow listeners.\n *\n * @param app - The loaded app.\n * @param options - `reuse`: keep the last bundle when its sources have not changed.\n * @returns Whether the app has a bundle, built now or kept from the last build.\n */\nexport async function buildAppWorkflows(\n app: BrickApp,\n options: { reuse?: boolean } = {},\n): Promise<boolean> {\n const target = app.events?.workflows;\n if (!target) return false;\n // Ids come from the path relative to the root, so the transform the files\n // loaded with and the bundle must share it. `brick build` loads none.\n if (registered.size && !registered.has(resolve(target.root)))\n throw new ConfigError(\n `Brick: the app's workflows root ${target.root} is not the folder its workflow files were transformed from (${[...registered.keys()].join(\", \")}). Run brick from the workflows root, or leave events.workflows.root unset.`,\n );\n // A compiled server reads the bundle `brick build` shipped beside it. Its\n // own copy of core knows, so ask the app rather than compare paths: run from\n // the outdir, the shipped bundle sits where a built one would.\n if (target.shipped) return true;\n const started = performance.now();\n const built = await buildWorkflows({\n root: target.root,\n reuse: options.reuse,\n });\n if (built)\n console.log(\n `[Brick-TS] Built workflows in ${Math.round(performance.now() - started)}ms`,\n );\n return true;\n}\n\n/**\n * What `brick build` ships: the workflow bundle, built from the project and\n * copied to `<outdir>/.well-known/workflow/v1`, where the compiled server reads\n * it. `brick build` calls it when the bundle holds a `\"use workflow\"` function, or\n * the loaded app runs workflows.\n *\n * @param root - The project root.\n * @param outdir - Where the compiled server is written.\n * @param required - The loaded app runs workflows, so the SDK must be installed.\n * @returns Whether a bundle was shipped: it holds a workflow, or one is required.\n */\nexport async function shipWorkflows(\n root: string,\n outdir: string,\n required: boolean,\n): Promise<boolean> {\n await buildWorkflows({ root });\n const dir = join(resolve(root), WORKFLOW_BUNDLE.dir);\n const manifest = JSON.parse(\n await readFile(join(dir, WORKFLOW_BUNDLE.manifest), \"utf8\"),\n ) as { workflows?: Record<string, unknown> };\n if (!required && !Object.keys(manifest.workflows ?? {}).length) return false;\n for (const name of [\n WORKFLOW_BUNDLE.flow,\n WORKFLOW_BUNDLE.steps,\n WORKFLOW_BUNDLE.webhook,\n WORKFLOW_BUNDLE.manifest,\n ])\n await cp(join(dir, name), join(outdir, WORKFLOW_BUNDLE.dir, name));\n return true;\n}\n"],"mappings":";;;;;;;;AAmCA,MAAM,YAAY;;;;;;AAOlB,MAAM,cAAc,IAAI,OACtB,OAAO,GAAG,yBAAyB,gBAAgB,IAAI,WAAW,KAAK,KAAK,EAAE,2BAChF;;AAGA,SAAS,UAAU,MAA2C;CAC5D,IAAI,KAAK,SAAS,MAAM,GAAG,OAAO;CAClC,IAAI,UAAU,KAAK,IAAI,GAAG,OAAO;CACjC,OAAO,KAAK,SAAS,MAAM,IAAI,OAAO;AACxC;AAEA,eAAe,aACb,MAC2D;CAC3D,IAAI;CACJ,IAAI;EACF,OAAO,cAAc,KAAK,MAAM,cAAc,CAAC,CAAC,CAAC,QAC/C,oBACF;CACF,QAAQ;EAEN;CACF;CACA,OAAO;EACL,UAAW,MAAM,OAAO,cAAc,IAAI,CAAC,CAAC;EAC5C;CACF;AACF;;;;;;;;;;;AAYA,eAAsB,wBACpB,OAAe,QAAQ,IAAI,GAC3B,aACgC;CAChC,MAAM,OAAO,MAAM,YAAY,MAAM,WAAW;CACh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AAK,QAAQ,gBAAgB,KAAK,IAAI,CAAC;CACnE,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brickkit/cli",
3
- "version": "0.13.2",
3
+ "version": "0.14.0",
4
4
  "description": "CLI and server engine for Brick-TS",
5
5
  "homepage": "https://brickkit.dev",
6
6
  "keywords": [
@@ -93,7 +93,7 @@
93
93
  "format:check": "oxfmt --check ."
94
94
  },
95
95
  "dependencies": {
96
- "@brickkit/core": "^0.13.2",
96
+ "@brickkit/core": "^0.14.0",
97
97
  "@opentelemetry/api": "^1.10.0",
98
98
  "@opentelemetry/context-async-hooks": "^3.0.0",
99
99
  "@opentelemetry/core": "^3.0.0",