@brickkit/cli 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +13 -3
  2. package/dashboard-dist/{CollapsiblePanel-DM8J3g8m.js → CollapsiblePanel-a54TwMKb.js} +1 -1
  3. package/dashboard-dist/{PopoverPopup-B6eMOlOC.js → PopoverPopup-BLzjTqsi.js} +1 -1
  4. package/dashboard-dist/{api-reference-wTdT1AVt.js → api-reference-r893F8zi.js} +2 -2
  5. package/dashboard-dist/app.css +1 -1
  6. package/dashboard-dist/app.js +13 -13
  7. package/dashboard-dist/core-BWAwhSFf.js +1 -0
  8. package/dashboard-dist/{docs-DflzpIIh.js → docs-CkMy3Y5i.js} +1 -1
  9. package/dashboard-dist/{preload-helper-CVJ-D494.js → preload-helper-CjQDFR0M.js} +1 -1
  10. package/dist/app-entry2.js +8 -1
  11. package/dist/app-entry2.js.map +1 -1
  12. package/dist/bin.js +6 -2
  13. package/dist/bin.js.map +1 -1
  14. package/dist/build.js +18 -5
  15. package/dist/build.js.map +1 -1
  16. package/dist/dev-telemetry-store.js +148 -5
  17. package/dist/dev-telemetry-store.js.map +1 -1
  18. package/dist/dev-telemetry.js.map +1 -1
  19. package/dist/dev-worker.js +19 -2
  20. package/dist/dev-worker.js.map +1 -1
  21. package/dist/index.d.ts +14 -0
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +2 -2
  24. package/dist/runner.js +69 -3
  25. package/dist/runner.js.map +1 -1
  26. package/dist/workflows.d.ts +61 -0
  27. package/dist/workflows.d.ts.map +1 -0
  28. package/dist/workflows.js +1 -0
  29. package/dist/workflows2.js +298 -0
  30. package/dist/workflows2.js.map +1 -0
  31. package/inspector-dist/LICENSE.md +201 -0
  32. package/inspector-dist/NOTICE +20 -0
  33. package/inspector-dist/client/assets/api.rpc-l0sNRNKZ.js +1 -0
  34. package/inspector-dist/client/assets/api.stream._streamId-l0sNRNKZ.js +1 -0
  35. package/inspector-dist/client/assets/app-CY7CQBRo.css +1 -0
  36. package/inspector-dist/client/assets/entry.client-BJ6G3n5t.js +11697 -0
  37. package/inspector-dist/client/assets/highlighted-body-B3W2YXNL-C-3wZnxf.js +19 -0
  38. package/inspector-dist/client/assets/home-CSKAS4P2.js +4979 -0
  39. package/inspector-dist/client/assets/index-DECCyMR0.js +4482 -0
  40. package/inspector-dist/client/assets/index-Dot7CgrA.js +9837 -0
  41. package/inspector-dist/client/assets/index-HqNj_XIX.js +200 -0
  42. package/inspector-dist/client/assets/manifest-4baa7c6f.js +1 -0
  43. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-DC0K8uTy.js +58626 -0
  44. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-F88p7PFX.css +1 -0
  45. package/inspector-dist/client/assets/root-Bmn5n3jF.js +305 -0
  46. package/inspector-dist/client/assets/root-CfCr265_.css +1 -0
  47. package/inspector-dist/client/assets/run-detail-CWoGxu_0.css +1 -0
  48. package/inspector-dist/client/assets/run-detail-Cc7tSGNq.js +6237 -0
  49. package/inspector-dist/client/assets/world-config-context-BAD1QCrR.js +26 -0
  50. package/inspector-dist/client/assets/zstd-B5R2yJjB.wasm +0 -0
  51. package/inspector-dist/client/assets/zstd-browser-decoder-BQoRpP7L.js +28 -0
  52. package/inspector-dist/server/assets/app-C-ZVJtic.js +174880 -0
  53. package/inspector-dist/server/assets/highlighted-body-B3W2YXNL-C8sq8F_D.js +71 -0
  54. package/inspector-dist/server/assets/index-BfLBLRRi.js +204 -0
  55. package/inspector-dist/server/assets/index-BzrGWk7J.js +1164 -0
  56. package/inspector-dist/server/assets/index-CWJr34WJ.js +1296 -0
  57. package/inspector-dist/server/assets/index-CYlmUaKx.js +191 -0
  58. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-Dv5rjfMN.js +58 -0
  59. package/inspector-dist/server/assets/token-DnLp3wBO.js +95 -0
  60. package/inspector-dist/server/assets/token-util-Bpfp-B0w.js +33 -0
  61. package/inspector-dist/server/assets/wrapper-D5LIcZ_u.js +67 -0
  62. package/inspector-dist/server/assets/zstd-browser-decoder-BM8GpVB8.js +77 -0
  63. package/inspector-dist/server/index.js +58 -0
  64. package/package.json +12 -4
  65. package/dashboard-dist/core-CHWYtApw.js +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"dev-telemetry.js","names":[],"sources":["../src/dev-telemetry.ts"],"sourcesContent":["import {\n context,\n propagation,\n SpanStatusCode,\n trace,\n type Attributes,\n type HrTime,\n} from \"@opentelemetry/api\";\nimport { AsyncLocalStorageContextManager } from \"@opentelemetry/context-async-hooks\";\nimport { W3CTraceContextPropagator } from \"@opentelemetry/core\";\nimport {\n BasicTracerProvider,\n type ReadableSpan,\n type Span,\n type SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\nimport type {\n ApiDocument,\n ArchitectureSchema,\n DocumentationOptions,\n} from \"@brickkit/core\";\n\n/** Read by @brickkit/core's logger; see `createLogger` there. */\nconst LOG_CAPTURE = Symbol.for(\"brickkit.logs.capture\");\n/** Core's function that records a line on the running span; see `recordActive` there. */\nconst LOG_RECORD = Symbol.for(\"brickkit.logs.record\");\nconst CONSOLE_CAPTURED = Symbol.for(\"brickkit.console.captured\");\n\nconst CONSOLE_LEVELS = {\n log: \"info\",\n info: \"info\",\n warn: \"warn\",\n error: \"error\",\n debug: \"debug\",\n} as const;\n\nconst MAX_TEXT_LENGTH = 500;\nconst MAX_STACK_LENGTH = 4000;\nconst FLUSH_DELAY_MS = 20;\nconst MAX_BATCH_SIZE = 200;\nconst SEND_TIMEOUT_MS = 1000;\n\nexport interface SpanEventRecord {\n name: string;\n timeMs: number;\n attributes: Attributes;\n}\n\nexport interface SpanStartRecord {\n phase: \"start\";\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n name: string;\n startMs: number;\n attributes: Attributes;\n}\n\nexport interface SpanEndRecord {\n phase: \"end\";\n traceId: string;\n spanId: string;\n name: string;\n endMs: number;\n status: \"unset\" | \"ok\" | \"error\";\n statusMessage?: string;\n attributes: Attributes;\n events: SpanEventRecord[];\n}\n\nexport type TelemetryRecord = SpanStartRecord | SpanEndRecord;\n\nexport type WorkerErrorPhase = \"startup\" | \"uncaught\" | \"unhandled-rejection\";\n\nexport interface SerializedError {\n name: string;\n message: string;\n stack?: string;\n}\n\n/** Messages the dev worker sends to the supervisor over the IPC channel. */\nexport type WorkerMessage =\n | { type: \"brick:telemetry\"; records: TelemetryRecord[] }\n | { type: \"brick:error\"; phase: WorkerErrorPhase; error: SerializedError }\n | { type: \"brick:architecture\"; architecture: ArchitectureSchema }\n | { type: \"brick:api-documents\"; documents: ApiDocument[] }\n | {\n type: \"brick:documentation\";\n /** The app's `documentation` option; absent when it has none. */\n documentation?: DocumentationOptions;\n };\n\n/**\n * Register the tracer provider, context manager, and W3C trace context\n * propagator. Span records are batched and passed to `onRecords`. Returns false\n * when another tracer provider was already registered, in which case\n * `onRecords` never runs.\n */\nexport function installTracing(\n onRecords: (records: TelemetryRecord[]) => void,\n): boolean {\n const batcher = new RecordBatcher(onRecords);\n const registered = trace.setGlobalTracerProvider(\n new BasicTracerProvider({\n spanProcessors: [new SupervisorSpanProcessor(batcher)],\n }),\n );\n context.setGlobalContextManager(\n new AsyncLocalStorageContextManager().enable(),\n );\n propagation.setGlobalPropagator(new W3CTraceContextPropagator());\n // From here the dashboard shows what actions and tools log, as span events,\n // so @brickkit/core stops printing it. The key is shared by name because the\n // app and the dev server may each hold their own copy of core.\n if (registered) {\n (globalThis as Record<symbol, unknown>)[LOG_CAPTURE] = true;\n captureConsole();\n }\n return registered;\n}\n\ntype Restore = () => void;\n\n/**\n * Send `console.log`, `info`, `warn`, `error`, and `debug` to the dashboard\n * while a traced request is running, as `ctx.logger` does, so code that logs\n * with `console` needs no change. Lines logged outside a request print as\n * usual. Only a dashboard turns this on, `brick dev`'s or the monitoring one\n * of `brick start`: with neither, the console is left alone. Calling it again\n * does nothing; the returned function puts the console back.\n */\nexport function captureConsole(): Restore {\n const target = console as unknown as Record<string | symbol, unknown>;\n const existing = target[CONSOLE_CAPTURED];\n if (typeof existing === \"function\") return existing as Restore;\n\n const globals = globalThis as Record<symbol, unknown>;\n const originals = new Map<string, (...args: unknown[]) => void>();\n for (const [method, level] of Object.entries(CONSOLE_LEVELS)) {\n const original = target[method] as (...args: unknown[]) => void;\n originals.set(method, original);\n target[method] = function (this: unknown, ...args: unknown[]) {\n const record = globals[LOG_RECORD];\n if (\n globals[LOG_CAPTURE] === true &&\n typeof record === \"function\" &&\n record(level, args) === true\n )\n return;\n original.apply(this, args);\n };\n }\n const restore: Restore = () => {\n for (const [method, original] of originals) target[method] = original;\n delete target[CONSOLE_CAPTURED];\n };\n target[CONSOLE_CAPTURED] = restore;\n return restore;\n}\n\n/**\n * Install tracing in the dev worker, so spans from apps built with\n * `brick({ telemetry: true })` reach the supervisor and join callers' traces.\n * Call before the app entry is imported.\n */\nexport function installWorkerTelemetry(): void {\n installTracing((records) => {\n void sendToSupervisor({ type: \"brick:telemetry\", records });\n });\n}\n\n/** Resolves once the message is written, or after a short timeout if the channel is gone. */\nexport function sendToSupervisor(message: WorkerMessage): Promise<void> {\n if (!process.send) return Promise.resolve();\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, SEND_TIMEOUT_MS);\n try {\n process.send!(message, () => {\n clearTimeout(timer);\n resolve();\n });\n } catch {\n clearTimeout(timer);\n resolve();\n }\n });\n}\n\nexport function reportWorkerError(\n phase: WorkerErrorPhase,\n error: unknown,\n): Promise<void> {\n return sendToSupervisor({\n type: \"brick:error\",\n phase,\n error: serializeError(error),\n });\n}\n\nexport function serializeError(error: unknown): SerializedError {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: truncate(error.message),\n stack:\n error.stack === undefined\n ? undefined\n : truncate(error.stack, MAX_STACK_LENGTH),\n };\n }\n return { name: \"Error\", message: truncate(String(error)) };\n}\n\nfunction truncate(text: string, limit = MAX_TEXT_LENGTH): string {\n return text.length > limit ? `${text.slice(0, limit)}…` : text;\n}\n\nfunction toMs(time: HrTime): number {\n return time[0] * 1000 + time[1] / 1e6;\n}\n\nfunction statusName(code: SpanStatusCode): \"unset\" | \"ok\" | \"error\" {\n if (code === SpanStatusCode.ERROR) return \"error\";\n if (code === SpanStatusCode.OK) return \"ok\";\n return \"unset\";\n}\n\nfunction boundAttributes(attributes: Attributes | undefined): Attributes {\n const bounded: Attributes = {};\n for (const [key, value] of Object.entries(attributes ?? {})) {\n bounded[key] =\n typeof value === \"string\" ? truncate(value, MAX_STACK_LENGTH) : value;\n }\n return bounded;\n}\n\nclass RecordBatcher {\n #records: TelemetryRecord[] = [];\n #timer: ReturnType<typeof setTimeout> | undefined;\n readonly #send: (records: TelemetryRecord[]) => void;\n\n constructor(send: (records: TelemetryRecord[]) => void) {\n this.#send = send;\n }\n\n push(record: TelemetryRecord): void {\n this.#records.push(record);\n if (this.#records.length >= MAX_BATCH_SIZE) this.flush();\n else this.#timer ??= setTimeout(() => this.flush(), FLUSH_DELAY_MS);\n }\n\n flush(): void {\n clearTimeout(this.#timer);\n this.#timer = undefined;\n if (this.#records.length === 0) return;\n const records = this.#records;\n this.#records = [];\n this.#send(records);\n }\n}\n\nclass SupervisorSpanProcessor implements SpanProcessor {\n readonly #batcher: RecordBatcher;\n\n constructor(batcher: RecordBatcher) {\n this.#batcher = batcher;\n }\n\n onStart(span: Span): void {\n const { traceId, spanId } = span.spanContext();\n this.#batcher.push({\n phase: \"start\",\n traceId,\n spanId,\n parentSpanId: span.parentSpanContext?.spanId,\n name: span.name,\n startMs: toMs(span.startTime),\n attributes: boundAttributes(span.attributes),\n });\n }\n\n onEnd(span: ReadableSpan): void {\n const { traceId, spanId } = span.spanContext();\n this.#batcher.push({\n phase: \"end\",\n traceId,\n spanId,\n name: span.name,\n endMs: toMs(span.endTime),\n status: statusName(span.status.code),\n statusMessage: span.status.message,\n attributes: boundAttributes(span.attributes),\n events: span.events.map((event) => ({\n name: event.name,\n timeMs: toMs(event.time),\n attributes: boundAttributes(event.attributes),\n })),\n });\n }\n\n async forceFlush(): Promise<void> {\n this.#batcher.flush();\n }\n\n async shutdown(): Promise<void> {\n this.#batcher.flush();\n }\n}\n"],"mappings":";;;;;;AAuBA,MAAM,cAAc,OAAO,IAAI,uBAAuB;;AAEtD,MAAM,aAAa,OAAO,IAAI,sBAAsB;AACpD,MAAM,mBAAmB,OAAO,IAAI,2BAA2B;AAE/D,MAAM,iBAAiB;CACrB,KAAK;CACL,MAAM;CACN,MAAM;CACN,OAAO;CACP,OAAO;AACT;AAEA,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;;;;;;;AA0DxB,SAAgB,eACd,WACS;CACT,MAAM,UAAU,IAAI,cAAc,SAAS;CAC3C,MAAM,aAAa,MAAM,wBACvB,IAAI,oBAAoB,EACtB,gBAAgB,CAAC,IAAI,wBAAwB,OAAO,CAAC,EACvD,CAAC,CACH;CACA,QAAQ,wBACN,IAAI,gCAAgC,CAAC,CAAC,OAAO,CAC/C;CACA,YAAY,oBAAoB,IAAI,0BAA0B,CAAC;CAI/D,IAAI,YAAY;EACd,WAAwC,eAAe;EACvD,eAAe;CACjB;CACA,OAAO;AACT;;;;;;;;;AAYA,SAAgB,iBAA0B;CACxC,MAAM,SAAS;CACf,MAAM,WAAW,OAAO;CACxB,IAAI,OAAO,aAAa,YAAY,OAAO;CAE3C,MAAM,UAAU;CAChB,MAAM,4BAAY,IAAI,IAA0C;CAChE,KAAK,MAAM,CAAC,QAAQ,UAAU,OAAO,QAAQ,cAAc,GAAG;EAC5D,MAAM,WAAW,OAAO;EACxB,UAAU,IAAI,QAAQ,QAAQ;EAC9B,OAAO,UAAU,SAAyB,GAAG,MAAiB;GAC5D,MAAM,SAAS,QAAQ;GACvB,IACE,QAAQ,iBAAiB,QACzB,OAAO,WAAW,cAClB,OAAO,OAAO,IAAI,MAAM,MAExB;GACF,SAAS,MAAM,MAAM,IAAI;E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,WAAW;IAClC,MAAM,MAAM;IACZ,QAAQ,KAAK,MAAM,IAAI;IACvB,YAAY,gBAAgB,MAAM,UAAU;GAC9C,EAAE;EACJ,CAAC;CACH;CAEA,MAAM,aAA4B;EAChC,KAAK,SAAS,MAAM;CACtB;CAEA,MAAM,WAA0B;EAC9B,KAAK,SAAS,MAAM;CACtB;AACF"}
