@gravito/core 1.6.1 → 2.0.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 (168) hide show
  1. package/README.md +100 -6
  2. package/README.zh-TW.md +101 -6
  3. package/dist/Application.d.ts +256 -0
  4. package/dist/CommandKernel.d.ts +33 -0
  5. package/dist/ConfigManager.d.ts +65 -0
  6. package/dist/Container/RequestScopeManager.d.ts +62 -0
  7. package/dist/Container/RequestScopeMetrics.d.ts +144 -0
  8. package/dist/Container.d.ts +153 -0
  9. package/dist/ErrorHandler.d.ts +66 -0
  10. package/dist/Event.d.ts +5 -0
  11. package/dist/EventManager.d.ts +123 -0
  12. package/dist/GlobalErrorHandlers.d.ts +47 -0
  13. package/dist/GravitoServer.d.ts +28 -0
  14. package/dist/HookManager.d.ts +435 -0
  15. package/dist/Listener.d.ts +4 -0
  16. package/dist/Logger.d.ts +20 -0
  17. package/dist/PlanetCore.d.ts +402 -0
  18. package/dist/RequestContext.d.ts +97 -0
  19. package/dist/Route.d.ts +36 -0
  20. package/dist/Router.d.ts +270 -0
  21. package/dist/ServiceProvider.d.ts +178 -0
  22. package/dist/adapters/GravitoEngineAdapter.d.ts +27 -0
  23. package/dist/adapters/bun/AdaptiveAdapter.d.ts +99 -0
  24. package/dist/adapters/bun/BunContext.d.ts +54 -0
  25. package/dist/adapters/bun/BunNativeAdapter.d.ts +66 -0
  26. package/dist/adapters/bun/BunRequest.d.ts +31 -0
  27. package/dist/adapters/bun/BunWebSocketHandler.d.ts +48 -0
  28. package/dist/adapters/bun/RadixNode.d.ts +19 -0
  29. package/dist/adapters/bun/RadixRouter.d.ts +32 -0
  30. package/dist/adapters/bun/index.d.ts +7 -0
  31. package/dist/adapters/bun/types.d.ts +20 -0
  32. package/dist/adapters/index.d.ts +12 -0
  33. package/dist/adapters/types.d.ts +235 -0
  34. package/dist/binary/BinaryUtils.d.ts +105 -0
  35. package/dist/binary/index.d.ts +5 -0
  36. package/dist/cli/queue-commands.d.ts +6 -0
  37. package/dist/compat/async-local-storage.browser.d.ts +9 -0
  38. package/dist/compat/async-local-storage.d.ts +7 -0
  39. package/dist/compat/crypto.browser.d.ts +5 -0
  40. package/dist/compat/crypto.d.ts +6 -0
  41. package/dist/compat.d.ts +23 -1
  42. package/dist/compat.js +3 -0
  43. package/dist/compat.js.map +9 -0
  44. package/dist/engine/AOTRouter.d.ts +139 -0
  45. package/dist/engine/FastContext.d.ts +141 -0
  46. package/dist/engine/Gravito.d.ts +131 -0
  47. package/dist/engine/MinimalContext.d.ts +102 -0
  48. package/dist/engine/analyzer.d.ts +113 -0
  49. package/dist/engine/constants.d.ts +23 -0
  50. package/dist/engine/index.d.ts +14 -910
  51. package/dist/engine/index.js +623 -622
  52. package/dist/engine/index.js.map +23 -0
  53. package/dist/engine/path.d.ts +26 -0
  54. package/dist/engine/pool.d.ts +83 -0
  55. package/dist/engine/types.d.ts +149 -0
  56. package/dist/error-handling/RequestScopeErrorContext.d.ts +126 -0
  57. package/dist/events/BackpressureManager.d.ts +215 -0
  58. package/dist/events/CircuitBreaker.d.ts +229 -0
  59. package/dist/events/DeadLetterQueue.d.ts +219 -0
  60. package/dist/events/EventBackend.d.ts +12 -0
  61. package/dist/events/EventOptions.d.ts +204 -0
  62. package/dist/events/EventPriorityQueue.d.ts +63 -0
  63. package/dist/events/FlowControlStrategy.d.ts +109 -0
  64. package/dist/events/IdempotencyCache.d.ts +60 -0
  65. package/dist/events/MessageQueueBridge.d.ts +184 -0
  66. package/dist/events/PriorityEscalationManager.d.ts +82 -0
  67. package/dist/events/RetryScheduler.d.ts +104 -0
  68. package/dist/events/WorkerPool.d.ts +98 -0
  69. package/dist/events/WorkerPoolConfig.d.ts +153 -0
  70. package/dist/events/WorkerPoolMetrics.d.ts +65 -0
  71. package/dist/events/aggregation/AggregationWindow.d.ts +77 -0
  72. package/dist/events/aggregation/DeduplicationManager.d.ts +135 -0
  73. package/dist/events/aggregation/EventAggregationManager.d.ts +108 -0
  74. package/dist/events/aggregation/EventBatcher.d.ts +99 -0
  75. package/dist/events/aggregation/index.d.ts +10 -0
  76. package/dist/events/aggregation/types.d.ts +117 -0
  77. package/dist/events/index.d.ts +26 -0
  78. package/dist/events/observability/EventMetrics.d.ts +132 -0
  79. package/dist/events/observability/EventTracer.d.ts +68 -0
  80. package/dist/events/observability/EventTracing.d.ts +161 -0
  81. package/dist/events/observability/OTelEventMetrics.d.ts +332 -0
  82. package/dist/events/observability/ObservableHookManager.d.ts +108 -0
  83. package/dist/events/observability/StreamWorkerMetrics.d.ts +76 -0
  84. package/dist/events/observability/index.d.ts +24 -0
  85. package/dist/events/observability/metrics-types.d.ts +16 -0
  86. package/dist/events/queue-core.d.ts +77 -0
  87. package/dist/events/task-executor.d.ts +51 -0
  88. package/dist/events/types.d.ts +134 -0
  89. package/dist/exceptions/AuthenticationException.d.ts +8 -0
  90. package/dist/exceptions/AuthorizationException.d.ts +8 -0
  91. package/dist/exceptions/CircularDependencyException.d.ts +9 -0
  92. package/dist/exceptions/GravitoException.d.ts +23 -0
  93. package/dist/exceptions/HttpException.d.ts +9 -0
  94. package/dist/exceptions/ModelNotFoundException.d.ts +10 -0
  95. package/dist/exceptions/ValidationException.d.ts +22 -0
  96. package/dist/exceptions/index.d.ts +7 -0
  97. package/dist/ffi/NativeAccelerator.d.ts +69 -0
  98. package/dist/ffi/NativeHasher.d.ts +139 -0
  99. package/dist/ffi/cbor-fallback.d.ts +96 -0
  100. package/dist/ffi/hash-fallback.d.ts +33 -0
  101. package/dist/ffi/index.d.ts +10 -0
  102. package/dist/ffi/index.js +131 -0
  103. package/dist/ffi/index.js.map +11 -0
  104. package/dist/ffi/types.d.ts +135 -0
  105. package/dist/health/HealthProvider.d.ts +67 -0
  106. package/dist/helpers/Arr.d.ts +19 -0
  107. package/dist/helpers/Str.d.ts +38 -0
  108. package/dist/helpers/data.d.ts +25 -0
  109. package/dist/helpers/errors.d.ts +34 -0
  110. package/dist/helpers/response.d.ts +41 -0
  111. package/dist/helpers.d.ts +338 -0
  112. package/dist/hooks/ActionManager.d.ts +132 -0
  113. package/dist/hooks/AsyncDetector.d.ts +84 -0
  114. package/dist/hooks/FilterManager.d.ts +71 -0
  115. package/dist/hooks/MigrationWarner.d.ts +24 -0
  116. package/dist/hooks/dlq-operations.d.ts +60 -0
  117. package/dist/hooks/index.d.ts +11 -0
  118. package/dist/hooks/types.d.ts +107 -0
  119. package/dist/http/CookieJar.d.ts +51 -0
  120. package/dist/http/cookie.d.ts +29 -0
  121. package/dist/http/index.d.ts +12 -0
  122. package/dist/{compat-CI8hiulX.d.cts → http/types.d.ts} +35 -16
  123. package/dist/index.browser.d.ts +34 -0
  124. package/dist/index.d.ts +60 -10981
  125. package/dist/index.js +10808 -11273
  126. package/dist/index.js.map +166 -0
  127. package/dist/observability/QueueDashboard.d.ts +136 -0
  128. package/dist/observability/contracts.d.ts +137 -0
  129. package/dist/observability/index.d.ts +13 -0
  130. package/dist/reliability/DeadLetterQueueManager.d.ts +349 -0
  131. package/dist/reliability/RetryPolicy.d.ts +217 -0
  132. package/dist/reliability/index.d.ts +6 -0
  133. package/dist/router/ControllerDispatcher.d.ts +12 -0
  134. package/dist/router/RequestValidator.d.ts +20 -0
  135. package/dist/runtime/adapter-bun.d.ts +12 -0
  136. package/dist/runtime/adapter-deno.d.ts +12 -0
  137. package/dist/runtime/adapter-node.d.ts +12 -0
  138. package/dist/runtime/adapter-unknown.d.ts +13 -0
  139. package/dist/runtime/archive.d.ts +17 -0
  140. package/dist/runtime/compression.d.ts +21 -0
  141. package/dist/runtime/deep-equals.d.ts +56 -0
  142. package/dist/runtime/detection.d.ts +22 -0
  143. package/dist/runtime/escape.d.ts +34 -0
  144. package/dist/runtime/index.browser.d.ts +20 -0
  145. package/dist/runtime/index.d.ts +44 -0
  146. package/dist/runtime/markdown.d.ts +44 -0
  147. package/dist/runtime/types.d.ts +436 -0
  148. package/dist/runtime-helpers.d.ts +67 -0
  149. package/dist/runtime.d.ts +11 -0
  150. package/dist/security/Encrypter.d.ts +33 -0
  151. package/dist/security/Hasher.d.ts +29 -0
  152. package/dist/testing/HttpTester.d.ts +39 -0
  153. package/dist/testing/TestResponse.d.ts +78 -0
  154. package/dist/testing/index.d.ts +2 -0
  155. package/dist/transpiler-utils.d.ts +170 -0
  156. package/dist/types/events.d.ts +94 -0
  157. package/dist/types.d.ts +13 -0
  158. package/package.json +25 -56
  159. package/src/ffi/native/cbor.c +1148 -0
  160. package/dist/Metrics-VOWWRNNR.js +0 -219
  161. package/dist/chunk-R5U7XKVJ.js +0 -16
  162. package/dist/compat-CI8hiulX.d.ts +0 -376
  163. package/dist/compat.cjs +0 -18
  164. package/dist/compat.d.cts +0 -1
  165. package/dist/engine/index.cjs +0 -1764
  166. package/dist/engine/index.d.cts +0 -922
  167. package/dist/index.cjs +0 -14906
  168. package/dist/index.d.cts +0 -11008
