@forinda/kickjs 10.2.0 → 10.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/dist/adapter-6fjmVVc2.d.mts +2324 -0
  2. package/dist/adapter-6fjmVVc2.d.mts.map +1 -0
  3. package/dist/{app-module-Ftz6m7SO.d.mts → app-module-Cuu-Ma_E.d.mts} +5 -4
  4. package/dist/app-module-Cuu-Ma_E.d.mts.map +1 -0
  5. package/dist/application-BuUWvaqp.d.mts +1985 -0
  6. package/dist/application-BuUWvaqp.d.mts.map +1 -0
  7. package/dist/{application-Ch5jT4fj.mjs → application-CYCvctQx.mjs} +3 -3
  8. package/dist/{application-Ch5jT4fj.mjs.map → application-CYCvctQx.mjs.map} +1 -1
  9. package/dist/bootstrap-CfaYHbmd.mjs +12 -0
  10. package/dist/{bootstrap-D56HIq1N.mjs.map → bootstrap-CfaYHbmd.mjs.map} +1 -1
  11. package/dist/{bounded-counters-B9dzk5o_.mjs → bounded-counters-BcA0f0bV.mjs} +2 -2
  12. package/dist/{bounded-counters-B9dzk5o_.mjs.map → bounded-counters-BcA0f0bV.mjs.map} +1 -1
  13. package/dist/{client-ip-lYnBU2PR.mjs → client-ip-BpauuVN_.mjs} +2 -2
  14. package/dist/{client-ip-lYnBU2PR.mjs.map → client-ip-BpauuVN_.mjs.map} +1 -1
  15. package/dist/config/index.d.mts +1 -1
  16. package/dist/config/index.mjs +2 -2
  17. package/dist/{config-BfImCyaG.mjs → config-DgMxtfcW.mjs} +3 -3
  18. package/dist/{config-BfImCyaG.mjs.map → config-DgMxtfcW.mjs.map} +1 -1
  19. package/dist/container-4iJdDkRH.d.mts +3 -0
  20. package/dist/{context-C6iKf9hN.mjs → context-DJvuLfrx.mjs} +3 -3
  21. package/dist/{context-C6iKf9hN.mjs.map → context-DJvuLfrx.mjs.map} +1 -1
  22. package/dist/{context-errors-6psUheqc.mjs → context-errors-BGIOYMV5.mjs} +2 -2
  23. package/dist/{context-errors-6psUheqc.mjs.map → context-errors-BGIOYMV5.mjs.map} +1 -1
  24. package/dist/{contributor-runner-Bn-ipSS5.mjs → contributor-runner-CJn1gZ8h.mjs} +3 -3
  25. package/dist/{contributor-runner-Bn-ipSS5.mjs.map → contributor-runner-CJn1gZ8h.mjs.map} +1 -1
  26. package/dist/core/adapter.d.mts +1 -1
  27. package/dist/core/adapter.mjs +1 -1
  28. package/dist/core/app-module.d.mts +1 -1
  29. package/dist/core/app-module.mjs +1 -1
  30. package/dist/core/cache.mjs +1 -1
  31. package/dist/core/container.d.mts +2 -2
  32. package/dist/core/container.mjs +2 -2
  33. package/dist/core/cron.mjs +2 -2
  34. package/dist/core/decorators.d.mts +2 -2
  35. package/dist/core/decorators.mjs +2 -2
  36. package/dist/core/decorators.mjs.map +1 -1
  37. package/dist/core/errors.mjs +1 -1
  38. package/dist/core/interfaces.d.mts +2 -2
  39. package/dist/core/interfaces.mjs +2 -2
  40. package/dist/core/interfaces.mjs.map +1 -1
  41. package/dist/core/logger.mjs +1 -1
  42. package/dist/core/path.mjs +1 -1
  43. package/dist/core/plugin.d.mts +1 -1
  44. package/dist/core/plugin.mjs +1 -1
  45. package/dist/core/reactivity.mjs +1 -1
  46. package/dist/core-YE-k8IrU.mjs +12 -0
  47. package/dist/{core-CFXpwc7m.mjs.map → core-YE-k8IrU.mjs.map} +1 -1
  48. package/dist/{csrf-C3RRSCMs.mjs → csrf-C6Em76kH.mjs} +3 -3
  49. package/dist/{csrf-C3RRSCMs.mjs.map → csrf-C6Em76kH.mjs.map} +1 -1
  50. package/dist/{csrf-Cy1meSpf.d.mts → csrf-ahBjt1ay.d.mts} +2 -2
  51. package/dist/{csrf-Cy1meSpf.d.mts.map → csrf-ahBjt1ay.d.mts.map} +1 -1
  52. package/dist/decorate-CaEYam5J.mjs +13 -0
  53. package/dist/{decorate-DkxaoRo5.mjs.map → decorate-CaEYam5J.mjs.map} +1 -1
  54. package/dist/{decorators-DaQUNXOn.d.mts → decorators-deGmthGc.d.mts} +3 -199
  55. package/dist/decorators-deGmthGc.d.mts.map +1 -0
  56. package/dist/{define-adapter-BRJ6lXkV.mjs → define-adapter-C6H-I1og.mjs} +2 -2
  57. package/dist/{define-adapter-BRJ6lXkV.mjs.map → define-adapter-C6H-I1og.mjs.map} +1 -1
  58. package/dist/di-hooks-BE0IOQk-.mjs +132 -0
  59. package/dist/di-hooks-BE0IOQk-.mjs.map +1 -0
  60. package/dist/disposables-Cste73oY.mjs +11 -0
  61. package/dist/error-handler-C6JJJct_.d.mts +63 -0
  62. package/dist/error-handler-C6JJJct_.d.mts.map +1 -0
  63. package/dist/{handler-Dl_1fGxE.mjs → handler-DUyRCpPw.mjs} +3 -3
  64. package/dist/{handler-Dl_1fGxE.mjs.map → handler-DUyRCpPw.mjs.map} +1 -1
  65. package/dist/{host-DTQ5pZgg.mjs → host-fc-YQZnN.mjs} +2 -2
  66. package/dist/{host-DTQ5pZgg.mjs.map → host-fc-YQZnN.mjs.map} +1 -1
  67. package/dist/http/application.d.mts +1 -1
  68. package/dist/http/application.mjs +2 -2
  69. package/dist/http/bootstrap.d.mts +1 -1
  70. package/dist/http/bootstrap.mjs +2 -2
  71. package/dist/http/context.d.mts +2 -2
  72. package/dist/http/context.mjs +2 -2
  73. package/dist/http/middleware/allowed-hosts.mjs +2 -2
  74. package/dist/http/middleware/breach-padding.mjs +1 -1
  75. package/dist/http/middleware/cors.mjs +1 -1
  76. package/dist/http/middleware/csrf.d.mts +1 -1
  77. package/dist/http/middleware/csrf.mjs +2 -2
  78. package/dist/http/middleware/error-handler.d.mts +1 -1
  79. package/dist/http/middleware/error-handler.mjs +2 -2
  80. package/dist/http/middleware/helmet.mjs +1 -1
  81. package/dist/http/middleware/rate-limit.mjs +2 -2
  82. package/dist/http/middleware/request-id.mjs +1 -1
  83. package/dist/http/middleware/request-logger.mjs +2 -2
  84. package/dist/http/middleware/session.mjs +2 -2
  85. package/dist/http/middleware/spa.d.mts +1 -1
  86. package/dist/http/middleware/spa.mjs +2 -2
  87. package/dist/http/middleware/upload.d.mts +1 -1
  88. package/dist/http/middleware/upload.mjs +2 -3
  89. package/dist/http/middleware/upload.mjs.map +1 -1
  90. package/dist/http/middleware/validate.mjs +1 -1
  91. package/dist/http/middleware/views.d.mts +2 -2
  92. package/dist/http/middleware/views.mjs +2 -2
  93. package/dist/http/middleware/views.mjs.map +1 -1
  94. package/dist/http/query/index.mjs +2 -2
  95. package/dist/http/router-builder.d.mts +1 -1
  96. package/dist/http/router-builder.mjs +2 -2
  97. package/dist/http/runtimes/fastify.d.mts +1 -1
  98. package/dist/http/runtimes/fastify.d.mts.map +1 -1
  99. package/dist/http/runtimes/fastify.mjs +3 -3
  100. package/dist/http/runtimes/fastify.mjs.map +1 -1
  101. package/dist/http/runtimes/h3-web.mjs +1 -1
  102. package/dist/http/runtimes/h3.d.mts +5 -4
  103. package/dist/http/runtimes/h3.d.mts.map +1 -1
  104. package/dist/http/runtimes/h3.mjs +2 -2
  105. package/dist/http/runtimes/h3.mjs.map +1 -1
  106. package/dist/{index-CuiWSnZL.d.mts → index-Dms8LzHG.d.mts} +3 -3
  107. package/dist/{index-CuiWSnZL.d.mts.map → index-Dms8LzHG.d.mts.map} +1 -1
  108. package/dist/index.d.mts +17 -11
  109. package/dist/index.mjs +3 -3
  110. package/dist/index.mjs.map +1 -1
  111. package/dist/interfaces-C6LHcYsg.d.mts +34 -0
  112. package/dist/interfaces-C6LHcYsg.d.mts.map +1 -0
  113. package/dist/{is-production-tnFh6NCj.mjs → is-production-0lB5MU1j.mjs} +2 -2
  114. package/dist/{is-production-tnFh6NCj.mjs.map → is-production-0lB5MU1j.mjs.map} +1 -1
  115. package/dist/jobs-DWi_Lwbe.mjs +12 -0
  116. package/dist/{jobs-lLcPhIqq.mjs.map → jobs-DWi_Lwbe.mjs.map} +1 -1
  117. package/dist/kv-stores-BGXPKv15.d.mts +366 -0
  118. package/dist/kv-stores-BGXPKv15.d.mts.map +1 -0
  119. package/dist/{kv-stores-_wz4DEiw.mjs → kv-stores-BGXeNEDK.mjs} +3 -3
  120. package/dist/{kv-stores-_wz4DEiw.mjs.map → kv-stores-BGXeNEDK.mjs.map} +1 -1
  121. package/dist/lazy-serve-static-Barg3__1.mjs +12 -0
  122. package/dist/lazy-serve-static-Barg3__1.mjs.map +1 -0
  123. package/dist/metadata-CnL9sQFa.mjs +11 -0
  124. package/dist/{observers-IGga6yut.mjs → observers-BNMQ7VLb.mjs} +2 -2
  125. package/dist/{observers-IGga6yut.mjs.map → observers-BNMQ7VLb.mjs.map} +1 -1
  126. package/dist/{query-AnbWMCd6.mjs → query-mXPZYtQw.mjs} +2 -2
  127. package/dist/{query-AnbWMCd6.mjs.map → query-mXPZYtQw.mjs.map} +1 -1
  128. package/dist/{reply-DjysdCPI.mjs → reply-CMRk-Jp3.mjs} +3 -3
  129. package/dist/{reply-DjysdCPI.mjs.map → reply-CMRk-Jp3.mjs.map} +1 -1
  130. package/dist/{respond-vPZlRnZR.mjs → respond-gPELdOSi.mjs} +2 -2
  131. package/dist/{respond-vPZlRnZR.mjs.map → respond-gPELdOSi.mjs.map} +1 -1
  132. package/dist/{route-flag-BjRpxryx.mjs → route-flag-8Pi83-uw.mjs} +3 -3
  133. package/dist/{route-flag-BjRpxryx.mjs.map → route-flag-8Pi83-uw.mjs.map} +1 -1
  134. package/dist/{route-policy-Pffte5M1.mjs → route-policy-0LAfSzo-.mjs} +2 -2
  135. package/dist/{route-policy-Pffte5M1.mjs.map → route-policy-0LAfSzo-.mjs.map} +1 -1
  136. package/dist/router-builder-D0SDqFTr.mjs +12 -0
  137. package/dist/{router-builder-CrWKq6O2.mjs.map → router-builder-D0SDqFTr.mjs.map} +1 -1
  138. package/dist/router-builder-obSpg-Ub.d.mts +56 -0
  139. package/dist/router-builder-obSpg-Ub.d.mts.map +1 -0
  140. package/dist/settings-BW5gVm6c.mjs +14 -0
  141. package/dist/{settings-CFtEAQUs.mjs.map → settings-BW5gVm6c.mjs.map} +1 -1
  142. package/dist/{settings-C8VKewNS.d.mts → settings-BnE75hnr.d.mts} +2 -2
  143. package/dist/{settings-C8VKewNS.d.mts.map → settings-BnE75hnr.d.mts.map} +1 -1
  144. package/dist/token-D6jfTQLA.d.mts +3 -0
  145. package/dist/token-Q2c8xwJE.mjs +11 -0
  146. package/dist/upload-CyBSlnH_.d.mts +104 -0
  147. package/dist/upload-CyBSlnH_.d.mts.map +1 -0
  148. package/dist/{upload-config-DLgt4l7F.mjs → upload-config-D22qKth8.mjs} +2 -2
  149. package/dist/{upload-config-DLgt4l7F.mjs.map → upload-config-D22qKth8.mjs.map} +1 -1
  150. package/dist/url-for-UZ5kJjsG.mjs +12 -0
  151. package/dist/{url-for-Cyh7pJCb.mjs.map → url-for-UZ5kJjsG.mjs.map} +1 -1
  152. package/dist/web.d.mts +5 -4
  153. package/dist/web.d.mts.map +1 -1
  154. package/dist/web.mjs +2 -2
  155. package/dist/web.mjs.map +1 -1
  156. package/package.json +6 -1
  157. package/dist/adapter-C5I5e_-i.d.mts +0 -4866
  158. package/dist/adapter-C5I5e_-i.d.mts.map +0 -1
  159. package/dist/app-module-Ftz6m7SO.d.mts.map +0 -1
  160. package/dist/bootstrap-D56HIq1N.mjs +0 -12
  161. package/dist/container-C2aTj8Cb.mjs +0 -132
  162. package/dist/container-C2aTj8Cb.mjs.map +0 -1
  163. package/dist/container-Dpvd66Yt.d.mts +0 -298
  164. package/dist/container-Dpvd66Yt.d.mts.map +0 -1
  165. package/dist/core-CFXpwc7m.mjs +0 -12
  166. package/dist/decorate-DkxaoRo5.mjs +0 -13
  167. package/dist/decorators-DaQUNXOn.d.mts.map +0 -1
  168. package/dist/disposables-5nFqc1aC.mjs +0 -12
  169. package/dist/disposables-5nFqc1aC.mjs.map +0 -1
  170. package/dist/interfaces-C1hCSoLD.d.mts +0 -75
  171. package/dist/interfaces-C1hCSoLD.d.mts.map +0 -1
  172. package/dist/jobs-lLcPhIqq.mjs +0 -12
  173. package/dist/metadata-Tc6jhIBi.mjs +0 -12
  174. package/dist/metadata-Tc6jhIBi.mjs.map +0 -1
  175. package/dist/router-builder-CrWKq6O2.mjs +0 -12
  176. package/dist/settings-CFtEAQUs.mjs +0 -14
  177. package/dist/url-for-Cyh7pJCb.mjs +0 -12
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.2.0
2
+ * @forinda/kickjs v10.3.1
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 registerDisposable}from"../../disposables-5nFqc1aC.mjs";import{t as isProduction}from"../../is-production-tnFh6NCj.mjs";import{a as setCookie,r as replaceCookie,t as parseCookieHeader}from"../../respond-vPZlRnZR.mjs";import{createCipheriv,createDecipheriv,createHmac,hkdfSync,randomBytes,randomUUID,timingSafeEqual}from"node:crypto";var MemoryStore=class{sessions=/* @__PURE__ */ new Map;empty=/* @__PURE__ */ new Set;cleanupInterval;constructor(){this.cleanupInterval=setInterval(()=>this.purge(),6e4),this.cleanupInterval.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupInterval),this.sessions.clear(),this.empty.clear()}async get(sid){let entry=this.sessions.get(sid);return entry?Date.now()>entry.expires?(this.sessions.delete(sid),this.empty.delete(sid),null):entry.data:null}async set(sid,data,maxAge){for(this.sessions.delete(sid),this.sessions.set(sid,{data,expires:Date.now()+maxAge}),this.empty.delete(sid),Object.keys(data).length===0&&this.empty.add(sid);this.sessions.size>1e4;){let victim=this.empty.values().next().value??this.sessions.keys().next().value;this.sessions.delete(victim),this.empty.delete(victim)}}async destroy(sid){this.sessions.delete(sid),this.empty.delete(sid)}async touch(sid,maxAge){let entry=this.sessions.get(sid);entry&&(entry.expires=Date.now()+maxAge,this.sessions.delete(sid),this.sessions.set(sid,entry))}purge(){let now=Date.now();for(let[sid,entry]of this.sessions)now>entry.expires&&(this.sessions.delete(sid),this.empty.delete(sid))}};function secretList(secret){let list=Array.isArray(secret)?secret:[secret];if(list.length===0||list.some(s=>typeof s!=`string`||s.length===0))throw Error("session(): `secret` must be a non-empty string or list of strings");return list}function sign(value,secret){return`s:${value}.${createHmac(`sha256`,secret).update(value).digest(`base64url`)}`}function unsign(signed,secrets){if(!signed.startsWith(`s:`))return!1;let raw=signed.slice(2),dotIndex=raw.lastIndexOf(`.`);if(dotIndex===-1)return!1;let value=raw.slice(0,dotIndex),provided=Buffer.from(raw.slice(dotIndex+1));for(let[index,secret]of secrets.entries()){let expected=Buffer.from(createHmac(`sha256`,secret).update(value).digest(`base64url`));if(provided.length===expected.length&&timingSafeEqual(provided,expected))return{value,stale:index>0}}return!1}function session(options){if(options.store===`cookie`)return cookieSession(options);let{cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,cookie:cookieOpts={}}=options,secrets=secretList(options.secret),secret=secrets[0],store=options.store??new MemoryStore,cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??isProduction(),sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{},maxAge};return async(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let signedCookie=cookies[cookieName],sid=!1,sessionData=null,isNew=!1,staleSignature=!1;if(signedCookie){let unsigned=unsign(signedCookie,secrets);unsigned&&(sid=unsigned.value,staleSignature=unsigned.stale,sessionData=await store.get(sid))}(!sid||!sessionData)&&(sid=randomUUID(),sessionData={},isNew=!0);let currentSid=sid,currentData={...sessionData},destroyed=!1,sessionObj={get id(){return currentSid},data:currentData,async regenerate(){await store.destroy(currentSid),currentSid=randomUUID(),currentData={},sessionObj.data=currentData,await store.set(currentSid,currentData,maxAge),setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults)},async destroy(){await store.destroy(currentSid),destroyed=!0,currentData={},sessionObj.data=currentData,setCookie(res,cookieName,``,{...cookieDefaults,maxAge:0,expires:/* @__PURE__ */ new Date(0)})},async save(){destroyed||await store.set(currentSid,currentData,maxAge)}};req.session=sessionObj,isNew&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults),res.on(`finish`,async()=>{destroyed||(!isNew||saveUninitialized||Object.keys(currentData).length!==0)&&(await store.set(currentSid,currentData,maxAge),rolling&&!isNew&&store.touch&&await store.touch(currentSid,maxAge))}),!isNew&&(rolling||staleSignature)&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults),next()}}const cookieLog=createLogger(`Session`);function sealer(secrets,cookieName){let keys=secrets.map(secret=>Buffer.from(hkdfSync(`sha256`,secret,`kick.session`,`cookie-store-v1`,32))),key=keys[0],aad=Buffer.from(cookieName);return{seal(payload){let iv=randomBytes(12),cipher=createCipheriv(`aes-256-gcm`,key,iv).setAAD(aad),body=Buffer.concat([cipher.update(JSON.stringify(payload),`utf8`),cipher.final()]);return`v1.${Buffer.concat([iv,cipher.getAuthTag(),body]).toString(`base64url`)}`},open(value){if(!value.startsWith(`v1.`))return null;let raw;try{raw=Buffer.from(value.slice(3),`base64url`)}catch{return null}if(raw.length<29)return null;for(let[index,k]of keys.entries())try{let decipher=createDecipheriv(`aes-256-gcm`,k,raw.subarray(0,12)).setAAD(aad).setAuthTag(raw.subarray(12,28)),json=Buffer.concat([decipher.update(raw.subarray(28)),decipher.final()]),payload=JSON.parse(json.toString(`utf8`));return typeof payload?.i!=`string`||typeof payload.e!=`number`||!payload.d||typeof payload.d!=`object`?null:payload.e>Date.now()?{payload,stale:index>0}:null}catch{}return null}}}function cookieSession(options){let{cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,cookie:cookieOpts={}}=options,{seal,open}=sealer(secretList(options.secret),cookieName),cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??isProduction(),sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{}},warnedSize=!1;return(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let opened=cookies[cookieName]?open(cookies[cookieName]):null,existing=opened?.payload??null,isNew=!existing,id=existing?.i??randomUUID(),destroyed=!1,written=existing&&!opened?.stale?JSON.stringify(existing.d):void 0,write=(force=!1)=>{if(res.headersSent)return;if(destroyed){replaceCookie(res,cookieName,``,{...cookieDefaults,maxAge:0,expires:/* @__PURE__ */ new Date(0)});return}let json=JSON.stringify(sessionObj.data);if(json===written&&!force&&(!rolling||isNew)||written===void 0&&json===`{}`&&!saveUninitialized&&!force)return;let value=seal({i:id,d:sessionObj.data,e:Date.now()+maxAge});value.length+cookieName.length>4e3&&!warnedSize&&(warnedSize=!0,cookieLog.warn(`session cookie is ${value.length} bytes; browsers drop cookies over 4 KB, so this session will not be kept. Store less in it, or use a shared store.`)),replaceCookie(res,cookieName,value,{...cookieDefaults,maxAge}),written=json};for(let method of[`writeHead`,`flushHeaders`,`write`,`end`]){let original=res[method];typeof original==`function`&&(res[method]=function(...args){return write(),original.apply(this,args)})}res.on?.(`finish`,()=>write());let sessionObj={get id(){return id},data:existing?{...existing.d}:{},async regenerate(){id=randomUUID(),sessionObj.data={},written=void 0,write(!0)},async destroy(){destroyed=!0,sessionObj.data={},write()},async save(){write()}};req.session=sessionObj,next()}}export{MemoryStore,session};
11
+ import{createLogger}from"../../core/logger.mjs";import{r as registerDisposable}from"../../disposables-Cste73oY.mjs";import{t as isProduction}from"../../is-production-0lB5MU1j.mjs";import{a as setCookie,r as replaceCookie,t as parseCookieHeader}from"../../respond-gPELdOSi.mjs";import{createCipheriv,createDecipheriv,createHmac,hkdfSync,randomBytes,randomUUID,timingSafeEqual}from"node:crypto";var MemoryStore=class{sessions=/* @__PURE__ */ new Map;empty=/* @__PURE__ */ new Set;cleanupInterval;constructor(){this.cleanupInterval=setInterval(()=>this.purge(),6e4),this.cleanupInterval.unref(),registerDisposable(()=>this.dispose())}dispose(){clearInterval(this.cleanupInterval),this.sessions.clear(),this.empty.clear()}async get(sid){let entry=this.sessions.get(sid);return entry?Date.now()>entry.expires?(this.sessions.delete(sid),this.empty.delete(sid),null):entry.data:null}async set(sid,data,maxAge){for(this.sessions.delete(sid),this.sessions.set(sid,{data,expires:Date.now()+maxAge}),this.empty.delete(sid),Object.keys(data).length===0&&this.empty.add(sid);this.sessions.size>1e4;){let victim=this.empty.values().next().value??this.sessions.keys().next().value;this.sessions.delete(victim),this.empty.delete(victim)}}async destroy(sid){this.sessions.delete(sid),this.empty.delete(sid)}async touch(sid,maxAge){let entry=this.sessions.get(sid);entry&&(entry.expires=Date.now()+maxAge,this.sessions.delete(sid),this.sessions.set(sid,entry))}purge(){let now=Date.now();for(let[sid,entry]of this.sessions)now>entry.expires&&(this.sessions.delete(sid),this.empty.delete(sid))}};function secretList(secret){let list=Array.isArray(secret)?secret:[secret];if(list.length===0||list.some(s=>typeof s!=`string`||s.length===0))throw Error("session(): `secret` must be a non-empty string or list of strings");return list}function sign(value,secret){return`s:${value}.${createHmac(`sha256`,secret).update(value).digest(`base64url`)}`}function unsign(signed,secrets){if(!signed.startsWith(`s:`))return!1;let raw=signed.slice(2),dotIndex=raw.lastIndexOf(`.`);if(dotIndex===-1)return!1;let value=raw.slice(0,dotIndex),provided=Buffer.from(raw.slice(dotIndex+1));for(let[index,secret]of secrets.entries()){let expected=Buffer.from(createHmac(`sha256`,secret).update(value).digest(`base64url`));if(provided.length===expected.length&&timingSafeEqual(provided,expected))return{value,stale:index>0}}return!1}function session(options){if(options.store===`cookie`)return cookieSession(options);let{cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,cookie:cookieOpts={}}=options,secrets=secretList(options.secret),secret=secrets[0],store=options.store??new MemoryStore,cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??isProduction(),sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{},maxAge};return async(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let signedCookie=cookies[cookieName],sid=!1,sessionData=null,isNew=!1,staleSignature=!1;if(signedCookie){let unsigned=unsign(signedCookie,secrets);unsigned&&(sid=unsigned.value,staleSignature=unsigned.stale,sessionData=await store.get(sid))}(!sid||!sessionData)&&(sid=randomUUID(),sessionData={},isNew=!0);let currentSid=sid,currentData={...sessionData},destroyed=!1,sessionObj={get id(){return currentSid},data:currentData,async regenerate(){await store.destroy(currentSid),currentSid=randomUUID(),currentData={},sessionObj.data=currentData,await store.set(currentSid,currentData,maxAge),setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults)},async destroy(){await store.destroy(currentSid),destroyed=!0,currentData={},sessionObj.data=currentData,setCookie(res,cookieName,``,{...cookieDefaults,maxAge:0,expires:/* @__PURE__ */ new Date(0)})},async save(){destroyed||await store.set(currentSid,currentData,maxAge)}};req.session=sessionObj,isNew&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults),res.on(`finish`,async()=>{destroyed||(!isNew||saveUninitialized||Object.keys(currentData).length!==0)&&(await store.set(currentSid,currentData,maxAge),rolling&&!isNew&&store.touch&&await store.touch(currentSid,maxAge))}),!isNew&&(rolling||staleSignature)&&setCookie(res,cookieName,sign(currentSid,secret),cookieDefaults),next()}}const cookieLog=createLogger(`Session`);function sealer(secrets,cookieName){let keys=secrets.map(secret=>Buffer.from(hkdfSync(`sha256`,secret,`kick.session`,`cookie-store-v1`,32))),key=keys[0],aad=Buffer.from(cookieName);return{seal(payload){let iv=randomBytes(12),cipher=createCipheriv(`aes-256-gcm`,key,iv).setAAD(aad),body=Buffer.concat([cipher.update(JSON.stringify(payload),`utf8`),cipher.final()]);return`v1.${Buffer.concat([iv,cipher.getAuthTag(),body]).toString(`base64url`)}`},open(value){if(!value.startsWith(`v1.`))return null;let raw;try{raw=Buffer.from(value.slice(3),`base64url`)}catch{return null}if(raw.length<29)return null;for(let[index,k]of keys.entries())try{let decipher=createDecipheriv(`aes-256-gcm`,k,raw.subarray(0,12)).setAAD(aad).setAuthTag(raw.subarray(12,28)),json=Buffer.concat([decipher.update(raw.subarray(28)),decipher.final()]),payload=JSON.parse(json.toString(`utf8`));return typeof payload?.i!=`string`||typeof payload.e!=`number`||!payload.d||typeof payload.d!=`object`?null:payload.e>Date.now()?{payload,stale:index>0}:null}catch{}return null}}}function cookieSession(options){let{cookieName=`kick.sid`,maxAge=864e5,rolling=!1,saveUninitialized=!0,cookie:cookieOpts={}}=options,{seal,open}=sealer(secretList(options.secret),cookieName),cookieDefaults={httpOnly:cookieOpts.httpOnly??!0,secure:cookieOpts.secure??isProduction(),sameSite:cookieOpts.sameSite??`lax`,path:cookieOpts.path??`/`,...cookieOpts.domain?{domain:cookieOpts.domain}:{}},warnedSize=!1;return(req,res,next)=>{let cookies=req.cookies;if(!cookies){let header=req.headers.cookie;cookies=header?parseCookieHeader(header):{}}let opened=cookies[cookieName]?open(cookies[cookieName]):null,existing=opened?.payload??null,isNew=!existing,id=existing?.i??randomUUID(),destroyed=!1,written=existing&&!opened?.stale?JSON.stringify(existing.d):void 0,write=(force=!1)=>{if(res.headersSent)return;if(destroyed){replaceCookie(res,cookieName,``,{...cookieDefaults,maxAge:0,expires:/* @__PURE__ */ new Date(0)});return}let json=JSON.stringify(sessionObj.data);if(json===written&&!force&&(!rolling||isNew)||written===void 0&&json===`{}`&&!saveUninitialized&&!force)return;let value=seal({i:id,d:sessionObj.data,e:Date.now()+maxAge});value.length+cookieName.length>4e3&&!warnedSize&&(warnedSize=!0,cookieLog.warn(`session cookie is ${value.length} bytes; browsers drop cookies over 4 KB, so this session will not be kept. Store less in it, or use a shared store.`)),replaceCookie(res,cookieName,value,{...cookieDefaults,maxAge}),written=json};for(let method of[`writeHead`,`flushHeaders`,`write`,`end`]){let original=res[method];typeof original==`function`&&(res[method]=function(...args){return write(),original.apply(this,args)})}res.on?.(`finish`,()=>write());let sessionObj={get id(){return id},data:existing?{...existing.d}:{},async regenerate(){id=randomUUID(),sessionObj.data={},written=void 0,write(!0)},async destroy(){destroyed=!0,sessionObj.data={},write()},async save(){write()}};req.session=sessionObj,next()}}export{MemoryStore,session};
12
12
  //# sourceMappingURL=session.mjs.map