1
+ {"version":3,"file":"dev-telemetry.js","names":[],"sources":["../src/dev-telemetry.ts"],"sourcesContent":["import {\n context,\n propagation,\n SpanStatusCode,\n trace,\n type Attributes,\n type HrTime,\n} from \"@opentelemetry/api\";\nimport { AsyncLocalStorageContextManager } from \"@opentelemetry/context-async-hooks\";\nimport { W3CTraceContextPropagator } from \"@opentelemetry/core\";\nimport {\n BasicTracerProvider,\n type ReadableSpan,\n type Span,\n type SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\nimport type {\n ApiDocument,\n ArchitectureSchema,\n DocumentationOptions,\n} from \"@brickkit/core\";\n\n/** Read by @brickkit/core's logger; see `createLogger` there. */\nconst LOG_CAPTURE = Symbol.for(\"brickkit.logs.capture\");\n/** Core's function that records a line on the running span; see `recordActive` there. */\nconst LOG_RECORD = Symbol.for(\"brickkit.logs.record\");\nconst CONSOLE_CAPTURED = Symbol.for(\"brickkit.console.captured\");\n\nconst CONSOLE_LEVELS = {\n log: \"info\",\n info: \"info\",\n warn: \"warn\",\n error: \"error\",\n debug: \"debug\",\n} as const;\n\nconst MAX_TEXT_LENGTH = 500;\nconst MAX_STACK_LENGTH = 4000;\nconst FLUSH_DELAY_MS = 20;\nconst MAX_BATCH_SIZE = 200;\nconst SEND_TIMEOUT_MS = 1000;\n\nexport interface SpanEventRecord {\n name: string;\n timeMs: number;\n attributes: Attributes;\n}\n\nexport interface SpanStartRecord {\n phase: \"start\";\n traceId: string;\n spanId: string;\n parentSpanId?: string;\n name: string;\n startMs: number;\n attributes: Attributes;\n}\n\nexport interface SpanEndRecord {\n phase: \"end\";\n traceId: string;\n spanId: string;\n name: string;\n endMs: number;\n status: \"unset\" | \"ok\" | \"error\";\n statusMessage?: string;\n attributes: Attributes;\n events: SpanEventRecord[];\n}\n\nexport type TelemetryRecord = SpanStartRecord | SpanEndRecord;\n\nexport type WorkerErrorPhase = \"startup\" | \"uncaught\" | \"unhandled-rejection\";\n\nexport interface SerializedError {\n name: string;\n message: string;\n stack?: string;\n}\n\n/** Messages the dev worker sends to the supervisor over the IPC channel. */\nexport type WorkerMessage =\n | { type: \"brick:telemetry\"; records: TelemetryRecord[] }\n | { type: \"brick:error\"; phase: WorkerErrorPhase; error: SerializedError }\n | { type: \"brick:architecture\"; architecture: ArchitectureSchema }\n | { type: \"brick:api-documents\"; documents: ApiDocument[] }\n | {\n type: \"brick:inspector\";\n /** The loopback port the workflow inspector listens on. */\n port: number;\n /** What the dashboard sends with each request to prove who it is. */\n token: string;\n }\n | {\n type: \"brick:documentation\";\n /** The app's `documentation` option; absent when it has none. */\n documentation?: DocumentationOptions;\n };\n\n/**\n * Register the tracer provider, context manager, and W3C trace context\n * propagator. Span records are batched and passed to `onRecords`. Returns false\n * when another tracer provider was already registered, in which case\n * `onRecords` never runs.\n */\nexport function installTracing(\n onRecords: (records: TelemetryRecord[]) => void,\n): boolean {\n const batcher = new RecordBatcher(onRecords);\n const registered = trace.setGlobalTracerProvider(\n new BasicTracerProvider({\n spanProcessors: [new SupervisorSpanProcessor(batcher)],\n }),\n );\n context.setGlobalContextManager(\n new AsyncLocalStorageContextManager().enable(),\n );\n propagation.setGlobalPropagator(new W3CTraceContextPropagator());\n // From here the dashboard shows what actions and tools log, as span events,\n // so @brickkit/core stops printing it. The key is shared by name because the\n // app and the dev server may each hold their own copy of core.\n if (registered) {\n (globalThis as Record<symbol, unknown>)[LOG_CAPTURE] = true;\n captureConsole();\n }\n return registered;\n}\n\ntype Restore = () => void;\n\n/**\n * Send `console.log`, `info`, `warn`, `error`, and `debug` to the dashboard\n * while a traced request is running, as `ctx.logger` does, so code that logs\n * with `console` needs no change. Lines logged outside a request print as\n * usual. Only a dashboard turns this on, `brick dev`'s or the monitoring one\n * of `brick start`: with neither, the console is left alone. Calling it again\n * does nothing; the returned function puts the console back.\n */\nexport function captureConsole(): Restore {\n const target = console as unknown as Record<string | symbol, unknown>;\n const existing = target[CONSOLE_CAPTURED];\n if (typeof existing === \"function\") return existing as Restore;\n\n const globals = globalThis as Record<symbol, unknown>;\n const originals = new Map<string, (...args: unknown[]) => void>();\n for (const [method, level] of Object.entries(CONSOLE_LEVELS)) {\n const original = target[method] as (...args: unknown[]) => void;\n originals.set(method, original);\n target[method] = function (this: unknown, ...args: unknown[]) {\n const record = globals[LOG_RECORD];\n if (\n globals[LOG_CAPTURE] === true &&\n typeof record === \"function\" &&\n record(level, args) === true\n )\n return;\n original.apply(this, args);\n };\n }\n const restore: Restore = () => {\n for (const [method, original] of originals) target[method] = original;\n delete target[CONSOLE_CAPTURED];\n };\n target[CONSOLE_CAPTURED] = restore;\n return restore;\n}\n\n/**\n * Install tracing in the dev worker, so spans from apps built with\n * `brick({ telemetry: true })` reach the supervisor and join callers' traces.\n * Call before the app entry is imported.\n */\nexport function installWorkerTelemetry(): void {\n installTracing((records) => {\n void sendToSupervisor({ type: \"brick:telemetry\", records });\n });\n}\n\n/** Resolves once the message is written, or after a short timeout if the channel is gone. */\nexport function sendToSupervisor(message: WorkerMessage): Promise<void> {\n if (!process.send) return Promise.resolve();\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, SEND_TIMEOUT_MS);\n try {\n process.send!(message, () => {\n clearTimeout(timer);\n resolve();\n });\n } catch {\n clearTimeout(timer);\n resolve();\n }\n });\n}\n\nexport function reportWorkerError(\n phase: WorkerErrorPhase,\n error: unknown,\n): Promise<void> {\n return sendToSupervisor({\n type: \"brick:error\",\n phase,\n error: serializeError(error),\n });\n}\n\nexport function serializeError(error: unknown): SerializedError {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: truncate(error.message),\n stack:\n error.stack === undefined\n ? undefined\n : truncate(error.stack, MAX_STACK_LENGTH),\n };\n }\n return { name: \"Error\", message: truncate(String(error)) };\n}\n\nfunction truncate(text: string, limit = MAX_TEXT_LENGTH): string {\n return text.length > limit ? `${text.slice(0, limit)}…` : text;\n}\n\nfunction toMs(time: HrTime): number {\n return time[0] * 1000 + time[1] / 1e6;\n}\n\nfunction statusName(code: SpanStatusCode): \"unset\" | \"ok\" | \"error\" {\n if (code === SpanStatusCode.ERROR) return \"error\";\n if (code === SpanStatusCode.OK) return \"ok\";\n return \"unset\";\n}\n\nfunction boundAttributes(attributes: Attributes | undefined): Attributes {\n const bounded: Attributes = {};\n for (const [key, value] of Object.entries(attributes ?? {})) {\n bounded[key] =\n typeof value === \"string\" ? truncate(value, MAX_STACK_LENGTH) : value;\n }\n return bounded;\n}\n\nclass RecordBatcher {\n #records: TelemetryRecord[] = [];\n #timer: ReturnType<typeof setTimeout> | undefined;\n readonly #send: (records: TelemetryRecord[]) => void;\n\n constructor(send: (records: TelemetryRecord[]) => void) {\n this.#send = send;\n }\n\n push(record: TelemetryRecord): void {\n this.#records.push(record);\n if (this.#records.length >= MAX_BATCH_SIZE) this.flush();\n else this.#timer ??= setTimeout(() => this.flush(), FLUSH_DELAY_MS);\n }\n\n flush(): void {\n clearTimeout(this.#timer);\n this.#timer = undefined;\n if (this.#records.length === 0) return;\n const records = this.#records;\n this.#records = [];\n this.#send(records);\n }\n}\n\nclass SupervisorSpanProcessor implements SpanProcessor {\n readonly #batcher: RecordBatcher;\n\n constructor(batcher: RecordBatcher) {\n this.#batcher = batcher;\n }\n\n onStart(span: Span): void {\n const { traceId, spanId } = span.spanContext();\n this.#batcher.push({\n phase: \"start\",\n traceId,\n spanId,\n parentSpanId: span.parentSpanContext?.spanId,\n name: span.name,\n startMs: toMs(span.startTime),\n attributes: boundAttributes(span.attributes),\n });\n }\n\n onEnd(span: ReadableSpan): void {\n const { traceId, spanId } = span.spanContext();\n this.#batcher.push({\n phase: \"end\",\n traceId,\n spanId,\n name: span.name,\n endMs: toMs(span.endTime),\n status: statusName(span.status.code),\n statusMessage: span.status.message,\n attributes: boundAttributes(span.attributes),\n events: span.events.map((event) => ({\n name: event.name,\n timeMs: toMs(event.time),\n attributes: boundAttributes(event.attributes),\n })),\n });\n }\n\n async forceFlush(): Promise<void> {\n this.#batcher.flush();\n }\n\n async shutdown(): Promise<void> {\n this.#batcher.flush();\n }\n}\n"],"mappings":";;;;;;AAuBA,MAAM,cAAc,OAAO,IAAI,uBAAuB;;AAEtD,MAAM,aAAa,OAAO,IAAI,sBAAsB;AACpD,MAAM,mBAAmB,OAAO,IAAI,2BAA2B;AAE/D,MAAM,iBAAiB;CACrB,KAAK;CACL,MAAM;CACN,MAAM;CACN,OAAO;CACP,OAAO;AACT;AAEA,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;;;;;;;AAiExB,SAAgB,eACd,WACS;CACT,MAAM,UAAU,IAAI,cAAc,SAAS;CAC3C,MAAM,aAAa,MAAM,wBACvB,IAAI,oBAAoB,EACtB,gBAAgB,CAAC,IAAI,wBAAwB,OAAO,CAAC,EACvD,CAAC,CACH;CACA,QAAQ,wBACN,IAAI,gCAAgC,CAAC,CAAC,OAAO,CAC/C;CACA,YAAY,oBAAoB,IAAI,0BAA0B,CAAC;CAI/D,IAAI,YAAY;EACd,WAAwC,eAAe;EACvD,eAAe;CACjB;CACA,OAAO;AACT;;;;;;;;;AAYA,SAAgB,iBAA0B;CACxC,MAAM,SAAS;CACf,MAAM,WAAW,OAAO;CACxB,IAAI,OAAO,aAAa,YAAY,OAAO;CAE3C,MAAM,UAAU;CAChB,MAAM,4BAAY,IAAI,IAA0C;CAChE,KAAK,MAAM,CAAC,QAAQ,UAAU,OAAO,QAAQ,cAAc,GAAG;EAC5D,MAAM,WAAW,OAAO;EACxB,UAAU,IAAI,QAAQ,QAAQ;EAC9B,OAAO,UAAU,SAAyB,GAAG,MAAiB;GAC5D,MAAM,SAAS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AAQ,WAAW,KAAK,OAAO,IAAI;GACnC,eAAe,KAAK,OAAO;GAC3B,YAAY,gBAAgB,KAAK,UAAU;GAC3C,QAAQ,KAAK,OAAO,KAAK,WAAW;IAClC,MAAM,MAAM;IACZ,QAAQ,KAAK,MAAM,IAAI;IACvB,YAAY,gBAAgB,MAAM,UAAU;GAC9C,EAAE;EACJ,CAAC;CACH;CAEA,MAAM,aAA4B;EAChC,KAAK,SAAS,MAAM;CACtB;CAEA,MAAM,WAA0B;EAC9B,KAAK,SAAS,MAAM;CACtB;AACF"}
@@ -1,7 +1,19 @@
1
- import { i as parsePort, t as startDevApplication } from "./runner.js";
1
+ import { s as startInspector } from "./dev-telemetry-store.js";
2
+ import { a as parsePort, t as startDevApplication } from "./runner.js";
2
3
  import { i as sendToSupervisor, n as installWorkerTelemetry, r as reportWorkerError } from "./dev-telemetry.js";