@@ -1,219 +0,0 @@
1
- import "./chunk-R5U7XKVJ.js";
2
-
3
- // src/observability/Metrics.ts
4
- var DEFAULTS = {
5
- port: 9090,
6
- prefix: "gravito_event_",
7
- interval: 6e4,
8
- // 60 秒
9
- defaultMetrics: true
10
- };
11
- async function setupPrometheusMetrics(config = {}) {
12
- const finalConfig = {
13
- port: config.port ?? parseInt(process.env.PROMETHEUS_PORT || String(DEFAULTS.port), 10),
14
- prefix: config.prefix ?? process.env.PROMETHEUS_PREFIX ?? DEFAULTS.prefix,
15
- interval: config.interval ?? parseInt(process.env.PROMETHEUS_INTERVAL || String(DEFAULTS.interval), 10),
16
- defaultMetrics: config.defaultMetrics ?? process.env.PROMETHEUS_DEFAULT_METRICS !== "false"
17
- };
18
- try {
19
- const { metrics } = await import("@opentelemetry/api");
20
- const { MeterProvider } = await import("@opentelemetry/sdk-metrics");
21
- const { PrometheusExporter } = await import("@opentelemetry/exporter-prometheus");
22
- const exporter = new PrometheusExporter(
23
- {
24
- port: finalConfig.port,
25
- endpoint: "/metrics"
26
- },
27
- () => {
28
- console.log(
29
- `[Metrics] Prometheus metrics available at http://localhost:${finalConfig.port}/metrics`
30
- );
31
- }
32
- );
33
- const meterProvider = new MeterProvider({
34
- exporter,
35
- interval: finalConfig.interval
36
- });
37
- metrics.setGlobalMeterProvider(meterProvider);
38
- if (finalConfig.defaultMetrics) {
39
- try {
40
- const { collectDefaultMetrics } = await import("@opentelemetry/auto-instrumentations-node");
41
- collectDefaultMetrics({ meterProvider, prefix: finalConfig.prefix });
42
- } catch (error) {
43
- console.warn("[Metrics] Failed to setup default metrics:", error);
44
- }
45
- }
46
- return {
47
- port: finalConfig.port,
48
- endpoint: `/metrics`
49
- };
50
- } catch (error) {
51
- console.warn("[Metrics] Failed to setup Prometheus exporter:", error);
52
- console.log("[Metrics] Metrics will not be exported to Prometheus");
53
- return null;
54
- }
55
- }
56
- function getEventMetricsDefinition(prefix = DEFAULTS.prefix) {
57
- return {
58
- dispatchLatency: {
59
- name: `${prefix}dispatch_latency_seconds`,
60
- help: "Event dispatch latency distribution",
61
- labels: ["event_name", "priority"],
62
- buckets: [1e-3, 5e-3, 0.01, 0.05, 0.1, 0.5, 1, 2, 5]
63
- },
64
- listenerExecutionTime: {
65
- name: `${prefix}listener_execution_seconds`,
66
- help: "Individual listener execution time",
67
- labels: ["event_name", "listener_name"],
68
- buckets: [1e-3, 5e-3, 0.01, 0.05, 0.1, 0.5, 1, 2, 5]
69
- },
70
- queueDepth: {
71
- name: `${prefix}queue_depth`,
72
- help: "Current queue depth by priority",
73
- labels: ["priority"]
74
- },
75
- failureRate: {
76
- name: `${prefix}failures_total`,
77
- help: "Total event processing failures",
78
- labels: ["event_name", "error_type"]
79
- },
80
- timeoutCount: {
81
- name: `${prefix}timeouts_total`,
82
- help: "Total event timeouts",
83
- labels: ["event_name"]
84
- },
85
- throughput: {
86
- name: `${prefix}throughput_total`,
87
- help: "Total events processed",
88
- labels: ["event_name", "status"]
89
- },
90
- circuitBreakerState: {
91
- name: `${prefix}circuit_breaker_state`,
92
- help: "Current circuit breaker state (0=CLOSED, 1=HALF_OPEN, 2=OPEN)",
93
- labels: ["event_name"]
94
- },
95
- circuitBreakerTransitions: {
96
- name: `${prefix}circuit_breaker_transitions_total`,
97
- help: "Total number of circuit breaker state transitions",
98
- labels: ["event_name", "from_state", "to_state"]
99
- },
100
- circuitBreakerFailures: {
101
- name: `${prefix}circuit_breaker_failures_total`,
102
- help: "Total number of failures tracked by circuit breaker",
103
- labels: ["event_name"]
104
- },
105
- circuitBreakerSuccesses: {
106
- name: `${prefix}circuit_breaker_successes_total`,
107
- help: "Total number of successes tracked by circuit breaker",
108
- labels: ["event_name"]
109
- },
110
- circuitBreakerOpenDuration: {
111
- name: `${prefix}circuit_breaker_open_duration_seconds`,
112
- help: "Duration of circuit breaker OPEN state in seconds",
113
- labels: ["event_name"],
114
- buckets: [1, 5, 10, 30, 60, 120, 300]
115
- }
116
- };
117
- }
118
- var PROMETHEUS_QUERIES = {
119
- /** 事件派發延遲 P95 */
120
- dispatchLatencyP95: "histogram_quantile(0.95, rate(gravito_event_dispatch_latency_seconds_bucket[5m]))",
121
- /** 事件派發延遲 P99 */
122
- dispatchLatencyP99: "histogram_quantile(0.99, rate(gravito_event_dispatch_latency_seconds_bucket[5m]))",
123
- /** 隊列深度(按優先級) */
124
- queueDepthByPriority: "gravito_event_queue_depth",
125
- /** 吞吐量(事件/秒) */
126
- throughput: "rate(gravito_event_throughput_total[1m])",
127
- /** 失敗率 */
128
- failureRate: "rate(gravito_event_failures_total[5m]) / rate(gravito_event_throughput_total[5m])",
129
- /** 監聽器執行時間 P99 */
130
- listenerLatencyP99: "histogram_quantile(0.99, rate(gravito_event_listener_execution_seconds_bucket[5m]))",
131
- /** 超時次數 */
132
- timeoutCount: "rate(gravito_event_timeouts_total[5m])",
133
- /** 吞吐量異常檢測 */
134
- throughputAnomaly: "rate(gravito_event_throughput_total[5m]) < 100",
135
- /** 熔斷器狀態(0=CLOSED, 1=HALF_OPEN, 2=OPEN) */
136
- circuitBreakerState: "gravito_event_circuit_breaker_state",
137
- /** 熔斷器開啟率 */
138
- circuitBreakerOpenRate: 'rate(gravito_event_circuit_breaker_transitions_total{to_state="OPEN"}[5m])',
139
- /** 熔斷器恢復率 */
140
- circuitBreakerRecoveryRate: 'rate(gravito_event_circuit_breaker_transitions_total{to_state="CLOSED"}[5m])',
141
- /** 熔斷器失敗率 */
142
- circuitBreakerFailureRate: "rate(gravito_event_circuit_breaker_failures_total[5m])",
143
- /** 熔斷器 OPEN 持續時間 P95 */
144
- circuitBreakerOpenDurationP95: "histogram_quantile(0.95, rate(gravito_event_circuit_breaker_open_duration_seconds_bucket[5m]))",
145
- /** 熔斷器 OPEN 持續時間 P99 */
146
- circuitBreakerOpenDurationP99: "histogram_quantile(0.99, rate(gravito_event_circuit_breaker_open_duration_seconds_bucket[5m]))"
147
- };
148
- var PROMETHEUS_ALERT_RULES = {
149
- /** P99 延遲過高 */
150
- HighDispatchLatency: {
151
- expr: "histogram_quantile(0.99, gravito_event_dispatch_latency_seconds) > 0.8",
152
- for: "5m",
153
- severity: "critical",
154
- summary: "\u4E8B\u4EF6\u6D3E\u767C P99 \u5EF6\u9072\u904E\u9AD8",
155
- description: "P99 \u5EF6\u9072: {{ $value }}s\uFF0C\u5DF2\u8D85\u904E 800ms"
156
- },
157
- /** 隊列深度過高 */
158
- HighQueueDepth: {
159
- expr: 'gravito_event_queue_depth{priority="high"} > 1000',
160
- for: "2m",
161
- severity: "warning",
162
- summary: "\u9AD8\u512A\u5148\u7D1A\u4E8B\u4EF6\u968A\u5217\u5806\u7A4D",
163
- description: "\u968A\u5217\u6DF1\u5EA6: {{ $value }}\uFF0C\u61C9\u8ABF\u67E5\u539F\u56E0"
164
- },
165
- /** 失敗率過高 */
166
- HighFailureRate: {
167
- expr: "(rate(gravito_event_failures_total[5m]) / rate(gravito_event_throughput_total[5m])) > 0.05",
168
- for: "3m",
169
- severity: "critical",
170
- summary: "\u4E8B\u4EF6\u8655\u7406\u5931\u6557\u7387\u904E\u9AD8",
171
- description: "\u5931\u6557\u7387: {{ $value | humanizePercentage }}\uFF0C\u8D85\u904E 5%"
172
- },
173
- /** 監聽器執行時間過長 */
174
- SlowListener: {
175
- expr: "histogram_quantile(0.99, gravito_event_listener_execution_seconds) > 1.0",
176
- for: "5m",
177
- severity: "warning",
178
- summary: "\u76E3\u807D\u5668\u57F7\u884C\u6642\u9593\u904E\u9577",
179
- description: "P99 \u8017\u6642: {{ $value }}s\uFF0C\u76E3\u807D\u5668: {{ $labels.listener_name }}"
180
- },
181
- /** 吞吐量異常下降 */
182
- ThroughputDrop: {
183
- expr: "rate(gravito_event_throughput_total[5m]) < 100 and increase(gravito_event_throughput_total[1h]) > 0",
184
- for: "2m",
185
- severity: "critical",
186
- summary: "\u4E8B\u4EF6\u541E\u5410\u91CF\u7570\u5E38\u4E0B\u964D",
187
- description: "\u7576\u524D\u541E\u5410: {{ $value | humanize }} events/sec"
188
- },
189
- /** 熔斷器持續開啟 */
190
- CircuitBreakerOpen: {
191
- expr: 'gravito_event_circuit_breaker_state{event_name=~".+"} == 2',
192
- for: "5m",
193
- severity: "warning",
194
- summary: "\u7194\u65B7\u5668\u6301\u7E8C\u958B\u555F",
195
- description: "\u4E8B\u4EF6 {{ $labels.event_name }} \u7194\u65B7\u5668\u5DF2\u958B\u555F\u8D85\u904E 5 \u5206\u9418"
196
- },
197
- /** 熔斷器頻繁切換 */
198
- CircuitBreakerFlapping: {
199
- expr: "rate(gravito_event_circuit_breaker_transitions_total[5m]) > 10",
200
- for: "2m",
201
- severity: "critical",
202
- summary: "\u7194\u65B7\u5668\u983B\u7E41\u5207\u63DB",
203
- description: "\u4E8B\u4EF6 {{ $labels.event_name }} \u7194\u65B7\u5668\u72C0\u614B\u5207\u63DB\u904E\u65BC\u983B\u7E41\uFF0C\u5207\u63DB\u901F\u7387: {{ $value }}/sec"
204
- },
205
- /** 熔斷器故障率過高 */
206
- CircuitBreakerHighFailureRate: {
207
- expr: "rate(gravito_event_circuit_breaker_failures_total[5m]) > rate(gravito_event_circuit_breaker_successes_total[5m])",
208
- for: "3m",
209
- severity: "critical",
210
- summary: "\u7194\u65B7\u5668\u6545\u969C\u7387\u8D85\u904E\u6210\u529F\u7387",
211
- description: "\u4E8B\u4EF6 {{ $labels.event_name }} \u7684\u5931\u6557\u7387\u5DF2\u8D85\u904E\u6210\u529F\u7387"
212
- }
213
- };
214
- export {
215
- PROMETHEUS_ALERT_RULES,
216
- PROMETHEUS_QUERIES,
217
- getEventMetricsDefinition,
218
- setupPrometheusMetrics
219
- };
@@ -1,16 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
- }) : x)(function(x) {
5
- if (typeof require !== "undefined") return require.apply(this, arguments);
6
- throw Error('Dynamic require of "' + x + '" is not supported');
7
- });
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
-
13
- export {
14
- __require,
15
- __export
16
- };
@@ -1,376 +0,0 @@
1
- /**
2
- * @fileoverview Core HTTP Types for Gravito Framework
3
- *
4
- * These types provide a unified abstraction layer that decouples the framework
5
- * from any specific HTTP engine (Photon, Express, custom, etc.).
6
- *
7
- * @module @gravito/core/http
8
- * @since 2.0.0
9
- */
10
- declare global {
11
- interface ExecutionContext {
12
- waitUntil(promise: Promise<unknown>): void;
13
- passThroughOnException(): void;
14
- }
15
- }
16
- /**
17
- * Standard HTTP methods supported by Gravito
18
- */
19
- type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head';
20
- /**
21
- * HTTP status codes
22
- */
23
- type StatusCode = number;
24
- /**
25
- * Content-bearing HTTP status codes (excludes 1xx, 204, 304)
26
- */
27
- type ContentfulStatusCode = Exclude<StatusCode, 100 | 101 | 102 | 103 | 204 | 304>;
28
- /**
29
- * Base context variables available in every request
30
- * Orbits can extend this interface via module augmentation
31
- *
32
- * @example
33
- * ```typescript
34
- * // Extending variables in your orbit:
35
- * declare module '@gravito/core' {
36
- * interface GravitoVariables {
37
- * myService: MyService
38
- * }
39
- * }
40
- * ```
41
- */
42
- interface GravitoVariables {
43
- /**
44
- * The PlanetCore instance
45
- * @remarks Always available in PlanetCore-managed contexts
46
- */
47
- core?: unknown;
48
- /**
49
- * Logger instance
50
- */
51
- logger?: unknown;
52
- /**
53
- * Configuration manager
54
- */
55
- config?: unknown;
56
- /**
57
- * Cookie jar for managing response cookies
58
- */
59
- cookieJar?: unknown;
60
- /**
61
- * Middleware scope tracking for Orbit isolation
62
- * Tracks which Orbit/scope this request belongs to
63
- * Used to prevent cross-Orbit middleware contamination
64
- * @since 2.3.0
65
- */
66
- middlewareScope?: string;
67
- /** @deprecated Use ctx.route() instead */
68
- route?: unknown;
69
- [key: string]: unknown;
70
- }
71
- /**
72
- * Validated request data targets
73
- */
74
- type ValidationTarget = 'json' | 'query' | 'param' | 'header' | 'form' | 'cookie';
75
- /**
76
- * GravitoRequest - Unified request interface
77
- *
78
- * Provides a consistent API for accessing request data regardless of
79
- * the underlying HTTP engine.
80
- *
81
- * @example
82
- * ```typescript
83
- * const userId = ctx.req.param('id')
84
- * const search = ctx.req.query('q')
85
- * const body = await ctx.req.json<CreateUserDto>()
86
- * ```
87
- */
88
- interface GravitoRequest {
89
- /** Full request URL */
90
- readonly url: string;
91
- /** HTTP method (uppercase) */
92
- readonly method: string;
93
- /** Request path without query string */
94
- readonly path: string;
95
- /**
96
- * Route pattern (e.g., /users/:id) for the matched route
97
- *
98
- * This provides the parameterized route pattern instead of the concrete path,
99
- * which is critical for preventing high cardinality issues in metrics systems.
100
- *
101
- * @example
102
- * ```typescript
103
- * // For request: GET /users/123
104
- * ctx.req.path // => "/users/123"
105
- * ctx.req.routePattern // => "/users/:id"
106
- * ```
107
- */
108
- readonly routePattern?: string;
109
- /**
110
- * Get a route parameter value
111
- * @param name - Parameter name (e.g., 'id' for route '/users/:id')
112
- */
113
- param(name: string): string | undefined;
114
- /**
115
- * Get all route parameters
116
- */
117
- params(): Record<string, string>;
118
- /**
119
- * Get a query string parameter
120
- * @param name - Query parameter name
121
- */
122
- query(name: string): string | undefined;
123
- /**
124
- * Get all query parameters
125
- */
126
- queries(): Record<string, string | string[]>;
127
- /**
128
- * Get a request header value
129
- * @param name - Header name (case-insensitive)
130
- */
131
- header(name: string): string | undefined;
132
- /**
133
- * Get all request headers
134
- */
135
- header(): Record<string, string>;
136
- /**
137
- * Parse request body as JSON
138
- * @throws {Error} If body is not valid JSON
139
- */
140
- json<T = unknown>(): Promise<T>;
141
- /**
142
- * Parse request body as text
143
- */
144
- text(): Promise<string>;
145
- /**
146
- * Parse request body as FormData
147
- */
148
- formData(): Promise<FormData>;
149
- /**
150
- * Parse request body as ArrayBuffer
151
- */
152
- arrayBuffer(): Promise<ArrayBuffer>;
153
- /**
154
- * Parse form data (urlencoded or multipart)
155
- */
156
- parseBody<T = unknown>(): Promise<T>;
157
- /**
158
- * Get the raw Request object
159
- */
160
- readonly raw: Request;
161
- /**
162
- * Get validated data from a specific source
163
- * @param target - The validation target
164
- * @throws {Error} If validation was not performed for this target
165
- */
166
- valid<T = unknown>(target: ValidationTarget): T;
167
- }
168
- /**
169
- * Options for request forwarding (Proxy)
170
- */
171
- interface ProxyOptions {
172
- /** Override or add request headers */
173
- headers?: Record<string, string>;
174
- /** Whether to keep the original Host header (default: false) */
175
- preserveHost?: boolean;
176
- /** Whether to add X-Forwarded-* headers (default: true) */
177
- addForwardedHeaders?: boolean;
178
- /** Path rewriting logic */
179
- rewritePath?: (path: string) => string;
180
- }
181
- /**
182
- * GravitoContext - Unified request context
183
- *
184
- * This interface encapsulates all HTTP request/response operations,
185
- * enabling seamless replacement of the underlying HTTP engine.
186
- *
187
- * @typeParam V - Context variables type
188
- *
189
- * @example
190
- * ```typescript
191
- * // In a controller
192
- * async show(ctx: GravitoContext) {
193
- * const id = ctx.req.param('id')
194
- * const user = await User.find(id)
195
- * return ctx.json({ user })
196
- * }
197
- * ```
198
- */
199
- interface GravitoContext<V extends GravitoVariables = GravitoVariables> {
200
- /** The incoming request */
201
- readonly req: GravitoRequest;
202
- /**
203
- * Send a JSON response
204
- * @param data - Data to serialize as JSON
205
- * @param status - HTTP status code (default: 200)
206
- */
207
- json<T>(data: T, status?: ContentfulStatusCode): Response;
208
- /**
209
- * Send a plain text response
210
- * @param text - Text content
211
- * @param status - HTTP status code (default: 200)
212
- */
213
- text(text: string, status?: ContentfulStatusCode): Response;
214
- /**
215
- * Send an HTML response
216
- * @param html - HTML content
217
- * @param status - HTTP status code (default: 200)
218
- */
219
- html(html: string, status?: ContentfulStatusCode): Response;
220
- /**
221
- * Send a redirect response
222
- * @param url - Target URL
223
- * @param status - Redirect status code (default: 302)
224
- */
225
- redirect(url: string, status?: 301 | 302 | 303 | 307 | 308): Response;
226
- /**
227
- * Create a Response with no body
228
- * @param status - HTTP status code
229
- */
230
- body(data: BodyInit | null, status?: StatusCode): Response;
231
- /**
232
- * Stream a response
233
- * @param stream - ReadableStream to send
234
- * @param status - HTTP status code (default: 200)
235
- */
236
- stream(stream: ReadableStream, status?: ContentfulStatusCode): Response;
237
- /**
238
- * Send a 404 Not Found response
239
- */
240
- notFound(message?: string): Response;
241
- /**
242
- * Send a 403 Forbidden response
243
- */
244
- forbidden(message?: string): Response;
245
- /**
246
- * Send a 401 Unauthorized response
247
- */
248
- unauthorized(message?: string): Response;
249
- /**
250
- * Send a 400 Bad Request response
251
- */
252
- badRequest(message?: string): Response;
253
- /**
254
- * Forward the current request to another URL (Reverse Proxy)
255
- * @param target - Target URL or base URL to forward to
256
- * @param options - Optional proxy options
257
- */
258
- forward(target: string, options?: ProxyOptions): Promise<Response>;
259
- /**
260
- * Set a response header
261
- * @param name - Header name
262
- * @param value - Header value
263
- * @param options - Options (append: true to add multiple values)
264
- */
265
- header(name: string, value: string, options?: {
266
- append?: boolean;
267
- }): void;
268
- /**
269
- * Get a request header
270
- * @param name - Header name (case-insensitive)
271
- */
272
- header(name: string): string | undefined;
273
- /**
274
- * Set the response status code
275
- * @param code - HTTP status code
276
- */
277
- status(code: StatusCode): void;
278
- /**
279
- * Get a context variable
280
- * @param key - Variable key
281
- */
282
- get<K extends keyof V>(key: K): V[K];
283
- /**
284
- * Set a context variable
285
- * @param key - Variable key
286
- * @param value - Variable value
287
- */
288
- set<K extends keyof V>(key: K, value: V[K]): void;
289
- /**
290
- * Get the execution context (for Cloudflare Workers, etc.)
291
- */
292
- readonly executionCtx?: ExecutionContext;
293
- /**
294
- * Get environment bindings (for Cloudflare Workers, etc.)
295
- */
296
- readonly env?: Record<string, unknown>;
297
- /**
298
- * URL generator helper.
299
- * Generates a URL for a named route.
300
- */
301
- route: (name: string, params?: Record<string, any>, query?: Record<string, any>) => string;
302
- /**
303
- * Access the native context object from the underlying HTTP engine.
304
- *
305
- * ⚠️ WARNING: Using this ties your code to a specific adapter.
306
- * Prefer using the abstraction methods when possible.
307
- *
308
- * @example
309
- * ```typescript
310
- * // Only when absolutely necessary
311
- * const photonCtx = ctx.native as Context // Photon Context
312
- * ```
313
- */
314
- readonly native: unknown;
315
- /**
316
- * Access the RequestScopeManager for this request
317
- * Services resolved through this manager are scoped to the HTTP request lifetime.
318
- */
319
- requestScope(): any;
320
- /**
321
- * Resolve or create a request-scoped service
322
- *
323
- * @param key - Service key (string or symbol)
324
- * @param factory - Factory function to create the service if not cached
325
- * @returns The cached or newly created service instance
326
- *
327
- * @example
328
- * ```typescript
329
- * // Subsequent calls in the same request return the same instance
330
- * const cache = ctx.scoped('product:cache', () => new RequestProductCache())
331
- * ```
332
- */
333
- scoped<T>(key: string | symbol, factory: () => T): T;
334
- }
335
- /**
336
- * Next function for middleware chain
337
- */
338
- type GravitoNext = () => Promise<Response | undefined>;
339
- /**
340
- * GravitoHandler - Standard route handler type
341
- *
342
- * @typeParam V - Context variables type
343
- *
344
- * @example
345
- * ```typescript
346
- * const handler: GravitoHandler = async (ctx) => {
347
- * return ctx.json({ message: 'Hello, World!' })
348
- * }
349
- * ```
350
- */
351
- type GravitoHandler<V extends GravitoVariables = GravitoVariables> = (ctx: GravitoContext<V>) => Response | Promise<Response>;
352
- /**
353
- * GravitoMiddleware - Standard middleware type
354
- *
355
- * @typeParam V - Context variables type
356
- *
357
- * @example
358
- * ```typescript
359
- * const logger: GravitoMiddleware = async (ctx, next) => {
360
- * console.log(`${ctx.req.method} ${ctx.req.path}`)
361
- * await next()
362
- * return undefined
363
- * }
364
- * ```
365
- */
366
- type GravitoMiddleware<V extends GravitoVariables = GravitoVariables> = (ctx: GravitoContext<V>, next: GravitoNext) => Response | undefined | Promise<Response | undefined | undefined>;
367
- /**
368
- * Error handler type
369
- */
370
- type GravitoErrorHandler<V extends GravitoVariables = GravitoVariables> = (error: Error, ctx: GravitoContext<V>) => Response | Promise<Response>;
371
- /**
372
- * Not found handler type
373
- */
374
- type GravitoNotFoundHandler<V extends GravitoVariables = GravitoVariables> = (ctx: GravitoContext<V>) => Response | Promise<Response>;
375
-
376
- export type { ContentfulStatusCode as C, GravitoVariables as G, HttpMethod as H, ProxyOptions as P, StatusCode as S, ValidationTarget as V, GravitoHandler as a, GravitoMiddleware as b, GravitoErrorHandler as c, GravitoNotFoundHandler as d, GravitoContext as e, GravitoRequest as f, GravitoNext as g };
package/dist/compat.cjs DELETED
@@ -1,18 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __copyProps = (to, from, except, desc) => {
7
- if (from && typeof from === "object" || typeof from === "function") {
8
- for (let key of __getOwnPropNames(from))
9
- if (!__hasOwnProp.call(to, key) && key !== except)
10
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
- }
12
- return to;
13
- };
14
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
-
16
- // src/compat.ts
17
- var compat_exports = {};
18
- module.exports = __toCommonJS(compat_exports);
package/dist/compat.d.cts DELETED
@@ -1 +0,0 @@
1
- export { C as ContentfulStatusCode, e as Context, e as GravitoContext, c as GravitoErrorHandler, a as GravitoHandler, b as GravitoMiddleware, g as GravitoNext, d as GravitoNotFoundHandler, f as GravitoRequest, G as GravitoVariables, a as Handler, H as HttpMethod, b as MiddlewareHandler, g as Next, S as StatusCode, V as ValidationTarget, G as Variables } from './compat-CI8hiulX.cjs';