@brickkit/cli 0.13.1 → 0.13.3
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/bin.js +2 -0
- package/dist/bin.js.map +1 -1
- package/dist/build.js +30 -12
- package/dist/build.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/project.js +1 -1
- package/dist/workflows.d.ts +14 -1
- package/dist/workflows.js +1 -1
- package/dist/workflows2.js +32 -5
- package/dist/workflows2.js.map +1 -1
- package/package.json +2 -2
package/dist/bin.js
CHANGED
|
@@ -550,7 +550,9 @@ ${PORT_RESOLUTION_HELP}`);
|
|
|
550
550
|
console.log(`Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`);
|
|
551
551
|
console.log(`IR: ${result.outdir}/brick-ir.json`);
|
|
552
552
|
if (result.dashboard) console.log(`Dashboard extension: ${result.dashboard}`);
|
|
553
|
+
if (result.workflows) console.log(`Workflows: ${result.workflows}`);
|
|
553
554
|
console.log(`Run: bun ${result.entry}`);
|
|
555
|
+
process.exit(0);
|
|
554
556
|
});
|
|
555
557
|
const gen = program.command("gen").description("Generate artifacts from a BrickApp entry").argument("[subcommand]", "Generator to run (openapi, client, manifest)").action(async (subcommand, _opts, command) => {
|
|
556
558
|
const project = await projectOf(command);
|
package/dist/bin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bin.js","names":["posix","cliPkg.version"],"sources":["../src/lint/run.ts","../src/lint.ts","../src/db.ts","../src/bin.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport { mkdtempSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { ConfigError } from \"../config\";\nimport type { BrickSettings } from \"./ast\";\nimport type { Severity } from \"./presets\";\n\nexport interface LintMessage {\n /** Path from the project root. */\n file: string;\n line: number;\n column: number;\n /** `brick/<rule>`. */\n rule: string;\n severity: \"error\" | \"warn\";\n message: string;\n}\n\nlet fromSource: string | undefined;\n/** The lint/oxlint entry oxlint loads under Node: the bundle beside this code, or, run from source, a fresh bundle of it. */\nfunction pluginPath() {\n const here = fileURLToPath(import.meta.url);\n if (!here.endsWith(\".ts\")) return resolve(dirname(here), \"lint/oxlint.js\");\n if (fromSource) return fromSource;\n // Inside the package, so Node resolves the bundle's imports from here.\n const file = resolve(here, \"../../../node_modules/.cache/brick-lint.js\");\n // Built beside it, then renamed: another process may be loading it.\n const building = `${file}.${process.pid}`;\n const result = spawnSync(\n process.execPath,\n [\"build\", resolve(dirname(here), \"oxlint.ts\"), \"--target\", \"node\"].concat([\n \"--packages\",\n \"external\",\n \"--outfile\",\n building,\n ]),\n { encoding: \"utf8\" },\n );\n if (result.status !== 0)\n throw new Error(\n `Brick: building the lint plugin failed:\\n${result.stderr}`,\n );\n renameSync(building, file);\n return (fromSource = file);\n}\n\nfunction oxlintBin(root: string) {\n for (const base of [\n join(root, \"package.json\"),\n fileURLToPath(import.meta.url),\n ]) {\n try {\n const pkg = createRequire(base).resolve(\"oxlint/package.json\");\n return join(dirname(pkg), \"bin/oxlint\");\n } catch {}\n }\n throw new ConfigError(\n \"Brick: brick lint needs oxlint; add it: bun add -d oxlint\",\n );\n}\n\n/**\n * Run the file rules over a project with oxlint, as `brick lint` does.\n * Only rules set to \"error\" or \"warn\" run; `ignore` globs are relative to `root`.\n */\nexport function runFileRules(options: {\n root: string;\n rules: Record<string, Severity>;\n settings: BrickSettings;\n ignore?: string[];\n fix?: boolean;\n}): LintMessage[] {\n const rules = Object.fromEntries(\n Object.entries(options.rules).filter(([, severity]) => severity !== \"off\"),\n );\n if (Object.keys(rules).length === 0) return [];\n const directory = mkdtempSync(join(tmpdir(), \"brick-lint-\"));\n try {\n const config = join(directory, \"oxlintrc.json\");\n writeFileSync(\n config,\n JSON.stringify({\n plugins: [],\n categories: { correctness: \"off\" },\n jsPlugins: [{ name: \"brick\", specifier: pluginPath() }],\n settings: { brick: options.settings },\n rules,\n }),\n );\n const result = spawnSync(\n oxlintBin(options.root),\n [\n \"-c\",\n config,\n \"--format\",\n \"json\",\n \"--disable-nested-config\",\n \"--no-error-on-unmatched-pattern\",\n ...(options.fix ? [\"--fix\"] : []),\n ...(options.ignore ?? []).flatMap((pattern) => [\n \"--ignore-pattern\",\n pattern,\n ]),\n \".\",\n ],\n { cwd: options.root, encoding: \"utf8\", maxBuffer: 64 * 1024 * 1024 },\n );\n if (result.error) throw result.error;\n let report: {\n diagnostics?: {\n message: string;\n code?: string;\n severity: string;\n filename: string;\n labels?: { span: { line: number; column: number } }[];\n }[];\n };\n try {\n report = JSON.parse(result.stdout);\n } catch {\n throw new Error(\n `Brick: oxlint failed (exit ${result.status}):\\n${result.stderr || result.stdout}`,\n );\n }\n return (report.diagnostics ?? []).map((diagnostic) => ({\n file: diagnostic.filename,\n line: diagnostic.labels?.[0]?.span.line ?? 1,\n column: diagnostic.labels?.[0]?.span.column ?? 1,\n // Parse errors come without a rule code.\n rule: diagnostic.code?.replace(/^brick\\((.*)\\)$/, \"brick/$1\") ?? \"syntax\",\n severity: diagnostic.severity === \"error\" ? \"error\" : \"warn\",\n message: diagnostic.message,\n }));\n } finally {\n rmSync(directory, { recursive: true, force: true });\n }\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { basename, dirname, relative, resolve, sep } from \"node:path\";\nimport { isCrudEvent } from \"@brickkit/core\";\nimport type { BrickApp, DatabaseHandle } from \"@brickkit/core\";\nimport { loadBrickApp } from \"./app-entry\";\nimport type { LoadedConfig } from \"./config\";\nimport { APP_RULES, type Severity } from \"./lint/presets\";\nimport { projectRules } from \"./lint/project\";\nimport { serviceFolders } from \"./lint/ast\";\nimport { runFileRules, type LintMessage } from \"./lint/run\";\nimport {\n DEFINITION_EXTENSIONS,\n DEFINITION_FILE,\n TEST_FILE,\n} from \"./definitions\";\nimport { writeServiceManifest } from \"./manifest\";\n\nconst posix = (path: string) => path.split(sep).join(\"/\");\nconst SOURCE = new Bun.Glob(\n `**/*.{${[...DEFINITION_EXTENSIONS, \"cts\"].join(\",\")}}`,\n);\n\ninterface AppCheck {\n root: string;\n entry: string;\n services: string;\n severity: (rule: string) => Severity;\n ignored: (rel: string) => boolean;\n}\n\n/**\n * `brick lint`: the file rules through oxlint, then the app\n * rules against the loaded app. Prints `file:line:col` lines and returns the\n * exit code: 1 when anything is an error.\n */\nexport async function runLint(options: {\n entry?: string;\n project: LoadedConfig;\n}): Promise<number> {\n const entry = options.entry ? resolve(options.entry) : options.project.entry;\n const project = { ...options.project, entry };\n const { root, services } = project;\n const { resolved, rules, settings, ignore } = projectRules(project);\n const messages = runFileRules({ root, rules, settings, ignore });\n const globs = ignore.map((pattern) => new Bun.Glob(pattern));\n if (existsSync(entry)) {\n if (project.file) await writeServiceManifest(project);\n messages.push(\n ...(await checkApp({\n root,\n entry,\n services,\n severity: (rule) => resolved[`brick/${rule}`] ?? \"off\",\n ignored: (rel) =>\n rel.split(\"/\").includes(\"node_modules\") ||\n globs.some((glob) => glob.match(rel)),\n })),\n );\n } else if (options.entry || project.file)\n throw new Error(`Brick: entry not found: ${entry}`);\n return report(messages);\n}\n\nfunction report(messages: LintMessage[]): number {\n messages.sort(\n (a, b) =>\n a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column,\n );\n for (const m of messages)\n console.log(\n `${m.file}:${m.line}:${m.column} ${m.severity === \"error\" ? \"error\" : \"warning\"} ${m.message} ${m.rule}`,\n );\n const errors = messages.filter((m) => m.severity === \"error\").length;\n const warnings = messages.length - errors;\n console.log(\n messages.length\n ? `\\n✖ ${messages.length} problem${messages.length === 1 ? \"\" : \"s\"} (${errors} error${errors === 1 ? \"\" : \"s\"}, ${warnings} warning${warnings === 1 ? \"\" : \"s\"})`\n : \"✔ No lint problems\",\n );\n return errors > 0 ? 1 : 0;\n}\n\n/** Project source files, from the root, without tests, ignored and generated files. */\nfunction sourceFiles(check: AppCheck, under = check.root): string[] {\n if (!existsSync(under)) return [];\n return [...SOURCE.scanSync({ cwd: under, onlyFiles: true })]\n .map((file) => resolve(under, file))\n .filter((file) => {\n const rel = posix(relative(check.root, file));\n return (\n !check.ignored(rel) && !TEST_FILE.test(rel) && !rel.startsWith(\"dist/\")\n );\n });\n}\n\nfunction lineOf(source: string, index: number) {\n return source.slice(0, index).split(\"\\n\").length;\n}\n\ntype Add = (file: string, message: string, line?: number) => void;\ntype AppRule = (check: AppCheck, app: BrickApp, add: Add) => unknown;\n\n/** Each app rule's check; a rule in APP_RULES without one fails to compile. */\nconst APP_CHECKS: Record<(typeof APP_RULES)[number], AppRule> = {\n \"single-app-entry\": singleAppEntry,\n \"no-cross-service-tables\": noCrossServiceTables,\n // Startup refuses duplicate names, so checkApp reports it when the app loads.\n \"unique-names\": () => {},\n \"declared-events\": declaredEvents,\n \"test-colocated\": testColocated,\n};\n\nasync function checkApp(check: AppCheck): Promise<LintMessage[]> {\n const messages: LintMessage[] = [];\n const message = (\n rule: string,\n severity: Exclude<Severity, \"off\">,\n file: string,\n text: string,\n line = 1,\n ): LintMessage => ({\n file: posix(relative(check.root, file)),\n line,\n column: 1,\n rule: `brick/${rule}`,\n severity,\n message: text,\n });\n let app: BrickApp;\n try {\n app = await loadBrickApp(check.entry);\n } catch (error) {\n // An app that cannot start fails lint, even with unique-names off.\n if ((error as Error).name === \"DuplicateNameError\") {\n return [\n message(\"unique-names\", \"error\", check.entry, (error as Error).message),\n ];\n }\n throw error;\n }\n for (const [rule, run] of Object.entries(APP_CHECKS)) {\n const severity = check.severity(rule);\n if (severity === \"off\") continue;\n await run(check, app, (file, text, line) =>\n messages.push(message(rule, severity, file, text, line)),\n );\n }\n return messages;\n}\n\nfunction singleAppEntry(check: AppCheck, _app: BrickApp, add: Add) {\n let calls = 0;\n for (const file of sourceFiles(check)) {\n const source = readFileSync(file, \"utf8\");\n // shortcut: a text search for brick( in files that import it from core.\n if (\n !/import\\s*\\{[^}]*\\bbrick\\b[^}]*\\}\\s*from\\s*[\"']@brickkit\\/core[\"']/.test(\n source,\n )\n )\n continue;\n for (const match of source.matchAll(/(?<![.\\w])brick\\s*\\(/g)) {\n if (file === check.entry && ++calls === 1) continue;\n add(\n file,\n file === check.entry\n ? \"The entry calls brick() more than once; keep one app.\"\n : `brick() is called outside the entry (${posix(relative(check.root, check.entry))}); keep one app.`,\n lineOf(source, match.index),\n );\n }\n }\n}\n\n/** Which service owns each table: its resources' and registered tables, or a database it alone uses. */\nfunction tableOwners(app: BrickApp) {\n const owners = new Map<unknown, string>();\n const users = new Map<DatabaseHandle<unknown>, string[]>();\n for (const service of app.definition.services) {\n for (const table of service.tables.values())\n owners.set(table, service.name);\n const { database } = service.options;\n if (database)\n users.set(database, [...(users.get(database) ?? []), service.name]);\n }\n for (const [database, names] of users)\n if (names.length === 1)\n for (const table of Object.values(database.tables))\n if (!owners.has(table)) owners.set(table, names[0]!);\n return owners;\n}\n\nfunction serviceOfFolder(app: BrickApp, folder: string) {\n return app.definition.services.find((service) =>\n serviceFolders(service.name).includes(folder),\n )?.name;\n}\n\n// shortcut: a text search for static imports and re-exports; misses `import()`.\nconst IMPORT =\n /(?:import|export)\\s+(type\\s+)?([\\w$]+\\s*,?\\s*)?(\\*(?:\\s+as\\s+[\\w$]+)?|\\{[^}]*\\})?\\s*from\\s*[\"']([^\"']+)[\"']/g;\n\nasync function noCrossServiceTables(check: AppCheck, app: BrickApp, add: Add) {\n const owners = tableOwners(app);\n for (const file of sourceFiles(check, check.services)) {\n const folder = posix(relative(check.services, file)).split(\"/\")[0]!;\n const service = serviceOfFolder(app, folder);\n if (!service) continue;\n const source = readFileSync(file, \"utf8\");\n for (const match of source.matchAll(IMPORT)) {\n const [, typeOnly, defaultName, rest, specifier] = match;\n if (typeOnly || !specifier!.startsWith(\".\")) continue;\n let target: string;\n try {\n target = Bun.resolveSync(specifier!, dirname(file));\n } catch {\n continue;\n }\n const line = lineOf(source, match.index);\n const where = posix(relative(check.services, target)).split(\"/\");\n const otherFolder =\n !where[0]!.startsWith(\"..\") && where.length > 1 ? where[0] : undefined;\n if (\n otherFolder &&\n otherFolder !== folder &&\n DEFINITION_FILE.exec(basename(target))?.[2] === \"table\"\n ) {\n add(\n file,\n `Service \"${service}\" imports ${basename(target)} from ${otherFolder}/; call that service's actions or listen to its events instead.`,\n line,\n );\n continue;\n }\n const module: Record<string, unknown> = await import(target).catch(\n () => ({}),\n );\n const names: string[] = [];\n if (defaultName?.trim()) names.push(\"default\");\n if (rest?.startsWith(\"*\")) names.push(...Object.keys(module));\n else if (rest)\n for (const part of rest.slice(1, -1).split(\",\")) {\n const name = part.trim().split(/\\s+as\\s+/)[0]!;\n if (name && !name.startsWith(\"type \")) names.push(name);\n }\n for (const name of names) {\n const owner = owners.get(module[name]);\n if (owner && owner !== service)\n add(\n file,\n `Service \"${service}\" imports table ${name === \"default\" ? basename(target) : `\"${name}\"`} owned by \"${owner}\"; call ${owner}'s actions or listen to its events instead.`,\n line,\n );\n }\n }\n }\n}\n\nfunction declaredEvents(check: AppCheck, app: BrickApp, add: Add) {\n for (const service of app.definition.services) {\n if (!service.options.events) continue; // no catalog: any name goes\n const names = new Set(Object.values(service.events).map((e) => e.name));\n const resources = service.listResources().map((r) => r.name);\n const declared = (name: string) =>\n names.has(name) || isCrudEvent(name, resources);\n for (const action of service.listActions())\n for (const name of action.config.emits ?? [])\n if (!declared(name))\n add(\n check.entry,\n `Action \"${service.name}.${action.name}\" emits \"${name}\", which is not in ${service.name}'s event catalog.`,\n );\n const folder = serviceFolders(service.name)\n .map((name) => resolve(check.services, name))\n .find(existsSync);\n for (const file of folder ? sourceFiles(check, folder) : []) {\n const source = readFileSync(file, \"utf8\");\n for (const match of source.matchAll(\n /emitEvent\\s*\\([^,]+,\\s*[\"'`]([^\"'`]+)[\"'`]/g,\n ))\n if (!declared(match[1]!))\n add(\n file,\n `\"${match[1]}\" is not in ${service.name}'s event catalog.`,\n lineOf(source, match.index),\n );\n }\n }\n}\n\nfunction testColocated(check: AppCheck, _app: BrickApp, add: Add) {\n for (const file of sourceFiles(check, check.services)) {\n const match = DEFINITION_FILE.exec(basename(file));\n if (match?.[2] !== \"action\" && match?.[2] !== \"command\") continue;\n const tested = readdirSync(dirname(file)).some(\n (sibling) =>\n TEST_FILE.test(sibling) && sibling.replace(TEST_FILE, \"\") === match[1],\n );\n if (!tested)\n add(file, `${basename(file)} has no ${match[1]}.test.ts beside it.`);\n }\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n drizzleSchema,\n getTableName,\n migrateDatabase,\n sql,\n type BrickApp,\n type DatabaseHandle,\n type Table,\n} from \"@brickkit/core\";\n\n/** A database the app's services use, with every table Brick knows on it. */\nexport interface AppDatabase {\n /** `defineDatabase({ name })`, else the first service that uses it. */\n name: string;\n database: DatabaseHandle<unknown>;\n tables: Table[];\n}\n\n/**\n * The app's databases and their tables: those passed to `defineDatabase`\n * (outbox tables included), resource tables, and the tables plugins own.\n * Throws when two handles share a name, since the name picks the migrations folder.\n */\nexport function appDatabases(app: BrickApp): AppDatabase[] {\n const found = new Map<\n DatabaseHandle<unknown>,\n { name: string; services: number; tables: Set<Table> }\n >();\n for (const service of app.definition.services) {\n const database = service.getDatabaseHandle?.();\n if (!database) continue;\n let entry = found.get(database);\n if (!entry) {\n entry = {\n name: database.name ?? service.name,\n services: 0,\n tables: new Set(),\n };\n found.set(database, entry);\n }\n entry.services++;\n // By table object: same-named tables in different Postgres schemas both count.\n for (const table of [\n ...Object.values(database.tables),\n ...service.tables.values(),\n ])\n entry.tables.add(table);\n }\n const databases = [...found].filter(([, entry]) => entry.tables.size > 0);\n const names = new Map<string, DatabaseHandle<unknown>>();\n for (const [database, entry] of databases) {\n if (!database.name && entry.services > 1)\n throw new Error(\n `Brick: services share a database without a name, so its migrations folder would follow service order; give it \\`defineDatabase({ name })\\`.`,\n );\n if (names.has(entry.name))\n throw new Error(\n `Brick: two databases are named \"${entry.name}\"; give each \\`defineDatabase({ name })\\` its own name, or share one handle between the services.`,\n );\n names.set(entry.name, database);\n }\n return databases.map(([database, entry]) => ({\n name: entry.name,\n database,\n tables: [...entry.tables],\n }));\n}\n\nexport interface DbCommandOptions {\n /** Migrations folder; each database writes to its own `<out>/<name>` subfolder. */\n out: string;\n /** `generate`: the migration's name. */\n name?: string;\n /** `push`: apply changes that drop data. */\n force?: boolean;\n}\n\n/** Run `brick db generate|migrate|push` against every database of the app. */\nexport async function runDbCommand(\n command: \"generate\" | \"migrate\" | \"push\",\n app: BrickApp,\n options: DbCommandOptions,\n): Promise<void> {\n const databases = appDatabases(app);\n if (!databases.length)\n throw new Error(\"Brick: the app has no database with tables.\");\n try {\n // All or nothing: a missing journal stops migrate before any database moves.\n if (command === \"migrate\")\n for (const entry of databases) {\n const folder = join(options.out, entry.name);\n if (!existsSync(join(folder, \"meta\", \"_journal.json\")))\n throw new Error(\n `Brick: no migrations in ${folder}; run \\`brick db generate\\` first.`,\n );\n }\n for (const entry of databases) {\n // One layout for any database count, so adding a database never moves another's migrations.\n const folder = join(options.out, entry.name);\n const label = `${entry.name} (${entry.database.engine})`;\n if (command === \"generate\") {\n const file = await generate(entry, folder, options.name);\n console.log(\n file ? `${label}: wrote ${file}` : `${label}: no schema changes`,\n );\n } else if (command === \"migrate\") {\n await migrateDatabase(entry.database, folder);\n console.log(`${label}: migrations in ${folder} applied`);\n } else {\n const applied = await push(entry, options.force ?? false);\n console.log(\n applied\n ? `${label}: applied ${applied} change${applied === 1 ? \"\" : \"s\"}`\n : `${label}: no schema changes`,\n );\n }\n }\n } finally {\n await Promise.all(databases.map((entry) => entry.database.close?.()));\n }\n}\n\nconst kit = () => import(\"drizzle-kit/api\");\n\ntype Snapshot = { id: string; version: string };\ntype Journal = {\n version: string;\n dialect: string;\n entries: {\n idx: number;\n version: string;\n when: number;\n tag: string;\n breakpoints: boolean;\n }[];\n};\n\n/**\n * Diff the tables against the folder's last snapshot with drizzle-kit and write\n * the SQL, snapshot and journal in drizzle-kit's layout, so drizzle-kit and\n * Drizzle's migrator read the folder too. Returns the SQL file, if any.\n */\nasync function generate(\n entry: AppDatabase,\n folder: string,\n name = \"migration\",\n): Promise<string | undefined> {\n const { generateDrizzleJson, generateMigration, ...sqlite } = await kit();\n const postgres = entry.database.engine === \"postgres\";\n const meta = join(folder, \"meta\");\n const journalFile = join(meta, \"_journal.json\");\n const journal: Journal = existsSync(journalFile)\n ? JSON.parse(readFileSync(journalFile, \"utf8\"))\n : {\n version: \"7\",\n dialect: postgres ? \"postgresql\" : \"sqlite\",\n entries: [],\n };\n const last = journal.entries.at(-1);\n const idx = last ? last.idx + 1 : 0;\n const prev: Snapshot | undefined = last\n ? JSON.parse(\n readFileSync(\n join(meta, `${last.tag.slice(0, 4)}_snapshot.json`),\n \"utf8\",\n ),\n )\n : undefined;\n const schema = drizzleSchema(entry.tables);\n let cur: Snapshot;\n let statements: string[];\n if (postgres) {\n const next = generateDrizzleJson(schema, prev?.id);\n statements = await generateMigration(\n (prev as never) ?? generateDrizzleJson({}),\n next,\n );\n cur = next;\n } else {\n const next = await sqlite.generateSQLiteDrizzleJson(schema, prev?.id);\n statements = await sqlite.generateSQLiteMigration(\n (prev as never) ?? (await sqlite.generateSQLiteDrizzleJson({})),\n next,\n );\n cur = next;\n }\n if (!statements.length) return undefined;\n const prefix = String(idx).padStart(4, \"0\");\n const tag = `${prefix}_${name}`;\n mkdirSync(meta, { recursive: true });\n const file = join(folder, `${tag}.sql`);\n writeFileSync(file, statements.join(\"\\n--> statement-breakpoint\\n\"));\n writeFileSync(\n join(meta, `${prefix}_snapshot.json`),\n JSON.stringify(cur, null, 2),\n );\n journal.entries.push({\n idx,\n version: cur.version,\n when: Date.now(),\n tag,\n breakpoints: true,\n });\n writeFileSync(journalFile, JSON.stringify(journal, null, 2));\n return file;\n}\n\n/**\n * Make the database match the tables with drizzle-kit's push, touching only\n * the tables Brick knows. Returns how many statements ran.\n */\nasync function push(entry: AppDatabase, force: boolean): Promise<number> {\n const { pushSchema, pushSQLiteSchema } = await kit();\n const db = entry.database.getDb() as any;\n const names = new Set(entry.tables.map((table) => getTableName(table)));\n const schema = drizzleSchema(entry.tables);\n const postgres = entry.database.engine === \"postgres\";\n const result = postgres\n ? await pushSchema(\n schema,\n // drizzle-kit reads `rows` (node-postgres); postgres-js returns the rows.\n {\n execute: async (query: never) => ({ rows: await db.execute(query) }),\n } as never,\n [\n ...new Set(\n entry.tables.map(\n // What drizzle's getTableConfig(table).schema reads.\n (table) =>\n ((table as never)[Symbol.for(\"drizzle:Schema\")] as\n | string\n | undefined) ?? \"public\",\n ),\n ),\n ],\n [...names],\n )\n : await pushSQLiteSchema(schema, onlyTables(db, names) as never);\n const statements = result.statementsToExecute;\n if (!statements.length) return 0;\n for (const warning of result.warnings) console.log(warning);\n if (result.hasDataLoss && !force)\n throw new Error(\n `Brick: pushing ${entry.name} would lose data (see above). Rerun with --force to apply it, or use \\`brick db generate\\` and edit the migration.`,\n );\n if (postgres)\n await db.transaction(async (tx: any) => {\n for (const statement of statements) await tx.execute(sql.raw(statement));\n });\n else await result.apply();\n return statements.length;\n}\n\n/**\n * drizzle-kit's SQLite push has no table filter: hide the tables Brick does not\n * know (FTS sidecars, other apps' tables) from what it reads, so it neither\n * drops them nor asks whether a new table renames one.\n */\nfunction onlyTables(db: any, names: Set<string>) {\n return {\n all: (query: unknown) =>\n db.all(query).filter((row: Record<string, unknown>) => {\n const table =\n row.tableName ?? row.tableFrom ?? row.tbl_name ?? row.view_name;\n return table === undefined || names.has(table as string);\n }),\n run: (query: unknown) => db.run(query),\n };\n}\n","#!/usr/bin/env bun\nimport { resolve } from \"node:path\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport { startDevServer, startProdServer, startWorker } from \"./runner\";\nimport { buildApplication } from \"./build\";\nimport { writeClientContract } from \"./client-contract-file\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { loadBrickApp } from \"./app-entry\";\nimport {\n ConfigError,\n DEFAULT_DASHBOARD_PORT,\n DEFAULT_HISTORY_DAYS,\n DEFAULT_PORT,\n resolvePort,\n resolveDevDashboard,\n resolveProject,\n type LoadedConfig,\n} from \"./config\";\nimport { writeServiceManifest } from \"./manifest\";\nimport { runLint } from \"./lint\";\nimport { runDbCommand } from \"./db\";\nimport cliPkg from \"../package.json\";\n\n// Single source of truth for the CLI version (inlined at build time).\nconst CLI_VERSION: string = cliPkg.version;\n\nconst PORT_HELP = `Port to listen on (CLI --port overrides PORT env, default ${DEFAULT_PORT})`;\n\nconst EXTENSION_HELP =\n \"Dashboard extension module (default export defineDashboard(...)), or the dashboard folder brick build wrote\";\n\nconst PORT_RESOLUTION_HELP = `\nPort Resolution (dev/start commands):\n - CLI --port flag takes precedence\n - Falls back to PORT environment variable\n - Then dev.port in brick.config.ts (brick dev only)\n - Defaults to ${DEFAULT_PORT} if none is set\n - Valid range: 1-65535\n\nExamples:\n brick dev app.ts # port 4000 (default)\n brick dev app.ts --port 5000 # port 5000 (explicit)\n PORT=3000 brick dev app.ts # port 3000 (from env)\n brick dev app.ts --port 6000 # port 6000 (CLI overrides PORT=3000)\n`;\n\nconst CONFIG_HELP =\n \"Path to brick.config.ts (default: the nearest one in this folder or its parents)\";\n\nfunction parsePortOption(value: string): number {\n try {\n return resolvePort(value);\n } catch (err) {\n throw new InvalidArgumentError((err as Error).message);\n }\n}\n\nfunction parseHistoryDays(value: string): number {\n const days = Number(value);\n if (!/^\\d+$/.test(value.trim()) || !Number.isSafeInteger(days)) {\n throw new InvalidArgumentError(\n `--history-days must be a whole number of days, or 0 for none (got '${value}')`,\n );\n }\n return days;\n}\n\nfunction parseFileOption(value: string, usage: string): string {\n if (value.startsWith(\"-\")) {\n throw new InvalidArgumentError(`${usage} (got flag-like value '${value}')`);\n }\n return value;\n}\n\n/** The project of the program-level `--config`, else the nearest config file. */\nfunction projectOf(command: Command): Promise<LoadedConfig> {\n return resolveProject(command.optsWithGlobals<{ config?: string }>().config);\n}\n\nfunction entryOf(entry: string | undefined, project: LoadedConfig) {\n return entry ?? (project.file ? project.entry : undefined);\n}\n\n/** Without an entry argument or config entry, commander's usual error. */\nfunction requireEntry(\n command: Command,\n entry: string | undefined,\n project: LoadedConfig,\n): string {\n const resolved = entryOf(entry, project);\n if (!resolved)\n command.error(\"error: missing required argument 'entry'\", {\n exitCode: 1,\n code: \"commander.missingArgument\",\n });\n return resolved!;\n}\n\n/** Load the app after refreshing the services manifest it imports. */\nasync function loadProjectApp(entry: string, project: LoadedConfig) {\n if (project.file) await writeServiceManifest(project);\n return loadBrickApp(entry);\n}\n\nfunction fromRoot(\n project: LoadedConfig,\n path: string | undefined,\n): string | undefined {\n return path && resolve(project.root, path);\n}\n\n/** The config's dashboard settings; a `--dashboard-extension` flag replaces its extension. */\nfunction configDashboard(project: LoadedConfig, extensionFlag?: string) {\n const dashboard = project.config.dashboard;\n if (!dashboard && !extensionFlag) return undefined;\n return {\n extension: extensionFlag ?? fromRoot(project, dashboard?.extension),\n theme: dashboard?.theme,\n };\n}\n\nasync function writeOpenApi(\n entry: string,\n output: string | undefined,\n project: LoadedConfig,\n) {\n const app = await loadProjectApp(entry, project);\n const json = JSON.stringify(app.openApiDocument(), null, 2);\n if (output) await Bun.write(output, json);\n return json;\n}\n\nexport function createProgram(): Command {\n const program = new Command();\n program\n .name(\"brick\")\n .description(\"🧱 Brick-TS CLI\")\n .version(CLI_VERSION)\n .showHelpAfterError()\n .configureHelp({ showGlobalOptions: true })\n .option(\"--config <path>\", CONFIG_HELP)\n .addHelpText(\n \"after\",\n `\nWith a brick.config.ts, the entry and most flags come from the config file.\n${PORT_RESOLUTION_HELP}`,\n );\n\n program\n .command(\"dev\")\n .description(\"Start development server with live reload\")\n .option(\n \"--client <file>\",\n \"Generate and watch a browser contract before startup\",\n )\n .option(\n \"--frontend <command>\",\n \"Start frontend after contract generation; requires --client\",\n )\n .option(\n \"--dashboard-port <number>\",\n `Port for the local dashboard (default ${DEFAULT_DASHBOARD_PORT})`,\n parsePortOption,\n )\n .option(\n \"--history-days <number>\",\n `Days of requests the dashboard keeps on disk, 0 for none (default ${DEFAULT_HISTORY_DAYS})`,\n parseHistoryDays,\n )\n .option(\"--no-dashboard\", \"Do not start the local dashboard\")\n .option(\"--dashboard-extension <file>\", EXTENSION_HELP)\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--port <number>\", PORT_HELP, parsePortOption)\n .addHelpText(\"after\", PORT_RESOLUTION_HELP)\n .action(\n async (\n entryArg: string | undefined,\n opts: {\n port?: number;\n client?: string;\n frontend?: string;\n dashboardPort?: number;\n historyDays?: number;\n dashboard?: boolean;\n dashboardExtension?: string;\n },\n command: Command,\n ) => {\n const project = await projectOf(command);\n const { config } = project;\n const entry = entryOf(entryArg, project);\n const port = resolvePort(opts.port, config.dev?.port);\n const dashboard = resolveDevDashboard(config.dev?.dashboard, opts);\n await startDevServer({\n entry,\n port,\n clientOutput: opts.client ?? fromRoot(project, config.client?.output),\n frontend: opts.frontend ?? config.dev?.frontend,\n // The dashboard reads the app's requests, so it needs an entry.\n dashboard:\n entry && dashboard\n ? {\n ...dashboard,\n ...configDashboard(project, opts.dashboardExtension),\n }\n : false,\n manifest: project.file ? project : undefined,\n });\n },\n );\n\n program\n .command(\"start\")\n .description(\"Start production server\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--port <number>\", PORT_HELP, parsePortOption)\n .option(\"--dashboard-extension <file>\", EXTENSION_HELP)\n .addHelpText(\"after\", PORT_RESOLUTION_HELP)\n .action(\n async (\n entry: string | undefined,\n opts: { port?: number; dashboardExtension?: string },\n command: Command,\n ) => {\n const project = await projectOf(command);\n await startProdServer({\n entry: entryOf(entry, project),\n port: resolvePort(opts.port),\n dashboard: configDashboard(project, opts.dashboardExtension),\n });\n },\n );\n\n program\n .command(\"worker\")\n .description(\"Deliver the app's events without serving HTTP\")\n .argument(\n \"[entry]\",\n \"Application entry file (must default-export a BrickApp)\",\n )\n .action(\n async (entry: string | undefined, _opts: object, command: Command) => {\n const project = await projectOf(command);\n await startWorker({ entry: requireEntry(command, entry, project) });\n },\n );\n\n program\n .command(\"build\")\n .description(\"Compile a default-exported BrickApp into a Bun server\")\n .argument(\n \"[entry]\",\n \"Application entry file (must default-export a BrickApp)\",\n )\n .option(\"--outdir <dir>\", \"Output directory\", (v: string) =>\n parseFileOption(v, \"Usage: brick build <app.ts> [--outdir <directory>]\"),\n )\n .option(\"--port <number>\", \"Default listening port\", parsePortOption)\n .option(\"--no-aot\", \"Disable ahead-of-time compilation\")\n .option(\n \"--dashboard-extension <file>\",\n \"Dashboard extension module to build into <outdir>/dashboard\",\n )\n .option(\n \"--prefix <path>\",\n \"DEPRECATED: configure prefix in brick() app instead\",\n )\n .option(\n \"--no-request-logging\",\n \"DEPRECATED: configure requestLogging in brick() app instead\",\n )\n .action(\n async (\n entryArg: string | undefined,\n opts: {\n outdir?: string;\n port?: number;\n aot?: boolean;\n prefix?: string;\n requestLogging?: boolean;\n dashboardExtension?: string;\n },\n command: Command,\n ) => {\n if (opts.prefix !== undefined || opts.requestLogging === false) {\n throw new ConfigError(\n \"Brick: configure prefix and requestLogging in your default-exported brick() app instead of build flags.\",\n );\n }\n const project = await projectOf(command);\n const build = project.config.build;\n // shortcut: brick() sets up request logging when the app is created, so\n // a build cannot switch it off; only the default (true) is accepted.\n if (build?.requestLogging === false)\n throw new ConfigError(\n \"Brick: configure requestLogging in your default-exported brick() app instead of build.requestLogging.\",\n );\n const entry = requireEntry(command, entryArg, project);\n if (project.file) await writeServiceManifest(project);\n const result = await buildApplication({\n entry,\n outdir: opts.outdir ?? project.outdir,\n port: opts.port,\n // --no-aot can only switch it off, so otherwise the config decides.\n aot: opts.aot === false ? false : build?.aot,\n dashboard: configDashboard(project, opts.dashboardExtension),\n });\n for (const warning of result.ir.diagnostics)\n console.warn(`[Brick compiler] ${warning}`);\n console.log(\n `Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`,\n );\n console.log(`IR: ${result.outdir}/brick-ir.json`);\n if (result.dashboard)\n console.log(`Dashboard extension: ${result.dashboard}`);\n console.log(`Run: bun ${result.entry}`);\n },\n );\n\n const gen = program\n .command(\"gen\")\n .description(\"Generate artifacts from a BrickApp entry\")\n .argument(\"[subcommand]\", \"Generator to run (openapi, client, manifest)\")\n .action(\n async (\n subcommand: string | undefined,\n _opts: object,\n command: Command,\n ) => {\n const project = await projectOf(command);\n if (subcommand !== undefined || !project.file) {\n console.error(\n `Unknown generator: ${subcommand ?? \"(none)\"}. Available: openapi, client, manifest`,\n );\n process.exit(1);\n }\n // With a config, bare `brick gen` writes everything the config names.\n const manifest = await writeServiceManifest(project);\n console.log(`Services manifest written to ${manifest}`);\n if (project.config.client?.output) {\n await writeClientContract(project.entry, project.contract);\n console.log(`Client contract written to ${project.contract}`);\n }\n const openapi = fromRoot(project, project.config.openapi?.output);\n if (openapi) {\n await writeOpenApi(project.entry, openapi, project);\n console.log(`✅ OpenAPI 3.1 specification written to ${openapi}`);\n }\n },\n );\n\n gen\n .command(\"openapi\")\n .description(\"Generate OpenAPI 3.1 JSON specification\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\n \"--output <file>\",\n \"Write specification to file instead of stdout\",\n (v: string) =>\n parseFileOption(\n v,\n \"Usage: brick gen openapi <entry> [--output <file>]\",\n ),\n )\n .action(\n async (\n entry: string | undefined,\n opts: { output?: string },\n command: Command,\n ) => {\n const project = await projectOf(command);\n const output =\n opts.output ?? fromRoot(project, project.config.openapi?.output);\n const json = await writeOpenApi(\n requireEntry(command, entry, project),\n output,\n project,\n );\n if (output)\n console.log(`✅ OpenAPI 3.1 specification written to ${output}`);\n else console.log(json);\n },\n );\n\n gen\n .command(\"client\")\n .description(\"Generate a typed browser client contract\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\n \"--output <file>\",\n \"Write contract to file (default _brick/contract.ts)\",\n (v: string) =>\n parseFileOption(v, \"Usage: brick gen client <entry> [--output <file>]\"),\n )\n .action(\n async (\n entry: string | undefined,\n opts: { output?: string },\n command: Command,\n ) => {\n const project = await projectOf(command);\n const target = requireEntry(command, entry, project);\n if (project.file) await writeServiceManifest(project);\n const output = await writeClientContract(\n target,\n opts.output ?? project.contract,\n );\n console.log(`Client contract written to ${output}`);\n },\n );\n\n gen\n .command(\"manifest\")\n .description(\n \"Write <generated>/services.gen.ts, which imports every definition file\",\n )\n .action(async (_opts: object, command: Command) => {\n const output = await writeServiceManifest(await projectOf(command));\n console.log(`Services manifest written to ${output}`);\n });\n\n const db = program\n .command(\"db\")\n .description(\n \"Manage the app's database schema with drizzle-kit: generate, migrate, push\",\n );\n const dbCommand = (\n name: \"generate\" | \"migrate\" | \"push\",\n description: string,\n ) =>\n db\n .command(name)\n .description(description)\n .argument(\"[entry]\", \"Application entry file\");\n // push writes no files, so only generate and migrate take --out.\n const OUT_HELP =\n \"Migrations folder (default drizzle, beside brick.config.ts); each database gets a subfolder named after it\";\n const dbAction =\n (name: \"generate\" | \"migrate\" | \"push\") =>\n async (\n entry: string | undefined,\n opts: { out?: string; name?: string; force?: boolean },\n command: Command,\n ) => {\n const project = await projectOf(command);\n const app = await loadProjectApp(\n requireEntry(command, entry, project),\n project,\n );\n await runDbCommand(name, app, {\n out: opts.out ?? fromRoot(project, \"drizzle\")!,\n name: opts.name,\n force: opts.force,\n });\n };\n dbCommand(\n \"generate\",\n \"Write a SQL migration for the schema changes since the last one\",\n )\n .option(\"--out <dir>\", OUT_HELP)\n .option(\"--name <name>\", \"Migration name (default migration)\")\n .action(dbAction(\"generate\"));\n dbCommand(\"migrate\", \"Apply the migrations that have not run yet\")\n .option(\"--out <dir>\", OUT_HELP)\n .action(dbAction(\"migrate\"));\n dbCommand(\n \"push\",\n \"Change the database to match the schema directly, without migration files (development)\",\n )\n .option(\"--force\", \"Apply changes that drop data\")\n .action(dbAction(\"push\"));\n\n program\n .command(\"lint\")\n .description(\"Check the project against the Brick lint rules\")\n .argument(\"[entry]\", \"Application entry file\")\n .action(\n async (entry: string | undefined, _opts: object, command: Command) => {\n const project = await projectOf(command);\n const code = await runLint({ entry, project });\n if (code !== 0) process.exit(code);\n },\n );\n\n program\n .command(\"info\")\n .alias(\"services\")\n .description(\"Export architecture JSON schema\")\n .argument(\"[entry]\", \"Application entry file\")\n .action(\n async (entry: string | undefined, _opts: object, command: Command) => {\n const project = await projectOf(command);\n const app = await loadProjectApp(\n requireEntry(command, entry, project),\n project,\n );\n const architecture = getGlobalRegistry().exportArchitecture(\n app.definition,\n );\n console.log(JSON.stringify(architecture, null, 2));\n },\n );\n\n return program;\n}\n\nasync function main() {\n const program = createProgram();\n await program.parseAsync(\n process.argv.length > 2 ? process.argv : [...process.argv, \"dev\"],\n );\n}\n\nmain().catch((err) => {\n // Commander already prints validation errors (missing arg, unknown option,\n // invalid port) and exits. Only print Fatal error for action failures.\n if (err?.exitCode !== undefined) {\n process.exit(err.exitCode);\n }\n if (err?.code?.startsWith?.(\"commander.\")) {\n process.exit(1);\n }\n // A config error already names the file and key; a stack adds nothing.\n if (err instanceof ConfigError) {\n console.error(err.message);\n process.exit(1);\n }\n console.error(\"Fatal error:\", err);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,IAAI;;AAEJ,SAAS,aAAa;CACpB,MAAM,OAAO,cAAc,YAAY,GAAG;CAC1C,IAAI,CAAC,KAAK,SAAS,KAAK,GAAG,OAAO,QAAQ,QAAQ,IAAI,GAAG,gBAAgB;CACzE,IAAI,YAAY,OAAO;CAEvB,MAAM,OAAO,QAAQ,MAAM,4CAA4C;CAEvE,MAAM,WAAW,GAAG,KAAK,GAAG,QAAQ;CACpC,MAAM,SAAS,UACb,QAAQ,UACR;EAAC;EAAS,QAAQ,QAAQ,IAAI,GAAG,WAAW;EAAG;EAAY;CAAM,CAAC,CAAC,OAAO;EACxE;EACA;EACA;EACA;CACF,CAAC,GACD,EAAE,UAAU,OAAO,CACrB;CACA,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,MACR,4CAA4C,OAAO,QACrD;CACF,WAAW,U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,cACJ,CAAC,CAAC,WACZ,QAAQ,KAAK,SAAS,IAAI,QAAQ,OAAO,CAAC,GAAG,QAAQ,MAAM,KAAK,CAClE;AACF;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CAGpB,IAAI,KAAK,aAAa,KAAA,GACpB,QAAQ,KAAK,IAAI,QAAQ;CAE3B,IAAI,KAAK,MAAM,aAAa,YAAY,GACtC,QAAQ,KAAK,CAAC;CAGhB,IAAI,eAAe,aAAa;EAC9B,QAAQ,MAAM,IAAI,OAAO;EACzB,QAAQ,KAAK,CAAC;CAChB;CACA,QAAQ,MAAM,gBAAgB,GAAG;CACjC,QAAQ,KAAK,CAAC;AAChB,CAAC"}
|
|
1
|
+
{"version":3,"file":"bin.js","names":["posix","cliPkg.version"],"sources":["../src/lint/run.ts","../src/lint.ts","../src/db.ts","../src/bin.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport { mkdtempSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { ConfigError } from \"../config\";\nimport type { BrickSettings } from \"./ast\";\nimport type { Severity } from \"./presets\";\n\nexport interface LintMessage {\n /** Path from the project root. */\n file: string;\n line: number;\n column: number;\n /** `brick/<rule>`. */\n rule: string;\n severity: \"error\" | \"warn\";\n message: string;\n}\n\nlet fromSource: string | undefined;\n/** The lint/oxlint entry oxlint loads under Node: the bundle beside this code, or, run from source, a fresh bundle of it. */\nfunction pluginPath() {\n const here = fileURLToPath(import.meta.url);\n if (!here.endsWith(\".ts\")) return resolve(dirname(here), \"lint/oxlint.js\");\n if (fromSource) return fromSource;\n // Inside the package, so Node resolves the bundle's imports from here.\n const file = resolve(here, \"../../../node_modules/.cache/brick-lint.js\");\n // Built beside it, then renamed: another process may be loading it.\n const building = `${file}.${process.pid}`;\n const result = spawnSync(\n process.execPath,\n [\"build\", resolve(dirname(here), \"oxlint.ts\"), \"--target\", \"node\"].concat([\n \"--packages\",\n \"external\",\n \"--outfile\",\n building,\n ]),\n { encoding: \"utf8\" },\n );\n if (result.status !== 0)\n throw new Error(\n `Brick: building the lint plugin failed:\\n${result.stderr}`,\n );\n renameSync(building, file);\n return (fromSource = file);\n}\n\nfunction oxlintBin(root: string) {\n for (const base of [\n join(root, \"package.json\"),\n fileURLToPath(import.meta.url),\n ]) {\n try {\n const pkg = createRequire(base).resolve(\"oxlint/package.json\");\n return join(dirname(pkg), \"bin/oxlint\");\n } catch {}\n }\n throw new ConfigError(\n \"Brick: brick lint needs oxlint; add it: bun add -d oxlint\",\n );\n}\n\n/**\n * Run the file rules over a project with oxlint, as `brick lint` does.\n * Only rules set to \"error\" or \"warn\" run; `ignore` globs are relative to `root`.\n */\nexport function runFileRules(options: {\n root: string;\n rules: Record<string, Severity>;\n settings: BrickSettings;\n ignore?: string[];\n fix?: boolean;\n}): LintMessage[] {\n const rules = Object.fromEntries(\n Object.entries(options.rules).filter(([, severity]) => severity !== \"off\"),\n );\n if (Object.keys(rules).length === 0) return [];\n const directory = mkdtempSync(join(tmpdir(), \"brick-lint-\"));\n try {\n const config = join(directory, \"oxlintrc.json\");\n writeFileSync(\n config,\n JSON.stringify({\n plugins: [],\n categories: { correctness: \"off\" },\n jsPlugins: [{ name: \"brick\", specifier: pluginPath() }],\n settings: { brick: options.settings },\n rules,\n }),\n );\n const result = spawnSync(\n oxlintBin(options.root),\n [\n \"-c\",\n config,\n \"--format\",\n \"json\",\n \"--disable-nested-config\",\n \"--no-error-on-unmatched-pattern\",\n ...(options.fix ? [\"--fix\"] : []),\n ...(options.ignore ?? []).flatMap((pattern) => [\n \"--ignore-pattern\",\n pattern,\n ]),\n \".\",\n ],\n { cwd: options.root, encoding: \"utf8\", maxBuffer: 64 * 1024 * 1024 },\n );\n if (result.error) throw result.error;\n let report: {\n diagnostics?: {\n message: string;\n code?: string;\n severity: string;\n filename: string;\n labels?: { span: { line: number; column: number } }[];\n }[];\n };\n try {\n report = JSON.parse(result.stdout);\n } catch {\n throw new Error(\n `Brick: oxlint failed (exit ${result.status}):\\n${result.stderr || result.stdout}`,\n );\n }\n return (report.diagnostics ?? []).map((diagnostic) => ({\n file: diagnostic.filename,\n line: diagnostic.labels?.[0]?.span.line ?? 1,\n column: diagnostic.labels?.[0]?.span.column ?? 1,\n // Parse errors come without a rule code.\n rule: diagnostic.code?.replace(/^brick\\((.*)\\)$/, \"brick/$1\") ?? \"syntax\",\n severity: diagnostic.severity === \"error\" ? \"error\" : \"warn\",\n message: diagnostic.message,\n }));\n } finally {\n rmSync(directory, { recursive: true, force: true });\n }\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { basename, dirname, relative, resolve, sep } from \"node:path\";\nimport { isCrudEvent } from \"@brickkit/core\";\nimport type { BrickApp, DatabaseHandle } from \"@brickkit/core\";\nimport { loadBrickApp } from \"./app-entry\";\nimport type { LoadedConfig } from \"./config\";\nimport { APP_RULES, type Severity } from \"./lint/presets\";\nimport { projectRules } from \"./lint/project\";\nimport { serviceFolders } from \"./lint/ast\";\nimport { runFileRules, type LintMessage } from \"./lint/run\";\nimport {\n DEFINITION_EXTENSIONS,\n DEFINITION_FILE,\n TEST_FILE,\n} from \"./definitions\";\nimport { writeServiceManifest } from \"./manifest\";\n\nconst posix = (path: string) => path.split(sep).join(\"/\");\nconst SOURCE = new Bun.Glob(\n `**/*.{${[...DEFINITION_EXTENSIONS, \"cts\"].join(\",\")}}`,\n);\n\ninterface AppCheck {\n root: string;\n entry: string;\n services: string;\n severity: (rule: string) => Severity;\n ignored: (rel: string) => boolean;\n}\n\n/**\n * `brick lint`: the file rules through oxlint, then the app\n * rules against the loaded app. Prints `file:line:col` lines and returns the\n * exit code: 1 when anything is an error.\n */\nexport async function runLint(options: {\n entry?: string;\n project: LoadedConfig;\n}): Promise<number> {\n const entry = options.entry ? resolve(options.entry) : options.project.entry;\n const project = { ...options.project, entry };\n const { root, services } = project;\n const { resolved, rules, settings, ignore } = projectRules(project);\n const messages = runFileRules({ root, rules, settings, ignore });\n const globs = ignore.map((pattern) => new Bun.Glob(pattern));\n if (existsSync(entry)) {\n if (project.file) await writeServiceManifest(project);\n messages.push(\n ...(await checkApp({\n root,\n entry,\n services,\n severity: (rule) => resolved[`brick/${rule}`] ?? \"off\",\n ignored: (rel) =>\n rel.split(\"/\").includes(\"node_modules\") ||\n globs.some((glob) => glob.match(rel)),\n })),\n );\n } else if (options.entry || project.file)\n throw new Error(`Brick: entry not found: ${entry}`);\n return report(messages);\n}\n\nfunction report(messages: LintMessage[]): number {\n messages.sort(\n (a, b) =>\n a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column,\n );\n for (const m of messages)\n console.log(\n `${m.file}:${m.line}:${m.column} ${m.severity === \"error\" ? \"error\" : \"warning\"} ${m.message} ${m.rule}`,\n );\n const errors = messages.filter((m) => m.severity === \"error\").length;\n const warnings = messages.length - errors;\n console.log(\n messages.length\n ? `\\n✖ ${messages.length} problem${messages.length === 1 ? \"\" : \"s\"} (${errors} error${errors === 1 ? \"\" : \"s\"}, ${warnings} warning${warnings === 1 ? \"\" : \"s\"})`\n : \"✔ No lint problems\",\n );\n return errors > 0 ? 1 : 0;\n}\n\n/** Project source files, from the root, without tests, ignored and generated files. */\nfunction sourceFiles(check: AppCheck, under = check.root): string[] {\n if (!existsSync(under)) return [];\n return [...SOURCE.scanSync({ cwd: under, onlyFiles: true })]\n .map((file) => resolve(under, file))\n .filter((file) => {\n const rel = posix(relative(check.root, file));\n return (\n !check.ignored(rel) && !TEST_FILE.test(rel) && !rel.startsWith(\"dist/\")\n );\n });\n}\n\nfunction lineOf(source: string, index: number) {\n return source.slice(0, index).split(\"\\n\").length;\n}\n\ntype Add = (file: string, message: string, line?: number) => void;\ntype AppRule = (check: AppCheck, app: BrickApp, add: Add) => unknown;\n\n/** Each app rule's check; a rule in APP_RULES without one fails to compile. */\nconst APP_CHECKS: Record<(typeof APP_RULES)[number], AppRule> = {\n \"single-app-entry\": singleAppEntry,\n \"no-cross-service-tables\": noCrossServiceTables,\n // Startup refuses duplicate names, so checkApp reports it when the app loads.\n \"unique-names\": () => {},\n \"declared-events\": declaredEvents,\n \"test-colocated\": testColocated,\n};\n\nasync function checkApp(check: AppCheck): Promise<LintMessage[]> {\n const messages: LintMessage[] = [];\n const message = (\n rule: string,\n severity: Exclude<Severity, \"off\">,\n file: string,\n text: string,\n line = 1,\n ): LintMessage => ({\n file: posix(relative(check.root, file)),\n line,\n column: 1,\n rule: `brick/${rule}`,\n severity,\n message: text,\n });\n let app: BrickApp;\n try {\n app = await loadBrickApp(check.entry);\n } catch (error) {\n // An app that cannot start fails lint, even with unique-names off.\n if ((error as Error).name === \"DuplicateNameError\") {\n return [\n message(\"unique-names\", \"error\", check.entry, (error as Error).message),\n ];\n }\n throw error;\n }\n for (const [rule, run] of Object.entries(APP_CHECKS)) {\n const severity = check.severity(rule);\n if (severity === \"off\") continue;\n await run(check, app, (file, text, line) =>\n messages.push(message(rule, severity, file, text, line)),\n );\n }\n return messages;\n}\n\nfunction singleAppEntry(check: AppCheck, _app: BrickApp, add: Add) {\n let calls = 0;\n for (const file of sourceFiles(check)) {\n const source = readFileSync(file, \"utf8\");\n // shortcut: a text search for brick( in files that import it from core.\n if (\n !/import\\s*\\{[^}]*\\bbrick\\b[^}]*\\}\\s*from\\s*[\"']@brickkit\\/core[\"']/.test(\n source,\n )\n )\n continue;\n for (const match of source.matchAll(/(?<![.\\w])brick\\s*\\(/g)) {\n if (file === check.entry && ++calls === 1) continue;\n add(\n file,\n file === check.entry\n ? \"The entry calls brick() more than once; keep one app.\"\n : `brick() is called outside the entry (${posix(relative(check.root, check.entry))}); keep one app.`,\n lineOf(source, match.index),\n );\n }\n }\n}\n\n/** Which service owns each table: its resources' and registered tables, or a database it alone uses. */\nfunction tableOwners(app: BrickApp) {\n const owners = new Map<unknown, string>();\n const users = new Map<DatabaseHandle<unknown>, string[]>();\n for (const service of app.definition.services) {\n for (const table of service.tables.values())\n owners.set(table, service.name);\n const { database } = service.options;\n if (database)\n users.set(database, [...(users.get(database) ?? []), service.name]);\n }\n for (const [database, names] of users)\n if (names.length === 1)\n for (const table of Object.values(database.tables))\n if (!owners.has(table)) owners.set(table, names[0]!);\n return owners;\n}\n\nfunction serviceOfFolder(app: BrickApp, folder: string) {\n return app.definition.services.find((service) =>\n serviceFolders(service.name).includes(folder),\n )?.name;\n}\n\n// shortcut: a text search for static imports and re-exports; misses `import()`.\nconst IMPORT =\n /(?:import|export)\\s+(type\\s+)?([\\w$]+\\s*,?\\s*)?(\\*(?:\\s+as\\s+[\\w$]+)?|\\{[^}]*\\})?\\s*from\\s*[\"']([^\"']+)[\"']/g;\n\nasync function noCrossServiceTables(check: AppCheck, app: BrickApp, add: Add) {\n const owners = tableOwners(app);\n for (const file of sourceFiles(check, check.services)) {\n const folder = posix(relative(check.services, file)).split(\"/\")[0]!;\n const service = serviceOfFolder(app, folder);\n if (!service) continue;\n const source = readFileSync(file, \"utf8\");\n for (const match of source.matchAll(IMPORT)) {\n const [, typeOnly, defaultName, rest, specifier] = match;\n if (typeOnly || !specifier!.startsWith(\".\")) continue;\n let target: string;\n try {\n target = Bun.resolveSync(specifier!, dirname(file));\n } catch {\n continue;\n }\n const line = lineOf(source, match.index);\n const where = posix(relative(check.services, target)).split(\"/\");\n const otherFolder =\n !where[0]!.startsWith(\"..\") && where.length > 1 ? where[0] : undefined;\n if (\n otherFolder &&\n otherFolder !== folder &&\n DEFINITION_FILE.exec(basename(target))?.[2] === \"table\"\n ) {\n add(\n file,\n `Service \"${service}\" imports ${basename(target)} from ${otherFolder}/; call that service's actions or listen to its events instead.`,\n line,\n );\n continue;\n }\n const module: Record<string, unknown> = await import(target).catch(\n () => ({}),\n );\n const names: string[] = [];\n if (defaultName?.trim()) names.push(\"default\");\n if (rest?.startsWith(\"*\")) names.push(...Object.keys(module));\n else if (rest)\n for (const part of rest.slice(1, -1).split(\",\")) {\n const name = part.trim().split(/\\s+as\\s+/)[0]!;\n if (name && !name.startsWith(\"type \")) names.push(name);\n }\n for (const name of names) {\n const owner = owners.get(module[name]);\n if (owner && owner !== service)\n add(\n file,\n `Service \"${service}\" imports table ${name === \"default\" ? basename(target) : `\"${name}\"`} owned by \"${owner}\"; call ${owner}'s actions or listen to its events instead.`,\n line,\n );\n }\n }\n }\n}\n\nfunction declaredEvents(check: AppCheck, app: BrickApp, add: Add) {\n for (const service of app.definition.services) {\n if (!service.options.events) continue; // no catalog: any name goes\n const names = new Set(Object.values(service.events).map((e) => e.name));\n const resources = service.listResources().map((r) => r.name);\n const declared = (name: string) =>\n names.has(name) || isCrudEvent(name, resources);\n for (const action of service.listActions())\n for (const name of action.config.emits ?? [])\n if (!declared(name))\n add(\n check.entry,\n `Action \"${service.name}.${action.name}\" emits \"${name}\", which is not in ${service.name}'s event catalog.`,\n );\n const folder = serviceFolders(service.name)\n .map((name) => resolve(check.services, name))\n .find(existsSync);\n for (const file of folder ? sourceFiles(check, folder) : []) {\n const source = readFileSync(file, \"utf8\");\n for (const match of source.matchAll(\n /emitEvent\\s*\\([^,]+,\\s*[\"'`]([^\"'`]+)[\"'`]/g,\n ))\n if (!declared(match[1]!))\n add(\n file,\n `\"${match[1]}\" is not in ${service.name}'s event catalog.`,\n lineOf(source, match.index),\n );\n }\n }\n}\n\nfunction testColocated(check: AppCheck, _app: BrickApp, add: Add) {\n for (const file of sourceFiles(check, check.services)) {\n const match = DEFINITION_FILE.exec(basename(file));\n if (match?.[2] !== \"action\" && match?.[2] !== \"command\") continue;\n const tested = readdirSync(dirname(file)).some(\n (sibling) =>\n TEST_FILE.test(sibling) && sibling.replace(TEST_FILE, \"\") === match[1],\n );\n if (!tested)\n add(file, `${basename(file)} has no ${match[1]}.test.ts beside it.`);\n }\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n drizzleSchema,\n getTableName,\n migrateDatabase,\n sql,\n type BrickApp,\n type DatabaseHandle,\n type Table,\n} from \"@brickkit/core\";\n\n/** A database the app's services use, with every table Brick knows on it. */\nexport interface AppDatabase {\n /** `defineDatabase({ name })`, else the first service that uses it. */\n name: string;\n database: DatabaseHandle<unknown>;\n tables: Table[];\n}\n\n/**\n * The app's databases and their tables: those passed to `defineDatabase`\n * (outbox tables included), resource tables, and the tables plugins own.\n * Throws when two handles share a name, since the name picks the migrations folder.\n */\nexport function appDatabases(app: BrickApp): AppDatabase[] {\n const found = new Map<\n DatabaseHandle<unknown>,\n { name: string; services: number; tables: Set<Table> }\n >();\n for (const service of app.definition.services) {\n const database = service.getDatabaseHandle?.();\n if (!database) continue;\n let entry = found.get(database);\n if (!entry) {\n entry = {\n name: database.name ?? service.name,\n services: 0,\n tables: new Set(),\n };\n found.set(database, entry);\n }\n entry.services++;\n // By table object: same-named tables in different Postgres schemas both count.\n for (const table of [\n ...Object.values(database.tables),\n ...service.tables.values(),\n ])\n entry.tables.add(table);\n }\n const databases = [...found].filter(([, entry]) => entry.tables.size > 0);\n const names = new Map<string, DatabaseHandle<unknown>>();\n for (const [database, entry] of databases) {\n if (!database.name && entry.services > 1)\n throw new Error(\n `Brick: services share a database without a name, so its migrations folder would follow service order; give it \\`defineDatabase({ name })\\`.`,\n );\n if (names.has(entry.name))\n throw new Error(\n `Brick: two databases are named \"${entry.name}\"; give each \\`defineDatabase({ name })\\` its own name, or share one handle between the services.`,\n );\n names.set(entry.name, database);\n }\n return databases.map(([database, entry]) => ({\n name: entry.name,\n database,\n tables: [...entry.tables],\n }));\n}\n\nexport interface DbCommandOptions {\n /** Migrations folder; each database writes to its own `<out>/<name>` subfolder. */\n out: string;\n /** `generate`: the migration's name. */\n name?: string;\n /** `push`: apply changes that drop data. */\n force?: boolean;\n}\n\n/** Run `brick db generate|migrate|push` against every database of the app. */\nexport async function runDbCommand(\n command: \"generate\" | \"migrate\" | \"push\",\n app: BrickApp,\n options: DbCommandOptions,\n): Promise<void> {\n const databases = appDatabases(app);\n if (!databases.length)\n throw new Error(\"Brick: the app has no database with tables.\");\n try {\n // All or nothing: a missing journal stops migrate before any database moves.\n if (command === \"migrate\")\n for (const entry of databases) {\n const folder = join(options.out, entry.name);\n if (!existsSync(join(folder, \"meta\", \"_journal.json\")))\n throw new Error(\n `Brick: no migrations in ${folder}; run \\`brick db generate\\` first.`,\n );\n }\n for (const entry of databases) {\n // One layout for any database count, so adding a database never moves another's migrations.\n const folder = join(options.out, entry.name);\n const label = `${entry.name} (${entry.database.engine})`;\n if (command === \"generate\") {\n const file = await generate(entry, folder, options.name);\n console.log(\n file ? `${label}: wrote ${file}` : `${label}: no schema changes`,\n );\n } else if (command === \"migrate\") {\n await migrateDatabase(entry.database, folder);\n console.log(`${label}: migrations in ${folder} applied`);\n } else {\n const applied = await push(entry, options.force ?? false);\n console.log(\n applied\n ? `${label}: applied ${applied} change${applied === 1 ? \"\" : \"s\"}`\n : `${label}: no schema changes`,\n );\n }\n }\n } finally {\n await Promise.all(databases.map((entry) => entry.database.close?.()));\n }\n}\n\nconst kit = () => import(\"drizzle-kit/api\");\n\ntype Snapshot = { id: string; version: string };\ntype Journal = {\n version: string;\n dialect: string;\n entries: {\n idx: number;\n version: string;\n when: number;\n tag: string;\n breakpoints: boolean;\n }[];\n};\n\n/**\n * Diff the tables against the folder's last snapshot with drizzle-kit and write\n * the SQL, snapshot and journal in drizzle-kit's layout, so drizzle-kit and\n * Drizzle's migrator read the folder too. Returns the SQL file, if any.\n */\nasync function generate(\n entry: AppDatabase,\n folder: string,\n name = \"migration\",\n): Promise<string | undefined> {\n const { generateDrizzleJson, generateMigration, ...sqlite } = await kit();\n const postgres = entry.database.engine === \"postgres\";\n const meta = join(folder, \"meta\");\n const journalFile = join(meta, \"_journal.json\");\n const journal: Journal = existsSync(journalFile)\n ? JSON.parse(readFileSync(journalFile, \"utf8\"))\n : {\n version: \"7\",\n dialect: postgres ? \"postgresql\" : \"sqlite\",\n entries: [],\n };\n const last = journal.entries.at(-1);\n const idx = last ? last.idx + 1 : 0;\n const prev: Snapshot | undefined = last\n ? JSON.parse(\n readFileSync(\n join(meta, `${last.tag.slice(0, 4)}_snapshot.json`),\n \"utf8\",\n ),\n )\n : undefined;\n const schema = drizzleSchema(entry.tables);\n let cur: Snapshot;\n let statements: string[];\n if (postgres) {\n const next = generateDrizzleJson(schema, prev?.id);\n statements = await generateMigration(\n (prev as never) ?? generateDrizzleJson({}),\n next,\n );\n cur = next;\n } else {\n const next = await sqlite.generateSQLiteDrizzleJson(schema, prev?.id);\n statements = await sqlite.generateSQLiteMigration(\n (prev as never) ?? (await sqlite.generateSQLiteDrizzleJson({})),\n next,\n );\n cur = next;\n }\n if (!statements.length) return undefined;\n const prefix = String(idx).padStart(4, \"0\");\n const tag = `${prefix}_${name}`;\n mkdirSync(meta, { recursive: true });\n const file = join(folder, `${tag}.sql`);\n writeFileSync(file, statements.join(\"\\n--> statement-breakpoint\\n\"));\n writeFileSync(\n join(meta, `${prefix}_snapshot.json`),\n JSON.stringify(cur, null, 2),\n );\n journal.entries.push({\n idx,\n version: cur.version,\n when: Date.now(),\n tag,\n breakpoints: true,\n });\n writeFileSync(journalFile, JSON.stringify(journal, null, 2));\n return file;\n}\n\n/**\n * Make the database match the tables with drizzle-kit's push, touching only\n * the tables Brick knows. Returns how many statements ran.\n */\nasync function push(entry: AppDatabase, force: boolean): Promise<number> {\n const { pushSchema, pushSQLiteSchema } = await kit();\n const db = entry.database.getDb() as any;\n const names = new Set(entry.tables.map((table) => getTableName(table)));\n const schema = drizzleSchema(entry.tables);\n const postgres = entry.database.engine === \"postgres\";\n const result = postgres\n ? await pushSchema(\n schema,\n // drizzle-kit reads `rows` (node-postgres); postgres-js returns the rows.\n {\n execute: async (query: never) => ({ rows: await db.execute(query) }),\n } as never,\n [\n ...new Set(\n entry.tables.map(\n // What drizzle's getTableConfig(table).schema reads.\n (table) =>\n ((table as never)[Symbol.for(\"drizzle:Schema\")] as\n | string\n | undefined) ?? \"public\",\n ),\n ),\n ],\n [...names],\n )\n : await pushSQLiteSchema(schema, onlyTables(db, names) as never);\n const statements = result.statementsToExecute;\n if (!statements.length) return 0;\n for (const warning of result.warnings) console.log(warning);\n if (result.hasDataLoss && !force)\n throw new Error(\n `Brick: pushing ${entry.name} would lose data (see above). Rerun with --force to apply it, or use \\`brick db generate\\` and edit the migration.`,\n );\n if (postgres)\n await db.transaction(async (tx: any) => {\n for (const statement of statements) await tx.execute(sql.raw(statement));\n });\n else await result.apply();\n return statements.length;\n}\n\n/**\n * drizzle-kit's SQLite push has no table filter: hide the tables Brick does not\n * know (FTS sidecars, other apps' tables) from what it reads, so it neither\n * drops them nor asks whether a new table renames one.\n */\nfunction onlyTables(db: any, names: Set<string>) {\n return {\n all: (query: unknown) =>\n db.all(query).filter((row: Record<string, unknown>) => {\n const table =\n row.tableName ?? row.tableFrom ?? row.tbl_name ?? row.view_name;\n return table === undefined || names.has(table as string);\n }),\n run: (query: unknown) => db.run(query),\n };\n}\n","#!/usr/bin/env bun\nimport { resolve } from \"node:path\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport { startDevServer, startProdServer, startWorker } from \"./runner\";\nimport { buildApplication } from \"./build\";\nimport { writeClientContract } from \"./client-contract-file\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { loadBrickApp } from \"./app-entry\";\nimport {\n ConfigError,\n DEFAULT_DASHBOARD_PORT,\n DEFAULT_HISTORY_DAYS,\n DEFAULT_PORT,\n resolvePort,\n resolveDevDashboard,\n resolveProject,\n type LoadedConfig,\n} from \"./config\";\nimport { writeServiceManifest } from \"./manifest\";\nimport { runLint } from \"./lint\";\nimport { runDbCommand } from \"./db\";\nimport cliPkg from \"../package.json\";\n\n// Single source of truth for the CLI version (inlined at build time).\nconst CLI_VERSION: string = cliPkg.version;\n\nconst PORT_HELP = `Port to listen on (CLI --port overrides PORT env, default ${DEFAULT_PORT})`;\n\nconst EXTENSION_HELP =\n \"Dashboard extension module (default export defineDashboard(...)), or the dashboard folder brick build wrote\";\n\nconst PORT_RESOLUTION_HELP = `\nPort Resolution (dev/start commands):\n - CLI --port flag takes precedence\n - Falls back to PORT environment variable\n - Then dev.port in brick.config.ts (brick dev only)\n - Defaults to ${DEFAULT_PORT} if none is set\n - Valid range: 1-65535\n\nExamples:\n brick dev app.ts # port 4000 (default)\n brick dev app.ts --port 5000 # port 5000 (explicit)\n PORT=3000 brick dev app.ts # port 3000 (from env)\n brick dev app.ts --port 6000 # port 6000 (CLI overrides PORT=3000)\n`;\n\nconst CONFIG_HELP =\n \"Path to brick.config.ts (default: the nearest one in this folder or its parents)\";\n\nfunction parsePortOption(value: string): number {\n try {\n return resolvePort(value);\n } catch (err) {\n throw new InvalidArgumentError((err as Error).message);\n }\n}\n\nfunction parseHistoryDays(value: string): number {\n const days = Number(value);\n if (!/^\\d+$/.test(value.trim()) || !Number.isSafeInteger(days)) {\n throw new InvalidArgumentError(\n `--history-days must be a whole number of days, or 0 for none (got '${value}')`,\n );\n }\n return days;\n}\n\nfunction parseFileOption(value: string, usage: string): string {\n if (value.startsWith(\"-\")) {\n throw new InvalidArgumentError(`${usage} (got flag-like value '${value}')`);\n }\n return value;\n}\n\n/** The project of the program-level `--config`, else the nearest config file. */\nfunction projectOf(command: Command): Promise<LoadedConfig> {\n return resolveProject(command.optsWithGlobals<{ config?: string }>().config);\n}\n\nfunction entryOf(entry: string | undefined, project: LoadedConfig) {\n return entry ?? (project.file ? project.entry : undefined);\n}\n\n/** Without an entry argument or config entry, commander's usual error. */\nfunction requireEntry(\n command: Command,\n entry: string | undefined,\n project: LoadedConfig,\n): string {\n const resolved = entryOf(entry, project);\n if (!resolved)\n command.error(\"error: missing required argument 'entry'\", {\n exitCode: 1,\n code: \"commander.missingArgument\",\n });\n return resolved!;\n}\n\n/** Load the app after refreshing the services manifest it imports. */\nasync function loadProjectApp(entry: string, project: LoadedConfig) {\n if (project.file) await writeServiceManifest(project);\n return loadBrickApp(entry);\n}\n\nfunction fromRoot(\n project: LoadedConfig,\n path: string | undefined,\n): string | undefined {\n return path && resolve(project.root, path);\n}\n\n/** The config's dashboard settings; a `--dashboard-extension` flag replaces its extension. */\nfunction configDashboard(project: LoadedConfig, extensionFlag?: string) {\n const dashboard = project.config.dashboard;\n if (!dashboard && !extensionFlag) return undefined;\n return {\n extension: extensionFlag ?? fromRoot(project, dashboard?.extension),\n theme: dashboard?.theme,\n };\n}\n\nasync function writeOpenApi(\n entry: string,\n output: string | undefined,\n project: LoadedConfig,\n) {\n const app = await loadProjectApp(entry, project);\n const json = JSON.stringify(app.openApiDocument(), null, 2);\n if (output) await Bun.write(output, json);\n return json;\n}\n\nexport function createProgram(): Command {\n const program = new Command();\n program\n .name(\"brick\")\n .description(\"🧱 Brick-TS CLI\")\n .version(CLI_VERSION)\n .showHelpAfterError()\n .configureHelp({ showGlobalOptions: true })\n .option(\"--config <path>\", CONFIG_HELP)\n .addHelpText(\n \"after\",\n `\nWith a brick.config.ts, the entry and most flags come from the config file.\n${PORT_RESOLUTION_HELP}`,\n );\n\n program\n .command(\"dev\")\n .description(\"Start development server with live reload\")\n .option(\n \"--client <file>\",\n \"Generate and watch a browser contract before startup\",\n )\n .option(\n \"--frontend <command>\",\n \"Start frontend after contract generation; requires --client\",\n )\n .option(\n \"--dashboard-port <number>\",\n `Port for the local dashboard (default ${DEFAULT_DASHBOARD_PORT})`,\n parsePortOption,\n )\n .option(\n \"--history-days <number>\",\n `Days of requests the dashboard keeps on disk, 0 for none (default ${DEFAULT_HISTORY_DAYS})`,\n parseHistoryDays,\n )\n .option(\"--no-dashboard\", \"Do not start the local dashboard\")\n .option(\"--dashboard-extension <file>\", EXTENSION_HELP)\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--port <number>\", PORT_HELP, parsePortOption)\n .addHelpText(\"after\", PORT_RESOLUTION_HELP)\n .action(\n async (\n entryArg: string | undefined,\n opts: {\n port?: number;\n client?: string;\n frontend?: string;\n dashboardPort?: number;\n historyDays?: number;\n dashboard?: boolean;\n dashboardExtension?: string;\n },\n command: Command,\n ) => {\n const project = await projectOf(command);\n const { config } = project;\n const entry = entryOf(entryArg, project);\n const port = resolvePort(opts.port, config.dev?.port);\n const dashboard = resolveDevDashboard(config.dev?.dashboard, opts);\n await startDevServer({\n entry,\n port,\n clientOutput: opts.client ?? fromRoot(project, config.client?.output),\n frontend: opts.frontend ?? config.dev?.frontend,\n // The dashboard reads the app's requests, so it needs an entry.\n dashboard:\n entry && dashboard\n ? {\n ...dashboard,\n ...configDashboard(project, opts.dashboardExtension),\n }\n : false,\n manifest: project.file ? project : undefined,\n });\n },\n );\n\n program\n .command(\"start\")\n .description(\"Start production server\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--port <number>\", PORT_HELP, parsePortOption)\n .option(\"--dashboard-extension <file>\", EXTENSION_HELP)\n .addHelpText(\"after\", PORT_RESOLUTION_HELP)\n .action(\n async (\n entry: string | undefined,\n opts: { port?: number; dashboardExtension?: string },\n command: Command,\n ) => {\n const project = await projectOf(command);\n await startProdServer({\n entry: entryOf(entry, project),\n port: resolvePort(opts.port),\n dashboard: configDashboard(project, opts.dashboardExtension),\n });\n },\n );\n\n program\n .command(\"worker\")\n .description(\"Deliver the app's events without serving HTTP\")\n .argument(\n \"[entry]\",\n \"Application entry file (must default-export a BrickApp)\",\n )\n .action(\n async (entry: string | undefined, _opts: object, command: Command) => {\n const project = await projectOf(command);\n await startWorker({ entry: requireEntry(command, entry, project) });\n },\n );\n\n program\n .command(\"build\")\n .description(\"Compile a default-exported BrickApp into a Bun server\")\n .argument(\n \"[entry]\",\n \"Application entry file (must default-export a BrickApp)\",\n )\n .option(\"--outdir <dir>\", \"Output directory\", (v: string) =>\n parseFileOption(v, \"Usage: brick build <app.ts> [--outdir <directory>]\"),\n )\n .option(\"--port <number>\", \"Default listening port\", parsePortOption)\n .option(\"--no-aot\", \"Disable ahead-of-time compilation\")\n .option(\n \"--dashboard-extension <file>\",\n \"Dashboard extension module to build into <outdir>/dashboard\",\n )\n .option(\n \"--prefix <path>\",\n \"DEPRECATED: configure prefix in brick() app instead\",\n )\n .option(\n \"--no-request-logging\",\n \"DEPRECATED: configure requestLogging in brick() app instead\",\n )\n .action(\n async (\n entryArg: string | undefined,\n opts: {\n outdir?: string;\n port?: number;\n aot?: boolean;\n prefix?: string;\n requestLogging?: boolean;\n dashboardExtension?: string;\n },\n command: Command,\n ) => {\n if (opts.prefix !== undefined || opts.requestLogging === false) {\n throw new ConfigError(\n \"Brick: configure prefix and requestLogging in your default-exported brick() app instead of build flags.\",\n );\n }\n const project = await projectOf(command);\n const build = project.config.build;\n // shortcut: brick() sets up request logging when the app is created, so\n // a build cannot switch it off; only the default (true) is accepted.\n if (build?.requestLogging === false)\n throw new ConfigError(\n \"Brick: configure requestLogging in your default-exported brick() app instead of build.requestLogging.\",\n );\n const entry = requireEntry(command, entryArg, project);\n if (project.file) await writeServiceManifest(project);\n const result = await buildApplication({\n entry,\n outdir: opts.outdir ?? project.outdir,\n port: opts.port,\n // --no-aot can only switch it off, so otherwise the config decides.\n aot: opts.aot === false ? false : build?.aot,\n dashboard: configDashboard(project, opts.dashboardExtension),\n });\n for (const warning of result.ir.diagnostics)\n console.warn(`[Brick compiler] ${warning}`);\n console.log(\n `Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`,\n );\n console.log(`IR: ${result.outdir}/brick-ir.json`);\n if (result.dashboard)\n console.log(`Dashboard extension: ${result.dashboard}`);\n if (result.workflows) console.log(`Workflows: ${result.workflows}`);\n console.log(`Run: bun ${result.entry}`);\n // The imported entry may hold timers or sockets open (#109).\n process.exit(0);\n },\n );\n\n const gen = program\n .command(\"gen\")\n .description(\"Generate artifacts from a BrickApp entry\")\n .argument(\"[subcommand]\", \"Generator to run (openapi, client, manifest)\")\n .action(\n async (\n subcommand: string | undefined,\n _opts: object,\n command: Command,\n ) => {\n const project = await projectOf(command);\n if (subcommand !== undefined || !project.file) {\n console.error(\n `Unknown generator: ${subcommand ?? \"(none)\"}. Available: openapi, client, manifest`,\n );\n process.exit(1);\n }\n // With a config, bare `brick gen` writes everything the config names.\n const manifest = await writeServiceManifest(project);\n console.log(`Services manifest written to ${manifest}`);\n if (project.config.client?.output) {\n await writeClientContract(project.entry, project.contract);\n console.log(`Client contract written to ${project.contract}`);\n }\n const openapi = fromRoot(project, project.config.openapi?.output);\n if (openapi) {\n await writeOpenApi(project.entry, openapi, project);\n console.log(`✅ OpenAPI 3.1 specification written to ${openapi}`);\n }\n },\n );\n\n gen\n .command(\"openapi\")\n .description(\"Generate OpenAPI 3.1 JSON specification\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\n \"--output <file>\",\n \"Write specification to file instead of stdout\",\n (v: string) =>\n parseFileOption(\n v,\n \"Usage: brick gen openapi <entry> [--output <file>]\",\n ),\n )\n .action(\n async (\n entry: string | undefined,\n opts: { output?: string },\n command: Command,\n ) => {\n const project = await projectOf(command);\n const output =\n opts.output ?? fromRoot(project, project.config.openapi?.output);\n const json = await writeOpenApi(\n requireEntry(command, entry, project),\n output,\n project,\n );\n if (output)\n console.log(`✅ OpenAPI 3.1 specification written to ${output}`);\n else console.log(json);\n },\n );\n\n gen\n .command(\"client\")\n .description(\"Generate a typed browser client contract\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\n \"--output <file>\",\n \"Write contract to file (default _brick/contract.ts)\",\n (v: string) =>\n parseFileOption(v, \"Usage: brick gen client <entry> [--output <file>]\"),\n )\n .action(\n async (\n entry: string | undefined,\n opts: { output?: string },\n command: Command,\n ) => {\n const project = await projectOf(command);\n const target = requireEntry(command, entry, project);\n if (project.file) await writeServiceManifest(project);\n const output = await writeClientContract(\n target,\n opts.output ?? project.contract,\n );\n console.log(`Client contract written to ${output}`);\n },\n );\n\n gen\n .command(\"manifest\")\n .description(\n \"Write <generated>/services.gen.ts, which imports every definition file\",\n )\n .action(async (_opts: object, command: Command) => {\n const output = await writeServiceManifest(await projectOf(command));\n console.log(`Services manifest written to ${output}`);\n });\n\n const db = program\n .command(\"db\")\n .description(\n \"Manage the app's database schema with drizzle-kit: generate, migrate, push\",\n );\n const dbCommand = (\n name: \"generate\" | \"migrate\" | \"push\",\n description: string,\n ) =>\n db\n .command(name)\n .description(description)\n .argument(\"[entry]\", \"Application entry file\");\n // push writes no files, so only generate and migrate take --out.\n const OUT_HELP =\n \"Migrations folder (default drizzle, beside brick.config.ts); each database gets a subfolder named after it\";\n const dbAction =\n (name: \"generate\" | \"migrate\" | \"push\") =>\n async (\n entry: string | undefined,\n opts: { out?: string; name?: string; force?: boolean },\n command: Command,\n ) => {\n const project = await projectOf(command);\n const app = await loadProjectApp(\n requireEntry(command, entry, project),\n project,\n );\n await runDbCommand(name, app, {\n out: opts.out ?? fromRoot(project, \"drizzle\")!,\n name: opts.name,\n force: opts.force,\n });\n };\n dbCommand(\n \"generate\",\n \"Write a SQL migration for the schema changes since the last one\",\n )\n .option(\"--out <dir>\", OUT_HELP)\n .option(\"--name <name>\", \"Migration name (default migration)\")\n .action(dbAction(\"generate\"));\n dbCommand(\"migrate\", \"Apply the migrations that have not run yet\")\n .option(\"--out <dir>\", OUT_HELP)\n .action(dbAction(\"migrate\"));\n dbCommand(\n \"push\",\n \"Change the database to match the schema directly, without migration files (development)\",\n )\n .option(\"--force\", \"Apply changes that drop data\")\n .action(dbAction(\"push\"));\n\n program\n .command(\"lint\")\n .description(\"Check the project against the Brick lint rules\")\n .argument(\"[entry]\", \"Application entry file\")\n .action(\n async (entry: string | undefined, _opts: object, command: Command) => {\n const project = await projectOf(command);\n const code = await runLint({ entry, project });\n if (code !== 0) process.exit(code);\n },\n );\n\n program\n .command(\"info\")\n .alias(\"services\")\n .description(\"Export architecture JSON schema\")\n .argument(\"[entry]\", \"Application entry file\")\n .action(\n async (entry: string | undefined, _opts: object, command: Command) => {\n const project = await projectOf(command);\n const app = await loadProjectApp(\n requireEntry(command, entry, project),\n project,\n );\n const architecture = getGlobalRegistry().exportArchitecture(\n app.definition,\n );\n console.log(JSON.stringify(architecture, null, 2));\n },\n );\n\n return program;\n}\n\nasync function main() {\n const program = createProgram();\n await program.parseAsync(\n process.argv.length > 2 ? process.argv : [...process.argv, \"dev\"],\n );\n}\n\nmain().catch((err) => {\n // Commander already prints validation errors (missing arg, unknown option,\n // invalid port) and exits. Only print Fatal error for action failures.\n if (err?.exitCode !== undefined) {\n process.exit(err.exitCode);\n }\n if (err?.code?.startsWith?.(\"commander.\")) {\n process.exit(1);\n }\n // A config error already names the file and key; a stack adds nothing.\n if (err instanceof ConfigError) {\n console.error(err.message);\n process.exit(1);\n }\n console.error(\"Fatal error:\", err);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,IAAI;;AAEJ,SAAS,aAAa;CACpB,MAAM,OAAO,cAAc,YAAY,GAAG;CAC1C,IAAI,CAAC,KAAK,SAAS,KAAK,GAAG,OAAO,QAAQ,QAAQ,IAAI,GAAG,gBAAgB;CACzE,IAAI,YAAY,OAAO;CAEvB,MAAM,OAAO,QAAQ,MAAM,4CAA4C;CAEvE,MAAM,WAAW,GAAG,KAAK,GAAG,QAAQ;CACpC,MAAM,SAAS,UACb,QAAQ,UACR;EAAC;EAAS,QAAQ,QAAQ,IAAI,GAAG,WAAW;EAAG;EAAY;CAAM,CAAC,CAAC,OAAO;EACxE;EACA;EACA;EACA;CACF,CAAC,GACD,EAAE,UAAU,OAAO,CACrB;CACA,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,MACR,4CAA4C,OAAO,QACrD;CACF,WAAW,UAAU,IAAI;CACzB,OAAQ,aAAa;AACvB;AAEA,SAAS,UAAU,MAAc;CAC/B,KAAK,MAAM,QAAQ,CACjB,KAAK,MAAM,cAAc,GACzB,cAAc,YAAY,GAAG,CAC/B,GACE,IAAI;EACF,MAAM,MAAM,cAAc,IAAI,CAAC,CAAC,QAAQ,qBAAqB;EAC7D,OAAO,KAAK,QAAQ,GAAG,GAAG,YAAY;CACxC,QAAQ,CAAC;CAEX,MAAM,IAAI,YACR,2DACF;AACF;;;;;AAMA,SAAgB,aAAa,SAMX;CAChB,MAAM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AC;CAGhB,IAAI,eAAe,aAAa;EAC9B,QAAQ,MAAM,IAAI,OAAO;EACzB,QAAQ,KAAK,CAAC;CAChB;CACA,QAAQ,MAAM,gBAAgB,GAAG;CACjC,QAAQ,KAAK,CAAC;AAChB,CAAC"}
|
package/dist/build.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { f as resolvePort, n as ConfigError, s as PROJECT_DEFAULTS } from "./config2.js";
|
|
2
|
-
import {
|
|
2
|
+
import { a as workflowTransformPlugin, i as shipWorkflows, t as buildAppWorkflows } from "./workflows2.js";
|
|
3
3
|
import { i as writeFileIfChanged, o as importEntry, s as loadBrickApp } from "./client-contract-file.js";
|
|
4
4
|
import { n as themeCss, r as writeDashboardExtension, t as openDashboard } from "./dashboard-host.js";
|
|
5
5
|
import { t as ownModule } from "./own-module.js";
|
|
@@ -9,7 +9,7 @@ import { i as MANIFEST_FILE, n as DEFINITION_FILE, r as DEFINITION_KINDS, t as D
|
|
|
9
9
|
import { t as emitCompiledApplication } from "./compiler2.js";
|
|
10
10
|
import { existsSync, watch } from "node:fs";
|
|
11
11
|
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
12
|
-
import { brick, compileBrickApplication, isBrickApp } from "@brickkit/core";
|
|
12
|
+
import { WORKFLOW_BUNDLE, brick, compileBrickApplication, isBrickApp } from "@brickkit/core";
|
|
13
13
|
import { mkdir, mkdtemp, rename, rm } from "node:fs/promises";
|
|
14
14
|
import { aot } from "elysia/plugin/aot/bun";
|
|
15
15
|
// src/manifest.ts
|
|
@@ -328,8 +328,8 @@ async function startDevServer(options = {}) {
|
|
|
328
328
|
}
|
|
329
329
|
// src/compiler/aot.ts
|
|
330
330
|
/** Keep the pinned Elysia beta's incomplete stripping from breaking builds. */
|
|
331
|
-
function brickAot(entry,
|
|
332
|
-
if (
|
|
331
|
+
function brickAot(entry, keep) {
|
|
332
|
+
if (keep) return aot(entry, {
|
|
333
333
|
target: "bun",
|
|
334
334
|
strip: false
|
|
335
335
|
});
|
|
@@ -392,7 +392,7 @@ async function buildApplication(options) {
|
|
|
392
392
|
const extension = options.dashboard?.extension ? resolve(options.dashboard.extension) : void 0;
|
|
393
393
|
if (extension && !await Bun.file(extension).exists()) throw new Error(`Brick compiler: dashboard extension not found: ${extension}`);
|
|
394
394
|
const app = await loadBrickApp(entry);
|
|
395
|
-
|
|
395
|
+
const root = app.events?.workflows?.root ?? process.cwd();
|
|
396
396
|
const services = [...app.definition.services];
|
|
397
397
|
const compilation = compileBrickApplication({
|
|
398
398
|
services,
|
|
@@ -404,12 +404,16 @@ async function buildApplication(options) {
|
|
|
404
404
|
await Bun.write(join(staging, "routes.js"), emitCompiledApplication(compilation.ir));
|
|
405
405
|
const dashboard = await writeDashboardExtension(extension, app.definition.plugins ?? [], join(staging, "dashboard")) ? join(outdir, "dashboard") : void 0;
|
|
406
406
|
const theme = JSON.stringify(options.dashboard?.theme);
|
|
407
|
-
const source = `import {
|
|
407
|
+
const source = `import { existsSync } from "node:fs";
|
|
408
|
+
import { fileURLToPath } from "node:url";
|
|
408
409
|
import { loadCompiledBrickApp } from "@brickkit/core";
|
|
409
410
|
import { resolvePort } from ${JSON.stringify(ownModule("config"))};
|
|
410
411
|
import { serveApp, shutdownOnSignal } from ${JSON.stringify(ownModule("serve"))};
|
|
411
|
-
|
|
412
|
-
export const app = await loadCompiledBrickApp(() => import(${JSON.stringify(entry)}),
|
|
412
|
+
const workflows = fileURLToPath(new URL(${JSON.stringify(`./${WORKFLOW_BUNDLE.dir}`)}, import.meta.url));
|
|
413
|
+
export const app = await loadCompiledBrickApp(() => import(${JSON.stringify(entry)}), undefined, {
|
|
414
|
+
workflows: existsSync(workflows) ? workflows : undefined,
|
|
415
|
+
});
|
|
416
|
+
export default app;
|
|
413
417
|
if (import.meta.main) {
|
|
414
418
|
await serveApp(app, {
|
|
415
419
|
port: resolvePort(undefined, ${port}),
|
|
@@ -420,7 +424,10 @@ if (import.meta.main) {
|
|
|
420
424
|
}
|
|
421
425
|
`;
|
|
422
426
|
await Bun.write(join(staging, "entry.ts"), source);
|
|
423
|
-
|
|
427
|
+
let directives = false;
|
|
428
|
+
const transform = await workflowTransformPlugin(root, () => {
|
|
429
|
+
directives = true;
|
|
430
|
+
});
|
|
424
431
|
const result = await Bun.build({
|
|
425
432
|
entrypoints: [join(staging, "entry.ts")],
|
|
426
433
|
target: "bun",
|
|
@@ -429,15 +436,25 @@ if (import.meta.main) {
|
|
|
429
436
|
naming: "server.js",
|
|
430
437
|
sourcemap: "external",
|
|
431
438
|
plugins: [
|
|
432
|
-
...options.aot === false ? [] : [brickAot(join(staging, "entry.ts"), app.definition.sockets.length > 0)],
|
|
433
|
-
...
|
|
439
|
+
...options.aot === false ? [] : [brickAot(join(staging, "entry.ts"), app.definition.sockets.length > 0 || transform !== void 0)],
|
|
440
|
+
...transform ? [transform] : [],
|
|
434
441
|
productionDashboardAtRunTime
|
|
435
442
|
]
|
|
436
443
|
});
|
|
437
444
|
if (!result.success) throw new AggregateError(result.logs, "Brick compiler: bundling failed");
|
|
445
|
+
const workflows = (directives || Boolean(app.events?.workflows)) && await shipWorkflows(root, staging, Boolean(app.events?.workflows));
|
|
438
446
|
await Bun.write(join(staging, "brick-ir.json"), JSON.stringify(compilation.ir, null, 2) + "\n");
|
|
439
447
|
await mkdir(outdir, { recursive: true });
|
|
440
448
|
for (const name of OUTPUTS) await rename(join(staging, name), join(outdir, name));
|
|
449
|
+
const bundle = join(outdir, WORKFLOW_BUNDLE.dir);
|
|
450
|
+
await rm(bundle, {
|
|
451
|
+
recursive: true,
|
|
452
|
+
force: true
|
|
453
|
+
});
|
|
454
|
+
if (workflows) {
|
|
455
|
+
await mkdir(dirname(bundle), { recursive: true });
|
|
456
|
+
await rename(join(staging, WORKFLOW_BUNDLE.dir), bundle);
|
|
457
|
+
}
|
|
441
458
|
if (dashboard) {
|
|
442
459
|
await rm(dashboard, {
|
|
443
460
|
recursive: true,
|
|
@@ -449,7 +466,8 @@ if (import.meta.main) {
|
|
|
449
466
|
outdir,
|
|
450
467
|
entry: join(outdir, "server.js"),
|
|
451
468
|
ir: compilation.ir,
|
|
452
|
-
dashboard
|
|
469
|
+
dashboard,
|
|
470
|
+
workflows: workflows ? join(outdir, WORKFLOW_BUNDLE.dir) : void 0
|
|
453
471
|
};
|
|
454
472
|
} finally {
|
|
455
473
|
await rm(staging, {
|
package/dist/build.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.js","names":[],"sources":["../src/manifest.ts","../src/runner.ts","../src/compiler/aot.ts","../src/build.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\nimport { writeFileIfChanged } from \"./client-contract-file\";\n\nimport {\n DEFINITION_EXTENSIONS,\n DEFINITION_FILE,\n DEFINITION_KINDS,\n MANIFEST_FILE,\n type DefinitionKind,\n} from \"./definitions\";\n\n/** Services register before the resources that join them; every other kind after. */\nconst FIRST: readonly DefinitionKind[] = [\"service\", \"resource\"];\n\nfunction rank(file: string) {\n const index = FIRST.indexOf(\n DEFINITION_FILE.exec(file)?.[2] as DefinitionKind,\n );\n return index === -1 ? FIRST.length : index;\n}\n\n/** Definition files under `services`: service files first, then resources, then the rest, each by path. */\nexport function scanDefinitionFiles(services: string): string[] {\n if (!existsSync(services)) return [];\n // Built per call: index.ts imports this module (through runner) and still\n // exports defineConfig, so Node may load it (ESLint reading brick.config.ts).\n const glob = new Bun.Glob(\n `**/*.{${DEFINITION_KINDS.join(\",\")}}.{${DEFINITION_EXTENSIONS.join(\",\")}}`,\n );\n const files = [...glob.scanSync({ cwd: services, onlyFiles: true })]\n .map((file) => file.split(sep).join(\"/\"))\n .filter((file) => !file.split(\"/\").includes(\"node_modules\"));\n return files.sort(\n (a, b) => rank(a) - rank(b) || (a < b ? -1 : a > b ? 1 : 0),\n );\n}\n\n/** The source of `services.gen.ts`, which imports every definition file so each registers itself. */\nexport function renderManifest(services: string, generated: string): string {\n const imports = scanDefinitionFiles(services).map((file) => {\n let specifier = relative(generated, join(services, file))\n .split(sep)\n .join(\"/\")\n .replace(DEFINITION_FILE, \"$1.$2\");\n if (!specifier.startsWith(\".\")) specifier = `./${specifier}`;\n return `import ${JSON.stringify(specifier)};\\n`;\n });\n return `// Generated by Brick. Do not edit.\n// Imports every definition file under the services folder, so each one\n// registers itself on its service. The app entry imports this file.\n${imports.join(\"\")}\nexport {};\n`;\n}\n\n/** Write `<generated>/services.gen.ts`, leaving it untouched when nothing changed. */\nexport async function writeServiceManifest(options: {\n services: string;\n generated: string;\n}): Promise<string> {\n const output = join(options.generated, MANIFEST_FILE);\n await writeFileIfChanged(\n output,\n renderManifest(options.services, options.generated),\n );\n return output;\n}\n","import { existsSync, watch } from \"node:fs\";\nimport { basename, dirname, join, resolve, sep } from \"node:path\";\nimport { brick, isBrickApp } from \"@brickkit/core\";\nimport { importEntry } from \"./app-entry\";\nimport { TEMPORARY_FILE_PREFIX } from \"./client-contract-file\";\nimport {\n ConfigError,\n CONTRACT_FILE,\n DEFAULT_DASHBOARD_PORT,\n PROJECT_DEFAULTS,\n resolvePort,\n} from \"./config\";\nimport { openDashboard } from \"./dashboard-host\";\nimport { ownModule } from \"./own-module\";\nimport type { DashboardExtensionOptions } from \"./dashboard-extension\";\nimport { startDevApplication } from \"./dev-application\";\nimport type { WorkerMessage, WorkerOptions } from \"./dev-protocol\";\nimport { writeServiceManifest } from \"./manifest\";\nimport { printBanner, serveApp, shutdownOnSignal } from \"./serve\";\nimport { buildAppWorkflows } from \"./workflows\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n /**\n * @deprecated Only used without an `entry`; an exported app sets its own\n * prefix in `brick({ prefix })`.\n */\n prefix?: string;\n /** Generate a browser contract before starting the backend and frontend. */\n clientOutput?: string;\n /** Frontend command, launched once after the first successful generation. */\n frontend?: string;\n /**\n * Local dashboard with live requests, traces, errors, and reloads. Needs an\n * entry. `port` is where it listens and `historyDays` how long finished\n * requests are kept on disk; zero keeps live data only. `extension` and\n * `theme` customise it (see `DashboardExtensionOptions`).\n */\n dashboard?:\n | ({ port?: number; historyDays?: number } & DashboardExtensionOptions)\n | false;\n /**\n * Keep `<generated>/services.gen.ts` importing every definition file under\n * `services`: written before the app starts and again when files change.\n */\n manifest?: { services: string; generated: string };\n}\n\n/**\n * What `brick start` runs: serve the entry's default-exported app as it built\n * it (else one with the registered services), with the monitoring dashboard\n * it asks for, until SIGINT or SIGTERM.\n */\nexport async function startProdServer(options: {\n entry?: string;\n port?: number;\n /** The production dashboard's extension and theme. */\n dashboard?: DashboardExtensionOptions;\n}) {\n let exported: unknown;\n if (options.entry) {\n console.log(\n `[Brick-TS] Loading application entry: ${resolve(options.entry)}`,\n );\n exported = await importEntry(options.entry, { run: true });\n }\n const port = resolvePort(options.port);\n const app = isBrickApp(exported) ? exported : brick();\n await buildAppWorkflows(app);\n const dashboard = await serveApp(app, {\n port,\n dashboard: options.dashboard,\n });\n shutdownOnSignal(app);\n printBanner(app, { label: \"Production\", port, dashboard });\n return app;\n}\n\n/**\n * What `brick worker` runs: load the app and deliver its events from this\n * process, without serving HTTP. Run it beside API processes that only record\n * events (`events: { dispatch: false }`), or alone for an app with no routes.\n * Workflow listeners run here too: the world starts and the steps of every run\n * in it execute in this process.\n *\n * @param options - `entry`: the app file, which must default-export a `brick()` app.\n * @returns The app.\n * @throws When the entry is missing, has no `events`, or only records events.\n */\nexport async function startWorker(options: { entry: string }) {\n console.log(\n `[Brick-TS] Loading application entry: ${resolve(options.entry)}`,\n );\n const app = await importEntry(options.entry, { run: true });\n if (!isBrickApp(app))\n throw new ConfigError(\n \"Brick: a worker needs an entry that default-exports a BrickApp.\",\n );\n if (!app.events)\n throw new ConfigError(\n \"Brick: this app has no events, so a worker has nothing to deliver.\",\n );\n if (!app.events.describe().dispatch)\n throw new ConfigError(\n \"Brick: this app only records events (events.dispatch is false), so a worker would deliver nothing. Enable dispatch for the worker process.\",\n );\n await buildAppWorkflows(app);\n await app.start();\n app.events.start();\n shutdownOnSignal(app);\n const listeners = app.events.describe().listeners;\n console.log(`\\n🧱 Brick-TS Worker`);\n console.log(\n ` Delivering events to ${listeners.length} ${listeners.length === 1 ? \"listener\" : \"listeners\"}: ${listeners.map((l) => l.name).join(\", \") || \"none\"}\\n`,\n );\n return app;\n}\n\n/**\n * What `brick dev` runs: start the application, restart it when its files\n * change, and serve the dashboard beside it. With an `entry`, the app runs in\n * a worker process that restarts on every change to the entry or the files it\n * imports, and reports its requests to the dashboard; without one, a server\n * with the registered services starts in this process.\n *\n * @param options - `entry`, `port` (else `PORT`, else 4000), `prefix`,\n * `clientOutput` to regenerate the typed client's contract on each start,\n * `frontend` to launch a frontend command once, and `dashboard` (`port` and\n * `historyDays`, or `false`).\n * @returns The application, when started in this process.\n * @throws When `frontend` is given without `clientOutput`, or the dashboard\n * would use the app's port.\n */\nexport async function startDevServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n if (!entry && (options.clientOutput || options.frontend))\n throw new ConfigError(\n \"Brick: --client and --frontend require an app entry.\",\n );\n if (options.frontend && !options.clientOutput)\n throw new ConfigError(\"Brick: --frontend requires --client <file>.\");\n const port = resolvePort(options.port);\n if (!entry) return startDevApplication({ port, prefix: options.prefix });\n const resolvedEntry = resolve(entry);\n if (!existsSync(resolvedEntry))\n throw new ConfigError(\n `[Brick-TS] Error: Entry file not found: ${resolvedEntry}`,\n );\n\n if (\n options.dashboard &&\n (options.dashboard.port ?? DEFAULT_DASHBOARD_PORT) === port\n )\n throw new ConfigError(\n \"Brick: dashboard port must differ from the API port. Use --dashboard-port <number>.\",\n );\n const manifest = options.manifest;\n if (manifest) await writeServiceManifest(manifest);\n const contract = resolve(\n options.clientOutput ??\n join(manifest?.generated ?? PROJECT_DEFAULTS.generated, CONTRACT_FILE),\n );\n const workerOptions: WorkerOptions = {\n entry: resolvedEntry,\n port,\n prefix: options.prefix,\n clientOutput: options.clientOutput && contract,\n telemetry: Boolean(options.dashboard),\n };\n // Bind the dashboard before the first worker starts, so the worker's spans\n // have somewhere to go.\n const dashboard = options.dashboard\n ? await openDashboard({\n port: options.dashboard.port,\n directory: process.cwd(),\n historyDays: options.dashboard.historyDays,\n warn: (message) => console.warn(message),\n docs: true,\n dashboard: {\n extension: options.dashboard.extension,\n theme: options.dashboard.theme,\n },\n restart: () => {\n void restart(\"dashboard\");\n },\n portHint: \"Use --dashboard-port <number> or --no-dashboard.\",\n })\n : undefined;\n const telemetry = dashboard?.store;\n let frontend: ReturnType<typeof Bun.spawn> | undefined;\n const dependencyFiles = new Set<string>();\n const dependencyWatchers = new Map<string, ReturnType<typeof watch>>();\n let stopped = false;\n const intentionalExits = new WeakSet<ReturnType<typeof Bun.spawn>>();\n const receive = (message: WorkerMessage, generation: number) => {\n switch (message.type) {\n case \"brick:telemetry\":\n telemetry?.ingest(message.records, generation);\n return;\n case \"brick:error\":\n telemetry?.recordWorkerError(message.phase, message.error, generation);\n return;\n case \"brick:contract-ready\":\n if (options.frontend && !frontend && !stopped)\n frontend = Bun.spawn(\n [process.env.SHELL ?? \"/bin/sh\", \"-c\", options.frontend],\n {\n detached: true,\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n },\n );\n telemetry?.recordReload({\n kind: \"contract-ready\",\n generation,\n detail: \"browser contract generated\",\n });\n return;\n case \"brick:architecture\":\n telemetry?.setArchitecture(message.architecture, generation);\n void dashboard?.setPluginExtensions(message.architecture.plugins ?? []);\n return;\n case \"brick:inspector\":\n if (generation === telemetry?.latestGeneration)\n telemetry.setInspector({ port: message.port, token: message.token });\n return;\n case \"brick:documentation\":\n void dashboard?.docs?.configure(\n dirname(resolvedEntry),\n message.documentation,\n );\n return;\n case \"brick:api-documents\":\n telemetry?.setApiDocuments(\n message.documents,\n `http://localhost:${port}`,\n );\n return;\n case \"brick:dependencies\":\n for (const file of message.files) {\n if (file === contract) continue;\n dependencyFiles.add(file);\n const directory = dirname(file);\n if (!dependencyWatchers.has(directory))\n dependencyWatchers.set(\n directory,\n watch(directory, (_event, filename) => {\n if (\n !filename ||\n !dependencyFiles.has(resolve(directory, filename))\n )\n return;\n scheduleRestart();\n }),\n );\n }\n return;\n }\n };\n const launch = () => {\n // The new process serves its own inspector once it is up.\n telemetry?.setInspector(undefined);\n const generation = telemetry?.startGeneration() ?? 0;\n const application = Bun.spawn(\n [\n process.execPath,\n ownModule(\"dev-worker\"),\n JSON.stringify(workerOptions),\n ],\n {\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n ipc: (message: WorkerMessage) => receive(message, generation),\n },\n );\n void application.exited.then((code) => {\n if (generation === telemetry?.latestGeneration)\n telemetry.setInspector(undefined);\n if (!stopped && !intentionalExits.has(application)) {\n console.error(\n `[Brick-TS] Application process exited with code ${code}. Waiting for changes to restart.`,\n );\n telemetry?.recordReload({\n kind: \"exited\",\n generation,\n detail: `exit code ${code}`,\n });\n }\n telemetry?.interruptGeneration(generation);\n });\n return application;\n };\n if (dashboard) {\n console.log(`📊 Dev dashboard: http://127.0.0.1:${dashboard.port}`);\n }\n let child = launch();\n // The worker reports the other files the entry imports (brick:dependencies).\n const watchDirs = [\n ...new Set([\n dirname(resolvedEntry),\n ...(manifest ? [manifest.services] : []),\n ]),\n ].filter(existsSync);\n let pending: ReturnType<typeof setTimeout> | undefined;\n let restarting = false;\n let dirty = false;\n\n async function restart(trigger: \"changes\" | \"dashboard\" = \"changes\") {\n dirty = true;\n if (restarting || stopped) return;\n restarting = true;\n try {\n while (dirty && !stopped) {\n dirty = false;\n console.log(\n trigger === \"changes\"\n ? \"\\n📝 Changes detected. Restarting server...\"\n : \"\\n🔄 Restart requested from the dashboard. Restarting server...\",\n );\n telemetry?.recordReload({\n kind: \"restarting\",\n generation: telemetry.latestGeneration,\n detail:\n trigger === \"changes\" ? \"source changed\" : \"restart from dashboard\",\n });\n intentionalExits.add(child);\n child.kill();\n await child.exited;\n if (!stopped) child = launch();\n }\n } finally {\n restarting = false;\n }\n }\n\n function scheduleRestart() {\n clearTimeout(pending);\n pending = setTimeout(() => {\n void restart();\n }, 100);\n }\n const extension = options.dashboard && options.dashboard.extension;\n const extensionDir =\n extension && !watchDirs.includes(dirname(resolve(extension)))\n ? `${dirname(resolve(extension))}${sep}`\n : undefined;\n const watchers = watchDirs.map((dir) =>\n watch(dir, { recursive: true }, (_event, filename) => {\n if (!filename || filename.split(/[\\\\/]/).includes(\"node_modules\")) return;\n const file = resolve(dir, filename);\n if (\n file === contract ||\n basename(file).startsWith(TEMPORARY_FILE_PREFIX) ||\n // The dashboard rebuilds its extension itself; the app restarts only\n // for the files it imports.\n (extensionDir !== undefined &&\n file.startsWith(extensionDir) &&\n !dependencyFiles.has(file))\n )\n return;\n // A definition file was added or removed: refresh the import list first.\n if (manifest && file.startsWith(manifest.services + sep)) {\n void writeServiceManifest(manifest)\n .catch((error: unknown) =>\n console.error(\"[Brick-TS] Could not write services.gen.ts:\", error),\n )\n .finally(scheduleRestart);\n return;\n }\n scheduleRestart();\n }),\n );\n const stop = () => {\n if (stopped) return;\n stopped = true;\n clearTimeout(pending);\n for (const watcher of watchers) watcher.close();\n for (const watcher of dependencyWatchers.values()) watcher.close();\n if (frontend) {\n if (process.platform === \"win32\") {\n Bun.spawnSync([\"taskkill\", \"/pid\", String(frontend.pid), \"/t\", \"/f\"]);\n } else {\n try {\n process.kill(-frontend.pid, \"SIGTERM\");\n } catch (error) {\n if (\n !(\n error instanceof Error &&\n \"code\" in error &&\n error.code === \"ESRCH\"\n )\n )\n throw error;\n }\n }\n }\n dashboard?.stop();\n child.kill();\n process.off(\"SIGINT\", onSignal);\n process.off(\"SIGTERM\", onSignal);\n process.off(\"exit\", stop);\n };\n const onSignal = (signal: NodeJS.Signals) => {\n if (stopped) {\n child.kill(\"SIGKILL\");\n process.exit(signal === \"SIGINT\" ? 130 : 143);\n }\n stop();\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n void child.exited.then(() => process.exit(0));\n };\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n process.on(\"exit\", stop);\n console.log(`\\n👀 Watching for changes in: ${watchDirs.join(\", \")}`);\n return { stop };\n}\n","import { aot } from \"elysia/plugin/aot/bun\";\nimport type { BunPlugin } from \"bun\";\n\n/** Keep the pinned Elysia beta's incomplete stripping from breaking builds. */\nexport function brickAot(entry: string, hasSockets: boolean): BunPlugin {\n // WS routes still need cookie setup during reconstruction in beta.29.\n // Retain those modules while continuing to precompile HTTP handlers.\n if (hasSockets) return aot(entry, { target: \"bun\", strip: false });\n return {\n name: \"brick-elysia-aot\",\n async setup(build) {\n await aot(entry, { target: \"bun\", strip: true }).setup({\n ...build,\n onLoad(options, callback) {\n return build.onLoad(options, async (args) => {\n const result = await callback(args);\n if (\n !result ||\n !(\"contents\" in result) ||\n typeof result.contents !== \"string\"\n )\n return result;\n let contents = result.contents;\n if (\n /[/\\\\]elysia[/\\\\]dist[/\\\\]ws[/\\\\]route\\.m?js$/.test(args.path) &&\n contents.includes(\n \"[elysia-aot] WebSocket route builder was stripped\",\n )\n ) {\n for (const name of [\"resolveWSOptions\", \"accumulateWSOptions\"]) {\n if (!contents.includes(`export function ${name}`))\n contents += `\\nexport function ${name}() { throw new Error(\"WebSocket support was stripped\"); }\\n`;\n }\n }\n return contents === result.contents\n ? result\n : { ...result, contents };\n });\n },\n });\n },\n };\n}\n","import { mkdtemp, mkdir, rename, rm } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { compileBrickApplication } from \"@brickkit/core\";\nimport type { BunPlugin } from \"bun\";\nimport { emitCompiledApplication } from \"./compiler\";\nimport { brickAot } from \"./compiler/aot\";\nimport { loadBrickApp } from \"./app-entry\";\nimport { ownModule } from \"./own-module\";\nimport { DEFAULT_OUTDIR, resolvePort } from \"./config\";\nimport { buildAppWorkflows, workflowTransformPlugin } from \"./workflows\";\nimport {\n themeCss,\n writeDashboardExtension,\n type DashboardExtensionOptions,\n} from \"./dashboard-extension\";\n\nexport interface BuildApplicationOptions {\n /** A module whose default export is a BrickApp, without starting a server. */\n entry: string;\n outdir?: string;\n port?: number;\n /** Precompile Elysia's HTTP handlers at build time (default true). */\n aot?: boolean;\n /**\n * The dashboard's extension, built into `<outdir>/dashboard` with those of\n * the app's plugins for the production dashboard to serve; its theme is\n * checked here too.\n */\n dashboard?: DashboardExtensionOptions;\n}\n\n/**\n * The production dashboard stays out of the bundle: it serves files that ship\n * with @brickkit/cli, so a built server whose app asks for it imports it from\n * there at run time. Without a dashboard the bundle needs nothing installed.\n */\nconst productionDashboardAtRunTime: BunPlugin = {\n name: \"brick:production-dashboard\",\n setup(build) {\n build.onResolve({ filter: /^\\.\\/production-dashboard(\\.[jt]s)?$/ }, () => ({\n path: \"@brickkit/cli/production-dashboard\",\n external: true,\n }));\n },\n};\n\n/** The files `brick build` writes to the output folder, `server.js` last. */\nconst OUTPUTS = [\"routes.js\", \"brick-ir.json\", \"server.js.map\", \"server.js\"];\n\n/** Bundle an exported BrickApp with its compiled IR and its original configuration. */\nexport async function buildApplication(options: BuildApplicationOptions) {\n const entry = resolve(options.entry);\n if (!(await Bun.file(entry).exists()))\n throw new Error(`Brick compiler: entry not found: ${entry}`);\n const outdir = resolve(options.outdir ?? DEFAULT_OUTDIR);\n if (OUTPUTS.some((name) => entry === join(outdir, name)))\n throw new Error(\n \"Brick compiler: output would overwrite the application entry\",\n );\n const port = resolvePort(options.port, undefined, \"\");\n themeCss(options.dashboard?.theme);\n const extension = options.dashboard?.extension\n ? resolve(options.dashboard.extension)\n : undefined;\n if (extension && !(await Bun.file(extension).exists()))\n throw new Error(\n `Brick compiler: dashboard extension not found: ${extension}`,\n );\n const app = await loadBrickApp(entry);\n // The bundle stays in the project, where the server finds it from the working\n // directory, as `brick start` does.\n await buildAppWorkflows(app);\n const services = [...app.definition.services];\n const compilation = compileBrickApplication({\n services,\n prefix: app.definition.prefix,\n });\n await mkdir(dirname(outdir), { recursive: true });\n const staging = await mkdtemp(join(dirname(outdir), \".brick-build-\"));\n try {\n await Bun.write(\n join(staging, \"routes.js\"),\n emitCompiledApplication(compilation.ir),\n );\n const dashboard = (await writeDashboardExtension(\n extension,\n app.definition.plugins ?? [],\n join(staging, \"dashboard\"),\n ))\n ? join(outdir, \"dashboard\")\n : undefined;\n const theme = JSON.stringify(options.dashboard?.theme);\n const source = `import { fileURLToPath } from \"node:url\";\nimport { loadCompiledBrickApp } from \"@brickkit/core\";\nimport { resolvePort } from ${JSON.stringify(ownModule(\"config\"))};\nimport { serveApp, shutdownOnSignal } from ${JSON.stringify(ownModule(\"serve\"))};\nimport { ir } from \"./routes.js\";\nexport const app = await loadCompiledBrickApp(() => import(${JSON.stringify(entry)}), ir);\nif (import.meta.main) {\n await serveApp(app, {\n port: resolvePort(undefined, ${port}),\n dashboard: { extension: ${dashboard ? 'fileURLToPath(new URL(\"./dashboard\", import.meta.url))' : \"undefined\"}, theme: ${theme} },\n });\n console.log(\"Brick compiled server listening on http://localhost:\" + app.server.port);\n shutdownOnSignal(app);\n}\n`;\n await Bun.write(join(staging, \"entry.ts\"), source);\n const workflows = app.events?.workflows\n ? await workflowTransformPlugin(app.events.workflows.root)\n : undefined;\n const result = await Bun.build({\n entrypoints: [join(staging, \"entry.ts\")],\n target: \"bun\",\n format: \"esm\",\n outdir: staging,\n naming: \"server.js\",\n sourcemap: \"external\",\n // AOT first: the workflow plugin loads every project file it sees, so after\n // it the AOT plugin would never get to transform the entry.\n plugins: [\n ...(options.aot === false\n ? []\n : [\n brickAot(\n join(staging, \"entry.ts\"),\n app.definition.sockets.length > 0,\n ),\n ]),\n ...(workflows ? [workflows] : []),\n productionDashboardAtRunTime,\n ],\n });\n if (!result.success)\n throw new AggregateError(result.logs, \"Brick compiler: bundling failed\");\n await Bun.write(\n join(staging, \"brick-ir.json\"),\n JSON.stringify(compilation.ir, null, 2) + \"\\n\",\n );\n await mkdir(outdir, { recursive: true });\n for (const name of OUTPUTS)\n await rename(join(staging, name), join(outdir, name));\n if (dashboard) {\n await rm(dashboard, { recursive: true, force: true });\n await rename(join(staging, \"dashboard\"), dashboard);\n }\n return {\n outdir,\n entry: join(outdir, \"server.js\"),\n ir: compilation.ir,\n dashboard,\n };\n } finally {\n await rm(staging, { recursive: true, force: true });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,MAAM,QAAmC,CAAC,WAAW,UAAU;AAE/D,SAAS,KAAK,MAAc;CAC1B,MAAM,QAAQ,MAAM,QAClB,gBAAgB,KAAK,IAAI,CAAC,GAAG,EAC/B;CACA,OAAO,UAAU,KAAK,MAAM,SAAS;AACvC;;AAGA,SAAgB,oBAAoB,UAA4B;CAC9D,IAAI,CAAC,WAAW,QAAQ,GAAG,OAAO,CAAC;CASnC,OAHc,CAAC,GAAG,IAHD,IAAI,KACnB,SAAS,iBAAiB,KAAK,GAAG,EAAE,KAAK,sBAAsB,KAAK,GAAG,EAAE,EAEtD,CAAC,CAAC,SAAS;EAAE,KAAK;EAAU,WAAW;CAAK,CAAC,CAAC,CAAC,CACjE,KAAK,SAAS,KAAK,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CACxC,QAAQ,SAAS,CAAC,KAAK,MAAM,GAAG,CAAC,CAAC,SAAS,cAAc,CACjD,CAAC,CAAC,MACV,GAAG,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,EAC3D;AACF;;AAGA,SAAgB,eAAe,UAAkB,WAA2B;CAS1E,OAAO;;;EARS,oBAAoB,QAAQ,CAAC,CAAC,KAAK,SAAS;EAC1D,IAAI,YAAY,SAAS,WAAW,KAAK,UAAU,IAAI,CAAC,CAAC,CACtD,MAAM,GAAG,CAAC,CACV,KAAK,GAAG,CAAC,CACT,QAAQ,iBAAiB,OAAO;EACnC,IAAI,CAAC,UAAU,WAAW,GAAG,GAAG,YAAY,KAAK;EACjD,OAAO,UAAU,KAAK,UAAU,SAAS,EAAE;CAC7C,CAIM,CAAC,CAAC,KAAK,EAAE,EAAE;;;AAGnB;;AA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ACtD,IAAI,WAAW;GACb,MAAM,GAAG,WAAW;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;GACpD,MAAM,OAAO,KAAK,SAAS,WAAW,GAAG,SAAS;EACpD;EACA,OAAO;GACL;GACA,OAAO,KAAK,QAAQ,WAAW;GAC/B,IAAI,YAAY;GAChB;EACF;CACF,UAAU;EACR,MAAM,GAAG,SAAS;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CACpD;AACF"}
|
|
1
|
+
{"version":3,"file":"build.js","names":[],"sources":["../src/manifest.ts","../src/runner.ts","../src/compiler/aot.ts","../src/build.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\nimport { writeFileIfChanged } from \"./client-contract-file\";\n\nimport {\n DEFINITION_EXTENSIONS,\n DEFINITION_FILE,\n DEFINITION_KINDS,\n MANIFEST_FILE,\n type DefinitionKind,\n} from \"./definitions\";\n\n/** Services register before the resources that join them; every other kind after. */\nconst FIRST: readonly DefinitionKind[] = [\"service\", \"resource\"];\n\nfunction rank(file: string) {\n const index = FIRST.indexOf(\n DEFINITION_FILE.exec(file)?.[2] as DefinitionKind,\n );\n return index === -1 ? FIRST.length : index;\n}\n\n/** Definition files under `services`: service files first, then resources, then the rest, each by path. */\nexport function scanDefinitionFiles(services: string): string[] {\n if (!existsSync(services)) return [];\n // Built per call: index.ts imports this module (through runner) and still\n // exports defineConfig, so Node may load it (ESLint reading brick.config.ts).\n const glob = new Bun.Glob(\n `**/*.{${DEFINITION_KINDS.join(\",\")}}.{${DEFINITION_EXTENSIONS.join(\",\")}}`,\n );\n const files = [...glob.scanSync({ cwd: services, onlyFiles: true })]\n .map((file) => file.split(sep).join(\"/\"))\n .filter((file) => !file.split(\"/\").includes(\"node_modules\"));\n return files.sort(\n (a, b) => rank(a) - rank(b) || (a < b ? -1 : a > b ? 1 : 0),\n );\n}\n\n/** The source of `services.gen.ts`, which imports every definition file so each registers itself. */\nexport function renderManifest(services: string, generated: string): string {\n const imports = scanDefinitionFiles(services).map((file) => {\n let specifier = relative(generated, join(services, file))\n .split(sep)\n .join(\"/\")\n .replace(DEFINITION_FILE, \"$1.$2\");\n if (!specifier.startsWith(\".\")) specifier = `./${specifier}`;\n return `import ${JSON.stringify(specifier)};\\n`;\n });\n return `// Generated by Brick. Do not edit.\n// Imports every definition file under the services folder, so each one\n// registers itself on its service. The app entry imports this file.\n${imports.join(\"\")}\nexport {};\n`;\n}\n\n/** Write `<generated>/services.gen.ts`, leaving it untouched when nothing changed. */\nexport async function writeServiceManifest(options: {\n services: string;\n generated: string;\n}): Promise<string> {\n const output = join(options.generated, MANIFEST_FILE);\n await writeFileIfChanged(\n output,\n renderManifest(options.services, options.generated),\n );\n return output;\n}\n","import { existsSync, watch } from \"node:fs\";\nimport { basename, dirname, join, resolve, sep } from \"node:path\";\nimport { brick, isBrickApp } from \"@brickkit/core\";\nimport { importEntry } from \"./app-entry\";\nimport { TEMPORARY_FILE_PREFIX } from \"./client-contract-file\";\nimport {\n ConfigError,\n CONTRACT_FILE,\n DEFAULT_DASHBOARD_PORT,\n PROJECT_DEFAULTS,\n resolvePort,\n} from \"./config\";\nimport { openDashboard } from \"./dashboard-host\";\nimport { ownModule } from \"./own-module\";\nimport type { DashboardExtensionOptions } from \"./dashboard-extension\";\nimport { startDevApplication } from \"./dev-application\";\nimport type { WorkerMessage, WorkerOptions } from \"./dev-protocol\";\nimport { writeServiceManifest } from \"./manifest\";\nimport { printBanner, serveApp, shutdownOnSignal } from \"./serve\";\nimport { buildAppWorkflows } from \"./workflows\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n /**\n * @deprecated Only used without an `entry`; an exported app sets its own\n * prefix in `brick({ prefix })`.\n */\n prefix?: string;\n /** Generate a browser contract before starting the backend and frontend. */\n clientOutput?: string;\n /** Frontend command, launched once after the first successful generation. */\n frontend?: string;\n /**\n * Local dashboard with live requests, traces, errors, and reloads. Needs an\n * entry. `port` is where it listens and `historyDays` how long finished\n * requests are kept on disk; zero keeps live data only. `extension` and\n * `theme` customise it (see `DashboardExtensionOptions`).\n */\n dashboard?:\n | ({ port?: number; historyDays?: number } & DashboardExtensionOptions)\n | false;\n /**\n * Keep `<generated>/services.gen.ts` importing every definition file under\n * `services`: written before the app starts and again when files change.\n */\n manifest?: { services: string; generated: string };\n}\n\n/**\n * What `brick start` runs: serve the entry's default-exported app as it built\n * it (else one with the registered services), with the monitoring dashboard\n * it asks for, until SIGINT or SIGTERM.\n */\nexport async function startProdServer(options: {\n entry?: string;\n port?: number;\n /** The production dashboard's extension and theme. */\n dashboard?: DashboardExtensionOptions;\n}) {\n let exported: unknown;\n if (options.entry) {\n console.log(\n `[Brick-TS] Loading application entry: ${resolve(options.entry)}`,\n );\n exported = await importEntry(options.entry, { run: true });\n }\n const port = resolvePort(options.port);\n const app = isBrickApp(exported) ? exported : brick();\n await buildAppWorkflows(app);\n const dashboard = await serveApp(app, {\n port,\n dashboard: options.dashboard,\n });\n shutdownOnSignal(app);\n printBanner(app, { label: \"Production\", port, dashboard });\n return app;\n}\n\n/**\n * What `brick worker` runs: load the app and deliver its events from this\n * process, without serving HTTP. Run it beside API processes that only record\n * events (`events: { dispatch: false }`), or alone for an app with no routes.\n * Workflow listeners run here too: the world starts and the steps of every run\n * in it execute in this process.\n *\n * @param options - `entry`: the app file, which must default-export a `brick()` app.\n * @returns The app.\n * @throws When the entry is missing, has no `events`, or only records events.\n */\nexport async function startWorker(options: { entry: string }) {\n console.log(\n `[Brick-TS] Loading application entry: ${resolve(options.entry)}`,\n );\n const app = await importEntry(options.entry, { run: true });\n if (!isBrickApp(app))\n throw new ConfigError(\n \"Brick: a worker needs an entry that default-exports a BrickApp.\",\n );\n if (!app.events)\n throw new ConfigError(\n \"Brick: this app has no events, so a worker has nothing to deliver.\",\n );\n if (!app.events.describe().dispatch)\n throw new ConfigError(\n \"Brick: this app only records events (events.dispatch is false), so a worker would deliver nothing. Enable dispatch for the worker process.\",\n );\n await buildAppWorkflows(app);\n await app.start();\n app.events.start();\n shutdownOnSignal(app);\n const listeners = app.events.describe().listeners;\n console.log(`\\n🧱 Brick-TS Worker`);\n console.log(\n ` Delivering events to ${listeners.length} ${listeners.length === 1 ? \"listener\" : \"listeners\"}: ${listeners.map((l) => l.name).join(\", \") || \"none\"}\\n`,\n );\n return app;\n}\n\n/**\n * What `brick dev` runs: start the application, restart it when its files\n * change, and serve the dashboard beside it. With an `entry`, the app runs in\n * a worker process that restarts on every change to the entry or the files it\n * imports, and reports its requests to the dashboard; without one, a server\n * with the registered services starts in this process.\n *\n * @param options - `entry`, `port` (else `PORT`, else 4000), `prefix`,\n * `clientOutput` to regenerate the typed client's contract on each start,\n * `frontend` to launch a frontend command once, and `dashboard` (`port` and\n * `historyDays`, or `false`).\n * @returns The application, when started in this process.\n * @throws When `frontend` is given without `clientOutput`, or the dashboard\n * would use the app's port.\n */\nexport async function startDevServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n if (!entry && (options.clientOutput || options.frontend))\n throw new ConfigError(\n \"Brick: --client and --frontend require an app entry.\",\n );\n if (options.frontend && !options.clientOutput)\n throw new ConfigError(\"Brick: --frontend requires --client <file>.\");\n const port = resolvePort(options.port);\n if (!entry) return startDevApplication({ port, prefix: options.prefix });\n const resolvedEntry = resolve(entry);\n if (!existsSync(resolvedEntry))\n throw new ConfigError(\n `[Brick-TS] Error: Entry file not found: ${resolvedEntry}`,\n );\n\n if (\n options.dashboard &&\n (options.dashboard.port ?? DEFAULT_DASHBOARD_PORT) === port\n )\n throw new ConfigError(\n \"Brick: dashboard port must differ from the API port. Use --dashboard-port <number>.\",\n );\n const manifest = options.manifest;\n if (manifest) await writeServiceManifest(manifest);\n const contract = resolve(\n options.clientOutput ??\n join(manifest?.generated ?? PROJECT_DEFAULTS.generated, CONTRACT_FILE),\n );\n const workerOptions: WorkerOptions = {\n entry: resolvedEntry,\n port,\n prefix: options.prefix,\n clientOutput: options.clientOutput && contract,\n telemetry: Boolean(options.dashboard),\n };\n // Bind the dashboard before the first worker starts, so the worker's spans\n // have somewhere to go.\n const dashboard = options.dashboard\n ? await openDashboard({\n port: options.dashboard.port,\n directory: process.cwd(),\n historyDays: options.dashboard.historyDays,\n warn: (message) => console.warn(message),\n docs: true,\n dashboard: {\n extension: options.dashboard.extension,\n theme: options.dashboard.theme,\n },\n restart: () => {\n void restart(\"dashboard\");\n },\n portHint: \"Use --dashboard-port <number> or --no-dashboard.\",\n })\n : undefined;\n const telemetry = dashboard?.store;\n let frontend: ReturnType<typeof Bun.spawn> | undefined;\n const dependencyFiles = new Set<string>();\n const dependencyWatchers = new Map<string, ReturnType<typeof watch>>();\n let stopped = false;\n const intentionalExits = new WeakSet<ReturnType<typeof Bun.spawn>>();\n const receive = (message: WorkerMessage, generation: number) => {\n switch (message.type) {\n case \"brick:telemetry\":\n telemetry?.ingest(message.records, generation);\n return;\n case \"brick:error\":\n telemetry?.recordWorkerError(message.phase, message.error, generation);\n return;\n case \"brick:contract-ready\":\n if (options.frontend && !frontend && !stopped)\n frontend = Bun.spawn(\n [process.env.SHELL ?? \"/bin/sh\", \"-c\", options.frontend],\n {\n detached: true,\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n },\n );\n telemetry?.recordReload({\n kind: \"contract-ready\",\n generation,\n detail: \"browser contract generated\",\n });\n return;\n case \"brick:architecture\":\n telemetry?.setArchitecture(message.architecture, generation);\n void dashboard?.setPluginExtensions(message.architecture.plugins ?? []);\n return;\n case \"brick:inspector\":\n if (generation === telemetry?.latestGeneration)\n telemetry.setInspector({ port: message.port, token: message.token });\n return;\n case \"brick:documentation\":\n void dashboard?.docs?.configure(\n dirname(resolvedEntry),\n message.documentation,\n );\n return;\n case \"brick:api-documents\":\n telemetry?.setApiDocuments(\n message.documents,\n `http://localhost:${port}`,\n );\n return;\n case \"brick:dependencies\":\n for (const file of message.files) {\n if (file === contract) continue;\n dependencyFiles.add(file);\n const directory = dirname(file);\n if (!dependencyWatchers.has(directory))\n dependencyWatchers.set(\n directory,\n watch(directory, (_event, filename) => {\n if (\n !filename ||\n !dependencyFiles.has(resolve(directory, filename))\n )\n return;\n scheduleRestart();\n }),\n );\n }\n return;\n }\n };\n const launch = () => {\n // The new process serves its own inspector once it is up.\n telemetry?.setInspector(undefined);\n const generation = telemetry?.startGeneration() ?? 0;\n const application = Bun.spawn(\n [\n process.execPath,\n ownModule(\"dev-worker\"),\n JSON.stringify(workerOptions),\n ],\n {\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n ipc: (message: WorkerMessage) => receive(message, generation),\n },\n );\n void application.exited.then((code) => {\n if (generation === telemetry?.latestGeneration)\n telemetry.setInspector(undefined);\n if (!stopped && !intentionalExits.has(application)) {\n console.error(\n `[Brick-TS] Application process exited with code ${code}. Waiting for changes to restart.`,\n );\n telemetry?.recordReload({\n kind: \"exited\",\n generation,\n detail: `exit code ${code}`,\n });\n }\n telemetry?.interruptGeneration(generation);\n });\n return application;\n };\n if (dashboard) {\n console.log(`📊 Dev dashboard: http://127.0.0.1:${dashboard.port}`);\n }\n let child = launch();\n // The worker reports the other files the entry imports (brick:dependencies).\n const watchDirs = [\n ...new Set([\n dirname(resolvedEntry),\n ...(manifest ? [manifest.services] : []),\n ]),\n ].filter(existsSync);\n let pending: ReturnType<typeof setTimeout> | undefined;\n let restarting = false;\n let dirty = false;\n\n async function restart(trigger: \"changes\" | \"dashboard\" = \"changes\") {\n dirty = true;\n if (restarting || stopped) return;\n restarting = true;\n try {\n while (dirty && !stopped) {\n dirty = false;\n console.log(\n trigger === \"changes\"\n ? \"\\n📝 Changes detected. Restarting server...\"\n : \"\\n🔄 Restart requested from the dashboard. Restarting server...\",\n );\n telemetry?.recordReload({\n kind: \"restarting\",\n generation: telemetry.latestGeneration,\n detail:\n trigger === \"changes\" ? \"source changed\" : \"restart from dashboard\",\n });\n intentionalExits.add(child);\n child.kill();\n await child.exited;\n if (!stopped) child = launch();\n }\n } finally {\n restarting = false;\n }\n }\n\n function scheduleRestart() {\n clearTimeout(pending);\n pending = setTimeout(() => {\n void restart();\n }, 100);\n }\n const extension = options.dashboard && options.dashboard.extension;\n const extensionDir =\n extension && !watchDirs.includes(dirname(resolve(extension)))\n ? `${dirname(resolve(extension))}${sep}`\n : undefined;\n const watchers = watchDirs.map((dir) =>\n watch(dir, { recursive: true }, (_event, filename) => {\n if (!filename || filename.split(/[\\\\/]/).includes(\"node_modules\")) return;\n const file = resolve(dir, filename);\n if (\n file === contract ||\n basename(file).startsWith(TEMPORARY_FILE_PREFIX) ||\n // The dashboard rebuilds its extension itself; the app restarts only\n // for the files it imports.\n (extensionDir !== undefined &&\n file.startsWith(extensionDir) &&\n !dependencyFiles.has(file))\n )\n return;\n // A definition file was added or removed: refresh the import list first.\n if (manifest && file.startsWith(manifest.services + sep)) {\n void writeServiceManifest(manifest)\n .catch((error: unknown) =>\n console.error(\"[Brick-TS] Could not write services.gen.ts:\", error),\n )\n .finally(scheduleRestart);\n return;\n }\n scheduleRestart();\n }),\n );\n const stop = () => {\n if (stopped) return;\n stopped = true;\n clearTimeout(pending);\n for (const watcher of watchers) watcher.close();\n for (const watcher of dependencyWatchers.values()) watcher.close();\n if (frontend) {\n if (process.platform === \"win32\") {\n Bun.spawnSync([\"taskkill\", \"/pid\", String(frontend.pid), \"/t\", \"/f\"]);\n } else {\n try {\n process.kill(-frontend.pid, \"SIGTERM\");\n } catch (error) {\n if (\n !(\n error instanceof Error &&\n \"code\" in error &&\n error.code === \"ESRCH\"\n )\n )\n throw error;\n }\n }\n }\n dashboard?.stop();\n child.kill();\n process.off(\"SIGINT\", onSignal);\n process.off(\"SIGTERM\", onSignal);\n process.off(\"exit\", stop);\n };\n const onSignal = (signal: NodeJS.Signals) => {\n if (stopped) {\n child.kill(\"SIGKILL\");\n process.exit(signal === \"SIGINT\" ? 130 : 143);\n }\n stop();\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n void child.exited.then(() => process.exit(0));\n };\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n process.on(\"exit\", stop);\n console.log(`\\n👀 Watching for changes in: ${watchDirs.join(\", \")}`);\n return { stop };\n}\n","import { aot } from \"elysia/plugin/aot/bun\";\nimport type { BunPlugin } from \"bun\";\n\n/** Keep the pinned Elysia beta's incomplete stripping from breaking builds. */\nexport function brickAot(entry: string, keep: boolean): BunPlugin {\n // `keep`: WS routes still need cookie setup during reconstruction in beta.29,\n // and shipped workflows mount their webhook route only when a world is set at\n // run time. Retain those modules while continuing to precompile HTTP handlers.\n if (keep) return aot(entry, { target: \"bun\", strip: false });\n return {\n name: \"brick-elysia-aot\",\n async setup(build) {\n await aot(entry, { target: \"bun\", strip: true }).setup({\n ...build,\n onLoad(options, callback) {\n return build.onLoad(options, async (args) => {\n const result = await callback(args);\n if (\n !result ||\n !(\"contents\" in result) ||\n typeof result.contents !== \"string\"\n )\n return result;\n let contents = result.contents;\n if (\n /[/\\\\]elysia[/\\\\]dist[/\\\\]ws[/\\\\]route\\.m?js$/.test(args.path) &&\n contents.includes(\n \"[elysia-aot] WebSocket route builder was stripped\",\n )\n ) {\n for (const name of [\"resolveWSOptions\", \"accumulateWSOptions\"]) {\n if (!contents.includes(`export function ${name}`))\n contents += `\\nexport function ${name}() { throw new Error(\"WebSocket support was stripped\"); }\\n`;\n }\n }\n return contents === result.contents\n ? result\n : { ...result, contents };\n });\n },\n });\n },\n };\n}\n","import { mkdtemp, mkdir, rename, rm } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { compileBrickApplication, WORKFLOW_BUNDLE } from \"@brickkit/core\";\nimport type { BunPlugin } from \"bun\";\nimport { emitCompiledApplication } from \"./compiler\";\nimport { brickAot } from \"./compiler/aot\";\nimport { loadBrickApp } from \"./app-entry\";\nimport { ownModule } from \"./own-module\";\nimport { DEFAULT_OUTDIR, resolvePort } from \"./config\";\nimport { shipWorkflows, workflowTransformPlugin } from \"./workflows\";\nimport {\n themeCss,\n writeDashboardExtension,\n type DashboardExtensionOptions,\n} from \"./dashboard-extension\";\n\nexport interface BuildApplicationOptions {\n /** A module whose default export is a BrickApp, without starting a server. */\n entry: string;\n outdir?: string;\n port?: number;\n /** Precompile Elysia's HTTP handlers at build time (default true). */\n aot?: boolean;\n /**\n * The dashboard's extension, built into `<outdir>/dashboard` with those of\n * the app's plugins for the production dashboard to serve; its theme is\n * checked here too.\n */\n dashboard?: DashboardExtensionOptions;\n}\n\n/**\n * The production dashboard stays out of the bundle: it serves files that ship\n * with @brickkit/cli, so a built server whose app asks for it imports it from\n * there at run time. Without a dashboard the bundle needs nothing installed.\n */\nconst productionDashboardAtRunTime: BunPlugin = {\n name: \"brick:production-dashboard\",\n setup(build) {\n build.onResolve({ filter: /^\\.\\/production-dashboard(\\.[jt]s)?$/ }, () => ({\n path: \"@brickkit/cli/production-dashboard\",\n external: true,\n }));\n },\n};\n\n/** The files `brick build` writes to the output folder, `server.js` last. */\nconst OUTPUTS = [\"routes.js\", \"brick-ir.json\", \"server.js.map\", \"server.js\"];\n\n/** Bundle an exported BrickApp with its compiled IR and its original configuration. */\nexport async function buildApplication(options: BuildApplicationOptions) {\n const entry = resolve(options.entry);\n if (!(await Bun.file(entry).exists()))\n throw new Error(`Brick compiler: entry not found: ${entry}`);\n const outdir = resolve(options.outdir ?? DEFAULT_OUTDIR);\n if (OUTPUTS.some((name) => entry === join(outdir, name)))\n throw new Error(\n \"Brick compiler: output would overwrite the application entry\",\n );\n const port = resolvePort(options.port, undefined, \"\");\n themeCss(options.dashboard?.theme);\n const extension = options.dashboard?.extension\n ? resolve(options.dashboard.extension)\n : undefined;\n if (extension && !(await Bun.file(extension).exists()))\n throw new Error(\n `Brick compiler: dashboard extension not found: ${extension}`,\n );\n const app = await loadBrickApp(entry);\n const root = app.events?.workflows?.root ?? process.cwd();\n const services = [...app.definition.services];\n const compilation = compileBrickApplication({\n services,\n prefix: app.definition.prefix,\n });\n await mkdir(dirname(outdir), { recursive: true });\n const staging = await mkdtemp(join(dirname(outdir), \".brick-build-\"));\n try {\n await Bun.write(\n join(staging, \"routes.js\"),\n emitCompiledApplication(compilation.ir),\n );\n const dashboard = (await writeDashboardExtension(\n extension,\n app.definition.plugins ?? [],\n join(staging, \"dashboard\"),\n ))\n ? join(outdir, \"dashboard\")\n : undefined;\n const theme = JSON.stringify(options.dashboard?.theme);\n const source = `import { existsSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { loadCompiledBrickApp } from \"@brickkit/core\";\nimport { resolvePort } from ${JSON.stringify(ownModule(\"config\"))};\nimport { serveApp, shutdownOnSignal } from ${JSON.stringify(ownModule(\"serve\"))};\nconst workflows = fileURLToPath(new URL(${JSON.stringify(`./${WORKFLOW_BUNDLE.dir}`)}, import.meta.url));\nexport const app = await loadCompiledBrickApp(() => import(${JSON.stringify(entry)}), undefined, {\n workflows: existsSync(workflows) ? workflows : undefined,\n});\nexport default app;\nif (import.meta.main) {\n await serveApp(app, {\n port: resolvePort(undefined, ${port}),\n dashboard: { extension: ${dashboard ? 'fileURLToPath(new URL(\"./dashboard\", import.meta.url))' : \"undefined\"}, theme: ${theme} },\n });\n console.log(\"Brick compiled server listening on http://localhost:\" + app.server.port);\n shutdownOnSignal(app);\n}\n`;\n await Bun.write(join(staging, \"entry.ts\"), source);\n // Whether to ship workflows depends on the files the bundle holds, not on\n // the env: an app may declare its workflow listeners only at run time.\n let directives = false;\n const transform = await workflowTransformPlugin(root, () => {\n directives = true;\n });\n const result = await Bun.build({\n entrypoints: [join(staging, \"entry.ts\")],\n target: \"bun\",\n format: \"esm\",\n outdir: staging,\n naming: \"server.js\",\n sourcemap: \"external\",\n // AOT first: the workflow plugin loads every project file it sees, so after\n // it the AOT plugin would never get to transform the entry.\n plugins: [\n ...(options.aot === false\n ? []\n : [\n brickAot(\n join(staging, \"entry.ts\"),\n app.definition.sockets.length > 0 || transform !== undefined,\n ),\n ]),\n ...(transform ? [transform] : []),\n productionDashboardAtRunTime,\n ],\n });\n if (!result.success)\n throw new AggregateError(result.logs, \"Brick compiler: bundling failed\");\n const workflows =\n (directives || Boolean(app.events?.workflows)) &&\n (await shipWorkflows(root, staging, Boolean(app.events?.workflows)));\n await Bun.write(\n join(staging, \"brick-ir.json\"),\n JSON.stringify(compilation.ir, null, 2) + \"\\n\",\n );\n await mkdir(outdir, { recursive: true });\n for (const name of OUTPUTS)\n await rename(join(staging, name), join(outdir, name));\n // Only the bundle is ours: other files under .well-known stay.\n const bundle = join(outdir, WORKFLOW_BUNDLE.dir);\n await rm(bundle, { recursive: true, force: true });\n if (workflows) {\n await mkdir(dirname(bundle), { recursive: true });\n await rename(join(staging, WORKFLOW_BUNDLE.dir), bundle);\n }\n if (dashboard) {\n await rm(dashboard, { recursive: true, force: true });\n await rename(join(staging, \"dashboard\"), dashboard);\n }\n return {\n outdir,\n entry: join(outdir, \"server.js\"),\n ir: compilation.ir,\n dashboard,\n workflows: workflows ? join(outdir, WORKFLOW_BUNDLE.dir) : undefined,\n };\n } finally {\n await rm(staging, { recursive: true, force: true });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,MAAM,QAAmC,CAAC,WAAW,UAAU;AAE/D,SAAS,KAAK,MAAc;CAC1B,MAAM,QAAQ,MAAM,QAClB,gBAAgB,KAAK,IAAI,CAAC,GAAG,EAC/B;CACA,OAAO,UAAU,KAAK,MAAM,SAAS;AACvC;;AAGA,SAAgB,oBAAoB,UAA4B;CAC9D,IAAI,CAAC,WAAW,QAAQ,GAAG,OAAO,CAAC;CASnC,OAHc,CAAC,GAAG,IAHD,IAAI,KACnB,SAAS,iBAAiB,KAAK,GAAG,EAAE,KAAK,sBAAsB,KAAK,GAAG,EAAE,EAEtD,CAAC,CAAC,SAAS;EAAE,KAAK;EAAU,WAAW;CAAK,CAAC,CAAC,CAAC,CACjE,KAAK,SAAS,KAAK,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CACxC,QAAQ,SAAS,CAAC,KAAK,MAAM,GAAG,CAAC,CAAC,SAAS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U;EACR,MAAM,GAAG,SAAS;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CACpD;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -84,6 +84,7 @@ export declare function buildApplication(options: BuildApplicationOptions): Prom
|
|
|
84
84
|
entry: string;
|
|
85
85
|
ir: import("@brickkit/core").BrickIR;
|
|
86
86
|
dashboard: string | undefined;
|
|
87
|
+
workflows: string | undefined;
|
|
87
88
|
}>;
|
|
88
89
|
/** Generate browser metadata and transport types from the app's selected services. */
|
|
89
90
|
export declare function generateClientContract(app: BrickApp): string;
|
package/dist/project.js
CHANGED
|
@@ -212,7 +212,7 @@ function memberCall(node) {
|
|
|
212
212
|
};
|
|
213
213
|
}
|
|
214
214
|
// package.json
|
|
215
|
-
var version = "0.13.
|
|
215
|
+
var version = "0.13.3";
|
|
216
216
|
// src/lint/rules/checks.ts
|
|
217
217
|
const MANIFEST_STEM = MANIFEST_FILE.replace(/\.ts$/, "");
|
|
218
218
|
/** This release's range, for the `brick` field example: `^0.12.0`. */
|
package/dist/workflows.d.ts
CHANGED
|
@@ -6,10 +6,11 @@ type BunPlugin = Parameters<typeof Bun.plugin>[0];
|
|
|
6
6
|
* `brick build` hands it to `Bun.build`.
|
|
7
7
|
*
|
|
8
8
|
* @param root - The project root, where the SDK is installed. Default: the working directory.
|
|
9
|
+
* @param onDirective - Called for each file it loads that holds a `"use workflow"` function.
|
|
9
10
|
* @returns The plugin, or `undefined` when the Workflow SDK and its builders are not
|
|
10
11
|
* installed in the project.
|
|
11
12
|
*/
|
|
12
|
-
export declare function workflowTransformPlugin(root?: string): Promise<BunPlugin | undefined>;
|
|
13
|
+
export declare function workflowTransformPlugin(root?: string, onDirective?: () => void): Promise<BunPlugin | undefined>;
|
|
13
14
|
/**
|
|
14
15
|
* Make files marked `"use workflow"` or `"use step"` load as workflows and steps.
|
|
15
16
|
*
|
|
@@ -55,5 +56,17 @@ export declare function buildWorkflows(options?: {
|
|
|
55
56
|
export declare function buildAppWorkflows(app: BrickApp, options?: {
|
|
56
57
|
reuse?: boolean;
|
|
57
58
|
}): Promise<boolean>;
|
|
59
|
+
/**
|
|
60
|
+
* What `brick build` ships: the workflow bundle, built from the project and
|
|
61
|
+
* copied to `<outdir>/.well-known/workflow/v1`, where the compiled server reads
|
|
62
|
+
* it. `brick build` calls it when the bundle holds a `"use workflow"` function, or
|
|
63
|
+
* the loaded app runs workflows.
|
|
64
|
+
*
|
|
65
|
+
* @param root - The project root.
|
|
66
|
+
* @param outdir - Where the compiled server is written.
|
|
67
|
+
* @param required - The loaded app runs workflows, so the SDK must be installed.
|
|
68
|
+
* @returns Whether a bundle was shipped: it holds a workflow, or one is required.
|
|
69
|
+
*/
|
|
70
|
+
export declare function shipWorkflows(root: string, outdir: string, required: boolean): Promise<boolean>;
|
|
58
71
|
export {};
|
|
59
72
|
//# sourceMappingURL=workflows.d.ts.map
|
package/dist/workflows.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as buildAppWorkflows, n as buildWorkflows, r as registerWorkflowTransform, i as workflowTransformPlugin } from "./workflows2.js";
|
|
1
|
+
export { t as buildAppWorkflows, n as buildWorkflows, r as registerWorkflowTransform, i as shipWorkflows, a as workflowTransformPlugin } from "./workflows2.js";
|
package/dist/workflows2.js
CHANGED
|
@@ -4,7 +4,7 @@ import { existsSync, readFileSync } from "node:fs";
|
|
|
4
4
|
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
5
5
|
import { WORKFLOW_BUNDLE, resolveWorkflowPaths } from "@brickkit/core";
|
|
6
6
|
import { pathToFileURL } from "node:url";
|
|
7
|
-
import { readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
7
|
+
import { cp, readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
8
8
|
// src/workflows.ts
|
|
9
9
|
const DIRECTIVE = /["']use (?:step|workflow)["']/;
|
|
10
10
|
/**
|
|
@@ -37,11 +37,12 @@ async function loadBuilders(root) {
|
|
|
37
37
|
* `brick build` hands it to `Bun.build`.
|
|
38
38
|
*
|
|
39
39
|
* @param root - The project root, where the SDK is installed. Default: the working directory.
|
|
40
|
+
* @param onDirective - Called for each file it loads that holds a `"use workflow"` function.
|
|
40
41
|
* @returns The plugin, or `undefined` when the Workflow SDK and its builders are not
|
|
41
42
|
* installed in the project.
|
|
42
43
|
*/
|
|
43
|
-
async function workflowTransformPlugin(root = process.cwd()) {
|
|
44
|
-
const load = await transformer(root);
|
|
44
|
+
async function workflowTransformPlugin(root = process.cwd(), onDirective) {
|
|
45
|
+
const load = await transformer(root, onDirective);
|
|
45
46
|
if (!load) return void 0;
|
|
46
47
|
return {
|
|
47
48
|
name: "brick:workflows",
|
|
@@ -51,7 +52,7 @@ async function workflowTransformPlugin(root = process.cwd()) {
|
|
|
51
52
|
};
|
|
52
53
|
}
|
|
53
54
|
/** The transform for files of the project at `root`, or `undefined` without the SDK. */
|
|
54
|
-
async function transformer(root) {
|
|
55
|
+
async function transformer(root, onDirective) {
|
|
55
56
|
const projectRoot = resolve(root);
|
|
56
57
|
const builders = (await loadBuilders(projectRoot))?.builders;
|
|
57
58
|
if (!builders) return void 0;
|
|
@@ -61,6 +62,7 @@ async function transformer(root) {
|
|
|
61
62
|
contents: source,
|
|
62
63
|
loader: loaderFor(args.path)
|
|
63
64
|
};
|
|
65
|
+
if (onDirective && builders.detectWorkflowPatterns(source).hasUseWorkflow) onDirective();
|
|
64
66
|
return builders.applySwcTransform(relative(projectRoot, args.path).replaceAll("\\", "/"), source, "step", args.path, projectRoot, projectRoot).then(({ code }) => ({
|
|
65
67
|
contents: code,
|
|
66
68
|
loader: "jsx"
|
|
@@ -307,6 +309,7 @@ async function buildAppWorkflows(app, options = {}) {
|
|
|
307
309
|
const target = app.events?.workflows;
|
|
308
310
|
if (!target) return false;
|
|
309
311
|
if (registered.size && !registered.has(resolve(target.root))) throw new ConfigError(`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.`);
|
|
312
|
+
if (target.shipped) return true;
|
|
310
313
|
const started = performance.now();
|
|
311
314
|
if (await buildWorkflows({
|
|
312
315
|
root: target.root,
|
|
@@ -314,6 +317,30 @@ async function buildAppWorkflows(app, options = {}) {
|
|
|
314
317
|
})) console.log(`[Brick-TS] Built workflows in ${Math.round(performance.now() - started)}ms`);
|
|
315
318
|
return true;
|
|
316
319
|
}
|
|
317
|
-
|
|
320
|
+
/**
|
|
321
|
+
* What `brick build` ships: the workflow bundle, built from the project and
|
|
322
|
+
* copied to `<outdir>/.well-known/workflow/v1`, where the compiled server reads
|
|
323
|
+
* it. `brick build` calls it when the bundle holds a `"use workflow"` function, or
|
|
324
|
+
* the loaded app runs workflows.
|
|
325
|
+
*
|
|
326
|
+
* @param root - The project root.
|
|
327
|
+
* @param outdir - Where the compiled server is written.
|
|
328
|
+
* @param required - The loaded app runs workflows, so the SDK must be installed.
|
|
329
|
+
* @returns Whether a bundle was shipped: it holds a workflow, or one is required.
|
|
330
|
+
*/
|
|
331
|
+
async function shipWorkflows(root, outdir, required) {
|
|
332
|
+
await buildWorkflows({ root });
|
|
333
|
+
const dir = join(resolve(root), WORKFLOW_BUNDLE.dir);
|
|
334
|
+
const manifest = JSON.parse(await readFile(join(dir, WORKFLOW_BUNDLE.manifest), "utf8"));
|
|
335
|
+
if (!required && !Object.keys(manifest.workflows ?? {}).length) return false;
|
|
336
|
+
for (const name of [
|
|
337
|
+
WORKFLOW_BUNDLE.flow,
|
|
338
|
+
WORKFLOW_BUNDLE.steps,
|
|
339
|
+
WORKFLOW_BUNDLE.webhook,
|
|
340
|
+
WORKFLOW_BUNDLE.manifest
|
|
341
|
+
]) await cp(join(dir, name), join(outdir, WORKFLOW_BUNDLE.dir, name));
|
|
342
|
+
return true;
|
|
343
|
+
}
|
|
344
|
+
export { workflowTransformPlugin as a, shipWorkflows as i, buildWorkflows as n, registerWorkflowTransform as r, buildAppWorkflows as t };
|
|
318
345
|
|
|
319
346
|
//# sourceMappingURL=workflows2.js.map
|
package/dist/workflows2.js.map
CHANGED
|
@@ -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,KAAK,EAAE,2BAChF;;AAGA,SAAS,UAAU,MAA2C;CAC5D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A,MAAM,UAAU,MAAM,eAAe,MAAM,QAAQ,iBAAiB,CAAC;CACrE,MAAM,MAAM,KAAK,UAAU;EACzB;EACA,OAAO;EAEP,MAAM,OAAO,OAAO;EAEpB,GAAG;GACD;GACA;GACA;GACA;GACA;EACF,CAAC,CAAC,KAAK,SAAS,QAAQ,IAAI,SAAS,EAAE;CACzC,CAAC;CACD,MAAM,UAAU,MAAM,QAAQ,cAAc;CAC5C,IACE,QAAQ,SACP,MAAM,UAAU,WAAW,KAAK,SAAS,UAAU,OAAO,GAE3D,OAAO;CAET,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC;CACnC,MAAM,YAAY,KAAK,IAAI;CAC3B,MAAM,QAAQ,MAAM;CACpB,IAAI;EACF,MAAM,YACJ,WACA,KACA,SACA,UACA,MACA,KACA,SACA;GAAC,KAAK,MAAM,cAAc;GAAG,WAAW,IAAI;GAAG,GAAG;EAAO,GACzD,SACF;CACF,QAAQ,CAER;CACA,OAAO;AACT;;;;;;;;AASA,eAAsB,kBACpB,KACA,UAA+B,CAAC,GACd;CAClB,MAAM,SAAS,IAAI,QAAQ;CAC3B,IAAI,CAAC,QAAQ,OAAO;CAGpB,IAAI,WAAW,QAAQ,CAAC,WAAW,IAAI,QAAQ,OAAO,IAAI,CAAC,GACzD,MAAM,IAAI,YACR,mCAAmC,OAAO,KAAK,+DAA+D,CAAC,GAAG,WAAW,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,4EAClJ;CACF,MAAM,UAAU,YAAY,IAAI;CAKhC,IAAI,MAJgB,eAAe;EACjC,MAAM,OAAO;EACb,OAAO,QAAQ;CACjB,CAAC,GAEC,QAAQ,IACN,iCAAiC,KAAK,MAAM,YAAY,IAAI,IAAI,OAAO,EAAE,GAC3E;CACF,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"workflows2.js","names":[],"sources":["../src/workflows.ts"],"sourcesContent":["import { existsSync, 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;CAChD,IAAI,CAAC,MAAM,OAAO,KAAA;CAClB,OA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nE,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@brickkit/cli",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.3",
|
|
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.
|
|
96
|
+
"@brickkit/core": "^0.13.3",
|
|
97
97
|
"@opentelemetry/api": "^1.10.0",
|
|
98
98
|
"@opentelemetry/context-async-hooks": "^3.0.0",
|
|
99
99
|
"@opentelemetry/core": "^3.0.0",
|