raiton 6.5.0-beta.13 → 6.7.0-beta.15

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 (166) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +16 -9
  3. package/build/bin/index.mjs +10288 -6059
  4. package/deno.json +4 -1
  5. package/docs/contributors/framework/README.md +2 -0
  6. package/docs/contributors/framework/cache/README.md +55 -0
  7. package/docs/contributors/framework/cache/cache.md +86 -0
  8. package/docs/contributors/framework/cache/etag.md +82 -0
  9. package/docs/contributors/framework/decorators/README.md +1 -0
  10. package/docs/contributors/framework/plugins/csrf.md +277 -0
  11. package/docs/contributors/framework/plugins/security.md +40 -6
  12. package/docs/contributors/framework/runtime.md +13 -3
  13. package/docs/user-guide/README.md +8 -4
  14. package/docs/user-guide/best-practices.md +1 -0
  15. package/docs/user-guide/cache.md +79 -0
  16. package/docs/user-guide/cli.md +35 -3
  17. package/docs/user-guide/csrf.md +557 -0
  18. package/docs/user-guide/decorators/README.md +3 -0
  19. package/docs/user-guide/decorators/cache.md +79 -0
  20. package/docs/user-guide/decorators/health-check.md +125 -0
  21. package/docs/user-guide/health-check.md +117 -0
  22. package/docs/user-guide/runtime.md +2 -1
  23. package/docs/user-guide/security.md +8 -2
  24. package/package.json +8 -3
  25. package/source/bin/bootstrapper.ts +4 -4
  26. package/source/bin/cli-tools.ts +27 -3
  27. package/source/bin/cli.ts +2 -2
  28. package/source/bin/commands.registry.ts +17 -0
  29. package/source/bin/constants.ts +1 -0
  30. package/source/bin/index.ts +2 -2
  31. package/source/commands/artifact.command.ts +2 -2
  32. package/source/commands/build.command.ts +2 -2
  33. package/source/commands/develop.command.ts +4 -5
  34. package/source/commands/grafts.command.ts +1 -1
  35. package/source/commands/start.command.ts +2 -2
  36. package/source/core/application.ts +10 -10
  37. package/source/core/artifacts/artifact.ts +1 -1
  38. package/source/core/artifacts/index.ts +1 -1
  39. package/source/core/builder.ts +69 -15
  40. package/source/core/bytes.util.ts +1 -1
  41. package/source/core/commands.ts +24 -14
  42. package/source/core/config/config.ts +2 -2
  43. package/source/core/config/define.ts +2 -2
  44. package/source/core/config/index.ts +2 -2
  45. package/source/core/context.ts +1 -1
  46. package/source/core/controller/builder.ts +31 -8
  47. package/source/core/controller/compiler.ts +6 -6
  48. package/source/core/controller/index.ts +4 -4
  49. package/source/core/controller/metadata.ts +2 -2
  50. package/source/core/controller/tracker.ts +1 -1
  51. package/source/core/directories.ts +3 -2
  52. package/source/core/guards.ts +1 -1
  53. package/source/core/helpers/index.ts +1 -1
  54. package/source/core/hooks.ts +1 -1
  55. package/source/core/index.ts +16 -16
  56. package/source/core/injection/index.ts +1 -1
  57. package/source/core/injection/injection.ts +3 -3
  58. package/source/core/mcp/builder.ts +8 -8
  59. package/source/core/mcp/index.ts +3 -3
  60. package/source/core/mcp/metadata.ts +2 -2
  61. package/source/core/mcp/tracker.ts +1 -1
  62. package/source/core/middleware/compose.ts +2 -2
  63. package/source/core/middleware/index.ts +2 -2
  64. package/source/core/middleware/pipeline.ts +2 -2
  65. package/source/core/plugins/index.ts +2 -2
  66. package/source/core/plugins/plugin.ts +1 -1
  67. package/source/core/plugins/scope.ts +4 -4
  68. package/source/core/raiton.ts +1 -1
  69. package/source/core/router/handler.ts +30 -6
  70. package/source/core/router/handler.utils.ts +3 -3
  71. package/source/core/router/index.ts +4 -4
  72. package/source/core/router/matcher.ts +1 -1
  73. package/source/core/router/route.ts +1 -1
  74. package/source/core/router/router.ts +4 -4
  75. package/source/core/server.ts +1 -1
  76. package/source/core/socket/builder.ts +2 -2
  77. package/source/core/socket/index.ts +2 -2
  78. package/source/core/socket/metadata.ts +2 -2
  79. package/source/core/thread.ts +53 -20
  80. package/source/framework/artifacts.ts +8 -5
  81. package/source/framework/cache/cache.decorator.ts +35 -0
  82. package/source/framework/cache/cache.ts +197 -0
  83. package/source/framework/cache/etag.ts +174 -0
  84. package/source/framework/cache/index.ts +4 -0
  85. package/source/framework/cache/types.ts +111 -0
  86. package/source/framework/constants/decorators.constant.ts +4 -0
  87. package/source/framework/constants/index.ts +2 -2
  88. package/source/framework/decorators/access-guard.decorator.ts +2 -2
  89. package/source/framework/decorators/api-response.decorator.ts +1 -1
  90. package/source/framework/decorators/api.decorator.ts +1 -1
  91. package/source/framework/decorators/controllable.decorator.ts +3 -3
  92. package/source/framework/decorators/csrf-guard.decorator.ts +60 -0
  93. package/source/framework/decorators/csrf-token.decorator.ts +20 -0
  94. package/source/framework/decorators/guard.decorator.ts +4 -4
  95. package/source/framework/decorators/health-check.decorator.ts +50 -0
  96. package/source/framework/decorators/index.ts +14 -11
  97. package/source/framework/decorators/injection.decorator.ts +3 -3
  98. package/source/framework/decorators/mcp.decorator.ts +4 -4
  99. package/source/framework/decorators/middleware.decorator.ts +2 -2
  100. package/source/framework/decorators/parametrable.decorator.ts +2 -2
  101. package/source/framework/decorators/routable.decorator.ts +3 -3
  102. package/source/framework/decorators/route-interaction.decorator.ts +4 -4
  103. package/source/framework/decorators/socket.decorator.ts +3 -3
  104. package/source/framework/encryption.ts +2 -2
  105. package/source/framework/enums/csrf.enum.ts +4 -0
  106. package/source/framework/enums/index.ts +8 -7
  107. package/source/framework/enums/runtime.enum.ts +1 -2
  108. package/source/framework/env.ts +2 -2
  109. package/source/framework/exceptions/http-exception.ts +3 -3
  110. package/source/framework/exceptions/index.ts +2 -2
  111. package/source/framework/health-check.ts +137 -0
  112. package/source/framework/index.ts +18 -16
  113. package/source/framework/mcp/handler.ts +3 -3
  114. package/source/framework/mcp/index.ts +3 -3
  115. package/source/framework/mcp/protocol.ts +1 -1
  116. package/source/framework/mcp/streamable-http.ts +3 -3
  117. package/source/framework/parameter-bag.ts +2 -2
  118. package/source/framework/plugins/body-parser.plugin.ts +3 -3
  119. package/source/framework/plugins/index.ts +4 -4
  120. package/source/framework/plugins/mcp.plugin.ts +5 -5
  121. package/source/framework/plugins/openapi.plugin.ts +4 -4
  122. package/source/framework/plugins/security/body-limit.ts +3 -3
  123. package/source/framework/plugins/security/cors.ts +2 -2
  124. package/source/framework/plugins/security/csrf.ts +145 -0
  125. package/source/framework/plugins/security/headers.ts +2 -2
  126. package/source/framework/plugins/security/index.ts +7 -5
  127. package/source/framework/plugins/security/method-guard.ts +3 -3
  128. package/source/framework/plugins/security/rate-limit.ts +3 -3
  129. package/source/framework/repositories.ts +1 -1
  130. package/source/framework/responses/error.ts +2 -2
  131. package/source/framework/responses/helpers.ts +3 -3
  132. package/source/framework/responses/http-throwable.ts +3 -3
  133. package/source/framework/responses/http.ts +3 -3
  134. package/source/framework/responses/index.ts +4 -4
  135. package/source/framework/runtime/bun/server.ts +5 -5
  136. package/source/framework/runtime/deno/server.ts +156 -96
  137. package/source/framework/runtime/index.ts +11 -17
  138. package/source/framework/runtime/node/reply.ts +1 -1
  139. package/source/framework/runtime/node/request.ts +2 -2
  140. package/source/framework/runtime/node/server.ts +3 -3
  141. package/source/framework/runtime/web/server.ts +2 -2
  142. package/source/framework/services.ts +1 -1
  143. package/source/framework/utilities/artifact.util.ts +4 -0
  144. package/source/framework/utilities/csrf.util.ts +162 -0
  145. package/source/framework/utilities/index.ts +10 -9
  146. package/source/framework/utilities/openapi.utils.ts +7 -7
  147. package/source/framework/utilities/utilities.util.ts +1 -1
  148. package/source/types/application.ts +2 -2
  149. package/source/types/builder.ts +1 -1
  150. package/source/types/config.ts +1 -1
  151. package/source/types/controller.ts +3 -3
  152. package/source/types/core.ts +1 -1
  153. package/source/types/csrf.ts +38 -0
  154. package/source/types/guard.ts +1 -1
  155. package/source/types/http-responses.ts +1 -1
  156. package/source/types/index.ts +26 -25
  157. package/source/types/injection.ts +1 -1
  158. package/source/types/middleware.ts +1 -1
  159. package/source/types/plugin.ts +1 -1
  160. package/source/types/raiton.ts +1 -1
  161. package/source/types/responses.ts +2 -2
  162. package/source/types/router.ts +2 -2
  163. package/source/types/runtime.ts +3 -5
  164. package/source/types/thread.ts +4 -4
  165. /package/source/framework/utilities/{https.ts → https.util.ts} +0 -0
  166. /package/source/framework/utilities/{url.ts → url.util.ts} +0 -0