3
- import { getGlobalRegistry } from "@brickkit/core";
4
+ import { getGlobalRegistry, stopAllEvents } from "@brickkit/core";
4
5
  //#region src/dev-worker.ts
6
+ let stopping = false;
7
+ const stop = () => {
8
+ if (stopping) return;
9
+ stopping = true;
10
+ Promise.race([stopAllEvents(), Bun.sleep(3e3)]).catch((error) => console.error(`[Brick-TS] Could not stop the events: ${error instanceof Error ? error.message : String(error)}`)).finally(() => process.exit(0));
11
+ };
12
+ process.on("SIGTERM", stop);
13
+ if (process.connected && typeof process.send === "function") {
14
+ process.on("SIGINT", () => {});
15
+ process.on("disconnect", stop);
16
+ } else process.on("SIGINT", stop);
5
17
  const telemetry = process.argv[6] === "1";
6
18
  let startupComplete = false;
7
19
  let reported = false;
@@ -70,6 +82,11 @@ try {
70
82
  documents
71
83
  }), (error) => console.warn(`[Brick-TS] Could not load the API documents: ${error instanceof Error ? error.message : String(error)}`));
72
84
  }
85
+ if (telemetry) startInspector(app).then((inspector) => inspector && sendToSupervisor({
86
+ type: "brick:inspector",
87
+ port: inspector.port,
88
+ token: inspector.token
89
+ }), (error) => console.warn(`[Brick-TS] Could not start the workflow inspector: ${error instanceof Error ? error.message : String(error)}`));
73
90
  if (telemetry && !app.definition.telemetry) console.warn("[Brick-TS] The dashboard shows no requests: pass { telemetry: true } to brick() in your app entry.");
