@venizia/ignis 0.4.0 → 0.4.2
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/base/applications/base.d.ts +1 -1
- package/dist/base/applications/base.js +2 -2
- package/dist/base/applications/base.js.map +1 -1
- package/dist/base/applications/common/types.d.ts +9 -0
- package/dist/base/applications/common/types.d.ts.map +1 -1
- package/dist/base/applications/common/types.js.map +1 -1
- package/dist/base/applications/server.d.ts +15 -1
- package/dist/base/applications/server.d.ts.map +1 -1
- package/dist/base/applications/server.js +66 -4
- package/dist/base/applications/server.js.map +1 -1
- package/dist/base/middlewares/app-error/app-error.middleware.js +1 -1
- package/dist/base/middlewares/app-error/app-error.middleware.js.map +1 -1
- package/dist/components/auth/authenticate/controllers/factory.js +1 -1
- package/dist/components/auth/authenticate/controllers/factory.js.map +1 -1
- package/dist/components/auth/authenticate/controllers/jwks/controller.js.map +1 -1
- package/dist/components/auth/authenticate/controllers/service-certs/controller.js.map +1 -1
- package/dist/components/auth/authenticate/services/bearer/jwks/abstract.service.js +1 -1
- package/dist/components/auth/authenticate/services/bearer/jwks/abstract.service.js.map +1 -1
- package/dist/components/auth/authenticate/services/bearer/jwks/issuer.service.js +1 -1
- package/dist/components/auth/authenticate/services/bearer/jwks/issuer.service.js.map +1 -1
- package/dist/components/auth/authorize/adapters/custom-grant-expander.js +3 -3
- package/dist/components/auth/authorize/adapters/custom-grant-expander.js.map +1 -1
- package/dist/components/auth/authorize/adapters/scoped-casbin/adapter.d.ts.map +1 -1
- package/dist/components/auth/authorize/adapters/scoped-casbin/adapter.js +3 -3
- package/dist/components/auth/authorize/adapters/scoped-casbin/adapter.js.map +1 -1
- package/dist/components/auth/authorize/enforcers/casbin.enforcer.js +2 -2
- package/dist/components/auth/authorize/enforcers/casbin.enforcer.js.map +1 -1
- package/dist/components/auth/authorize/enforcers/user-policy-line-cache.js +1 -1
- package/dist/components/auth/authorize/enforcers/user-policy-line-cache.js.map +1 -1
- package/dist/components/health-check/controller.js +2 -2
- package/dist/components/health-check/controller.js.map +1 -1
- package/dist/components/mail/helpers/executors/bull-mq-executor.helper.js +2 -2
- package/dist/components/mail/helpers/executors/bull-mq-executor.helper.js.map +1 -1
- package/dist/components/mail/helpers/executors/internal-queue-executor.helper.js +2 -2
- package/dist/components/mail/helpers/executors/internal-queue-executor.helper.js.map +1 -1
- package/dist/components/mail/helpers/transporters/mailgun-transporter.helper.js +1 -1
- package/dist/components/mail/helpers/transporters/mailgun-transporter.helper.js.map +1 -1
- package/dist/components/mail/services/mail.service.js +2 -2
- package/dist/components/mail/services/mail.service.js.map +1 -1
- package/dist/components/mail/utilities/attachment.utility.js +2 -2
- package/dist/components/mail/utilities/attachment.utility.js.map +1 -1
- package/dist/components/mail/utilities/mime.utility.js +3 -3
- package/dist/components/mail/utilities/mime.utility.js.map +1 -1
- package/dist/components/static-asset/component.js +1 -1
- package/dist/components/static-asset/component.js.map +1 -1
- package/dist/components/static-asset/controller/factory.d.ts.map +1 -1
- package/dist/components/static-asset/controller/factory.js +9 -9
- package/dist/components/static-asset/controller/factory.js.map +1 -1
- package/dist/components/static-asset/controller/key-scope.js +1 -1
- package/dist/components/static-asset/controller/key-scope.js.map +1 -1
- package/dist/components/static-asset/controller/meta-link.js +2 -2
- package/dist/components/static-asset/controller/meta-link.js.map +1 -1
- package/dist/components/static-asset/models/base.model.js +1 -1
- package/dist/components/static-asset/models/base.model.js.map +1 -1
- package/dist/presets/app/files/src/smoke.test.ts +1 -1
- package/dist/presets/app/preset.json +4 -4
- package/dist/presets/lib/preset.json +3 -3
- package/package.json +9 -9
|
@@ -54,7 +54,7 @@ export declare abstract class BaseApplication extends ServerApplication implemen
|
|
|
54
54
|
initialize(): Promise<void>;
|
|
55
55
|
protected getBootSequence(): IBootSequenceStep[];
|
|
56
56
|
/**
|
|
57
|
-
* Refuses to start when a model's `settings.
|
|
57
|
+
* Refuses to start when a model's `settings.access` cannot take effect. Both failures are
|
|
58
58
|
* silent at runtime and opposite: a search-backed model returns too many rows, a context-less one none.
|
|
59
59
|
*/
|
|
60
60
|
protected validateScopeFilterSupport(): void;
|
|
@@ -112,7 +112,7 @@ class BaseApplication extends server_1.ServerApplication {
|
|
|
112
112
|
if (provider) {
|
|
113
113
|
await provider
|
|
114
114
|
.shutdown()
|
|
115
|
-
.catch(shutdownError => logger.error('Failed to shut down partially-built provider during fallback | error: %s', shutdownError));
|
|
115
|
+
.catch((shutdownError) => logger.error('Failed to shut down partially-built provider during fallback | error: %s', shutdownError));
|
|
116
116
|
}
|
|
117
117
|
provider = await (0, ignis_helpers_1.createSecretsHelper)({
|
|
118
118
|
provider: ignis_helpers_1.SecretProviders.SYSTEM_ENVS,
|
|
@@ -356,7 +356,7 @@ class BaseApplication extends server_1.ServerApplication {
|
|
|
356
356
|
];
|
|
357
357
|
}
|
|
358
358
|
/**
|
|
359
|
-
* Refuses to start when a model's `settings.
|
|
359
|
+
* Refuses to start when a model's `settings.access` cannot take effect. Both failures are
|
|
360
360
|
* silent at runtime and opposite: a search-backed model returns too many rows, a context-less one none.
|
|
361
361
|
*/
|
|
362
362
|
validateScopeFilterSupport() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/base/applications/base.ts"],"names":[],"mappings":";;;AAAA,gEAAuE;AACvE,wDAA6D;AAC7D,wDAAwE;AACxE,wDAAwD;AACxD,6CAAuD;AACvD,uDAA6D;AAC7D,wDAM+B;AAS/B,sDAAyE;AACzE,0DAA8E;AAC9E,0DAOgC;AAChC,0DAAqE;AACrE,gDAAkE;AAClE,6CAA+C;AAC/C,qCAA6C;AAI7C,8HAA8H;AAC9H,MAAM,mBAAmB,GAAG,CAAC,IAG5B,EAA0B,EAAE;IAC3B,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;IAC/B,MAAM,MAAM,GAA2B,EAAE,CAAC;IAE1C,IAAI,CAAC,KAAK,CAAC,IAAI,E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AAG,EAAE,CAAC,IAAI,CAAC,cAAc,EAAE,EAAE;SAClF,CAAC,CAAC;QAEH,+FAA+F;QAC/F,iGAAiG;QACjG,MAAM,cAAc,GAAG,2BAAY,CAAC,WAAW,CAAC;YAC9C,KAAK,EAAE,WAAW;YAClB,MAAM,EAAE,4BAAe,CAAC,iCAAiC;YACzD,IAAI,EAAE;gBACJ,IAAI,EAAE,4BAAe,CAAC,sBAAsB;gBAC5C,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,oBAAoB,EAAE;aACvC;SACF,CAAC,CAAC;QAEH,OAAO;YACL,GAAG,cAAc;YACjB,6DAA6D;YAC7D;gBACE,IAAI,EAAE,4BAAe,CAAC,6BAA6B;gBACnD,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,0BAA0B,EAAE;aAC7C;SACF,CAAC;IACJ,CAAC;IAED;;;OAGG;IACO,0BAA0B;QAClC,IAAA,6CAA0B,EAAC,EAAE,mBAAmB,EAAE,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC;IAClG,CAAC;CACF;AAlbD,0CAkbC","sourcesContent":["import { assertScopeFilterSupported } from '@venizia/ignis-connectors';\nimport { ControllerTransports } from '@venizia/ignis-kernel';\nimport { BindingNamespaces, CoreBindings } from '@venizia/ignis-kernel';\nimport { EnvironmentKeys } from '@/common/environments';\nimport { RequestTrackerComponent } from '@/components';\nimport { GrpcComponent } from '@/components/controller/grpc';\nimport {\n BindingScopes,\n BindingValueTypes,\n BootSequence,\n MetadataRegistry,\n RequestContextRegistry,\n} from '@venizia/ignis-kernel';\nimport type { ILogger } from '@venizia/ignis-helpers/core';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type {\n ISecretHydrateEntry,\n ISecretRotatable,\n ISecretsHelper,\n ISecretsRegistration,\n} from '@venizia/ignis-helpers';\nimport { blankToUndefined, getError } from '@venizia/ignis-helpers/core';\nimport { HTTP, RuntimeModules, isEmpty } from '@venizia/ignis-helpers/common';\nimport {\n applicationEnvironment,\n createSecretsHelper,\n Environment,\n executeWithPerformanceMeasure,\n SecretProviders,\n toBoolean,\n} from '@venizia/ignis-helpers';\nimport { contextStorage, tryGetContext } from 'hono/context-storage';\nimport { AppErrorMiddleware, emojiFavicon } from '../middlewares';\nimport { ServerBootSteps } from './boot-steps';\nimport { ServerApplication } from './server';\nimport type { IRestApplication } from '@venizia/ignis-kernel';\nimport type { IBootSequenceStep } from '@venizia/ignis-kernel';\n\n/** Maps a secret bundle to env names: the explicit `keys` mapping when present, otherwise every bundle key under `prefix`. */\nconst selectSecretEnvKeys = (opts: {\n bundle: Record<string, string>;\n entry: ISecretHydrateEntry;\n}): Record<string, string> => {\n const { bundle, entry } = opts;\n const merged: Record<string, string> = {};\n\n if (!entry.keys) {\n const bundleEntries = Object.entries(bundle);\n for (const [rawKey, value] of bundleEntries) {\n merged[`${entry.prefix ?? ''}${rawKey}`] = value;\n }\n\n return merged;\n }\n\n const entryKeysEntries = Object.entries(entry.keys);\n for (const [rawKey, envKey] of entryKeysEntries) {\n const value = bundle[rawKey];\n if (value === undefined) {\n continue;\n }\n\n merged[envKey] = value;\n }\n\n return merged;\n};\n\nexport abstract class BaseApplication extends ServerApplication implements IRestApplication {\n protected secretsProvider?: ISecretsHelper;\n protected secretsRegistration?: ISecretsRegistration;\n\n protected normalizePath(...segments: string[]): string {\n const joined = segments.join('/').replace(/\\/+/g, '/').replace(/\\/$/, '');\n return joined || '/';\n }\n\n /** Adds the gRPC branch the kernel cannot own: `GrpcComponent` needs `AbstractGrpcController`, core-only code that reaches `node:module`. */\n override async registerControllers(): Promise<void> {\n await super.registerControllers();\n\n await executeWithPerformanceMeasure({\n logger: this.logger,\n description: 'Register application gRPC controllers',\n scope: this.registerControllers.name,\n task: async () => {\n const transports = this.configs.transports ?? [ControllerTransports.REST];\n\n for (const transport of transports) {\n if (transport === ControllerTransports.REST) {\n continue;\n }\n\n if (transport !== ControllerTransports.GRPC) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[registerControllers] Unsupported transport: '${transport}'`,\n });\n }\n\n const grpcComponent = new GrpcComponent(this);\n await grpcComponent.configure();\n }\n\n // Warn if gRPC controllers exist but gRPC transport is not enabled\n if (transports.includes(ControllerTransports.GRPC)) {\n return;\n }\n\n const allBindings = this.findByTag({ tag: BindingNamespaces.CONTROLLER });\n for (const binding of allBindings) {\n const target = binding.getBindingMeta({ type: BindingValueTypes.CLASS });\n if (!target) {\n continue;\n }\n\n const metadata = MetadataRegistry.getInstance().getControllerMetadata({ target });\n if (metadata?.transport !== ControllerTransports.GRPC) {\n continue;\n }\n\n this.logger\n .for(this.registerControllers.name)\n .error(\n 'gRPC controller \"%s\" discovered but gRPC transport is not enabled. Add \"%s\" to transports config.',\n binding.key,\n ControllerTransports.GRPC,\n );\n }\n },\n });\n }\n\n registerSecrets(): ValueOrPromise<ISecretsRegistration> {\n return { provider: SecretProviders.SYSTEM_ENVS };\n }\n\n async hydrateSecrets(): Promise<void> {\n const logger = this.logger.for(this.hydrateSecrets.name);\n const registration = await this.registerSecrets();\n\n let provider: ISecretsHelper | undefined;\n const emptyHydrations: string[] = [];\n try {\n provider = await createSecretsHelper({ ...registration, identifier: 'app' });\n await provider.configure();\n\n await this.hydrateSecretEntries({ provider, registration, emptyHydrations, logger });\n\n const registrationLease = registration.lease ?? [];\n for (const entry of registrationLease) {\n await provider.lease({ path: entry.path, key: entry.key });\n }\n } catch (error) {\n const env = Environment.current;\n if (!Environment.DEVELOPMENT_ENVS.has(env.toLowerCase())) {\n throw getError({\n message: `[hydrateSecrets] Secret provider failed in non-development environment | env: ${env}`,\n });\n }\n logger.warn(\n 'Secret provider failed; falling back to system-envs | env: %s | error: %s',\n env,\n error,\n );\n\n if (provider) {\n await provider\n .shutdown()\n .catch(shutdownError =>\n logger.error(\n 'Failed to shut down partially-built provider during fallback | error: %s',\n shutdownError,\n ),\n );\n }\n provider = await createSecretsHelper({\n provider: SecretProviders.SYSTEM_ENVS,\n identifier: 'app',\n });\n }\n\n if (!provider) {\n throw getError({ message: '[hydrateSecrets] No secrets provider resolved' });\n }\n\n if (emptyHydrations.length > 0) {\n const env = Environment.current;\n if (!Environment.DEVELOPMENT_ENVS.has(env.toLowerCase())) {\n throw getError({\n message: `[hydrateSecrets] Hydrate entries resolved to an empty secret bundle in non-development environment | env: ${env} | paths: ${emptyHydrations.join(', ')}`,\n });\n }\n logger.warn(\n 'Hydrate entries resolved to an empty secret bundle; continuing in development | env: %s | paths: %s',\n env,\n emptyHydrations.join(', '),\n );\n }\n\n this.bind<ISecretsHelper>({ key: CoreBindings.APPLICATION_CONFIG })\n .toProvider(() => provider)\n .setScope(BindingScopes.SINGLETON);\n\n this.registerPostStopHook({ identifier: 'secrets.shutdown', hook: () => provider.shutdown() });\n this.secretsProvider = provider;\n this.secretsRegistration = registration;\n }\n\n /** Applies each hydrate entry in declaration order; paths that resolve empty while declaring an expectation are collected in `emptyHydrations` rather than failing here. */\n protected async hydrateSecretEntries(opts: {\n provider: ISecretsHelper;\n registration: ISecretsRegistration;\n emptyHydrations: string[];\n logger: ILogger;\n }): Promise<void> {\n const { provider, registration, emptyHydrations, logger } = opts;\n\n const registrationHydrate = registration.hydrate ?? [];\n for (const entry of registrationHydrate) {\n const bundle = await provider.getBundle({ path: entry.path });\n const merged = this.mergeSecretsIntoEnv({ bundle, entry });\n if (Object.keys(merged).length > 0) {\n continue;\n }\n\n if (this.hydrateEntryDeclaresExpectation({ entry })) {\n emptyHydrations.push(entry.path);\n continue;\n }\n\n logger.warn(\n 'Hydrate entry resolved to an empty bundle and declares no expected keys | path: %s',\n entry.path,\n );\n }\n }\n\n protected mergeSecretsIntoEnv(opts: {\n bundle: Record<string, string>;\n entry: ISecretHydrateEntry;\n }): Record<string, string> {\n const { bundle, entry } = opts;\n const merged = selectSecretEnvKeys({ bundle, entry });\n\n const mergedEntries = Object.entries(merged);\n for (const [key, value] of mergedEntries) {\n process.env[key] = value;\n }\n applicationEnvironment.merge({ envs: merged });\n return merged;\n }\n\n /** A hydrate entry declares an expectation only via explicit `keys` or a non-empty `prefix`; such an entry resolving to zero env values is a misconfiguration boot must not silently absorb. */\n protected hydrateEntryDeclaresExpectation(opts: { entry: ISecretHydrateEntry }): boolean {\n const { entry } = opts;\n if (entry.keys && Object.keys(entry.keys).length > 0) {\n return true;\n }\n return typeof entry.prefix === 'string' && entry.prefix.length > 0;\n }\n\n async wireSecretRotatables(): Promise<void> {\n const logger = this.logger.for(this.wireSecretRotatables.name);\n const provider = this.secretsProvider;\n const registration = this.secretsRegistration;\n if (!provider || !registration?.lease?.length) {\n return;\n }\n for (const entry of registration.lease) {\n const instance = this.get<ISecretRotatable>({ key: entry.key, isOptional: true });\n if (instance && typeof instance.onSecretRotated === 'function') {\n provider.registerRotatable({ key: entry.key, target: instance });\n logger.info('Wired rotatable | key: %s', entry.key);\n continue;\n }\n logger.debug('Lease key has no rotatable consumer | key: %s', entry.key);\n }\n }\n\n static(opts: { restPath?: string; folderPath: string }) {\n const { restPath = '*', folderPath } = opts;\n const server = this.getServer();\n\n switch (this.runtime) {\n case RuntimeModules.BUN: {\n const { serveStatic } = require('hono/bun');\n server.use(restPath, serveStatic({ root: folderPath }));\n break;\n }\n case RuntimeModules.NODE: {\n try {\n const { serveStatic } = require('@hono/node-server/serve-static');\n server.use(restPath, serveStatic({ root: folderPath }));\n } catch (error) {\n this.logger.for(this.static.name).error('Failed to serve static file | Error: %s', error);\n throw getError({\n message: `[static] @hono/node-server is required for Node.js runtime. Please install '@hono/node-server'`,\n });\n }\n break;\n }\n default: {\n throw getError({\n message: '[static] Invalid server runtime to config static loader!',\n });\n }\n }\n\n this.logger\n .for(this.static.name)\n .debug(\n 'Registered static files | runtime: %s | path: %s | folder: %s',\n this.runtime,\n restPath,\n folderPath,\n );\n return this;\n }\n\n /**\n * Every value is read HERE, not destructured at module load: an application that loads its\n * `.env` in its own entrypoint does so after this module is imported, and a module-load snapshot\n * would print the defaults for a host that configured everything correctly.\n */\n protected printStartUpInfo(opts: { scope: string }) {\n const { scope } = opts;\n const read = (key: string, fallback: string): string =>\n blankToUndefined(process.env[key]) ?? fallback;\n const divider = '------------------------------------------------------------------------';\n\n this.logger.for(scope).info(divider);\n this.logger\n .for(scope)\n .info(\n 'Starting application... | Name: %s | Env: %s | Runtime: %s',\n read(EnvironmentKeys.APP_ENV_APPLICATION_NAME, 'PNT'),\n Environment.ambient,\n this.runtime,\n );\n this.logger\n .for(scope)\n .info(\n 'AllowEmptyEnv: %s | Prefix: %s',\n read('ALLOW_EMPTY_ENV_VALUE', 'true'),\n read('APPLICATION_ENV_PREFIX', 'APP_ENV'),\n );\n this.logger.for(scope).info('RunMode: %s', process.env.RUN_MODE);\n this.logger\n .for(scope)\n .info('Timezone: %s', read(EnvironmentKeys.APP_ENV_APPLICATION_TIMEZONE, 'Asia/Ho_Chi_Minh'));\n this.logger\n .for(scope)\n .info('LogPath: %s', read(EnvironmentKeys.APP_ENV_LOGGER_FOLDER_PATH, './'));\n this.logger.for(scope).info(divider);\n }\n\n /** Swaps in the `ErrorPrettier`-backed formatter - `node:util`, so the kernel cannot build it. */\n protected override buildErrorMiddleware(): AppErrorMiddleware {\n return new AppErrorMiddleware({\n logger: this.logger,\n rootKey: this.configs.error?.rootKey ?? undefined,\n });\n }\n\n /** Adds what only a listening server has, on top of the kernel's three - which stay in `RestApplication` so a browser Worker answers with the same envelope. */\n protected override async registerDefaultMiddlewares() {\n await executeWithPerformanceMeasure({\n logger: this.logger,\n scope: this.registerDefaultMiddlewares.name,\n description: 'Register default application server handler',\n task: async () => {\n const server = this.getServer();\n\n await super.registerDefaultMiddlewares();\n\n // Always installed, not only under `asyncContext.enable`: `tryGetContext()` answers \"no context\"\n // without a store, and a `contextStorage()` the application registered itself stays visible to\n // the enrichers. Inside a method body because every package declares `sideEffects: false`.\n RequestContextRegistry.setResolver({ resolver: () => tryGetContext() });\n\n if (this.configs.asyncContext?.enable) {\n server.use(contextStorage());\n }\n\n // Request-body parsing and the access log; the request id it reads is already installed\n // above (also works around the Bun + Hono body-parsing bug: https://github.com/honojs/middleware/issues/81).\n this.component(RequestTrackerComponent);\n\n server.use(emojiFavicon({ icon: this.configs.favicon ?? '🔥' }));\n },\n });\n }\n\n /** Lives here rather than on `AbstractApplication` - `applicationEnvironment` reads `process.env` at module load, so a kernel-pure ancestor cannot carry it; this is the layer that already depends on it. */\n protected validateEnvs() {\n const t = performance.now();\n const envKeys = applicationEnvironment.keys();\n\n // Permissive by DEFAULT: a name a host leaves empty is the host's business, and an empty value\n // already falls back to `defaultValue` at read time, so refusing to boot over one fights the\n // reader rather than helping it. Set ALLOW_EMPTY_ENV_VALUE to `false` or `0` to turn the check\n // on. Read once rather than per key, and a blank value reads as unset - the same rule every\n // other env read follows.\n const configured = blankToUndefined(process.env.ALLOW_EMPTY_ENV_VALUE);\n const allowsEmpty = configured === undefined || toBoolean(configured);\n\n this.logger\n .for(this.initialize.name)\n .info(\n 'Envs: %s | START Validating application environments | Empty values: %s',\n envKeys.length,\n allowsEmpty ? 'ALLOWED (default)' : 'REJECTED',\n );\n\n if (allowsEmpty) {\n this.logger\n .for(this.validateEnvs.name)\n .info(\n 'Envs: %s | SKIPPED - set ALLOW_EMPTY_ENV_VALUE=false to reject empty values',\n envKeys.length,\n );\n return;\n }\n\n for (const argKey of envKeys) {\n const argValue = applicationEnvironment.get<string | number>(argKey);\n\n if (!isEmpty({ value: argValue })) {\n continue;\n }\n\n throw getError({\n message: `[validateEnvs] Invalid Application Environment! Key: ${argKey} | Value: ${argValue}`,\n });\n }\n\n this.logger\n .for(this.validateEnvs.name)\n .info(\n 'Envs: %s | DONE Validating application environments | Took: %s (ms)',\n envKeys.length,\n performance.now() - t,\n );\n }\n\n /**\n * Version tripwire, body identical to `RestApplication.initialize()`: a stale kernel without\n * `getBootSequence()`/`runBootSequence()` throws here before any socket binds.\n */\n override async initialize(): Promise<void> {\n await this.runBootSequence({ steps: this.getBootSequence() });\n }\n\n protected override getBootSequence(): IBootSequenceStep[] {\n const steps: IBootSequenceStep[] = [\n {\n name: ServerBootSteps.PRINT_START_UP_INFO,\n run: () => this.printStartUpInfo({ scope: this.initialize.name }),\n },\n { name: ServerBootSteps.VALIDATE_ENVS, run: () => this.validateEnvs() },\n {\n name: ServerBootSteps.REGISTER_DEFAULT_MIDDLEWARES,\n run: () => this.registerDefaultMiddlewares(),\n },\n ...super.getBootSequence(),\n ];\n\n const withHydrate = BootSequence.insertAfter({\n steps,\n target: ServerBootSteps.PRE_CONFIGURE,\n step: { name: ServerBootSteps.HYDRATE_SECRETS, run: () => this.hydrateSecrets() },\n });\n\n // Components can contribute datasources, so wire rotatables only after the contributed sweep -\n // a lease key pointing at a component-contributed datasource would otherwise resolve to nothing.\n const withRotatables = BootSequence.insertAfter({\n steps: withHydrate,\n target: ServerBootSteps.REGISTER_CONTRIBUTED_DATA_SOURCES,\n step: {\n name: ServerBootSteps.WIRE_SECRET_ROTATABLES,\n run: () => this.wireSecretRotatables(),\n },\n });\n\n return [\n ...withRotatables,\n // Last, so a model registered by a component is covered too.\n {\n name: ServerBootSteps.VALIDATE_SCOPE_FILTER_SUPPORT,\n run: () => this.validateScopeFilterSupport(),\n },\n ];\n }\n\n /**\n * Refuses to start when a model's `settings.scopeFilter` cannot take effect. Both failures are\n * silent at runtime and opposite: a search-backed model returns too many rows, a context-less one none.\n */\n protected validateScopeFilterSupport(): void {\n assertScopeFilterSupported({ asyncContextEnabled: this.configs.asyncContext?.enable ?? false });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/base/applications/base.ts"],"names":[],"mappings":";;;AAAA,gEAAuE;AACvE,wDAA6D;AAC7D,wDAAwE;AACxE,wDAAwD;AACxD,6CAAuD;AACvD,uDAA6D;AAC7D,wDAM+B;AAS/B,sDAAyE;AACzE,0DAA8E;AAC9E,0DAOgC;AAChC,0DAAqE;AACrE,gDAAkE;AAClE,6CAA+C;AAC/C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C;YACD,GAAG,KAAK,CAAC,eAAe,EAAE;SAC3B,CAAC;QAEF,MAAM,WAAW,GAAG,2BAAY,CAAC,WAAW,CAAC;YAC3C,KAAK;YACL,MAAM,EAAE,4BAAe,CAAC,aAAa;YACrC,IAAI,EAAE,EAAE,IAAI,EAAE,4BAAe,CAAC,eAAe,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,cAAc,EAAE,EAAE;SAClF,CAAC,CAAC;QAEH,+FAA+F;QAC/F,iGAAiG;QACjG,MAAM,cAAc,GAAG,2BAAY,CAAC,WAAW,CAAC;YAC9C,KAAK,EAAE,WAAW;YAClB,MAAM,EAAE,4BAAe,CAAC,iCAAiC;YACzD,IAAI,EAAE;gBACJ,IAAI,EAAE,4BAAe,CAAC,sBAAsB;gBAC5C,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,oBAAoB,EAAE;aACvC;SACF,CAAC,CAAC;QAEH,OAAO;YACL,GAAG,cAAc;YACjB,6DAA6D;YAC7D;gBACE,IAAI,EAAE,4BAAe,CAAC,6BAA6B;gBACnD,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,0BAA0B,EAAE;aAC7C;SACF,CAAC;IACJ,CAAC;IAED;;;OAGG;IACO,0BAA0B;QAClC,IAAA,6CAA0B,EAAC,EAAE,mBAAmB,EAAE,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,IAAI,KAAK,EAAE,CAAC,CAAC;IAClG,CAAC;CACF;AAlbD,0CAkbC","sourcesContent":["import { assertScopeFilterSupported } from '@venizia/ignis-connectors';\nimport { ControllerTransports } from '@venizia/ignis-kernel';\nimport { BindingNamespaces, CoreBindings } from '@venizia/ignis-kernel';\nimport { EnvironmentKeys } from '@/common/environments';\nimport { RequestTrackerComponent } from '@/components';\nimport { GrpcComponent } from '@/components/controller/grpc';\nimport {\n BindingScopes,\n BindingValueTypes,\n BootSequence,\n MetadataRegistry,\n RequestContextRegistry,\n} from '@venizia/ignis-kernel';\nimport type { ILogger } from '@venizia/ignis-helpers/core';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type {\n ISecretHydrateEntry,\n ISecretRotatable,\n ISecretsHelper,\n ISecretsRegistration,\n} from '@venizia/ignis-helpers';\nimport { blankToUndefined, getError } from '@venizia/ignis-helpers/core';\nimport { HTTP, RuntimeModules, isEmpty } from '@venizia/ignis-helpers/common';\nimport {\n applicationEnvironment,\n createSecretsHelper,\n Environment,\n executeWithPerformanceMeasure,\n SecretProviders,\n toBoolean,\n} from '@venizia/ignis-helpers';\nimport { contextStorage, tryGetContext } from 'hono/context-storage';\nimport { AppErrorMiddleware, emojiFavicon } from '../middlewares';\nimport { ServerBootSteps } from './boot-steps';\nimport { ServerApplication } from './server';\nimport type { IRestApplication } from '@venizia/ignis-kernel';\nimport type { IBootSequenceStep } from '@venizia/ignis-kernel';\n\n/** Maps a secret bundle to env names: the explicit `keys` mapping when present, otherwise every bundle key under `prefix`. */\nconst selectSecretEnvKeys = (opts: {\n bundle: Record<string, string>;\n entry: ISecretHydrateEntry;\n}): Record<string, string> => {\n const { bundle, entry } = opts;\n const merged: Record<string, string> = {};\n\n if (!entry.keys) {\n const bundleEntries = Object.entries(bundle);\n for (const [rawKey, value] of bundleEntries) {\n merged[`${entry.prefix ?? ''}${rawKey}`] = value;\n }\n\n return merged;\n }\n\n const entryKeysEntries = Object.entries(entry.keys);\n for (const [rawKey, envKey] of entryKeysEntries) {\n const value = bundle[rawKey];\n if (value === undefined) {\n continue;\n }\n\n merged[envKey] = value;\n }\n\n return merged;\n};\n\nexport abstract class BaseApplication extends ServerApplication implements IRestApplication {\n protected secretsProvider?: ISecretsHelper;\n protected secretsRegistration?: ISecretsRegistration;\n\n protected normalizePath(...segments: string[]): string {\n const joined = segments.join('/').replace(/\\/+/g, '/').replace(/\\/$/, '');\n return joined || '/';\n }\n\n /** Adds the gRPC branch the kernel cannot own: `GrpcComponent` needs `AbstractGrpcController`, core-only code that reaches `node:module`. */\n override async registerControllers(): Promise<void> {\n await super.registerControllers();\n\n await executeWithPerformanceMeasure({\n logger: this.logger,\n description: 'Register application gRPC controllers',\n scope: this.registerControllers.name,\n task: async () => {\n const transports = this.configs.transports ?? [ControllerTransports.REST];\n\n for (const transport of transports) {\n if (transport === ControllerTransports.REST) {\n continue;\n }\n\n if (transport !== ControllerTransports.GRPC) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[registerControllers] Unsupported transport: '${transport}'`,\n });\n }\n\n const grpcComponent = new GrpcComponent(this);\n await grpcComponent.configure();\n }\n\n // Warn if gRPC controllers exist but gRPC transport is not enabled\n if (transports.includes(ControllerTransports.GRPC)) {\n return;\n }\n\n const allBindings = this.findByTag({ tag: BindingNamespaces.CONTROLLER });\n for (const binding of allBindings) {\n const target = binding.getBindingMeta({ type: BindingValueTypes.CLASS });\n if (!target) {\n continue;\n }\n\n const metadata = MetadataRegistry.getInstance().getControllerMetadata({ target });\n if (metadata?.transport !== ControllerTransports.GRPC) {\n continue;\n }\n\n this.logger\n .for(this.registerControllers.name)\n .error(\n 'gRPC controller \"%s\" discovered but gRPC transport is not enabled. Add \"%s\" to transports config.',\n binding.key,\n ControllerTransports.GRPC,\n );\n }\n },\n });\n }\n\n registerSecrets(): ValueOrPromise<ISecretsRegistration> {\n return { provider: SecretProviders.SYSTEM_ENVS };\n }\n\n async hydrateSecrets(): Promise<void> {\n const logger = this.logger.for(this.hydrateSecrets.name);\n const registration = await this.registerSecrets();\n\n let provider: ISecretsHelper | undefined;\n const emptyHydrations: string[] = [];\n try {\n provider = await createSecretsHelper({ ...registration, identifier: 'app' });\n await provider.configure();\n\n await this.hydrateSecretEntries({ provider, registration, emptyHydrations, logger });\n\n const registrationLease = registration.lease ?? [];\n for (const entry of registrationLease) {\n await provider.lease({ path: entry.path, key: entry.key });\n }\n } catch (error) {\n const env = Environment.current;\n if (!Environment.DEVELOPMENT_ENVS.has(env.toLowerCase())) {\n throw getError({\n message: `[hydrateSecrets] Secret provider failed in non-development environment | env: ${env}`,\n });\n }\n logger.warn(\n 'Secret provider failed; falling back to system-envs | env: %s | error: %s',\n env,\n error,\n );\n\n if (provider) {\n await provider\n .shutdown()\n .catch((shutdownError) =>\n logger.error(\n 'Failed to shut down partially-built provider during fallback | error: %s',\n shutdownError,\n ),\n );\n }\n provider = await createSecretsHelper({\n provider: SecretProviders.SYSTEM_ENVS,\n identifier: 'app',\n });\n }\n\n if (!provider) {\n throw getError({ message: '[hydrateSecrets] No secrets provider resolved' });\n }\n\n if (emptyHydrations.length > 0) {\n const env = Environment.current;\n if (!Environment.DEVELOPMENT_ENVS.has(env.toLowerCase())) {\n throw getError({\n message: `[hydrateSecrets] Hydrate entries resolved to an empty secret bundle in non-development environment | env: ${env} | paths: ${emptyHydrations.join(', ')}`,\n });\n }\n logger.warn(\n 'Hydrate entries resolved to an empty secret bundle; continuing in development | env: %s | paths: %s',\n env,\n emptyHydrations.join(', '),\n );\n }\n\n this.bind<ISecretsHelper>({ key: CoreBindings.APPLICATION_CONFIG })\n .toProvider(() => provider)\n .setScope(BindingScopes.SINGLETON);\n\n this.registerPostStopHook({ identifier: 'secrets.shutdown', hook: () => provider.shutdown() });\n this.secretsProvider = provider;\n this.secretsRegistration = registration;\n }\n\n /** Applies each hydrate entry in declaration order; paths that resolve empty while declaring an expectation are collected in `emptyHydrations` rather than failing here. */\n protected async hydrateSecretEntries(opts: {\n provider: ISecretsHelper;\n registration: ISecretsRegistration;\n emptyHydrations: string[];\n logger: ILogger;\n }): Promise<void> {\n const { provider, registration, emptyHydrations, logger } = opts;\n\n const registrationHydrate = registration.hydrate ?? [];\n for (const entry of registrationHydrate) {\n const bundle = await provider.getBundle({ path: entry.path });\n const merged = this.mergeSecretsIntoEnv({ bundle, entry });\n if (Object.keys(merged).length > 0) {\n continue;\n }\n\n if (this.hydrateEntryDeclaresExpectation({ entry })) {\n emptyHydrations.push(entry.path);\n continue;\n }\n\n logger.warn(\n 'Hydrate entry resolved to an empty bundle and declares no expected keys | path: %s',\n entry.path,\n );\n }\n }\n\n protected mergeSecretsIntoEnv(opts: {\n bundle: Record<string, string>;\n entry: ISecretHydrateEntry;\n }): Record<string, string> {\n const { bundle, entry } = opts;\n const merged = selectSecretEnvKeys({ bundle, entry });\n\n const mergedEntries = Object.entries(merged);\n for (const [key, value] of mergedEntries) {\n process.env[key] = value;\n }\n applicationEnvironment.merge({ envs: merged });\n return merged;\n }\n\n /** A hydrate entry declares an expectation only via explicit `keys` or a non-empty `prefix`; such an entry resolving to zero env values is a misconfiguration boot must not silently absorb. */\n protected hydrateEntryDeclaresExpectation(opts: { entry: ISecretHydrateEntry }): boolean {\n const { entry } = opts;\n if (entry.keys && Object.keys(entry.keys).length > 0) {\n return true;\n }\n return typeof entry.prefix === 'string' && entry.prefix.length > 0;\n }\n\n async wireSecretRotatables(): Promise<void> {\n const logger = this.logger.for(this.wireSecretRotatables.name);\n const provider = this.secretsProvider;\n const registration = this.secretsRegistration;\n if (!provider || !registration?.lease?.length) {\n return;\n }\n for (const entry of registration.lease) {\n const instance = this.get<ISecretRotatable>({ key: entry.key, isOptional: true });\n if (instance && typeof instance.onSecretRotated === 'function') {\n provider.registerRotatable({ key: entry.key, target: instance });\n logger.info('Wired rotatable | key: %s', entry.key);\n continue;\n }\n logger.debug('Lease key has no rotatable consumer | key: %s', entry.key);\n }\n }\n\n static(opts: { restPath?: string; folderPath: string }) {\n const { restPath = '*', folderPath } = opts;\n const server = this.getServer();\n\n switch (this.runtime) {\n case RuntimeModules.BUN: {\n const { serveStatic } = require('hono/bun');\n server.use(restPath, serveStatic({ root: folderPath }));\n break;\n }\n case RuntimeModules.NODE: {\n try {\n const { serveStatic } = require('@hono/node-server/serve-static');\n server.use(restPath, serveStatic({ root: folderPath }));\n } catch (error) {\n this.logger.for(this.static.name).error('Failed to serve static file | Error: %s', error);\n throw getError({\n message: `[static] @hono/node-server is required for Node.js runtime. Please install '@hono/node-server'`,\n });\n }\n break;\n }\n default: {\n throw getError({\n message: '[static] Invalid server runtime to config static loader!',\n });\n }\n }\n\n this.logger\n .for(this.static.name)\n .debug(\n 'Registered static files | runtime: %s | path: %s | folder: %s',\n this.runtime,\n restPath,\n folderPath,\n );\n return this;\n }\n\n /**\n * Every value is read HERE, not destructured at module load: an application that loads its\n * `.env` in its own entrypoint does so after this module is imported, and a module-load snapshot\n * would print the defaults for a host that configured everything correctly.\n */\n protected printStartUpInfo(opts: { scope: string }) {\n const { scope } = opts;\n const read = (key: string, fallback: string): string =>\n blankToUndefined(process.env[key]) ?? fallback;\n const divider = '------------------------------------------------------------------------';\n\n this.logger.for(scope).info(divider);\n this.logger\n .for(scope)\n .info(\n 'Starting application... | Name: %s | Env: %s | Runtime: %s',\n read(EnvironmentKeys.APP_ENV_APPLICATION_NAME, 'PNT'),\n Environment.ambient,\n this.runtime,\n );\n this.logger\n .for(scope)\n .info(\n 'AllowEmptyEnv: %s | Prefix: %s',\n read('ALLOW_EMPTY_ENV_VALUE', 'true'),\n read('APPLICATION_ENV_PREFIX', 'APP_ENV'),\n );\n this.logger.for(scope).info('RunMode: %s', process.env.RUN_MODE);\n this.logger\n .for(scope)\n .info('Timezone: %s', read(EnvironmentKeys.APP_ENV_APPLICATION_TIMEZONE, 'Asia/Ho_Chi_Minh'));\n this.logger\n .for(scope)\n .info('LogPath: %s', read(EnvironmentKeys.APP_ENV_LOGGER_FOLDER_PATH, './'));\n this.logger.for(scope).info(divider);\n }\n\n /** Swaps in the `ErrorPrettier`-backed formatter - `node:util`, so the kernel cannot build it. */\n protected override buildErrorMiddleware(): AppErrorMiddleware {\n return new AppErrorMiddleware({\n logger: this.logger,\n rootKey: this.configs.error?.rootKey ?? undefined,\n });\n }\n\n /** Adds what only a listening server has, on top of the kernel's three - which stay in `RestApplication` so a browser Worker answers with the same envelope. */\n protected override async registerDefaultMiddlewares() {\n await executeWithPerformanceMeasure({\n logger: this.logger,\n scope: this.registerDefaultMiddlewares.name,\n description: 'Register default application server handler',\n task: async () => {\n const server = this.getServer();\n\n await super.registerDefaultMiddlewares();\n\n // Always installed, not only under `asyncContext.enable`: `tryGetContext()` answers \"no context\"\n // without a store, and a `contextStorage()` the application registered itself stays visible to\n // the enrichers. Inside a method body because every package declares `sideEffects: false`.\n RequestContextRegistry.setResolver({ resolver: () => tryGetContext() });\n\n if (this.configs.asyncContext?.enable) {\n server.use(contextStorage());\n }\n\n // Request-body parsing and the access log; the request id it reads is already installed\n // above (also works around the Bun + Hono body-parsing bug: https://github.com/honojs/middleware/issues/81).\n this.component(RequestTrackerComponent);\n\n server.use(emojiFavicon({ icon: this.configs.favicon ?? '🔥' }));\n },\n });\n }\n\n /** Lives here rather than on `AbstractApplication` - `applicationEnvironment` reads `process.env` at module load, so a kernel-pure ancestor cannot carry it; this is the layer that already depends on it. */\n protected validateEnvs() {\n const t = performance.now();\n const envKeys = applicationEnvironment.keys();\n\n // Permissive by DEFAULT: a name a host leaves empty is the host's business, and an empty value\n // already falls back to `defaultValue` at read time, so refusing to boot over one fights the\n // reader rather than helping it. Set ALLOW_EMPTY_ENV_VALUE to `false` or `0` to turn the check\n // on. Read once rather than per key, and a blank value reads as unset - the same rule every\n // other env read follows.\n const configured = blankToUndefined(process.env.ALLOW_EMPTY_ENV_VALUE);\n const allowsEmpty = configured === undefined || toBoolean(configured);\n\n this.logger\n .for(this.initialize.name)\n .info(\n 'Envs: %s | START Validating application environments | Empty values: %s',\n envKeys.length,\n allowsEmpty ? 'ALLOWED (default)' : 'REJECTED',\n );\n\n if (allowsEmpty) {\n this.logger\n .for(this.validateEnvs.name)\n .info(\n 'Envs: %s | SKIPPED - set ALLOW_EMPTY_ENV_VALUE=false to reject empty values',\n envKeys.length,\n );\n return;\n }\n\n for (const argKey of envKeys) {\n const argValue = applicationEnvironment.get<string | number>(argKey);\n\n if (!isEmpty({ value: argValue })) {\n continue;\n }\n\n throw getError({\n message: `[validateEnvs] Invalid Application Environment! Key: ${argKey} | Value: ${argValue}`,\n });\n }\n\n this.logger\n .for(this.validateEnvs.name)\n .info(\n 'Envs: %s | DONE Validating application environments | Took: %s (ms)',\n envKeys.length,\n performance.now() - t,\n );\n }\n\n /**\n * Version tripwire, body identical to `RestApplication.initialize()`: a stale kernel without\n * `getBootSequence()`/`runBootSequence()` throws here before any socket binds.\n */\n override async initialize(): Promise<void> {\n await this.runBootSequence({ steps: this.getBootSequence() });\n }\n\n protected override getBootSequence(): IBootSequenceStep[] {\n const steps: IBootSequenceStep[] = [\n {\n name: ServerBootSteps.PRINT_START_UP_INFO,\n run: () => this.printStartUpInfo({ scope: this.initialize.name }),\n },\n { name: ServerBootSteps.VALIDATE_ENVS, run: () => this.validateEnvs() },\n {\n name: ServerBootSteps.REGISTER_DEFAULT_MIDDLEWARES,\n run: () => this.registerDefaultMiddlewares(),\n },\n ...super.getBootSequence(),\n ];\n\n const withHydrate = BootSequence.insertAfter({\n steps,\n target: ServerBootSteps.PRE_CONFIGURE,\n step: { name: ServerBootSteps.HYDRATE_SECRETS, run: () => this.hydrateSecrets() },\n });\n\n // Components can contribute datasources, so wire rotatables only after the contributed sweep -\n // a lease key pointing at a component-contributed datasource would otherwise resolve to nothing.\n const withRotatables = BootSequence.insertAfter({\n steps: withHydrate,\n target: ServerBootSteps.REGISTER_CONTRIBUTED_DATA_SOURCES,\n step: {\n name: ServerBootSteps.WIRE_SECRET_ROTATABLES,\n run: () => this.wireSecretRotatables(),\n },\n });\n\n return [\n ...withRotatables,\n // Last, so a model registered by a component is covered too.\n {\n name: ServerBootSteps.VALIDATE_SCOPE_FILTER_SUPPORT,\n run: () => this.validateScopeFilterSupport(),\n },\n ];\n }\n\n /**\n * Refuses to start when a model's `settings.access` cannot take effect. Both failures are\n * silent at runtime and opposite: a search-backed model returns too many rows, a context-less one none.\n */\n protected validateScopeFilterSupport(): void {\n assertScopeFilterSupported({ asyncContextEnabled: this.configs.asyncContext?.enable ?? false });\n }\n}\n"]}
|
|
@@ -27,6 +27,15 @@ export interface IServerRuntimeConfigs {
|
|
|
27
27
|
* implements none of these: a browser Worker has no host, no port, and nothing to `start()` - it
|
|
28
28
|
* answers `postMessage` instead.
|
|
29
29
|
*/
|
|
30
|
+
/** Options of `ServerApplication.installShutdownSignals`. */
|
|
31
|
+
export interface IShutdownSignalsOptions {
|
|
32
|
+
/** The signals that stop the application. Default `['SIGTERM', 'SIGINT']`. */
|
|
33
|
+
signals?: NodeJS.Signals[];
|
|
34
|
+
/** How long a shutdown may take before the process is force-exited with code 1. Default `15_000`. */
|
|
35
|
+
timeoutMs?: number;
|
|
36
|
+
/** What ends the process: `process.exit` by default. A seam for tests and for hosts that exit differently. */
|
|
37
|
+
exit?: (code: number) => void;
|
|
38
|
+
}
|
|
30
39
|
export interface IServerApplication<AppEnv extends Env = Env, AppSchema extends Schema = Schema, BasePath extends string = '/'> extends IApplication<AppEnv, AppSchema, BasePath> {
|
|
31
40
|
getServerHost(): string;
|
|
32
41
|
getServerPort(): number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/base/applications/common/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,YAAY,EACZ,mBAAmB,IAAI,yBAAyB,EACjD,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAExC,4HAA4H;AAC5H,MAAM,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEtC;;;;GAIG;AACH,MAAM,WAAW,yBAA0B,SAAQ,yBAAyB;IAC1E,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,sOAAsO;IACtO,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,oJAAoJ;IACpJ,MAAM,CAAC,EAAE,qBAAqB,CAAC;CAChC;AAED,8GAA8G;AAC9G,MAAM,WAAW,qBAAqB;IACpC,kFAAkF;IAClF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,qCAAqC;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,8EAA8E;IAC9E,OAAO,CAAC,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;IAE3B,qGAAqG;IACrG,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB,8GAA8G;IAC9G,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAC/B;AAED,MAAM,WAAW,kBAAkB,CACjC,MAAM,SAAS,GAAG,GAAG,GAAG,EACxB,SAAS,SAAS,MAAM,GAAG,MAAM,EACjC,QAAQ,SAAS,MAAM,GAAG,GAAG,CAC7B,SAAQ,YAAY,CAAC,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC;IACjD,aAAa,IAAI,MAAM,CAAC;IACxB,aAAa,IAAI,MAAM,CAAC;IACxB,gBAAgB,IAAI,MAAM,CAAC;IAE3B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC9B,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;CAC9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/base/applications/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n IApplication,\n IApplicationConfigs as IKernelApplicationConfigs,\n} from '@venizia/ignis-kernel';\nimport type { Env, Schema } from 'hono';\n\n/** `any`, resolved at runtime from `@hono/node-server` - naming its real type would make that package a hard dependency. */\nexport type TNodeServerInstance = any;\n\n/**\n * What a host with a real socket configures on top of the kernel's shape. `host` and `port` are\n * meaningless to a browser Worker, which is why they are not on the kernel's own interface - see\n * {@link IServerApplication}.\n */\nexport interface IServerApplicationConfigs extends IKernelApplicationConfigs {\n host?: string;\n port?: number;\n /** Bound as `CoreBindings.APPLICATION_PROJECT_ROOT` at construction and handed to `ModuleUtility`; default `process.cwd()`. Must be the directory holding `node_modules` at run time - never `__dirname` inside a compiled binary. */\n projectRoot?: string;\n /** Bun-only socket options passed straight to `Bun.serve`; the node runtime logs a warning and ignores them. Unset keys keep Bun's own defaults. */\n server?: IServerRuntimeConfigs;\n}\n\n/** The `Bun.serve` options an application has a reason to change without re-implementing `startBunModule`. */\nexport interface IServerRuntimeConfigs {\n /** Seconds a connection may sit idle before Bun closes it; Bun caps it at 255. */\n idleTimeout?: number;\n /** Largest request body in bytes. */\n maxRequestBodySize?: number;\n}\n\n/**\n * The kernel's contract plus what only a listening server can answer. `RestApplication` deliberately\n * implements none of these: a browser Worker has no host, no port, and nothing to `start()` - it\n * answers `postMessage` instead.\n */\nexport interface IServerApplication<\n AppEnv extends Env = Env,\n AppSchema extends Schema = Schema,\n BasePath extends string = '/',\n> extends IApplication<AppEnv, AppSchema, BasePath> {\n getServerHost(): string;\n getServerPort(): number;\n getServerAddress(): string;\n\n start(): Promise<void> | void;\n stop(): Promise<void> | void;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/base/applications/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n IApplication,\n IApplicationConfigs as IKernelApplicationConfigs,\n} from '@venizia/ignis-kernel';\nimport type { Env, Schema } from 'hono';\n\n/** `any`, resolved at runtime from `@hono/node-server` - naming its real type would make that package a hard dependency. */\nexport type TNodeServerInstance = any;\n\n/**\n * What a host with a real socket configures on top of the kernel's shape. `host` and `port` are\n * meaningless to a browser Worker, which is why they are not on the kernel's own interface - see\n * {@link IServerApplication}.\n */\nexport interface IServerApplicationConfigs extends IKernelApplicationConfigs {\n host?: string;\n port?: number;\n /** Bound as `CoreBindings.APPLICATION_PROJECT_ROOT` at construction and handed to `ModuleUtility`; default `process.cwd()`. Must be the directory holding `node_modules` at run time - never `__dirname` inside a compiled binary. */\n projectRoot?: string;\n /** Bun-only socket options passed straight to `Bun.serve`; the node runtime logs a warning and ignores them. Unset keys keep Bun's own defaults. */\n server?: IServerRuntimeConfigs;\n}\n\n/** The `Bun.serve` options an application has a reason to change without re-implementing `startBunModule`. */\nexport interface IServerRuntimeConfigs {\n /** Seconds a connection may sit idle before Bun closes it; Bun caps it at 255. */\n idleTimeout?: number;\n /** Largest request body in bytes. */\n maxRequestBodySize?: number;\n}\n\n/**\n * The kernel's contract plus what only a listening server can answer. `RestApplication` deliberately\n * implements none of these: a browser Worker has no host, no port, and nothing to `start()` - it\n * answers `postMessage` instead.\n */\n/** Options of `ServerApplication.installShutdownSignals`. */\nexport interface IShutdownSignalsOptions {\n /** The signals that stop the application. Default `['SIGTERM', 'SIGINT']`. */\n signals?: NodeJS.Signals[];\n\n /** How long a shutdown may take before the process is force-exited with code 1. Default `15_000`. */\n timeoutMs?: number;\n\n /** What ends the process: `process.exit` by default. A seam for tests and for hosts that exit differently. */\n exit?: (code: number) => void;\n}\n\nexport interface IServerApplication<\n AppEnv extends Env = Env,\n AppSchema extends Schema = Schema,\n BasePath extends string = '/',\n> extends IApplication<AppEnv, AppSchema, BasePath> {\n getServerHost(): string;\n getServerPort(): number;\n getServerAddress(): string;\n\n start(): Promise<void> | void;\n stop(): Promise<void> | void;\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { RestApplication } from '@venizia/ignis-kernel';
|
|
2
2
|
import type { Env, Schema } from 'hono';
|
|
3
|
-
import type { IServerApplication, IServerApplicationConfigs, IServerRuntimeConfigs, TNodeServerInstance } from './common';
|
|
3
|
+
import type { IServerApplication, IServerApplicationConfigs, IServerRuntimeConfigs, IShutdownSignalsOptions, TNodeServerInstance } from './common';
|
|
4
4
|
/** Lives here, not in the kernel: `Bun.serve` resolves only through `@types/bun`, and emitting `Bun` into the kernel's published `.d.ts` would force that dependency on every browser consumer of `@venizia/ignis-kernel`. This package legitimately has Bun types - it is the layer that calls `Bun.serve`. */
|
|
5
5
|
export type TBunServerInstance = ReturnType<typeof Bun.serve>;
|
|
6
6
|
/** Adds the listening server (`Bun.serve` / `@hono/node-server`) on top of `RestApplication` - the only layer that touches a socket, so it is the layer that stays out of the browser-pure kernel. */
|
|
@@ -34,6 +34,20 @@ export declare abstract class ServerApplication<AppEnv extends Env = Env, AppSch
|
|
|
34
34
|
start(): Promise<void>;
|
|
35
35
|
/** Post-stop hooks, then the server, then the datasources - closed even when the server fails to, so a stopped application holds no connection. */
|
|
36
36
|
stop(): Promise<void>;
|
|
37
|
+
/** Set once `installShutdownSignals` ran; holds the way back, so a second call is a no-op. */
|
|
38
|
+
protected shutdownSignals?: {
|
|
39
|
+
uninstall: () => void;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Stops the application on a signal (SIGTERM and SIGINT by default), then exits the process.
|
|
43
|
+
* Opt-in: nothing is installed until you call it, usually right after `start()`.
|
|
44
|
+
*
|
|
45
|
+
* - Calls `stop()` once. A second signal while it runs is ignored.
|
|
46
|
+
* - Exits 0 when `stop()` finishes, 1 when it throws or does not finish within `timeoutMs`.
|
|
47
|
+
* - Idempotent: calling it again returns the same uninstall function and adds no listener.
|
|
48
|
+
* - Returns an uninstall function that removes the listeners and the pending timeout.
|
|
49
|
+
*/
|
|
50
|
+
installShutdownSignals(opts?: IShutdownSignalsOptions): () => void;
|
|
37
51
|
protected stopServer(): Promise<void>;
|
|
38
52
|
}
|
|
39
53
|
//# sourceMappingURL=server.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../../src/base/applications/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAItE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAGxC,OAAO,KAAK,EACV,kBAAkB,EAClB,yBAAyB,EACzB,qBAAqB,EACrB,mBAAmB,EACpB,MAAM,UAAU,CAAC;AAElB,gTAAgT;AAChT,MAAM,MAAM,kBAAkB,GAAG,UAAU,CAAC,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../../src/base/applications/server.ts"],"names":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AS,CAAC,eAAe;IAuDnB,KAAK;IA0BX,mJAAmJ;IAC7I,IAAI;IAUV,8FAA8F;IAC9F,SAAS,CAAC,eAAe,CAAC,EAAE;QAAE,SAAS,EAAE,MAAM,IAAI,CAAA;KAAE,CAAC;IAEtD;;;;;;;;OAQG;IACH,sBAAsB,CAAC,IAAI,GAAE,uBAA4B,GAAG,MAAM,IAAI;cAyEtD,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;CAoC5C"}
|
|
@@ -10,6 +10,8 @@ const core_1 = require("@venizia/ignis-helpers/core");
|
|
|
10
10
|
const common_1 = require("@venizia/ignis-helpers/common");
|
|
11
11
|
const node_fs_1 = require("node:fs");
|
|
12
12
|
const node_path_1 = __importDefault(require("node:path"));
|
|
13
|
+
const DEFAULT_SHUTDOWN_SIGNALS = ['SIGTERM', 'SIGINT'];
|
|
14
|
+
const DEFAULT_SHUTDOWN_TIMEOUT_MS = 15_000;
|
|
13
15
|
const DEFAULT_SERVER_HOST = 'localhost';
|
|
14
16
|
const DEFAULT_SERVER_PORT = 3000;
|
|
15
17
|
const MAX_SERVER_PORT = 65535;
|
|
@@ -106,7 +108,7 @@ class ServerApplication extends ignis_kernel_1.RestApplication {
|
|
|
106
108
|
fetch: server.fetch,
|
|
107
109
|
...this.getServerRuntimeOptions(),
|
|
108
110
|
}))
|
|
109
|
-
.then(rs => {
|
|
111
|
+
.then((rs) => {
|
|
110
112
|
this.serverInstance = rs;
|
|
111
113
|
this.configs.port = rs.port;
|
|
112
114
|
this.inspectRoutes();
|
|
@@ -138,10 +140,10 @@ class ServerApplication extends ignis_kernel_1.RestApplication {
|
|
|
138
140
|
.warn('configs.server is Bun-only | ignored on node: %s', ignored.join(', '));
|
|
139
141
|
}
|
|
140
142
|
import('@hono/node-server')
|
|
141
|
-
.then(module => {
|
|
143
|
+
.then((module) => {
|
|
142
144
|
const { serve } = module;
|
|
143
145
|
// Resolve from the listening callback, not serve()'s synchronous return - only then is the socket bound and the OS-assigned port (config port `0`) known.
|
|
144
|
-
const rs = serve({ fetch: server.fetch, port, hostname: host }, info => {
|
|
146
|
+
const rs = serve({ fetch: server.fetch, port, hostname: host }, (info) => {
|
|
145
147
|
this.configs.port = info.port;
|
|
146
148
|
this.inspectRoutes();
|
|
147
149
|
this.logger
|
|
@@ -154,7 +156,7 @@ class ServerApplication extends ignis_kernel_1.RestApplication {
|
|
|
154
156
|
resolve(rs);
|
|
155
157
|
});
|
|
156
158
|
})
|
|
157
|
-
.catch(error => {
|
|
159
|
+
.catch((error) => {
|
|
158
160
|
this.logger
|
|
159
161
|
.for(this.start.name)
|
|
160
162
|
.error('Failed to import @hono/node-server | Error: %s', error);
|
|
@@ -196,6 +198,66 @@ class ServerApplication extends ignis_kernel_1.RestApplication {
|
|
|
196
198
|
await this.closeDataSources();
|
|
197
199
|
}
|
|
198
200
|
}
|
|
201
|
+
/**
|
|
202
|
+
* Stops the application on a signal (SIGTERM and SIGINT by default), then exits the process.
|
|
203
|
+
* Opt-in: nothing is installed until you call it, usually right after `start()`.
|
|
204
|
+
*
|
|
205
|
+
* - Calls `stop()` once. A second signal while it runs is ignored.
|
|
206
|
+
* - Exits 0 when `stop()` finishes, 1 when it throws or does not finish within `timeoutMs`.
|
|
207
|
+
* - Idempotent: calling it again returns the same uninstall function and adds no listener.
|
|
208
|
+
* - Returns an uninstall function that removes the listeners and the pending timeout.
|
|
209
|
+
*/
|
|
210
|
+
installShutdownSignals(opts = {}) {
|
|
211
|
+
if (this.shutdownSignals) {
|
|
212
|
+
return this.shutdownSignals.uninstall;
|
|
213
|
+
}
|
|
214
|
+
const { signals = DEFAULT_SHUTDOWN_SIGNALS, timeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS, exit = (code) => process.exit(code), } = opts;
|
|
215
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
216
|
+
throw (0, core_1.getError)({
|
|
217
|
+
message: `[installShutdownSignals] timeoutMs must be a positive number of milliseconds | value: ${String(timeoutMs)}`,
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
const log = this.logger.for(this.installShutdownSignals.name);
|
|
221
|
+
let isShuttingDown = false;
|
|
222
|
+
let timer;
|
|
223
|
+
const finish = (code) => {
|
|
224
|
+
clearTimeout(timer);
|
|
225
|
+
exit(code);
|
|
226
|
+
};
|
|
227
|
+
const onSignal = (signal) => {
|
|
228
|
+
if (isShuttingDown) {
|
|
229
|
+
log.warn('Signal %s ignored | shutdown already in progress', signal);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
isShuttingDown = true;
|
|
233
|
+
log.info('Signal %s received | stopping the application | timeout: %s ms', signal, timeoutMs);
|
|
234
|
+
timer = setTimeout(() => {
|
|
235
|
+
log.error('Shutdown did not finish within %s ms | forcing exit', timeoutMs);
|
|
236
|
+
exit(1);
|
|
237
|
+
}, timeoutMs);
|
|
238
|
+
this.stop().then(() => {
|
|
239
|
+
log.info('Application stopped | exiting');
|
|
240
|
+
finish(0);
|
|
241
|
+
}, (error) => {
|
|
242
|
+
log.error('Shutdown failed | error: %s', error instanceof Error ? error.message : String(error));
|
|
243
|
+
finish(1);
|
|
244
|
+
});
|
|
245
|
+
};
|
|
246
|
+
const listeners = signals.map((signal) => {
|
|
247
|
+
const listener = () => onSignal(signal);
|
|
248
|
+
process.on(signal, listener);
|
|
249
|
+
return { signal, listener };
|
|
250
|
+
});
|
|
251
|
+
const uninstall = () => {
|
|
252
|
+
clearTimeout(timer);
|
|
253
|
+
for (const { signal, listener } of listeners) {
|
|
254
|
+
process.off(signal, listener);
|
|
255
|
+
}
|
|
256
|
+
this.shutdownSignals = undefined;
|
|
257
|
+
};
|
|
258
|
+
this.shutdownSignals = { uninstall };
|
|
259
|
+
return uninstall;
|
|
260
|
+
}
|
|
199
261
|
async stopServer() {
|
|
200
262
|
const instance = this.serverInstance;
|
|
201
263
|
if (!instance) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../../src/base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C;YACjF,OAAO;QACT,CAAC;QAED,QAAQ,IAAI,CAAC,OAAO,EAAE,CAAC;YACrB,KAAK,uBAAc,CAAC,GAAG,CAAC,CAAC,CAAC;gBACxB,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;gBACtB,MAAM;YACR,CAAC;YACD,KAAK,uBAAc,CAAC,IAAI,CAAC,CAAC,CAAC;gBACzB,yJAAyJ;gBACzJ,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;oBAC1C,QAAQ,CAAC,KAAK,CAAC,CAAC,KAAa,EAAE,EAAE;wBAC/B,IAAI,KAAK,EAAE,CAAC;4BACV,MAAM,CAAC,KAAK,CAAC,CAAC;4BACd,OAAO;wBACT,CAAC;wBAED,OAAO,EAAE,CAAC;oBACZ,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;gBACH,MAAM;YACR,CAAC;YACD,OAAO,CAAC,CAAC,CAAC;gBACR,MAAM,IAAA,eAAQ,EAAC;oBACb,OAAO,EAAE,uDAAuD;iBACjE,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;IACzD,CAAC;CACF;AA1PD,8CA0PC","sourcesContent":["import { CoreBindings, RestApplication } from '@venizia/ignis-kernel';\nimport { ModuleUtility } from '@venizia/ignis-helpers';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { RuntimeModules } from '@venizia/ignis-helpers/common';\nimport type { Env, Schema } from 'hono';\nimport { existsSync } from 'node:fs';\nimport path from 'node:path';\nimport type {\n IServerApplication,\n IServerApplicationConfigs,\n IServerRuntimeConfigs,\n TNodeServerInstance,\n} from './common';\n\n/** Lives here, not in the kernel: `Bun.serve` resolves only through `@types/bun`, and emitting `Bun` into the kernel's published `.d.ts` would force that dependency on every browser consumer of `@venizia/ignis-kernel`. This package legitimately has Bun types - it is the layer that calls `Bun.serve`. */\nexport type TBunServerInstance = ReturnType<typeof Bun.serve>;\n\nconst DEFAULT_SERVER_HOST = 'localhost';\nconst DEFAULT_SERVER_PORT = 3000;\nconst MAX_SERVER_PORT = 65535;\n\n/**\n * The first candidate USABLE as a port. Rejection is on validity, never falsiness: `0` legitimately\n * asks the OS for an ephemeral port, and taking the first TRUTHY value instead let an unusable\n * `PORT` shadow a usable `APP_ENV_SERVER_PORT` - `PORT=abc APP_ENV_SERVER_PORT=8080` bound 3000, as\n * did Docker's legacy container-link form `PORT=tcp://172.17.0.5:8080`.\n */\nconst resolveServerPort = (opts: { candidates: Array<number | string | undefined> }): number => {\n for (const candidate of opts.candidates) {\n if (candidate === undefined || candidate === null) {\n continue;\n }\n\n const normalized = typeof candidate === 'string' ? candidate.trim() : candidate;\n if (normalized === '') {\n continue;\n }\n\n const parsed = Number(normalized);\n if (!Number.isInteger(parsed) || parsed < 0 || parsed > MAX_SERVER_PORT) {\n continue;\n }\n\n return parsed;\n }\n\n return DEFAULT_SERVER_PORT;\n};\n\n/** Adds the listening server (`Bun.serve` / `@hono/node-server`) on top of `RestApplication` - the only layer that touches a socket, so it is the layer that stays out of the browser-pure kernel. */\nexport abstract class ServerApplication<\n AppEnv extends Env = Env,\n AppSchema extends Schema = {},\n BasePath extends string = '/',\n>\n extends RestApplication<AppEnv, AppSchema, BasePath>\n implements IServerApplication<AppEnv, AppSchema, BasePath>\n{\n /** Which runtime is underneath, and the socket once one is bound. Both live here, not on `RestApplication`: a browser Worker has neither, and `RuntimeModules.detect()` answers `'node'` there. */\n protected runtime = RuntimeModules.detect();\n protected serverInstance?: TBunServerInstance | TNodeServerInstance;\n\n /** Widened by this layer, which is the only one that binds a socket. Assigned by the base constructor - `declare` so no field initializer runs here and overwrites it with `undefined`. */\n declare protected configs: IServerApplicationConfigs;\n\n /**\n * The address resolution the kernel deliberately does not do: `host` and `port` mean nothing to a\n * host with no socket, and resolving them there silently configured every browser Worker with\n * `localhost:3000`. Env is the fallback, explicit config always wins.\n */\n constructor(opts: { scope: string; config: IServerApplicationConfigs }) {\n super(opts);\n\n this.configs.host =\n [opts.config.host, process.env.HOST, process.env.APP_ENV_SERVER_HOST].find(Boolean) ??\n DEFAULT_SERVER_HOST;\n this.configs.port = resolveServerPort({\n candidates: [opts.config.port, process.env.PORT, process.env.APP_ENV_SERVER_PORT],\n });\n }\n\n /** Restores the pre-split default: a server-capable application installs `hono/context-storage` unless the caller opts out explicitly. */\n protected override getDefaultAsyncContextEnabled(): boolean {\n return true;\n }\n\n /** `configs.projectRoot` wins, else the process cwd. The value is bound AND handed to `ModuleUtility`, so every peer lookup (optional modules, the gRPC adapter) resolves under it - a compiled binary sets it to where its `node_modules` really is. */\n override getProjectRoot(): string {\n const projectRoot = this.configs.projectRoot ?? process.cwd();\n if (this.configs.projectRoot && !existsSync(path.join(projectRoot, 'node_modules'))) {\n this.logger\n .for(this.getProjectRoot.name)\n .warn(\n 'configs.projectRoot has no node_modules | root: %s | optional peers will not resolve from it',\n projectRoot,\n );\n }\n this.bind<string>({ key: CoreBindings.APPLICATION_PROJECT_ROOT }).toValue(projectRoot);\n ModuleUtility.setProjectRoot({ projectRoot });\n return projectRoot;\n }\n\n getServerHost(): string {\n return this.configs.host!;\n }\n\n getServerPort(): number {\n return this.configs.port!;\n }\n\n getServerAddress() {\n return `${this.getServerHost()}:${this.getServerPort()}`;\n }\n\n /** `configs.server` with unset keys dropped, so a missing option keeps Bun's default instead of passing `undefined`. */\n protected getServerRuntimeOptions(): IServerRuntimeConfigs {\n const { idleTimeout, maxRequestBodySize } = this.configs.server ?? {};\n return {\n ...(idleTimeout === undefined ? {} : { idleTimeout }),\n ...(maxRequestBodySize === undefined ? {} : { maxRequestBodySize }),\n };\n }\n\n getServerInstance<\n T extends TBunServerInstance | TNodeServerInstance = TBunServerInstance | TNodeServerInstance,\n >(): T | undefined {\n return this.serverInstance as T | undefined;\n }\n\n protected startBunModule() {\n return new Promise((resolve, reject) => {\n if (this.runtime !== RuntimeModules.BUN) {\n return reject(\n getError({\n message: `[startBunModule] Invalid runtime to start server | runtime: ${this.runtime} | required: ${RuntimeModules.BUN}`,\n }),\n );\n }\n\n const port = this.getServerPort();\n const host = this.getServerHost();\n const server = this.getServer();\n\n Promise.resolve(\n Bun.serve({\n port,\n hostname: host,\n fetch: server.fetch,\n ...this.getServerRuntimeOptions(),\n }),\n )\n .then(rs => {\n this.serverInstance = rs;\n this.configs.port = rs.port;\n this.inspectRoutes();\n\n this.logger\n .for(this.start.name)\n .info('Server STARTED | Address: %s', this.getServerAddress());\n this.logger\n .for(this.start.name)\n .info(\n 'Log folder: %s',\n path.resolve(process.env.APP_ENV_LOGGER_FOLDER_PATH ?? '').toString(),\n );\n\n resolve(rs);\n })\n .catch(reject);\n });\n }\n\n protected startNodeModule() {\n return new Promise((resolve, reject) => {\n if (this.runtime !== RuntimeModules.NODE) {\n return reject(\n getError({\n message: `[startNodeModule] Invalid runtime to start server | runtime: ${this.runtime} | required: ${RuntimeModules.NODE}`,\n }),\n );\n }\n\n const port = this.getServerPort();\n const host = this.getServerHost();\n const server = this.getServer();\n const ignored = Object.keys(this.getServerRuntimeOptions());\n if (ignored.length > 0) {\n this.logger\n .for(this.startNodeModule.name)\n .warn('configs.server is Bun-only | ignored on node: %s', ignored.join(', '));\n }\n\n import('@hono/node-server')\n .then(module => {\n const { serve } = module;\n\n // Resolve from the listening callback, not serve()'s synchronous return - only then is the socket bound and the OS-assigned port (config port `0`) known.\n const rs = serve({ fetch: server.fetch, port, hostname: host }, info => {\n this.configs.port = info.port;\n this.inspectRoutes();\n this.logger\n .for(this.start.name)\n .info('Server STARTED | Address: %s | Info: %j', this.getServerAddress(), info);\n this.logger\n .for(this.start.name)\n .info(\n 'Log folder: %s',\n path.resolve(process.env.APP_ENV_LOGGER_FOLDER_PATH ?? '').toString(),\n );\n\n this.serverInstance = rs;\n resolve(rs);\n });\n })\n .catch(error => {\n this.logger\n .for(this.start.name)\n .error('Failed to import @hono/node-server | Error: %s', error);\n reject(\n getError({\n message: `[start] @hono/node-server is required for Node.js runtime. Please install '@hono/node-server'`,\n }),\n );\n });\n });\n }\n\n async start() {\n await this.initialize();\n await this.setupMiddlewares();\n\n const server = this.getServer();\n server.route(this.configs.path.base, this.rootRouter);\n\n switch (this.runtime) {\n case RuntimeModules.BUN: {\n await this.startBunModule();\n break;\n }\n case RuntimeModules.NODE: {\n await this.startNodeModule();\n break;\n }\n default: {\n throw getError({\n message: '[start] Invalid runtimeModule to start server instance!',\n });\n }\n }\n\n await this.executePostStartHooks();\n }\n\n /** Post-stop hooks, then the server, then the datasources - closed even when the server fails to, so a stopped application holds no connection. */\n async stop() {\n await this.executePostStopHooks();\n\n try {\n await this.stopServer();\n } finally {\n await this.closeDataSources();\n }\n }\n\n protected async stopServer(): Promise<void> {\n const instance = this.serverInstance;\n if (!instance) {\n this.logger.for(this.stop.name).info('Server was not started | Nothing to stop');\n return;\n }\n\n switch (this.runtime) {\n case RuntimeModules.BUN: {\n await instance.stop();\n break;\n }\n case RuntimeModules.NODE: {\n // `close()` is callback-based: without this bridge stop() resolves while the socket is still bound, so an immediate restart races the previous listener.\n await new Promise<void>((resolve, reject) => {\n instance.close((error?: Error) => {\n if (error) {\n reject(error);\n return;\n }\n\n resolve();\n });\n });\n break;\n }\n default: {\n throw getError({\n message: '[stop] Invalid runtimeModule to stop server instance!',\n });\n }\n }\n\n this.serverInstance = undefined;\n this.logger.for(this.stop.name).info('Server STOPPED');\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../../src/base/applications/server.ts"],"names":[],"mappings":";;;;;;AAAA,wDAAsE;AACtE,0DAAuD;AACvD,sDAAuD;AACvD,0DAA+D;AAE/D,qCAAqC;AACrC,0DAA6B;AAY7B,MAAM,wBAAwB,GAAqB,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;AACzE,MAAM,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ACtB,MAAM;YACR,CAAC;YACD,KAAK,uBAAc,CAAC,IAAI,CAAC,CAAC,CAAC;gBACzB,yJAAyJ;gBACzJ,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;oBAC1C,QAAQ,CAAC,KAAK,CAAC,CAAC,KAAa,EAAE,EAAE;wBAC/B,IAAI,KAAK,EAAE,CAAC;4BACV,MAAM,CAAC,KAAK,CAAC,CAAC;4BACd,OAAO;wBACT,CAAC;wBAED,OAAO,EAAE,CAAC;oBACZ,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;gBACH,MAAM;YACR,CAAC;YACD,OAAO,CAAC,CAAC,CAAC;gBACR,MAAM,IAAA,eAAQ,EAAC;oBACb,OAAO,EAAE,uDAAuD;iBACjE,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;IACzD,CAAC;CACF;AA/UD,8CA+UC","sourcesContent":["import { CoreBindings, RestApplication } from '@venizia/ignis-kernel';\nimport { ModuleUtility } from '@venizia/ignis-helpers';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { RuntimeModules } from '@venizia/ignis-helpers/common';\nimport type { Env, Schema } from 'hono';\nimport { existsSync } from 'node:fs';\nimport path from 'node:path';\nimport type {\n IServerApplication,\n IServerApplicationConfigs,\n IServerRuntimeConfigs,\n IShutdownSignalsOptions,\n TNodeServerInstance,\n} from './common';\n\n/** Lives here, not in the kernel: `Bun.serve` resolves only through `@types/bun`, and emitting `Bun` into the kernel's published `.d.ts` would force that dependency on every browser consumer of `@venizia/ignis-kernel`. This package legitimately has Bun types - it is the layer that calls `Bun.serve`. */\nexport type TBunServerInstance = ReturnType<typeof Bun.serve>;\n\nconst DEFAULT_SHUTDOWN_SIGNALS: NodeJS.Signals[] = ['SIGTERM', 'SIGINT'];\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 15_000;\n\nconst DEFAULT_SERVER_HOST = 'localhost';\nconst DEFAULT_SERVER_PORT = 3000;\nconst MAX_SERVER_PORT = 65535;\n\n/**\n * The first candidate USABLE as a port. Rejection is on validity, never falsiness: `0` legitimately\n * asks the OS for an ephemeral port, and taking the first TRUTHY value instead let an unusable\n * `PORT` shadow a usable `APP_ENV_SERVER_PORT` - `PORT=abc APP_ENV_SERVER_PORT=8080` bound 3000, as\n * did Docker's legacy container-link form `PORT=tcp://172.17.0.5:8080`.\n */\nconst resolveServerPort = (opts: { candidates: Array<number | string | undefined> }): number => {\n for (const candidate of opts.candidates) {\n if (candidate === undefined || candidate === null) {\n continue;\n }\n\n const normalized = typeof candidate === 'string' ? candidate.trim() : candidate;\n if (normalized === '') {\n continue;\n }\n\n const parsed = Number(normalized);\n if (!Number.isInteger(parsed) || parsed < 0 || parsed > MAX_SERVER_PORT) {\n continue;\n }\n\n return parsed;\n }\n\n return DEFAULT_SERVER_PORT;\n};\n\n/** Adds the listening server (`Bun.serve` / `@hono/node-server`) on top of `RestApplication` - the only layer that touches a socket, so it is the layer that stays out of the browser-pure kernel. */\nexport abstract class ServerApplication<\n AppEnv extends Env = Env,\n AppSchema extends Schema = {},\n BasePath extends string = '/',\n>\n extends RestApplication<AppEnv, AppSchema, BasePath>\n implements IServerApplication<AppEnv, AppSchema, BasePath>\n{\n /** Which runtime is underneath, and the socket once one is bound. Both live here, not on `RestApplication`: a browser Worker has neither, and `RuntimeModules.detect()` answers `'node'` there. */\n protected runtime = RuntimeModules.detect();\n protected serverInstance?: TBunServerInstance | TNodeServerInstance;\n\n /** Widened by this layer, which is the only one that binds a socket. Assigned by the base constructor - `declare` so no field initializer runs here and overwrites it with `undefined`. */\n declare protected configs: IServerApplicationConfigs;\n\n /**\n * The address resolution the kernel deliberately does not do: `host` and `port` mean nothing to a\n * host with no socket, and resolving them there silently configured every browser Worker with\n * `localhost:3000`. Env is the fallback, explicit config always wins.\n */\n constructor(opts: { scope: string; config: IServerApplicationConfigs }) {\n super(opts);\n\n this.configs.host =\n [opts.config.host, process.env.HOST, process.env.APP_ENV_SERVER_HOST].find(Boolean) ??\n DEFAULT_SERVER_HOST;\n this.configs.port = resolveServerPort({\n candidates: [opts.config.port, process.env.PORT, process.env.APP_ENV_SERVER_PORT],\n });\n }\n\n /** Restores the pre-split default: a server-capable application installs `hono/context-storage` unless the caller opts out explicitly. */\n protected override getDefaultAsyncContextEnabled(): boolean {\n return true;\n }\n\n /** `configs.projectRoot` wins, else the process cwd. The value is bound AND handed to `ModuleUtility`, so every peer lookup (optional modules, the gRPC adapter) resolves under it - a compiled binary sets it to where its `node_modules` really is. */\n override getProjectRoot(): string {\n const projectRoot = this.configs.projectRoot ?? process.cwd();\n if (this.configs.projectRoot && !existsSync(path.join(projectRoot, 'node_modules'))) {\n this.logger\n .for(this.getProjectRoot.name)\n .warn(\n 'configs.projectRoot has no node_modules | root: %s | optional peers will not resolve from it',\n projectRoot,\n );\n }\n this.bind<string>({ key: CoreBindings.APPLICATION_PROJECT_ROOT }).toValue(projectRoot);\n ModuleUtility.setProjectRoot({ projectRoot });\n return projectRoot;\n }\n\n getServerHost(): string {\n return this.configs.host!;\n }\n\n getServerPort(): number {\n return this.configs.port!;\n }\n\n getServerAddress() {\n return `${this.getServerHost()}:${this.getServerPort()}`;\n }\n\n /** `configs.server` with unset keys dropped, so a missing option keeps Bun's default instead of passing `undefined`. */\n protected getServerRuntimeOptions(): IServerRuntimeConfigs {\n const { idleTimeout, maxRequestBodySize } = this.configs.server ?? {};\n return {\n ...(idleTimeout === undefined ? {} : { idleTimeout }),\n ...(maxRequestBodySize === undefined ? {} : { maxRequestBodySize }),\n };\n }\n\n getServerInstance<\n T extends TBunServerInstance | TNodeServerInstance = TBunServerInstance | TNodeServerInstance,\n >(): T | undefined {\n return this.serverInstance as T | undefined;\n }\n\n protected startBunModule() {\n return new Promise((resolve, reject) => {\n if (this.runtime !== RuntimeModules.BUN) {\n return reject(\n getError({\n message: `[startBunModule] Invalid runtime to start server | runtime: ${this.runtime} | required: ${RuntimeModules.BUN}`,\n }),\n );\n }\n\n const port = this.getServerPort();\n const host = this.getServerHost();\n const server = this.getServer();\n\n Promise.resolve(\n Bun.serve({\n port,\n hostname: host,\n fetch: server.fetch,\n ...this.getServerRuntimeOptions(),\n }),\n )\n .then((rs) => {\n this.serverInstance = rs;\n this.configs.port = rs.port;\n this.inspectRoutes();\n\n this.logger\n .for(this.start.name)\n .info('Server STARTED | Address: %s', this.getServerAddress());\n this.logger\n .for(this.start.name)\n .info(\n 'Log folder: %s',\n path.resolve(process.env.APP_ENV_LOGGER_FOLDER_PATH ?? '').toString(),\n );\n\n resolve(rs);\n })\n .catch(reject);\n });\n }\n\n protected startNodeModule() {\n return new Promise((resolve, reject) => {\n if (this.runtime !== RuntimeModules.NODE) {\n return reject(\n getError({\n message: `[startNodeModule] Invalid runtime to start server | runtime: ${this.runtime} | required: ${RuntimeModules.NODE}`,\n }),\n );\n }\n\n const port = this.getServerPort();\n const host = this.getServerHost();\n const server = this.getServer();\n const ignored = Object.keys(this.getServerRuntimeOptions());\n if (ignored.length > 0) {\n this.logger\n .for(this.startNodeModule.name)\n .warn('configs.server is Bun-only | ignored on node: %s', ignored.join(', '));\n }\n\n import('@hono/node-server')\n .then((module) => {\n const { serve } = module;\n\n // Resolve from the listening callback, not serve()'s synchronous return - only then is the socket bound and the OS-assigned port (config port `0`) known.\n const rs = serve({ fetch: server.fetch, port, hostname: host }, (info) => {\n this.configs.port = info.port;\n this.inspectRoutes();\n this.logger\n .for(this.start.name)\n .info('Server STARTED | Address: %s | Info: %j', this.getServerAddress(), info);\n this.logger\n .for(this.start.name)\n .info(\n 'Log folder: %s',\n path.resolve(process.env.APP_ENV_LOGGER_FOLDER_PATH ?? '').toString(),\n );\n\n this.serverInstance = rs;\n resolve(rs);\n });\n })\n .catch((error) => {\n this.logger\n .for(this.start.name)\n .error('Failed to import @hono/node-server | Error: %s', error);\n reject(\n getError({\n message: `[start] @hono/node-server is required for Node.js runtime. Please install '@hono/node-server'`,\n }),\n );\n });\n });\n }\n\n async start() {\n await this.initialize();\n await this.setupMiddlewares();\n\n const server = this.getServer();\n server.route(this.configs.path.base, this.rootRouter);\n\n switch (this.runtime) {\n case RuntimeModules.BUN: {\n await this.startBunModule();\n break;\n }\n case RuntimeModules.NODE: {\n await this.startNodeModule();\n break;\n }\n default: {\n throw getError({\n message: '[start] Invalid runtimeModule to start server instance!',\n });\n }\n }\n\n await this.executePostStartHooks();\n }\n\n /** Post-stop hooks, then the server, then the datasources - closed even when the server fails to, so a stopped application holds no connection. */\n async stop() {\n await this.executePostStopHooks();\n\n try {\n await this.stopServer();\n } finally {\n await this.closeDataSources();\n }\n }\n\n /** Set once `installShutdownSignals` ran; holds the way back, so a second call is a no-op. */\n protected shutdownSignals?: { uninstall: () => void };\n\n /**\n * Stops the application on a signal (SIGTERM and SIGINT by default), then exits the process.\n * Opt-in: nothing is installed until you call it, usually right after `start()`.\n *\n * - Calls `stop()` once. A second signal while it runs is ignored.\n * - Exits 0 when `stop()` finishes, 1 when it throws or does not finish within `timeoutMs`.\n * - Idempotent: calling it again returns the same uninstall function and adds no listener.\n * - Returns an uninstall function that removes the listeners and the pending timeout.\n */\n installShutdownSignals(opts: IShutdownSignalsOptions = {}): () => void {\n if (this.shutdownSignals) {\n return this.shutdownSignals.uninstall;\n }\n\n const {\n signals = DEFAULT_SHUTDOWN_SIGNALS,\n timeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS,\n exit = (code: number) => process.exit(code),\n } = opts;\n\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw getError({\n message: `[installShutdownSignals] timeoutMs must be a positive number of milliseconds | value: ${String(timeoutMs)}`,\n });\n }\n\n const log = this.logger.for(this.installShutdownSignals.name);\n let isShuttingDown = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const finish = (code: number) => {\n clearTimeout(timer);\n exit(code);\n };\n\n const onSignal = (signal: NodeJS.Signals) => {\n if (isShuttingDown) {\n log.warn('Signal %s ignored | shutdown already in progress', signal);\n return;\n }\n\n isShuttingDown = true;\n log.info('Signal %s received | stopping the application | timeout: %s ms', signal, timeoutMs);\n\n timer = setTimeout(() => {\n log.error('Shutdown did not finish within %s ms | forcing exit', timeoutMs);\n exit(1);\n }, timeoutMs);\n\n this.stop().then(\n () => {\n log.info('Application stopped | exiting');\n finish(0);\n },\n (error: unknown) => {\n log.error(\n 'Shutdown failed | error: %s',\n error instanceof Error ? error.message : String(error),\n );\n finish(1);\n },\n );\n };\n\n const listeners = signals.map((signal) => {\n const listener = () => onSignal(signal);\n process.on(signal, listener);\n return { signal, listener };\n });\n\n const uninstall = () => {\n clearTimeout(timer);\n for (const { signal, listener } of listeners) {\n process.off(signal, listener);\n }\n this.shutdownSignals = undefined;\n };\n\n this.shutdownSignals = { uninstall };\n return uninstall;\n }\n\n protected async stopServer(): Promise<void> {\n const instance = this.serverInstance;\n if (!instance) {\n this.logger.for(this.stop.name).info('Server was not started | Nothing to stop');\n return;\n }\n\n switch (this.runtime) {\n case RuntimeModules.BUN: {\n await instance.stop();\n break;\n }\n case RuntimeModules.NODE: {\n // `close()` is callback-based: without this bridge stop() resolves while the socket is still bound, so an immediate restart races the previous listener.\n await new Promise<void>((resolve, reject) => {\n instance.close((error?: Error) => {\n if (error) {\n reject(error);\n return;\n }\n\n resolve();\n });\n });\n break;\n }\n default: {\n throw getError({\n message: '[stop] Invalid runtimeModule to stop server instance!',\n });\n }\n }\n\n this.serverInstance = undefined;\n this.logger.for(this.stop.name).info('Server STOPPED');\n }\n}\n"]}
|
|
@@ -19,7 +19,7 @@ class AppErrorMiddleware extends ignis_kernel_1.BaseAppErrorMiddleware {
|
|
|
19
19
|
// Present, so an unresolved name here is a real misconfiguration and keeps its error line - a
|
|
20
20
|
// node host always HAS an ambient environment, even when it is not set.
|
|
21
21
|
environment: opts?.environment ?? (() => ignis_helpers_1.Environment.ambient),
|
|
22
|
-
formatError: opts?.formatError ?? (formatOpts => ignis_helpers_1.ErrorPrettier.format(formatOpts)),
|
|
22
|
+
formatError: opts?.formatError ?? ((formatOpts) => ignis_helpers_1.ErrorPrettier.format(formatOpts)),
|
|
23
23
|
});
|
|
24
24
|
}
|
|
25
25
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-error.middleware.js","sourceRoot":"","sources":["../../../../src/base/middlewares/app-error/app-error.middleware.ts"],"names":[],"mappings":";;;AAAA,0DAAoE;AACpE,wDAA+D;AAI/D;;;;;;;;GAQG;AACH,MAAa,kBAAmB,SAAQ,qCAAsB;IAC5D,YAAY,IAOX;QACC,KAAK,CAAC;YACJ,GAAG,IAAI;YACP,8FAA8F;YAC9F,wEAAwE;YACxE,WAAW,EAAE,IAAI,EAAE,WAAW,IAAI,CAAC,GAAG,EAAE,CAAC,2BAAW,CAAC,OAAO,CAAC;YAC7D,WAAW,EAAE,IAAI,EAAE,WAAW,IAAI,CAAC,UAAU,
|
|
1
|
+
{"version":3,"file":"app-error.middleware.js","sourceRoot":"","sources":["../../../../src/base/middlewares/app-error/app-error.middleware.ts"],"names":[],"mappings":";;;AAAA,0DAAoE;AACpE,wDAA+D;AAI/D;;;;;;;;GAQG;AACH,MAAa,kBAAmB,SAAQ,qCAAsB;IAC5D,YAAY,IAOX;QACC,KAAK,CAAC;YACJ,GAAG,IAAI;YACP,8FAA8F;YAC9F,wEAAwE;YACxE,WAAW,EAAE,IAAI,EAAE,WAAW,IAAI,CAAC,GAAG,EAAE,CAAC,2BAAW,CAAC,OAAO,CAAC;YAC7D,WAAW,EAAE,IAAI,EAAE,WAAW,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,6BAAa,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;SACrF,CAAC,CAAC;IACL,CAAC;CACF;AAjBD,gDAiBC","sourcesContent":["import { Environment, ErrorPrettier } from '@venizia/ignis-helpers';\nimport { BaseAppErrorMiddleware } from '@venizia/ignis-kernel';\nimport type { ILogger } from '@venizia/ignis-helpers/core';\nimport type { TErrorLogFormatter } from '@venizia/ignis-kernel';\n\n/**\n * The server-side error handler: everything it does lives on {@link BaseAppErrorMiddleware}, which\n * is browser-pure. This supplies the two host reads as OPTIONS - the ambient `NODE_ENV` through\n * `Environment.ambient` (a read `bun build` cannot fold into a literal), and `ErrorPrettier`, which\n * reaches `node:util` and so cannot sit in the kernel.\n *\n * A class only so the name `AppErrorMiddleware` keeps resolving for existing consumers; it overrides\n * nothing. New code can pass the same two options to `BaseAppErrorMiddleware` directly.\n */\nexport class AppErrorMiddleware extends BaseAppErrorMiddleware {\n constructor(opts?: {\n logger?: ILogger;\n rootKey?: string;\n intentionalStackFrames?: number;\n unexpectedStackFrames?: number;\n environment?: () => string | undefined;\n formatError?: TErrorLogFormatter;\n }) {\n super({\n ...opts,\n // Present, so an unresolved name here is a real misconfiguration and keeps its error line - a\n // node host always HAS an ambient environment, even when it is not set.\n environment: opts?.environment ?? (() => Environment.ambient),\n formatError: opts?.formatError ?? ((formatOpts) => ErrorPrettier.format(formatOpts)),\n });\n }\n}\n"]}
|
|
@@ -155,7 +155,7 @@ const defineAuthController = (opts) => {
|
|
|
155
155
|
query: zod_openapi_1.z.object({
|
|
156
156
|
withUserInformation: zod_openapi_1.z
|
|
157
157
|
.enum(['true', 'false', '1', '0'])
|
|
158
|
-
.transform(value => value === 'true' || value === '1')
|
|
158
|
+
.transform((value) => value === 'true' || value === '1')
|
|
159
159
|
.optional()
|
|
160
160
|
.openapi({
|
|
161
161
|
description: 'Whether to attach user information to currentUser',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory.js","sourceRoot":"","sources":["../../../../../src/components/auth/authenticate/controllers/factory.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wDAA2D;AAC3D,wDAA+C;AAC/C,wDAAmD;AACnD,wDAAkE;AAClE,2CAAgD;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C1B,OAAO,EAAE,oBAAoB;4BAC7B,MAAM,EAAE,IAAI,CAAC,MAAM;yBACpB,CAAC,CAAC;oBACL,CAAC;oBAED,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;oBAC9D,OAAO,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,aAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBACpD,CAAC;aACF,CAAC,CAAC;QACL,CAAC;KACF,CAAA;IA1MK,cAAc;QADnB,IAAA,yBAAU,EAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;;OACzB,cAAc,CA0MnB;IAED,IAAA,qBAAM,EAAC,EAAE,GAAG,EAAE,UAAU,EAAE,CAAC,CAAC,cAAc,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC;IAE1D,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC;AAnNW,QAAA,oBAAoB,wBAmN/B","sourcesContent":["import { BaseRestController } from '@venizia/ignis-kernel';\nimport { inject } from '@venizia/ignis-kernel';\nimport { controller } from '@venizia/ignis-kernel';\nimport { jsonContent, jsonResponse } from '@venizia/ignis-kernel';\nimport { throwNotSupported } from '@/utilities';\nimport { AnyObjectSchema } from '@venizia/ignis-kernel';\nimport { z } from '@hono/zod-openapi';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { HTTP, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport {\n ChangePasswordRequestSchema,\n SignInRequestSchema,\n SignUpRequestSchema,\n} from '@venizia/ignis-kernel';\nimport {\n Authentication,\n type IAuthService,\n type TDefineAuthControllerOpts,\n} from '@venizia/ignis-kernel';\n\nexport const JWTTokenPayloadSchema = z.object({\n userId: z.string().or(z.number()),\n roles: z.array(\n z.object({\n id: z.string().or(z.number()),\n identifier: z.string(),\n priority: z.number().int(),\n }),\n ),\n clientId: z.string().optional(),\n provider: z.string().optional(),\n email: z.email().optional(),\n});\n\nexport const defineAuthController = (opts: TDefineAuthControllerOpts) => {\n const { restPath = '/auth', serviceKey, requireAuthenticatedSignUp = false, payload = {} } = opts;\n\n @controller({ path: restPath })\n class AuthController extends BaseRestController {\n service: IAuthService;\n\n constructor(authService: IAuthService) {\n super({\n scope: AuthController.name,\n path: restPath,\n isStrict: true,\n });\n\n if (!authService) {\n throw getError({\n message:\n '[AuthController] Failed to init auth controller | Invalid injectable authentication service!',\n });\n }\n\n this.service = authService;\n }\n\n override binding(): ValueOrPromise<void> {\n this.defineRoute({\n configs: {\n description: 'Sign In',\n path: '/sign-in',\n method: HTTP.Methods.POST,\n request: {\n body: jsonContent({\n description: 'Sign-in request body',\n required: true,\n schema: payload?.signIn?.request?.schema ?? SignInRequestSchema,\n }),\n },\n responses: jsonResponse({\n schema: payload?.signIn?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n },\n handler: async context => {\n const body = await context.req.json();\n const rs = await this.service.signIn(context, body);\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n description: 'Sign Up',\n path: '/sign-up',\n method: HTTP.Methods.POST,\n authenticate: {\n strategies: !requireAuthenticatedSignUp ? [] : [Authentication.STRATEGY_JWT],\n },\n request: {\n body: jsonContent({\n description: 'Sign-up request body',\n required: true,\n schema: payload?.signUp?.request?.schema ?? SignUpRequestSchema,\n }),\n },\n responses: jsonResponse({\n schema: payload?.signUp?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n },\n handler: async context => {\n const body = await context.req.json();\n const rs = await this.service.signUp(context, body);\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n description: 'Change password',\n path: '/change-password',\n method: HTTP.Methods.POST,\n request: {\n body: jsonContent({\n description: 'Change password request body',\n required: true,\n schema: payload?.changePassword?.request?.schema ?? ChangePasswordRequestSchema,\n }),\n },\n responses: jsonResponse({\n schema: payload?.changePassword?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async context => {\n const body = await context.req.json();\n const rs = await this.service.changePassword(context, body);\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n // Re-issues an access token using the caller's currently valid JWT — no separate refresh token. Implementers must enforce their own rotation/revocation policy if needed.\n this.defineRoute({\n configs: {\n description: 'Refresh access token',\n path: '/token/refresh',\n method: HTTP.Methods.POST,\n responses: jsonResponse({\n schema: payload?.refreshToken?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async context => {\n if (!this.service.refreshToken) {\n return throwNotSupported({\n scope: AuthController.name,\n feature: 'refreshToken',\n logger: this.logger,\n });\n }\n\n const rs = await this.service.refreshToken(context);\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n path: '/who-am-i',\n method: HTTP.Methods.GET,\n request: {\n query: z.object({\n withUserInformation: z\n .enum(['true', 'false', '1', '0'])\n .transform(value => value === 'true' || value === '1')\n .optional()\n .openapi({\n description: 'Whether to attach user information to currentUser',\n }),\n }),\n },\n responses: {\n [HTTP.ResultCodes.RS_2.Ok]: jsonContent({\n description: 'Success Response',\n schema: JWTTokenPayloadSchema.extend({\n userInformation: (payload?.getUserInformation?.response?.schema ?? AnyObjectSchema)\n .optional()\n .openapi({\n description: 'Attached when withUserInformation is truthy',\n }),\n }),\n }),\n },\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async context => {\n const { withUserInformation = false } = context.req.valid<{\n withUserInformation?: boolean;\n }>('query');\n\n const currentUser = context.get(Authentication.CURRENT_USER);\n let rs = currentUser;\n\n if (withUserInformation) {\n if (!this.service.getUserInformation) {\n return throwNotSupported({\n scope: AuthController.name,\n feature: 'getUserInformation',\n logger: this.logger,\n });\n }\n\n const userInformation = await this.service.getUserInformation(context, {});\n rs = Object.assign({}, currentUser, { userInformation });\n }\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n description: 'Get current user information',\n path: '/me',\n method: HTTP.Methods.GET,\n responses: jsonResponse({\n schema: payload?.getUserInformation?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async context => {\n if (!this.service.getUserInformation) {\n return throwNotSupported({\n scope: AuthController.name,\n feature: 'getUserInformation',\n logger: this.logger,\n });\n }\n\n const rs = await this.service.getUserInformation(context, {});\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n }\n }\n\n inject({ key: serviceKey })(AuthController, undefined, 0);\n\n return AuthController;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"factory.js","sourceRoot":"","sources":["../../../../../src/components/auth/authenticate/controllers/factory.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wDAA2D;AAC3D,wDAA+C;AAC/C,wDAAmD;AACnD,wDAAkE;AAClE,2CAAgD;AAChD,wDAAwD;AACxD,mDAAsC;AACtC,sDAAuD;AACvD,0DAA0E;AAC1E,wDAI+B;AAC/B,wDAI+B;AAElB,QAAA,qBAAqB,GAAG,eAAC,CAAC,MAAM,CAAC;IAC5C,MAAM,EAAE,eAAC,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,eAAC,CAAC,MAAM,EAAE,CAAC;IACjC,KAAK,EAAE,eAAC,CAAC,KAAK,CACZ,eAAC,CAAC,MAAM,CAAC;QACP,EAAE,EAAE,eAAC,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,eAAC,CAAC,MAAM,EAAE,CAAC;QAC7B,UAAU,EAAE,eAAC,CAAC,MAAM,EAAE;QACtB,QAAQ,EAAE,eAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE;KAC3B,CAAC,CACH;IACD,QAAQ,EAAE,eAAC,CAAC,MAAM,EAA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,CAAC,CAAC;IAE1D,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC;AAnNW,QAAA,oBAAoB,wBAmN/B","sourcesContent":["import { BaseRestController } from '@venizia/ignis-kernel';\nimport { inject } from '@venizia/ignis-kernel';\nimport { controller } from '@venizia/ignis-kernel';\nimport { jsonContent, jsonResponse } from '@venizia/ignis-kernel';\nimport { throwNotSupported } from '@/utilities';\nimport { AnyObjectSchema } from '@venizia/ignis-kernel';\nimport { z } from '@hono/zod-openapi';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport { HTTP, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport {\n ChangePasswordRequestSchema,\n SignInRequestSchema,\n SignUpRequestSchema,\n} from '@venizia/ignis-kernel';\nimport {\n Authentication,\n type IAuthService,\n type TDefineAuthControllerOpts,\n} from '@venizia/ignis-kernel';\n\nexport const JWTTokenPayloadSchema = z.object({\n userId: z.string().or(z.number()),\n roles: z.array(\n z.object({\n id: z.string().or(z.number()),\n identifier: z.string(),\n priority: z.number().int(),\n }),\n ),\n clientId: z.string().optional(),\n provider: z.string().optional(),\n email: z.email().optional(),\n});\n\nexport const defineAuthController = (opts: TDefineAuthControllerOpts) => {\n const { restPath = '/auth', serviceKey, requireAuthenticatedSignUp = false, payload = {} } = opts;\n\n @controller({ path: restPath })\n class AuthController extends BaseRestController {\n service: IAuthService;\n\n constructor(authService: IAuthService) {\n super({\n scope: AuthController.name,\n path: restPath,\n isStrict: true,\n });\n\n if (!authService) {\n throw getError({\n message:\n '[AuthController] Failed to init auth controller | Invalid injectable authentication service!',\n });\n }\n\n this.service = authService;\n }\n\n override binding(): ValueOrPromise<void> {\n this.defineRoute({\n configs: {\n description: 'Sign In',\n path: '/sign-in',\n method: HTTP.Methods.POST,\n request: {\n body: jsonContent({\n description: 'Sign-in request body',\n required: true,\n schema: payload?.signIn?.request?.schema ?? SignInRequestSchema,\n }),\n },\n responses: jsonResponse({\n schema: payload?.signIn?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n },\n handler: async (context) => {\n const body = await context.req.json();\n const rs = await this.service.signIn(context, body);\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n description: 'Sign Up',\n path: '/sign-up',\n method: HTTP.Methods.POST,\n authenticate: {\n strategies: !requireAuthenticatedSignUp ? [] : [Authentication.STRATEGY_JWT],\n },\n request: {\n body: jsonContent({\n description: 'Sign-up request body',\n required: true,\n schema: payload?.signUp?.request?.schema ?? SignUpRequestSchema,\n }),\n },\n responses: jsonResponse({\n schema: payload?.signUp?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n },\n handler: async (context) => {\n const body = await context.req.json();\n const rs = await this.service.signUp(context, body);\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n description: 'Change password',\n path: '/change-password',\n method: HTTP.Methods.POST,\n request: {\n body: jsonContent({\n description: 'Change password request body',\n required: true,\n schema: payload?.changePassword?.request?.schema ?? ChangePasswordRequestSchema,\n }),\n },\n responses: jsonResponse({\n schema: payload?.changePassword?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async (context) => {\n const body = await context.req.json();\n const rs = await this.service.changePassword(context, body);\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n // Re-issues an access token using the caller's currently valid JWT — no separate refresh token. Implementers must enforce their own rotation/revocation policy if needed.\n this.defineRoute({\n configs: {\n description: 'Refresh access token',\n path: '/token/refresh',\n method: HTTP.Methods.POST,\n responses: jsonResponse({\n schema: payload?.refreshToken?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async (context) => {\n if (!this.service.refreshToken) {\n return throwNotSupported({\n scope: AuthController.name,\n feature: 'refreshToken',\n logger: this.logger,\n });\n }\n\n const rs = await this.service.refreshToken(context);\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n path: '/who-am-i',\n method: HTTP.Methods.GET,\n request: {\n query: z.object({\n withUserInformation: z\n .enum(['true', 'false', '1', '0'])\n .transform((value) => value === 'true' || value === '1')\n .optional()\n .openapi({\n description: 'Whether to attach user information to currentUser',\n }),\n }),\n },\n responses: {\n [HTTP.ResultCodes.RS_2.Ok]: jsonContent({\n description: 'Success Response',\n schema: JWTTokenPayloadSchema.extend({\n userInformation: (payload?.getUserInformation?.response?.schema ?? AnyObjectSchema)\n .optional()\n .openapi({\n description: 'Attached when withUserInformation is truthy',\n }),\n }),\n }),\n },\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async (context) => {\n const { withUserInformation = false } = context.req.valid<{\n withUserInformation?: boolean;\n }>('query');\n\n const currentUser = context.get(Authentication.CURRENT_USER);\n let rs = currentUser;\n\n if (withUserInformation) {\n if (!this.service.getUserInformation) {\n return throwNotSupported({\n scope: AuthController.name,\n feature: 'getUserInformation',\n logger: this.logger,\n });\n }\n\n const userInformation = await this.service.getUserInformation(context, {});\n rs = Object.assign({}, currentUser, { userInformation });\n }\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n\n this.defineRoute({\n configs: {\n description: 'Get current user information',\n path: '/me',\n method: HTTP.Methods.GET,\n responses: jsonResponse({\n schema: payload?.getUserInformation?.response?.schema ?? AnyObjectSchema,\n description: 'Success Response',\n }),\n authenticate: { strategies: [Authentication.STRATEGY_JWT] },\n },\n handler: async (context) => {\n if (!this.service.getUserInformation) {\n return throwNotSupported({\n scope: AuthController.name,\n feature: 'getUserInformation',\n logger: this.logger,\n });\n }\n\n const rs = await this.service.getUserInformation(context, {});\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n }\n }\n\n inject({ key: serviceKey })(AuthController, undefined, 0);\n\n return AuthController;\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"controller.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/controllers/jwks/controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,wDAA2D;AAC3D,wDAA+C;AAC/C,wDAA0D;AAC1D,0DAA0E;AAC1E,8DAAuD;AACvD,6CAAwD;AACxD,+CAA6C;AAE7C,IAAa,cAAc,sBAA3B,MAAa,cAAe,SAAQ,iCAAkB;IACpD,YAOU,WAAmC;QAE3C,KAAK,CAAC;YACJ,KAAK,EAAE,gBAAc,CAAC,IAAI;YAC1B,IAAI,EAAE,QAAQ;YACd,QAAQ,EAAE,IAAI;SACf,CAAC,CAAC;QANK,gBAAW,GAAX,WAAW,CAAwB;IAO7C,CAAC;IAEQ,OAAO;QACd,IAAI,CAAC,WAAW,CAAC;YACf,OAAO,EAAE,0BAAY,CAAC,cAAc;YACpC,OAAO,EAAE,KAAK,
|
|
1
|
+
{"version":3,"file":"controller.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/controllers/jwks/controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,wDAA2D;AAC3D,wDAA+C;AAC/C,wDAA0D;AAC1D,0DAA0E;AAC1E,8DAAuD;AACvD,6CAAwD;AACxD,+CAA6C;AAE7C,IAAa,cAAc,sBAA3B,MAAa,cAAe,SAAQ,iCAAkB;IACpD,YAOU,WAAmC;QAE3C,KAAK,CAAC;YACJ,KAAK,EAAE,gBAAc,CAAC,IAAI;YAC1B,IAAI,EAAE,QAAQ;YACd,QAAQ,EAAE,IAAI;SACf,CAAC,CAAC;QANK,gBAAW,GAAX,WAAW,CAAwB;IAO7C,CAAC;IAEQ,OAAO;QACd,IAAI,CAAC,WAAW,CAAC;YACf,OAAO,EAAE,0BAAY,CAAC,cAAc;YACpC,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;gBACzB,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,YAAY,EAAE,CAAC;gBACnD,OAAO,CAAC,MAAM,CAAC,eAAe,EAAE,oDAAoD,CAAC,CAAC;gBACtF,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,aAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACtD,CAAC;SACF,CAAC,CAAC;IACL,CAAC;CACF,CAAA;AA3BY,wCAAc;yBAAd,cAAc;IAEtB,WAAA,IAAA,qBAAM,EAAC;QACN,GAAG,EAAE,6BAAW,CAAC,KAAK,CAAC;YACrB,SAAS,EAAE,gCAAiB,CAAC,OAAO;YACpC,GAAG,EAAE,iCAAsB,CAAC,IAAI;SACjC,CAAC;KACH,CAAC,CAAA;qCACmB,iCAAsB;GARlC,cAAc,CA2B1B","sourcesContent":["import { BaseRestController } from '@venizia/ignis-kernel';\nimport { inject } from '@venizia/ignis-kernel';\nimport { BindingNamespaces } from '@venizia/ignis-kernel';\nimport { HTTP, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BindingKeys } from '@venizia/ignis-inversion';\nimport { JWKSIssuerTokenService } from '../../services';\nimport { RouteConfigs } from './definitions';\n\nexport class JWKSController extends BaseRestController {\n constructor(\n @inject({\n key: BindingKeys.build({\n namespace: BindingNamespaces.SERVICE,\n key: JWKSIssuerTokenService.name,\n }),\n })\n private jwksService: JWKSIssuerTokenService,\n ) {\n super({\n scope: JWKSController.name,\n path: '/certs',\n isStrict: true,\n });\n }\n\n override binding(): ValueOrPromise<void> {\n this.defineRoute({\n configs: RouteConfigs.GET_JWKS_CERTS,\n handler: async (context) => {\n const jwks = await this.jwksService.getJWKSAsync();\n context.header('Cache-Control', 'public, max-age=3600, stale-while-revalidate=86400');\n return context.json(jwks, HTTP.ResultCodes.RS_2.Ok);\n },\n });\n }\n}\n"]}
|