@@ -1,4 +1,4 @@
1
- import type {ServerInterface, ServerOptionsInterface} from "../types";
1
+ import type {ServerInterface, ServerOptionsInterface} from "../types/index.ts";
2
2
 
3
3
 
4
4
  export class Server implements ServerInterface {
@@ -1,5 +1,5 @@
1
- import {registerSocket, unregisterSocket, getSocketMetadata} from "./metadata";
2
- import {Injection} from "../injection";
1
+ import {registerSocket, unregisterSocket, getSocketMetadata} from "./metadata.ts";
2
+ import {Injection} from "../injection/index.ts";
3
3
 
4
4
  export function compileSocket(SocketClass: any) {
5
5
  const metadata = getSocketMetadata(SocketClass.prototype || SocketClass)
@@ -1,2 +1,2 @@
1
- export * from "./metadata"
2
- export * from "./builder"
1
+ export * from "./metadata.ts"
2
+ export * from "./builder.ts"
@@ -1,5 +1,5 @@
1
- import {ConstructorType, SocketMetaInterface} from "../../types";
2
- import {METADATA_KEYS} from "../../framework";
1
+ import {ConstructorType, SocketMetaInterface} from "../../types/index.ts";
2
+ import {METADATA_KEYS} from "../../framework/index.ts";
3
3
  import "reflect-metadata";
4
4
 
5
5
  export interface SocketRegistryEntryInterface {
@@ -7,17 +7,19 @@ import type {
7
7
  ThreadOptionsInterface,
8
8
  ThreadSetupOptionsInterface,
9
9
  ThreadWaitCallable,
10
- } from "../types";
11
- import {EventMessageEnum, RuntimeType} from "../framework/enums";
10
+ } from "../types/index.ts";
11
+ import {EventMessageEnum, RuntimeType} from "../framework/enums/index.ts";
12
12
  import {ProcessUtility} from "@protorians/core";
13
- import {until} from "./process.util";
14
- import {ApplicationInterface} from "../types/application";
15
- import {Runtime} from "../framework/runtime";
13
+ import {until} from "./process.util.ts";
14
+ import {ApplicationInterface} from "../types/application.ts";
15
+ import {Runtime} from "../framework/runtime/index.ts";
16
16
  import {LBadge, Logger} from "@protorians/logger";
17
- import {ControllerBuilder} from "./controller";
18
- import {bodyParserPlugin} from "../framework/plugins/body-parser.plugin";
19
- import {Injection} from "./injection/injection";
20
- import {Throwable} from "../framework/exceptions";
17
+ import {ControllerBuilder} from "./controller/index.ts";
18
+ import {registerDefaultHealthCheck} from "../framework/health-check.ts";
19
+ import {bodyParserPlugin} from "../framework/plugins/body-parser.plugin.ts";
20
+ import {Injection} from "./injection/injection.ts";
21
+ import {Throwable} from "../framework/exceptions/index.ts";
22
+ import {isBunUsed, isDenoUsed, isNodeUsed} from "../bin/constants.ts";
21
23
  import os from "os";
22
24
 
23
25
 
@@ -40,16 +42,30 @@ export class RaitonThread implements ThreadInterface {
40
42
  public readonly builder: BuilderInterface,
41
43
  protected _options: ThreadOptionsInterface = {}
42
44
  ) {
43
- this.appDir = process.cwd();
45
+ this.appDir = isDenoUsed ? (globalThis as any).Deno.cwd() : process.cwd();
44
46
  RaitonThread.instance = this;
45
47
  }
46
48
 
47
49
  public restart(): void {
48
- process.send?.(EventMessageEnum.RESTART)
50
+ if (isDenoUsed) {
51
+ (globalThis as any).Deno.emit?.(EventMessageEnum.RESTART)
52
+ return
53
+ }
54
+ try {
55
+ if (typeof process.send === 'function' && process.connected) {
56
+ process.send(EventMessageEnum.RESTART)
57
+ }
58
+ } catch (e: any) {
59
+ Logger.debug('Restart IPC unavailable', e?.message ?? e)
60
+ }
49
61
  }
50
62
 
51
63
  public async stop(): Promise<void> {
52
64
  await Injection.shutdown();
65
+ if (isDenoUsed) {
66
+ (globalThis as any).Deno.exit(0)
67
+ return
68
+ }
53
69
  process.exit(0)
54
70
  }
55
71
 
@@ -74,7 +90,9 @@ export class RaitonThread implements ThreadInterface {
74
90
  }
75
91
 
76
92
  public setup({application, runtime}: ThreadSetupOptionsInterface): this {
77
- const defaultRuntime = typeof Bun !== 'undefined' ? RuntimeType.Bun : RuntimeType.Node;
93
+ const defaultRuntime = isBunUsed
94
+ ? RuntimeType.Bun
95
+ : (isDenoUsed ? RuntimeType.Deno : RuntimeType.Node);
78
96
  this.runtime = new Runtime(runtime || defaultRuntime);
79
97
  this.application = application;
80
98
  this.application.use(bodyParserPlugin())
@@ -88,16 +106,31 @@ export class RaitonThread implements ThreadInterface {
88
106
  if (!this.runtime)
89
107
  throw new Throwable('Runtime not defined');
90
108
 
91
- if (this.builder.source) await ControllerBuilder.scan(this.builder.source)
109
+ const scanRoot = isNodeUsed
110
+ ? (this.builder.out || this.builder.source)
111
+ : this.builder.source;
92
112
 
93
- if (this._options.serve) {
94
- process.on('SIGINT', async () => {
95
- await this.stop();
96
- });
113
+ if (scanRoot) {
114
+ await ControllerBuilder.scan(scanRoot)
115
+ registerDefaultHealthCheck(this.application)
116
+ }
97
117
 
98
- process.on('SIGTERM', async () => {
99
- await this.stop();
100
- });
118
+ if (this._options.serve) {
119
+ if (isDenoUsed) {
120
+ const addSignalListener = (globalThis as any).Deno.addSignalListener;
121
+ if (typeof addSignalListener === 'function') {
122
+ addSignalListener('SIGINT', async () => { await this.stop(); });
123
+ addSignalListener('SIGTERM', async () => { await this.stop(); });
124
+ }
125
+ } else {
126
+ process.on('SIGINT', async () => {
127
+ await this.stop();
128
+ });
129
+
130
+ process.on('SIGTERM', async () => {
131
+ await this.stop();
132
+ });
133
+ }
101
134
 
102
135
  const port = this.application.config.port || 5712;
103
136
  const hostname = this.application.config.hostname || '0.0.0.0';
@@ -1,9 +1,9 @@
1
- import {Injection} from "../core/injection";
1
+ import {Injection} from "../core/injection/index.ts";
2
2
  import {Logger} from "@protorians/logger";
3
- import type {ConstructorType} from "../types";
4
- import {Raiton} from "../core/raiton";
5
- import {isArtifact} from "./utilities";
6
- import {compileMcp} from "../core/mcp/builder";
3
+ import type {ConstructorType} from "../types/index.ts";
4
+ import {Raiton} from "../core/raiton.ts";
5
+ import {isArtifact} from "./utilities/index.ts";
6
+ import {compileMcp} from "../core/mcp/builder.ts";
7
7
 
8
8
  export type HmrChannel =
9
9
  | 'hmr:di'
@@ -12,6 +12,7 @@ export type HmrChannel =
12
12
  | 'hmr:middleware'
13
13
  | 'hmr:hook'
14
14
  | 'hmr:mcp'
15
+ | 'hmr:health-check'
15
16
 
16
17
  export interface ArtifactClassification {
17
18
  channel: HmrChannel
@@ -46,6 +47,7 @@ export const HMR_CHANNELS: Record<HmrChannel, readonly string[]> = {
46
47
  'hmr:middleware': ['middleware'],
47
48
  'hmr:hook': ['hook', 'event', 'listener'],
48
49
  'hmr:mcp': ['mcp'],
50
+ 'hmr:health-check': ['health-check'],
49
51
  }
50
52
 
51
53
  export class Artifacts {
@@ -81,6 +83,7 @@ export class Artifacts {
81
83
  'schema',
82
84
  'socket',
83
85
  'mcp',
86
+ 'health-check',
84
87
  ]
85
88
 
86
89
  static register(type: string) {
@@ -0,0 +1,35 @@
1
+ import "reflect-metadata";
2
+ import {METADATA_KEYS} from "../constants/decorators.constant.ts";
3
+ import type {CacheOptions} from "./types.ts";
4
+
5
+ /**
6
+ * Décorateur de route : met en cache la réponse du handler pendant `ttl`.
7
+ *
8
+ * Contrairement aux ETag (validation), le cache évite complètement l'exécution
9
+ * du handler tant que l'entrée est fraîche.
10
+ *
11
+ * @example
12
+ * @Controllable("/products")
13
+ * class ProductController {
14
+ * @Get("/featured")
15
+ * @Cache({ ttl: 60_000, vary: ["accept-language"] })
16
+ * featured() {
17
+ * return this.products.findFeatured()
18
+ * }
19
+ * }
20
+ */
21
+ export function Cache(options: CacheOptions = {}) {
22
+ return (target: any, propertyKey?: string) => {
23
+ if (propertyKey) {
24
+ Reflect.defineMetadata(METADATA_KEYS.CACHE, options, target, propertyKey);
25
+ }
26
+ };
27
+ }
28
+
29
+ export function getCacheMetadata(target: any, propertyKey: string): CacheOptions | undefined {
30
+ return Reflect.getMetadata(METADATA_KEYS.CACHE, target, propertyKey);
31
+ }
32
+
33
+ export function isCached(target: any, propertyKey: string): boolean {
34
+ return Reflect.hasMetadata(METADATA_KEYS.CACHE, target, propertyKey);
35
+ }
@@ -0,0 +1,197 @@
1
+ import type {RequestContext} from "../../core/context.ts";
2
+ import type {CacheEntry, CacheOptions, CacheStore} from "./types.ts";
3
+
4
+ /**
5
+ * Store en mémoire, à durée de vie bornée (TTL) et taille maximale bornée,
6
+ * utilisé par défaut pour la mise en cache des réponses de routes.
7
+ */
8
+ export class MemoryCacheStore implements CacheStore {
9
+ private entries = new Map<string, CacheEntry>();
10
+ private readonly maxSize: number;
11
+
12
+ constructor(maxSize = 1000) {
13
+ this.maxSize = maxSize;
14
+ }
15
+
16
+ get<T = any>(key: string): CacheEntry<T> | undefined {
17
+ const entry = this.entries.get(key);
18
+ if (!entry) return undefined;
19
+ if (entry.expiresAt <= Date.now()) {
20
+ this.entries.delete(key);
21
+ return undefined;
22
+ }
23
+ return entry;
24
+ }
25
+
26
+ set<T = any>(key: string, entry: CacheEntry<T>, _ttl?: number): void {
27
+ this.evictIfNeeded();
28
+ this.entries.set(key, entry);
29
+ }
30
+
31
+ has(key: string): boolean {
32
+ return this.get(key) !== undefined;
33
+ }
34
+
35
+ delete(key: string): boolean {
36
+ return this.entries.delete(key);
37
+ }
38
+
39
+ clear(): void {
40
+ this.entries.clear();
41
+ }
42
+
43
+ size(): number {
44
+ return this.entries.size;
45
+ }
46
+
47
+ private evictIfNeeded(): void {
48
+ if (this.entries.size < this.maxSize) return;
49
+ const oldestKey = this.entries.keys().next().value;
50
+ if (oldestKey !== undefined) this.entries.delete(oldestKey);
51
+ }
52
+ }
53
+
54
+ /**
55
+ * `CacheManager` configure le comportement global du cache de routes, à la
56
+ * manière des autres managers du framework.
57
+ */
58
+ export class CacheManager {
59
+ private static _store: CacheStore = new MemoryCacheStore();
60
+ private static _defaults: Partial<CacheOptions> = {};
61
+
62
+ static configure(options: Partial<CacheOptions>): void {
63
+ this._defaults = {...this._defaults, ...options};
64
+ if (options.maxEntries && this._store instanceof MemoryCacheStore) {
65
+ this._store = new MemoryCacheStore(options.maxEntries);
66
+ }
67
+ }
68
+
69
+ static getDefaults(): Partial<CacheOptions> {
70
+ return {...this._defaults};
71
+ }
72
+
73
+ static getStore(): CacheStore {
74
+ return this._store;
75
+ }
76
+
77
+ static setStore(store: CacheStore): void {
78
+ this._store = store;
79
+ }
80
+
81
+ static clear(): void {
82
+ this._store.clear();
83
+ }
84
+ }
85
+
86
+ const DEFAULT_METHODS = ['GET', 'HEAD'];
87
+
88
+ /**
89
+ * Construit la clé de cache par défaut : méthode + route + paramètres d'URL.
90
+ */
91
+ export function defaultCacheKey(context: RequestContext, route: string): string {
92
+ const parts = [context.req.method, route];
93
+ const params = (context as any).params ?? context.req.params;
94
+ if (params) {
95
+ for (const value of Object.values(params)) {
96
+ parts.push(String(value));
97
+ }
98
+ }
99
+ return parts.join('|');
100
+ }
101
+
102
+ /**
103
+ * Résout les options effectives d'une route (défauts globaux + options locales).
104
+ */
105
+ export function resolveCacheOptions(route: string, options: CacheOptions = {}): CacheOptions {
106
+ return {
107
+ ...CacheManager.getDefaults(),
108
+ ...options,
109
+ key: options.key ?? CacheManager.getDefaults().key,
110
+ };
111
+ }
112
+
113
+ /**
114
+ * Calcule la clé de cache pour une requête donnée.
115
+ */
116
+ export async function buildCacheKey(context: RequestContext, route: string, options: CacheOptions): Promise<string> {
117
+ const base = options.key
118
+ ? await options.key(context, route)
119
+ : defaultCacheKey(context, route);
120
+
121
+ const vary = options.vary ?? [];
122
+ if (vary.length === 0) return base;
123
+
124
+ const varyParts = vary.map(name => `${name}=${context.req.headers.get(name) ?? ''}`);
125
+ return `${base}|${varyParts.join('&')}`;
126
+ }
127
+
128
+ /**
129
+ * Applique une réponse en cache au contexte (statut + en-têtes + corps).
130
+ */
131
+ export function sendCachedEntry(context: RequestContext, entry: CacheEntry): void {
132
+ context.reply.status(entry.status);
133
+ for (const [name, value] of Object.entries(entry.headers)) {
134
+ context.reply.header(name, value);
135
+ }
136
+ context.reply.send(entry.body);
137
+ }
138
+
139
+ /**
140
+ * Mécanisme cœur du cache de routes, pensé pour être intégré au niveau du
141
+ * handler (dans `createHandler`). Il évite complètement d'exécuter le handler
142
+ * tant qu'une entrée fraîche existe pour la clé de requête.
143
+ *
144
+ * - `get` renvoie l'entrée fraîche si elle existe.
145
+ * - `set` stocke la réponse si elle est éligible (méthode + statut 2xx).
146
+ */
147
+ export class RouteCache {
148
+ private readonly store: CacheStore;
149
+ private readonly route: string;
150
+ private readonly options: CacheOptions;
151
+
152
+ constructor(route: string, options: CacheOptions = {}) {
153
+ this.route = route;
154
+ this.options = resolveCacheOptions(route, options);
155
+ this.store = CacheManager.getStore();
156
+ }
157
+
158
+ get enabled(): boolean {
159
+ return this.options.enabled ?? true;
160
+ }
161
+
162
+ matchesMethod(method: string): boolean {
163
+ return (this.options.methods ?? DEFAULT_METHODS).includes(method.toUpperCase());
164
+ }
165
+
166
+ key(context: RequestContext): Promise<string> {
167
+ return buildCacheKey(context, this.route, this.options);
168
+ }
169
+
170
+ async get<T = any>(context: RequestContext, key?: string): Promise<CacheEntry<T> | undefined> {
171
+ return this.store.get<T>(key ?? await this.key(context));
172
+ }
173
+
174
+ async set<T = any>(context: RequestContext, body: T, status = 200, headers: Record<string, string> = {}, key?: string): Promise<void> {
175
+ const ttl = this.options.ttl ?? 60_000;
176
+ this.store.set(key ?? await this.key(context), {
177
+ body,
178
+ status,
179
+ headers,
180
+ createdAt: Date.now(),
181
+ expiresAt: Date.now() + ttl,
182
+ }, ttl);
183
+ }
184
+
185
+ shouldCache(status: number): boolean {
186
+ return status >= 200 && status < 300;
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Helper de contrôle-manipulation du cache-Control, valeur commode pour les
192
+ * routes qui ne veulent pas passer par le middleware ETag.
193
+ */
194
+ export function cacheControl(context: RequestContext, value: string | number, publicAccess = true): void {
195
+ const directive = typeof value === 'number' ? `max-age=${value}` : value;
196
+ context.reply.header('Cache-Control', `${publicAccess ? 'public' : 'private'}, ${directive}`);
197
+ }
@@ -0,0 +1,174 @@
1
+ import type {RequestContext} from "../../core/context.ts";
2
+ import type {ETagOptions, ETagResult} from "./types.ts";
3
+ import {HttpStatus} from "../enums/index.ts";
4
+
5
+ const DEFAULT_HEADER_NAME = 'ETag';
6
+
7
+ /**
8
+ * Hachage FNV-1a (32 bits) utilisé par défaut pour générer une valeur d'ETag
9
+ * stable à partir du corps sérialisé de la réponse.
10
+ */
11
+ function fnv1a(input: string): string {
12
+ let hash = 0x811c9dc5;
13
+ for (let i = 0; i < input.length; i++) {
14
+ hash ^= input.charCodeAt(i);
15
+ hash = Math.imul(hash, 0x01000193);
16
+ }
17
+ return (hash >>> 0).toString(16);
18
+ }
19
+
20
+ /**
21
+ * Sérialise un corps de réponse en chaîne de caractères, de la même manière
22
+ * que les runtimes du framework le font avant l'envoi.
23
+ */
24
+ function serialize(body: any): string {
25
+ if (body === undefined || body === null) return '';
26
+ if (typeof body === 'string') return body;
27
+ if (Buffer.isBuffer(body)) return body.toString();
28
+ if (typeof body === 'object' && !(body instanceof Response)) return JSON.stringify(body);
29
+ return String(body);
30
+ }
31
+
32
+ /**
33
+ * `Etagger` est le gestionnaire complet des ETag. Il est entièrement
34
+ * personnalisable par le développeur : algorithme de hachage, marqueur faible,
35
+ * en-tête, cache-control et prédicat d'exclusion.
36
+ *
37
+ * @example
38
+ * const etagger = new Etagger({ weak: true, cacheControl: { maxAge: 300 } })
39
+ * const { tag, notModified } = await etagger.evaluate(context, body)
40
+ */
41
+ export class Etagger {
42
+ private readonly enabled: boolean;
43
+ private readonly weak: boolean;
44
+ private readonly algorithm?: (body: string) => string | Promise<string>;
45
+ private readonly cacheControl?: ETagOptions['cacheControl'];
46
+ private readonly headerName: string;
47
+ private readonly skip?: ETagOptions['skip'];
48
+
49
+ constructor(options: ETagOptions = {}) {
50
+ this.enabled = options.enabled ?? true;
51
+ this.weak = options.weak ?? false;
52
+ this.algorithm = options.algorithm;
53
+ this.cacheControl = options.cacheControl;
54
+ this.headerName = options.headerName ?? DEFAULT_HEADER_NAME;
55
+ this.skip = options.skip;
56
+ }
57
+
58
+ /**
59
+ * Calcule la valeur d'ETag d'un corps de réponse sérialisé.
60
+ */
61
+ async generate(body: any): Promise<string> {
62
+ const serialized = serialize(body);
63
+ let value: string;
64
+ if (this.algorithm) {
65
+ value = await this.algorithm(serialized);
66
+ } else {
67
+ value = fnv1a(serialized);
68
+ }
69
+ value = `"${value}"`;
70
+ if (this.weak) value = `W/${value}`;
71
+ return value;
72
+ }
73
+
74
+ /**
75
+ * Vérifie si la liste d'ETag envoyée par le client (en-tête `If-None-Match`)
76
+ * matche avec l'ETag calculé. Un `*` matche n'importe quelle ressource.
77
+ */
78
+ matches(clientTags: string | null | undefined, tag: string): boolean {
79
+ if (!clientTags) return false;
80
+ const expected = tag.replace(/^W\//, '');
81
+ return clientTags.split(',').some(part => {
82
+ const candidate = part.trim().replace(/^W\//, '');
83
+ return candidate === '*' || candidate === expected;
84
+ });
85
+ }
86
+
87
+ /**
88
+ * Applique la politique de cache à en-têtes de réponse.
89
+ */
90
+ applyCacheControl(context: RequestContext): void {
91
+ const cc = this.cacheControl;
92
+ if (!cc) return;
93
+
94
+ const directives: string[] = [];
95
+ if (cc === true) {
96
+ directives.push('no-cache');
97
+ } else {
98
+ if (cc.public) directives.push('public');
99
+ else directives.push('private');
100
+ if (cc.maxAge !== undefined) directives.push(`max-age=${cc.maxAge}`);
101
+ if (cc.noCache) directives.push('no-cache');
102
+ if (cc.noStore) directives.push('no-store');
103
+ if (cc.mustRevalidate) directives.push('must-revalidate');
104
+ }
105
+ context.reply.header('Cache-Control', directives.join(', '));
106
+ }
107
+
108
+ /**
109
+ * Évalue la requête condititionnelle complète. Si un ETag fort/faible est
110
+ * présent et que le client l'a déjà (via `If-None-Match`), la réponse est
111
+ * marquée `notModified` et doit être envoyée avec le statut `304`.
112
+ */
113
+ async evaluate(context: RequestContext, body: any): Promise<ETagResult> {
114
+ if (!this.enabled || this.skip?.(context, body)) {
115
+ return {tag: '', body, notModified: false};
116
+ }
117
+
118
+ const tag = await this.generate(body);
119
+ const header = this.headerName;
120
+ context.reply.header(header, tag);
121
+ this.applyCacheControl(context);
122
+
123
+ const ifNoneMatch = context.req.headers.get('if-none-match');
124
+ if (this.matches(ifNoneMatch, tag)) {
125
+ return {tag, body: null, notModified: true};
126
+ }
127
+
128
+ return {tag, body, notModified: false};
129
+ }
130
+
131
+ /**
132
+ * Raccourci statique, construit une instance à la volée et évalue.
133
+ */
134
+ static async apply(context: RequestContext, body: any, options?: ETagOptions): Promise<ETagResult> {
135
+ return new Etagger(options).evaluate(context, body);
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Instance singulière utilisée par défaut par le middleware `etag()`.
141
+ */
142
+ export const defaultEtagger = new Etagger();
143
+
144
+ /**
145
+ * Middleware ETag prêt à l'emploi. À brancher globalement ou par route :
146
+ *
147
+ * ```typescript
148
+ * app.use(etag({ weak: false, cacheControl: { maxAge: 300 } }))
149
+ * ```
150
+ *
151
+ * Le middleware intercepte `context.reply.send`, calcule l'ETag du corps
152
+ * sérialisé, pose l'en-tête correspondant et répond `304 Not Modified` si le
153
+ * client déclare déjà posséder la représentation (`If-None-Match`).
154
+ */
155
+ export function etag(options: ETagOptions = {}) {
156
+ return async ({context, next}: { context: RequestContext; next: () => Promise<any> }) => {
157
+ const reply = context.reply;
158
+ const originalSend = reply.send.bind(reply);
159
+ const etagger = new Etagger(options);
160
+
161
+ reply.send = (body: any) => {
162
+ etagger.evaluate(context, body).then(({notModified, body: nextBody}) => {
163
+ if (notModified) {
164
+ reply.status(HttpStatus.NOT_MODIFIED);
165
+ originalSend(null);
166
+ return;
167
+ }
168
+ originalSend(nextBody);
169
+ });
170
+ };
171
+
172
+ await next();
173
+ };
174
+ }
@@ -0,0 +1,4 @@
1
+ export * from "./types.ts"
2
+ export * from "./etag.ts"
3
+ export * from "./cache.ts"
4
+ export * from "./cache.decorator.ts"