74
91
  } catch (error) {
75
92
  await reportOnce("startup", error);
@@ -1 +1 @@
1
- {"version":3,"file":"dev-worker.js","names":[],"sources":["../src/dev-worker.ts"],"sourcesContent":["import { getGlobalRegistry } from \"@brickkit/core\";\nimport { startDevApplication } from \"./runner\";\nimport { parsePort } from \"./port-utils\";\nimport {\n installWorkerTelemetry,\n reportWorkerError,\n sendToSupervisor,\n} from \"./dev-telemetry\";\nimport type { WorkerErrorPhase } from \"./dev-telemetry\";\n\n// argv[6] is \"1\" when the supervisor serves the dashboard and needs spans.\nconst telemetry = process.argv[6] === \"1\";\nlet startupComplete = false;\nlet reported = false;\n\nasync function reportOnce(phase: WorkerErrorPhase, error: unknown) {\n if (!telemetry || reported) return;\n reported = true;\n await reportWorkerError(phase, error);\n}\n\nasync function exitAfterFailure(phase: WorkerErrorPhase, error: unknown) {\n await reportOnce(phase, error);\n console.error(error);\n process.exit(1);\n}\n\nif (telemetry) {\n installWorkerTelemetry();\n // Failures before the app is listening are startup failures, not crashes.\n const phaseOf = (): WorkerErrorPhase =>\n startupComplete ? \"uncaught\" : \"startup\";\n process.on(\"uncaughtException\", (error) => {\n void exitAfterFailure(phaseOf(), error);\n });\n process.on(\"unhandledRejection\", (reason) => {\n void exitAfterFailure(\n startupComplete ? \"unhandled-rejection\" : \"startup\",\n reason,\n );\n });\n}\n\n// Scan local imports so dependencies outside the app directory are watched too.\nif (process.argv[2]) {\n const files = new Set<string>();\n try {\n await Bun.build({\n entrypoints: [process.argv[2]],\n target: \"bun\",\n packages: \"external\",\n plugins: [\n {\n name: \"brick:dependencies\",\n setup(build) {\n build.onLoad({ filter: /./ }, (args) => {\n files.add(args.path);\n return undefined;\n });\n },\n },\n ],\n });\n } finally {\n process.send?.({ type: \"brick:dependencies\", files: [...files] });\n }\n}\n\ntry {\n const app = await startDevApplication({\n entry: process.argv[2],\n port: parsePort(process.argv[3] || undefined, process.env.PORT),\n prefix: process.argv[4] || undefined,\n clientOutput: process.argv[5] || undefined,\n });\n startupComplete = true;\n if (telemetry) {\n void sendToSupervisor({\n type: \"brick:architecture\",\n architecture: getGlobalRegistry().exportArchitecture(app.definition),\n });\n void sendToSupervisor({\n type: \"brick:documentation\",\n documentation: app.definition.documentation,\n });\n void app.referenceDocuments().then(\n (documents) =>\n sendToSupervisor({ type: \"brick:api-documents\", documents }),\n (error: unknown) =>\n console.warn(\n `[Brick-TS] Could not load the API documents: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n if (telemetry && !app.definition.telemetry) {\n console.warn(\n \"[Brick-TS] The dashboard shows no requests: pass { telemetry: true } to brick() in your app entry.\",\n );\n }\n} catch (error) {\n await reportOnce(\"startup\", error);\n throw error;\n}\n"],"mappings":";;;;AAWA,MAAM,YAAY,QAAQ,KAAK,OAAO;AACtC,IAAI,kBAAkB;AACtB,IAAI,WAAW;AAEf,eAAe,WAAW,OAAyB,OAAgB;CACjE,IAAI,CAAC,aAAa,UAAU;CAC5B,WAAW;CACX,MAAM,kBAAkB,OAAO,KAAK;AACtC;AAEA,eAAe,iBAAiB,OAAyB,OAAgB;CACvE,MAAM,WAAW,OAAO,KAAK;CAC7B,QAAQ,MAAM,KAAK;CACnB,QAAQ,KAAK,CAAC;AAChB;AAEA,IAAI,WAAW;CACb,uBAAuB;CAEvB,MAAM,gBACJ,kBAAkB,aAAa;CACjC,QAAQ,GAAG,sBAAsB,UAAU;EACzC,iBAAsB,QAAQ,GAAG,KAAK;CACxC,CAAC;CACD,QAAQ,GAAG,uBAAuB,WAAW;EAC3C,iBACE,kBAAkB,wBAAwB,WAC1C,MACF;CACF,CAAC;AACH;AAGA,IAAI,QAAQ,KAAK,IAAI;CACnB,MAAM,wBAAQ,IAAI,IAAY;CAC9B,IAAI;EACF,MAAM,IAAI,MAAM;GACd,aAAa,CAAC,QAAQ,KAAK,EAAE;GAC7B,QAAQ;GACR,UAAU;GACV,SAAS,CACP;IACE,MAAM;IACN,MAAM,OAAO;KACX,MAAM,OAAO,EAAE,QAAQ,IAAI,IAAI,SAAS;MACtC,MAAM,IAAI,KAAK,IAAI;KAErB,CAAC;IACH;GACF,CACF;EACF,CAAC;CACH,UAAU;EACR,QAAQ,OAAO;GAAE,MAAM;GAAsB,OAAO,CAAC,GAAG,KAAK;EAAE,CAAC;CAClE;AACF;AAEA,IAAI;CACF,MAAM,MAAM,MAAM,oBAAoB;EACpC,OAAO,QAAQ,KAAK;EACpB,MAAM,UAAU,QAAQ,KAAK,MAAM,KAAA,GAAW,QAAQ,IAAI,IAAI;EAC9D,QAAQ,QAAQ,KAAK,MAAM,KAAA;EAC3B,cAAc,QAAQ,KAAK,MAAM,KAAA;CACnC,CAAC;CACD,kBAAkB;CAClB,IAAI,WAAW;EACb,iBAAsB;GACpB,MAAM;GACN,cAAc,kBAAkB,CAAC,CAAC,mBAAmB,IAAI,UAAU;EACrE,CAAC;EACD,iBAAsB;GACpB,MAAM;GACN,eAAe,IAAI,WAAW;EAChC,CAAC;EACD,IAAS,mBAAmB,CAAC,CAAC,MAC3B,cACC,iBAAiB;GAAE,MAAM;GAAuB;EAAU,CAAC,IAC5D,UACC,QAAQ,KACN,gDAAgD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACvG,CACJ;CACF;CACA,IAAI,aAAa,CAAC,IAAI,WAAW,WAC/B,QAAQ,KACN,oGACF;AAEJ,SAAS,OAAO;CACd,MAAM,WAAW,WAAW,KAAK;CACjC,MAAM;AACR"}
1
+ {"version":3,"file":"dev-worker.js","names":[],"sources":["../src/dev-worker.ts"],"sourcesContent":["import { getGlobalRegistry, stopAllEvents } from \"@brickkit/core\";\nimport { startInspector } from \"./dev-inspector\";\nimport { startDevApplication } from \"./runner\";\nimport { parsePort } from \"./port-utils\";\nimport {\n installWorkerTelemetry,\n reportWorkerError,\n sendToSupervisor,\n} from \"./dev-telemetry\";\nimport type { WorkerErrorPhase } from \"./dev-telemetry\";\n\nlet stopping = false;\n// A reload stops this process. Deliveries cut off would stay claimed, and wait\n// a minute (claimTimeoutMs) before the next process takes them. Stop every\n// started hub: an event emitted while the entry still loads starts one.\nconst stop = () => {\n if (stopping) return;\n stopping = true;\n void Promise.race([stopAllEvents(), Bun.sleep(3000)])\n .catch((error: unknown) =>\n console.error(\n `[Brick-TS] Could not stop the events: ${error instanceof Error ? error.message : String(error)}`,\n ),\n )\n .finally(() => process.exit(0));\n};\nprocess.on(\"SIGTERM\", stop);\nif (process.connected && typeof process.send === \"function\") {\n // The terminal also signals the supervisor, which sends SIGTERM and waits for us.\n process.on(\"SIGINT\", () => {});\n process.on(\"disconnect\", stop);\n} else {\n process.on(\"SIGINT\", stop);\n}\n\n// argv[6] is \"1\" when the supervisor serves the dashboard and needs spans.\nconst telemetry = process.argv[6] === \"1\";\nlet startupComplete = false;\nlet reported = false;\n\nasync function reportOnce(phase: WorkerErrorPhase, error: unknown) {\n if (!telemetry || reported) return;\n reported = true;\n await reportWorkerError(phase, error);\n}\n\nasync function exitAfterFailure(phase: WorkerErrorPhase, error: unknown) {\n await reportOnce(phase, error);\n console.error(error);\n process.exit(1);\n}\n\nif (telemetry) {\n installWorkerTelemetry();\n // Failures before the app is listening are startup failures, not crashes.\n const phaseOf = (): WorkerErrorPhase =>\n startupComplete ? \"uncaught\" : \"startup\";\n process.on(\"uncaughtException\", (error) => {\n void exitAfterFailure(phaseOf(), error);\n });\n process.on(\"unhandledRejection\", (reason) => {\n void exitAfterFailure(\n startupComplete ? \"unhandled-rejection\" : \"startup\",\n reason,\n );\n });\n}\n\n// Scan local imports so dependencies outside the app directory are watched too.\nif (process.argv[2]) {\n const files = new Set<string>();\n try {\n await Bun.build({\n entrypoints: [process.argv[2]],\n target: \"bun\",\n packages: \"external\",\n plugins: [\n {\n name: \"brick:dependencies\",\n setup(build) {\n build.onLoad({ filter: /./ }, (args) => {\n files.add(args.path);\n return undefined;\n });\n },\n },\n ],\n });\n } finally {\n process.send?.({ type: \"brick:dependencies\", files: [...files] });\n }\n}\n\ntry {\n const app = await startDevApplication({\n entry: process.argv[2],\n port: parsePort(process.argv[3] || undefined, process.env.PORT),\n prefix: process.argv[4] || undefined,\n clientOutput: process.argv[5] || undefined,\n });\n startupComplete = true;\n if (telemetry) {\n void sendToSupervisor({\n type: \"brick:architecture\",\n architecture: getGlobalRegistry().exportArchitecture(app.definition),\n });\n void sendToSupervisor({\n type: \"brick:documentation\",\n documentation: app.definition.documentation,\n });\n void app.referenceDocuments().then(\n (documents) =>\n sendToSupervisor({ type: \"brick:api-documents\", documents }),\n (error: unknown) =>\n console.warn(\n `[Brick-TS] Could not load the API documents: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n if (telemetry) {\n void startInspector(app).then(\n (inspector) =>\n inspector &&\n sendToSupervisor({\n type: \"brick:inspector\",\n port: inspector.port,\n token: inspector.token,\n }),\n (error: unknown) =>\n console.warn(\n `[Brick-TS] Could not start the workflow inspector: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n }\n if (telemetry && !app.definition.telemetry) {\n console.warn(\n \"[Brick-TS] The dashboard shows no requests: pass { telemetry: true } to brick() in your app entry.\",\n );\n }\n} catch (error) {\n await reportOnce(\"startup\", error);\n throw error;\n}\n"],"mappings":";;;;;AAWA,IAAI,WAAW;AAIf,MAAM,aAAa;CACjB,IAAI,UAAU;CACd,WAAW;CACX,QAAa,KAAK,CAAC,cAAc,GAAG,IAAI,MAAM,GAAI,CAAC,CAAC,CAAC,CAClD,OAAO,UACN,QAAQ,MACN,yCAAyC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAChG,CACF,CAAC,CACA,cAAc,QAAQ,KAAK,CAAC,CAAC;AAClC;AACA,QAAQ,GAAG,WAAW,IAAI;AAC1B,IAAI,QAAQ,aAAa,OAAO,QAAQ,SAAS,YAAY;CAE3D,QAAQ,GAAG,gBAAgB,CAAC,CAAC;CA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K,MAAM,KAAA;CACnC,CAAC;CACD,kBAAkB;CAClB,IAAI,WAAW;EACb,iBAAsB;GACpB,MAAM;GACN,cAAc,kBAAkB,CAAC,CAAC,mBAAmB,IAAI,UAAU;EACrE,CAAC;EACD,iBAAsB;GACpB,MAAM;GACN,eAAe,IAAI,WAAW;EAChC,CAAC;EACD,IAAS,mBAAmB,CAAC,CAAC,MAC3B,cACC,iBAAiB;GAAE,MAAM;GAAuB;EAAU,CAAC,IAC5D,UACC,QAAQ,KACN,gDAAgD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACvG,CACJ;CACF;CACA,IAAI,WACF,eAAoB,GAAG,CAAC,CAAC,MACtB,cACC,aACA,iBAAiB;EACf,MAAM;EACN,MAAM,UAAU;EAChB,OAAO,UAAU;CACnB,CAAC,IACF,UACC,QAAQ,KACN,sDAAsD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAC7G,CACJ;CAEF,IAAI,aAAa,CAAC,IAAI,WAAW,WAC/B,QAAQ,KACN,oGACF;AAEJ,SAAS,OAAO;CACd,MAAM,WAAW,WAAW,KAAK;CACjC,MAAM;AACR"}
package/dist/index.d.ts CHANGED
@@ -19,6 +19,20 @@ interface DevServerOptions {
19
19
  historyDays?: number;
20
20
  } | false;
21
21
  }
