@buildplease/apikit 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,33 +1,50 @@
1
1
  # @buildplease/apikit
2
2
 
3
- ApiKit is the BuildPlease backend runtime for Fastify applications. It combines typed application configuration with server infrastructure, dependency injection, validation, localization, HTTP primitives, and common backend services.
3
+ ApiKit is the BuildPlease application kit for backend services and APIs. It builds on Core and provides the runtime and infrastructure needed for Fastify applications.
4
4
 
5
- ## Install
5
+ ## Installation
6
6
 
7
7
  ```bash
8
8
  pnpm add @buildplease/apikit
9
9
  ```
10
10
 
11
- ## Usage
11
+ ## Configuration
12
12
 
13
- ApiKit applications are configured with `defineApiKit` and can use the backend primitives directly from the package:
13
+ ApiKit uses the shared BuildPlease `environment.config.ts` convention. Its `defineConfig()` adds the required ApiKit contract while still allowing app-owned typed configurations.
14
14
 
15
15
  ```ts
16
- import { defineApiKit, defineEnvironments, ServerController } from '@buildplease/apikit';
16
+ import { defineConfig, defineEnvironments, defineSource } from '@buildplease/apikit';
17
+
18
+ const environments = defineEnvironments({
19
+ test: { file: '.env.test' },
20
+ production: { file: '.env.production' },
21
+ });
22
+
23
+ const from = defineSource(environments);
24
+
25
+ export default defineConfig(environments, {
26
+ server: {
27
+ identifier: from.compute(({ buildMetadata, environment }) => {
28
+ return `${buildMetadata.name.original}:${environment.name}`;
29
+ }),
30
+ host: from.env('SERVER_HOST').default('127.0.0.1'),
31
+ port: from.env('SERVER_PORT').default('30000'),
32
+ },
33
+ });
17
34
  ```
18
35
 
19
- ApiKit also re-exports the Core and Core Node APIs used by backend applications.
36
+ ApiKit also exposes the BuildPlease primitives commonly used by backend applications.
20
37
 
21
- ## What’s included
38
+ ## Features
22
39
 
23
- - typed configuration and environment loading
24
- - Fastify server, request, response, cookie, CORS, multipart, static, health, and metrics support
40
+ - typed application configuration and environments
41
+ - Fastify server and HTTP infrastructure
25
42
  - dependency injection and application assemblies
26
43
  - validation, errors, formatting, and normalization
27
- - i18n and L10n resources
28
- - OpenAPI helpers
29
- - email and notification infrastructure
30
- - files, images, database helpers, cryptography, and tokens
31
- - `apikit` CLI
44
+ - i18n and L10n integration
45
+ - OpenAPI, notifications, email, files, and database helpers
46
+ - backend CLI tooling
32
47
 