@@ -1,3 +1,3 @@
1
1
 
2
- import { L as SpaAdapter, R as SpaAdapterOptions, z as resolveClientDir } from "../../adapter-C5I5e_-i.mjs";
2
+ import { _ as resolveClientDir, g as SpaAdapterOptions, h as SpaAdapter } from "../../application-BuUWvaqp.mjs";
3
3
  export { SpaAdapter, SpaAdapterOptions, resolveClientDir };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.2.0
2
+ * @forinda/kickjs v10.3.1
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{Logger}from"../../core/logger.mjs";import"../../core-CFXpwc7m.mjs";import{t as defineAdapter}from"../../define-adapter-BRJ6lXkV.mjs";import{existsSync,readFileSync,readdirSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";const log=Logger.for(`SpaAdapter`);function nearestPackageRoot(from){let dir=from;for(;;){if(existsSync(join(dir,`package.json`)))return dir;let parent=dirname(dir);if(parent===dir)return null;dir=parent}}function resolveClientDir(clientDir,cwd=process.cwd(),entry=process.argv[1]){if(isAbsolute(clientDir))return resolve(clientDir);let fromCwd=resolve(cwd,clientDir);if(existsSync(fromCwd))return fromCwd;if(entry){let root=nearestPackageRoot(dirname(resolve(entry)));if(root){let fromEntry=resolve(root,clientDir);if(existsSync(fromEntry))return fromEntry}}return fromCwd}function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`),h=url.indexOf(`#`),end=Math.min(q===-1?url.length:q,h===-1?url.length:h);return url.slice(0,end)||`/`}function isUnder(pathname,prefix){if(!prefix||prefix===`/`)return!0;let p=prefix.endsWith(`/`)?prefix.slice(0,-1):prefix;return pathname===p||pathname.startsWith(`${p}/`)}const HTML_TYPES=[`text/html`,`application/xhtml+xml`];function qualityOf(params){let q=params.find(param=>param.startsWith(`q=`));if(!q)return 1;let value=Number.parseFloat(q.slice(2));return Number.isNaN(value)?1:value}function acceptsHtml(accept){let raw=Array.isArray(accept)?accept.join(`,`):accept??``;if(!raw)return!1;let ranges=raw.split(`,`).map(part=>part.split(`;`).map(t=>t.trim().toLowerCase())).filter(([type])=>!!type);return HTML_TYPES.some(htmlType=>{let[group]=htmlType.split(`/`),exact=ranges.find(([type])=>type===htmlType),wildcard=ranges.find(([type])=>type===`${group}/*`),match=exact??wildcard;return match?qualityOf(match.slice(1))>0:!1})}const SpaAdapter=defineAdapter({name:`SpaAdapter`,defaults:{clientDir:`dist/client`,apiPrefix:`/api`,exclude:[],cacheControl:`public, max-age=31536000, immutable`,indexCacheControl:`no-cache`,alwaysFallback:!1},build:config=>{let clientDir=resolveClientDir(config.clientDir??`dist/client`),rawPrefix=config.apiPrefix??`/api`,apiPrefixes=Array.isArray(rawPrefix)?rawPrefix:[rawPrefix],excludePaths=config.exclude??[],cacheControl=config.cacheControl??`public, max-age=31536000, immutable`,indexCacheControl=config.indexCacheControl??`no-cache`,alwaysFallback=config.alwaysFallback??!1,indexHtml=null,assetPaths=/* @__PURE__ */ new Set;function snapshotClientDir(){let paths=/* @__PURE__ */ new Set,walk=(absDir,prefix)=>{for(let entry of readdirSync(absDir,{withFileTypes:!0})){let child=`${prefix}/${entry.name}`;entry.isDirectory()?walk(join(absDir,entry.name),child):entry.isFile()&&paths.add(child)}};try{walk(clientDir,``)}catch{return/* @__PURE__ */ new Set}return paths}let classifyPath=pathname=>{let decoded;try{decoded=decodeURIComponent(pathname)}catch{return null}if(decoded.includes(`\0`))return null;let asIndex=decoded.endsWith(`/`)?`${decoded}index.html`:null;return asIndex&&assetPaths.has(asIndex)?`index`:assetPaths.has(decoded)?decoded.endsWith(`.html`)?`index`:`file`:null},isReserved=pathname=>apiPrefixes.some(p=>isUnder(pathname,p))||excludePaths.some(p=>isUnder(pathname,p));return{beforeMount({http}){if(!existsSync(clientDir)){log.warn(`SPA client directory not found: ${clientDir}`),log.warn(`Build your frontend first, or set clientDir to the correct path (relative paths resolve from ${process.cwd()}).`);return}let indexPath=join(clientDir,`index.html`);existsSync(indexPath)?(indexHtml=readFileSync(indexPath,`utf-8`),assetPaths=snapshotClientDir(),cacheControl!==!1&&http.use(((req,res,next)=>{let pathname=pathnameOf(req.url),kind=isReserved(pathname)?null:classifyPath(pathname);kind&&res.setHeader(`Cache-Control`,kind===`index`?indexCacheControl:cacheControl),next()})),http.serveStatic(`/`,clientDir),log.debug(`Serving SPA from ${clientDir}`)):log.warn(`index.html not found in ${clientDir}`)},beforeStart({http}){indexHtml&&http.use(((req,res,next)=>{let method=(req.method??`GET`).toUpperCase();if(method!==`GET`&&method!==`HEAD`)return next();let pathname=pathnameOf(req.url);if(isReserved(pathname))return next();let accept=req.headers?.accept;if(!alwaysFallback&&!acceptsHtml(accept))return next();let body=indexHtml;res.setHeader(`Content-Type`,`text/html; charset=utf-8`),res.setHeader(`Cache-Control`,indexCacheControl),res.setHeader(`Content-Length`,String(Buffer.byteLength(body))),res.statusCode=200,res.end(method===`HEAD`?void 0:body)}))}}}});export{SpaAdapter,resolveClientDir};
11
+ import{Logger}from"../../core/logger.mjs";import"../../core-YE-k8IrU.mjs";import{t as defineAdapter}from"../../define-adapter-C6H-I1og.mjs";import{existsSync,readFileSync,readdirSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";const log=Logger.for(`SpaAdapter`);function nearestPackageRoot(from){let dir=from;for(;;){if(existsSync(join(dir,`package.json`)))return dir;let parent=dirname(dir);if(parent===dir)return null;dir=parent}}function resolveClientDir(clientDir,cwd=process.cwd(),entry=process.argv[1]){if(isAbsolute(clientDir))return resolve(clientDir);let fromCwd=resolve(cwd,clientDir);if(existsSync(fromCwd))return fromCwd;if(entry){let root=nearestPackageRoot(dirname(resolve(entry)));if(root){let fromEntry=resolve(root,clientDir);if(existsSync(fromEntry))return fromEntry}}return fromCwd}function pathnameOf(url){if(!url)return`/`;let q=url.indexOf(`?`),h=url.indexOf(`#`),end=Math.min(q===-1?url.length:q,h===-1?url.length:h);return url.slice(0,end)||`/`}function isUnder(pathname,prefix){if(!prefix||prefix===`/`)return!0;let p=prefix.endsWith(`/`)?prefix.slice(0,-1):prefix;return pathname===p||pathname.startsWith(`${p}/`)}const HTML_TYPES=[`text/html`,`application/xhtml+xml`];function qualityOf(params){let q=params.find(param=>param.startsWith(`q=`));if(!q)return 1;let value=Number.parseFloat(q.slice(2));return Number.isNaN(value)?1:value}function acceptsHtml(accept){let raw=Array.isArray(accept)?accept.join(`,`):accept??``;if(!raw)return!1;let ranges=raw.split(`,`).map(part=>part.split(`;`).map(t=>t.trim().toLowerCase())).filter(([type])=>!!type);return HTML_TYPES.some(htmlType=>{let[group]=htmlType.split(`/`),exact=ranges.find(([type])=>type===htmlType),wildcard=ranges.find(([type])=>type===`${group}/*`),match=exact??wildcard;return match?qualityOf(match.slice(1))>0:!1})}const SpaAdapter=defineAdapter({name:`SpaAdapter`,defaults:{clientDir:`dist/client`,apiPrefix:`/api`,exclude:[],cacheControl:`public, max-age=31536000, immutable`,indexCacheControl:`no-cache`,alwaysFallback:!1},build:config=>{let clientDir=resolveClientDir(config.clientDir??`dist/client`),rawPrefix=config.apiPrefix??`/api`,apiPrefixes=Array.isArray(rawPrefix)?rawPrefix:[rawPrefix],excludePaths=config.exclude??[],cacheControl=config.cacheControl??`public, max-age=31536000, immutable`,indexCacheControl=config.indexCacheControl??`no-cache`,alwaysFallback=config.alwaysFallback??!1,indexHtml=null,assetPaths=/* @__PURE__ */ new Set;function snapshotClientDir(){let paths=/* @__PURE__ */ new Set,walk=(absDir,prefix)=>{for(let entry of readdirSync(absDir,{withFileTypes:!0})){let child=`${prefix}/${entry.name}`;entry.isDirectory()?walk(join(absDir,entry.name),child):entry.isFile()&&paths.add(child)}};try{walk(clientDir,``)}catch{return/* @__PURE__ */ new Set}return paths}let classifyPath=pathname=>{let decoded;try{decoded=decodeURIComponent(pathname)}catch{return null}if(decoded.includes(`\0`))return null;let asIndex=decoded.endsWith(`/`)?`${decoded}index.html`:null;return asIndex&&assetPaths.has(asIndex)?`index`:assetPaths.has(decoded)?decoded.endsWith(`.html`)?`index`:`file`:null},isReserved=pathname=>apiPrefixes.some(p=>isUnder(pathname,p))||excludePaths.some(p=>isUnder(pathname,p));return{beforeMount({http}){if(!existsSync(clientDir)){log.warn(`SPA client directory not found: ${clientDir}`),log.warn(`Build your frontend first, or set clientDir to the correct path (relative paths resolve from ${process.cwd()}).`);return}let indexPath=join(clientDir,`index.html`);existsSync(indexPath)?(indexHtml=readFileSync(indexPath,`utf-8`),assetPaths=snapshotClientDir(),cacheControl!==!1&&http.use(((req,res,next)=>{let pathname=pathnameOf(req.url),kind=isReserved(pathname)?null:classifyPath(pathname);kind&&res.setHeader(`Cache-Control`,kind===`index`?indexCacheControl:cacheControl),next()})),http.serveStatic(`/`,clientDir),log.debug(`Serving SPA from ${clientDir}`)):log.warn(`index.html not found in ${clientDir}`)},beforeStart({http}){indexHtml&&http.use(((req,res,next)=>{let method=(req.method??`GET`).toUpperCase();if(method!==`GET`&&method!==`HEAD`)return next();let pathname=pathnameOf(req.url);if(isReserved(pathname))return next();let accept=req.headers?.accept;if(!alwaysFallback&&!acceptsHtml(accept))return next();let body=indexHtml;res.setHeader(`Content-Type`,`text/html; charset=utf-8`),res.setHeader(`Cache-Control`,indexCacheControl),res.setHeader(`Content-Length`,String(Buffer.byteLength(body))),res.statusCode=200,res.end(method===`HEAD`?void 0:body)}))}}}});export{SpaAdapter,resolveClientDir};
12
12
  //# sourceMappingURL=spa.mjs.map
@@ -1,3 +1,3 @@
1
1
 
2
- import { $ as applyUploadConfig, J as buildUploadMiddleware, Q as UploadedFileLike, X as upload, Y as cleanupFiles, Z as RawUploadPart, et as buildFileTypeFilter, q as UploadOptions, tt as resolveMimeTypes } from "../../adapter-C5I5e_-i.mjs";
2
+ import { a as RawUploadPart, c as buildFileTypeFilter, i as upload, l as resolveMimeTypes, n as buildUploadMiddleware, o as UploadedFileLike, r as cleanupFiles, s as applyUploadConfig, t as UploadOptions } from "../../upload-CyBSlnH_.mjs";
3
3
  export { type RawUploadPart, UploadOptions, type UploadedFileLike, applyUploadConfig, buildFileTypeFilter, buildUploadMiddleware, cleanupFiles, resolveMimeTypes, upload };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.2.0
2
+ * @forinda/kickjs v10.3.1
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,6 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{HttpException,HttpStatus}from"../../core/errors.mjs";import{n as buildFileTypeFilter,r as resolveMimeTypes,t as applyUploadConfig}from"../../upload-config-DLgt4l7F.mjs";import{createRequire}from"node:module";import{unlink}from"node:fs/promises";const requireFromHere=createRequire(import.meta.url);let _multer;function loadMulter(){if(_multer)return _multer;try{return _multer=requireFromHere(`multer`),_multer}catch{throw Error(`@forinda/kickjs: file uploads require the 'multer' package, which is not installed.
12
- Install it as a peer dependency: pnpm add multer (or npm i multer / yarn add multer).`)}}function translateMulterErrors(mw,options){let maxSize=options.maxSize??5242880;return(req,res,next)=>{mw(req,res,err=>{if(err&&err.code===`LIMIT_FILE_SIZE`){let name=err.field??`file`;return next(new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${name} exceeds the ${maxSize}-byte limit`))}next(err)})}}function createMulter(options){let limits={fileSize:options.maxSize??5242880},fileFilter;if(options.allowedTypes){let typeAllowed=buildFileTypeFilter(options.allowedTypes,options.customMimeMap);fileFilter=(_req,file,cb)=>{typeAllowed(file.mimetype,file.originalname)?cb(null,!0):cb(new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${file.mimetype} is not allowed`))}}let multerOptions={limits,...fileFilter?{fileFilter}:{},...options.storage?{storage:options.storage}:{},...options.dest?{dest:options.dest}:{}};return loadMulter()(multerOptions)}function bothConventions(handler){return((first,second,third)=>third===void 0&&typeof second==`function`&&typeof first==`object`&&first&&`req`in first&&`res`in first?new Promise((resolve,reject)=>{handler(first.req,first.res,err=>{if(err)return reject(err);resolve(),second()})}):handler(first,second,third))}function single(fieldName,options={}){return bothConventions(translateMulterErrors(createMulter(options).single(fieldName),options))}function array(fieldName,maxCount=10,options={}){return bothConventions(translateMulterErrors(createMulter(options).array(fieldName,maxCount),options))}function none(options={}){return bothConventions(translateMulterErrors(createMulter(options).none(),options))}function cleanupFiles(){return(req,res,next)=>{res.on(`finish`,async()=>{let files=[];if(req.file?.path&&files.push(req.file),Array.isArray(req.files))for(let f of req.files)f?.path&&files.push(f);for(let file of files)try{await unlink(file.path)}catch{}}),next()}}function buildUploadMiddleware(config){let options={};config.maxSize&&(options.maxSize=config.maxSize),config.allowedTypes&&(options.allowedTypes=config.allowedTypes),config.customMimeMap&&(options.customMimeMap=config.customMimeMap);let fieldName=config.fieldName??`file`;switch(config.mode){case`single`:return single(fieldName,options);case`array`:return array(fieldName,config.maxCount??10,options);case`none`:return none(options)}}const upload={single,array,none};export{applyUploadConfig,buildFileTypeFilter,buildUploadMiddleware,cleanupFiles,resolveMimeTypes,upload};
11
+ import{HttpException,HttpStatus}from"../../core/errors.mjs";import{n as buildFileTypeFilter,r as resolveMimeTypes,t as applyUploadConfig}from"../../upload-config-D22qKth8.mjs";import{unlink}from"node:fs/promises";let _multer;function loadMulter(){return _multer??=import(`multer`).then(mod=>mod.default??mod,()=>{throw Error(`@forinda/kickjs: file uploads require the 'multer' package, which is not installed. Add it to your dependencies.`)})}function translateMulterErrors(mw,options){let maxSize=options.maxSize??5242880;return(req,res,next)=>{mw(req,res,err=>{if(err&&err.code===`LIMIT_FILE_SIZE`){let name=err.field??`file`;return next(new HttpException(HttpStatus.PAYLOAD_TOO_LARGE,`File ${name} exceeds the ${maxSize}-byte limit`))}next(err)})}}function createMulter(options){let limits={fileSize:options.maxSize??5242880},fileFilter;if(options.allowedTypes){let typeAllowed=buildFileTypeFilter(options.allowedTypes,options.customMimeMap);fileFilter=(_req,file,cb)=>{typeAllowed(file.mimetype,file.originalname)?cb(null,!0):cb(new HttpException(HttpStatus.UNSUPPORTED_MEDIA_TYPE,`File type ${file.mimetype} is not allowed`))}}let multerOptions={limits,...fileFilter?{fileFilter}:{},...options.storage?{storage:options.storage}:{},...options.dest?{dest:options.dest}:{}},built,lazy=pick=>{let handler;return(req,res,next)=>{handler??=(built??=loadMulter().then(multer=>multer(multerOptions))).then(pick),handler.then(run=>run(req,res,next),err=>{handler=built=_multer=void 0,next(err)})}};return{single:field=>lazy(m=>m.single(field)),array:(field,maxCount)=>lazy(m=>m.array(field,maxCount)),none:()=>lazy(m=>m.none())}}function bothConventions(handler){return((first,second,third)=>third===void 0&&typeof second==`function`&&typeof first==`object`&&first&&`req`in first&&`res`in first?new Promise((resolve,reject)=>{handler(first.req,first.res,err=>{if(err)return reject(err);resolve(),second()})}):handler(first,second,third))}function single(fieldName,options={}){return bothConventions(translateMulterErrors(createMulter(options).single(fieldName),options))}function array(fieldName,maxCount=10,options={}){return bothConventions(translateMulterErrors(createMulter(options).array(fieldName,maxCount),options))}function none(options={}){return bothConventions(translateMulterErrors(createMulter(options).none(),options))}function cleanupFiles(){return(req,res,next)=>{res.on(`finish`,async()=>{let files=[];if(req.file?.path&&files.push(req.file),Array.isArray(req.files))for(let f of req.files)f?.path&&files.push(f);for(let file of files)try{await unlink(file.path)}catch{}}),next()}}function buildUploadMiddleware(config){let options={};config.maxSize&&(options.maxSize=config.maxSize),config.allowedTypes&&(options.allowedTypes=config.allowedTypes),config.customMimeMap&&(options.customMimeMap=config.customMimeMap);let fieldName=config.fieldName??`file`;switch(config.mode){case`single`:return single(fieldName,options);case`array`:return array(fieldName,config.maxCount??10,options);case`none`:return none(options)}}const upload={single,array,none};export{applyUploadConfig,buildFileTypeFilter,buildUploadMiddleware,cleanupFiles,resolveMimeTypes,upload};
13
12
  //# sourceMappingURL=upload.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"upload.mjs","names":[],"sources":["../../../src/http/middleware/upload.ts"],"sourcesContent":["import { HttpException, HttpStatus } from '../../core/errors'\nimport { unlink } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport type { Request, Response, NextFunction, RequestHandler } from 'express'\nimport type { Options as MulterOptions } from 'multer'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core'\n\n// `multer` is an optional peer dependency. We load it lazily via\n// `createRequire` so importing this module never touches `multer` —\n// only constructing an upload middleware does. Adopters who never\n// call `upload.single/array/none()` or use `@FileUpload` don't need\n// `multer` installed at all.\n//\n// multer uses CJS `export = multer`, so the module is itself the\n// callable factory — no `.default` indirection on either the type\n// or the runtime side.\nconst requireFromHere = createRequire(import.meta.url)\ntype MulterFactory = typeof import('multer')\nlet _multer: MulterFactory | undefined\n\nfunction loadMulter(): MulterFactory {\n if (_multer) return _multer\n try {\n _multer = requireFromHere('multer') as MulterFactory\n return _multer\n } catch {\n throw new Error(\n \"@forinda/kickjs: file uploads require the 'multer' package, which is not installed.\\n\" +\n 'Install it as a peer dependency: pnpm add multer (or npm i multer / yarn add multer).',\n )\n }\n}\n\n// Pure upload core (MIME map, type filter, applyUploadConfig) moved to\n// `./upload-config` so the edge-safe web entry can use it without this\n// module's node-only surface. Re-exported here for compatibility.\nexport {\n buildFileTypeFilter,\n resolveMimeTypes,\n applyUploadConfig,\n type UploadedFileLike,\n type RawUploadPart,\n} from './upload-config'\nimport { buildFileTypeFilter } from './upload-config'\n\n/**\n * Upload options for the middleware.\n * Extends BaseUploadOptions from core (shared with @FileUpload decorator)\n * and adds Multer-specific storage options.\n */\nexport interface UploadOptions extends BaseUploadOptions {\n /** Multer storage config (default: memory storage) */\n storage?: MulterOptions['storage']\n /** Multer dest for disk storage shorthand */\n dest?: string\n}\n\n/**\n * Turn multer's own errors into the exceptions the other runtimes raise.\n *\n * multer reports a file over the limit as `MulterError: File too large`, a\n * plain error the handler maps to 500 — so an oversized upload was reported as\n * a server fault on Express while Fastify and h3 answered 413. The message is\n * matched to `applyUploadConfig` so the response does not depend on the engine.\n */\nfunction translateMulterErrors(mw: RequestHandler, options: UploadOptions): RequestHandler {\n const maxSize = options.maxSize ?? 5 * 1024 * 1024\n return (req, res, next) => {\n mw(req, res, (err?: unknown) => {\n if (err && (err as { code?: string }).code === 'LIMIT_FILE_SIZE') {\n const name = (err as { field?: string }).field ?? 'file'\n return next(\n new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${name} exceeds the ${maxSize}-byte limit`,\n ),\n )\n }\n next(err as never)\n })\n }\n}\n\nfunction createMulter(options: UploadOptions) {\n const limits: MulterOptions['limits'] = {\n fileSize: options.maxSize ?? 5 * 1024 * 1024,\n }\n\n let fileFilter: MulterOptions['fileFilter'] | undefined\n if (options.allowedTypes) {\n const typeAllowed = buildFileTypeFilter(options.allowedTypes, options.customMimeMap)\n fileFilter = (_req, file, cb) => {\n if (typeAllowed(file.mimetype, file.originalname)) {\n cb(null, true)\n } else {\n // Same exception the Fastify and h3 path raises from\n // `applyUploadConfig`. A plain Error here reached the handler as a 500,\n // so Express blamed itself for the client's file — and leaked a multer\n // stack doing it.\n cb(\n new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${file.mimetype} is not allowed`,\n ),\n )\n }\n }\n }\n\n const multerOptions: MulterOptions = {\n limits,\n ...(fileFilter ? { fileFilter } : {}),\n ...(options.storage ? { storage: options.storage } : {}),\n ...(options.dest ? { dest: options.dest } : {}),\n }\n\n return loadMulter()(multerOptions)\n}\n\n/**\n * Single file upload middleware. Attaches the file to `req.file`.\n *\n * @example\n * ```ts\n * @Post('/avatar')\n * @Middleware(upload.single('avatar', { maxSize: 2 * 1024 * 1024, allowedTypes: ['jpg', 'png'] }))\n * async uploadAvatar(ctx: RequestContext) {\n * ctx.json({ filename: ctx.file.originalname })\n * }\n * ```\n */\n/**\n * The handler, callable both ways it gets used: as Express middleware\n * `(req, res, next)` — `middlewares: [upload.single(...)]`, and what\n * `@FileUpload` builds — and as a route middleware `(ctx, next)`, which is\n * how `@Middleware(upload.single(...))` calls it. Called the second way,\n * Multer got the context as its request and failed on every upload.\n */\nfunction bothConventions(handler: RequestHandler): RequestHandler {\n return ((first: any, second: any, third?: any) => {\n const isRouteMiddleware =\n third === undefined &&\n typeof second === 'function' &&\n first !== null &&\n typeof first === 'object' &&\n 'req' in first &&\n 'res' in first\n if (!isRouteMiddleware) return handler(first, second, third)\n return new Promise<void>((resolve, reject) => {\n handler(first.req, first.res, (err?: unknown) => {\n if (err) return reject(err)\n resolve()\n second()\n })\n })\n }) as RequestHandler\n}\n\nfunction single(fieldName: string, options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n return bothConventions(translateMulterErrors(m.single(fieldName) as RequestHandler, options))\n}\n\n/**\n * Multiple file upload middleware. Attaches files to `req.files`.\n */\nfunction array(fieldName: string, maxCount = 10, options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n return bothConventions(\n translateMulterErrors(m.array(fieldName, maxCount) as RequestHandler, options),\n )\n}\n\n/**\n * No file upload — just parse multipart form data without file fields.\n */\nfunction none(options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n return bothConventions(translateMulterErrors(m.none() as RequestHandler, options))\n}\n\n/**\n * Removes temporary files from disk after the response is sent.\n * Attach this as Express middleware after the upload middleware.\n * Works with both `req.file` (single) and `req.files` (array).\n *\n * @example\n * ```ts\n * @Post('/process')\n * @Middleware(upload.single('document', { dest: '/tmp/uploads' }), cleanupFiles())\n * async processDocument(ctx: RequestContext) {\n * ctx.json({ ok: true })\n * }\n * ```\n */\nexport function cleanupFiles() {\n return (req: Request, res: Response, next: NextFunction) => {\n res.on('finish', async () => {\n const files: any[] = []\n\n if ((req as any).file?.path) {\n files.push((req as any).file)\n }\n if (Array.isArray((req as any).files)) {\n for (const f of (req as any).files) {\n if (f?.path) files.push(f)\n }\n }\n\n for (const file of files) {\n try {\n await unlink(file.path)\n } catch {\n // File may already be moved/deleted by the handler — ignore\n }\n }\n })\n\n next()\n }\n}\n\n/**\n * Build upload middleware from a @FileUpload decorator config.\n * Used internally by the router builder when it detects FILE_UPLOAD metadata.\n * Accepts the same FileUploadConfig interface used by the @FileUpload decorator.\n */\nexport function buildUploadMiddleware(config: FileUploadConfig): RequestHandler {\n const options: UploadOptions = {}\n if (config.maxSize) options.maxSize = config.maxSize\n if (config.allowedTypes) options.allowedTypes = config.allowedTypes\n if (config.customMimeMap) options.customMimeMap = config.customMimeMap\n\n const fieldName = config.fieldName ?? 'file'\n\n switch (config.mode) {\n case 'single':\n return single(fieldName, options)\n case 'array':\n return array(fieldName, config.maxCount ?? 10, options)\n case 'none':\n return none(options)\n }\n}\n\n/** Upload middleware factory with `.single()`, `.array()`, `.none()` methods */\nexport const upload = { single, array, none }\n"],"mappings":";;;;;;;;;;4PAgBA,MAAM,gBAAkB,cAAc,YAAY,GAAG,EAErD,IAAI,QAEJ,SAAS,YAA4B,CACnC,GAAI,QAAS,OAAO,QACpB,GAAI,CAEF,MADA,SAAU,gBAAgB,QAAQ,EAC3B,OACT,MAAQ,CACN,MAAU,MACR;sFAEF,CACF,CACF,CAkCA,SAAS,sBAAsB,GAAoB,QAAwC,CACzF,IAAM,QAAU,QAAQ,SAAW,QACnC,OAAQ,IAAK,IAAK,OAAS,CACzB,GAAG,IAAK,IAAM,KAAkB,CAC9B,GAAI,KAAQ,IAA0B,OAAS,kBAAmB,CAChE,IAAM,KAAQ,IAA2B,OAAS,OAClD,OAAO,KACL,IAAI,cACF,WAAW,kBACX,QAAQ,KAAK,eAAe,QAAQ,YACtC,CACF,CACF,CACA,KAAK,GAAY,CACnB,CAAC,CACH,CACF,CAEA,SAAS,aAAa,QAAwB,CAC5C,IAAM,OAAkC,CACtC,SAAU,QAAQ,SAAW,OAC/B,EAEI,WACJ,GAAI,QAAQ,aAAc,CACxB,IAAM,YAAc,oBAAoB,QAAQ,aAAc,QAAQ,aAAa,EACn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AAU,SAAY,CAC3B,IAAM,MAAe,CAAC,EAKtB,GAHK,IAAY,MAAM,MACrB,MAAM,KAAM,IAAY,IAAI,EAE1B,MAAM,QAAS,IAAY,KAAK,EAC7B,IAAA,IAAM,KAAM,IAAY,MACvB,GAAG,MAAM,MAAM,KAAK,CAAC,EAI7B,IAAK,IAAM,QAAQ,MACjB,GAAI,CACF,MAAM,OAAO,KAAK,IAAI,CACxB,MAAQ,CAER,CAEJ,CAAC,EAED,KAAK,CACP,CACF,CAOA,SAAgB,sBAAsB,OAA0C,CAC9E,IAAM,QAAyB,CAAC,EAC5B,OAAO,UAAS,QAAQ,QAAU,OAAO,SACzC,OAAO,eAAc,QAAQ,aAAe,OAAO,cACnD,OAAO,gBAAe,QAAQ,cAAgB,OAAO,eAEzD,IAAM,UAAY,OAAO,WAAa,OAEtC,OAAQ,OAAO,KAAf,CACE,IAAK,SACH,OAAO,OAAO,UAAW,OAAO,EAClC,IAAK,QACH,OAAO,MAAM,UAAW,OAAO,UAAY,GAAI,OAAO,EACxD,IAAK,OACH,OAAO,KAAK,OAAO,CACvB,CACF,CAGA,MAAa,OAAS,CAAE,OAAQ,MAAO,IAAK"}
1
+ {"version":3,"file":"upload.mjs","names":[],"sources":["../../../src/http/middleware/upload.ts"],"sourcesContent":["import { HttpException, HttpStatus } from '../../core/errors'\nimport { unlink } from 'node:fs/promises'\nimport type { Request, Response, NextFunction, RequestHandler } from 'express'\nimport type { Options as MulterOptions } from 'multer'\nimport type { BaseUploadOptions, FileUploadConfig } from '../../core'\n\n// `multer` is an optional peer dependency, imported when the first upload\n// arrives — adopters who never take uploads don't need it installed. An\n// `import()`, not `createRequire`: a bundler follows it, so a Netlify or\n// Vercel function built by `kick build:*` carries multer with it.\ntype MulterFactory = typeof import('multer')\ntype Multer = ReturnType<MulterFactory>\nlet _multer: Promise<MulterFactory> | undefined\n\nfunction loadMulter(): Promise<MulterFactory> {\n return (_multer ??= import('multer').then(\n // multer is CJS `export = multer`: the factory is the module's default.\n (mod) => ((mod as { default?: unknown }).default ?? mod) as MulterFactory,\n () => {\n throw new Error(\n \"@forinda/kickjs: file uploads require the 'multer' package, which is not installed. \" +\n 'Add it to your dependencies.',\n )\n },\n ))\n}\n\n// Pure upload core (MIME map, type filter, applyUploadConfig) moved to\n// `./upload-config` so the edge-safe web entry can use it without this\n// module's node-only surface. Re-exported here for compatibility.\nexport {\n buildFileTypeFilter,\n resolveMimeTypes,\n applyUploadConfig,\n type UploadedFileLike,\n type RawUploadPart,\n} from './upload-config'\nimport { buildFileTypeFilter } from './upload-config'\n\n/**\n * Upload options for the middleware.\n * Extends BaseUploadOptions from core (shared with @FileUpload decorator)\n * and adds Multer-specific storage options.\n */\nexport interface UploadOptions extends BaseUploadOptions {\n /** Multer storage config (default: memory storage) */\n storage?: MulterOptions['storage']\n /** Multer dest for disk storage shorthand */\n dest?: string\n}\n\n/**\n * Turn multer's own errors into the exceptions the other runtimes raise.\n *\n * multer reports a file over the limit as `MulterError: File too large`, a\n * plain error the handler maps to 500 — so an oversized upload was reported as\n * a server fault on Express while Fastify and h3 answered 413. The message is\n * matched to `applyUploadConfig` so the response does not depend on the engine.\n */\nfunction translateMulterErrors(mw: RequestHandler, options: UploadOptions): RequestHandler {\n const maxSize = options.maxSize ?? 5 * 1024 * 1024\n return (req, res, next) => {\n mw(req, res, (err?: unknown) => {\n if (err && (err as { code?: string }).code === 'LIMIT_FILE_SIZE') {\n const name = (err as { field?: string }).field ?? 'file'\n return next(\n new HttpException(\n HttpStatus.PAYLOAD_TOO_LARGE,\n `File ${name} exceeds the ${maxSize}-byte limit`,\n ),\n )\n }\n next(err as never)\n })\n }\n}\n\nfunction createMulter(options: UploadOptions) {\n const limits: MulterOptions['limits'] = {\n fileSize: options.maxSize ?? 5 * 1024 * 1024,\n }\n\n let fileFilter: MulterOptions['fileFilter'] | undefined\n if (options.allowedTypes) {\n const typeAllowed = buildFileTypeFilter(options.allowedTypes, options.customMimeMap)\n fileFilter = (_req, file, cb) => {\n if (typeAllowed(file.mimetype, file.originalname)) {\n cb(null, true)\n } else {\n // Same exception the Fastify and h3 path raises from\n // `applyUploadConfig`. A plain Error here reached the handler as a 500,\n // so Express blamed itself for the client's file — and leaked a multer\n // stack doing it.\n cb(\n new HttpException(\n HttpStatus.UNSUPPORTED_MEDIA_TYPE,\n `File type ${file.mimetype} is not allowed`,\n ),\n )\n }\n }\n }\n\n const multerOptions: MulterOptions = {\n limits,\n ...(fileFilter ? { fileFilter } : {}),\n ...(options.storage ? { storage: options.storage } : {}),\n ...(options.dest ? { dest: options.dest } : {}),\n }\n\n // Built on the first request that needs it, then reused.\n let built: Promise<Multer> | undefined\n const lazy = (pick: (multer: Multer) => RequestHandler): RequestHandler => {\n let handler: Promise<RequestHandler> | undefined\n return (req, res, next) => {\n handler ??= (built ??= loadMulter().then((multer) => multer(multerOptions))).then(pick)\n handler.then(\n (run) => run(req, res, next),\n (err) => {\n // Not cached: multer installed while `kick dev` runs works on the next upload.\n handler = built = _multer = undefined\n next(err)\n },\n )\n }\n }\n return {\n single: (field: string) => lazy((m) => m.single(field) as RequestHandler),\n array: (field: string, maxCount: number) =>\n lazy((m) => m.array(field, maxCount) as RequestHandler),\n none: () => lazy((m) => m.none() as RequestHandler),\n }\n}\n\n/**\n * Single file upload middleware. Attaches the file to `req.file`.\n *\n * @example\n * ```ts\n * @Post('/avatar')\n * @Middleware(upload.single('avatar', { maxSize: 2 * 1024 * 1024, allowedTypes: ['jpg', 'png'] }))\n * async uploadAvatar(ctx: RequestContext) {\n * ctx.json({ filename: ctx.file.originalname })\n * }\n * ```\n */\n/**\n * The handler, callable both ways it gets used: as Express middleware\n * `(req, res, next)` — `middlewares: [upload.single(...)]`, and what\n * `@FileUpload` builds — and as a route middleware `(ctx, next)`, which is\n * how `@Middleware(upload.single(...))` calls it. Called the second way,\n * Multer got the context as its request and failed on every upload.\n */\nfunction bothConventions(handler: RequestHandler): RequestHandler {\n return ((first: any, second: any, third?: any) => {\n const isRouteMiddleware =\n third === undefined &&\n typeof second === 'function' &&\n first !== null &&\n typeof first === 'object' &&\n 'req' in first &&\n 'res' in first\n if (!isRouteMiddleware) return handler(first, second, third)\n return new Promise<void>((resolve, reject) => {\n handler(first.req, first.res, (err?: unknown) => {\n if (err) return reject(err)\n resolve()\n second()\n })\n })\n }) as RequestHandler\n}\n\nfunction single(fieldName: string, options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n return bothConventions(translateMulterErrors(m.single(fieldName), options))\n}\n\n/**\n * Multiple file upload middleware. Attaches files to `req.files`.\n */\nfunction array(fieldName: string, maxCount = 10, options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n return bothConventions(translateMulterErrors(m.array(fieldName, maxCount), options))\n}\n\n/**\n * No file upload — just parse multipart form data without file fields.\n */\nfunction none(options: UploadOptions = {}): RequestHandler {\n const m = createMulter(options)\n return bothConventions(translateMulterErrors(m.none(), options))\n}\n\n/**\n * Removes temporary files from disk after the response is sent.\n * Attach this as Express middleware after the upload middleware.\n * Works with both `req.file` (single) and `req.files` (array).\n *\n * @example\n * ```ts\n * @Post('/process')\n * @Middleware(upload.single('document', { dest: '/tmp/uploads' }), cleanupFiles())\n * async processDocument(ctx: RequestContext) {\n * ctx.json({ ok: true })\n * }\n * ```\n */\nexport function cleanupFiles() {\n return (req: Request, res: Response, next: NextFunction) => {\n res.on('finish', async () => {\n const files: any[] = []\n\n if ((req as any).file?.path) {\n files.push((req as any).file)\n }\n if (Array.isArray((req as any).files)) {\n for (const f of (req as any).files) {\n if (f?.path) files.push(f)\n }\n }\n\n for (const file of files) {\n try {\n await unlink(file.path)\n } catch {\n // File may already be moved/deleted by the handler — ignore\n }\n }\n })\n\n next()\n }\n}\n\n/**\n * Build upload middleware from a @FileUpload decorator config.\n * Used internally by the router builder when it detects FILE_UPLOAD metadata.\n * Accepts the same FileUploadConfig interface used by the @FileUpload decorator.\n */\nexport function buildUploadMiddleware(config: FileUploadConfig): RequestHandler {\n const options: UploadOptions = {}\n if (config.maxSize) options.maxSize = config.maxSize\n if (config.allowedTypes) options.allowedTypes = config.allowedTypes\n if (config.customMimeMap) options.customMimeMap = config.customMimeMap\n\n const fieldName = config.fieldName ?? 'file'\n\n switch (config.mode) {\n case 'single':\n return single(fieldName, options)\n case 'array':\n return array(fieldName, config.maxCount ?? 10, options)\n case 'none':\n return none(options)\n }\n}\n\n/** Upload middleware factory with `.single()`, `.array()`, `.none()` methods */\nexport const upload = { single, array, none }\n"],"mappings":";;;;;;;;;;qNAYA,IAAI,QAEJ,SAAS,YAAqC,CAC5C,MAAQ,WAAY,OAAO,SAAS,CAAC,KAElC,KAAU,IAA8B,SAAW,QAC9C,CACJ,MAAU,MACR,kHAEF,CACF,CACF,CACF,CAkCA,SAAS,sBAAsB,GAAoB,QAAwC,CACzF,IAAM,QAAU,QAAQ,SAAW,QACnC,OAAQ,IAAK,IAAK,OAAS,CACzB,GAAG,IAAK,IAAM,KAAkB,CAC9B,GAAI,KAAQ,IAA0B,OAAS,kBAAmB,CAChE,IAAM,KAAQ,IAA2B,OAAS,OAClD,OAAO,KACL,IAAI,cACF,WAAW,kBACX,QAAQ,KAAK,eAAe,QAAQ,YACtC,CACF,CACF,CACA,KAAK,GAAY,CACnB,CAAC,CACH,CACF,CAEA,SAAS,aAAa,QAAwB,CAC5C,IAAM,OAAkC,CACtC,SAAU,QAAQ,SAAW,OAC/B,EAEI,WACJ,GAAI,QAAQ,aAAc,CACxB,IAAM,YAAc,oBAAoB,QAAQ,aAAc,QAAQ,aAAa,EACnF,YAAc,KAAM,KAAM,KAAO,CAC3B,YAAY,KAAK,SAAU,KAAK,YAAY,EAC9C,GAAG,KAAM,EAAI,EAMb,GACE,IAAI,cACF,WAAW,uBACX,aAAa,KAAK,SAAS,gBAC7B,CACF,CAEJ,CACF,CAEA,IAAM,cAA+B,CACnC,OACA,GAAI,WAAa,CAAE,UAAW,EAAI,CAAC,EACnC,GAAI,QAAQ,QAAU,CAAE,QAAS,QAAQ,OAAQ,EAAI,CAAC,E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AgB,sBADb,aAAa,OACsB,CAAC,CAAC,KAAK,EAAG,OAAO,CAAC,CACjE,CAgBA,SAAgB,cAAe,CAC7B,OAAQ,IAAc,IAAe,OAAuB,CAC1D,IAAI,GAAG,SAAU,SAAY,CAC3B,IAAM,MAAe,CAAC,EAKtB,GAHK,IAAY,MAAM,MACrB,MAAM,KAAM,IAAY,IAAI,EAE1B,MAAM,QAAS,IAAY,KAAK,EAC7B,IAAA,IAAM,KAAM,IAAY,MACvB,GAAG,MAAM,MAAM,KAAK,CAAC,EAI7B,IAAK,IAAM,QAAQ,MACjB,GAAI,CACF,MAAM,OAAO,KAAK,IAAI,CACxB,MAAQ,CAER,CAEJ,CAAC,EAED,KAAK,CACP,CACF,CAOA,SAAgB,sBAAsB,OAA0C,CAC9E,IAAM,QAAyB,CAAC,EAC5B,OAAO,UAAS,QAAQ,QAAU,OAAO,SACzC,OAAO,eAAc,QAAQ,aAAe,OAAO,cACnD,OAAO,gBAAe,QAAQ,cAAgB,OAAO,eAEzD,IAAM,UAAY,OAAO,WAAa,OAEtC,OAAQ,OAAO,KAAf,CACE,IAAK,SACH,OAAO,OAAO,UAAW,OAAO,EAClC,IAAK,QACH,OAAO,MAAM,UAAW,OAAO,UAAY,GAAI,OAAO,EACxD,IAAK,OACH,OAAO,KAAK,OAAO,CACvB,CACF,CAGA,MAAa,OAAS,CAAE,OAAQ,MAAO,IAAK"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.2.0
2
+ * @forinda/kickjs v10.3.1
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,3 +1,3 @@
1
1
 
2
- import { B as ViewAdapter, V as ViewAdapterOptions } from "../../adapter-C5I5e_-i.mjs";
3
- export { ViewAdapter, ViewAdapterOptions };
2
+ import { b as viewDirs, v as ViewAdapter, y as ViewAdapterOptions } from "../../application-BuUWvaqp.mjs";
3
+ export { ViewAdapter, ViewAdapterOptions, viewDirs };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.2.0
2
+ * @forinda/kickjs v10.3.1
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{Logger}from"../../core/logger.mjs";import"../../core-CFXpwc7m.mjs";import{t as defineAdapter}from"../../define-adapter-BRJ6lXkV.mjs";import{resolve}from"node:path";const log=Logger.for(`ViewEngine`),ViewAdapter=defineAdapter({name:`ViewAdapter`,build:options=>({beforeMount({app}){let{engine,ext,viewsDir=`src/views`}=options;engine.__express?app.engine(ext,engine.__express):typeof engine.renderFile==`function`?app.engine(ext,(path,opts,callback)=>{engine.renderFile(path,opts,callback)}):(typeof engine==`function`||log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`),app.engine(ext,engine)),app.set(`view engine`,ext),app.set(`views`,resolve(viewsDir)),log.debug(`View engine: ${ext} (${resolve(viewsDir)})`)}})});export{ViewAdapter};
11
+ import{Logger}from"../../core/logger.mjs";import"../../core-YE-k8IrU.mjs";import{t as defineAdapter}from"../../define-adapter-C6H-I1og.mjs";import{dirname,resolve}from"node:path";const log=Logger.for(`ViewEngine`),ViewAdapter=defineAdapter({name:`ViewAdapter`,build:options=>({beforeMount({app}){let{engine,ext,viewsDir=`src/views`}=options;engine.__express?app.engine(ext,engine.__express):typeof engine.renderFile==`function`?app.engine(ext,(path,opts,callback)=>{engine.renderFile(path,opts,callback)}):(typeof engine==`function`||log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`),app.engine(ext,engine)),app.set(`view engine`,ext),app.set(`views`,viewDirs(viewsDir)),log.debug(`View engine: ${ext} (${viewDirs(viewsDir).join(`, `)})`)}})});function viewDirs(viewsDir){let root=resolve(process.env.KICK_APP_ROOT??process.cwd(),viewsDir),entry=process.argv[1]?resolve(dirname(resolve(process.argv[1])),viewsDir):root;return[.../* @__PURE__ */ new Set([root,entry])]}export{ViewAdapter,viewDirs};
12
12
  //# sourceMappingURL=views.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"views.mjs","names":[],"sources":["../../../src/http/middleware/views.ts"],"sourcesContent":["import { resolve } from 'node:path'\nimport { Logger, defineAdapter } from '../../core'\n\nconst log = Logger.for('ViewEngine')\n\nexport interface ViewAdapterOptions {\n /**\n * Template engine — pass the engine module or a render function.\n * Supported engines: ejs, pug, handlebars, nunjucks, or any\n * Express-compatible engine with a __express property.\n *\n * @example\n * ```ts\n * import ejs from 'ejs'\n * ViewAdapter({ engine: ejs, ext: 'ejs' })\n *\n * import pug from 'pug'\n * ViewAdapter({ engine: pug, ext: 'pug' })\n * ```\n */\n engine: any\n\n /** File extension for templates (e.g., 'ejs', 'pug', 'hbs') */\n ext: string\n\n /** Directory containing template files (default: 'src/views') */\n viewsDir?: string\n\n /** Default layout template (optional — depends on engine) */\n layout?: string\n}\n\n/**\n * View/template adapter — pluggable template engine support for KickJS.\n *\n * Registers an Express view engine and sets the views directory.\n * Use `ctx.render()` in controllers to render templates.\n *\n * Migrated to the `defineAdapter()` factory in v4 — call without `new`.\n * The pre-v4 `new ViewAdapter({...})` form is gone; see\n * `docs/guide/migration-v3-to-v4.md` for the rename.\n *\n * @example\n * ```ts\n * import ejs from 'ejs'\n * import { ViewAdapter } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * adapters: [\n * ViewAdapter({ engine: ejs, ext: 'ejs', viewsDir: 'src/views' }),\n * ],\n * })\n *\n * // In a controller:\n * @Get('/dashboard')\n * async dashboard(ctx: RequestContext) {\n * ctx.render('dashboard', { user: currentUser, title: 'Dashboard' })\n * }\n * ```\n */\nexport const ViewAdapter = defineAdapter<ViewAdapterOptions>({\n name: 'ViewAdapter',\n build: (options) => ({\n beforeMount({ app }) {\n const { engine, ext, viewsDir = 'src/views' } = options\n\n // Register the engine. Three resolution paths cover every\n // mainstream template engine + a fall-through for custom ones.\n if (engine.__express) {\n // EJS, Pug — have __express method\n app.engine(ext, engine.__express)\n } else if (typeof engine.renderFile === 'function') {\n // Engines with renderFile (nunjucks-style)\n app.engine(\n ext,\n (path: string, opts: any, callback: (err: Error | null, html?: string) => void) => {\n engine.renderFile(path, opts, callback)\n },\n )\n } else if (typeof engine === 'function') {\n // Custom render function: (path, options, callback) => void\n app.engine(ext, engine)\n } else {\n log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`)\n app.engine(ext, engine)\n }\n\n app.set('view engine', ext)\n app.set('views', resolve(viewsDir))\n\n log.debug(`View engine: ${ext} (${resolve(viewsDir)})`)\n },\n }),\n})\n"],"mappings":";;;;;;;;;;2KAGA,MAAM,IAAM,OAAO,IAAI,YAAY,EA0DtB,YAAc,cAAkC,CAC3D,KAAM,cACN,MAAQ,UAAa,CACnB,YAAY,CAAE,KAAO,CACnB,GAAM,CAAE,OAAQ,IAAK,SAAW,aAAgB,QAI5C,OAAO,UAET,IAAI,OAAO,IAAK,OAAO,SAAS,EACvB,OAAO,OAAO,YAAe,WAEtC,IAAI,OACF,KACC,KAAc,KAAW,WAAyD,CACjF,OAAO,WAAW,KAAM,KAAM,QAAQ,CACxC,CACF,GACS,OAAO,QAAW,YAI3B,IAAI,KAAK,eAAe,IAAI,sDAAsD,EAClF,IAAI,OAAO,IAAK,MAAM,GAGxB,IAAI,IAAI,cAAe,GAAG,EAC1B,IAAI,IAAI,QAAS,QAAQ,QAAQ,CAAC,EAElC,IAAI,MAAM,gBAAgB,IAAI,IAAI,QAAQ,QAAQ,EAAE,EAAE,CACxD,CACF,EACF,CAAC"}
1
+ {"version":3,"file":"views.mjs","names":[],"sources":["../../../src/http/middleware/views.ts"],"sourcesContent":["import { dirname, resolve } from 'node:path'\nimport { Logger, defineAdapter } from '../../core'\n\nconst log = Logger.for('ViewEngine')\n\nexport interface ViewAdapterOptions {\n /**\n * Template engine — pass the engine module or a render function.\n * Supported engines: ejs, pug, handlebars, nunjucks, or any\n * Express-compatible engine with a __express property.\n *\n * @example\n * ```ts\n * import ejs from 'ejs'\n * ViewAdapter({ engine: ejs, ext: 'ejs' })\n *\n * import pug from 'pug'\n * ViewAdapter({ engine: pug, ext: 'pug' })\n * ```\n */\n engine: any\n\n /** File extension for templates (e.g., 'ejs', 'pug', 'hbs') */\n ext: string\n\n /**\n * Directory containing template files (default: 'src/views'), relative to\n * the project. Also looked up beside the running entry file, where\n * `copyDirs: ['src/views']` puts it in a build (`dist/src/views`), so a\n * deployment holding only `dist/` still finds it.\n */\n viewsDir?: string\n\n /** Default layout template (optional — depends on engine) */\n layout?: string\n}\n\n/**\n * View/template adapter — pluggable template engine support for KickJS.\n *\n * Registers an Express view engine and sets the views directory.\n * Use `ctx.render()` in controllers to render templates.\n *\n * Migrated to the `defineAdapter()` factory in v4 — call without `new`.\n * The pre-v4 `new ViewAdapter({...})` form is gone; see\n * `docs/guide/migration-v3-to-v4.md` for the rename.\n *\n * @example\n * ```ts\n * import ejs from 'ejs'\n * import { ViewAdapter } from '@forinda/kickjs'\n *\n * bootstrap({\n * modules,\n * adapters: [\n * ViewAdapter({ engine: ejs, ext: 'ejs', viewsDir: 'src/views' }),\n * ],\n * })\n *\n * // In a controller:\n * @Get('/dashboard')\n * async dashboard(ctx: RequestContext) {\n * ctx.render('dashboard', { user: currentUser, title: 'Dashboard' })\n * }\n * ```\n */\nexport const ViewAdapter = defineAdapter<ViewAdapterOptions>({\n name: 'ViewAdapter',\n build: (options) => ({\n beforeMount({ app }) {\n const { engine, ext, viewsDir = 'src/views' } = options\n\n // Register the engine. Three resolution paths cover every\n // mainstream template engine + a fall-through for custom ones.\n if (engine.__express) {\n // EJS, Pug — have __express method\n app.engine(ext, engine.__express)\n } else if (typeof engine.renderFile === 'function') {\n // Engines with renderFile (nunjucks-style)\n app.engine(\n ext,\n (path: string, opts: any, callback: (err: Error | null, html?: string) => void) => {\n engine.renderFile(path, opts, callback)\n },\n )\n } else if (typeof engine === 'function') {\n // Custom render function: (path, options, callback) => void\n app.engine(ext, engine)\n } else {\n log.warn(`Engine for .${ext} does not have __express or renderFile. Trying as-is.`)\n app.engine(ext, engine)\n }\n\n app.set('view engine', ext)\n app.set('views', viewDirs(viewsDir))\n\n log.debug(`View engine: ${ext} (${viewDirs(viewsDir).join(', ')})`)\n },\n }),\n})\n\n/**\n * Where to look for `viewsDir`: the project — `KICK_APP_ROOT` when set (the\n * Netlify and Vercel functions `kick build:*` writes set it to where\n * `deploy.include` files land), else the working directory — then beside the\n * running entry file (`node dist/index.js` → `dist/<viewsDir>`, where\n * `copyDirs` copies it). Express tries them in order.\n */\nexport function viewDirs(viewsDir: string): string[] {\n const root = resolve(process.env.KICK_APP_ROOT ?? process.cwd(), viewsDir)\n const entry = process.argv[1] ? resolve(dirname(resolve(process.argv[1])), viewsDir) : root\n return [...new Set([root, entry])]\n}\n"],"mappings":";;;;;;;;;;mLAGA,MAAM,IAAM,OAAO,IAAI,YAAY,EA+DtB,YAAc,cAAkC,CAC3D,KAAM,cACN,MAAQ,UAAa,CACnB,YAAY,CAAE,KAAO,CACnB,GAAM,CAAE,OAAQ,IAAK,SAAW,aAAgB,QAI5C,OAAO,UAET,IAAI,OAAO,IAAK,OAAO,SAAS,EACvB,OAAO,OAAO,YAAe,WAEtC,IAAI,OACF,KACC,KAAc,KAAW,WAAyD,CACjF,OAAO,WAAW,KAAM,KAAM,QAAQ,CACxC,CACF,GACS,OAAO,QAAW,YAI3B,IAAI,KAAK,eAAe,IAAI,sDAAsD,EAClF,IAAI,OAAO,IAAK,MAAM,GAGxB,IAAI,IAAI,cAAe,GAAG,EAC1B,IAAI,IAAI,QAAS,SAAS,QAAQ,CAAC,EAEnC,IAAI,MAAM,gBAAgB,IAAI,IAAI,SAAS,QAAQ,CAAC,CAAC,KAAK,IAAI,EAAE,EAAE,CACpE,CACF,EACF,CAAC,EASD,SAAgB,SAAS,SAA4B,CACnD,IAAM,KAAO,QAAQ,QAAQ,IAAI,eAAiB,QAAQ,IAAI,EAAG,QAAQ,EACnE,MAAQ,QAAQ,KAAK,GAAK,QAAQ,QAAQ,QAAQ,QAAQ,KAAK,EAAE,CAAC,EAAG,QAAQ,EAAI,KACvF,MAAO,CAAC,mBAAG,IAAI,IAAI,CAAC,KAAM,KAAK,CAAC,CAAC,CACnC"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.2.0
2
+ * @forinda/kickjs v10.3.1
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- export{u as FILTER_OPERATORS,t as buildQueryParams,n as getQueryParsingDefaults,r as parseFilters,i as parsePagination,a as parseQuery,o as parseSearchQuery,s as parseSort,c as resetQueryParsingDefaults,l as setQueryParsingDefaults}from"../../query-AnbWMCd6.mjs";
11
+ export{u as FILTER_OPERATORS,t as buildQueryParams,n as getQueryParsingDefaults,r as parseFilters,i as parsePagination,a as parseQuery,o as parseSearchQuery,s as parseSort,c as resetQueryParsingDefaults,l as setQueryParsingDefaults}from"../../query-mXPZYtQw.mjs";
@@ -1,3 +1,3 @@
1
1
 
2
- import { Ct as buildRouteTable, St as assertRouteUnique, bt as BuildRoutesOptions, xt as _setExternalContributorSources } from "../adapter-C5I5e_-i.mjs";
2
+ import { i as buildRouteTable, n as _setExternalContributorSources, r as assertRouteUnique, t as BuildRoutesOptions } from "../router-builder-obSpg-Ub.mjs";
3
3
  export { BuildRoutesOptions, _setExternalContributorSources, assertRouteUnique, buildRouteTable };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.2.0
2
+ * @forinda/kickjs v10.3.1
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- export{t as _setExternalContributorSources,n as assertRouteUnique,r as buildRouteTable}from"../router-builder-CrWKq6O2.mjs";
11
+ export{t as _setExternalContributorSources,n as assertRouteUnique,r as buildRouteTable}from"../router-builder-D0SDqFTr.mjs";
@@ -1,5 +1,5 @@
1
1
 
2
- import { p as HttpRuntime } from "../../adapter-C5I5e_-i.mjs";
2
+ import { p as HttpRuntime } from "../../adapter-6fjmVVc2.mjs";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  //#region src/http/runtimes/fastify.d.ts
5
5
  interface FastifyReplyLike {
@@ -1 +1 @@
1
- {"version":3,"file":"fastify.d.mts","names":[],"sources":["../../../src/http/runtimes/fastify.ts"],"mappings":";;;;UAgDU;EACR,KAAK,qBAAqB;EAC1B,KAAK,oBAAoB;EACzB,OAAO,cAAc,iBAAiB;EACtC,aAAa,eAAe;EAC5B,KAAK,sBAAsB;EAC3B,WAAW,KAAK,8BAA8B;EAC9C,UAAU;EACV;;EAEA;WACS;WACA,KAAK;;UAEN;EACR,KAAK;EACL;EACA;EACA;;EAEA,UAAU;;EAEV,cAAc,sBAAsB;EACpC;;KAEG,kBAAkB,SAAS,oBAAoB,OAAO,4BAA4B;UAC7E;EACR,SAAS;EACT,SAAS,iBAAiB,iBAAiB,gBAAgB;EAC3D,IAAI,eAAe;EACnB,MAAM;IAAQ;IAAgB;IAAa,SAAS;;EACpD,mBAAmB,SAAS;EAC5B,gBACE,UAAU,cAAc,KAAK,oBAAoB,OAAO;EAE1D,SAAS;EACT,QAAQ,KAAK,iBAAiB,KAAK;;;;;;EAMnC,sBACE,kBAAkB,mBAClB;IAAQ;KACR,QAAQ;;;KAQP,qBACH,KAAK,oBACL,eAAe,QACf,OAAO,KAAK,cAAc;UA4BlB;EACR;EACA;EACA;EACA;EACA;EACA,iBAAiB,QAAQ;;;;;;;wBAwNX,kBAAkB,YAAY;;;;;;;;iBA4O7B;EACf,2BAA2B;EAC3B,4BAA4B;EAC5B,uBAAuB"}
1
+ {"version":3,"file":"fastify.d.mts","names":[],"sources":["../../../src/http/runtimes/fastify.ts"],"mappings":";;;;UAoDU;EACR,KAAK,qBAAqB;EAC1B,KAAK,oBAAoB;EACzB,OAAO,cAAc,iBAAiB;EACtC,aAAa,eAAe;EAC5B,KAAK,sBAAsB;EAC3B,WAAW,KAAK,8BAA8B;EAC9C,UAAU;EACV;;EAEA;WACS;WACA,KAAK;;UAEN;EACR,KAAK;EACL;EACA;EACA;;EAEA,UAAU;;EAEV,cAAc,sBAAsB;EACpC;;KAEG,kBAAkB,SAAS,oBAAoB,OAAO,4BAA4B;UAC7E;EACR,SAAS;EACT,SAAS,iBAAiB,iBAAiB,gBAAgB;EAC3D,IAAI,eAAe;EACnB,MAAM;IAAQ;IAAgB;IAAa,SAAS;;EACpD,mBAAmB,SAAS;EAC5B,gBACE,UAAU,cAAc,KAAK,oBAAoB,OAAO;EAE1D,SAAS;EACT,QAAQ,KAAK,iBAAiB,KAAK;;;;;;EAMnC,sBACE,kBAAkB,mBAClB;IAAQ;KACR,QAAQ;;;KAQP,qBACH,KAAK,oBACL,eAAe,QACf,OAAO,KAAK,cAAc;UA4BlB;EACR;EACA;EACA;EACA;EACA;EACA,iBAAiB,QAAQ;;;;;;;wBAwNX,kBAAkB,YAAY;;;;;;;;iBA8O7B;EACf,2BAA2B;EAC3B,4BAA4B;EAC5B,uBAAuB"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.2.0
2
+ * @forinda/kickjs v10.3.1
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,6 +8,6 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{HttpException}from"../../core/errors.mjs";import{_ as unsupportedMediaTypeError,m as parseForm,n as applyHandlerResult,o as createRequestStore,s as disposeRequestStore}from"../../reply-DjysdCPI.mjs";import{f as requestStore,i as stringifyJson,r as publishMatchedRoute,t as RequestContext}from"../../context-C6iKf9hN.mjs";import{validate}from"../middleware/validate.mjs";import{t as applyUploadConfig}from"../../upload-config-DLgt4l7F.mjs";import"../middleware/upload.mjs";import{createRequire}from"node:module";const peerRequire=createRequire(import.meta.url),loadPeer=name=>{let mod=peerRequire(name);return mod&&mod.__esModule&&mod.default?mod.default:mod.default??mod},QUEUE=Symbol(`kickjs.fastify.connectQueue`),READY=Symbol(`kickjs.fastify.ready`),NEXT=Symbol(`kickjs.fastify.next`),NEEDS_MULTIPART=Symbol(`kickjs.fastify.needsMultipart`),NOOP_NEXT=()=>{};function settleOrFail(reply,returned){typeof returned?.then==`function`&&Promise.resolve(returned).then(void 0,()=>{!reply.sent&&!reply.raw.headersSent&&reply.code(500).send({message:`Internal Server Error`})})}const NO_FALLTHROUGH=Symbol(`kickjs.fastify.noFallthrough`);var FastifyReplyDriver=class{reply;constructor(reply){this.reply=reply}status(code){return this.reply.code(code),this}json(data){return this.reply.getHeader(`content-type`)||this.reply.type(`application/json; charset=utf-8`),this.reply.serializer(stringifyJson).send(data),this}send(data){return this.reply.send(data),this}type(contentType){return this.reply.type(contentType),this}getHeader(name){return this.reply.getHeader(name)}setHeader(name,value){return this.reply.removeHeader(name),this.reply.header(name,value),this}render(){throw Error(`ctx.render() is not supported on the Fastify runtime (no view engine).`)}writeHead(statusCode,headers){return this.reply.hijack(),this.reply.raw.writeHead(statusCode,headers),this}flushHeaders(){return this.reply.raw.flushHeaders?.(),this}write(chunk){return this.reply.raw.write(chunk)}end(data){return this.reply.raw.headersSent?this.reply.raw.end(data):this.reply.send(data??``),this}once(event,listener){return this.reply.raw.once(event,listener),this}get headersSent(){return this.reply.sent||this.reply.raw.headersSent}};function replyDriver(reply){return new FastifyReplyDriver(reply)}function routeHandler(entry){let validator=entry.meta.validation?validate(entry.meta.validation,{validationError:entry.validationError}):void 0;return async(request,reply)=>{let raw=request.raw;if(raw.body=request.body,raw.params=request.params,raw.query=request.query,entry.meta.upload&&entry.meta.upload.mode!==`none`){if(typeof request.parts!=`function`)throw Error(`@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.
12
- Install it as a peer dependency: pnpm add @fastify/multipart.`);let rawParts=[],fields={};for await(let part of request.parts())part.type===`file`&&part.toBuffer?rawParts.push({fieldname:part.fieldname,filename:part.filename??``,mimetype:part.mimetype??`application/octet-stream`,buffer:await part.toBuffer()}):fields[part.fieldname]=part.value;let{file,files}=applyUploadConfig(rawParts,entry.meta.upload);raw.file=file,raw.files=files,raw.body={...raw.body,...fields}}let headerId=raw.headers[`x-request-id`],requestId=raw.requestId||(Array.isArray(headerId)?headerId[0]:headerId),store=createRequestStore(requestId);raw.requestId=store.requestId,reply.getHeader(`x-request-id`)||reply.header(`x-request-id`,store.requestId),reply.raw.once(`close`,()=>disposeRequestStore(store)),await requestStore.run(store,async()=>{publishMatchedRoute(raw,entry);let ctx=new RequestContext(raw,reply,NOOP_NEXT,replyDriver(reply));if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),reply.sent))return;validator&&await new Promise((resolve,reject)=>{validator(raw,void 0,err=>err?reject(err):resolve())});for(let mw of entry.middlewares){let advanced=!1;if(await new Promise((resolve,reject)=>{Promise.resolve(mw(ctx,err=>{advanced=!0,err?reject(err):resolve()})).catch(reject)}),!advanced||reply.sent)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),reply.sent)return;let result=await entry.handler(ctx);!reply.sent&&!await applyHandlerResult(ctx,result)&&reply.callNotFound()})}}function hopTrust(hops){return(_ip,hopIndex)=>hopIndex<hops}function fastifyRuntime(){return{name:`fastify`,createApp(options={}){let app=loadPeer(`fastify`)({logger:!1,routerOptions:{ignoreTrailingSlash:!0},...options.bodyLimit===void 0?{}:{bodyLimit:options.bodyLimit},trustProxy:typeof options.trustProxy==`number`?hopTrust(options.trustProxy):options.trustProxy});app[QUEUE]=[];let addParser=app.addContentTypeParser?.bind(app);return addParser&&(addParser(/^application\/[\w.+-]+\+json$/,{parseAs:`string`},(_req,body,done)=>{if(body===``)return done(null,void 0);try{done(null,JSON.parse(body))}catch(err){done(HttpException.badRequest(err instanceof Error?err.message:`Request body could not be parsed`),void 0)}}),addParser(`application/x-www-form-urlencoded`,{parseAs:`string`},(_req,body,done)=>{done(null,parseForm(body))}),addParser(/^text\//,{parseAs:`string`},(_req,body,done)=>{done(null,body)}),addParser(`*`,{parseAs:`string`},(req,body,done)=>{if(!body)return done(null,void 0);done(unsupportedMediaTypeError(req.headers?.[`content-type`]),void 0)})),options.notFoundFallthrough===!1&&(app[NO_FALLTHROUGH]=!0),app},nodeHandler(app){let state=app;state[READY]||(state[READY]=(async()=>{if(state[NEEDS_MULTIPART]){let multipart=loadPeer(`@fastify/multipart`);await app.register(multipart,{limits:{fileSize:2**53-1}})}let middie=loadPeer(`@fastify/middie`);await app.register(middie);for(let{mw,opts}of state[QUEUE]??[])opts?.path===void 0?app.use(mw):app.use(opts.path,mw);await app.ready()})());let readyP=state[READY],ready=!1;return readyP.then(()=>ready=!0,()=>{}),(req,res,next)=>{next&&(req[NEXT]=next),ready?app.routing(req,res):readyP.then(()=>app.routing(req,res)).catch(err=>{next&&next(err)})}},mountRoutes(app,table){for(let{mountPath,routes}of table)for(let entry of routes){entry.meta.upload&&(app[NEEDS_MULTIPART]=!0);let url=joinPath(mountPath,entry.path);app.route({method:entry.method,url,handler:routeHandler(entry)})}},useConnect(app,mw,opts){app[QUEUE]?.push({mw,opts})},serveStatic(app,prefix,dir){let serveStatic=loadPeer(`serve-static`);this.useConnect(app,serveStatic(dir),{path:prefix})},setNotFound(app,mw){app.setNotFoundHandler((request,reply)=>{let next=request.raw[NEXT];next&&!app[NO_FALLTHROUGH]?(reply.hijack(),next()):settleOrFail(reply,mw(request.raw,replyDriver(reply),NOOP_NEXT))})},setErrorHandler(app,mw){app.setErrorHandler((err,request,reply)=>{settleOrFail(reply,mw(err,request.raw,replyDriver(reply),NOOP_NEXT))})},close(app){return app.close()},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0,http2:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{fastifyRuntime};
11
+ import{createLogger}from"../../core/logger.mjs";import{HttpException}from"../../core/errors.mjs";import{_ as unsupportedMediaTypeError,m as parseForm,n as applyHandlerResult,o as createRequestStore,s as disposeRequestStore}from"../../reply-CMRk-Jp3.mjs";import{f as requestStore,i as stringifyJson,r as publishMatchedRoute,t as RequestContext}from"../../context-DJvuLfrx.mjs";import{validate}from"../middleware/validate.mjs";import{t as applyUploadConfig}from"../../upload-config-D22qKth8.mjs";import"../middleware/upload.mjs";import{t as lazyServeStatic}from"../../lazy-serve-static-Barg3__1.mjs";import Fastify from"fastify";const pluginOf=mod=>mod.default??mod,createFastify=Fastify,log=createLogger(`FastifyRuntime`),QUEUE=Symbol(`kickjs.fastify.connectQueue`),READY=Symbol(`kickjs.fastify.ready`),NEXT=Symbol(`kickjs.fastify.next`),NEEDS_MULTIPART=Symbol(`kickjs.fastify.needsMultipart`),NOOP_NEXT=()=>{};function settleOrFail(reply,returned){typeof returned?.then==`function`&&Promise.resolve(returned).then(void 0,()=>{!reply.sent&&!reply.raw.headersSent&&reply.code(500).send({message:`Internal Server Error`})})}const NO_FALLTHROUGH=Symbol(`kickjs.fastify.noFallthrough`);var FastifyReplyDriver=class{reply;constructor(reply){this.reply=reply}status(code){return this.reply.code(code),this}json(data){return this.reply.getHeader(`content-type`)||this.reply.type(`application/json; charset=utf-8`),this.reply.serializer(stringifyJson).send(data),this}send(data){return this.reply.send(data),this}type(contentType){return this.reply.type(contentType),this}getHeader(name){return this.reply.getHeader(name)}setHeader(name,value){return this.reply.removeHeader(name),this.reply.header(name,value),this}render(){throw Error(`ctx.render() is not supported on the Fastify runtime (no view engine).`)}writeHead(statusCode,headers){return this.reply.hijack(),this.reply.raw.writeHead(statusCode,headers),this}flushHeaders(){return this.reply.raw.flushHeaders?.(),this}write(chunk){return this.reply.raw.write(chunk)}end(data){return this.reply.raw.headersSent?this.reply.raw.end(data):this.reply.send(data??``),this}once(event,listener){return this.reply.raw.once(event,listener),this}get headersSent(){return this.reply.sent||this.reply.raw.headersSent}};function replyDriver(reply){return new FastifyReplyDriver(reply)}function routeHandler(entry){let validator=entry.meta.validation?validate(entry.meta.validation,{validationError:entry.validationError}):void 0;return async(request,reply)=>{let raw=request.raw;if(raw.body=request.body,raw.params=request.params,raw.query=request.query,entry.meta.upload&&entry.meta.upload.mode!==`none`){if(typeof request.parts!=`function`)throw Error(`@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.
12
+ Install it as a peer dependency: pnpm add @fastify/multipart.`);let rawParts=[],fields={};for await(let part of request.parts())part.type===`file`&&part.toBuffer?rawParts.push({fieldname:part.fieldname,filename:part.filename??``,mimetype:part.mimetype??`application/octet-stream`,buffer:await part.toBuffer()}):fields[part.fieldname]=part.value;let{file,files}=applyUploadConfig(rawParts,entry.meta.upload);raw.file=file,raw.files=files,raw.body={...raw.body,...fields}}let headerId=raw.headers[`x-request-id`],requestId=raw.requestId||(Array.isArray(headerId)?headerId[0]:headerId),store=createRequestStore(requestId);raw.requestId=store.requestId,reply.getHeader(`x-request-id`)||reply.header(`x-request-id`,store.requestId),reply.raw.once(`close`,()=>disposeRequestStore(store)),await requestStore.run(store,async()=>{publishMatchedRoute(raw,entry);let ctx=new RequestContext(raw,reply,NOOP_NEXT,replyDriver(reply));if(entry.earlyContributorRunner&&(await entry.earlyContributorRunner(ctx),reply.sent))return;validator&&await new Promise((resolve,reject)=>{validator(raw,void 0,err=>err?reject(err):resolve())});for(let mw of entry.middlewares){let advanced=!1;if(await new Promise((resolve,reject)=>{Promise.resolve(mw(ctx,err=>{advanced=!0,err?reject(err):resolve()})).catch(reject)}),!advanced||reply.sent)return}if(entry.contributorRunner&&await entry.contributorRunner(ctx),reply.sent)return;let result=await entry.handler(ctx);!reply.sent&&!await applyHandlerResult(ctx,result)&&reply.callNotFound()})}}function hopTrust(hops){return(_ip,hopIndex)=>hopIndex<hops}function fastifyRuntime(){return{name:`fastify`,createApp(options={}){let app=createFastify({logger:!1,routerOptions:{ignoreTrailingSlash:!0},...options.bodyLimit===void 0?{}:{bodyLimit:options.bodyLimit},trustProxy:typeof options.trustProxy==`number`?hopTrust(options.trustProxy):options.trustProxy});app[QUEUE]=[];let addParser=app.addContentTypeParser?.bind(app);return addParser&&(addParser(/^application\/[\w.+-]+\+json$/,{parseAs:`string`},(_req,body,done)=>{if(body===``)return done(null,void 0);try{done(null,JSON.parse(body))}catch(err){done(HttpException.badRequest(err instanceof Error?err.message:`Request body could not be parsed`),void 0)}}),addParser(`application/x-www-form-urlencoded`,{parseAs:`string`},(_req,body,done)=>{done(null,parseForm(body))}),addParser(/^text\//,{parseAs:`string`},(_req,body,done)=>{done(null,body)}),addParser(`*`,{parseAs:`string`},(req,body,done)=>{if(!body)return done(null,void 0);done(unsupportedMediaTypeError(req.headers?.[`content-type`]),void 0)})),options.notFoundFallthrough===!1&&(app[NO_FALLTHROUGH]=!0),app},nodeHandler(app){let state=app;state[READY]||(state[READY]=(async()=>{if(state[NEEDS_MULTIPART]){let multipart=pluginOf(await import(`@fastify/multipart`));await app.register(multipart,{limits:{fileSize:2**53-1}})}let middie=pluginOf(await import(`@fastify/middie`));await app.register(middie);for(let{mw,opts}of state[QUEUE]??[])opts?.path===void 0?app.use(mw):app.use(opts.path,mw);await app.ready()})());let readyP=state[READY],ready=!1;return readyP.then(()=>ready=!0,()=>{}),(req,res,next)=>{next&&(req[NEXT]=next),ready?app.routing(req,res):readyP.then(()=>app.routing(req,res)).catch(err=>{if(next)return next(err);log.error(err,`Fastify failed to start`),res.statusCode=500,res.end(`Internal Server Error`)})}},mountRoutes(app,table){for(let{mountPath,routes}of table)for(let entry of routes){entry.meta.upload&&(app[NEEDS_MULTIPART]=!0);let url=joinPath(mountPath,entry.path);app.route({method:entry.method,url,handler:routeHandler(entry)})}},useConnect(app,mw,opts){app[QUEUE]?.push({mw,opts})},serveStatic(app,prefix,dir){this.useConnect(app,lazyServeStatic(dir),{path:prefix})},setNotFound(app,mw){app.setNotFoundHandler((request,reply)=>{let next=request.raw[NEXT];next&&!app[NO_FALLTHROUGH]?(reply.hijack(),next()):settleOrFail(reply,mw(request.raw,replyDriver(reply),NOOP_NEXT))})},setErrorHandler(app,mw){app.setErrorHandler((err,request,reply)=>{settleOrFail(reply,mw(err,request.raw,replyDriver(reply),NOOP_NEXT))})},close(app){return app.close()},capabilities:{render:!1,uploads:!0,connectMiddleware:!0,nativeBodyParsing:!0,http2:!0}}}function joinPath(mountPath,path){let a=mountPath.endsWith(`/`)?mountPath.slice(0,-1):mountPath;return path===`/`||path===``?a===``?`/`:a:`${a}${path.startsWith(`/`)?path:`/${path}`}`}export{fastifyRuntime};
13
13
  //# sourceMappingURL=fastify.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fastify.mjs","names":[],"sources":["../../../src/http/runtimes/fastify.ts"],"sourcesContent":["// The Fastify runtime — `@forinda/kickjs/fastify`.\n//\n// Implements the same HttpRuntime contract as expressRuntime, over Fastify 5.\n// KickJS still owns decorators → RouteTable, the contributor pipeline, and the\n// RequestContext surface; this runtime materializes routes as NATIVE Fastify\n// routes and wraps `reply` in a RuntimeResponse so `ctx.json` / `ctx.html` /\n// `ctx.sse` work unchanged.\n//\n// `fastify`, `@fastify/middie` are optional peers — install them alongside\n// `@forinda/kickjs` to use this subpath.\n//\n// Lifecycle note: Fastify registration (`register` / `use` / `route`) is\n// deferred until `ready()`. Connect middleware needs `@fastify/middie`\n// registered first, so `useConnect` only QUEUES middleware; `nodeHandler`\n// registers middie, then the queued middleware, then awaits `ready()`.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { createRequire } from 'node:module'\n\nimport { HttpException } from '../../core/errors'\nimport { parseForm, unsupportedMediaTypeError } from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute, stringifyJson } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n RuntimeResponse,\n UseConnectOptions,\n} from '../runtime'\n\n// ESM-safe require for the optional peers (fastify / @fastify/middie /\n// serve-static), resolved from wherever this module is installed.\nconst peerRequire = createRequire(import.meta.url)\nconst loadPeer = (name: string): any => {\n const mod = peerRequire(name)\n return mod && mod.__esModule && mod.default ? mod.default : (mod.default ?? mod)\n}\n\n// Minimal structural surface we use from Fastify — avoids a hard type dep so\n// the root package never needs `fastify` installed to typecheck.\ninterface FastifyReplyLike {\n code(statusCode: number): FastifyReplyLike\n send(payload?: unknown): FastifyReplyLike\n header(name: string, value: unknown): FastifyReplyLike\n removeHeader(name: string): FastifyReplyLike\n type(contentType: string): FastifyReplyLike\n serializer(fn: (payload: unknown) => string): FastifyReplyLike\n getHeader(name: string): unknown\n hijack(): void\n /** Hand the request to the not-found handler (Fastify 5). */\n callNotFound(): void\n readonly sent: boolean\n readonly raw: ServerResponse\n}\ninterface FastifyRequestLike {\n raw: IncomingMessage\n body?: unknown\n params?: unknown\n query?: unknown\n /** Request headers, as Fastify normalises them (lowercased keys). */\n headers?: Record<string, string | string[] | undefined>\n /** Present once @fastify/multipart is registered — async iterator of parts. */\n parts?: () => AsyncIterableIterator<MultipartPart>\n isMultipart?: () => boolean\n}\ntype FastifyHandler = (request: FastifyRequestLike, reply: FastifyReplyLike) => void | Promise<void>\ninterface FastifyAppLike {\n close(): Promise<void>\n register(plugin: unknown, opts?: unknown): Promise<void> | FastifyAppLike\n use(path: unknown, mw?: unknown): unknown\n route(opts: { method: string; url: string; handler: FastifyHandler }): unknown\n setNotFoundHandler(handler: FastifyHandler): unknown\n setErrorHandler(\n handler: (err: unknown, req: FastifyRequestLike, reply: FastifyReplyLike) => void,\n ): unknown\n ready(): Promise<void>\n routing(req: IncomingMessage, res: ServerResponse): void\n /**\n * Fastify's content-type parser registry. Typed here rather than reached for\n * with a cast so the callback shape is checked at the call site — these\n * parsers decide what `ctx.body` is on this runtime.\n */\n addContentTypeParser?(\n matcher: string | RegExp | string[],\n opts: { parseAs: 'string' | 'buffer' },\n parser: FastifyBodyParser,\n ): unknown\n}\n\n/** The `done` callback a Fastify content-type parser calls. */\ntype FastifyParserDone = (err: Error | null, body?: unknown) => void\n\n/** `done`-style callback Fastify hands a content-type parser. */\ntype FastifyBodyParser = (\n req: FastifyRequestLike,\n body: string | Buffer,\n done: (err: Error | null, body?: unknown) => void,\n) => void\n\nconst QUEUE = Symbol('kickjs.fastify.connectQueue')\nconst READY = Symbol('kickjs.fastify.ready')\nconst NEXT = Symbol('kickjs.fastify.next')\n// Set during mountRoutes when any route carries @FileUpload metadata, so\n// nodeHandler knows to register @fastify/multipart before ready().\nconst NEEDS_MULTIPART = Symbol('kickjs.fastify.needsMultipart')\nconst NOOP_NEXT = (): void => {}\n\n/**\n * An async error / not-found handler that rejects never answers; answer 500\n * so the request ends instead of hanging until the client gives up.\n */\nfunction settleOrFail(reply: FastifyReplyLike, returned: unknown): void {\n if (typeof (returned as PromiseLike<void> | undefined)?.then !== 'function') return\n Promise.resolve(returned).then(undefined, () => {\n if (!reply.sent && !reply.raw.headersSent) {\n // The 500 body every engine's built-in error handler starts from.\n reply.code(500).send({ message: 'Internal Server Error' })\n }\n })\n}\n/** `notFoundFallthrough: false` — answer unmatched requests instead of handing them back. */\nconst NO_FALLTHROUGH = Symbol('kickjs.fastify.noFallthrough')\n\n// A @fastify/multipart part as we consume it from `request.parts()`.\ninterface MultipartPart {\n type: 'file' | 'field'\n fieldname: string\n filename?: string\n mimetype?: string\n value?: unknown\n toBuffer?: () => Promise<Buffer>\n}\n\n/**\n * Wrap a Fastify reply so the RequestContext response helpers drive it.\n * A class so the ~12 driver methods live on a shared prototype — the previous\n * object-literal version re-allocated every method closure on each request.\n */\nclass FastifyReplyDriver implements RuntimeResponse {\n constructor(private readonly reply: FastifyReplyLike) {}\n status(code: number): this {\n this.reply.code(code)\n return this\n }\n json(data: unknown): this {\n // A custom serializer drops Fastify's default content-type; keep one the\n // caller chose (`application/problem+json`).\n if (!this.reply.getHeader('content-type')) this.reply.type('application/json; charset=utf-8')\n this.reply.serializer(stringifyJson).send(data)\n return this\n }\n send(data: unknown): this {\n this.reply.send(data)\n return this\n }\n type(contentType: string): this {\n this.reply.type(contentType)\n return this\n }\n getHeader(name: string): unknown {\n return this.reply.getHeader(name)\n }\n setHeader(name: string, value: unknown): this {\n // Replace, as node's `res.setHeader` and the web driver do. Fastify's\n // `header()` appends for `set-cookie`, so `setCookie()` — which passes the\n // whole list each time — sent the first cookie twice.\n this.reply.removeHeader(name)\n this.reply.header(name, value)\n return this\n }\n render(): never {\n throw new Error('ctx.render() is not supported on the Fastify runtime (no view engine).')\n }\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n // Streaming / SSE: take over the raw socket so Fastify doesn't try to\n // serialize a reply we're writing by hand.\n this.reply.hijack()\n this.reply.raw.writeHead(statusCode, headers)\n return this\n }\n flushHeaders(): this {\n ;(this.reply.raw as ServerResponse & { flushHeaders?: () => void }).flushHeaders?.()\n return this\n }\n write(chunk: unknown): boolean {\n return this.reply.raw.write(chunk as never)\n }\n end(data?: unknown): this {\n // After writeHead (streaming, SSE) the reply is hijacked and the raw\n // socket is ours to finish. Otherwise finish through the reply, so the\n // status and headers set on it are sent — `ctx.redirect()` writes its\n // Location with setHeader() and then calls end().\n if (this.reply.raw.headersSent) this.reply.raw.end(data as never)\n else this.reply.send(data ?? '')\n return this\n }\n once(event: string, listener: (...args: unknown[]) => void): this {\n this.reply.raw.once(event, listener)\n return this\n }\n get headersSent(): boolean {\n return this.reply.sent || this.reply.raw.headersSent\n }\n}\n\nfunction replyDriver(reply: FastifyReplyLike): RuntimeResponse {\n return new FastifyReplyDriver(reply) as unknown as RuntimeResponse\n}\n\n/** Build the Fastify per-route handler that runs the kickjs pipeline. */\nfunction routeHandler(entry: RouteEntry): FastifyHandler {\n // Validation middleware is built ONCE per route (parity with the Express\n // materializer) — `validate()` constructs a fresh closure, so calling it\n // per request was pure allocation waste.\n const validator = entry.meta.validation\n ? validate(entry.meta.validation, { validationError: entry.validationError })\n : undefined\n return async (request, reply) => {\n // Fastify runs the route handler OUTSIDE the connect-middleware chain, so\n // (unlike Express) the requestScopeMiddleware ALS frame isn't active here.\n // Establish it around the pipeline so REQUEST-scoped DI, contributors, and\n // ctx.set/get work. Reuse the inbound x-request-id, or the id a connect\n // middleware (requestId / requestScope, run earlier via middie) already\n // stamped on the raw request, before generating a fresh one.\n // Use the raw node request as `ctx.req`: it natively provides the stream\n // events (`on('close')` / `once`) that SSE and `ctx.signal` need — Fastify's\n // request object doesn't. Copy Fastify's parsed body/params/query onto it so\n // `ctx.body` / `ctx.params` / `ctx.query` keep working.\n const raw = request.raw as IncomingMessage & {\n requestId?: string\n body?: unknown\n params?: unknown\n query?: unknown\n file?: unknown\n files?: unknown\n }\n raw.body = request.body\n raw.params = request.params\n raw.query = request.query\n\n // @FileUpload: buffer multipart parts into the multer-shaped file(s) that\n // `ctx.file` / `ctx.files` expose. Fastify doesn't parse multipart natively\n // — @fastify/multipart (registered in nodeHandler when any route needs it)\n // provides `request.parts()`. Non-file fields are merged onto `raw.body` so\n // validation / `ctx.body` see them, matching multer's req.body behavior.\n if (entry.meta.upload && entry.meta.upload.mode !== 'none') {\n if (typeof request.parts !== 'function') {\n throw new Error(\n \"@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.\\n\" +\n 'Install it as a peer dependency: pnpm add @fastify/multipart.',\n )\n }\n const rawParts: RawUploadPart[] = []\n const fields: Record<string, unknown> = {}\n for await (const part of request.parts()) {\n if (part.type === 'file' && part.toBuffer) {\n rawParts.push({\n fieldname: part.fieldname,\n filename: part.filename ?? '',\n mimetype: part.mimetype ?? 'application/octet-stream',\n buffer: await part.toBuffer(),\n })\n } else {\n fields[part.fieldname] = part.value\n }\n }\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload)\n raw.file = file\n raw.files = files\n raw.body = { ...(raw.body as Record<string, unknown> | undefined), ...fields }\n }\n\n const headerId = raw.headers['x-request-id']\n // An id already assigned (requestId() middleware) wins over the header,\n // as on Express and h3.\n const requestId = raw.requestId || (Array.isArray(headerId) ? headerId[0] : headerId)\n const store = createRequestStore(requestId)\n // Propagate the resolved id back onto the raw request so anything reading\n // `req.requestId` inside the frame (e.g. request-logger) matches the store\n // and the X-Request-Id response header — parity with Express.\n raw.requestId = store.requestId\n if (!reply.getHeader('x-request-id')) reply.header('x-request-id', store.requestId)\n\n // @PreDestroy teardown for REQUEST-scoped instances once the response\n // closes (finished or aborted) — parity with requestScopeMiddleware.\n reply.raw.once('close', () => disposeRequestStore(store))\n\n await requestStore.run(store, async () => {\n publishMatchedRoute(raw, entry)\n const ctx = new RequestContext(raw as never, reply as never, NOOP_NEXT, replyDriver(reply))\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (reply.sent) return\n }\n\n // Validation (from @Get(path, schema) / route.validation). `validator` is a\n // connect-style middleware built once at route registration; it mutates\n // req.body/query/params to the parsed value and calls next(err) on failure\n // — it never touches `res`, so it runs cleanly here. A rejection\n // propagates to the error handler (422).\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(raw as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n // Class + method middleware — `(ctx, next)`; await each, stop if it ended\n // the response or called next(err).\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || reply.sent) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (reply.sent) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // Nothing written and nothing returned falls through to the 404 handler,\n // as on Express and h3 — not Fastify's own empty 200.\n if (!reply.sent && !(await applyHandlerResult(ctx, result))) reply.callNotFound()\n })\n }\n}\n\n/** Express's `trust proxy` number: trust the first `hops` addresses from the socket. */\nfunction hopTrust(hops: number): (ip: string, hopIndex: number) => boolean {\n return (_ip, hopIndex) => hopIndex < hops\n}\n\n/**\n * The Fastify HTTP runtime. Pass to `bootstrap({ runtime: fastifyRuntime() })`.\n * Per spec §10: Fastify's built-in pino logger is disabled (`logger: false`) so\n * the kickjs `requestLogger` middleware stays the single log format.\n */\nexport function fastifyRuntime(): HttpRuntime<FastifyAppLike> {\n return {\n name: 'fastify',\n\n createApp(options: RuntimeAppOptions = {}): FastifyAppLike {\n const Fastify = loadPeer('fastify')\n const app = Fastify({\n logger: false,\n // Match Express / h3 routing leniency: `/api/v1/hello` and\n // `/api/v1/hello/` resolve to the same route. Without this, Fastify's\n // strict router 404s a trailing-slash request — e.g. a controller's\n // root `@Get('/')` (mounted at the prefix) misses `${prefix}/`. Set under\n // `routerOptions` (Fastify 5+; top-level `ignoreTrailingSlash` is\n // deprecated, removed in Fastify 6).\n routerOptions: { ignoreTrailingSlash: true },\n // `jsonLimit`, which Fastify otherwise ignores in favour of its own 1 MiB.\n ...(options.bodyLimit !== undefined ? { bodyLimit: options.bodyLimit } : {}),\n // Express semantics for every form. Fastify takes a predicate as-is,\n // but reads a hop count as \"trust nothing\", where Express trusts that\n // many hops from the socket.\n trustProxy:\n typeof options.trustProxy === 'number'\n ? hopTrust(options.trustProxy)\n : options.trustProxy,\n }) as FastifyAppLike & {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n }\n app[QUEUE] = []\n\n // Fastify ships parsers for `application/json` and `text/plain` only, and\n // answers 415 for everything else. That made a form post work on Express\n // and h3 but fail on Fastify alone (#590). Register the rest of the\n // framework's supported set so all engines agree.\n //\n // Deliberately NOT a `'*'` catch-all: that would swallow multipart, and\n // `@fastify/multipart` is itself the multipart content-type parser,\n // registered conditionally in `nodeHandler` when a route needs it.\n const addParser = app.addContentTypeParser?.bind(app)\n if (addParser) {\n // `application/*+json` — RFC 6838 §4.2.8 guarantees the bytes are JSON.\n addParser(\n /^application\\/[\\w.+-]+\\+json$/,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n if (body === '') return done(null, undefined)\n try {\n done(null, JSON.parse(body as string))\n } catch (err) {\n // A bare SyntaxError carries no status, so the shared error handler\n // would call it a 500 — Fastify's own JSON parser answers 400\n // (FST_ERR_CTP_INVALID_JSON_BODY), and so must this one.\n done(\n HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n ),\n undefined,\n )\n }\n },\n )\n addParser(\n 'application/x-www-form-urlencoded',\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, parseForm(body as string))\n },\n )\n // `text/*` beyond Fastify's built-in `text/plain`. Raw string, never\n // JSON: `text/plain` is CORS-safelisted, so parsing it as JSON would\n // re-open no-preflight CSRF against a JSON API.\n addParser(\n /^text\\//,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, body)\n },\n )\n // Fastify already answers 415 for a type it has no parser for, but with\n // its own message and no `Accept`. `'*'` is Fastify's documented\n // fallback — consulted only when nothing more specific matches — so it\n // does not shadow the parsers above, nor `@fastify/multipart`, which\n // registers `multipart/form-data` when an upload route needs it.\n addParser(\n '*',\n { parseAs: 'string' },\n (req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n // No body is not an unsupported body. Fastify calls the parser even\n // for an empty payload, so without this a bodyless POST carrying an\n // unrelated content type would be rejected.\n if (!body) return done(null, undefined)\n done(unsupportedMediaTypeError(req.headers?.['content-type']), undefined)\n },\n )\n }\n\n if (options.notFoundFallthrough === false) {\n ;(app as { [NO_FALLTHROUGH]?: boolean })[NO_FALLTHROUGH] = true\n }\n return app\n },\n\n nodeHandler(app) {\n // Register middie + queued connect middleware + finalize `ready()` exactly\n // ONCE per app, even though Application may call nodeHandler per request.\n const state = app as {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n [READY]?: Promise<void>\n [NEEDS_MULTIPART]?: boolean\n }\n if (!state[READY]) {\n state[READY] = (async () => {\n // Register @fastify/multipart first when any route uses @FileUpload so\n // `request.parts()` is available. Our applyUploadConfig enforces the\n // real per-file maxSize, so give the plugin a generous fileSize ceiling\n // (its 1MB default would silently truncate larger uploads first).\n if (state[NEEDS_MULTIPART]) {\n const multipart = loadPeer('@fastify/multipart')\n await app.register(multipart, { limits: { fileSize: Number.MAX_SAFE_INTEGER } })\n }\n const middie = loadPeer('@fastify/middie')\n await app.register(middie)\n for (const { mw, opts } of state[QUEUE] ?? []) {\n if (opts?.path !== undefined)\n (app.use as (p: unknown, m: unknown) => void)(opts.path, mw)\n else (app.use as (m: unknown) => void)(mw)\n }\n await app.ready()\n })()\n }\n const readyP = state[READY]\n // Once ready, route synchronously — no promise hop per request.\n let ready = false\n readyP.then(\n () => (ready = true),\n () => {},\n )\n\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n if (ready) {\n app.routing(req, res)\n return\n }\n readyP\n .then(() => app.routing(req, res))\n .catch((err) => {\n if (next) next(err)\n })\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n if (entry.meta.upload) (app as { [NEEDS_MULTIPART]?: boolean })[NEEDS_MULTIPART] = true\n const url = joinPath(mountPath, entry.path)\n app.route({ method: entry.method, url, handler: routeHandler(entry) })\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n const queue = (\n app as { [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }> }\n )[QUEUE]\n queue?.push({ mw, opts })\n },\n\n serveStatic(app, prefix, dir) {\n // Serve via `serve-static` (the standalone connect middleware behind\n // express.static) so the Fastify runtime carries no `express` dependency —\n // queued like any other connect middleware, bridged through middie.\n const serveStatic = loadPeer('serve-static')\n this.useConnect(app, serveStatic(dir) as ConnectMiddleware, { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n app.setNotFoundHandler((request, reply) => {\n const next = (request.raw as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT]\n if (next && !(app as { [NO_FALLTHROUGH]?: boolean })[NO_FALLTHROUGH]) {\n // Vite dev fall-through: hand the request back to the outer chain.\n reply.hijack()\n next()\n return\n }\n // Pass the reply DRIVER (not raw res) so the connect-style\n // notFoundHandler's `res.status().json()` lands on the Fastify reply.\n settleOrFail(\n reply,\n (mw as (req: unknown, res: unknown, next: () => void) => unknown)(\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n ),\n )\n })\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n app.setErrorHandler((err, request, reply) => {\n // Reply driver (not raw res) so the connect-style errorHandler's\n // `res.status().json()` / `setHeader` land on the Fastify reply.\n settleOrFail(\n reply,\n (mw as (e: unknown, req: unknown, res: unknown, next: () => void) => unknown)(\n err,\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n ),\n )\n })\n },\n\n close(app) {\n // Runs the instance's onClose hooks (plugins registered on it).\n return app.close()\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n http2: true,\n },\n }\n}\n\n/**\n * The Fastify runtime's engine-native types — what the runtime-typed escape\n * hatches resolve to once the `kick/runtime` typegen emits a `KickRuntimeRegister`\n * augmentation pointing here (spec §4.3b). `AdapterContext.app` / `getRuntimeApp()`\n * become `FastifyInstance`; `ctx.req` / `ctx.res` the Fastify request / reply.\n * Mirrors {@link import('../runtime').ExpressRuntimeTypes} for the default engine.\n */\nexport interface FastifyRuntimeTypes {\n request: import('fastify').FastifyRequest\n response: import('fastify').FastifyReply\n app: import('fastify').FastifyInstance\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n // A root route path ('/' or '') maps to the mount prefix itself — otherwise a\n // controller `@Post('/')` would register at `${prefix}/`, and a request to\n // `${prefix}` (no trailing slash) wouldn't match under Fastify's strict router.\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;sgBAwCA,MAAM,YAAc,cAAc,YAAY,GAAG,EAC3C,SAAY,MAAsB,CACtC,IAAM,IAAM,YAAY,IAAI,EAC5B,OAAO,KAAO,IAAI,YAAc,IAAI,QAAU,IAAI,QAAW,IAAI,SAAW,GAC9E,EA+DM,MAAQ,OAAO,6BAA6B,EAC5C,MAAQ,OAAO,sBAAsB,EACrC,KAAO,OAAO,qBAAqB,EAGnC,gBAAkB,OAAO,+BAA+B,EACxD,cAAwB,CAAC,EAM/B,SAAS,aAAa,MAAyB,SAAyB,CAClE,OAAQ,UAA4C,MAAS,YACjE,QAAQ,QAAQ,QAAQ,CAAC,CAAC,KAAK,IAAA,OAAiB,CAC1C,CAAC,MAAM,MAAQ,CAAC,MAAM,IAAI,aAE5B,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,CAAE,QAAS,uBAAwB,CAAC,CAE7D,CAAC,CACH,CAEA,MAAM,eAAiB,OAAO,8BAA8B,EAiB5D,IAAM,mBAAN,KAAoD,CACrB,MAA7B,YAAY,MAA0C,CAAzB,KAAA,MAAA,KAA0B,CACvD,OAAO,KAAoB,CAEzB,OADA,KAAK,MAAM,KAAK,IAAI,EACb,IACT,CACA,KAAK,KAAqB,CAKxB,OAFK,KAAK,MAAM,UAAU,cAAc,GAAG,KAAK,MAAM,KAAK,iCAAiC,EAC5F,KAAK,MAAM,WAAW,aAAa,CAAC,CAAC,KAAK,IAAI,EACvC,IACT,CACA,KAAK,KAAqB,CAExB,OADA,KAAK,MAAM,KAAK,IAAI,EACb,IACT,CACA,KAAK,YAA2B,CAE9B,OADA,KAAK,MAAM,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S,aAAa,KAAK,CAAE,CAAC,CACvE,CAEJ,EAEA,WAAW,IAAK,GAAuB,KAA0B,CAI/D,IADE,MACG,EAAE,KAAK,CAAE,GAAI,IAAK,CAAC,CAC1B,EAEA,YAAY,IAAK,OAAQ,IAAK,CAI5B,IAAM,YAAc,SAAS,cAAc,EAC3C,KAAK,WAAW,IAAK,YAAY,GAAG,EAAwB,CAAE,KAAM,MAAO,CAAC,CAC9E,EAEA,YAAY,IAAK,GAAuB,CACtC,IAAI,oBAAoB,QAAS,QAAU,CACzC,IAAM,KAAQ,QAAQ,IAA+D,MACjF,MAAQ,CAAE,IAAuC,iBAEnD,MAAM,OAAO,EACb,KAAK,GAKP,aACE,MACC,GACC,QAAQ,IACR,YAAY,KAAK,EACjB,SACF,CACF,CACF,CAAC,CACH,EAEA,gBAAgB,IAAK,GAAuB,CAC1C,IAAI,iBAAiB,IAAK,QAAS,QAAU,CAG3C,aACE,MACC,GACC,IACA,QAAQ,IACR,YAAY,KAAK,EACjB,SACF,CACF,CACF,CAAC,CACH,EAEA,MAAM,IAAK,CAET,OAAO,IAAI,MAAM,CACnB,EAEA,aAAc,CACZ,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,GACnB,MAAO,EACT,CACF,CACF,CAgBA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAM7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C"}
1
+ {"version":3,"file":"fastify.mjs","names":[],"sources":["../../../src/http/runtimes/fastify.ts"],"sourcesContent":["// The Fastify runtime — `@forinda/kickjs/fastify`.\n//\n// Implements the same HttpRuntime contract as expressRuntime, over Fastify 5.\n// KickJS still owns decorators → RouteTable, the contributor pipeline, and the\n// RequestContext surface; this runtime materializes routes as NATIVE Fastify\n// routes and wraps `reply` in a RuntimeResponse so `ctx.json` / `ctx.html` /\n// `ctx.sse` work unchanged.\n//\n// `fastify`, `@fastify/middie` are optional peers — install them alongside\n// `@forinda/kickjs` to use this subpath.\n//\n// Lifecycle note: Fastify registration (`register` / `use` / `route`) is\n// deferred until `ready()`. Connect middleware needs `@fastify/middie`\n// registered first, so `useConnect` only QUEUES middleware; `nodeHandler`\n// registers middie, then the queued middleware, then awaits `ready()`.\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport Fastify from 'fastify'\n\nimport { HttpException } from '../../core/errors'\nimport { parseForm, unsupportedMediaTypeError } from '../body-policy'\nimport { RequestContext } from '../context'\nimport { publishMatchedRoute, stringifyJson } from '../runtime'\nimport { applyHandlerResult } from '../reply'\nimport { requestStore } from '../request-store'\nimport { createRequestStore, disposeRequestStore } from '../middleware/request-scope'\nimport { validate } from '../middleware/validate'\nimport { applyUploadConfig, type RawUploadPart } from '../middleware/upload'\nimport { lazyServeStatic } from './lazy-serve-static'\nimport { createLogger } from '../../core/logger'\nimport type {\n ConnectMiddleware,\n HttpRuntime,\n RouteEntry,\n RouteTable,\n RuntimeAppOptions,\n RuntimeResponse,\n UseConnectOptions,\n} from '../runtime'\n\n// The peers load through `import`, never `createRequire`: a bundler follows an\n// import, so `kick build:netlify|vercel` inlines them into the function. A\n// computed require is left for the platform to resolve, and the function has\n// no node_modules. `fastify` is static (this entry is the Fastify runtime);\n// the plugins are imported when first needed.\nconst pluginOf = (mod: { default?: unknown }): any => mod.default ?? mod\n// Typed structurally below (FastifyAppLike), as when this was required untyped.\nconst createFastify = Fastify as unknown as (options: object) => unknown\nconst log = createLogger('FastifyRuntime')\n\n// Minimal structural surface we use from Fastify — avoids a hard type dep so\n// the root package never needs `fastify` installed to typecheck.\ninterface FastifyReplyLike {\n code(statusCode: number): FastifyReplyLike\n send(payload?: unknown): FastifyReplyLike\n header(name: string, value: unknown): FastifyReplyLike\n removeHeader(name: string): FastifyReplyLike\n type(contentType: string): FastifyReplyLike\n serializer(fn: (payload: unknown) => string): FastifyReplyLike\n getHeader(name: string): unknown\n hijack(): void\n /** Hand the request to the not-found handler (Fastify 5). */\n callNotFound(): void\n readonly sent: boolean\n readonly raw: ServerResponse\n}\ninterface FastifyRequestLike {\n raw: IncomingMessage\n body?: unknown\n params?: unknown\n query?: unknown\n /** Request headers, as Fastify normalises them (lowercased keys). */\n headers?: Record<string, string | string[] | undefined>\n /** Present once @fastify/multipart is registered — async iterator of parts. */\n parts?: () => AsyncIterableIterator<MultipartPart>\n isMultipart?: () => boolean\n}\ntype FastifyHandler = (request: FastifyRequestLike, reply: FastifyReplyLike) => void | Promise<void>\ninterface FastifyAppLike {\n close(): Promise<void>\n register(plugin: unknown, opts?: unknown): Promise<void> | FastifyAppLike\n use(path: unknown, mw?: unknown): unknown\n route(opts: { method: string; url: string; handler: FastifyHandler }): unknown\n setNotFoundHandler(handler: FastifyHandler): unknown\n setErrorHandler(\n handler: (err: unknown, req: FastifyRequestLike, reply: FastifyReplyLike) => void,\n ): unknown\n ready(): Promise<void>\n routing(req: IncomingMessage, res: ServerResponse): void\n /**\n * Fastify's content-type parser registry. Typed here rather than reached for\n * with a cast so the callback shape is checked at the call site — these\n * parsers decide what `ctx.body` is on this runtime.\n */\n addContentTypeParser?(\n matcher: string | RegExp | string[],\n opts: { parseAs: 'string' | 'buffer' },\n parser: FastifyBodyParser,\n ): unknown\n}\n\n/** The `done` callback a Fastify content-type parser calls. */\ntype FastifyParserDone = (err: Error | null, body?: unknown) => void\n\n/** `done`-style callback Fastify hands a content-type parser. */\ntype FastifyBodyParser = (\n req: FastifyRequestLike,\n body: string | Buffer,\n done: (err: Error | null, body?: unknown) => void,\n) => void\n\nconst QUEUE = Symbol('kickjs.fastify.connectQueue')\nconst READY = Symbol('kickjs.fastify.ready')\nconst NEXT = Symbol('kickjs.fastify.next')\n// Set during mountRoutes when any route carries @FileUpload metadata, so\n// nodeHandler knows to register @fastify/multipart before ready().\nconst NEEDS_MULTIPART = Symbol('kickjs.fastify.needsMultipart')\nconst NOOP_NEXT = (): void => {}\n\n/**\n * An async error / not-found handler that rejects never answers; answer 500\n * so the request ends instead of hanging until the client gives up.\n */\nfunction settleOrFail(reply: FastifyReplyLike, returned: unknown): void {\n if (typeof (returned as PromiseLike<void> | undefined)?.then !== 'function') return\n Promise.resolve(returned).then(undefined, () => {\n if (!reply.sent && !reply.raw.headersSent) {\n // The 500 body every engine's built-in error handler starts from.\n reply.code(500).send({ message: 'Internal Server Error' })\n }\n })\n}\n/** `notFoundFallthrough: false` — answer unmatched requests instead of handing them back. */\nconst NO_FALLTHROUGH = Symbol('kickjs.fastify.noFallthrough')\n\n// A @fastify/multipart part as we consume it from `request.parts()`.\ninterface MultipartPart {\n type: 'file' | 'field'\n fieldname: string\n filename?: string\n mimetype?: string\n value?: unknown\n toBuffer?: () => Promise<Buffer>\n}\n\n/**\n * Wrap a Fastify reply so the RequestContext response helpers drive it.\n * A class so the ~12 driver methods live on a shared prototype — the previous\n * object-literal version re-allocated every method closure on each request.\n */\nclass FastifyReplyDriver implements RuntimeResponse {\n constructor(private readonly reply: FastifyReplyLike) {}\n status(code: number): this {\n this.reply.code(code)\n return this\n }\n json(data: unknown): this {\n // A custom serializer drops Fastify's default content-type; keep one the\n // caller chose (`application/problem+json`).\n if (!this.reply.getHeader('content-type')) this.reply.type('application/json; charset=utf-8')\n this.reply.serializer(stringifyJson).send(data)\n return this\n }\n send(data: unknown): this {\n this.reply.send(data)\n return this\n }\n type(contentType: string): this {\n this.reply.type(contentType)\n return this\n }\n getHeader(name: string): unknown {\n return this.reply.getHeader(name)\n }\n setHeader(name: string, value: unknown): this {\n // Replace, as node's `res.setHeader` and the web driver do. Fastify's\n // `header()` appends for `set-cookie`, so `setCookie()` — which passes the\n // whole list each time — sent the first cookie twice.\n this.reply.removeHeader(name)\n this.reply.header(name, value)\n return this\n }\n render(): never {\n throw new Error('ctx.render() is not supported on the Fastify runtime (no view engine).')\n }\n writeHead(statusCode: number, headers?: Record<string, string | number | string[]>): this {\n // Streaming / SSE: take over the raw socket so Fastify doesn't try to\n // serialize a reply we're writing by hand.\n this.reply.hijack()\n this.reply.raw.writeHead(statusCode, headers)\n return this\n }\n flushHeaders(): this {\n ;(this.reply.raw as ServerResponse & { flushHeaders?: () => void }).flushHeaders?.()\n return this\n }\n write(chunk: unknown): boolean {\n return this.reply.raw.write(chunk as never)\n }\n end(data?: unknown): this {\n // After writeHead (streaming, SSE) the reply is hijacked and the raw\n // socket is ours to finish. Otherwise finish through the reply, so the\n // status and headers set on it are sent — `ctx.redirect()` writes its\n // Location with setHeader() and then calls end().\n if (this.reply.raw.headersSent) this.reply.raw.end(data as never)\n else this.reply.send(data ?? '')\n return this\n }\n once(event: string, listener: (...args: unknown[]) => void): this {\n this.reply.raw.once(event, listener)\n return this\n }\n get headersSent(): boolean {\n return this.reply.sent || this.reply.raw.headersSent\n }\n}\n\nfunction replyDriver(reply: FastifyReplyLike): RuntimeResponse {\n return new FastifyReplyDriver(reply) as unknown as RuntimeResponse\n}\n\n/** Build the Fastify per-route handler that runs the kickjs pipeline. */\nfunction routeHandler(entry: RouteEntry): FastifyHandler {\n // Validation middleware is built ONCE per route (parity with the Express\n // materializer) — `validate()` constructs a fresh closure, so calling it\n // per request was pure allocation waste.\n const validator = entry.meta.validation\n ? validate(entry.meta.validation, { validationError: entry.validationError })\n : undefined\n return async (request, reply) => {\n // Fastify runs the route handler OUTSIDE the connect-middleware chain, so\n // (unlike Express) the requestScopeMiddleware ALS frame isn't active here.\n // Establish it around the pipeline so REQUEST-scoped DI, contributors, and\n // ctx.set/get work. Reuse the inbound x-request-id, or the id a connect\n // middleware (requestId / requestScope, run earlier via middie) already\n // stamped on the raw request, before generating a fresh one.\n // Use the raw node request as `ctx.req`: it natively provides the stream\n // events (`on('close')` / `once`) that SSE and `ctx.signal` need — Fastify's\n // request object doesn't. Copy Fastify's parsed body/params/query onto it so\n // `ctx.body` / `ctx.params` / `ctx.query` keep working.\n const raw = request.raw as IncomingMessage & {\n requestId?: string\n body?: unknown\n params?: unknown\n query?: unknown\n file?: unknown\n files?: unknown\n }\n raw.body = request.body\n raw.params = request.params\n raw.query = request.query\n\n // @FileUpload: buffer multipart parts into the multer-shaped file(s) that\n // `ctx.file` / `ctx.files` expose. Fastify doesn't parse multipart natively\n // — @fastify/multipart (registered in nodeHandler when any route needs it)\n // provides `request.parts()`. Non-file fields are merged onto `raw.body` so\n // validation / `ctx.body` see them, matching multer's req.body behavior.\n if (entry.meta.upload && entry.meta.upload.mode !== 'none') {\n if (typeof request.parts !== 'function') {\n throw new Error(\n \"@forinda/kickjs: @FileUpload on the Fastify runtime requires '@fastify/multipart'.\\n\" +\n 'Install it as a peer dependency: pnpm add @fastify/multipart.',\n )\n }\n const rawParts: RawUploadPart[] = []\n const fields: Record<string, unknown> = {}\n for await (const part of request.parts()) {\n if (part.type === 'file' && part.toBuffer) {\n rawParts.push({\n fieldname: part.fieldname,\n filename: part.filename ?? '',\n mimetype: part.mimetype ?? 'application/octet-stream',\n buffer: await part.toBuffer(),\n })\n } else {\n fields[part.fieldname] = part.value\n }\n }\n const { file, files } = applyUploadConfig(rawParts, entry.meta.upload)\n raw.file = file\n raw.files = files\n raw.body = { ...(raw.body as Record<string, unknown> | undefined), ...fields }\n }\n\n const headerId = raw.headers['x-request-id']\n // An id already assigned (requestId() middleware) wins over the header,\n // as on Express and h3.\n const requestId = raw.requestId || (Array.isArray(headerId) ? headerId[0] : headerId)\n const store = createRequestStore(requestId)\n // Propagate the resolved id back onto the raw request so anything reading\n // `req.requestId` inside the frame (e.g. request-logger) matches the store\n // and the X-Request-Id response header — parity with Express.\n raw.requestId = store.requestId\n if (!reply.getHeader('x-request-id')) reply.header('x-request-id', store.requestId)\n\n // @PreDestroy teardown for REQUEST-scoped instances once the response\n // closes (finished or aborted) — parity with requestScopeMiddleware.\n reply.raw.once('close', () => disposeRequestStore(store))\n\n await requestStore.run(store, async () => {\n publishMatchedRoute(raw, entry)\n const ctx = new RequestContext(raw as never, reply as never, NOOP_NEXT, replyDriver(reply))\n\n // `beforeValidation` contributors (#677) — ahead of validation and middleware.\n if (entry.earlyContributorRunner) {\n await entry.earlyContributorRunner(ctx)\n if (reply.sent) return\n }\n\n // Validation (from @Get(path, schema) / route.validation). `validator` is a\n // connect-style middleware built once at route registration; it mutates\n // req.body/query/params to the parsed value and calls next(err) on failure\n // — it never touches `res`, so it runs cleanly here. A rejection\n // propagates to the error handler (422).\n if (validator) {\n await new Promise<void>((resolve, reject) => {\n validator(raw as never, undefined as never, (err?: unknown) =>\n err ? reject(err) : resolve(),\n )\n })\n }\n\n // Class + method middleware — `(ctx, next)`; await each, stop if it ended\n // the response or called next(err).\n for (const mw of entry.middlewares) {\n let advanced = false\n await new Promise<void>((resolve, reject) => {\n const next = (err?: unknown): void => {\n advanced = true\n if (err) reject(err)\n else resolve()\n }\n Promise.resolve(mw(ctx, next)).catch(reject)\n })\n if (!advanced || reply.sent) return\n }\n\n if (entry.contributorRunner) await entry.contributorRunner(ctx)\n if (reply.sent) return\n const result = await entry.handler(ctx)\n // Return-value handlers (reply.ts): auto-send when nothing was written.\n // Nothing written and nothing returned falls through to the 404 handler,\n // as on Express and h3 — not Fastify's own empty 200.\n if (!reply.sent && !(await applyHandlerResult(ctx, result))) reply.callNotFound()\n })\n }\n}\n\n/** Express's `trust proxy` number: trust the first `hops` addresses from the socket. */\nfunction hopTrust(hops: number): (ip: string, hopIndex: number) => boolean {\n return (_ip, hopIndex) => hopIndex < hops\n}\n\n/**\n * The Fastify HTTP runtime. Pass to `bootstrap({ runtime: fastifyRuntime() })`.\n * Per spec §10: Fastify's built-in pino logger is disabled (`logger: false`) so\n * the kickjs `requestLogger` middleware stays the single log format.\n */\nexport function fastifyRuntime(): HttpRuntime<FastifyAppLike> {\n return {\n name: 'fastify',\n\n createApp(options: RuntimeAppOptions = {}): FastifyAppLike {\n const app = createFastify({\n logger: false,\n // Match Express / h3 routing leniency: `/api/v1/hello` and\n // `/api/v1/hello/` resolve to the same route. Without this, Fastify's\n // strict router 404s a trailing-slash request — e.g. a controller's\n // root `@Get('/')` (mounted at the prefix) misses `${prefix}/`. Set under\n // `routerOptions` (Fastify 5+; top-level `ignoreTrailingSlash` is\n // deprecated, removed in Fastify 6).\n routerOptions: { ignoreTrailingSlash: true },\n // `jsonLimit`, which Fastify otherwise ignores in favour of its own 1 MiB.\n ...(options.bodyLimit !== undefined ? { bodyLimit: options.bodyLimit } : {}),\n // Express semantics for every form. Fastify takes a predicate as-is,\n // but reads a hop count as \"trust nothing\", where Express trusts that\n // many hops from the socket.\n trustProxy:\n typeof options.trustProxy === 'number'\n ? hopTrust(options.trustProxy)\n : options.trustProxy,\n }) as FastifyAppLike & {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n }\n app[QUEUE] = []\n\n // Fastify ships parsers for `application/json` and `text/plain` only, and\n // answers 415 for everything else. That made a form post work on Express\n // and h3 but fail on Fastify alone (#590). Register the rest of the\n // framework's supported set so all engines agree.\n //\n // Deliberately NOT a `'*'` catch-all: that would swallow multipart, and\n // `@fastify/multipart` is itself the multipart content-type parser,\n // registered conditionally in `nodeHandler` when a route needs it.\n const addParser = app.addContentTypeParser?.bind(app)\n if (addParser) {\n // `application/*+json` — RFC 6838 §4.2.8 guarantees the bytes are JSON.\n addParser(\n /^application\\/[\\w.+-]+\\+json$/,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n if (body === '') return done(null, undefined)\n try {\n done(null, JSON.parse(body as string))\n } catch (err) {\n // A bare SyntaxError carries no status, so the shared error handler\n // would call it a 500 — Fastify's own JSON parser answers 400\n // (FST_ERR_CTP_INVALID_JSON_BODY), and so must this one.\n done(\n HttpException.badRequest(\n err instanceof Error ? err.message : 'Request body could not be parsed',\n ),\n undefined,\n )\n }\n },\n )\n addParser(\n 'application/x-www-form-urlencoded',\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, parseForm(body as string))\n },\n )\n // `text/*` beyond Fastify's built-in `text/plain`. Raw string, never\n // JSON: `text/plain` is CORS-safelisted, so parsing it as JSON would\n // re-open no-preflight CSRF against a JSON API.\n addParser(\n /^text\\//,\n { parseAs: 'string' },\n (_req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n done(null, body)\n },\n )\n // Fastify already answers 415 for a type it has no parser for, but with\n // its own message and no `Accept`. `'*'` is Fastify's documented\n // fallback — consulted only when nothing more specific matches — so it\n // does not shadow the parsers above, nor `@fastify/multipart`, which\n // registers `multipart/form-data` when an upload route needs it.\n addParser(\n '*',\n { parseAs: 'string' },\n (req: FastifyRequestLike, body: string | Buffer, done: FastifyParserDone) => {\n // No body is not an unsupported body. Fastify calls the parser even\n // for an empty payload, so without this a bodyless POST carrying an\n // unrelated content type would be rejected.\n if (!body) return done(null, undefined)\n done(unsupportedMediaTypeError(req.headers?.['content-type']), undefined)\n },\n )\n }\n\n if (options.notFoundFallthrough === false) {\n ;(app as { [NO_FALLTHROUGH]?: boolean })[NO_FALLTHROUGH] = true\n }\n return app\n },\n\n nodeHandler(app) {\n // Register middie + queued connect middleware + finalize `ready()` exactly\n // ONCE per app, even though Application may call nodeHandler per request.\n const state = app as {\n [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }>\n [READY]?: Promise<void>\n [NEEDS_MULTIPART]?: boolean\n }\n if (!state[READY]) {\n state[READY] = (async () => {\n // Register @fastify/multipart first when any route uses @FileUpload so\n // `request.parts()` is available. Our applyUploadConfig enforces the\n // real per-file maxSize, so give the plugin a generous fileSize ceiling\n // (its 1MB default would silently truncate larger uploads first).\n if (state[NEEDS_MULTIPART]) {\n const multipart = pluginOf(await import('@fastify/multipart'))\n await app.register(multipart, { limits: { fileSize: Number.MAX_SAFE_INTEGER } })\n }\n const middie = pluginOf(await import('@fastify/middie'))\n await app.register(middie)\n for (const { mw, opts } of state[QUEUE] ?? []) {\n if (opts?.path !== undefined)\n (app.use as (p: unknown, m: unknown) => void)(opts.path, mw)\n else (app.use as (m: unknown) => void)(mw)\n }\n await app.ready()\n })()\n }\n const readyP = state[READY]\n // Once ready, route synchronously — no promise hop per request.\n let ready = false\n readyP.then(\n () => (ready = true),\n () => {},\n )\n\n return (req: IncomingMessage, res: ServerResponse, next?: (err?: unknown) => void) => {\n if (next) (req as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT] = next\n if (ready) {\n app.routing(req, res)\n return\n }\n readyP\n .then(() => app.routing(req, res))\n .catch((err) => {\n if (next) return next(err)\n // No host to hand the error to: answer rather than leave the request open.\n log.error(err, 'Fastify failed to start')\n res.statusCode = 500\n res.end('Internal Server Error')\n })\n }\n },\n\n mountRoutes(app, table: RouteTable) {\n for (const { mountPath, routes } of table) {\n for (const entry of routes) {\n if (entry.meta.upload) (app as { [NEEDS_MULTIPART]?: boolean })[NEEDS_MULTIPART] = true\n const url = joinPath(mountPath, entry.path)\n app.route({ method: entry.method, url, handler: routeHandler(entry) })\n }\n }\n },\n\n useConnect(app, mw: ConnectMiddleware, opts?: UseConnectOptions) {\n const queue = (\n app as { [QUEUE]?: Array<{ mw: ConnectMiddleware; opts?: UseConnectOptions }> }\n )[QUEUE]\n queue?.push({ mw, opts })\n },\n\n serveStatic(app, prefix, dir) {\n // Serve via `serve-static` (the standalone connect middleware behind\n // express.static) so the Fastify runtime carries no `express` dependency —\n // queued like any other connect middleware, bridged through middie.\n this.useConnect(app, lazyServeStatic(dir), { path: prefix })\n },\n\n setNotFound(app, mw: ConnectMiddleware) {\n app.setNotFoundHandler((request, reply) => {\n const next = (request.raw as IncomingMessage & { [NEXT]?: (err?: unknown) => void })[NEXT]\n if (next && !(app as { [NO_FALLTHROUGH]?: boolean })[NO_FALLTHROUGH]) {\n // Vite dev fall-through: hand the request back to the outer chain.\n reply.hijack()\n next()\n return\n }\n // Pass the reply DRIVER (not raw res) so the connect-style\n // notFoundHandler's `res.status().json()` lands on the Fastify reply.\n settleOrFail(\n reply,\n (mw as (req: unknown, res: unknown, next: () => void) => unknown)(\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n ),\n )\n })\n },\n\n setErrorHandler(app, mw: ConnectMiddleware) {\n app.setErrorHandler((err, request, reply) => {\n // Reply driver (not raw res) so the connect-style errorHandler's\n // `res.status().json()` / `setHeader` land on the Fastify reply.\n settleOrFail(\n reply,\n (mw as (e: unknown, req: unknown, res: unknown, next: () => void) => unknown)(\n err,\n request.raw,\n replyDriver(reply),\n NOOP_NEXT,\n ),\n )\n })\n },\n\n close(app) {\n // Runs the instance's onClose hooks (plugins registered on it).\n return app.close()\n },\n\n capabilities: {\n render: false,\n uploads: true,\n connectMiddleware: true,\n nativeBodyParsing: true,\n http2: true,\n },\n }\n}\n\n/**\n * The Fastify runtime's engine-native types — what the runtime-typed escape\n * hatches resolve to once the `kick/runtime` typegen emits a `KickRuntimeRegister`\n * augmentation pointing here (spec §4.3b). `AdapterContext.app` / `getRuntimeApp()`\n * become `FastifyInstance`; `ctx.req` / `ctx.res` the Fastify request / reply.\n * Mirrors {@link import('../runtime').ExpressRuntimeTypes} for the default engine.\n */\nexport interface FastifyRuntimeTypes {\n request: import('fastify').FastifyRequest\n response: import('fastify').FastifyReply\n app: import('fastify').FastifyInstance\n}\n\n/** Join a mount prefix and a route path into one URL, collapsing slashes. */\nfunction joinPath(mountPath: string, path: string): string {\n const a = mountPath.endsWith('/') ? mountPath.slice(0, -1) : mountPath\n // A root route path ('/' or '') maps to the mount prefix itself — otherwise a\n // controller `@Post('/')` would register at `${prefix}/`, and a request to\n // `${prefix}` (no trailing slash) wouldn't match under Fastify's strict router.\n if (path === '/' || path === '') return a === '' ? '/' : a\n const b = path.startsWith('/') ? path : `/${path}`\n return `${a}${b}`\n}\n"],"mappings":";;;;;;;;;;mnBA6CA,MAAM,SAAY,KAAoC,IAAI,SAAW,IAE/D,cAAgB,QAChB,IAAM,aAAa,gBAAgB,EA+DnC,MAAQ,OAAO,6BAA6B,EAC5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,CAAE,IAAuC,iBAEnD,MAAM,OAAO,EACb,KAAK,GAKP,aACE,MACC,GACC,QAAQ,IACR,YAAY,KAAK,EACjB,SACF,CACF,CACF,CAAC,CACH,EAEA,gBAAgB,IAAK,GAAuB,CAC1C,IAAI,iBAAiB,IAAK,QAAS,QAAU,CAG3C,aACE,MACC,GACC,IACA,QAAQ,IACR,YAAY,KAAK,EACjB,SACF,CACF,CACF,CAAC,CACH,EAEA,MAAM,IAAK,CAET,OAAO,IAAI,MAAM,CACnB,EAEA,aAAc,CACZ,OAAQ,GACR,QAAS,GACT,kBAAmB,GACnB,kBAAmB,GACnB,MAAO,EACT,CACF,CACF,CAgBA,SAAS,SAAS,UAAmB,KAAsB,CACzD,IAAM,EAAI,UAAU,SAAS,GAAG,EAAI,UAAU,MAAM,EAAG,EAAE,EAAI,UAM7D,OAFI,OAAS,KAAO,OAAS,GAAW,IAAM,GAAK,IAAM,EAElD,GAAG,IADA,KAAK,WAAW,GAAG,EAAI,KAAO,IAAI,QAE9C"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v10.2.0
2
+ * @forinda/kickjs v10.3.1
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,5 +1,5 @@
1
1
 
2
- import { p as HttpRuntime } from "../../adapter-C5I5e_-i.mjs";
2
+ import { p as HttpRuntime } from "../../adapter-6fjmVVc2.mjs";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  //#region src/http/runtimes/h3.d.ts
5
5
  interface H3AppLike {
@@ -24,10 +24,11 @@ interface H3EventLike {
24
24
  }
25
25
  export interface H3RuntimeOptions {
26
26
  /**
27
- * Pre-imported h3 module, for when the app's `h3` is not the one this
28
- * package resolves (a linked checkout, a bundler):
27
+ * Pre-imported h3 module, for when the app's `h3` is a different copy from
28
+ * the one this package resolves (a linked checkout):
29
29
  * `h3Runtime({ h3: await import('h3') })`.
30
- * Omitted → the installed `h3` peer.
30
+ * Omitted → the installed `h3` peer. The peer must be installed either way:
31
+ * this entry imports it statically so `kick build:netlify|vercel` bundles it.
31
32
  */
32
33
  h3?: unknown;
33
34
  }
@@ -1 +1 @@
1
- {"version":3,"file":"h3.d.mts","names":[],"sources":["../../../src/http/runtimes/h3.ts"],"mappings":";;;;UAmDU;EACR,GAAG,gBAAgB,cAAc,UAAU,OAAO;EAClD,IAAI,cAAc,UAAU,OAAO;EACnC,OAAO;EACP,MAAM,SAAS,UAAU,QAAQ;;UAEzB;EACR,KAAK;IAAY;MAAY;QAAS,KAAK;QAAiB,KAAK;;;;EACjE,KAAK;EACL;IAAW,SAAS;;;iBASL;;;;;;;EAOf;;;;;;wBAiYc,UAAU,UAAS,mBAAwB,YAAY;;;;;iBAgKtD;EACf,SAAS;EACT,UAAU;EACV;IAAmC,YAAY,wBAAwB;MAAM;;;qBAYlE,qBAAY;;YAEb,sBAAsB;;YAEtB,oBAAoB"}
1
+ {"version":3,"file":"h3.d.mts","names":[],"sources":["../../../src/http/runtimes/h3.ts"],"mappings":";;;;UAkDU;EACR,GAAG,gBAAgB,cAAc,UAAU,OAAO;EAClD,IAAI,cAAc,UAAU,OAAO;EACnC,OAAO;EACP,MAAM,SAAS,UAAU,QAAQ;;UAEzB;EACR,KAAK;IAAY;MAAY;QAAS,KAAK;QAAiB,KAAK;;;;EACjE,KAAK;EACL;IAAW,SAAS;;;iBASL;;;;;;;;EAQf;;;;;;wBAkYc,UAAU,UAAS,mBAAwB,YAAY;;;;;iBA+JtD;EACf,SAAS;EACT,UAAU;EACV;IAAmC,YAAY,wBAAwB;MAAM;;;qBAYlE,qBAAY;;YAEb,sBAAsB;;YAEtB,oBAAoB"}