22
+ /**
23
+ * What `brick worker` runs: load the app and deliver its events from this
24
+ * process, without serving HTTP. Run it beside API processes that only record
25
+ * events (`events: { dispatch: false }`), or alone for an app with no routes.
26
+ * Workflow listeners run here too: the world starts and the steps of every run
27
+ * in it execute in this process.
28
+ *
29
+ * @param options - `entry`: the app file, which must default-export a `brick()` app.
30
+ * @returns The app.
31
+ * @throws When the entry is missing, has no `events`, or only records events.
32
+ */
33
+ export declare function startWorker(options: {
34
+ entry: string;
35
+ }): Promise<BrickApp$1>;
22
36
  /**
23
37
  * What `brick dev` runs: start the application, restart it when its files
24
38
  * change, and serve the dashboard beside it. With an `entry`, the app runs in
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["BrickApp","BrickApp"],"sources":["../src/runner.ts","../src/build.ts","../src/client-contract.ts"],"mappings":";;;UAyBiB;EACf;EACA;EACA;;EAEA;;EAEA;;;;;;EAMA;IAAc;IAAc;;;;;;;;;;;;;;;;;;wBAqMR,eAAe,UAAS,mBAAqB,QAAAA;;;;;UCrOlD;;EAEf;EACA;EACA;;EAEA;;;wBAIoB,iBAAiB,SAAS,0BAAuB;;;;;;;;wBCVvD,uBAAuB,KAAKC"}
1
+ {"version":3,"file":"index.d.ts","names":["BrickApp","BrickApp"],"sources":["../src/runner.ts","../src/build.ts","../src/client-contract.ts"],"mappings":";;;UA2BiB;EACf;EACA;EACA;;EAEA;;EAEA;;;;;;EAMA;IAAc;IAAc;;;;;;;;;;;;;;wBAyLR,YAAY;EAAW;IAAe,QAAAA;;;;;;;;;;;;;;;;wBAmFtC,eAAe,UAAS,mBAAqB,QAAAA;;;;;UC7SlD;;EAEf;EACA;EACA;;EAEA;;;wBAIoB,iBAAiB,SAAS,0BAAuB;;;;;;;;wBCXvD,uBAAuB,KAAKC"}
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { n as startDevServer } from "./runner.js";
1
+ import { i as startWorker, n as startDevServer } from "./runner.js";
2
2
  import { a as emitHandlerFactory, i as emitCompiledApplication } from "./compiler2.js";
3
3
  import { t as buildApplication } from "./build.js";
4
4
  import { t as generateClientContract } from "./client-contract2.js";
5
5
  import { bindCompiledApplication, brick, compileBrickApplication, loadCompiledBrickApp, referencePlugin, registerReferenceRoute, requestLoggingPlugin, scalarDocsHTML } from "@brickkit/core";
6
- export { bindCompiledApplication, brick, buildApplication, compileBrickApplication, emitCompiledApplication, emitHandlerFactory, generateClientContract, loadCompiledBrickApp, referencePlugin, registerReferenceRoute, requestLoggingPlugin, scalarDocsHTML, startDevServer };
6
+ export { bindCompiledApplication, brick, buildApplication, compileBrickApplication, emitCompiledApplication, emitHandlerFactory, generateClientContract, loadCompiledBrickApp, referencePlugin, registerReferenceRoute, requestLoggingPlugin, scalarDocsHTML, startDevServer, startWorker };
package/dist/runner.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { a as isLoopbackHost, i as startDevDashboard, n as DocsHost, o as openHistory, t as DevTelemetryStore } from "./dev-telemetry-store.js";
2
+ import { r as registerWorkflowTransform, t as buildAppWorkflows } from "./workflows2.js";
2
3
  import { t as installTracing } from "./dev-telemetry.js";
3
4
  import { brick, getGlobalRegistry, getPluginActionRoute, isBrickApp } from "@brickkit/core";
4
5
  import { existsSync, watch } from "fs";
@@ -82,7 +83,9 @@ async function createServer(options, label, application) {
82
83
  port,
83
84
  prefix: options.prefix
84
85
  });
86
+ await buildAppWorkflows(app, { reuse: label === "Development" });
85
87
  await app.listen({ port });
88
+ app.events?.start();
86
89
  const prefix = app.definition.prefix;
87
90
  const services = app.definition.services;
88
91
  console.log(`\n🧱 Brick-TS ${label} Server`);
@@ -103,6 +106,19 @@ async function createServer(options, label, application) {
103
106
  console.log(`🗺️ Architecture graph: http://localhost:${port}/_brick/services\n`);
104
107
  return app;
105
108
  }
109
+ /**
110
+ * Finish the deliveries in flight at SIGINT or SIGTERM, then exit. A second
111
+ * signal exits at once, for a delivery that never finishes.
112
+ */
113
+ function finishDeliveriesOnSignal(events, signals = ["SIGINT", "SIGTERM"]) {
114
+ let stopping = false;
115
+ const stop = (signal) => {
116
+ if (stopping) return process.exit(signal === "SIGINT" ? 130 : 143);
117
+ stopping = true;
118
+ events.stop().finally(() => process.exit(0));
119
+ };
120
+ for (const signal of signals) process.on(signal, stop);
121
+ }
106
122
  async function startProdServer(options = {}) {
107
123
  const entry = options.entry;
108
124
  let exported;
@@ -113,6 +129,7 @@ async function startProdServer(options = {}) {
113
129
  process.exit(1);
114
130
  }
115
131
  console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);
132
+ await registerWorkflowTransform();
116
133
  const module = await import(resolvedEntry);
117
134
  if (isBrickApp(module?.default)) exported = module.default;
118
135
  }
@@ -138,8 +155,13 @@ async function startProdServer(options = {}) {
138
155
  console.log(` -> ${method.padEnd(6)} ${path}`);
139
156
  }
140
157
  }
158
+ await buildAppWorkflows(app);
141
159
  const dashboard = await startProductionDashboard(app, { appPort: port });
142
160
  app.listen(port);
161
+ if (app.events) {
162
+ app.events.start();
163
+ finishDeliveriesOnSignal(app.events);
164
+ }
143
165
  console.log(`\n⚡ API Gateway running on: http://localhost:${port}`);
144
166
  console.log(`🩺 Health check: http://localhost:${port}/_health`);
