@cyanheads/mcp-ts-core 0.1.0-beta.12

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 (485) hide show
  1. package/CLAUDE.md +583 -0
  2. package/LICENSE +201 -0
  3. package/README.md +287 -0
  4. package/biome.json +103 -0
  5. package/dist/app.d.ts +82 -0
  6. package/dist/app.d.ts.map +1 -0
  7. package/dist/app.js +222 -0
  8. package/dist/app.js.map +1 -0
  9. package/dist/cli/init.d.ts +8 -0
  10. package/dist/cli/init.d.ts.map +1 -0
  11. package/dist/cli/init.js +161 -0
  12. package/dist/cli/init.js.map +1 -0
  13. package/dist/config/index.d.ts +349 -0
  14. package/dist/config/index.d.ts.map +1 -0
  15. package/dist/config/index.js +464 -0
  16. package/dist/config/index.js.map +1 -0
  17. package/dist/context.d.ts +119 -0
  18. package/dist/context.d.ts.map +1 -0
  19. package/dist/context.js +144 -0
  20. package/dist/context.js.map +1 -0
  21. package/dist/index.d.ts +8 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +9 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/mcp-server/prompts/prompt-registration.d.ts +33 -0
  26. package/dist/mcp-server/prompts/prompt-registration.d.ts.map +1 -0
  27. package/dist/mcp-server/prompts/prompt-registration.js +91 -0
  28. package/dist/mcp-server/prompts/prompt-registration.js.map +1 -0
  29. package/dist/mcp-server/prompts/utils/newPromptDefinition.d.ts +49 -0
  30. package/dist/mcp-server/prompts/utils/newPromptDefinition.d.ts.map +1 -0
  31. package/dist/mcp-server/prompts/utils/newPromptDefinition.js +39 -0
  32. package/dist/mcp-server/prompts/utils/newPromptDefinition.js.map +1 -0
  33. package/dist/mcp-server/prompts/utils/promptDefinition.d.ts +37 -0
  34. package/dist/mcp-server/prompts/utils/promptDefinition.d.ts.map +1 -0
  35. package/dist/mcp-server/prompts/utils/promptDefinition.js +2 -0
  36. package/dist/mcp-server/prompts/utils/promptDefinition.js.map +1 -0
  37. package/dist/mcp-server/resources/resource-registration.d.ts +27 -0
  38. package/dist/mcp-server/resources/resource-registration.d.ts.map +1 -0
  39. package/dist/mcp-server/resources/resource-registration.js +85 -0
  40. package/dist/mcp-server/resources/resource-registration.js.map +1 -0
  41. package/dist/mcp-server/resources/utils/newResourceDefinition.d.ts +84 -0
  42. package/dist/mcp-server/resources/utils/newResourceDefinition.d.ts.map +1 -0
  43. package/dist/mcp-server/resources/utils/newResourceDefinition.js +40 -0
  44. package/dist/mcp-server/resources/utils/newResourceDefinition.js.map +1 -0
  45. package/dist/mcp-server/resources/utils/newResourceHandlerFactory.d.ts +32 -0
  46. package/dist/mcp-server/resources/utils/newResourceHandlerFactory.d.ts.map +1 -0
  47. package/dist/mcp-server/resources/utils/newResourceHandlerFactory.js +103 -0
  48. package/dist/mcp-server/resources/utils/newResourceHandlerFactory.js.map +1 -0
  49. package/dist/mcp-server/resources/utils/resourceDefinition.d.ts +94 -0
  50. package/dist/mcp-server/resources/utils/resourceDefinition.d.ts.map +1 -0
  51. package/dist/mcp-server/resources/utils/resourceDefinition.js +2 -0
  52. package/dist/mcp-server/resources/utils/resourceDefinition.js.map +1 -0
  53. package/dist/mcp-server/resources/utils/resourceHandlerFactory.d.ts +14 -0
  54. package/dist/mcp-server/resources/utils/resourceHandlerFactory.d.ts.map +1 -0
  55. package/dist/mcp-server/resources/utils/resourceHandlerFactory.js +111 -0
  56. package/dist/mcp-server/resources/utils/resourceHandlerFactory.js.map +1 -0
  57. package/dist/mcp-server/roots/roots-registration.d.ts +22 -0
  58. package/dist/mcp-server/roots/roots-registration.d.ts.map +1 -0
  59. package/dist/mcp-server/roots/roots-registration.js +25 -0
  60. package/dist/mcp-server/roots/roots-registration.js.map +1 -0
  61. package/dist/mcp-server/server.d.ts +34 -0
  62. package/dist/mcp-server/server.d.ts.map +1 -0
  63. package/dist/mcp-server/server.js +62 -0
  64. package/dist/mcp-server/server.js.map +1 -0
  65. package/dist/mcp-server/tasks/core/sessionAwareTaskStore.d.ts +42 -0
  66. package/dist/mcp-server/tasks/core/sessionAwareTaskStore.d.ts.map +1 -0
  67. package/dist/mcp-server/tasks/core/sessionAwareTaskStore.js +70 -0
  68. package/dist/mcp-server/tasks/core/sessionAwareTaskStore.js.map +1 -0
  69. package/dist/mcp-server/tasks/core/storageBackedTaskStore.d.ts +109 -0
  70. package/dist/mcp-server/tasks/core/storageBackedTaskStore.d.ts.map +1 -0
  71. package/dist/mcp-server/tasks/core/storageBackedTaskStore.js +209 -0
  72. package/dist/mcp-server/tasks/core/storageBackedTaskStore.js.map +1 -0
  73. package/dist/mcp-server/tasks/core/taskManager.d.ts +103 -0
  74. package/dist/mcp-server/tasks/core/taskManager.d.ts.map +1 -0
  75. package/dist/mcp-server/tasks/core/taskManager.js +144 -0
  76. package/dist/mcp-server/tasks/core/taskManager.js.map +1 -0
  77. package/dist/mcp-server/tasks/core/taskTypes.d.ts +11 -0
  78. package/dist/mcp-server/tasks/core/taskTypes.d.ts.map +1 -0
  79. package/dist/mcp-server/tasks/core/taskTypes.js +13 -0
  80. package/dist/mcp-server/tasks/core/taskTypes.js.map +1 -0
  81. package/dist/mcp-server/tasks/utils/taskToolDefinition.d.ts +108 -0
  82. package/dist/mcp-server/tasks/utils/taskToolDefinition.d.ts.map +1 -0
  83. package/dist/mcp-server/tasks/utils/taskToolDefinition.js +14 -0
  84. package/dist/mcp-server/tasks/utils/taskToolDefinition.js.map +1 -0
  85. package/dist/mcp-server/tools/tool-registration.d.ts +49 -0
  86. package/dist/mcp-server/tools/tool-registration.d.ts.map +1 -0
  87. package/dist/mcp-server/tools/tool-registration.js +269 -0
  88. package/dist/mcp-server/tools/tool-registration.js.map +1 -0
  89. package/dist/mcp-server/tools/utils/newToolDefinition.d.ts +73 -0
  90. package/dist/mcp-server/tools/utils/newToolDefinition.d.ts.map +1 -0
  91. package/dist/mcp-server/tools/utils/newToolDefinition.js +45 -0
  92. package/dist/mcp-server/tools/utils/newToolDefinition.js.map +1 -0
  93. package/dist/mcp-server/tools/utils/newToolHandlerFactory.d.ts +33 -0
  94. package/dist/mcp-server/tools/utils/newToolHandlerFactory.d.ts.map +1 -0
  95. package/dist/mcp-server/tools/utils/newToolHandlerFactory.js +107 -0
  96. package/dist/mcp-server/tools/utils/newToolHandlerFactory.js.map +1 -0
  97. package/dist/mcp-server/tools/utils/toolDefinition.d.ts +118 -0
  98. package/dist/mcp-server/tools/utils/toolDefinition.d.ts.map +1 -0
  99. package/dist/mcp-server/tools/utils/toolDefinition.js +2 -0
  100. package/dist/mcp-server/tools/utils/toolDefinition.js.map +1 -0
  101. package/dist/mcp-server/tools/utils/toolHandlerFactory.d.ts +34 -0
  102. package/dist/mcp-server/tools/utils/toolHandlerFactory.d.ts.map +1 -0
  103. package/dist/mcp-server/tools/utils/toolHandlerFactory.js +68 -0
  104. package/dist/mcp-server/tools/utils/toolHandlerFactory.js.map +1 -0
  105. package/dist/mcp-server/transports/ITransport.d.ts +15 -0
  106. package/dist/mcp-server/transports/ITransport.d.ts.map +1 -0
  107. package/dist/mcp-server/transports/ITransport.js +2 -0
  108. package/dist/mcp-server/transports/ITransport.js.map +1 -0
  109. package/dist/mcp-server/transports/auth/authFactory.d.ts +11 -0
  110. package/dist/mcp-server/transports/auth/authFactory.d.ts.map +1 -0
  111. package/dist/mcp-server/transports/auth/authFactory.js +43 -0
  112. package/dist/mcp-server/transports/auth/authFactory.js.map +1 -0
  113. package/dist/mcp-server/transports/auth/authMiddleware.d.ts +24 -0
  114. package/dist/mcp-server/transports/auth/authMiddleware.d.ts.map +1 -0
  115. package/dist/mcp-server/transports/auth/authMiddleware.js +69 -0
  116. package/dist/mcp-server/transports/auth/authMiddleware.js.map +1 -0
  117. package/dist/mcp-server/transports/auth/lib/authContext.d.ts +34 -0
  118. package/dist/mcp-server/transports/auth/lib/authContext.d.ts.map +1 -0
  119. package/dist/mcp-server/transports/auth/lib/authContext.js +25 -0
  120. package/dist/mcp-server/transports/auth/lib/authContext.js.map +1 -0
  121. package/dist/mcp-server/transports/auth/lib/authTypes.d.ts +19 -0
  122. package/dist/mcp-server/transports/auth/lib/authTypes.d.ts.map +1 -0
  123. package/dist/mcp-server/transports/auth/lib/authTypes.js +2 -0
  124. package/dist/mcp-server/transports/auth/lib/authTypes.js.map +1 -0
  125. package/dist/mcp-server/transports/auth/lib/authUtils.d.ts +18 -0
  126. package/dist/mcp-server/transports/auth/lib/authUtils.d.ts.map +1 -0
  127. package/dist/mcp-server/transports/auth/lib/authUtils.js +64 -0
  128. package/dist/mcp-server/transports/auth/lib/authUtils.js.map +1 -0
  129. package/dist/mcp-server/transports/auth/lib/checkScopes.d.ts +25 -0
  130. package/dist/mcp-server/transports/auth/lib/checkScopes.d.ts.map +1 -0
  131. package/dist/mcp-server/transports/auth/lib/checkScopes.js +34 -0
  132. package/dist/mcp-server/transports/auth/lib/checkScopes.js.map +1 -0
  133. package/dist/mcp-server/transports/auth/lib/claimParser.d.ts +34 -0
  134. package/dist/mcp-server/transports/auth/lib/claimParser.d.ts.map +1 -0
  135. package/dist/mcp-server/transports/auth/lib/claimParser.js +58 -0
  136. package/dist/mcp-server/transports/auth/lib/claimParser.js.map +1 -0
  137. package/dist/mcp-server/transports/auth/lib/withAuth.d.ts +25 -0
  138. package/dist/mcp-server/transports/auth/lib/withAuth.d.ts.map +1 -0
  139. package/dist/mcp-server/transports/auth/lib/withAuth.js +30 -0
  140. package/dist/mcp-server/transports/auth/lib/withAuth.js.map +1 -0
  141. package/dist/mcp-server/transports/auth/strategies/authStrategy.d.ts +18 -0
  142. package/dist/mcp-server/transports/auth/strategies/authStrategy.d.ts.map +1 -0
  143. package/dist/mcp-server/transports/auth/strategies/authStrategy.js +2 -0
  144. package/dist/mcp-server/transports/auth/strategies/authStrategy.js.map +1 -0
  145. package/dist/mcp-server/transports/auth/strategies/jwtStrategy.d.ts +14 -0
  146. package/dist/mcp-server/transports/auth/strategies/jwtStrategy.d.ts.map +1 -0
  147. package/dist/mcp-server/transports/auth/strategies/jwtStrategy.js +86 -0
  148. package/dist/mcp-server/transports/auth/strategies/jwtStrategy.js.map +1 -0
  149. package/dist/mcp-server/transports/auth/strategies/oauthStrategy.d.ts +14 -0
  150. package/dist/mcp-server/transports/auth/strategies/oauthStrategy.d.ts.map +1 -0
  151. package/dist/mcp-server/transports/auth/strategies/oauthStrategy.js +113 -0
  152. package/dist/mcp-server/transports/auth/strategies/oauthStrategy.js.map +1 -0
  153. package/dist/mcp-server/transports/http/httpErrorHandler.d.ts +25 -0
  154. package/dist/mcp-server/transports/http/httpErrorHandler.d.ts.map +1 -0
  155. package/dist/mcp-server/transports/http/httpErrorHandler.js +112 -0
  156. package/dist/mcp-server/transports/http/httpErrorHandler.js.map +1 -0
  157. package/dist/mcp-server/transports/http/httpTransport.d.ts +47 -0
  158. package/dist/mcp-server/transports/http/httpTransport.d.ts.map +1 -0
  159. package/dist/mcp-server/transports/http/httpTransport.js +396 -0
  160. package/dist/mcp-server/transports/http/httpTransport.js.map +1 -0
  161. package/dist/mcp-server/transports/http/httpTypes.d.ts +17 -0
  162. package/dist/mcp-server/transports/http/httpTypes.d.ts.map +1 -0
  163. package/dist/mcp-server/transports/http/httpTypes.js +2 -0
  164. package/dist/mcp-server/transports/http/httpTypes.js.map +1 -0
  165. package/dist/mcp-server/transports/http/protectedResourceMetadata.d.ts +21 -0
  166. package/dist/mcp-server/transports/http/protectedResourceMetadata.d.ts.map +1 -0
  167. package/dist/mcp-server/transports/http/protectedResourceMetadata.js +44 -0
  168. package/dist/mcp-server/transports/http/protectedResourceMetadata.js.map +1 -0
  169. package/dist/mcp-server/transports/http/sessionIdUtils.d.ts +33 -0
  170. package/dist/mcp-server/transports/http/sessionIdUtils.d.ts.map +1 -0
  171. package/dist/mcp-server/transports/http/sessionIdUtils.js +54 -0
  172. package/dist/mcp-server/transports/http/sessionIdUtils.js.map +1 -0
  173. package/dist/mcp-server/transports/http/sessionStore.d.ts +87 -0
  174. package/dist/mcp-server/transports/http/sessionStore.d.ts.map +1 -0
  175. package/dist/mcp-server/transports/http/sessionStore.js +209 -0
  176. package/dist/mcp-server/transports/http/sessionStore.js.map +1 -0
  177. package/dist/mcp-server/transports/manager.d.ts +22 -0
  178. package/dist/mcp-server/transports/manager.d.ts.map +1 -0
  179. package/dist/mcp-server/transports/manager.js +62 -0
  180. package/dist/mcp-server/transports/manager.js.map +1 -0
  181. package/dist/mcp-server/transports/stdio/stdioTransport.d.ts +44 -0
  182. package/dist/mcp-server/transports/stdio/stdioTransport.d.ts.map +1 -0
  183. package/dist/mcp-server/transports/stdio/stdioTransport.js +63 -0
  184. package/dist/mcp-server/transports/stdio/stdioTransport.js.map +1 -0
  185. package/dist/services/graph/core/GraphService.d.ts +205 -0
  186. package/dist/services/graph/core/GraphService.d.ts.map +1 -0
  187. package/dist/services/graph/core/GraphService.js +231 -0
  188. package/dist/services/graph/core/GraphService.js.map +1 -0
  189. package/dist/services/graph/core/IGraphProvider.d.ts +295 -0
  190. package/dist/services/graph/core/IGraphProvider.d.ts.map +1 -0
  191. package/dist/services/graph/core/IGraphProvider.js +8 -0
  192. package/dist/services/graph/core/IGraphProvider.js.map +1 -0
  193. package/dist/services/graph/types.d.ts +107 -0
  194. package/dist/services/graph/types.d.ts.map +1 -0
  195. package/dist/services/graph/types.js +8 -0
  196. package/dist/services/graph/types.js.map +1 -0
  197. package/dist/services/llm/core/ILlmProvider.d.ts +86 -0
  198. package/dist/services/llm/core/ILlmProvider.d.ts.map +1 -0
  199. package/dist/services/llm/core/ILlmProvider.js +2 -0
  200. package/dist/services/llm/core/ILlmProvider.js.map +1 -0
  201. package/dist/services/llm/providers/openrouter.provider.d.ts +187 -0
  202. package/dist/services/llm/providers/openrouter.provider.d.ts.map +1 -0
  203. package/dist/services/llm/providers/openrouter.provider.js +302 -0
  204. package/dist/services/llm/providers/openrouter.provider.js.map +1 -0
  205. package/dist/services/llm/types.d.ts +16 -0
  206. package/dist/services/llm/types.d.ts.map +1 -0
  207. package/dist/services/llm/types.js +9 -0
  208. package/dist/services/llm/types.js.map +1 -0
  209. package/dist/services/speech/core/ISpeechProvider.d.ts +92 -0
  210. package/dist/services/speech/core/ISpeechProvider.d.ts.map +1 -0
  211. package/dist/services/speech/core/ISpeechProvider.js +34 -0
  212. package/dist/services/speech/core/ISpeechProvider.js.map +1 -0
  213. package/dist/services/speech/core/SpeechService.d.ts +87 -0
  214. package/dist/services/speech/core/SpeechService.d.ts.map +1 -0
  215. package/dist/services/speech/core/SpeechService.js +135 -0
  216. package/dist/services/speech/core/SpeechService.js.map +1 -0
  217. package/dist/services/speech/providers/elevenlabs.provider.d.ts +77 -0
  218. package/dist/services/speech/providers/elevenlabs.provider.d.ts.map +1 -0
  219. package/dist/services/speech/providers/elevenlabs.provider.js +199 -0
  220. package/dist/services/speech/providers/elevenlabs.provider.js.map +1 -0
  221. package/dist/services/speech/providers/whisper.provider.d.ts +94 -0
  222. package/dist/services/speech/providers/whisper.provider.d.ts.map +1 -0
  223. package/dist/services/speech/providers/whisper.provider.js +240 -0
  224. package/dist/services/speech/providers/whisper.provider.js.map +1 -0
  225. package/dist/services/speech/types.d.ts +173 -0
  226. package/dist/services/speech/types.d.ts.map +1 -0
  227. package/dist/services/speech/types.js +8 -0
  228. package/dist/services/speech/types.js.map +1 -0
  229. package/dist/storage/core/IStorageProvider.d.ts +159 -0
  230. package/dist/storage/core/IStorageProvider.d.ts.map +1 -0
  231. package/dist/storage/core/IStorageProvider.js +2 -0
  232. package/dist/storage/core/IStorageProvider.js.map +1 -0
  233. package/dist/storage/core/StorageService.d.ts +22 -0
  234. package/dist/storage/core/StorageService.d.ts.map +1 -0
  235. package/dist/storage/core/StorageService.js +151 -0
  236. package/dist/storage/core/StorageService.js.map +1 -0
  237. package/dist/storage/core/storageFactory.d.ts +66 -0
  238. package/dist/storage/core/storageFactory.d.ts.map +1 -0
  239. package/dist/storage/core/storageFactory.js +122 -0
  240. package/dist/storage/core/storageFactory.js.map +1 -0
  241. package/dist/storage/core/storageValidation.d.ts +77 -0
  242. package/dist/storage/core/storageValidation.d.ts.map +1 -0
  243. package/dist/storage/core/storageValidation.js +303 -0
  244. package/dist/storage/core/storageValidation.js.map +1 -0
  245. package/dist/storage/providers/cloudflare/d1Provider.d.ts +94 -0
  246. package/dist/storage/providers/cloudflare/d1Provider.d.ts.map +1 -0
  247. package/dist/storage/providers/cloudflare/d1Provider.js +347 -0
  248. package/dist/storage/providers/cloudflare/d1Provider.js.map +1 -0
  249. package/dist/storage/providers/cloudflare/kvProvider.d.ts +21 -0
  250. package/dist/storage/providers/cloudflare/kvProvider.d.ts.map +1 -0
  251. package/dist/storage/providers/cloudflare/kvProvider.js +183 -0
  252. package/dist/storage/providers/cloudflare/kvProvider.js.map +1 -0
  253. package/dist/storage/providers/cloudflare/r2Provider.d.ts +28 -0
  254. package/dist/storage/providers/cloudflare/r2Provider.d.ts.map +1 -0
  255. package/dist/storage/providers/cloudflare/r2Provider.js +222 -0
  256. package/dist/storage/providers/cloudflare/r2Provider.js.map +1 -0
  257. package/dist/storage/providers/fileSystem/fileSystemProvider.d.ts +20 -0
  258. package/dist/storage/providers/fileSystem/fileSystemProvider.d.ts.map +1 -0
  259. package/dist/storage/providers/fileSystem/fileSystemProvider.js +282 -0
  260. package/dist/storage/providers/fileSystem/fileSystemProvider.js.map +1 -0
  261. package/dist/storage/providers/inMemory/inMemoryProvider.d.ts +21 -0
  262. package/dist/storage/providers/inMemory/inMemoryProvider.d.ts.map +1 -0
  263. package/dist/storage/providers/inMemory/inMemoryProvider.js +139 -0
  264. package/dist/storage/providers/inMemory/inMemoryProvider.js.map +1 -0
  265. package/dist/storage/providers/supabase/supabase.types.d.ts +49 -0
  266. package/dist/storage/providers/supabase/supabase.types.d.ts.map +1 -0
  267. package/dist/storage/providers/supabase/supabase.types.js +8 -0
  268. package/dist/storage/providers/supabase/supabase.types.js.map +1 -0
  269. package/dist/storage/providers/supabase/supabaseProvider.d.ts +24 -0
  270. package/dist/storage/providers/supabase/supabaseProvider.d.ts.map +1 -0
  271. package/dist/storage/providers/supabase/supabaseProvider.js +209 -0
  272. package/dist/storage/providers/supabase/supabaseProvider.js.map +1 -0
  273. package/dist/testing/index.d.ts +53 -0
  274. package/dist/testing/index.d.ts.map +1 -0
  275. package/dist/testing/index.js +132 -0
  276. package/dist/testing/index.js.map +1 -0
  277. package/dist/types-global/errors.d.ts +83 -0
  278. package/dist/types-global/errors.d.ts.map +1 -0
  279. package/dist/types-global/errors.js +113 -0
  280. package/dist/types-global/errors.js.map +1 -0
  281. package/dist/utils/formatting/diffFormatter.d.ts +227 -0
  282. package/dist/utils/formatting/diffFormatter.d.ts.map +1 -0
  283. package/dist/utils/formatting/diffFormatter.js +369 -0
  284. package/dist/utils/formatting/diffFormatter.js.map +1 -0
  285. package/dist/utils/formatting/index.d.ts +9 -0
  286. package/dist/utils/formatting/index.d.ts.map +1 -0
  287. package/dist/utils/formatting/index.js +9 -0
  288. package/dist/utils/formatting/index.js.map +1 -0
  289. package/dist/utils/formatting/markdownBuilder.d.ts +543 -0
  290. package/dist/utils/formatting/markdownBuilder.d.ts.map +1 -0
  291. package/dist/utils/formatting/markdownBuilder.js +674 -0
  292. package/dist/utils/formatting/markdownBuilder.js.map +1 -0
  293. package/dist/utils/formatting/tableFormatter.d.ts +261 -0
  294. package/dist/utils/formatting/tableFormatter.d.ts.map +1 -0
  295. package/dist/utils/formatting/tableFormatter.js +456 -0
  296. package/dist/utils/formatting/tableFormatter.js.map +1 -0
  297. package/dist/utils/formatting/treeFormatter.d.ts +344 -0
  298. package/dist/utils/formatting/treeFormatter.d.ts.map +1 -0
  299. package/dist/utils/formatting/treeFormatter.js +400 -0
  300. package/dist/utils/formatting/treeFormatter.js.map +1 -0
  301. package/dist/utils/internal/encoding.d.ts +42 -0
  302. package/dist/utils/internal/encoding.d.ts.map +1 -0
  303. package/dist/utils/internal/encoding.js +87 -0
  304. package/dist/utils/internal/encoding.js.map +1 -0
  305. package/dist/utils/internal/error-handler/errorHandler.d.ts +140 -0
  306. package/dist/utils/internal/error-handler/errorHandler.d.ts.map +1 -0
  307. package/dist/utils/internal/error-handler/errorHandler.js +318 -0
  308. package/dist/utils/internal/error-handler/errorHandler.js.map +1 -0
  309. package/dist/utils/internal/error-handler/helpers.d.ts +98 -0
  310. package/dist/utils/internal/error-handler/helpers.d.ts.map +1 -0
  311. package/dist/utils/internal/error-handler/helpers.js +214 -0
  312. package/dist/utils/internal/error-handler/helpers.js.map +1 -0
  313. package/dist/utils/internal/error-handler/mappings.d.ts +85 -0
  314. package/dist/utils/internal/error-handler/mappings.d.ts.map +1 -0
  315. package/dist/utils/internal/error-handler/mappings.js +234 -0
  316. package/dist/utils/internal/error-handler/mappings.js.map +1 -0
  317. package/dist/utils/internal/error-handler/types.d.ts +160 -0
  318. package/dist/utils/internal/error-handler/types.d.ts.map +1 -0
  319. package/dist/utils/internal/error-handler/types.js +6 -0
  320. package/dist/utils/internal/error-handler/types.js.map +1 -0
  321. package/dist/utils/internal/health.d.ts +60 -0
  322. package/dist/utils/internal/health.d.ts.map +1 -0
  323. package/dist/utils/internal/health.js +46 -0
  324. package/dist/utils/internal/health.js.map +1 -0
  325. package/dist/utils/internal/logger.d.ts +300 -0
  326. package/dist/utils/internal/logger.d.ts.map +1 -0
  327. package/dist/utils/internal/logger.js +573 -0
  328. package/dist/utils/internal/logger.js.map +1 -0
  329. package/dist/utils/internal/performance.d.ts +78 -0
  330. package/dist/utils/internal/performance.d.ts.map +1 -0
  331. package/dist/utils/internal/performance.js +227 -0
  332. package/dist/utils/internal/performance.js.map +1 -0
  333. package/dist/utils/internal/requestContext.d.ts +200 -0
  334. package/dist/utils/internal/requestContext.d.ts.map +1 -0
  335. package/dist/utils/internal/requestContext.js +163 -0
  336. package/dist/utils/internal/requestContext.js.map +1 -0
  337. package/dist/utils/internal/runtime.d.ts +49 -0
  338. package/dist/utils/internal/runtime.d.ts.map +1 -0
  339. package/dist/utils/internal/runtime.js +90 -0
  340. package/dist/utils/internal/runtime.js.map +1 -0
  341. package/dist/utils/internal/startupBanner.d.ts +23 -0
  342. package/dist/utils/internal/startupBanner.d.ts.map +1 -0
  343. package/dist/utils/internal/startupBanner.js +34 -0
  344. package/dist/utils/internal/startupBanner.js.map +1 -0
  345. package/dist/utils/metrics/tokenCounter.d.ts +97 -0
  346. package/dist/utils/metrics/tokenCounter.d.ts.map +1 -0
  347. package/dist/utils/metrics/tokenCounter.js +162 -0
  348. package/dist/utils/metrics/tokenCounter.js.map +1 -0
  349. package/dist/utils/network/fetchWithTimeout.d.ts +91 -0
  350. package/dist/utils/network/fetchWithTimeout.d.ts.map +1 -0
  351. package/dist/utils/network/fetchWithTimeout.js +305 -0
  352. package/dist/utils/network/fetchWithTimeout.js.map +1 -0
  353. package/dist/utils/pagination/pagination.d.ts +157 -0
  354. package/dist/utils/pagination/pagination.d.ts.map +1 -0
  355. package/dist/utils/pagination/pagination.js +191 -0
  356. package/dist/utils/pagination/pagination.js.map +1 -0
  357. package/dist/utils/parsing/csvParser.d.ts +84 -0
  358. package/dist/utils/parsing/csvParser.d.ts.map +1 -0
  359. package/dist/utils/parsing/csvParser.js +132 -0
  360. package/dist/utils/parsing/csvParser.js.map +1 -0
  361. package/dist/utils/parsing/dateParser.d.ts +103 -0
  362. package/dist/utils/parsing/dateParser.d.ts.map +1 -0
  363. package/dist/utils/parsing/dateParser.js +142 -0
  364. package/dist/utils/parsing/dateParser.js.map +1 -0
  365. package/dist/utils/parsing/frontmatterParser.d.ts +91 -0
  366. package/dist/utils/parsing/frontmatterParser.d.ts.map +1 -0
  367. package/dist/utils/parsing/frontmatterParser.js +163 -0
  368. package/dist/utils/parsing/frontmatterParser.js.map +1 -0
  369. package/dist/utils/parsing/index.d.ts +15 -0
  370. package/dist/utils/parsing/index.d.ts.map +1 -0
  371. package/dist/utils/parsing/index.js +15 -0
  372. package/dist/utils/parsing/index.js.map +1 -0
  373. package/dist/utils/parsing/jsonParser.d.ts +115 -0
  374. package/dist/utils/parsing/jsonParser.d.ts.map +1 -0
  375. package/dist/utils/parsing/jsonParser.js +177 -0
  376. package/dist/utils/parsing/jsonParser.js.map +1 -0
  377. package/dist/utils/parsing/pdfParser.d.ts +563 -0
  378. package/dist/utils/parsing/pdfParser.d.ts.map +1 -0
  379. package/dist/utils/parsing/pdfParser.js +775 -0
  380. package/dist/utils/parsing/pdfParser.js.map +1 -0
  381. package/dist/utils/parsing/thinkBlock.d.ts +31 -0
  382. package/dist/utils/parsing/thinkBlock.d.ts.map +1 -0
  383. package/dist/utils/parsing/thinkBlock.js +31 -0
  384. package/dist/utils/parsing/thinkBlock.js.map +1 -0
  385. package/dist/utils/parsing/xmlParser.d.ts +69 -0
  386. package/dist/utils/parsing/xmlParser.d.ts.map +1 -0
  387. package/dist/utils/parsing/xmlParser.js +140 -0
  388. package/dist/utils/parsing/xmlParser.js.map +1 -0
  389. package/dist/utils/parsing/yamlParser.d.ts +64 -0
  390. package/dist/utils/parsing/yamlParser.d.ts.map +1 -0
  391. package/dist/utils/parsing/yamlParser.js +129 -0
  392. package/dist/utils/parsing/yamlParser.js.map +1 -0
  393. package/dist/utils/scheduling/scheduler.d.ts +174 -0
  394. package/dist/utils/scheduling/scheduler.d.ts.map +1 -0
  395. package/dist/utils/scheduling/scheduler.js +248 -0
  396. package/dist/utils/scheduling/scheduler.js.map +1 -0
  397. package/dist/utils/security/idGenerator.d.ts +189 -0
  398. package/dist/utils/security/idGenerator.d.ts.map +1 -0
  399. package/dist/utils/security/idGenerator.js +301 -0
  400. package/dist/utils/security/idGenerator.js.map +1 -0
  401. package/dist/utils/security/index.d.ts +8 -0
  402. package/dist/utils/security/index.d.ts.map +1 -0
  403. package/dist/utils/security/index.js +8 -0
  404. package/dist/utils/security/index.js.map +1 -0
  405. package/dist/utils/security/rateLimiter.d.ts +171 -0
  406. package/dist/utils/security/rateLimiter.d.ts.map +1 -0
  407. package/dist/utils/security/rateLimiter.js +294 -0
  408. package/dist/utils/security/rateLimiter.js.map +1 -0
  409. package/dist/utils/security/sanitization.d.ts +430 -0
  410. package/dist/utils/security/sanitization.d.ts.map +1 -0
  411. package/dist/utils/security/sanitization.js +759 -0
  412. package/dist/utils/security/sanitization.js.map +1 -0
  413. package/dist/utils/telemetry/index.d.ts +12 -0
  414. package/dist/utils/telemetry/index.d.ts.map +1 -0
  415. package/dist/utils/telemetry/index.js +12 -0
  416. package/dist/utils/telemetry/index.js.map +1 -0
  417. package/dist/utils/telemetry/instrumentation.d.ts +62 -0
  418. package/dist/utils/telemetry/instrumentation.d.ts.map +1 -0
  419. package/dist/utils/telemetry/instrumentation.js +223 -0
  420. package/dist/utils/telemetry/instrumentation.js.map +1 -0
  421. package/dist/utils/telemetry/metrics.d.ts +170 -0
  422. package/dist/utils/telemetry/metrics.d.ts.map +1 -0
  423. package/dist/utils/telemetry/metrics.js +205 -0
  424. package/dist/utils/telemetry/metrics.js.map +1 -0
  425. package/dist/utils/telemetry/semconv.d.ts +147 -0
  426. package/dist/utils/telemetry/semconv.d.ts.map +1 -0
  427. package/dist/utils/telemetry/semconv.js +159 -0
  428. package/dist/utils/telemetry/semconv.js.map +1 -0
  429. package/dist/utils/telemetry/trace.d.ts +141 -0
  430. package/dist/utils/telemetry/trace.d.ts.map +1 -0
  431. package/dist/utils/telemetry/trace.js +193 -0
  432. package/dist/utils/telemetry/trace.js.map +1 -0
  433. package/dist/utils/types/guards.d.ts +209 -0
  434. package/dist/utils/types/guards.d.ts.map +1 -0
  435. package/dist/utils/types/guards.js +229 -0
  436. package/dist/utils/types/guards.js.map +1 -0
  437. package/dist/utils/types/index.d.ts +6 -0
  438. package/dist/utils/types/index.d.ts.map +1 -0
  439. package/dist/utils/types/index.js +6 -0
  440. package/dist/utils/types/index.js.map +1 -0
  441. package/dist/worker.d.ts +59 -0
  442. package/dist/worker.d.ts.map +1 -0
  443. package/dist/worker.js +216 -0
  444. package/dist/worker.js.map +1 -0
  445. package/package.json +377 -0
  446. package/skills/README.md +38 -0
  447. package/skills/add-export/SKILL.md +49 -0
  448. package/skills/add-prompt/SKILL.md +97 -0
  449. package/skills/add-provider/SKILL.md +53 -0
  450. package/skills/add-resource/SKILL.md +107 -0
  451. package/skills/add-service/SKILL.md +113 -0
  452. package/skills/add-tool/SKILL.md +110 -0
  453. package/skills/api-auth/SKILL.md +173 -0
  454. package/skills/api-config/SKILL.md +68 -0
  455. package/skills/api-context/SKILL.md +321 -0
  456. package/skills/api-errors/SKILL.md +146 -0
  457. package/skills/api-services/SKILL.md +24 -0
  458. package/skills/api-services/references/graph.md +124 -0
  459. package/skills/api-services/references/llm.md +46 -0
  460. package/skills/api-services/references/speech.md +72 -0
  461. package/skills/api-testing/SKILL.md +263 -0
  462. package/skills/api-utils/SKILL.md +106 -0
  463. package/skills/api-utils/references/formatting.md +237 -0
  464. package/skills/api-utils/references/parsing.md +263 -0
  465. package/skills/api-utils/references/security.md +226 -0
  466. package/skills/api-workers/SKILL.md +165 -0
  467. package/skills/devcheck/SKILL.md +31 -0
  468. package/skills/maintenance/SKILL.md +52 -0
  469. package/skills/migrate-mcp-ts-template/SKILL.md +131 -0
  470. package/skills/release/SKILL.md +67 -0
  471. package/skills/setup/SKILL.md +89 -0
  472. package/skills/walkthrough-init/SKILL.md +50 -0
  473. package/templates/.env.example +17 -0
  474. package/templates/AGENTS.md +113 -0
  475. package/templates/CLAUDE.md +113 -0
  476. package/templates/_tsconfig.json +33 -0
  477. package/templates/biome.template.json +43 -0
  478. package/templates/package.json +26 -0
  479. package/templates/src/index.ts +16 -0
  480. package/templates/src/mcp-server/prompts/definitions/echo.prompt.ts +19 -0
  481. package/templates/src/mcp-server/resources/definitions/echo.resource.ts +30 -0
  482. package/templates/src/mcp-server/tools/definitions/echo.tool.ts +24 -0
  483. package/templates/vitest.config.ts +12 -0
  484. package/tsconfig.base.json +44 -0
  485. package/vitest.config.base.ts +38 -0
