@forinda/kickjs 10.11.0 → 10.12.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/dist/{application-EinAcKLu.d.mts → application-Rb6jeTAp.d.mts} +55 -2
- package/dist/application-Rb6jeTAp.d.mts.map +1 -0
- package/dist/{application-BCXdtJd1.mjs → application-W8fhRn97.mjs} +3 -3
- package/dist/{application-BCXdtJd1.mjs.map → application-W8fhRn97.mjs.map} +1 -1
- package/dist/{body-policy-DccDxmmR.mjs → body-policy-cWfUReGC.mjs} +2 -2
- package/dist/{body-policy-DccDxmmR.mjs.map → body-policy-cWfUReGC.mjs.map} +1 -1
- package/dist/{bootstrap-C5op763j.mjs → bootstrap-Cg3-PXxu.mjs} +3 -3
- package/dist/{bootstrap-C5op763j.mjs.map → bootstrap-Cg3-PXxu.mjs.map} +1 -1
- package/dist/{bounded-counters-CmmPOr2v.mjs → bounded-counters-BIrM6PXT.mjs} +2 -2
- package/dist/{bounded-counters-CmmPOr2v.mjs.map → bounded-counters-BIrM6PXT.mjs.map} +1 -1
- package/dist/{client-ip-STshfERA.mjs → client-ip-BAtoGmC3.mjs} +2 -2
- package/dist/{client-ip-STshfERA.mjs.map → client-ip-BAtoGmC3.mjs.map} +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-DZd8tqGC.mjs → config-DCjeCuL2.mjs} +3 -3
- package/dist/{config-DZd8tqGC.mjs.map → config-DCjeCuL2.mjs.map} +1 -1
- package/dist/{context-BJ6HVq4W.mjs → context-Cc6k0gsM.mjs} +3 -3
- package/dist/{context-BJ6HVq4W.mjs.map → context-Cc6k0gsM.mjs.map} +1 -1
- package/dist/{context-errors-s1zG7eax.mjs → context-errors-BULDLnr1.mjs} +2 -2
- package/dist/{context-errors-s1zG7eax.mjs.map → context-errors-BULDLnr1.mjs.map} +1 -1
- package/dist/{contributor-runner-B5pv7_R-.mjs → contributor-runner-CKv5LriN.mjs} +3 -3
- package/dist/{contributor-runner-B5pv7_R-.mjs.map → contributor-runner-CKv5LriN.mjs.map} +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/logger.mjs +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +2 -2
- package/dist/{core-Cf6gPv9R.mjs → core-Kqw_11xA.mjs} +3 -3
- package/dist/{core-Cf6gPv9R.mjs.map → core-Kqw_11xA.mjs.map} +1 -1
- package/dist/{decorate-BQA6M9jq.mjs → decorate-Dji9dYab.mjs} +3 -3
- package/dist/{decorate-BQA6M9jq.mjs.map → decorate-Dji9dYab.mjs.map} +1 -1
- package/dist/{define-adapter-B9DcBJKt.mjs → define-adapter-DqTV48jK.mjs} +2 -2
- package/dist/{define-adapter-B9DcBJKt.mjs.map → define-adapter-DqTV48jK.mjs.map} +1 -1
- package/dist/{di-hooks-DGmtRWDI.mjs → di-hooks-CUWf3HlQ.mjs} +2 -2
- package/dist/{di-hooks-DGmtRWDI.mjs.map → di-hooks-CUWf3HlQ.mjs.map} +1 -1
- package/dist/{disposables-C1xhXyD6.mjs → disposables-D7NlxYjq.mjs} +1 -1
- package/dist/{express-DqWsJylQ.mjs → express-B6jvEdCZ.mjs} +3 -3
- package/dist/{express-DqWsJylQ.mjs.map → express-B6jvEdCZ.mjs.map} +1 -1
- package/dist/{express-lazy-CdPN1krb.mjs → express-lazy-BE10FhlA.mjs} +3 -3
- package/dist/{express-lazy-CdPN1krb.mjs.map → express-lazy-BE10FhlA.mjs.map} +1 -1
- package/dist/{handler-Ce16qhGr.mjs → handler-BpMOjmfq.mjs} +3 -3
- package/dist/{handler-Ce16qhGr.mjs.map → handler-BpMOjmfq.mjs.map} +1 -1
- package/dist/{host-BZcjkJ-A.mjs → host-B5w-Sz-2.mjs} +2 -2
- package/dist/{host-BZcjkJ-A.mjs.map → host-B5w-Sz-2.mjs.map} +1 -1
- package/dist/http/application.d.mts +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.d.mts +1 -1
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/allowed-hosts.mjs +2 -2
- package/dist/http/middleware/breach-padding.mjs +1 -1
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/spa.d.mts +1 -1
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/views.d.mts +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/express.mjs +2 -2
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/h3-web.mjs +1 -1
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/dist/{is-production-et6gyyxF.mjs → is-production-D0kfhCW4.mjs} +2 -2
- package/dist/{is-production-et6gyyxF.mjs.map → is-production-D0kfhCW4.mjs.map} +1 -1
- package/dist/{jobs-B4wle0iS.mjs → jobs-F8vpXQt7.mjs} +3 -3
- package/dist/{jobs-B4wle0iS.mjs.map → jobs-F8vpXQt7.mjs.map} +1 -1
- package/dist/{kv-stores-CLR0N5im.mjs → kv-stores-DxVO4y2v.mjs} +3 -3
- package/dist/{kv-stores-CLR0N5im.mjs.map → kv-stores-DxVO4y2v.mjs.map} +1 -1
- package/dist/{lazy-serve-static-CKaL8clq.mjs → lazy-serve-static-BeucQAk2.mjs} +3 -3
- package/dist/{lazy-serve-static-CKaL8clq.mjs.map → lazy-serve-static-BeucQAk2.mjs.map} +1 -1
- package/dist/{metadata-CsfVw6pp.mjs → metadata-DeXrp8uO.mjs} +1 -1
- package/dist/{observers-BbNYzGfC.mjs → observers-DL7RRlLR.mjs} +2 -2
- package/dist/{observers-BbNYzGfC.mjs.map → observers-DL7RRlLR.mjs.map} +1 -1
- package/dist/{precompressed-BTEVCjT_.mjs → precompressed-CYkmmoRU.mjs} +2 -2
- package/dist/{precompressed-BTEVCjT_.mjs.map → precompressed-CYkmmoRU.mjs.map} +1 -1
- package/dist/{query-EQM3lEr_.mjs → query-Coc1hIiS.mjs} +2 -2
- package/dist/{query-EQM3lEr_.mjs.map → query-Coc1hIiS.mjs.map} +1 -1
- package/dist/{reply-Detphot1.mjs → reply-Bg1gyBtE.mjs} +3 -3
- package/dist/{reply-Detphot1.mjs.map → reply-Bg1gyBtE.mjs.map} +1 -1
- package/dist/{request-scope-D5ggZdvq.mjs → request-scope-R9FuLLnB.mjs} +3 -3
- package/dist/{request-scope-D5ggZdvq.mjs.map → request-scope-R9FuLLnB.mjs.map} +1 -1
- package/dist/{respond-B_5BPAJp.mjs → respond-BDd0h6bG.mjs} +2 -2
- package/dist/{respond-B_5BPAJp.mjs.map → respond-BDd0h6bG.mjs.map} +1 -1
- package/dist/{rolldown-runtime-BgeRdaSa.mjs → rolldown-runtime-OjcH9Gd_.mjs} +1 -1
- package/dist/{route-flag-CO7wkxhn.mjs → route-flag-ECQsPj4x.mjs} +3 -3
- package/dist/{route-flag-CO7wkxhn.mjs.map → route-flag-ECQsPj4x.mjs.map} +1 -1
- package/dist/{route-policy-DJd0iddt.mjs → route-policy-0ZBRrh9x.mjs} +2 -2
- package/dist/{route-policy-DJd0iddt.mjs.map → route-policy-0ZBRrh9x.mjs.map} +1 -1
- package/dist/{router-builder-DtjsnD0b.mjs → router-builder-abKMvAmP.mjs} +3 -3
- package/dist/{router-builder-DtjsnD0b.mjs.map → router-builder-abKMvAmP.mjs.map} +1 -1
- package/dist/{settings-CJWJPERr.mjs → settings-vuB5TedF.mjs} +3 -3
- package/dist/{settings-CJWJPERr.mjs.map → settings-vuB5TedF.mjs.map} +1 -1
- package/dist/{token-kfP7I0D6.mjs → token-BJJiF3_2.mjs} +1 -1
- package/dist/{upload-config-DldXNOHe.mjs → upload-config-TFTYQPaH.mjs} +2 -2
- package/dist/{upload-config-DldXNOHe.mjs.map → upload-config-TFTYQPaH.mjs.map} +1 -1
- package/dist/{url-for-O-DQnRvH.mjs → url-for-kZidAFyr.mjs} +3 -3
- package/dist/{url-for-O-DQnRvH.mjs.map → url-for-kZidAFyr.mjs.map} +1 -1
- package/dist/{view-renderer-NbkTobFF.mjs → view-renderer-CSPD7F-f.mjs} +3 -3
- package/dist/{view-renderer-NbkTobFF.mjs.map → view-renderer-CSPD7F-f.mjs.map} +1 -1
- package/dist/{web-crypto-BNP8o7BF.mjs → web-crypto-Q0WFs8ua.mjs} +2 -2
- package/dist/{web-crypto-BNP8o7BF.mjs.map → web-crypto-Q0WFs8ua.mjs.map} +1 -1
- package/dist/web.mjs +2 -2
- package/package.json +1 -1
- package/dist/application-EinAcKLu.d.mts.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.12.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
import{HttpException,HttpStatus}from"./core/errors.mjs";const MIME_MAP={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`,bmp:`image/bmp`,ico:`image/x-icon`,tiff:`image/tiff`,tif:`image/tiff`,avif:`image/avif`,pdf:`application/pdf`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,odt:`application/vnd.oasis.opendocument.text`,ods:`application/vnd.oasis.opendocument.spreadsheet`,odp:`application/vnd.oasis.opendocument.presentation`,rtf:`application/rtf`,txt:`text/plain`,csv:`text/csv`,zip:`application/zip`,gz:`application/gzip`,tar:`application/x-tar`,rar:`application/vnd.rar`,"7z":`application/x-7z-compressed`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`,flac:`audio/flac`,aac:`audio/aac`,mp4:`video/mp4`,webm:`video/webm`,avi:`video/x-msvideo`,mov:`video/quicktime`,mkv:`video/x-matroska`,json:`application/json`,xml:`application/xml`,html:`text/html`};function resolveMimeTypes(types){return types.map(t=>{let lower=t.toLowerCase().replace(/^\./,``);return MIME_MAP[lower]??t})}function buildFileTypeFilter(allowedTypes,customMimeMap){if(!allowedTypes)return()=>!0;if(typeof allowedTypes==`function`)return allowedTypes;let mimeMap=customMimeMap?{...MIME_MAP,...customMimeMap}:MIME_MAP,resolved=allowedTypes.map(t=>mimeMap[t.toLowerCase().replace(/^\./,``)]??t);return mimetype=>resolved.some(type=>type.endsWith(`/*`)?mimetype.startsWith(type.replace(`/*`,`/`)):mimetype===type)}const DEFAULT_MAX_SIZE=5242880;function normalizeOriginalName(name){return(name.normalize(`NFC`).split(/[\\/]/).pop()??``).replace(/[\u0000-\u001f\u007f]/g,``).trim()}function matchingExtension(name,mimetype,customMimeMap){let dot=name.lastIndexOf(`.`);if(dot<=0)return``;let ext=name.slice(dot+1).toLowerCase(),type=mimetype.split(`;`)[0].trim().toLowerCase();return(customMimeMap?.[ext]??MIME_MAP[ext])===type?`.${ext}`:``}function serverFileName(file,options={}){let{rename,customMimeMap}=options;if(!rename){let ext=matchingExtension(file.originalname,file.mimetype,customMimeMap);return`${globalThis.crypto.randomUUID()}${ext}`}let name=rename(file);if(typeof name!=`string`||name===``||name===`.`||name===`..`||name.length>255||/[\\/\0]/.test(name))throw Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`);return name}const UPLOAD_FIELDS_ALLOWANCE=1048576,MAX_UPLOAD_FIELDS=1e3;function uploadLimits(config){let fileSize=config.maxSize??DEFAULT_MAX_SIZE,files=config.mode===`none`?0:config.mode===`single`?1:config.maxCount??10;return{fileSize,files,total:fileSize*files+UPLOAD_FIELDS_ALLOWANCE}}function tooManyFiles(limit){return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`Too many files: at most ${limit}`)}function applyUploadConfig(parts,config){if(config.mode===`none`)return{};let field=config.fieldName??`file`,maxSize=config.maxSize??DEFAULT_MAX_SIZE,typeAllowed=buildFileTypeFilter(config.allowedTypes,config.customMimeMap),files=parts.filter(p=>p.fieldname===field).map(p=>{if(!typeAllowed(p.mimetype,p.filename))throw new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${p.mimetype} is not allowed`);if(p.buffer.length>maxSize)throw new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${p.filename} exceeds the ${maxSize}-byte limit`);let named={fieldname:p.fieldname,originalname:normalizeOriginalName(p.filename),mimetype:p.mimetype,size:p.buffer.length};return{...named,filename:serverFileName(named,config),encoding:`7bit`,buffer:p.buffer}});if(config.mode===`single`)return{file:files[0]};let maxCount=config.maxCount??10;return{files:files.slice(0,maxCount)}}export{normalizeOriginalName as a,tooManyFiles as c,buildFileTypeFilter as i,uploadLimits as l,UPLOAD_FIELDS_ALLOWANCE as n,resolveMimeTypes as o,applyUploadConfig as r,serverFileName as s,MAX_UPLOAD_FIELDS as t};
|
|
12
|
-
//# sourceMappingURL=upload-config-
|
|
12
|
+
//# sourceMappingURL=upload-config-TFTYQPaH.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"upload-config-DldXNOHe.mjs","names":[],"sources":["../src/http/middleware/upload-config.ts"],"sourcesContent":["// Pure (edge-safe) upload core — the engine-neutral half of the upload\n// middleware. Extracted from `upload.ts` so the `@forinda/kickjs/web` entry\n// graph can validate/shape buffered multipart parts WITHOUT dragging in\n// upload.ts's node-only surface (multer peer loading via `node:module`,\n// disk cleanup via `node:fs/promises`). `upload.ts` re-exports everything\n// here, so existing import sites are unchanged.\n\nimport { HttpException, HttpStatus } from '../../core/errors'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core/decorators'\n\nexport const MIME_MAP: Record<string, string> = {\n // Images\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n bmp: 'image/bmp',\n ico: 'image/x-icon',\n tiff: 'image/tiff',\n tif: 'image/tiff',\n avif: 'image/avif',\n // Documents\n pdf: 'application/pdf',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n odt: 'application/vnd.oasis.opendocument.text',\n ods: 'application/vnd.oasis.opendocument.spreadsheet',\n odp: 'application/vnd.oasis.opendocument.presentation',\n rtf: 'application/rtf',\n txt: 'text/plain',\n csv: 'text/csv',\n // Archives\n zip: 'application/zip',\n gz: 'application/gzip',\n tar: 'application/x-tar',\n rar: 'application/vnd.rar',\n '7z': 'application/x-7z-compressed',\n // Audio\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n flac: 'audio/flac',\n aac: 'audio/aac',\n // Video\n mp4: 'video/mp4',\n webm: 'video/webm',\n avi: 'video/x-msvideo',\n mov: 'video/quicktime',\n mkv: 'video/x-matroska',\n // Other\n json: 'application/json',\n xml: 'application/xml',\n html: 'text/html',\n}\n\n/**\n * Resolves a list of file type identifiers to MIME type strings.\n * Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).\n *\n * @example\n * ```ts\n * resolveMimeTypes(['jpg', 'png', 'application/pdf'])\n * // → ['image/jpeg', 'image/png', 'application/pdf']\n * ```\n */\nexport function resolveMimeTypes(types: string[]): string[] {\n return types.map((t) => {\n const lower = t.toLowerCase().replace(/^\\./, '')\n return MIME_MAP[lower] ?? t\n })\n}\n\n/**\n * Build a runtime-agnostic `(mimetype, filename) => boolean` file-type filter\n * from `allowedTypes` (a predicate, or a list of extensions / MIME types /\n * wildcards). Returned by both the multer middleware (Express) and the\n * Fastify / h3 / web multipart paths so the accept/reject rule stays\n * identical across engines. No `allowedTypes` → accept everything.\n */\nexport function buildFileTypeFilter(\n allowedTypes: BaseUploadOptions['allowedTypes'],\n customMimeMap?: Record<string, string>,\n): (mimetype: string, filename: string) => boolean {\n if (!allowedTypes) return () => true\n if (typeof allowedTypes === 'function') return allowedTypes\n const mimeMap = customMimeMap ? { ...MIME_MAP, ...customMimeMap } : MIME_MAP\n const resolved = allowedTypes.map((t) => mimeMap[t.toLowerCase().replace(/^\\./, '')] ?? t)\n return (mimetype: string) =>\n resolved.some((type) =>\n type.endsWith('/*') ? mimetype.startsWith(type.replace('/*', '/')) : mimetype === type,\n )\n}\n\n/** A multer-shaped uploaded file — what `ctx.file` / `ctx.files` expose. */\nexport interface UploadedFileLike {\n fieldname: string\n /**\n * The client's name for the file, made safe to show: Unicode NFC, no\n * directory part, no control characters. Still the client's choice — use\n * `filename` to store the file.\n */\n originalname: string\n /** The server-side name: generated (or from `rename`), safe as a storage key. */\n filename: string\n encoding: string\n mimetype: string\n size: number\n buffer: Buffer\n}\n\n/**\n * An uploaded file as `ctx.file` / `ctx.files` hold it, on every runtime —\n * multer's shape, declared here so the typings need no `@types/multer`. The\n * disk fields are set only by `upload({ dest })` / a multer `diskStorage`\n * (Express), which leaves `buffer` unset, as multer does.\n */\nexport interface UploadedFile extends UploadedFileLike {\n destination?: string\n path?: string\n}\n\n/**\n * A multer storage engine — `multer.diskStorage()`, `multer.memoryStorage()` or\n * your own — declared here so the typings need no `@types/multer`.\n */\nexport interface UploadStorageEngine {\n _handleFile(req: any, file: any, callback: (error?: any, info?: any) => void): void\n _removeFile(req: any, file: any, callback: (error: Error | null) => void): void\n}\n\n/** A buffered multipart file part, as the runtime hands it to {@link applyUploadConfig}. */\nexport interface RawUploadPart {\n fieldname: string\n filename: string\n mimetype: string\n buffer: Buffer\n}\n\nconst DEFAULT_MAX_SIZE = 5 * 1024 * 1024\n\n/**\n * The client's file name made safe to show: Unicode NFC (so the same text\n * compares equal however the client composed it), without a directory part\n * (`C:\\fakepath\\a.png` → `a.png`) or control characters. Non-Latin text and\n * emoji are kept as they are.\n */\nexport function normalizeOriginalName(name: string): string {\n const base = name.normalize('NFC').split(/[\\\\/]/).pop() ?? ''\n // oxlint-disable-next-line no-control-regex\n return base.replace(/[\\u0000-\\u001f\\u007f]/g, '').trim()\n}\n\n/**\n * The client name's extension, kept only when it names the file's own type:\n * `photo.PNG` sent as `image/png` → `.png`. `evil.html` sent as `image/png`\n * gets none — an extension the type check never saw must not decide how the\n * stored file is later served.\n */\nfunction matchingExtension(\n name: string,\n mimetype: string,\n customMimeMap?: Record<string, string>,\n): string {\n const dot = name.lastIndexOf('.')\n if (dot <= 0) return ''\n const ext = name.slice(dot + 1).toLowerCase()\n const type = mimetype.split(';')[0]!.trim().toLowerCase()\n return (customMimeMap?.[ext] ?? MIME_MAP[ext]) === type ? `.${ext}` : ''\n}\n\n/**\n * The server-side name for an upload: `rename`'s, checked, or a random UUID\n * plus the extension of the file's type when the client name carries it.\n */\nexport function serverFileName(\n file: { originalname: string; mimetype: string; fieldname: string; size: number },\n options: Pick<BaseUploadOptions, 'rename' | 'customMimeMap'> = {},\n): string {\n const { rename, customMimeMap } = options\n if (!rename) {\n const ext = matchingExtension(file.originalname, file.mimetype, customMimeMap)\n return `${globalThis.crypto.randomUUID()}${ext}`\n }\n const name = rename(file)\n if (\n typeof name !== 'string' ||\n name === '' ||\n name === '.' ||\n name === '..' ||\n name.length > 255 ||\n /[\\\\/\\0]/.test(name)\n ) {\n throw new Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`)\n }\n return name\n}\n\n/** What an upload request may carry besides its files: field values, part headers. */\nexport const UPLOAD_FIELDS_ALLOWANCE = 1024 * 1024\n\n/** Form fields an upload request may carry beside its files. */\nexport const MAX_UPLOAD_FIELDS = 1000\n\n/**\n * The most a `@FileUpload` request may carry, for stopping the parser before it\n * buffers more: `fileSize` per file, `files` in all (on any field), and `total`\n * bytes for the whole body.\n */\nexport function uploadLimits(config: FileUploadConfig): {\n fileSize: number\n files: number\n total: number\n} {\n const fileSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const files = config.mode === 'none' ? 0 : config.mode === 'single' ? 1 : (config.maxCount ?? 10)\n return { fileSize, files, total: fileSize * files + UPLOAD_FIELDS_ALLOWANCE }\n}\n\n/** The 413 for more files than a route takes. */\nexport function tooManyFiles(limit: number): HttpException {\n return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE, `Too many files: at most ${limit}`)\n}\n\n/**\n * Apply a `@FileUpload` config to already-buffered multipart parts and return\n * the multer-shaped `file` / `files` for `ctx`. Enforces the field name, type\n * filter, per-file size limit, and (array mode) max count — throwing\n * `HttpException` on a violation, mirroring the Express/multer error path.\n * Used by the Fastify, h3 and web runtimes; Express keeps using multer directly.\n */\nexport function applyUploadConfig(\n parts: RawUploadPart[],\n config: FileUploadConfig,\n): { file?: UploadedFileLike; files?: UploadedFileLike[] } {\n if (config.mode === 'none') return {}\n\n const field = config.fieldName ?? 'file'\n const maxSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const typeAllowed = buildFileTypeFilter(config.allowedTypes, config.customMimeMap)\n\n const matched = parts.filter((p) => p.fieldname === field)\n const files: UploadedFileLike[] = matched.map((p) => {\n if (!typeAllowed(p.mimetype, p.filename)) {\n throw new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${p.mimetype} is not allowed`,\n )\n }\n if (p.buffer.length > maxSize) {\n throw new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${p.filename} exceeds the ${maxSize}-byte limit`,\n )\n }\n const named = {\n fieldname: p.fieldname,\n originalname: normalizeOriginalName(p.filename),\n mimetype: p.mimetype,\n size: p.buffer.length,\n }\n return {\n ...named,\n filename: serverFileName(named, config),\n encoding: '7bit',\n buffer: p.buffer,\n }\n })\n\n if (config.mode === 'single') return { file: files[0] }\n const maxCount = config.maxCount ?? 10\n return { files: files.slice(0, maxCount) }\n}\n"],"mappings":";;;;;;;;;;wDAUA,MAAa,SAAmC,CAE9C,IAAK,aACL,KAAM,aACN,IAAK,YACL,IAAK,YACL,KAAM,aACN,IAAK,gBACL,IAAK,YACL,IAAK,eACL,KAAM,aACN,IAAK,aACL,KAAM,aAEN,IAAK,kBACL,IAAK,qBACL,KAAM,0EACN,IAAK,2BACL,KAAM,oEACN,IAAK,gCACL,KAAM,4EACN,IAAK,0CACL,IAAK,iDACL,IAAK,kDACL,IAAK,kBACL,IAAK,aACL,IAAK,WAEL,IAAK,kBACL,GAAI,mBACJ,IAAK,oBACL,IAAK,sBACL,KAAM,8BAEN,IAAK,aACL,IAAK,YACL,IAAK,YACL,KAAM,aACN,IAAK,YAEL,IAAK,YACL,KAAM,aACN,IAAK,kBACL,IAAK,kBACL,IAAK,mBAEL,KAAM,mBACN,IAAK,kBACL,KAAM,WACR,EAYA,SAAgB,iBAAiB,MAA2B,CAC1D,OAAO,MAAM,IAAK,GAAM,CACtB,IAAM,MAAQ,EAAE,YAAY,CAAC,CAAC,QAAQ,MAAO,EAAE,EAC/C,OAAO,SAAS,QAAU,CAC5B,CAAC,CACH,CASA,SAAgB,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","names":[],"sources":["../src/http/middleware/upload-config.ts"],"sourcesContent":["// Pure (edge-safe) upload core — the engine-neutral half of the upload\n// middleware. Extracted from `upload.ts` so the `@forinda/kickjs/web` entry\n// graph can validate/shape buffered multipart parts WITHOUT dragging in\n// upload.ts's node-only surface (multer peer loading via `node:module`,\n// disk cleanup via `node:fs/promises`). `upload.ts` re-exports everything\n// here, so existing import sites are unchanged.\n\nimport { HttpException, HttpStatus } from '../../core/errors'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core/decorators'\n\nexport const MIME_MAP: Record<string, string> = {\n // Images\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n bmp: 'image/bmp',\n ico: 'image/x-icon',\n tiff: 'image/tiff',\n tif: 'image/tiff',\n avif: 'image/avif',\n // Documents\n pdf: 'application/pdf',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n odt: 'application/vnd.oasis.opendocument.text',\n ods: 'application/vnd.oasis.opendocument.spreadsheet',\n odp: 'application/vnd.oasis.opendocument.presentation',\n rtf: 'application/rtf',\n txt: 'text/plain',\n csv: 'text/csv',\n // Archives\n zip: 'application/zip',\n gz: 'application/gzip',\n tar: 'application/x-tar',\n rar: 'application/vnd.rar',\n '7z': 'application/x-7z-compressed',\n // Audio\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n flac: 'audio/flac',\n aac: 'audio/aac',\n // Video\n mp4: 'video/mp4',\n webm: 'video/webm',\n avi: 'video/x-msvideo',\n mov: 'video/quicktime',\n mkv: 'video/x-matroska',\n // Other\n json: 'application/json',\n xml: 'application/xml',\n html: 'text/html',\n}\n\n/**\n * Resolves a list of file type identifiers to MIME type strings.\n * Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).\n *\n * @example\n * ```ts\n * resolveMimeTypes(['jpg', 'png', 'application/pdf'])\n * // → ['image/jpeg', 'image/png', 'application/pdf']\n * ```\n */\nexport function resolveMimeTypes(types: string[]): string[] {\n return types.map((t) => {\n const lower = t.toLowerCase().replace(/^\\./, '')\n return MIME_MAP[lower] ?? t\n })\n}\n\n/**\n * Build a runtime-agnostic `(mimetype, filename) => boolean` file-type filter\n * from `allowedTypes` (a predicate, or a list of extensions / MIME types /\n * wildcards). Returned by both the multer middleware (Express) and the\n * Fastify / h3 / web multipart paths so the accept/reject rule stays\n * identical across engines. No `allowedTypes` → accept everything.\n */\nexport function buildFileTypeFilter(\n allowedTypes: BaseUploadOptions['allowedTypes'],\n customMimeMap?: Record<string, string>,\n): (mimetype: string, filename: string) => boolean {\n if (!allowedTypes) return () => true\n if (typeof allowedTypes === 'function') return allowedTypes\n const mimeMap = customMimeMap ? { ...MIME_MAP, ...customMimeMap } : MIME_MAP\n const resolved = allowedTypes.map((t) => mimeMap[t.toLowerCase().replace(/^\\./, '')] ?? t)\n return (mimetype: string) =>\n resolved.some((type) =>\n type.endsWith('/*') ? mimetype.startsWith(type.replace('/*', '/')) : mimetype === type,\n )\n}\n\n/** A multer-shaped uploaded file — what `ctx.file` / `ctx.files` expose. */\nexport interface UploadedFileLike {\n fieldname: string\n /**\n * The client's name for the file, made safe to show: Unicode NFC, no\n * directory part, no control characters. Still the client's choice — use\n * `filename` to store the file.\n */\n originalname: string\n /** The server-side name: generated (or from `rename`), safe as a storage key. */\n filename: string\n encoding: string\n mimetype: string\n size: number\n buffer: Buffer\n}\n\n/**\n * An uploaded file as `ctx.file` / `ctx.files` hold it, on every runtime —\n * multer's shape, declared here so the typings need no `@types/multer`. The\n * disk fields are set only by `upload({ dest })` / a multer `diskStorage`\n * (Express), which leaves `buffer` unset, as multer does.\n */\nexport interface UploadedFile extends UploadedFileLike {\n destination?: string\n path?: string\n}\n\n/**\n * A multer storage engine — `multer.diskStorage()`, `multer.memoryStorage()` or\n * your own — declared here so the typings need no `@types/multer`.\n */\nexport interface UploadStorageEngine {\n _handleFile(req: any, file: any, callback: (error?: any, info?: any) => void): void\n _removeFile(req: any, file: any, callback: (error: Error | null) => void): void\n}\n\n/** A buffered multipart file part, as the runtime hands it to {@link applyUploadConfig}. */\nexport interface RawUploadPart {\n fieldname: string\n filename: string\n mimetype: string\n buffer: Buffer\n}\n\nconst DEFAULT_MAX_SIZE = 5 * 1024 * 1024\n\n/**\n * The client's file name made safe to show: Unicode NFC (so the same text\n * compares equal however the client composed it), without a directory part\n * (`C:\\fakepath\\a.png` → `a.png`) or control characters. Non-Latin text and\n * emoji are kept as they are.\n */\nexport function normalizeOriginalName(name: string): string {\n const base = name.normalize('NFC').split(/[\\\\/]/).pop() ?? ''\n // oxlint-disable-next-line no-control-regex\n return base.replace(/[\\u0000-\\u001f\\u007f]/g, '').trim()\n}\n\n/**\n * The client name's extension, kept only when it names the file's own type:\n * `photo.PNG` sent as `image/png` → `.png`. `evil.html` sent as `image/png`\n * gets none — an extension the type check never saw must not decide how the\n * stored file is later served.\n */\nfunction matchingExtension(\n name: string,\n mimetype: string,\n customMimeMap?: Record<string, string>,\n): string {\n const dot = name.lastIndexOf('.')\n if (dot <= 0) return ''\n const ext = name.slice(dot + 1).toLowerCase()\n const type = mimetype.split(';')[0]!.trim().toLowerCase()\n return (customMimeMap?.[ext] ?? MIME_MAP[ext]) === type ? `.${ext}` : ''\n}\n\n/**\n * The server-side name for an upload: `rename`'s, checked, or a random UUID\n * plus the extension of the file's type when the client name carries it.\n */\nexport function serverFileName(\n file: { originalname: string; mimetype: string; fieldname: string; size: number },\n options: Pick<BaseUploadOptions, 'rename' | 'customMimeMap'> = {},\n): string {\n const { rename, customMimeMap } = options\n if (!rename) {\n const ext = matchingExtension(file.originalname, file.mimetype, customMimeMap)\n return `${globalThis.crypto.randomUUID()}${ext}`\n }\n const name = rename(file)\n if (\n typeof name !== 'string' ||\n name === '' ||\n name === '.' ||\n name === '..' ||\n name.length > 255 ||\n /[\\\\/\\0]/.test(name)\n ) {\n throw new Error(`@FileUpload rename(): '${String(name)}' is not a safe file name`)\n }\n return name\n}\n\n/** What an upload request may carry besides its files: field values, part headers. */\nexport const UPLOAD_FIELDS_ALLOWANCE = 1024 * 1024\n\n/** Form fields an upload request may carry beside its files. */\nexport const MAX_UPLOAD_FIELDS = 1000\n\n/**\n * The most a `@FileUpload` request may carry, for stopping the parser before it\n * buffers more: `fileSize` per file, `files` in all (on any field), and `total`\n * bytes for the whole body.\n */\nexport function uploadLimits(config: FileUploadConfig): {\n fileSize: number\n files: number\n total: number\n} {\n const fileSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const files = config.mode === 'none' ? 0 : config.mode === 'single' ? 1 : (config.maxCount ?? 10)\n return { fileSize, files, total: fileSize * files + UPLOAD_FIELDS_ALLOWANCE }\n}\n\n/** The 413 for more files than a route takes. */\nexport function tooManyFiles(limit: number): HttpException {\n return new HttpException(HttpStatus.PAYLOAD_TOO_LARGE, `Too many files: at most ${limit}`)\n}\n\n/**\n * Apply a `@FileUpload` config to already-buffered multipart parts and return\n * the multer-shaped `file` / `files` for `ctx`. Enforces the field name, type\n * filter, per-file size limit, and (array mode) max count — throwing\n * `HttpException` on a violation, mirroring the Express/multer error path.\n * Used by the Fastify, h3 and web runtimes; Express keeps using multer directly.\n */\nexport function applyUploadConfig(\n parts: RawUploadPart[],\n config: FileUploadConfig,\n): { file?: UploadedFileLike; files?: UploadedFileLike[] } {\n if (config.mode === 'none') return {}\n\n const field = config.fieldName ?? 'file'\n const maxSize = config.maxSize ?? DEFAULT_MAX_SIZE\n const typeAllowed = buildFileTypeFilter(config.allowedTypes, config.customMimeMap)\n\n const matched = parts.filter((p) => p.fieldname === field)\n const files: UploadedFileLike[] = matched.map((p) => {\n if (!typeAllowed(p.mimetype, p.filename)) {\n throw new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${p.mimetype} is not allowed`,\n )\n }\n if (p.buffer.length > maxSize) {\n throw new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${p.filename} exceeds the ${maxSize}-byte limit`,\n )\n }\n const named = {\n fieldname: p.fieldname,\n originalname: normalizeOriginalName(p.filename),\n mimetype: p.mimetype,\n size: p.buffer.length,\n }\n return {\n ...named,\n filename: serverFileName(named, config),\n encoding: '7bit',\n buffer: p.buffer,\n }\n })\n\n if (config.mode === 'single') return { file: files[0] }\n const maxCount = config.maxCount ?? 10\n return { files: files.slice(0, maxCount) }\n}\n"],"mappings":";;;;;;;;;;wDAUA,MAAa,SAAmC,CAE9C,IAAK,aACL,KAAM,aACN,IAAK,YACL,IAAK,YACL,KAAM,aACN,IAAK,gBACL,IAAK,YACL,IAAK,eACL,KAAM,aACN,IAAK,aACL,KAAM,aAEN,IAAK,kBACL,IAAK,qBACL,KAAM,0EACN,IAAK,2BACL,KAAM,oEACN,IAAK,gCACL,KAAM,4EACN,IAAK,0CACL,IAAK,iDACL,IAAK,kDACL,IAAK,kBACL,IAAK,aACL,IAAK,WAEL,IAAK,kBACL,GAAI,mBACJ,IAAK,oBACL,IAAK,sBACL,KAAM,8BAEN,IAAK,aACL,IAAK,YACL,IAAK,YACL,KAAM,aACN,IAAK,YAEL,IAAK,YACL,KAAM,aACN,IAAK,kBACL,IAAK,kBACL,IAAK,mBAEL,KAAM,mBACN,IAAK,kBACL,KAAM,WACR,EAYA,SAAgB,iBAAiB,MAA2B,CAC1D,OAAO,MAAM,IAAK,GAAM,CACtB,IAAM,MAAQ,EAAE,YAAY,CAAC,CAAC,QAAQ,MAAO,EAAE,EAC/C,OAAO,SAAS,QAAU,CAC5B,CAAC,CACH,CASA,SAAgB,oBACd,aACA,cACiD,CACjD,GAAI,CAAC,aAAc,UAAa,GAChC,GAAI,OAAO,cAAiB,WAAY,OAAO,aAC/C,IAAM,QAAU,cAAgB,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
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{n as createToken}from"./token-
|
|
12
|
-
//# sourceMappingURL=url-for-
|
|
11
|
+
import{n as createToken}from"./token-BJJiF3_2.mjs";const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function defineModule(options){if(typeof options!=`object`||!options)throw TypeError(`defineModule: options must be an object literal. See architecture.md §21 for the spec shape.`);if(typeof options.name!=`string`||options.name.length===0){let got=typeof options.name==`string`?`""`:typeof options.name;throw TypeError(`defineModule: options.name must be a non-empty string (got ${got}). Module names appear in diagnostics and \`.scoped()\` namespacing — anonymous modules make cycle / missing-dep errors hard to localize.`)}if(typeof options.build!=`function`)throw TypeError(`defineModule(${options.name}): options.build is required and must be a function (got ${typeof options.build}). The build function returns the AppModule shape — register() / routes() / contributors() — wired with the resolved config.`);let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return Object.defineProperty(built,"__moduleName",{value:instanceName,enumerable:!1,writable:!1,configurable:!1}),built},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),Object.defineProperty(factory,"definition",{value:Object.freeze({...options}),writable:!1,enumerable:!0,configurable:!1}),factory}function moduleName(mod){let{__moduleName,name}=mod;if(typeof __moduleName==`string`&&__moduleName)return __moduleName;if(typeof name==`string`&&name)return name;let ctorName=mod.constructor?.name;return ctorName&&ctorName!==`Object`?ctorName:`module`}var MutableModuleRegistry=class{entries=[];mount(module){this.entries.push(module)}};const ROUTE_URLS=createToken(`kick/Http/routeUrls`);var RouteUrls=class{paths=/* @__PURE__ */ new Map;add(name,path){this.paths.has(name)||this.paths.set(name,path)}urlFor(name,...args){let[params,query]=args;return this.build(name,params,query)}build(name,params,query){let pattern=this.paths.get(name);if(pattern===void 0)throw Error(`urlFor: no route named '${name}' — expected 'Controller.method'`);let path=pattern.replace(/:([A-Za-z0-9_]+)/g,(_,key)=>{let value=params?.[key];if(value==null||value===``)throw Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`);return encodeURIComponent(String(value))});if(!query)return path;let search=new URLSearchParams;for(let[key,value]of Object.entries(query))for(let v of Array.isArray(value)?value:[value])search.append(key,String(v));let qs=search.toString();return qs?`${path}?${qs}`:path}};export{moduleName as a,defineModule as i,RouteUrls as n,MutableModuleRegistry as r,ROUTE_URLS as t};
|
|
12
|
+
//# sourceMappingURL=url-for-kZidAFyr.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"url-for-O-DQnRvH.mjs","names":[],"sources":["../src/core/define-module.ts","../src/core/module-registry.ts","../src/http/url-for.ts"],"sourcesContent":["import type { AppModule } from './app-module'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineModule}. Mirrors {@link DefineAdapterOptions}\n * and {@link DefinePluginOptions} so adopters learn one mental model\n * across all three primitives.\n *\n * The optional `TExtra` generic lets a module ship public methods\n * beyond the standard {@link AppModule} contract — they're preserved\n * on the returned module instance so external callers (tests, sibling\n * modules) can invoke them directly.\n */\nexport interface DefineModuleOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity surfaced in diagnostics, route logs, and\n * `.scoped()` namespacing. Required because boot-time error\n * messages reference modules by name — anonymous modules make\n * cycles + missing-dep errors hard to localize.\n */\n name: string\n /** Optional version string surfaced in diagnostics. */\n version?: string\n /**\n * Optional kickjs version constraint. Enforced by the framework\n * when implemented; today it lives on the definition for\n * documentation and forward compatibility.\n */\n requires?: { kickjs?: string }\n /**\n * Default config merged with overrides at instantiation time\n * (`MyModule({ field: x })`). Call-site overrides win.\n */\n defaults?: Partial<TConfig>\n /**\n * Build the AppModule shape from the resolved config and context.\n * `ctx.name` is the resolved instance name (the bare definition\n * name for the default call, or `${name}:${scope}` for\n * `.scoped()`); `ctx.scoped` discriminates so the build function\n * can branch on namespacing if needed.\n *\n * Return any extension methods alongside the standard\n * {@link AppModule} surface — they're typed via `TExtra` and stay\n * accessible on the resulting instance.\n */\n build(config: TConfig, ctx: BuildContext): AppModule & TExtra\n}\n\n/**\n * Factory returned by {@link defineModule}. Mirrors {@link AdapterFactory}\n * — call (`MyModule({...})`), scope (`MyModule.scoped('public', {...})`),\n * inspect (`MyModule.definition`).\n *\n * `.async()` is intentionally **not** part of the module factory\n * surface. Module config has no async-resolution window: `register()`\n * and `routes()` both run synchronously during bootstrap, before any\n * adapter `beforeStart` hook fires. Adopters that need async-resolved\n * config push it into an adapter (which has `beforeStart`), then\n * inject the resolved value into the module via DI tokens.\n */\nexport interface ModuleFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppModule & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppModule & TExtra\n readonly definition: Readonly<DefineModuleOptions<TConfig, TExtra>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build an {@link AppModule} factory from a typed definition. Pairs\n * with {@link defineAdapter}, {@link definePlugin}, and\n * {@link defineContextDecorator} as the fourth `define*` primitive\n * — adopters write modules the same way they write adapters and\n * plugins.\n *\n * The returned factory produces real {@link AppModule} instances\n * that drop into `bootstrap({ modules })` directly. The legacy\n * class form (`class TasksModule implements AppModule { ... }`) keeps\n * working — `bootstrap` accepts either shape.\n *\n * @example\n * ```ts\n * interface TasksConfig {\n * scope: 'public' | 'admin'\n * }\n *\n * const TasksModule = defineModule<TasksConfig>({\n * name: 'TasksModule',\n * defaults: { scope: 'public' },\n * build: (config, { name }) => ({\n * register(container) {\n * container.registerInstance(`tasks:scope:${name}`, config.scope)\n * },\n * routes() {\n * return { path: `/${config.scope}/tasks`, router: buildTasksRouter() }\n * },\n * contributors() {\n * return [LoadTenant.registration]\n * },\n * }),\n * })\n *\n * bootstrap({\n * modules: [\n * TasksModule(), // public scope (defaults)\n * TasksModule.scoped('admin', { scope: 'admin' }),\n * ],\n * })\n * ```\n */\nexport function defineModule<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineModuleOptions<TConfig, TExtra>,\n): ModuleFactory<TConfig, TExtra> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError(\n 'defineModule: options must be an object literal. ' +\n 'See architecture.md §21 for the spec shape.',\n )\n }\n if (typeof options.name !== 'string' || options.name.length === 0) {\n const got = typeof options.name === 'string' ? '\"\"' : typeof options.name\n throw new TypeError(\n `defineModule: options.name must be a non-empty string (got ${got}). ` +\n 'Module names appear in diagnostics and `.scoped()` namespacing — anonymous ' +\n 'modules make cycle / missing-dep errors hard to localize.',\n )\n }\n if (typeof options.build !== 'function') {\n throw new TypeError(\n `defineModule(${options.name}): options.build is required and must be a function ` +\n `(got ${typeof options.build}). The build function returns the AppModule shape — ` +\n 'register() / routes() / contributors() — wired with the resolved config.',\n )\n }\n\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppModule & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate-in-place rather than spread: spread strips prototype methods\n // when build() returns a class instance, and the existing defineAdapter\n // pattern uses the same approach. `TExtra` properties survive because\n // they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped })\n // AppModule has no `name` field today, but stamping the resolved\n // instance name onto the result lets diagnostics surface it without\n // adopter wiring. The cast keeps the public AppModule type\n // unchanged while the data is available for any framework code\n // that wants it.\n Object.defineProperty(built, '__moduleName', {\n value: instanceName,\n enumerable: false,\n writable: false,\n configurable: false,\n })\n return built\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as ModuleFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n Object.defineProperty(factory, 'definition', {\n value: Object.freeze({ ...options }),\n writable: false,\n enumerable: true,\n configurable: false,\n })\n\n return factory\n}\n\n/**\n * The name a module is labelled with in diagnostics — `describeConfig()`,\n * `.env.example`'s \"declared by\", the contributors table. `defineModule`\n * stamps it as `__moduleName`; a hand-written module may carry `name`; a\n * class module falls back to its class name. Plain objects say `module`, not\n * `Object`.\n */\nexport function moduleName(mod: AppModule): string {\n const { __moduleName, name } = mod as { __moduleName?: unknown; name?: unknown }\n if (typeof __moduleName === 'string' && __moduleName) return __moduleName\n if (typeof name === 'string' && name) return name\n const ctorName = mod.constructor?.name\n return ctorName && ctorName !== 'Object' ? ctorName : 'module'\n}\n","import type { AppModuleEntry } from './app-module'\n\n/**\n * Imperative receiver passed to {@link KickPlugin.setup} and the\n * top-level `bootstrap({ setup })` callback so adopters can register\n * modules conditionally — based on env flags, runtime config,\n * tenant lists, etc. — instead of being limited to the static\n * `modules: [...]` array.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules: [HelloModule()], // static — always mounted\n * setup(registry) {\n * if (env.ENABLE_ADMIN) registry.mount(AdminModule())\n * for (const tenant of env.TENANTS) {\n * registry.mount(TenantModule.scoped(tenant.id, { id: tenant.id }))\n * }\n * },\n * })\n * ```\n *\n * **Currently exposes only `.mount(module)` — the HTTP-feature path.**\n * A future `.use(module)` for non-HTTP modules (queues, cron, workers,\n * DI-only seeds) is planned but not yet implemented; existing non-HTTP\n * modules continue returning `null` from `routes()` and registering\n * via `.mount()`.\n *\n * Same dispatch rules as the static `modules: [...]` array — class\n * entries get `new`-ed at boot, `defineModule` factory output is used\n * directly. The registry doesn't validate the entry shape itself; the\n * Application loader does the typeof discrimination at mount time.\n */\nexport interface ModuleRegistry {\n /**\n * Register a module for the full HTTP lifecycle: `register()` runs,\n * `import.meta.glob` decorator side-effects fire, `routes()` is\n * called and its result mounted, `contributors()` are merged at\n * `'module'` precedence and applied to the mounted routes.\n *\n * Modules are mounted in registration order (first call → first\n * mount). Order across sources is: plugin static modules → plugin\n * `setup()` calls → user static modules → user `setup()` callback.\n */\n mount(module: AppModuleEntry): void\n}\n\n/**\n * Internal collector implementing {@link ModuleRegistry}. Application\n * passes one of these to every `setup()` callback during bootstrap;\n * the collected `entries` array is then run through the same\n * class-vs-instance dispatch as the static `modules: [...]` array.\n *\n * Not exported from the public surface — adopters interact only\n * through the {@link ModuleRegistry} interface.\n */\nexport class MutableModuleRegistry implements ModuleRegistry {\n readonly entries: AppModuleEntry[] = []\n\n mount(module: AppModuleEntry): void {\n this.entries.push(module)\n }\n}\n","/**\n * Build a route's URL from its name — `'UsersController.show'` — instead of\n * spelling the path where you link to it, so a moved route can't leave a\n * redirect, a `Location` header or an email link pointing at the old one.\n *\n * @module @forinda/kickjs/http/url-for\n */\n\nimport { createToken } from '../core/token'\n\n/**\n * Route names `kick typegen` knows: `'Controller.method'` → the route's\n * shape. Falls back to `string` before typegen has run.\n */\nexport type RouteName = [keyof KickRoutes.Named] extends [never]\n ? string\n : Extract<keyof KickRoutes.Named, string>\n\ntype ParamsOf<N> = N extends keyof KickRoutes.Named\n ? KickRoutes.Named[N] extends { params: infer P }\n ? P\n : Record<string, string | number>\n : Record<string, string | number>\n\n/** `params` is optional when the route has none, required otherwise. */\nexport type UrlForArgs<N> =\n Record<string, never> extends ParamsOf<N>\n ? [params?: ParamsOf<N>, query?: UrlQuery]\n : [params: ParamsOf<N>, query?: UrlQuery]\n\nexport type UrlQuery = Record<string, string | number | boolean | Array<string | number>>\n\n/** Builds route URLs by name — what `ROUTE_URLS` resolves to. */\nexport interface UrlBuilder {\n /**\n * The URL of a route, by name — `'Controller.method'` — with its `:params`\n * filled (encoded) and an optional query string.\n */\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string\n}\n\n/**\n * The app's {@link UrlBuilder}, for code outside a request — a job, a mailer,\n * a service building a link:\n *\n * ```ts\n * @Service()\n * class Mailer {\n * constructor(@Inject(ROUTE_URLS) private readonly urls: UrlBuilder) {}\n * resetLink(token: string) {\n * return `https://example.com${this.urls.urlFor('AuthController.reset', { token })}`\n * }\n * }\n * ```\n */\nexport const ROUTE_URLS = createToken<UrlBuilder>('kick/Http/routeUrls')\n// One per process, like every DI binding: the container is process-wide, so\n// with two apps in one process this is the one set up last. `ctx.urlFor()`\n// always uses the app that is serving the request.\n\n/** One app's route name → full path pattern (`/api/v1/users/:id`). */\nexport class RouteUrls implements UrlBuilder {\n private readonly paths = new Map<string, string>()\n\n /** First registration wins — a controller mounted twice keeps its first path. */\n add(name: string, path: string): void {\n if (!this.paths.has(name)) this.paths.set(name, path)\n }\n\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string {\n const [params, query] = args\n return this.build(name, params as Record<string, unknown> | undefined, query)\n }\n\n build(name: string, params?: Record<string, unknown>, query?: UrlQuery): string {\n const pattern = this.paths.get(name)\n if (pattern === undefined) {\n throw new Error(`urlFor: no route named '${name}' — expected 'Controller.method'`)\n }\n const path = pattern.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {\n const value = params?.[key]\n if (value === undefined || value === null || value === '') {\n throw new Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`)\n }\n return encodeURIComponent(String(value))\n })\n if (!query) return path\n const search = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n for (const v of Array.isArray(value) ? value : [value]) search.append(key, String(v))\n }\n const qs = search.toString()\n return qs ? `${path}?${qs}` : path\n }\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace KickRoutes {\n /** `'Controller.method'` → route shape, written by `kick typegen`. */\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface Named {}\n }\n}\n"],"mappings":";;;;;;;;;;mDAkEA,MAAM,aACJ,SAA6B,CAAC,EAC9B,UAA8B,CAAC,KAClB,CAAE,GAAG,SAAU,GAAG,SAAU,GAErC,aAAe,KAAc,QAA0B,GAAG,KAAK,GAAG,QA4CxE,SAAgB,aACd,QACgC,CAChC,GAAwB,OAAO,SAAY,WAA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AAI,IAG7B,IAAI,KAAc,KAAoB,CAC/B,KAAK,MAAM,IAAI,IAAI,GAAG,KAAK,MAAM,IAAI,KAAM,IAAI,CACtD,CAEA,OAA4B,KAAS,GAAG,KAA6B,CACnE,GAAM,CAAC,OAAQ,OAAS,KACxB,OAAO,KAAK,MAAM,KAAM,OAA+C,KAAK,CAC9E,CAEA,MAAM,KAAc,OAAkC,MAA0B,CAC9E,IAAM,QAAU,KAAK,MAAM,IAAI,IAAI,EACnC,GAAI,UAAY,IAAA,GACd,MAAU,MAAM,2BAA2B,KAAK,iCAAiC,EAEnF,IAAM,KAAO,QAAQ,QAAQ,qBAAsB,EAAG,MAAgB,CACpE,IAAM,MAAQ,SAAS,KACvB,GAAI,OAAiC,MAAQ,QAAU,GACrD,MAAU,MAAM,WAAW,KAAK,qBAAqB,IAAI,SAAS,QAAQ,EAAE,EAE9E,OAAO,mBAAmB,OAAO,KAAK,CAAC,CACzC,CAAC,EACD,GAAI,CAAC,MAAO,OAAO,KACnB,IAAM,OAAS,IAAI,gBACnB,IAAK,GAAM,CAAC,IAAK,SAAU,OAAO,QAAQ,KAAK,EAC7C,IAAK,IAAM,KAAK,MAAM,QAAQ,KAAK,EAAI,MAAQ,CAAC,KAAK,EAAG,OAAO,OAAO,IAAK,OAAO,CAAC,CAAC,EAEtF,IAAM,GAAK,OAAO,SAAS,EAC3B,OAAO,GAAK,GAAG,KAAK,GAAG,KAAO,IAChC,CACF"}
|
|
1
|
+
{"version":3,"file":"url-for-kZidAFyr.mjs","names":[],"sources":["../src/core/define-module.ts","../src/core/module-registry.ts","../src/http/url-for.ts"],"sourcesContent":["import type { AppModule } from './app-module'\nimport type { BuildContext } from './define-plugin'\n\n/**\n * Options passed to {@link defineModule}. Mirrors {@link DefineAdapterOptions}\n * and {@link DefinePluginOptions} so adopters learn one mental model\n * across all three primitives.\n *\n * The optional `TExtra` generic lets a module ship public methods\n * beyond the standard {@link AppModule} contract — they're preserved\n * on the returned module instance so external callers (tests, sibling\n * modules) can invoke them directly.\n */\nexport interface DefineModuleOptions<TConfig, TExtra = unknown> {\n /**\n * Stable identity surfaced in diagnostics, route logs, and\n * `.scoped()` namespacing. Required because boot-time error\n * messages reference modules by name — anonymous modules make\n * cycles + missing-dep errors hard to localize.\n */\n name: string\n /** Optional version string surfaced in diagnostics. */\n version?: string\n /**\n * Optional kickjs version constraint. Enforced by the framework\n * when implemented; today it lives on the definition for\n * documentation and forward compatibility.\n */\n requires?: { kickjs?: string }\n /**\n * Default config merged with overrides at instantiation time\n * (`MyModule({ field: x })`). Call-site overrides win.\n */\n defaults?: Partial<TConfig>\n /**\n * Build the AppModule shape from the resolved config and context.\n * `ctx.name` is the resolved instance name (the bare definition\n * name for the default call, or `${name}:${scope}` for\n * `.scoped()`); `ctx.scoped` discriminates so the build function\n * can branch on namespacing if needed.\n *\n * Return any extension methods alongside the standard\n * {@link AppModule} surface — they're typed via `TExtra` and stay\n * accessible on the resulting instance.\n */\n build(config: TConfig, ctx: BuildContext): AppModule & TExtra\n}\n\n/**\n * Factory returned by {@link defineModule}. Mirrors {@link AdapterFactory}\n * — call (`MyModule({...})`), scope (`MyModule.scoped('public', {...})`),\n * inspect (`MyModule.definition`).\n *\n * `.async()` is intentionally **not** part of the module factory\n * surface. Module config has no async-resolution window: `register()`\n * and `routes()` both run synchronously during bootstrap, before any\n * adapter `beforeStart` hook fires. Adopters that need async-resolved\n * config push it into an adapter (which has `beforeStart`), then\n * inject the resolved value into the module via DI tokens.\n */\nexport interface ModuleFactory<TConfig, TExtra = unknown> {\n (config?: Partial<TConfig>): AppModule & TExtra\n scoped(scopeName: string, config?: Partial<TConfig>): AppModule & TExtra\n readonly definition: Readonly<DefineModuleOptions<TConfig, TExtra>>\n}\n\nconst mergeConfig = <TConfig>(\n defaults: Partial<TConfig> = {},\n overrides: Partial<TConfig> = {},\n): TConfig => ({ ...defaults, ...overrides }) as TConfig\n\nconst composeName = (base: string, scope: string): string => `${base}:${scope}`\n\n/**\n * Build an {@link AppModule} factory from a typed definition. Pairs\n * with {@link defineAdapter}, {@link definePlugin}, and\n * {@link defineContextDecorator} as the fourth `define*` primitive\n * — adopters write modules the same way they write adapters and\n * plugins.\n *\n * The returned factory produces real {@link AppModule} instances\n * that drop into `bootstrap({ modules })` directly. The legacy\n * class form (`class TasksModule implements AppModule { ... }`) keeps\n * working — `bootstrap` accepts either shape.\n *\n * @example\n * ```ts\n * interface TasksConfig {\n * scope: 'public' | 'admin'\n * }\n *\n * const TasksModule = defineModule<TasksConfig>({\n * name: 'TasksModule',\n * defaults: { scope: 'public' },\n * build: (config, { name }) => ({\n * register(container) {\n * container.registerInstance(`tasks:scope:${name}`, config.scope)\n * },\n * routes() {\n * return { path: `/${config.scope}/tasks`, router: buildTasksRouter() }\n * },\n * contributors() {\n * return [LoadTenant.registration]\n * },\n * }),\n * })\n *\n * bootstrap({\n * modules: [\n * TasksModule(), // public scope (defaults)\n * TasksModule.scoped('admin', { scope: 'admin' }),\n * ],\n * })\n * ```\n */\nexport function defineModule<TConfig = Record<string, unknown>, TExtra = unknown>(\n options: DefineModuleOptions<TConfig, TExtra>,\n): ModuleFactory<TConfig, TExtra> {\n if (options === null || typeof options !== 'object') {\n throw new TypeError(\n 'defineModule: options must be an object literal. ' +\n 'See architecture.md §21 for the spec shape.',\n )\n }\n if (typeof options.name !== 'string' || options.name.length === 0) {\n const got = typeof options.name === 'string' ? '\"\"' : typeof options.name\n throw new TypeError(\n `defineModule: options.name must be a non-empty string (got ${got}). ` +\n 'Module names appear in diagnostics and `.scoped()` namespacing — anonymous ' +\n 'modules make cycle / missing-dep errors hard to localize.',\n )\n }\n if (typeof options.build !== 'function') {\n throw new TypeError(\n `defineModule(${options.name}): options.build is required and must be a function ` +\n `(got ${typeof options.build}). The build function returns the AppModule shape — ` +\n 'register() / routes() / contributors() — wired with the resolved config.',\n )\n }\n\n const buildSync = (\n instanceName: string,\n scoped: boolean,\n overrides?: Partial<TConfig>,\n ): AppModule & TExtra => {\n const config = mergeConfig(options.defaults, overrides)\n // Mutate-in-place rather than spread: spread strips prototype methods\n // when build() returns a class instance, and the existing defineAdapter\n // pattern uses the same approach. `TExtra` properties survive because\n // they're own properties on the build result.\n const built = options.build(config, { name: instanceName, scoped })\n // AppModule has no `name` field today, but stamping the resolved\n // instance name onto the result lets diagnostics surface it without\n // adopter wiring. The cast keeps the public AppModule type\n // unchanged while the data is available for any framework code\n // that wants it.\n Object.defineProperty(built, '__moduleName', {\n value: instanceName,\n enumerable: false,\n writable: false,\n configurable: false,\n })\n return built\n }\n\n const factory = ((config?: Partial<TConfig>) =>\n buildSync(options.name, false, config)) as ModuleFactory<TConfig, TExtra>\n\n factory.scoped = (scopeName: string, config?: Partial<TConfig>) =>\n buildSync(composeName(options.name, scopeName), true, config)\n\n Object.defineProperty(factory, 'definition', {\n value: Object.freeze({ ...options }),\n writable: false,\n enumerable: true,\n configurable: false,\n })\n\n return factory\n}\n\n/**\n * The name a module is labelled with in diagnostics — `describeConfig()`,\n * `.env.example`'s \"declared by\", the contributors table. `defineModule`\n * stamps it as `__moduleName`; a hand-written module may carry `name`; a\n * class module falls back to its class name. Plain objects say `module`, not\n * `Object`.\n */\nexport function moduleName(mod: AppModule): string {\n const { __moduleName, name } = mod as { __moduleName?: unknown; name?: unknown }\n if (typeof __moduleName === 'string' && __moduleName) return __moduleName\n if (typeof name === 'string' && name) return name\n const ctorName = mod.constructor?.name\n return ctorName && ctorName !== 'Object' ? ctorName : 'module'\n}\n","import type { AppModuleEntry } from './app-module'\n\n/**\n * Imperative receiver passed to {@link KickPlugin.setup} and the\n * top-level `bootstrap({ setup })` callback so adopters can register\n * modules conditionally — based on env flags, runtime config,\n * tenant lists, etc. — instead of being limited to the static\n * `modules: [...]` array.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules: [HelloModule()], // static — always mounted\n * setup(registry) {\n * if (env.ENABLE_ADMIN) registry.mount(AdminModule())\n * for (const tenant of env.TENANTS) {\n * registry.mount(TenantModule.scoped(tenant.id, { id: tenant.id }))\n * }\n * },\n * })\n * ```\n *\n * **Currently exposes only `.mount(module)` — the HTTP-feature path.**\n * A future `.use(module)` for non-HTTP modules (queues, cron, workers,\n * DI-only seeds) is planned but not yet implemented; existing non-HTTP\n * modules continue returning `null` from `routes()` and registering\n * via `.mount()`.\n *\n * Same dispatch rules as the static `modules: [...]` array — class\n * entries get `new`-ed at boot, `defineModule` factory output is used\n * directly. The registry doesn't validate the entry shape itself; the\n * Application loader does the typeof discrimination at mount time.\n */\nexport interface ModuleRegistry {\n /**\n * Register a module for the full HTTP lifecycle: `register()` runs,\n * `import.meta.glob` decorator side-effects fire, `routes()` is\n * called and its result mounted, `contributors()` are merged at\n * `'module'` precedence and applied to the mounted routes.\n *\n * Modules are mounted in registration order (first call → first\n * mount). Order across sources is: plugin static modules → plugin\n * `setup()` calls → user static modules → user `setup()` callback.\n */\n mount(module: AppModuleEntry): void\n}\n\n/**\n * Internal collector implementing {@link ModuleRegistry}. Application\n * passes one of these to every `setup()` callback during bootstrap;\n * the collected `entries` array is then run through the same\n * class-vs-instance dispatch as the static `modules: [...]` array.\n *\n * Not exported from the public surface — adopters interact only\n * through the {@link ModuleRegistry} interface.\n */\nexport class MutableModuleRegistry implements ModuleRegistry {\n readonly entries: AppModuleEntry[] = []\n\n mount(module: AppModuleEntry): void {\n this.entries.push(module)\n }\n}\n","/**\n * Build a route's URL from its name — `'UsersController.show'` — instead of\n * spelling the path where you link to it, so a moved route can't leave a\n * redirect, a `Location` header or an email link pointing at the old one.\n *\n * @module @forinda/kickjs/http/url-for\n */\n\nimport { createToken } from '../core/token'\n\n/**\n * Route names `kick typegen` knows: `'Controller.method'` → the route's\n * shape. Falls back to `string` before typegen has run.\n */\nexport type RouteName = [keyof KickRoutes.Named] extends [never]\n ? string\n : Extract<keyof KickRoutes.Named, string>\n\ntype ParamsOf<N> = N extends keyof KickRoutes.Named\n ? KickRoutes.Named[N] extends { params: infer P }\n ? P\n : Record<string, string | number>\n : Record<string, string | number>\n\n/** `params` is optional when the route has none, required otherwise. */\nexport type UrlForArgs<N> =\n Record<string, never> extends ParamsOf<N>\n ? [params?: ParamsOf<N>, query?: UrlQuery]\n : [params: ParamsOf<N>, query?: UrlQuery]\n\nexport type UrlQuery = Record<string, string | number | boolean | Array<string | number>>\n\n/** Builds route URLs by name — what `ROUTE_URLS` resolves to. */\nexport interface UrlBuilder {\n /**\n * The URL of a route, by name — `'Controller.method'` — with its `:params`\n * filled (encoded) and an optional query string.\n */\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string\n}\n\n/**\n * The app's {@link UrlBuilder}, for code outside a request — a job, a mailer,\n * a service building a link:\n *\n * ```ts\n * @Service()\n * class Mailer {\n * constructor(@Inject(ROUTE_URLS) private readonly urls: UrlBuilder) {}\n * resetLink(token: string) {\n * return `https://example.com${this.urls.urlFor('AuthController.reset', { token })}`\n * }\n * }\n * ```\n */\nexport const ROUTE_URLS = createToken<UrlBuilder>('kick/Http/routeUrls')\n// One per process, like every DI binding: the container is process-wide, so\n// with two apps in one process this is the one set up last. `ctx.urlFor()`\n// always uses the app that is serving the request.\n\n/** One app's route name → full path pattern (`/api/v1/users/:id`). */\nexport class RouteUrls implements UrlBuilder {\n private readonly paths = new Map<string, string>()\n\n /** First registration wins — a controller mounted twice keeps its first path. */\n add(name: string, path: string): void {\n if (!this.paths.has(name)) this.paths.set(name, path)\n }\n\n urlFor<N extends RouteName>(name: N, ...args: UrlForArgs<N>): string {\n const [params, query] = args\n return this.build(name, params as Record<string, unknown> | undefined, query)\n }\n\n build(name: string, params?: Record<string, unknown>, query?: UrlQuery): string {\n const pattern = this.paths.get(name)\n if (pattern === undefined) {\n throw new Error(`urlFor: no route named '${name}' — expected 'Controller.method'`)\n }\n const path = pattern.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {\n const value = params?.[key]\n if (value === undefined || value === null || value === '') {\n throw new Error(`urlFor('${name}'): missing param '${key}' for '${pattern}'`)\n }\n return encodeURIComponent(String(value))\n })\n if (!query) return path\n const search = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n for (const v of Array.isArray(value) ? value : [value]) search.append(key, String(v))\n }\n const qs = search.toString()\n return qs ? `${path}?${qs}` : path\n }\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace KickRoutes {\n /** `'Controller.method'` → route shape, written by `kick typegen`. */\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface Named {}\n }\n}\n"],"mappings":";;;;;;;;;;mDAkEA,MAAM,aACJ,SAA6B,CAAC,EAC9B,UAA8B,CAAC,KAClB,CAAE,GAAG,SAAU,GAAG,SAAU,GAErC,aAAe,KAAc,QAA0B,GAAG,KAAK,GAAG,QA4CxE,SAAgB,aACd,QACgC,CAChC,GAAwB,OAAO,SAAY,WAAvC,QACF,MAAU,UACR,8FAEF,EAEF,GAAI,OAAO,QAAQ,MAAS,UAAY,QAAQ,KAAK,SAAW,EAAG,CACjE,IAAM,IAAM,OAAO,QAAQ,MAAS,SAAW,KAAO,OAAO,QAAQ,KACrE,MAAU,UACR,8DAA8D,IAAI,0IAGpE,CACF,CACA,GAAI,OAAO,QAAQ,OAAU,WAC3B,MAAU,UACR,gBAAgB,QAAQ,KAAK,2DACnB,OAAO,QAAQ,MAAM,6HAEjC,EAGF,IAAM,WACJ,aACA,OACA,YACuB,CACvB,IAAM,OAAS,YAAY,QAAQ,SAAU,SAAS,EAKhD,MAAQ,QAAQ,MAAM,OAAQ,CAAE,KAAM,aAAc,MAAO,CAAC,EAYlE,OANA,OAAO,eAAe,MAAO,eAAgB,CAC3C,MAAO,aACP,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EACM,KACT,EAEM,SAAY,QAChB,UAAU,QAAQ,KAAM,GAAO,MAAM,GAYvC,MAVA,SAAQ,QAAU,UAAmB,SACnC,UAAU,YAAY,QAAQ,KAAM,SAAS,EAAG,GAAM,MAAM,EAE9D,OAAO,eAAe,QAAS,aAAc,CAC3C,MAAO,OAAO,OAAO,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AI,MAAQ,CAAC,KAAK,EAAG,OAAO,OAAO,IAAK,OAAO,CAAC,CAAC,EAEtF,IAAM,GAAK,OAAO,SAAS,EAC3B,OAAO,GAAK,GAAG,KAAK,GAAG,KAAO,IAChC,CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.12.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{createLogger}from"./core/logger.mjs";import{r as reportError}from"./observers-
|
|
12
|
-
//# sourceMappingURL=view-renderer-
|
|
11
|
+
import{createLogger}from"./core/logger.mjs";import{r as reportError}from"./observers-DL7RRlLR.mjs";import{AsyncLocalStorage}from"node:async_hooks";const requestStore=new AsyncLocalStorage;function getRequestStore(){let store=requestStore.getStore();if(!store)throw Error(`No active request context. REQUEST-scoped services can only be resolved during an HTTP request.`);return store}function getRequestValue(key){return requestStore.getStore()?.values.get(key)}const log=createLogger(`waitUntil`),pending=/* @__PURE__ */ new Set;function waitUntil(promise){let requestId=requestStore.getStore()?.requestId,tracked=Promise.resolve(promise).then(()=>{},err=>{log.error({err,requestId},`Background work passed to waitUntil() failed`),reportError(err,{source:`background`,requestId})});pending.add(tracked),tracked.finally(()=>pending.delete(tracked))}async function settleBackgroundWork(){for(;pending.size>0;)await Promise.all(pending)}function pendingBackgroundWork(){return pending.size}function forwardBackgroundWork(platform){platform?.waitUntil?.(settleBackgroundWork())}const VIEW_RENDERER=Symbol.for(`kickjs.viewRenderer`);function bindViewRenderer(req,renderer){req[VIEW_RENDERER]=renderer}function viewRendererFor(req){return req?.[VIEW_RENDERER]}const PENDING=Symbol(`kickjs.pendingResponse`);function setPendingResponse(ctx,p){ctx[PENDING]=p}function pendingResponse(ctx){return ctx[PENDING]}export{viewRendererFor as a,settleBackgroundWork as c,getRequestValue as d,requestStore as f,setPendingResponse as i,waitUntil as l,bindViewRenderer as n,forwardBackgroundWork as o,pendingResponse as r,pendingBackgroundWork as s,VIEW_RENDERER as t,getRequestStore as u};
|
|
12
|
+
//# sourceMappingURL=view-renderer-CSPD7F-f.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"view-renderer-NbkTobFF.mjs","names":[],"sources":["../src/http/request-store.ts","../src/http/background.ts","../src/http/view-renderer.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { ContextMetaKey, MetaValue } from '../core/execution-context'\n\n/** Per-request storage for REQUEST-scoped DI and request context propagation */\nexport interface RequestStore {\n /** Unique request identifier */\n requestId: string\n /**\n * Per-request singleton cache for REQUEST-scoped services. Keys are\n * heterogeneous (class constructors, `InjectionToken` objects, raw\n * strings), so the map type stays `Map<any, any>`.\n */\n instances: Map<any, any>\n /**\n * Per-request key/value bag. Canonical backing store for\n * `RequestContext.set/get` and the Context Contributor pipeline (#107)\n * since Phase 3. Anything written here is visible to every concrete\n * execution context constructed for the same request, regardless of\n * which middleware/contributor wrote it.\n *\n * Keys are constrained to `string` per the locked decision in\n * `architecture.md` §20.12 (#4); the value type is `unknown` because\n * the concrete shape at each key is determined by the consumer's\n * `ContextMeta` augmentation, not by the store itself.\n *\n * Prefer the {@link getRequestValue} helper over reaching into this\n * map directly — it threads the augmented `ContextMeta` shape through\n * `MetaValue<K>` so consumers get typed reads without an `as` cast.\n * Writes should flow through `ctx.set(key, value)` or a Context\n * Contributor's return value — see the `setRequestValue` note below\n * for why this package intentionally does NOT ship a service-level\n * write helper.\n */\n values: Map<string, unknown>\n /** Set once {@link disposeRequestStore} has run — guards double-dispose. */\n disposed?: boolean\n}\n\n/** AsyncLocalStorage instance shared across the framework */\nexport const requestStore = new AsyncLocalStorage<RequestStore>()\n\n/**\n * Get the current request store. Throws if called outside a request context.\n * Used by the Container to resolve REQUEST-scoped dependencies.\n */\nexport function getRequestStore(): RequestStore {\n const store = requestStore.getStore()\n if (!store) {\n throw new Error(\n 'No active request context. REQUEST-scoped services can only be resolved during an HTTP request.',\n )\n }\n return store\n}\n\n/**\n * Read a per-request `ContextMeta`-keyed value from outside a controller\n * (services, repositories, anywhere with no `ctx` reference). Returns\n * the augmented type for the key — `MetaValue<K>` — so consumers get the\n * same static safety as `ctx.get(key)` without holding the context.\n *\n * Returns `undefined` outside an active request frame (background jobs,\n * startup code, tests without `requestScopeMiddleware()`) — the helper\n * is intentionally null-tolerant so calling it from a service that\n * runs in both request and non-request paths doesn't throw.\n *\n * @example\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface ContextMeta { tenant: { id: string; name: string } }\n * }\n *\n * @Service()\n * class AuditService {\n * log(action: string) {\n * const tenant = getRequestValue('tenant') // typed: { id; name } | undefined\n * db.audit.insert({ action, tenantId: tenant?.id })\n * }\n * }\n * ```\n */\nexport function getRequestValue<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined {\n return requestStore.getStore()?.values.get(key) as MetaValue<K> | undefined\n}\n\n// Intentionally NO `setRequestValue` export.\n//\n// Writes are deliberately context-scoped — only the controlled write\n// surfaces should mutate the per-request Map:\n//\n// 1. A Context Contributor's `resolve()` / `onError()` return value\n// (the runner does `ctx.set(reg.key, value)` on the contributor's\n// behalf). This is the canonical way to populate a key.\n// 2. A controller / middleware / contributor that holds a\n// `RequestContext` instance can call `ctx.set(key, value)`\n// directly. The write is auditable inline at the call site.\n//\n// Letting arbitrary services reach in and mutate the store from\n// anywhere produces \"spooky action at a distance\" — keys appear in\n// the request bag without an obvious source, and tracing which\n// service polluted what becomes a grep exercise. Services that need\n// to publish per-request state should return the value to the caller\n// (controller or contributor) and let *that* layer write it via\n// `ctx.set`. If a future need genuinely requires a service-level\n// write surface, expose a narrow function (`recordTrace`,\n// `markStartTime`) on a service that captures the side effect, not a\n// generic `setRequestValue`.\n","/**\n * Work that outlives the response — `waitUntil(promise)`.\n *\n * A handler that fires off an audit log, an email, or an analytics call and\n * answers without awaiting it leaves that promise unowned: on serverless the\n * platform freezes or kills the instance once the response is sent, and on a\n * Node server `SIGTERM` exits before it settles. `waitUntil` registers the\n * promise so something waits for it:\n *\n * - on the Node server, `shutdown()` awaits it (within `shutdownTimeout`);\n * - through `createHandler()` and the web entry, it is handed to the\n * platform's own `waitUntil` (Workers `ctx`, Netlify `context`, Vercel's\n * `waitUntil`) when you pass it in.\n *\n * Process-wide, like the DI container: one app per process.\n *\n * @module @forinda/kickjs/http/background\n */\nimport { createLogger } from '../core/logger'\nimport { reportError } from '../core/observers'\nimport { requestStore } from './request-store'\n\nconst log = createLogger('waitUntil')\nconst pending = new Set<Promise<void>>()\n\n/**\n * Keep `promise` alive past the response. A rejection is logged (with the\n * request id when called during a request), never left unhandled.\n *\n * @example\n * ```ts\n * @Post('/')\n * async create(ctx: RequestContext) {\n * const order = await this.orders.create(ctx.body)\n * ctx.waitUntil(this.mailer.sendReceipt(order)) // or waitUntil(...) outside a handler\n * return order\n * }\n * ```\n */\nexport function waitUntil(promise: Promise<unknown>): void {\n const requestId = requestStore.getStore()?.requestId\n const tracked: Promise<void> = Promise.resolve(promise).then(\n () => {},\n (err: unknown) => {\n log.error({ err, requestId }, 'Background work passed to waitUntil() failed')\n reportError(err, { source: 'background', requestId })\n },\n )\n pending.add(tracked)\n void tracked.finally(() => pending.delete(tracked))\n}\n\n/**\n * Resolve once every registered promise has settled — including work\n * registered while waiting. Never rejects.\n */\nexport async function settleBackgroundWork(): Promise<void> {\n while (pending.size > 0) await Promise.all(pending)\n}\n\n/** How many `waitUntil` promises have not settled yet. */\nexport function pendingBackgroundWork(): number {\n return pending.size\n}\n\n/**\n * The platform hook `createHandler()` and the web entry forward background\n * work to. Cloudflare Workers' `ctx`, Netlify's `context`, and `{ waitUntil }`\n * from `@vercel/functions` all have this shape.\n */\nexport interface PlatformContext {\n waitUntil?(promise: Promise<unknown>): void\n}\n\n/** Hand every pending (and later-registered) promise to the platform. */\nexport function forwardBackgroundWork(platform: PlatformContext | undefined): void {\n platform?.waitUntil?.(settleBackgroundWork())\n}\n","/**\n * The slot a view engine fills so `ctx.render()` works on every runtime.\n * An adapter binds a renderer onto each request; `ctx.render` asks it first\n * and falls back to the runtime's own engine (Express + ViewAdapter) when it\n * doesn't own the name. `Symbol.for`, so an engine binds it without\n * importing this module.\n */\nimport type { RequestContext } from './context'\n\nexport const VIEW_RENDERER = Symbol.for('kickjs.viewRenderer')\n\nexport interface ViewRenderOptions {\n status?: number\n headers?: Record<string, string>\n /** A layout for this render, or `false` for none — a partial response. */\n layout?: boolean | string\n locale?: string\n timeZone?: string\n}\n\n/** Resolves to the HTML, or to `undefined` when the name isn't this engine's. */\nexport type ViewRenderer = (\n name: string,\n data: Record<string, unknown>,\n opts: ViewRenderOptions,\n ctx: RequestContext,\n) => Promise<string | undefined>\n\nexport function bindViewRenderer(req: object, renderer: ViewRenderer): void {\n ;(req as Record<symbol, unknown>)[VIEW_RENDERER] = renderer\n}\n\nexport function viewRendererFor(req: unknown): ViewRenderer | undefined {\n return (req as Record<symbol, ViewRenderer | undefined> | null)?.[VIEW_RENDERER]\n}\n\nconst PENDING = Symbol('kickjs.pendingResponse')\n\n/** Remember a response still being produced, so the pipeline waits for it. */\nexport function setPendingResponse(ctx: object, p: Promise<void>): void {\n ;(ctx as Record<symbol, unknown>)[PENDING] = p\n}\n\n/** A response `ctx.render()` is still producing, when the handler didn't await it. */\nexport function pendingResponse(ctx: object): Promise<void> | undefined {\n return (ctx as Record<symbol, Promise<void> | undefined>)[PENDING]\n}\n"],"mappings":";;;;;;;;;;mJAuCA,MAAa,aAAe,IAAI,kBAMhC,SAAgB,iBAAgC,CAC9C,IAAM,MAAQ,aAAa,SAAS,EACpC,GAAI,CAAC,MACH,MAAU,MACR,iGACF,EAEF,OAAO,KACT,CA4BA,SAAgB,gBAA0C,IAAkC,CAC1F,OAAO,aAAa,SAAS,CAAC,EAAE,OAAO,IAAI,GAAG,CAChD,CC7DA,MAAM,IAAM,aAAa,WAAW,EAC9B,wBAAU,IAAI,IAgBpB,SAAgB,UAAU,QAAiC,CACzD,IAAM,UAAY,aAAa,SAAS,CAAC,EAAE,UACrC,QAAyB,QAAQ,QAAQ,OAAO,CAAC,CAAC,SAChD,CAAC,EACN,KAAiB,CAChB,IAAI,MAAM,CAAE,IAAK,SAAU,EAAG,8CAA8C,EAC5E,YAAY,IAAK,CAAE,OAAQ,aAAc,SAAU,CAAC,CACtD,CACF,EACA,QAAQ,IAAI,OAAO,EACnB,QAAa,YAAc,QAAQ,OAAO,OAAO,CAAC,CACpD,CAMA,eAAsB,sBAAsC,CAC1D,KAAO,QAAQ,KAAO,GAAG,MAAM,QAAQ,IAAI,OAAO,CACpD,CAGA,SAAgB,uBAAgC,CAC9C,OAAO,QAAQ,IACjB,CAYA,SAAgB,sBAAsB,SAA6C,CACjF,UAAU,YAAY,qBAAqB,CAAC,CAC9C,CCpEA,MAAa,cAAgB,OAAO,IAAI,qBAAqB,EAmB7D,SAAgB,iBAAiB,IAAa,SAA8B,CACzE,IAAiC,eAAiB,QACrD,CAEA,SAAgB,gBAAgB,IAAwC,CACtE,OAAQ,MAA0D,cACpE,CAEA,MAAM,QAAU,OAAO,wBAAwB,EAG/C,SAAgB,mBAAmB,IAAa,EAAwB,CACrE,IAAiC,SAAW,CAC/C,CAGA,SAAgB,gBAAgB,IAAwC,CACtE,OAAQ,IAAkD,QAC5D"}
|
|
1
|
+
{"version":3,"file":"view-renderer-CSPD7F-f.mjs","names":[],"sources":["../src/http/request-store.ts","../src/http/background.ts","../src/http/view-renderer.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { ContextMetaKey, MetaValue } from '../core/execution-context'\n\n/** Per-request storage for REQUEST-scoped DI and request context propagation */\nexport interface RequestStore {\n /** Unique request identifier */\n requestId: string\n /**\n * Per-request singleton cache for REQUEST-scoped services. Keys are\n * heterogeneous (class constructors, `InjectionToken` objects, raw\n * strings), so the map type stays `Map<any, any>`.\n */\n instances: Map<any, any>\n /**\n * Per-request key/value bag. Canonical backing store for\n * `RequestContext.set/get` and the Context Contributor pipeline (#107)\n * since Phase 3. Anything written here is visible to every concrete\n * execution context constructed for the same request, regardless of\n * which middleware/contributor wrote it.\n *\n * Keys are constrained to `string` per the locked decision in\n * `architecture.md` §20.12 (#4); the value type is `unknown` because\n * the concrete shape at each key is determined by the consumer's\n * `ContextMeta` augmentation, not by the store itself.\n *\n * Prefer the {@link getRequestValue} helper over reaching into this\n * map directly — it threads the augmented `ContextMeta` shape through\n * `MetaValue<K>` so consumers get typed reads without an `as` cast.\n * Writes should flow through `ctx.set(key, value)` or a Context\n * Contributor's return value — see the `setRequestValue` note below\n * for why this package intentionally does NOT ship a service-level\n * write helper.\n */\n values: Map<string, unknown>\n /** Set once {@link disposeRequestStore} has run — guards double-dispose. */\n disposed?: boolean\n}\n\n/** AsyncLocalStorage instance shared across the framework */\nexport const requestStore = new AsyncLocalStorage<RequestStore>()\n\n/**\n * Get the current request store. Throws if called outside a request context.\n * Used by the Container to resolve REQUEST-scoped dependencies.\n */\nexport function getRequestStore(): RequestStore {\n const store = requestStore.getStore()\n if (!store) {\n throw new Error(\n 'No active request context. REQUEST-scoped services can only be resolved during an HTTP request.',\n )\n }\n return store\n}\n\n/**\n * Read a per-request `ContextMeta`-keyed value from outside a controller\n * (services, repositories, anywhere with no `ctx` reference). Returns\n * the augmented type for the key — `MetaValue<K>` — so consumers get the\n * same static safety as `ctx.get(key)` without holding the context.\n *\n * Returns `undefined` outside an active request frame (background jobs,\n * startup code, tests without `requestScopeMiddleware()`) — the helper\n * is intentionally null-tolerant so calling it from a service that\n * runs in both request and non-request paths doesn't throw.\n *\n * @example\n * ```ts\n * declare module '@forinda/kickjs' {\n * interface ContextMeta { tenant: { id: string; name: string } }\n * }\n *\n * @Service()\n * class AuditService {\n * log(action: string) {\n * const tenant = getRequestValue('tenant') // typed: { id; name } | undefined\n * db.audit.insert({ action, tenantId: tenant?.id })\n * }\n * }\n * ```\n */\nexport function getRequestValue<K extends ContextMetaKey>(key: K): MetaValue<K> | undefined {\n return requestStore.getStore()?.values.get(key) as MetaValue<K> | undefined\n}\n\n// Intentionally NO `setRequestValue` export.\n//\n// Writes are deliberately context-scoped — only the controlled write\n// surfaces should mutate the per-request Map:\n//\n// 1. A Context Contributor's `resolve()` / `onError()` return value\n// (the runner does `ctx.set(reg.key, value)` on the contributor's\n// behalf). This is the canonical way to populate a key.\n// 2. A controller / middleware / contributor that holds a\n// `RequestContext` instance can call `ctx.set(key, value)`\n// directly. The write is auditable inline at the call site.\n//\n// Letting arbitrary services reach in and mutate the store from\n// anywhere produces \"spooky action at a distance\" — keys appear in\n// the request bag without an obvious source, and tracing which\n// service polluted what becomes a grep exercise. Services that need\n// to publish per-request state should return the value to the caller\n// (controller or contributor) and let *that* layer write it via\n// `ctx.set`. If a future need genuinely requires a service-level\n// write surface, expose a narrow function (`recordTrace`,\n// `markStartTime`) on a service that captures the side effect, not a\n// generic `setRequestValue`.\n","/**\n * Work that outlives the response — `waitUntil(promise)`.\n *\n * A handler that fires off an audit log, an email, or an analytics call and\n * answers without awaiting it leaves that promise unowned: on serverless the\n * platform freezes or kills the instance once the response is sent, and on a\n * Node server `SIGTERM` exits before it settles. `waitUntil` registers the\n * promise so something waits for it:\n *\n * - on the Node server, `shutdown()` awaits it (within `shutdownTimeout`);\n * - through `createHandler()` and the web entry, it is handed to the\n * platform's own `waitUntil` (Workers `ctx`, Netlify `context`, Vercel's\n * `waitUntil`) when you pass it in.\n *\n * Process-wide, like the DI container: one app per process.\n *\n * @module @forinda/kickjs/http/background\n */\nimport { createLogger } from '../core/logger'\nimport { reportError } from '../core/observers'\nimport { requestStore } from './request-store'\n\nconst log = createLogger('waitUntil')\nconst pending = new Set<Promise<void>>()\n\n/**\n * Keep `promise` alive past the response. A rejection is logged (with the\n * request id when called during a request), never left unhandled.\n *\n * @example\n * ```ts\n * @Post('/')\n * async create(ctx: RequestContext) {\n * const order = await this.orders.create(ctx.body)\n * ctx.waitUntil(this.mailer.sendReceipt(order)) // or waitUntil(...) outside a handler\n * return order\n * }\n * ```\n */\nexport function waitUntil(promise: Promise<unknown>): void {\n const requestId = requestStore.getStore()?.requestId\n const tracked: Promise<void> = Promise.resolve(promise).then(\n () => {},\n (err: unknown) => {\n log.error({ err, requestId }, 'Background work passed to waitUntil() failed')\n reportError(err, { source: 'background', requestId })\n },\n )\n pending.add(tracked)\n void tracked.finally(() => pending.delete(tracked))\n}\n\n/**\n * Resolve once every registered promise has settled — including work\n * registered while waiting. Never rejects.\n */\nexport async function settleBackgroundWork(): Promise<void> {\n while (pending.size > 0) await Promise.all(pending)\n}\n\n/** How many `waitUntil` promises have not settled yet. */\nexport function pendingBackgroundWork(): number {\n return pending.size\n}\n\n/**\n * The platform hook `createHandler()` and the web entry forward background\n * work to. Cloudflare Workers' `ctx`, Netlify's `context`, and `{ waitUntil }`\n * from `@vercel/functions` all have this shape.\n */\nexport interface PlatformContext {\n waitUntil?(promise: Promise<unknown>): void\n}\n\n/** Hand every pending (and later-registered) promise to the platform. */\nexport function forwardBackgroundWork(platform: PlatformContext | undefined): void {\n platform?.waitUntil?.(settleBackgroundWork())\n}\n","/**\n * The slot a view engine fills so `ctx.render()` works on every runtime.\n * An adapter binds a renderer onto each request; `ctx.render` asks it first\n * and falls back to the runtime's own engine (Express + ViewAdapter) when it\n * doesn't own the name. `Symbol.for`, so an engine binds it without\n * importing this module.\n */\nimport type { RequestContext } from './context'\n\nexport const VIEW_RENDERER = Symbol.for('kickjs.viewRenderer')\n\nexport interface ViewRenderOptions {\n status?: number\n headers?: Record<string, string>\n /** A layout for this render, or `false` for none — a partial response. */\n layout?: boolean | string\n locale?: string\n timeZone?: string\n}\n\n/** Resolves to the HTML, or to `undefined` when the name isn't this engine's. */\nexport type ViewRenderer = (\n name: string,\n data: Record<string, unknown>,\n opts: ViewRenderOptions,\n ctx: RequestContext,\n) => Promise<string | undefined>\n\nexport function bindViewRenderer(req: object, renderer: ViewRenderer): void {\n ;(req as Record<symbol, unknown>)[VIEW_RENDERER] = renderer\n}\n\nexport function viewRendererFor(req: unknown): ViewRenderer | undefined {\n return (req as Record<symbol, ViewRenderer | undefined> | null)?.[VIEW_RENDERER]\n}\n\nconst PENDING = Symbol('kickjs.pendingResponse')\n\n/** Remember a response still being produced, so the pipeline waits for it. */\nexport function setPendingResponse(ctx: object, p: Promise<void>): void {\n ;(ctx as Record<symbol, unknown>)[PENDING] = p\n}\n\n/** A response `ctx.render()` is still producing, when the handler didn't await it. */\nexport function pendingResponse(ctx: object): Promise<void> | undefined {\n return (ctx as Record<symbol, Promise<void> | undefined>)[PENDING]\n}\n"],"mappings":";;;;;;;;;;mJAuCA,MAAa,aAAe,IAAI,kBAMhC,SAAgB,iBAAgC,CAC9C,IAAM,MAAQ,aAAa,SAAS,EACpC,GAAI,CAAC,MACH,MAAU,MACR,iGACF,EAEF,OAAO,KACT,CA4BA,SAAgB,gBAA0C,IAAkC,CAC1F,OAAO,aAAa,SAAS,CAAC,EAAE,OAAO,IAAI,GAAG,CAChD,CC7DA,MAAM,IAAM,aAAa,WAAW,EAC9B,wBAAU,IAAI,IAgBpB,SAAgB,UAAU,QAAiC,CACzD,IAAM,UAAY,aAAa,SAAS,CAAC,EAAE,UACrC,QAAyB,QAAQ,QAAQ,OAAO,CAAC,CAAC,SAChD,CAAC,EACN,KAAiB,CAChB,IAAI,MAAM,CAAE,IAAK,SAAU,EAAG,8CAA8C,EAC5E,YAAY,IAAK,CAAE,OAAQ,aAAc,SAAU,CAAC,CACtD,CACF,EACA,QAAQ,IAAI,OAAO,EACnB,QAAa,YAAc,QAAQ,OAAO,OAAO,CAAC,CACpD,CAMA,eAAsB,sBAAsC,CAC1D,KAAO,QAAQ,KAAO,GAAG,MAAM,QAAQ,IAAI,OAAO,CACpD,CAGA,SAAgB,uBAAgC,CAC9C,OAAO,QAAQ,IACjB,CAYA,SAAgB,sBAAsB,SAA6C,CACjF,UAAU,YAAY,qBAAqB,CAAC,CAC9C,CCpEA,MAAa,cAAgB,OAAO,IAAI,qBAAqB,EAmB7D,SAAgB,iBAAiB,IAAa,SAA8B,CACzE,IAAiC,eAAiB,QACrD,CAEA,SAAgB,gBAAgB,IAAwC,CACtE,OAAQ,MAA0D,cACpE,CAEA,MAAM,QAAU,OAAO,wBAAwB,EAG/C,SAAgB,mBAAmB,IAAa,EAAwB,CACrE,IAAiC,SAAW,CAC/C,CAGA,SAAgB,gBAAgB,IAAwC,CACtE,OAAQ,IAAkD,QAC5D"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.12.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
function randomHex(bytes){let buf=crypto.getRandomValues(new Uint8Array(bytes));return Array.from(buf,b=>b.toString(16).padStart(2,`0`)).join(``)}function safeEqual(a,b){let length=Math.max(a.length,b.length),diff=a.length^b.length;for(let i=0;i<length;i++)diff|=a.charCodeAt(i)^b.charCodeAt(i);return diff===0}function matchesBearer(header,secret){return typeof header==`string`&&typeof secret==`string`&&secret.length>0&&safeEqual(header,`Bearer ${secret}`)}export{randomHex as n,safeEqual as r,matchesBearer as t};
|
|
12
|
-
//# sourceMappingURL=web-crypto-
|
|
12
|
+
//# sourceMappingURL=web-crypto-Q0WFs8ua.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"web-crypto-
|
|
1
|
+
{"version":3,"file":"web-crypto-Q0WFs8ua.mjs","names":[],"sources":["../src/core/web-crypto.ts"],"sourcesContent":["/**\n * Web Crypto helpers — portable across node/bun/deno/workers via\n * `globalThis.crypto`. The Web Crypto migration lives here so the request\n * path never imports `node:crypto` (edge-runtime portability).\n */\n\n/** Random hex string — replacement for `randomBytes(n).toString('hex')`. */\nexport function randomHex(bytes: number): string {\n const buf = crypto.getRandomValues(new Uint8Array(bytes))\n return Array.from(buf, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/**\n * Constant-time string comparison for secrets and tokens — the portable\n * counterpart of `timingSafeEqual`. Walks the longer input and folds the\n * length difference in, so it doesn't stop at the first wrong character and\n * a guess's contents don't show in the timing. The loop runs over the longer\n * input, so the time can still reveal the expected value's length.\n */\nexport function safeEqual(a: string, b: string): boolean {\n const length = Math.max(a.length, b.length)\n let diff = a.length ^ b.length\n // Past the end, charCodeAt is NaN, which `^` treats as 0.\n for (let i = 0; i < length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\n\n/**\n * Constant-time check of an `Authorization: Bearer <secret>` header against a\n * shared secret — a cron trigger, a metrics scrape, a webhook. `false` for a\n * missing or non-string header, and for an empty secret (an unset env var\n * must not let `Authorization: Bearer ` through). Pass\n * `ctx.headers.authorization` as is.\n */\nexport function matchesBearer(header: unknown, secret: string): boolean {\n return (\n typeof header === 'string' &&\n typeof secret === 'string' &&\n secret.length > 0 &&\n safeEqual(header, `Bearer ${secret}`)\n )\n}\n"],"mappings":";;;;;;;;;;AAOA,SAAgB,UAAU,MAAuB,CAC/C,IAAM,IAAM,OAAO,gBAAgB,IAAI,WAAW,KAAK,CAAC,EACxD,OAAO,MAAM,KAAK,IAAM,GAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,CACxE,CASA,SAAgB,UAAU,EAAW,EAAoB,CACvD,IAAM,OAAS,KAAK,IAAI,EAAE,OAAQ,EAAE,MAAM,EACtC,KAAO,EAAE,OAAS,EAAE,OAExB,IAAK,IAAI,EAAI,EAAG,EAAI,OAAQ,IAAK,MAAQ,EAAE,WAAW,CAAC,EAAI,EAAE,WAAW,CAAC,EACzE,OAAO,OAAS,CAClB,CASA,SAAgB,cAAc,OAAiB,OAAyB,CACtE,OACE,OAAO,QAAW,UAClB,OAAO,QAAW,UAClB,OAAO,OAAS,GAChB,UAAU,OAAQ,UAAU,QAAQ,CAExC"}
|
package/dist/web.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v10.
|
|
2
|
+
* @forinda/kickjs v10.12.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{Container}from"./core/container.mjs";import{a as moduleName,n as RouteUrls,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-
|
|
11
|
+
import{Container}from"./core/container.mjs";import{a as moduleName,n as RouteUrls,r as MutableModuleRegistry,t as ROUTE_URLS}from"./url-for-kZidAFyr.mjs";import{runCronJobs}from"./core/cron.mjs";import{d as stampJobContext,l as registerJobContext,t as JOB_CONTEXT_FIELD,u as runJob}from"./jobs-F8vpXQt7.mjs";import{buildMountPath}from"./core/path.mjs";import{n as assertRouteUnique,r as buildRouteTable,t as _setExternalContributorSources}from"./router-builder-abKMvAmP.mjs";import{t as matchesBearer}from"./web-crypto-Q0WFs8ua.mjs";import{o as parseByteSize}from"./body-policy-cWfUReGC.mjs";import{f as requestStore,l as waitUntil,o as forwardBackgroundWork}from"./view-renderer-CSPD7F-f.mjs";import{notFoundHandler}from"./http/middleware/error-handler.mjs";import{i as loadSettings}from"./settings-vuB5TedF.mjs";import{a as reply,r as isReply}from"./reply-Bg1gyBtE.mjs";import{n as KvSessionStore,r as rateLimitGuard,t as KvRateLimitStore}from"./kv-stores-DxVO4y2v.mjs";import{a as WebResponseDriver,i as WebRequestShim,n as headFromGet,t as compileWebRoute}from"./handler-BpMOjmfq.mjs";function createWebApp(options){let h3mod=options.h3;if(typeof h3mod?.H3!=`function`)throw Error(`@forinda/kickjs/web: pass the h3 v2 module — \`createWebApp({ h3: await import("h3"), ... })\`. The installed h3 must be v2 (npm dist-tag 'latest'); v1 has no H3 class.`);let container=Container.getInstance(),routeUrls=new RouteUrls;if(container.registerInstance(ROUTE_URLS,routeUrls),options.env){let env=options.env;Container.setEnvResolver(key=>env[key])}Container.setRequestStoreProvider(()=>requestStore.getStore()??null);let registry=new MutableModuleRegistry;for(let m of options.modules)registry.mount(m);let modules=registry.entries.map(entry=>typeof entry==`function`?new entry:entry),settingsEnv=options.env??(typeof process<`u`?process.env:{});for(let[section,value]of loadSettings([...options.settings??[],...modules.flatMap(mod=>mod.settings?.()??[])],settingsEnv))container.registerInstance(section,value);for(let mod of modules)mod.register?.(container);container.bootstrap();let app=new h3mod.H3,getUrls=[],apiPrefix=options.apiPrefix??`/api`,defaultVersion=options.defaultVersion??1,globalMiddleware=options.middlewares??[],bodyLimit=parseByteSize(options.jsonLimit??`1mb`),globalSources=(options.contributors??[]).map(registration=>({source:`global`,registration,label:`createWebApp`})),seenRoutes=/* @__PURE__ */ new Map,mounted=[];for(let mod of modules){let moduleLabel=moduleName(mod),moduleSources=(mod.contributors?.()??[]).map(registration=>({source:`module`,registration,label:moduleLabel}));_setExternalContributorSources([...moduleSources,...globalSources]);try{let result=mod.routes();if(!result)continue;let routeSets=Array.isArray(result)?result:[result];for(let route of routeSets){if(!route.controller)throw Error(`@forinda/kickjs/web: module route at '${route.path}' has no controller. Express-style \`router\` mounts are not supported on the web entry.`);let version=route.version??defaultVersion,mountPath=buildMountPath(route.prefix===!1?``:apiPrefix,version,route.path);for(let entry of buildRouteTable(route.controller,{mountFlags:route.flags})){let url=joinPath(mountPath,entry.path),owner=`${route.controller.name??`controller`}.${String(entry.meta.handlerName??`?`)}`;assertRouteUnique(seenRoutes,entry.method,url,owner),mounted.push({method:entry.method,path:url}),globalMiddleware.length>0&&(entry.middlewares=[...globalMiddleware,...entry.middlewares]),entry.validationError=options.validationError,entry.urls=routeUrls,routeUrls.add(owner,url);let run=compileWebRoute(entry,void 0,{bodyLimit}),handler=event=>run({request:event.req,url:event.url,params:event.context.params??{}});app.on(entry.method,url,handler),entry.method===`GET`&&getUrls.push({url,handler})}}}finally{_setExternalContributorSources([])}}for(let{url,handler}of getUrls)app.on(`HEAD`,url,event=>headFromGet(handler(event)));let notFound=notFoundHandler(mounted);return app.all(`/**`,event=>{let driver=new WebResponseDriver(event.req.signal);return notFound(new WebRequestShim(event.req,event.url),driver,()=>{}),driver.ready}),{fetch:async(request,platform)=>{let response=await app.fetch(request);return forwardBackgroundWork(platform),response},h3:app}}function createFetchHandler(build){let app;return{fetch:(request,env={},ctx)=>(app??=createWebApp(build(env)),app.fetch(request,ctx)),scheduled:async(event,env={},ctx)=>{app??=createWebApp(build(env));let run=runCronJobs(Container.getInstance(),{expression:event.cron},`workers`).then(()=>{});ctx?.waitUntil?.(run),await run},queue:async(batch,env={})=>{app??=createWebApp(build(env));let container=Container.getInstance();await Promise.all(batch.messages.map(async message=>{let body=message.body,named=typeof body==`object`&&!!body&&typeof body.name==`string`;try{await runJob(container,batch.queue,{name:named?body.name:``,data:named?body.data:message.body,id:message.id}),message.ack()}catch{message.retry()}}))}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{JOB_CONTEXT_FIELD,KvRateLimitStore,KvSessionStore,WebRequestShim,WebResponseDriver,compileWebRoute,createFetchHandler,createWebApp,isReply,matchesBearer,rateLimitGuard,registerJobContext,reply,runCronJobs,runJob,stampJobContext,waitUntil};
|
|
12
12
|
//# sourceMappingURL=web.mjs.map
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"application-EinAcKLu.d.mts","names":["_$__0.AdapterFactory","Request","Response","NextFunction","Request","Response","NextFunction","_$_____0.AdapterFactory","_$_____0.AdapterFactory","_$__reply0.Reply","_$__0.ModuleFactory"],"sources":["../src/core/kick-error.ts","../src/core/circuit-breaker.ts","../src/core/context-errors.ts","../src/core/mount-sort.ts","../src/core/asset-keys.ts","../src/core/route-policy.ts","../src/http/startup-timeline.ts","../src/http/startup-checks.ts","../src/http/cache-response.ts","../src/http/metrics.ts","../src/http/body-policy.ts","../src/http/cron-adapter.ts","../src/http/tracing.ts","../src/http/bootstrap.ts","../src/http/handler.ts","../src/http/cluster.ts","../src/http/define-http-context-decorator.ts","../src/core/password.ts","../src/core/signing.ts","../src/http/runtimes/express-lazy.ts","../src/http/request-store.ts","../src/http/middleware/request-scope.ts","../src/http/middleware/trace-context.ts","../src/http/middleware/views.ts","../src/http/middleware/spa.ts","../src/http/health-module.ts","../src/http/application.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAiBiB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,UAAU;;cAGC,kBAAkB;WACb;WACA;WACA;WACA;WACA;WACA,UAAU;EAE1B,YAAY,MAAM;;UAiDH;;;;;;EAMf;;;;;;;iBAQc,gBACd,KAAK,gBAAgB,WACrB,UAAS;;;;;;;;;;;;;;;;;;;;KCvFC;UAEK;;EAEf;;EAEA;;EAEA;;UAGe;EACf;EACA;EACA,OAAO;EACP,cAAc;;;;;cAMH,yBAAyB;WACR;EAA5B,YAA4B;;cAMjB;WAaO;UAZV;UACA;UACA;UACA;UACA;UACA;mBAES;mBACA;mBACA;EAEjB,YACkB,cAChB,SAAS;;;;;EAWL,QAAQ,GAAG,UAAU,QAAQ,KAAK,QAAQ;;EA0BhD,YAAY;;EAMZ,YAAY;;EAWZ;UASQ;UAWA;UAeA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cC1HG,gCAAgC;WAClC;WACA;WACA;WACA;EAET,YAAY,aAAa,mBAAmB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA0CjD,iCAAiC;WACnC;WACA;EAET,YAAY,aAAa;;;;;;;;;;;;cA6Cd,8BAA8B;WAChC;WACA;EAET,YAAY,0BAA0B;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