33
- Part of [BuildPlease](https://github.com/BuildPlease/buildplease).
48
+ ## License
49
+
50
+ MIT
@@ -1,7 +1,7 @@
1
- import{defineCommand as e,runMain as t}from"citty";import{Console as n,createDirectory as r,createFile as i,ensureDirectory as a,loadPackageJSON as o,removePath as s,resolvePath as c}from"@buildplease/core/node";import ee from"node:fs";import l from"node:path";import{createJiti as te}from"jiti";import{injectable as u}from"inversify";import"@dotenvx/dotenvx";import{v7 as d}from"uuid";const f={build:{outDir:`.apikit`},logger:{enabled:!1},server:{debug:!1,trustProxy:!1},metrics:{enabled:!1,endpoint:`/metrics`,name:`metrics`,defaultMetrics:{enabled:!0},routeMetrics:{enabled:!0},clearRegisterOnInit:!1},health:{enabled:!0,url:`/health`,pressure:{maxEventLoopDelay:0,maxHeapUsedBytes:0,maxRssBytes:0,maxEventLoopUtilization:0}},notification:{enabled:!1},email:{enabled:!1,templatesPath:`./src/templates`,globals:{}},i18n:{resources:{},directories:[],files:[],defaultLanguage:`en`,fallbackLanguages:`en`,supportedLanguages:[`en`,`sk`,`cs`],load:`languageOnly`,preload:[`en`,`sk`,`cs`],nonExplicitSupportedLngs:!0,lowerCaseLng:!0,cleanCode:!0,defaultNamespace:`translation`,keySeparator:`.`,nsSeparator:`:`,pluralSeparator:`_`,contextSeparator:`_`},staticFiles:{enabled:!1,routePrefix:`/`,maxAge:3600,dotfiles:`ignore`,etag:!0,immutable:!0,decorateReply:!0,preCompressed:!1},basicAuth:{enabled:!1,authenticate:!1,proxyMode:!1,header:void 0,strictCredentials:void 0},cors:{enabled:!1,allowAllOrigins:!1,includeWwwSubdomain:!0,options:{methods:[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`OPTIONS`],credentials:!0,optionsSuccessStatus:200}},multipart:{enabled:!1,options:{limits:{fileSize:20971520}}}},p=[`.ts`,`.mts`,`.cts`,`.js`,`.mjs`,`.cjs`,`.json`];async function ne(e,t={}){let n=re(t.dir),r=m(n,t.config??e.defaultName);try{let t=await h(n,r);return{config:e.validate(t,r),configFilePath:r,rootDir:n}}catch(t){throw Error(`Failed to load ${e.name} config: ${t instanceof Error?t.message:String(t)}`)}}function re(e){let t=e?c(process.cwd(),e):process.cwd();return a(t),t}function m(e,t){let n=c(e,t);for(let e of p){let t=`${n}${e}`;if(ee.existsSync(t))return t}return n}async function h(e,t){return te(e,{interopDefault:!0,extensions:[...p],tsconfigPaths:!0}).import(t,{try:!0,default:!0})}const g=`apikit.config`;async function _(e={}){return ne({name:`ApiKit`,defaultName:g,validate:v},e)}function v(e,t){if(!e||typeof e!=`object`)throw Error(`ApiKit config is missing (${t})`);return e}const y=Symbol(`apikit.configuration.field`),b={string(){return x((e,t)=>{if(typeof e!=`string`)throw Error(`${t} must be string.`);let n=e.trim();if(!n)throw Error(`${t} must not be empty.`);return n},{required:!0})},number(){return x((e,t)=>{let n=typeof e==`number`?e:Number(e);if(!Number.isFinite(n))throw Error(`${t} must be number.`);return n},{required:!0})},boolean(){return x((e,t)=>{if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}throw Error(`${t} must be boolean.`)},{required:!0})},array(e){return x((t,n)=>{if(!Array.isArray(t))throw Error(`${n} must be array.`);return t.map((t,r)=>e.parse(t,`${n}[${r}]`))},{required:!0})},custom(){return x(e=>e,{required:!0})}};function ie(e){return!!(e&&typeof e==`object`&&e[y]===!0)}function x(e,t){let n={required:t.required,hasDefault:t.hasDefault??!1,defaultValue:t.defaultValue,parse:e,optional(){return x((t,n)=>{if(t!=null)return e(t,n)},{required:!1})},default(t){return x(e,{required:!1,hasDefault:!0,defaultValue:t})},map(n){let r=t.hasDefault&&t.defaultValue!==void 0?n(t.defaultValue):void 0;return x((t,r)=>n(e(t,r)),{required:t.required,hasDefault:t.hasDefault,defaultValue:r})}};return Object.defineProperty(n,y,{value:!0}),n}const ae=Symbol(`apikit.configuration.contract`),S=Symbol(`apikit.configuration.binding`);function C(e,t){let n=e.trim();if(!n)throw Error(`Configuration key must not be empty.`);let r=(e=>{let t={contract:r,input:e};return Object.defineProperty(t,S,{value:!0}),t});return Object.defineProperties(r,{[ae]:{value:!0},key:{value:n},schema:{value:t}}),r}function oe(e){return!!(e&&typeof e==`object`&&e[S]===!0)}const se=Symbol(`apikit.configuration.source`);function w(e){return!!(e&&typeof e==`object`&&e[se]===!0)}async function T(e,t,n={}){let r={buildMetadata:n.buildMetadata,environment:n.environment};return D(e.schema,t,r,e.key)}async function E(e,t){return T(e.contract,e.input,t)}async function D(e,t,n,r){if(ie(e))return O(e,t,n,r);let i=await k(t,n,r)??{};if(!i||typeof i!=`object`||Array.isArray(i))throw Error(`${r} must be object.`);let a={};for(let[t,o]of Object.entries(e))a[t]=await D(o,i[t],n,`${r}.${t}`);return a}async function O(e,t,n,r){let i=await k(t,n,r);if(i==null){if(e.hasDefault)return j(e.defaultValue);if(!e.required)return;throw Error(`Missing required configuration: ${r}`)}return e.parse(i,r)}async function k(e,t,n){if(w(e))return A(e,t,n);if(oe(e))return E(e,t);if(Array.isArray(e))return Promise.all(e.map((e,r)=>k(e,t,`${n}[${r}]`)));if(e&&typeof e==`object`){let r={};for(let[i,a]of Object.entries(e))r[i]=await k(a,t,`${n}.${i}`);return r}return e}async function A(e,t,n){let r;switch(e.kind){case`env`:{let{name:t}=e.options,n=process.env[t];r=typeof n==`string`&&n.trim()?n.trim():void 0;break}case`by-environment`:{if(!t.environment)throw Error(`${n} requires runtime environment.`);let{cases:i}=e.options;r=await k(i[t.environment.name],t,n);break}case`compute`:{if(!t.environment)throw Error(`${n} requires runtime environment.`);if(!t.buildMetadata)throw Error(`${n} requires build metadata.`);let{compute:i}=e.options;r=await i(t);break}case`static`:{let{value:t}=e.options;r=t;break}}for(let i of e.transforms){if(!t.environment)throw Error(`${n} source transforms require runtime environment.`);if(!t.buildMetadata)throw Error(`${n} source transforms require build metadata.`);r=await i(r,t)}return r}function j(e){if(Array.isArray(e))return e.map(e=>j(e));if(M(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=j(r);return t}return e}function M(e){return Object.prototype.toString.call(e)===`[object Object]`}C(`apikit.basic-auth`,{enabled:b.boolean().default(f.basicAuth.enabled),authenticate:b.custom().default(f.basicAuth.authenticate),proxyMode:b.boolean().default(f.basicAuth.proxyMode),header:b.string().optional().default(f.basicAuth.header),strictCredentials:b.boolean().optional().default(f.basicAuth.strictCredentials),username:b.string().optional(),password:b.string().optional()});const N=C(`apikit.build`,{outDir:b.string().default(f.build.outDir)});C(`apikit.cors`,{enabled:b.boolean().default(f.cors.enabled),allowAllOrigins:b.boolean().default(f.cors.allowAllOrigins),includeWwwSubdomain:b.boolean().default(f.cors.includeWwwSubdomain),options:b.custom().default({}).map(P)});function P(e){return{...f.cors.options,...e}}C(`apikit.email`,{enabled:b.boolean().default(f.email.enabled),templatesPath:b.string().default(f.email.templatesPath),globals:b.custom().default(f.email.globals),smtp:{host:b.string().optional(),port:b.number().optional(),secure:b.boolean().optional(),user:b.string().optional(),password:b.string().optional()}}),C(`apikit.health`,{enabled:b.boolean().default(f.health.enabled),url:b.string().default(f.health.url).map(F),pressure:{maxEventLoopDelay:b.number().default(f.health.pressure.maxEventLoopDelay),maxHeapUsedBytes:b.number().default(f.health.pressure.maxHeapUsedBytes),maxRssBytes:b.number().default(f.health.pressure.maxRssBytes),maxEventLoopUtilization:b.number().default(f.health.pressure.maxEventLoopUtilization)}});function F(e){if(!e.startsWith(`/`))throw Error(`apikit.health.url must start with slash.`);if(e===`/`)throw Error(`apikit.health.url must not be root path.`);if(e.includes(`?`)||e.includes(`#`))throw Error(`apikit.health.url must not contain query string or fragment.`);return e.length>1?e.replace(/\/+$/,``):e}C(`apikit.i18n`,{resources:b.custom().default(f.i18n.resources),directories:b.array(b.custom()).default(f.i18n.directories),files:b.array(b.custom()).default(f.i18n.files),defaultLanguage:b.string().default(f.i18n.defaultLanguage),fallbackLanguages:b.custom().default(f.i18n.fallbackLanguages),supportedLanguages:b.array(b.string()).default(f.i18n.supportedLanguages),load:b.custom().default(f.i18n.load),preload:b.custom().default(f.i18n.preload),nonExplicitSupportedLngs:b.boolean().default(f.i18n.nonExplicitSupportedLngs),lowerCaseLng:b.boolean().default(f.i18n.lowerCaseLng),cleanCode:b.boolean().default(f.i18n.cleanCode),namespaces:b.array(b.string()).optional(),defaultNamespace:b.string().default(f.i18n.defaultNamespace),keySeparator:b.string().default(f.i18n.keySeparator),nsSeparator:b.string().default(f.i18n.nsSeparator),pluralSeparator:b.string().default(f.i18n.pluralSeparator),contextSeparator:b.string().default(f.i18n.contextSeparator)}),C(`apikit.logger`,b.custom().default({enabled:f.logger.enabled}).map(I));function I(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.logger must be object.`);if(typeof e.enabled!=`boolean`)throw Error(`apikit.logger.enabled must be boolean.`);if(!e.enabled){if(`transports`in e&&e.transports!==void 0)throw Error(`apikit.logger.transports cannot be configured when logger is disabled.`);if(`request`in e&&e.request!==void 0)throw Error(`apikit.logger.request cannot be configured when logger is disabled.`);return{enabled:!1}}if(!Array.isArray(e.transports)||e.transports.length===0)throw Error(`apikit.logger.transports must be a non-empty array when logger is enabled.`);let t=L(e.request);return{enabled:!0,transports:e.transports,...t?{request:t}:{}}}function L(e){if(e!==void 0){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.logger.request must be object.`);if(e.ignoredPaths===void 0)return{};if(!Array.isArray(e.ignoredPaths))throw Error(`apikit.logger.request.ignoredPaths must be array.`);return{ignoredPaths:e.ignoredPaths.map((e,t)=>R(e,t))}}}function R(e,t){if(typeof e!=`string`)throw Error(`apikit.logger.request.ignoredPaths[${t}] must be string.`);let n=e.trim();if(!n)throw Error(`apikit.logger.request.ignoredPaths[${t}] must not be empty.`);if(!n.startsWith(`/`))throw Error(`apikit.logger.request.ignoredPaths[${t}] must start with slash.`);if(n===`/`)throw Error(`apikit.logger.request.ignoredPaths[${t}] must not be root path.`);if(n.includes(`?`)||n.includes(`#`))throw Error(`apikit.logger.request.ignoredPaths[${t}] must not contain query string or fragment.`);return n.length>1?n.replace(/\/+$/,``):n}C(`apikit.metrics`,{enabled:b.boolean().default(f.metrics.enabled),endpoint:b.custom().default(f.metrics.endpoint),name:b.string().default(f.metrics.name),defaultMetrics:b.custom().default(f.metrics.defaultMetrics),routeMetrics:b.custom().default(f.metrics.routeMetrics),clearRegisterOnInit:b.boolean().default(f.metrics.clearRegisterOnInit)}),C(`apikit.multipart`,{enabled:b.boolean().default(f.multipart.enabled),options:b.custom().default(f.multipart.options)}),C(`apikit.notification`,b.custom().default({enabled:f.notification.enabled}).map(z));function z(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.notification must be object.`);if(typeof e.enabled!=`boolean`)throw Error(`apikit.notification.enabled must be boolean.`);if(!e.enabled){if(`channels`in e&&e.channels!==void 0)throw Error(`apikit.notification.channels cannot be configured when notification is disabled.`);return{enabled:!1}}if(!e.channels||typeof e.channels!=`object`||Array.isArray(e.channels))throw Error(`apikit.notification.channels must be object when notification is enabled.`);V(e.channels);let t=B(e.channels.telegram);if(!t)throw Error(`apikit.notification.channels must contain at least one configured channel.`);return{enabled:!0,channels:{telegram:t}}}function B(e){if(e!==void 0){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.notification.channels.telegram must be object.`);return{token:H(e.token,`apikit.notification.channels.telegram.token`),chatId:H(e.chatId,`apikit.notification.channels.telegram.chatId`)}}}function V(e){for(let t of Object.keys(e))if(t!==`telegram`)throw Error(`apikit.notification.channels.${t} is not supported.`)}function H(e,t){if(typeof e!=`string`)throw Error(`${t} must be string.`);let n=e.trim();if(!n)throw Error(`${t} must not be empty.`);return n}C(`apikit.server`,{identifier:b.string(),debug:b.boolean().default(f.server.debug),host:b.string(),port:b.number(),trustProxy:b.custom().default(f.server.trustProxy)}),C(`apikit.staticFiles`,{enabled:b.boolean().default(f.staticFiles.enabled),publicDirectory:b.string().optional(),routePrefix:b.string().default(f.staticFiles.routePrefix),maxAge:b.number().default(f.staticFiles.maxAge),dotfiles:b.custom().default(f.staticFiles.dotfiles),etag:b.boolean().default(f.staticFiles.etag),immutable:b.boolean().default(f.staticFiles.immutable),decorateReply:b.boolean().default(f.staticFiles.decorateReply),preCompressed:b.boolean().default(f.staticFiles.preCompressed)});function U(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let W=class{get build(){return global.apikit.build}get isDebug(){return global.apikit.serverConfig.debug}get environment(){return global.apikit.environmentConfig}get logger(){return global.apikit.loggerConfig}get server(){return global.apikit.serverConfig}get metrics(){return global.apikit.metricsConfig}get health(){return global.apikit.healthConfig}get email(){return global.apikit.emailConfig}get notification(){return global.apikit.notificationConfig}get i18n(){return global.apikit.i18nConfig}get staticFiles(){return global.apikit.staticFilesConfig}get basicAuth(){return global.apikit.basicAuthConfig}get cors(){return global.apikit.corsConfig}get multipart(){return global.apikit.multipartConfig}get(e){if(!global.apikit.configurations.has(e.key))throw Error(`Configuration "${e.key}" is missing.`);return global.apikit.configurations.get(e.key)}optional(e){return global.apikit.configurations.get(e.key)}};W=U([u()],W),new n;async function G(e){return{build:await T(N,e.build,{})}}function K(e,t){let n=``;for(let r=0;r<e.length;r++)e[r]===t?n+=`\\`:e[r]===`\r`&&e[r+1]===`
1
+ import{defineCommand as e,runMain as t}from"citty";import{Console as n,ENVIRONMENT_CONFIG_FILE as r,createDirectory as i,createFile as a,defineConfiguration as o,field as s,loadConfig as c,loadPackageJSON as l,removePath as u,resolveConfiguration as d,resolvePath as f}from"@buildplease/core/node";import p from"node:path";import"jiti";import{injectable as m}from"inversify";import{v7 as ee}from"uuid";const h={build:{outDir:`.apikit`},logger:{enabled:!1},server:{debug:!1,trustProxy:!1},metrics:{enabled:!1,endpoint:`/metrics`,name:`metrics`,defaultMetrics:{enabled:!0},routeMetrics:{enabled:!0},clearRegisterOnInit:!1},health:{enabled:!0,url:`/health`,pressure:{maxEventLoopDelay:0,maxHeapUsedBytes:0,maxRssBytes:0,maxEventLoopUtilization:0}},notification:{enabled:!1},email:{enabled:!1,templatesPath:`./src/templates`,globals:{}},i18n:{resources:{},directories:[],files:[],defaultLanguage:`en`,fallbackLanguages:`en`,supportedLanguages:[`en`,`sk`,`cs`],load:`languageOnly`,preload:[`en`,`sk`,`cs`],nonExplicitSupportedLngs:!0,lowerCaseLng:!0,cleanCode:!0,defaultNamespace:`translation`,keySeparator:`.`,nsSeparator:`:`,pluralSeparator:`_`,contextSeparator:`_`},staticFiles:{enabled:!1,routePrefix:`/`,maxAge:3600,dotfiles:`ignore`,etag:!0,immutable:!0,decorateReply:!0,preCompressed:!1},basicAuth:{enabled:!1,authenticate:!1,proxyMode:!1,header:void 0,strictCredentials:void 0},cors:{enabled:!1,allowAllOrigins:!1,includeWwwSubdomain:!0,options:{methods:[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`OPTIONS`],credentials:!0,optionsSuccessStatus:200}},multipart:{enabled:!1,options:{limits:{fileSize:20971520}}}};o(`apikit.basic-auth`,{enabled:s.boolean().default(h.basicAuth.enabled),authenticate:s.custom().default(h.basicAuth.authenticate),proxyMode:s.boolean().default(h.basicAuth.proxyMode),header:s.string().optional().default(h.basicAuth.header),strictCredentials:s.boolean().optional().default(h.basicAuth.strictCredentials),username:s.string().optional(),password:s.string().optional()});const g=o(`apikit.build`,{outDir:s.string().default(h.build.outDir)});o(`apikit.cors`,{enabled:s.boolean().default(h.cors.enabled),allowAllOrigins:s.boolean().default(h.cors.allowAllOrigins),includeWwwSubdomain:s.boolean().default(h.cors.includeWwwSubdomain),options:s.custom().default({}).map(_)});function _(e){return{...h.cors.options,...e}}o(`apikit.email`,{enabled:s.boolean().default(h.email.enabled),templatesPath:s.string().default(h.email.templatesPath),globals:s.custom().default(h.email.globals),smtp:{host:s.string().optional(),port:s.number().optional(),secure:s.boolean().optional(),user:s.string().optional(),password:s.string().optional()}}),o(`apikit.health`,{enabled:s.boolean().default(h.health.enabled),url:s.string().default(h.health.url).map(v),pressure:{maxEventLoopDelay:s.number().default(h.health.pressure.maxEventLoopDelay),maxHeapUsedBytes:s.number().default(h.health.pressure.maxHeapUsedBytes),maxRssBytes:s.number().default(h.health.pressure.maxRssBytes),maxEventLoopUtilization:s.number().default(h.health.pressure.maxEventLoopUtilization)}});function v(e){if(!e.startsWith(`/`))throw Error(`apikit.health.url must start with slash.`);if(e===`/`)throw Error(`apikit.health.url must not be root path.`);if(e.includes(`?`)||e.includes(`#`))throw Error(`apikit.health.url must not contain query string or fragment.`);return e.length>1?e.replace(/\/+$/,``):e}o(`apikit.i18n`,{resources:s.custom().default(h.i18n.resources),directories:s.array(s.custom()).default(h.i18n.directories),files:s.array(s.custom()).default(h.i18n.files),defaultLanguage:s.string().default(h.i18n.defaultLanguage),fallbackLanguages:s.custom().default(h.i18n.fallbackLanguages),supportedLanguages:s.array(s.string()).default(h.i18n.supportedLanguages),load:s.custom().default(h.i18n.load),preload:s.custom().default(h.i18n.preload),nonExplicitSupportedLngs:s.boolean().default(h.i18n.nonExplicitSupportedLngs),lowerCaseLng:s.boolean().default(h.i18n.lowerCaseLng),cleanCode:s.boolean().default(h.i18n.cleanCode),namespaces:s.array(s.string()).optional(),defaultNamespace:s.string().default(h.i18n.defaultNamespace),keySeparator:s.string().default(h.i18n.keySeparator),nsSeparator:s.string().default(h.i18n.nsSeparator),pluralSeparator:s.string().default(h.i18n.pluralSeparator),contextSeparator:s.string().default(h.i18n.contextSeparator)}),o(`apikit.logger`,s.custom().default({enabled:h.logger.enabled}).map(y));function y(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.logger must be object.`);if(typeof e.enabled!=`boolean`)throw Error(`apikit.logger.enabled must be boolean.`);if(!e.enabled){if(`transports`in e&&e.transports!==void 0)throw Error(`apikit.logger.transports cannot be configured when logger is disabled.`);if(`request`in e&&e.request!==void 0)throw Error(`apikit.logger.request cannot be configured when logger is disabled.`);return{enabled:!1}}if(!Array.isArray(e.transports)||e.transports.length===0)throw Error(`apikit.logger.transports must be a non-empty array when logger is enabled.`);let t=b(e.request);return{enabled:!0,transports:e.transports,...t?{request:t}:{}}}function b(e){if(e!==void 0){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.logger.request must be object.`);if(e.ignoredPaths===void 0)return{};if(!Array.isArray(e.ignoredPaths))throw Error(`apikit.logger.request.ignoredPaths must be array.`);return{ignoredPaths:e.ignoredPaths.map((e,t)=>x(e,t))}}}function x(e,t){if(typeof e!=`string`)throw Error(`apikit.logger.request.ignoredPaths[${t}] must be string.`);let n=e.trim();if(!n)throw Error(`apikit.logger.request.ignoredPaths[${t}] must not be empty.`);if(!n.startsWith(`/`))throw Error(`apikit.logger.request.ignoredPaths[${t}] must start with slash.`);if(n===`/`)throw Error(`apikit.logger.request.ignoredPaths[${t}] must not be root path.`);if(n.includes(`?`)||n.includes(`#`))throw Error(`apikit.logger.request.ignoredPaths[${t}] must not contain query string or fragment.`);return n.length>1?n.replace(/\/+$/,``):n}o(`apikit.metrics`,{enabled:s.boolean().default(h.metrics.enabled),endpoint:s.custom().default(h.metrics.endpoint),name:s.string().default(h.metrics.name),defaultMetrics:s.custom().default(h.metrics.defaultMetrics),routeMetrics:s.custom().default(h.metrics.routeMetrics),clearRegisterOnInit:s.boolean().default(h.metrics.clearRegisterOnInit)}),o(`apikit.multipart`,{enabled:s.boolean().default(h.multipart.enabled),options:s.custom().default(h.multipart.options)}),o(`apikit.notification`,s.custom().default({enabled:h.notification.enabled}).map(S));function S(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.notification must be object.`);if(typeof e.enabled!=`boolean`)throw Error(`apikit.notification.enabled must be boolean.`);if(!e.enabled){if(`channels`in e&&e.channels!==void 0)throw Error(`apikit.notification.channels cannot be configured when notification is disabled.`);return{enabled:!1}}if(!e.channels||typeof e.channels!=`object`||Array.isArray(e.channels))throw Error(`apikit.notification.channels must be object when notification is enabled.`);w(e.channels);let t=C(e.channels.telegram);if(!t)throw Error(`apikit.notification.channels must contain at least one configured channel.`);return{enabled:!0,channels:{telegram:t}}}function C(e){if(e!==void 0){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.notification.channels.telegram must be object.`);return{token:T(e.token,`apikit.notification.channels.telegram.token`),chatId:T(e.chatId,`apikit.notification.channels.telegram.chatId`)}}}function w(e){for(let t of Object.keys(e))if(t!==`telegram`)throw Error(`apikit.notification.channels.${t} is not supported.`)}function T(e,t){if(typeof e!=`string`)throw Error(`${t} must be string.`);let n=e.trim();if(!n)throw Error(`${t} must not be empty.`);return n}o(`apikit.server`,{identifier:s.string(),debug:s.boolean().default(h.server.debug),host:s.string(),port:s.number(),trustProxy:s.custom().default(h.server.trustProxy)}),o(`apikit.staticFiles`,{enabled:s.boolean().default(h.staticFiles.enabled),publicDirectory:s.string().optional(),routePrefix:s.string().default(h.staticFiles.routePrefix),maxAge:s.number().default(h.staticFiles.maxAge),dotfiles:s.custom().default(h.staticFiles.dotfiles),etag:s.boolean().default(h.staticFiles.etag),immutable:s.boolean().default(h.staticFiles.immutable),decorateReply:s.boolean().default(h.staticFiles.decorateReply),preCompressed:s.boolean().default(h.staticFiles.preCompressed)});function E(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let D=class{get build(){return global.apikit.build}get isDebug(){return global.apikit.serverConfig.debug}get environment(){return global.apikit.environmentConfig}get logger(){return global.apikit.loggerConfig}get server(){return global.apikit.serverConfig}get metrics(){return global.apikit.metricsConfig}get health(){return global.apikit.healthConfig}get email(){return global.apikit.emailConfig}get notification(){return global.apikit.notificationConfig}get i18n(){return global.apikit.i18nConfig}get staticFiles(){return global.apikit.staticFilesConfig}get basicAuth(){return global.apikit.basicAuthConfig}get cors(){return global.apikit.corsConfig}get multipart(){return global.apikit.multipartConfig}get(e){if(!global.apikit.configurations.has(e.key))throw Error(`Configuration "${e.key}" is missing.`);return global.apikit.configurations.get(e.key)}optional(e){return global.apikit.configurations.get(e.key)}};D=E([m()],D),new n;async function O(e){return{build:await d(g,e.input.build,{})}}function k(e,t){let n=``;for(let r=0;r<e.length;r++)e[r]===t?n+=`\\`:e[r]===`\r`&&e[r+1]===`
2
2
  `?(n+=`\\r\\n\\`,r++):e[r]===`
3
- `?n+=`\\n\\`:e[r]===`\\`&&(n+=`\\`),n+=e[r];return n}function q(e){return e instanceof Function?e():e}var J;(function(e){e[e.Line=0]=`Line`,e[e.Star=1]=`Star`})(J||={});const Y={BACK_SLASH:92,FORWARD_SLASH:47,NEW_LINE:10,CARRIAGE_RETURN:13,ASTERISK:42,DOUBLE_QUOTE:34,SINGLE_QUOTE:39,BACK_TICK:96,OPEN_BRACE:123,CLOSE_BRACE:125,DOLLAR_SIGN:36,SPACE:32,TAB:9},ce=new Set([Y.BACK_SLASH,Y.FORWARD_SLASH,Y.NEW_LINE,Y.CARRIAGE_RETURN,Y.ASTERISK,Y.DOUBLE_QUOTE,Y.SINGLE_QUOTE,Y.BACK_TICK,Y.OPEN_BRACE,Y.CLOSE_BRACE]);var X=class e{constructor(e={}){Object.defineProperty(this,"_indentationText",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_newLine",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_useTabs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_quoteChar",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_indentNumberOfSpaces",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_currentIndentation",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_queuedIndentation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_queuedOnlyIfNotBlock",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_length",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_newLineOnNextWrite",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_currentCommentChar",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_stringCharStack",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_isInRegEx",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_isOnFirstLineOfBlock",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_texts",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this._newLine=e.newLine||`
4
- `,this._useTabs=e.useTabs||!1,this._indentNumberOfSpaces=e.indentNumberOfSpaces||4,this._indentationText=ue(this._useTabs,this._indentNumberOfSpaces),this._quoteChar=e.useSingleQuote?`'`:`"`}getOptions(){return{indentNumberOfSpaces:this._indentNumberOfSpaces,newLine:this._newLine,useTabs:this._useTabs,useSingleQuote:this._quoteChar===`'`}}queueIndentationLevel(e){return this._queuedIndentation=this._getIndentationLevelFromArg(e),this._queuedOnlyIfNotBlock=void 0,this}hangingIndent(e){return this._withResetIndentation(()=>this.queueIndentationLevel(this.getIndentationLevel()+1),e)}hangingIndentUnlessBlock(e){return this._withResetIndentation(()=>{this.queueIndentationLevel(this.getIndentationLevel()+1),this._queuedOnlyIfNotBlock=!0},e)}setIndentationLevel(e){return this._currentIndentation=this._getIndentationLevelFromArg(e),this}withIndentationLevel(e,t){return this._withResetIndentation(()=>this.setIndentationLevel(e),t)}_withResetIndentation(e,t){let n=this._getIndentationState();e();try{t()}finally{this._setIndentationState(n)}return this}getIndentationLevel(){return this._currentIndentation}block(e){return this._newLineIfNewLineOnNextWrite(),this.getLength()>0&&!this.isLastNewLine()&&this.spaceIfLastNot(),this.inlineBlock(e),this._newLineOnNextWrite=!0,this}inlineBlock(e){return this._newLineIfNewLineOnNextWrite(),this.write(`{`),this._indentBlockInternal(e),this.newLineIfLastNot().write(`}`),this}indent(e=1){return typeof e==`number`?(this._newLineIfNewLineOnNextWrite(),this.write(this._indentationText.repeat(e))):(this._indentBlockInternal(e),this.isLastNewLine()||(this._newLineOnNextWrite=!0),this)}_indentBlockInternal(e){this.getLastChar()!=null&&this.newLineIfLastNot(),this._currentIndentation++,this._isOnFirstLineOfBlock=!0,e?.(),this._isOnFirstLineOfBlock=!1,this._currentIndentation=Math.max(0,this._currentIndentation-1)}conditionalWriteLine(e,t){return e&&this.writeLine(q(t)),this}writeLine(e){return this._newLineIfNewLineOnNextWrite(),this.getLastChar()!=null&&this.newLineIfLastNot(),this._writeIndentingNewLines(e),this.newLine(),this}newLineIfLastNot(){return this._newLineIfNewLineOnNextWrite(),this.isLastNewLine()||this.newLine(),this}blankLineIfLastNot(){return this.isLastBlankLine()||this.blankLine(),this}conditionalBlankLine(e){return e&&this.blankLine(),this}blankLine(){return this.newLineIfLastNot().newLine()}conditionalNewLine(e){return e&&this.newLine(),this}newLine(){return this._newLineOnNextWrite=!1,this._baseWriteNewline(),this}quote(e){return this._newLineIfNewLineOnNextWrite(),this._writeIndentingNewLines(e==null?this._quoteChar:this._quoteChar+K(e,this._quoteChar)+this._quoteChar),this}spaceIfLastNot(){return this._newLineIfNewLineOnNextWrite(),this.isLastSpace()||this._writeIndentingNewLines(` `),this}space(e=1){return this._newLineIfNewLineOnNextWrite(),this._writeIndentingNewLines(` `.repeat(e)),this}tabIfLastNot(){return this._newLineIfNewLineOnNextWrite(),this.isLastTab()||this._writeIndentingNewLines(` `),this}tab(e=1){return this._newLineIfNewLineOnNextWrite(),this._writeIndentingNewLines(` `.repeat(e)),this}conditionalWrite(e,t){return e&&this.write(q(t)),this}write(e){return this._newLineIfNewLineOnNextWrite(),this._writeIndentingNewLines(e),this}closeComment(){switch(this._currentCommentChar){case J.Line:this.newLine();break;case J.Star:this.isLastNewLine()||this.spaceIfLastNot(),this.write(`*/`)}return this}unsafeInsert(e,t){let n=this._length,r=this._texts;if(i(),e===n)return this.write(t);return a(),this._length+=t.length,this;function i(){if(e<0)throw Error(`Provided position of '${e}' was less than zero.`);if(e>n)throw Error(`Provided position of '${e}' was greater than the text length of '${n}'.`)}function a(){let{index:e,localIndex:n}=o();if(n===0)r.splice(e,0,t);else if(n===r[e].length)r.splice(e+1,0,t);else{let i=r[e],a=i.substring(0,n),o=i.substring(n);r.splice(e,1,a,t,o)}}function o(){if(e<n/2){let t=0;for(let n=0;n<r.length;n++){let i=r[n],a=t;if(t+=i.length,t>=e)return{index:n,localIndex:e-a}}}else{let t=n;for(let n=r.length-1;n>=0;n--){let i=r[n];if(t-=i.length,t<=e)return{index:n,localIndex:e-t}}}throw Error(`Unhandled situation inserting. This should never happen.`)}}getLength(){return this._length}isInComment(){return this._currentCommentChar!==void 0}isAtStartOfFirstLineOfBlock(){return this.isOnFirstLineOfBlock()&&(this.isLastNewLine()||this.getLastChar()==null)}isOnFirstLineOfBlock(){return this._isOnFirstLineOfBlock}isInString(){return this._stringCharStack.length>0&&this._stringCharStack[this._stringCharStack.length-1]!==Y.OPEN_BRACE}isLastNewLine(){let e=this.getLastChar();return e===`
5
- `||e===`\r`}isLastBlankLine(){let e=0;for(let t=this._texts.length-1;t>=0;t--){let n=this._texts[t];for(let t=n.length-1;t>=0;t--){let r=n.charCodeAt(t);if(r===Y.NEW_LINE){if(e++,e===2)return!0}else if(r!==Y.CARRIAGE_RETURN)return!1}}return!1}isLastSpace(){return this.getLastChar()===` `}isLastTab(){return this.getLastChar()===` `}getLastChar(){let e=this._getLastCharCodeWithOffset(0);return e==null?void 0:String.fromCharCode(e)}endsWith(e){let t=this._length;return this.iterateLastCharCodes((n,r)=>{let i=t-r,a=e.length-i;return e.charCodeAt(a)===n?a===0||void 0:!1})||!1}iterateLastChars(e){return this.iterateLastCharCodes((t,n)=>e(String.fromCharCode(t),n))}iterateLastCharCodes(e){let t=this._length;for(let n=this._texts.length-1;n>=0;n--){let r=this._texts[n];for(let n=r.length-1;n>=0;n--){t--;let i=e(r.charCodeAt(n),t);if(i!=null)return i}}}toString(){if(this._texts.length>1){let e=this._texts.join(``);this._texts.length=0,this._texts.push(e)}return this._texts[0]||``}_writeIndentingNewLines(t){if(t||=``,t.length===0){n(this,``);return}t.split(e._newLineRegEx).forEach((e,t)=>{t>0&&this._baseWriteNewline(),e.length!==0&&n(this,e)});function n(e,t){e.isInString()||(e.isLastNewLine()||e.getLastChar()==null)&&e._writeIndentation(),e._updateInternalState(t),e._internalWrite(t)}}_baseWriteNewline(){this._currentCommentChar===J.Line&&(this._currentCommentChar=void 0);let e=this._stringCharStack[this._stringCharStack.length-1];(e===Y.DOUBLE_QUOTE||e===Y.SINGLE_QUOTE)&&this._getLastCharCodeWithOffset(0)!==Y.BACK_SLASH&&this._stringCharStack.pop(),this._internalWrite(this._newLine),this._isOnFirstLineOfBlock=!1,this._dequeueQueuedIndentation()}_dequeueQueuedIndentation(){if(this._queuedIndentation==null)return;this._queuedOnlyIfNotBlock&&e(this)?(this._queuedIndentation=void 0,this._queuedOnlyIfNotBlock=void 0):(this._currentIndentation=this._queuedIndentation,this._queuedIndentation=void 0);function e(e){let t=!1;return e.iterateLastCharCodes(e=>{switch(e){case Y.NEW_LINE:if(t)return!1;t=!0;break;case Y.CARRIAGE_RETURN:return;case Y.OPEN_BRACE:return!0;default:return!1}})}}_updateInternalState(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(!ce.has(n))continue;let r=t===0?this._getLastCharCodeWithOffset(0):e.charCodeAt(t-1),i=t===0?this._getLastCharCodeWithOffset(1):t===1?this._getLastCharCodeWithOffset(0):e.charCodeAt(t-2);if(this._isInRegEx){if(r===Y.FORWARD_SLASH&&i!==Y.BACK_SLASH||r===Y.NEW_LINE)this._isInRegEx=!1;else continue}else if(!this.isInString()&&!this.isInComment()&&le(n,r,i)){this._isInRegEx=!0;continue}if(this.isInString()||(this._currentCommentChar==null&&r===Y.FORWARD_SLASH&&n===Y.FORWARD_SLASH?this._currentCommentChar=J.Line:this._currentCommentChar==null&&r===Y.FORWARD_SLASH&&n===Y.ASTERISK?this._currentCommentChar=J.Star:this._currentCommentChar===J.Star&&r===Y.ASTERISK&&n===Y.FORWARD_SLASH&&(this._currentCommentChar=void 0)),this.isInComment())continue;let a=this._stringCharStack.length===0?void 0:this._stringCharStack[this._stringCharStack.length-1];r!==Y.BACK_SLASH&&(n===Y.DOUBLE_QUOTE||n===Y.SINGLE_QUOTE||n===Y.BACK_TICK)?a===n?this._stringCharStack.pop():(a===Y.OPEN_BRACE||a===void 0)&&this._stringCharStack.push(n):i!==Y.BACK_SLASH&&r===Y.DOLLAR_SIGN&&n===Y.OPEN_BRACE&&a===Y.BACK_TICK?this._stringCharStack.push(n):n===Y.CLOSE_BRACE&&a===Y.OPEN_BRACE&&this._stringCharStack.pop()}}_getLastCharCodeWithOffset(e){if(!(e>=this._length||e<0))for(let t=this._texts.length-1;t>=0;t--){let n=this._texts[t];if(e>=n.length)e-=n.length;else return n.charCodeAt(n.length-1-e)}}_writeIndentation(){let e=Math.floor(this._currentIndentation);this._internalWrite(this._indentationText.repeat(e));let t=this._currentIndentation-e;if(this._useTabs)t>.5&&this._internalWrite(this._indentationText);else{let e=Math.round(this._indentationText.length*t),n=``;for(let t=0;t<e;t++)n+=this._indentationText[t];this._internalWrite(n)}}_newLineIfNewLineOnNextWrite(){this._newLineOnNextWrite&&(this._newLineOnNextWrite=!1,this.newLine())}_internalWrite(e){e.length!==0&&(this._texts.push(e),this._length+=e.length)}_getIndentationLevelFromArg(t){if(typeof t==`number`){if(t<0)throw Error(`Passed in indentation level should be greater than or equal to 0.`);return t}if(typeof t==`string`){if(!e._spacesOrTabsRegEx.test(t))throw Error(`Provided string must be empty or only contain spaces or tabs.`);let{spacesCount:n,tabsCount:r}=de(t);return r+n/this._indentNumberOfSpaces}throw Error(`Argument provided must be a string or number.`)}_setIndentationState(e){this._currentIndentation=e.current,this._queuedIndentation=e.queued,this._queuedOnlyIfNotBlock=e.queuedOnlyIfNotBlock}_getIndentationState(){return{current:this._currentIndentation,queued:this._queuedIndentation,queuedOnlyIfNotBlock:this._queuedOnlyIfNotBlock}}};Object.defineProperty(X,"_newLineRegEx",{enumerable:!0,configurable:!0,writable:!0,value:/\r?\n/}),Object.defineProperty(X,"_spacesOrTabsRegEx",{enumerable:!0,configurable:!0,writable:!0,value:/^[ \t]*$/});function le(e,t,n){return t===Y.FORWARD_SLASH&&e!==Y.FORWARD_SLASH&&e!==Y.ASTERISK&&n!==Y.ASTERISK&&n!==Y.FORWARD_SLASH}function ue(e,t){return e?` `:Array(t+1).join(` `)}function de(e){let t=0,n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i===Y.SPACE?t++:i===Y.TAB&&n++}return{spacesCount:t,tabsCount:n}}var fe=class extends X{constructor(){super({newLine:`
6
- `,indentNumberOfSpaces:2,useTabs:!1,useSingleQuote:!0})}};function pe(e){let t=c(process.cwd(),e.build.outDir);if(t===process.cwd())throw Error(`Cannot use root directory as output path.`);return{outputPath:t,writer:fe}}function me(e){s(e.outputPath,{recursive:!0,force:!0}),r(e.outputPath)}async function he(e,t){let n=new e.writer;for(let e of t)n.write(`export * from `).quote(`./${e}.js`).write(`;`).newLine();i(l.join(e.outputPath,`index.ts`),n.toString())}async function ge(e){let t=_e(o(l.resolve(process.cwd(),`package.json`))),n=new e.writer;n.writeLine(`import type { BuildMetadata as BuildMetadataContract } from '@buildplease/apikit';`),n.blankLine(),n.writeLine(`export const BuildMetadata = {`),n.indent(()=>{n.writeLine(`name: {`),n.indent(()=>{n.write(`original: `).quote(t.name.original).write(`,`).newLine(),n.write(`base: `).quote(t.name.base).write(`,`).newLine()}),n.writeLine(`},`),n.write(`version: `).quote(t.version).write(`,`).newLine(),n.write(`id: `).quote(t.id).write(`,`).newLine(),n.write(`createdAt: `).quote(t.createdAt).write(`,`).newLine()}),n.writeLine(`} as const satisfies BuildMetadataContract;`);let r=`build-metadata`;return i(l.join(e.outputPath,`${r}.ts`),n.toString()),[r]}function _e(e){return{name:{original:e.name.original,base:e.name.base},version:e.version,id:d(),createdAt:new Date().toISOString()}}async function ve(e,t){let n=Object.entries(e),r=new t.writer;r.writeLine(`export enum Environment {`),r.indent(()=>{for(let[e]of n)r.write(`${e} = `).quote(e).write(`,`).newLine()}),r.writeLine(`}`),r.blankLine(),r.writeLine(`export const Environments = {`),r.indent(()=>{for(let[e,t]of n)r.writeLine(`${e}: {`),r.indent(()=>{r.writeLine(`name: Environment.${e},`),r.write(`file: `).quote(t.file).write(`,`).newLine(),r.write(`fileDir: `).quote(t.fileDir??``).write(`,`).newLine()}),r.writeLine(`},`)}),r.writeLine(`} as const;`),r.blankLine(),r.writeLine(`export type EnvironmentType = keyof typeof Environments;`);let a=`environment`;return i(l.join(t.outputPath,`${a}.ts`),r.toString()),[a]}async function ye(e){let t=pe(e.generatorConfig);me(t),await he(t,[...await ge(t),...await ve(e.config.environments,t)])}const Z=new n,be={dir:{type:`string`,description:`Directory to look for the config file`,name:`dir`,alias:`d`,required:!1},config:{type:`string`,name:`config`,alias:`c`,description:`Config file name or path relative to the selected project directory.`,required:!1}};function xe(e){let t=l.relative(process.cwd(),e);return!t||t.startsWith(`..`)?e:t}async function Q(e,t){let n=process.cwd();try{return process.chdir(e),await t()}finally{process.chdir(n)}}function Se(e,t){Z.error(e),Z.error(t instanceof Error?t.message:String(t)),process.exit(1)}const $=new n;function Ce(t){return e({meta:{name:`build:app`,description:[`Generate ApiKit app output`,``,`Usage:`,` apikit build:app [--dir <directory>] [--config <config-name>]`,``,`Config lookup:`,` ${g}.*`,``,`Examples:`,` apikit build:app`,` apikit build:app --dir ./apps/main-api`,` apikit build:app -c custom.config`].join(`
7
- `)},args:be,run:async({args:e})=>we(e,t)})}async function we(e,t){try{let n=await _({dir:e.dir,config:e.config}),r=await G(n.config);$.title(`ApiKit`,`app`,[{label:`config`,value:xe(n.configFilePath)},{label:`output`,value:r.build.outDir}]);let i=Object.entries(n.config.environments);$.panel(`environments`,i.map(([e,t])=>({label:e,value:t.fileDir?`${t.fileDir}/${t.file}`:t.file})),i.length),await Q(n.rootDir,()=>ye({config:n.config,generatorConfig:r})),$.success($.step(`app`,`Generated ${r.build.outDir}`)),$.success($.step(`done`,`Completed in ${$.duration(Date.now()-t.startTime)}`)),$.emptyLine()}catch(e){Se(`ApiKit app build failed`,e)}}function Te(t){return e({meta:{name:t.package.name,version:t.package.version},subCommands:{"build:app":Ce(t)}})}function Ee(e){return t(Te(e))}export{Ee as runMain};
3
+ `?n+=`\\n\\`:e[r]===`\\`&&(n+=`\\`),n+=e[r];return n}function A(e){return e instanceof Function?e():e}var j;(function(e){e[e.Line=0]=`Line`,e[e.Star=1]=`Star`})(j||={});const M={BACK_SLASH:92,FORWARD_SLASH:47,NEW_LINE:10,CARRIAGE_RETURN:13,ASTERISK:42,DOUBLE_QUOTE:34,SINGLE_QUOTE:39,BACK_TICK:96,OPEN_BRACE:123,CLOSE_BRACE:125,DOLLAR_SIGN:36,SPACE:32,TAB:9},N=new Set([M.BACK_SLASH,M.FORWARD_SLASH,M.NEW_LINE,M.CARRIAGE_RETURN,M.ASTERISK,M.DOUBLE_QUOTE,M.SINGLE_QUOTE,M.BACK_TICK,M.OPEN_BRACE,M.CLOSE_BRACE]);var P=class e{constructor(e={}){Object.defineProperty(this,"_indentationText",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_newLine",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_useTabs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_quoteChar",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_indentNumberOfSpaces",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_currentIndentation",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_queuedIndentation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_queuedOnlyIfNotBlock",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_length",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_newLineOnNextWrite",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_currentCommentChar",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_stringCharStack",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"_isInRegEx",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_isOnFirstLineOfBlock",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"_texts",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this._newLine=e.newLine||`
4
+ `,this._useTabs=e.useTabs||!1,this._indentNumberOfSpaces=e.indentNumberOfSpaces||4,this._indentationText=I(this._useTabs,this._indentNumberOfSpaces),this._quoteChar=e.useSingleQuote?`'`:`"`}getOptions(){return{indentNumberOfSpaces:this._indentNumberOfSpaces,newLine:this._newLine,useTabs:this._useTabs,useSingleQuote:this._quoteChar===`'`}}queueIndentationLevel(e){return this._queuedIndentation=this._getIndentationLevelFromArg(e),this._queuedOnlyIfNotBlock=void 0,this}hangingIndent(e){return this._withResetIndentation(()=>this.queueIndentationLevel(this.getIndentationLevel()+1),e)}hangingIndentUnlessBlock(e){return this._withResetIndentation(()=>{this.queueIndentationLevel(this.getIndentationLevel()+1),this._queuedOnlyIfNotBlock=!0},e)}setIndentationLevel(e){return this._currentIndentation=this._getIndentationLevelFromArg(e),this}withIndentationLevel(e,t){return this._withResetIndentation(()=>this.setIndentationLevel(e),t)}_withResetIndentation(e,t){let n=this._getIndentationState();e();try{t()}finally{this._setIndentationState(n)}return this}getIndentationLevel(){return this._currentIndentation}block(e){return this._newLineIfNewLineOnNextWrite(),this.getLength()>0&&!this.isLastNewLine()&&this.spaceIfLastNot(),this.inlineBlock(e),this._newLineOnNextWrite=!0,this}inlineBlock(e){return this._newLineIfNewLineOnNextWrite(),this.write(`{`),this._indentBlockInternal(e),this.newLineIfLastNot().write(`}`),this}indent(e=1){return typeof e==`number`?(this._newLineIfNewLineOnNextWrite(),this.write(this._indentationText.repeat(e))):(this._indentBlockInternal(e),this.isLastNewLine()||(this._newLineOnNextWrite=!0),this)}_indentBlockInternal(e){this.getLastChar()!=null&&this.newLineIfLastNot(),this._currentIndentation++,this._isOnFirstLineOfBlock=!0,e?.(),this._isOnFirstLineOfBlock=!1,this._currentIndentation=Math.max(0,this._currentIndentation-1)}conditionalWriteLine(e,t){return e&&this.writeLine(A(t)),this}writeLine(e){return this._newLineIfNewLineOnNextWrite(),this.getLastChar()!=null&&this.newLineIfLastNot(),this._writeIndentingNewLines(e),this.newLine(),this}newLineIfLastNot(){return this._newLineIfNewLineOnNextWrite(),this.isLastNewLine()||this.newLine(),this}blankLineIfLastNot(){return this.isLastBlankLine()||this.blankLine(),this}conditionalBlankLine(e){return e&&this.blankLine(),this}blankLine(){return this.newLineIfLastNot().newLine()}conditionalNewLine(e){return e&&this.newLine(),this}newLine(){return this._newLineOnNextWrite=!1,this._baseWriteNewline(),this}quote(e){return this._newLineIfNewLineOnNextWrite(),this._writeIndentingNewLines(e==null?this._quoteChar:this._quoteChar+k(e,this._quoteChar)+this._quoteChar),this}spaceIfLastNot(){return this._newLineIfNewLineOnNextWrite(),this.isLastSpace()||this._writeIndentingNewLines(` `),this}space(e=1){return this._newLineIfNewLineOnNextWrite(),this._writeIndentingNewLines(` `.repeat(e)),this}tabIfLastNot(){return this._newLineIfNewLineOnNextWrite(),this.isLastTab()||this._writeIndentingNewLines(` `),this}tab(e=1){return this._newLineIfNewLineOnNextWrite(),this._writeIndentingNewLines(` `.repeat(e)),this}conditionalWrite(e,t){return e&&this.write(A(t)),this}write(e){return this._newLineIfNewLineOnNextWrite(),this._writeIndentingNewLines(e),this}closeComment(){switch(this._currentCommentChar){case j.Line:this.newLine();break;case j.Star:this.isLastNewLine()||this.spaceIfLastNot(),this.write(`*/`)}return this}unsafeInsert(e,t){let n=this._length,r=this._texts;if(i(),e===n)return this.write(t);return a(),this._length+=t.length,this;function i(){if(e<0)throw Error(`Provided position of '${e}' was less than zero.`);if(e>n)throw Error(`Provided position of '${e}' was greater than the text length of '${n}'.`)}function a(){let{index:e,localIndex:n}=o();if(n===0)r.splice(e,0,t);else if(n===r[e].length)r.splice(e+1,0,t);else{let i=r[e],a=i.substring(0,n),o=i.substring(n);r.splice(e,1,a,t,o)}}function o(){if(e<n/2){let t=0;for(let n=0;n<r.length;n++){let i=r[n],a=t;if(t+=i.length,t>=e)return{index:n,localIndex:e-a}}}else{let t=n;for(let n=r.length-1;n>=0;n--){let i=r[n];if(t-=i.length,t<=e)return{index:n,localIndex:e-t}}}throw Error(`Unhandled situation inserting. This should never happen.`)}}getLength(){return this._length}isInComment(){return this._currentCommentChar!==void 0}isAtStartOfFirstLineOfBlock(){return this.isOnFirstLineOfBlock()&&(this.isLastNewLine()||this.getLastChar()==null)}isOnFirstLineOfBlock(){return this._isOnFirstLineOfBlock}isInString(){return this._stringCharStack.length>0&&this._stringCharStack[this._stringCharStack.length-1]!==M.OPEN_BRACE}isLastNewLine(){let e=this.getLastChar();return e===`
5
+ `||e===`\r`}isLastBlankLine(){let e=0;for(let t=this._texts.length-1;t>=0;t--){let n=this._texts[t];for(let t=n.length-1;t>=0;t--){let r=n.charCodeAt(t);if(r===M.NEW_LINE){if(e++,e===2)return!0}else if(r!==M.CARRIAGE_RETURN)return!1}}return!1}isLastSpace(){return this.getLastChar()===` `}isLastTab(){return this.getLastChar()===` `}getLastChar(){let e=this._getLastCharCodeWithOffset(0);return e==null?void 0:String.fromCharCode(e)}endsWith(e){let t=this._length;return this.iterateLastCharCodes((n,r)=>{let i=t-r,a=e.length-i;return e.charCodeAt(a)===n?a===0||void 0:!1})||!1}iterateLastChars(e){return this.iterateLastCharCodes((t,n)=>e(String.fromCharCode(t),n))}iterateLastCharCodes(e){let t=this._length;for(let n=this._texts.length-1;n>=0;n--){let r=this._texts[n];for(let n=r.length-1;n>=0;n--){t--;let i=e(r.charCodeAt(n),t);if(i!=null)return i}}}toString(){if(this._texts.length>1){let e=this._texts.join(``);this._texts.length=0,this._texts.push(e)}return this._texts[0]||``}_writeIndentingNewLines(t){if(t||=``,t.length===0){n(this,``);return}t.split(e._newLineRegEx).forEach((e,t)=>{t>0&&this._baseWriteNewline(),e.length!==0&&n(this,e)});function n(e,t){e.isInString()||(e.isLastNewLine()||e.getLastChar()==null)&&e._writeIndentation(),e._updateInternalState(t),e._internalWrite(t)}}_baseWriteNewline(){this._currentCommentChar===j.Line&&(this._currentCommentChar=void 0);let e=this._stringCharStack[this._stringCharStack.length-1];(e===M.DOUBLE_QUOTE||e===M.SINGLE_QUOTE)&&this._getLastCharCodeWithOffset(0)!==M.BACK_SLASH&&this._stringCharStack.pop(),this._internalWrite(this._newLine),this._isOnFirstLineOfBlock=!1,this._dequeueQueuedIndentation()}_dequeueQueuedIndentation(){if(this._queuedIndentation==null)return;this._queuedOnlyIfNotBlock&&e(this)?(this._queuedIndentation=void 0,this._queuedOnlyIfNotBlock=void 0):(this._currentIndentation=this._queuedIndentation,this._queuedIndentation=void 0);function e(e){let t=!1;return e.iterateLastCharCodes(e=>{switch(e){case M.NEW_LINE:if(t)return!1;t=!0;break;case M.CARRIAGE_RETURN:return;case M.OPEN_BRACE:return!0;default:return!1}})}}_updateInternalState(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(!N.has(n))continue;let r=t===0?this._getLastCharCodeWithOffset(0):e.charCodeAt(t-1),i=t===0?this._getLastCharCodeWithOffset(1):t===1?this._getLastCharCodeWithOffset(0):e.charCodeAt(t-2);if(this._isInRegEx){if(r===M.FORWARD_SLASH&&i!==M.BACK_SLASH||r===M.NEW_LINE)this._isInRegEx=!1;else continue}else if(!this.isInString()&&!this.isInComment()&&F(n,r,i)){this._isInRegEx=!0;continue}if(this.isInString()||(this._currentCommentChar==null&&r===M.FORWARD_SLASH&&n===M.FORWARD_SLASH?this._currentCommentChar=j.Line:this._currentCommentChar==null&&r===M.FORWARD_SLASH&&n===M.ASTERISK?this._currentCommentChar=j.Star:this._currentCommentChar===j.Star&&r===M.ASTERISK&&n===M.FORWARD_SLASH&&(this._currentCommentChar=void 0)),this.isInComment())continue;let a=this._stringCharStack.length===0?void 0:this._stringCharStack[this._stringCharStack.length-1];r!==M.BACK_SLASH&&(n===M.DOUBLE_QUOTE||n===M.SINGLE_QUOTE||n===M.BACK_TICK)?a===n?this._stringCharStack.pop():(a===M.OPEN_BRACE||a===void 0)&&this._stringCharStack.push(n):i!==M.BACK_SLASH&&r===M.DOLLAR_SIGN&&n===M.OPEN_BRACE&&a===M.BACK_TICK?this._stringCharStack.push(n):n===M.CLOSE_BRACE&&a===M.OPEN_BRACE&&this._stringCharStack.pop()}}_getLastCharCodeWithOffset(e){if(!(e>=this._length||e<0))for(let t=this._texts.length-1;t>=0;t--){let n=this._texts[t];if(e>=n.length)e-=n.length;else return n.charCodeAt(n.length-1-e)}}_writeIndentation(){let e=Math.floor(this._currentIndentation);this._internalWrite(this._indentationText.repeat(e));let t=this._currentIndentation-e;if(this._useTabs)t>.5&&this._internalWrite(this._indentationText);else{let e=Math.round(this._indentationText.length*t),n=``;for(let t=0;t<e;t++)n+=this._indentationText[t];this._internalWrite(n)}}_newLineIfNewLineOnNextWrite(){this._newLineOnNextWrite&&(this._newLineOnNextWrite=!1,this.newLine())}_internalWrite(e){e.length!==0&&(this._texts.push(e),this._length+=e.length)}_getIndentationLevelFromArg(t){if(typeof t==`number`){if(t<0)throw Error(`Passed in indentation level should be greater than or equal to 0.`);return t}if(typeof t==`string`){if(!e._spacesOrTabsRegEx.test(t))throw Error(`Provided string must be empty or only contain spaces or tabs.`);let{spacesCount:n,tabsCount:r}=L(t);return r+n/this._indentNumberOfSpaces}throw Error(`Argument provided must be a string or number.`)}_setIndentationState(e){this._currentIndentation=e.current,this._queuedIndentation=e.queued,this._queuedOnlyIfNotBlock=e.queuedOnlyIfNotBlock}_getIndentationState(){return{current:this._currentIndentation,queued:this._queuedIndentation,queuedOnlyIfNotBlock:this._queuedOnlyIfNotBlock}}};Object.defineProperty(P,"_newLineRegEx",{enumerable:!0,configurable:!0,writable:!0,value:/\r?\n/}),Object.defineProperty(P,"_spacesOrTabsRegEx",{enumerable:!0,configurable:!0,writable:!0,value:/^[ \t]*$/});function F(e,t,n){return t===M.FORWARD_SLASH&&e!==M.FORWARD_SLASH&&e!==M.ASTERISK&&n!==M.ASTERISK&&n!==M.FORWARD_SLASH}function I(e,t){return e?` `:Array(t+1).join(` `)}function L(e){let t=0,n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i===M.SPACE?t++:i===M.TAB&&n++}return{spacesCount:t,tabsCount:n}}var R=class extends P{constructor(){super({newLine:`
6
+ `,indentNumberOfSpaces:2,useTabs:!1,useSingleQuote:!0})}};function z(e){let t=f(process.cwd(),e.build.outDir);if(t===process.cwd())throw Error(`Cannot use root directory as output path.`);return{outputPath:t,writer:R}}function B(e){u(e.outputPath,{recursive:!0,force:!0}),i(e.outputPath)}async function V(e,t){let n=new e.writer;for(let e of t)n.write(`export * from `).quote(`./${e}.js`).write(`;`).newLine();a(p.join(e.outputPath,`index.ts`),n.toString())}async function H(e){let t=U(l(p.resolve(process.cwd(),`package.json`))),n=new e.writer;n.writeLine(`import type { BuildMetadata as BuildMetadataContract } from '@buildplease/apikit';`),n.blankLine(),n.writeLine(`export const BuildMetadata = {`),n.indent(()=>{n.writeLine(`name: {`),n.indent(()=>{n.write(`original: `).quote(t.name.original).write(`,`).newLine(),n.write(`base: `).quote(t.name.base).write(`,`).newLine()}),n.writeLine(`},`),n.write(`version: `).quote(t.version).write(`,`).newLine(),n.write(`id: `).quote(t.id).write(`,`).newLine(),n.write(`createdAt: `).quote(t.createdAt).write(`,`).newLine()}),n.writeLine(`} as const satisfies BuildMetadataContract;`);let r=`build-metadata`;return a(p.join(e.outputPath,`${r}.ts`),n.toString()),[r]}function U(e){return{name:{original:e.name.original,base:e.name.base},version:e.version,id:ee(),createdAt:new Date().toISOString()}}async function W(e,t){let n=Object.entries(e),r=new t.writer;r.writeLine(`export enum Environment {`),r.indent(()=>{for(let[e]of n)r.write(`${e} = `).quote(e).write(`,`).newLine()}),r.writeLine(`}`),r.blankLine(),r.writeLine(`export const Environments = {`),r.indent(()=>{for(let[e,t]of n)r.writeLine(`${e}: {`),r.indent(()=>{r.writeLine(`name: Environment.${e},`),r.write(`file: `).quote(t.file).write(`,`).newLine(),r.write(`fileDir: `).quote(t.fileDir??``).write(`,`).newLine()}),r.writeLine(`},`)}),r.writeLine(`} as const;`),r.blankLine(),r.writeLine(`export type EnvironmentType = keyof typeof Environments;`);let i=`environment`;return a(p.join(t.outputPath,`${i}.ts`),r.toString()),[i]}async function G(e){let t=z(e.generatorConfig);B(t),await V(t,[...await H(t),...await W(e.config.environments,t)])}const K=new n,q={dir:{type:`string`,description:`Directory to look for the config file`,name:`dir`,alias:`d`,required:!1},config:{type:`string`,name:`config`,alias:`c`,description:`Config file name or path relative to the selected project directory.`,required:!1}};function J(e){let t=p.relative(process.cwd(),e);return!t||t.startsWith(`..`)?e:t}async function Y(e,t){let n=process.cwd();try{return process.chdir(e),await t()}finally{process.chdir(n)}}function X(e,t){K.error(e),K.error(t instanceof Error?t.message:String(t)),process.exit(1)}const Z=new n;function Q(t){return e({meta:{name:`build:app`,description:[`Generate ApiKit app output`,``,`Usage:`,` apikit build:app [--dir <directory>] [--config <config-name>]`,``,`Config lookup:`,` ${r}`,``,`Examples:`,` apikit build:app`,` apikit build:app --dir ./apps/main-api`,` apikit build:app -c custom.config`].join(`
7
+ `)},args:q,run:async({args:e})=>$(e,t)})}async function $(e,t){try{let n=await c({dir:e.dir,config:e.config}),r=await O(n.config);Z.title(`ApiKit`,`app`,[{label:`config`,value:J(n.configFilePath)},{label:`output`,value:r.build.outDir}]);let i=Object.entries(n.config.environments);Z.panel(`environments`,i.map(([e,t])=>({label:e,value:t.fileDir?`${t.fileDir}/${t.file}`:t.file})),i.length),await Y(n.rootDir,()=>G({config:n.config,generatorConfig:r})),Z.success(Z.step(`app`,`Generated ${r.build.outDir}`)),Z.success(Z.step(`done`,`Completed in ${Z.duration(Date.now()-t.startTime)}`)),Z.emptyLine()}catch(e){X(`ApiKit app build failed`,e)}}function te(t){return e({meta:{name:t.package.name,version:t.package.version},subCommands:{"build:app":Q(t)}})}function ne(e){return t(te(e))}export{ne as runMain};
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));require("reflect-metadata");let c=require("@buildplease/core/node"),l=require("@buildplease/core"),u=require("node:fs");u=s(u,1);let d=require("node:path");d=s(d,1);let ee=require("jiti"),f=require("inversify"),te=require("@dotenvx/dotenvx");te=s(te,1);let ne=require("node:fs/promises");ne=s(ne,1);let re=require("ejs");re=s(re,1);let ie=require("nodemailer");ie=s(ie,1);let ae=require("node:os");ae=s(ae,1);let oe=require("node:stream"),se=require("node:stream/promises"),p=require("mime-types");p=s(p,1);let m=require("lodash.merge");m=s(m,1);let h=require("i18next");h=s(h,1);let g=require("@fastify/cookie");g=s(g,1);let ce=require("node:async_hooks"),_=require("node:crypto");_=s(_,1);let le=require("uuid"),ue=require("stream"),de=require("stream/promises"),v=require("sharp");v=s(v,1);let y=require("libphonenumber-js"),b=require("validator");b=s(b,1);let x=require("argon2");x=s(x,1);let fe=require("@fastify/basic-auth");fe=s(fe,1);let S=require("fastify-plugin");S=s(S,1);let pe=require("@fastify/cors");pe=s(pe,1);let C=require("@fastify/under-pressure");C=s(C,1);let w=require("fastify-ip");w=s(w,1);let T=require("fastify-metrics");T=s(T,1);let me=require("@fastify/multipart");me=s(me,1);let he=require("@fastify/static");he=s(he,1);let ge=require("@fastify/view");ge=s(ge,1);let _e=require("fastify");_e=s(_e,1);let ve=require("zod");const ye=Symbol(`apikit.configuration.field`),E={string(){return D((e,t)=>{if(typeof e!=`string`)throw Error(`${t} must be string.`);let n=e.trim();if(!n)throw Error(`${t} must not be empty.`);return n},{required:!0})},number(){return D((e,t)=>{let n=typeof e==`number`?e:Number(e);if(!Number.isFinite(n))throw Error(`${t} must be number.`);return n},{required:!0})},boolean(){return D((e,t)=>{if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}throw Error(`${t} must be boolean.`)},{required:!0})},array(e){return D((t,n)=>{if(!Array.isArray(t))throw Error(`${n} must be array.`);return t.map((t,r)=>e.parse(t,`${n}[${r}]`))},{required:!0})},custom(){return D(e=>e,{required:!0})}};function be(e){return!!(e&&typeof e==`object`&&e[ye]===!0)}function D(e,t){let n={required:t.required,hasDefault:t.hasDefault??!1,defaultValue:t.defaultValue,parse:e,optional(){return D((t,n)=>{if(t!=null)return e(t,n)},{required:!1})},default(t){return D(e,{required:!1,hasDefault:!0,defaultValue:t})},map(n){let r=t.hasDefault&&t.defaultValue!==void 0?n(t.defaultValue):void 0;return D((t,r)=>n(e(t,r)),{required:t.required,hasDefault:t.hasDefault,defaultValue:r})}};return Object.defineProperty(n,ye,{value:!0}),n}const xe=Symbol(`apikit.configuration.contract`),Se=Symbol(`apikit.configuration.binding`);function O(e,t){let n=e.trim();if(!n)throw Error(`Configuration key must not be empty.`);let r=(e=>{let t={contract:r,input:e};return Object.defineProperty(t,Se,{value:!0}),t});return Object.defineProperties(r,{[xe]:{value:!0},key:{value:n},schema:{value:t}}),r}function Ce(e){return!!(e&&typeof e==`object`&&e[Se]===!0)}function we(e){let t=Object.entries(e);if(!t.length)throw Error(`At least one environment must be defined.`);for(let[e,n]of t)Ee(e,n);return e}function Te(e,t,n={}){let r=e[t];if(!r)throw Error(`Environment "${t}" is not defined.`);return{name:t,file:r.file.trim(),fileDir:r.fileDir?.trim()||n.fileDir?.trim()||process.cwd()}}function Ee(e,t){if(!e.trim())throw Error(`Environment name must not be empty.`);if(typeof t.file!=`string`||!t.file.trim())throw Error(`Environment file must not be empty for "${e}".`)}const De=Symbol(`apikit.configuration.source`);function Oe(e){return{env(e){return k(`env`,{name:e})},byEnvironment(e){return k(`by-environment`,{cases:e})},compute(e){return k(`compute`,{compute:e})},static(e){return k(`static`,{value:e})}}}function ke(e){return!!(e&&typeof e==`object`&&e[De]===!0)}function k(e,t,n=[]){let r={kind:e,options:t,transforms:n,map(r){return k(e,t,[...n,r])}};return Object.defineProperty(r,De,{value:!0}),r}const A={build:{outDir:`.apikit`},logger:{enabled:!1},server:{debug:!1,trustProxy:!1},metrics:{enabled:!1,endpoint:`/metrics`,name:`metrics`,defaultMetrics:{enabled:!0},routeMetrics:{enabled:!0},clearRegisterOnInit:!1},health:{enabled:!0,url:`/health`,pressure:{maxEventLoopDelay:0,maxHeapUsedBytes:0,maxRssBytes:0,maxEventLoopUtilization:0}},notification:{enabled:!1},email:{enabled:!1,templatesPath:`./src/templates`,globals:{}},i18n:{resources:{},directories:[],files:[],defaultLanguage:`en`,fallbackLanguages:`en`,supportedLanguages:[`en`,`sk`,`cs`],load:`languageOnly`,preload:[`en`,`sk`,`cs`],nonExplicitSupportedLngs:!0,lowerCaseLng:!0,cleanCode:!0,defaultNamespace:`translation`,keySeparator:`.`,nsSeparator:`:`,pluralSeparator:`_`,contextSeparator:`_`},staticFiles:{enabled:!1,routePrefix:`/`,maxAge:3600,dotfiles:`ignore`,etag:!0,immutable:!0,decorateReply:!0,preCompressed:!1},basicAuth:{enabled:!1,authenticate:!1,proxyMode:!1,header:void 0,strictCredentials:void 0},cors:{enabled:!1,allowAllOrigins:!1,includeWwwSubdomain:!0,options:{methods:[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`OPTIONS`],credentials:!0,optionsSuccessStatus:200}},multipart:{enabled:!1,options:{limits:{fileSize:20971520}}}};async function Ae(e,t){let n=d.default.resolve(e,t,`build-metadata.ts`);if(!u.default.existsSync(n))throw Error(`ApiKit build metadata "${n}" does not exist. Run "apikit build:app" first.`);return je(await(0,ee.createJiti)(e,{interopDefault:!1}).import(n,{try:!0}),n)}function je(e,t){if(!Me(e)||!Me(e.BuildMetadata))throw Error(`ApiKit build metadata is missing (${t}).`);let n=e.BuildMetadata,r=n.name;if(!Me(r)||typeof r.original!=`string`||typeof r.base!=`string`||typeof n.version!=`string`||typeof n.id!=`string`||typeof n.createdAt!=`string`)throw Error(`ApiKit build metadata is invalid (${t}).`);return{name:{original:r.original,base:r.base},version:n.version,id:n.id,createdAt:n.createdAt}}function Me(e){return typeof e==`object`&&!!e}const Ne=[`.ts`,`.mts`,`.cts`,`.js`,`.mjs`,`.cjs`,`.json`];async function Pe(e,t={}){let n=Fe(t.dir),r=Ie(n,t.config??e.defaultName);try{let t=await Le(n,r);return{config:e.validate(t,r),configFilePath:r,rootDir:n}}catch(t){throw Error(`Failed to load ${e.name} config: ${t instanceof Error?t.message:String(t)}`)}}function Fe(e){let t=e?(0,c.resolvePath)(process.cwd(),e):process.cwd();return(0,c.ensureDirectory)(t),t}function Ie(e,t){let n=(0,c.resolvePath)(e,t);for(let e of Ne){let t=`${n}${e}`;if(u.default.existsSync(t))return t}return n}async function Le(e,t){return(0,ee.createJiti)(e,{interopDefault:!0,extensions:[...Ne],tsconfigPaths:!0}).import(t,{try:!0,default:!0})}async function Re(e={}){return Pe({name:`ApiKit`,defaultName:`apikit.config`,validate:ze},e)}function ze(e,t){if(!e||typeof e!=`object`)throw Error(`ApiKit config is missing (${t})`);return e}async function j(e,t,n={}){let r={buildMetadata:n.buildMetadata,environment:n.environment};return Ve(e.schema,t,r,e.key)}async function Be(e,t){return j(e.contract,e.input,t)}async function Ve(e,t,n,r){if(be(e))return He(e,t,n,r);let i=await M(t,n,r)??{};if(!i||typeof i!=`object`||Array.isArray(i))throw Error(`${r} must be object.`);let a={};for(let[t,o]of Object.entries(e))a[t]=await Ve(o,i[t],n,`${r}.${t}`);return a}async function He(e,t,n,r){let i=await M(t,n,r);if(i==null){if(e.hasDefault)return We(e.defaultValue);if(!e.required)return;throw Error(`Missing required configuration: ${r}`)}return e.parse(i,r)}async function M(e,t,n){if(ke(e))return Ue(e,t,n);if(Ce(e))return Be(e,t);if(Array.isArray(e))return Promise.all(e.map((e,r)=>M(e,t,`${n}[${r}]`)));if(e&&typeof e==`object`){let r={};for(let[i,a]of Object.entries(e))r[i]=await M(a,t,`${n}.${i}`);return r}return e}async function Ue(e,t,n){let r;switch(e.kind){case`env`:{let{name:t}=e.options,n=process.env[t];r=typeof n==`string`&&n.trim()?n.trim():void 0;break}case`by-environment`:{if(!t.environment)throw Error(`${n} requires runtime environment.`);let{cases:i}=e.options;r=await M(i[t.environment.name],t,n);break}case`compute`:{if(!t.environment)throw Error(`${n} requires runtime environment.`);if(!t.buildMetadata)throw Error(`${n} requires build metadata.`);let{compute:i}=e.options;r=await i(t);break}case`static`:{let{value:t}=e.options;r=t;break}}for(let i of e.transforms){if(!t.environment)throw Error(`${n} source transforms require runtime environment.`);if(!t.buildMetadata)throw Error(`${n} source transforms require build metadata.`);r=await i(r,t)}return r}function We(e){if(Array.isArray(e))return e.map(e=>We(e));if(Ge(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=We(r);return t}return e}function Ge(e){return Object.prototype.toString.call(e)===`[object Object]`}const Ke=O(`apikit.basic-auth`,{enabled:E.boolean().default(A.basicAuth.enabled),authenticate:E.custom().default(A.basicAuth.authenticate),proxyMode:E.boolean().default(A.basicAuth.proxyMode),header:E.string().optional().default(A.basicAuth.header),strictCredentials:E.boolean().optional().default(A.basicAuth.strictCredentials),username:E.string().optional(),password:E.string().optional()}),qe=O(`apikit.build`,{outDir:E.string().default(A.build.outDir)}),Je=O(`apikit.cors`,{enabled:E.boolean().default(A.cors.enabled),allowAllOrigins:E.boolean().default(A.cors.allowAllOrigins),includeWwwSubdomain:E.boolean().default(A.cors.includeWwwSubdomain),options:E.custom().default({}).map(Ye)});function Ye(e){return{...A.cors.options,...e}}const Xe=O(`apikit.email`,{enabled:E.boolean().default(A.email.enabled),templatesPath:E.string().default(A.email.templatesPath),globals:E.custom().default(A.email.globals),smtp:{host:E.string().optional(),port:E.number().optional(),secure:E.boolean().optional(),user:E.string().optional(),password:E.string().optional()}}),Ze=O(`apikit.health`,{enabled:E.boolean().default(A.health.enabled),url:E.string().default(A.health.url).map(Qe),pressure:{maxEventLoopDelay:E.number().default(A.health.pressure.maxEventLoopDelay),maxHeapUsedBytes:E.number().default(A.health.pressure.maxHeapUsedBytes),maxRssBytes:E.number().default(A.health.pressure.maxRssBytes),maxEventLoopUtilization:E.number().default(A.health.pressure.maxEventLoopUtilization)}});function Qe(e){if(!e.startsWith(`/`))throw Error(`apikit.health.url must start with slash.`);if(e===`/`)throw Error(`apikit.health.url must not be root path.`);if(e.includes(`?`)||e.includes(`#`))throw Error(`apikit.health.url must not contain query string or fragment.`);return e.length>1?e.replace(/\/+$/,``):e}const $e=O(`apikit.i18n`,{resources:E.custom().default(A.i18n.resources),directories:E.array(E.custom()).default(A.i18n.directories),files:E.array(E.custom()).default(A.i18n.files),defaultLanguage:E.string().default(A.i18n.defaultLanguage),fallbackLanguages:E.custom().default(A.i18n.fallbackLanguages),supportedLanguages:E.array(E.string()).default(A.i18n.supportedLanguages),load:E.custom().default(A.i18n.load),preload:E.custom().default(A.i18n.preload),nonExplicitSupportedLngs:E.boolean().default(A.i18n.nonExplicitSupportedLngs),lowerCaseLng:E.boolean().default(A.i18n.lowerCaseLng),cleanCode:E.boolean().default(A.i18n.cleanCode),namespaces:E.array(E.string()).optional(),defaultNamespace:E.string().default(A.i18n.defaultNamespace),keySeparator:E.string().default(A.i18n.keySeparator),nsSeparator:E.string().default(A.i18n.nsSeparator),pluralSeparator:E.string().default(A.i18n.pluralSeparator),contextSeparator:E.string().default(A.i18n.contextSeparator)}),et=O(`apikit.logger`,E.custom().default({enabled:A.logger.enabled}).map(tt));function tt(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.logger must be object.`);if(typeof e.enabled!=`boolean`)throw Error(`apikit.logger.enabled must be boolean.`);if(!e.enabled){if(`transports`in e&&e.transports!==void 0)throw Error(`apikit.logger.transports cannot be configured when logger is disabled.`);if(`request`in e&&e.request!==void 0)throw Error(`apikit.logger.request cannot be configured when logger is disabled.`);return{enabled:!1}}if(!Array.isArray(e.transports)||e.transports.length===0)throw Error(`apikit.logger.transports must be a non-empty array when logger is enabled.`);let t=nt(e.request);return{enabled:!0,transports:e.transports,...t?{request:t}:{}}}function nt(e){if(e!==void 0){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.logger.request must be object.`);if(e.ignoredPaths===void 0)return{};if(!Array.isArray(e.ignoredPaths))throw Error(`apikit.logger.request.ignoredPaths must be array.`);return{ignoredPaths:e.ignoredPaths.map((e,t)=>rt(e,t))}}}function rt(e,t){if(typeof e!=`string`)throw Error(`apikit.logger.request.ignoredPaths[${t}] must be string.`);let n=e.trim();if(!n)throw Error(`apikit.logger.request.ignoredPaths[${t}] must not be empty.`);if(!n.startsWith(`/`))throw Error(`apikit.logger.request.ignoredPaths[${t}] must start with slash.`);if(n===`/`)throw Error(`apikit.logger.request.ignoredPaths[${t}] must not be root path.`);if(n.includes(`?`)||n.includes(`#`))throw Error(`apikit.logger.request.ignoredPaths[${t}] must not contain query string or fragment.`);return n.length>1?n.replace(/\/+$/,``):n}const it=O(`apikit.metrics`,{enabled:E.boolean().default(A.metrics.enabled),endpoint:E.custom().default(A.metrics.endpoint),name:E.string().default(A.metrics.name),defaultMetrics:E.custom().default(A.metrics.defaultMetrics),routeMetrics:E.custom().default(A.metrics.routeMetrics),clearRegisterOnInit:E.boolean().default(A.metrics.clearRegisterOnInit)}),at=O(`apikit.multipart`,{enabled:E.boolean().default(A.multipart.enabled),options:E.custom().default(A.multipart.options)}),ot=O(`apikit.notification`,E.custom().default({enabled:A.notification.enabled}).map(st));function st(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.notification must be object.`);if(typeof e.enabled!=`boolean`)throw Error(`apikit.notification.enabled must be boolean.`);if(!e.enabled){if(`channels`in e&&e.channels!==void 0)throw Error(`apikit.notification.channels cannot be configured when notification is disabled.`);return{enabled:!1}}if(!e.channels||typeof e.channels!=`object`||Array.isArray(e.channels))throw Error(`apikit.notification.channels must be object when notification is enabled.`);lt(e.channels);let t=ct(e.channels.telegram);if(!t)throw Error(`apikit.notification.channels must contain at least one configured channel.`);return{enabled:!0,channels:{telegram:t}}}function ct(e){if(e!==void 0){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.notification.channels.telegram must be object.`);return{token:ut(e.token,`apikit.notification.channels.telegram.token`),chatId:ut(e.chatId,`apikit.notification.channels.telegram.chatId`)}}}function lt(e){for(let t of Object.keys(e))if(t!==`telegram`)throw Error(`apikit.notification.channels.${t} is not supported.`)}function ut(e,t){if(typeof e!=`string`)throw Error(`${t} must be string.`);let n=e.trim();if(!n)throw Error(`${t} must not be empty.`);return n}const dt=O(`apikit.server`,{identifier:E.string(),debug:E.boolean().default(A.server.debug),host:E.string(),port:E.number(),trustProxy:E.custom().default(A.server.trustProxy)}),ft=O(`apikit.staticFiles`,{enabled:E.boolean().default(A.staticFiles.enabled),publicDirectory:E.string().optional(),routePrefix:E.string().default(A.staticFiles.routePrefix),maxAge:E.number().default(A.staticFiles.maxAge),dotfiles:E.custom().default(A.staticFiles.dotfiles),etag:E.boolean().default(A.staticFiles.etag),immutable:E.boolean().default(A.staticFiles.immutable),decorateReply:E.boolean().default(A.staticFiles.decorateReply),preCompressed:E.boolean().default(A.staticFiles.preCompressed)});function N(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let pt=class{get build(){return global.apikit.build}get isDebug(){return global.apikit.serverConfig.debug}get environment(){return global.apikit.environmentConfig}get logger(){return global.apikit.loggerConfig}get server(){return global.apikit.serverConfig}get metrics(){return global.apikit.metricsConfig}get health(){return global.apikit.healthConfig}get email(){return global.apikit.emailConfig}get notification(){return global.apikit.notificationConfig}get i18n(){return global.apikit.i18nConfig}get staticFiles(){return global.apikit.staticFilesConfig}get basicAuth(){return global.apikit.basicAuthConfig}get cors(){return global.apikit.corsConfig}get multipart(){return global.apikit.multipartConfig}get(e){if(!global.apikit.configurations.has(e.key))throw Error(`Configuration "${e.key}" is missing.`);return global.apikit.configurations.get(e.key)}optional(e){return global.apikit.configurations.get(e.key)}};pt=N([(0,f.injectable)()],pt);function mt(e,t){return{...t,environments:e,configurations:t.configurations??[]}}const ht=new c.Console;async function gt(e){let t=await Re({config:e.config}),n=await j(qe,t.config.build),r=await Ae(t.rootDir,n.outDir),i=Te(t.config.environments,e.environment,{fileDir:t.rootDir});yt(i);let a={buildMetadata:r,environment:i},o=await _t(t.config,a);global.apikit={build:r,environmentConfig:i,...o},ht.success(`[ApiKit] Context created for ${i.name} environment`)}async function _t(e,t){return{serverConfig:await j(dt,e.server,t),loggerConfig:await j(et,e.logger,t),metricsConfig:await j(it,e.metrics,t),healthConfig:await j(Ze,e.health,t),emailConfig:await j(Xe,e.email,t),notificationConfig:await j(ot,e.notification,t),i18nConfig:await j($e,e.i18n,t),staticFilesConfig:await j(ft,e.staticFiles,t),basicAuthConfig:await j(Ke,e.basicAuth,t),corsConfig:await j(Je,e.cors,t),multipartConfig:await j(at,e.multipart,t),configurations:await vt(e.configurations,t)}}async function vt(e,t){let n=new Map;for(let r of e){if(r.contract.key.startsWith(`apikit.`))throw Error(`Configuration key "${r.contract.key}" is reserved for ApiKit.`);if(n.has(r.contract.key))throw Error(`Configuration "${r.contract.key}" is registered more than once.`);n.set(r.contract.key,await Be(r,t))}return n}function yt(e){let t=d.default.resolve(e.fileDir,e.file);if(!u.default.existsSync(t))throw Error(`Environment file "${t}" does not exist.`);te.default.config({path:t}),process.env.NODE_ENV=e.name}const bt={name:`buildplease`,displayName:`BuildPlease`,scope:`@buildplease`},P=`${bt.name}.ApiKit.DI`,F={DI:{Configuration:{Controller:Symbol.for(`${P}.Configuration.Controller`)},Database:{MongoDB:{QueryFormatter:Symbol.for(`${P}.Database.MongoDB.QueryFormatter`)}},Email:{Controller:Symbol.for(`${P}.Email.Controller`)},File:{TemporaryRepository:Symbol.for(`${P}.File.TemporaryRepository`)},Validation:{Controller:Symbol.for(`${P}.Validation.Controller`),DtoController:Symbol.for(`${P}.Validation.DtoController`)},OpenAPI:{SchemaController:Symbol.for(`${P}.OpenAPI.SchemaController`)},I18n:{Controller:Symbol.for(`${P}.I18n.Controller`)},Notification:{Controller:Symbol.for(`${P}.Notification.Controller`)},Normalization:{Controller:Symbol.for(`${P}.Normalization.Controller`)},Formatter:{Controller:Symbol.for(`${P}.Formatter.Controller`),MultipartController:Symbol.for(`${P}.Formatter.MultipartController`)},Generator:{RandomValueGenerator:Symbol.for(`${P}.Generator.RandomValueGenerator`)},Image:{NormalizationController:Symbol.for(`${P}.Image.NormalizationController`)},Server:{Controller:Symbol.for(`${P}.Server.Controller`),RequestController:Symbol.for(`${P}.Server.RequestController`),ResponseController:Symbol.for(`${P}.Server.ResponseController`)},Security:{CryptographyController:Symbol.for(`${P}.Security.CryptographyController`)}}};var xt=class{assemble(e){e.bind(F.DI.Configuration.Controller).to(pt).inSingletonScope()}};let St=class{format(e){return this.flattenRecursive(e,``)}flattenRecursive(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];if(i===void 0||this.isPlainObject(i)&&Object.keys(i).length===0)continue;if(this.isOperator(r)){n[r]=this.processOperator(r,i);continue}let a=t?`${t}.${r}`:r;this.isPlainObject(i)?this.containsOperator(i)?n[a]={...i}:Object.assign(n,this.flattenRecursive(i,a)):n[a]=i}return n}isOperator(e){return e.startsWith(`$`)}containsOperator(e){return Object.keys(e).some(e=>this.isOperator(e))}isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}processOperator(e,t){return e===`$expr`?t:Array.isArray(t)?t.map(e=>this.flattenRecursive(e,``)):this.isPlainObject(t)?this.flattenRecursive(t,``):t}};St=N([(0,f.injectable)()],St);var Ct=class{assemble(e){e.bind(F.DI.Database.MongoDB.QueryFormatter).to(St)}};function I(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function L(e,t){return function(n,r){t(n,r,e)}}const R=`[Email]`;let z=class{configuration;logger;transporter;templatesPath;isEnabled;smtpConfig;constructor(e,t){this.configuration=e,this.logger=t,this.isEnabled=this.configuration.email.enabled,this.smtpConfig=wt(this.configuration.email),this.templatesPath=Tt(this.configuration.email.templatesPath)}async sendEmail(e){try{if(!this.isEnabled){this.logger.debug(`${R} Sending skipped — disabled`);return}let t=this.getOrCreateTransporter(),n=await this.renderTemplate(e),r={to:e.recipient,from:e.sender,subject:e.subject,html:n,...e.replyTo===void 0?{}:{replyTo:e.replyTo}};await t.sendMail(r)}catch(e){throw this.logger.error(`${R} Send failed`,{error:e}),e}}getOrCreateTransporter(){return this.transporter||=ie.default.createTransport({host:this.smtpConfig.host,port:this.smtpConfig.port,secure:this.smtpConfig.secure,auth:{user:this.smtpConfig.user,pass:this.smtpConfig.pass}}),this.transporter}async renderTemplate(e){try{let t=this.makeFilePath(e.templatePath,e.fallbackPath),n=await ne.default.readFile(t,`utf-8`),r={globals:this.makeGlobals(),...e.data};return re.default.render(n,r)}catch(e){throw this.logger.error(`${R} Render failed`,{error:e}),e}}makeFilePath(e,t){let n=d.default.join(this.templatesPath,this.sanitizeTemplatePath(e));if((0,u.existsSync)(n))return n;if(t){let e=d.default.join(this.templatesPath,this.sanitizeTemplatePath(t));if((0,u.existsSync)(e))return e}throw Error(`${R} Template not found: ${n}${t?` or ${t}`:``}`)}makeGlobals(){let e=this.configuration.email.globals;return{generatedDate:new Date().toISOString().replace(`T`,` `).substring(0,16)+` UTC`,...e}}sanitizeTemplatePath(e){if(e.includes(`..`))throw Error(`${R} Invalid template path: ${e}`);let t=e.replace(/^\/+/,``);return t.endsWith(`.ejs`)?t:`${t}.ejs`}};z=N([(0,f.injectable)(),L(0,(0,f.inject)(F.DI.Configuration.Controller)),L(1,(0,f.inject)(l.CoreSymbols.DI.Logger)),I(`design:paramtypes`,[Object,Object])],z);function wt(e){if(!e.enabled)return{host:``,port:0,secure:!1,user:``,pass:``};let t=e.smtp;if(!t.host)throw Error(`${R} email.smtp.host is required when email is enabled`);if(!t.port)throw Error(`${R} email.smtp.port is required when email is enabled`);if(t.secure===void 0)throw Error(`${R} email.smtp.secure is required when email is enabled`);if(!t.user)throw Error(`${R} email.smtp.user is required when email is enabled`);if(!t.password)throw Error(`${R} email.smtp.password is required when email is enabled`);if(!Number.isInteger(t.port)||t.port<=0)throw Error(`${R} email.smtp.port must be a positive integer`);return{host:t.host,port:t.port,secure:t.secure,user:t.user,pass:t.password}}function Tt(e){let t=e.trim();return d.default.isAbsolute(t)?d.default.normalize(t):d.default.resolve(process.cwd(),t)}var Et=class{data;recipient;sender;subject;replyTo;constructor(e){this.data=e.data,this.recipient=e.recipient,this.sender=e.sender??this.defaultSender(),this.subject=e.subject??this.defaultSubject(),e.replyTo!==void 0&&(this.replyTo=e.replyTo)}get fallbackPath(){}},Dt=class{assemble(e){e.bind(F.DI.Email.Controller).to(z).inSingletonScope()}};const B=`[ApiKit:TemporaryFile]`;let V=class{logger;rootDir;constructor(e){this.logger=e,this.rootDir=ae.default.tmpdir()}get rootDirectory(){return this.rootDir}async createDirectory(e){let t=this.safeJoin(e);try{return await(0,c.createDirectoryAsync)(t)}catch(e){throw this.logger.error(`${B} Create directory failed`,{error:e,details:{abs:t}}),e}}async deleteDirectory(e){let t=this.safeJoin(e);try{await(0,c.removePathAsync)(t,{recursive:!0,force:!0})}catch(e){throw this.logger.error(`${B} Delete directory failed`,{error:e,details:{abs:t}}),e}}async save(e,t,n,r){let i=this.safeJoin(r),a=d.default.join(i,`${e}.${n.extension}`);try{if(await(0,c.createDirectoryAsync)(i),await(0,c.ensureDirectoryAsync)(i),Buffer.isBuffer(t))return await u.default.promises.writeFile(a,t),a;if(t instanceof oe.Readable){let e=u.default.createWriteStream(a);try{return await(0,se.pipeline)(t,e),a}finally{e.close()}}let e=Error(`Unsupported content type: expected Buffer or Readable.`);throw this.logger.error(`${B} Save unsupported content`,{error:e,details:{fileAbs:a,typeof:typeof t}}),e}catch(t){throw this.logger.error(`${B} Save failed`,{error:t,details:{fileAbs:a,relativeDirectory:r,filename:e,extension:n.extension}}),t}}async delete(e){let t=this.safeJoin(e);try{await(0,c.removePathAsync)(t,{recursive:!1,force:!0})}catch(e){throw this.logger.error(`${B} Delete failed`,{error:e,details:{abs:t}}),e}}safeJoin(e){let t=d.default.resolve(this.rootDir,e),n=this.rootDir.endsWith(d.default.sep)?this.rootDir:this.rootDir+d.default.sep;if(!t.startsWith(n)&&t!==this.rootDir){let n=Error(`Path escapes repository root: "${e}"`);throw this.logger.error(`${B} Path traversal attempt`,{error:n,details:{root:this.rootDir,attempted:t}}),n}return t}};V=N([(0,f.injectable)(),L(0,(0,f.inject)(l.CoreSymbols.DI.Logger)),I(`design:paramtypes`,[Object])],V);var Ot=class{assemble(e){e.bind(F.DI.File.TemporaryRepository).to(V)}},H=class e extends Error{_code;_statusCode;_details;constructor({code:t,message:n,statusCode:r,details:i}){super(n),this._code=t,this._statusCode=r,this._details=i,Error.captureStackTrace&&Error.captureStackTrace(this,e),Object.setPrototypeOf(this,e.prototype)}get code(){return this._code}get statusCode(){return this._statusCode}get details(){return this._details}toJSON(){let e={code:this._code,message:this.message,details:this.formatDetails(this.details)};return(0,l.filterObject)(e,{filterNull:!0,filterUndefined:!0,filterEmptyString:!0,filterEmptyObject:!0})}formatDetails(e){if(e!=null)return typeof e==`string`?{_error:[e]}:Array.isArray(e)&&e.every(e=>typeof e==`string`)?{_errors:e}:e}};function U(e){return typeof e==`object`&&!!e&&`message`in e&&typeof e.message==`string`&&`code`in e&&typeof e.code==`string`&&`statusCode`in e&&typeof e.statusCode==`number`}const W=l.CoreL10nResource.extend({resources:{en:{apikit:{errors:{common:{not_found:`The requested resource was not found`,unable_to_process_request:`We’re unable to process your request.`,unknown_error:`An unknown error occurred. Please try again later.`,already_exists:`The resource already exists`},server:{internal:`An internal server error occurred`,unavailable:`The service is temporarily unavailable. Try again later`,dependency_failed:`An external service or dependency failed`,timeout:`The server did not respond in time`},limit:{too_many_requests:`Too many requests. Try again later`},auth:{unauthorized:`You are not authorized to perform this action`,forbidden:`You do not have access to this resource`},validation:{bad_request:`The request is malformed or invalid`,invalid_json_syntax:`Invalid JSON syntax`,invalid_properties:`Some of the provided values are invalid`,invalid_format:`Invalid format`,invalid_date_format:`The date format is incorrect`,invalid_password:`The password you entered is incorrect`,invalid_password_new_same_as_old:`The new password must be different from the current one`,invalid_phone_number_format:`Invalid phone number format`,invalid_phone_new_same_as_old:`TThe new phone number must be different from the old one`,invalid_email_format:`Invalid email format`,invalid_email_new_same_as_old:`The new email must be different from the current one`},format:{unsupported:`Unsupported format`,max_size_exceeded:`Payload is too large.`},image:{max_size_exceeded:`Image is too large. Maximum allowed size is {{specs.maxSize}} {{specs.unit}}.`}}}},sk:{apikit:{errors:{common:{not_found:`Požadovaný zdroj sa nenašiel`,unable_to_process_request:`Vašu požiadavku sa nepodarilo spracovať.`,unknown_error:`Vyskytla sa neznáma chyba. Skúste to prosím znova neskôr.`,already_exists:`Zdroj už existuje`},server:{internal:`Vyskytla sa interná chyba servera`,unavailable:`Služba je momentálne nedostupná. Skúste to neskôr`,dependency_failed:`Zlyhala externá služba alebo závislosť`,timeout:`Server neodpovedal v stanovenom čase`},limit:{too_many_requests:`Príliš veľa požiadaviek. Skúste to neskôr`},auth:{unauthorized:`Nemáte oprávnenie na vykonanie tejto akcie`,forbidden:`K tomuto zdroju nemáte prístup`},validation:{bad_request:`Požiadavka je neplatná alebo nesprávna`,invalid_json_syntax:`Neplatná syntax JSON`,invalid_properties:`Niektoré z poskytnutých hodnôt sú neplatné`,invalid_format:`Neplatný formát`,invalid_date_format:`Formát dátumu je nesprávny`,invalid_password:`Zadané heslo je nesprávne`,invalid_password_new_same_as_old:`Nové heslo sa musí líšiť od aktuálneho`,invalid_phone_number_format:`Neplatný formát telefónneho čísla`,invalid_phone_new_same_as_old:`Nové telefónne číslo sa musí líšiť od pôvodného`,invalid_email_format:`Neplatný formát e-mailu`,invalid_email_new_same_as_old:`Nový e-mail sa musí líšiť od aktuálneho`},format:{unsupported:`Nepodporovaný formát`,max_size_exceeded:`Súbor je príliš veľký.`},image:{max_size_exceeded:`Obrázok je príliš veľký. Maximálna povolená veľkosť je {{specs.maxSize}} {{specs.unit}}.`}}}},cs:{apikit:{errors:{common:{not_found:`Požadovaný zdroj nebyl nalezen`,unable_to_process_request:`Vaši žádost se nepodařilo zpracovat.`,unknown_error:`Došlo k neznámé chybě. Zkuste to prosím později.`,already_exists:`Zdroj již existuje`},server:{internal:`Došlo k interní chybě serveru`,unavailable:`Služba je momentálně nedostupná. Zkuste to později`,dependency_failed:`Selhala externí služba nebo závislost`,timeout:`Server neodpověděl včas`},limit:{too_many_requests:`Příliš mnoho požadavků. Zkuste to později`},auth:{unauthorized:`Nemáte oprávnění k provedení této akce`,forbidden:`K tomuto zdroji nemáte přístup`},validation:{bad_request:`Požadavek je neplatný nebo nesprávný`,invalid_json_syntax:`Neplatná syntaxe JSON`,invalid_properties:`Některé z poskytnutých hodnot jsou neplatné`,invalid_format:`Neplatný formát`,invalid_date_format:`Formát data je nesprávný`,invalid_password:`Zadané heslo je nesprávné`,invalid_password_new_same_as_old:`Nové heslo se musí lišit od aktuálního`,invalid_phone_number_format:`Neplatný formát telefonního čísla`,invalid_phone_new_same_as_old:`Nové telefonní číslo se musí lišit od původního`,invalid_email_format:`Neplatný formát e-mailu`,invalid_email_new_same_as_old:`Nový e-mail se musí lišit od aktuálního`},format:{unsupported:`Nepodporovaný formát`,max_size_exceeded:`Soubor je příliš velký.`},image:{max_size_exceeded:`Obrázek je příliš velký. Maximální povolená velikost je {{specs.maxSize}} {{specs.unit}}.`}}}}}}),G=(0,l.defineL10n)(W);function kt(e){return(e??``).toLowerCase().replace(/_/g,`-`).trim()}function At(e){let[t,n]=e.split(`-`);return{base:t||``,region:n}}let jt=class{configurationController;constructor(e){this.configurationController=e}async prepare(){let e=this.makeOptions();await h.default.init(e)}parseLocale(e,t={}){let{supportedLanguages:n,defaultLanguage:r}=this.makeConfig(),{ignoreRegion:i=!0}=t;if(!e||!e.trim())return r;let a=new Set(n.map(e=>e.toLowerCase())),o,s,c=0;for(let t of e.split(`,`)){let e=t.trim();if(!e){c++;continue}let n=e.split(`;`),r=kt(n[0]??``);if(!r||r===`*`){c++;continue}let l=zt(n.find(e=>e.startsWith(`q=`)));if(l===0){c++;continue}let{base:u}=At(r);if(!u){c++;continue}!i&&a.has(r)&&(!o||l>o.q||l===o.q&&c<o.idx)&&(o={code:r,q:l,idx:c}),a.has(u)&&(!s||l>s.q||l===s.q&&c<s.idx)&&(s={code:u,q:l,idx:c}),c++}return o?o.code:s?s.code:r}makeOptions(){let e=this.makeConfig(),t=Mt(e);return{debug:!1,lng:e.defaultLanguage,fallbackLng:e.fallbackLanguages,supportedLngs:e.supportedLanguages,load:e.load,nonExplicitSupportedLngs:e.nonExplicitSupportedLngs,preload:e.preload,lowerCaseLng:e.lowerCaseLng,cleanCode:e.cleanCode,ns:e.namespaces,defaultNS:e.defaultNamespace,keySeparator:e.keySeparator,nsSeparator:e.nsSeparator,pluralSeparator:e.pluralSeparator,contextSeparator:e.contextSeparator,resources:t}}makeConfig(){let e=this.configurationController.i18n??{},t=e.defaultNamespace??`translation`,n=e.defaultLanguage??`en`,r=e.fallbackLanguages??n,i=(e.directories??[]).map(e=>({path:e.path,namespace:e.namespace??t})),a=(e.files??[]).map(e=>({locale:e.locale,path:e.path,namespace:e.namespace??t})),o=this.makeNamespaces(e.namespaces,t,i,a);return{resources:e.resources??{},directories:i,files:a,defaultLanguage:n,fallbackLanguages:r,supportedLanguages:e.supportedLanguages??[`en`,`sk`,`cs`],load:e.load??`languageOnly`,nonExplicitSupportedLngs:e.nonExplicitSupportedLngs??!0,preload:e.preload??!1,lowerCaseLng:e.lowerCaseLng??!0,cleanCode:e.cleanCode??!0,namespaces:o,defaultNamespace:t,keySeparator:e.keySeparator??`.`,nsSeparator:e.nsSeparator??`:`,pluralSeparator:e.pluralSeparator??`_`,contextSeparator:e.contextSeparator??`_`}}makeNamespaces(e,t,n,r){let i=Array.isArray(e)?e.filter(e=>typeof e==`string`):typeof e==`string`?[e]:[],a=new Set(i.length?i:[t]);for(let e of n)a.add(e.namespace);for(let e of r)a.add(e.namespace);return Array.from(a)}};jt=N([(0,f.injectable)(),L(0,(0,f.inject)(F.DI.Configuration.Controller)),I(`design:paramtypes`,[Object])],jt);function Mt(e){let t=Pt(e);Nt(t,e);let n=[...It(e),...Lt(e)];for(let{locale:e,ns:r,path:i}of n){let n=t[e]||={},a=JSON.parse(u.default.readFileSync(i,`utf-8`));n[r]=(0,m.default)(n[r]||{},a)}return t}function Nt(e,t){for(let n of Object.keys(t.resources).sort()){let r=t.resources[n];if(!r)continue;let i=e[n]||={};i[t.defaultNamespace]=(0,m.default)(i[t.defaultNamespace]||{},r)}}function Pt(e){let t={};for(let n of Object.keys(W.resources).sort()){let r=t[n]||={};r[e.defaultNamespace]=Ft(W.resources[n])}return t}function Ft(e){return JSON.parse(JSON.stringify(e))}function It(e){let t=[];for(let n of e.directories){let e=Rt((0,c.resolvePath)(process.cwd(),n.path));for(let r of e)t.push({locale:r.locale,ns:n.namespace,path:r.path})}return t}function Lt(e){return e.files.map(e=>({locale:e.locale,ns:e.namespace,path:(0,c.resolvePath)(process.cwd(),e.path)}))}function Rt(e){let t=(0,c.ensureDirectory)(e),n=u.default.readdirSync(t).filter(e=>e.endsWith(`.json`)).sort();if(!n.length)throw Error(`[ApiKit:I18n] No .json files in ${t}`);return n.map(e=>({locale:e.replace(/\.json$/,``),path:(0,c.resolvePath)(t,e)}))}function zt(e){if(!e)return 1;let t=parseFloat(e.slice(2).replace(`,`,`.`));return Number.isFinite(t)?Math.max(0,Math.min(1,t)):1}var Bt=class{_name;_value;_options;constructor(e,t,n={}){this._name=e,this._value=t,this._options={...n}}get name(){return this._name}get value(){return this._value}get options(){return{...this._options}}mutate(e){return e.name!==void 0&&(this._name=e.name),e.value!==void 0&&(this._value=e.value),e.options!==void 0&&(this._options={...this._options,...e.options}),this}serialize(){return g.fastifyCookie.serialize(this._name,this._value,this._options)}toString(){return this.serialize()}};const K={accept:`accept`,acceptLanguage:`accept-language`,authorization:`authorization`,cacheControl:`cache-control`,contentType:`content-type`,cookie:`cookie`,setCookie:`set-cookie`,userAgent:`user-agent`};let Vt=function(e){return e.POST=`POST`,e.PUT=`PUT`,e.PATCH=`PATCH`,e.GET=`GET`,e.DELETE=`DELETE`,e.OPTIONS=`OPTIONS`,e}({}),Ht=function(e){return e.JSON=`JSON`,e.File=`File`,e}({});var Ut=class{statusCode;headers;constructor({statusCode:e,headers:t}){this.statusCode=e,this.headers=t}},Wt=class extends Ut{data;responseType=`JSON`;constructor({statusCode:e,data:t,headers:n}){super({statusCode:e,headers:n}),this.data=t}},Gt=class extends Ut{filePath;shouldRender;data;responseType=`File`;constructor({statusCode:e,filePath:t,shouldRender:n,headers:r,data:i}){super({statusCode:e,headers:r}),this.filePath=t,this.shouldRender=n,this.data=i}},q=class{metadata;constructor(e){this.metadata=e}toJSON(){let e={[K.userAgent]:this.metadata.headers?.[K.userAgent],[K.contentType]:this.metadata.headers?.[K.contentType],[K.acceptLanguage]:this.metadata.headers?.[K.acceptLanguage],[K.accept]:this.metadata.headers?.[K.accept]},t=(0,l.filterObject)({reqId:this.metadata.requestId,method:this.metadata.method,url:this.metadata.url,protocol:this.metadata.protocol,query:this.metadata.query,params:this.metadata.params,ip:this.metadata.ip,locale:this.metadata.locale,headers:e},{filterNull:!0,filterUndefined:!0,filterEmptyString:!0,filterEmptyArray:!0,filterEmptyObject:!0});return(0,l.isEmptyObject)(t)?void 0:t}};const Kt=Symbol.for(`request-scope.storage`);function qt(){let e=Reflect.get(globalThis,Kt);if(e)return e;let t=new ce.AsyncLocalStorage;return Reflect.defineProperty(globalThis,Kt,{value:t,configurable:!1,enumerable:!1,writable:!1}),t}const Jt=qt(),Yt={run(e,t){return Jt.run(e,t)},get metadata(){let e=Jt.getStore();if(!e?.metadata)throw Error("[RequestScope] Attempted to access `metadata` outside of request lifecycle.");return e.metadata},get requestId(){return this.metadata.requestId},get locale(){return this.metadata.locale}};var Xt=class{static t(e,t={}){let n=Yt.locale;return h.default.t(e,{...t,lng:n})}static get currentLocale(){return Yt.locale}static isSupportedLanguage(e,t={ignoreRegion:!0}){let n=kt(e);if(!n)return!1;let r=h.default.options.supportedLngs;if(!r)return!1;let i=new Set(r.map(kt));if(i.has(n))return!0;if(t.ignoreRegion){let{base:e}=At(n);if(e&&i.has(e))return!0}return!1}},Zt=class{static make(e,t={}){return this.translateKey(e,t)}static translateKey(e,t={}){let{overrideMessage:n,i18n:r}=t;return n??Xt.t(e,r)}};function J(e){return sn(e),e}const Qt=J({NOT_FOUND:{message:G.Apikit.Errors.Common.NotFound,code:`RESOURCE_NOT_FOUND`,statusCode:404},UNKNOWN_ERROR:{message:G.Apikit.Errors.Common.UnknownError,code:`UNKNOWN_ERROR`,statusCode:500},UNABLE_TO_PROCESS_REQUEST:{message:G.Apikit.Errors.Common.UnableToProcessRequest,code:`UNABLE_TO_PROCESS_REQUEST`,statusCode:500},RESOURCE_ALREADY_EXISTS:{message:G.Apikit.Errors.Common.AlreadyExists,code:`RESOURCE_ALREADY_EXISTS`,statusCode:409}}),$t=J({INTERNAL_SERVER_ERROR:{message:G.Apikit.Errors.Server.Internal,code:`INTERNAL_SERVER_ERROR`,statusCode:500},SERVICE_UNAVAILABLE:{message:G.Apikit.Errors.Server.Unavailable,code:`SERVICE_UNAVAILABLE`,statusCode:503},DEPENDENCY_FAILED:{message:G.Apikit.Errors.Server.DependencyFailed,code:`DEPENDENCY_FAILED`,statusCode:424},TIMEOUT:{message:G.Apikit.Errors.Server.Timeout,code:`TIMEOUT`,statusCode:504}}),en=J({TOO_MANY_REQUESTS:{message:G.Apikit.Errors.Limit.TooManyRequests,code:`TOO_MANY_REQUESTS`,statusCode:429}}),tn=J({UNAUTHORIZED:{message:G.Apikit.Errors.Auth.Unauthorized,code:`UNAUTHORIZED`,statusCode:401},FORBIDDEN:{message:G.Apikit.Errors.Auth.Forbidden,code:`FORBIDDEN`,statusCode:403}}),nn=J({BAD_REQUEST:{message:G.Apikit.Errors.Validation.BadRequest,code:`BAD_REQUEST`,statusCode:400},INVALID_JSON_SYNTAX:{message:G.Apikit.Errors.Validation.InvalidJsonSyntax,code:`JSON_SYNTAX_ERROR`,statusCode:400},INVALID_PROPERTIES:{message:G.Apikit.Errors.Validation.InvalidProperties,code:`INVALID_PROPERTIES`,statusCode:400},INVALID_FORMAT:{message:G.Apikit.Errors.Validation.InvalidFormat,code:`INVALID_FORMAT`,statusCode:400},INVALID_DATE_FORMAT:{message:G.Apikit.Errors.Validation.InvalidDateFormat,code:`INVALID_DATE_FORMAT`,statusCode:400},INVALID_PASSWORD:{message:G.Apikit.Errors.Validation.InvalidPassword,code:`INVALID_PASSWORD`,statusCode:403},INVALID_PASSWORD_NEW_SAME_AS_OLD:{message:G.Apikit.Errors.Validation.InvalidPasswordNewSameAsOld,code:`INVALID_PASSWORD_NEW_SAME_AS_OLD`,statusCode:409},INVALID_PHONE_NUMBER_FORMAT:{message:G.Apikit.Errors.Validation.InvalidPhoneNumberFormat,code:`INVALID_PHONE_NUMBER_FORMAT`,statusCode:400},INVALID_PHONE_NEW_SAME_AS_OLD:{message:G.Apikit.Errors.Validation.InvalidPhoneNewSameAsOld,code:`INVALID_PHONE_NEW_SAME_AS_OLD`,statusCode:409},INVALID_EMAIL_FORMAT:{message:G.Apikit.Errors.Validation.InvalidEmailFormat,code:`INVALID_EMAIL_FORMAT`,statusCode:400},INVALID_EMAIL_NEW_SAME_AS_OLD:{message:G.Apikit.Errors.Validation.InvalidEmailNewSameAsOld,code:`INVALID_EMAIL_NEW_SAME_AS_OLD`,statusCode:409}}),rn=J({UNSUPPORTED_FORMAT:{message:G.Apikit.Errors.Format.Unsupported,code:`UNSUPPORTED_FORMAT`,statusCode:400},MAX_SIZE_EXCEEDED:{message:G.Apikit.Errors.Format.MaxSizeExceeded,code:`MAX_SIZE_EXCEEDED`,statusCode:413}}),an=J({MAX_SIZE_EXCEEDED:{message:G.Apikit.Errors.Image.MaxSizeExceeded,code:`IMAGE_MAX_SIZE_EXCEEDED`,statusCode:413}}),on=J({Common:Qt,Server:$t,Limit:en,Authorization:tn,Validation:nn,Format:rn,Image:an});function sn(e){let t=new Set;cn(e,e=>{if(t.has(e.message))throw Error(`Duplicate API error message key: ${e.message}`);t.add(e.message)})}function cn(e,t){for(let n of Object.values(e)){if(U(n)){t(n);continue}cn(n,t)}}const Y=ln(on);function ln(e){return{codes:e,make(t,n={}){let r=dn(e,t);if(!r)throw Error(`Invalid API error code path: ${t}`);return un(r,n)},extend(t){let n=(0,m.default)({},e,t);return J(n),ln(n)}}}function un(e,t){let{overrideMessage:n,details:r,i18n:i}=t,a=Zt.translateKey(e.message,{overrideMessage:n,i18n:i});return new H({code:e.code,statusCode:e.statusCode,message:a,details:r})}function dn(e,t){let n=t.split(`.`),r=e;for(let e of n){if(!r||U(r))return;r=r[e]}if(!(!r||!U(r)))return r}var fn=class{mimeType;constructor(e){if(e.includes(`/`)){if(!p.default.extension(e))throw Y.make(`Format.UNSUPPORTED_FORMAT`);this.mimeType=e;return}let t=p.default.lookup(e);if(!t)throw Y.make(`Format.UNSUPPORTED_FORMAT`);this.mimeType=t}get value(){return this.mimeType}get extension(){let e=p.default.extension(this.mimeType);if(!e)throw Y.make(`Format.UNSUPPORTED_FORMAT`);return e}equals(e){return this.mimeType===e.value}},pn=class{value;constructor(e){this.value=e}apply(e){return typeof e==`function`?this.value=e(this.value):this.applyTransformations(e),this}filter(e=e=>e!==void 0){let t=n=>{if(Array.isArray(n)){let r=n.map(t).filter(e);return r.length>0?r:void 0}if((0,l.isPlainObject)(n)){let r=Object.entries(n).map(([e,n])=>[e,t(n)]).filter(([t,n])=>e(n));return r.length>0?Object.fromEntries(r):void 0}return e(n)?n:void 0};return this.value=t(this.value),this}exec(){return this.value}applyTransformations(e){(0,l.isObject)(this.value)&&(this.value=Object.fromEntries(Object.entries(this.value).map(([t,n])=>[t,e[t]?.(n)??n])))}};let mn=class{format(e){return new pn(e)}};mn=N([(0,f.injectable)()],mn);let hn=class{normalizeFields(e){let t={};for(let[n,r]of Object.entries(e))t[n]=this.normalizeValue(r,n);return t}normalizeValue(e,t){if(e===void 0)return;if(e===null)return null;if(!(0,l.isNonEmptyString)(e))return e;let n=e.trim();if(n===``)return e;if(n===`null`)return null;if(n===`true`)return!0;if(n===`false`)return!1;if(!Number.isNaN(Number(n)))return Number(n);try{return JSON.parse(n)}catch{return e}}};hn=N([(0,f.injectable)()],hn);var gn=class{assemble(e){e.bind(F.DI.Formatter.Controller).to(mn),e.bind(F.DI.Formatter.MultipartController).to(hn)}};const X={maxStringLength:4096,randomIntegerRangeLimit:2**48},_n={length:8,alphabet:`alphanumeric`},vn={decimal:`0123456789`,lowercase:`abcdefghijklmnopqrstuvwxyz`,uppercase:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`,letters:`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`,alphanumeric:`0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`,hex:`0123456789abcdef`,base64:`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,base64url:`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`};let yn=class{generateNumber(e){return this.assertGenerateNumberOptions(e),e.min===e.max?e.min:(0,_.randomInt)(e.min,e.max+1)}generateString(e=_n){let t=e.length??_n.length,n=this.resolveAlphabet(e.alphabet??_n.alphabet);this.assertStringLength(t),this.assertAlphabet(n);let r=``;for(let e=0;e<t;e++)r+=n.charAt((0,_.randomInt)(0,n.length));return r}generateUuidV4(){return(0,le.v4)()}generateUuidV7(){return(0,le.v7)()}resolveAlphabet(e){return typeof e==`string`?vn[e]:e.characters}assertGenerateNumberOptions(e){if(!Number.isSafeInteger(e.min))throw Error(`GenerateNumberOptions.min must be a safe integer`);if(!Number.isSafeInteger(e.max))throw Error(`GenerateNumberOptions.max must be a safe integer`);if(e.max<e.min)throw Error(`GenerateNumberOptions.max must be greater than or equal to min`);if(e.max===2**53-1)throw Error(`GenerateNumberOptions.max must be lower than Number.MAX_SAFE_INTEGER`);if(e.max-e.min>=X.randomIntegerRangeLimit)throw Error(`GenerateNumberOptions range must be lower than ${X.randomIntegerRangeLimit}`)}assertStringLength(e){if(!Number.isSafeInteger(e))throw Error(`GenerateStringOptions.length must be a safe integer`);if(e<=0)throw Error(`GenerateStringOptions.length must be greater than 0`);if(e>X.maxStringLength)throw Error(`GenerateStringOptions.length must be lower than or equal to ${X.maxStringLength}`)}assertAlphabet(e){if(e.length<2)throw Error(`GenerateStringOptions.alphabet must contain at least 2 characters`);if(!/^[!-~]+$/.test(e))throw Error(`GenerateStringOptions.alphabet must contain printable ASCII characters without whitespace`);if(new Set(e).size!==e.length)throw Error(`GenerateStringOptions.alphabet must not contain duplicate characters`)}};yn=N([(0,f.injectable)()],yn);var bn=class{assemble(e){e.bind(F.DI.Generator.RandomValueGenerator).to(yn)}},xn=class{assemble(e){e.bind(F.DI.I18n.Controller).to(jt)}};let Sn=class{formatter;constructor(e){this.formatter=e}async processBufferToBuffer(e,t){let{processed:n,type:r}=await this.transform((0,v.default)(e),t);return{buffer:await n.toBuffer(),type:r}}async processBufferToStream(e,t){let{processed:n,type:r}=await this.transform((0,v.default)(e),t);return{stream:this.asReadable(n),type:r}}async processStreamToBuffer(e,t){let n=(0,v.default)();await(0,de.pipeline)(e,n);let{processed:r,type:i}=await this.transform(n,t);return{buffer:await r.toBuffer(),type:i}}async processStreamToStream(e,t){let n=(0,v.default)();await(0,de.pipeline)(e,n);let{processed:r,type:i}=await this.transform(n,t);return{stream:this.asReadable(r),type:i}}async transform(e,t){let n=t??this.makeDefaultOptions(),r;try{r=await e.metadata()}catch{throw Y.make(`Format.UNSUPPORTED_FORMAT`,{details:`Invalid or unsupported image file`})}this.validateMaximumSize(r.size,n.maximumSize),this.validateInputFormat(r.format,n.allowedInputFormats);let i=await this.applyNormalization(e,r,n),a=this.toSharpFormat(n.outputFormat),{sharp:o}=n;i=o?.toFormat?i.toFormat(a,o.toFormat):i.toFormat(a),o?.configure&&(i=o.configure(i));let s=this.toFormatType(n.outputFormat);return{processed:i,type:s}}validateInputFormat(e,t){if(!e||!v.default.format[e]?.input)throw Y.make(`Format.UNSUPPORTED_FORMAT`,{details:`Unsupported input format: ${e}`});if(t&&!t.includes(e))throw Y.make(`Format.UNSUPPORTED_FORMAT`,{details:`Format not allowed: ${e}`})}validateMaximumSize(e,t){if(!(!t||!e)&&e>t){let n=this.formatter.formatBytes(t,{inputUnit:l.ByteUnit.Byte,outputUnit:`auto`,decimals:1});throw Y.make(`Image.MAX_SIZE_EXCEEDED`,{i18n:{specs:{maxSize:n.value,unit:n.unit}},details:`current=${e}B, max=${t}B, exceeded=${e-t}B`})}}toSharpFormat(e){return e}toFormatType(e){if(!this.getFormatInfo(e)?.output){let t=`Cannot encode output format: ${e}`;throw Y.make(`Format.UNSUPPORTED_FORMAT`,{details:t})}return new fn(e)}getFormatInfo(e){return v.default.format[e]}asReadable(e){let t=new ue.PassThrough;return e.on(`error`,e=>t.destroy(e)),e.pipe(t),t}async applyNormalization(e,t,n){if(n.minWidth==null&&n.maxWidth==null&&n.minAspectRatio==null&&n.maxAspectRatio==null)return n.sharp?.resize&&(e=e.resize(n.sharp.resize)),e;this.validateConstraints(n);let r=t.width??0,i=t.height??0;if(!(r>0&&i>0))throw Y.make(`Validation.INVALID_PROPERTIES`,{details:`Missing image dimensions.`});let a=n.aspectRatioTolerance??0,o=r/i,s=this.pickTargetAspectRatio(o,n.minAspectRatio,n.maxAspectRatio,a),c=r;if(s!==void 0){let t=o>s,n=t?Math.max(1,Math.round(i*s)):r,a=t?i:Math.max(1,Math.round(r/s)),l=Math.max(0,Math.floor((r-n)/2)),u=Math.max(0,Math.floor((i-a)/2));e=e.extract({left:l,top:u,width:n,height:a}),c=n}let{minWidth:l,maxWidth:u}=n,d=typeof u==`number`&&c>u?u:typeof l==`number`&&c<l?l:c;return d!==c&&(e=e.resize({width:d})),e}validateConstraints(e){let t=[],n=e=>Number.isFinite(e)&&e>0;if(e.minWidth!=null&&!n(e.minWidth)&&t.push(`minWidth must be > 0`),e.maxWidth!=null&&!n(e.maxWidth)&&t.push(`maxWidth must be > 0`),e.minAspectRatio!=null&&!n(e.minAspectRatio)&&t.push(`minAspectRatio must be > 0`),e.maxAspectRatio!=null&&!n(e.maxAspectRatio)&&t.push(`maxAspectRatio must be > 0`),e.aspectRatioTolerance!=null&&!(e=>Number.isFinite(e)&&e>=0)(e.aspectRatioTolerance)&&t.push(`aspectRatioTolerance must be ≥ 0`),e.minWidth!=null&&e.maxWidth!=null&&e.minWidth>e.maxWidth&&t.push(`minWidth must be ≤ maxWidth`),e.minAspectRatio!=null&&e.maxAspectRatio!=null&&e.minAspectRatio>e.maxAspectRatio&&t.push(`minAspectRatio must be ≤ maxAspectRatio`),t.length)throw Y.make(`Validation.INVALID_PROPERTIES`,{details:t.join(`; `)})}pickTargetAspectRatio(e,t,n,r=0){if(typeof t==`number`&&e<t-r)return t;if(typeof n==`number`&&e>n+r)return n}makeDefaultOptions(){return{outputFormat:`jpeg`,maximumSize:7864320,minWidth:320,maxWidth:1080,minAspectRatio:.8,maxAspectRatio:1.91,aspectRatioTolerance:.01,sharp:{toFormat:{quality:82,progressive:!0}}}}};Sn=N([(0,f.injectable)(),L(0,(0,f.inject)(l.CoreSymbols.DI.Formatter.UnitController)),I(`design:paramtypes`,[Object])],Sn);var Cn=class{assemble(e){e.bind(F.DI.Image.NormalizationController).to(Sn)}};let wn=class{normalizeEmail(e){let t=e.trim();if(!b.default.isEmail(t))throw Y.make(`Validation.INVALID_EMAIL_FORMAT`);let n=b.default.normalizeEmail(t,{all_lowercase:!0,gmail_lowercase:!0,gmail_remove_dots:!0,gmail_remove_subaddress:!0,gmail_convert_googlemaildotcom:!0,outlookdotcom_lowercase:!0,outlookdotcom_remove_subaddress:!0,yahoo_lowercase:!0,yahoo_remove_subaddress:!0,icloud_lowercase:!0,icloud_remove_subaddress:!0});if(!n)throw Y.make(`Validation.INVALID_EMAIL_FORMAT`);return n}normalizePhoneToE164(e){try{return(0,y.parsePhoneNumberWithError)(e).format(`E.164`)}catch{throw Y.make(`Validation.INVALID_PHONE_NUMBER_FORMAT`)}}normalizePhoneToInternational(e){try{return(0,y.parsePhoneNumberWithError)(e).format(`INTERNATIONAL`)}catch{throw Y.make(`Validation.INVALID_PHONE_NUMBER_FORMAT`)}}normalizePhoneToNational(e){try{return(0,y.parsePhoneNumberWithError)(e).format(`NATIONAL`).replace(/[^\d]/g,``)}catch{throw Y.make(`Validation.INVALID_PHONE_NUMBER_FORMAT`)}}};wn=N([(0,f.injectable)()],wn);var Tn=class{assemble(e){e.bind(F.DI.Normalization.Controller).to(wn)}};const En=`${bt.name}.ApiKit.Internal.DI`,Dn={DI:{Notification:{ChannelController:Symbol.for(`${En}.Notification.ChannelController`)}}},On=`[Notification]`;let kn=function(e){return e.Telegram=`telegram`,e}({});const An=`${On}:Telegram`;var jn=class{configuration;channel=`telegram`;constructor(e){this.configuration=e}async send(e){if(e.type!==this.channel)throw Error(`${An} Invalid channel request.`);let t;try{t=await fetch(`https://api.telegram.org/bot${this.configuration.token}/sendMessage`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({chat_id:this.configuration.chatId,text:Mn(e.payload)})})}catch{throw Error(`${An} Request failed.`)}if(!t.ok)throw Error(`${An} Request failed with status ${t.status}.`)}};function Mn(e){return e.title===void 0?e.message:`${e.title}\n\n${e.message}`}let Nn=class{logger;channelControllers;constructor(e,t){this.logger=t,this.channelControllers=Pn(e??[])}async send(e,t={}){let n=t.throwOnFailure===!0,r=[];for(let t of e.channels)r.push(await this.deliver(t,n));return{deliveries:r}}async deliver(e,t){let n={channel:e.type,status:`failed`};try{let t=this.channelControllers.get(e.type);if(!t)throw Error(`${On} Channel "${e.type}" is unavailable.`);return await t.send(e),{channel:e.type,status:`sent`}}catch(r){if(this.logger.error(`${On} Delivery failed.`,{error:r,details:{channel:e.type}}),t)throw r;return n}}};Nn=N([(0,f.injectable)(),L(0,(0,f.multiInject)(Dn.DI.Notification.ChannelController)),L(0,(0,f.optional)()),L(1,(0,f.inject)(l.CoreSymbols.DI.Logger)),I(`design:paramtypes`,[Object,Object])],Nn);function Pn(e){let t=new Map;for(let n of e){if(t.has(n.channel))throw Error(`${On} Channel "${n.channel}" is registered more than once.`);t.set(n.channel,n)}return t}var Fn=class{assemble(e){this.assembleChannelControllers(e),e.bind(F.DI.Notification.Controller).to(Nn).inSingletonScope()}assembleChannelControllers(e){let t=global.apikit.notificationConfig;if(!t.enabled)return;let n=t.channels.telegram;n&&e.bind(Dn.DI.Notification.ChannelController).toConstantValue(new jn(n))}};let In=class{makeResponse(e,t,n){return{description:e,content:this.constructContent(t),headers:n?this.constructHeaders(n):void 0}}constructContent(e){return Object.entries(e).reduce((e,[t,{schema:n,examples:r}])=>(e[t]={schema:n,examples:r?this.constructExamples(r):void 0},e),{})}constructExamples(e){return Object.entries(e).reduce((e,[t,n])=>(e[t]={summary:n.summary,value:n.value},e),{})}constructHeaders(e){return e||{}}};In=N([(0,f.injectable)()],In);var Ln=class{assemble(e){e.bind(F.DI.OpenAPI.SchemaController).to(In)}};let Z=class{digest(e,t){let n=(0,_.createHash)(this.resolveDigestAlgorithm(t.algorithm)).update(e,`utf8`).digest();return this.encode(n,t.outputEncoding)}mac(e,t){let n=(0,_.createHmac)(this.resolveMacAlgorithm(t.algorithm),t.secret).update(e,`utf8`).digest();return this.encode(n,t.outputEncoding)}verifyMac(e,t,n){let r=this.mac(e,n);return this.timingSafeEqual(r,t)}async hashPassword(e,t){if(t.algorithm===`argon2id`)return x.hash(e,{type:x.argon2id,memoryCost:t.memoryCost,timeCost:t.timeCost,parallelism:t.parallelism})}async verifyPassword(e,t){try{return await x.verify(t,e)}catch{return!1}}timingSafeEqual(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&(0,_.timingSafeEqual)(n,r)}encode(e,t){switch(t){case`hex`:return e.toString(`hex`);case`base64url`:return e.toString(`base64url`)}}resolveDigestAlgorithm(e){switch(e){case`sha256`:return`sha256`;case`sha384`:return`sha384`;case`sha512`:return`sha512`}}resolveMacAlgorithm(e){switch(e){case`hmac-sha256`:return`sha256`;case`hmac-sha384`:return`sha384`;case`hmac-sha512`:return`sha512`}}};Z=N([(0,f.injectable)()],Z);var Rn=class{_value;_payload;constructor(e,t){this._value=e,this._payload=t}get value(){return this._value}get payload(){return this._payload}getField(e){return(0,l.ignoreError)(()=>this._payload[e]).orDefault(void 0)}},zn=class{assemble(e){e.bind(F.DI.Security.CryptographyController).to(Z)}},Bn=(0,S.default)(async(e,t)=>{let n=t.apikitController.basicAuth;if(!n.enabled)return;let r=n.username,i=n.password;if(!r||!i)throw Error(`[ApiKit:BasicAuth] username and password are required when basic auth is enabled.`);await e.register(fe.default,{validate:Vn(r,i),authenticate:n.authenticate,proxyMode:n.proxyMode,header:n.header,strictCredentials:n.strictCredentials})},{name:`apikit-basic-auth`});function Vn(e,t){return async(n,r)=>{Hn({inputUsername:n,inputPassword:r,expectedUsername:e,expectedPassword:t})}}function Hn(e){let t=Un(e.inputUsername,e.expectedUsername),n=Un(e.inputPassword,e.expectedPassword);if(!t||!n)throw Error(`Access denied`)}function Un(e,t){let n=Buffer.isBuffer(e)?e:Buffer.from(e,`utf-8`),r=Buffer.isBuffer(t)?t:Buffer.from(t,`utf-8`);return n.length===r.length?_.default.timingSafeEqual(n,r):(_.default.timingSafeEqual(n,n),!1)}var Wn=(0,S.default)(async e=>{await e.register(g.default,{hook:`onRequest`,parseOptions:{}})},{name:`apikit-cookie`}),Gn=(0,S.default)(async(e,t)=>{let n=t.apikitController.cors;n.enabled&&await e.register(pe.default,Kn(n))},{name:`apikit-cors`});function Kn(e){let t=e.allowAllOrigins?!0:qn(e.options.origin,{includeWwwSubdomain:e.includeWwwSubdomain});return{...e.options,origin:t}}function qn(e,t){return e&&(typeof e==`string`?Xn(e,t):Array.isArray(e)?Jn(e,t):e)}function Jn(e,t){let n=[];for(let r of e)Yn(n,r,t);return Qn(n)}function Yn(e,t,n){if(typeof t==`string`){e.push(...Xn(t,n));return}if(t instanceof RegExp||typeof t==`boolean`){e.push(t);return}if(Array.isArray(t))for(let r of t)Yn(e,r,n)}function Xn(e,t){let n=Zn(e);if(!n)return[e];if(!t.includeWwwSubdomain)return[n];let{protocol:r,host:i}=new URL(n);return/^[a-zA-Z][a-zA-Z0-9.-]*$/.test(i)?[n,`${r}//${i.startsWith(`www.`)?i:`www.${i}`}`]:[n]}function Zn(e){try{let{protocol:t,host:n}=new URL(e);return`${t}//${n}`}catch{return null}}function Qn(e){let t=new Set,n=[];for(let r of e){if(typeof r!=`string`){n.push(r);continue}t.has(r)||(t.add(r),n.push(r))}return n}const $n=`[ApiKit:Health]`;var er=(0,S.default)(async(e,t)=>{let n=t.apikitController.health;if(!n.enabled){e.log.info(`${$n} Disabled — skipping`);return}await e.register(C.default,{exposeStatusRoute:n.url,maxEventLoopDelay:n.pressure.maxEventLoopDelay,maxHeapUsedBytes:n.pressure.maxHeapUsedBytes,maxRssBytes:n.pressure.maxRssBytes,maxEventLoopUtilization:n.pressure.maxEventLoopUtilization}),e.log.info(`${$n} Enabled`)},{name:`apikit-health`}),tr=(0,S.default)(async e=>{await e.register(w.default,{strict:!1,isAWS:!1})},{name:`apikit-ip`});const nr=`[ApiKit:Metrics]`;var rr=(0,S.default)(async(e,t)=>{let n=t.apikitController.metrics;if(!n.enabled){e.log.info(`${nr} Disabled — skipping`);return}await e.register(T.default,{endpoint:n.endpoint,name:n.name,defaultMetrics:n.defaultMetrics,routeMetrics:n.routeMetrics,clearRegisterOnInit:n.clearRegisterOnInit}),e.log.info(`${nr} Enabled`)},{name:`apikit-metrics`}),ir=(0,S.default)(async(e,t)=>{let n=t.apikitController.multipart;n.enabled&&await e.register(me.default,n.options)},{name:`apikit-multipart`});function ar(e){let t=e.apikitController,n=t.logger;return n.enabled?ur([t.health.enabled?t.health.url:void 0,t.metrics.enabled?sr(t.metrics.endpoint):void 0,...n.request?.ignoredPaths??[]]):[]}function or(e,t){let n=lr(cr(e));return t.some(e=>{let t=lr(e);return n===t||n.startsWith(`${t}/`)})}function sr(e){if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`url`in e){let t=e.url;return typeof t==`string`?t:void 0}}function cr(e){return e.split(/[?#]/,1)[0]||`/`}function lr(e){let t=e.trim(),n=t.startsWith(`/`)?t:`/${t}`;return n.length>1?n.replace(/\/+$/,``):n}function ur(e){return[...new Set(e.filter(e=>!!e?.trim()).map(lr).filter(e=>e!==`/`))]}const dr=`[ApiKit:Request]`,fr=`[ApiKit:Response]`;var pr=(0,S.default)(async(e,t)=>{let n=t.logger,r=t.apikitController.logger,i=t.apikitController.isDebug,a=ar(t);r.enabled&&(e.addHook(`onRequest`,async e=>{if(or(e.url,a))return;let t=new q(e.metadata);(0,l.ignoreError)(()=>{n.info(`${dr} onRequest`,{metadata:t})})}),e.addHook(`preValidation`,async e=>{if(or(e.url,a)||!i)return;let t=new q({requestId:e.metadata.requestId});(0,l.ignoreError)(()=>{n.debug(`${dr} preValidation`,{metadata:t,details:{body:mr(e.body,e.headers)}})})}),e.addHook(`onSend`,async(e,t,r)=>(or(e.url,a)||(0,l.ignoreError)(()=>{let a=new q({requestId:e.metadata.requestId}),o={elapsedTime:t.elapsedTime,statusCode:t.statusCode};i?n.debug(`${fr} onSend`,{metadata:a,details:{...o,body:mr(r,t.getHeaders())}}):n.info(`${fr} onSend`,{metadata:a,details:o})}),r)))},{name:`apikit-request-logger`,dependencies:[`apikit-request-metadata`]});function mr(e,t){return String(t?.[K.contentType]??``).toLowerCase().includes(`multipart/form-data`)?`[Multipart]`:hr(e)}function hr(e,t=new WeakSet,n=0){if(!(0,l.isDefinedAndNotNull)(e))return`[Not provided]`;if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}if(typeof e==`number`||typeof e==`boolean`)return e;if(typeof e==`bigint`||typeof e==`symbol`)return e.toString();if(typeof e==`function`)return`[Function: ${e.name||`anonymous`}]`;if(Buffer.isBuffer(e))return`[Buffer]`;if(e instanceof ue.Readable)return`[Stream]`;if(typeof e==`object`&&e&&`file`in e&&`filename`in e)return`[File]`;if(typeof e==`object`){if(t.has(e))return`[Circular]`;if(t.add(e),Array.isArray(e))return e.map(e=>hr(e,t,n+1));let r={};for(let[i,a]of Object.entries(e))r[i]=hr(a,t,n+1);return r}return String(e)}var gr=(0,S.default)(async(e,t)=>{let n=t.i18nController;e.addHook(`onRequest`,async e=>{e.metadata={requestId:e.id,method:e.method,url:e.url,protocol:e.protocol,query:e.query,params:e.params,ip:(0,l.isNullOrEmpty)(e.ip)?e.ips?.[0]??e.ip:e.ip,locale:n.parseLocale(e.headers[K.acceptLanguage]),headers:e.headers}})},{name:`apikit-request-metadata`}),_r=(0,S.default)(async e=>{e.addHook(`onRequest`,(e,t,n)=>{let r=e.metadata;Yt.run({metadata:r},()=>{n()})})},{name:`apikit-request-scope`,dependencies:[`apikit-request-metadata`]});const vr=`[ApiKit:Static]`,Q={basicAuth:Bn,cookie:Wn,cors:Gn,health:er,ip:tr,metrics:rr,multipart:ir,requestLogger:pr,requestMetadata:gr,requestScope:_r,staticFiles:(0,S.default)(async(e,t)=>{let n=t.apikitController.staticFiles;if(!n.enabled){e.log.info(`${vr} Disabled — skipping`);return}if(!n.publicDirectory){let t=`${vr} publicDirectory is required when static files are enabled.`;throw e.log.error(t),Error(t)}await e.register(he.default,{root:n.publicDirectory,prefix:n.routePrefix,maxAge:n.maxAge,dotfiles:n.dotfiles,etag:n.etag,immutable:n.immutable,decorateReply:n.decorateReply,preCompressed:n.preCompressed}),e.log.info(`${vr} Enabled from ${n.publicDirectory}`)},{name:`apikit-static`}),view:(0,S.default)(async e=>{await e.register(ge.default,{engine:{ejs:re.default}})},{name:`apikit-view`})},$=`[Server]`;let yr=class{i18n;logger;configuration;server;constructor(e,t,n){this.i18n=e,this.logger=t,this.configuration=n,this.server=(0,_e.default)({loggerInstance:this.logger.instance,logController:new _e.LogController({disableRequestLogging:!0,requestIdLogLabel:`requestId`}),ajv:{customOptions:{strict:!0,keywords:[`example`]}},trustProxy:this.configuration.server.trustProxy})}get instance(){return this.server}async preparePlugins(e=async()=>{}){let t={i18nController:this.i18n,logger:this.logger,apikitController:this.configuration},n=[Q.cookie,Q.ip,Q.requestMetadata,Q.requestScope,Q.requestLogger,Q.cors,Q.multipart,Q.basicAuth,Q.health,Q.metrics],r=[Q.staticFiles,Q.view];for(let e of n)await this.server.register(e,t);await e(this.server,t);for(let e of r)await this.server.register(e,t)}async prepare(e){await this.configureErrorHandler(),await this.configureShutdownHandler(e)}async start(){let e=this.configuration.server.host,t=this.configuration.server.port;if(!Number.isInteger(t)||t<=0||t>65535)throw Error(`Invalid server port "${t}", must be an integer 1-65535.`);await this.server.ready(),await this.server.listen({host:e,port:t,listenTextResolver:e=>`${$} Listening at ${e}`}),this.logger.info(`${$} Debug mode ${this.configuration.isDebug?`ON`:`OFF`}`),this.logger.info(`${$} Started on ${e}:${t}`)}async configureErrorHandler(){this.server.setErrorHandler(async(e,t,n)=>{let r=Array.isArray(e.validation),i=!e.statusCode||e.statusCode===500,a=Y.make(`Server.INTERNAL_SERVER_ERROR`);switch(this.configuration.isDebug&&this.logger.debug(`${$} Error Handler:`,{error:e}),!0){case e instanceof H:return n.status(e.statusCode).send(e.toJSON());case r:{let t=Y.make(`Validation.BAD_REQUEST`),r=e.statusCode||t.statusCode,i=new H({statusCode:r,code:t.code,message:t.message});return n.status(r).send(i.toJSON())}case i:return this.logger.error(`${$} Internal Server Error`,{flag:c.LogFlag.Important,metadata:new q({requestId:t.metadata.requestId}),error:e}),n.status(500).send(a.toJSON());default:{let t=e.statusCode||500,r=new H({statusCode:t,code:e.code||e.name||a.code,message:e.message||a.message});return n.status(t).send(r.toJSON())}}})}async configureShutdownHandler(e){let t=async(t,n)=>{if(this.logger.warn(`${$} ⛔ Shutdown: ${t}`),e)try{await e()}catch(e){this.logger.error(`${$} ⚠️ Shutdown hook failed`,{error:e})}try{await this.server.close(),this.logger.info(`${$} ✅ Closed`)}catch(e){this.logger.error(`${$} ❌ Close failed`,{error:e})}n&&this.logger.error(`${$} 🚨 Fatal error during shutdown`,{error:n}),process.exit(+!!n)},n=[[`SIGINT`,()=>t(`SIGINT`)],[`SIGTERM`,()=>t(`SIGTERM`)],[`uncaughtException`,e=>t(`uncaughtException`,e)],[`unhandledRejection`,e=>t(`unhandledRejection`,e)]];for(let[e,t]of n)process.on(e,t)}};yr=N([(0,f.injectable)(),L(0,(0,f.inject)(F.DI.I18n.Controller)),L(1,(0,f.inject)(l.CoreSymbols.DI.Logger)),L(2,(0,f.inject)(F.DI.Configuration.Controller)),I(`design:paramtypes`,[Object,Object,Object])],yr);const br=`[ApiKit:Request]`;let xr=class{logger;responseController;constructor(e,t){this.logger=e,this.responseController=t}handler(e,t={}){return async(n,r)=>{try{let i=await e(n,t);return await this.responseController.sendResponse(n,r,i)}catch(e){throw await this.logError(n,e),e}}}preHandler(e,t={}){return async(n,r)=>{try{let i=await e(n,t);if(i)return await this.responseController.sendResponse(n,r,i)}catch(e){throw await this.logError(n,e),e}}}async logError(e,t){await(0,l.ignoreErrorAsync)(()=>{let n=e.metadata.requestId;t instanceof H?this.logger.info(`${br} Api error response`,{error:t,metadata:new q({requestId:n})}):this.logger.error(`${br} Unexpected error`,{flag:c.LogFlag.Important,error:t,metadata:new q({requestId:n})})})}};xr=N([(0,f.injectable)(),L(0,(0,f.inject)(l.CoreSymbols.DI.Logger)),L(1,(0,f.inject)(F.DI.Server.ResponseController)),I(`design:paramtypes`,[Object,Object])],xr);const Sr=`[ApiKit:Response]`;let Cr=class{logger;constructor(e){this.logger=e}async sendResponse(e,t,n){switch(n.responseType){case`JSON`:return await this.sendJSONResponse(e,t,n);case`File`:return await this.sendFileResponse(e,t,n);default:throw Error(`${Sr} Unsupported response type`)}}async sendJSONResponse(e,t,n){let r=this.createResponseHeaders(n.headers);return t.headers(r).type(`application/json`).status(n.statusCode).send(n.data)}async sendFileResponse(e,t,n){let r=this.createResponseHeaders(n.headers);t.headers(r).type(`text/html`).status(n.statusCode);try{if(n.shouldRender){let e=await t.viewAsync(n.filePath,n.data);return t.send(e)}return t.sendFile(n.filePath)}catch(t){let n=e.metadata.requestId;throw this.logger.error(`${Sr} File response failed`,{error:t,metadata:new q({requestId:n})}),t}}createResponseHeaders(e){return{[K.cacheControl]:`no-store`,...e||{}}}};Cr=N([(0,f.injectable)(),L(0,(0,f.inject)(l.CoreSymbols.DI.Logger)),I(`design:paramtypes`,[Object])],Cr);var wr=class{assemble(e){e.bind(F.DI.Server.Controller).to(yr).inSingletonScope(),e.bind(F.DI.Server.RequestController).to(xr).inSingletonScope(),e.bind(F.DI.Server.ResponseController).to(Cr).inSingletonScope()}};let Tr=class{configuration;logger;constructor(e,t){this.configuration=e,this.logger=t}validate(e,t){try{return e.parse(t)}catch(e){this.handleError(e)}}async validateAsync(e,t){try{return await e.parseAsync(t)}catch(e){this.handleError(e)}}handleError(e){if(e instanceof ve.ZodError){this.configuration.isDebug&&this.logger.debug(`[ApiKit:Validation] Dto validation failed`,{details:{tree:ve.z.treeifyError(e)}});let t=this.buildValidationDetails(e),n=this.buildValidationMessage(e);throw Y.make(`Validation.INVALID_PROPERTIES`,{details:t,overrideMessage:n})}throw e}buildValidationDetails(e){return{issues:e.issues.map(e=>({code:e.code,path:e.path.map(e=>typeof e==`number`?e:String(e)),message:e.message}))}}buildValidationMessage(e){for(let t of e.issues){if(t.code!==`custom`||!t.params)continue;let e=t.params;if(!e?.i18n?.key)continue;let{key:n,values:r}=e.i18n;return r?Xt.t(n,r):Xt.t(n)}return null}};Tr=N([(0,f.injectable)(),L(0,(0,f.inject)(F.DI.Configuration.Controller)),L(1,(0,f.inject)(l.CoreSymbols.DI.Logger)),I(`design:paramtypes`,[Object,Object])],Tr);let Er=class{isValidEmail(e){return!!e&&b.default.isEmail(e)}isValidEmailThrowing(e){if(!this.isValidEmail(e))throw Y.make(`Validation.INVALID_EMAIL_FORMAT`)}isValidPhoneNumber(e,t){if(!e)return!1;let n;return n=t?(0,y.parsePhoneNumberFromString)(e,t):(0,y.parsePhoneNumberFromString)(e),!!n?.isValid()}isValidPhoneNumberThrowing(e,t){if(!this.isValidPhoneNumber(e,t))throw Y.make(`Validation.INVALID_PHONE_NUMBER_FORMAT`)}isValidCode(e){return!!e&&/^\d{6}$/.test(e)}isValidCodeThrowing(e){if(!this.isValidCode(e))throw Y.make(`Validation.INVALID_FORMAT`,{details:`Input is not a valid code`})}isEmail(e){return!!e&&b.default.isEmail(e)}isEmailThrowing(e){if(!this.isEmail(e))throw Y.make(`Validation.INVALID_EMAIL_FORMAT`)}isPhoneNumber(e){return!!e&&b.default.isMobilePhone(e)}isPhoneNumberThrowing(e){if(!this.isPhoneNumber(e))throw Y.make(`Validation.INVALID_PHONE_NUMBER_FORMAT`)}isNumber(e){return typeof e==`number`&&!isNaN(e)}isNumberThrowing(e){if(!this.isNumber(e))throw Y.make(`Validation.INVALID_PROPERTIES`,{details:`Input is not a valid number`})}isString(e){return typeof e==`string`}isStringThrowing(e){if(!this.isString(e))throw Y.make(`Validation.INVALID_PROPERTIES`,{details:`Input is not a valid string`})}isEmptyString(e){return e==null||e.trim()===``}isEmptyStringThrowing(e){if(!this.isEmptyString(e))throw Y.make(`Validation.INVALID_PROPERTIES`,{details:`Input is not an empty string`})}isNonEmptyString(e){return this.isString(e)&&!this.isEmptyString(e)}isNonEmptyStringThrowing(e){let t=e;if(typeof t!=`string`||t.trim()===``)throw Y.make(`Validation.INVALID_PROPERTIES`,{details:`Input is empty or not a string`});return t}isValidDate(e){if(!e)return!1;let t=new Date(e);return!isNaN(t.getTime())}isValidDateThrowing(e){if(!this.isValidDate(e))throw Y.make(`Validation.INVALID_DATE_FORMAT`);return new Date(e)}};Er=N([(0,f.injectable)()],Er);var Dr=class{assemble(e){e.bind(F.DI.Validation.Controller).to(Er),e.bind(F.DI.Validation.DtoController).to(Tr)}};function Or(){return[new xt,new Ct,new Dt,new Ot,new gn,new bn,new xn,new Cn,new Tn,new Fn,new Ln,new zn,new wr,new Dr]}function kr(){let e=global.apikit.loggerConfig,t=e.enabled?{enabled:!0,debug:global.apikit.serverConfig.debug,transports:e.transports}:{enabled:!1,debug:global.apikit.serverConfig.debug};return[...(0,c.coreNodeAssembly)({logger:t}),...Or()]}exports.ApiError=H,exports.ApiErrorCodes=on,exports.ApiErrorFactory=Y,Object.defineProperty(exports,"ApiKitControllerImpl",{enumerable:!0,get:function(){return pt}}),exports.ApiKitL10n=G,exports.ApiKitL10nResource=W,exports.ApiKitSymbols=F,exports.AuthorizationErrors=tn,exports.BaseEmailTemplate=Et,exports.BasicAuthConfiguration=Ke,exports.BuildConfiguration=qe,exports.CommonErrors=Qt,exports.Cookie=Bt,exports.CorsConfiguration=Je,Object.defineProperty(exports,"CryptographyControllerImpl",{enumerable:!0,get:function(){return Z}}),exports.DEFAULT_GENERATE_STRING_OPTIONS=_n,Object.defineProperty(exports,"DtoValidationControllerImpl",{enumerable:!0,get:function(){return Tr}}),exports.EmailConfiguration=Xe,Object.defineProperty(exports,"EmailControllerImpl",{enumerable:!0,get:function(){return z}}),exports.FastifyPlugins=Q,exports.FileHttpResponse=Gt,exports.FormatErrors=rn,exports.FormatType=fn,exports.Formatter=pn,Object.defineProperty(exports,"FormatterControllerImpl",{enumerable:!0,get:function(){return mn}}),exports.HealthConfiguration=Ze,exports.HttpHeaders=K,exports.HttpMethod=Vt,exports.HttpResponse=Ut,exports.I18nConfiguration=$e,Object.defineProperty(exports,"I18nControllerImpl",{enumerable:!0,get:function(){return jt}}),exports.I18nFactory=Zt,exports.I18nProvider=Xt,exports.ImageErrors=an,Object.defineProperty(exports,"ImageNormalizationControllerImpl",{enumerable:!0,get:function(){return Sn}}),exports.JSONHttpResponse=Wt,exports.LimitErrors=en,exports.LoggerConfiguration=et,exports.MetricsConfiguration=it,Object.defineProperty(exports,"MongoDbQueryFormatterImpl",{enumerable:!0,get:function(){return St}}),exports.MultipartConfiguration=at,Object.defineProperty(exports,"MultipartFormatterControllerImpl",{enumerable:!0,get:function(){return hn}}),Object.defineProperty(exports,"NormalizationControllerImpl",{enumerable:!0,get:function(){return wn}}),exports.NotificationChannel=kn,exports.NotificationConfiguration=ot,Object.defineProperty(exports,"OpenAPISchemaControllerImpl",{enumerable:!0,get:function(){return In}}),exports.RANDOM_VALUE_GENERATOR_LIMITS=X,Object.defineProperty(exports,"RandomValueGeneratorImpl",{enumerable:!0,get:function(){return yn}}),Object.defineProperty(exports,"RequestControllerImpl",{enumerable:!0,get:function(){return xr}}),exports.RequestLogMetadata=q,exports.RequestScope=Yt,Object.defineProperty(exports,"ResponseControllerImpl",{enumerable:!0,get:function(){return Cr}}),exports.ResponseType=Ht,exports.ServerConfiguration=dt,Object.defineProperty(exports,"ServerControllerImpl",{enumerable:!0,get:function(){return yr}}),exports.ServerErrors=$t,exports.StaticFilesConfiguration=ft,Object.defineProperty(exports,"TemporaryFileRepositoryImpl",{enumerable:!0,get:function(){return V}}),exports.Token=Rn,Object.defineProperty(exports,"ValidationControllerImpl",{enumerable:!0,get:function(){return Er}}),exports.ValidationErrors=nn,exports.apikitAssembly=kr,exports.defineApiKit=mt,exports.defineConfiguration=O,exports.defineEnvironments=we,exports.defineErrors=J,exports.defineSource=Oe,Object.defineProperty(exports,"fastifyBasicAuth",{enumerable:!0,get:function(){return fe.default}}),Object.defineProperty(exports,"fastifyCookie",{enumerable:!0,get:function(){return g.default}}),Object.defineProperty(exports,"fastifyCors",{enumerable:!0,get:function(){return pe.default}}),Object.defineProperty(exports,"fastifyIp",{enumerable:!0,get:function(){return w.default}}),Object.defineProperty(exports,"fastifyMetrics",{enumerable:!0,get:function(){return T.default}}),Object.defineProperty(exports,"fastifyMultipart",{enumerable:!0,get:function(){return me.default}}),Object.defineProperty(exports,"fastifyStatic",{enumerable:!0,get:function(){return he.default}}),Object.defineProperty(exports,"fastifyUnderPressure",{enumerable:!0,get:function(){return C.default}}),Object.defineProperty(exports,"fastifyView",{enumerable:!0,get:function(){return ge.default}}),exports.field=E,Object.defineProperty(exports,"fp",{enumerable:!0,get:function(){return S.default}}),exports.isApiErrorDefinition=U,exports.loadApiKitContext=gt,Object.keys(l).forEach(function(e){e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:function(){return l[e]}})}),Object.keys(c).forEach(function(e){e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:function(){return c[e]}})});
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));require("reflect-metadata");let c=require("@buildplease/core/node"),l=require("@buildplease/core"),u=require("node:fs");u=s(u,1);let d=require("node:path");d=s(d,1);let ee=require("jiti"),f=require("inversify"),te=require("node:fs/promises");te=s(te,1);let ne=require("ejs");ne=s(ne,1);let re=require("nodemailer");re=s(re,1);let ie=require("node:os");ie=s(ie,1);let ae=require("node:stream"),oe=require("node:stream/promises"),p=require("mime-types");p=s(p,1);let m=require("lodash.merge");m=s(m,1);let h=require("i18next");h=s(h,1);let g=require("@fastify/cookie");g=s(g,1);let se=require("node:async_hooks"),_=require("node:crypto");_=s(_,1);let ce=require("uuid"),le=require("stream"),ue=require("stream/promises"),v=require("sharp");v=s(v,1);let y=require("libphonenumber-js"),b=require("validator");b=s(b,1);let x=require("argon2");x=s(x,1);let de=require("@fastify/basic-auth");de=s(de,1);let S=require("fastify-plugin");S=s(S,1);let C=require("@fastify/cors");C=s(C,1);let w=require("@fastify/under-pressure");w=s(w,1);let T=require("fastify-ip");T=s(T,1);let E=require("fastify-metrics");E=s(E,1);let D=require("@fastify/multipart");D=s(D,1);let O=require("@fastify/static");O=s(O,1);let k=require("@fastify/view");k=s(k,1);let A=require("fastify");A=s(A,1);let fe=require("zod");const j={build:{outDir:`.apikit`},logger:{enabled:!1},server:{debug:!1,trustProxy:!1},metrics:{enabled:!1,endpoint:`/metrics`,name:`metrics`,defaultMetrics:{enabled:!0},routeMetrics:{enabled:!0},clearRegisterOnInit:!1},health:{enabled:!0,url:`/health`,pressure:{maxEventLoopDelay:0,maxHeapUsedBytes:0,maxRssBytes:0,maxEventLoopUtilization:0}},notification:{enabled:!1},email:{enabled:!1,templatesPath:`./src/templates`,globals:{}},i18n:{resources:{},directories:[],files:[],defaultLanguage:`en`,fallbackLanguages:`en`,supportedLanguages:[`en`,`sk`,`cs`],load:`languageOnly`,preload:[`en`,`sk`,`cs`],nonExplicitSupportedLngs:!0,lowerCaseLng:!0,cleanCode:!0,defaultNamespace:`translation`,keySeparator:`.`,nsSeparator:`:`,pluralSeparator:`_`,contextSeparator:`_`},staticFiles:{enabled:!1,routePrefix:`/`,maxAge:3600,dotfiles:`ignore`,etag:!0,immutable:!0,decorateReply:!0,preCompressed:!1},basicAuth:{enabled:!1,authenticate:!1,proxyMode:!1,header:void 0,strictCredentials:void 0},cors:{enabled:!1,allowAllOrigins:!1,includeWwwSubdomain:!0,options:{methods:[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`OPTIONS`],credentials:!0,optionsSuccessStatus:200}},multipart:{enabled:!1,options:{limits:{fileSize:20971520}}}};async function pe(e,t){let n=d.default.resolve(e,t,`build-metadata.ts`);if(!u.default.existsSync(n))throw Error(`ApiKit build metadata "${n}" does not exist. Run "apikit build:app" first.`);return me(await(0,ee.createJiti)(e,{interopDefault:!1}).import(n,{try:!0}),n)}function me(e,t){if(!he(e)||!he(e.BuildMetadata))throw Error(`ApiKit build metadata is missing (${t}).`);let n=e.BuildMetadata,r=n.name;if(!he(r)||typeof r.original!=`string`||typeof r.base!=`string`||typeof n.version!=`string`||typeof n.id!=`string`||typeof n.createdAt!=`string`)throw Error(`ApiKit build metadata is invalid (${t}).`);return{name:{original:r.original,base:r.base},version:n.version,id:n.id,createdAt:n.createdAt}}function he(e){return typeof e==`object`&&!!e}const ge=(0,c.defineConfiguration)(`apikit.basic-auth`,{enabled:c.field.boolean().default(j.basicAuth.enabled),authenticate:c.field.custom().default(j.basicAuth.authenticate),proxyMode:c.field.boolean().default(j.basicAuth.proxyMode),header:c.field.string().optional().default(j.basicAuth.header),strictCredentials:c.field.boolean().optional().default(j.basicAuth.strictCredentials),username:c.field.string().optional(),password:c.field.string().optional()}),_e=(0,c.defineConfiguration)(`apikit.build`,{outDir:c.field.string().default(j.build.outDir)}),ve=(0,c.defineConfiguration)(`apikit.cors`,{enabled:c.field.boolean().default(j.cors.enabled),allowAllOrigins:c.field.boolean().default(j.cors.allowAllOrigins),includeWwwSubdomain:c.field.boolean().default(j.cors.includeWwwSubdomain),options:c.field.custom().default({}).map(ye)});function ye(e){return{...j.cors.options,...e}}const be=(0,c.defineConfiguration)(`apikit.email`,{enabled:c.field.boolean().default(j.email.enabled),templatesPath:c.field.string().default(j.email.templatesPath),globals:c.field.custom().default(j.email.globals),smtp:{host:c.field.string().optional(),port:c.field.number().optional(),secure:c.field.boolean().optional(),user:c.field.string().optional(),password:c.field.string().optional()}}),xe=(0,c.defineConfiguration)(`apikit.health`,{enabled:c.field.boolean().default(j.health.enabled),url:c.field.string().default(j.health.url).map(Se),pressure:{maxEventLoopDelay:c.field.number().default(j.health.pressure.maxEventLoopDelay),maxHeapUsedBytes:c.field.number().default(j.health.pressure.maxHeapUsedBytes),maxRssBytes:c.field.number().default(j.health.pressure.maxRssBytes),maxEventLoopUtilization:c.field.number().default(j.health.pressure.maxEventLoopUtilization)}});function Se(e){if(!e.startsWith(`/`))throw Error(`apikit.health.url must start with slash.`);if(e===`/`)throw Error(`apikit.health.url must not be root path.`);if(e.includes(`?`)||e.includes(`#`))throw Error(`apikit.health.url must not contain query string or fragment.`);return e.length>1?e.replace(/\/+$/,``):e}const Ce=(0,c.defineConfiguration)(`apikit.i18n`,{resources:c.field.custom().default(j.i18n.resources),directories:c.field.array(c.field.custom()).default(j.i18n.directories),files:c.field.array(c.field.custom()).default(j.i18n.files),defaultLanguage:c.field.string().default(j.i18n.defaultLanguage),fallbackLanguages:c.field.custom().default(j.i18n.fallbackLanguages),supportedLanguages:c.field.array(c.field.string()).default(j.i18n.supportedLanguages),load:c.field.custom().default(j.i18n.load),preload:c.field.custom().default(j.i18n.preload),nonExplicitSupportedLngs:c.field.boolean().default(j.i18n.nonExplicitSupportedLngs),lowerCaseLng:c.field.boolean().default(j.i18n.lowerCaseLng),cleanCode:c.field.boolean().default(j.i18n.cleanCode),namespaces:c.field.array(c.field.string()).optional(),defaultNamespace:c.field.string().default(j.i18n.defaultNamespace),keySeparator:c.field.string().default(j.i18n.keySeparator),nsSeparator:c.field.string().default(j.i18n.nsSeparator),pluralSeparator:c.field.string().default(j.i18n.pluralSeparator),contextSeparator:c.field.string().default(j.i18n.contextSeparator)}),we=(0,c.defineConfiguration)(`apikit.logger`,c.field.custom().default({enabled:j.logger.enabled}).map(Te));function Te(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.logger must be object.`);if(typeof e.enabled!=`boolean`)throw Error(`apikit.logger.enabled must be boolean.`);if(!e.enabled){if(`transports`in e&&e.transports!==void 0)throw Error(`apikit.logger.transports cannot be configured when logger is disabled.`);if(`request`in e&&e.request!==void 0)throw Error(`apikit.logger.request cannot be configured when logger is disabled.`);return{enabled:!1}}if(!Array.isArray(e.transports)||e.transports.length===0)throw Error(`apikit.logger.transports must be a non-empty array when logger is enabled.`);let t=Ee(e.request);return{enabled:!0,transports:e.transports,...t?{request:t}:{}}}function Ee(e){if(e!==void 0){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.logger.request must be object.`);if(e.ignoredPaths===void 0)return{};if(!Array.isArray(e.ignoredPaths))throw Error(`apikit.logger.request.ignoredPaths must be array.`);return{ignoredPaths:e.ignoredPaths.map((e,t)=>De(e,t))}}}function De(e,t){if(typeof e!=`string`)throw Error(`apikit.logger.request.ignoredPaths[${t}] must be string.`);let n=e.trim();if(!n)throw Error(`apikit.logger.request.ignoredPaths[${t}] must not be empty.`);if(!n.startsWith(`/`))throw Error(`apikit.logger.request.ignoredPaths[${t}] must start with slash.`);if(n===`/`)throw Error(`apikit.logger.request.ignoredPaths[${t}] must not be root path.`);if(n.includes(`?`)||n.includes(`#`))throw Error(`apikit.logger.request.ignoredPaths[${t}] must not contain query string or fragment.`);return n.length>1?n.replace(/\/+$/,``):n}const Oe=(0,c.defineConfiguration)(`apikit.metrics`,{enabled:c.field.boolean().default(j.metrics.enabled),endpoint:c.field.custom().default(j.metrics.endpoint),name:c.field.string().default(j.metrics.name),defaultMetrics:c.field.custom().default(j.metrics.defaultMetrics),routeMetrics:c.field.custom().default(j.metrics.routeMetrics),clearRegisterOnInit:c.field.boolean().default(j.metrics.clearRegisterOnInit)}),ke=(0,c.defineConfiguration)(`apikit.multipart`,{enabled:c.field.boolean().default(j.multipart.enabled),options:c.field.custom().default(j.multipart.options)}),Ae=(0,c.defineConfiguration)(`apikit.notification`,c.field.custom().default({enabled:j.notification.enabled}).map(je));function je(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.notification must be object.`);if(typeof e.enabled!=`boolean`)throw Error(`apikit.notification.enabled must be boolean.`);if(!e.enabled){if(`channels`in e&&e.channels!==void 0)throw Error(`apikit.notification.channels cannot be configured when notification is disabled.`);return{enabled:!1}}if(!e.channels||typeof e.channels!=`object`||Array.isArray(e.channels))throw Error(`apikit.notification.channels must be object when notification is enabled.`);Ne(e.channels);let t=Me(e.channels.telegram);if(!t)throw Error(`apikit.notification.channels must contain at least one configured channel.`);return{enabled:!0,channels:{telegram:t}}}function Me(e){if(e!==void 0){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`apikit.notification.channels.telegram must be object.`);return{token:Pe(e.token,`apikit.notification.channels.telegram.token`),chatId:Pe(e.chatId,`apikit.notification.channels.telegram.chatId`)}}}function Ne(e){for(let t of Object.keys(e))if(t!==`telegram`)throw Error(`apikit.notification.channels.${t} is not supported.`)}function Pe(e,t){if(typeof e!=`string`)throw Error(`${t} must be string.`);let n=e.trim();if(!n)throw Error(`${t} must not be empty.`);return n}const Fe=(0,c.defineConfiguration)(`apikit.server`,{identifier:c.field.string(),debug:c.field.boolean().default(j.server.debug),host:c.field.string(),port:c.field.number(),trustProxy:c.field.custom().default(j.server.trustProxy)}),Ie=(0,c.defineConfiguration)(`apikit.staticFiles`,{enabled:c.field.boolean().default(j.staticFiles.enabled),publicDirectory:c.field.string().optional(),routePrefix:c.field.string().default(j.staticFiles.routePrefix),maxAge:c.field.number().default(j.staticFiles.maxAge),dotfiles:c.field.custom().default(j.staticFiles.dotfiles),etag:c.field.boolean().default(j.staticFiles.etag),immutable:c.field.boolean().default(j.staticFiles.immutable),decorateReply:c.field.boolean().default(j.staticFiles.decorateReply),preCompressed:c.field.boolean().default(j.staticFiles.preCompressed)});function M(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let Le=class{get build(){return global.apikit.build}get isDebug(){return global.apikit.serverConfig.debug}get environment(){return global.apikit.environmentConfig}get logger(){return global.apikit.loggerConfig}get server(){return global.apikit.serverConfig}get metrics(){return global.apikit.metricsConfig}get health(){return global.apikit.healthConfig}get email(){return global.apikit.emailConfig}get notification(){return global.apikit.notificationConfig}get i18n(){return global.apikit.i18nConfig}get staticFiles(){return global.apikit.staticFilesConfig}get basicAuth(){return global.apikit.basicAuthConfig}get cors(){return global.apikit.corsConfig}get multipart(){return global.apikit.multipartConfig}get(e){if(!global.apikit.configurations.has(e.key))throw Error(`Configuration "${e.key}" is missing.`);return global.apikit.configurations.get(e.key)}optional(e){return global.apikit.configurations.get(e.key)}};Le=M([(0,f.injectable)()],Le);const Re=new c.Console;async function ze(e){let t=await(0,c.loadConfig)({config:e.config,environment:e.environment}),n=t.config.input,r=t.environment,i=await(0,c.resolveConfiguration)(_e,n.build,{environment:r}),a=await pe(t.rootDir,i.outDir),o=await Be(n,{buildMetadata:a,environment:r});global.apikit={build:a,environmentConfig:r,...o},Re.success(`[ApiKit] Context created for ${r.name} environment`)}async function Be(e,t){return{serverConfig:await(0,c.resolveConfiguration)(Fe,e.server,t),loggerConfig:await(0,c.resolveConfiguration)(we,e.logger,t),metricsConfig:await(0,c.resolveConfiguration)(Oe,e.metrics,t),healthConfig:await(0,c.resolveConfiguration)(xe,e.health,t),emailConfig:await(0,c.resolveConfiguration)(be,e.email,t),notificationConfig:await(0,c.resolveConfiguration)(Ae,e.notification,t),i18nConfig:await(0,c.resolveConfiguration)(Ce,e.i18n,t),staticFilesConfig:await(0,c.resolveConfiguration)(Ie,e.staticFiles,t),basicAuthConfig:await(0,c.resolveConfiguration)(ge,e.basicAuth,t),corsConfig:await(0,c.resolveConfiguration)(ve,e.cors,t),multipartConfig:await(0,c.resolveConfiguration)(ke,e.multipart,t),configurations:await Ve(e.configurations,t)}}async function Ve(e,t){let n=new Map;for(let r of e){if(r.contract.key.startsWith(`apikit.`))throw Error(`Configuration key "${r.contract.key}" is reserved for ApiKit.`);if(n.has(r.contract.key))throw Error(`Configuration "${r.contract.key}" is registered more than once.`);n.set(r.contract.key,await(0,c.resolveConfigurationBinding)(r,t))}return n}function He(e,t){return(0,c.defineConfig)(e,{...t,configurations:t.configurations??[]})}const Ue={name:`buildplease`,displayName:`BuildPlease`,scope:`@buildplease`},N=`${Ue.name}.ApiKit.DI`,P={DI:{Configuration:{Controller:Symbol.for(`${N}.Configuration.Controller`)},Database:{MongoDB:{QueryFormatter:Symbol.for(`${N}.Database.MongoDB.QueryFormatter`)}},Email:{Controller:Symbol.for(`${N}.Email.Controller`)},File:{TemporaryRepository:Symbol.for(`${N}.File.TemporaryRepository`)},Validation:{Controller:Symbol.for(`${N}.Validation.Controller`),DtoController:Symbol.for(`${N}.Validation.DtoController`)},OpenAPI:{SchemaController:Symbol.for(`${N}.OpenAPI.SchemaController`)},I18n:{Controller:Symbol.for(`${N}.I18n.Controller`)},Notification:{Controller:Symbol.for(`${N}.Notification.Controller`)},Normalization:{Controller:Symbol.for(`${N}.Normalization.Controller`)},Formatter:{Controller:Symbol.for(`${N}.Formatter.Controller`),MultipartController:Symbol.for(`${N}.Formatter.MultipartController`)},Generator:{RandomValueGenerator:Symbol.for(`${N}.Generator.RandomValueGenerator`)},Image:{NormalizationController:Symbol.for(`${N}.Image.NormalizationController`)},Server:{Controller:Symbol.for(`${N}.Server.Controller`),RequestController:Symbol.for(`${N}.Server.RequestController`),ResponseController:Symbol.for(`${N}.Server.ResponseController`)},Security:{CryptographyController:Symbol.for(`${N}.Security.CryptographyController`)}}};var We=class{assemble(e){e.bind(P.DI.Configuration.Controller).to(Le).inSingletonScope()}};let Ge=class{format(e){return this.flattenRecursive(e,``)}flattenRecursive(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];if(i===void 0||this.isPlainObject(i)&&Object.keys(i).length===0)continue;if(this.isOperator(r)){n[r]=this.processOperator(r,i);continue}let a=t?`${t}.${r}`:r;this.isPlainObject(i)?this.containsOperator(i)?n[a]={...i}:Object.assign(n,this.flattenRecursive(i,a)):n[a]=i}return n}isOperator(e){return e.startsWith(`$`)}containsOperator(e){return Object.keys(e).some(e=>this.isOperator(e))}isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}processOperator(e,t){return e===`$expr`?t:Array.isArray(t)?t.map(e=>this.flattenRecursive(e,``)):this.isPlainObject(t)?this.flattenRecursive(t,``):t}};Ge=M([(0,f.injectable)()],Ge);var Ke=class{assemble(e){e.bind(P.DI.Database.MongoDB.QueryFormatter).to(Ge)}};function F(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function I(e,t){return function(n,r){t(n,r,e)}}const L=`[Email]`;let R=class{configuration;logger;transporter;templatesPath;isEnabled;smtpConfig;constructor(e,t){this.configuration=e,this.logger=t,this.isEnabled=this.configuration.email.enabled,this.smtpConfig=qe(this.configuration.email),this.templatesPath=Je(this.configuration.email.templatesPath)}async sendEmail(e){try{if(!this.isEnabled){this.logger.debug(`${L} Sending skipped — disabled`);return}let t=this.getOrCreateTransporter(),n=await this.renderTemplate(e),r={to:e.recipient,from:e.sender,subject:e.subject,html:n,...e.replyTo===void 0?{}:{replyTo:e.replyTo}};await t.sendMail(r)}catch(e){throw this.logger.error(`${L} Send failed`,{error:e}),e}}getOrCreateTransporter(){return this.transporter||=re.default.createTransport({host:this.smtpConfig.host,port:this.smtpConfig.port,secure:this.smtpConfig.secure,auth:{user:this.smtpConfig.user,pass:this.smtpConfig.pass}}),this.transporter}async renderTemplate(e){try{let t=this.makeFilePath(e.templatePath,e.fallbackPath),n=await te.default.readFile(t,`utf-8`),r={globals:this.makeGlobals(),...e.data};return ne.default.render(n,r)}catch(e){throw this.logger.error(`${L} Render failed`,{error:e}),e}}makeFilePath(e,t){let n=d.default.join(this.templatesPath,this.sanitizeTemplatePath(e));if((0,u.existsSync)(n))return n;if(t){let e=d.default.join(this.templatesPath,this.sanitizeTemplatePath(t));if((0,u.existsSync)(e))return e}throw Error(`${L} Template not found: ${n}${t?` or ${t}`:``}`)}makeGlobals(){let e=this.configuration.email.globals;return{generatedDate:new Date().toISOString().replace(`T`,` `).substring(0,16)+` UTC`,...e}}sanitizeTemplatePath(e){if(e.includes(`..`))throw Error(`${L} Invalid template path: ${e}`);let t=e.replace(/^\/+/,``);return t.endsWith(`.ejs`)?t:`${t}.ejs`}};R=M([(0,f.injectable)(),I(0,(0,f.inject)(P.DI.Configuration.Controller)),I(1,(0,f.inject)(l.CoreSymbols.DI.Logger)),F(`design:paramtypes`,[Object,Object])],R);function qe(e){if(!e.enabled)return{host:``,port:0,secure:!1,user:``,pass:``};let t=e.smtp;if(!t.host)throw Error(`${L} email.smtp.host is required when email is enabled`);if(!t.port)throw Error(`${L} email.smtp.port is required when email is enabled`);if(t.secure===void 0)throw Error(`${L} email.smtp.secure is required when email is enabled`);if(!t.user)throw Error(`${L} email.smtp.user is required when email is enabled`);if(!t.password)throw Error(`${L} email.smtp.password is required when email is enabled`);if(!Number.isInteger(t.port)||t.port<=0)throw Error(`${L} email.smtp.port must be a positive integer`);return{host:t.host,port:t.port,secure:t.secure,user:t.user,pass:t.password}}function Je(e){let t=e.trim();return d.default.isAbsolute(t)?d.default.normalize(t):d.default.resolve(process.cwd(),t)}var Ye=class{data;recipient;sender;subject;replyTo;constructor(e){this.data=e.data,this.recipient=e.recipient,this.sender=e.sender??this.defaultSender(),this.subject=e.subject??this.defaultSubject(),e.replyTo!==void 0&&(this.replyTo=e.replyTo)}get fallbackPath(){}},Xe=class{assemble(e){e.bind(P.DI.Email.Controller).to(R).inSingletonScope()}};const z=`[ApiKit:TemporaryFile]`;let B=class{logger;rootDir;constructor(e){this.logger=e,this.rootDir=ie.default.tmpdir()}get rootDirectory(){return this.rootDir}async createDirectory(e){let t=this.safeJoin(e);try{return await(0,c.createDirectoryAsync)(t)}catch(e){throw this.logger.error(`${z} Create directory failed`,{error:e,details:{abs:t}}),e}}async deleteDirectory(e){let t=this.safeJoin(e);try{await(0,c.removePathAsync)(t,{recursive:!0,force:!0})}catch(e){throw this.logger.error(`${z} Delete directory failed`,{error:e,details:{abs:t}}),e}}async save(e,t,n,r){let i=this.safeJoin(r),a=d.default.join(i,`${e}.${n.extension}`);try{if(await(0,c.createDirectoryAsync)(i),await(0,c.ensureDirectoryAsync)(i),Buffer.isBuffer(t))return await u.default.promises.writeFile(a,t),a;if(t instanceof ae.Readable){let e=u.default.createWriteStream(a);try{return await(0,oe.pipeline)(t,e),a}finally{e.close()}}let e=Error(`Unsupported content type: expected Buffer or Readable.`);throw this.logger.error(`${z} Save unsupported content`,{error:e,details:{fileAbs:a,typeof:typeof t}}),e}catch(t){throw this.logger.error(`${z} Save failed`,{error:t,details:{fileAbs:a,relativeDirectory:r,filename:e,extension:n.extension}}),t}}async delete(e){let t=this.safeJoin(e);try{await(0,c.removePathAsync)(t,{recursive:!1,force:!0})}catch(e){throw this.logger.error(`${z} Delete failed`,{error:e,details:{abs:t}}),e}}safeJoin(e){let t=d.default.resolve(this.rootDir,e),n=this.rootDir.endsWith(d.default.sep)?this.rootDir:this.rootDir+d.default.sep;if(!t.startsWith(n)&&t!==this.rootDir){let n=Error(`Path escapes repository root: "${e}"`);throw this.logger.error(`${z} Path traversal attempt`,{error:n,details:{root:this.rootDir,attempted:t}}),n}return t}};B=M([(0,f.injectable)(),I(0,(0,f.inject)(l.CoreSymbols.DI.Logger)),F(`design:paramtypes`,[Object])],B);var Ze=class{assemble(e){e.bind(P.DI.File.TemporaryRepository).to(B)}},V=class e extends Error{_code;_statusCode;_details;constructor({code:t,message:n,statusCode:r,details:i}){super(n),this._code=t,this._statusCode=r,this._details=i,Error.captureStackTrace&&Error.captureStackTrace(this,e),Object.setPrototypeOf(this,e.prototype)}get code(){return this._code}get statusCode(){return this._statusCode}get details(){return this._details}toJSON(){let e={code:this._code,message:this.message,details:this.formatDetails(this.details)};return(0,l.filterObject)(e,{filterNull:!0,filterUndefined:!0,filterEmptyString:!0,filterEmptyObject:!0})}formatDetails(e){if(e!=null)return typeof e==`string`?{_error:[e]}:Array.isArray(e)&&e.every(e=>typeof e==`string`)?{_errors:e}:e}};function H(e){return typeof e==`object`&&!!e&&`message`in e&&typeof e.message==`string`&&`code`in e&&typeof e.code==`string`&&`statusCode`in e&&typeof e.statusCode==`number`}const U=l.CoreL10nResource.extend({resources:{en:{apikit:{errors:{common:{not_found:`The requested resource was not found`,unable_to_process_request:`We’re unable to process your request.`,unknown_error:`An unknown error occurred. Please try again later.`,already_exists:`The resource already exists`},server:{internal:`An internal server error occurred`,unavailable:`The service is temporarily unavailable. Try again later`,dependency_failed:`An external service or dependency failed`,timeout:`The server did not respond in time`},limit:{too_many_requests:`Too many requests. Try again later`},auth:{unauthorized:`You are not authorized to perform this action`,forbidden:`You do not have access to this resource`},validation:{bad_request:`The request is malformed or invalid`,invalid_json_syntax:`Invalid JSON syntax`,invalid_properties:`Some of the provided values are invalid`,invalid_format:`Invalid format`,invalid_date_format:`The date format is incorrect`,invalid_password:`The password you entered is incorrect`,invalid_password_new_same_as_old:`The new password must be different from the current one`,invalid_phone_number_format:`Invalid phone number format`,invalid_phone_new_same_as_old:`TThe new phone number must be different from the old one`,invalid_email_format:`Invalid email format`,invalid_email_new_same_as_old:`The new email must be different from the current one`},format:{unsupported:`Unsupported format`,max_size_exceeded:`Payload is too large.`},image:{max_size_exceeded:`Image is too large. Maximum allowed size is {{specs.maxSize}} {{specs.unit}}.`}}}},sk:{apikit:{errors:{common:{not_found:`Požadovaný zdroj sa nenašiel`,unable_to_process_request:`Vašu požiadavku sa nepodarilo spracovať.`,unknown_error:`Vyskytla sa neznáma chyba. Skúste to prosím znova neskôr.`,already_exists:`Zdroj už existuje`},server:{internal:`Vyskytla sa interná chyba servera`,unavailable:`Služba je momentálne nedostupná. Skúste to neskôr`,dependency_failed:`Zlyhala externá služba alebo závislosť`,timeout:`Server neodpovedal v stanovenom čase`},limit:{too_many_requests:`Príliš veľa požiadaviek. Skúste to neskôr`},auth:{unauthorized:`Nemáte oprávnenie na vykonanie tejto akcie`,forbidden:`K tomuto zdroju nemáte prístup`},validation:{bad_request:`Požiadavka je neplatná alebo nesprávna`,invalid_json_syntax:`Neplatná syntax JSON`,invalid_properties:`Niektoré z poskytnutých hodnôt sú neplatné`,invalid_format:`Neplatný formát`,invalid_date_format:`Formát dátumu je nesprávny`,invalid_password:`Zadané heslo je nesprávne`,invalid_password_new_same_as_old:`Nové heslo sa musí líšiť od aktuálneho`,invalid_phone_number_format:`Neplatný formát telefónneho čísla`,invalid_phone_new_same_as_old:`Nové telefónne číslo sa musí líšiť od pôvodného`,invalid_email_format:`Neplatný formát e-mailu`,invalid_email_new_same_as_old:`Nový e-mail sa musí líšiť od aktuálneho`},format:{unsupported:`Nepodporovaný formát`,max_size_exceeded:`Súbor je príliš veľký.`},image:{max_size_exceeded:`Obrázok je príliš veľký. Maximálna povolená veľkosť je {{specs.maxSize}} {{specs.unit}}.`}}}},cs:{apikit:{errors:{common:{not_found:`Požadovaný zdroj nebyl nalezen`,unable_to_process_request:`Vaši žádost se nepodařilo zpracovat.`,unknown_error:`Došlo k neznámé chybě. Zkuste to prosím později.`,already_exists:`Zdroj již existuje`},server:{internal:`Došlo k interní chybě serveru`,unavailable:`Služba je momentálně nedostupná. Zkuste to později`,dependency_failed:`Selhala externí služba nebo závislost`,timeout:`Server neodpověděl včas`},limit:{too_many_requests:`Příliš mnoho požadavků. Zkuste to později`},auth:{unauthorized:`Nemáte oprávnění k provedení této akce`,forbidden:`K tomuto zdroji nemáte přístup`},validation:{bad_request:`Požadavek je neplatný nebo nesprávný`,invalid_json_syntax:`Neplatná syntaxe JSON`,invalid_properties:`Některé z poskytnutých hodnot jsou neplatné`,invalid_format:`Neplatný formát`,invalid_date_format:`Formát data je nesprávný`,invalid_password:`Zadané heslo je nesprávné`,invalid_password_new_same_as_old:`Nové heslo se musí lišit od aktuálního`,invalid_phone_number_format:`Neplatný formát telefonního čísla`,invalid_phone_new_same_as_old:`Nové telefonní číslo se musí lišit od původního`,invalid_email_format:`Neplatný formát e-mailu`,invalid_email_new_same_as_old:`Nový e-mail se musí lišit od aktuálního`},format:{unsupported:`Nepodporovaný formát`,max_size_exceeded:`Soubor je příliš velký.`},image:{max_size_exceeded:`Obrázek je příliš velký. Maximální povolená velikost je {{specs.maxSize}} {{specs.unit}}.`}}}}}}),W=(0,l.defineL10n)(U);function Qe(e){return(e??``).toLowerCase().replace(/_/g,`-`).trim()}function $e(e){let[t,n]=e.split(`-`);return{base:t||``,region:n}}let G=class{configurationController;constructor(e){this.configurationController=e}async prepare(){let e=this.makeOptions();await h.default.init(e)}parseLocale(e,t={}){let{supportedLanguages:n,defaultLanguage:r}=this.makeConfig(),{ignoreRegion:i=!0}=t;if(!e||!e.trim())return r;let a=new Set(n.map(e=>e.toLowerCase())),o,s,c=0;for(let t of e.split(`,`)){let e=t.trim();if(!e){c++;continue}let n=e.split(`;`),r=Qe(n[0]??``);if(!r||r===`*`){c++;continue}let l=st(n.find(e=>e.startsWith(`q=`)));if(l===0){c++;continue}let{base:u}=$e(r);if(!u){c++;continue}!i&&a.has(r)&&(!o||l>o.q||l===o.q&&c<o.idx)&&(o={code:r,q:l,idx:c}),a.has(u)&&(!s||l>s.q||l===s.q&&c<s.idx)&&(s={code:u,q:l,idx:c}),c++}return o?o.code:s?s.code:r}makeOptions(){let e=this.makeConfig(),t=et(e);return{debug:!1,lng:e.defaultLanguage,fallbackLng:e.fallbackLanguages,supportedLngs:e.supportedLanguages,load:e.load,nonExplicitSupportedLngs:e.nonExplicitSupportedLngs,preload:e.preload,lowerCaseLng:e.lowerCaseLng,cleanCode:e.cleanCode,ns:e.namespaces,defaultNS:e.defaultNamespace,keySeparator:e.keySeparator,nsSeparator:e.nsSeparator,pluralSeparator:e.pluralSeparator,contextSeparator:e.contextSeparator,resources:t}}makeConfig(){let e=this.configurationController.i18n??{},t=e.defaultNamespace??`translation`,n=e.defaultLanguage??`en`,r=e.fallbackLanguages??n,i=(e.directories??[]).map(e=>({path:e.path,namespace:e.namespace??t})),a=(e.files??[]).map(e=>({locale:e.locale,path:e.path,namespace:e.namespace??t})),o=this.makeNamespaces(e.namespaces,t,i,a);return{resources:e.resources??{},directories:i,files:a,defaultLanguage:n,fallbackLanguages:r,supportedLanguages:e.supportedLanguages??[`en`,`sk`,`cs`],load:e.load??`languageOnly`,nonExplicitSupportedLngs:e.nonExplicitSupportedLngs??!0,preload:e.preload??!1,lowerCaseLng:e.lowerCaseLng??!0,cleanCode:e.cleanCode??!0,namespaces:o,defaultNamespace:t,keySeparator:e.keySeparator??`.`,nsSeparator:e.nsSeparator??`:`,pluralSeparator:e.pluralSeparator??`_`,contextSeparator:e.contextSeparator??`_`}}makeNamespaces(e,t,n,r){let i=Array.isArray(e)?e.filter(e=>typeof e==`string`):typeof e==`string`?[e]:[],a=new Set(i.length?i:[t]);for(let e of n)a.add(e.namespace);for(let e of r)a.add(e.namespace);return Array.from(a)}};G=M([(0,f.injectable)(),I(0,(0,f.inject)(P.DI.Configuration.Controller)),F(`design:paramtypes`,[Object])],G);function et(e){let t=nt(e);tt(t,e);let n=[...it(e),...at(e)];for(let{locale:e,ns:r,path:i}of n){let n=t[e]||={},a=JSON.parse(u.default.readFileSync(i,`utf-8`));n[r]=(0,m.default)(n[r]||{},a)}return t}function tt(e,t){for(let n of Object.keys(t.resources).sort()){let r=t.resources[n];if(!r)continue;let i=e[n]||={};i[t.defaultNamespace]=(0,m.default)(i[t.defaultNamespace]||{},r)}}function nt(e){let t={};for(let n of Object.keys(U.resources).sort()){let r=t[n]||={};r[e.defaultNamespace]=rt(U.resources[n])}return t}function rt(e){return JSON.parse(JSON.stringify(e))}function it(e){let t=[];for(let n of e.directories){let e=ot((0,c.resolvePath)(process.cwd(),n.path));for(let r of e)t.push({locale:r.locale,ns:n.namespace,path:r.path})}return t}function at(e){return e.files.map(e=>({locale:e.locale,ns:e.namespace,path:(0,c.resolvePath)(process.cwd(),e.path)}))}function ot(e){let t=(0,c.ensureDirectory)(e),n=u.default.readdirSync(t).filter(e=>e.endsWith(`.json`)).sort();if(!n.length)throw Error(`[ApiKit:I18n] No .json files in ${t}`);return n.map(e=>({locale:e.replace(/\.json$/,``),path:(0,c.resolvePath)(t,e)}))}function st(e){if(!e)return 1;let t=parseFloat(e.slice(2).replace(`,`,`.`));return Number.isFinite(t)?Math.max(0,Math.min(1,t)):1}var ct=class{_name;_value;_options;constructor(e,t,n={}){this._name=e,this._value=t,this._options={...n}}get name(){return this._name}get value(){return this._value}get options(){return{...this._options}}mutate(e){return e.name!==void 0&&(this._name=e.name),e.value!==void 0&&(this._value=e.value),e.options!==void 0&&(this._options={...this._options,...e.options}),this}serialize(){return g.fastifyCookie.serialize(this._name,this._value,this._options)}toString(){return this.serialize()}};const K={accept:`accept`,acceptLanguage:`accept-language`,authorization:`authorization`,cacheControl:`cache-control`,contentType:`content-type`,cookie:`cookie`,setCookie:`set-cookie`,userAgent:`user-agent`};let lt=function(e){return e.POST=`POST`,e.PUT=`PUT`,e.PATCH=`PATCH`,e.GET=`GET`,e.DELETE=`DELETE`,e.OPTIONS=`OPTIONS`,e}({}),ut=function(e){return e.JSON=`JSON`,e.File=`File`,e}({});var dt=class{statusCode;headers;constructor({statusCode:e,headers:t}){this.statusCode=e,this.headers=t}},ft=class extends dt{data;responseType=`JSON`;constructor({statusCode:e,data:t,headers:n}){super({statusCode:e,headers:n}),this.data=t}},pt=class extends dt{filePath;shouldRender;data;responseType=`File`;constructor({statusCode:e,filePath:t,shouldRender:n,headers:r,data:i}){super({statusCode:e,headers:r}),this.filePath=t,this.shouldRender=n,this.data=i}},q=class{metadata;constructor(e){this.metadata=e}toJSON(){let e={[K.userAgent]:this.metadata.headers?.[K.userAgent],[K.contentType]:this.metadata.headers?.[K.contentType],[K.acceptLanguage]:this.metadata.headers?.[K.acceptLanguage],[K.accept]:this.metadata.headers?.[K.accept]},t=(0,l.filterObject)({reqId:this.metadata.requestId,method:this.metadata.method,url:this.metadata.url,protocol:this.metadata.protocol,query:this.metadata.query,params:this.metadata.params,ip:this.metadata.ip,locale:this.metadata.locale,headers:e},{filterNull:!0,filterUndefined:!0,filterEmptyString:!0,filterEmptyArray:!0,filterEmptyObject:!0});return(0,l.isEmptyObject)(t)?void 0:t}};const mt=Symbol.for(`request-scope.storage`);function ht(){let e=Reflect.get(globalThis,mt);if(e)return e;let t=new se.AsyncLocalStorage;return Reflect.defineProperty(globalThis,mt,{value:t,configurable:!1,enumerable:!1,writable:!1}),t}const gt=ht(),_t={run(e,t){return gt.run(e,t)},get metadata(){let e=gt.getStore();if(!e?.metadata)throw Error("[RequestScope] Attempted to access `metadata` outside of request lifecycle.");return e.metadata},get requestId(){return this.metadata.requestId},get locale(){return this.metadata.locale}};var vt=class{static t(e,t={}){let n=_t.locale;return h.default.t(e,{...t,lng:n})}static get currentLocale(){return _t.locale}static isSupportedLanguage(e,t={ignoreRegion:!0}){let n=Qe(e);if(!n)return!1;let r=h.default.options.supportedLngs;if(!r)return!1;let i=new Set(r.map(Qe));if(i.has(n))return!0;if(t.ignoreRegion){let{base:e}=$e(n);if(e&&i.has(e))return!0}return!1}},yt=class{static make(e,t={}){return this.translateKey(e,t)}static translateKey(e,t={}){let{overrideMessage:n,i18n:r}=t;return n??vt.t(e,r)}};function J(e){return Ot(e),e}const bt=J({NOT_FOUND:{message:W.Apikit.Errors.Common.NotFound,code:`RESOURCE_NOT_FOUND`,statusCode:404},UNKNOWN_ERROR:{message:W.Apikit.Errors.Common.UnknownError,code:`UNKNOWN_ERROR`,statusCode:500},UNABLE_TO_PROCESS_REQUEST:{message:W.Apikit.Errors.Common.UnableToProcessRequest,code:`UNABLE_TO_PROCESS_REQUEST`,statusCode:500},RESOURCE_ALREADY_EXISTS:{message:W.Apikit.Errors.Common.AlreadyExists,code:`RESOURCE_ALREADY_EXISTS`,statusCode:409}}),xt=J({INTERNAL_SERVER_ERROR:{message:W.Apikit.Errors.Server.Internal,code:`INTERNAL_SERVER_ERROR`,statusCode:500},SERVICE_UNAVAILABLE:{message:W.Apikit.Errors.Server.Unavailable,code:`SERVICE_UNAVAILABLE`,statusCode:503},DEPENDENCY_FAILED:{message:W.Apikit.Errors.Server.DependencyFailed,code:`DEPENDENCY_FAILED`,statusCode:424},TIMEOUT:{message:W.Apikit.Errors.Server.Timeout,code:`TIMEOUT`,statusCode:504}}),St=J({TOO_MANY_REQUESTS:{message:W.Apikit.Errors.Limit.TooManyRequests,code:`TOO_MANY_REQUESTS`,statusCode:429}}),Ct=J({UNAUTHORIZED:{message:W.Apikit.Errors.Auth.Unauthorized,code:`UNAUTHORIZED`,statusCode:401},FORBIDDEN:{message:W.Apikit.Errors.Auth.Forbidden,code:`FORBIDDEN`,statusCode:403}}),wt=J({BAD_REQUEST:{message:W.Apikit.Errors.Validation.BadRequest,code:`BAD_REQUEST`,statusCode:400},INVALID_JSON_SYNTAX:{message:W.Apikit.Errors.Validation.InvalidJsonSyntax,code:`JSON_SYNTAX_ERROR`,statusCode:400},INVALID_PROPERTIES:{message:W.Apikit.Errors.Validation.InvalidProperties,code:`INVALID_PROPERTIES`,statusCode:400},INVALID_FORMAT:{message:W.Apikit.Errors.Validation.InvalidFormat,code:`INVALID_FORMAT`,statusCode:400},INVALID_DATE_FORMAT:{message:W.Apikit.Errors.Validation.InvalidDateFormat,code:`INVALID_DATE_FORMAT`,statusCode:400},INVALID_PASSWORD:{message:W.Apikit.Errors.Validation.InvalidPassword,code:`INVALID_PASSWORD`,statusCode:403},INVALID_PASSWORD_NEW_SAME_AS_OLD:{message:W.Apikit.Errors.Validation.InvalidPasswordNewSameAsOld,code:`INVALID_PASSWORD_NEW_SAME_AS_OLD`,statusCode:409},INVALID_PHONE_NUMBER_FORMAT:{message:W.Apikit.Errors.Validation.InvalidPhoneNumberFormat,code:`INVALID_PHONE_NUMBER_FORMAT`,statusCode:400},INVALID_PHONE_NEW_SAME_AS_OLD:{message:W.Apikit.Errors.Validation.InvalidPhoneNewSameAsOld,code:`INVALID_PHONE_NEW_SAME_AS_OLD`,statusCode:409},INVALID_EMAIL_FORMAT:{message:W.Apikit.Errors.Validation.InvalidEmailFormat,code:`INVALID_EMAIL_FORMAT`,statusCode:400},INVALID_EMAIL_NEW_SAME_AS_OLD:{message:W.Apikit.Errors.Validation.InvalidEmailNewSameAsOld,code:`INVALID_EMAIL_NEW_SAME_AS_OLD`,statusCode:409}}),Tt=J({UNSUPPORTED_FORMAT:{message:W.Apikit.Errors.Format.Unsupported,code:`UNSUPPORTED_FORMAT`,statusCode:400},MAX_SIZE_EXCEEDED:{message:W.Apikit.Errors.Format.MaxSizeExceeded,code:`MAX_SIZE_EXCEEDED`,statusCode:413}}),Et=J({MAX_SIZE_EXCEEDED:{message:W.Apikit.Errors.Image.MaxSizeExceeded,code:`IMAGE_MAX_SIZE_EXCEEDED`,statusCode:413}}),Dt=J({Common:bt,Server:xt,Limit:St,Authorization:Ct,Validation:wt,Format:Tt,Image:Et});function Ot(e){let t=new Set;kt(e,e=>{if(t.has(e.message))throw Error(`Duplicate API error message key: ${e.message}`);t.add(e.message)})}function kt(e,t){for(let n of Object.values(e)){if(H(n)){t(n);continue}kt(n,t)}}const Y=At(Dt);function At(e){return{codes:e,make(t,n={}){let r=Mt(e,t);if(!r)throw Error(`Invalid API error code path: ${t}`);return jt(r,n)},extend(t){let n=(0,m.default)({},e,t);return J(n),At(n)}}}function jt(e,t){let{overrideMessage:n,details:r,i18n:i}=t,a=yt.translateKey(e.message,{overrideMessage:n,i18n:i});return new V({code:e.code,statusCode:e.statusCode,message:a,details:r})}function Mt(e,t){let n=t.split(`.`),r=e;for(let e of n){if(!r||H(r))return;r=r[e]}if(!(!r||!H(r)))return r}var Nt=class{mimeType;constructor(e){if(e.includes(`/`)){if(!p.default.extension(e))throw Y.make(`Format.UNSUPPORTED_FORMAT`);this.mimeType=e;return}let t=p.default.lookup(e);if(!t)throw Y.make(`Format.UNSUPPORTED_FORMAT`);this.mimeType=t}get value(){return this.mimeType}get extension(){let e=p.default.extension(this.mimeType);if(!e)throw Y.make(`Format.UNSUPPORTED_FORMAT`);return e}equals(e){return this.mimeType===e.value}},Pt=class{value;constructor(e){this.value=e}apply(e){return typeof e==`function`?this.value=e(this.value):this.applyTransformations(e),this}filter(e=e=>e!==void 0){let t=n=>{if(Array.isArray(n)){let r=n.map(t).filter(e);return r.length>0?r:void 0}if((0,l.isPlainObject)(n)){let r=Object.entries(n).map(([e,n])=>[e,t(n)]).filter(([t,n])=>e(n));return r.length>0?Object.fromEntries(r):void 0}return e(n)?n:void 0};return this.value=t(this.value),this}exec(){return this.value}applyTransformations(e){(0,l.isObject)(this.value)&&(this.value=Object.fromEntries(Object.entries(this.value).map(([t,n])=>[t,e[t]?.(n)??n])))}};let Ft=class{format(e){return new Pt(e)}};Ft=M([(0,f.injectable)()],Ft);let It=class{normalizeFields(e){let t={};for(let[n,r]of Object.entries(e))t[n]=this.normalizeValue(r,n);return t}normalizeValue(e,t){if(e===void 0)return;if(e===null)return null;if(!(0,l.isNonEmptyString)(e))return e;let n=e.trim();if(n===``)return e;if(n===`null`)return null;if(n===`true`)return!0;if(n===`false`)return!1;if(!Number.isNaN(Number(n)))return Number(n);try{return JSON.parse(n)}catch{return e}}};It=M([(0,f.injectable)()],It);var Lt=class{assemble(e){e.bind(P.DI.Formatter.Controller).to(Ft),e.bind(P.DI.Formatter.MultipartController).to(It)}};const X={maxStringLength:4096,randomIntegerRangeLimit:2**48},Rt={length:8,alphabet:`alphanumeric`},zt={decimal:`0123456789`,lowercase:`abcdefghijklmnopqrstuvwxyz`,uppercase:`ABCDEFGHIJKLMNOPQRSTUVWXYZ`,letters:`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`,alphanumeric:`0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`,hex:`0123456789abcdef`,base64:`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,base64url:`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`};let Bt=class{generateNumber(e){return this.assertGenerateNumberOptions(e),e.min===e.max?e.min:(0,_.randomInt)(e.min,e.max+1)}generateString(e=Rt){let t=e.length??Rt.length,n=this.resolveAlphabet(e.alphabet??Rt.alphabet);this.assertStringLength(t),this.assertAlphabet(n);let r=``;for(let e=0;e<t;e++)r+=n.charAt((0,_.randomInt)(0,n.length));return r}generateUuidV4(){return(0,ce.v4)()}generateUuidV7(){return(0,ce.v7)()}resolveAlphabet(e){return typeof e==`string`?zt[e]:e.characters}assertGenerateNumberOptions(e){if(!Number.isSafeInteger(e.min))throw Error(`GenerateNumberOptions.min must be a safe integer`);if(!Number.isSafeInteger(e.max))throw Error(`GenerateNumberOptions.max must be a safe integer`);if(e.max<e.min)throw Error(`GenerateNumberOptions.max must be greater than or equal to min`);if(e.max===2**53-1)throw Error(`GenerateNumberOptions.max must be lower than Number.MAX_SAFE_INTEGER`);if(e.max-e.min>=X.randomIntegerRangeLimit)throw Error(`GenerateNumberOptions range must be lower than ${X.randomIntegerRangeLimit}`)}assertStringLength(e){if(!Number.isSafeInteger(e))throw Error(`GenerateStringOptions.length must be a safe integer`);if(e<=0)throw Error(`GenerateStringOptions.length must be greater than 0`);if(e>X.maxStringLength)throw Error(`GenerateStringOptions.length must be lower than or equal to ${X.maxStringLength}`)}assertAlphabet(e){if(e.length<2)throw Error(`GenerateStringOptions.alphabet must contain at least 2 characters`);if(!/^[!-~]+$/.test(e))throw Error(`GenerateStringOptions.alphabet must contain printable ASCII characters without whitespace`);if(new Set(e).size!==e.length)throw Error(`GenerateStringOptions.alphabet must not contain duplicate characters`)}};Bt=M([(0,f.injectable)()],Bt);var Vt=class{assemble(e){e.bind(P.DI.Generator.RandomValueGenerator).to(Bt)}},Ht=class{assemble(e){e.bind(P.DI.I18n.Controller).to(G)}};let Ut=class{formatter;constructor(e){this.formatter=e}async processBufferToBuffer(e,t){let{processed:n,type:r}=await this.transform((0,v.default)(e),t);return{buffer:await n.toBuffer(),type:r}}async processBufferToStream(e,t){let{processed:n,type:r}=await this.transform((0,v.default)(e),t);return{stream:this.asReadable(n),type:r}}async processStreamToBuffer(e,t){let n=(0,v.default)();await(0,ue.pipeline)(e,n);let{processed:r,type:i}=await this.transform(n,t);return{buffer:await r.toBuffer(),type:i}}async processStreamToStream(e,t){let n=(0,v.default)();await(0,ue.pipeline)(e,n);let{processed:r,type:i}=await this.transform(n,t);return{stream:this.asReadable(r),type:i}}async transform(e,t){let n=t??this.makeDefaultOptions(),r;try{r=await e.metadata()}catch{throw Y.make(`Format.UNSUPPORTED_FORMAT`,{details:`Invalid or unsupported image file`})}this.validateMaximumSize(r.size,n.maximumSize),this.validateInputFormat(r.format,n.allowedInputFormats);let i=await this.applyNormalization(e,r,n),a=this.toSharpFormat(n.outputFormat),{sharp:o}=n;i=o?.toFormat?i.toFormat(a,o.toFormat):i.toFormat(a),o?.configure&&(i=o.configure(i));let s=this.toFormatType(n.outputFormat);return{processed:i,type:s}}validateInputFormat(e,t){if(!e||!v.default.format[e]?.input)throw Y.make(`Format.UNSUPPORTED_FORMAT`,{details:`Unsupported input format: ${e}`});if(t&&!t.includes(e))throw Y.make(`Format.UNSUPPORTED_FORMAT`,{details:`Format not allowed: ${e}`})}validateMaximumSize(e,t){if(!(!t||!e)&&e>t){let n=this.formatter.formatBytes(t,{inputUnit:l.ByteUnit.Byte,outputUnit:`auto`,decimals:1});throw Y.make(`Image.MAX_SIZE_EXCEEDED`,{i18n:{specs:{maxSize:n.value,unit:n.unit}},details:`current=${e}B, max=${t}B, exceeded=${e-t}B`})}}toSharpFormat(e){return e}toFormatType(e){if(!this.getFormatInfo(e)?.output){let t=`Cannot encode output format: ${e}`;throw Y.make(`Format.UNSUPPORTED_FORMAT`,{details:t})}return new Nt(e)}getFormatInfo(e){return v.default.format[e]}asReadable(e){let t=new le.PassThrough;return e.on(`error`,e=>t.destroy(e)),e.pipe(t),t}async applyNormalization(e,t,n){if(n.minWidth==null&&n.maxWidth==null&&n.minAspectRatio==null&&n.maxAspectRatio==null)return n.sharp?.resize&&(e=e.resize(n.sharp.resize)),e;this.validateConstraints(n);let r=t.width??0,i=t.height??0;if(!(r>0&&i>0))throw Y.make(`Validation.INVALID_PROPERTIES`,{details:`Missing image dimensions.`});let a=n.aspectRatioTolerance??0,o=r/i,s=this.pickTargetAspectRatio(o,n.minAspectRatio,n.maxAspectRatio,a),c=r;if(s!==void 0){let t=o>s,n=t?Math.max(1,Math.round(i*s)):r,a=t?i:Math.max(1,Math.round(r/s)),l=Math.max(0,Math.floor((r-n)/2)),u=Math.max(0,Math.floor((i-a)/2));e=e.extract({left:l,top:u,width:n,height:a}),c=n}let{minWidth:l,maxWidth:u}=n,d=typeof u==`number`&&c>u?u:typeof l==`number`&&c<l?l:c;return d!==c&&(e=e.resize({width:d})),e}validateConstraints(e){let t=[],n=e=>Number.isFinite(e)&&e>0;if(e.minWidth!=null&&!n(e.minWidth)&&t.push(`minWidth must be > 0`),e.maxWidth!=null&&!n(e.maxWidth)&&t.push(`maxWidth must be > 0`),e.minAspectRatio!=null&&!n(e.minAspectRatio)&&t.push(`minAspectRatio must be > 0`),e.maxAspectRatio!=null&&!n(e.maxAspectRatio)&&t.push(`maxAspectRatio must be > 0`),e.aspectRatioTolerance!=null&&!(e=>Number.isFinite(e)&&e>=0)(e.aspectRatioTolerance)&&t.push(`aspectRatioTolerance must be ≥ 0`),e.minWidth!=null&&e.maxWidth!=null&&e.minWidth>e.maxWidth&&t.push(`minWidth must be ≤ maxWidth`),e.minAspectRatio!=null&&e.maxAspectRatio!=null&&e.minAspectRatio>e.maxAspectRatio&&t.push(`minAspectRatio must be ≤ maxAspectRatio`),t.length)throw Y.make(`Validation.INVALID_PROPERTIES`,{details:t.join(`; `)})}pickTargetAspectRatio(e,t,n,r=0){if(typeof t==`number`&&e<t-r)return t;if(typeof n==`number`&&e>n+r)return n}makeDefaultOptions(){return{outputFormat:`jpeg`,maximumSize:7864320,minWidth:320,maxWidth:1080,minAspectRatio:.8,maxAspectRatio:1.91,aspectRatioTolerance:.01,sharp:{toFormat:{quality:82,progressive:!0}}}}};Ut=M([(0,f.injectable)(),I(0,(0,f.inject)(l.CoreSymbols.DI.Formatter.UnitController)),F(`design:paramtypes`,[Object])],Ut);var Wt=class{assemble(e){e.bind(P.DI.Image.NormalizationController).to(Ut)}};let Gt=class{normalizeEmail(e){let t=e.trim();if(!b.default.isEmail(t))throw Y.make(`Validation.INVALID_EMAIL_FORMAT`);let n=b.default.normalizeEmail(t,{all_lowercase:!0,gmail_lowercase:!0,gmail_remove_dots:!0,gmail_remove_subaddress:!0,gmail_convert_googlemaildotcom:!0,outlookdotcom_lowercase:!0,outlookdotcom_remove_subaddress:!0,yahoo_lowercase:!0,yahoo_remove_subaddress:!0,icloud_lowercase:!0,icloud_remove_subaddress:!0});if(!n)throw Y.make(`Validation.INVALID_EMAIL_FORMAT`);return n}normalizePhoneToE164(e){try{return(0,y.parsePhoneNumberWithError)(e).format(`E.164`)}catch{throw Y.make(`Validation.INVALID_PHONE_NUMBER_FORMAT`)}}normalizePhoneToInternational(e){try{return(0,y.parsePhoneNumberWithError)(e).format(`INTERNATIONAL`)}catch{throw Y.make(`Validation.INVALID_PHONE_NUMBER_FORMAT`)}}normalizePhoneToNational(e){try{return(0,y.parsePhoneNumberWithError)(e).format(`NATIONAL`).replace(/[^\d]/g,``)}catch{throw Y.make(`Validation.INVALID_PHONE_NUMBER_FORMAT`)}}};Gt=M([(0,f.injectable)()],Gt);var Kt=class{assemble(e){e.bind(P.DI.Normalization.Controller).to(Gt)}};const qt=`${Ue.name}.ApiKit.Internal.DI`,Jt={DI:{Notification:{ChannelController:Symbol.for(`${qt}.Notification.ChannelController`)}}},Yt=`[Notification]`;let Xt=function(e){return e.Telegram=`telegram`,e}({});const Zt=`${Yt}:Telegram`;var Qt=class{configuration;channel=`telegram`;constructor(e){this.configuration=e}async send(e){if(e.type!==this.channel)throw Error(`${Zt} Invalid channel request.`);let t;try{t=await fetch(`https://api.telegram.org/bot${this.configuration.token}/sendMessage`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({chat_id:this.configuration.chatId,text:$t(e.payload)})})}catch{throw Error(`${Zt} Request failed.`)}if(!t.ok)throw Error(`${Zt} Request failed with status ${t.status}.`)}};function $t(e){return e.title===void 0?e.message:`${e.title}\n\n${e.message}`}let en=class{logger;channelControllers;constructor(e,t){this.logger=t,this.channelControllers=tn(e??[])}async send(e,t={}){let n=t.throwOnFailure===!0,r=[];for(let t of e.channels)r.push(await this.deliver(t,n));return{deliveries:r}}async deliver(e,t){let n={channel:e.type,status:`failed`};try{let t=this.channelControllers.get(e.type);if(!t)throw Error(`${Yt} Channel "${e.type}" is unavailable.`);return await t.send(e),{channel:e.type,status:`sent`}}catch(r){if(this.logger.error(`${Yt} Delivery failed.`,{error:r,details:{channel:e.type}}),t)throw r;return n}}};en=M([(0,f.injectable)(),I(0,(0,f.multiInject)(Jt.DI.Notification.ChannelController)),I(0,(0,f.optional)()),I(1,(0,f.inject)(l.CoreSymbols.DI.Logger)),F(`design:paramtypes`,[Object,Object])],en);function tn(e){let t=new Map;for(let n of e){if(t.has(n.channel))throw Error(`${Yt} Channel "${n.channel}" is registered more than once.`);t.set(n.channel,n)}return t}var nn=class{assemble(e){this.assembleChannelControllers(e),e.bind(P.DI.Notification.Controller).to(en).inSingletonScope()}assembleChannelControllers(e){let t=global.apikit.notificationConfig;if(!t.enabled)return;let n=t.channels.telegram;n&&e.bind(Jt.DI.Notification.ChannelController).toConstantValue(new Qt(n))}};let rn=class{makeResponse(e,t,n){return{description:e,content:this.constructContent(t),headers:n?this.constructHeaders(n):void 0}}constructContent(e){return Object.entries(e).reduce((e,[t,{schema:n,examples:r}])=>(e[t]={schema:n,examples:r?this.constructExamples(r):void 0},e),{})}constructExamples(e){return Object.entries(e).reduce((e,[t,n])=>(e[t]={summary:n.summary,value:n.value},e),{})}constructHeaders(e){return e||{}}};rn=M([(0,f.injectable)()],rn);var an=class{assemble(e){e.bind(P.DI.OpenAPI.SchemaController).to(rn)}};let Z=class{digest(e,t){let n=(0,_.createHash)(this.resolveDigestAlgorithm(t.algorithm)).update(e,`utf8`).digest();return this.encode(n,t.outputEncoding)}mac(e,t){let n=(0,_.createHmac)(this.resolveMacAlgorithm(t.algorithm),t.secret).update(e,`utf8`).digest();return this.encode(n,t.outputEncoding)}verifyMac(e,t,n){let r=this.mac(e,n);return this.timingSafeEqual(r,t)}async hashPassword(e,t){if(t.algorithm===`argon2id`)return x.hash(e,{type:x.argon2id,memoryCost:t.memoryCost,timeCost:t.timeCost,parallelism:t.parallelism})}async verifyPassword(e,t){try{return await x.verify(t,e)}catch{return!1}}timingSafeEqual(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&(0,_.timingSafeEqual)(n,r)}encode(e,t){switch(t){case`hex`:return e.toString(`hex`);case`base64url`:return e.toString(`base64url`)}}resolveDigestAlgorithm(e){switch(e){case`sha256`:return`sha256`;case`sha384`:return`sha384`;case`sha512`:return`sha512`}}resolveMacAlgorithm(e){switch(e){case`hmac-sha256`:return`sha256`;case`hmac-sha384`:return`sha384`;case`hmac-sha512`:return`sha512`}}};Z=M([(0,f.injectable)()],Z);var on=class{_value;_payload;constructor(e,t){this._value=e,this._payload=t}get value(){return this._value}get payload(){return this._payload}getField(e){return(0,l.ignoreError)(()=>this._payload[e]).orDefault(void 0)}},sn=class{assemble(e){e.bind(P.DI.Security.CryptographyController).to(Z)}},cn=(0,S.default)(async(e,t)=>{let n=t.apikitController.basicAuth;if(!n.enabled)return;let r=n.username,i=n.password;if(!r||!i)throw Error(`[ApiKit:BasicAuth] username and password are required when basic auth is enabled.`);await e.register(de.default,{validate:ln(r,i),authenticate:n.authenticate,proxyMode:n.proxyMode,header:n.header,strictCredentials:n.strictCredentials})},{name:`apikit-basic-auth`});function ln(e,t){return async(n,r)=>{un({inputUsername:n,inputPassword:r,expectedUsername:e,expectedPassword:t})}}function un(e){let t=dn(e.inputUsername,e.expectedUsername),n=dn(e.inputPassword,e.expectedPassword);if(!t||!n)throw Error(`Access denied`)}function dn(e,t){let n=Buffer.isBuffer(e)?e:Buffer.from(e,`utf-8`),r=Buffer.isBuffer(t)?t:Buffer.from(t,`utf-8`);return n.length===r.length?_.default.timingSafeEqual(n,r):(_.default.timingSafeEqual(n,n),!1)}var fn=(0,S.default)(async e=>{await e.register(g.default,{hook:`onRequest`,parseOptions:{}})},{name:`apikit-cookie`}),pn=(0,S.default)(async(e,t)=>{let n=t.apikitController.cors;n.enabled&&await e.register(C.default,mn(n))},{name:`apikit-cors`});function mn(e){let t=e.allowAllOrigins?!0:hn(e.options.origin,{includeWwwSubdomain:e.includeWwwSubdomain});return{...e.options,origin:t}}function hn(e,t){return e&&(typeof e==`string`?vn(e,t):Array.isArray(e)?gn(e,t):e)}function gn(e,t){let n=[];for(let r of e)_n(n,r,t);return bn(n)}function _n(e,t,n){if(typeof t==`string`){e.push(...vn(t,n));return}if(t instanceof RegExp||typeof t==`boolean`){e.push(t);return}if(Array.isArray(t))for(let r of t)_n(e,r,n)}function vn(e,t){let n=yn(e);if(!n)return[e];if(!t.includeWwwSubdomain)return[n];let{protocol:r,host:i}=new URL(n);return/^[a-zA-Z][a-zA-Z0-9.-]*$/.test(i)?[n,`${r}//${i.startsWith(`www.`)?i:`www.${i}`}`]:[n]}function yn(e){try{let{protocol:t,host:n}=new URL(e);return`${t}//${n}`}catch{return null}}function bn(e){let t=new Set,n=[];for(let r of e){if(typeof r!=`string`){n.push(r);continue}t.has(r)||(t.add(r),n.push(r))}return n}const xn=`[ApiKit:Health]`;var Sn=(0,S.default)(async(e,t)=>{let n=t.apikitController.health;if(!n.enabled){e.log.info(`${xn} Disabled — skipping`);return}await e.register(w.default,{exposeStatusRoute:n.url,maxEventLoopDelay:n.pressure.maxEventLoopDelay,maxHeapUsedBytes:n.pressure.maxHeapUsedBytes,maxRssBytes:n.pressure.maxRssBytes,maxEventLoopUtilization:n.pressure.maxEventLoopUtilization}),e.log.info(`${xn} Enabled`)},{name:`apikit-health`}),Cn=(0,S.default)(async e=>{await e.register(T.default,{strict:!1,isAWS:!1})},{name:`apikit-ip`});const wn=`[ApiKit:Metrics]`;var Tn=(0,S.default)(async(e,t)=>{let n=t.apikitController.metrics;if(!n.enabled){e.log.info(`${wn} Disabled — skipping`);return}await e.register(E.default,{endpoint:n.endpoint,name:n.name,defaultMetrics:n.defaultMetrics,routeMetrics:n.routeMetrics,clearRegisterOnInit:n.clearRegisterOnInit}),e.log.info(`${wn} Enabled`)},{name:`apikit-metrics`}),En=(0,S.default)(async(e,t)=>{let n=t.apikitController.multipart;n.enabled&&await e.register(D.default,n.options)},{name:`apikit-multipart`});function Dn(e){let t=e.apikitController,n=t.logger;return n.enabled?Mn([t.health.enabled?t.health.url:void 0,t.metrics.enabled?kn(t.metrics.endpoint):void 0,...n.request?.ignoredPaths??[]]):[]}function On(e,t){let n=jn(An(e));return t.some(e=>{let t=jn(e);return n===t||n.startsWith(`${t}/`)})}function kn(e){if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`url`in e){let t=e.url;return typeof t==`string`?t:void 0}}function An(e){return e.split(/[?#]/,1)[0]||`/`}function jn(e){let t=e.trim(),n=t.startsWith(`/`)?t:`/${t}`;return n.length>1?n.replace(/\/+$/,``):n}function Mn(e){return[...new Set(e.filter(e=>!!e?.trim()).map(jn).filter(e=>e!==`/`))]}const Nn=`[ApiKit:Request]`,Pn=`[ApiKit:Response]`;var Fn=(0,S.default)(async(e,t)=>{let n=t.logger,r=t.apikitController.logger,i=t.apikitController.isDebug,a=Dn(t);r.enabled&&(e.addHook(`onRequest`,async e=>{if(On(e.url,a))return;let t=new q(e.metadata);(0,l.ignoreError)(()=>{n.info(`${Nn} onRequest`,{metadata:t})})}),e.addHook(`preValidation`,async e=>{if(On(e.url,a)||!i)return;let t=new q({requestId:e.metadata.requestId});(0,l.ignoreError)(()=>{n.debug(`${Nn} preValidation`,{metadata:t,details:{body:In(e.body,e.headers)}})})}),e.addHook(`onSend`,async(e,t,r)=>(On(e.url,a)||(0,l.ignoreError)(()=>{let a=new q({requestId:e.metadata.requestId}),o={elapsedTime:t.elapsedTime,statusCode:t.statusCode};i?n.debug(`${Pn} onSend`,{metadata:a,details:{...o,body:In(r,t.getHeaders())}}):n.info(`${Pn} onSend`,{metadata:a,details:o})}),r)))},{name:`apikit-request-logger`,dependencies:[`apikit-request-metadata`]});function In(e,t){return String(t?.[K.contentType]??``).toLowerCase().includes(`multipart/form-data`)?`[Multipart]`:Ln(e)}function Ln(e,t=new WeakSet,n=0){if(!(0,l.isDefinedAndNotNull)(e))return`[Not provided]`;if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}if(typeof e==`number`||typeof e==`boolean`)return e;if(typeof e==`bigint`||typeof e==`symbol`)return e.toString();if(typeof e==`function`)return`[Function: ${e.name||`anonymous`}]`;if(Buffer.isBuffer(e))return`[Buffer]`;if(e instanceof le.Readable)return`[Stream]`;if(typeof e==`object`&&e&&`file`in e&&`filename`in e)return`[File]`;if(typeof e==`object`){if(t.has(e))return`[Circular]`;if(t.add(e),Array.isArray(e))return e.map(e=>Ln(e,t,n+1));let r={};for(let[i,a]of Object.entries(e))r[i]=Ln(a,t,n+1);return r}return String(e)}var Rn=(0,S.default)(async(e,t)=>{let n=t.i18nController;e.addHook(`onRequest`,async e=>{e.metadata={requestId:e.id,method:e.method,url:e.url,protocol:e.protocol,query:e.query,params:e.params,ip:(0,l.isNullOrEmpty)(e.ip)?e.ips?.[0]??e.ip:e.ip,locale:n.parseLocale(e.headers[K.acceptLanguage]),headers:e.headers}})},{name:`apikit-request-metadata`}),zn=(0,S.default)(async e=>{e.addHook(`onRequest`,(e,t,n)=>{let r=e.metadata;_t.run({metadata:r},()=>{n()})})},{name:`apikit-request-scope`,dependencies:[`apikit-request-metadata`]});const Bn=`[ApiKit:Static]`,Q={basicAuth:cn,cookie:fn,cors:pn,health:Sn,ip:Cn,metrics:Tn,multipart:En,requestLogger:Fn,requestMetadata:Rn,requestScope:zn,staticFiles:(0,S.default)(async(e,t)=>{let n=t.apikitController.staticFiles;if(!n.enabled){e.log.info(`${Bn} Disabled — skipping`);return}if(!n.publicDirectory){let t=`${Bn} publicDirectory is required when static files are enabled.`;throw e.log.error(t),Error(t)}await e.register(O.default,{root:n.publicDirectory,prefix:n.routePrefix,maxAge:n.maxAge,dotfiles:n.dotfiles,etag:n.etag,immutable:n.immutable,decorateReply:n.decorateReply,preCompressed:n.preCompressed}),e.log.info(`${Bn} Enabled from ${n.publicDirectory}`)},{name:`apikit-static`}),view:(0,S.default)(async e=>{await e.register(k.default,{engine:{ejs:ne.default}})},{name:`apikit-view`})},$=`[Server]`;let Vn=class{i18n;logger;configuration;server;constructor(e,t,n){this.i18n=e,this.logger=t,this.configuration=n,this.server=(0,A.default)({loggerInstance:this.logger.instance,logController:new A.LogController({disableRequestLogging:!0,requestIdLogLabel:`requestId`}),ajv:{customOptions:{strict:!0,keywords:[`example`]}},trustProxy:this.configuration.server.trustProxy})}get instance(){return this.server}async preparePlugins(e=async()=>{}){let t={i18nController:this.i18n,logger:this.logger,apikitController:this.configuration},n=[Q.cookie,Q.ip,Q.requestMetadata,Q.requestScope,Q.requestLogger,Q.cors,Q.multipart,Q.basicAuth,Q.health,Q.metrics],r=[Q.staticFiles,Q.view];for(let e of n)await this.server.register(e,t);await e(this.server,t);for(let e of r)await this.server.register(e,t)}async prepare(e){await this.configureErrorHandler(),await this.configureShutdownHandler(e)}async start(){let e=this.configuration.server.host,t=this.configuration.server.port;if(!Number.isInteger(t)||t<=0||t>65535)throw Error(`Invalid server port "${t}", must be an integer 1-65535.`);await this.server.ready(),await this.server.listen({host:e,port:t,listenTextResolver:e=>`${$} Listening at ${e}`}),this.logger.info(`${$} Debug mode ${this.configuration.isDebug?`ON`:`OFF`}`),this.logger.info(`${$} Started on ${e}:${t}`)}async configureErrorHandler(){this.server.setErrorHandler(async(e,t,n)=>{let r=Array.isArray(e.validation),i=!e.statusCode||e.statusCode===500,a=Y.make(`Server.INTERNAL_SERVER_ERROR`);switch(this.configuration.isDebug&&this.logger.debug(`${$} Error Handler:`,{error:e}),!0){case e instanceof V:return n.status(e.statusCode).send(e.toJSON());case r:{let t=Y.make(`Validation.BAD_REQUEST`),r=e.statusCode||t.statusCode,i=new V({statusCode:r,code:t.code,message:t.message});return n.status(r).send(i.toJSON())}case i:return this.logger.error(`${$} Internal Server Error`,{flag:c.LogFlag.Important,metadata:new q({requestId:t.metadata.requestId}),error:e}),n.status(500).send(a.toJSON());default:{let t=e.statusCode||500,r=new V({statusCode:t,code:e.code||e.name||a.code,message:e.message||a.message});return n.status(t).send(r.toJSON())}}})}async configureShutdownHandler(e){let t=async(t,n)=>{if(this.logger.warn(`${$} ⛔ Shutdown: ${t}`),e)try{await e()}catch(e){this.logger.error(`${$} ⚠️ Shutdown hook failed`,{error:e})}try{await this.server.close(),this.logger.info(`${$} ✅ Closed`)}catch(e){this.logger.error(`${$} ❌ Close failed`,{error:e})}n&&this.logger.error(`${$} 🚨 Fatal error during shutdown`,{error:n}),process.exit(+!!n)},n=[[`SIGINT`,()=>t(`SIGINT`)],[`SIGTERM`,()=>t(`SIGTERM`)],[`uncaughtException`,e=>t(`uncaughtException`,e)],[`unhandledRejection`,e=>t(`unhandledRejection`,e)]];for(let[e,t]of n)process.on(e,t)}};Vn=M([(0,f.injectable)(),I(0,(0,f.inject)(P.DI.I18n.Controller)),I(1,(0,f.inject)(l.CoreSymbols.DI.Logger)),I(2,(0,f.inject)(P.DI.Configuration.Controller)),F(`design:paramtypes`,[Object,Object,Object])],Vn);const Hn=`[ApiKit:Request]`;let Un=class{logger;responseController;constructor(e,t){this.logger=e,this.responseController=t}handler(e,t={}){return async(n,r)=>{try{let i=await e(n,t);return await this.responseController.sendResponse(n,r,i)}catch(e){throw await this.logError(n,e),e}}}preHandler(e,t={}){return async(n,r)=>{try{let i=await e(n,t);if(i)return await this.responseController.sendResponse(n,r,i)}catch(e){throw await this.logError(n,e),e}}}async logError(e,t){await(0,l.ignoreErrorAsync)(()=>{let n=e.metadata.requestId;t instanceof V?this.logger.info(`${Hn} Api error response`,{error:t,metadata:new q({requestId:n})}):this.logger.error(`${Hn} Unexpected error`,{flag:c.LogFlag.Important,error:t,metadata:new q({requestId:n})})})}};Un=M([(0,f.injectable)(),I(0,(0,f.inject)(l.CoreSymbols.DI.Logger)),I(1,(0,f.inject)(P.DI.Server.ResponseController)),F(`design:paramtypes`,[Object,Object])],Un);const Wn=`[ApiKit:Response]`;let Gn=class{logger;constructor(e){this.logger=e}async sendResponse(e,t,n){switch(n.responseType){case`JSON`:return await this.sendJSONResponse(e,t,n);case`File`:return await this.sendFileResponse(e,t,n);default:throw Error(`${Wn} Unsupported response type`)}}async sendJSONResponse(e,t,n){let r=this.createResponseHeaders(n.headers);return t.headers(r).type(`application/json`).status(n.statusCode).send(n.data)}async sendFileResponse(e,t,n){let r=this.createResponseHeaders(n.headers);t.headers(r).type(`text/html`).status(n.statusCode);try{if(n.shouldRender){let e=await t.viewAsync(n.filePath,n.data);return t.send(e)}return t.sendFile(n.filePath)}catch(t){let n=e.metadata.requestId;throw this.logger.error(`${Wn} File response failed`,{error:t,metadata:new q({requestId:n})}),t}}createResponseHeaders(e){return{[K.cacheControl]:`no-store`,...e||{}}}};Gn=M([(0,f.injectable)(),I(0,(0,f.inject)(l.CoreSymbols.DI.Logger)),F(`design:paramtypes`,[Object])],Gn);var Kn=class{assemble(e){e.bind(P.DI.Server.Controller).to(Vn).inSingletonScope(),e.bind(P.DI.Server.RequestController).to(Un).inSingletonScope(),e.bind(P.DI.Server.ResponseController).to(Gn).inSingletonScope()}};let qn=class{configuration;logger;constructor(e,t){this.configuration=e,this.logger=t}validate(e,t){try{return e.parse(t)}catch(e){this.handleError(e)}}async validateAsync(e,t){try{return await e.parseAsync(t)}catch(e){this.handleError(e)}}handleError(e){if(e instanceof fe.ZodError){this.configuration.isDebug&&this.logger.debug(`[ApiKit:Validation] Dto validation failed`,{details:{tree:fe.z.treeifyError(e)}});let t=this.buildValidationDetails(e),n=this.buildValidationMessage(e);throw Y.make(`Validation.INVALID_PROPERTIES`,{details:t,overrideMessage:n})}throw e}buildValidationDetails(e){return{issues:e.issues.map(e=>({code:e.code,path:e.path.map(e=>typeof e==`number`?e:String(e)),message:e.message}))}}buildValidationMessage(e){for(let t of e.issues){if(t.code!==`custom`||!t.params)continue;let e=t.params;if(!e?.i18n?.key)continue;let{key:n,values:r}=e.i18n;return r?vt.t(n,r):vt.t(n)}return null}};qn=M([(0,f.injectable)(),I(0,(0,f.inject)(P.DI.Configuration.Controller)),I(1,(0,f.inject)(l.CoreSymbols.DI.Logger)),F(`design:paramtypes`,[Object,Object])],qn);let Jn=class{isValidEmail(e){return!!e&&b.default.isEmail(e)}isValidEmailThrowing(e){if(!this.isValidEmail(e))throw Y.make(`Validation.INVALID_EMAIL_FORMAT`)}isValidPhoneNumber(e,t){if(!e)return!1;let n;return n=t?(0,y.parsePhoneNumberFromString)(e,t):(0,y.parsePhoneNumberFromString)(e),!!n?.isValid()}isValidPhoneNumberThrowing(e,t){if(!this.isValidPhoneNumber(e,t))throw Y.make(`Validation.INVALID_PHONE_NUMBER_FORMAT`)}isValidCode(e){return!!e&&/^\d{6}$/.test(e)}isValidCodeThrowing(e){if(!this.isValidCode(e))throw Y.make(`Validation.INVALID_FORMAT`,{details:`Input is not a valid code`})}isEmail(e){return!!e&&b.default.isEmail(e)}isEmailThrowing(e){if(!this.isEmail(e))throw Y.make(`Validation.INVALID_EMAIL_FORMAT`)}isPhoneNumber(e){return!!e&&b.default.isMobilePhone(e)}isPhoneNumberThrowing(e){if(!this.isPhoneNumber(e))throw Y.make(`Validation.INVALID_PHONE_NUMBER_FORMAT`)}isNumber(e){return typeof e==`number`&&!isNaN(e)}isNumberThrowing(e){if(!this.isNumber(e))throw Y.make(`Validation.INVALID_PROPERTIES`,{details:`Input is not a valid number`})}isString(e){return typeof e==`string`}isStringThrowing(e){if(!this.isString(e))throw Y.make(`Validation.INVALID_PROPERTIES`,{details:`Input is not a valid string`})}isEmptyString(e){return e==null||e.trim()===``}isEmptyStringThrowing(e){if(!this.isEmptyString(e))throw Y.make(`Validation.INVALID_PROPERTIES`,{details:`Input is not an empty string`})}isNonEmptyString(e){return this.isString(e)&&!this.isEmptyString(e)}isNonEmptyStringThrowing(e){let t=e;if(typeof t!=`string`||t.trim()===``)throw Y.make(`Validation.INVALID_PROPERTIES`,{details:`Input is empty or not a string`});return t}isValidDate(e){if(!e)return!1;let t=new Date(e);return!isNaN(t.getTime())}isValidDateThrowing(e){if(!this.isValidDate(e))throw Y.make(`Validation.INVALID_DATE_FORMAT`);return new Date(e)}};Jn=M([(0,f.injectable)()],Jn);var Yn=class{assemble(e){e.bind(P.DI.Validation.Controller).to(Jn),e.bind(P.DI.Validation.DtoController).to(qn)}};function Xn(){return[new We,new Ke,new Xe,new Ze,new Lt,new Vt,new Ht,new Wt,new Kt,new nn,new an,new sn,new Kn,new Yn]}function Zn(){let e=global.apikit.loggerConfig,t=e.enabled?{enabled:!0,debug:global.apikit.serverConfig.debug,transports:e.transports}:{enabled:!1,debug:global.apikit.serverConfig.debug};return[...(0,c.coreNodeAssembly)({logger:t}),...Xn()]}exports.ApiError=V,exports.ApiErrorCodes=Dt,exports.ApiErrorFactory=Y,Object.defineProperty(exports,"ApiKitControllerImpl",{enumerable:!0,get:function(){return Le}}),exports.ApiKitL10n=W,exports.ApiKitL10nResource=U,exports.ApiKitSymbols=P,exports.AuthorizationErrors=Ct,exports.BaseEmailTemplate=Ye,exports.BasicAuthConfiguration=ge,exports.BuildConfiguration=_e,exports.CommonErrors=bt,exports.Cookie=ct,exports.CorsConfiguration=ve,Object.defineProperty(exports,"CryptographyControllerImpl",{enumerable:!0,get:function(){return Z}}),exports.DEFAULT_GENERATE_STRING_OPTIONS=Rt,Object.defineProperty(exports,"DtoValidationControllerImpl",{enumerable:!0,get:function(){return qn}}),exports.EmailConfiguration=be,Object.defineProperty(exports,"EmailControllerImpl",{enumerable:!0,get:function(){return R}}),exports.FastifyPlugins=Q,exports.FileHttpResponse=pt,exports.FormatErrors=Tt,exports.FormatType=Nt,exports.Formatter=Pt,Object.defineProperty(exports,"FormatterControllerImpl",{enumerable:!0,get:function(){return Ft}}),exports.HealthConfiguration=xe,exports.HttpHeaders=K,exports.HttpMethod=lt,exports.HttpResponse=dt,exports.I18nConfiguration=Ce,Object.defineProperty(exports,"I18nControllerImpl",{enumerable:!0,get:function(){return G}}),exports.I18nFactory=yt,exports.I18nProvider=vt,exports.ImageErrors=Et,Object.defineProperty(exports,"ImageNormalizationControllerImpl",{enumerable:!0,get:function(){return Ut}}),exports.JSONHttpResponse=ft,exports.LimitErrors=St,exports.LoggerConfiguration=we,exports.MetricsConfiguration=Oe,Object.defineProperty(exports,"MongoDbQueryFormatterImpl",{enumerable:!0,get:function(){return Ge}}),exports.MultipartConfiguration=ke,Object.defineProperty(exports,"MultipartFormatterControllerImpl",{enumerable:!0,get:function(){return It}}),Object.defineProperty(exports,"NormalizationControllerImpl",{enumerable:!0,get:function(){return Gt}}),exports.NotificationChannel=Xt,exports.NotificationConfiguration=Ae,Object.defineProperty(exports,"OpenAPISchemaControllerImpl",{enumerable:!0,get:function(){return rn}}),exports.RANDOM_VALUE_GENERATOR_LIMITS=X,Object.defineProperty(exports,"RandomValueGeneratorImpl",{enumerable:!0,get:function(){return Bt}}),Object.defineProperty(exports,"RequestControllerImpl",{enumerable:!0,get:function(){return Un}}),exports.RequestLogMetadata=q,exports.RequestScope=_t,Object.defineProperty(exports,"ResponseControllerImpl",{enumerable:!0,get:function(){return Gn}}),exports.ResponseType=ut,exports.ServerConfiguration=Fe,Object.defineProperty(exports,"ServerControllerImpl",{enumerable:!0,get:function(){return Vn}}),exports.ServerErrors=xt,exports.StaticFilesConfiguration=Ie,Object.defineProperty(exports,"TemporaryFileRepositoryImpl",{enumerable:!0,get:function(){return B}}),exports.Token=on,Object.defineProperty(exports,"ValidationControllerImpl",{enumerable:!0,get:function(){return Jn}}),exports.ValidationErrors=wt,exports.apikitAssembly=Zn,exports.defineConfig=He,exports.defineErrors=J,Object.defineProperty(exports,"fastifyBasicAuth",{enumerable:!0,get:function(){return de.default}}),Object.defineProperty(exports,"fastifyCookie",{enumerable:!0,get:function(){return g.default}}),Object.defineProperty(exports,"fastifyCors",{enumerable:!0,get:function(){return C.default}}),Object.defineProperty(exports,"fastifyIp",{enumerable:!0,get:function(){return T.default}}),Object.defineProperty(exports,"fastifyMetrics",{enumerable:!0,get:function(){return E.default}}),Object.defineProperty(exports,"fastifyMultipart",{enumerable:!0,get:function(){return D.default}}),Object.defineProperty(exports,"fastifyStatic",{enumerable:!0,get:function(){return O.default}}),Object.defineProperty(exports,"fastifyUnderPressure",{enumerable:!0,get:function(){return w.default}}),Object.defineProperty(exports,"fastifyView",{enumerable:!0,get:function(){return k.default}}),Object.defineProperty(exports,"fp",{enumerable:!0,get:function(){return S.default}}),exports.isApiErrorDefinition=H,exports.loadApiKitContext=ze,Object.keys(l).forEach(function(e){e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:function(){return l[e]}})}),Object.keys(c).forEach(function(e){e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:function(){return c[e]}})});