@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
@@ -0,0 +1,134 @@
1
+ import type { ActionCallback } from '../HookManager';
2
+ import type { BackpressureConfig } from './BackpressureManager';
3
+ import type { EventOptions } from './EventOptions';
4
+ /**
5
+ * Event task for priority queue processing.
6
+ * @internal
7
+ */
8
+ export interface EventTask {
9
+ /**
10
+ * Unique identifier for this event task.
11
+ */
12
+ id: string;
13
+ /**
14
+ * Event hook name.
15
+ */
16
+ hook: string;
17
+ /**
18
+ * Event payload/arguments.
19
+ */
20
+ args: unknown;
21
+ /**
22
+ * Event options.
23
+ */
24
+ options: EventOptions;
25
+ /**
26
+ * Callbacks to execute for this event.
27
+ */
28
+ callbacks: ActionCallback[];
29
+ /**
30
+ * Timestamp when the event was created.
31
+ */
32
+ createdAt: number;
33
+ /**
34
+ * Timestamp when the event was enqueued (added to the queue).
35
+ * Used for priority escalation calculations.
36
+ * @internal
37
+ */
38
+ enqueuedAt: number;
39
+ /**
40
+ * Partition key for ordering (if applicable).
41
+ */
42
+ partitionKey?: string;
43
+ /**
44
+ * Number of retry attempts made.
45
+ * @internal
46
+ */
47
+ retryCount?: number;
48
+ /**
49
+ * Timestamp when the event first failed.
50
+ * @internal
51
+ */
52
+ firstFailedAt?: number;
53
+ /**
54
+ * Last error encountered.
55
+ * @internal
56
+ */
57
+ lastError?: Error;
58
+ }
59
+ /**
60
+ * Strategy for handling backpressure when the queue is full.
61
+ */
62
+ export type BackpressureStrategy = 'reject' | 'drop-oldest' | 'drop-newest' | 'ignore';
63
+ /**
64
+ * Configuration for the event priority queue.
65
+ */
66
+ export interface EventQueueConfig {
67
+ /**
68
+ * Maximum number of pending events in the queue.
69
+ * If exceeded, the backpressure strategy is applied.
70
+ * @default undefined (unbounded)
71
+ */
72
+ maxSize?: number;
73
+ /**
74
+ * Strategy to use when the queue is full.
75
+ * - 'reject': Throw an error (default)
76
+ * - 'drop-oldest': Drop the oldest lowest-priority event
77
+ * - 'drop-newest': Drop the incoming event
78
+ * - 'ignore': Silently drop the incoming event
79
+ * @default 'reject'
80
+ */
81
+ strategy?: BackpressureStrategy;
82
+ /**
83
+ * Advanced backpressure management configuration.
84
+ * When enabled, provides state-based flow control with multi-strategy support.
85
+ * If not provided, falls back to simple strategy-based backpressure.
86
+ * @default undefined (disabled, uses simple strategy)
87
+ */
88
+ backpressure?: BackpressureConfig;
89
+ }
90
+ /**
91
+ * Multi-priority queue depth snapshot (FS-103)
92
+ * Represents the current queue depth for each priority level.
93
+ * @internal
94
+ */
95
+ export interface MultiPriorityQueueDepth {
96
+ /** Queue depth for CRITICAL priority events */
97
+ critical: number;
98
+ /** Queue depth for HIGH priority events */
99
+ high: number;
100
+ /** Queue depth for NORMAL priority events */
101
+ normal: number;
102
+ /** Queue depth for LOW priority events */
103
+ low: number;
104
+ /** Total queue depth across all priorities */
105
+ total: number;
106
+ }
107
+ /**
108
+ * Window adjustment record for backpressure feedback (FS-103)
109
+ * Records when and why the aggregation window was adjusted.
110
+ * @internal
111
+ */
112
+ export interface WindowAdjustment {
113
+ /** Timestamp of the adjustment */
114
+ timestamp: number;
115
+ /** Previous window size in milliseconds */
116
+ from: number;
117
+ /** New window size in milliseconds */
118
+ to: number;
119
+ /** Backpressure state that triggered the adjustment */
120
+ reason: string;
121
+ }
122
+ /**
123
+ * Dead letter queue routing decision (FS-103)
124
+ * Determines whether an event should be routed to the DLQ.
125
+ * @internal
126
+ */
127
+ export interface DeadLetterDecision {
128
+ /** Whether the event should be routed to DLQ */
129
+ shouldRoute: boolean;
130
+ /** Reason for the decision (if applicable) */
131
+ reason?: string;
132
+ /** Suggested retry strategy */
133
+ retryStrategy?: 'immediate' | 'delayed' | 'dlq-only';
134
+ }
@@ -0,0 +1,8 @@
1
+ import { GravitoException } from './GravitoException';
2
+ /**
3
+ * Exception thrown when authentication fails.
4
+ * @public
5
+ */
6
+ export declare class AuthenticationException extends GravitoException {
7
+ constructor(message?: string);
8
+ }
@@ -0,0 +1,8 @@
1
+ import { GravitoException } from './GravitoException';
2
+ /**
3
+ * Exception thrown when user is not authorized to perform an action.
4
+ * @public
5
+ */
6
+ export declare class AuthorizationException extends GravitoException {
7
+ constructor(message?: string);
8
+ }
@@ -0,0 +1,9 @@
1
+ import type { ServiceKey } from '../Container';
2
+ /**
3
+ * CircularDependencyException - Thrown when the container detects an infinite loop.
4
+ *
5
+ * @module @gravito/core
6
+ */
7
+ export declare class CircularDependencyException extends Error {
8
+ constructor(key: ServiceKey, stack: ServiceKey[]);
9
+ }
@@ -0,0 +1,23 @@
1
+ import type { ContentfulStatusCode } from '../http/types';
2
+ /**
3
+ * Options for creating a GravitoException
4
+ * @public
5
+ */
6
+ export interface ExceptionOptions {
7
+ message?: string;
8
+ cause?: unknown;
9
+ i18nKey?: string;
10
+ i18nParams?: Record<string, string | number>;
11
+ }
12
+ /**
13
+ * Base exception class for consistent error handling.
14
+ * @public
15
+ */
16
+ export declare abstract class GravitoException extends Error {
17
+ readonly status: ContentfulStatusCode;
18
+ readonly code: string;
19
+ readonly i18nKey?: string;
20
+ readonly i18nParams?: Record<string, string | number>;
21
+ constructor(status: number, code: string, options?: ExceptionOptions);
22
+ getLocalizedMessage(t: (key: string, params?: Record<string, string | number>) => string): string;
23
+ }
@@ -0,0 +1,9 @@
1
+ import type { ContentfulStatusCode } from '../http/types';
2
+ import { type ExceptionOptions, GravitoException } from './GravitoException';
3
+ /**
4
+ * Generic HTTP Exception
5
+ * @public
6
+ */
7
+ export declare class HttpException extends GravitoException {
8
+ constructor(status: ContentfulStatusCode, options?: ExceptionOptions);
9
+ }
@@ -0,0 +1,10 @@
1
+ import { GravitoException } from './GravitoException';
2
+ /**
3
+ * Exception thrown when a database model is not found.
4
+ * @public
5
+ */
6
+ export declare class ModelNotFoundException extends GravitoException {
7
+ readonly model: string;
8
+ readonly id?: string | number;
9
+ constructor(model: string, id?: string | number);
10
+ }
@@ -0,0 +1,22 @@
1
+ import { GravitoException } from './GravitoException';
2
+ /**
3
+ * Structure of a validation error
4
+ * @public
5
+ */
6
+ export interface ValidationError {
7
+ field: string;
8
+ message: string;
9
+ code?: string;
10
+ }
11
+ /**
12
+ * Exception thrown when data validation fails.
13
+ * @public
14
+ */
15
+ export declare class ValidationException extends GravitoException {
16
+ readonly errors: ValidationError[];
17
+ redirectTo?: string;
18
+ input?: unknown;
19
+ constructor(errors: ValidationError[], message?: string);
20
+ withRedirect(url: string): this;
21
+ withInput(input: unknown): this;
22
+ }
@@ -0,0 +1,7 @@
1
+ export * from './AuthenticationException';
2
+ export * from './AuthorizationException';
3
+ export * from './CircularDependencyException';
4
+ export * from './GravitoException';
5
+ export * from './HttpException';
6
+ export * from './ModelNotFoundException';
7
+ export * from './ValidationException';
@@ -0,0 +1,69 @@
1
+ /**
2
+ * 原生加速器統一入口
3
+ * 遵循 Galaxy Architecture 的運行時自適應模式
4
+ * 與 RuntimeAdapter 模式保持一致
5
+ */
6
+ import type { CborAccelerator, NativeAcceleratorStatus } from './types';
7
+ /**
8
+ * 原生加速器類別
9
+ * 提供運行時自適應的 CBOR 編碼/解碼加速
10
+ * - 在 Bun 環境下優先使用 C 編譯器實現(bun:ffi)
11
+ * - 在非 Bun 環境或 FFI 不可用時自動降級到 JavaScript 實現
12
+ */
13
+ export declare class NativeAccelerator {
14
+ private static readonly DEBUG_ENV;
15
+ private static readonly DISABLE_ENV;
16
+ /**
17
+ * FFI 可用性緩存
18
+ * null: 未檢測, true: 可用, false: 不可用
19
+ */
20
+ private static available;
21
+ /**
22
+ * 當前加速器實例緩存
23
+ */
24
+ private static cborAccelerator;
25
+ /**
26
+ * 當前狀態
27
+ */
28
+ private static status;
29
+ /**
30
+ * 檢測原生 FFI 是否可用
31
+ * 偵測邏輯:
32
+ * 1. 檢查 GRAVITO_FFI_DISABLE 環境變數
33
+ * 2. 檢查 Bun 運行時可用性
34
+ * 3. 檢查 bun:ffi 的 cc() 是否可用
35
+ */
36
+ static isAvailable(): boolean;
37
+ /**
38
+ * 取得 CBOR 加速器實例
39
+ * 優先使用 Native,失敗則降級到 Fallback
40
+ */
41
+ static getCborAccelerator(): CborAccelerator;
42
+ /**
43
+ * 取得加速器狀態
44
+ */
45
+ static getStatus(): NativeAcceleratorStatus;
46
+ /**
47
+ * 重置加速器狀態(用於測試)
48
+ */
49
+ static reset(): void;
50
+ /**
51
+ * 解析 C 原始碼路徑
52
+ * 支援從原始碼目錄或 npm 套件的 src/ffi/native 目錄載入
53
+ */
54
+ private static resolveCSourcePath;
55
+ /**
56
+ * 載入原生 C 實現
57
+ * 使用 bun:ffi 的 cc() 動態編譯 C 代碼
58
+ * 優先從檔案載入完整實現,避免內聯限制
59
+ */
60
+ private static loadNativeImplementation;
61
+ /**
62
+ * 檢查是否啟用調試模式
63
+ */
64
+ private static isDebugEnabled;
65
+ /**
66
+ * 更新狀態
67
+ */
68
+ private static updateStatus;
69
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * 原生雜湊加速器
3
+ * 運行時自適應實現,遵循 Galaxy Architecture 的設計模式
4
+ *
5
+ * 架構:
6
+ * - 在 Bun 環境:使用 Bun.CryptoHasher(C 實現,高效)
7
+ * - 其他環境:自動降級到 node:crypto
8
+ * - 完全相同的 API 和結果保證
9
+ *
10
+ * 性能:
11
+ * - Bun 環境:2-3x 快於 node:crypto(消除 N-API 開銷)
12
+ * - 跨運行時:完全相容性
13
+ *
14
+ * 應用場景:
15
+ * - FileStore.hashKey() 熱路徑
16
+ * - Encrypter.hash() 加密雜湊
17
+ * - 任何需要高效雜湊計算的地方
18
+ */
19
+ import type { NativeHasherStatus } from './types';
20
+ /**
21
+ * 原生雜湊加速器統一入口
22
+ * 提供運行時自適應的 SHA-256/HMAC-SHA256 計算
23
+ *
24
+ * 使用範例:
25
+ * ```typescript
26
+ * // SHA-256
27
+ * const hash = NativeHasher.sha256('data')
28
+ *
29
+ * // HMAC-SHA256
30
+ * const hmac = NativeHasher.hmacSha256('secret', 'message')
31
+ *
32
+ * // 檢查狀態
33
+ * const status = NativeHasher.getStatus()
34
+ * console.log(`使用: ${status.runtime}`)
35
+ * ```
36
+ */
37
+ export declare class NativeHasher {
38
+ /**
39
+ * 當前加速器實例緩存
40
+ */
41
+ private static accelerator;
42
+ /**
43
+ * 當前狀態緩存
44
+ */
45
+ private static status;
46
+ /**
47
+ * 取得雜湊加速器實例
48
+ * 優先使用 Bun.CryptoHasher,失敗則降級到 node:crypto
49
+ *
50
+ * @returns 雜湊加速器實例
51
+ */
52
+ private static getAccelerator;
53
+ /**
54
+ * 檢測 Bun 運行時和 CryptoHasher 可用性
55
+ *
56
+ * @returns Bun.CryptoHasher 是否可用
57
+ */
58
+ private static isBunAvailable;
59
+ /**
60
+ * 更新狀態
61
+ *
62
+ * @param runtime - 當前使用的運行時
63
+ */
64
+ private static updateStatus;
65
+ /**
66
+ * 計算 SHA-256 雜湊
67
+ * 支援字串和二進制輸入
68
+ *
69
+ * @param input - 要雜湊的數據(字串或 Uint8Array)
70
+ * @returns 十六進制編碼的 SHA-256 雜湊值(64 字元)
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * const hash = NativeHasher.sha256('hello')
75
+ * // '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
76
+ *
77
+ * // 支援 Uint8Array
78
+ * const bytes = new TextEncoder().encode('hello')
79
+ * const hash2 = NativeHasher.sha256(bytes)
80
+ * // 相同結果
81
+ * ```
82
+ */
83
+ static sha256(input: string | Uint8Array): string;
84
+ /**
85
+ * 計算 HMAC-SHA256
86
+ * 用於認證消息完整性
87
+ *
88
+ * @param key - HMAC 密鑰
89
+ * @param data - 要雜湊的數據
90
+ * @returns 十六進制編碼的 HMAC-SHA256 值(64 字元)
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * const hmac = NativeHasher.hmacSha256('secret', 'message')
95
+ * // '8b1a9953c4611296aed9e132b8502cf413b1b881fed3e8d26ab'...
96
+ *
97
+ * // 適用於加密驗證
98
+ * const iv = Buffer.from('...').toString('base64')
99
+ * const encrypted = '...'
100
+ * const mac = NativeHasher.hmacSha256(key, iv + encrypted)
101
+ * ```
102
+ */
103
+ static hmacSha256(key: string, data: string): string;
104
+ /**
105
+ * 取得加速器狀態
106
+ * 用於診斷和性能監測
107
+ *
108
+ * @returns 加速器狀態報告
109
+ *
110
+ * @example
111
+ * ```typescript
112
+ * const status = NativeHasher.getStatus()
113
+ * console.log(`可用: ${status.available}`)
114
+ * console.log(`運行時: ${status.runtime}`)
115
+ *
116
+ * // 條件邏輯
117
+ * if (status.runtime === 'bun-crypto-hasher') {
118
+ * console.log('使用 Bun 原生實現(高效)')
119
+ * } else {
120
+ * console.log('使用 node:crypto(相容性回退)')
121
+ * }
122
+ * ```
123
+ */
124
+ static getStatus(): NativeHasherStatus;
125
+ /**
126
+ * 重置加速器狀態
127
+ * 主要用於測試目的,允許重新初始化運行時檢測
128
+ *
129
+ * @internal
130
+ * @example
131
+ * ```typescript
132
+ * // 測試中
133
+ * NativeHasher.reset()
134
+ * // 下一次呼叫會重新偵測運行時
135
+ * const status = NativeHasher.getStatus()
136
+ * ```
137
+ */
138
+ static reset(): void;
139
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * JavaScript CBOR 回退實現
3
+ * 用於非 Bun 環境或 FFI 不可用的情況
4
+ * 符合 RFC 7049 規範
5
+ */
6
+ import type { CborAccelerator } from './types';
7
+ /**
8
+ * CBOR 編碼器
9
+ * 將 JavaScript 物件編碼為 CBOR 二進制格式
10
+ */
11
+ export declare class CborFallbackEncoder implements CborAccelerator {
12
+ private static readonly DEFAULT_BUFFER_SIZE;
13
+ private static readonly MAX_DEPTH;
14
+ private static readonly MAX_BUFFER_SIZE;
15
+ private buffer;
16
+ private offset;
17
+ constructor();
18
+ /**
19
+ * 編碼 JavaScript 物件為 CBOR 格式
20
+ */
21
+ encode(data: Record<string, unknown>): Uint8Array;
22
+ /**
23
+ * 解碼 CBOR 二進制為 JavaScript 物件
24
+ */
25
+ decode(bytes: Uint8Array): Record<string, unknown>;
26
+ /**
27
+ * 確保 buffer 有足夠空間
28
+ */
29
+ private ensureCapacity;
30
+ /**
31
+ * 編寫一個位元組
32
+ */
33
+ private writeByte;
34
+ /**
35
+ * 編寫多個位元組
36
+ */
37
+ private writeBytes;
38
+ /**
39
+ * 編寫 CBOR 長度(Major Type + Additional Info)
40
+ */
41
+ private writeLength;
42
+ /**
43
+ * 遞迴編碼值
44
+ */
45
+ private encodeValue;
46
+ /**
47
+ * 編碼整數或浮點數
48
+ * 對於超過 uint32 範圍的整數,使用 float64 編碼(JavaScript 精度限制)
49
+ */
50
+ private encodeNumber;
51
+ /**
52
+ * 編碼字串
53
+ */
54
+ private encodeString;
55
+ /**
56
+ * 編碼位元組陣列
57
+ */
58
+ private encodeBytes;
59
+ /**
60
+ * 編碼陣列
61
+ */
62
+ private encodeArray;
63
+ /**
64
+ * 編碼物件(Map)
65
+ */
66
+ private encodeMap;
67
+ }
68
+ /**
69
+ * CBOR 解碼器
70
+ */
71
+ export declare class CborFallbackDecoder {
72
+ private static readonly MAX_DEPTH;
73
+ private data;
74
+ private offset;
75
+ constructor(data: Uint8Array);
76
+ /**
77
+ * 解碼 CBOR 資料
78
+ */
79
+ decode(): unknown;
80
+ /**
81
+ * 讀取一個位元組
82
+ */
83
+ private readByte;
84
+ /**
85
+ * 讀取固定長度的位元組
86
+ */
87
+ private readBytes;
88
+ /**
89
+ * 讀取 CBOR 長度
90
+ */
91
+ private readLength;
92
+ /**
93
+ * 遞迴解碼值
94
+ */
95
+ private decodeValue;
96
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * 雜湊加速器 JavaScript 回退實現
3
+ * 基於 node:crypto 標準庫
4
+ *
5
+ * 使用場景:
6
+ * - 非 Bun 環境(Node.js、Deno 等)
7
+ * - Bun CryptoHasher 不可用的情況
8
+ *
9
+ * 性能特性:
10
+ * - 短 key (<100 bytes):~1-2x 慢於 Bun.CryptoHasher(N-API 橋接開銷)
11
+ * - 長 payload:差異較小(主要計算時間)
12
+ * - 一致性:與 node:crypto 標準行為完全相同
13
+ */
14
+ import type { HashAccelerator } from './types';
15
+ /**
16
+ * Node.js crypto 回退實現
17
+ * 適用於非 Bun 環境
18
+ */
19
+ export declare class HashFallback implements HashAccelerator {
20
+ /**
21
+ * SHA-256 計算(回退實現)
22
+ * @param input - 輸入(字串或 Uint8Array)
23
+ * @returns 十六進制編碼的 SHA-256 雜湊值
24
+ */
25
+ sha256(input: string | Uint8Array): string;
26
+ /**
27
+ * HMAC-SHA256 計算(回退實現)
28
+ * @param key - 密鑰
29
+ * @param data - 要雜湊的數據
30
+ * @returns 十六進制編碼的 HMAC-SHA256 值
31
+ */
32
+ hmacSha256(key: string, data: string): string;
33
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * FFI (Foreign Function Interface) 模組導出
3
+ * 提供原生加速層支持(CBOR 編碼/解碼、雜湊計算)
4
+ */
5
+ export { CborFallbackDecoder, CborFallbackEncoder } from './cbor-fallback';
6
+ export { HashFallback } from './hash-fallback';
7
+ export { NativeAccelerator } from './NativeAccelerator';
8
+ export { NativeHasher } from './NativeHasher';
9
+ export type { CborAccelerator, FfiConfig, HashAccelerator, NativeAcceleratorStatus, NativeHasherStatus, } from './types';
10
+ export { CBOR_LENGTH_ENCODING, CBOR_MAJOR_TYPES, CBOR_SIMPLE_VALUES, } from './types';