apcore-js 0.5.0 → 0.6.0

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 (314) hide show
  1. package/dist/acl.d.ts +27 -0
  2. package/dist/acl.d.ts.map +1 -0
  3. package/dist/acl.js +175 -0
  4. package/dist/acl.js.map +1 -0
  5. package/dist/async-task.d.ts +90 -0
  6. package/dist/async-task.d.ts.map +1 -0
  7. package/dist/async-task.js +215 -0
  8. package/dist/async-task.js.map +1 -0
  9. package/dist/bindings.d.ts +12 -0
  10. package/dist/bindings.d.ts.map +1 -0
  11. package/dist/bindings.js +185 -0
  12. package/dist/bindings.js.map +1 -0
  13. package/dist/cancel.d.ts +14 -0
  14. package/dist/cancel.d.ts.map +1 -0
  15. package/dist/cancel.js +27 -0
  16. package/dist/cancel.js.map +1 -0
  17. package/dist/config.d.ts +9 -0
  18. package/dist/config.d.ts.map +1 -0
  19. package/dist/config.js +23 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/context.d.ts +50 -0
  22. package/dist/context.d.ts.map +1 -0
  23. package/dist/context.js +87 -0
  24. package/dist/context.js.map +1 -0
  25. package/dist/decorator.d.ts +57 -0
  26. package/dist/decorator.d.ts.map +1 -0
  27. package/dist/decorator.js +74 -0
  28. package/dist/decorator.js.map +1 -0
  29. package/dist/errors.d.ts +215 -0
  30. package/dist/errors.d.ts.map +1 -0
  31. package/dist/errors.js +246 -0
  32. package/dist/errors.js.map +1 -0
  33. package/dist/executor.d.ts +67 -0
  34. package/dist/executor.d.ts.map +1 -0
  35. package/dist/executor.js +372 -0
  36. package/dist/executor.js.map +1 -0
  37. package/dist/extensions.d.ts +58 -0
  38. package/dist/extensions.d.ts.map +1 -0
  39. package/dist/extensions.js +220 -0
  40. package/dist/extensions.js.map +1 -0
  41. package/{src/index.ts → dist/index.d.ts} +3 -62
  42. package/dist/index.d.ts.map +1 -0
  43. package/dist/index.js +43 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/middleware/adapters.d.ts +18 -0
  46. package/dist/middleware/adapters.d.ts.map +1 -0
  47. package/dist/middleware/adapters.js +25 -0
  48. package/dist/middleware/adapters.js.map +1 -0
  49. package/dist/middleware/base.d.ts +10 -0
  50. package/dist/middleware/base.d.ts.map +1 -0
  51. package/dist/middleware/base.js +15 -0
  52. package/dist/middleware/base.js.map +1 -0
  53. package/{src/middleware/index.ts → dist/middleware/index.d.ts} +1 -0
  54. package/dist/middleware/index.d.ts.map +1 -0
  55. package/dist/middleware/index.js +5 -0
  56. package/dist/middleware/index.js.map +1 -0
  57. package/dist/middleware/logging.d.ts +25 -0
  58. package/dist/middleware/logging.d.ts.map +1 -0
  59. package/dist/middleware/logging.js +64 -0
  60. package/dist/middleware/logging.js.map +1 -0
  61. package/dist/middleware/manager.d.ts +21 -0
  62. package/dist/middleware/manager.d.ts.map +1 -0
  63. package/dist/middleware/manager.js +77 -0
  64. package/dist/middleware/manager.js.map +1 -0
  65. package/dist/module.d.ts +31 -0
  66. package/dist/module.d.ts.map +1 -0
  67. package/dist/module.js +12 -0
  68. package/dist/module.js.map +1 -0
  69. package/dist/observability/context-logger.d.ts +54 -0
  70. package/dist/observability/context-logger.d.ts.map +1 -0
  71. package/dist/observability/context-logger.js +151 -0
  72. package/dist/observability/context-logger.js.map +1 -0
  73. package/{src/observability/index.ts → dist/observability/index.d.ts} +1 -0
  74. package/dist/observability/index.d.ts.map +1 -0
  75. package/dist/observability/index.js +4 -0
  76. package/dist/observability/index.js.map +1 -0
  77. package/dist/observability/metrics.d.ts +30 -0
  78. package/dist/observability/metrics.d.ts.map +1 -0
  79. package/dist/observability/metrics.js +177 -0
  80. package/dist/observability/metrics.js.map +1 -0
  81. package/dist/observability/tracing.d.ts +62 -0
  82. package/dist/observability/tracing.d.ts.map +1 -0
  83. package/dist/observability/tracing.js +184 -0
  84. package/dist/observability/tracing.js.map +1 -0
  85. package/dist/registry/dependencies.d.ts +6 -0
  86. package/dist/registry/dependencies.d.ts.map +1 -0
  87. package/dist/registry/dependencies.js +83 -0
  88. package/dist/registry/dependencies.js.map +1 -0
  89. package/dist/registry/entry-point.d.ts +6 -0
  90. package/dist/registry/entry-point.d.ts.map +1 -0
  91. package/dist/registry/entry-point.js +55 -0
  92. package/dist/registry/entry-point.js.map +1 -0
  93. package/{src/registry/index.ts → dist/registry/index.d.ts} +1 -0
  94. package/dist/registry/index.d.ts.map +1 -0
  95. package/dist/registry/index.js +8 -0
  96. package/dist/registry/index.js.map +1 -0
  97. package/dist/registry/metadata.d.ts +9 -0
  98. package/dist/registry/metadata.d.ts.map +1 -0
  99. package/dist/registry/metadata.js +105 -0
  100. package/dist/registry/metadata.js.map +1 -0
  101. package/dist/registry/registry.d.ts +102 -0
  102. package/dist/registry/registry.d.ts.map +1 -0
  103. package/dist/registry/registry.js +534 -0
  104. package/dist/registry/registry.js.map +1 -0
  105. package/dist/registry/scanner.d.ts +7 -0
  106. package/dist/registry/scanner.d.ts.map +1 -0
  107. package/dist/registry/scanner.js +164 -0
  108. package/dist/registry/scanner.js.map +1 -0
  109. package/dist/registry/schema-export.d.ts +9 -0
  110. package/dist/registry/schema-export.d.ts.map +1 -0
  111. package/dist/registry/schema-export.js +132 -0
  112. package/dist/registry/schema-export.js.map +1 -0
  113. package/dist/registry/types.d.ts +29 -0
  114. package/dist/registry/types.d.ts.map +1 -0
  115. package/dist/registry/types.js +5 -0
  116. package/dist/registry/types.js.map +1 -0
  117. package/dist/registry/validation.d.ts +9 -0
  118. package/dist/registry/validation.d.ts.map +1 -0
  119. package/dist/registry/validation.js +33 -0
  120. package/dist/registry/validation.js.map +1 -0
  121. package/dist/schema/annotations.d.ts +8 -0
  122. package/dist/schema/annotations.d.ts.map +1 -0
  123. package/dist/schema/annotations.js +52 -0
  124. package/dist/schema/annotations.js.map +1 -0
  125. package/dist/schema/exporter.d.ts +13 -0
  126. package/dist/schema/exporter.d.ts.map +1 -0
  127. package/dist/schema/exporter.js +71 -0
  128. package/dist/schema/exporter.js.map +1 -0
  129. package/dist/schema/index.d.ts +9 -0
  130. package/dist/schema/index.d.ts.map +1 -0
  131. package/{src/schema/index.ts → dist/schema/index.js} +1 -7
  132. package/dist/schema/index.js.map +1 -0
  133. package/dist/schema/loader.d.ts +30 -0
  134. package/dist/schema/loader.d.ts.map +1 -0
  135. package/dist/schema/loader.js +260 -0
  136. package/dist/schema/loader.js.map +1 -0
  137. package/dist/schema/ref-resolver.d.ts +19 -0
  138. package/dist/schema/ref-resolver.d.ts.map +1 -0
  139. package/dist/schema/ref-resolver.js +212 -0
  140. package/dist/schema/ref-resolver.js.map +1 -0
  141. package/dist/schema/strict.d.ts +7 -0
  142. package/dist/schema/strict.d.ts.map +1 -0
  143. package/dist/schema/strict.js +127 -0
  144. package/dist/schema/strict.js.map +1 -0
  145. package/dist/schema/types.d.ts +53 -0
  146. package/dist/schema/types.d.ts.map +1 -0
  147. package/dist/schema/types.js +31 -0
  148. package/dist/schema/types.js.map +1 -0
  149. package/dist/schema/validator.d.ts +16 -0
  150. package/dist/schema/validator.d.ts.map +1 -0
  151. package/dist/schema/validator.js +71 -0
  152. package/dist/schema/validator.js.map +1 -0
  153. package/dist/trace-context.d.ts +35 -0
  154. package/dist/trace-context.d.ts.map +1 -0
  155. package/dist/trace-context.js +86 -0
  156. package/dist/trace-context.js.map +1 -0
  157. package/dist/utils/index.d.ts +11 -0
  158. package/dist/utils/index.d.ts.map +1 -0
  159. package/dist/utils/index.js +32 -0
  160. package/dist/utils/index.js.map +1 -0
  161. package/dist/utils/pattern.d.ts +5 -0
  162. package/dist/utils/pattern.d.ts.map +1 -0
  163. package/dist/utils/pattern.js +31 -0
  164. package/dist/utils/pattern.js.map +1 -0
  165. package/package.json +8 -2
  166. package/.claude/settings.local.json +0 -12
  167. package/.github/workflows/ci.yml +0 -39
  168. package/.gitmessage +0 -60
  169. package/.pre-commit-config.yaml +0 -28
  170. package/CHANGELOG.md +0 -214
  171. package/CLAUDE.md +0 -68
  172. package/apcore-logo.svg +0 -79
  173. package/planning/acl-system/overview.md +0 -54
  174. package/planning/acl-system/plan.md +0 -92
  175. package/planning/acl-system/state.json +0 -76
  176. package/planning/acl-system/tasks/acl-core.md +0 -226
  177. package/planning/acl-system/tasks/acl-rule.md +0 -92
  178. package/planning/acl-system/tasks/conditional-rules.md +0 -259
  179. package/planning/acl-system/tasks/pattern-matching.md +0 -152
  180. package/planning/acl-system/tasks/yaml-loading.md +0 -271
  181. package/planning/core-executor/overview.md +0 -53
  182. package/planning/core-executor/plan.md +0 -88
  183. package/planning/core-executor/state.json +0 -76
  184. package/planning/core-executor/tasks/async-support.md +0 -106
  185. package/planning/core-executor/tasks/execution-pipeline.md +0 -113
  186. package/planning/core-executor/tasks/redaction.md +0 -85
  187. package/planning/core-executor/tasks/safety-checks.md +0 -65
  188. package/planning/core-executor/tasks/setup.md +0 -75
  189. package/planning/decorator-bindings/overview.md +0 -62
  190. package/planning/decorator-bindings/plan.md +0 -104
  191. package/planning/decorator-bindings/state.json +0 -87
  192. package/planning/decorator-bindings/tasks/binding-directory.md +0 -79
  193. package/planning/decorator-bindings/tasks/binding-loader.md +0 -148
  194. package/planning/decorator-bindings/tasks/explicit-schemas.md +0 -85
  195. package/planning/decorator-bindings/tasks/function-module.md +0 -127
  196. package/planning/decorator-bindings/tasks/module-factory.md +0 -89
  197. package/planning/decorator-bindings/tasks/schema-modes.md +0 -142
  198. package/planning/middleware-system/overview.md +0 -48
  199. package/planning/middleware-system/plan.md +0 -102
  200. package/planning/middleware-system/state.json +0 -65
  201. package/planning/middleware-system/tasks/adapters.md +0 -170
  202. package/planning/middleware-system/tasks/base.md +0 -115
  203. package/planning/middleware-system/tasks/logging-middleware.md +0 -304
  204. package/planning/middleware-system/tasks/manager.md +0 -313
  205. package/planning/observability/overview.md +0 -53
  206. package/planning/observability/plan.md +0 -119
  207. package/planning/observability/state.json +0 -98
  208. package/planning/observability/tasks/context-logger.md +0 -201
  209. package/planning/observability/tasks/exporters.md +0 -121
  210. package/planning/observability/tasks/metrics-collector.md +0 -162
  211. package/planning/observability/tasks/metrics-middleware.md +0 -141
  212. package/planning/observability/tasks/obs-logging-middleware.md +0 -179
  213. package/planning/observability/tasks/span-model.md +0 -120
  214. package/planning/observability/tasks/tracing-middleware.md +0 -179
  215. package/planning/overview.md +0 -81
  216. package/planning/registry-system/overview.md +0 -57
  217. package/planning/registry-system/plan.md +0 -114
  218. package/planning/registry-system/state.json +0 -109
  219. package/planning/registry-system/tasks/dependencies.md +0 -157
  220. package/planning/registry-system/tasks/entry-point.md +0 -148
  221. package/planning/registry-system/tasks/metadata.md +0 -198
  222. package/planning/registry-system/tasks/registry-core.md +0 -323
  223. package/planning/registry-system/tasks/scanner.md +0 -172
  224. package/planning/registry-system/tasks/schema-export.md +0 -261
  225. package/planning/registry-system/tasks/types.md +0 -124
  226. package/planning/registry-system/tasks/validation.md +0 -177
  227. package/planning/schema-system/overview.md +0 -56
  228. package/planning/schema-system/plan.md +0 -121
  229. package/planning/schema-system/state.json +0 -98
  230. package/planning/schema-system/tasks/exporter.md +0 -153
  231. package/planning/schema-system/tasks/loader.md +0 -106
  232. package/planning/schema-system/tasks/ref-resolver.md +0 -133
  233. package/planning/schema-system/tasks/strict-mode.md +0 -140
  234. package/planning/schema-system/tasks/typebox-generation.md +0 -133
  235. package/planning/schema-system/tasks/types-and-annotations.md +0 -160
  236. package/planning/schema-system/tasks/validator.md +0 -149
  237. package/src/acl.ts +0 -200
  238. package/src/async-task.ts +0 -267
  239. package/src/bindings.ts +0 -207
  240. package/src/cancel.ts +0 -32
  241. package/src/config.ts +0 -24
  242. package/src/context.ts +0 -160
  243. package/src/decorator.ts +0 -110
  244. package/src/errors.ts +0 -429
  245. package/src/executor.ts +0 -493
  246. package/src/extensions.ts +0 -265
  247. package/src/middleware/adapters.ts +0 -54
  248. package/src/middleware/base.ts +0 -33
  249. package/src/middleware/logging.ts +0 -103
  250. package/src/middleware/manager.ts +0 -105
  251. package/src/module.ts +0 -43
  252. package/src/observability/context-logger.ts +0 -203
  253. package/src/observability/metrics.ts +0 -214
  254. package/src/observability/tracing.ts +0 -252
  255. package/src/registry/dependencies.ts +0 -99
  256. package/src/registry/entry-point.ts +0 -64
  257. package/src/registry/metadata.ts +0 -111
  258. package/src/registry/registry.ts +0 -580
  259. package/src/registry/scanner.ts +0 -168
  260. package/src/registry/schema-export.ts +0 -181
  261. package/src/registry/types.ts +0 -32
  262. package/src/registry/validation.ts +0 -38
  263. package/src/schema/annotations.ts +0 -68
  264. package/src/schema/exporter.ts +0 -90
  265. package/src/schema/loader.ts +0 -273
  266. package/src/schema/ref-resolver.ts +0 -244
  267. package/src/schema/strict.ts +0 -136
  268. package/src/schema/types.ts +0 -73
  269. package/src/schema/validator.ts +0 -82
  270. package/src/trace-context.ts +0 -102
  271. package/src/utils/index.ts +0 -5
  272. package/src/utils/pattern.ts +0 -30
  273. package/tests/async-task.test.ts +0 -335
  274. package/tests/helpers.ts +0 -30
  275. package/tests/integration/test-acl-safety.test.ts +0 -269
  276. package/tests/integration/test-binding-executor.test.ts +0 -194
  277. package/tests/integration/test-e2e-flow.test.ts +0 -117
  278. package/tests/integration/test-error-propagation.test.ts +0 -259
  279. package/tests/integration/test-middleware-chain.test.ts +0 -120
  280. package/tests/integration/test-observability-integration.test.ts +0 -438
  281. package/tests/observability/test-context-logger.test.ts +0 -123
  282. package/tests/observability/test-metrics.test.ts +0 -186
  283. package/tests/observability/test-tracing.test.ts +0 -303
  284. package/tests/registry/test-dependencies.test.ts +0 -70
  285. package/tests/registry/test-entry-point.test.ts +0 -133
  286. package/tests/registry/test-metadata.test.ts +0 -265
  287. package/tests/registry/test-registry.test.ts +0 -1397
  288. package/tests/registry/test-scanner.test.ts +0 -257
  289. package/tests/registry/test-schema-export.test.ts +0 -355
  290. package/tests/registry/test-validation.test.ts +0 -75
  291. package/tests/schema/test-annotations.test.ts +0 -137
  292. package/tests/schema/test-exporter.test.ts +0 -172
  293. package/tests/schema/test-loader.test.ts +0 -461
  294. package/tests/schema/test-ref-resolver.test.ts +0 -530
  295. package/tests/schema/test-strict.test.ts +0 -348
  296. package/tests/schema/test-validator.test.ts +0 -64
  297. package/tests/test-acl.test.ts +0 -423
  298. package/tests/test-bindings.test.ts +0 -227
  299. package/tests/test-cancel.test.ts +0 -71
  300. package/tests/test-config.test.ts +0 -76
  301. package/tests/test-context.test.ts +0 -266
  302. package/tests/test-decorator.test.ts +0 -173
  303. package/tests/test-errors.test.ts +0 -647
  304. package/tests/test-executor-stream.test.ts +0 -208
  305. package/tests/test-executor.test.ts +0 -252
  306. package/tests/test-extensions.test.ts +0 -310
  307. package/tests/test-logging-middleware.test.ts +0 -150
  308. package/tests/test-middleware-manager.test.ts +0 -185
  309. package/tests/test-middleware.test.ts +0 -86
  310. package/tests/test-trace-context.test.ts +0 -251
  311. package/tests/utils/test-pattern.test.ts +0 -109
  312. package/tsconfig.build.json +0 -8
  313. package/tsconfig.json +0 -20
  314. package/vitest.config.ts +0 -18