145
167
  if (dashboard) {
@@ -149,7 +171,39 @@ async function startProdServer(options = {}) {
149
171
  console.log(`🗺️ Architecture graph: http://localhost:${port}/_brick/services\n`);
150
172
  return app;
151
173
  }
174
+ /**
175
+ * What `brick worker` runs: load the app and deliver its events from this
176
+ * process, without serving HTTP. Run it beside API processes that only record
177
+ * events (`events: { dispatch: false }`), or alone for an app with no routes.
178
+ * Workflow listeners run here too: the world starts and the steps of every run
179
+ * in it execute in this process.
180
+ *
181
+ * @param options - `entry`: the app file, which must default-export a `brick()` app.
182
+ * @returns The app.
183
+ * @throws When the entry is missing, has no `events`, or only records events.
184
+ */
185
+ async function startWorker(options) {
186
+ const resolvedEntry = resolve(process.cwd(), options.entry);
187
+ if (!existsSync(resolvedEntry)) {
188
+ console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);
189
+ process.exit(1);
190
+ }
191
+ console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);
192
+ await registerWorkflowTransform();
193
+ const app = (await import(resolvedEntry))?.default;
194
+ if (!isBrickApp(app)) throw new Error("Brick: a worker needs an entry that default-exports a BrickApp.");
195
+ if (!app.events) throw new Error("Brick: this app has no events, so a worker has nothing to deliver.");
196
+ if (!app.events.describe().dispatch) throw new Error("Brick: this app only records events (events.dispatch is false), so a worker would deliver nothing. Enable dispatch for the worker process.");
197
+ await buildAppWorkflows(app);
198
+ app.events.start();
199
+ finishDeliveriesOnSignal(app.events);
200
+ const listeners = app.events.describe().listeners;
201
+ console.log(`\n🧱 Brick-TS Worker`);
202
+ console.log(` Delivering events to ${listeners.length} ${listeners.length === 1 ? "listener" : "listeners"}: ${listeners.map((l) => l.name).join(", ") || "none"}\n`);
203
+ return app;
204
+ }
152
205
  async function startDevApplication(options) {
206
+ if (options.entry) await registerWorkflowTransform();
153
207
  const module = options.entry ? await import(resolve(options.entry)) : void 0;
154
208
  if (isBrickApp(module?.default) && options.prefix !== void 0) console.warn(`[Brick-TS] Ignoring prefix ${options.prefix}: exported BrickApp prefix ${module.default.definition.prefix} takes precedence.`);
155
209
  if (options.clientOutput) {
@@ -209,6 +263,7 @@ async function startDevServer(options = {}) {
209
263
  const launch = () => {
210
264
  const generation = ++generationCount;
211
265
  childGeneration = generation;
266
+ telemetry?.setInspector(void 0);
212
267
  telemetry?.recordReload({
213
268
  kind: "started",
214
269
  generation
@@ -240,6 +295,10 @@ async function startDevServer(options = {}) {
240
295
  stderr: "inherit"
241
296
  });
242
297
  if (telemetry && message.type === "brick:architecture" && "architecture" in message) telemetry.setArchitecture(message.architecture, generation);
298
+ if (telemetry && message.type === "brick:inspector" && generation === childGeneration && "port" in message && "token" in message) telemetry.setInspector({
299
+ port: message.port,
300
+ token: message.token
301
+ });
243
302
  if (docs && message.type === "brick:documentation") docs.configure(dirname(resolvedEntry), "documentation" in message ? message.documentation : void 0);
244
303
  if (telemetry && message.type === "brick:api-documents" && "documents" in message && Array.isArray(message.documents)) telemetry.setApiDocuments(message.documents, `http://localhost:${appPort()}`);
245
304
  if (telemetry && message.type === "brick:contract-ready") telemetry.recordReload({
@@ -259,6 +318,7 @@ async function startDevServer(options = {}) {
259
318
  }
260
319
  });
261
320
  application.exited.then((code) => {
321
+ if (generation === childGeneration) telemetry?.setInspector(void 0);
262
322
  if (!stopped && !intentionalExits.has(application)) {
263
323
  console.error(`[Brick-TS] Application process exited with code ${code}. Waiting for changes to restart.`);
264
324
  telemetry?.recordReload({
@@ -355,9 +415,15 @@ async function startDevServer(options = {}) {
355
415
  process.off("SIGTERM", onSignal);
356
416
  process.off("exit", stop);
357
417
  };
358
- const onSignal = () => {
418
+ const onSignal = (signal) => {
419
+ if (stopped) {
420
+ child.kill("SIGKILL");
421
+ process.exit(signal === "SIGINT" ? 130 : 143);
422
+ }
359
423
  stop();
360
- process.exit(0);
424
+ process.on("SIGINT", onSignal);
425
+ process.on("SIGTERM", onSignal);
426
+ child.exited.then(() => process.exit(0));
361
427
  };
362
428
  process.on("SIGINT", onSignal);
363
429
  process.on("SIGTERM", onSignal);
@@ -366,6 +432,6 @@ async function startDevServer(options = {}) {
366
432
  return { stop };
367
433
  }
368
434
  //#endregion
369
- export { parsePort as i, startDevServer as n, startProdServer as r, startDevApplication as t };
435
+ export { parsePort as a, startWorker as i, startDevServer as n, startProdServer as r, startDevApplication as t };
370
436
 
371
437
  //# sourceMappingURL=runner.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"runner.js","names":[],"sources":["../src/port-utils.ts","../src/production-dashboard.ts","../src/runner.ts"],"sourcesContent":["export function parsePort(\n portStr: string | undefined,\n envPort?: string | undefined,\n): number {\n let port: number | undefined;\n if (portStr !== undefined) {\n port = Number(portStr);\n } else if (envPort !== undefined && envPort !== \"\") {\n port = Number(envPort);\n } else {\n port = 4000;\n }\n\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n return port;\n}\n","import { getGlobalRegistry, type BrickApp } from \"@brickkit/core\";\nimport { isLoopbackHost } from \"./dashboard-access\";\nimport { DEFAULT_DASHBOARD_PORT, startDevDashboard } from \"./dev-dashboard\";\nimport { openHistory } from \"./dev-history\";\nimport { installTracing } from \"./dev-telemetry\";\nimport { DevTelemetryStore } from \"./dev-telemetry-store\";\n\nexport interface ProductionDashboard {\n readonly host: string;\n readonly port: number;\n stop(): void;\n}\n\n/**\n * Serve the monitoring dashboard an app asks for with `brick({ dashboard })`,\n * in the process that serves the app. It listens on a port of its own, so it\n * stays up when the app's routes do not answer, and its `/_health` tells an\n * uptime monitor whether the app does. From here on `ctx.logger` and `console`\n * lines written during a request go to the dashboard, not the console.\n *\n * Call it before the app starts listening. Returns undefined when the app\n * asks for no dashboard, or when it cannot start (the app runs on without it,\n * and says so). A configuration that would leave the dashboard open to others\n * throws instead: the app must not start unprotected.\n */\nexport async function startProductionDashboard(\n app: BrickApp,\n options: {\n /** The port the app listens on, for the health probe. */\n appPort: number;\n /** Where `.brick/` history is kept; the working folder by default. */\n directory?: string;\n warn?: (message: string) => void;\n },\n): Promise<ProductionDashboard | undefined> {\n const config = app.definition.dashboard;\n if (!config) return undefined;\n const warn = options.warn ?? ((message) => console.warn(message));\n const host = config.host ?? \"127.0.0.1\";\n const port = config.port ?? DEFAULT_DASHBOARD_PORT;\n if (!isLoopbackHost(host) && !config.auth) {\n throw new Error(\n `Brick: the dashboard would listen on ${host}, where others can reach it, so it needs access control. Set dashboard.auth with a token or an authorize function.`,\n );\n }\n\n const history = await openHistory({\n directory: options.directory ?? process.cwd(),\n days: config.historyDays ?? 0,\n warn,\n });\n const store = new DevTelemetryStore({ history });\n let started;\n try {\n started = await startDevDashboard({\n port,\n host,\n mode: \"production\",\n auth: config.auth,\n store,\n history,\n probe: async () => {\n const response = await fetch(\n `http://127.0.0.1:${options.appPort}/_health`,\n { signal: AbortSignal.timeout(2000) },\n );\n return response.ok;\n },\n });\n } catch (error) {\n history?.close();\n const reason = error instanceof Error ? error.message : String(error);\n warn(`[Brick-TS] ${reason} Continuing without the dashboard.`);\n return undefined;\n }\n\n const registered = installTracing((records) =>\n store.ingest(records, store.latestGeneration),\n );\n if (!registered) {\n warn(\n \"[Brick-TS] Another tracer provider is already registered, so the dashboard will show no requests or logs.\",\n );\n }\n const generation = store.startGeneration(\"application started\");\n store.setArchitecture(\n getGlobalRegistry().exportArchitecture(app.definition),\n generation,\n );\n return {\n host,\n port: started.port,\n stop() {\n started.stop();\n history?.close();\n },\n };\n}\n","import { existsSync } from \"fs\";\nimport { watch } from \"fs\";\nimport { resolve, dirname, basename } from \"path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n brick,\n getPluginActionRoute,\n isBrickApp,\n type ApiDocument,\n type ArchitectureSchema,\n type BrickApp,\n type DocumentationOptions,\n} from \"@brickkit/core\";\nimport { startDevDashboard, type DevDashboard } from \"./dev-dashboard\";\nimport { DocsHost } from \"./dev-docs\";\nimport { DEFAULT_HISTORY_DAYS, openHistory } from \"./dev-history\";\nimport { DevTelemetryStore } from \"./dev-telemetry-store\";\nimport { parsePort } from \"./port-utils\";\nimport { startProductionDashboard } from \"./production-dashboard\";\nimport type {\n SerializedError,\n TelemetryRecord,\n WorkerErrorPhase,\n} from \"./dev-telemetry\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\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. `historyDays` is how long finished requests are kept on disk\n * (default 90); zero keeps live data only.\n */\n dashboard?: { port: number; historyDays?: number } | false;\n}\n\nasync function createServer(\n options: DevServerOptions,\n label: string,\n application?: BrickApp,\n) {\n let port: number;\n if (options.port !== undefined) {\n port = options.port;\n } else if (process.env.PORT !== undefined && process.env.PORT !== \"\") {\n port = Number(process.env.PORT);\n } else {\n port = 4000;\n }\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n\n const app =\n application ??\n brick({\n port,\n prefix: options.prefix,\n });\n\n await app.listen({ port });\n\n const prefix = app.definition.prefix;\n const services = app.definition.services;\n\n console.log(`\\n🧱 Brick-TS ${label} Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n const actions = svc.listActions();\n console.log(` • ${svc.name} (${actions.length} actions)`);\n for (const act of actions) {\n const pluginRoute = getPluginActionRoute(act, prefix);\n if (pluginRoute === false) continue;\n const method = pluginRoute?.method ?? act.config.method ?? \"POST\";\n const path =\n pluginRoute?.path ??\n act.config.path ??\n `${prefix}/${svc.name}/${act.name}`;\n console.log(` -> ${method.padEnd(6)} ${path}`);\n }\n }\n\n console.log(`\\n⚡ API Gateway running on: http://localhost:${port}`);\n console.log(`🩺 Health check: http://localhost:${port}/_health`);\n console.log(\n `🗺️ Architecture graph: http://localhost:${port}/_brick/services\\n`,\n );\n\n return app;\n}\n\nexport async function startProdServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n\n let exported: BrickApp | undefined;\n if (entry) {\n const resolvedEntry = resolve(process.cwd(), entry);\n if (!existsSync(resolvedEntry)) {\n console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);\n process.exit(1);\n }\n console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);\n const module = await import(resolvedEntry);\n // An entry that default-exports its app is served as it built it, with its\n // options (telemetry, dashboard, and the rest), as `brick dev` does.\n if (isBrickApp(module?.default)) exported = module.default;\n }\n if (exported && options.prefix !== undefined) {\n console.warn(\n `[Brick-TS] Ignoring prefix ${options.prefix}: exported BrickApp prefix ${exported.definition.prefix} takes precedence.`,\n );\n }\n\n const port =\n options.port !== undefined\n ? options.port\n : process.env.PORT !== undefined && process.env.PORT !== \"\"\n ? Number(process.env.PORT)\n : 4000;\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n\n const app =\n exported ??\n brick({\n port,\n prefix: options.prefix,\n });\n\n const prefix = app.definition.prefix;\n const services = app.definition.services;\n\n console.log(`\\n🧱 Brick-TS Production Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n const actions = svc.listActions();\n console.log(` • ${svc.name} (${actions.length} actions)`);\n for (const act of actions) {\n const pluginRoute = getPluginActionRoute(act, prefix);\n if (pluginRoute === false) continue;\n const method = pluginRoute?.method ?? act.config.method ?? \"POST\";\n const path =\n pluginRoute?.path ??\n act.config.path ??\n `${prefix}/${svc.name}/${act.name}`;\n console.log(` -> ${method.padEnd(6)} ${path}`);\n }\n }\n\n // Before listening, so the first request is already traced and its logs kept.\n const dashboard = await startProductionDashboard(app, { appPort: port });\n app.listen(port);\n\n console.log(`\\n⚡ API Gateway running on: http://localhost:${port}`);\n console.log(`🩺 Health check: http://localhost:${port}/_health`);\n if (dashboard) {\n const shown =\n dashboard.host === \"0.0.0.0\" || dashboard.host === \"::\"\n ? \"localhost\"\n : dashboard.host.includes(\":\")\n ? `[${dashboard.host.replace(/^\\[|\\]$/g, \"\")}]`\n : dashboard.host;\n console.log(\n `📊 Dashboard: http://${shown}:${dashboard.port} (health: /_health)`,\n );\n }\n console.log(\n `🗺️ Architecture graph: http://localhost:${port}/_brick/services\\n`,\n );\n\n return app;\n}\n\nexport async function startDevApplication(options: DevServerOptions) {\n const module = options.entry\n ? await import(resolve(options.entry))\n : undefined;\n if (isBrickApp(module?.default) && options.prefix !== undefined) {\n console.warn(\n `[Brick-TS] Ignoring prefix ${options.prefix}: exported BrickApp prefix ${module.default.definition.prefix} takes precedence.`,\n );\n }\n if (options.clientOutput) {\n if (!isBrickApp(module?.default))\n throw new Error(\n \"Brick: client generation requires a default-exported BrickApp.\",\n );\n const { generateClientContract } = await import(\"./client-contract\");\n const { writeContractSource } = await import(\"./client-contract-file\");\n const { requireBrickApp } = await import(\"./app-entry\");\n const output = resolve(options.clientOutput);\n if (output === resolve(options.entry!))\n throw new Error(\n \"Brick: contract output must not overwrite the app entry.\",\n );\n await writeContractSource(\n output,\n generateClientContract(requireBrickApp(module.default)),\n );\n process.send?.({ type: \"brick:contract-ready\" });\n }\n return createServer(\n options,\n \"Development\",\n isBrickApp(module?.default) ? module.default : undefined,\n );\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 Error(\"Brick: --client and --frontend require an app entry.\");\n if (!entry) return createServer(options, \"Development\");\n const resolvedEntry = resolve(entry);\n if (!existsSync(resolvedEntry)) {\n console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);\n process.exit(1);\n }\n\n const worker = new URL(\n import.meta.url.endsWith(\".ts\") ? \"./dev-worker.ts\" : \"./dev-worker.js\",\n import.meta.url,\n );\n if (options.frontend && !options.clientOutput)\n throw new Error(\"Brick: --frontend requires --client <file>.\");\n if (\n options.dashboard &&\n options.port !== undefined &&\n options.dashboard.port === options.port\n )\n throw new Error(\n \"Brick: dashboard port must differ from the API port. Use --dashboard-port <number>.\",\n );\n // The worker resolves its port the same way, so this is where the app listens.\n const appPort = () =>\n parsePort(\n options.port === undefined ? undefined : String(options.port),\n process.env.PORT,\n );\n const history = options.dashboard\n ? await openHistory({\n directory: process.cwd(),\n days: options.dashboard.historyDays ?? DEFAULT_HISTORY_DAYS,\n warn: (message) => console.warn(message),\n })\n : undefined;\n const telemetry = options.dashboard\n ? new DevTelemetryStore({ history })\n : undefined;\n const docs = telemetry\n ? new DocsHost(telemetry, (message) => console.warn(message))\n : undefined;\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 let generationCount = 0;\n let childGeneration = 0;\n const launch = () => {\n const generation = ++generationCount;\n childGeneration = generation;\n telemetry?.recordReload({ kind: \"started\", generation });\n const application = Bun.spawn(\n [\n process.execPath,\n fileURLToPath(worker),\n resolvedEntry,\n String(options.port ?? \"\"),\n options.prefix ?? \"\",\n options.clientOutput ? resolve(options.clientOutput) : \"\",\n telemetry ? \"1\" : \"\",\n ],\n {\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n ipc(message) {\n if (!message || typeof message !== \"object\" || !(\"type\" in message))\n return;\n if (\n telemetry &&\n message.type === \"brick:telemetry\" &&\n \"records\" in message &&\n Array.isArray(message.records)\n ) {\n telemetry.ingest(message.records as TelemetryRecord[], generation);\n }\n if (\n telemetry &&\n message.type === \"brick:error\" &&\n \"phase\" in message &&\n \"error\" in message\n ) {\n telemetry.recordWorkerError(\n message.phase as WorkerErrorPhase,\n message.error as SerializedError,\n generation,\n );\n }\n if (\n message.type === \"brick:contract-ready\" &&\n options.frontend &&\n !frontend &&\n !stopped\n ) {\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 }\n if (\n telemetry &&\n message.type === \"brick:architecture\" &&\n \"architecture\" in message\n ) {\n telemetry.setArchitecture(\n message.architecture as ArchitectureSchema,\n generation,\n );\n }\n if (docs && message.type === \"brick:documentation\") {\n void docs.configure(\n dirname(resolvedEntry),\n \"documentation\" in message\n ? (message.documentation as DocumentationOptions | undefined)\n : undefined,\n );\n }\n if (\n telemetry &&\n message.type === \"brick:api-documents\" &&\n \"documents\" in message &&\n Array.isArray(message.documents)\n ) {\n telemetry.setApiDocuments(\n message.documents as ApiDocument[],\n `http://localhost:${appPort()}`,\n );\n }\n if (telemetry && message.type === \"brick:contract-ready\") {\n telemetry.recordReload({\n kind: \"contract-ready\",\n generation,\n detail: \"browser contract generated\",\n });\n }\n if (\n message.type === \"brick:dependencies\" &&\n \"files\" in message &&\n Array.isArray(message.files)\n ) {\n for (const file of message.files) {\n if (\n typeof file !== \"string\" ||\n file === resolve(options.clientOutput ?? \"_brick/contract.ts\")\n )\n 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 }\n },\n },\n );\n void application.exited.then((code) => {\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 // Bind the dashboard before the first worker starts, so a port conflict\n // does not leave an application process running.\n const dashboard: DevDashboard | undefined =\n telemetry && options.dashboard\n ? await startDevDashboard({\n port: options.dashboard.port,\n store: telemetry,\n history,\n docs: () => docs?.current,\n restart: () => {\n void restart(\"dashboard\");\n },\n }).catch((error: unknown) => {\n history?.close();\n throw error;\n })\n : undefined;\n if (dashboard) {\n console.log(`📊 Dev dashboard: http://127.0.0.1:${dashboard.port}`);\n }\n let child = launch();\n const watchDirs = [\n ...new Set([resolve(\"src\"), resolve(\"app\"), resolve(resolvedEntry, \"..\")]),\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: childGeneration,\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 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 === resolve(options.clientOutput ?? \"_brick/contract.ts\") ||\n basename(file).startsWith(\".brick-contract-\")\n )\n return;\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 docs?.close();\n history?.close();\n child.kill();\n process.off(\"SIGINT\", onSignal);\n process.off(\"SIGTERM\", onSignal);\n process.off(\"exit\", stop);\n };\n const onSignal = () => {\n stop();\n 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"],"mappings":";;;;;;;AAAA,SAAgB,UACd,SACA,SACQ;CACR,IAAI;CACJ,IAAI,YAAY,KAAA,GACd,OAAO,OAAO,OAAO;MAChB,IAAI,YAAY,KAAA,KAAa,YAAY,IAC9C,OAAO,OAAO,OAAO;MAErB,OAAO;CAGT,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OAChD,MAAM,IAAI,MACR,iBAAiB,KAAK,8CACxB;CAEF,OAAO;AACT;;;;;;;;;;;;;;;ACMA,eAAsB,yBACpB,KACA,SAO0C;CAC1C,MAAM,SAAS,I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AQ,IAAI;CAC1B;CACA,MAAM,iBAAiB;EACrB,KAAK;EACL,QAAQ,KAAK,CAAC;CAChB;CACA,QAAQ,GAAG,UAAU,QAAQ;CAC7B,QAAQ,GAAG,WAAW,QAAQ;CAC9B,QAAQ,GAAG,QAAQ,IAAI;CACvB,QAAQ,IAAI,iCAAiC,UAAU,KAAK,IAAI,GAAG;CACnE,OAAO,EAAE,KAAK;AAChB"}
1
+ {"version":3,"file":"runner.js","names":[],"sources":["../src/port-utils.ts","../src/production-dashboard.ts","../src/runner.ts"],"sourcesContent":["export function parsePort(\n portStr: string | undefined,\n envPort?: string | undefined,\n): number {\n let port: number | undefined;\n if (portStr !== undefined) {\n port = Number(portStr);\n } else if (envPort !== undefined && envPort !== \"\") {\n port = Number(envPort);\n } else {\n port = 4000;\n }\n\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n return port;\n}\n","import { getGlobalRegistry, type BrickApp } from \"@brickkit/core\";\nimport { isLoopbackHost } from \"./dashboard-access\";\nimport { DEFAULT_DASHBOARD_PORT, startDevDashboard } from \"./dev-dashboard\";\nimport { openHistory } from \"./dev-history\";\nimport { installTracing } from \"./dev-telemetry\";\nimport { DevTelemetryStore } from \"./dev-telemetry-store\";\n\nexport interface ProductionDashboard {\n readonly host: string;\n readonly port: number;\n stop(): void;\n}\n\n/**\n * Serve the monitoring dashboard an app asks for with `brick({ dashboard })`,\n * in the process that serves the app. It listens on a port of its own, so it\n * stays up when the app's routes do not answer, and its `/_health` tells an\n * uptime monitor whether the app does. From here on `ctx.logger` and `console`\n * lines written during a request go to the dashboard, not the console.\n *\n * Call it before the app starts listening. Returns undefined when the app\n * asks for no dashboard, or when it cannot start (the app runs on without it,\n * and says so). A configuration that would leave the dashboard open to others\n * throws instead: the app must not start unprotected.\n */\nexport async function startProductionDashboard(\n app: BrickApp,\n options: {\n /** The port the app listens on, for the health probe. */\n appPort: number;\n /** Where `.brick/` history is kept; the working folder by default. */\n directory?: string;\n warn?: (message: string) => void;\n },\n): Promise<ProductionDashboard | undefined> {\n const config = app.definition.dashboard;\n if (!config) return undefined;\n const warn = options.warn ?? ((message) => console.warn(message));\n const host = config.host ?? \"127.0.0.1\";\n const port = config.port ?? DEFAULT_DASHBOARD_PORT;\n if (!isLoopbackHost(host) && !config.auth) {\n throw new Error(\n `Brick: the dashboard would listen on ${host}, where others can reach it, so it needs access control. Set dashboard.auth with a token or an authorize function.`,\n );\n }\n\n const history = await openHistory({\n directory: options.directory ?? process.cwd(),\n days: config.historyDays ?? 0,\n warn,\n });\n const store = new DevTelemetryStore({ history });\n let started;\n try {\n started = await startDevDashboard({\n port,\n host,\n mode: \"production\",\n auth: config.auth,\n store,\n history,\n probe: async () => {\n const response = await fetch(\n `http://127.0.0.1:${options.appPort}/_health`,\n { signal: AbortSignal.timeout(2000) },\n );\n return response.ok;\n },\n });\n } catch (error) {\n history?.close();\n const reason = error instanceof Error ? error.message : String(error);\n warn(`[Brick-TS] ${reason} Continuing without the dashboard.`);\n return undefined;\n }\n\n const registered = installTracing((records) =>\n store.ingest(records, store.latestGeneration),\n );\n if (!registered) {\n warn(\n \"[Brick-TS] Another tracer provider is already registered, so the dashboard will show no requests or logs.\",\n );\n }\n const generation = store.startGeneration(\"application started\");\n store.setArchitecture(\n getGlobalRegistry().exportArchitecture(app.definition),\n generation,\n );\n return {\n host,\n port: started.port,\n stop() {\n started.stop();\n history?.close();\n },\n };\n}\n","import { existsSync } from \"fs\";\nimport { watch } from \"fs\";\nimport { resolve, dirname, basename } from \"path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n brick,\n getPluginActionRoute,\n isBrickApp,\n type ApiDocument,\n type ArchitectureSchema,\n type BrickApp,\n type DocumentationOptions,\n type EventsHub,\n} from \"@brickkit/core\";\nimport { startDevDashboard, type DevDashboard } from \"./dev-dashboard\";\nimport { DocsHost } from \"./dev-docs\";\nimport { DEFAULT_HISTORY_DAYS, openHistory } from \"./dev-history\";\nimport { DevTelemetryStore } from \"./dev-telemetry-store\";\nimport { parsePort } from \"./port-utils\";\nimport { buildAppWorkflows, registerWorkflowTransform } from \"./workflows\";\nimport { startProductionDashboard } from \"./production-dashboard\";\nimport type {\n SerializedError,\n TelemetryRecord,\n WorkerErrorPhase,\n} from \"./dev-telemetry\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\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. `historyDays` is how long finished requests are kept on disk\n * (default 90); zero keeps live data only.\n */\n dashboard?: { port: number; historyDays?: number } | false;\n}\n\nasync function createServer(\n options: DevServerOptions,\n label: string,\n application?: BrickApp,\n) {\n let port: number;\n if (options.port !== undefined) {\n port = options.port;\n } else if (process.env.PORT !== undefined && process.env.PORT !== \"\") {\n port = Number(process.env.PORT);\n } else {\n port = 4000;\n }\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n\n const app =\n application ??\n brick({\n port,\n prefix: options.prefix,\n });\n\n await buildAppWorkflows(app, { reuse: label === \"Development\" });\n await app.listen({ port });\n app.events?.start();\n\n const prefix = app.definition.prefix;\n const services = app.definition.services;\n\n console.log(`\\n🧱 Brick-TS ${label} Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n const actions = svc.listActions();\n console.log(` • ${svc.name} (${actions.length} actions)`);\n for (const act of actions) {\n const pluginRoute = getPluginActionRoute(act, prefix);\n if (pluginRoute === false) continue;\n const method = pluginRoute?.method ?? act.config.method ?? \"POST\";\n const path =\n pluginRoute?.path ??\n act.config.path ??\n `${prefix}/${svc.name}/${act.name}`;\n console.log(` -> ${method.padEnd(6)} ${path}`);\n }\n }\n\n console.log(`\\n⚡ API Gateway running on: http://localhost:${port}`);\n console.log(`🩺 Health check: http://localhost:${port}/_health`);\n console.log(\n `🗺️ Architecture graph: http://localhost:${port}/_brick/services\\n`,\n );\n\n return app;\n}\n\n/**\n * Finish the deliveries in flight at SIGINT or SIGTERM, then exit. A second\n * signal exits at once, for a delivery that never finishes.\n */\nexport function finishDeliveriesOnSignal(\n events: Pick<EventsHub, \"stop\">,\n signals: NodeJS.Signals[] = [\"SIGINT\", \"SIGTERM\"],\n) {\n let stopping = false;\n const stop = (signal: NodeJS.Signals) => {\n if (stopping) return process.exit(signal === \"SIGINT\" ? 130 : 143);\n stopping = true;\n void events.stop().finally(() => process.exit(0));\n };\n // `on`, not `once`: the workflow bundle loads signal-exit, which re-raises the\n // signal itself when it finds no listener left, and `once` removes ours first.\n for (const signal of signals) process.on(signal, stop);\n}\n\nexport async function startProdServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n\n let exported: BrickApp | undefined;\n if (entry) {\n const resolvedEntry = resolve(process.cwd(), entry);\n if (!existsSync(resolvedEntry)) {\n console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);\n process.exit(1);\n }\n console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);\n await registerWorkflowTransform();\n const module = await import(resolvedEntry);\n // An entry that default-exports its app is served as it built it, with its\n // options (telemetry, dashboard, and the rest), as `brick dev` does.\n if (isBrickApp(module?.default)) exported = module.default;\n }\n if (exported && options.prefix !== undefined) {\n console.warn(\n `[Brick-TS] Ignoring prefix ${options.prefix}: exported BrickApp prefix ${exported.definition.prefix} takes precedence.`,\n );\n }\n\n const port =\n options.port !== undefined\n ? options.port\n : process.env.PORT !== undefined && process.env.PORT !== \"\"\n ? Number(process.env.PORT)\n : 4000;\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error(\n `Invalid port: ${port}. Port must be an integer between 1 and 65535`,\n );\n }\n\n const app =\n exported ??\n brick({\n port,\n prefix: options.prefix,\n });\n\n const prefix = app.definition.prefix;\n const services = app.definition.services;\n\n console.log(`\\n🧱 Brick-TS Production Server`);\n console.log(` Registered Services: ${services.length}`);\n\n for (const svc of services) {\n const actions = svc.listActions();\n console.log(` • ${svc.name} (${actions.length} actions)`);\n for (const act of actions) {\n const pluginRoute = getPluginActionRoute(act, prefix);\n if (pluginRoute === false) continue;\n const method = pluginRoute?.method ?? act.config.method ?? \"POST\";\n const path =\n pluginRoute?.path ??\n act.config.path ??\n `${prefix}/${svc.name}/${act.name}`;\n console.log(` -> ${method.padEnd(6)} ${path}`);\n }\n }\n\n await buildAppWorkflows(app);\n // Before listening, so the first request is already traced and its logs kept.\n const dashboard = await startProductionDashboard(app, { appPort: port });\n app.listen(port);\n if (app.events) {\n app.events.start();\n finishDeliveriesOnSignal(app.events);\n }\n\n console.log(`\\n⚡ API Gateway running on: http://localhost:${port}`);\n console.log(`🩺 Health check: http://localhost:${port}/_health`);\n if (dashboard) {\n const shown =\n dashboard.host === \"0.0.0.0\" || dashboard.host === \"::\"\n ? \"localhost\"\n : dashboard.host.includes(\":\")\n ? `[${dashboard.host.replace(/^\\[|\\]$/g, \"\")}]`\n : dashboard.host;\n console.log(\n `📊 Dashboard: http://${shown}:${dashboard.port} (health: /_health)`,\n );\n }\n console.log(\n `🗺️ Architecture graph: http://localhost:${port}/_brick/services\\n`,\n );\n\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 const resolvedEntry = resolve(process.cwd(), options.entry);\n if (!existsSync(resolvedEntry)) {\n console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);\n process.exit(1);\n }\n console.log(`[Brick-TS] Loading application entry: ${resolvedEntry}`);\n await registerWorkflowTransform();\n const app = (await import(resolvedEntry))?.default;\n if (!isBrickApp(app))\n throw new Error(\n \"Brick: a worker needs an entry that default-exports a BrickApp.\",\n );\n if (!app.events)\n throw new Error(\n \"Brick: this app has no events, so a worker has nothing to deliver.\",\n );\n if (!app.events.describe().dispatch)\n throw new Error(\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 app.events.start();\n finishDeliveriesOnSignal(app.events);\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\nexport async function startDevApplication(options: DevServerOptions) {\n if (options.entry) await registerWorkflowTransform();\n const module = options.entry\n ? await import(resolve(options.entry))\n : undefined;\n if (isBrickApp(module?.default) && options.prefix !== undefined) {\n console.warn(\n `[Brick-TS] Ignoring prefix ${options.prefix}: exported BrickApp prefix ${module.default.definition.prefix} takes precedence.`,\n );\n }\n if (options.clientOutput) {\n if (!isBrickApp(module?.default))\n throw new Error(\n \"Brick: client generation requires a default-exported BrickApp.\",\n );\n const { generateClientContract } = await import(\"./client-contract\");\n const { writeContractSource } = await import(\"./client-contract-file\");\n const { requireBrickApp } = await import(\"./app-entry\");\n const output = resolve(options.clientOutput);\n if (output === resolve(options.entry!))\n throw new Error(\n \"Brick: contract output must not overwrite the app entry.\",\n );\n await writeContractSource(\n output,\n generateClientContract(requireBrickApp(module.default)),\n );\n process.send?.({ type: \"brick:contract-ready\" });\n }\n return createServer(\n options,\n \"Development\",\n isBrickApp(module?.default) ? module.default : undefined,\n );\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 Error(\"Brick: --client and --frontend require an app entry.\");\n if (!entry) return createServer(options, \"Development\");\n const resolvedEntry = resolve(entry);\n if (!existsSync(resolvedEntry)) {\n console.error(`[Brick-TS] Error: Entry file not found: ${resolvedEntry}`);\n process.exit(1);\n }\n\n const worker = new URL(\n import.meta.url.endsWith(\".ts\") ? \"./dev-worker.ts\" : \"./dev-worker.js\",\n import.meta.url,\n );\n if (options.frontend && !options.clientOutput)\n throw new Error(\"Brick: --frontend requires --client <file>.\");\n if (\n options.dashboard &&\n options.port !== undefined &&\n options.dashboard.port === options.port\n )\n throw new Error(\n \"Brick: dashboard port must differ from the API port. Use --dashboard-port <number>.\",\n );\n // The worker resolves its port the same way, so this is where the app listens.\n const appPort = () =>\n parsePort(\n options.port === undefined ? undefined : String(options.port),\n process.env.PORT,\n );\n const history = options.dashboard\n ? await openHistory({\n directory: process.cwd(),\n days: options.dashboard.historyDays ?? DEFAULT_HISTORY_DAYS,\n warn: (message) => console.warn(message),\n })\n : undefined;\n const telemetry = options.dashboard\n ? new DevTelemetryStore({ history })\n : undefined;\n const docs = telemetry\n ? new DocsHost(telemetry, (message) => console.warn(message))\n : undefined;\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 let generationCount = 0;\n let childGeneration = 0;\n const launch = () => {\n const generation = ++generationCount;\n childGeneration = generation;\n // The new process serves its own inspector once it is up.\n telemetry?.setInspector(undefined);\n telemetry?.recordReload({ kind: \"started\", generation });\n const application = Bun.spawn(\n [\n process.execPath,\n fileURLToPath(worker),\n resolvedEntry,\n String(options.port ?? \"\"),\n options.prefix ?? \"\",\n options.clientOutput ? resolve(options.clientOutput) : \"\",\n telemetry ? \"1\" : \"\",\n ],\n {\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n ipc(message) {\n if (!message || typeof message !== \"object\" || !(\"type\" in message))\n return;\n if (\n telemetry &&\n message.type === \"brick:telemetry\" &&\n \"records\" in message &&\n Array.isArray(message.records)\n ) {\n telemetry.ingest(message.records as TelemetryRecord[], generation);\n }\n if (\n telemetry &&\n message.type === \"brick:error\" &&\n \"phase\" in message &&\n \"error\" in message\n ) {\n telemetry.recordWorkerError(\n message.phase as WorkerErrorPhase,\n message.error as SerializedError,\n generation,\n );\n }\n if (\n message.type === \"brick:contract-ready\" &&\n options.frontend &&\n !frontend &&\n !stopped\n ) {\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 }\n if (\n telemetry &&\n message.type === \"brick:architecture\" &&\n \"architecture\" in message\n ) {\n telemetry.setArchitecture(\n message.architecture as ArchitectureSchema,\n generation,\n );\n }\n if (\n telemetry &&\n message.type === \"brick:inspector\" &&\n generation === childGeneration &&\n \"port\" in message &&\n \"token\" in message\n ) {\n telemetry.setInspector({\n port: message.port as number,\n token: message.token as string,\n });\n }\n if (docs && message.type === \"brick:documentation\") {\n void docs.configure(\n dirname(resolvedEntry),\n \"documentation\" in message\n ? (message.documentation as DocumentationOptions | undefined)\n : undefined,\n );\n }\n if (\n telemetry &&\n message.type === \"brick:api-documents\" &&\n \"documents\" in message &&\n Array.isArray(message.documents)\n ) {\n telemetry.setApiDocuments(\n message.documents as ApiDocument[],\n `http://localhost:${appPort()}`,\n );\n }\n if (telemetry && message.type === \"brick:contract-ready\") {\n telemetry.recordReload({\n kind: \"contract-ready\",\n generation,\n detail: \"browser contract generated\",\n });\n }\n if (\n message.type === \"brick:dependencies\" &&\n \"files\" in message &&\n Array.isArray(message.files)\n ) {\n for (const file of message.files) {\n if (\n typeof file !== \"string\" ||\n file === resolve(options.clientOutput ?? \"_brick/contract.ts\")\n )\n 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 }\n },\n },\n );\n void application.exited.then((code) => {\n if (generation === childGeneration) 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 // Bind the dashboard before the first worker starts, so a port conflict\n // does not leave an application process running.\n const dashboard: DevDashboard | undefined =\n telemetry && options.dashboard\n ? await startDevDashboard({\n port: options.dashboard.port,\n store: telemetry,\n history,\n docs: () => docs?.current,\n restart: () => {\n void restart(\"dashboard\");\n },\n }).catch((error: unknown) => {\n history?.close();\n throw error;\n })\n : undefined;\n if (dashboard) {\n console.log(`📊 Dev dashboard: http://127.0.0.1:${dashboard.port}`);\n }\n let child = launch();\n const watchDirs = [\n ...new Set([resolve(\"src\"), resolve(\"app\"), resolve(resolvedEntry, \"..\")]),\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: childGeneration,\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 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 === resolve(options.clientOutput ?? \"_brick/contract.ts\") ||\n basename(file).startsWith(\".brick-contract-\")\n )\n return;\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 docs?.close();\n history?.close();\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"],"mappings":";;;;;;;;A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ters<typeof Bun.plugin>[0];
4
+ /**
5
+ * The plugin that turns `"use workflow"` and `"use step"` files into workflows and
6
+ * steps. `registerWorkflowTransform` installs it for the running process;
7
+ * `brick build` hands it to `Bun.build`.
8
+ *
9
+ * @param root - The project root, where the SDK is installed. Default: the working directory.
10
+ * @returns The plugin, or `undefined` when the Workflow SDK and its builders are not
11
+ * installed in the project.
12
+ */
13
+ export declare function workflowTransformPlugin(root?: string): Promise<BunPlugin | undefined>;
14
+ /**
15
+ * Make files marked `"use workflow"` or `"use step"` load as workflows and steps.
16
+ *
17
+ * A workflow function gets the `workflowId` that `defineListener({ workflow })`
18
+ * needs, and a step registers itself so the runtime can run it in this process.
19
+ * `brick dev`, `brick start` and `brick worker` call it before they load the app.
20
+ * Call it in a script or test before importing the files, with the project root.
21
+ *
22
+ * It does nothing, and returns `false`, when the Workflow SDK and its builders are
23
+ * not installed in the project. Bun allows plugins once per process, so a second
24
+ * call is ignored.
25
+ *
26
+ * @param root - The project root, where the SDK is installed. Default: the working directory.
27
+ * @returns Whether the transform is active.
28
+ */
29
+ export declare function registerWorkflowTransform(root?: string): Promise<boolean>;
30
+ /**
31
+ * Build the bundle that runs an app's workflows: `flow.mjs` and `manifest.json`
32
+ * in `<root>/.well-known/workflow/v1`, from every file under `root` marked
33
+ * `"use workflow"` or `"use step"`.
34
+ *
35
+ * `brick dev` and `brick start` call it before events start. Call it in a script
36
+ * or test before starting events.
37
+ *
38
+ * @param options - `root`: the project root. Default: the working directory.
39
+ * `reuse`: keep the bundle of the last build when nothing it was built from has
40
+ * changed, which saves about a second on each reload of `brick dev`. Default:
41
+ * `false`, always build.
42
+ * @returns Whether it built the bundle; `false` when it kept the last one.
43
+ * @throws When `@workflow/builders` is not installed in the project.
44
+ */
45
+ export declare function buildWorkflows(options?: {
46
+ root?: string;
47
+ reuse?: boolean;
48
+ }): Promise<boolean>;
49
+ /**
50
+ * Build the workflow bundle an app needs, if it has workflow listeners.
51
+ *
52
+ * @param app - The loaded app.
53
+ * @param options - `reuse`: keep the last bundle when its sources have not changed.
54
+ * @returns Whether the app has a bundle, built now or kept from the last build.
55
+ */
56
+ export declare function buildAppWorkflows(app: BrickApp, options?: {
57
+ reuse?: boolean;
58
+ }): Promise<boolean>;
59
+ //#endregion
60
+ export {};
61
+ //# sourceMappingURL=workflows.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflows.d.ts","names":[],"sources":["../src/workflows.ts"],"mappings":";;KA2BK,YAAY,kBAAkB,IAAI;;;;;;;;;;wBA6CjB,wBACpB,gBACC,QAAQ;;;;;;;;;;;;;;;;wBA8CW,0BACpB,gBACC;;;;;;;;;;;;;;;;wBA4NmB,eACpB;EAAW;EAAe;IACzB;;;;;;;;wBAgFmB,kBACpB,KAAK,UACL;EAAW;IACV"}
@@ -0,0 +1 @@
1
+ export { t as buildAppWorkflows, n as buildWorkflows, r as registerWorkflowTransform, i as workflowTransformPlugin } from "./workflows2.js";