@@ -0,0 +1,227 @@
1
+ /**
2
+ * @fileoverview Performance utility for tool execution with modern observability.
3
+ * Wraps tool logic to measure duration, payload sizes, and memory usage, and
4
+ * records results to OpenTelemetry plus structured logs. No manual spans beyond
5
+ * the single wrapper span here per project guidelines.
6
+ * @module src/utils/internal/performance
7
+ */
8
+ import { SpanStatusCode, trace } from '@opentelemetry/api';
9
+ import { config } from '../../config/index.js';
10
+ import { McpError } from '../../types-global/errors.js';
11
+ import { logger } from '../../utils/internal/logger.js';
12
+ import { createCounter, createHistogram } from '../../utils/telemetry/metrics.js';
13
+ import { ATTR_CODE_FUNCTION, ATTR_CODE_NAMESPACE, ATTR_MCP_TOOL_DURATION_MS, ATTR_MCP_TOOL_ERROR_CODE, ATTR_MCP_TOOL_INPUT_BYTES, ATTR_MCP_TOOL_MEMORY_HEAP_USED_AFTER, ATTR_MCP_TOOL_MEMORY_HEAP_USED_BEFORE, ATTR_MCP_TOOL_MEMORY_HEAP_USED_DELTA, ATTR_MCP_TOOL_MEMORY_RSS_AFTER, ATTR_MCP_TOOL_MEMORY_RSS_BEFORE, ATTR_MCP_TOOL_MEMORY_RSS_DELTA, ATTR_MCP_TOOL_NAME, ATTR_MCP_TOOL_OUTPUT_BYTES, ATTR_MCP_TOOL_SUCCESS, } from '../../utils/telemetry/semconv.js';
14
+ // OTel metric instruments for tool execution (lazy-initialized on first use)
15
+ let toolCallCounter;
16
+ let toolCallDuration;
17
+ let toolCallErrors;
18
+ function getToolMetrics() {
19
+ toolCallCounter ??= createCounter('mcp.tool.calls', 'Total MCP tool invocations', '{calls}');
20
+ toolCallDuration ??= createHistogram('mcp.tool.duration', 'MCP tool execution duration', 'ms');
21
+ toolCallErrors ??= createCounter('mcp.tool.errors', 'Total MCP tool errors', '{errors}');
22
+ return { toolCallCounter, toolCallDuration, toolCallErrors };
23
+ }
24
+ // Environment-aware high-resolution timer
25
+ let performanceNow = () => Date.now(); // Fallback
26
+ /**
27
+ * Dynamically loads Node's `perf_hooks` module.
28
+ * Exposed as a named export so tests can inject a mock loader into
29
+ * {@link initHighResTimer} without patching the dynamic import machinery.
30
+ *
31
+ * @returns A promise resolving to the `perf_hooks` module shape (just the `performance` export).
32
+ */
33
+ export async function loadPerfHooks() {
34
+ return await import('node:perf_hooks');
35
+ }
36
+ /**
37
+ * Initializes the module-level high-resolution timer used by {@link nowMs}.
38
+ *
39
+ * Resolution priority:
40
+ * 1. `globalThis.performance.now` — available in Cloudflare Workers and modern browsers.
41
+ * 2. `node:perf_hooks` `performance.now` — loaded dynamically to stay Workers-compatible.
42
+ * 3. `Date.now()` — millisecond-precision fallback; a warning is logged when this path is taken.
43
+ *
44
+ * Must be called once during server startup (before any tool executions) to ensure
45
+ * sub-millisecond timing accuracy. Subsequent calls are safe but no-ops in practice
46
+ * because the module-level `performanceNow` closure is overwritten each time.
47
+ *
48
+ * @param perfLoader - Optional override for the `perf_hooks` import; defaults to
49
+ * {@link loadPerfHooks}. Inject a mock here in unit tests.
50
+ * @returns A promise that resolves once the timer is ready.
51
+ */
52
+ export async function initHighResTimer(perfLoader = loadPerfHooks) {
53
+ // Use a type assertion to safely access `performance` on `globalThis`,
54
+ // which is present in browser-like environments (e.g., Cloudflare Workers)
55
+ // but not in Node.js's default global type.
56
+ const globalWithPerf = globalThis;
57
+ if (typeof globalWithPerf.performance?.now === 'function') {
58
+ const perf = globalWithPerf.performance;
59
+ performanceNow = () => perf.now();
60
+ }
61
+ else {
62
+ try {
63
+ const { performance: nodePerformance } = await perfLoader();
64
+ performanceNow = () => nodePerformance.now();
65
+ }
66
+ catch (_e) {
67
+ performanceNow = () => Date.now();
68
+ logger.warning('Could not import perf_hooks, falling back to Date.now() for performance timing.');
69
+ }
70
+ }
71
+ }
72
+ /**
73
+ * Returns the current time in milliseconds using the highest-resolution timer
74
+ * available in this environment.
75
+ *
76
+ * The precision depends on which timer was selected by {@link initHighResTimer}:
77
+ * sub-millisecond after a successful init, millisecond-granular otherwise.
78
+ * The returned value is suitable for computing durations but its epoch origin
79
+ * is implementation-defined — do not treat it as a wall-clock timestamp.
80
+ *
81
+ * @returns Current time in milliseconds.
82
+ */
83
+ export const nowMs = () => performanceNow();
84
+ const toBytes = (payload) => {
85
+ if (payload == null)
86
+ return 0;
87
+ try {
88
+ const json = JSON.stringify(payload);
89
+ // Prefer Buffer when available (Node), otherwise TextEncoder (Web/Workers)
90
+ if (typeof Buffer !== 'undefined' && typeof Buffer.byteLength === 'function') {
91
+ return Buffer.byteLength(json, 'utf8');
92
+ }
93
+ if (typeof TextEncoder !== 'undefined') {
94
+ return new TextEncoder().encode(json).length;
95
+ }
96
+ return json.length;
97
+ }
98
+ catch {
99
+ return 0;
100
+ }
101
+ };
102
+ const zeroMemory = {
103
+ rss: 0,
104
+ heapUsed: 0,
105
+ heapTotal: 0,
106
+ external: 0,
107
+ arrayBuffers: 0,
108
+ };
109
+ const getMemoryUsage = () => typeof process !== 'undefined' && typeof process.memoryUsage === 'function'
110
+ ? process.memoryUsage()
111
+ : zeroMemory;
112
+ /**
113
+ * Wraps a tool's logic function with full observability: an OpenTelemetry span,
114
+ * OTel metric counters/histogram, structured log, and memory/payload size capture.
115
+ *
116
+ * The caller supplies the raw tool logic as `toolLogicFn`; this function handles
117
+ * all instrumentation so tool handlers stay free of telemetry boilerplate.
118
+ *
119
+ * On success the resolved value is passed through transparently.
120
+ * On failure the error is re-thrown after being recorded on the span and metrics;
121
+ * `McpError` instances surface their numeric `code` as the error code attribute.
122
+ *
123
+ * @template T - The resolved type of the tool's return value.
124
+ * @param toolLogicFn - Zero-argument async function containing the tool's business logic.
125
+ * @param context - Request context extended with `toolName`; used for span/log correlation.
126
+ * @param inputPayload - The raw input object passed to the tool, serialized to compute byte size.
127
+ * @returns A promise that resolves with the tool's return value or rejects with the original error.
128
+ *
129
+ * @example
130
+ * ```typescript
131
+ * const result = await measureToolExecution(
132
+ * () => myToolHandler(parsedInput),
133
+ * { ...requestContext, toolName: 'my_tool' },
134
+ * parsedInput,
135
+ * );
136
+ * ```
137
+ */
138
+ export async function measureToolExecution(toolLogicFn, context, inputPayload) {
139
+ const tracer = trace.getTracer(config.openTelemetry.serviceName, config.openTelemetry.serviceVersion);
140
+ const { toolName } = context;
141
+ return await tracer.startActiveSpan(`tool_execution:${toolName}`, async (span) => {
142
+ // Pre-capture lightweight metrics
143
+ const memBefore = getMemoryUsage();
144
+ const t0 = nowMs();
145
+ span.setAttributes({
146
+ [ATTR_CODE_FUNCTION]: toolName,
147
+ [ATTR_CODE_NAMESPACE]: 'mcp-tools',
148
+ [ATTR_MCP_TOOL_INPUT_BYTES]: toBytes(inputPayload),
149
+ [ATTR_MCP_TOOL_MEMORY_RSS_BEFORE]: memBefore.rss,
150
+ [ATTR_MCP_TOOL_MEMORY_HEAP_USED_BEFORE]: memBefore.heapUsed,
151
+ });
152
+ let ok = false;
153
+ let errorCode;
154
+ let output;
155
+ try {
156
+ const result = await toolLogicFn();
157
+ ok = true;
158
+ output = result;
159
+ span.setStatus({ code: SpanStatusCode.OK });
160
+ span.setAttribute(ATTR_MCP_TOOL_OUTPUT_BYTES, toBytes(output));
161
+ return result;
162
+ }
163
+ catch (err) {
164
+ if (err instanceof McpError)
165
+ errorCode = String(err.code);
166
+ else if (err instanceof Error)
167
+ errorCode = 'UNHANDLED_ERROR';
168
+ else
169
+ errorCode = 'UNKNOWN_ERROR';
170
+ if (err instanceof Error)
171
+ span.recordException(err);
172
+ span.setStatus({
173
+ code: SpanStatusCode.ERROR,
174
+ message: err instanceof Error ? err.message : String(err),
175
+ });
176
+ throw err;
177
+ }
178
+ finally {
179
+ const t1 = nowMs();
180
+ const durationMs = Number((t1 - t0).toFixed(2));
181
+ const memAfter = getMemoryUsage();
182
+ const rssDelta = memAfter.rss - memBefore.rss;
183
+ const heapUsedDelta = memAfter.heapUsed - memBefore.heapUsed;
184
+ span.setAttributes({
185
+ [ATTR_MCP_TOOL_DURATION_MS]: durationMs,
186
+ [ATTR_MCP_TOOL_SUCCESS]: ok,
187
+ [ATTR_MCP_TOOL_MEMORY_RSS_AFTER]: memAfter.rss,
188
+ [ATTR_MCP_TOOL_MEMORY_HEAP_USED_AFTER]: memAfter.heapUsed,
189
+ [ATTR_MCP_TOOL_MEMORY_RSS_DELTA]: rssDelta,
190
+ [ATTR_MCP_TOOL_MEMORY_HEAP_USED_DELTA]: heapUsedDelta,
191
+ });
192
+ if (errorCode)
193
+ span.setAttribute(ATTR_MCP_TOOL_ERROR_CODE, errorCode);
194
+ span.end();
195
+ // Record to OTel metric instruments (durable across restarts)
196
+ const m = getToolMetrics();
197
+ const metricAttrs = { [ATTR_MCP_TOOL_NAME]: toolName, [ATTR_MCP_TOOL_SUCCESS]: ok };
198
+ m.toolCallCounter.add(1, metricAttrs);
199
+ m.toolCallDuration.record(durationMs, metricAttrs);
200
+ if (!ok)
201
+ m.toolCallErrors.add(1, { [ATTR_MCP_TOOL_NAME]: toolName });
202
+ logger.info('Tool execution finished.', {
203
+ ...context,
204
+ metrics: {
205
+ durationMs,
206
+ isSuccess: ok,
207
+ errorCode,
208
+ inputBytes: toBytes(inputPayload),
209
+ outputBytes: toBytes(output),
210
+ memory: {
211
+ rss: {
212
+ before: memBefore.rss,
213
+ after: memAfter.rss,
214
+ delta: rssDelta,
215
+ },
216
+ heapUsed: {
217
+ before: memBefore.heapUsed,
218
+ after: memAfter.heapUsed,
219
+ delta: heapUsedDelta,
220
+ },
221
+ },
222
+ },
223
+ });
224
+ }
225
+ });
226
+ }
227
+ //# sourceMappingURL=performance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"performance.js","sourceRoot":"","sources":["../../../src/utils/internal/performance.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAE3D,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AAEpD,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC9E,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,yBAAyB,EACzB,wBA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L,CAAC"}
@@ -0,0 +1,200 @@
1
+ import type { AuthInfo } from '../../mcp-server/transports/auth/lib/authTypes.js';
2
+ /**
3
+ * Processed authentication data extracted from a validated JWT or OAuth token
4
+ * and attached to a {@link RequestContext} by {@link requestContextService.withAuthInfo}.
5
+ *
6
+ * Fields map directly to standard JWT claims: `clientId` ← `cid`/`client_id`,
7
+ * `scopes` ← `scp`/`scope` (split to array), `sub` ← `sub`, `tenantId` ← `tid`.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * const auth: AuthContext = ctx.auth!;
12
+ * if (auth.scopes.includes('tool:my_tool:read')) {
13
+ * // authorized
14
+ * }
15
+ * ```
16
+ */
17
+ export interface AuthContext {
18
+ /** The client application identifier (`cid` or `client_id` JWT claim). */
19
+ clientId: string;
20
+ /** Granted permission scopes derived from the `scp` or `scope` JWT claim. */
21
+ scopes: string[];
22
+ /** Subject identifier — the user or service principal (`sub` JWT claim). Falls back to `clientId` when `sub` is absent. */
23
+ sub: string;
24
+ /** Tenant identifier from the `tid` JWT claim. Present only for multi-tenant tokens. */
25
+ tenantId?: string;
26
+ /** The raw JWT or OAuth bearer token string. */
27
+ token: string;
28
+ /** Additional token payload properties not mapped to named fields. */
29
+ [key: string]: unknown;
30
+ }
31
+ /**
32
+ * Core context object associated with a single request or operation.
33
+ *
34
+ * Every handler invocation receives a `RequestContext` (wrapped in `Context`).
35
+ * It is the authoritative source for log correlation (`requestId`, `traceId`,
36
+ * `spanId`), multi-tenancy isolation (`tenantId`), and auth (`auth`).
37
+ *
38
+ * Optional fields (`traceId`, `spanId`) are injected automatically when an
39
+ * OpenTelemetry active span exists at context-creation time.
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * // Read-only access in a handler
44
+ * ctx.log.info('Handling request', { requestId: ctx.requestId, tenantId: ctx.tenantId });
45
+ * ```
46
+ */
47
+ export interface RequestContext {
48
+ /**
49
+ * Authentication data populated by {@link requestContextService.withAuthInfo}.
50
+ * `undefined` when the request is unauthenticated or auth mode is `none`.
51
+ */
52
+ auth?: AuthContext;
53
+ /**
54
+ * Unique identifier for this request, used to correlate log entries across
55
+ * service boundaries. Inherited from a parent context when provided;
56
+ * otherwise generated by {@link generateRequestContextId}.
57
+ */
58
+ requestId: string;
59
+ /**
60
+ * OpenTelemetry span ID from the active span at context-creation time.
61
+ * `undefined` when no active span exists.
62
+ */
63
+ spanId?: string;
64
+ /**
65
+ * Tenant identifier used for multi-tenancy data isolation.
66
+ * Resolved in priority order: `additionalContext.tenantId` →
67
+ * rest params → `parentContext.tenantId` → AsyncLocalStorage auth store.
68
+ */
69
+ tenantId?: string;
70
+ /**
71
+ * ISO 8601 UTC timestamp recorded at the moment this context was created.
72
+ */
73
+ timestamp: string;
74
+ /**
75
+ * OpenTelemetry trace ID from the active span at context-creation time.
76
+ * `undefined` when no active span exists.
77
+ */
78
+ traceId?: string;
79
+ /**
80
+ * Additional arbitrary key-value pairs for operation-specific context.
81
+ * Consumers must type-check before accessing extended properties.
82
+ */
83
+ [key: string]: unknown;
84
+ }
85
+ /**
86
+ * Parameters accepted by {@link requestContextService.createRequestContext}.
87
+ *
88
+ * Named fields (`parentContext`, `additionalContext`, `operation`) receive
89
+ * special handling. All other properties are spread directly onto the resulting
90
+ * {@link RequestContext} as-is, allowing ad-hoc context extension without
91
+ * modifying this interface.
92
+ *
93
+ * @example
94
+ * ```typescript
95
+ * const ctx = requestContextService.createRequestContext({
96
+ * operation: 'fetchUser',
97
+ * parentContext: incomingCtx,
98
+ * additionalContext: { userId: '123' },
99
+ * });
100
+ * ```
101
+ */
102
+ export interface CreateRequestContextParams {
103
+ /**
104
+ * Key-value pairs merged into the context after `parentContext` properties
105
+ * but before `requestId`/`timestamp` are pinned. Takes precedence over
106
+ * `parentContext` for overlapping keys. `requestId` and `timestamp` keys in
107
+ * `additionalContext` are silently stripped to prevent overwrites.
108
+ */
109
+ additionalContext?: Record<string, unknown>;
110
+ /**
111
+ * Human-readable label for the operation creating this context.
112
+ * Written onto the context as `context.operation` when provided.
113
+ */
114
+ operation?: string;
115
+ /**
116
+ * Parent context whose properties are inherited as the base. When
117
+ * `parentContext.requestId` is a non-empty string it is reused as-is,
118
+ * preserving the same request ID across a call chain.
119
+ */
120
+ parentContext?: Record<string, unknown> | RequestContext | undefined;
121
+ /** Any additional key-value pairs spread directly onto the resulting context. */
122
+ [key: string]: unknown;
123
+ }
124
+ /**
125
+ * Service for creating and enriching {@link RequestContext} instances.
126
+ *
127
+ * The two primary methods cover the full lifecycle:
128
+ * - {@link requestContextService.createRequestContext} — general-purpose context
129
+ * creation with parent propagation and OTel integration.
130
+ * - {@link requestContextService.withAuthInfo} — enriches a context with
131
+ * structured auth data from a validated token.
132
+ *
133
+ * @example
134
+ * ```typescript
135
+ * import { requestContextService } from '../../utils/internal/requestContext.js';
136
+ *
137
+ * // Create a root context for an incoming request
138
+ * const ctx = requestContextService.createRequestContext({ operation: 'handleRequest' });
139
+ *
140
+ * // Enrich with auth after token verification
141
+ * const authCtx = requestContextService.withAuthInfo(verifiedAuthInfo, ctx);
142
+ * ```
143
+ */
144
+ export declare const requestContextService: {
145
+ /**
146
+ * Creates a new {@link RequestContext} with a guaranteed unique `requestId`
147
+ * and current ISO 8601 `timestamp`.
148
+ *
149
+ * Merge order (later entries win, except `requestId`/`timestamp` which are
150
+ * always generated fresh or inherited):
151
+ * 1. `parentContext` properties (base)
152
+ * 2. Remaining spread params (everything in `params` except named fields)
153
+ * 3. `additionalContext` properties (`requestId`/`timestamp` stripped)
154
+ * 4. Resolved `requestId` and `timestamp` (canonical, never overwritten)
155
+ * 5. Resolved `tenantId` (see priority order in {@link RequestContext.tenantId})
156
+ * 6. `operation` (written as `context.operation` when provided)
157
+ * 7. OTel `traceId`/`spanId` from the active span (when present)
158
+ *
159
+ * @param params - Context creation parameters. Defaults to `{}`.
160
+ * @returns A fully constructed `RequestContext`.
161
+ *
162
+ * @example
163
+ * ```typescript
164
+ * // Minimal — generates a fresh requestId and timestamp
165
+ * const ctx = requestContextService.createRequestContext();
166
+ *
167
+ * // Propagate an existing request ID across a call chain
168
+ * const childCtx = requestContextService.createRequestContext({
169
+ * parentContext: incomingCtx,
170
+ * operation: 'processItem',
171
+ * additionalContext: { itemId: item.id },
172
+ * });
173
+ * ```
174
+ */
175
+ createRequestContext(params?: CreateRequestContextParams): RequestContext;
176
+ /**
177
+ * Creates a new {@link RequestContext} enriched with authentication information.
178
+ * This method populates the context with auth data from a validated token,
179
+ * including tenant ID, client ID, scopes, and subject.
180
+ *
181
+ * **Note:** This method builds and returns a `RequestContext` object only.
182
+ * It does NOT propagate auth into `AsyncLocalStorage`. ALS propagation is
183
+ * handled by the auth middleware via `authContext.run()`. If you need
184
+ * scope enforcement via `withRequiredScopes()`, ensure the call runs
185
+ * inside the middleware's ALS continuation.
186
+ *
187
+ * @param authInfo - The validated authentication information from JWT/OAuth token.
188
+ * @param parentContext - Optional parent context to inherit properties from.
189
+ * @returns A new `RequestContext` object with auth information populated.
190
+ *
191
+ * @example
192
+ * ```typescript
193
+ * const authInfo = await jwtStrategy.verify(token);
194
+ * const context = requestContextService.withAuthInfo(authInfo);
195
+ * // context now includes: { requestId, timestamp, tenantId, auth: {...}, ... }
196
+ * ```
197
+ */
198
+ withAuthInfo(authInfo: AuthInfo, parentContext?: Record<string, unknown> | RequestContext): RequestContext;
199
+ };
200
+ //# sourceMappingURL=requestContext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"requestContext.d.ts","sourceRoot":"","sources":["../../../src/utils/internal/requestContext.ts"],"names":[],"mappings":"AAyBA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,+CAA+C,CAAC;AAG9E;;;;;;;;;;;;;;GAcG;AACH,MAAM,WAAW,WAAW;IAC1B,0EAA0E;IAC1E,QAAQ,EAAE,MAAM,CAAC;IACjB,6EAA6E;IAC7E,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,2HAA2H;IAC3H,GAAG,EAAE,MAAM,CAAC;IACZ,wFAAwF;IACxF,QAAQ,C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ating and managing request contexts.
3
+ *
4
+ * A request context is an immutable-by-convention object that carries a unique
5
+ * request ID, ISO 8601 timestamp, optional tenant ID, and optional auth data.
6
+ * It is the primary carrier for log correlation, distributed tracing, and
7
+ * multi-tenancy isolation throughout the server.
8
+ *
9
+ * Key behaviors:
10
+ * - `requestId` is inherited from a parent context when provided, otherwise a
11
+ * new unique ID is generated via {@link generateRequestContextId}.
12
+ * - `tenantId` is resolved with the following priority (highest to lowest):
13
+ * `additionalContext.tenantId` → spread rest params → `parentContext.tenantId`
14
+ * → AsyncLocalStorage auth store (`authContext`).
15
+ * - OpenTelemetry `traceId` and `spanId` are automatically injected from the
16
+ * active span when one exists.
17
+ * - Auth data is populated separately via {@link requestContextService.withAuthInfo}
18
+ * and is NOT stored in AsyncLocalStorage by this module — ALS propagation is
19
+ * the responsibility of auth middleware.
20
+ *
21
+ * @module src/utils/internal/requestContext
22
+ */
23
+ import { trace } from '@opentelemetry/api';
24
+ import { authContext as alsAuthContext } from '../../mcp-server/transports/auth/lib/authContext.js';
25
+ import { generateRequestContextId } from '../../utils/security/idGenerator.js';
26
+ /**
27
+ * Singleton-like service object for managing request context operations.
28
+ * @private
29
+ */
30
+ const requestContextServiceInstance = {
31
+ /**
32
+ * Creates a new {@link RequestContext} with a guaranteed unique `requestId`
33
+ * and current ISO 8601 `timestamp`.
34
+ *
35
+ * Merge order (later entries win, except `requestId`/`timestamp` which are
36
+ * always generated fresh or inherited):
37
+ * 1. `parentContext` properties (base)
38
+ * 2. Remaining spread params (everything in `params` except named fields)
39
+ * 3. `additionalContext` properties (`requestId`/`timestamp` stripped)
40
+ * 4. Resolved `requestId` and `timestamp` (canonical, never overwritten)
41
+ * 5. Resolved `tenantId` (see priority order in {@link RequestContext.tenantId})
42
+ * 6. `operation` (written as `context.operation` when provided)
43
+ * 7. OTel `traceId`/`spanId` from the active span (when present)
44
+ *
45
+ * @param params - Context creation parameters. Defaults to `{}`.
46
+ * @returns A fully constructed `RequestContext`.
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * // Minimal — generates a fresh requestId and timestamp
51
+ * const ctx = requestContextService.createRequestContext();
52
+ *
53
+ * // Propagate an existing request ID across a call chain
54
+ * const childCtx = requestContextService.createRequestContext({
55
+ * parentContext: incomingCtx,
56
+ * operation: 'processItem',
57
+ * additionalContext: { itemId: item.id },
58
+ * });
59
+ * ```
60
+ */
61
+ createRequestContext(params = {}) {
62
+ const { parentContext, additionalContext, operation, ...rest } = params;
63
+ const inheritedContext = parentContext && typeof parentContext === 'object' ? { ...parentContext } : {};
64
+ const authStore = alsAuthContext.getStore();
65
+ const tenantIdFromAuth = authStore?.authInfo?.tenantId;
66
+ const requestId = typeof inheritedContext.requestId === 'string' && inheritedContext.requestId
67
+ ? inheritedContext.requestId
68
+ : generateRequestContextId();
69
+ const timestamp = new Date().toISOString();
70
+ const extractTenantId = (obj) => obj != null && typeof obj.tenantId === 'string' ? obj.tenantId : undefined;
71
+ const resolvedTenantId = extractTenantId(additionalContext) ??
72
+ extractTenantId(rest) ??
73
+ extractTenantId(inheritedContext) ??
74
+ tenantIdFromAuth;
75
+ // Strip system fields from additionalContext to prevent overwriting requestId/timestamp
76
+ const { requestId: _r, timestamp: _t, ...safeAdditional } = additionalContext && typeof additionalContext === 'object' ? additionalContext : {};
77
+ const context = {
78
+ ...inheritedContext,
79
+ ...rest, // Spread any other properties from the params object
80
+ ...safeAdditional,
81
+ requestId,
82
+ timestamp,
83
+ ...(resolvedTenantId ? { tenantId: resolvedTenantId } : {}),
84
+ ...(operation && typeof operation === 'string' ? { operation } : {}),
85
+ };
86
+ // --- OpenTelemetry Integration ---
87
+ const activeSpan = trace.getActiveSpan();
88
+ if (activeSpan && typeof activeSpan.spanContext === 'function') {
89
+ const spanContext = activeSpan.spanContext();
90
+ if (spanContext) {
91
+ context.traceId = spanContext.traceId;
92
+ context.spanId = spanContext.spanId;
93
+ }
94
+ }
95
+ // --- End OpenTelemetry Integration ---
96
+ return context;
97
+ },
98
+ /**
99
+ * Creates a new {@link RequestContext} enriched with authentication information.
100
+ * This method populates the context with auth data from a validated token,
101
+ * including tenant ID, client ID, scopes, and subject.
102
+ *
103
+ * **Note:** This method builds and returns a `RequestContext` object only.
104
+ * It does NOT propagate auth into `AsyncLocalStorage`. ALS propagation is
105
+ * handled by the auth middleware via `authContext.run()`. If you need
106
+ * scope enforcement via `withRequiredScopes()`, ensure the call runs
107
+ * inside the middleware's ALS continuation.
108
+ *
109
+ * @param authInfo - The validated authentication information from JWT/OAuth token.
110
+ * @param parentContext - Optional parent context to inherit properties from.
111
+ * @returns A new `RequestContext` object with auth information populated.
112
+ *
113
+ * @example
114
+ * ```typescript
115
+ * const authInfo = await jwtStrategy.verify(token);
116
+ * const context = requestContextService.withAuthInfo(authInfo);
117
+ * // context now includes: { requestId, timestamp, tenantId, auth: {...}, ... }
118
+ * ```
119
+ */
120
+ withAuthInfo(authInfo, parentContext) {
121
+ const baseContext = this.createRequestContext({
122
+ operation: 'withAuthInfo',
123
+ parentContext,
124
+ additionalContext: {
125
+ tenantId: authInfo.tenantId,
126
+ },
127
+ });
128
+ // Populate auth property with structured authentication context
129
+ const authContext = {
130
+ sub: authInfo.subject ?? authInfo.clientId,
131
+ scopes: authInfo.scopes,
132
+ clientId: authInfo.clientId,
133
+ token: authInfo.token,
134
+ ...(authInfo.tenantId ? { tenantId: authInfo.tenantId } : {}),
135
+ };
136
+ return {
137
+ ...baseContext,
138
+ auth: authContext,
139
+ };
140
+ },
141
+ };
142
+ /**
143
+ * Service for creating and enriching {@link RequestContext} instances.
144
+ *
145
+ * The two primary methods cover the full lifecycle:
146
+ * - {@link requestContextService.createRequestContext} — general-purpose context
147
+ * creation with parent propagation and OTel integration.
148
+ * - {@link requestContextService.withAuthInfo} — enriches a context with
149
+ * structured auth data from a validated token.
150
+ *
151
+ * @example
152
+ * ```typescript
153
+ * import { requestContextService } from '../../utils/internal/requestContext.js';
154
+ *
155
+ * // Create a root context for an incoming request
156
+ * const ctx = requestContextService.createRequestContext({ operation: 'handleRequest' });
157
+ *
158
+ * // Enrich with auth after token verification
159
+ * const authCtx = requestContextService.withAuthInfo(verifiedAuthInfo, ctx);
160
+ * ```
161
+ */
162
+ export const requestContextService = requestContextServiceInstance;
163
+ //# sourceMappingURL=requestContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"requestContext.js","sourceRoot":"","sources":["../../../src/utils/internal/requestContext.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAE3C,OAAO,EAAE,WAAW,IAAI,cAAc,EAAE,MAAM,iDAAiD,CAAC;AAEhG,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAuI3E;;;GAGG;AACH,MAAM,6BAA6B,GAAG;IACpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA6BG;IACH,oBAAoB,CAAC,SAAqC,EAAE;QAC1D,MAAM,EAAE,aAAa,EAAE,iBAAiB,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;QAExE,MAAM,gBAAgB,GACpB,aAAa,IAAI,OAAO,aAAa,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAEjF,MAAM,SAAS,GAAG,cAAc,CAAC,QAAQ,EAAE,CAAC;QAC5C,MAAM,gBAAgB,GAAG,SAAS,EAAE,QAAQ,EAAE,QAAQ,CAAC;QAEvD,MAAM,SAAS,GACb,OAAO,gBAAgB,CAAC,SAAS,KAAK,QAAQ,IAAI,gBAAgB,CAAC,SAAS;YAC1E,CAAC,CAAC,gBAAgB,CAAC,SAAS;YAC5B,CAAC,CAAC,wBAAwB,EAAE,CAAC;QACjC,MAAM,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QAE3C,MAAM,eAAe,GAAG,CAAC,GAAwC,EAAsB,EAAE,CAC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AC;IACjB,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,YAAY,CACV,QAAkB,EAClB,aAAwD;QAExD,MAAM,WAAW,GAAG,IAAI,CAAC,oBAAoB,CAAC;YAC5C,SAAS,EAAE,cAAc;YACzB,aAAa;YACb,iBAAiB,EAAE;gBACjB,QAAQ,EAAE,QAAQ,CAAC,QAAQ;aAC5B;SACF,CAAC,CAAC;QAEH,gEAAgE;QAChE,MAAM,WAAW,GAAgB;YAC/B,GAAG,EAAE,QAAQ,CAAC,OAAO,IAAI,QAAQ,CAAC,QAAQ;YAC1C,MAAM,EAAE,QAAQ,CAAC,MAAM;YACvB,QAAQ,EAAE,QAAQ,CAAC,QAAQ;YAC3B,KAAK,EAAE,QAAQ,CAAC,KAAK;YACrB,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,QAAQ,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC9D,CAAC;QAEF,OAAO;YACL,GAAG,WAAW;YACd,IAAI,EAAE,WAAW;SAClB,CAAC;IACJ,CAAC;CACF,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,6BAA6B,CAAC"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @fileoverview Runtime capability detection for multi-environment support.
3
+ * Detects presence of Node features, Web/Workers APIs, and common globals.
4
+ * @module src/utils/internal/runtime
5
+ */
6
+ /**
7
+ * Snapshot of runtime feature availability detected at module load time.
8
+ * All fields are booleans computed once via safe feature-detection; they never
9
+ * throw and never change after the module is first imported.
10
+ */
11
+ export interface RuntimeCapabilities {
12
+ /** True when the Node.js `Buffer` global is available. */
13
+ hasBuffer: boolean;
14
+ /** True when `globalThis.performance.now` is a callable function. */
15
+ hasPerformanceNow: boolean;
16
+ /** True when the `process` global is defined (Node.js, Bun, or some bundled envs). */
17
+ hasProcess: boolean;
18
+ /** True when `TextEncoder` is available on `globalThis`. */
19
+ hasTextEncoder: boolean;
20
+ /** True when running in a browser main thread (has `window`, not a Worker or Node). */
21
+ isBrowserLike: boolean;
22
+ /**
23
+ * True when running under Bun.
24
+ * Bun sets both `process.versions.node` and `process.versions.bun`,
25
+ * so `isNode` is also true in Bun environments.
26
+ */
27
+ isBun: boolean;
28
+ /** True when `process.versions.node` is a string (Node.js or Bun). */
29
+ isNode: boolean;
30
+ /** True when running inside a Web Worker or Cloudflare Worker (`WorkerGlobalScope` is present). */
31
+ isWorkerLike: boolean;
32
+ }
33
+ /**
34
+ * Singleton snapshot of runtime capabilities for the current environment.
35
+ * Computed once at module load; safe to read at any time without async.
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * import { runtimeCaps } from './runtime.js';
40
+ *
41
+ * if (runtimeCaps.hasBuffer) {
42
+ * // Node.js / Bun path — use Buffer for encoding
43
+ * } else {
44
+ * // Worker / browser path — use Web APIs
45
+ * }
46
+ * ```
47
+ */
48
+ export declare const runtimeCaps: RuntimeCapabilities;
49
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../src/utils/internal/runtime.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;GAIG;AACH,MAAM,WAAW,mBAAmB;IAClC,0DAA0D;IAC1D,SAAS,EAAE,OAAO,CAAC;IACnB,qEAAqE;IACrE,iBAAiB,EAAE,OAAO,CAAC;IAC3B,sFAAsF;IACtF,UAAU,EAAE,OAAO,CAAC;IACpB,4DAA4D;IAC5D,cAAc,EAAE,OAAO,CAAC;IACxB,uFAAuF;IACvF,aAAa,EAAE,OAAO,CAAC;IACvB;;;;OAIG;IACH,KAAK,EAAE,OAAO,CAAC;IACf,sEAAsE;IACtE,MAAM,EAAE,OAAO,CAAC;IAChB,mGAAmG;IACnG,YAAY,EAAE,OAAO,CAAC;CACvB;AAiED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,WAAW,EAAE,mBASzB,CAAC"}