@@ -1,73 +0,0 @@
1
- /**
2
- * Schema type definitions and data structures for the apcore schema system.
3
- */
4
-
5
- import type { TSchema } from '@sinclair/typebox';
6
- import { SchemaValidationError } from '../errors.js';
7
-
8
- export enum SchemaStrategy {
9
- YamlFirst = 'yaml_first',
10
- NativeFirst = 'native_first',
11
- YamlOnly = 'yaml_only',
12
- }
13
-
14
- export enum ExportProfile {
15
- MCP = 'mcp',
16
- OpenAI = 'openai',
17
- Anthropic = 'anthropic',
18
- Generic = 'generic',
19
- }
20
-
21
- export interface SchemaDefinition {
22
- moduleId: string;
23
- description: string;
24
- inputSchema: Record<string, unknown>;
25
- outputSchema: Record<string, unknown>;
26
- errorSchema?: Record<string, unknown> | null;
27
- definitions: Record<string, unknown>;
28
- version: string;
29
- documentation?: string | null;
30
- schemaUrl?: string | null;
31
- }
32
-
33
- export interface ResolvedSchema {
34
- jsonSchema: Record<string, unknown>;
35
- schema: TSchema;
36
- moduleId: string;
37
- direction: string;
38
- }
39
-
40
- export interface SchemaValidationErrorDetail {
41
- path: string;
42
- message: string;
43
- constraint?: string | null;
44
- expected?: unknown;
45
- actual?: unknown;
46
- }
47
-
48
- export interface SchemaValidationResult {
49
- valid: boolean;
50
- errors: SchemaValidationErrorDetail[];
51
- }
52
-
53
- export function validationResultToError(result: SchemaValidationResult): SchemaValidationError {
54
- if (result.valid) {
55
- throw new Error('Cannot convert valid result to error');
56
- }
57
- const errorDicts = result.errors.map((e) => ({
58
- path: e.path,
59
- message: e.message,
60
- constraint: e.constraint ?? null,
61
- expected: e.expected ?? null,
62
- actual: e.actual ?? null,
63
- }));
64
- return new SchemaValidationError('Schema validation failed', errorDicts);
65
- }
66
-
67
- export interface LLMExtensions {
68
- llmDescription?: string | null;
69
- examples?: unknown[] | null;
70
- sensitive: boolean;
71
- constraints?: string | null;
72
- deprecated?: Record<string, unknown> | null;
73
- }
@@ -1,82 +0,0 @@
1
- /**
2
- * SchemaValidator — validates runtime data against TypeBox schemas.
3
- */
4
-
5
- import { type TSchema } from '@sinclair/typebox';
6
- import { Value, type ValueError } from '@sinclair/typebox/value';
7
- import type { SchemaValidationErrorDetail, SchemaValidationResult } from './types.js';
8
- import { validationResultToError } from './types.js';
9
-
10
- export class SchemaValidator {
11
- private _coerceTypes: boolean;
12
-
13
- constructor(coerceTypes: boolean = true) {
14
- this._coerceTypes = coerceTypes;
15
- }
16
-
17
- validate(data: Record<string, unknown>, schema: TSchema): SchemaValidationResult {
18
- if (this._coerceTypes) {
19
- try {
20
- Value.Decode(schema, data);
21
- return { valid: true, errors: [] };
22
- } catch {
23
- return { valid: false, errors: this._collectErrors(schema, data) };
24
- }
25
- }
26
-
27
- if (Value.Check(schema, data)) {
28
- return { valid: true, errors: [] };
29
- }
30
- return { valid: false, errors: this._collectErrors(schema, data) };
31
- }
32
-
33
- validateInput(data: Record<string, unknown>, schema: TSchema): Record<string, unknown> {
34
- return this._validateAndReturn(data, schema);
35
- }
36
-
37
- validateOutput(data: Record<string, unknown>, schema: TSchema): Record<string, unknown> {
38
- return this._validateAndReturn(data, schema);
39
- }
40
-
41
- private _validateAndReturn(data: Record<string, unknown>, schema: TSchema): Record<string, unknown> {
42
- if (this._coerceTypes) {
43
- try {
44
- return Value.Decode(schema, data) as Record<string, unknown>;
45
- } catch {
46
- const result: SchemaValidationResult = {
47
- valid: false,
48
- errors: this._collectErrors(schema, data),
49
- };
50
- throw validationResultToError(result);
51
- }
52
- }
53
-
54
- if (Value.Check(schema, data)) {
55
- return data;
56
- }
57
-
58
- const result: SchemaValidationResult = {
59
- valid: false,
60
- errors: this._collectErrors(schema, data),
61
- };
62
- throw validationResultToError(result);
63
- }
64
-
65
- private _collectErrors(schema: TSchema, data: unknown): SchemaValidationErrorDetail[] {
66
- const errors: SchemaValidationErrorDetail[] = [];
67
- for (const error of Value.Errors(schema, data)) {
68
- errors.push(this._typeboxErrorToDetail(error));
69
- }
70
- return errors;
71
- }
72
-
73
- private _typeboxErrorToDetail(error: ValueError): SchemaValidationErrorDetail {
74
- return {
75
- path: error.path || '/',
76
- message: error.message,
77
- constraint: String(error.type),
78
- expected: error.schema,
79
- actual: error.value,
80
- };
81
- }
82
- }
@@ -1,102 +0,0 @@
1
- /**
2
- * W3C Trace Context support: TraceParent parsing and TraceContext injection/extraction.
3
- */
4
-
5
- import { randomBytes } from 'node:crypto';
6
- import type { Context } from './context.js';
7
- import type { Span } from './observability/tracing.js';
8
-
9
- const TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
10
-
11
- export interface TraceParent {
12
- readonly version: string; // "00"
13
- readonly traceId: string; // 32 lowercase hex chars
14
- readonly parentId: string; // 16 lowercase hex chars
15
- readonly traceFlags: string; // "01" (sampled) or "00"
16
- }
17
-
18
- export class TraceContext {
19
- /**
20
- * Build a traceparent header dict from an apcore Context.
21
- *
22
- * Converts `context.traceId` (UUID with dashes) to the 32-hex
23
- * format required by the W3C traceparent spec. Uses the last span's
24
- * `spanId` from the tracing stack if available, otherwise generates
25
- * a random 16-hex parent id.
26
- */
27
- static inject(context: Context): Record<string, string> {
28
- const traceIdHex = context.traceId.replace(/-/g, '');
29
-
30
- const spansStack = context.data['_tracing_spans'] as Span[] | undefined;
31
- let parentId: string;
32
- if (spansStack && spansStack.length > 0) {
33
- parentId = spansStack[spansStack.length - 1].spanId;
34
- } else {
35
- parentId = randomBytes(8).toString('hex');
36
- }
37
-
38
- const traceparent = `00-${traceIdHex}-${parentId}-01`;
39
- return { traceparent };
40
- }
41
-
42
- /**
43
- * Parse the `traceparent` header from the given headers object.
44
- *
45
- * Returns `null` if the header is missing or malformed.
46
- */
47
- static extract(headers: Record<string, string>): TraceParent | null {
48
- const raw = headers['traceparent'];
49
- if (raw === undefined) {
50
- return null;
51
- }
52
- const match = TRACEPARENT_RE.exec(raw.trim().toLowerCase());
53
- if (match === null) {
54
- return null;
55
- }
56
- const version = match[1];
57
- const traceId = match[2];
58
- const parentId = match[3];
59
- if (version === 'ff') {
60
- return null;
61
- }
62
- if (traceId === '0'.repeat(32) || parentId === '0'.repeat(16)) {
63
- return null;
64
- }
65
- return Object.freeze({
66
- version,
67
- traceId,
68
- parentId,
69
- traceFlags: match[4],
70
- });
71
- }
72
-
73
- /**
74
- * Strictly parse a traceparent string, throwing on invalid format.
75
- *
76
- * @throws {Error} If the traceparent does not match the expected
77
- * `00-<32 hex>-<16 hex>-<2 hex>` format.
78
- */
79
- static fromTraceparent(traceparent: string): TraceParent {
80
- const match = TRACEPARENT_RE.exec(traceparent.trim().toLowerCase());
81
- if (match === null) {
82
- throw new Error(
83
- `Malformed traceparent: ${JSON.stringify(traceparent.slice(0, 100))}. Expected format: 00-<32 hex>-<16 hex>-<2 hex>`,
84
- );
85
- }
86
- const version = match[1];
87
- const traceId = match[2];
88
- const parentId = match[3];
89
- if (version === 'ff') {
90
- throw new Error('Invalid traceparent: version ff is not allowed');
91
- }
92
- if (traceId === '0'.repeat(32) || parentId === '0'.repeat(16)) {
93
- throw new Error('Invalid traceparent: all-zero trace_id or parent_id');
94
- }
95
- return Object.freeze({
96
- version,
97
- traceId,
98
- parentId,
99
- traceFlags: match[4],
100
- });
101
- }
102
- }
@@ -1,5 +0,0 @@
1
- export { matchPattern } from './pattern.js';
2
-
3
- export function deepCopy<T>(obj: T): T {
4
- return JSON.parse(JSON.stringify(obj));
5
- }
@@ -1,30 +0,0 @@
1
- /**
2
- * Wildcard pattern matching for module IDs (Algorithm A08).
3
- */
4
-
5
- export function matchPattern(pattern: string, moduleId: string): boolean {
6
- if (pattern === '*') return true;
7
- if (!pattern.includes('*')) return pattern === moduleId;
8
-
9
- const segments = pattern.split('*');
10
- let pos = 0;
11
-
12
- if (!pattern.startsWith('*')) {
13
- if (!moduleId.startsWith(segments[0])) return false;
14
- pos = segments[0].length;
15
- }
16
-
17
- for (let i = 1; i < segments.length; i++) {
18
- const segment = segments[i];
19
- if (!segment) continue;
20
- const idx = moduleId.indexOf(segment, pos);
21
- if (idx === -1) return false;
22
- pos = idx + segment.length;
23
- }
24
-
25
- if (!pattern.endsWith('*')) {
26
- if (!moduleId.endsWith(segments[segments.length - 1])) return false;
27
- }
28
-
29
- return true;
30
- }
@@ -1,335 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { Type } from '@sinclair/typebox';
3
- import { AsyncTaskManager, TaskStatus } from '../src/async-task.js';
4
- import type { TaskInfo } from '../src/async-task.js';
5
- import { Executor } from '../src/executor.js';
6
- import { FunctionModule } from '../src/decorator.js';
7
- import { Registry } from '../src/registry/registry.js';
8
-
9
- function createRegistry(): Registry {
10
- const registry = new Registry();
11
-
12
- const simpleModule = new FunctionModule({
13
- execute: (inputs) => ({ value: (inputs['x'] as number) ?? 0 }),
14
- moduleId: 'test.simple',
15
- inputSchema: Type.Object({ x: Type.Optional(Type.Number()) }),
16
- outputSchema: Type.Object({ value: Type.Number() }),
17
- description: 'Simple module',
18
- });
19
-
20
- const failingModule = new FunctionModule({
21
- execute: () => { throw new Error('intentional failure'); },
22
- moduleId: 'test.failing',
23
- inputSchema: Type.Object({}),
24
- outputSchema: Type.Object({}),
25
- description: 'Failing module',
26
- });
27
-
28
- const slowModule = new FunctionModule({
29
- execute: async (inputs) => {
30
- const ms = (inputs['delay'] as number) ?? 1000;
31
- await new Promise((resolve) => setTimeout(resolve, ms));
32
- return { done: true };
33
- },
34
- moduleId: 'test.slow',
35
- inputSchema: Type.Object({ delay: Type.Optional(Type.Number()) }),
36
- outputSchema: Type.Object({ done: Type.Boolean() }),
37
- description: 'Slow module',
38
- });
39
-
40
- registry.register('test.simple', simpleModule);
41
- registry.register('test.failing', failingModule);
42
- registry.register('test.slow', slowModule);
43
-
44
- return registry;
45
- }
46
-
47
- function createManager(maxConcurrent: number = 10): { manager: AsyncTaskManager; executor: Executor } {
48
- const registry = createRegistry();
49
- const executor = new Executor({ registry });
50
- const manager = new AsyncTaskManager(executor, maxConcurrent);
51
- return { manager, executor };
52
- }
53
-
54
- function wait(ms: number): Promise<void> {
55
- return new Promise((resolve) => setTimeout(resolve, ms));
56
- }
57
-
58
- describe('TaskStatus', () => {
59
- it('has correct enum values', () => {
60
- expect(TaskStatus.PENDING).toBe('pending');
61
- expect(TaskStatus.RUNNING).toBe('running');
62
- expect(TaskStatus.COMPLETED).toBe('completed');
63
- expect(TaskStatus.FAILED).toBe('failed');
64
- expect(TaskStatus.CANCELLED).toBe('cancelled');
65
- });
66
- });
67
-
68
- describe('AsyncTaskManager', () => {
69
- describe('submit and status transitions', () => {
70
- it('submits a task and transitions to COMPLETED', async () => {
71
- const { manager } = createManager();
72
- const taskId = manager.submit('test.simple', { x: 42 });
73
-
74
- const info = manager.getStatus(taskId);
75
- expect(info).not.toBeNull();
76
- expect(info!.moduleId).toBe('test.simple');
77
-
78
- await wait(100);
79
-
80
- const completed = manager.getStatus(taskId);
81
- expect(completed).not.toBeNull();
82
- expect(completed!.status).toBe(TaskStatus.COMPLETED);
83
- expect(completed!.result).toEqual({ value: 42 });
84
- expect(completed!.startedAt).not.toBeNull();
85
- expect(completed!.completedAt).not.toBeNull();
86
- expect(completed!.error).toBeNull();
87
- });
88
-
89
- it('returns a unique task id', () => {
90
- const { manager } = createManager();
91
- const id1 = manager.submit('test.simple', { x: 1 });
92
- const id2 = manager.submit('test.simple', { x: 2 });
93
- expect(id1).not.toBe(id2);
94
- });
95
- });
96
-
97
- describe('task failure', () => {
98
- it('sets status to FAILED with error message', async () => {
99
- const { manager } = createManager();
100
- const taskId = manager.submit('test.failing', {});
101
-
102
- await wait(100);
103
-
104
- const info = manager.getStatus(taskId);
105
- expect(info).not.toBeNull();
106
- expect(info!.status).toBe(TaskStatus.FAILED);
107
- expect(info!.error).toContain('intentional failure');
108
- expect(info!.completedAt).not.toBeNull();
109
- expect(info!.result).toBeNull();
110
- });
111
- });
112
-
113
- describe('task cancellation', () => {
114
- it('cancels a running task', async () => {
115
- const { manager } = createManager();
116
- const taskId = manager.submit('test.slow', { delay: 60000 });
117
-
118
- await wait(100);
119
-
120
- const info = manager.getStatus(taskId);
121
- expect(info).not.toBeNull();
122
- expect(info!.status).toBe(TaskStatus.RUNNING);
123
-
124
- const cancelled = manager.cancel(taskId);
125
- expect(cancelled).toBe(true);
126
-
127
- const after = manager.getStatus(taskId);
128
- expect(after).not.toBeNull();
129
- expect(after!.status).toBe(TaskStatus.CANCELLED);
130
- expect(after!.completedAt).not.toBeNull();
131
- });
132
-
133
- it('returns false for nonexistent task', () => {
134
- const { manager } = createManager();
135
- const result = manager.cancel('no-such-id');
136
- expect(result).toBe(false);
137
- });
138
-
139
- it('returns false for already completed task', async () => {
140
- const { manager } = createManager();
141
- const taskId = manager.submit('test.simple', { x: 1 });
142
- await wait(100);
143
-
144
- expect(manager.getStatus(taskId)!.status).toBe(TaskStatus.COMPLETED);
145
-
146
- const result = manager.cancel(taskId);
147
- expect(result).toBe(false);
148
- });
149
- });
150
-
151
- describe('concurrency limit', () => {
152
- it('limits concurrent executions to maxConcurrent', async () => {
153
- const { manager } = createManager(2);
154
-
155
- const taskIds: string[] = [];
156
- for (let i = 0; i < 4; i++) {
157
- taskIds.push(manager.submit('test.slow', { delay: 60000 }));
158
- }
159
-
160
- await wait(200);
161
-
162
- const running = manager.listTasks(TaskStatus.RUNNING);
163
- const pending = manager.listTasks(TaskStatus.PENDING);
164
-
165
- expect(running.length).toBeLessThanOrEqual(2);
166
- expect(running.length + pending.length).toBe(4);
167
-
168
- // Cleanup: cancel all (synchronous, no need to await)
169
- for (const id of taskIds) {
170
- manager.cancel(id);
171
- }
172
- });
173
- });
174
-
175
- describe('getResult', () => {
176
- it('returns result for completed task', async () => {
177
- const { manager } = createManager();
178
- const taskId = manager.submit('test.simple', { x: 99 });
179
- await wait(100);
180
-
181
- const result = manager.getResult(taskId);
182
- expect(result).toEqual({ value: 99 });
183
- });
184
-
185
- it('throws for unknown task', () => {
186
- const { manager } = createManager();
187
- expect(() => manager.getResult('no-such-task')).toThrow('Task not found');
188
- });
189
-
190
- it('throws for non-completed task', () => {
191
- const { manager } = createManager();
192
- const taskId = manager.submit('test.slow', { delay: 60000 });
193
-
194
- expect(() => manager.getResult(taskId)).toThrow('not completed');
195
-
196
- manager.cancel(taskId);
197
- });
198
- });
199
-
200
- describe('getStatus', () => {
201
- it('returns null for unknown task', () => {
202
- const { manager } = createManager();
203
- expect(manager.getStatus('nonexistent')).toBeNull();
204
- });
205
- });
206
-
207
- describe('listTasks', () => {
208
- it('returns all tasks', async () => {
209
- const { manager } = createManager();
210
- manager.submit('test.simple', { x: 1 });
211
- manager.submit('test.simple', { x: 2 });
212
- await wait(100);
213
-
214
- const all = manager.listTasks();
215
- expect(all.length).toBe(2);
216
- });
217
-
218
- it('filters tasks by status', async () => {
219
- const { manager } = createManager();
220
- manager.submit('test.simple', { x: 1 });
221
- manager.submit('test.failing', {});
222
- await wait(100);
223
-
224
- const completed = manager.listTasks(TaskStatus.COMPLETED);
225
- const failed = manager.listTasks(TaskStatus.FAILED);
226
- expect(completed.length).toBe(1);
227
- expect(failed.length).toBe(1);
228
- });
229
- });
230
-
231
- describe('max tasks limit', () => {
232
- it('throws when task limit is exceeded', () => {
233
- const { manager } = createManager();
234
- // Create a manager with a small limit
235
- const registry = createRegistry();
236
- const executor = new Executor({ registry });
237
- const limitedManager = new AsyncTaskManager(executor, 10, 3);
238
-
239
- limitedManager.submit('test.simple', { x: 1 });
240
- limitedManager.submit('test.simple', { x: 2 });
241
- limitedManager.submit('test.simple', { x: 3 });
242
-
243
- expect(() => limitedManager.submit('test.simple', { x: 4 })).toThrow(
244
- 'Task limit reached (3)',
245
- );
246
- });
247
-
248
- it('allows submissions after cleanup frees slots', async () => {
249
- const registry = createRegistry();
250
- const executor = new Executor({ registry });
251
- const limitedManager = new AsyncTaskManager(executor, 10, 2);
252
-
253
- limitedManager.submit('test.simple', { x: 1 });
254
- limitedManager.submit('test.simple', { x: 2 });
255
-
256
- await wait(100);
257
- limitedManager.cleanup(0);
258
-
259
- // Should succeed after cleanup
260
- const taskId = limitedManager.submit('test.simple', { x: 3 });
261
- expect(taskId).toBeDefined();
262
- });
263
- });
264
-
265
- describe('double release fix', () => {
266
- it('does not corrupt concurrency counter when cancelling a queued task', async () => {
267
- // Use maxConcurrent=1 so the second task queues behind the first
268
- const registry = createRegistry();
269
- const executor = new Executor({ registry });
270
- const mgr = new AsyncTaskManager(executor, 1);
271
-
272
- // Submit a short task to fill the single slot
273
- const firstId = mgr.submit('test.slow', { delay: 50 });
274
- await wait(10);
275
-
276
- // Submit a second task -- it will be waiting in the queue
277
- const queuedId = mgr.submit('test.slow', { delay: 50 });
278
- await wait(10);
279
-
280
- // The queued task should still be PENDING
281
- expect(mgr.getStatus(queuedId)!.status).toBe(TaskStatus.PENDING);
282
-
283
- // Cancel the queued task while it's waiting for a slot
284
- mgr.cancel(queuedId);
285
-
286
- // Wait for the first task to complete, which releases the slot
287
- // and wakes the cancelled queued task. The queued task should
288
- // see cancelled=true and return; finally releases the slot once.
289
- await wait(200);
290
-
291
- // The running count should be 0 (not negative from double release)
292
- const runningCount = (mgr as unknown as { _runningCount: number })._runningCount;
293
- expect(runningCount).toBe(0);
294
-
295
- // Also verify the first task completed successfully
296
- expect(mgr.getStatus(firstId)!.status).toBe(TaskStatus.COMPLETED);
297
- expect(mgr.getStatus(queuedId)!.status).toBe(TaskStatus.CANCELLED);
298
- });
299
- });
300
-
301
- describe('cleanup', () => {
302
- it('removes old completed tasks', async () => {
303
- const { manager } = createManager();
304
- const taskId = manager.submit('test.simple', { x: 1 });
305
- await wait(100);
306
-
307
- expect(manager.getStatus(taskId)!.status).toBe(TaskStatus.COMPLETED);
308
-
309
- const removed = manager.cleanup(0);
310
- expect(removed).toBe(1);
311
- expect(manager.getStatus(taskId)).toBeNull();
312
- });
313
-
314
- it('preserves recent tasks', async () => {
315
- const { manager } = createManager();
316
- manager.submit('test.simple', { x: 1 });
317
- await wait(100);
318
-
319
- const removed = manager.cleanup(3600);
320
- expect(removed).toBe(0);
321
- expect(manager.listTasks().length).toBe(1);
322
- });
323
-
324
- it('preserves running tasks', async () => {
325
- const { manager } = createManager();
326
- const taskId = manager.submit('test.slow', { delay: 60000 });
327
- await wait(100);
328
-
329
- const removed = manager.cleanup(0);
330
- expect(removed).toBe(0);
331
-
332
- manager.cancel(taskId);
333
- });
334
- });
335
- });
package/tests/helpers.ts DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * Shared test fixtures and helpers.
3
- */
4
-
5
- import { Type } from '@sinclair/typebox';
6
- import { Context, createIdentity } from '../src/context.js';
7
- import { FunctionModule } from '../src/decorator.js';
8
- import { Registry } from '../src/registry/registry.js';
9
-
10
- export function createTestModule(options?: {
11
- moduleId?: string;
12
- description?: string;
13
- execute?: (inputs: Record<string, unknown>, context: Context) => Record<string, unknown>;
14
- }): FunctionModule {
15
- return new FunctionModule({
16
- execute: options?.execute ?? ((inputs) => ({ echo: inputs['name'] ?? 'world' })),
17
- moduleId: options?.moduleId ?? 'test.module',
18
- inputSchema: Type.Object({ name: Type.Optional(Type.String()) }),
19
- outputSchema: Type.Object({ echo: Type.String() }),
20
- description: options?.description ?? 'A test module',
21
- });
22
- }
23
-
24
- export function createTestRegistry(): Registry {
25
- return new Registry();
26
- }
27
-
28
- export function createTestContext(executor?: unknown): Context {
29
- return Context.create(executor, createIdentity('test-user'));
30
- }