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,273 +0,0 @@
1
- /**
2
- * SchemaLoader — primary entry point for the schema system.
3
- *
4
- * Uses TypeBox for schema representation. Since TypeBox schemas ARE JSON Schema,
5
- * the conversion layer is minimal.
6
- */
7
-
8
- import { readFileSync, existsSync } from 'node:fs';
9
- import { resolve, join } from 'node:path';
10
- import { Type, type TSchema } from '@sinclair/typebox';
11
- import yaml from 'js-yaml';
12
- import type { Config } from '../config.js';
13
- import { SchemaNotFoundError, SchemaParseError } from '../errors.js';
14
- import { RefResolver } from './ref-resolver.js';
15
- import type { ResolvedSchema, SchemaDefinition } from './types.js';
16
- import { SchemaStrategy } from './types.js';
17
-
18
- export class SchemaLoader {
19
- private _config: Config;
20
- private _schemasDir: string;
21
- private _resolver: RefResolver;
22
- private _schemaCache: Map<string, SchemaDefinition> = new Map();
23
- private _modelCache: Map<string, [ResolvedSchema, ResolvedSchema]> = new Map();
24
-
25
- constructor(config: Config, schemasDir?: string | null) {
26
- this._config = config;
27
- if (schemasDir != null) {
28
- this._schemasDir = resolve(schemasDir);
29
- } else {
30
- this._schemasDir = resolve(config.get('schema.root', './schemas') as string);
31
- }
32
- const maxDepth = (config.get('schema.max_ref_depth', 32) as number);
33
- this._resolver = new RefResolver(this._schemasDir, maxDepth);
34
- }
35
-
36
- load(moduleId: string): SchemaDefinition {
37
- const cached = this._schemaCache.get(moduleId);
38
- if (cached) return cached;
39
-
40
- const filePath = join(this._schemasDir, moduleId.replace(/\./g, '/') + '.schema.yaml');
41
- if (!existsSync(filePath)) {
42
- throw new SchemaNotFoundError(moduleId);
43
- }
44
-
45
- let data: unknown;
46
- try {
47
- data = yaml.load(readFileSync(filePath, 'utf-8'));
48
- } catch (e) {
49
- throw new SchemaParseError(`Invalid YAML in schema for '${moduleId}': ${e}`);
50
- }
51
-
52
- if (data === null || data === undefined || typeof data !== 'object' || Array.isArray(data)) {
53
- throw new SchemaParseError(`Schema file for '${moduleId}' is empty or not a mapping`);
54
- }
55
-
56
- const dataObj = data as Record<string, unknown>;
57
- for (const fieldName of ['input_schema', 'output_schema', 'description']) {
58
- if (!(fieldName in dataObj)) {
59
- throw new SchemaParseError(`Missing required field: ${fieldName} in schema for '${moduleId}'`);
60
- }
61
- }
62
-
63
- const definitions: Record<string, unknown> = {
64
- ...((dataObj['definitions'] as Record<string, unknown>) ?? {}),
65
- ...((dataObj['$defs'] as Record<string, unknown>) ?? {}),
66
- };
67
-
68
- const sd: SchemaDefinition = {
69
- moduleId: (dataObj['module_id'] as string) ?? moduleId,
70
- description: dataObj['description'] as string,
71
- inputSchema: dataObj['input_schema'] as Record<string, unknown>,
72
- outputSchema: dataObj['output_schema'] as Record<string, unknown>,
73
- errorSchema: (dataObj['error_schema'] as Record<string, unknown>) ?? null,
74
- definitions,
75
- version: (dataObj['version'] as string) ?? '1.0.0',
76
- documentation: (dataObj['documentation'] as string) ?? null,
77
- schemaUrl: (dataObj['$schema'] as string) ?? null,
78
- };
79
-
80
- this._schemaCache.set(moduleId, sd);
81
- return sd;
82
- }
83
-
84
- resolve(schemaDef: SchemaDefinition): [ResolvedSchema, ResolvedSchema] {
85
- const resolvedInput = this._resolver.resolve(schemaDef.inputSchema);
86
- const resolvedOutput = this._resolver.resolve(schemaDef.outputSchema);
87
-
88
- const inputSchema = jsonSchemaToTypeBox(resolvedInput);
89
- const outputSchema = jsonSchemaToTypeBox(resolvedOutput);
90
-
91
- const inputRs: ResolvedSchema = {
92
- jsonSchema: resolvedInput,
93
- schema: inputSchema,
94
- moduleId: schemaDef.moduleId,
95
- direction: 'input',
96
- };
97
- const outputRs: ResolvedSchema = {
98
- jsonSchema: resolvedOutput,
99
- schema: outputSchema,
100
- moduleId: schemaDef.moduleId,
101
- direction: 'output',
102
- };
103
- return [inputRs, outputRs];
104
- }
105
-
106
- getSchema(
107
- moduleId: string,
108
- nativeInputSchema?: TSchema | null,
109
- nativeOutputSchema?: TSchema | null,
110
- ): [ResolvedSchema, ResolvedSchema] {
111
- const cached = this._modelCache.get(moduleId);
112
- if (cached) return cached;
113
-
114
- const strategyMap: Record<string, SchemaStrategy> = {
115
- yaml_first: SchemaStrategy.YamlFirst,
116
- native_first: SchemaStrategy.NativeFirst,
117
- yaml_only: SchemaStrategy.YamlOnly,
118
- };
119
- const rawStrategy = this._config.get('schema.strategy', 'yaml_first') as string;
120
- const strategy = strategyMap[rawStrategy] ?? SchemaStrategy.YamlFirst;
121
-
122
- let result: [ResolvedSchema, ResolvedSchema] | null = null;
123
-
124
- if (strategy === SchemaStrategy.YamlFirst) {
125
- try {
126
- result = this._loadAndResolve(moduleId);
127
- } catch (e) {
128
- if (e instanceof SchemaNotFoundError && nativeInputSchema && nativeOutputSchema) {
129
- result = this._wrapNative(moduleId, nativeInputSchema, nativeOutputSchema);
130
- } else {
131
- throw e;
132
- }
133
- }
134
- } else if (strategy === SchemaStrategy.NativeFirst) {
135
- if (nativeInputSchema && nativeOutputSchema) {
136
- result = this._wrapNative(moduleId, nativeInputSchema, nativeOutputSchema);
137
- } else {
138
- result = this._loadAndResolve(moduleId);
139
- }
140
- } else if (strategy === SchemaStrategy.YamlOnly) {
141
- result = this._loadAndResolve(moduleId);
142
- }
143
-
144
- if (result === null) {
145
- throw new SchemaNotFoundError(moduleId);
146
- }
147
-
148
- this._modelCache.set(moduleId, result);
149
- return result;
150
- }
151
-
152
- private _loadAndResolve(moduleId: string): [ResolvedSchema, ResolvedSchema] {
153
- const cached = this._modelCache.get(moduleId);
154
- if (cached) return cached;
155
- const sd = this.load(moduleId);
156
- const result = this.resolve(sd);
157
- this._modelCache.set(moduleId, result);
158
- return result;
159
- }
160
-
161
- private _wrapNative(
162
- moduleId: string,
163
- inputSchema: TSchema,
164
- outputSchema: TSchema,
165
- ): [ResolvedSchema, ResolvedSchema] {
166
- const inputRs: ResolvedSchema = {
167
- jsonSchema: inputSchema as unknown as Record<string, unknown>,
168
- schema: inputSchema,
169
- moduleId,
170
- direction: 'input',
171
- };
172
- const outputRs: ResolvedSchema = {
173
- jsonSchema: outputSchema as unknown as Record<string, unknown>,
174
- schema: outputSchema,
175
- moduleId,
176
- direction: 'output',
177
- };
178
- return [inputRs, outputRs];
179
- }
180
-
181
- clearCache(): void {
182
- this._schemaCache.clear();
183
- this._modelCache.clear();
184
- this._resolver.clearCache();
185
- }
186
- }
187
-
188
- /**
189
- * Convert a JSON Schema dict to a TypeBox TSchema.
190
- * Since TypeBox schemas ARE JSON Schema, this wraps the raw object
191
- * so it can be used with Value.Check/Value.Decode.
192
- */
193
- export function jsonSchemaToTypeBox(schema: Record<string, unknown>): TSchema {
194
- const schemaType = schema['type'] as string | undefined;
195
-
196
- let result: TSchema;
197
- if (schemaType === 'object') result = convertObjectSchema(schema);
198
- else if (schemaType === 'array') result = convertArraySchema(schema);
199
- else if (schemaType === 'string') result = convertStringSchema(schema);
200
- else if (schemaType === 'integer') result = convertNumericSchema(schema, Type.Integer);
201
- else if (schemaType === 'number') result = convertNumericSchema(schema, Type.Number);
202
- else if (schemaType === 'boolean') result = Type.Boolean();
203
- else if (schemaType === 'null') result = Type.Null();
204
- else result = convertCombinatorSchema(schema);
205
-
206
- // Preserve JSON Schema metadata
207
- if (typeof schema['description'] === 'string') result['description'] = schema['description'];
208
- if (typeof schema['title'] === 'string') result['title'] = schema['title'];
209
-
210
- return result;
211
- }
212
-
213
- function convertObjectSchema(schema: Record<string, unknown>): TSchema {
214
- const properties = schema['properties'] as Record<string, Record<string, unknown>> | undefined;
215
- const required = new Set((schema['required'] as string[]) ?? []);
216
-
217
- if (properties) {
218
- const typeboxProps: Record<string, TSchema> = {};
219
- for (const [name, propSchema] of Object.entries(properties)) {
220
- const propType = jsonSchemaToTypeBox(propSchema);
221
- typeboxProps[name] = required.has(name) ? propType : Type.Optional(propType);
222
- }
223
- return Type.Object(typeboxProps);
224
- }
225
- return Type.Record(Type.String(), Type.Unknown());
226
- }
227
-
228
- function convertArraySchema(schema: Record<string, unknown>): TSchema {
229
- const items = schema['items'] as Record<string, unknown> | undefined;
230
- return items ? Type.Array(jsonSchemaToTypeBox(items)) : Type.Array(Type.Unknown());
231
- }
232
-
233
- function convertStringSchema(schema: Record<string, unknown>): TSchema {
234
- const opts: Record<string, unknown> = {};
235
- for (const key of ['minLength', 'maxLength', 'pattern', 'format']) {
236
- if (key in schema) opts[key] = schema[key];
237
- }
238
- return Type.String(opts);
239
- }
240
-
241
- function convertNumericSchema(
242
- schema: Record<string, unknown>,
243
- factory: (opts?: Record<string, unknown>) => TSchema,
244
- ): TSchema {
245
- const opts: Record<string, unknown> = {};
246
- for (const key of ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf']) {
247
- if (key in schema) opts[key] = schema[key];
248
- }
249
- return factory(opts);
250
- }
251
-
252
- function convertCombinatorSchema(schema: Record<string, unknown>): TSchema {
253
- if ('enum' in schema) {
254
- const values = schema['enum'] as unknown[];
255
- return Type.Union(values.map((v) =>
256
- v === null ? Type.Null() : Type.Literal(v as string | number | boolean),
257
- ));
258
- }
259
- if ('const' in schema) {
260
- const value = schema['const'];
261
- return value === null ? Type.Null() : Type.Literal(value as string | number | boolean);
262
- }
263
- if ('oneOf' in schema) {
264
- return Type.Union((schema['oneOf'] as Record<string, unknown>[]).map(jsonSchemaToTypeBox));
265
- }
266
- if ('anyOf' in schema) {
267
- return Type.Union((schema['anyOf'] as Record<string, unknown>[]).map(jsonSchemaToTypeBox));
268
- }
269
- if ('allOf' in schema) {
270
- return Type.Intersect((schema['allOf'] as Record<string, unknown>[]).map(jsonSchemaToTypeBox));
271
- }
272
- return Type.Unknown();
273
- }
@@ -1,244 +0,0 @@
1
- /**
2
- * $ref resolution for JSON Schema documents following Algorithm A05.
3
- */
4
-
5
- import { readFileSync, existsSync } from 'node:fs';
6
- import { resolve, dirname, join } from 'node:path';
7
- import yaml from 'js-yaml';
8
- import { SchemaCircularRefError, SchemaNotFoundError, SchemaParseError } from '../errors.js';
9
- import { deepCopy } from '../utils/index.js';
10
-
11
- const INLINE_SENTINEL = '__inline__';
12
-
13
- export class RefResolver {
14
- private _schemasDir: string;
15
- private _maxDepth: number;
16
- private _fileCache: Map<string, Record<string, unknown>> = new Map();
17
-
18
- constructor(schemasDir: string, maxDepth: number = 32) {
19
- this._schemasDir = resolve(schemasDir);
20
- this._maxDepth = maxDepth;
21
- }
22
-
23
- resolve(schema: Record<string, unknown>, currentFile?: string | null): Record<string, unknown> {
24
- const result = deepCopy(schema);
25
- this._fileCache.set(INLINE_SENTINEL, result);
26
- try {
27
- this._resolveNode(result, currentFile ?? null, new Set(), 0);
28
- } finally {
29
- this._fileCache.delete(INLINE_SENTINEL);
30
- }
31
- return result;
32
- }
33
-
34
- resolveRef(
35
- refString: string,
36
- currentFile: string | null,
37
- visitedRefs?: Set<string>,
38
- depth: number = 0,
39
- siblingKeys?: Record<string, unknown> | null,
40
- ): unknown {
41
- const visited = visitedRefs ?? new Set<string>();
42
-
43
- if (visited.has(refString)) {
44
- throw new SchemaCircularRefError(refString);
45
- }
46
-
47
- if (depth >= this._maxDepth) {
48
- throw new SchemaCircularRefError(
49
- `Maximum reference depth ${this._maxDepth} exceeded resolving: ${refString}`,
50
- );
51
- }
52
-
53
- visited.add(refString);
54
-
55
- const [filePath, jsonPointer] = this._parseRef(refString, currentFile);
56
- const document = this._loadFile(filePath);
57
- const target = this._resolveJsonPointer(document, jsonPointer, refString);
58
-
59
- let result: unknown = deepCopy(target);
60
-
61
- if (siblingKeys && typeof result === 'object' && result !== null && !Array.isArray(result)) {
62
- Object.assign(result as Record<string, unknown>, siblingKeys);
63
- }
64
-
65
- const effectiveFile = filePath === INLINE_SENTINEL ? currentFile : filePath;
66
-
67
- if (typeof result === 'object' && result !== null && !Array.isArray(result)) {
68
- const resultObj = result as Record<string, unknown>;
69
- if ('$ref' in resultObj) {
70
- const nestedRef = resultObj['$ref'] as string;
71
- delete resultObj['$ref'];
72
- const nestedSiblings = Object.keys(resultObj).length > 0 ? { ...resultObj } : null;
73
- result = this.resolveRef(nestedRef, effectiveFile, visited, depth + 1, nestedSiblings);
74
- }
75
- }
76
-
77
- this._resolveNode(result, effectiveFile, visited, depth + 1);
78
- return result;
79
- }
80
-
81
- private _resolveNode(
82
- node: unknown,
83
- currentFile: string | null,
84
- visitedRefs: Set<string>,
85
- depth: number,
86
- ): unknown {
87
- if (typeof node === 'object' && node !== null && !Array.isArray(node)) {
88
- const nodeObj = node as Record<string, unknown>;
89
- if ('$ref' in nodeObj) {
90
- const refString = nodeObj['$ref'] as string;
91
- const siblingKeys: Record<string, unknown> = {};
92
- for (const [k, v] of Object.entries(nodeObj)) {
93
- if (k !== '$ref') siblingKeys[k] = v;
94
- }
95
- const resolved = this.resolveRef(
96
- refString,
97
- currentFile,
98
- new Set(visitedRefs),
99
- depth,
100
- Object.keys(siblingKeys).length > 0 ? siblingKeys : null,
101
- );
102
- // Clear and replace
103
- for (const key of Object.keys(nodeObj)) delete nodeObj[key];
104
- if (typeof resolved === 'object' && resolved !== null && !Array.isArray(resolved)) {
105
- Object.assign(nodeObj, resolved as Record<string, unknown>);
106
- } else {
107
- return resolved;
108
- }
109
- } else {
110
- for (const key of Object.keys(nodeObj)) {
111
- const result = this._resolveNode(nodeObj[key], currentFile, visitedRefs, depth);
112
- if (result !== nodeObj[key]) {
113
- nodeObj[key] = result;
114
- }
115
- }
116
- }
117
- } else if (Array.isArray(node)) {
118
- for (let i = 0; i < node.length; i++) {
119
- const result = this._resolveNode(node[i], currentFile, visitedRefs, depth);
120
- if (result !== node[i]) {
121
- node[i] = result;
122
- }
123
- }
124
- }
125
- return node;
126
- }
127
-
128
- private _parseRef(refString: string, currentFile: string | null): [string, string] {
129
- if (refString.startsWith('#')) {
130
- const pointer = refString.slice(1);
131
- if (currentFile) return [currentFile, pointer];
132
- return [INLINE_SENTINEL, pointer];
133
- }
134
-
135
- if (refString.startsWith('apcore://')) {
136
- return this._convertCanonicalToPath(refString);
137
- }
138
-
139
- if (refString.includes('#')) {
140
- const [filePart, pointer] = refString.split('#', 2);
141
- const base = currentFile ? dirname(currentFile) : this._schemasDir;
142
- const resolvedPath = resolve(base, filePart);
143
- this._assertWithinSchemasDir(resolvedPath, refString);
144
- return [resolvedPath, pointer];
145
- }
146
-
147
- const base = currentFile ? dirname(currentFile) : this._schemasDir;
148
- const resolvedPath = resolve(base, refString);
149
- this._assertWithinSchemasDir(resolvedPath, refString);
150
- return [resolvedPath, ''];
151
- }
152
-
153
- private _assertWithinSchemasDir(resolvedPath: string, refString: string): void {
154
- if (!resolvedPath.startsWith(this._schemasDir + '/') && resolvedPath !== this._schemasDir) {
155
- throw new SchemaNotFoundError(
156
- `Reference '${refString}' resolves outside schemas directory`,
157
- );
158
- }
159
- }
160
-
161
- private _convertCanonicalToPath(uri: string): [string, string] {
162
- const remainder = uri.slice('apcore://'.length);
163
- const parts = remainder.split('/');
164
- const canonicalId = parts[0];
165
- const pointerParts = parts.slice(1);
166
-
167
- const fileRel = canonicalId.replace(/\./g, '/') + '.schema.yaml';
168
- const filePath = resolve(this._schemasDir, fileRel);
169
-
170
- const pointer = pointerParts.length > 0 ? '/' + pointerParts.join('/') : '';
171
- return [filePath, pointer];
172
- }
173
-
174
- private _resolveJsonPointer(document: unknown, pointer: string, refString: string): unknown {
175
- if (!pointer) return document;
176
-
177
- let segments = pointer.split('/');
178
- if (segments.length > 0 && segments[0] === '') {
179
- segments = segments.slice(1);
180
- }
181
-
182
- let current = document;
183
- for (const rawSegment of segments) {
184
- const segment = rawSegment.replace(/~1/g, '/').replace(/~0/g, '~');
185
- if (typeof current === 'object' && current !== null && !Array.isArray(current)) {
186
- const obj = current as Record<string, unknown>;
187
- if (segment in obj) {
188
- current = obj[segment];
189
- } else {
190
- throw new SchemaNotFoundError(`${refString} (segment '${segment}' not found)`);
191
- }
192
- } else {
193
- throw new SchemaNotFoundError(`${refString} (segment '${segment}' not found)`);
194
- }
195
- }
196
- return current;
197
- }
198
-
199
- private _loadFile(filePath: string): Record<string, unknown> {
200
- if (filePath === INLINE_SENTINEL) {
201
- return this._fileCache.get(INLINE_SENTINEL) ?? {};
202
- }
203
-
204
- const resolved = resolve(filePath);
205
- const cached = this._fileCache.get(resolved);
206
- if (cached !== undefined) return cached;
207
-
208
- if (!existsSync(resolved)) {
209
- throw new SchemaNotFoundError(resolved);
210
- }
211
-
212
- const content = readFileSync(resolved, 'utf-8');
213
- if (!content.trim()) {
214
- this._fileCache.set(resolved, {});
215
- return {};
216
- }
217
-
218
- let parsed: unknown;
219
- try {
220
- parsed = yaml.load(content);
221
- } catch (e) {
222
- throw new SchemaParseError(`Invalid YAML in ${resolved}: ${e}`);
223
- }
224
-
225
- if (parsed === null || parsed === undefined) {
226
- this._fileCache.set(resolved, {});
227
- return {};
228
- }
229
-
230
- if (typeof parsed !== 'object' || Array.isArray(parsed)) {
231
- throw new SchemaParseError(
232
- `Schema file ${resolved} must be a YAML mapping, got ${typeof parsed}`,
233
- );
234
- }
235
-
236
- const result = parsed as Record<string, unknown>;
237
- this._fileCache.set(resolved, result);
238
- return result;
239
- }
240
-
241
- clearCache(): void {
242
- this._fileCache.clear();
243
- }
244
- }
@@ -1,136 +0,0 @@
1
- /**
2
- * Strict mode conversion for JSON Schemas (Algorithm A23).
3
- */
4
-
5
- import { deepCopy } from '../utils/index.js';
6
-
7
- export function toStrictSchema(schema: Record<string, unknown>): Record<string, unknown> {
8
- const result = deepCopy(schema);
9
- stripExtensions(result);
10
- convertToStrict(result);
11
- return result;
12
- }
13
-
14
- export function applyLlmDescriptions(node: unknown): void {
15
- if (typeof node !== 'object' || node === null || Array.isArray(node)) return;
16
-
17
- const obj = node as Record<string, unknown>;
18
- if ('x-llm-description' in obj) {
19
- obj['description'] = obj['x-llm-description'];
20
- }
21
-
22
- if ('properties' in obj && typeof obj['properties'] === 'object' && obj['properties'] !== null) {
23
- for (const prop of Object.values(obj['properties'] as Record<string, unknown>)) {
24
- applyLlmDescriptions(prop);
25
- }
26
- }
27
- if ('items' in obj && typeof obj['items'] === 'object') {
28
- applyLlmDescriptions(obj['items']);
29
- }
30
- for (const keyword of ['oneOf', 'anyOf', 'allOf']) {
31
- if (keyword in obj && Array.isArray(obj[keyword])) {
32
- for (const sub of obj[keyword] as unknown[]) {
33
- applyLlmDescriptions(sub);
34
- }
35
- }
36
- }
37
- for (const defsKey of ['definitions', '$defs']) {
38
- if (defsKey in obj && typeof obj[defsKey] === 'object' && obj[defsKey] !== null) {
39
- for (const defn of Object.values(obj[defsKey] as Record<string, unknown>)) {
40
- applyLlmDescriptions(defn);
41
- }
42
- }
43
- }
44
- }
45
-
46
- export function stripExtensions(node: unknown): void {
47
- if (typeof node !== 'object' || node === null || Array.isArray(node)) return;
48
-
49
- const obj = node as Record<string, unknown>;
50
- const keysToRemove = Object.keys(obj).filter(
51
- (k) => (typeof k === 'string' && k.startsWith('x-')) || k === 'default',
52
- );
53
- for (const k of keysToRemove) {
54
- delete obj[k];
55
- }
56
-
57
- for (const value of Object.values(obj)) {
58
- if (typeof value === 'object' && value !== null) {
59
- if (Array.isArray(value)) {
60
- for (const item of value) {
61
- if (typeof item === 'object' && item !== null) {
62
- stripExtensions(item);
63
- }
64
- }
65
- } else {
66
- stripExtensions(value);
67
- }
68
- }
69
- }
70
- }
71
-
72
- function convertToStrict(node: unknown): void {
73
- if (typeof node !== 'object' || node === null || Array.isArray(node)) return;
74
-
75
- const obj = node as Record<string, unknown>;
76
-
77
- if (obj['type'] === 'object' && 'properties' in obj) {
78
- obj['additionalProperties'] = false;
79
- const existingRequired = new Set(
80
- Array.isArray(obj['required']) ? (obj['required'] as string[]) : [],
81
- );
82
- const properties = obj['properties'] as Record<string, unknown>;
83
- const allNames = Object.keys(properties);
84
- const optionalNames = allNames.filter((n) => !existingRequired.has(n));
85
-
86
- for (const name of optionalNames) {
87
- const prop = properties[name] as Record<string, unknown>;
88
- if ('type' in prop) {
89
- if (typeof prop['type'] === 'string') {
90
- prop['type'] = [prop['type'], 'null'];
91
- } else if (Array.isArray(prop['type'])) {
92
- if (!(prop['type'] as string[]).includes('null')) {
93
- (prop['type'] as string[]).push('null');
94
- }
95
- }
96
- } else if ('oneOf' in prop && Array.isArray(prop['oneOf'])) {
97
- const variants = prop['oneOf'] as Record<string, unknown>[];
98
- if (!variants.some((v) => v['type'] === 'null')) {
99
- variants.push({ type: 'null' });
100
- }
101
- } else if ('anyOf' in prop && Array.isArray(prop['anyOf'])) {
102
- const variants = prop['anyOf'] as Record<string, unknown>[];
103
- if (!variants.some((v) => v['type'] === 'null')) {
104
- variants.push({ type: 'null' });
105
- }
106
- } else {
107
- properties[name] = { oneOf: [prop, { type: 'null' }] };
108
- }
109
- }
110
-
111
- obj['required'] = [...allNames].sort();
112
- }
113
-
114
- if ('properties' in obj && typeof obj['properties'] === 'object' && obj['properties'] !== null) {
115
- for (const prop of Object.values(obj['properties'] as Record<string, unknown>)) {
116
- convertToStrict(prop);
117
- }
118
- }
119
- if ('items' in obj && typeof obj['items'] === 'object') {
120
- convertToStrict(obj['items']);
121
- }
122
- for (const keyword of ['oneOf', 'anyOf', 'allOf']) {
123
- if (keyword in obj && Array.isArray(obj[keyword])) {
124
- for (const sub of obj[keyword] as unknown[]) {
125
- convertToStrict(sub);
126
- }
127
- }
128
- }
129
- for (const defsKey of ['definitions', '$defs']) {
130
- if (defsKey in obj && typeof obj[defsKey] === 'object' && obj[defsKey] !== null) {
131
- for (const defn of Object.values(obj[defsKey] as Record<string, unknown>)) {
132
- convertToStrict(defn);
133
- }
134
- }
135
- }
136
- }