stratal 0.0.15 → 0.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{application-Du0d8O_e.d.mts → application-zG8b-pol.d.mts} +4 -4
- package/dist/{application-Du0d8O_e.d.mts.map → application-zG8b-pol.d.mts.map} +1 -1
- package/dist/{base-email.provider-CNwsPbwm.mjs → base-email.provider-Cuw4OAB0.mjs} +1 -1
- package/dist/{base-email.provider-CNwsPbwm.mjs.map → base-email.provider-Cuw4OAB0.mjs.map} +1 -1
- package/dist/bin/quarry.mjs +47 -43
- package/dist/bin/quarry.mjs.map +1 -1
- package/dist/cache/index.d.mts +2 -2
- package/dist/cache/index.mjs +7 -6
- package/dist/cache/index.mjs.map +1 -1
- package/dist/colors-DJaRDXoS.mjs +16 -0
- package/dist/colors-DJaRDXoS.mjs.map +1 -0
- package/dist/{command-DcebcSrL.d.mts → command-B-QH-Vu3.d.mts} +2 -2
- package/dist/{command-DcebcSrL.d.mts.map → command-B-QH-Vu3.d.mts.map} +1 -1
- package/dist/{command-DG_u5ob2.mjs → command-BvCOD6df.mjs} +10 -9
- package/dist/{command-DG_u5ob2.mjs.map → command-BvCOD6df.mjs.map} +1 -1
- package/dist/config/index.d.mts +2 -2
- package/dist/config/index.mjs +7 -6
- package/dist/config/index.mjs.map +1 -1
- package/dist/cron/index.d.mts +1 -1
- package/dist/cron/index.mjs +1 -1
- package/dist/{cron-manager-BRh86QCS.mjs → cron-manager-DR7fiG6o.mjs} +1 -1
- package/dist/{cron-manager-BRh86QCS.mjs.map → cron-manager-DR7fiG6o.mjs.map} +1 -1
- package/dist/di/index.d.mts +1 -1
- package/dist/email/index.d.mts +3 -3
- package/dist/email/index.mjs +13 -11
- package/dist/email/index.mjs.map +1 -1
- package/dist/{en-uVIaxFXR.mjs → en-DaewN8hc.mjs} +1 -1
- package/dist/{en-uVIaxFXR.mjs.map → en-DaewN8hc.mjs.map} +1 -1
- package/dist/errors/index.d.mts +1 -1
- package/dist/errors-H3TZnVeX.mjs +67 -0
- package/dist/errors-H3TZnVeX.mjs.map +1 -0
- package/dist/events/index.d.mts +2 -2
- package/dist/{gateway-context-90CQEQDR.mjs → gateway-context-BkZ4UKaX.mjs} +2 -2
- package/dist/{gateway-context-90CQEQDR.mjs.map → gateway-context-BkZ4UKaX.mjs.map} +1 -1
- package/dist/guards/index.d.mts +3 -3
- package/dist/guards/index.mjs +1 -1
- package/dist/{guards-DMbsAxSX.mjs → guards-DUk_Kzst.mjs} +1 -1
- package/dist/{guards-DMbsAxSX.mjs.map → guards-DUk_Kzst.mjs.map} +1 -1
- package/dist/i18n/index.d.mts +2 -2
- package/dist/i18n/index.mjs +11 -10
- package/dist/i18n/messages/en/index.d.mts +1 -1
- package/dist/i18n/messages/en/index.mjs +1 -1
- package/dist/i18n/validation/index.d.mts +1 -1
- package/dist/i18n/validation/index.mjs +1 -1
- package/dist/{i18n.module-qNrpIVts.mjs → i18n.module-W8OJxg3d.mjs} +8 -8
- package/dist/{i18n.module-qNrpIVts.mjs.map → i18n.module-W8OJxg3d.mjs.map} +1 -1
- package/dist/{index-D69rxo8H.d.mts → index-BJWm863C.d.mts} +5 -5
- package/dist/{index-D69rxo8H.d.mts.map → index-BJWm863C.d.mts.map} +1 -1
- package/dist/{index-H-Su81aK.d.mts → index-D9iYu2Yc.d.mts} +3 -3
- package/dist/{index-H-Su81aK.d.mts.map → index-D9iYu2Yc.d.mts.map} +1 -1
- package/dist/{index-CpAN9ENH.d.mts → index-DVhdhLvE.d.mts} +2 -2
- package/dist/{index-CpAN9ENH.d.mts.map → index-DVhdhLvE.d.mts.map} +1 -1
- package/dist/{index-CSuHOJc3.d.mts → index-D_w_Rmtd.d.mts} +1 -1
- package/dist/{index-CSuHOJc3.d.mts.map → index-D_w_Rmtd.d.mts.map} +1 -1
- package/dist/{index-Cfkie8JM.d.mts → index-Dp6A5ywM.d.mts} +1 -1
- package/dist/{index-Cfkie8JM.d.mts.map → index-Dp6A5ywM.d.mts.map} +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +16 -15
- package/dist/{is-command-MZDCH-0T.mjs → is-command-BfCgWAcQ.mjs} +2 -2
- package/dist/{is-command-MZDCH-0T.mjs.map → is-command-BfCgWAcQ.mjs.map} +1 -1
- package/dist/{is-seeder-BN9Ej1r7.mjs → is-seeder-CebjZCDn.mjs} +1 -1
- package/dist/{is-seeder-BN9Ej1r7.mjs.map → is-seeder-CebjZCDn.mjs.map} +1 -1
- package/dist/logger/index.d.mts +1 -1
- package/dist/middleware/index.d.mts +1 -1
- package/dist/middleware/index.mjs +2 -2
- package/dist/{middleware-iRhNjsPH.mjs → middleware-C0Ebzswy.mjs} +2 -2
- package/dist/{middleware-iRhNjsPH.mjs.map → middleware-C0Ebzswy.mjs.map} +1 -1
- package/dist/module/index.d.mts +3 -3
- package/dist/module/index.mjs +7 -6
- package/dist/{module-BH7t7BGG.mjs → module-BgdxxzBe.mjs} +4 -4
- package/dist/{module-BH7t7BGG.mjs.map → module-BgdxxzBe.mjs.map} +1 -1
- package/dist/openapi/index.d.mts +3 -3
- package/dist/openapi/index.mjs +11 -10
- package/dist/quarry/index.d.mts +12 -4
- package/dist/quarry/index.d.mts.map +1 -1
- package/dist/quarry/index.mjs +5 -4
- package/dist/{quarry-registry-BPmKVjhG.mjs → quarry-registry-DCwqVcRp.mjs} +11 -3
- package/dist/{quarry-registry-BPmKVjhG.mjs.map → quarry-registry-DCwqVcRp.mjs.map} +1 -1
- package/dist/queue/index.d.mts +1 -1
- package/dist/queue/index.mjs +8 -7
- package/dist/queue/index.mjs.map +1 -1
- package/dist/{queue.module-BdXWUvIM.mjs → queue.module-BZvmeAMj.mjs} +2 -2
- package/dist/{queue.module-BdXWUvIM.mjs.map → queue.module-BZvmeAMj.mjs.map} +1 -1
- package/dist/{resend.provider-CQT5be5E.mjs → resend.provider-BCCACQAU.mjs} +2 -2
- package/dist/{resend.provider-CQT5be5E.mjs.map → resend.provider-BCCACQAU.mjs.map} +1 -1
- package/dist/router/index.d.mts +1 -1
- package/dist/router/index.mjs +11 -10
- package/dist/{router-context-BLn4PrRG.mjs → router-context-BEJe9HEB.mjs} +1 -1
- package/dist/{router-context-BLn4PrRG.mjs.map → router-context-BEJe9HEB.mjs.map} +1 -1
- package/dist/s3-storage.provider-BLlzQYiJ.mjs +336 -0
- package/dist/s3-storage.provider-BLlzQYiJ.mjs.map +1 -0
- package/dist/seeder/index.d.mts +4 -4
- package/dist/seeder/index.mjs +4 -3
- package/dist/{seeder-DatfjJvU.mjs → seeder-Cupi5jl-.mjs} +3 -3
- package/dist/{seeder-DatfjJvU.mjs.map → seeder-Cupi5jl-.mjs.map} +1 -1
- package/dist/{smtp.provider-Cj7BUFbJ.mjs → smtp.provider-B8XtOcHU.mjs} +2 -2
- package/dist/{smtp.provider-Cj7BUFbJ.mjs.map → smtp.provider-B8XtOcHU.mjs.map} +1 -1
- package/dist/storage/index.d.mts +6 -272
- package/dist/storage/index.d.mts.map +1 -1
- package/dist/storage/index.mjs +11 -9
- package/dist/{storage-BtcfgibD.mjs → storage-By_ow2o_.mjs} +34 -410
- package/dist/storage-By_ow2o_.mjs.map +1 -0
- package/dist/{stratal-Cm0Yy8v4.mjs → stratal-CE0iTz4f.mjs} +7 -7
- package/dist/{stratal-Cm0Yy8v4.mjs.map → stratal-CE0iTz4f.mjs.map} +1 -1
- package/dist/{types-N84Ak6YT.d.mts → types-CLhOhYsQ.d.mts} +1 -1
- package/dist/{types-N84Ak6YT.d.mts.map → types-CLhOhYsQ.d.mts.map} +1 -1
- package/dist/{types-Cu4jkeiH.d.mts → types-DahElfUw.d.mts} +1 -1
- package/dist/types-DahElfUw.d.mts.map +1 -0
- package/dist/usage-generator-C9hWziY4.mjs +158 -0
- package/dist/usage-generator-C9hWziY4.mjs.map +1 -0
- package/dist/{validation-Dbt-snjx.mjs → validation-Bh875Lyg.mjs} +1 -1
- package/dist/{validation-Dbt-snjx.mjs.map → validation-Bh875Lyg.mjs.map} +1 -1
- package/dist/websocket/index.d.mts +2 -2
- package/dist/websocket/index.mjs +2 -2
- package/dist/workers/index.d.mts +1 -1
- package/dist/workers/index.mjs +16 -15
- package/dist/workers/index.mjs.map +1 -1
- package/package.json +3 -7
- package/dist/storage-BtcfgibD.mjs.map +0 -1
- package/dist/types-Cu4jkeiH.d.mts.map +0 -1
- package/dist/usage-generator-BTZDk5zx.mjs +0 -75
- package/dist/usage-generator-BTZDk5zx.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stratal-Cm0Yy8v4.mjs","names":["tsyringeRootContainer"],"sources":["../src/application.ts","../src/stratal.ts"],"sourcesContent":["import { injectable, container as tsyringeRootContainer } from 'tsyringe'\nimport { CacheModule } from './cache'\nimport type { CronJob } from './cron/cron-job'\nimport { CronManager } from './cron/cron-manager'\nimport { Container } from './di/container'\nimport { DI_TOKENS } from './di/tokens'\nimport { Scope } from './di/types'\nimport { type StratalEnv } from './env'\nimport { ApplicationError, GlobalErrorHandler } from './errors'\nimport type { EventHandler } from './events'\nimport { EventRegistry, getListenerHandlers } from './events'\nimport type { StratalExecutionContext } from './execution-context'\nimport { I18nModule } from './i18n/i18n.module'\nimport { ConsoleTransport, JsonFormatter, LOGGER_TOKENS, LoggerService, LogLevel, PrettyFormatter } from './logger'\nimport { ModuleRegistry } from './module/module-registry'\nimport type { DynamicModule, ModuleClass } from './module/types'\nimport { OpenAPIModule } from './openapi'\nimport type { Command } from './quarry/command'\nimport { QuarryRegistry } from './quarry/quarry-registry'\nimport type { CommandInput, CommandResult } from './quarry/types'\nimport { type ConsumerRegistry } from './queue/consumer-registry'\nimport type { IQueueConsumer, QueueMessage } from './queue/queue-consumer'\nimport { type QueueManager } from './queue/queue-manager'\nimport { QueueModule } from './queue/queue.module'\nimport { type IController, type RouterContext } from './router'\nimport { HonoApp } from './router/hono-app'\nimport type { VersioningOptions } from './router/types'\nimport { DbSeedCommand, DbSeedListCommand, SEEDER_TOKENS, SeederRegistry, type Seeder } from './seeder'\nimport type { Constructor } from './types'\n\nexport interface ApplicationConfig {\n /** Root application module */\n module: ModuleClass | DynamicModule\n /** Logging configuration. Defaults: level=INFO, formatter='json' */\n logging?: {\n level?: LogLevel\n formatter?: 'json' | 'pretty'\n }\n /**\n * API versioning configuration.\n * When provided, enables URI-based versioning for controllers.\n */\n versioning?: VersioningOptions\n}\n\nexport interface ApplicationOptions extends ApplicationConfig {\n env: StratalEnv\n ctx: StratalExecutionContext\n}\n\n/**\n * Application\n *\n * Main application class managing the two-tier container hierarchy:\n * - Global Container: All services (singletons via tsyringe native)\n * - Request Container: Child of global, context-enriched instances per request\n *\n * @example\n * ```typescript\n * const app = new Application({ module: AppModule, env, ctx })\n * await app.initialize()\n *\n * // Access container via getter\n * const service = app.container.resolve(MY_TOKEN)\n *\n * // Handle HTTP request (via HonoApp)\n * // Handle queue batch\n * await app.handleQueue(batch, 'my-queue')\n * ```\n */\nexport class Application {\n /**\n * Unified Container - manages all DI operations\n */\n private _container: Container\n\n private honoApp!: HonoApp\n private moduleRegistry: ModuleRegistry\n private consumerRegistry!: ConsumerRegistry\n private cronManager!: CronManager\n private quarry!: QuarryRegistry\n private initialized = false\n\n readonly env: StratalEnv\n private readonly appConfig: ApplicationConfig\n\n constructor({ env, ctx, ...config }: ApplicationOptions) {\n this.env = env\n this.appConfig = config\n\n ApplicationError.captureStackTraces = env.ENVIRONMENT !== 'production'\n\n // Create unified Container with explicit child container\n this._container = new Container({\n container: tsyringeRootContainer.createChildContainer()\n })\n\n // Register globally — env and ctx always available\n this._container.registerValue(DI_TOKENS.Application, this)\n this._container.registerValue(DI_TOKENS.CloudflareEnv, env)\n this._container.registerValue(DI_TOKENS.ExecutionContext, ctx)\n\n // Register core infrastructure inline\n this.registerLoggerService()\n this.registerCoreServices()\n\n // Create ModuleRegistry with our Container\n const logger = this._container.resolve<LoggerService>(LOGGER_TOKENS.LoggerService)\n this.moduleRegistry = new ModuleRegistry(this._container, logger)\n\n // Register ModuleRegistry in container so modules can access it in onInitialize\n this._container.registerValue(DI_TOKENS.ModuleRegistry, this.moduleRegistry)\n }\n\n /**\n * Get the Container instance\n */\n get container(): Container {\n return this._container\n }\n\n /**\n * Get the HonoApp instance\n */\n get hono(): HonoApp {\n return this.honoApp\n }\n\n async initialize(): Promise<void> {\n if (this.initialized) {\n return\n }\n\n // Phase 1: Register core infrastructure modules (internal)\n this.moduleRegistry.registerAll([\n I18nModule,\n OpenAPIModule,\n QueueModule,\n CacheModule,\n ])\n\n // Phase 2: Register user's root module (traverses imports)\n this.moduleRegistry.register(this.appConfig.module)\n\n // Phase 3: Initialize all modules\n await this.moduleRegistry.initialize()\n\n // Phase 4: Resolve managers from container\n this.consumerRegistry = this._container.resolve<ConsumerRegistry>(DI_TOKENS.ConsumerRegistry)\n this.cronManager = this._container.resolve<CronManager>(DI_TOKENS.Cron)\n this.quarry = this._container.resolve<QuarryRegistry>(DI_TOKENS.Quarry)\n\n // Phase 5: Create & configure HonoApp\n const logger = this._container.resolve<LoggerService>(LOGGER_TOKENS.LoggerService)\n this.honoApp = new HonoApp(this._container, logger)\n const middlewareConfigs = this.moduleRegistry.getAllMiddlewareConfigs()\n const controllers = this.moduleRegistry.getAllControllers() as Constructor<IController>[]\n await this.honoApp.configure(middlewareConfigs, controllers, this.appConfig.versioning)\n\n // Phase 6: Configure queues, cron, events, commands, seeders\n this.registerQueueConsumers()\n this.registerCronJobs()\n this.registerEventListeners()\n this.registerSeeders()\n this.registerCommands()\n\n this.initialized = true\n }\n\n /**\n * Resolve a service from the container\n */\n resolve<T>(token: symbol): T {\n try {\n return this._container.resolve(token)\n } catch (error) {\n const errorHandler = this._container.resolve<GlobalErrorHandler>(DI_TOKENS.ErrorHandler)\n const errorResponse = errorHandler.handle(error)\n throw errorResponse as unknown as Error\n }\n }\n\n /**\n * Handle queue batch processing\n */\n async handleQueue(batch: MessageBatch, queueName: string): Promise<void> {\n const firstMessage = batch.messages[0]?.body as QueueMessage | undefined\n const locale = firstMessage?.metadata?.locale ?? 'en'\n const mockRouterContext = this.createMockRouterContext(locale)\n\n await this._container.runInRequestScope(mockRouterContext, async (requestContainer) => {\n try {\n const queueManager = requestContainer.resolve<QueueManager>(DI_TOKENS.Queue)\n await queueManager.processBatch(queueName, batch)\n } catch (error) {\n const errorHandler = requestContainer.resolve<GlobalErrorHandler>(DI_TOKENS.ErrorHandler)\n errorHandler.handle(error)\n throw error\n }\n })\n }\n\n /**\n * Handle scheduled cron trigger\n */\n async handleScheduled(controller: ScheduledController): Promise<void> {\n const mockRouterContext = this.createMockRouterContext('en')\n\n await this._container.runInRequestScope(mockRouterContext, async (requestContainer) => {\n try {\n await this.cronManager.executeScheduled(controller)\n } catch (error) {\n const errorHandler = requestContainer.resolve<GlobalErrorHandler>(DI_TOKENS.ErrorHandler)\n errorHandler.handle(error)\n throw error\n }\n })\n }\n\n /**\n * Create mock RouterContext for queue/cron/seeder processing\n */\n createMockRouterContext(locale = 'en'): RouterContext {\n return {\n getLocale: () => locale,\n setLocale: () => { /* no-op */ },\n getContainer: () => this._container,\n } as unknown as RouterContext\n }\n\n async shutdown(): Promise<void> {\n if (!this.initialized) return\n this.initialized = false\n\n await this.moduleRegistry.shutdown()\n\n const logger = this._container.resolve<LoggerService>(LOGGER_TOKENS.LoggerService)\n logger.info('Disposing container...')\n\n await this._container.dispose()\n }\n\n /**\n * Execute a command by name in a request-scoped container.\n */\n async handleCommand(name: string, input?: CommandInput): Promise<CommandResult> {\n const mockContext = this.createMockRouterContext('en')\n return this._container.runInRequestScope(mockContext, async () => {\n return this.quarry.call(name, input)\n })\n }\n\n private registerCommands(): void {\n // Built-in seeder commands (always available)\n const builtinCommands: Constructor<Command>[] = [DbSeedCommand, DbSeedListCommand]\n for (const Cmd of builtinCommands) {\n injectable()(Cmd)\n this._container.register(Cmd, Cmd, Scope.Singleton)\n this.quarry.register(Cmd)\n }\n\n // User commands from modules\n const commands = this.moduleRegistry.getAllCommands()\n if (commands.length === 0) {\n return\n }\n\n for (const CommandClass of commands) {\n this.quarry.register(CommandClass as Constructor<Command>)\n }\n }\n\n private registerSeeders(): void {\n const seeders = this.moduleRegistry.getAllSeeders()\n if (seeders.length === 0) return\n const registry = this._container.resolve<SeederRegistry>(SEEDER_TOKENS.SeederRegistry)\n for (const SeederClass of seeders) {\n registry.register(SeederClass as Constructor<Seeder>)\n }\n }\n\n private registerQueueConsumers(): void {\n for (const ConsumerClass of this.moduleRegistry.getAllConsumers()) {\n const consumer = this._container.resolve(ConsumerClass) as IQueueConsumer\n this.consumerRegistry.register(consumer)\n }\n }\n\n private registerCronJobs(): void {\n for (const JobClass of this.moduleRegistry.getAllJobs()) {\n const job = this._container.resolve(JobClass) as CronJob\n this.cronManager.registerJob(job)\n }\n }\n\n /**\n * Auto-wire `@Listener()` classes with the EventRegistry.\n */\n private registerEventListeners(): void {\n const listeners = this.moduleRegistry.getAllListeners()\n if (listeners.length === 0) {\n return\n }\n\n const eventRegistry = this._container.resolve<EventRegistry>(DI_TOKENS.EventRegistry)\n\n for (const ListenerClass of listeners) {\n const instance = this._container.resolve(ListenerClass) as Record<string, ((...args: unknown[]) => unknown)>\n const handlers = getListenerHandlers(ListenerClass)\n\n for (const { methodName, event, options } of handlers) {\n eventRegistry.on(event, instance[methodName].bind(instance) as EventHandler, options)\n }\n }\n }\n\n /**\n * Register LoggerService and dependencies\n */\n private registerLoggerService(): void {\n const logLevel = this.appConfig.logging?.level ?? LogLevel.INFO\n const formatter = this.appConfig.logging?.formatter ?? 'json'\n\n this._container.registerValue(LOGGER_TOKENS.LogLevelOptions, logLevel)\n\n this._container\n .when(() => formatter === 'pretty')\n .use(LOGGER_TOKENS.Formatter)\n .give(PrettyFormatter)\n .otherwise(JsonFormatter)\n\n this._container.registerSingleton(LOGGER_TOKENS.ConsoleTransport, ConsoleTransport)\n this._container.registerFactory(LOGGER_TOKENS.Transports, (c) => [c.resolve(LOGGER_TOKENS.ConsoleTransport)])\n this._container.registerSingleton(LOGGER_TOKENS.LoggerService, LoggerService)\n }\n\n /**\n * Register core services with explicit scope\n */\n private registerCoreServices(): void {\n this._container.registerSingleton(DI_TOKENS.Cron, CronManager)\n this._container.register(DI_TOKENS.ErrorHandler, GlobalErrorHandler)\n this._container.registerSingleton(DI_TOKENS.EventRegistry, EventRegistry)\n this._container.registerSingleton(DI_TOKENS.Quarry, QuarryRegistry)\n this._container.registerValue(SEEDER_TOKENS.SeederRegistry, new SeederRegistry(this))\n }\n}\n","import 'reflect-metadata'\n\nimport { Application, type ApplicationConfig } from './application'\nimport type { StratalEnv } from './env'\nimport { StratalNotInitializedError } from './errors'\nimport type { HonoApp } from './router/hono-app'\n\n/**\n * Stratal — Hono-style entry point for Cloudflare Workers.\n *\n * Eagerly bootstraps the Application at construction time, dynamically\n * importing `cloudflare:workers` for env and waitUntil.\n *\n * @example\n * ```typescript\n * import { Stratal } from 'stratal'\n * import { AppModule } from './app.module'\n *\n * export default new Stratal({ module: AppModule })\n * ```\n */\nexport class Stratal<Env extends StratalEnv = StratalEnv> {\n private app: Application | null = null\n private initPromise: Promise<Application>\n\n private static _application: Promise<Application> | null = null\n\n constructor(config: ApplicationConfig) {\n this.fetch = this.fetch.bind(this)\n this.queue = this.queue.bind(this)\n this.scheduled = this.scheduled.bind(this)\n\n this.initPromise = this.prepareApp(config)\n Stratal._application = this.initPromise\n }\n\n async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {\n const app = await this.ensureReady()\n return app.hono.fetch(request, env, ctx)\n }\n\n async queue(batch: MessageBatch): Promise<void> {\n const app = await this.ensureReady()\n return app.handleQueue(batch, batch.queue)\n }\n\n async scheduled(controller: ScheduledController): Promise<void> {\n const app = await this.ensureReady()\n return app.handleScheduled(controller)\n }\n\n get hono(): Promise<HonoApp> {\n return this.initPromise.then(app => app.hono)\n }\n\n async shutdown(): Promise<void> {\n try { this.app = await this.initPromise } catch { /* ignore */ }\n if (this.app) {\n await this.app.shutdown()\n this.app = null\n }\n }\n\n /**\n * @internal\n * Resolves the Application instance from the static singleton.\n * Used by worker base classes (DurableObject, Workflow, WorkerEntrypoint)\n * to access the DI container without going through Cloudflare RPC.\n */\n static resolveApplication(): Promise<Application> {\n if (!Stratal._application) {\n throw new StratalNotInitializedError()\n }\n return Stratal._application\n }\n\n private async ensureReady(): Promise<Application> {\n this.app ??= await this.initPromise;\n return this.app\n }\n\n private async prepareApp(config: ApplicationConfig): Promise<Application> {\n const { env, waitUntil } = await import('cloudflare:workers')\n const app = new Application({ ...config, env: env as Env, ctx: { waitUntil } })\n await app.initialize()\n return app\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,IAAa,cAAb,MAAyB;;;;CAIvB;CAEA;CACA;CACA;CACA;CACA;CACA,cAAsB;CAEtB;CACA;CAEA,YAAY,EAAE,KAAK,KAAK,GAAG,UAA8B;AACvD,OAAK,MAAM;AACX,OAAK,YAAY;AAEjB,mBAAiB,qBAAqB,IAAI,gBAAgB;AAG1D,OAAK,aAAa,IAAI,UAAU,EAC9B,WAAWA,UAAsB,sBAAsB,EACxD,CAAC;AAGF,OAAK,WAAW,cAAc,UAAU,aAAa,KAAK;AAC1D,OAAK,WAAW,cAAc,UAAU,eAAe,IAAI;AAC3D,OAAK,WAAW,cAAc,UAAU,kBAAkB,IAAI;AAG9D,OAAK,uBAAuB;AAC5B,OAAK,sBAAsB;EAG3B,MAAM,SAAS,KAAK,WAAW,QAAuB,cAAc,cAAc;AAClF,OAAK,iBAAiB,IAAI,eAAe,KAAK,YAAY,OAAO;AAGjE,OAAK,WAAW,cAAc,UAAU,gBAAgB,KAAK,eAAe;;;;;CAM9E,IAAI,YAAuB;AACzB,SAAO,KAAK;;;;;CAMd,IAAI,OAAgB;AAClB,SAAO,KAAK;;CAGd,MAAM,aAA4B;AAChC,MAAI,KAAK,YACP;AAIF,OAAK,eAAe,YAAY;GAC9B;GACA;GACA;GACA;GACD,CAAC;AAGF,OAAK,eAAe,SAAS,KAAK,UAAU,OAAO;AAGnD,Q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,MAAkC;CAClC;CAEA,OAAe,eAA4C;CAE3D,YAAY,QAA2B;AACrC,OAAK,QAAQ,KAAK,MAAM,KAAK,KAAK;AAClC,OAAK,QAAQ,KAAK,MAAM,KAAK,KAAK;AAClC,OAAK,YAAY,KAAK,UAAU,KAAK,KAAK;AAE1C,OAAK,cAAc,KAAK,WAAW,OAAO;AAC1C,UAAQ,eAAe,KAAK;;CAG9B,MAAM,MAAM,SAAkB,KAAU,KAA0C;AAEhF,UADY,MAAM,KAAK,aAAa,EACzB,KAAK,MAAM,SAAS,KAAK,IAAI;;CAG1C,MAAM,MAAM,OAAoC;AAE9C,UADY,MAAM,KAAK,aAAa,EACzB,YAAY,OAAO,MAAM,MAAM;;CAG5C,MAAM,UAAU,YAAgD;AAE9D,UADY,MAAM,KAAK,aAAa,EACzB,gBAAgB,WAAW;;CAGxC,IAAI,OAAyB;AAC3B,SAAO,KAAK,YAAY,MAAK,QAAO,IAAI,KAAK;;CAG/C,MAAM,WAA0B;AAC9B,MAAI;AAAE,QAAK,MAAM,MAAM,KAAK;UAAoB;AAChD,MAAI,KAAK,KAAK;AACZ,SAAM,KAAK,IAAI,UAAU;AACzB,QAAK,MAAM;;;;;;;;;CAUf,OAAO,qBAA2C;AAChD,MAAI,CAAC,QAAQ,aACX,OAAM,IAAI,4BAA4B;AAExC,SAAO,QAAQ;;CAGjB,MAAc,cAAoC;AAChD,OAAK,QAAQ,MAAM,KAAK;AACxB,SAAO,KAAK;;CAGd,MAAc,WAAW,QAAiD;EACxE,MAAM,EAAE,KAAK,cAAc,MAAM,OAAO;EACxC,MAAM,MAAM,IAAI,YAAY;GAAE,GAAG;GAAa;GAAY,KAAK,EAAE,WAAW;GAAE,CAAC;AAC/E,QAAM,IAAI,YAAY;AACtB,SAAO"}
|
|
1
|
+
{"version":3,"file":"stratal-CE0iTz4f.mjs","names":["tsyringeRootContainer"],"sources":["../src/application.ts","../src/stratal.ts"],"sourcesContent":["import { injectable, container as tsyringeRootContainer } from 'tsyringe'\nimport { CacheModule } from './cache'\nimport type { CronJob } from './cron/cron-job'\nimport { CronManager } from './cron/cron-manager'\nimport { Container } from './di/container'\nimport { DI_TOKENS } from './di/tokens'\nimport { Scope } from './di/types'\nimport { type StratalEnv } from './env'\nimport { ApplicationError, GlobalErrorHandler } from './errors'\nimport type { EventHandler } from './events'\nimport { EventRegistry, getListenerHandlers } from './events'\nimport type { StratalExecutionContext } from './execution-context'\nimport { I18nModule } from './i18n/i18n.module'\nimport { ConsoleTransport, JsonFormatter, LOGGER_TOKENS, LoggerService, LogLevel, PrettyFormatter } from './logger'\nimport { ModuleRegistry } from './module/module-registry'\nimport type { DynamicModule, ModuleClass } from './module/types'\nimport { OpenAPIModule } from './openapi'\nimport type { Command } from './quarry/command'\nimport { QuarryRegistry } from './quarry/quarry-registry'\nimport type { CommandInput, CommandResult } from './quarry/types'\nimport { type ConsumerRegistry } from './queue/consumer-registry'\nimport type { IQueueConsumer, QueueMessage } from './queue/queue-consumer'\nimport { type QueueManager } from './queue/queue-manager'\nimport { QueueModule } from './queue/queue.module'\nimport { type IController, type RouterContext } from './router'\nimport { HonoApp } from './router/hono-app'\nimport type { VersioningOptions } from './router/types'\nimport { DbSeedCommand, DbSeedListCommand, SEEDER_TOKENS, SeederRegistry, type Seeder } from './seeder'\nimport type { Constructor } from './types'\n\nexport interface ApplicationConfig {\n /** Root application module */\n module: ModuleClass | DynamicModule\n /** Logging configuration. Defaults: level=INFO, formatter='json' */\n logging?: {\n level?: LogLevel\n formatter?: 'json' | 'pretty'\n }\n /**\n * API versioning configuration.\n * When provided, enables URI-based versioning for controllers.\n */\n versioning?: VersioningOptions\n}\n\nexport interface ApplicationOptions extends ApplicationConfig {\n env: StratalEnv\n ctx: StratalExecutionContext\n}\n\n/**\n * Application\n *\n * Main application class managing the two-tier container hierarchy:\n * - Global Container: All services (singletons via tsyringe native)\n * - Request Container: Child of global, context-enriched instances per request\n *\n * @example\n * ```typescript\n * const app = new Application({ module: AppModule, env, ctx })\n * await app.initialize()\n *\n * // Access container via getter\n * const service = app.container.resolve(MY_TOKEN)\n *\n * // Handle HTTP request (via HonoApp)\n * // Handle queue batch\n * await app.handleQueue(batch, 'my-queue')\n * ```\n */\nexport class Application {\n /**\n * Unified Container - manages all DI operations\n */\n private _container: Container\n\n private honoApp!: HonoApp\n private moduleRegistry: ModuleRegistry\n private consumerRegistry!: ConsumerRegistry\n private cronManager!: CronManager\n private quarry!: QuarryRegistry\n private initialized = false\n\n readonly env: StratalEnv\n private readonly appConfig: ApplicationConfig\n\n constructor({ env, ctx, ...config }: ApplicationOptions) {\n this.env = env\n this.appConfig = config\n\n ApplicationError.captureStackTraces = env.ENVIRONMENT !== 'production'\n\n // Create unified Container with explicit child container\n this._container = new Container({\n container: tsyringeRootContainer.createChildContainer()\n })\n\n // Register globally — env and ctx always available\n this._container.registerValue(DI_TOKENS.Application, this)\n this._container.registerValue(DI_TOKENS.CloudflareEnv, env)\n this._container.registerValue(DI_TOKENS.ExecutionContext, ctx)\n\n // Register core infrastructure inline\n this.registerLoggerService()\n this.registerCoreServices()\n\n // Create ModuleRegistry with our Container\n const logger = this._container.resolve<LoggerService>(LOGGER_TOKENS.LoggerService)\n this.moduleRegistry = new ModuleRegistry(this._container, logger)\n\n // Register ModuleRegistry in container so modules can access it in onInitialize\n this._container.registerValue(DI_TOKENS.ModuleRegistry, this.moduleRegistry)\n }\n\n /**\n * Get the Container instance\n */\n get container(): Container {\n return this._container\n }\n\n /**\n * Get the HonoApp instance\n */\n get hono(): HonoApp {\n return this.honoApp\n }\n\n async initialize(): Promise<void> {\n if (this.initialized) {\n return\n }\n\n // Phase 1: Register core infrastructure modules (internal)\n this.moduleRegistry.registerAll([\n I18nModule,\n OpenAPIModule,\n QueueModule,\n CacheModule,\n ])\n\n // Phase 2: Register user's root module (traverses imports)\n this.moduleRegistry.register(this.appConfig.module)\n\n // Phase 3: Initialize all modules\n await this.moduleRegistry.initialize()\n\n // Phase 4: Resolve managers from container\n this.consumerRegistry = this._container.resolve<ConsumerRegistry>(DI_TOKENS.ConsumerRegistry)\n this.cronManager = this._container.resolve<CronManager>(DI_TOKENS.Cron)\n this.quarry = this._container.resolve<QuarryRegistry>(DI_TOKENS.Quarry)\n\n // Phase 5: Create & configure HonoApp\n const logger = this._container.resolve<LoggerService>(LOGGER_TOKENS.LoggerService)\n this.honoApp = new HonoApp(this._container, logger)\n const middlewareConfigs = this.moduleRegistry.getAllMiddlewareConfigs()\n const controllers = this.moduleRegistry.getAllControllers() as Constructor<IController>[]\n await this.honoApp.configure(middlewareConfigs, controllers, this.appConfig.versioning)\n\n // Phase 6: Configure queues, cron, events, commands, seeders\n this.registerQueueConsumers()\n this.registerCronJobs()\n this.registerEventListeners()\n this.registerSeeders()\n this.registerCommands()\n\n this.initialized = true\n }\n\n /**\n * Resolve a service from the container\n */\n resolve<T>(token: symbol): T {\n try {\n return this._container.resolve(token)\n } catch (error) {\n const errorHandler = this._container.resolve<GlobalErrorHandler>(DI_TOKENS.ErrorHandler)\n const errorResponse = errorHandler.handle(error)\n throw errorResponse as unknown as Error\n }\n }\n\n /**\n * Handle queue batch processing\n */\n async handleQueue(batch: MessageBatch, queueName: string): Promise<void> {\n const firstMessage = batch.messages[0]?.body as QueueMessage | undefined\n const locale = firstMessage?.metadata?.locale ?? 'en'\n const mockRouterContext = this.createMockRouterContext(locale)\n\n await this._container.runInRequestScope(mockRouterContext, async (requestContainer) => {\n try {\n const queueManager = requestContainer.resolve<QueueManager>(DI_TOKENS.Queue)\n await queueManager.processBatch(queueName, batch)\n } catch (error) {\n const errorHandler = requestContainer.resolve<GlobalErrorHandler>(DI_TOKENS.ErrorHandler)\n errorHandler.handle(error)\n throw error\n }\n })\n }\n\n /**\n * Handle scheduled cron trigger\n */\n async handleScheduled(controller: ScheduledController): Promise<void> {\n const mockRouterContext = this.createMockRouterContext('en')\n\n await this._container.runInRequestScope(mockRouterContext, async (requestContainer) => {\n try {\n await this.cronManager.executeScheduled(controller)\n } catch (error) {\n const errorHandler = requestContainer.resolve<GlobalErrorHandler>(DI_TOKENS.ErrorHandler)\n errorHandler.handle(error)\n throw error\n }\n })\n }\n\n /**\n * Create mock RouterContext for queue/cron/seeder processing\n */\n createMockRouterContext(locale = 'en'): RouterContext {\n return {\n getLocale: () => locale,\n setLocale: () => { /* no-op */ },\n getContainer: () => this._container,\n } as unknown as RouterContext\n }\n\n async shutdown(): Promise<void> {\n if (!this.initialized) return\n this.initialized = false\n\n await this.moduleRegistry.shutdown()\n\n const logger = this._container.resolve<LoggerService>(LOGGER_TOKENS.LoggerService)\n logger.info('Disposing container...')\n\n await this._container.dispose()\n }\n\n /**\n * Execute a command by name in a request-scoped container.\n */\n async handleCommand(name: string, input?: CommandInput): Promise<CommandResult> {\n const mockContext = this.createMockRouterContext('en')\n return this._container.runInRequestScope(mockContext, async () => {\n return this.quarry.call(name, input)\n })\n }\n\n private registerCommands(): void {\n // Built-in seeder commands (always available)\n const builtinCommands: Constructor<Command>[] = [DbSeedCommand, DbSeedListCommand]\n for (const Cmd of builtinCommands) {\n injectable()(Cmd)\n this._container.register(Cmd, Cmd, Scope.Singleton)\n this.quarry.register(Cmd)\n }\n\n // User commands from modules\n const commands = this.moduleRegistry.getAllCommands()\n if (commands.length === 0) {\n return\n }\n\n for (const CommandClass of commands) {\n this.quarry.register(CommandClass as Constructor<Command>)\n }\n }\n\n private registerSeeders(): void {\n const seeders = this.moduleRegistry.getAllSeeders()\n if (seeders.length === 0) return\n const registry = this._container.resolve<SeederRegistry>(SEEDER_TOKENS.SeederRegistry)\n for (const SeederClass of seeders) {\n registry.register(SeederClass as Constructor<Seeder>)\n }\n }\n\n private registerQueueConsumers(): void {\n for (const ConsumerClass of this.moduleRegistry.getAllConsumers()) {\n const consumer = this._container.resolve(ConsumerClass) as IQueueConsumer\n this.consumerRegistry.register(consumer)\n }\n }\n\n private registerCronJobs(): void {\n for (const JobClass of this.moduleRegistry.getAllJobs()) {\n const job = this._container.resolve(JobClass) as CronJob\n this.cronManager.registerJob(job)\n }\n }\n\n /**\n * Auto-wire `@Listener()` classes with the EventRegistry.\n */\n private registerEventListeners(): void {\n const listeners = this.moduleRegistry.getAllListeners()\n if (listeners.length === 0) {\n return\n }\n\n const eventRegistry = this._container.resolve<EventRegistry>(DI_TOKENS.EventRegistry)\n\n for (const ListenerClass of listeners) {\n const instance = this._container.resolve(ListenerClass) as Record<string, ((...args: unknown[]) => unknown)>\n const handlers = getListenerHandlers(ListenerClass)\n\n for (const { methodName, event, options } of handlers) {\n eventRegistry.on(event, instance[methodName].bind(instance) as EventHandler, options)\n }\n }\n }\n\n /**\n * Register LoggerService and dependencies\n */\n private registerLoggerService(): void {\n const logLevel = this.appConfig.logging?.level ?? LogLevel.INFO\n const formatter = this.appConfig.logging?.formatter ?? 'json'\n\n this._container.registerValue(LOGGER_TOKENS.LogLevelOptions, logLevel)\n\n this._container\n .when(() => formatter === 'pretty')\n .use(LOGGER_TOKENS.Formatter)\n .give(PrettyFormatter)\n .otherwise(JsonFormatter)\n\n this._container.registerSingleton(LOGGER_TOKENS.ConsoleTransport, ConsoleTransport)\n this._container.registerFactory(LOGGER_TOKENS.Transports, (c) => [c.resolve(LOGGER_TOKENS.ConsoleTransport)])\n this._container.registerSingleton(LOGGER_TOKENS.LoggerService, LoggerService)\n }\n\n /**\n * Register core services with explicit scope\n */\n private registerCoreServices(): void {\n this._container.registerSingleton(DI_TOKENS.Cron, CronManager)\n this._container.register(DI_TOKENS.ErrorHandler, GlobalErrorHandler)\n this._container.registerSingleton(DI_TOKENS.EventRegistry, EventRegistry)\n this._container.registerSingleton(DI_TOKENS.Quarry, QuarryRegistry)\n this._container.registerValue(SEEDER_TOKENS.SeederRegistry, new SeederRegistry(this))\n }\n}\n","import 'reflect-metadata'\n\nimport { Application, type ApplicationConfig } from './application'\nimport type { StratalEnv } from './env'\nimport { StratalNotInitializedError } from './errors'\nimport type { HonoApp } from './router/hono-app'\n\n/**\n * Stratal — Hono-style entry point for Cloudflare Workers.\n *\n * Eagerly bootstraps the Application at construction time, dynamically\n * importing `cloudflare:workers` for env and waitUntil.\n *\n * @example\n * ```typescript\n * import { Stratal } from 'stratal'\n * import { AppModule } from './app.module'\n *\n * export default new Stratal({ module: AppModule })\n * ```\n */\nexport class Stratal<Env extends StratalEnv = StratalEnv> {\n private app: Application | null = null\n private initPromise: Promise<Application>\n\n private static _application: Promise<Application> | null = null\n\n constructor(config: ApplicationConfig) {\n this.fetch = this.fetch.bind(this)\n this.queue = this.queue.bind(this)\n this.scheduled = this.scheduled.bind(this)\n\n this.initPromise = this.prepareApp(config)\n Stratal._application = this.initPromise\n }\n\n async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {\n const app = await this.ensureReady()\n return app.hono.fetch(request, env, ctx)\n }\n\n async queue(batch: MessageBatch): Promise<void> {\n const app = await this.ensureReady()\n return app.handleQueue(batch, batch.queue)\n }\n\n async scheduled(controller: ScheduledController): Promise<void> {\n const app = await this.ensureReady()\n return app.handleScheduled(controller)\n }\n\n get hono(): Promise<HonoApp> {\n return this.initPromise.then(app => app.hono)\n }\n\n async shutdown(): Promise<void> {\n try { this.app = await this.initPromise } catch { /* ignore */ }\n if (this.app) {\n await this.app.shutdown()\n this.app = null\n }\n }\n\n /**\n * @internal\n * Resolves the Application instance from the static singleton.\n * Used by worker base classes (DurableObject, Workflow, WorkerEntrypoint)\n * to access the DI container without going through Cloudflare RPC.\n */\n static resolveApplication(): Promise<Application> {\n if (!Stratal._application) {\n throw new StratalNotInitializedError()\n }\n return Stratal._application\n }\n\n private async ensureReady(): Promise<Application> {\n this.app ??= await this.initPromise;\n return this.app\n }\n\n private async prepareApp(config: ApplicationConfig): Promise<Application> {\n const { env, waitUntil } = await import('cloudflare:workers')\n const app = new Application({ ...config, env: env as Env, ctx: { waitUntil } })\n await app.initialize()\n return app\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,IAAa,cAAb,MAAyB;;;;CAIvB;CAEA;CACA;CACA;CACA;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MAAM,UAAU,YAAgD;AAE9D,UADY,MAAM,KAAK,aAAa,EACzB,gBAAgB,WAAW;;CAGxC,IAAI,OAAyB;AAC3B,SAAO,KAAK,YAAY,MAAK,QAAO,IAAI,KAAK;;CAG/C,MAAM,WAA0B;AAC9B,MAAI;AAAE,QAAK,MAAM,MAAM,KAAK;UAAoB;AAChD,MAAI,KAAK,KAAK;AACZ,SAAM,KAAK,IAAI,UAAU;AACzB,QAAK,MAAM;;;;;;;;;CAUf,OAAO,qBAA2C;AAChD,MAAI,CAAC,QAAQ,aACX,OAAM,IAAI,4BAA4B;AAExC,SAAO,QAAQ;;CAGjB,MAAc,cAAoC;AAChD,OAAK,QAAQ,MAAM,KAAK;AACxB,SAAO,KAAK;;CAGd,MAAc,WAAW,QAAiD;EACxE,MAAM,EAAE,KAAK,cAAc,MAAM,OAAO;EACxC,MAAM,MAAM,IAAI,YAAY;GAAE,GAAG;GAAa;GAAY,KAAK,EAAE,WAAW;GAAE,CAAC;AAC/E,QAAM,IAAI,YAAY;AACtB,SAAO"}
|
|
@@ -61,4 +61,4 @@ interface ParsedSignature {
|
|
|
61
61
|
}
|
|
62
62
|
//#endregion
|
|
63
63
|
export { ParsedOption as a, ParsedArgument as i, CommandInternals as n, ParsedSignature as o, CommandResult as r, Quarry as s, CommandInput as t };
|
|
64
|
-
//# sourceMappingURL=types-
|
|
64
|
+
//# sourceMappingURL=types-CLhOhYsQ.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types-
|
|
1
|
+
{"version":3,"file":"types-CLhOhYsQ.d.mts","names":[],"sources":["../src/quarry/types.ts"],"mappings":";;AAGA;;KAAY,YAAA,GAAe,MAAA;;;AAK3B;UAAiB,aAAA;EACf,QAAA;EACA,MAAA;EACA,MAAA;AAAA;;;;AAQF;;UAAiB,MAAA;EACf,IAAA,CAAK,IAAA,UAAc,KAAA,GAAQ,YAAA,GAAe,OAAA,CAAQ,aAAA;AAAA;;;;;UAOnC,gBAAA;EACf,MAAA,EAAQ,YAAA;EACR,MAAA;EACA,MAAA;EACA,QAAA;EACA,MAAA,EAAQ,MAAA;AAAA;AALV;;;AAAA,UAWiB,cAAA;EACf,IAAA;EACA,QAAA;EACA,OAAA;EACA,WAAA;EACA,OAAA;AAAA;;;;UAMe,YAAA;EACf,IAAA;EACA,KAAA;EACA,MAAA;EACA,OAAA;EACA,OAAA;EACA,WAAA;AAAA;;;;UAMe,eAAA;EACf,IAAA;EACA,SAAA,EAAW,cAAA;EACX,OAAA,EAAS,YAAA;AAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-DahElfUw.d.mts","names":[],"sources":["../src/types.ts"],"mappings":";;AAeA;;;;;;;;;;;;;KAAY,WAAA,sCAAiD,IAAA,YAAgB,CAAA"}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { t as __exportAll } from "./chunk-D1SwGrFN.mjs";
|
|
2
|
+
import { i as dimWhite, n as cyan, r as dim, s as yellow, t as bold } from "./colors-DJaRDXoS.mjs";
|
|
3
|
+
//#region src/quarry/usage-generator.ts
|
|
4
|
+
var usage_generator_exports = /* @__PURE__ */ __exportAll({
|
|
5
|
+
generateListing: () => generateListing,
|
|
6
|
+
generateUsage: () => generateUsage
|
|
7
|
+
});
|
|
8
|
+
/**
|
|
9
|
+
* Generate formatted help/usage text from a parsed signature.
|
|
10
|
+
*
|
|
11
|
+
* Pure function, edge-compatible.
|
|
12
|
+
*/
|
|
13
|
+
function generateUsage(signature, description) {
|
|
14
|
+
const lines = [];
|
|
15
|
+
lines.push(`${bold("Usage:")} ${bold(cyan("quarry " + buildUsageLine(signature)))}`);
|
|
16
|
+
if (description) {
|
|
17
|
+
lines.push("");
|
|
18
|
+
lines.push(description);
|
|
19
|
+
}
|
|
20
|
+
if (signature.arguments.length > 0) {
|
|
21
|
+
lines.push("");
|
|
22
|
+
lines.push(bold(yellow("Arguments:")));
|
|
23
|
+
const argRows = signature.arguments.map((arg) => {
|
|
24
|
+
const label = arg.name;
|
|
25
|
+
const parts = [];
|
|
26
|
+
if (arg.description) parts.push(arg.description);
|
|
27
|
+
if (arg.isArray) parts.push("(variadic)");
|
|
28
|
+
else if (arg.required) parts.push("(required)");
|
|
29
|
+
else if (arg.default !== void 0) parts.push(dim(`(default: ${arg.default})`));
|
|
30
|
+
else parts.push("(optional)");
|
|
31
|
+
return [label, parts.join(" ")];
|
|
32
|
+
});
|
|
33
|
+
lines.push(...formatTable(argRows));
|
|
34
|
+
}
|
|
35
|
+
if (signature.options.length > 0) {
|
|
36
|
+
lines.push("");
|
|
37
|
+
lines.push(bold(yellow("Options:")));
|
|
38
|
+
const optRows = signature.options.map((opt) => {
|
|
39
|
+
const flagParts = [];
|
|
40
|
+
if (opt.alias) flagParts.push(`-${opt.alias},`);
|
|
41
|
+
flagParts.push(`--${opt.name}`);
|
|
42
|
+
const label = flagParts.join(" ");
|
|
43
|
+
const parts = [];
|
|
44
|
+
if (opt.description) parts.push(opt.description);
|
|
45
|
+
if (!opt.isFlag && !opt.description) parts.push("Accepts a value");
|
|
46
|
+
if (opt.isFlag && !opt.description) parts.push("Boolean flag");
|
|
47
|
+
if (opt.isArray) parts.push("(multiple)");
|
|
48
|
+
if (opt.default !== void 0) parts.push(dim(`(default: ${opt.default})`));
|
|
49
|
+
return [label, parts.join(" ")];
|
|
50
|
+
});
|
|
51
|
+
lines.push(...formatTable(optRows));
|
|
52
|
+
}
|
|
53
|
+
return lines.join("\n");
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Generate a compact command listing with visual hierarchy.
|
|
57
|
+
*/
|
|
58
|
+
function generateListing(commands, signatures, options) {
|
|
59
|
+
const bin = options?.binaryName ?? "quarry";
|
|
60
|
+
const label = options?.binaryLabel ?? "Quarry CLI";
|
|
61
|
+
const version = options?.binaryVersion;
|
|
62
|
+
const lines = [];
|
|
63
|
+
lines.push(bold(`${label}${version ? ` v${version}` : ""}`));
|
|
64
|
+
lines.push("");
|
|
65
|
+
lines.push(bold(yellow("Usage")));
|
|
66
|
+
lines.push(` $ ${bin} <command> [options]`);
|
|
67
|
+
lines.push("");
|
|
68
|
+
if (commands.length === 0) {
|
|
69
|
+
lines.push("No registered commands.");
|
|
70
|
+
return lines.join("\n");
|
|
71
|
+
}
|
|
72
|
+
lines.push(bold(yellow("Commands")));
|
|
73
|
+
const termWidth = typeof process !== "undefined" ? process.stdout.columns ?? 80 : 80;
|
|
74
|
+
for (let i = 0; i < commands.length; i++) {
|
|
75
|
+
const cmd = commands[i];
|
|
76
|
+
const sig = signatures.get(cmd.name);
|
|
77
|
+
const sigParts = [cyan(cmd.name)];
|
|
78
|
+
if (cmd.aliases.length > 0) sigParts.push(cyan(`(alias: ${cmd.aliases.join(", ")})`));
|
|
79
|
+
if (sig) {
|
|
80
|
+
const inlineParts = [];
|
|
81
|
+
for (const arg of sig.arguments) inlineParts.push(formatArgPlaceholder(arg));
|
|
82
|
+
for (const opt of sig.options) {
|
|
83
|
+
const flagStr = opt.alias ? `-${opt.alias},--${opt.name}` : `--${opt.name}`;
|
|
84
|
+
inlineParts.push(`[${flagStr}]`);
|
|
85
|
+
}
|
|
86
|
+
if (inlineParts.length > 0) sigParts.push(dim(inlineParts.join(" ")));
|
|
87
|
+
}
|
|
88
|
+
const sigLine = " " + sigParts.join(" ");
|
|
89
|
+
lines.push(...wrapLine(sigLine, termWidth, " "));
|
|
90
|
+
if (cmd.description) lines.push(` ${dimWhite(cmd.description)}`);
|
|
91
|
+
if (i < commands.length - 1) lines.push("");
|
|
92
|
+
}
|
|
93
|
+
lines.push("");
|
|
94
|
+
lines.push(dimWhite(`Run ${bin} help <command> for detailed information.`));
|
|
95
|
+
return lines.join("\n");
|
|
96
|
+
}
|
|
97
|
+
/** Format a single argument into its placeholder representation (e.g. `<name>`, `[name=default]`). */
|
|
98
|
+
function formatArgPlaceholder(arg) {
|
|
99
|
+
if (arg.isArray) return `<${arg.name}...>`;
|
|
100
|
+
if (arg.required) return `<${arg.name}>`;
|
|
101
|
+
if (arg.default !== void 0) return `[${arg.name}=${arg.default}]`;
|
|
102
|
+
return `[${arg.name}]`;
|
|
103
|
+
}
|
|
104
|
+
/** Build the inline usage line showing the command name with argument and option placeholders. */
|
|
105
|
+
function buildUsageLine(signature) {
|
|
106
|
+
const parts = [signature.name];
|
|
107
|
+
for (const arg of signature.arguments) parts.push(formatArgPlaceholder(arg));
|
|
108
|
+
for (const opt of signature.options) {
|
|
109
|
+
const flagStr = opt.alias ? `-${opt.alias},--${opt.name}` : `--${opt.name}`;
|
|
110
|
+
if (opt.isFlag) parts.push(`[${flagStr}]`);
|
|
111
|
+
else if (opt.isArray) parts.push(`[${flagStr} <value...>]`);
|
|
112
|
+
else parts.push(`[${flagStr} <value>]`);
|
|
113
|
+
}
|
|
114
|
+
return parts.join(" ");
|
|
115
|
+
}
|
|
116
|
+
const ANSI_RE = /\x1b\[[0-9;]*m/g;
|
|
117
|
+
/** Remove ANSI escape sequences from a string. */
|
|
118
|
+
function stripAnsi(s) {
|
|
119
|
+
return s.replace(ANSI_RE, "");
|
|
120
|
+
}
|
|
121
|
+
const TOKEN_RE = /(?:\x1b\[[0-9;]*m)*[^\s\x1b]+(?:\x1b\[[0-9;]*m)*/g;
|
|
122
|
+
/** Wrap a single line at word boundaries, preserving ANSI codes across wrapped segments. */
|
|
123
|
+
function wrapLine(text, maxWidth, continuationIndent) {
|
|
124
|
+
if (stripAnsi(text).length <= maxWidth) return [text];
|
|
125
|
+
const tokens = text.match(TOKEN_RE) ?? [text];
|
|
126
|
+
const lines = [];
|
|
127
|
+
let currentLine = "";
|
|
128
|
+
let currentVisibleLen = 0;
|
|
129
|
+
for (const token of tokens) {
|
|
130
|
+
const tokenVisible = stripAnsi(token).length;
|
|
131
|
+
const separator = currentLine === "" ? "" : " ";
|
|
132
|
+
const separatorLen = separator.length;
|
|
133
|
+
if (currentLine !== "" && currentVisibleLen + separatorLen + tokenVisible > maxWidth) {
|
|
134
|
+
lines.push(currentLine);
|
|
135
|
+
currentLine = continuationIndent + token;
|
|
136
|
+
currentVisibleLen = continuationIndent.length + tokenVisible;
|
|
137
|
+
} else {
|
|
138
|
+
currentLine += separator + token;
|
|
139
|
+
currentVisibleLen += separatorLen + tokenVisible;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (currentLine !== "") lines.push(currentLine);
|
|
143
|
+
return lines;
|
|
144
|
+
}
|
|
145
|
+
/** Format label/description pairs into aligned two-column table rows. */
|
|
146
|
+
function formatTable(rows) {
|
|
147
|
+
if (rows.length === 0) return [];
|
|
148
|
+
const maxLabel = Math.max(...rows.map(([label]) => stripAnsi(label).length));
|
|
149
|
+
const padding = 4;
|
|
150
|
+
return rows.map(([label, desc]) => {
|
|
151
|
+
const visibleLen = stripAnsi(label).length;
|
|
152
|
+
return ` ${label}${" ".repeat(maxLabel - visibleLen + padding)}${desc}`;
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
//#endregion
|
|
156
|
+
export { usage_generator_exports as n, generateUsage as t };
|
|
157
|
+
|
|
158
|
+
//# sourceMappingURL=usage-generator-C9hWziY4.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"usage-generator-C9hWziY4.mjs","names":[],"sources":["../src/quarry/usage-generator.ts"],"sourcesContent":["import { bold, cyan, dim, dimWhite, yellow } from './colors'\nimport type { ParsedSignature } from './types'\n\n/**\n * Generate formatted help/usage text from a parsed signature.\n *\n * Pure function, edge-compatible.\n */\nexport function generateUsage(signature: ParsedSignature, description?: string): string {\n const lines: string[] = []\n\n // Usage line\n lines.push(`${bold('Usage:')} ${bold(cyan('quarry ' + buildUsageLine(signature)))}`)\n\n // Description\n if (description) {\n lines.push('')\n lines.push(description)\n }\n\n // Arguments section\n if (signature.arguments.length > 0) {\n lines.push('')\n lines.push(bold(yellow('Arguments:')))\n const argRows = signature.arguments.map((arg) => {\n const label = arg.name\n const parts: string[] = []\n\n if (arg.description) parts.push(arg.description)\n\n if (arg.isArray) {\n parts.push('(variadic)')\n } else if (arg.required) {\n parts.push('(required)')\n } else if (arg.default !== undefined) {\n parts.push(dim(`(default: ${arg.default})`))\n } else {\n parts.push('(optional)')\n }\n\n return [label, parts.join(' ')] as const\n })\n lines.push(...formatTable(argRows))\n }\n\n // Options section\n if (signature.options.length > 0) {\n lines.push('')\n lines.push(bold(yellow('Options:')))\n const optRows = signature.options.map((opt) => {\n const flagParts: string[] = []\n if (opt.alias) flagParts.push(`-${opt.alias},`)\n flagParts.push(`--${opt.name}`)\n\n const label = flagParts.join(' ')\n const parts: string[] = []\n\n if (opt.description) parts.push(opt.description)\n if (!opt.isFlag && !opt.description) parts.push('Accepts a value')\n if (opt.isFlag && !opt.description) parts.push('Boolean flag')\n if (opt.isArray) parts.push('(multiple)')\n if (opt.default !== undefined) parts.push(dim(`(default: ${opt.default})`))\n\n return [label, parts.join(' ')] as const\n })\n lines.push(...formatTable(optRows))\n }\n\n return lines.join('\\n')\n}\n\nexport interface ListingOptions {\n binaryName?: string\n binaryLabel?: string\n binaryVersion?: string\n}\n\n/**\n * Generate a compact command listing with visual hierarchy.\n */\nexport function generateListing(\n commands: { name: string; description?: string; aliases: string[] }[],\n signatures: Map<string, ParsedSignature>,\n options?: ListingOptions,\n): string {\n const bin = options?.binaryName ?? 'quarry'\n const label = options?.binaryLabel ?? 'Quarry CLI'\n const version = options?.binaryVersion\n\n const lines: string[] = []\n\n // Header\n lines.push(bold(`${label}${version ? ` v${version}` : ''}`))\n lines.push('')\n\n // Usage\n lines.push(bold(yellow('Usage')))\n lines.push(` $ ${bin} <command> [options]`)\n lines.push('')\n\n // Commands\n if (commands.length === 0) {\n lines.push('No registered commands.')\n return lines.join('\\n')\n }\n\n lines.push(bold(yellow('Commands')))\n\n const termWidth = typeof process !== 'undefined'\n ? (process.stdout.columns as number | undefined) ?? 80\n : 80\n\n for (let i = 0; i < commands.length; i++) {\n const cmd = commands[i]\n const sig = signatures.get(cmd.name)\n const sigParts: string[] = [cyan(cmd.name)]\n\n if (cmd.aliases.length > 0) {\n sigParts.push(cyan(`(alias: ${cmd.aliases.join(', ')})`))\n }\n\n if (sig) {\n const inlineParts: string[] = []\n for (const arg of sig.arguments) {\n inlineParts.push(formatArgPlaceholder(arg))\n }\n\n for (const opt of sig.options) {\n const flagStr = opt.alias ? `-${opt.alias},--${opt.name}` : `--${opt.name}`\n inlineParts.push(`[${flagStr}]`)\n }\n\n if (inlineParts.length > 0) {\n sigParts.push(dim(inlineParts.join(' ')))\n }\n }\n\n const sigLine = ' ' + sigParts.join(' ')\n lines.push(...wrapLine(sigLine, termWidth, ' '))\n\n if (cmd.description) {\n lines.push(` ${dimWhite(cmd.description)}`)\n }\n\n if (i < commands.length - 1) {\n lines.push('')\n }\n }\n\n lines.push('')\n\n // Footer\n lines.push(dimWhite(`Run ${bin} help <command> for detailed information.`))\n\n return lines.join('\\n')\n}\n\n/** Format a single argument into its placeholder representation (e.g. `<name>`, `[name=default]`). */\nfunction formatArgPlaceholder(arg: ParsedSignature['arguments'][number]): string {\n if (arg.isArray) return `<${arg.name}...>`\n if (arg.required) return `<${arg.name}>`\n if (arg.default !== undefined) return `[${arg.name}=${arg.default}]`\n return `[${arg.name}]`\n}\n\n/** Build the inline usage line showing the command name with argument and option placeholders. */\nfunction buildUsageLine(signature: ParsedSignature): string {\n const parts = [signature.name]\n\n for (const arg of signature.arguments) {\n parts.push(formatArgPlaceholder(arg))\n }\n\n for (const opt of signature.options) {\n const flagStr = opt.alias ? `-${opt.alias},--${opt.name}` : `--${opt.name}`\n\n if (opt.isFlag) {\n parts.push(`[${flagStr}]`)\n } else if (opt.isArray) {\n parts.push(`[${flagStr} <value...>]`)\n } else {\n parts.push(`[${flagStr} <value>]`)\n }\n }\n\n return parts.join(' ')\n}\n\n// eslint-disable-next-line no-control-regex\nconst ANSI_RE = /\\x1b\\[[0-9;]*m/g\n\n/** Remove ANSI escape sequences from a string. */\nfunction stripAnsi(s: string): string {\n return s.replace(ANSI_RE, '')\n}\n\n// eslint-disable-next-line no-control-regex\nconst TOKEN_RE = /(?:\\x1b\\[[0-9;]*m)*[^\\s\\x1b]+(?:\\x1b\\[[0-9;]*m)*/g\n\n/** Wrap a single line at word boundaries, preserving ANSI codes across wrapped segments. */\nfunction wrapLine(text: string, maxWidth: number, continuationIndent: string): string[] {\n const visibleLen = stripAnsi(text).length\n if (visibleLen <= maxWidth) return [text]\n\n const tokens = text.match(TOKEN_RE) ?? [text]\n\n const lines: string[] = []\n let currentLine = ''\n let currentVisibleLen = 0\n\n for (const token of tokens) {\n const tokenVisible = stripAnsi(token).length\n const separator = currentLine === '' ? '' : ' '\n const separatorLen = separator.length\n\n if (currentLine !== '' && currentVisibleLen + separatorLen + tokenVisible > maxWidth) {\n lines.push(currentLine)\n currentLine = continuationIndent + token\n currentVisibleLen = continuationIndent.length + tokenVisible\n } else {\n currentLine += separator + token\n currentVisibleLen += separatorLen + tokenVisible\n }\n }\n\n if (currentLine !== '') {\n lines.push(currentLine)\n }\n\n return lines\n}\n\n/** Format label/description pairs into aligned two-column table rows. */\nfunction formatTable(rows: readonly (readonly [string, string])[]): string[] {\n if (rows.length === 0) return []\n\n const maxLabel = Math.max(...rows.map(([label]) => stripAnsi(label).length))\n const padding = 4\n\n return rows.map(([label, desc]) => {\n const visibleLen = stripAnsi(label).length\n const pad = ' '.repeat(maxLabel - visibleLen + padding)\n return ` ${label}${pad}${desc}`\n })\n}\n"],"mappings":";;;;;;;;;;;;AAQA,SAAgB,cAAc,WAA4B,aAA8B;CACtF,MAAM,QAAkB,EAAE;AAG1B,OAAM,KAAK,GAAG,KAAK,SAAS,CAAC,GAAG,KAAK,KAAK,YAAY,eAAe,UAAU,CAAC,CAAC,GAAG;AAGpF,KAAI,aAAa;AACf,QAAM,KAAK,GAAG;AACd,QAAM,KAAK,YAAY;;AAIzB,KAAI,UAAU,UAAU,SAAS,GAAG;AAClC,QAAM,KAAK,GAAG;AACd,QAAM,KAAK,KAAK,OAAO,aAAa,CAAC,CAAC;EACtC,MAAM,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oB;AAExB,MAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,eAAe,UAAU,MAAM,CAAC;EACtC,MAAM,YAAY,gBAAgB,KAAK,KAAK;EAC5C,MAAM,eAAe,UAAU;AAE/B,MAAI,gBAAgB,MAAM,oBAAoB,eAAe,eAAe,UAAU;AACpF,SAAM,KAAK,YAAY;AACvB,iBAAc,qBAAqB;AACnC,uBAAoB,mBAAmB,SAAS;SAC3C;AACL,kBAAe,YAAY;AAC3B,wBAAqB,eAAe;;;AAIxC,KAAI,gBAAgB,GAClB,OAAM,KAAK,YAAY;AAGzB,QAAO;;;AAIT,SAAS,YAAY,MAAwD;AAC3E,KAAI,KAAK,WAAW,EAAG,QAAO,EAAE;CAEhC,MAAM,WAAW,KAAK,IAAI,GAAG,KAAK,KAAK,CAAC,WAAW,UAAU,MAAM,CAAC,OAAO,CAAC;CAC5E,MAAM,UAAU;AAEhB,QAAO,KAAK,KAAK,CAAC,OAAO,UAAU;EACjC,MAAM,aAAa,UAAU,MAAM,CAAC;AAEpC,SAAO,KAAK,QADA,IAAI,OAAO,WAAW,aAAa,QAAQ,GAC7B;GAC1B"}
|
|
@@ -191,4 +191,4 @@ __reExport(validation_exports, import__hono_zod_openapi);
|
|
|
191
191
|
//#endregion
|
|
192
192
|
export { withI18n as a, z as i, ZodError as n, backendErrorMap as o, validation_exports as r, runWithErrorMapContext as s, OpenAPIHono as t };
|
|
193
193
|
|
|
194
|
-
//# sourceMappingURL=validation-
|
|
194
|
+
//# sourceMappingURL=validation-Bh875Lyg.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation-Dbt-snjx.mjs","names":[],"sources":["../src/i18n/validation/validation.error-map.ts","../src/i18n/validation/validation.context.ts","../src/i18n/validation/with-i18n.ts","../src/i18n/validation/index.ts"],"sourcesContent":["import type {\n $ZodErrorMap,\n $ZodIssueInvalidKey,\n $ZodIssueInvalidStringFormat,\n $ZodIssueInvalidType,\n $ZodIssueInvalidUnion,\n $ZodIssueNotMultipleOf,\n $ZodIssueTooBig,\n $ZodIssueTooSmall,\n $ZodIssueUnrecognizedKeys,\n $ZodRawIssue,\n} from 'zod/v4/core'\nimport type { MessageKeys } from '../i18n.types'\nimport type { ErrorMapContext } from './validation.types'\n\n/**\n * Type guards for narrowing Zod v4 issue types\n */\nfunction isInvalidType(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueInvalidType> {\n return issue.code === 'invalid_type'\n}\n\nfunction isTooBig(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueTooBig> {\n return issue.code === 'too_big'\n}\n\nfunction isTooSmall(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueTooSmall> {\n return issue.code === 'too_small'\n}\n\nfunction isInvalidFormat(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueInvalidStringFormat> {\n return issue.code === 'invalid_format'\n}\n\nfunction isNotMultipleOf(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueNotMultipleOf> {\n return issue.code === 'not_multiple_of'\n}\n\nfunction isUnrecognizedKeys(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueUnrecognizedKeys> {\n return issue.code === 'unrecognized_keys'\n}\n\nfunction isInvalidUnion(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueInvalidUnion> {\n return issue.code === 'invalid_union'\n}\n\nfunction isInvalidKey(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueInvalidKey> {\n return issue.code === 'invalid_key'\n}\n\n/**\n * Maps Zod issue codes to zodI18n message keys\n * Adapted for Zod v4's simpler issue code system\n */\nfunction getMessageKey(issue: $ZodRawIssue): MessageKeys {\n if (isInvalidType(issue)) {\n if (issue.input === undefined) {\n return 'zodI18n.errors.required'\n }\n return 'zodI18n.errors.invalid_type'\n }\n\n if (isTooSmall(issue)) {\n const typeKey = issue.origin || 'string'\n const exactKey = issue.exact\n ? 'exact'\n : issue.inclusive\n ? 'inclusive'\n : 'not_inclusive'\n return `zodI18n.errors.too_small.${typeKey}.${exactKey}` as MessageKeys\n }\n\n if (isTooBig(issue)) {\n const typeKey = issue.origin || 'string'\n const exactKey = issue.exact\n ? 'exact'\n : issue.inclusive\n ? 'inclusive'\n : 'not_inclusive'\n return `zodI18n.errors.too_big.${typeKey}.${exactKey}` as MessageKeys\n }\n\n if (isInvalidFormat(issue)) {\n // Map v4's format to v3-style validation keys\n return `zodI18n.errors.invalid_string.${issue.format}` as MessageKeys\n }\n\n if (isNotMultipleOf(issue)) {\n return 'zodI18n.errors.not_multiple_of'\n }\n\n if (isUnrecognizedKeys(issue)) {\n return 'zodI18n.errors.unrecognized_keys'\n }\n\n if (isInvalidUnion(issue)) {\n return 'zodI18n.errors.invalid_union'\n }\n\n if (isInvalidKey(issue)) {\n // v4: Replaces invalid_enum_value, invalid_literal\n return 'zodI18n.errors.invalid_enum_value'\n }\n\n // invalid_element, invalid_value, or unknown codes\n return 'zodI18n.errors.custom.default'\n}\n\n/**\n * Extracts interpolation parameters from Zod issue\n * Uses proper type narrowing for v4\n */\nfunction getMessageParams(issue: $ZodRawIssue): Record<string, unknown> {\n const params: Record<string, unknown> = {}\n\n if (isInvalidType(issue)) {\n params.expected = issue.expected\n params.received = String(issue.input)\n return params\n }\n\n if (isUnrecognizedKeys(issue)) {\n params.keys = issue.keys.join(', ')\n return params\n }\n\n if (isInvalidKey(issue)) {\n // v4: For enums and records\n // Since v4 doesn't have options field, we'll use generic message\n return params\n }\n\n if (isInvalidFormat(issue)) {\n params.validation = issue.format\n\n // Check for specific string format issues with additional fields\n if ('prefix' in issue) {\n params.startsWith = (issue as { prefix?: string }).prefix\n }\n if ('suffix' in issue) {\n params.endsWith = (issue as { suffix?: string }).suffix\n }\n if ('includes' in issue) {\n params.includes = (issue as { includes?: string }).includes\n }\n if (issue.pattern) {\n params.pattern = issue.pattern\n }\n\n return params\n }\n\n if (isTooSmall(issue)) {\n params.minimum = issue.minimum\n params.type = issue.origin\n if (issue.origin === 'date') {\n params.minimum = new Date(Number(issue.minimum)).toLocaleDateString()\n }\n return params\n }\n\n if (isTooBig(issue)) {\n params.maximum = issue.maximum\n params.type = issue.origin\n if (issue.origin === 'date') {\n params.maximum = new Date(Number(issue.maximum)).toLocaleDateString()\n }\n return params\n }\n\n if (isNotMultipleOf(issue)) {\n params.multipleOf = issue.divisor\n return params\n }\n\n return params\n}\n\n/**\n * Creates a Zod error map that uses i18n for translation\n * Uses Zod v4 native $ZodErrorMap signature (no ctx parameter)\n */\nexport function createI18nErrorMap(getContext: () => ErrorMapContext | undefined): $ZodErrorMap {\n return (issue: $ZodRawIssue): { message: string } => {\n // Get message key and params for this issue\n const messageKey = getMessageKey(issue)\n const messageParams = getMessageParams(issue)\n\n // Get translation context\n const context = getContext()\n\n if (!context) {\n // Fallback: Use English messages directly\n // This handles config validation at startup, tests, etc.\n return { message: 'Invalid input' }\n }\n\n // Normal flow: Use context-aware i18n (respects user locale)\n return {\n message: context.t(messageKey, messageParams),\n }\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { ErrorMapContext } from './validation.types'\nimport { createI18nErrorMap } from './validation.error-map'\n\n/**\n * AsyncLocalStorage for storing request-scoped ErrorMapContext\n * Allows error map to access I18nService without passing through function calls\n */\nexport const errorMapContextStorage = new AsyncLocalStorage<ErrorMapContext>()\n\n/**\n * Gets the current error map context from AsyncLocalStorage\n */\nfunction getErrorMapContext(): ErrorMapContext | undefined {\n return errorMapContextStorage.getStore()\n}\n\n/**\n * Backend error map that accesses I18nService from AsyncLocalStorage\n * Must be initialized in router middleware after locale detection\n */\nexport const backendErrorMap = createI18nErrorMap(getErrorMapContext)\n\n/**\n * Runs a function within an error map context\n * Used by router middleware to provide I18nService to validation\n *\n * @example\n * ```typescript\n * router.use('*', async (c, next) => {\n * const i18nService = c.get('i18nService')\n * const locale = c.get('locale')\n *\n * return runWithErrorMapContext(\n * {\n * t: (key, params) => i18nService.t(key, params),\n * locale,\n * },\n * () => next()\n * )\n * })\n * ```\n */\nexport function runWithErrorMapContext<T>(\n context: ErrorMapContext,\n fn: () => T\n): T {\n return errorMapContextStorage.run(context, fn)\n}\n","import type { MessageKeys } from '../i18n.types'\nimport { errorMapContextStorage } from './validation.context'\n\n/**\n * Type-safe helper for creating custom Zod error messages with i18n support (Backend)\n *\n * Usage with .refine():\n * ```typescript\n * const schema = z.string().refine(\n * (val) => val.length > 5,\n * withI18n('validation.minLength', { min: 5 })\n * )\n * ```\n *\n * Usage with built-in validators:\n * ```typescript\n * const schema = z.string().min(5, withI18n('validation.minLength', { min: 5 }))\n * const schema = z.string().email(withI18n('validation.email'))\n * ```\n *\n * Note: This is the backend version using AsyncLocalStorage.\n * For frontend, use withI18nFrontend from the frontend validation module\n *\n * @param key - Message key from shared i18n messages (type-safe via MessageKeys)\n * @param params - Optional interpolation parameters for the message\n * @returns Zod error configuration object with translated message\n */\nexport function withI18n(\n key: MessageKeys,\n params?: Record<string, unknown>\n): { error: () => string } {\n return {\n error: () => {\n // Get i18n context from AsyncLocalStorage (backend)\n // This is set by the router middleware before validation\n const context = errorMapContextStorage.getStore()\n\n // Translate using context if available, otherwise fallback to generic message\n const message = context\n ? context.t(key, params as Record<string, string | number> | undefined)\n : 'Invalid input'\n\n return message\n },\n }\n}\n","// Consolidated zod - single source from @hono/zod-openapi (superset of zod)\nexport { OpenAPIHono, z } from '@hono/zod-openapi'\nexport type * from 'zod'\nexport { ZodError } from 'zod'\n\n// OpenAPI utilities\nexport * from '@hono/zod-openapi'\nexport type { OpenAPIObject, PathItemObject } from 'openapi3-ts/oas30'\n\n// Helpers\nexport { withI18n } from './with-i18n'\n\n// Backend utilities\nexport { backendErrorMap, runWithErrorMapContext } from './validation.context'\n\n// Types\nexport type { ErrorMapContext, I18nErrorMetadata, LocaleProvider, ZodCustomIssue } from './validation.types'\n\n"],"mappings":";;;;;;;;AAkBA,SAAS,cAAc,OAAkE;AACvF,QAAO,MAAM,SAAS;;AAGxB,SAAS,SAAS,OAA6D;AAC7E,QAAO,MA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AOjD,SAJgB,UACZ,QAAQ,EAAE,KAAK,OAAsD,GACrE;IAIP"}
|
|
1
|
+
{"version":3,"file":"validation-Bh875Lyg.mjs","names":[],"sources":["../src/i18n/validation/validation.error-map.ts","../src/i18n/validation/validation.context.ts","../src/i18n/validation/with-i18n.ts","../src/i18n/validation/index.ts"],"sourcesContent":["import type {\n $ZodErrorMap,\n $ZodIssueInvalidKey,\n $ZodIssueInvalidStringFormat,\n $ZodIssueInvalidType,\n $ZodIssueInvalidUnion,\n $ZodIssueNotMultipleOf,\n $ZodIssueTooBig,\n $ZodIssueTooSmall,\n $ZodIssueUnrecognizedKeys,\n $ZodRawIssue,\n} from 'zod/v4/core'\nimport type { MessageKeys } from '../i18n.types'\nimport type { ErrorMapContext } from './validation.types'\n\n/**\n * Type guards for narrowing Zod v4 issue types\n */\nfunction isInvalidType(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueInvalidType> {\n return issue.code === 'invalid_type'\n}\n\nfunction isTooBig(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueTooBig> {\n return issue.code === 'too_big'\n}\n\nfunction isTooSmall(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueTooSmall> {\n return issue.code === 'too_small'\n}\n\nfunction isInvalidFormat(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueInvalidStringFormat> {\n return issue.code === 'invalid_format'\n}\n\nfunction isNotMultipleOf(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueNotMultipleOf> {\n return issue.code === 'not_multiple_of'\n}\n\nfunction isUnrecognizedKeys(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueUnrecognizedKeys> {\n return issue.code === 'unrecognized_keys'\n}\n\nfunction isInvalidUnion(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueInvalidUnion> {\n return issue.code === 'invalid_union'\n}\n\nfunction isInvalidKey(issue: $ZodRawIssue): issue is $ZodRawIssue<$ZodIssueInvalidKey> {\n return issue.code === 'invalid_key'\n}\n\n/**\n * Maps Zod issue codes to zodI18n message keys\n * Adapted for Zod v4's simpler issue code system\n */\nfunction getMessageKey(issue: $ZodRawIssue): MessageKeys {\n if (isInvalidType(issue)) {\n if (issue.input === undefined) {\n return 'zodI18n.errors.required'\n }\n return 'zodI18n.errors.invalid_type'\n }\n\n if (isTooSmall(issue)) {\n const typeKey = issue.origin || 'string'\n const exactKey = issue.exact\n ? 'exact'\n : issue.inclusive\n ? 'inclusive'\n : 'not_inclusive'\n return `zodI18n.errors.too_small.${typeKey}.${exactKey}` as MessageKeys\n }\n\n if (isTooBig(issue)) {\n const typeKey = issue.origin || 'string'\n const exactKey = issue.exact\n ? 'exact'\n : issue.inclusive\n ? 'inclusive'\n : 'not_inclusive'\n return `zodI18n.errors.too_big.${typeKey}.${exactKey}` as MessageKeys\n }\n\n if (isInvalidFormat(issue)) {\n // Map v4's format to v3-style validation keys\n return `zodI18n.errors.invalid_string.${issue.format}` as MessageKeys\n }\n\n if (isNotMultipleOf(issue)) {\n return 'zodI18n.errors.not_multiple_of'\n }\n\n if (isUnrecognizedKeys(issue)) {\n return 'zodI18n.errors.unrecognized_keys'\n }\n\n if (isInvalidUnion(issue)) {\n return 'zodI18n.errors.invalid_union'\n }\n\n if (isInvalidKey(issue)) {\n // v4: Replaces invalid_enum_value, invalid_literal\n return 'zodI18n.errors.invalid_enum_value'\n }\n\n // invalid_element, invalid_value, or unknown codes\n return 'zodI18n.errors.custom.default'\n}\n\n/**\n * Extracts interpolation parameters from Zod issue\n * Uses proper type narrowing for v4\n */\nfunction getMessageParams(issue: $ZodRawIssue): Record<string, unknown> {\n const params: Record<string, unknown> = {}\n\n if (isInvalidType(issue)) {\n params.expected = issue.expected\n params.received = String(issue.input)\n return params\n }\n\n if (isUnrecognizedKeys(issue)) {\n params.keys = issue.keys.join(', ')\n return params\n }\n\n if (isInvalidKey(issue)) {\n // v4: For enums and records\n // Since v4 doesn't have options field, we'll use generic message\n return params\n }\n\n if (isInvalidFormat(issue)) {\n params.validation = issue.format\n\n // Check for specific string format issues with additional fields\n if ('prefix' in issue) {\n params.startsWith = (issue as { prefix?: string }).prefix\n }\n if ('suffix' in issue) {\n params.endsWith = (issue as { suffix?: string }).suffix\n }\n if ('includes' in issue) {\n params.includes = (issue as { includes?: string }).includes\n }\n if (issue.pattern) {\n params.pattern = issue.pattern\n }\n\n return params\n }\n\n if (isTooSmall(issue)) {\n params.minimum = issue.minimum\n params.type = issue.origin\n if (issue.origin === 'date') {\n params.minimum = new Date(Number(issue.minimum)).toLocaleDateString()\n }\n return params\n }\n\n if (isTooBig(issue)) {\n params.maximum = issue.maximum\n params.type = issue.origin\n if (issue.origin === 'date') {\n params.maximum = new Date(Number(issue.maximum)).toLocaleDateString()\n }\n return params\n }\n\n if (isNotMultipleOf(issue)) {\n params.multipleOf = issue.divisor\n return params\n }\n\n return params\n}\n\n/**\n * Creates a Zod error map that uses i18n for translation\n * Uses Zod v4 native $ZodErrorMap signature (no ctx parameter)\n */\nexport function createI18nErrorMap(getContext: () => ErrorMapContext | undefined): $ZodErrorMap {\n return (issue: $ZodRawIssue): { message: string } => {\n // Get message key and params for this issue\n const messageKey = getMessageKey(issue)\n const messageParams = getMessageParams(issue)\n\n // Get translation context\n const context = getContext()\n\n if (!context) {\n // Fallback: Use English messages directly\n // This handles config validation at startup, tests, etc.\n return { message: 'Invalid input' }\n }\n\n // Normal flow: Use context-aware i18n (respects user locale)\n return {\n message: context.t(messageKey, messageParams),\n }\n }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { ErrorMapContext } from './validation.types'\nimport { createI18nErrorMap } from './validation.error-map'\n\n/**\n * AsyncLocalStorage for storing request-scoped ErrorMapContext\n * Allows error map to access I18nService without passing through function calls\n */\nexport const errorMapContextStorage = new AsyncLocalStorage<ErrorMapContext>()\n\n/**\n * Gets the current error map context from AsyncLocalStorage\n */\nfunction getErrorMapContext(): ErrorMapContext | undefined {\n return errorMapContextStorage.getStore()\n}\n\n/**\n * Backend error map that accesses I18nService from AsyncLocalStorage\n * Must be initialized in router middleware after locale detection\n */\nexport const backendErrorMap = createI18nErrorMap(getErrorMapContext)\n\n/**\n * Runs a function within an error map context\n * Used by router middleware to provide I18nService to validation\n *\n * @example\n * ```typescript\n * router.use('*', async (c, next) => {\n * const i18nService = c.get('i18nService')\n * const locale = c.get('locale')\n *\n * return runWithErrorMapContext(\n * {\n * t: (key, params) => i18nService.t(key, params),\n * locale,\n * },\n * () => next()\n * )\n * })\n * ```\n */\nexport function runWithErrorMapContext<T>(\n context: ErrorMapContext,\n fn: () => T\n): T {\n return errorMapContextStorage.run(context, fn)\n}\n","import type { MessageKeys } from '../i18n.types'\nimport { errorMapContextStorage } from './validation.context'\n\n/**\n * Type-safe helper for creating custom Zod error messages with i18n support (Backend)\n *\n * Usage with .refine():\n * ```typescript\n * const schema = z.string().refine(\n * (val) => val.length > 5,\n * withI18n('validation.minLength', { min: 5 })\n * )\n * ```\n *\n * Usage with built-in validators:\n * ```typescript\n * const schema = z.string().min(5, withI18n('validation.minLength', { min: 5 }))\n * const schema = z.string().email(withI18n('validation.email'))\n * ```\n *\n * Note: This is the backend version using AsyncLocalStorage.\n * For frontend, use withI18nFrontend from the frontend validation module\n *\n * @param key - Message key from shared i18n messages (type-safe via MessageKeys)\n * @param params - Optional interpolation parameters for the message\n * @returns Zod error configuration object with translated message\n */\nexport function withI18n(\n key: MessageKeys,\n params?: Record<string, unknown>\n): { error: () => string } {\n return {\n error: () => {\n // Get i18n context from AsyncLocalStorage (backend)\n // This is set by the router middleware before validation\n const context = errorMapContextStorage.getStore()\n\n // Translate using context if available, otherwise fallback to generic message\n const message = context\n ? context.t(key, params as Record<string, string | number> | undefined)\n : 'Invalid input'\n\n return message\n },\n }\n}\n","// Consolidated zod - single source from @hono/zod-openapi (superset of zod)\nexport { OpenAPIHono, z } from '@hono/zod-openapi'\nexport type * from 'zod'\nexport { ZodError } from 'zod'\n\n// OpenAPI utilities\nexport * from '@hono/zod-openapi'\nexport type { OpenAPIObject, PathItemObject } from 'openapi3-ts/oas30'\n\n// Helpers\nexport { withI18n } from './with-i18n'\n\n// Backend utilities\nexport { backendErrorMap, runWithErrorMapContext } from './validation.context'\n\n// Types\nexport type { ErrorMapContext, I18nErrorMetadata, LocaleProvider, ZodCustomIssue } from './validation.types'\n\n"],"mappings":";;;;;;;;AAkBA,SAAS,cAAc,OAAkE;AACvF,QAAO,MAAM,SAAS;;AAGxB,SAAS,SAAS,OAA6D;AAC7E,QAAO,MAAM,SAAS;;AAGxB,SAAS,WAAW,OAA+D;AACjF,QAAO,MAAM,SAAS;;AAGxB,SAAS,gBAAgB,OAA0E;AACjG,QAAO,MAAM,SAAS;;AAGxB,SAAS,gBAAgB,OAAoE;AAC3F,QAAO,MAAM,SAAS;;AAGxB,SAAS,mBAAmB,OAAuE;AACjG,QAAO,MAAM,SAAS;;AAGxB,SAAS,eAAe,OAAmE;AACzF,QAAO,MAAM,SAAS;;AAGxB,SAAS,aAAa,OAAiE;AACrF,QAAO,MAAM,SAAS;;;;;;AAOxB,SAAS,cAAc,OAAkC;AACvD,KAAI,cAAc,MAAM,EAAE;AACxB,MAAI,MAAM,UAAU,KAAA,EAClB,QAAO;AAET,SAAO;;AAGT,KAAI,WAAW,MAAM,CAOnB,QAAO,4BANS,MAAM,UAAU,SAMW,GAL1B,MAAM,QACnB,UACA,MAAM,YACJ,cACA;AAIR,KAAI,SAAS,MAAM,CAOjB,QAAO,0BANS,MAAM,UAAU,SAMS,GALxB,MAAM,QACnB,UACA,MAAM,YACJ,cACA;AAIR,KAAI,gBAAgB,MAAM,CAExB,QAAO,iCAAiC,MAAM;AAGhD,KAAI,gBAAgB,MAAM,CACxB,QAAO;AAGT,KAAI,mBAAmB,MAAM,CAC3B,QAAO;AAGT,KAAI,eAAe,MAAM,CACvB,QAAO;AAGT,KAAI,aAAa,MAAM,CAErB,QAAO;AAIT,QAAO;;;;;;AAOT,SAAS,iBAAiB,OAA8C;CACtE,MAAM,SAAkC,E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oC;;;;AAK9E,SAAS,qBAAkD;AACzD,QAAO,uBAAuB,UAAU;;;;;;AAO1C,MAAa,kBAAkB,mBAAmB,mBAAmB;;;;;;;;;;;;;;;;;;;;;AAsBrE,SAAgB,uBACd,SACA,IACG;AACH,QAAO,uBAAuB,IAAI,SAAS,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACpBhD,SAAgB,SACd,KACA,QACyB;AACzB,QAAO,EACL,aAAa;EAGX,MAAM,UAAU,uBAAuB,UAAU;AAOjD,SAJgB,UACZ,QAAQ,EAAE,KAAK,OAAsD,GACrE;IAIP"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Et as ControllerOptions, Nt as RouterEnv, Tt as RouterContext, s as ApplicationError, wt as ContextQueryResult } from "../index-
|
|
2
|
-
import { t as Constructor } from "../types-
|
|
1
|
+
import { Et as ControllerOptions, Nt as RouterEnv, Tt as RouterContext, s as ApplicationError, wt as ContextQueryResult } from "../index-BJWm863C.mjs";
|
|
2
|
+
import { t as Constructor } from "../types-DahElfUw.mjs";
|
|
3
3
|
import { Context } from "hono";
|
|
4
4
|
import { WSContext, WSContext as WSContext$1, WSEvents, WSMessageReceive, WSReadyState, WSReadyState as WSReadyState$1 } from "hono/ws";
|
|
5
5
|
|
package/dist/websocket/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "../errors-CtCi1wn6.mjs";
|
|
2
2
|
import "../decorate-D5j-d9_z.mjs";
|
|
3
3
|
import "../logger-BR1-s1Um.mjs";
|
|
4
|
-
import "../router-context-
|
|
5
|
-
import { a as OnMessage, c as getWsOnMessageMethod, d as isGateway, i as OnError, l as WebSocketDuplicateEventHandlerError, n as WebSocketBodyNotAvailableError, o as getWsOnCloseMethod, r as OnClose, s as getWsOnErrorMethod, t as GatewayContext, u as Gateway } from "../gateway-context-
|
|
4
|
+
import "../router-context-BEJe9HEB.mjs";
|
|
5
|
+
import { a as OnMessage, c as getWsOnMessageMethod, d as isGateway, i as OnError, l as WebSocketDuplicateEventHandlerError, n as WebSocketBodyNotAvailableError, o as getWsOnCloseMethod, r as OnClose, s as getWsOnErrorMethod, t as GatewayContext, u as Gateway } from "../gateway-context-BkZ4UKaX.mjs";
|
|
6
6
|
export { Gateway, GatewayContext, OnClose, OnError, OnMessage, WebSocketBodyNotAvailableError, WebSocketDuplicateEventHandlerError, getWsOnCloseMethod, getWsOnErrorMethod, getWsOnMessageMethod, isGateway };
|
package/dist/workers/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $t as Container, Ht as StratalEnv } from "../index-
|
|
1
|
+
import { $t as Container, Ht as StratalEnv } from "../index-BJWm863C.mjs";
|
|
2
2
|
import { DurableObject, WorkerEntrypoint, WorkflowEntrypoint } from "cloudflare:workers";
|
|
3
3
|
|
|
4
4
|
//#region src/workers/run-in-scope.d.ts
|
package/dist/workers/index.mjs
CHANGED
|
@@ -1,22 +1,23 @@
|
|
|
1
1
|
import "../errors-CtCi1wn6.mjs";
|
|
2
2
|
import { l as DI_TOKENS } from "../decorate-D5j-d9_z.mjs";
|
|
3
3
|
import "../logger-BR1-s1Um.mjs";
|
|
4
|
-
import "../module-
|
|
4
|
+
import "../module-BgdxxzBe.mjs";
|
|
5
5
|
import "../events-CXl-o1Ad.mjs";
|
|
6
|
-
import "../
|
|
7
|
-
import "../
|
|
8
|
-
import "../is-
|
|
9
|
-
import "../
|
|
10
|
-
import "../
|
|
11
|
-
import "../
|
|
12
|
-
import "../
|
|
13
|
-
import "../
|
|
14
|
-
import "../
|
|
15
|
-
import "../
|
|
16
|
-
import "../
|
|
17
|
-
import "../
|
|
18
|
-
import "../
|
|
19
|
-
import
|
|
6
|
+
import "../colors-DJaRDXoS.mjs";
|
|
7
|
+
import "../command-BvCOD6df.mjs";
|
|
8
|
+
import "../is-command-BfCgWAcQ.mjs";
|
|
9
|
+
import "../is-seeder-CebjZCDn.mjs";
|
|
10
|
+
import "../middleware-C0Ebzswy.mjs";
|
|
11
|
+
import "../router-context-BEJe9HEB.mjs";
|
|
12
|
+
import "../cron-manager-DR7fiG6o.mjs";
|
|
13
|
+
import "../validation-Bh875Lyg.mjs";
|
|
14
|
+
import "../i18n.module-W8OJxg3d.mjs";
|
|
15
|
+
import "../guards-DUk_Kzst.mjs";
|
|
16
|
+
import "../gateway-context-BkZ4UKaX.mjs";
|
|
17
|
+
import "../quarry-registry-DCwqVcRp.mjs";
|
|
18
|
+
import "../queue.module-BZvmeAMj.mjs";
|
|
19
|
+
import "../seeder-Cupi5jl-.mjs";
|
|
20
|
+
import { t as Stratal } from "../stratal-CE0iTz4f.mjs";
|
|
20
21
|
import { DurableObject, WorkerEntrypoint, WorkflowEntrypoint } from "cloudflare:workers";
|
|
21
22
|
//#region src/workers/run-in-scope.ts
|
|
22
23
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/workers/run-in-scope.ts","../../src/workers/stratal-durable-object.ts","../../src/workers/stratal-worker-entrypoint.ts","../../src/workers/stratal-workflow.ts"],"sourcesContent":["import type { Container } from '../di/container'\nimport { Stratal } from '../stratal'\n\n/**\n * Shared helper that creates a request-scoped DI container by accessing the\n * Stratal Application via the static singleton.\n *\n * Works with Durable Objects, Workflows, and WorkerEntrypoints.\n */\nexport async function runInScope<T>(\n callback: (container: Container) => T | Promise<T>\n): Promise<T> {\n const app = await Stratal.resolveApplication()\n const mockCtx = app.createMockRouterContext('en')\n return app.container.runInRequestScope(mockCtx, callback)\n}\n","import { DurableObject } from 'cloudflare:workers'\nimport type { Container } from '../di/container'\nimport { DI_TOKENS } from '../di/tokens'\nimport type { StratalEnv } from '../env'\nimport { runInScope } from './run-in-scope'\n\n/**\n * Base class for Durable Objects with full DI access.\n *\n * Extends Cloudflare's `DurableObject` and provides a `runInScope()` helper\n * that creates a request-scoped container with `DurableObjectState` and\n * `DurableObjectId` tokens registered.\n *\n * @example\n * ```typescript\n * import { StratalDurableObject } from 'stratal/workers'\n *\n * export class Counter extends StratalDurableObject {\n * async increment() {\n * return this.runInScope(async (container) => {\n * const svc = container.resolve(CounterService)\n * return svc.increment()\n * })\n * }\n * }\n * ```\n */\nexport abstract class StratalDurableObject<\n Env extends StratalEnv = StratalEnv\n> extends DurableObject<Env> {\n protected async runInScope<T>(\n callback: (container: Container) => T | Promise<T>\n ): Promise<T> {\n return runInScope(async (requestContainer) => {\n requestContainer.registerValue(DI_TOKENS.DurableObjectState, this.ctx)\n requestContainer.registerValue(DI_TOKENS.DurableObjectId, this.ctx.id)\n return callback(requestContainer)\n })\n }\n}\n","import { WorkerEntrypoint } from 'cloudflare:workers'\nimport type { Container } from '../di/container'\nimport type { StratalEnv } from '../env'\nimport { runInScope } from './run-in-scope'\n\n/**\n * Base class for Cloudflare WorkerEntrypoints (Service Bindings / RPC) with full DI access.\n *\n * Extends Cloudflare's `WorkerEntrypoint` and provides a `runInScope()` helper\n * that creates a request-scoped DI container.\n *\n * @example\n * ```typescript\n * import { StratalWorkerEntrypoint } from 'stratal/workers'\n *\n * export class AuthRpc extends StratalWorkerEntrypoint {\n * async verifyToken(token: string) {\n * return this.runInScope(async (container) => {\n * const auth = container.resolve(AuthService)\n * return auth.verify(token)\n * })\n * }\n * }\n * ```\n */\nexport abstract class StratalWorkerEntrypoint<\n Env extends StratalEnv = StratalEnv\n> extends WorkerEntrypoint<Env> {\n protected runInScope<T>(\n callback: (container: Container) => T | Promise<T>\n ): Promise<T> {\n return runInScope(callback)\n }\n}\n","import { WorkflowEntrypoint } from 'cloudflare:workers'\nimport type { Container } from '../di/container'\nimport type { StratalEnv } from '../env'\nimport { runInScope } from './run-in-scope'\n\n/**\n * Base class for Cloudflare Workflows with full DI access.\n *\n * Extends Cloudflare's `WorkflowEntrypoint` and provides a `runInScope()` helper\n * that creates a request-scoped DI container.\n *\n * @example\n * ```typescript\n * import { StratalWorkflow } from 'stratal/workers'\n *\n * export class MyWorkflow extends StratalWorkflow<Env, { userId: string }> {\n * async run(event: WorkflowEvent<{ userId: string }>, step: WorkflowStep) {\n * await this.runInScope(async (container) => {\n * const svc = container.resolve(UserService)\n * await svc.process(event.payload.userId)\n * })\n * }\n * }\n * ```\n */\nexport abstract class StratalWorkflow<\n Env extends StratalEnv = StratalEnv,\n Params = unknown\n> extends WorkflowEntrypoint<Env, Params> {\n protected runInScope<T>(\n callback: (container: Container) => T | Promise<T>\n ): Promise<T> {\n return runInScope(callback)\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/workers/run-in-scope.ts","../../src/workers/stratal-durable-object.ts","../../src/workers/stratal-worker-entrypoint.ts","../../src/workers/stratal-workflow.ts"],"sourcesContent":["import type { Container } from '../di/container'\nimport { Stratal } from '../stratal'\n\n/**\n * Shared helper that creates a request-scoped DI container by accessing the\n * Stratal Application via the static singleton.\n *\n * Works with Durable Objects, Workflows, and WorkerEntrypoints.\n */\nexport async function runInScope<T>(\n callback: (container: Container) => T | Promise<T>\n): Promise<T> {\n const app = await Stratal.resolveApplication()\n const mockCtx = app.createMockRouterContext('en')\n return app.container.runInRequestScope(mockCtx, callback)\n}\n","import { DurableObject } from 'cloudflare:workers'\nimport type { Container } from '../di/container'\nimport { DI_TOKENS } from '../di/tokens'\nimport type { StratalEnv } from '../env'\nimport { runInScope } from './run-in-scope'\n\n/**\n * Base class for Durable Objects with full DI access.\n *\n * Extends Cloudflare's `DurableObject` and provides a `runInScope()` helper\n * that creates a request-scoped container with `DurableObjectState` and\n * `DurableObjectId` tokens registered.\n *\n * @example\n * ```typescript\n * import { StratalDurableObject } from 'stratal/workers'\n *\n * export class Counter extends StratalDurableObject {\n * async increment() {\n * return this.runInScope(async (container) => {\n * const svc = container.resolve(CounterService)\n * return svc.increment()\n * })\n * }\n * }\n * ```\n */\nexport abstract class StratalDurableObject<\n Env extends StratalEnv = StratalEnv\n> extends DurableObject<Env> {\n protected async runInScope<T>(\n callback: (container: Container) => T | Promise<T>\n ): Promise<T> {\n return runInScope(async (requestContainer) => {\n requestContainer.registerValue(DI_TOKENS.DurableObjectState, this.ctx)\n requestContainer.registerValue(DI_TOKENS.DurableObjectId, this.ctx.id)\n return callback(requestContainer)\n })\n }\n}\n","import { WorkerEntrypoint } from 'cloudflare:workers'\nimport type { Container } from '../di/container'\nimport type { StratalEnv } from '../env'\nimport { runInScope } from './run-in-scope'\n\n/**\n * Base class for Cloudflare WorkerEntrypoints (Service Bindings / RPC) with full DI access.\n *\n * Extends Cloudflare's `WorkerEntrypoint` and provides a `runInScope()` helper\n * that creates a request-scoped DI container.\n *\n * @example\n * ```typescript\n * import { StratalWorkerEntrypoint } from 'stratal/workers'\n *\n * export class AuthRpc extends StratalWorkerEntrypoint {\n * async verifyToken(token: string) {\n * return this.runInScope(async (container) => {\n * const auth = container.resolve(AuthService)\n * return auth.verify(token)\n * })\n * }\n * }\n * ```\n */\nexport abstract class StratalWorkerEntrypoint<\n Env extends StratalEnv = StratalEnv\n> extends WorkerEntrypoint<Env> {\n protected runInScope<T>(\n callback: (container: Container) => T | Promise<T>\n ): Promise<T> {\n return runInScope(callback)\n }\n}\n","import { WorkflowEntrypoint } from 'cloudflare:workers'\nimport type { Container } from '../di/container'\nimport type { StratalEnv } from '../env'\nimport { runInScope } from './run-in-scope'\n\n/**\n * Base class for Cloudflare Workflows with full DI access.\n *\n * Extends Cloudflare's `WorkflowEntrypoint` and provides a `runInScope()` helper\n * that creates a request-scoped DI container.\n *\n * @example\n * ```typescript\n * import { StratalWorkflow } from 'stratal/workers'\n *\n * export class MyWorkflow extends StratalWorkflow<Env, { userId: string }> {\n * async run(event: WorkflowEvent<{ userId: string }>, step: WorkflowStep) {\n * await this.runInScope(async (container) => {\n * const svc = container.resolve(UserService)\n * await svc.process(event.payload.userId)\n * })\n * }\n * }\n * ```\n */\nexport abstract class StratalWorkflow<\n Env extends StratalEnv = StratalEnv,\n Params = unknown\n> extends WorkflowEntrypoint<Env, Params> {\n protected runInScope<T>(\n callback: (container: Container) => T | Promise<T>\n ): Promise<T> {\n return runInScope(callback)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,eAAsB,WACpB,UACY;CACZ,MAAM,MAAM,MAAM,QAAQ,oBAAoB;CAC9C,MAAM,UAAU,IAAI,wBAAwB,KAAK;AACjD,QAAO,IAAI,UAAU,kBAAkB,SAAS,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;ACa3D,IAAsB,uBAAtB,cAEU,cAAmB;CAC3B,MAAgB,WACd,UACY;AACZ,SAAO,WAAW,OAAO,qBAAqB;AAC5C,oBAAiB,cAAc,UAAU,oBAAoB,KAAK,IAAI;AACtE,oBAAiB,cAAc,UAAU,iBAAiB,KAAK,IAAI,GAAG;AACtE,UAAO,SAAS,iBAAiB;IACjC;;;;;;;;;;;;;;;;;;;;;;;;;ACZN,IAAsB,0BAAtB,cAEU,iBAAsB;CAC9B,WACE,UACY;AACZ,SAAO,WAAW,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;ACN/B,IAAsB,kBAAtB,cAGU,mBAAgC;CACxC,WACE,UACY;AACZ,SAAO,WAAW,SAAS"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stratal",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.16",
|
|
4
4
|
"description": "A modular Cloudflare Workers framework with dependency injection, queue-based events, and type-safe configuration",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -159,7 +159,6 @@
|
|
|
159
159
|
"@xmldom/xmldom": "^0.8.11",
|
|
160
160
|
"clipanion": "^4.0.0-rc.4",
|
|
161
161
|
"hono": "^4.12.8",
|
|
162
|
-
"reflect-metadata": "^0.2.2",
|
|
163
162
|
"tsyringe": "^4.10.0",
|
|
164
163
|
"zod": "^4.3.6"
|
|
165
164
|
},
|
|
@@ -168,10 +167,10 @@
|
|
|
168
167
|
"@aws-sdk/lib-storage": "^3.700.0",
|
|
169
168
|
"@aws-sdk/s3-request-presigner": "^3.700.0",
|
|
170
169
|
"@react-email/components": "^1.0.0",
|
|
171
|
-
"@tus/server": "^2.0.0",
|
|
172
170
|
"nodemailer": ">=7.0.0",
|
|
173
171
|
"react": "^19.0.0",
|
|
174
172
|
"react-dom": "^19.0.0",
|
|
173
|
+
"reflect-metadata": "^0.2.2",
|
|
175
174
|
"resend": "^6.0.0"
|
|
176
175
|
},
|
|
177
176
|
"peerDependenciesMeta": {
|
|
@@ -187,9 +186,6 @@
|
|
|
187
186
|
"@react-email/components": {
|
|
188
187
|
"optional": true
|
|
189
188
|
},
|
|
190
|
-
"@tus/server": {
|
|
191
|
-
"optional": true
|
|
192
|
-
},
|
|
193
189
|
"nodemailer": {
|
|
194
190
|
"optional": true
|
|
195
191
|
},
|
|
@@ -211,7 +207,6 @@
|
|
|
211
207
|
"@cloudflare/workers-types": "4.20260317.1",
|
|
212
208
|
"@react-email/components": "^1.0.10",
|
|
213
209
|
"@stratal/testing": "workspace:*",
|
|
214
|
-
"@tus/server": "^2.3.0",
|
|
215
210
|
"@types/node": "^25.5.0",
|
|
216
211
|
"@types/nodemailer": "^7.0.11",
|
|
217
212
|
"@types/react": "^19.2.14",
|
|
@@ -222,6 +217,7 @@
|
|
|
222
217
|
"nodemailer": "^8.0.2",
|
|
223
218
|
"react": "^19.2.4",
|
|
224
219
|
"react-dom": "^19.2.4",
|
|
220
|
+
"reflect-metadata": "^0.2.2",
|
|
225
221
|
"resend": "^6.9.4",
|
|
226
222
|
"tsdown": "^0.21.4",
|
|
227
223
|
"typescript": "^5.9.3",
|